code
stringlengths 2
1.05M
| repo_name
stringlengths 5
114
| path
stringlengths 4
991
| language
stringclasses 1
value | license
stringclasses 15
values | size
int32 2
1.05M
|
---|---|---|---|---|---|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
'use strict';
import {BatchedBridge} from 'react-native/Libraries/ReactPrivate/ReactNativePrivateInterface';
// TODO @sema: Adjust types
import type {ReactNativeType} from './ReactNativeTypes';
let ReactFabric;
if (__DEV__) {
ReactFabric = require('../implementations/ReactFabric-dev');
} else {
ReactFabric = require('../implementations/ReactFabric-prod');
}
BatchedBridge.registerCallableModule('ReactFabric', ReactFabric);
module.exports = (ReactFabric: ReactNativeType);
| VioletLife/react | scripts/rollup/shims/react-native/ReactFabric.js | JavaScript | mit | 698 |
// -----------------------------------------------------------------------------
// Globals
// Major version of Flash required
var requiredMajorVersion = 8;
// Minor version of Flash required
var requiredMinorVersion = 0;
// Minor version of Flash required
var requiredRevision = 0;
// the version of javascript supported
var jsVersion = 1.0;
// -----------------------------------------------------------------------------
var isIE = (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
var isWin = (navigator.appVersion.toLowerCase().indexOf("win") != -1) ? true : false;
var isOpera = (navigator.userAgent.indexOf("Opera") != -1) ? true : false;
jsVersion = 1.1;
// JavaScript helper required to detect Flash Player PlugIn version information
function JSGetSwfVer(i){
// NS/Opera version >= 3 check for Flash plugin in plugin array
if (navigator.plugins != null && navigator.plugins.length > 0) {
if (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]) {
var swVer2 = navigator.plugins["Shockwave Flash 2.0"] ? " 2.0" : "";
var flashDescription = navigator.plugins["Shockwave Flash" + swVer2].description;
descArray = flashDescription.split(" ");
tempArrayMajor = descArray[2].split(".");
versionMajor = tempArrayMajor[0];
versionMinor = tempArrayMajor[1];
if ( descArray[3] != "" ) {
tempArrayMinor = descArray[3].split("r");
} else {
tempArrayMinor = descArray[4].split("r");
}
versionRevision = tempArrayMinor[1] > 0 ? tempArrayMinor[1] : 0;
flashVer = versionMajor + "." + versionMinor + "." + versionRevision;
} else {
flashVer = -1;
}
}
// MSN/WebTV 2.6 supports Flash 4
else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.6") != -1) flashVer = 4;
// WebTV 2.5 supports Flash 3
else if (navigator.userAgent.toLowerCase().indexOf("webtv/2.5") != -1) flashVer = 3;
// older WebTV supports Flash 2
else if (navigator.userAgent.toLowerCase().indexOf("webtv") != -1) flashVer = 2;
// Can't detect in all other cases
else {
flashVer = -1;
}
return flashVer;
}
// When called with reqMajorVer, reqMinorVer, reqRevision returns true if that version or greater is available
function DetectFlashVer(reqMajorVer, reqMinorVer, reqRevision)
{
reqVer = parseFloat(reqMajorVer + "." + reqRevision);
// loop backwards through the versions until we find the newest version
for (i=25;i>0;i--) {
if (isIE && isWin && !isOpera) {
versionStr = VBGetSwfVer(i);
} else {
versionStr = JSGetSwfVer(i);
}
if (versionStr == -1 ) {
return false;
} else if (versionStr != 0) {
if(isIE && isWin && !isOpera) {
tempArray = versionStr.split(" ");
tempString = tempArray[1];
versionArray = tempString .split(",");
} else {
versionArray = versionStr.split(".");
}
versionMajor = versionArray[0];
versionMinor = versionArray[1];
versionRevision = versionArray[2];
versionString = versionMajor + "." + versionRevision; // 7.0r24 == 7.24
versionNum = parseFloat(versionString);
// is the major.revision >= requested major.revision AND the minor version >= requested minor
if ( (versionMajor > reqMajorVer) && (versionNum >= reqVer) ) {
return true;
} else {
return ((versionNum >= reqVer && versionMinor >= reqMinorVer) ? true : false );
}
}
}
}
| zhiqinghuang/core | dotCMS/html/js/flash/detectFlash.js | JavaScript | gpl-3.0 | 3,505 |
dojo.provide("dojox.charting.widget.nls.Chart2D_en-us");dojo.provide("dojo.cldr.nls.number");dojo.cldr.nls.number._built=true;dojo.provide("dojo.cldr.nls.number.en_us");dojo.cldr.nls.number.en_us={"group":",","percentSign":"%","exponential":"E","percentFormat":"#,##0%","scientificFormat":"#E0","list":";","infinity":"∞","patternDigit":"#","minusSign":"-","decimal":".","nan":"NaN","nativeZeroDigit":"0","perMille":"‰","decimalFormat":"#,##0.###","currencyFormat":"¤#,##0.00;(¤#,##0.00)","plusSign":"+","currencySpacing-afterCurrency-currencyMatch":"[:letter:]","currencySpacing-beforeCurrency-surroundingMatch":"[:digit:]","currencySpacing-afterCurrency-insertBetween":" ","currencySpacing-afterCurrency-surroundingMatch":"[:digit:]","currencySpacing-beforeCurrency-currencyMatch":"[:letter:]","currencySpacing-beforeCurrency-insertBetween":" "};
| ontoden/ontobee | public/js/dojox/charting/widget/nls/Chart2D_en-us.js | JavaScript | apache-2.0 | 856 |
var JEY_TOPO = {"type":"Topology","objects":{"jey":{"type":"GeometryCollection","geometries":[{"type":"Polygon","properties":{"name":"Jersey"},"id":"JE","arcs":[[0]]}]}},"arcs":[[[6817,9289],[634,-999],[2019,-1611],[-56,-1021],[199,-429],[233,-638],[153,-293],[-373,-548],[-170,-676],[-45,-868],[3,-1156],[-110,-1050],[-283,13],[-380,446],[-393,268],[-1316,42],[-728,519],[-994,1620],[-371,408],[-386,268],[-296,0],[-346,-595],[-329,-961],[-345,-1301],[-362,196],[-536,935],[-446,297],[-122,-161],[-874,-595],[-438,-22],[306,2245],[-289,2351],[-376,2032],[38,1284],[503,289],[606,-289],[810,-714],[579,68],[444,229],[413,434],[472,693],[337,-540],[933,-374],[484,-510],[291,501],[270,154],[637,59]]],"transform":{"scale":[0.000023374733373337532,0.00000957126962695701],"translate":[-2.242014126999919,49.17133209800008]}} | yoer/hue | desktop/core/src/desktop/static/desktop/ext/js/topo/jey.topo.js | JavaScript | apache-2.0 | 822 |
version https://git-lfs.github.com/spec/v1
oid sha256:ac03974d85317d75edc2dc62eb1c40e9514aae0dcfe5e69e3a62c6d419484632
size 887
| yogeshsaroya/new-cdnjs | ajax/libs/dojo/1.9.7/cldr/monetary.js | JavaScript | mit | 128 |
version https://git-lfs.github.com/spec/v1
oid sha256:98117aa63db915fed8f72d5c0c414049013e63982817c75864b5e01bb3997090
size 17927
| yogeshsaroya/new-cdnjs | ajax/libs/yui/3.9.1/dd-drop/dd-drop-debug.js | JavaScript | mit | 130 |
"use strict";import"../../Stock/Indicators/SlowStochastic/SlowStochasticIndicator.js"; | cdnjs/cdnjs | ajax/libs/highcharts/9.3.3/es-modules/masters/indicators/slow-stochastic.src.min.js | JavaScript | mit | 86 |
var class_mix_e_r_p_1_1_net_1_1_core_1_1_modules_1_1_sales_1_1_setup_1_1_bonus_slabs =
[
[ "OnControlLoad", "class_mix_e_r_p_1_1_net_1_1_core_1_1_modules_1_1_sales_1_1_setup_1_1_bonus_slabs.html#ab16b782e4c9f10ebbbc47fd52dbc6ae1", null ],
[ "ScrudPlaceholder", "class_mix_e_r_p_1_1_net_1_1_core_1_1_modules_1_1_sales_1_1_setup_1_1_bonus_slabs.html#a3402588f607d9920f295a38336e9ca8d", null ]
]; | mixerp6/mixerp | docs/api/class_mix_e_r_p_1_1_net_1_1_core_1_1_modules_1_1_sales_1_1_setup_1_1_bonus_slabs.js | JavaScript | gpl-2.0 | 401 |
var class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee =
[
[ "AccountId", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#aa5f13daf52f6212580695248d62ed83d", null ],
[ "AuditTs", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#a95210c8ea60bb4107cb1a76b0617e58a", null ],
[ "AuditUserId", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#ad3b75c8f461c7ebc2756c1fddca8991d", null ],
[ "IsFlatAmount", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#a7f09ea80a18909ebaeb1f2c561a63e77", null ],
[ "LateFeeCode", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#af38567944abc8be98c7ac91c30d4f1f5", null ],
[ "LateFeeId", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#a95fd529069d0e5705260329f8d895e5c", null ],
[ "LateFeeName", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#a770c2823bf447fb41c54062fef2334ba", null ],
[ "Rate", "class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.html#ab6a4512cbe1dcde39c2ec00be539acbf", null ]
]; | mixerp6/mixerp | docs/api/class_mix_e_r_p_1_1_net_1_1_entities_1_1_core_1_1_late_fee.js | JavaScript | gpl-2.0 | 1,094 |
var class_peta_poco_1_1_factory =
[
[ "ProviderName", "class_peta_poco_1_1_factory.html#ab3fd0d733879b1a810f8d5e3731c721b", null ]
]; | mixerp/mixerp | docs/api/class_peta_poco_1_1_factory.js | JavaScript | gpl-3.0 | 137 |
/*
CryptoJS v3.1.2
code.google.com/p/crypto-js
(c) 2009-2013 by Jeff Mott. All rights reserved.
code.google.com/p/crypto-js/wiki/License
*/
var CryptoJS=CryptoJS||function(s,l){var e={},n=e.lib={},p=function(){},b=n.Base={extend:function(c){p.prototype=this;var a=new p;c&&a.mixIn(c);a.hasOwnProperty("init")||(a.init=function(){a.$super.init.apply(this,arguments)});a.init.prototype=a;a.$super=this;return a},create:function(){var c=this.extend();c.init.apply(c,arguments);return c},init:function(){},mixIn:function(c){for(var a in c)c.hasOwnProperty(a)&&(this[a]=c[a]);c.hasOwnProperty("toString")&&(this.toString=c.toString)},clone:function(){return this.init.prototype.extend(this)}},
d=n.WordArray=b.extend({init:function(c,a){c=this.words=c||[];this.sigBytes=a!=l?a:4*c.length},toString:function(c){return(c||q).stringify(this)},concat:function(c){var a=this.words,m=c.words,f=this.sigBytes;c=c.sigBytes;this.clamp();if(f%4)for(var r=0;r<c;r++)a[f+r>>>2]|=(m[r>>>2]>>>24-8*(r%4)&255)<<24-8*((f+r)%4);else if(65535<m.length)for(r=0;r<c;r+=4)a[f+r>>>2]=m[r>>>2];else a.push.apply(a,m);this.sigBytes+=c;return this},clamp:function(){var c=this.words,a=this.sigBytes;c[a>>>2]&=4294967295<<
32-8*(a%4);c.length=s.ceil(a/4)},clone:function(){var c=b.clone.call(this);c.words=this.words.slice(0);return c},random:function(c){for(var a=[],m=0;m<c;m+=4)a.push(4294967296*s.random()|0);return new d.init(a,c)}}),t=e.enc={},q=t.Hex={stringify:function(c){var a=c.words;c=c.sigBytes;for(var m=[],f=0;f<c;f++){var r=a[f>>>2]>>>24-8*(f%4)&255;m.push((r>>>4).toString(16));m.push((r&15).toString(16))}return m.join("")},parse:function(c){for(var a=c.length,m=[],f=0;f<a;f+=2)m[f>>>3]|=parseInt(c.substr(f,
2),16)<<24-4*(f%8);return new d.init(m,a/2)}},a=t.Latin1={stringify:function(c){var a=c.words;c=c.sigBytes;for(var m=[],f=0;f<c;f++)m.push(String.fromCharCode(a[f>>>2]>>>24-8*(f%4)&255));return m.join("")},parse:function(c){for(var a=c.length,m=[],f=0;f<a;f++)m[f>>>2]|=(c.charCodeAt(f)&255)<<24-8*(f%4);return new d.init(m,a)}},v=t.Utf8={stringify:function(c){try{return decodeURIComponent(escape(a.stringify(c)))}catch(u){throw Error("Malformed UTF-8 data");}},parse:function(c){return a.parse(unescape(encodeURIComponent(c)))}},
u=n.BufferedBlockAlgorithm=b.extend({reset:function(){this._data=new d.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=v.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var u=this._data,m=u.words,f=u.sigBytes,r=this.blockSize,e=f/(4*r),e=a?s.ceil(e):s.max((e|0)-this._minBufferSize,0);a=e*r;f=s.min(4*a,f);if(a){for(var b=0;b<a;b+=r)this._doProcessBlock(m,b);b=m.splice(0,a);u.sigBytes-=f}return new d.init(b,f)},clone:function(){var a=b.clone.call(this);
a._data=this._data.clone();return a},_minBufferSize:0});n.Hasher=u.extend({cfg:b.extend(),init:function(a){this.cfg=this.cfg.extend(a);this.reset()},reset:function(){u.reset.call(this);this._doReset()},update:function(a){this._append(a);this._process();return this},finalize:function(a){a&&this._append(a);return this._doFinalize()},blockSize:16,_createHelper:function(a){return function(u,m){return(new a.init(m)).finalize(u)}},_createHmacHelper:function(a){return function(u,m){return(new w.HMAC.init(a,
m)).finalize(u)}}});var w=e.algo={};return e}(Math);
(function(){var s=CryptoJS,l=s.lib.WordArray;s.enc.Base64={stringify:function(e){var n=e.words,l=e.sigBytes,b=this._map;e.clamp();e=[];for(var d=0;d<l;d+=3)for(var t=(n[d>>>2]>>>24-8*(d%4)&255)<<16|(n[d+1>>>2]>>>24-8*((d+1)%4)&255)<<8|n[d+2>>>2]>>>24-8*((d+2)%4)&255,q=0;4>q&&d+0.75*q<l;q++)e.push(b.charAt(t>>>6*(3-q)&63));if(n=b.charAt(64))for(;e.length%4;)e.push(n);return e.join("")},parse:function(e){var n=e.length,p=this._map,b=p.charAt(64);b&&(b=e.indexOf(b),-1!=b&&(n=b));for(var b=[],d=0,t=0;t<
n;t++)if(t%4){var q=p.indexOf(e.charAt(t-1))<<2*(t%4),a=p.indexOf(e.charAt(t))>>>6-2*(t%4);b[d>>>2]|=(q|a)<<24-8*(d%4);d++}return l.create(b,d)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})();
(function(s){function l(a,b,c,e,m,f,r){a=a+(b&c|~b&e)+m+r;return(a<<f|a>>>32-f)+b}function e(a,b,c,e,m,f,r){a=a+(b&e|c&~e)+m+r;return(a<<f|a>>>32-f)+b}function n(a,b,c,e,m,f,r){a=a+(b^c^e)+m+r;return(a<<f|a>>>32-f)+b}function p(a,b,c,e,m,f,r){a=a+(c^(b|~e))+m+r;return(a<<f|a>>>32-f)+b}for(var b=CryptoJS,d=b.lib,t=d.WordArray,q=d.Hasher,d=b.algo,a=[],v=0;64>v;v++)a[v]=4294967296*s.abs(s.sin(v+1))|0;d=d.MD5=q.extend({_doReset:function(){this._hash=new t.init([1732584193,4023233417,2562383102,271733878])},
_doProcessBlock:function(b,d){for(var c=0;16>c;c++){var q=d+c,m=b[q];b[q]=(m<<8|m>>>24)&16711935|(m<<24|m>>>8)&4278255360}var c=this._hash.words,q=b[d+0],m=b[d+1],f=b[d+2],r=b[d+3],x=b[d+4],t=b[d+5],s=b[d+6],v=b[d+7],y=b[d+8],z=b[d+9],A=b[d+10],B=b[d+11],C=b[d+12],D=b[d+13],E=b[d+14],F=b[d+15],g=c[0],h=c[1],j=c[2],k=c[3],g=l(g,h,j,k,q,7,a[0]),k=l(k,g,h,j,m,12,a[1]),j=l(j,k,g,h,f,17,a[2]),h=l(h,j,k,g,r,22,a[3]),g=l(g,h,j,k,x,7,a[4]),k=l(k,g,h,j,t,12,a[5]),j=l(j,k,g,h,s,17,a[6]),h=l(h,j,k,g,v,22,a[7]),
g=l(g,h,j,k,y,7,a[8]),k=l(k,g,h,j,z,12,a[9]),j=l(j,k,g,h,A,17,a[10]),h=l(h,j,k,g,B,22,a[11]),g=l(g,h,j,k,C,7,a[12]),k=l(k,g,h,j,D,12,a[13]),j=l(j,k,g,h,E,17,a[14]),h=l(h,j,k,g,F,22,a[15]),g=e(g,h,j,k,m,5,a[16]),k=e(k,g,h,j,s,9,a[17]),j=e(j,k,g,h,B,14,a[18]),h=e(h,j,k,g,q,20,a[19]),g=e(g,h,j,k,t,5,a[20]),k=e(k,g,h,j,A,9,a[21]),j=e(j,k,g,h,F,14,a[22]),h=e(h,j,k,g,x,20,a[23]),g=e(g,h,j,k,z,5,a[24]),k=e(k,g,h,j,E,9,a[25]),j=e(j,k,g,h,r,14,a[26]),h=e(h,j,k,g,y,20,a[27]),g=e(g,h,j,k,D,5,a[28]),k=e(k,g,
h,j,f,9,a[29]),j=e(j,k,g,h,v,14,a[30]),h=e(h,j,k,g,C,20,a[31]),g=n(g,h,j,k,t,4,a[32]),k=n(k,g,h,j,y,11,a[33]),j=n(j,k,g,h,B,16,a[34]),h=n(h,j,k,g,E,23,a[35]),g=n(g,h,j,k,m,4,a[36]),k=n(k,g,h,j,x,11,a[37]),j=n(j,k,g,h,v,16,a[38]),h=n(h,j,k,g,A,23,a[39]),g=n(g,h,j,k,D,4,a[40]),k=n(k,g,h,j,q,11,a[41]),j=n(j,k,g,h,r,16,a[42]),h=n(h,j,k,g,s,23,a[43]),g=n(g,h,j,k,z,4,a[44]),k=n(k,g,h,j,C,11,a[45]),j=n(j,k,g,h,F,16,a[46]),h=n(h,j,k,g,f,23,a[47]),g=p(g,h,j,k,q,6,a[48]),k=p(k,g,h,j,v,10,a[49]),j=p(j,k,g,h,
E,15,a[50]),h=p(h,j,k,g,t,21,a[51]),g=p(g,h,j,k,C,6,a[52]),k=p(k,g,h,j,r,10,a[53]),j=p(j,k,g,h,A,15,a[54]),h=p(h,j,k,g,m,21,a[55]),g=p(g,h,j,k,y,6,a[56]),k=p(k,g,h,j,F,10,a[57]),j=p(j,k,g,h,s,15,a[58]),h=p(h,j,k,g,D,21,a[59]),g=p(g,h,j,k,x,6,a[60]),k=p(k,g,h,j,B,10,a[61]),j=p(j,k,g,h,f,15,a[62]),h=p(h,j,k,g,z,21,a[63]);c[0]=c[0]+g|0;c[1]=c[1]+h|0;c[2]=c[2]+j|0;c[3]=c[3]+k|0},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32;var m=s.floor(c/
4294967296);b[(d+64>>>9<<4)+15]=(m<<8|m>>>24)&16711935|(m<<24|m>>>8)&4278255360;b[(d+64>>>9<<4)+14]=(c<<8|c>>>24)&16711935|(c<<24|c>>>8)&4278255360;a.sigBytes=4*(b.length+1);this._process();a=this._hash;b=a.words;for(c=0;4>c;c++)d=b[c],b[c]=(d<<8|d>>>24)&16711935|(d<<24|d>>>8)&4278255360;return a},clone:function(){var a=q.clone.call(this);a._hash=this._hash.clone();return a}});b.MD5=q._createHelper(d);b.HmacMD5=q._createHmacHelper(d)})(Math);
(function(){var s=CryptoJS,l=s.lib,e=l.Base,n=l.WordArray,l=s.algo,p=l.EvpKDF=e.extend({cfg:e.extend({keySize:4,hasher:l.MD5,iterations:1}),init:function(b){this.cfg=this.cfg.extend(b)},compute:function(b,d){for(var e=this.cfg,q=e.hasher.create(),a=n.create(),l=a.words,p=e.keySize,e=e.iterations;l.length<p;){s&&q.update(s);var s=q.update(b).finalize(d);q.reset();for(var c=1;c<e;c++)s=q.finalize(s),q.reset();a.concat(s)}a.sigBytes=4*p;return a}});s.EvpKDF=function(b,d,e){return p.create(e).compute(b,
d)}})();
CryptoJS.lib.Cipher||function(s){var l=CryptoJS,e=l.lib,n=e.Base,p=e.WordArray,b=e.BufferedBlockAlgorithm,d=l.enc.Base64,t=l.algo.EvpKDF,q=e.Cipher=b.extend({cfg:n.extend(),createEncryptor:function(a,f){return this.create(this._ENC_XFORM_MODE,a,f)},createDecryptor:function(a,f){return this.create(this._DEC_XFORM_MODE,a,f)},init:function(a,f,c){this.cfg=this.cfg.extend(c);this._xformMode=a;this._key=f;this.reset()},reset:function(){b.reset.call(this);this._doReset()},process:function(a){this._append(a);return this._process()},
finalize:function(a){a&&this._append(a);return this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(a){return{encrypt:function(f,b,d){return("string"==typeof b?G:c).encrypt(a,f,b,d)},decrypt:function(f,b,d){return("string"==typeof b?G:c).decrypt(a,f,b,d)}}}});e.StreamCipher=q.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var a=l.mode={},v=function(a,f,b){var c=this._iv;c?this._iv=s:c=this._prevBlock;for(var d=0;d<b;d++)a[f+d]^=
c[d]},u=(e.BlockCipherMode=n.extend({createEncryptor:function(a,f){return this.Encryptor.create(a,f)},createDecryptor:function(a,f){return this.Decryptor.create(a,f)},init:function(a,f){this._cipher=a;this._iv=f}})).extend();u.Encryptor=u.extend({processBlock:function(a,f){var b=this._cipher,c=b.blockSize;v.call(this,a,f,c);b.encryptBlock(a,f);this._prevBlock=a.slice(f,f+c)}});u.Decryptor=u.extend({processBlock:function(a,f){var b=this._cipher,c=b.blockSize,d=a.slice(f,f+c);b.decryptBlock(a,f);v.call(this,
a,f,c);this._prevBlock=d}});a=a.CBC=u;u=(l.pad={}).Pkcs7={pad:function(a,f){for(var b=4*f,b=b-a.sigBytes%b,c=b<<24|b<<16|b<<8|b,d=[],e=0;e<b;e+=4)d.push(c);b=p.create(d,b);a.concat(b)},unpad:function(a){a.sigBytes-=a.words[a.sigBytes-1>>>2]&255}};e.BlockCipher=q.extend({cfg:q.cfg.extend({mode:a,padding:u}),reset:function(){q.reset.call(this);var a=this.cfg,b=a.iv,a=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var c=a.createEncryptor;else c=a.createDecryptor,this._minBufferSize=1;this._mode=c.call(a,
this,b&&b.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else b=this._process(!0),a.unpad(b);return b},blockSize:4});var w=e.CipherParams=n.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}}),a=(l.format={}).OpenSSL={stringify:function(a){var b=a.ciphertext;a=a.salt;return(a?p.create([1398893684,
1701076831]).concat(a).concat(b):b).toString(d)},parse:function(a){a=d.parse(a);var b=a.words;if(1398893684==b[0]&&1701076831==b[1]){var c=p.create(b.slice(2,4));b.splice(0,4);a.sigBytes-=16}return w.create({ciphertext:a,salt:c})}},c=e.SerializableCipher=n.extend({cfg:n.extend({format:a}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=a.createEncryptor(c,d);b=e.finalize(b);e=e.cfg;return w.create({ciphertext:b,key:c,iv:e.iv,algorithm:a,mode:e.mode,padding:e.padding,blockSize:a.blockSize,formatter:d.format})},
decrypt:function(a,b,c,d){d=this.cfg.extend(d);b=this._parse(b,d.format);return a.createDecryptor(c,d).finalize(b.ciphertext)},_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),l=(l.kdf={}).OpenSSL={execute:function(a,b,c,d){d||(d=p.random(8));a=t.create({keySize:b+c}).compute(a,d);c=p.create(a.words.slice(b),4*c);a.sigBytes=4*b;return w.create({key:a,iv:c,salt:d})}},G=e.PasswordBasedCipher=c.extend({cfg:c.cfg.extend({kdf:l}),encrypt:function(a,b,d,e){e=this.cfg.extend(e);d=e.kdf.execute(d,
a.keySize,a.ivSize);e.iv=d.iv;a=c.encrypt.call(this,a,b,d.key,e);a.mixIn(d);return a},decrypt:function(a,b,d,e){e=this.cfg.extend(e);b=this._parse(b,e.format);d=e.kdf.execute(d,a.keySize,a.ivSize,b.salt);e.iv=d.iv;return c.decrypt.call(this,a,b,d.key,e)}})}();
(function(){function s(){for(var b=this._S,d=this._i,e=this._j,q=0,a=0;4>a;a++){var d=(d+1)%256,e=(e+b[d])%256,l=b[d];b[d]=b[e];b[e]=l;q|=b[(b[d]+b[e])%256]<<24-8*a}this._i=d;this._j=e;return q}var l=CryptoJS,e=l.lib.StreamCipher,n=l.algo,p=n.RC4=e.extend({_doReset:function(){for(var b=this._key,d=b.words,b=b.sigBytes,e=this._S=[],l=0;256>l;l++)e[l]=l;for(var a=l=0;256>l;l++){var n=l%b,a=(a+e[l]+(d[n>>>2]>>>24-8*(n%4)&255))%256,n=e[l];e[l]=e[a];e[a]=n}this._i=this._j=0},_doProcessBlock:function(b,
d){b[d]^=s.call(this)},keySize:8,ivSize:0});l.RC4=e._createHelper(p);n=n.RC4Drop=p.extend({cfg:p.cfg.extend({drop:192}),_doReset:function(){p._doReset.call(this);for(var b=this.cfg.drop;0<b;b--)s.call(this)}});l.RC4Drop=e._createHelper(n)})();
| quenlang/NetopGO | static/scripts/libs/cryptojs/rollups/rc4.js | JavaScript | apache-2.0 | 12,159 |
/**
* Usage for accepting signatures:
* $('.sigPad').signaturePad()
*
* Usage for displaying previous signatures:
* $('.sigPad').signaturePad({displayOnly:true}).regenerate(sig)
* or
* var api = $('.sigPad').signaturePad({displayOnly:true})
* api.regenerate(sig)
*/
(function ($) {
function SignaturePad (selector, options) {
/**
* Reference to the object for use in public methods
*
* @private
*
* @type {Object}
*/
var self = this
/**
* Holds the merged default settings and user passed settings
*
* @private
*
* @type {Object}
*/
, settings = $.extend({}, $.fn.signaturePad.defaults, options)
/**
* The current context, as passed by jQuery, of selected items
*
* @private
*
* @type {Object}
*/
, context = $(selector)
/**
* jQuery reference to the canvas element inside the signature pad
*
* @private
*
* @type {Object}
*/
, canvas = $(settings.canvas, context)
/**
* Dom reference to the canvas element inside the signature pad
*
* @private
*
* @type {Object}
*/
, element = canvas.get(0)
/**
* The drawing context for the signature canvas
*
* @private
*
* @type {Object}
*/
, canvasContext = null
/**
* Holds the previous point of drawing
* Disallows drawing over the same location to make lines more delicate
*
* @private
*
* @type {Object}
*/
, previous = {'x': null, 'y': null}
/**
* An array holding all the points and lines to generate the signature
* Each item is an object like:
* {
* mx: moveTo x coordinate
* my: moveTo y coordinate
* lx: lineTo x coordinate
* lx: lineTo y coordinate
* }
*
* @private
*
* @type {Array}
*/
, output = []
/**
* Stores a timeout for when the mouse leaves the canvas
* If the mouse has left the canvas for a specific amount of time
* Stops drawing on the canvas
*
* @private
*
* @type {Object}
*/
, mouseLeaveTimeout = false
/**
* Whether the mouse button is currently pressed down or not
*
* @private
*
* @type {Boolean}
*/
, mouseButtonDown = false
/**
* Whether the browser is a touch event browser or not
*
* @private
*
* @type {Boolean}
*/
, touchable = false
/**
* Whether events have already been bound to the canvas or not
*
* @private
*
* @type {Boolean}
*/
, eventsBound = false
/**
* Remembers the default font-size when typing, and will allow it to be scaled for bigger/smaller names
*
* @private
*
* @type {Number}
*/
, typeItDefaultFontSize = 30
/**
* Remembers the current font-size when typing
*
* @private
*
* @type {Number}
*/
, typeItCurrentFontSize = typeItDefaultFontSize
/**
* Remembers how many characters are in the name field, to help with the scaling feature
*
* @private
*
* @type {Number}
*/
, typeItNumChars = 0
/**
* Clears the mouseLeaveTimeout
* Resets some other variables that may be active
*
* @private
*/
function clearMouseLeaveTimeout () {
clearTimeout(mouseLeaveTimeout)
mouseLeaveTimeout = false
mouseButtonDown = false
}
/**
* Draws a line on canvas using the mouse position
* Checks previous position to not draw over top of previous drawing
* (makes the line really thick and poorly anti-aliased)
*
* @private
*
* @param {Object} e The event object
* @param {Number} newYOffset A pixel value for drawing the newY, used for drawing a single dot on click
*/
function drawLine (e, newYOffset) {
var offset, newX, newY
e.preventDefault()
offset = $(e.target).offset()
clearTimeout(mouseLeaveTimeout)
mouseLeaveTimeout = false
if (typeof e.targetTouches !== 'undefined') {
newX = Math.floor(e.targetTouches[0].pageX - offset.left)
newY = Math.floor(e.targetTouches[0].pageY - offset.top)
} else {
newX = Math.floor(e.pageX - offset.left)
newY = Math.floor(e.pageY - offset.top)
}
if (previous.x === newX && previous.y === newY)
return true
if (previous.x === null)
previous.x = newX
if (previous.y === null)
previous.y = newY
if (newYOffset)
newY += newYOffset
canvasContext.beginPath()
canvasContext.moveTo(previous.x, previous.y)
canvasContext.lineTo(newX, newY)
canvasContext.lineCap = settings.penCap
canvasContext.stroke()
canvasContext.closePath()
output.push({
'lx' : newX
, 'ly' : newY
, 'mx' : previous.x
, 'my' : previous.y
})
previous.x = newX
previous.y = newY
if (settings.onDraw && typeof settings.onDraw === 'function')
settings.onDraw.apply(self)
}
/**
* Callback wrapper for executing stopDrawing without the event
* Put up here so that it can be removed at a later time
*
* @private
*/
function stopDrawingWrapper () {
stopDrawing()
}
/**
* Callback registered to mouse/touch events of the canvas
* Stops the drawing abilities
*
* @private
*
* @param {Object} e The event object
*/
function stopDrawing (e) {
if (!!e) {
drawLine(e, 1)
} else {
if (touchable) {
canvas.each(function () {
this.removeEventListener('touchmove', drawLine)
// this.removeEventListener('MSPointerMove', drawLine)
})
} else {
canvas.unbind('mousemove.signaturepad')
}
if (output.length > 0 && settings.onDrawEnd && typeof settings.onDrawEnd === 'function')
settings.onDrawEnd.apply(self)
}
previous.x = null
previous.y = null
if (settings.output && output.length > 0)
$(settings.output, context).val(JSON.stringify(output))
}
/**
* Draws the signature line
*
* @private
*/
function drawSigLine () {
if (!settings.lineWidth)
return false
canvasContext.beginPath()
canvasContext.lineWidth = settings.lineWidth
canvasContext.strokeStyle = settings.lineColour
canvasContext.moveTo(settings.lineMargin, settings.lineTop)
canvasContext.lineTo(element.width - settings.lineMargin, settings.lineTop)
canvasContext.stroke()
canvasContext.closePath()
}
/**
* Clears all drawings off the canvas and redraws the signature line
*
* @private
*/
function clearCanvas () {
canvasContext.clearRect(0, 0, element.width, element.height)
canvasContext.fillStyle = settings.bgColour
canvasContext.fillRect(0, 0, element.width, element.height)
if (!settings.displayOnly)
drawSigLine()
canvasContext.lineWidth = settings.penWidth
canvasContext.strokeStyle = settings.penColour
$(settings.output, context).val('')
output = []
stopDrawing()
}
/**
* Callback registered to mouse/touch events of the canvas
* Draws a line at the mouse cursor location, starting a new line if necessary
*
* @private
*
* @param {Object} e The event object
* @param {Object} o The object context registered to the event; canvas
*/
function onMouseMove(e, o) {
if (previous.x == null) {
drawLine(e, 1)
} else {
drawLine(e, o)
}
}
/**
* Callback registered to mouse/touch events of canvas
* Triggers the drawLine function
*
* @private
*
* @param {Object} e The event object
* @param {Object} touchObject The object context registered to the event; canvas
*/
function startDrawing (e, touchObject) {
if (touchable) {
touchObject.addEventListener('touchmove', onMouseMove, false)
// touchObject.addEventListener('MSPointerMove', onMouseMove, false)
} else {
canvas.bind('mousemove.signaturepad', onMouseMove)
}
// Draws a single point on initial mouse down, for people with periods in their name
drawLine(e, 1)
}
/**
* Removes all the mouse events from the canvas
*
* @private
*/
function disableCanvas () {
eventsBound = false
canvas.each(function () {
if (this.removeEventListener) {
this.removeEventListener('touchend', stopDrawingWrapper)
this.removeEventListener('touchcancel', stopDrawingWrapper)
this.removeEventListener('touchmove', drawLine)
// this.removeEventListener('MSPointerUp', stopDrawingWrapper)
// this.removeEventListener('MSPointerCancel', stopDrawingWrapper)
// this.removeEventListener('MSPointerMove', drawLine)
}
if (this.ontouchstart)
this.ontouchstart = null;
})
$(document).unbind('mouseup.signaturepad')
canvas.unbind('mousedown.signaturepad')
canvas.unbind('mousemove.signaturepad')
canvas.unbind('mouseleave.signaturepad')
$(settings.clear, context).unbind('click.signaturepad')
}
/**
* Lazy touch event detection
* Uses the first press on the canvas to detect either touch or mouse reliably
* Will then bind other events as needed
*
* @private
*
* @param {Object} e The event object
*/
function initDrawEvents (e) {
if (eventsBound)
return false
eventsBound = true
// Closes open keyboards to free up space
$('input').blur();
if (typeof e.targetTouches !== 'undefined')
touchable = true
if (touchable) {
canvas.each(function () {
this.addEventListener('touchend', stopDrawingWrapper, false)
this.addEventListener('touchcancel', stopDrawingWrapper, false)
// this.addEventListener('MSPointerUp', stopDrawingWrapper, false)
// this.addEventListener('MSPointerCancel', stopDrawingWrapper, false)
})
canvas.unbind('mousedown.signaturepad')
} else {
$(document).bind('mouseup.signaturepad', function () {
if (mouseButtonDown) {
stopDrawing()
clearMouseLeaveTimeout()
}
})
canvas.bind('mouseleave.signaturepad', function (e) {
if (mouseButtonDown) stopDrawing(e)
if (mouseButtonDown && !mouseLeaveTimeout) {
mouseLeaveTimeout = setTimeout(function () {
stopDrawing()
clearMouseLeaveTimeout()
}, 500)
}
})
canvas.each(function () {
this.ontouchstart = null
})
}
}
/**
* Triggers the abilities to draw on the canvas
* Sets up mouse/touch events, hides and shows descriptions and sets current classes
*
* @private
*/
function drawIt () {
$(settings.typed, context).hide()
clearCanvas()
canvas.each(function () {
this.ontouchstart = function (e) {
e.preventDefault()
mouseButtonDown = true
initDrawEvents(e)
startDrawing(e, this)
}
})
canvas.bind('mousedown.signaturepad', function (e) {
e.preventDefault()
// Only allow left mouse clicks to trigger signature drawing
if (e.which > 1) return false
mouseButtonDown = true
initDrawEvents(e)
startDrawing(e)
})
$(settings.clear, context).bind('click.signaturepad', function (e) { e.preventDefault(); clearCanvas() })
$(settings.typeIt, context).bind('click.signaturepad', function (e) { e.preventDefault(); typeIt() })
$(settings.drawIt, context).unbind('click.signaturepad')
$(settings.drawIt, context).bind('click.signaturepad', function (e) { e.preventDefault() })
$(settings.typeIt, context).removeClass(settings.currentClass)
$(settings.drawIt, context).addClass(settings.currentClass)
$(settings.sig, context).addClass(settings.currentClass)
$(settings.typeItDesc, context).hide()
$(settings.drawItDesc, context).show()
$(settings.clear, context).show()
}
/**
* Triggers the abilities to type in the input for generating a signature
* Sets up mouse events, hides and shows descriptions and sets current classes
*
* @private
*/
function typeIt () {
clearCanvas()
disableCanvas()
$(settings.typed, context).show()
$(settings.drawIt, context).bind('click.signaturepad', function (e) { e.preventDefault(); drawIt() })
$(settings.typeIt, context).unbind('click.signaturepad')
$(settings.typeIt, context).bind('click.signaturepad', function (e) { e.preventDefault() })
$(settings.output, context).val('')
$(settings.drawIt, context).removeClass(settings.currentClass)
$(settings.typeIt, context).addClass(settings.currentClass)
$(settings.sig, context).removeClass(settings.currentClass)
$(settings.drawItDesc, context).hide()
$(settings.clear, context).hide()
$(settings.typeItDesc, context).show()
typeItCurrentFontSize = typeItDefaultFontSize = $(settings.typed, context).css('font-size').replace(/px/, '')
}
/**
* Callback registered on key up and blur events for input field
* Writes the text fields value as Html into an element
*
* @private
*
* @param {String} val The value of the input field
*/
function type (val) {
var typed = $(settings.typed, context)
, cleanedVal = val.replace(/>/g, '>').replace(/</g, '<').trim()
, oldLength = typeItNumChars
, edgeOffset = typeItCurrentFontSize * 0.5
typeItNumChars = cleanedVal.length
typed.html(cleanedVal)
if (!cleanedVal) {
typed.css('font-size', typeItDefaultFontSize + 'px')
return
}
if (typeItNumChars > oldLength && typed.outerWidth() > element.width) {
while (typed.outerWidth() > element.width) {
typeItCurrentFontSize--
typed.css('font-size', typeItCurrentFontSize + 'px')
}
}
if (typeItNumChars < oldLength && typed.outerWidth() + edgeOffset < element.width && typeItCurrentFontSize < typeItDefaultFontSize) {
while (typed.outerWidth() + edgeOffset < element.width && typeItCurrentFontSize < typeItDefaultFontSize) {
typeItCurrentFontSize++
typed.css('font-size', typeItCurrentFontSize + 'px')
}
}
}
/**
* Default onBeforeValidate function to clear errors
*
* @private
*
* @param {Object} context current context object
* @param {Object} settings provided settings
*/
function onBeforeValidate (context, settings) {
$('p.' + settings.errorClass, context).remove()
context.removeClass(settings.errorClass)
$('input, label', context).removeClass(settings.errorClass)
}
/**
* Default onFormError function to show errors
*
* @private
*
* @param {Object} errors object contains validation errors (e.g. nameInvalid=true)
* @param {Object} context current context object
* @param {Object} settings provided settings
*/
function onFormError (errors, context, settings) {
if (errors.nameInvalid) {
context.prepend(['<p class="', settings.errorClass, '">', settings.errorMessage, '</p>'].join(''))
$(settings.name, context).focus()
$(settings.name, context).addClass(settings.errorClass)
$('label[for=' + $(settings.name).attr('id') + ']', context).addClass(settings.errorClass)
}
if (errors.drawInvalid)
context.prepend(['<p class="', settings.errorClass, '">', settings.errorMessageDraw, '</p>'].join(''))
}
/**
* Validates the form to confirm a name was typed in the field
* If drawOnly also confirms that the user drew a signature
*
* @private
*
* @return {Boolean}
*/
function validateForm () {
var valid = true
, errors = {drawInvalid: false, nameInvalid: false}
, onBeforeArguments = [context, settings]
, onErrorArguments = [errors, context, settings]
if (settings.onBeforeValidate && typeof settings.onBeforeValidate === 'function') {
settings.onBeforeValidate.apply(self,onBeforeArguments)
} else {
onBeforeValidate.apply(self, onBeforeArguments)
}
if (settings.drawOnly && output.length < 1) {
errors.drawInvalid = true
valid = false
}
if ($(settings.name, context).val() === '') {
errors.nameInvalid = true
valid = false
}
if (settings.onFormError && typeof settings.onFormError === 'function') {
settings.onFormError.apply(self,onErrorArguments)
} else {
onFormError.apply(self, onErrorArguments)
}
return valid
}
/**
* Redraws the signature on a specific canvas
*
* @private
*
* @param {Array} paths the signature JSON
* @param {Object} context the canvas context to draw on
* @param {Boolean} saveOutput whether to write the path to the output array or not
*/
function drawSignature (paths, context, saveOutput) {
for(var i in paths) {
if (typeof paths[i] === 'object') {
context.beginPath()
context.moveTo(paths[i].mx, paths[i].my)
context.lineTo(paths[i].lx, paths[i].ly)
context.lineCap = settings.penCap
context.stroke()
context.closePath()
if (saveOutput) {
output.push({
'lx' : paths[i].lx
, 'ly' : paths[i].ly
, 'mx' : paths[i].mx
, 'my' : paths[i].my
})
}
}
}
}
/**
* Initialisation function, called immediately after all declarations
* Technically public, but only should be used internally
*
* @private
*/
function init () {
// Fixes the jQuery.fn.offset() function for Mobile Safari Browsers i.e. iPod Touch, iPad and iPhone
// https://gist.github.com/661844
// http://bugs.jquery.com/ticket/6446
if (parseFloat(((/CPU.+OS ([0-9_]{3}).*AppleWebkit.*Mobile/i.exec(navigator.userAgent)) || [0,'4_2'])[1].replace('_','.')) < 4.1) {
$.fn.Oldoffset = $.fn.offset;
$.fn.offset = function () {
var result = $(this).Oldoffset()
result.top -= window.scrollY
result.left -= window.scrollX
return result
}
}
// Disable selection on the typed div and canvas
$(settings.typed, context).bind('selectstart.signaturepad', function (e) { return $(e.target).is(':input') })
canvas.bind('selectstart.signaturepad', function (e) { return $(e.target).is(':input') })
if (!element.getContext && FlashCanvas)
FlashCanvas.initElement(element)
if (element.getContext) {
canvasContext = element.getContext('2d')
$(settings.sig, context).show()
if (!settings.displayOnly) {
if (!settings.drawOnly) {
$(settings.name, context).bind('keyup.signaturepad', function () {
type($(this).val())
})
$(settings.name, context).bind('blur.signaturepad', function () {
type($(this).val())
})
$(settings.drawIt, context).bind('click.signaturepad', function (e) {
e.preventDefault()
drawIt()
})
}
if (settings.drawOnly || settings.defaultAction === 'drawIt') {
drawIt()
} else {
typeIt()
}
if (settings.validateFields) {
if ($(selector).is('form')) {
$(selector).bind('submit.signaturepad', function () { return validateForm() })
} else {
$(selector).parents('form').bind('submit.signaturepad', function () { return validateForm() })
}
}
$(settings.sigNav, context).show()
}
}
}
$.extend(self, {
/**
* A property to store the current version of Signature Pad
*/
signaturePad : '{{version}}'
/**
* Initializes SignaturePad
*/
, init : function () { init() }
/**
* Allows options to be updated after initialization
*
* @param {Object} options An object containing the options to be changed
*/
, updateOptions : function (options) {
$.extend(settings, options)
}
/**
* Regenerates a signature on the canvas using an array of objects
* Follows same format as object property
* @see var object
*
* @param {Array} paths An array of the lines and points
*/
, regenerate : function (paths) {
self.clearCanvas()
$(settings.typed, context).hide()
if (typeof paths === 'string')
paths = JSON.parse(paths)
drawSignature(paths, canvasContext, true)
if (settings.output && $(settings.output, context).length > 0)
$(settings.output, context).val(JSON.stringify(output))
}
/**
* Clears the canvas
* Redraws the background colour and the signature line
*/
, clearCanvas : function () { clearCanvas() }
/**
* Returns the signature as a Js array
*
* @return {Array}
*/
, getSignature : function () { return output }
/**
* Returns the signature as a Json string
*
* @return {String}
*/
, getSignatureString : function () { return JSON.stringify(output) }
/**
* Returns the signature as an image
* Re-draws the signature in a shadow canvas to create a clean version
*
* @return {String}
*/
, getSignatureImage : function () {
var tmpCanvas = document.createElement('canvas')
, tmpContext = null
, data = null
tmpCanvas.style.position = 'absolute'
tmpCanvas.style.top = '-999em'
tmpCanvas.width = element.width
tmpCanvas.height = element.height
document.body.appendChild(tmpCanvas)
if (!tmpCanvas.getContext && FlashCanvas)
FlashCanvas.initElement(tmpCanvas)
tmpContext = tmpCanvas.getContext('2d')
tmpContext.fillStyle = settings.bgColour
tmpContext.fillRect(0, 0, element.width, element.height)
tmpContext.lineWidth = settings.penWidth
tmpContext.strokeStyle = settings.penColour
drawSignature(output, tmpContext)
data = tmpCanvas.toDataURL.apply(tmpCanvas, arguments)
document.body.removeChild(tmpCanvas)
tmpCanvas = null
return data
}
/**
* The form validation function
* Validates that the signature has been filled in properly
* Allows it to be hooked into another validation function and called at a different time
*
* @return {Boolean}
*/
, validateForm : function () { return validateForm() }
})
}
/**
* Create the plugin
* Returns an Api which can be used to call specific methods
*
* @param {Object} options The options array
*
* @return {Object} The Api for controlling the instance
*/
$.fn.signaturePad = function (options) {
var api = null
this.each(function () {
if (!$.data(this, 'plugin-signaturePad')) {
api = new SignaturePad(this, options)
api.init()
$.data(this, 'plugin-signaturePad', api)
} else {
api = $.data(this, 'plugin-signaturePad')
api.updateOptions(options)
}
})
return api
}
/**
* Expose the defaults so they can be overwritten for multiple instances
*
* @type {Object}
*/
$.fn.signaturePad.defaults = {
defaultAction : 'typeIt' // What action should be highlighted first: typeIt or drawIt
, displayOnly : false // Initialize canvas for signature display only; ignore buttons and inputs
, drawOnly : false // Whether the to allow a typed signature or not
, canvas : 'canvas' // Selector for selecting the canvas element
, sig : '.sig' // Parts of the signature form that require Javascript (hidden by default)
, sigNav : '.sigNav' // The TypeIt/DrawIt navigation (hidden by default)
, bgColour : '#ffffff' // The colour fill for the background of the canvas; or transparent
, penColour : '#145394' // Colour of the drawing ink
, penWidth : 2 // Thickness of the pen
, penCap : 'round' // Determines how the end points of each line are drawn (values: 'butt', 'round', 'square')
, lineColour : '#ccc' // Colour of the signature line
, lineWidth : 2 // Thickness of the signature line
, lineMargin : 5 // Margin on right and left of signature line
, lineTop : 35 // Distance to draw the line from the top
, name : '.name' // The input field for typing a name
, typed : '.typed' // The Html element to accept the printed name
, clear : '.clearButton' // Button for clearing the canvas
, typeIt : '.typeIt a' // Button to trigger name typing actions (current by default)
, drawIt : '.drawIt a' // Button to trigger name drawing actions
, typeItDesc : '.typeItDesc' // The description for TypeIt actions
, drawItDesc : '.drawItDesc' // The description for DrawIt actions (hidden by default)
, output : '.output' // The hidden input field for remembering line coordinates
, currentClass : 'current' // The class used to mark items as being currently active
, validateFields : true // Whether the name, draw fields should be validated
, errorClass : 'error' // The class applied to the new error Html element
, errorMessage : 'Please enter your name' // The error message displayed on invalid submission
, errorMessageDraw : 'Please sign the document' // The error message displayed when drawOnly and no signature is drawn
, onBeforeValidate : null // Pass a callback to be used instead of the built-in function
, onFormError : null // Pass a callback to be used instead of the built-in function
, onDraw : null // Pass a callback to be used to capture the drawing process
, onDrawEnd : null // Pass a callback to be exectued after the drawing process
}
}(jQuery))
| cornernote/yii-dressing | yii-dressing/assets/signature-pad/jquery.signaturepad.js | JavaScript | bsd-3-clause | 25,256 |
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Copyright 2006 Google Inc. All Rights Reserved.
/**
* @fileoverview Anchored viewport positioning class with both adjust and
* resize options for the popup.
*
*/
goog.provide('goog.positioning.MenuAnchoredPosition');
goog.require('goog.math.Box');
goog.require('goog.math.Coordinate');
goog.require('goog.math.Size');
goog.require('goog.positioning');
goog.require('goog.positioning.AnchoredViewportPosition');
goog.require('goog.positioning.Corner');
goog.require('goog.positioning.CornerBit');
goog.require('goog.positioning.Overflow');
goog.require('goog.positioning.OverflowStatus');
/**
* Encapsulates a popup position where the popup is anchored at a corner of
* an element. The positioning behavior changes based on the values of
* opt_adjust and opt_resize.
*
* When using this positioning object it's recommended that the movable element
* be absolutely positioned.
*
* @param {Element} anchorElement Element the movable element should be
* anchored against.
* @param {goog.positioning.Corner} corner Corner of anchored element the
* movable element should be positioned at.
* @param {boolean} opt_adjust Whether the positioning should be adjusted until
* the element fits inside the viewport even if that means that the anchored
* corners are ignored.
* @param {boolean} opt_resize Whether the positioning should be adjusted until
* the element fits inside the viewport on the X axis and it's heigh is
* resized so if fits in the viewport. This take precedence over
* opt_adjust.
* @constructor
* @extends {goog.positioning.AnchoredViewportPosition}
*/
goog.positioning.MenuAnchoredPosition = function(anchorElement,
corner,
opt_adjust,
opt_resize) {
goog.positioning.AnchoredViewportPosition.call(this, anchorElement, corner,
opt_adjust);
/**
* Whether the positioning should be adjusted until the element fits inside
* the viewport even if that means that the anchored corners are ignored.
* @type {boolean|undefined}
* @private
*/
this.resize_ = opt_resize;
};
goog.inherits(goog.positioning.MenuAnchoredPosition,
goog.positioning.AnchoredViewportPosition);
/**
* Repositions the movable element.
*
* @param {Element} movableElement Element to position.
* @param {goog.positioning.Corner} movableCorner Corner of the movable element
* that should be positioned adjacent to the anchored element.
* @param {goog.math.Box} opt_margin A margin specifin pixels.
* @param {goog.math.Size} opt_preferredSize Preferred size of the
* moveableElement.
*/
goog.positioning.MenuAnchoredPosition.prototype.reposition =
function(movableElement, movableCorner, opt_margin, opt_preferredSize) {
if (this.resize_) {
goog.positioning.positionAtAnchor(this.element, this.corner,
movableElement, movableCorner, null, opt_margin,
goog.positioning.Overflow.ADJUST_X |
goog.positioning.Overflow.RESIZE_HEIGHT, opt_preferredSize);
} else {
goog.positioning.MenuAnchoredPosition.superClass_.reposition.call(
this,
movableElement,
movableCorner,
opt_margin,
opt_preferredSize);
}
};
| yesudeep/puppy | tools/google-closure-library/closure/goog/positioning/menuanchoredposition.js | JavaScript | mit | 3,921 |
let x = { a: (b ? 1 : 2)};
| jimenglish81/ember-suave | tests/fixtures/rules/require-spaces-inside-object-brackets/bad/nested-object.js | JavaScript | mit | 27 |
angular.module('examples', [])
.factory('formPostData', ['$document', function($document) {
return function(url, fields) {
var form = angular.element('<form style="display: none;" method="post" action="' + url + '" target="_blank"></form>');
angular.forEach(fields, function(value, name) {
var input = angular.element('<input type="hidden" name="' + name + '">');
input.attr('value', value);
form.append(input);
});
$document.find('body').append(form);
form[0].submit();
form.remove();
};
}])
.factory('openPlunkr', ['formPostData', '$http', '$q', function(formPostData, $http, $q) {
return function(exampleFolder) {
var exampleName = 'AngularJS Example';
// Load the manifest for the example
$http.get(exampleFolder + '/manifest.json')
.then(function(response) {
return response.data;
})
.then(function(manifest) {
var filePromises = [];
// Build a pretty title for the Plunkr
var exampleNameParts = manifest.name.split('-');
exampleNameParts.unshift('AngularJS');
angular.forEach(exampleNameParts, function(part, index) {
exampleNameParts[index] = part.charAt(0).toUpperCase() + part.substr(1);
});
exampleName = exampleNameParts.join(' - ');
angular.forEach(manifest.files, function(filename) {
filePromises.push($http.get(exampleFolder + '/' + filename, { transformResponse: [] })
.then(function(response) {
// The manifests provide the production index file but Plunkr wants
// a straight index.html
if (filename === "index-production.html") {
filename = "index.html"
}
return {
name: filename,
content: response.data
};
}));
});
return $q.all(filePromises);
})
.then(function(files) {
var postData = {};
angular.forEach(files, function(file) {
postData['files[' + file.name + ']'] = file.content;
});
postData['tags[0]'] = "angularjs";
postData['tags[1]'] = "example";
postData.private = true;
postData.description = exampleName;
formPostData('http://plnkr.co/edit/?p=preview', postData);
});
};
}]); | niluka2a/angular.js | docs/app/src/examples.js | JavaScript | mit | 2,355 |
// Generated by CoffeeScript 1.4.0
var isDefined,
__bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; },
__slice = [].slice,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
window.serious = {};
window.serious.Utils = {};
isDefined = function(obj) {
return typeof obj !== 'undefined' && obj !== null;
};
jQuery.fn.opacity = function(int) {
return $(this).css({
opacity: int
});
};
window.serious.Utils.clone = function(obj) {
var flags, key, newInstance;
if (!(obj != null) || typeof obj !== 'object') {
return obj;
}
if (obj instanceof Date) {
return new Date(obj.getTime());
}
if (obj instanceof RegExp) {
flags = '';
if (obj.global != null) {
flags += 'g';
}
if (obj.ignoreCase != null) {
flags += 'i';
}
if (obj.multiline != null) {
flags += 'm';
}
if (obj.sticky != null) {
flags += 'y';
}
return new RegExp(obj.source, flags);
}
newInstance = new obj.constructor();
for (key in obj) {
newInstance[key] = window.serious.Utils.clone(obj[key]);
}
return newInstance;
};
jQuery.fn.cloneTemplate = function(dict, removeUnusedField) {
var klass, nui, value;
if (removeUnusedField == null) {
removeUnusedField = false;
}
nui = $(this[0]).clone();
nui = nui.removeClass("template hidden").addClass("actual");
if (typeof dict === "object") {
for (klass in dict) {
value = dict[klass];
if (value !== null) {
nui.find(".out." + klass).html(value);
}
}
if (removeUnusedField) {
nui.find(".out").each(function() {
if ($(this).html() === "") {
return $(this).remove();
}
});
}
}
return nui;
};
Object.size = function(obj) {
var key, size;
size = 0;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
size++;
}
}
return size;
};
window.serious.States = (function() {
function States() {
this.states = {};
}
States.prototype.set = function(state, value, scope) {
if (value == null) {
value = true;
}
if (scope == null) {
scope = document;
}
this.states[state] = value;
return this._showState(state, value);
};
States.prototype._showState = function(state, value, scope) {
if (value == null) {
value = true;
}
if (scope == null) {
scope = document;
}
$(".when-" + state, scope).each(function(idx, element) {
var expected_value;
element = $(element);
expected_value = element.data('state') || true;
return $(element).toggleClass('hidden', expected_value.toString() !== value.toString());
});
return $(".when-not-" + state, scope).each(function(idx, element) {
var expected_value;
element = $(element);
expected_value = element.data('state') || true;
return $(element).toggleClass('hidden', expected_value.toString() === value.toString());
});
};
return States;
})();
window.serious.Widget = (function() {
function Widget() {
this.cloneTemplate = __bind(this.cloneTemplate, this);
this.show = __bind(this.show, this);
this.hide = __bind(this.hide, this);
this.get = __bind(this.get, this);
this.set = __bind(this.set, this);
}
Widget.bindAll = function() {
var first, firsts, _i, _len;
firsts = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
if (firsts) {
for (_i = 0, _len = firsts.length; _i < _len; _i++) {
first = firsts[_i];
Widget.ensureWidget($(first));
}
}
return $(".widget").each(function() {
var self;
self = $(this);
if (!self.hasClass('template') && !self.parents().hasClass('template')) {
return Widget.ensureWidget(self);
}
});
};
Widget.ensureWidget = function(ui) {
var widget, widget_class;
ui = $(ui);
if (!ui.length) {
return null;
} else if (ui[0]._widget != null) {
return ui[0]._widget;
} else {
widget_class = Widget.getWidgetClass(ui);
if (widget_class != null) {
widget = new widget_class();
widget.bindUI(ui);
return widget;
} else {
console.warn("widget not found for", ui);
return null;
}
}
};
Widget.getWidgetClass = function(ui) {
return eval("(" + $(ui).attr("data-widget") + ")");
};
Widget.prototype.bindUI = function(ui) {
var action, key, nui, value, _i, _len, _ref, _ref1, _results;
this.ui = $(ui);
if (this.ui[0]._widget) {
delete this.ui[0]._widget;
}
this.ui[0]._widget = this;
this.uis = {};
if (typeof this.UIS !== "undefined") {
_ref = this.UIS;
for (key in _ref) {
value = _ref[key];
nui = this.ui.find(value);
if (nui.length < 1) {
console.warn("uis", key, "not found in", ui);
}
this.uis[key] = nui;
}
}
if (this.ACTIONS != null) {
_ref1 = this.ACTIONS;
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
action = _ref1[_i];
_results.push(this._bindClick(this.ui.find(".do[data-action=" + action + "]"), action));
}
return _results;
}
};
Widget.prototype.set = function(field, value, context) {
/* Set a value to all tag with the given data-field attribute.
Field can be a dict or a field name.
If it is a dict, the second parameter should be a context.
The default context is the widget itself.
*/
var name, _value;
if (typeof field === "object") {
context = value || this.ui;
for (name in field) {
_value = field[name];
context.find(".out[data-field=" + name + "]").html(_value);
}
} else {
context = context || this.ui;
context.find(".out[data-field=" + field + "]").html(value);
}
return context;
};
Widget.prototype.get = function(form) {
var data;
form = $(form);
data = {};
form.find('input.in').each(function() {
var input;
input = $(this);
if (!input.hasClass('template') && !input.parents().hasClass('template')) {
return data[input.attr('name')] = input.val();
}
});
return data;
};
Widget.prototype.hide = function() {
return this.ui.addClass("hidden");
};
Widget.prototype.show = function() {
return this.ui.removeClass("hidden");
};
Widget.prototype.cloneTemplate = function(template_nui, dict, removeUnusedField) {
var action, klass, nui, value, _i, _len, _ref;
if (removeUnusedField == null) {
removeUnusedField = false;
}
nui = template_nui.clone();
nui = nui.removeClass("template hidden").addClass("actual");
if (typeof dict === "object") {
for (klass in dict) {
value = dict[klass];
if (value !== null) {
nui.find(".out." + klass).html(value);
}
}
if (removeUnusedField) {
nui.find(".out").each(function() {
if ($(this).html() === "") {
return $(this).remove();
}
});
}
}
if (this.ACTIONS != null) {
_ref = this.ACTIONS;
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
action = _ref[_i];
this._bindClick(nui.find(".do[data-action=" + action + "]"), action);
}
}
return nui;
};
Widget.prototype._bindClick = function(nui, action) {
var _this = this;
if ((action != null) && __indexOf.call(this.ACTIONS, action) >= 0) {
return nui.click(function(e) {
_this[action](e);
return e.preventDefault();
});
}
};
return Widget;
})();
window.serious.URL = (function() {
function URL() {
this.toString = __bind(this.toString, this);
this.fromString = __bind(this.fromString, this);
this.enableDynamicLinks = __bind(this.enableDynamicLinks, this);
this.updateUrl = __bind(this.updateUrl, this);
this.hasBeenAdded = __bind(this.hasBeenAdded, this);
this.hasChanged = __bind(this.hasChanged, this);
this.remove = __bind(this.remove, this);
this.update = __bind(this.update, this);
this.set = __bind(this.set, this);
this.onStateChanged = __bind(this.onStateChanged, this);
this.get = __bind(this.get, this);
var _this = this;
this.previousHash = [];
this.handlers = [];
this.hash = this.fromString(location.hash);
$(window).hashchange(function() {
var handler, _i, _len, _ref, _results;
_this.previousHash = window.serious.Utils.clone(_this.hash);
_this.hash = _this.fromString(location.hash);
_ref = _this.handlers;
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
handler = _ref[_i];
_results.push(handler());
}
return _results;
});
}
URL.prototype.get = function(field) {
if (field == null) {
field = null;
}
if (field) {
return this.hash[field];
} else {
return this.hash;
}
};
URL.prototype.onStateChanged = function(handler) {
return this.handlers.push(handler);
};
URL.prototype.set = function(fields, silent) {
var hash, key, value;
if (silent == null) {
silent = false;
}
hash = silent ? this.hash : window.serious.Utils.clone(this.hash);
hash = [];
for (key in fields) {
value = fields[key];
if (isDefined(value)) {
hash[key] = value;
}
}
return this.updateUrl(hash);
};
URL.prototype.update = function(fields, silent) {
var hash, key, value;
if (silent == null) {
silent = false;
}
hash = silent ? this.hash : window.serious.Utils.clone(this.hash);
for (key in fields) {
value = fields[key];
if (isDefined(value)) {
hash[key] = value;
} else {
delete hash[key];
}
}
return this.updateUrl(hash);
};
URL.prototype.remove = function(key, silent) {
var hash;
if (silent == null) {
silent = false;
}
hash = silent ? this.hash : window.serious.Utils.clone(this.hash);
if (hash[key]) {
delete hash[key];
}
return this.updateUrl(hash);
};
URL.prototype.hasChanged = function(key) {
if (this.hash[key] != null) {
if (this.previousHash[key] != null) {
return this.hash[key].toString() !== this.previousHash[key].toString();
} else {
return true;
}
} else {
if (this.previousHash[key] != null) {
return true;
}
}
return false;
};
URL.prototype.hasBeenAdded = function(key) {
return console.error("not implemented");
};
URL.prototype.updateUrl = function(hash) {
if (hash == null) {
hash = null;
}
if (!hash || Object.size(hash) === 0) {
return location.hash = '_';
} else {
return location.hash = this.toString(hash);
}
};
URL.prototype.enableDynamicLinks = function(context) {
var _this = this;
if (context == null) {
context = null;
}
return $("a.internal[href]", context).click(function(e) {
var href, link;
link = $(e.currentTarget);
href = link.attr("data-href") || link.attr("href");
if (href[0] === "#") {
if (href.length > 1 && href[1] === "+") {
_this.update(_this.fromString(href.slice(2)));
} else if (href.length > 1 && href[1] === "-") {
_this.remove(_this.fromString(href.slice(2)));
} else {
_this.set(_this.fromString(href.slice(1)));
}
}
return false;
});
};
URL.prototype.fromString = function(value) {
var hash, hash_list, item, key, key_value, val, _i, _len;
value = value || location.hash;
hash = {};
value = value.replace('!', '');
hash_list = value.split("&");
for (_i = 0, _len = hash_list.length; _i < _len; _i++) {
item = hash_list[_i];
if (item != null) {
key_value = item.split("=");
if (key_value.length === 2) {
key = key_value[0].replace("#", "");
val = key_value[1].replace("#", "");
hash[key] = val;
}
}
}
return hash;
};
URL.prototype.toString = function(hash_list) {
var i, key, new_hash, value;
if (hash_list == null) {
hash_list = null;
}
hash_list = hash_list || this.hash;
new_hash = "!";
i = 0;
for (key in hash_list) {
value = hash_list[key];
if (i > 0) {
new_hash += "&";
}
new_hash += key + "=" + value;
i++;
}
return new_hash;
};
return URL;
})();
| shelsonjava/datawrapper | www/static/vendor/serious-toolkit/serious-widget.js | JavaScript | mit | 12,671 |
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'autoembed', 'pl', {
embeddingInProgress: 'Osadzanie wklejonego adresu URL...',
embeddingFailed: 'Ten adres URL multimediów nie może być automatycznie osadzony.'
} );
| tsipa88/ckeditor | vendor/assets/javascripts/ckeditor/plugins/autoembed/lang/pl.js | JavaScript | mit | 344 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* Operator --x uses [[Default Value]]
*
* @path ch11/11.4/11.4.5/S11.4.5_A2.2_T1.js
* @description If Type(value) is Object, evaluate ToPrimitive(value, Number)
*/
//CHECK#1
var object = {valueOf: function() {return 1}};
if (--object !== 1 - 1) {
$ERROR('#1: var object = {valueOf: function() {return 1}}; --object === 1 - 1. Actual: ' + (--object));
} else {
if (object !== 1 - 1) {
$ERROR('#1: var object = {valueOf: function() {return 1}}; --object; object === 1 - 1. Actual: ' + (object));
}
}
//CHECK#2
var object = {valueOf: function() {return 1}, toString: function() {return 0}};
if (--object !== 1 - 1) {
$ERROR('#2: var object = {valueOf: function() {return 1}, toString: function() {return 0}}; --object === 1 - 1. Actual: ' + (--object));
} else {
if (object !== 1 - 1) {
$ERROR('#2: var object = {valueOf: function() {return 1}, toString: function() {return 0}}; --object; object === 1 - 1. Actual: ' + (object));
}
}
//CHECK#3
var object = {valueOf: function() {return 1}, toString: function() {return {}}};
if (--object !== 1 - 1) {
$ERROR('#3: var object = {valueOf: function() {return 1}, toString: function() {return {}}}; --object === 1 - 1. Actual: ' + (--object));
} else {
if (object !== 1 - 1) {
$ERROR('#3: var object = {valueOf: function() {return 1}, toString: function() {return {}}}; --object; object === 1 - 1. Actual: ' + (object));
}
}
//CHECK#4
try {
var object = {valueOf: function() {return 1}, toString: function() {throw "error"}};
if (--object !== 1 - 1) {
$ERROR('#4.1: var object = {valueOf: function() {return 1}, toString: function() {throw "error"}}; --object === 1 - 1. Actual: ' + (--object));
} else {
if (object !== 1 - 1) {
$ERROR('#4.1: var object = {valueOf: function() {return 1}, toString: function() {throw "error"}}; --object; object === 1 - 1. Actual: ' + (object));
}
}
}
catch (e) {
if (e === "error") {
$ERROR('#4.2: var object = {valueOf: function() {return 1}, toString: function() {throw "error"}}; --object not throw "error"');
} else {
$ERROR('#4.3: var object = {valueOf: function() {return 1}, toString: function() {throw "error"}}; --object not throw Error. Actual: ' + (e));
}
}
//CHECK#5
var object = {toString: function() {return 1}};
if (--object !== 1 - 1) {
$ERROR('#5.1: var object = {toString: function() {return 1}}; --object === 1 - 1. Actual: ' + (--object));
} else {
if (object !== 1 - 1) {
$ERROR('#5.2: var object = {toString: function() {return 1}}; --object; object === 1 - 1. Actual: ' + (object));
}
}
//CHECK#6
var object = {valueOf: function() {return {}}, toString: function() {return 1}}
if (--object !== 1 - 1) {
$ERROR('#6.1: var object = {valueOf: function() {return {}}, toString: function() {return 1}}; --object === 1 - 1. Actual: ' + (--object));
} else {
if (object !== 1 - 1) {
$ERROR('#6.2: var object = {valueOf: function() {return {}}, toString: function() {return 1}}; --object; object === 1 - 1. Actual: ' + (object));
}
}
//CHECK#7
try {
var object = {valueOf: function() {throw "error"}, toString: function() {return 1}};
--object;
$ERROR('#7.1: var object = {valueOf: function() {throw "error"}, toString: function() {return 1}}; --object throw "error". Actual: ' + (--object));
}
catch (e) {
if (e !== "error") {
$ERROR('#7.2: var object = {valueOf: function() {throw "error"}, toString: function() {return 1}}; --object throw "error". Actual: ' + (e));
}
}
//CHECK#8
try {
var object = {valueOf: function() {return {}}, toString: function() {return {}}};
--object;
$ERROR('#8.1: var object = {valueOf: function() {return {}}, toString: function() {return {}}}; --object throw TypeError. Actual: ' + (--object));
}
catch (e) {
if ((e instanceof TypeError) !== true) {
$ERROR('#8.2: var object = {valueOf: function() {return {}}, toString: function() {return {}}}; --object throw TypeError. Actual: ' + (e));
}
}
| hippich/typescript | tests/Fidelity/test262/suite/ch11/11.4/11.4.5/S11.4.5_A2.2_T1.js | JavaScript | apache-2.0 | 4,094 |
// ----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ----------------------------------------------------------------------------
/// <reference path="../../../ZumoE2ETestAppJs/ZumoE2ETestAppJs/js/MobileServices.js" />
/// <reference path="/LiveSDKHTML/js/wl.js" />
/// <reference path="../testFramework.js" />
function defineLoginTestsNamespace() {
var tests = [];
var i;
var TABLE_PERMISSION_PUBLIC = 1;
var TABLE_PERMISSION_APPLICATION = 2;
var TABLE_PERMISSION_USER = 3;
var TABLE_PERMISSION_ADMIN = 4;
var TABLE_NAME_PUBLIC = 'public';
var TABLE_NAME_APPLICATION = 'application';
var TABLE_NAME_AUTHENTICATED = 'authenticated';
var TABLE_NAME_ADMIN = 'admin';
var tables = [
{ name: TABLE_NAME_PUBLIC, permission: TABLE_PERMISSION_PUBLIC },
{ name: TABLE_NAME_APPLICATION, permission: TABLE_PERMISSION_APPLICATION },
{ name: TABLE_NAME_AUTHENTICATED, permission: TABLE_PERMISSION_USER },
{ name: TABLE_NAME_ADMIN, permission: TABLE_PERMISSION_ADMIN }];
var supportRecycledToken = {
facebook: true,
google: false, // Known bug - Drop login via Google token until Google client flow is reintroduced
twitter: false,
microsoftaccount: false
};
tests.push(createLogoutTest());
var index, table;
for (index = 0; index < tables.length; index++) {
table = tables[index];
tests.push(createCRUDTest(table.name, null, table.permission, false));
}
var indexOfTestsWithAuthentication = 0;
var lastUserIdentityObject = null;
var providers = ['facebook', 'google', 'twitter', 'microsoftaccount'];
for (i = 0; i < providers.length; i++) {
var provider = providers[i];
tests.push(createLogoutTest());
tests.push(createLoginTest(provider));
for (index = 0; index < tables.length; index++) {
table = tables[index];
if (table.permission !== TABLE_PERMISSION_PUBLIC) {
tests.push(createCRUDTest(table.name, provider, table.permission, true));
}
}
if (supportRecycledToken[provider]) {
tests.push(createLogoutTest());
tests.push(createClientSideLoginTest(provider));
tests.push(createCRUDTest(TABLE_NAME_AUTHENTICATED, provider, TABLE_PERMISSION_USER, true));
}
}
if (!testPlatform.IsHTMLApplication) {
//In Browser, default is single signon and LIVE SDK is not supported
tests.push(createLogoutTest());
tests.push(createLiveSDKLoginTest());
tests.push(createCRUDTest(TABLE_NAME_AUTHENTICATED, 'microsoftaccount', TABLE_PERMISSION_USER, true));
providers.forEach(function (provider) {
if (provider === 'microsoftaccount') {
// Known issue - SSO for MS account does not work in application which also uses the Live SDK
} else {
tests.push(createLogoutTest());
tests.push(createLoginTest(provider, true));
tests.push(createCRUDTest(TABLE_NAME_AUTHENTICATED, provider, TABLE_PERMISSION_USER, true));
}
});
}
for (var i = indexOfTestsWithAuthentication; i < tests.length; i++) {
tests[i].canRunUnattended = false;
}
function createLiveSDKLoginTest() {
var liveSDKInitialized = false;
return new zumo.Test('Login via token with the Live SDK', function (test, done) {
/// <param name="test" type="zumo.Test">The test associated with this execution.</param>
var client = zumo.getClient();
if (!liveSDKInitialized) {
WL.init({ redirect_uri: client.applicationUrl });
liveSDKInitialized = true;
test.addLog('Initialized the WL object');
}
WL.login({ scope: 'wl.basic' }).then(function (wlLoginResult) {
test.addLog('Logged in via Live SDK: ', wlLoginResult);
WL.api({ path: 'me', method: 'GET' }).then(function (wlMeResult) {
test.addLog('My information: ', wlMeResult);
var token = { authenticationToken: wlLoginResult.session.authentication_token };
client.login('microsoftaccount', token).done(function (user) {
test.addLog('Logged in as ', user);
done(true);
}, function (err) {
test.addLog('Error logging into the mobile service: ', err);
done(false);
});
}, function (err) {
test.addLog('Error calling WL.api: ', err);
done(false);
});
}, function (err) {
test.addLog('Error logging in via Live SDK: ', err);
done(false);
});
});
}
function createClientSideLoginTest(provider) {
/// <param name="provider" type="String" mayBeNull="true">The name of the authentication provider for
/// the client. Currently only 'facebook' and 'google' are supported for this test.</param>
return new zumo.Test('Login via token for ' + provider, function (test, done) {
/// <param name="test" type="zumo.Test">The test associated with this execution.</param>
var client = zumo.getClient();
var lastIdentity = lastUserIdentityObject;
if (!lastIdentity) {
test.addLog('Last identity object is null. Cannot run this test.');
done(false);
} else {
var token = {};
if (provider === 'facebook' || provider === 'google') {
token.access_token = lastIdentity[provider].accessToken;
client.login(provider, token).done(function (user) {
test.addLog('Logged in as ', user);
done(true);
}, function (err) {
test.addLog('Error on login: ', err);
done(false);
});
} else {
test.addLog('Client-side login for ' + provider + ' is not implemented or not supported.');
done(false);
}
}
});
}
function createCRUDTest(tableName, provider, tablePermission, userIsAuthenticated) {
/// <param name="tableName" type="String">The name of the table to attempt the CRUD operations for.</param>
/// <param name="provider" type="String" mayBeNull="true">The name of the authentication provider for
/// the client.</param>
/// <param name="tablePermission" type="Number" mayBeNull="false">The permission required to access the
/// table. One of the constants defined in the scope.</param>
/// <param name="userIsAuthenticated" type="Boolean" mayBeNull="false">The name of the table to attempt
/// the CRUD operations for.</param>
/// <return type="zumo.Test"/>
var testName = 'CRUD, ' + (userIsAuthenticated ? ('auth by ' + provider) : 'unauthenticated');
testName = testName + ', table with ';
testName = testName + ['public', 'application', 'user', 'admin'][tablePermission - 1];
testName = testName + ' permission.';
return new zumo.Test(testName, function (test, done) {
/// <param name="test" type="zumo.Test">The test associated with this execution.</param>
var crudShouldWork = tablePermission === TABLE_PERMISSION_PUBLIC ||
tablePermission === TABLE_PERMISSION_APPLICATION ||
(tablePermission === TABLE_PERMISSION_USER && userIsAuthenticated);
var client = zumo.getClient();
var table = client.getTable(tableName);
var currentUser = client.currentUser;
var item = { name: 'hello' };
var insertedItem;
var validateCRUDResult = function (operation, error) {
var result = false;
if (crudShouldWork) {
if (error) {
test.addLog(operation + ' should have succeeded, but got error: ', error);
} else {
test.addLog(operation + ' succeeded as expected.');
result = true;
}
} else {
if (error) {
var xhr = error.request;
if (xhr) {
var isInternetExplorer10 = testPlatform.IsHTMLApplication && window.ActiveXObject && window.navigator.userAgent.toLowerCase().match(/msie ([\d.]+)/)[1] == "10.0";
// IE 10 has a bug in which it doesn't set the status code correctly - https://connect.microsoft.com/IE/feedback/details/785990
// so we cannot validate the status code if this is the case.
if (isInternetExplorer10) {
result = true;
} else {
if (xhr.status == 401) {
test.addLog('Got expected response code (401) for ', operation);
result = true;
} else {
zumo.util.traceResponse(test, xhr);
test.addLog('Error, incorrect response.');
}
}
} else {
test.addLog('Error, error object does not have a \'request\' (for the XMLHttpRequest object) property.');
}
} else {
test.addLog(operation + ' should not have succeeded, but the success callback was called.');
}
}
if (!result) {
done(false);
}
return result;
}
// The last of the callbacks, which will call 'done(true);' if validation succeeds.
// called by readCallback
function deleteCallback(error) {
if (validateCRUDResult('delete', error)) {
test.addLog('Validation succeeded for all operations');
done(true);
}
}
// called by updateCallback
function readCallback(error) {
if (validateCRUDResult('read', error)) {
//table.del({ id: insertedItem.id || 1 }).done(function () { deleteCallback(); }, function (err) { deleteCallback(err); });
table.del({ id: insertedItem.id }).done(function () { deleteCallback(); }, function (err) { deleteCallback(err); });
}
}
// called by insertCallback
function updateCallback(error) {
if (validateCRUDResult('update', error)) {
item.id = insertedItem.id || 1;
table.where({ id: item.id }).read().done(function (items) {
test.addLog('Read items: ', items);
if (items.length !== 1) {
test.addLog('Error, query should have returned exactly one item');
done(false);
} else {
var retrievedItem = items[0];
var usersFeatureEnabled = retrievedItem.UsersEnabled;
if (retrievedItem.Identities) {
lastUserIdentityObject = JSON.parse(items[0].Identities);
test.addLog('Identities object: ', lastUserIdentityObject);
var providerName = provider;
if (providerName.toLowerCase() === 'microsoftaccount') {
providerName = 'microsoft';
}
var providerIdentity = lastUserIdentityObject[providerName];
if (!providerIdentity) {
test.addLog('Error, cannot fetch the identity for provider ', providerName);
done(false);
return;
}
if (usersFeatureEnabled) {
var userName = providerIdentity.name || providerIdentity.screen_name;
if (userName) {
test.addLog('Found user name: ', userName);
} else {
test.addLog('Could not find user name!');
done(false);
return;
}
}
}
readCallback();
}
}, function (err) {
readCallback(err);
});
}
}
// called by the callback for insert.
function insertCallback(error) {
if (validateCRUDResult('insert', error)) {
if (tablePermission === TABLE_PERMISSION_PUBLIC) {
// No need for app key anymore
client = new WindowsAzure.MobileServiceClient(client.applicationUrl);
table = client.getTable(tableName);
}
item.id = insertedItem.id || 1;
item.text = 'world';
table.update(item).done(function (newItem) {
test.addLog('Updated item: ', newItem);
updateCallback();
}, function (err) {
updateCallback(err);
});
}
}
table.insert(item).done(function (newItem) {
insertedItem = newItem;
test.addLog('Inserted item: ', newItem);
if (tablePermission === TABLE_PERMISSION_USER) {
var currentUser = client.currentUser.userId;
if (currentUser === newItem.userId) {
test.addLog('User id correctly added by the server script');
} else {
test.addLog('Error, user id not set by the server script');
done(false);
return;
}
}
insertCallback();
}, function (err) {
insertedItem = item;
insertedItem.id = item.id || 1;
insertCallback(err);
});
});
}
function createLoginTest(provider, useSingleSignOn) {
/// <param name="provider" type="String">The authentication provider to use.</param>
/// <param name="useSingleSignOn" type="Boolean">Whether to use the single sign-on parameter for login.</param>
/// <return type="zumo.Test" />
return new zumo.Test('Login with ' + provider + (useSingleSignOn ? ' (using single sign-on)' : ''), function (test, done) {
/// <param name="test" type="zumo.Test">The test associated with this execution.</param>
var client = zumo.getClient();
var successFunction = function (user) {
test.addLog('Logged in: ', user);
done(true);
};
var errorFunction = function (err) {
test.addLog('Error during login: ', err);
done(false);
};
if (useSingleSignOn) {
client.login(provider, true).done(successFunction, errorFunction);
} else {
client.login(provider).done(successFunction, errorFunction);
}
});
}
function createLogoutTest() {
return new zumo.Test('Log out', function (test, done) {
var client = zumo.getClient();
client.logout();
test.addLog('Logged out');
done(true);
});
}
return {
name: 'Login',
tests: tests
};
}
zumo.tests.login = defineLoginTestsNamespace();
| soninaren/azure-mobile-services-test | sdk/JavaScript/TestFramework/js/tests/loginTests.js | JavaScript | apache-2.0 | 16,739 |
// Copyright 2009 the Sputnik authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/**
* The production x *= y is the same as the production x = x * y
*
* @path ch11/11.13/11.13.2/S11.13.2_A4.1_T2.6.js
* @description Type(x) is different from Type(y) and both types vary between primitive String (primitive or object) and Undefined
*/
//CHECK#1
x = "1";
x *= undefined;
if (isNaN(x) !== true) {
$ERROR('#1: x = "1"; x *= undefined; x === Not-a-Number. Actual: ' + (x));
}
//CHECK#2
x = undefined;
x *= "1";
if (isNaN(x) !== true) {
$ERROR('#2: x = undefined; x *= "1"; x === Not-a-Number. Actual: ' + (x));
}
//CHECK#3
x = new String("1");
x *= undefined;
if (isNaN(x) !== true) {
$ERROR('#3: x = new String("1"); x *= undefined; x === Not-a-Number. Actual: ' + (x));
}
//CHECK#4
x = undefined;
x *= new String("1");
if (isNaN(x) !== true) {
$ERROR('#4: x = undefined; x *= new String("1"); x === Not-a-Number. Actual: ' + (x));
}
| hippich/typescript | tests/Fidelity/test262/suite/ch11/11.13/11.13.2/S11.13.2_A4.1_T2.6.js | JavaScript | apache-2.0 | 999 |
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is JavaScript Engine testing utilities.
*
* The Initial Developer of the Original Code is
* Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor(s): Jeff Walden
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
//-----------------------------------------------------------------------------
var BUGNUMBER = 465980;
var summary = 'Do not crash @ InitArrayElements';
var actual = '';
var expect = '';
//-----------------------------------------------------------------------------
test();
//-----------------------------------------------------------------------------
function test()
{
enterFunc ('test');
printBugNumber(BUGNUMBER);
printStatus (summary);
function describe(name, startLength, pushArgs, expectThrow, expectLength)
{
return name + "(" + startLength + ", " +
"[" + pushArgs.join(", ") + "], " +
expectThrow + ", " +
expectLength + ")";
}
var push = Array.prototype.push;
var unshift = Array.prototype.unshift;
function testArrayPush(startLength, pushArgs, expectThrow, expectLength)
{
print("running testArrayPush(" +
startLength + ", " +
"[" + pushArgs.join(", ") + "], " +
expectThrow + ", " +
expectLength + ")...");
var a = new Array(startLength);
try
{
push.apply(a, pushArgs);
if (expectThrow)
{
throw "expected to throw for " +
describe("testArrayPush", startLength, pushArgs, expectThrow,
expectLength);
}
}
catch (e)
{
if (!(e instanceof RangeError))
{
throw "unexpected exception type thrown: " + e + " for " +
describe("testArrayPush", startLength, pushArgs, expectThrow,
expectLength);
}
if (!expectThrow)
{
throw "unexpected exception " + e + " for " +
describe("testArrayPush", startLength, pushArgs, expectThrow,
expectLength);
}
}
if (a.length !== expectLength)
{
throw "unexpected modified-array length for " +
describe("testArrayPush", startLength, pushArgs, expectThrow,
expectLength);
}
for (var i = 0, sz = pushArgs.length; i < sz; i++)
{
var index = i + startLength;
if (a[index] !== pushArgs[i])
{
throw "unexpected value " + a[index] +
" at index " + index + " (" + i + ") during " +
describe("testArrayPush", startLength, pushArgs, expectThrow,
expectLength) + ", expected " + pushArgs[i];
}
}
}
function testArrayUnshift(startLength, unshiftArgs, expectThrow, expectLength)
{
print("running testArrayUnshift(" +
startLength + ", " +
"[" + unshiftArgs.join(", ") + "], " +
expectThrow + ", " +
expectLength + ")...");
var a = new Array(startLength);
try
{
unshift.apply(a, unshiftArgs);
if (expectThrow)
{
throw "expected to throw for " +
describe("testArrayUnshift", startLength, unshiftArgs, expectThrow,
expectLength);
}
}
catch (e)
{
if (!(e instanceof RangeError))
{
throw "unexpected exception type thrown: " + e + " for " +
describe("testArrayUnshift", startLength, unshiftArgs, expectThrow,
expectLength);
}
if (!expectThrow)
{
throw "unexpected exception " + e + " for " +
describe("testArrayUnshift", startLength, unshiftArgs, expectThrow,
expectLength);
}
}
if (a.length !== expectLength)
{
throw "unexpected modified-array length for " +
describe("testArrayUnshift", startLength, unshiftArgs, expectThrow,
expectLength);
}
for (var i = 0, sz = unshiftArgs.length; i < sz; i++)
{
if (a[i] !== unshiftArgs[i])
{
throw "unexpected value at index " + i + " during " +
describe("testArrayUnshift", startLength, unshiftArgs, expectThrow,
expectLength);
}
}
}
var failed = true;
try
{
var foo = "foo", bar = "bar", baz = "baz";
testArrayPush(4294967294, [foo], false, 4294967295);
testArrayPush(4294967294, [foo, bar], true, 4294967295);
testArrayPush(4294967294, [foo, bar, baz], true, 4294967295);
testArrayPush(4294967295, [foo], true, 4294967295);
testArrayPush(4294967295, [foo, bar], true, 4294967295);
testArrayPush(4294967295, [foo, bar, baz], true, 4294967295);
testArrayUnshift(4294967294, [foo], false, 4294967295);
testArrayUnshift(4294967294, [foo, bar], true, 4294967294);
testArrayUnshift(4294967294, [foo, bar, baz], true, 4294967294);
testArrayUnshift(4294967295, [foo], true, 4294967295);
testArrayUnshift(4294967295, [foo, bar], true, 4294967295);
testArrayUnshift(4294967295, [foo, bar, baz], true, 4294967295);
}
catch (e)
{
actual = e + '';
}
reportCompare(expect, actual, summary);
exitFunc ('test');
}
| daejunpark/jsaf | tests/parser_tests/js/src/tests/js1_5/Array/regress-465980-02.js | JavaScript | bsd-3-clause | 6,616 |
'use strict';
// There's an example D script here to showcase a "slow" handler where it's
// wildcard'd by the route name. In "real life" you'd probably start with a
// d script that breaks down the route -start and -done, and then you'd want
// to see which handler is taking longest from there.
//
// $ node demo.js
// $ curl localhost:9080/foo/bar
// $ sudo ./handler-timing.d
// ^C
//
// handler-6
// value ------------- Distribution ------------- count
// -1 | 0
// 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10
// 1 | 0
//
// parseAccept
// value ------------- Distribution ------------- count
// -1 | 0
// 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10
// 1 | 0
//
// parseAuthorization
// value ------------- Distribution ------------- count
// -1 | 0
// 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10
// 1 | 0
//
// parseDate
// value ------------- Distribution ------------- count
// -1 | 0
// 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10
// 1 | 0
//
// parseQueryString
// value ------------- Distribution ------------- count
// -1 | 0
// 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10
// 1 | 0
//
// parseUrlEncodedBody
// value ------------- Distribution ------------- count
// -1 | 0
// 0 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 10
// 1 | 0
//
// sendResult
// value ------------- Distribution ------------- count
// 1 | 0
// 2 |@@@@ 1
// 4 | 0
// 8 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 9
// 16 | 0
//
// slowHandler
// value ------------- Distribution ------------- count
// 64 | 0
// 128 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 9
// 256 |@@@@ 1
// 512 | 0
//
// getfoo
// value ------------- Distribution ------------- count
// 64 | 0
// 128 |@@@@ 1
// 256 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 9
// 512 | 0
var restify = require('../../lib');
var Logger = require('bunyan');
///--- Globals
var NAME = 'exampleapp';
///--- Mainline
var log = new Logger({
name: NAME,
level: 'trace',
service: NAME,
serializers: restify.bunyan.serializers
});
var server = restify.createServer({
name: NAME,
Logger: log,
formatters: {
'application/foo': function (req, res, body, cb) {
if (body instanceof Error) {
body = body.stack;
} else if (Buffer.isBuffer(body)) {
body = body.toString('base64');
} else {
switch (typeof body) {
case 'boolean':
case 'number':
case 'string':
body = body.toString();
break;
case 'undefined':
body = '';
break;
default:
body = body === null ? '' :
'Demoing application/foo formatter; ' +
JSON.stringify(body);
break;
}
}
return cb(null, body);
}
}
});
server.use(restify.acceptParser(server.acceptable));
server.use(restify.authorizationParser());
server.use(restify.dateParser());
server.use(restify.queryParser());
server.use(restify.urlEncodedBodyParser());
server.use(function slowHandler(req, res, next) {
setTimeout(function () {
next();
}, 250);
});
server.get({url: '/foo/:id', name: 'GetFoo'}, function (req, res, next) {
next();
}, function sendResult(req, res, next) {
res.contentType = 'application/foo';
res.send({
hello: req.params.id
});
next();
});
server.head('/foo/:id', function (req, res, next) {
res.send({
hello: req.params.id
});
next();
});
server.put('/foo/:id', function (req, res, next) {
res.send({
hello: req.params.id
});
next();
});
server.post('/foo/:id', function (req, res, next) {
res.json(201, req.params);
next();
});
server.del('/foo/:id', function (req, res, next) {
res.send(204);
next();
});
server.on('after', function (req, res, name) {
req.log.info('%s just finished: %d.', name, res.code);
});
server.on('NotFound', function (req, res) {
res.send(404, req.url + ' was not found');
});
server.listen(9080, function () {
log.info('listening: %s', server.url);
});
| mboudreau/node-restify | examples/dtrace/demo.js | JavaScript | mit | 5,705 |
var names = Alloy.Collections.name;
function green(str) { return '\x1B[32m' + str + '\x1B[39m'; }
function red(str) { return '\x1B[31m' + str + '\x1B[39m'; }
// show the info from the selected model
function showInfo(e) {
// get the model id from the list item
var modelId = e.section.getItemAt(e.itemIndex).properties.modelId;
// fetch a specific model based on the given id
var model = Alloy.createModel('info');
model.fetch({ id: modelId });
// assert we got the right data back
var pass = JSON.stringify(model.attributes) === JSON.stringify({
id: modelId,
info: 'info ' + modelId
});
Ti.API.info('Assert single info model returned with "{id:' + modelId + '}": ' + (pass ? green('OK') : red('FAIL')));
}
// fetch the data to update the UI
names.fetch();
// open the window
$.index.open(); | brentonhouse/brentonhouse.alloy | test/apps/testing/ALOY-829/controllers/index.js | JavaScript | apache-2.0 | 810 |
//// [tests/cases/compiler/extendingClassFromAliasAndUsageInIndexer.ts] ////
//// [extendingClassFromAliasAndUsageInIndexer_backbone.ts]
export class Model {
public someData: string;
}
//// [extendingClassFromAliasAndUsageInIndexer_moduleA.ts]
import Backbone = require("./extendingClassFromAliasAndUsageInIndexer_backbone");
export class VisualizationModel extends Backbone.Model {
// interesting stuff here
}
//// [extendingClassFromAliasAndUsageInIndexer_moduleB.ts]
import Backbone = require("./extendingClassFromAliasAndUsageInIndexer_backbone");
export class VisualizationModel extends Backbone.Model {
// different interesting stuff here
}
//// [extendingClassFromAliasAndUsageInIndexer_main.ts]
import Backbone = require("./extendingClassFromAliasAndUsageInIndexer_backbone");
import moduleA = require("./extendingClassFromAliasAndUsageInIndexer_moduleA");
import moduleB = require("./extendingClassFromAliasAndUsageInIndexer_moduleB");
interface IHasVisualizationModel {
VisualizationModel: typeof Backbone.Model;
}
var moduleATyped: IHasVisualizationModel = moduleA;
var moduleMap: { [key: string]: IHasVisualizationModel } = {
"moduleA": moduleA,
"moduleB": moduleB
};
var moduleName: string;
var visModel = new moduleMap[moduleName].VisualizationModel();
//// [extendingClassFromAliasAndUsageInIndexer_backbone.js]
"use strict";
var Model = (function () {
function Model() {
}
return Model;
}());
exports.Model = Model;
//// [extendingClassFromAliasAndUsageInIndexer_moduleA.js]
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Backbone = require("./extendingClassFromAliasAndUsageInIndexer_backbone");
var VisualizationModel = (function (_super) {
__extends(VisualizationModel, _super);
function VisualizationModel() {
_super.apply(this, arguments);
}
return VisualizationModel;
}(Backbone.Model));
exports.VisualizationModel = VisualizationModel;
//// [extendingClassFromAliasAndUsageInIndexer_moduleB.js]
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var Backbone = require("./extendingClassFromAliasAndUsageInIndexer_backbone");
var VisualizationModel = (function (_super) {
__extends(VisualizationModel, _super);
function VisualizationModel() {
_super.apply(this, arguments);
}
return VisualizationModel;
}(Backbone.Model));
exports.VisualizationModel = VisualizationModel;
//// [extendingClassFromAliasAndUsageInIndexer_main.js]
"use strict";
var moduleA = require("./extendingClassFromAliasAndUsageInIndexer_moduleA");
var moduleB = require("./extendingClassFromAliasAndUsageInIndexer_moduleB");
var moduleATyped = moduleA;
var moduleMap = {
"moduleA": moduleA,
"moduleB": moduleB
};
var moduleName;
var visModel = new moduleMap[moduleName].VisualizationModel();
| kimamula/TypeScript | tests/baselines/reference/extendingClassFromAliasAndUsageInIndexer.js | JavaScript | apache-2.0 | 3,294 |
import { ChangeDetectorRef, Component, ElementRef, Input, Optional, Renderer, ViewChild, ViewEncapsulation } from '@angular/core';
import { NG_VALUE_ACCESSOR } from '@angular/forms';
import { clamp, isTrueProperty } from '../../util/util';
import { Config } from '../../config/config';
import { DomController } from '../../platform/dom-controller';
import { Form } from '../../util/form';
import { Haptic } from '../../tap-click/haptic';
import { BaseInput } from '../../util/base-input';
import { Item } from '../item/item';
import { Platform } from '../../platform/platform';
import { pointerCoord } from '../../util/dom';
import { UIEventManager } from '../../gestures/ui-event-manager';
/**
* \@name Range
* \@description
* The Range slider lets users select from a range of values by moving
* the slider knob. It can accept dual knobs, but by default one knob
* controls the value of the range.
*
* ### Range Labels
* Labels can be placed on either side of the range by adding the
* `range-left` or `range-right` property to the element. The element
* doesn't have to be an `ion-label`, it can be added to any element
* to place it to the left or right of the range. See [usage](#usage)
* below for examples.
*
*
* ### Minimum and Maximum Values
* Minimum and maximum values can be passed to the range through the `min`
* and `max` properties, respectively. By default, the range sets the `min`
* to `0` and the `max` to `100`.
*
*
* ### Steps and Snaps
* The `step` property specifies the value granularity of the range's value.
* It can be useful to set the `step` when the value isn't in increments of `1`.
* Setting the `step` property will show tick marks on the range for each step.
* The `snaps` property can be set to automatically move the knob to the nearest
* tick mark based on the step property value.
*
*
* ### Dual Knobs
* Setting the `dualKnobs` property to `true` on the range component will
* enable two knobs on the range. If the range has two knobs, the value will
* be an object containing two properties: `lower` and `upper`.
*
*
* \@usage
* ```html
* <ion-list>
* <ion-item>
* <ion-range [(ngModel)]="singleValue" color="danger" pin="true"></ion-range>
* </ion-item>
*
* <ion-item>
* <ion-range min="-200" max="200" [(ngModel)]="saturation" color="secondary">
* <ion-label range-left>-200</ion-label>
* <ion-label range-right>200</ion-label>
* </ion-range>
* </ion-item>
*
* <ion-item>
* <ion-range min="20" max="80" step="2" [(ngModel)]="brightness">
* <ion-icon small range-left name="sunny"></ion-icon>
* <ion-icon range-right name="sunny"></ion-icon>
* </ion-range>
* </ion-item>
*
* <ion-item>
* <ion-label>step=100, snaps, {{singleValue4}}</ion-label>
* <ion-range min="1000" max="2000" step="100" snaps="true" color="secondary" [(ngModel)]="singleValue4"></ion-range>
* </ion-item>
*
* <ion-item>
* <ion-label>dual, step=3, snaps, {{dualValue2 | json}}</ion-label>
* <ion-range dualKnobs="true" [(ngModel)]="dualValue2" min="21" max="72" step="3" snaps="true"></ion-range>
* </ion-item>
* </ion-list>
* ```
*
*
* \@demo /docs/demos/src/range/
*/
export class Range extends BaseInput {
/**
* @param {?} form
* @param {?} _haptic
* @param {?} item
* @param {?} config
* @param {?} _plt
* @param {?} elementRef
* @param {?} renderer
* @param {?} _dom
* @param {?} _cd
*/
constructor(form, _haptic, item, config, _plt, elementRef, renderer, _dom, _cd) {
super(config, elementRef, renderer, 'range', 0, form, item, null);
this._haptic = _haptic;
this._plt = _plt;
this._dom = _dom;
this._cd = _cd;
this._min = 0;
this._max = 100;
this._step = 1;
this._valA = 0;
this._valB = 0;
this._ratioA = 0;
this._ratioB = 0;
this._events = new UIEventManager(_plt);
}
/**
* \@input {number} Minimum integer value of the range. Defaults to `0`.
* @return {?}
*/
get min() {
return this._min;
}
/**
* @param {?} val
* @return {?}
*/
set min(val) {
val = Math.round(val);
if (!isNaN(val)) {
this._min = val;
this._inputUpdated();
}
}
/**
* \@input {number} Maximum integer value of the range. Defaults to `100`.
* @return {?}
*/
get max() {
return this._max;
}
/**
* @param {?} val
* @return {?}
*/
set max(val) {
val = Math.round(val);
if (!isNaN(val)) {
this._max = val;
this._inputUpdated();
}
}
/**
* \@input {number} Specifies the value granularity. Defaults to `1`.
* @return {?}
*/
get step() {
return this._step;
}
/**
* @param {?} val
* @return {?}
*/
set step(val) {
val = Math.round(val);
if (!isNaN(val) && val > 0) {
this._step = val;
}
}
/**
* \@input {boolean} If true, the knob snaps to tick marks evenly spaced based
* on the step property value. Defaults to `false`.
* @return {?}
*/
get snaps() {
return this._snaps;
}
/**
* @param {?} val
* @return {?}
*/
set snaps(val) {
this._snaps = isTrueProperty(val);
}
/**
* \@input {boolean} If true, a pin with integer value is shown when the knob
* is pressed. Defaults to `false`.
* @return {?}
*/
get pin() {
return this._pin;
}
/**
* @param {?} val
* @return {?}
*/
set pin(val) {
this._pin = isTrueProperty(val);
}
/**
* \@input {number} How long, in milliseconds, to wait to trigger the
* `ionChange` event after each change in the range value. Default `0`.
* @return {?}
*/
get debounce() {
return this._debouncer.wait;
}
/**
* @param {?} val
* @return {?}
*/
set debounce(val) {
this._debouncer.wait = val;
}
/**
* \@input {boolean} Show two knobs. Defaults to `false`.
* @return {?}
*/
get dualKnobs() {
return this._dual;
}
/**
* @param {?} val
* @return {?}
*/
set dualKnobs(val) {
this._dual = isTrueProperty(val);
}
/**
* Returns the ratio of the knob's is current location, which is a number
* between `0` and `1`. If two knobs are used, this property represents
* the lower value.
* @return {?}
*/
get ratio() {
if (this._dual) {
return Math.min(this._ratioA, this._ratioB);
}
return this._ratioA;
}
/**
* Returns the ratio of the upper value's is current location, which is
* a number between `0` and `1`. If there is only one knob, then this
* will return `null`.
* @return {?}
*/
get ratioUpper() {
if (this._dual) {
return Math.max(this._ratioA, this._ratioB);
}
return null;
}
/**
* @hidden
* @return {?}
*/
ngAfterContentInit() {
this._initialize();
// add touchstart/mousedown listeners
this._events.pointerEvents({
element: this._slider.nativeElement,
pointerDown: this._pointerDown.bind(this),
pointerMove: this._pointerMove.bind(this),
pointerUp: this._pointerUp.bind(this),
zone: true
});
// build all the ticks if there are any to show
this._createTicks();
}
/**
* \@internal
* @param {?} ev
* @return {?}
*/
_pointerDown(ev) {
// TODO: we could stop listening for events instead of checking this._disabled.
// since there are a lot of events involved, this solution is
// enough for the moment
if (this._disabled) {
return false;
}
// trigger ionFocus event
this._fireFocus();
// prevent default so scrolling does not happen
ev.preventDefault();
ev.stopPropagation();
// get the start coordinates
const /** @type {?} */ current = pointerCoord(ev);
// get the full dimensions of the slider element
const /** @type {?} */ rect = this._rect = this._plt.getElementBoundingClientRect(this._slider.nativeElement);
// figure out which knob they started closer to
const /** @type {?} */ ratio = clamp(0, (current.x - rect.left) / (rect.width), 1);
this._activeB = this._dual && (Math.abs(ratio - this._ratioA) > Math.abs(ratio - this._ratioB));
// update the active knob's position
this._update(current, rect, true);
// trigger a haptic start
this._haptic.gestureSelectionStart();
// return true so the pointer events
// know everything's still valid
return true;
}
/**
* \@internal
* @param {?} ev
* @return {?}
*/
_pointerMove(ev) {
if (this._disabled) {
return;
}
// prevent default so scrolling does not happen
ev.preventDefault();
ev.stopPropagation();
// update the active knob's position
const /** @type {?} */ hasChanged = this._update(pointerCoord(ev), this._rect, true);
if (hasChanged && this._snaps) {
// trigger a haptic selection changed event
// if this is a snap range
this._haptic.gestureSelectionChanged();
}
}
/**
* \@internal
* @param {?} ev
* @return {?}
*/
_pointerUp(ev) {
if (this._disabled) {
return;
}
// prevent default so scrolling does not happen
ev.preventDefault();
ev.stopPropagation();
// update the active knob's position
this._update(pointerCoord(ev), this._rect, false);
// trigger a haptic end
this._haptic.gestureSelectionEnd();
// trigger ionBlur event
this._fireBlur();
}
/**
* \@internal
* @param {?} current
* @param {?} rect
* @param {?} isPressed
* @return {?}
*/
_update(current, rect, isPressed) {
// figure out where the pointer is currently at
// update the knob being interacted with
let /** @type {?} */ ratio = clamp(0, (current.x - rect.left) / (rect.width), 1);
let /** @type {?} */ val = this._ratioToValue(ratio);
if (this._snaps) {
// snaps the ratio to the current value
ratio = this._valueToRatio(val);
}
// update which knob is pressed
this._pressed = isPressed;
let /** @type {?} */ valChanged = false;
if (this._activeB) {
// when the pointer down started it was determined
// that knob B was the one they were interacting with
this._pressedB = isPressed;
this._pressedA = false;
this._ratioB = ratio;
valChanged = val === this._valB;
this._valB = val;
}
else {
// interacting with knob A
this._pressedA = isPressed;
this._pressedB = false;
this._ratioA = ratio;
valChanged = val === this._valA;
this._valA = val;
}
this._updateBar();
if (valChanged) {
return false;
}
// value has been updated
let /** @type {?} */ value;
if (this._dual) {
// dual knobs have an lower and upper value
value = {
lower: Math.min(this._valA, this._valB),
upper: Math.max(this._valA, this._valB)
};
(void 0) /* console.debug */;
}
else {
// single knob only has one value
value = this._valA;
(void 0) /* console.debug */;
}
// Update input value
this.value = value;
return true;
}
/**
* \@internal
* @return {?}
*/
_updateBar() {
const /** @type {?} */ ratioA = this._ratioA;
const /** @type {?} */ ratioB = this._ratioB;
if (this._dual) {
this._barL = `${(Math.min(ratioA, ratioB) * 100)}%`;
this._barR = `${100 - (Math.max(ratioA, ratioB) * 100)}%`;
}
else {
this._barL = '';
this._barR = `${100 - (ratioA * 100)}%`;
}
this._updateTicks();
}
/**
* \@internal
* @return {?}
*/
_createTicks() {
if (this._snaps) {
this._dom.write(() => {
// TODO: Fix to not use RAF
this._ticks = [];
for (var /** @type {?} */ value = this._min; value <= this._max; value += this._step) {
var /** @type {?} */ ratio = this._valueToRatio(value);
this._ticks.push({
ratio: ratio,
left: `${ratio * 100}%`,
});
}
this._updateTicks();
});
}
}
/**
* \@internal
* @return {?}
*/
_updateTicks() {
const /** @type {?} */ ticks = this._ticks;
const /** @type {?} */ ratio = this.ratio;
if (this._snaps && ticks) {
if (this._dual) {
var /** @type {?} */ upperRatio = this.ratioUpper;
ticks.forEach(t => {
t.active = (t.ratio >= ratio && t.ratio <= upperRatio);
});
}
else {
ticks.forEach(t => {
t.active = (t.ratio <= ratio);
});
}
}
}
/**
* @hidden
* @param {?} isIncrease
* @param {?} isKnobB
* @return {?}
*/
_keyChg(isIncrease, isKnobB) {
const /** @type {?} */ step = this._step;
if (isKnobB) {
if (isIncrease) {
this._valB += step;
}
else {
this._valB -= step;
}
this._valB = clamp(this._min, this._valB, this._max);
this._ratioB = this._valueToRatio(this._valB);
}
else {
if (isIncrease) {
this._valA += step;
}
else {
this._valA -= step;
}
this._valA = clamp(this._min, this._valA, this._max);
this._ratioA = this._valueToRatio(this._valA);
}
this._updateBar();
}
/**
* \@internal
* @param {?} ratio
* @return {?}
*/
_ratioToValue(ratio) {
ratio = Math.round(((this._max - this._min) * ratio));
ratio = Math.round(ratio / this._step) * this._step + this._min;
return clamp(this._min, ratio, this._max);
}
/**
* \@internal
* @param {?} value
* @return {?}
*/
_valueToRatio(value) {
value = Math.round((value - this._min) / this._step) * this._step;
value = value / (this._max - this._min);
return clamp(0, value, 1);
}
/**
* @param {?} val
* @return {?}
*/
_inputNormalize(val) {
if (this._dual) {
return val;
}
else {
val = parseFloat(val);
return isNaN(val) ? undefined : val;
}
}
/**
* @hidden
* @return {?}
*/
_inputUpdated() {
const /** @type {?} */ val = this.value;
if (this._dual) {
this._valA = val.lower;
this._valB = val.upper;
this._ratioA = this._valueToRatio(val.lower);
this._ratioB = this._valueToRatio(val.upper);
}
else {
this._valA = val;
this._ratioA = this._valueToRatio(val);
}
this._updateBar();
this._cd.detectChanges();
}
/**
* @hidden
* @return {?}
*/
ngOnDestroy() {
super.ngOnDestroy();
this._events.destroy();
}
}
Range.decorators = [
{ type: Component, args: [{
selector: 'ion-range',
template: '<ng-content select="[range-left]"></ng-content>' +
'<div class="range-slider" #slider>' +
'<div class="range-tick" *ngFor="let t of _ticks" [style.left]="t.left" [class.range-tick-active]="t.active" role="presentation"></div>' +
'<div class="range-bar" role="presentation"></div>' +
'<div class="range-bar range-bar-active" [style.left]="_barL" [style.right]="_barR" #bar role="presentation"></div>' +
'<div class="range-knob-handle" (ionIncrease)="_keyChg(true, false)" (ionDecrease)="_keyChg(false, false)" [ratio]="_ratioA" [val]="_valA" [pin]="_pin" [pressed]="_pressedA" [min]="_min" [max]="_max" [disabled]="_disabled" [labelId]="_labelId"></div>' +
'<div class="range-knob-handle" (ionIncrease)="_keyChg(true, true)" (ionDecrease)="_keyChg(false, true)" [ratio]="_ratioB" [val]="_valB" [pin]="_pin" [pressed]="_pressedB" [min]="_min" [max]="_max" [disabled]="_disabled" [labelId]="_labelId" *ngIf="_dual"></div>' +
'</div>' +
'<ng-content select="[range-right]"></ng-content>',
host: {
'[class.range-disabled]': '_disabled',
'[class.range-pressed]': '_pressed',
'[class.range-has-pin]': '_pin'
},
providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: Range, multi: true }],
encapsulation: ViewEncapsulation.None,
},] },
];
/**
* @nocollapse
*/
Range.ctorParameters = () => [
{ type: Form, },
{ type: Haptic, },
{ type: Item, decorators: [{ type: Optional },] },
{ type: Config, },
{ type: Platform, },
{ type: ElementRef, },
{ type: Renderer, },
{ type: DomController, },
{ type: ChangeDetectorRef, },
];
Range.propDecorators = {
'_slider': [{ type: ViewChild, args: ['slider',] },],
'min': [{ type: Input },],
'max': [{ type: Input },],
'step': [{ type: Input },],
'snaps': [{ type: Input },],
'pin': [{ type: Input },],
'debounce': [{ type: Input },],
'dualKnobs': [{ type: Input },],
};
function Range_tsickle_Closure_declarations() {
/** @type {?} */
Range.decorators;
/**
* @nocollapse
* @type {?}
*/
Range.ctorParameters;
/** @type {?} */
Range.propDecorators;
/** @type {?} */
Range.prototype._dual;
/** @type {?} */
Range.prototype._pin;
/** @type {?} */
Range.prototype._pressed;
/** @type {?} */
Range.prototype._activeB;
/** @type {?} */
Range.prototype._rect;
/** @type {?} */
Range.prototype._ticks;
/** @type {?} */
Range.prototype._min;
/** @type {?} */
Range.prototype._max;
/** @type {?} */
Range.prototype._step;
/** @type {?} */
Range.prototype._snaps;
/** @type {?} */
Range.prototype._valA;
/** @type {?} */
Range.prototype._valB;
/** @type {?} */
Range.prototype._ratioA;
/** @type {?} */
Range.prototype._ratioB;
/** @type {?} */
Range.prototype._pressedA;
/** @type {?} */
Range.prototype._pressedB;
/** @type {?} */
Range.prototype._barL;
/** @type {?} */
Range.prototype._barR;
/** @type {?} */
Range.prototype._events;
/** @type {?} */
Range.prototype._slider;
/** @type {?} */
Range.prototype._haptic;
/** @type {?} */
Range.prototype._plt;
/** @type {?} */
Range.prototype._dom;
/** @type {?} */
Range.prototype._cd;
}
//# sourceMappingURL=range.js.map | vivadaniele/spid-ionic-sdk | node_modules/ionic-angular/es2015/components/range/range.js | JavaScript | bsd-3-clause | 19,852 |
import getCompletions from "./get-completions"
// Add an autosuggest completer
export const addAutosuggestionCompleters = (ori, system) => (context) => {
return ori(context).concat([{
getCompletions(...args) {
// Add `context`, then `system` as the last args
return getCompletions(...args, context, system)
}
}])
}
| thomaxxl/safrs | swagger-editor/src/plugins/editor-autosuggest-snippets/wrap-actions.js | JavaScript | gpl-3.0 | 340 |
var foo = arr.map(v => ({
x: v.bar,
y: v.bar * 2
}));
var fn = () => ({}).key;
| rmacklin/babel | packages/babel-generator/test/fixtures/parentheses/arrow-function-object-body/expected.js | JavaScript | mit | 83 |
/**
* ag-grid - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v12.0.1
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
var gridOptionsWrapper_1 = require("../gridOptionsWrapper");
var columnController_1 = require("../columnController/columnController");
var gridPanel_1 = require("../gridPanel/gridPanel");
var column_1 = require("../entities/column");
var context_1 = require("../context/context");
var headerContainer_1 = require("./headerContainer");
var eventService_1 = require("../eventService");
var events_1 = require("../events");
var scrollVisibleService_1 = require("../gridPanel/scrollVisibleService");
var HeaderRenderer = (function () {
function HeaderRenderer() {
}
HeaderRenderer.prototype.init = function () {
var _this = this;
this.eHeaderViewport = this.gridPanel.getHeaderViewport();
this.eRoot = this.gridPanel.getRoot();
this.eHeaderOverlay = this.gridPanel.getHeaderOverlay();
this.centerContainer = new headerContainer_1.HeaderContainer(this.gridPanel.getHeaderContainer(), this.gridPanel.getHeaderViewport(), this.eRoot, null);
this.childContainers = [this.centerContainer];
if (!this.gridOptionsWrapper.isForPrint()) {
this.pinnedLeftContainer = new headerContainer_1.HeaderContainer(this.gridPanel.getPinnedLeftHeader(), null, this.eRoot, column_1.Column.PINNED_LEFT);
this.pinnedRightContainer = new headerContainer_1.HeaderContainer(this.gridPanel.getPinnedRightHeader(), null, this.eRoot, column_1.Column.PINNED_RIGHT);
this.childContainers.push(this.pinnedLeftContainer);
this.childContainers.push(this.pinnedRightContainer);
}
this.childContainers.forEach(function (container) { return _this.context.wireBean(container); });
// when grid columns change, it means the number of rows in the header has changed and it's all new columns
this.eventService.addEventListener(events_1.Events.EVENT_GRID_COLUMNS_CHANGED, this.onGridColumnsChanged.bind(this));
// shotgun way to get labels to change, eg from sum(amount) to avg(amount)
this.eventService.addEventListener(events_1.Events.EVENT_COLUMN_VALUE_CHANGED, this.refreshHeader.bind(this));
// for resized, the individual cells take care of this, so don't need to refresh everything
this.eventService.addEventListener(events_1.Events.EVENT_COLUMN_RESIZED, this.setPinnedColContainerWidth.bind(this));
this.eventService.addEventListener(events_1.Events.EVENT_DISPLAYED_COLUMNS_CHANGED, this.setPinnedColContainerWidth.bind(this));
this.eventService.addEventListener(events_1.Events.EVENT_SCROLL_VISIBILITY_CHANGED, this.onScrollVisibilityChanged.bind(this));
if (this.columnController.isReady()) {
this.refreshHeader();
}
};
HeaderRenderer.prototype.onScrollVisibilityChanged = function () {
this.setPinnedColContainerWidth();
};
HeaderRenderer.prototype.forEachHeaderElement = function (callback) {
this.childContainers.forEach(function (childContainer) { return childContainer.forEachHeaderElement(callback); });
};
HeaderRenderer.prototype.destroy = function () {
this.childContainers.forEach(function (container) { return container.destroy(); });
};
HeaderRenderer.prototype.onGridColumnsChanged = function () {
this.setHeight();
};
HeaderRenderer.prototype.refreshHeader = function () {
this.setHeight();
this.childContainers.forEach(function (container) { return container.refresh(); });
this.setPinnedColContainerWidth();
};
HeaderRenderer.prototype.setHeight = function () {
// if forPrint, overlay is missing
if (this.eHeaderOverlay) {
var rowHeight = this.gridOptionsWrapper.getHeaderHeight();
// we can probably get rid of this when we no longer need the overlay
var dept = this.columnController.getHeaderRowCount();
this.eHeaderOverlay.style.height = rowHeight + 'px';
this.eHeaderOverlay.style.top = ((dept - 1) * rowHeight) + 'px';
}
};
HeaderRenderer.prototype.setPinnedColContainerWidth = function () {
// pinned col doesn't exist when doing forPrint
if (this.gridOptionsWrapper.isForPrint()) {
return;
}
var pinnedLeftWidthWithScroll = this.scrollVisibleService.getPinnedLeftWithScrollWidth();
var pinnedRightWidthWithScroll = this.scrollVisibleService.getPinnedRightWithScrollWidth();
this.eHeaderViewport.style.marginLeft = pinnedLeftWidthWithScroll + 'px';
this.eHeaderViewport.style.marginRight = pinnedRightWidthWithScroll + 'px';
};
__decorate([
context_1.Autowired('gridOptionsWrapper'),
__metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper)
], HeaderRenderer.prototype, "gridOptionsWrapper", void 0);
__decorate([
context_1.Autowired('columnController'),
__metadata("design:type", columnController_1.ColumnController)
], HeaderRenderer.prototype, "columnController", void 0);
__decorate([
context_1.Autowired('gridPanel'),
__metadata("design:type", gridPanel_1.GridPanel)
], HeaderRenderer.prototype, "gridPanel", void 0);
__decorate([
context_1.Autowired('context'),
__metadata("design:type", context_1.Context)
], HeaderRenderer.prototype, "context", void 0);
__decorate([
context_1.Autowired('eventService'),
__metadata("design:type", eventService_1.EventService)
], HeaderRenderer.prototype, "eventService", void 0);
__decorate([
context_1.Autowired('scrollVisibleService'),
__metadata("design:type", scrollVisibleService_1.ScrollVisibleService)
], HeaderRenderer.prototype, "scrollVisibleService", void 0);
__decorate([
context_1.PostConstruct,
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", void 0)
], HeaderRenderer.prototype, "init", null);
__decorate([
context_1.PreDestroy,
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", void 0)
], HeaderRenderer.prototype, "destroy", null);
HeaderRenderer = __decorate([
context_1.Bean('headerRenderer')
], HeaderRenderer);
return HeaderRenderer;
}());
exports.HeaderRenderer = HeaderRenderer;
| sufuf3/cdnjs | ajax/libs/ag-grid/12.0.1/lib/headerRendering/headerRenderer.js | JavaScript | mit | 7,396 |
// Copyright 2008 The Closure Library Authors. All Rights Reserved.
//
// 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.
/**
* @fileoverview Generator for unique element IDs.
*
*/
goog.provide('goog.ui.IdGenerator');
/**
* Creates a new id generator.
* @constructor
*/
goog.ui.IdGenerator = function() {
};
goog.addSingletonGetter(goog.ui.IdGenerator);
/**
* Next unique ID to use
* @type {number}
* @private
*/
goog.ui.IdGenerator.prototype.nextId_ = 0;
/**
* Gets the next unique ID.
* @return {string} The next unique identifier.
*/
goog.ui.IdGenerator.prototype.getNextUniqueId = function() {
return ':' + (this.nextId_++).toString(36);
};
/**
* Default instance for id generation. Done as an instance instead of statics
* so it's possible to inject a mock for unit testing purposes.
* @type {goog.ui.IdGenerator}
* @deprecated Use goog.ui.IdGenerator.getInstance() instead and do not refer
* to goog.ui.IdGenerator.instance anymore.
*/
goog.ui.IdGenerator.instance = goog.ui.IdGenerator.getInstance();
| marcelohg/NasajonWebTeamplateProject | web/js/google-closure/closure/goog/ui/idgenerator.js | JavaScript | mit | 1,545 |
version https://git-lfs.github.com/spec/v1
oid sha256:df5a7287a63d8b28fe1df2552b7f2deaa719327f8aa49fef192f5fb72bbbbaad
size 4023
| yogeshsaroya/new-cdnjs | ajax/libs/ink/3.1.7/js/html5shiv-printshiv.js | JavaScript | mit | 129 |
'use strict';
var path = require('path');
var mergeTrees = require('broccoli-merge-trees');
var SassCompiler = require('../broccoli-sass');
function SASSPlugin() {
this.name = 'ember-cli-sass';
this.ext = ['scss', 'sass'];
}
SASSPlugin.prototype.toTree = function(tree, inputPath, outputPath, inputOptions) {
var options = inputOptions;
var inputTrees = [tree];
if (options.includePaths) {
inputTrees = inputTrees.concat(options.includePaths);
}
var ext = options.extension || 'scss';
var paths = options.outputPaths;
var trees = Object.keys(paths).map(function(file) {
var input = path.join(inputPath, file + '.' + ext);
var output = paths[file];
return new SassCompiler(inputTrees, input, output, options);
});
return mergeTrees(trees);
};
module.exports = {
name: 'ember-cli-sass',
setupPreprocessorRegistry: function(type, registry) {
registry.add('css', new SASSPlugin());
},
};
| xtian/ember-cli | tests/fixtures/preprocessor-tests/app-with-addon-with-preprocessors/node_modules/ember-cli-sass/index.js | JavaScript | mit | 940 |
declare class X {
a: number;
static b: number;
c: number;
}
| cbishopvelti/babylon | test/fixtures/flow/declare-statements/17/actual.js | JavaScript | mit | 63 |
/*!
* jQuery UI Effects Fold 1.11.2
* http://jqueryui.com
*
* Copyright 2014 jQuery Foundation and other contributors
* Released under the MIT license.
* http://jquery.org/license
*
* http://api.jqueryui.com/fold-effect/
*/(function(e){typeof define=="function"&&define.amd?define(["jquery","./effect"],e):e(jQuery)})(function(e){return e.effects.effect.fold=function(t,n){var r=e(this),i=["position","top","bottom","left","right","height","width"],s=e.effects.setMode(r,t.mode||"hide"),o=s==="show",u=s==="hide",a=t.size||15,f=/([0-9]+)%/.exec(a),l=!!t.horizFirst,c=o!==l,h=c?["width","height"]:["height","width"],p=t.duration/2,d,v,m={},g={};e.effects.save(r,i),r.show(),d=e.effects.createWrapper(r).css({overflow:"hidden"}),v=c?[d.width(),d.height()]:[d.height(),d.width()],f&&(a=parseInt(f[1],10)/100*v[u?0:1]),o&&d.css(l?{height:0,width:a}:{height:a,width:0}),m[h[0]]=o?v[0]:a,g[h[1]]=o?v[1]:0,d.animate(m,p,t.easing).animate(g,p,t.easing,function(){u&&r.hide(),e.effects.restore(r,i),e.effects.removeWrapper(r),n()})}}); | Nikola-xiii/d8intranet | drupal/core/assets/vendor/jquery.ui/ui/effect-fold-min.js | JavaScript | gpl-2.0 | 1,035 |
// eSpeak and other code here are under the GNU GPL.
function generateSpeech(text, args) {
var self = { text: text, args: args, ret: null };
(function() {
| francoislaberge/texttospeech | src/shell_pre.js | JavaScript | gpl-3.0 | 160 |
/******/ (function() { // webpackBootstrap
/******/ "use strict";
/******/
/******/
/******/ })()
; | mindsharelabs/mindshare-api | includes/acf/assets/build/css/pro/acf-pro-input.css.js | JavaScript | gpl-3.0 | 104 |
/**
*
* SugarCRM Community Edition is a customer relationship management program developed by
* SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
*
* SuiteCRM is an extension to SugarCRM Community Edition developed by SalesAgility Ltd.
* Copyright (C) 2011 - 2018 SalesAgility Ltd.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by the
* Free Software Foundation with the addition of the following permission added
* to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
* IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
* OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along with
* this program; if not, see http://www.gnu.org/licenses or write to the Free
* Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301 USA.
*
* You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
* SW2-130, Cupertino, CA 95014, USA. or at email address [email protected].
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "Powered by
* SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
* reasonably feasible for technical reasons, the Appropriate Legal Notices must
* display the words "Powered by SugarCRM" and "Supercharged by SuiteCRM".
*/
var aclviewer = function () {
var lastDisplay = '';
return {
view: function (role_id, role_module) {
YAHOO.util.Connect.asyncRequest('POST', 'index.php', {
'success': aclviewer.display,
'failure': aclviewer.failed
}, 'module=ACLRoles&action=EditRole&record=' + role_id + '&category_name=' + role_module);
ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_REQUEST_PROCESSED'));
},
save: function (form_name) {
var formObject = document.getElementById(form_name);
YAHOO.util.Connect.setForm(formObject);
YAHOO.util.Connect.asyncRequest('POST', 'index.php', {
'success': aclviewer.postSave,
'failure': aclviewer.failed
});
ajaxStatus.showStatus(SUGAR.language.get('app_strings', 'LBL_SAVING'));
},
postSave: function (o) {
SUGAR.util.globalEval(o.responseText);
aclviewer.view(result['role_id'], result['module']);
},
display: function (o) {
aclviewer.lastDisplay = '';
ajaxStatus.flashStatus('Done');
document.getElementById('category_data').innerHTML = o.responseText;
},
failed: function () {
ajax.flashStatus('Could Not Connect');
},
toggleDisplay: function (id) {
if (aclviewer.lastDisplay != '' && typeof(aclviewer.lastDisplay) != 'undefined') {
aclviewer.hideDisplay(aclviewer.lastDisplay);
}
if (aclviewer.lastDisplay != id) {
aclviewer.showDisplay(id);
aclviewer.lastDisplay = id;
} else {
aclviewer.lastDisplay = '';
}
},
hideDisplay: function (id) {
document.getElementById(id).style.display = 'none';
document.getElementById(id + 'link').style.display = '';
},
showDisplay: function (id) {
document.getElementById(id).style.display = '';
document.getElementById(id + 'link').style.display = 'none';
}
};
}();
| lionixevolve/SuiteCRM | jssource/src_files/modules/ACLRoles/ACLRoles.js | JavaScript | agpl-3.0 | 3,972 |
({"text":"รายละเอียด","insertImageTitle":"คุณสมบัติอิมเมจ","set":"ตั้งค่า","newWindow":"หน้าต่างใหม่","topWindow":"หน้าต่างบนสุด","target":"เป้าหมาย:","createLinkTitle":"คุณสมบัติลิงก์","parentWindow":"หน้าต่างหลัก","currentWindow":"หน้าต่างปัจจุบัน","url":"URL:"}) | ozoneplatform/owf-framework | web-app/js-lib/dojo-release-1.5.0/dijit/_editor/nls/th/LinkDialog.js | JavaScript | apache-2.0 | 479 |
/*
YUI 3.17.2 (build 9c3c78e)
Copyright 2014 Yahoo! Inc. All rights reserved.
Licensed under the BSD License.
http://yuilibrary.com/license/
*/
YUI.add('axis-time-base', function (Y, NAME) {
/**
* Provides functionality for the handling of time axis data for a chart.
*
* @module charts
* @submodule axis-time-base
*/
var Y_Lang = Y.Lang;
/**
* TimeImpl contains logic for time data. TimeImpl is used by the following classes:
* <ul>
* <li>{{#crossLink "TimeAxisBase"}}{{/crossLink}}</li>
* <li>{{#crossLink "TimeAxis"}}{{/crossLink}}</li>
* </ul>
*
* @class TimeImpl
* @constructor
* @submodule axis-time-base
*/
function TimeImpl()
{
}
TimeImpl.NAME = "timeImpl";
TimeImpl.ATTRS =
{
/**
* Method used for formatting a label. This attribute allows for the default label formatting method to overridden.
* The method use would need to implement the arguments below and return a `String` or an `HTMLElement`. The default
* implementation of the method returns a `String`. The output of this method will be rendered to the DOM using
* `appendChild`. If you override the `labelFunction` method and return an html string, you will also need to override
* the Axis' `appendLabelFunction` to accept html as a `String`.
* <dl>
* <dt>val</dt><dd>Label to be formatted. (`String`)</dd>
* <dt>format</dt><dd>STRFTime string used to format the label. (optional)</dd>
* </dl>
*
* @attribute labelFunction
* @type Function
*/
/**
* Pattern used by the `labelFunction` to format a label.
*
* @attribute labelFormat
* @type String
*/
labelFormat: {
value: "%b %d, %y"
}
};
TimeImpl.prototype = {
/**
* Type of data used in `Data`.
*
* @property _type
* @readOnly
* @private
*/
_type: "time",
/**
* Getter method for maximum attribute.
*
* @method _maximumGetter
* @return Number
* @private
*/
_maximumGetter: function ()
{
var max = this._getNumber(this._setMaximum);
if(!Y_Lang.isNumber(max))
{
max = this._getNumber(this.get("dataMaximum"));
}
return parseFloat(max);
},
/**
* Setter method for maximum attribute.
*
* @method _maximumSetter
* @param {Object} value
* @private
*/
_maximumSetter: function (value)
{
this._setMaximum = this._getNumber(value);
return value;
},
/**
* Getter method for minimum attribute.
*
* @method _minimumGetter
* @return Number
* @private
*/
_minimumGetter: function ()
{
var min = this._getNumber(this._setMinimum);
if(!Y_Lang.isNumber(min))
{
min = this._getNumber(this.get("dataMinimum"));
}
return parseFloat(min);
},
/**
* Setter method for minimum attribute.
*
* @method _minimumSetter
* @param {Object} value
* @private
*/
_minimumSetter: function (value)
{
this._setMinimum = this._getNumber(value);
return value;
},
/**
* Indicates whether or not the maximum attribute has been explicitly set.
*
* @method _getSetMax
* @return Boolean
* @private
*/
_getSetMax: function()
{
var max = this._getNumber(this._setMaximum);
return (Y_Lang.isNumber(max));
},
/**
* Indicates whether or not the minimum attribute has been explicitly set.
*
* @method _getSetMin
* @return Boolean
* @private
*/
_getSetMin: function()
{
var min = this._getNumber(this._setMinimum);
return (Y_Lang.isNumber(min));
},
/**
* Formats a label based on the axis type and optionally specified format.
*
* @method formatLabel
* @param {Object} value
* @param {Object} format Pattern used to format the value.
* @return String
*/
formatLabel: function(val, format)
{
val = Y.DataType.Date.parse(val);
if(format)
{
return Y.DataType.Date.format(val, {format:format});
}
return val;
},
/**
* Constant used to generate unique id.
*
* @property GUID
* @type String
* @private
*/
GUID: "yuitimeaxis",
/**
* Type of data used in `Axis`.
*
* @property _dataType
* @readOnly
* @private
*/
_dataType: "time",
/**
* Gets an array of values based on a key.
*
* @method _getKeyArray
* @param {String} key Value key associated with the data array.
* @param {Array} data Array in which the data resides.
* @return Array
* @private
*/
_getKeyArray: function(key, data)
{
var obj,
keyArray = [],
i = 0,
val,
len = data.length;
for(; i < len; ++i)
{
obj = data[i][key];
if(Y_Lang.isDate(obj))
{
val = obj.valueOf();
}
else
{
val = new Date(obj);
if(Y_Lang.isDate(val))
{
val = val.valueOf();
}
else if(!Y_Lang.isNumber(obj))
{
if(Y_Lang.isNumber(parseFloat(obj)))
{
val = parseFloat(obj);
}
else
{
if(typeof obj !== "string")
{
obj = obj;
}
val = new Date(obj).valueOf();
}
}
else
{
val = obj;
}
}
keyArray[i] = val;
}
return keyArray;
},
/**
* Calculates the maximum and minimum values for the `Axis`.
*
* @method _updateMinAndMax
* @private
*/
_updateMinAndMax: function()
{
var data = this.get("data"),
max = 0,
min = 0,
len,
num,
i;
if(data && data.length && data.length > 0)
{
len = data.length;
max = min = data[0];
if(len > 1)
{
for(i = 1; i < len; i++)
{
num = data[i];
if(isNaN(num))
{
continue;
}
max = Math.max(num, max);
min = Math.min(num, min);
}
}
}
this._dataMaximum = max;
this._dataMinimum = min;
},
/**
* Returns a coordinate corresponding to a data values.
*
* @method _getCoordFromValue
* @param {Number} min The minimum for the axis.
* @param {Number} max The maximum for the axis.
* @param {Number} length The distance that the axis spans.
* @param {Number} dataValue A value used to ascertain the coordinate.
* @param {Number} offset Value in which to offset the coordinates.
* @param {Boolean} reverse Indicates whether the coordinates should start from
* the end of an axis. Only used in the numeric implementation.
* @return Number
* @private
*/
_getCoordFromValue: function(min, max, length, dataValue, offset)
{
var range,
multiplier,
valuecoord,
isNumber = Y_Lang.isNumber;
dataValue = this._getNumber(dataValue);
if(isNumber(dataValue))
{
range = max - min;
multiplier = length/range;
valuecoord = (dataValue - min) * multiplier;
valuecoord = offset + valuecoord;
}
else
{
valuecoord = NaN;
}
return valuecoord;
},
/**
* Parses value into a number.
*
* @method _getNumber
* @param val {Object} Value to parse into a number
* @return Number
* @private
*/
_getNumber: function(val)
{
if(Y_Lang.isDate(val))
{
val = val.valueOf();
}
else if(!Y_Lang.isNumber(val) && val)
{
val = new Date(val).valueOf();
}
return val;
}
};
Y.TimeImpl = TimeImpl;
/**
* TimeAxisBase manages time data for an axis.
*
* @class TimeAxisBase
* @extends AxisBase
* @uses TimeImpl
* @constructor
* @param {Object} config (optional) Configuration parameters.
* @submodule axis-time-base
*/
Y.TimeAxisBase = Y.Base.create("timeAxisBase", Y.AxisBase, [Y.TimeImpl]);
}, '3.17.2', {"requires": ["axis-base"]});
| gdomingos/Wegas | wegas-resources/src/main/webapp/lib/yui3/build/axis-time-base/axis-time-base.js | JavaScript | mit | 8,841 |
/**
* @copyright (C) 2016 Open Source Matters, Inc. <https://www.joomla.org>
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
!(function(document, $) {
"use strict";
function initMinicolorsField (event) {
$(event.target).find('.minicolors').each(function() {
$(this).minicolors({
control: $(this).attr('data-control') || 'hue',
format: $(this).attr('data-validate') === 'color'
? 'hex'
: ($(this).attr('data-format') === 'rgba'
? 'rgb'
: $(this).attr('data-format'))
|| 'hex',
keywords: $(this).attr('data-keywords') || '',
opacity: $(this).attr('data-format') === 'rgba',
position: $(this).attr('data-position') || 'default',
swatches: $(this).attr('data-colors') ? $(this).attr('data-colors').split(",") : [],
theme: 'bootstrap'
});
});
}
/**
* Initialize at an initial page load
*/
document.addEventListener("DOMContentLoaded", initMinicolorsField);
/**
* Initialize when a part of the page was updated
*/
document.addEventListener("joomla:updated", initMinicolorsField);
})(document, jQuery);
| Fedik/joomla-cms | build/media_source/system/js/fields/color-field-adv-init.es5.js | JavaScript | gpl-2.0 | 1,118 |
/**
* Plugin that highlights matched word partials in a given element.
* TODO: Add a function for restoring the previous text.
* TODO: Accept mappings for converting shortcuts like WP: to Wikipedia:.
*/
( function ( $ ) {
$.highlightText = {
// Split our pattern string at spaces and run our highlight function on the results
splitAndHighlight: function ( node, pat ) {
var i,
patArray = pat.split( ' ' );
for ( i = 0; i < patArray.length; i++ ) {
if ( patArray[i].length === 0 ) {
continue;
}
$.highlightText.innerHighlight( node, patArray[i] );
}
return node;
},
// scans a node looking for the pattern and wraps a span around each match
innerHighlight: function ( node, pat ) {
var i, match, pos, spannode, middlebit, middleclone;
// if this is a text node
if ( node.nodeType === 3 ) {
// TODO - need to be smarter about the character matching here.
// non latin characters can make regex think a new word has begun: do not use \b
// http://stackoverflow.com/questions/3787072/regex-wordwrap-with-utf8-characters-in-js
// look for an occurrence of our pattern and store the starting position
match = node.data.match( new RegExp( "(^|\\s)" + $.escapeRE( pat ), "i" ) );
if ( match ) {
pos = match.index + match[1].length; // include length of any matched spaces
// create the span wrapper for the matched text
spannode = document.createElement( 'span' );
spannode.className = 'highlight';
// shave off the characters preceding the matched text
middlebit = node.splitText( pos );
// shave off any unmatched text off the end
middlebit.splitText( pat.length );
// clone for appending to our span
middleclone = middlebit.cloneNode( true );
// append the matched text node to the span
spannode.appendChild( middleclone );
// replace the matched node, with our span-wrapped clone of the matched node
middlebit.parentNode.replaceChild( spannode, middlebit );
}
// if this is an element with childnodes, and not a script, style or an element we created
} else if ( node.nodeType === 1 && node.childNodes && !/(script|style)/i.test( node.tagName )
&& !( node.tagName.toLowerCase() === 'span' && node.className.match( /\bhighlight/ ) ) ) {
for ( i = 0; i < node.childNodes.length; ++i ) {
// call the highlight function for each child node
$.highlightText.innerHighlight( node.childNodes[i], pat );
}
}
}
};
$.fn.highlightText = function ( matchString ) {
return this.each( function () {
var $el = $( this );
$el.data( 'highlightText', { originalText: $el.text() } );
$.highlightText.splitAndHighlight( this, matchString );
} );
};
}( jQuery ) );
| IEEEBerkeley/anabolic_window | resources/jquery/jquery.highlightText.js | JavaScript | gpl-2.0 | 2,750 |
odoo.define('web.domain_tests', function (require) {
"use strict";
var Domain = require('web.Domain');
QUnit.module('core', {}, function () {
QUnit.module('domain');
QUnit.test("basic", function (assert) {
assert.expect(3);
var fields = {
a: 3,
group_method: 'line',
select1: 'day',
rrule_type: 'monthly',
};
assert.ok(new Domain([['a', '=', 3]]).compute(fields));
assert.ok(new Domain([['group_method','!=','count']]).compute(fields));
assert.ok(new Domain([['select1','=','day'], ['rrule_type','=','monthly']]).compute(fields));
});
QUnit.test("or", function (assert) {
assert.expect(3);
var web = {
section_id: null,
user_id: null,
member_ids: null,
};
var currentDomain = [
'|',
['section_id', '=', 42],
'|',
['user_id', '=', 3],
['member_ids', 'in', [3]]
];
assert.ok(new Domain(currentDomain).compute(_.extend({}, web, {section_id: 42})));
assert.ok(new Domain(currentDomain).compute(_.extend({}, web, {user_id: 3})));
assert.ok(new Domain(currentDomain).compute(_.extend({}, web, {member_ids: 3})));
});
QUnit.test("not", function (assert) {
assert.expect(2);
var fields = {
a: 5,
group_method: 'line',
};
assert.ok(new Domain(['!', ['a', '=', 3]]).compute(fields));
assert.ok(new Domain(['!', ['group_method','=','count']]).compute(fields));
});
QUnit.test("domains initialized with a number", function (assert) {
assert.expect(2);
assert.ok(new Domain(1).compute({}));
assert.notOk(new Domain(0).compute({}));
});
});
});
| maxive/erp | addons/web/static/tests/core/domain_tests.js | JavaScript | agpl-3.0 | 1,846 |
/*
Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'elementspath', 'ca', {
eleLabel: 'Ruta dels elements',
eleTitle: '%1 element'
} );
| Jasig/resource-server | resource-server-content/src/main/webapp/rs/ckeditor/4.3.2/_source/plugins/elementspath/lang/ca.js | JavaScript | apache-2.0 | 258 |
var colors = require('../safe');
console.log(colors.yellow('First some yellow text'));
console.log(colors.yellow.underline('Underline that text'));
console.log(colors.red.bold('Make it bold and red'));
console.log(colors.rainbow('Double Raindows All Day Long'));
console.log(colors.trap('Drop the bass'));
console.log(colors.rainbow(colors.trap('DROP THE RAINBOW BASS')));
// styles not widely supported
console.log(colors.bold.italic.underline.red('Chains are also cool.'));
// styles not widely supported
console.log(colors.green('So ') + colors.underline('are') + ' '
+ colors.inverse('inverse') + colors.yellow.bold(' styles! '));
console.log(colors.zebra('Zebras are so fun!'));
console.log('This is ' + colors.strikethrough('not') + ' fun.');
console.log(colors.black.bgWhite('Background color attack!'));
console.log(colors.random('Use random styles on everything!'));
console.log(colors.america('America, Heck Yeah!'));
console.log(colors.brightCyan('Blindingly ') + colors.brightRed('bright? ') + colors.brightYellow('Why ') + colors.brightGreen('not?!'));
console.log('Setting themes is useful');
//
// Custom themes
//
// console.log('Generic logging theme as JSON'.green.bold.underline);
// Load theme with JSON literal
colors.setTheme({
silly: 'rainbow',
input: 'blue',
verbose: 'cyan',
prompt: 'grey',
info: 'green',
data: 'grey',
help: 'cyan',
warn: 'yellow',
debug: 'blue',
error: 'red',
});
// outputs red text
console.log(colors.error('this is an error'));
// outputs yellow text
console.log(colors.warn('this is a warning'));
// outputs blue text
console.log(colors.input('this is an input'));
// console.log('Generic logging theme as file'.green.bold.underline);
// Load a theme from file
colors.setTheme(require(__dirname + '/../themes/generic-logging.js'));
// outputs red text
console.log(colors.error('this is an error'));
// outputs yellow text
console.log(colors.warn('this is a warning'));
// outputs grey text
console.log(colors.input('this is an input'));
// console.log(colors.zalgo("Don't summon him"))
| BigBoss424/portfolio | v8/development/node_modules/colors/examples/safe-string.js | JavaScript | apache-2.0 | 2,083 |
// Copyright 2009 the Sputnik authors. All rights reserved.
/**
* Operator x ? y : z uses GetValue
*
* @path ch11/11.12/S11.12_A2.1_T3.js
* @description If ToBoolean(x) is true and GetBase(y) is null, throw ReferenceError
*/
//CHECK#1
try {
true ? y : false;
$ERROR('#1.1: true ? y : false throw ReferenceError. Actual: ' + (true ? y : false));
}
catch (e) {
if ((e instanceof ReferenceError) !== true) {
$ERROR('#1.2: true ? y : false throw ReferenceError. Actual: ' + (e));
}
}
| Oceanswave/NiL.JS | Tests/tests/sputnik/ch11/11.12/S11.12_A2.1_T3.js | JavaScript | bsd-3-clause | 504 |
/**
* sp-pnp-js v2.0.6-beta.1 - A JavaScript library for SharePoint development.
* MIT (https://github.com/SharePoint/PnP-JS-Core/blob/master/LICENSE)
* Copyright (c) 2017 Microsoft
* docs: http://officedev.github.io/PnP-JS-Core
* source: https://github.com/SharePoint/PnP-JS-Core
* bugs: https://github.com/SharePoint/PnP-JS-Core/issues
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define([], factory);
else if(typeof exports === 'object')
exports["$pnp"] = factory();
else
root["$pnp"] = 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] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = 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;
/******/
/******/ // identity function for calling harmony imports with the correct context
/******/ __webpack_require__.i = function(value) { return value; };
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "/assets/";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 41);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {
Object.defineProperty(exports, "__esModule", { value: true });
var pnplibconfig_1 = __webpack_require__(4);
var Util = (function () {
function Util() {
}
/**
* Gets a callback function which will maintain context across async calls.
* Allows for the calling pattern getCtxCallback(thisobj, method, methodarg1, methodarg2, ...)
*
* @param context The object that will be the 'this' value in the callback
* @param method The method to which we will apply the context and parameters
* @param params Optional, additional arguments to supply to the wrapped method when it is invoked
*/
Util.getCtxCallback = function (context, method) {
var params = [];
for (var _i = 2; _i < arguments.length; _i++) {
params[_i - 2] = arguments[_i];
}
return function () {
method.apply(context, params);
};
};
/**
* Tests if a url param exists
*
* @param name The name of the url paramter to check
*/
Util.urlParamExists = function (name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
return regex.test(location.search);
};
/**
* Gets a url param value by name
*
* @param name The name of the paramter for which we want the value
*/
Util.getUrlParamByName = function (name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)");
var results = regex.exec(location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
};
/**
* Gets a url param by name and attempts to parse a bool value
*
* @param name The name of the paramter for which we want the boolean value
*/
Util.getUrlParamBoolByName = function (name) {
var p = this.getUrlParamByName(name);
var isFalse = (p === "" || /false|0/i.test(p));
return !isFalse;
};
/**
* Inserts the string s into the string target as the index specified by index
*
* @param target The string into which we will insert s
* @param index The location in target to insert s (zero based)
* @param s The string to insert into target at position index
*/
Util.stringInsert = function (target, index, s) {
if (index > 0) {
return target.substring(0, index) + s + target.substring(index, target.length);
}
return s + target;
};
/**
* Adds a value to a date
*
* @param date The date to which we will add units, done in local time
* @param interval The name of the interval to add, one of: ['year', 'quarter', 'month', 'week', 'day', 'hour', 'minute', 'second']
* @param units The amount to add to date of the given interval
*
* http://stackoverflow.com/questions/1197928/how-to-add-30-minutes-to-a-javascript-date-object
*/
Util.dateAdd = function (date, interval, units) {
var ret = new Date(date.toLocaleString()); // don't change original date
switch (interval.toLowerCase()) {
case "year":
ret.setFullYear(ret.getFullYear() + units);
break;
case "quarter":
ret.setMonth(ret.getMonth() + 3 * units);
break;
case "month":
ret.setMonth(ret.getMonth() + units);
break;
case "week":
ret.setDate(ret.getDate() + 7 * units);
break;
case "day":
ret.setDate(ret.getDate() + units);
break;
case "hour":
ret.setTime(ret.getTime() + units * 3600000);
break;
case "minute":
ret.setTime(ret.getTime() + units * 60000);
break;
case "second":
ret.setTime(ret.getTime() + units * 1000);
break;
default:
ret = undefined;
break;
}
return ret;
};
/**
* Loads a stylesheet into the current page
*
* @param path The url to the stylesheet
* @param avoidCache If true a value will be appended as a query string to avoid browser caching issues
*/
Util.loadStylesheet = function (path, avoidCache) {
if (avoidCache) {
path += "?" + encodeURIComponent((new Date()).getTime().toString());
}
var head = document.getElementsByTagName("head");
if (head.length > 0) {
var e = document.createElement("link");
head[0].appendChild(e);
e.setAttribute("type", "text/css");
e.setAttribute("rel", "stylesheet");
e.setAttribute("href", path);
}
};
/**
* Combines an arbitrary set of paths ensuring that the slashes are normalized
*
* @param paths 0 to n path parts to combine
*/
Util.combinePaths = function () {
var paths = [];
for (var _i = 0; _i < arguments.length; _i++) {
paths[_i] = arguments[_i];
}
return paths
.filter(function (path) { return !Util.stringIsNullOrEmpty(path); })
.map(function (path) { return path.replace(/^[\\|\/]/, "").replace(/[\\|\/]$/, ""); })
.join("/")
.replace(/\\/g, "/");
};
/**
* Gets a random string of chars length
*
* @param chars The length of the random string to generate
*/
Util.getRandomString = function (chars) {
var text = new Array(chars);
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < chars; i++) {
text[i] = possible.charAt(Math.floor(Math.random() * possible.length));
}
return text.join("");
};
/**
* Gets a random GUID value
*
* http://stackoverflow.com/questions/105034/create-guid-uuid-in-javascript
*/
/* tslint:disable no-bitwise */
Util.getGUID = function () {
var d = new Date().getTime();
var guid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
var r = (d + Math.random() * 16) % 16 | 0;
d = Math.floor(d / 16);
return (c === "x" ? r : (r & 0x3 | 0x8)).toString(16);
});
return guid;
};
/* tslint:enable */
/**
* Determines if a given value is a function
*
* @param candidateFunction The thing to test for being a function
*/
Util.isFunction = function (candidateFunction) {
return typeof candidateFunction === "function";
};
/**
* @returns whether the provided parameter is a JavaScript Array or not.
*/
Util.isArray = function (array) {
if (Array.isArray) {
return Array.isArray(array);
}
return array && typeof array.length === "number" && array.constructor === Array;
};
/**
* Determines if a string is null or empty or undefined
*
* @param s The string to test
*/
Util.stringIsNullOrEmpty = function (s) {
return typeof s === "undefined" || s === null || s.length < 1;
};
/**
* Provides functionality to extend the given object by doing a shallow copy
*
* @param target The object to which properties will be copied
* @param source The source object from which properties will be copied
* @param noOverwrite If true existing properties on the target are not overwritten from the source
*
*/
Util.extend = function (target, source, noOverwrite) {
if (noOverwrite === void 0) { noOverwrite = false; }
if (source === null || typeof source === "undefined") {
return target;
}
// ensure we don't overwrite things we don't want overwritten
var check = noOverwrite ? function (o, i) { return !(i in o); } : function () { return true; };
return Object.getOwnPropertyNames(source)
.filter(function (v) { return check(target, v); })
.reduce(function (t, v) {
t[v] = source[v];
return t;
}, target);
};
/**
* Determines if a given url is absolute
*
* @param url The url to check to see if it is absolute
*/
Util.isUrlAbsolute = function (url) {
return /^https?:\/\/|^\/\//i.test(url);
};
/**
* Ensures that a given url is absolute for the current web based on context
*
* @param candidateUrl The url to make absolute
*
*/
Util.toAbsoluteUrl = function (candidateUrl) {
return new Promise(function (resolve) {
if (Util.isUrlAbsolute(candidateUrl)) {
// if we are already absolute, then just return the url
return resolve(candidateUrl);
}
if (pnplibconfig_1.RuntimeConfig.baseUrl !== null) {
// base url specified either with baseUrl of spfxContext config property
return resolve(Util.combinePaths(pnplibconfig_1.RuntimeConfig.baseUrl, candidateUrl));
}
if (typeof global._spPageContextInfo !== "undefined") {
// operating in classic pages
if (global._spPageContextInfo.hasOwnProperty("webAbsoluteUrl")) {
return resolve(Util.combinePaths(global._spPageContextInfo.webAbsoluteUrl, candidateUrl));
}
else if (global._spPageContextInfo.hasOwnProperty("webServerRelativeUrl")) {
return resolve(Util.combinePaths(global._spPageContextInfo.webServerRelativeUrl, candidateUrl));
}
}
// does window.location exist and have _layouts in it?
if (typeof global.location !== "undefined") {
var index = global.location.toString().toLowerCase().indexOf("/_layouts/");
if (index > 0) {
// we are likely in the workbench in /_layouts/
return resolve(Util.combinePaths(global.location.toString().substr(0, index), candidateUrl));
}
}
return resolve(candidateUrl);
});
};
return Util;
}());
exports.Util = Util;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(32)))
/***/ }),
/* 1 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 util_1 = __webpack_require__(0);
var collections_1 = __webpack_require__(6);
var odata_1 = __webpack_require__(2);
var pnplibconfig_1 = __webpack_require__(4);
var exceptions_1 = __webpack_require__(3);
var logging_1 = __webpack_require__(5);
var pipeline_1 = __webpack_require__(45);
/**
* Queryable Base Class
*
*/
var Queryable = (function () {
/**
* Creates a new instance of the Queryable class
*
* @constructor
* @param baseUrl A string or Queryable that should form the base part of the url
*
*/
function Queryable(baseUrl, path) {
this._query = new collections_1.Dictionary();
this._batch = null;
if (typeof baseUrl === "string") {
// we need to do some extra parsing to get the parent url correct if we are
// being created from just a string.
var urlStr = baseUrl;
if (util_1.Util.isUrlAbsolute(urlStr) || urlStr.lastIndexOf("/") < 0) {
this._parentUrl = urlStr;
this._url = util_1.Util.combinePaths(urlStr, path);
}
else if (urlStr.lastIndexOf("/") > urlStr.lastIndexOf("(")) {
// .../items(19)/fields
var index = urlStr.lastIndexOf("/");
this._parentUrl = urlStr.slice(0, index);
path = util_1.Util.combinePaths(urlStr.slice(index), path);
this._url = util_1.Util.combinePaths(this._parentUrl, path);
}
else {
// .../items(19)
var index = urlStr.lastIndexOf("(");
this._parentUrl = urlStr.slice(0, index);
this._url = util_1.Util.combinePaths(urlStr, path);
}
}
else {
var q = baseUrl;
this._parentUrl = q._url;
var target = q._query.get("@target");
if (target !== null) {
this._query.add("@target", target);
}
this._url = util_1.Util.combinePaths(this._parentUrl, path);
}
}
/**
* Directly concatonates the supplied string to the current url, not normalizing "/" chars
*
* @param pathPart The string to concatonate to the url
*/
Queryable.prototype.concat = function (pathPart) {
this._url += pathPart;
return this;
};
/**
* Appends the given string and normalizes "/" chars
*
* @param pathPart The string to append
*/
Queryable.prototype.append = function (pathPart) {
this._url = util_1.Util.combinePaths(this._url, pathPart);
};
/**
* Blocks a batch call from occuring, MUST be cleared by calling the returned function
*/
Queryable.prototype.addBatchDependency = function () {
if (this.hasBatch) {
return this._batch.addDependency();
}
return function () { return null; };
};
Object.defineProperty(Queryable.prototype, "hasBatch", {
/**
* Indicates if the current query has a batch associated
*
*/
get: function () {
return this._batch !== null;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Queryable.prototype, "batch", {
/**
* The batch currently associated with this query or null
*
*/
get: function () {
return this.hasBatch ? this._batch : null;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Queryable.prototype, "parentUrl", {
/**
* Gets the parent url used when creating this instance
*
*/
get: function () {
return this._parentUrl;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Queryable.prototype, "query", {
/**
* Provides access to the query builder for this url
*
*/
get: function () {
return this._query;
},
enumerable: true,
configurable: true
});
/**
* Creates a new instance of the supplied factory and extends this into that new instance
*
* @param factory constructor for the new queryable
*/
Queryable.prototype.as = function (factory) {
var o = new factory(this._url, null);
return util_1.Util.extend(o, this, true);
};
/**
* Adds this query to the supplied batch
*
* @example
* ```
*
* let b = pnp.sp.createBatch();
* pnp.sp.web.inBatch(b).get().then(...);
* b.execute().then(...)
* ```
*/
Queryable.prototype.inBatch = function (batch) {
if (this._batch !== null) {
throw new exceptions_1.AlreadyInBatchException();
}
this._batch = batch;
return this;
};
/**
* Enables caching for this request
*
* @param options Defines the options used when caching this request
*/
Queryable.prototype.usingCaching = function (options) {
if (!pnplibconfig_1.RuntimeConfig.globalCacheDisable) {
this._useCaching = true;
this._cachingOptions = options;
}
return this;
};
/**
* Gets the currentl url, made absolute based on the availability of the _spPageContextInfo object
*
*/
Queryable.prototype.toUrl = function () {
return this._url;
};
/**
* Gets the full url with query information
*
*/
Queryable.prototype.toUrlAndQuery = function () {
var aliasedParams = new collections_1.Dictionary();
var url = this.toUrl().replace(/'!(@.*?)::(.*?)'/ig, function (match, labelName, value) {
logging_1.Logger.write("Rewriting aliased parameter from match " + match + " to label: " + labelName + " value: " + value, logging_1.LogLevel.Verbose);
aliasedParams.add(labelName, "'" + value + "'");
return labelName;
});
// inlude our explicitly set query string params
aliasedParams.merge(this._query);
if (aliasedParams.count() > 0) {
url += "?" + aliasedParams.getKeys().map(function (key) { return key + "=" + aliasedParams.get(key); }).join("&");
}
return url;
};
/**
* Gets a parent for this instance as specified
*
* @param factory The contructor for the class to create
*/
Queryable.prototype.getParent = function (factory, baseUrl, path, batch) {
if (baseUrl === void 0) { baseUrl = this.parentUrl; }
var parent = new factory(baseUrl, path);
var target = this.query.get("@target");
if (target !== null) {
parent.query.add("@target", target);
}
if (typeof batch !== "undefined") {
parent = parent.inBatch(batch);
}
return parent;
};
/**
* Clones this queryable into a new queryable instance of T
* @param factory Constructor used to create the new instance
* @param additionalPath Any additional path to include in the clone
* @param includeBatch If true this instance's batch will be added to the cloned instance
*/
Queryable.prototype.clone = function (factory, additionalPath, includeBatch) {
if (includeBatch === void 0) { includeBatch = false; }
var clone = new factory(this, additionalPath);
var target = this.query.get("@target");
if (target !== null) {
clone.query.add("@target", target);
}
if (includeBatch && this.hasBatch) {
clone = clone.inBatch(this.batch);
}
return clone;
};
/**
* Executes the currently built request
*
* @param parser Allows you to specify a parser to handle the result
* @param getOptions The options used for this request
*/
Queryable.prototype.get = function (parser, getOptions) {
if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); }
if (getOptions === void 0) { getOptions = {}; }
return this.toRequestContext("GET", getOptions, parser).then(function (context) { return pipeline_1.pipe(context); });
};
Queryable.prototype.getAs = function (parser, getOptions) {
if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); }
if (getOptions === void 0) { getOptions = {}; }
return this.toRequestContext("GET", getOptions, parser).then(function (context) { return pipeline_1.pipe(context); });
};
Queryable.prototype.post = function (postOptions, parser) {
if (postOptions === void 0) { postOptions = {}; }
if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); }
return this.toRequestContext("POST", postOptions, parser).then(function (context) { return pipeline_1.pipe(context); });
};
Queryable.prototype.postAs = function (postOptions, parser) {
if (postOptions === void 0) { postOptions = {}; }
if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); }
return this.toRequestContext("POST", postOptions, parser).then(function (context) { return pipeline_1.pipe(context); });
};
Queryable.prototype.patch = function (patchOptions, parser) {
if (patchOptions === void 0) { patchOptions = {}; }
if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); }
return this.toRequestContext("PATCH", patchOptions, parser).then(function (context) { return pipeline_1.pipe(context); });
};
Queryable.prototype.delete = function (deleteOptions, parser) {
if (deleteOptions === void 0) { deleteOptions = {}; }
if (parser === void 0) { parser = new odata_1.ODataDefaultParser(); }
return this.toRequestContext("DELETE", deleteOptions, parser).then(function (context) { return pipeline_1.pipe(context); });
};
/**
* Converts the current instance to a request context
*
* @param verb The request verb
* @param options The set of supplied request options
* @param parser The supplied ODataParser instance
* @param pipeline Optional request processing pipeline
*/
Queryable.prototype.toRequestContext = function (verb, options, parser, pipeline) {
var _this = this;
if (options === void 0) { options = {}; }
if (pipeline === void 0) { pipeline = pipeline_1.PipelineMethods.default; }
var dependencyDispose = this.hasBatch ? this.addBatchDependency() : function () { return; };
return util_1.Util.toAbsoluteUrl(this.toUrlAndQuery()).then(function (url) {
// build our request context
var context = {
batch: _this._batch,
batchDependency: dependencyDispose,
cachingOptions: _this._cachingOptions,
isBatched: _this.hasBatch,
isCached: _this._useCaching,
options: options,
parser: parser,
pipeline: pipeline,
requestAbsoluteUrl: url,
requestId: util_1.Util.getGUID(),
verb: verb,
};
return context;
});
};
return Queryable;
}());
exports.Queryable = Queryable;
/**
* Represents a REST collection which can be filtered, paged, and selected
*
*/
var QueryableCollection = (function (_super) {
__extends(QueryableCollection, _super);
function QueryableCollection() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Filters the returned collection (https://msdn.microsoft.com/en-us/library/office/fp142385.aspx#bk_supported)
*
* @param filter The string representing the filter query
*/
QueryableCollection.prototype.filter = function (filter) {
this._query.add("$filter", filter);
return this;
};
/**
* Choose which fields to return
*
* @param selects One or more fields to return
*/
QueryableCollection.prototype.select = function () {
var selects = [];
for (var _i = 0; _i < arguments.length; _i++) {
selects[_i] = arguments[_i];
}
if (selects.length > 0) {
this._query.add("$select", selects.join(","));
}
return this;
};
/**
* Expands fields such as lookups to get additional data
*
* @param expands The Fields for which to expand the values
*/
QueryableCollection.prototype.expand = function () {
var expands = [];
for (var _i = 0; _i < arguments.length; _i++) {
expands[_i] = arguments[_i];
}
if (expands.length > 0) {
this._query.add("$expand", expands.join(","));
}
return this;
};
/**
* Orders based on the supplied fields ascending
*
* @param orderby The name of the field to sort on
* @param ascending If false DESC is appended, otherwise ASC (default)
*/
QueryableCollection.prototype.orderBy = function (orderBy, ascending) {
if (ascending === void 0) { ascending = true; }
var keys = this._query.getKeys();
var query = [];
var asc = ascending ? " asc" : " desc";
for (var i = 0; i < keys.length; i++) {
if (keys[i] === "$orderby") {
query.push(this._query.get("$orderby"));
break;
}
}
query.push("" + orderBy + asc);
this._query.add("$orderby", query.join(","));
return this;
};
/**
* Skips the specified number of items
*
* @param skip The number of items to skip
*/
QueryableCollection.prototype.skip = function (skip) {
this._query.add("$skip", skip.toString());
return this;
};
/**
* Limits the query to only return the specified number of items
*
* @param top The query row limit
*/
QueryableCollection.prototype.top = function (top) {
this._query.add("$top", top.toString());
return this;
};
return QueryableCollection;
}(Queryable));
exports.QueryableCollection = QueryableCollection;
/**
* Represents an instance that can be selected
*
*/
var QueryableInstance = (function (_super) {
__extends(QueryableInstance, _super);
function QueryableInstance() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Choose which fields to return
*
* @param selects One or more fields to return
*/
QueryableInstance.prototype.select = function () {
var selects = [];
for (var _i = 0; _i < arguments.length; _i++) {
selects[_i] = arguments[_i];
}
if (selects.length > 0) {
this._query.add("$select", selects.join(","));
}
return this;
};
/**
* Expands fields such as lookups to get additional data
*
* @param expands The Fields for which to expand the values
*/
QueryableInstance.prototype.expand = function () {
var expands = [];
for (var _i = 0; _i < arguments.length; _i++) {
expands[_i] = arguments[_i];
}
if (expands.length > 0) {
this._query.add("$expand", expands.join(","));
}
return this;
};
return QueryableInstance;
}(Queryable));
exports.QueryableInstance = QueryableInstance;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 util_1 = __webpack_require__(0);
var logging_1 = __webpack_require__(5);
var httpclient_1 = __webpack_require__(15);
var pnplibconfig_1 = __webpack_require__(4);
var exceptions_1 = __webpack_require__(3);
var exceptions_2 = __webpack_require__(3);
function extractOdataId(candidate) {
if (candidate.hasOwnProperty("odata.id")) {
return candidate["odata.id"];
}
else if (candidate.hasOwnProperty("__metadata") && candidate.__metadata.hasOwnProperty("id")) {
return candidate.__metadata.id;
}
else {
throw new exceptions_1.ODataIdException(candidate);
}
}
exports.extractOdataId = extractOdataId;
var ODataParserBase = (function () {
function ODataParserBase() {
}
ODataParserBase.prototype.parse = function (r) {
var _this = this;
return new Promise(function (resolve, reject) {
if (_this.handleError(r, reject)) {
if ((r.headers.has("Content-Length") && parseFloat(r.headers.get("Content-Length")) === 0) || r.status === 204) {
resolve({});
}
else {
r.json().then(function (json) { return resolve(_this.parseODataJSON(json)); }).catch(function (e) { return reject(e); });
}
}
});
};
ODataParserBase.prototype.handleError = function (r, reject) {
if (!r.ok) {
r.json().then(function (json) {
// include the headers as they contain diagnostic information
var data = {
responseBody: json,
responseHeaders: r.headers,
};
reject(new exceptions_2.ProcessHttpClientResponseException(r.status, r.statusText, data));
}).catch(function (e) {
// we failed to read the body - possibly it is empty. Let's report the original status that caused
// the request to fail and log the error with parsing the body if anyone needs it for debugging
logging_1.Logger.log({
data: e,
level: logging_1.LogLevel.Warning,
message: "There was an error parsing the error response body. See data for details.",
});
// include the headers as they contain diagnostic information
var data = {
responseBody: "[[body not available]]",
responseHeaders: r.headers,
};
reject(new exceptions_2.ProcessHttpClientResponseException(r.status, r.statusText, data));
});
}
return r.ok;
};
ODataParserBase.prototype.parseODataJSON = function (json) {
var result = json;
if (json.hasOwnProperty("d")) {
if (json.d.hasOwnProperty("results")) {
result = json.d.results;
}
else {
result = json.d;
}
}
else if (json.hasOwnProperty("value")) {
result = json.value;
}
return result;
};
return ODataParserBase;
}());
exports.ODataParserBase = ODataParserBase;
var ODataDefaultParser = (function (_super) {
__extends(ODataDefaultParser, _super);
function ODataDefaultParser() {
return _super !== null && _super.apply(this, arguments) || this;
}
return ODataDefaultParser;
}(ODataParserBase));
exports.ODataDefaultParser = ODataDefaultParser;
var ODataRawParserImpl = (function () {
function ODataRawParserImpl() {
}
ODataRawParserImpl.prototype.parse = function (r) {
return r.json();
};
return ODataRawParserImpl;
}());
exports.ODataRawParserImpl = ODataRawParserImpl;
var ODataValueParserImpl = (function (_super) {
__extends(ODataValueParserImpl, _super);
function ODataValueParserImpl() {
return _super !== null && _super.apply(this, arguments) || this;
}
ODataValueParserImpl.prototype.parse = function (r) {
return _super.prototype.parse.call(this, r).then(function (d) { return d; });
};
return ODataValueParserImpl;
}(ODataParserBase));
var ODataEntityParserImpl = (function (_super) {
__extends(ODataEntityParserImpl, _super);
function ODataEntityParserImpl(factory) {
var _this = _super.call(this) || this;
_this.factory = factory;
return _this;
}
ODataEntityParserImpl.prototype.parse = function (r) {
var _this = this;
return _super.prototype.parse.call(this, r).then(function (d) {
var o = new _this.factory(getEntityUrl(d), null);
return util_1.Util.extend(o, d);
});
};
return ODataEntityParserImpl;
}(ODataParserBase));
var ODataEntityArrayParserImpl = (function (_super) {
__extends(ODataEntityArrayParserImpl, _super);
function ODataEntityArrayParserImpl(factory) {
var _this = _super.call(this) || this;
_this.factory = factory;
return _this;
}
ODataEntityArrayParserImpl.prototype.parse = function (r) {
var _this = this;
return _super.prototype.parse.call(this, r).then(function (d) {
return d.map(function (v) {
var o = new _this.factory(getEntityUrl(v), null);
return util_1.Util.extend(o, v);
});
});
};
return ODataEntityArrayParserImpl;
}(ODataParserBase));
function getEntityUrl(entity) {
if (entity.hasOwnProperty("odata.editLink")) {
// we are dealign with minimal metadata (default)
return util_1.Util.combinePaths("_api", entity["odata.editLink"]);
}
else if (entity.hasOwnProperty("__metadata")) {
// we are dealing with verbose, which has an absolute uri
return entity.__metadata.uri;
}
else {
// we are likely dealing with nometadata, so don't error but we won't be able to
// chain off these objects
logging_1.Logger.write("No uri information found in ODataEntity parsing, chaining will fail for this object.", logging_1.LogLevel.Warning);
return "";
}
}
exports.getEntityUrl = getEntityUrl;
exports.ODataRaw = new ODataRawParserImpl();
function ODataValue() {
return new ODataValueParserImpl();
}
exports.ODataValue = ODataValue;
function ODataEntity(factory) {
return new ODataEntityParserImpl(factory);
}
exports.ODataEntity = ODataEntity;
function ODataEntityArray(factory) {
return new ODataEntityArrayParserImpl(factory);
}
exports.ODataEntityArray = ODataEntityArray;
/**
* Manages a batch of OData operations
*/
var ODataBatch = (function () {
function ODataBatch(baseUrl, _batchId) {
if (_batchId === void 0) { _batchId = util_1.Util.getGUID(); }
this.baseUrl = baseUrl;
this._batchId = _batchId;
this._requests = [];
this._dependencies = [];
}
Object.defineProperty(ODataBatch.prototype, "batchId", {
get: function () {
return this._batchId;
},
enumerable: true,
configurable: true
});
/**
* Adds a request to a batch (not designed for public use)
*
* @param url The full url of the request
* @param method The http method GET, POST, etc
* @param options Any options to include in the request
* @param parser The parser that will hadle the results of the request
*/
ODataBatch.prototype.add = function (url, method, options, parser) {
var info = {
method: method.toUpperCase(),
options: options,
parser: parser,
reject: null,
resolve: null,
url: url,
};
var p = new Promise(function (resolve, reject) {
info.resolve = resolve;
info.reject = reject;
});
this._requests.push(info);
return p;
};
/**
* Adds a dependency insuring that some set of actions will occur before a batch is processed.
* MUST be cleared using the returned resolve delegate to allow batches to run
*/
ODataBatch.prototype.addDependency = function () {
var resolver;
var promise = new Promise(function (resolve) {
resolver = resolve;
});
this._dependencies.push(promise);
return resolver;
};
/**
* Execute the current batch and resolve the associated promises
*
* @returns A promise which will be resolved once all of the batch's child promises have resolved
*/
ODataBatch.prototype.execute = function () {
var _this = this;
// we need to check the dependencies twice due to how different engines handle things.
// We can get a second set of promises added after the first set resolve
return Promise.all(this._dependencies).then(function () { return Promise.all(_this._dependencies); }).then(function () { return _this.executeImpl(); });
};
ODataBatch.prototype.executeImpl = function () {
var _this = this;
logging_1.Logger.write("[" + this.batchId + "] (" + (new Date()).getTime() + ") Executing batch with " + this._requests.length + " requests.", logging_1.LogLevel.Info);
// if we don't have any requests, don't bother sending anything
// this could be due to caching further upstream, or just an empty batch
if (this._requests.length < 1) {
logging_1.Logger.write("Resolving empty batch.", logging_1.LogLevel.Info);
return Promise.resolve();
}
// creating the client here allows the url to be populated for nodejs client as well as potentially
// any other hacks needed for other types of clients. Essentially allows the absoluteRequestUrl
// below to be correct
var client = new httpclient_1.HttpClient();
// due to timing we need to get the absolute url here so we can use it for all the individual requests
// and for sending the entire batch
return util_1.Util.toAbsoluteUrl(this.baseUrl).then(function (absoluteRequestUrl) {
// build all the requests, send them, pipe results in order to parsers
var batchBody = [];
var currentChangeSetId = "";
for (var i = 0; i < _this._requests.length; i++) {
var reqInfo = _this._requests[i];
if (reqInfo.method === "GET") {
if (currentChangeSetId.length > 0) {
// end an existing change set
batchBody.push("--changeset_" + currentChangeSetId + "--\n\n");
currentChangeSetId = "";
}
batchBody.push("--batch_" + _this._batchId + "\n");
}
else {
if (currentChangeSetId.length < 1) {
// start new change set
currentChangeSetId = util_1.Util.getGUID();
batchBody.push("--batch_" + _this._batchId + "\n");
batchBody.push("Content-Type: multipart/mixed; boundary=\"changeset_" + currentChangeSetId + "\"\n\n");
}
batchBody.push("--changeset_" + currentChangeSetId + "\n");
}
// common batch part prefix
batchBody.push("Content-Type: application/http\n");
batchBody.push("Content-Transfer-Encoding: binary\n\n");
var headers = {
"Accept": "application/json;",
};
// this is the url of the individual request within the batch
var url = util_1.Util.isUrlAbsolute(reqInfo.url) ? reqInfo.url : util_1.Util.combinePaths(absoluteRequestUrl, reqInfo.url);
logging_1.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Adding request " + reqInfo.method + " " + url + " to batch.", logging_1.LogLevel.Verbose);
if (reqInfo.method !== "GET") {
var method = reqInfo.method;
if (reqInfo.hasOwnProperty("options") && reqInfo.options.hasOwnProperty("headers") && typeof reqInfo.options.headers["X-HTTP-Method"] !== "undefined") {
method = reqInfo.options.headers["X-HTTP-Method"];
delete reqInfo.options.headers["X-HTTP-Method"];
}
batchBody.push(method + " " + url + " HTTP/1.1\n");
headers = util_1.Util.extend(headers, { "Content-Type": "application/json;odata=verbose;charset=utf-8" });
}
else {
batchBody.push(reqInfo.method + " " + url + " HTTP/1.1\n");
}
if (typeof pnplibconfig_1.RuntimeConfig.headers !== "undefined") {
headers = util_1.Util.extend(headers, pnplibconfig_1.RuntimeConfig.headers);
}
if (reqInfo.options && reqInfo.options.headers) {
headers = util_1.Util.extend(headers, reqInfo.options.headers);
}
for (var name_1 in headers) {
if (headers.hasOwnProperty(name_1)) {
batchBody.push(name_1 + ": " + headers[name_1] + "\n");
}
}
batchBody.push("\n");
if (reqInfo.options.body) {
batchBody.push(reqInfo.options.body + "\n\n");
}
}
if (currentChangeSetId.length > 0) {
// Close the changeset
batchBody.push("--changeset_" + currentChangeSetId + "--\n\n");
currentChangeSetId = "";
}
batchBody.push("--batch_" + _this._batchId + "--\n");
var batchHeaders = {
"Content-Type": "multipart/mixed; boundary=batch_" + _this._batchId,
};
var batchOptions = {
"body": batchBody.join(""),
"headers": batchHeaders,
};
logging_1.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Sending batch request.", logging_1.LogLevel.Info);
return client.post(util_1.Util.combinePaths(absoluteRequestUrl, "/_api/$batch"), batchOptions)
.then(function (r) { return r.text(); })
.then(_this._parseResponse)
.then(function (responses) {
if (responses.length !== _this._requests.length) {
throw new exceptions_1.BatchParseException("Could not properly parse responses to match requests in batch.");
}
logging_1.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Resolving batched requests.", logging_1.LogLevel.Info);
return responses.reduce(function (chain, response, index) {
var request = _this._requests[index];
logging_1.Logger.write("[" + _this.batchId + "] (" + (new Date()).getTime() + ") Resolving batched request " + request.method + " " + request.url + ".", logging_1.LogLevel.Verbose);
return chain.then(function (_) { return request.parser.parse(response).then(request.resolve).catch(request.reject); });
}, Promise.resolve());
});
});
};
/**
* Parses the response from a batch request into an array of Response instances
*
* @param body Text body of the response from the batch request
*/
ODataBatch.prototype._parseResponse = function (body) {
return new Promise(function (resolve, reject) {
var responses = [];
var header = "--batchresponse_";
// Ex. "HTTP/1.1 500 Internal Server Error"
var statusRegExp = new RegExp("^HTTP/[0-9.]+ +([0-9]+) +(.*)", "i");
var lines = body.split("\n");
var state = "batch";
var status;
var statusText;
for (var i = 0; i < lines.length; ++i) {
var line = lines[i];
switch (state) {
case "batch":
if (line.substr(0, header.length) === header) {
state = "batchHeaders";
}
else {
if (line.trim() !== "") {
throw new exceptions_1.BatchParseException("Invalid response, line " + i);
}
}
break;
case "batchHeaders":
if (line.trim() === "") {
state = "status";
}
break;
case "status":
var parts = statusRegExp.exec(line);
if (parts.length !== 3) {
throw new exceptions_1.BatchParseException("Invalid status, line " + i);
}
status = parseInt(parts[1], 10);
statusText = parts[2];
state = "statusHeaders";
break;
case "statusHeaders":
if (line.trim() === "") {
state = "body";
}
break;
case "body":
responses.push((status === 204) ? new Response() : new Response(line, { status: status, statusText: statusText }));
state = "batch";
break;
}
}
if (state !== "status") {
reject(new exceptions_1.BatchParseException("Unexpected end of input"));
}
resolve(responses);
});
};
return ODataBatch;
}());
exports.ODataBatch = ODataBatch;
var TextFileParser = (function () {
function TextFileParser() {
}
TextFileParser.prototype.parse = function (r) {
return r.text();
};
return TextFileParser;
}());
exports.TextFileParser = TextFileParser;
var BlobFileParser = (function () {
function BlobFileParser() {
}
BlobFileParser.prototype.parse = function (r) {
return r.blob();
};
return BlobFileParser;
}());
exports.BlobFileParser = BlobFileParser;
var JSONFileParser = (function () {
function JSONFileParser() {
}
JSONFileParser.prototype.parse = function (r) {
return r.json();
};
return JSONFileParser;
}());
exports.JSONFileParser = JSONFileParser;
var BufferFileParser = (function () {
function BufferFileParser() {
}
BufferFileParser.prototype.parse = function (r) {
if (util_1.Util.isFunction(r.arrayBuffer)) {
return r.arrayBuffer();
}
return r.buffer();
};
return BufferFileParser;
}());
exports.BufferFileParser = BufferFileParser;
/***/ }),
/* 3 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 logging_1 = __webpack_require__(5);
function defaultLog(error) {
logging_1.Logger.log({ data: {}, level: logging_1.LogLevel.Error, message: "[" + error.name + "]::" + error.message });
}
/**
* Represents an exception with an HttpClient request
*
*/
var ProcessHttpClientResponseException = (function (_super) {
__extends(ProcessHttpClientResponseException, _super);
function ProcessHttpClientResponseException(status, statusText, data) {
var _this = _super.call(this, "Error making HttpClient request in queryable: [" + status + "] " + statusText) || this;
_this.status = status;
_this.statusText = statusText;
_this.data = data;
_this.name = "ProcessHttpClientResponseException";
logging_1.Logger.log({ data: _this.data, level: logging_1.LogLevel.Error, message: _this.message });
return _this;
}
return ProcessHttpClientResponseException;
}(Error));
exports.ProcessHttpClientResponseException = ProcessHttpClientResponseException;
var NoCacheAvailableException = (function (_super) {
__extends(NoCacheAvailableException, _super);
function NoCacheAvailableException(msg) {
if (msg === void 0) { msg = "Cannot create a caching configuration provider since cache is not available."; }
var _this = _super.call(this, msg) || this;
_this.name = "NoCacheAvailableException";
defaultLog(_this);
return _this;
}
return NoCacheAvailableException;
}(Error));
exports.NoCacheAvailableException = NoCacheAvailableException;
var APIUrlException = (function (_super) {
__extends(APIUrlException, _super);
function APIUrlException(msg) {
if (msg === void 0) { msg = "Unable to determine API url."; }
var _this = _super.call(this, msg) || this;
_this.name = "APIUrlException";
defaultLog(_this);
return _this;
}
return APIUrlException;
}(Error));
exports.APIUrlException = APIUrlException;
var AuthUrlException = (function (_super) {
__extends(AuthUrlException, _super);
function AuthUrlException(data, msg) {
if (msg === void 0) { msg = "Auth URL Endpoint could not be determined from data. Data logged."; }
var _this = _super.call(this, msg) || this;
_this.name = "APIUrlException";
logging_1.Logger.log({ data: data, level: logging_1.LogLevel.Error, message: _this.message });
return _this;
}
return AuthUrlException;
}(Error));
exports.AuthUrlException = AuthUrlException;
var NodeFetchClientUnsupportedException = (function (_super) {
__extends(NodeFetchClientUnsupportedException, _super);
function NodeFetchClientUnsupportedException(msg) {
if (msg === void 0) { msg = "Using NodeFetchClient in the browser is not supported."; }
var _this = _super.call(this, msg) || this;
_this.name = "NodeFetchClientUnsupportedException";
defaultLog(_this);
return _this;
}
return NodeFetchClientUnsupportedException;
}(Error));
exports.NodeFetchClientUnsupportedException = NodeFetchClientUnsupportedException;
var SPRequestExecutorUndefinedException = (function (_super) {
__extends(SPRequestExecutorUndefinedException, _super);
function SPRequestExecutorUndefinedException() {
var _this = this;
var msg = [
"SP.RequestExecutor is undefined. ",
"Load the SP.RequestExecutor.js library (/_layouts/15/SP.RequestExecutor.js) before loading the PnP JS Core library.",
].join(" ");
_this = _super.call(this, msg) || this;
_this.name = "SPRequestExecutorUndefinedException";
defaultLog(_this);
return _this;
}
return SPRequestExecutorUndefinedException;
}(Error));
exports.SPRequestExecutorUndefinedException = SPRequestExecutorUndefinedException;
var MaxCommentLengthException = (function (_super) {
__extends(MaxCommentLengthException, _super);
function MaxCommentLengthException(msg) {
if (msg === void 0) { msg = "The maximum comment length is 1023 characters."; }
var _this = _super.call(this, msg) || this;
_this.name = "MaxCommentLengthException";
defaultLog(_this);
return _this;
}
return MaxCommentLengthException;
}(Error));
exports.MaxCommentLengthException = MaxCommentLengthException;
var NotSupportedInBatchException = (function (_super) {
__extends(NotSupportedInBatchException, _super);
function NotSupportedInBatchException(operation) {
if (operation === void 0) { operation = "This operation"; }
var _this = _super.call(this, operation + " is not supported as part of a batch.") || this;
_this.name = "NotSupportedInBatchException";
defaultLog(_this);
return _this;
}
return NotSupportedInBatchException;
}(Error));
exports.NotSupportedInBatchException = NotSupportedInBatchException;
var ODataIdException = (function (_super) {
__extends(ODataIdException, _super);
function ODataIdException(data, msg) {
if (msg === void 0) { msg = "Could not extract odata id in object, you may be using nometadata. Object data logged to logger."; }
var _this = _super.call(this, msg) || this;
_this.name = "ODataIdException";
logging_1.Logger.log({ data: data, level: logging_1.LogLevel.Error, message: _this.message });
return _this;
}
return ODataIdException;
}(Error));
exports.ODataIdException = ODataIdException;
var BatchParseException = (function (_super) {
__extends(BatchParseException, _super);
function BatchParseException(msg) {
var _this = _super.call(this, msg) || this;
_this.name = "BatchParseException";
defaultLog(_this);
return _this;
}
return BatchParseException;
}(Error));
exports.BatchParseException = BatchParseException;
var AlreadyInBatchException = (function (_super) {
__extends(AlreadyInBatchException, _super);
function AlreadyInBatchException(msg) {
if (msg === void 0) { msg = "This query is already part of a batch."; }
var _this = _super.call(this, msg) || this;
_this.name = "AlreadyInBatchException";
defaultLog(_this);
return _this;
}
return AlreadyInBatchException;
}(Error));
exports.AlreadyInBatchException = AlreadyInBatchException;
var FunctionExpectedException = (function (_super) {
__extends(FunctionExpectedException, _super);
function FunctionExpectedException(msg) {
if (msg === void 0) { msg = "This query is already part of a batch."; }
var _this = _super.call(this, msg) || this;
_this.name = "FunctionExpectedException";
defaultLog(_this);
return _this;
}
return FunctionExpectedException;
}(Error));
exports.FunctionExpectedException = FunctionExpectedException;
var UrlException = (function (_super) {
__extends(UrlException, _super);
function UrlException(msg) {
var _this = _super.call(this, msg) || this;
_this.name = "UrlException";
defaultLog(_this);
return _this;
}
return UrlException;
}(Error));
exports.UrlException = UrlException;
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var fetchclient_1 = __webpack_require__(21);
var RuntimeConfigImpl = (function () {
function RuntimeConfigImpl() {
// these are our default values for the library
this._headers = null;
this._defaultCachingStore = "session";
this._defaultCachingTimeoutSeconds = 60;
this._globalCacheDisable = false;
this._fetchClientFactory = function () { return new fetchclient_1.FetchClient(); };
this._baseUrl = null;
this._spfxContext = null;
}
RuntimeConfigImpl.prototype.set = function (config) {
if (config.hasOwnProperty("headers")) {
this._headers = config.headers;
}
if (config.hasOwnProperty("globalCacheDisable")) {
this._globalCacheDisable = config.globalCacheDisable;
}
if (config.hasOwnProperty("defaultCachingStore")) {
this._defaultCachingStore = config.defaultCachingStore;
}
if (config.hasOwnProperty("defaultCachingTimeoutSeconds")) {
this._defaultCachingTimeoutSeconds = config.defaultCachingTimeoutSeconds;
}
if (config.hasOwnProperty("fetchClientFactory")) {
this._fetchClientFactory = config.fetchClientFactory;
}
if (config.hasOwnProperty("baseUrl")) {
this._baseUrl = config.baseUrl;
}
if (config.hasOwnProperty("spfxContext")) {
this._spfxContext = config.spfxContext;
}
};
Object.defineProperty(RuntimeConfigImpl.prototype, "headers", {
get: function () {
return this._headers;
},
enumerable: true,
configurable: true
});
Object.defineProperty(RuntimeConfigImpl.prototype, "defaultCachingStore", {
get: function () {
return this._defaultCachingStore;
},
enumerable: true,
configurable: true
});
Object.defineProperty(RuntimeConfigImpl.prototype, "defaultCachingTimeoutSeconds", {
get: function () {
return this._defaultCachingTimeoutSeconds;
},
enumerable: true,
configurable: true
});
Object.defineProperty(RuntimeConfigImpl.prototype, "globalCacheDisable", {
get: function () {
return this._globalCacheDisable;
},
enumerable: true,
configurable: true
});
Object.defineProperty(RuntimeConfigImpl.prototype, "fetchClientFactory", {
get: function () {
return this._fetchClientFactory;
},
enumerable: true,
configurable: true
});
Object.defineProperty(RuntimeConfigImpl.prototype, "baseUrl", {
get: function () {
if (this._baseUrl !== null) {
return this._baseUrl;
}
else if (this._spfxContext !== null) {
return this._spfxContext.pageContext.web.absoluteUrl;
}
return null;
},
enumerable: true,
configurable: true
});
return RuntimeConfigImpl;
}());
exports.RuntimeConfigImpl = RuntimeConfigImpl;
var _runtimeConfig = new RuntimeConfigImpl();
exports.RuntimeConfig = _runtimeConfig;
function setRuntimeConfig(config) {
_runtimeConfig.set(config);
}
exports.setRuntimeConfig = setRuntimeConfig;
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* A set of logging levels
*
*/
var LogLevel;
(function (LogLevel) {
LogLevel[LogLevel["Verbose"] = 0] = "Verbose";
LogLevel[LogLevel["Info"] = 1] = "Info";
LogLevel[LogLevel["Warning"] = 2] = "Warning";
LogLevel[LogLevel["Error"] = 3] = "Error";
LogLevel[LogLevel["Off"] = 99] = "Off";
})(LogLevel = exports.LogLevel || (exports.LogLevel = {}));
/**
* Class used to subscribe ILogListener and log messages throughout an application
*
*/
var Logger = (function () {
function Logger() {
}
Object.defineProperty(Logger, "activeLogLevel", {
get: function () {
return Logger.instance.activeLogLevel;
},
set: function (value) {
Logger.instance.activeLogLevel = value;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Logger, "instance", {
get: function () {
if (typeof Logger._instance === "undefined" || Logger._instance === null) {
Logger._instance = new LoggerImpl();
}
return Logger._instance;
},
enumerable: true,
configurable: true
});
/**
* Adds ILogListener instances to the set of subscribed listeners
*
* @param listeners One or more listeners to subscribe to this log
*/
Logger.subscribe = function () {
var listeners = [];
for (var _i = 0; _i < arguments.length; _i++) {
listeners[_i] = arguments[_i];
}
listeners.map(function (listener) { return Logger.instance.subscribe(listener); });
};
/**
* Clears the subscribers collection, returning the collection before modifiction
*/
Logger.clearSubscribers = function () {
return Logger.instance.clearSubscribers();
};
Object.defineProperty(Logger, "count", {
/**
* Gets the current subscriber count
*/
get: function () {
return Logger.instance.count;
},
enumerable: true,
configurable: true
});
/**
* Writes the supplied string to the subscribed listeners
*
* @param message The message to write
* @param level [Optional] if supplied will be used as the level of the entry (Default: LogLevel.Verbose)
*/
Logger.write = function (message, level) {
if (level === void 0) { level = LogLevel.Verbose; }
Logger.instance.log({ level: level, message: message });
};
/**
* Writes the supplied string to the subscribed listeners
*
* @param json The json object to stringify and write
* @param level [Optional] if supplied will be used as the level of the entry (Default: LogLevel.Verbose)
*/
Logger.writeJSON = function (json, level) {
if (level === void 0) { level = LogLevel.Verbose; }
Logger.instance.log({ level: level, message: JSON.stringify(json) });
};
/**
* Logs the supplied entry to the subscribed listeners
*
* @param entry The message to log
*/
Logger.log = function (entry) {
Logger.instance.log(entry);
};
/**
* Logs performance tracking data for the the execution duration of the supplied function using console.profile
*
* @param name The name of this profile boundary
* @param f The function to execute and track within this performance boundary
*/
Logger.measure = function (name, f) {
return Logger.instance.measure(name, f);
};
return Logger;
}());
exports.Logger = Logger;
var LoggerImpl = (function () {
function LoggerImpl(activeLogLevel, subscribers) {
if (activeLogLevel === void 0) { activeLogLevel = LogLevel.Warning; }
if (subscribers === void 0) { subscribers = []; }
this.activeLogLevel = activeLogLevel;
this.subscribers = subscribers;
}
LoggerImpl.prototype.subscribe = function (listener) {
this.subscribers.push(listener);
};
LoggerImpl.prototype.clearSubscribers = function () {
var s = this.subscribers.slice(0);
this.subscribers.length = 0;
return s;
};
Object.defineProperty(LoggerImpl.prototype, "count", {
get: function () {
return this.subscribers.length;
},
enumerable: true,
configurable: true
});
LoggerImpl.prototype.write = function (message, level) {
if (level === void 0) { level = LogLevel.Verbose; }
this.log({ level: level, message: message });
};
LoggerImpl.prototype.log = function (entry) {
if (typeof entry === "undefined" || entry.level < this.activeLogLevel) {
return;
}
this.subscribers.map(function (subscriber) { return subscriber.log(entry); });
};
LoggerImpl.prototype.measure = function (name, f) {
console.profile(name);
try {
return f();
}
finally {
console.profileEnd();
}
};
return LoggerImpl;
}());
/**
* Implementation of ILogListener which logs to the browser console
*
*/
var ConsoleListener = (function () {
function ConsoleListener() {
}
/**
* Any associated data that a given logging listener may choose to log or ignore
*
* @param entry The information to be logged
*/
ConsoleListener.prototype.log = function (entry) {
var msg = this.format(entry);
switch (entry.level) {
case LogLevel.Verbose:
case LogLevel.Info:
console.log(msg);
break;
case LogLevel.Warning:
console.warn(msg);
break;
case LogLevel.Error:
console.error(msg);
break;
}
};
/**
* Formats the message
*
* @param entry The information to format into a string
*/
ConsoleListener.prototype.format = function (entry) {
return "Message: " + entry.message + " Data: " + JSON.stringify(entry.data);
};
return ConsoleListener;
}());
exports.ConsoleListener = ConsoleListener;
/**
* Implementation of ILogListener which logs to the supplied function
*
*/
var FunctionListener = (function () {
/**
* Creates a new instance of the FunctionListener class
*
* @constructor
* @param method The method to which any logging data will be passed
*/
function FunctionListener(method) {
this.method = method;
}
/**
* Any associated data that a given logging listener may choose to log or ignore
*
* @param entry The information to be logged
*/
FunctionListener.prototype.log = function (entry) {
this.method(entry);
};
return FunctionListener;
}());
exports.FunctionListener = FunctionListener;
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Generic dictionary
*/
var Dictionary = (function () {
/**
* Creates a new instance of the Dictionary<T> class
*
* @constructor
*/
function Dictionary(keys, values) {
if (keys === void 0) { keys = []; }
if (values === void 0) { values = []; }
this.keys = keys;
this.values = values;
}
/**
* Gets a value from the collection using the specified key
*
* @param key The key whose value we want to return, returns null if the key does not exist
*/
Dictionary.prototype.get = function (key) {
var index = this.keys.indexOf(key);
if (index < 0) {
return null;
}
return this.values[index];
};
/**
* Adds the supplied key and value to the dictionary
*
* @param key The key to add
* @param o The value to add
*/
Dictionary.prototype.add = function (key, o) {
var index = this.keys.indexOf(key);
if (index > -1) {
this.values[index] = o;
}
else {
this.keys.push(key);
this.values.push(o);
}
};
/**
* Merges the supplied typed hash into this dictionary instance. Existing values are updated and new ones are created as appropriate.
*/
Dictionary.prototype.merge = function (source) {
var _this = this;
if ("getKeys" in source) {
var sourceAsDictionary_1 = source;
sourceAsDictionary_1.getKeys().map(function (key) {
_this.add(key, sourceAsDictionary_1.get(key));
});
}
else {
var sourceAsHash = source;
for (var key in sourceAsHash) {
if (sourceAsHash.hasOwnProperty(key)) {
this.add(key, sourceAsHash[key]);
}
}
}
};
/**
* Removes a value from the dictionary
*
* @param key The key of the key/value pair to remove. Returns null if the key was not found.
*/
Dictionary.prototype.remove = function (key) {
var index = this.keys.indexOf(key);
if (index < 0) {
return null;
}
var val = this.values[index];
this.keys.splice(index, 1);
this.values.splice(index, 1);
return val;
};
/**
* Returns all the keys currently in the dictionary as an array
*/
Dictionary.prototype.getKeys = function () {
return this.keys;
};
/**
* Returns all the values currently in the dictionary as an array
*/
Dictionary.prototype.getValues = function () {
return this.values;
};
/**
* Clears the current dictionary
*/
Dictionary.prototype.clear = function () {
this.keys = [];
this.values = [];
};
/**
* Gets a count of the items currently in the dictionary
*/
Dictionary.prototype.count = function () {
return this.keys.length;
};
return Dictionary;
}());
exports.Dictionary = Dictionary;
/***/ }),
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 queryable_1 = __webpack_require__(1);
var odata_1 = __webpack_require__(2);
var util_1 = __webpack_require__(0);
var exceptions_1 = __webpack_require__(3);
var webparts_1 = __webpack_require__(50);
var items_1 = __webpack_require__(10);
var queryableshareable_1 = __webpack_require__(12);
var odata_2 = __webpack_require__(2);
/**
* Describes a collection of File objects
*
*/
var Files = (function (_super) {
__extends(Files, _super);
/**
* Creates a new instance of the Files class
*
* @param baseUrl The url or Queryable which forms the parent of this fields collection
*/
function Files(baseUrl, path) {
if (path === void 0) { path = "files"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a File by filename
*
* @param name The name of the file, including extension.
*/
Files.prototype.getByName = function (name) {
var f = new File(this);
f.concat("('" + name + "')");
return f;
};
/**
* Uploads a file. Not supported for batching
*
* @param url The folder-relative url of the file.
* @param content The file contents blob.
* @param shouldOverWrite Should a file with the same name in the same location be overwritten? (default: true)
* @returns The new File and the raw response.
*/
Files.prototype.add = function (url, content, shouldOverWrite) {
var _this = this;
if (shouldOverWrite === void 0) { shouldOverWrite = true; }
return new Files(this, "add(overwrite=" + shouldOverWrite + ",url='" + url + "')")
.post({
body: content,
}).then(function (response) {
return {
data: response,
file: _this.getByName(url),
};
});
};
/**
* Uploads a file. Not supported for batching
*
* @param url The folder-relative url of the file.
* @param content The Blob file content to add
* @param progress A callback function which can be used to track the progress of the upload
* @param shouldOverWrite Should a file with the same name in the same location be overwritten? (default: true)
* @param chunkSize The size of each file slice, in bytes (default: 10485760)
* @returns The new File and the raw response.
*/
Files.prototype.addChunked = function (url, content, progress, shouldOverWrite, chunkSize) {
var _this = this;
if (shouldOverWrite === void 0) { shouldOverWrite = true; }
if (chunkSize === void 0) { chunkSize = 10485760; }
var adder = this.clone(Files, "add(overwrite=" + shouldOverWrite + ",url='" + url + "')");
return adder.post().then(function () { return _this.getByName(url); }).then(function (file) { return file.setContentChunked(content, progress, chunkSize); }).then(function (response) {
return {
data: response,
file: _this.getByName(url),
};
});
};
/**
* Adds a ghosted file to an existing list or document library. Not supported for batching.
*
* @param fileUrl The server-relative url where you want to save the file.
* @param templateFileType The type of use to create the file.
* @returns The template file that was added and the raw response.
*/
Files.prototype.addTemplateFile = function (fileUrl, templateFileType) {
var _this = this;
return this.clone(Files, "addTemplateFile(urloffile='" + fileUrl + "',templatefiletype=" + templateFileType + ")")
.post().then(function (response) {
return {
data: response,
file: _this.getByName(fileUrl),
};
});
};
return Files;
}(queryable_1.QueryableCollection));
exports.Files = Files;
/**
* Describes a single File instance
*
*/
var File = (function (_super) {
__extends(File, _super);
function File() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(File.prototype, "listItemAllFields", {
/**
* Gets a value that specifies the list item field values for the list item corresponding to the file.
*
*/
get: function () {
return new queryable_1.QueryableCollection(this, "listItemAllFields");
},
enumerable: true,
configurable: true
});
Object.defineProperty(File.prototype, "versions", {
/**
* Gets a collection of versions
*
*/
get: function () {
return new Versions(this);
},
enumerable: true,
configurable: true
});
/**
* Approves the file submitted for content approval with the specified comment.
* Only documents in lists that are enabled for content approval can be approved.
*
* @param comment The comment for the approval.
*/
File.prototype.approve = function (comment) {
if (comment === void 0) { comment = ""; }
return this.clone(File, "approve(comment='" + comment + "')", true).post();
};
/**
* Stops the chunk upload session without saving the uploaded data. Does not support batching.
* If the file doesn’t already exist in the library, the partially uploaded file will be deleted.
* Use this in response to user action (as in a request to cancel an upload) or an error or exception.
* Use the uploadId value that was passed to the StartUpload method that started the upload session.
* This method is currently available only on Office 365.
*
* @param uploadId The unique identifier of the upload session.
*/
File.prototype.cancelUpload = function (uploadId) {
return this.clone(File, "cancelUpload(uploadId=guid'" + uploadId + "')", false).post();
};
/**
* Checks the file in to a document library based on the check-in type.
*
* @param comment A comment for the check-in. Its length must be <= 1023.
* @param checkinType The check-in type for the file.
*/
File.prototype.checkin = function (comment, checkinType) {
if (comment === void 0) { comment = ""; }
if (checkinType === void 0) { checkinType = CheckinType.Major; }
if (comment.length > 1023) {
throw new exceptions_1.MaxCommentLengthException();
}
return this.clone(File, "checkin(comment='" + comment + "',checkintype=" + checkinType + ")", true).post();
};
/**
* Checks out the file from a document library.
*/
File.prototype.checkout = function () {
return this.clone(File, "checkout", true).post();
};
/**
* Copies the file to the destination url.
*
* @param url The absolute url or server relative url of the destination file path to copy to.
* @param shouldOverWrite Should a file with the same name in the same location be overwritten?
*/
File.prototype.copyTo = function (url, shouldOverWrite) {
if (shouldOverWrite === void 0) { shouldOverWrite = true; }
return this.clone(File, "copyTo(strnewurl='" + url + "',boverwrite=" + shouldOverWrite + ")", true).post();
};
/**
* Delete this file.
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
File.prototype.delete = function (eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.clone(File, null, true).post({
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "DELETE",
},
});
};
/**
* Denies approval for a file that was submitted for content approval.
* Only documents in lists that are enabled for content approval can be denied.
*
* @param comment The comment for the denial.
*/
File.prototype.deny = function (comment) {
if (comment === void 0) { comment = ""; }
if (comment.length > 1023) {
throw new exceptions_1.MaxCommentLengthException();
}
return this.clone(File, "deny(comment='" + comment + "')", true).post();
};
/**
* Specifies the control set used to access, modify, or add Web Parts associated with this Web Part Page and view.
* An exception is thrown if the file is not an ASPX page.
*
* @param scope The WebPartsPersonalizationScope view on the Web Parts page.
*/
File.prototype.getLimitedWebPartManager = function (scope) {
if (scope === void 0) { scope = WebPartsPersonalizationScope.Shared; }
return new webparts_1.LimitedWebPartManager(this, "getLimitedWebPartManager(scope=" + scope + ")");
};
/**
* Moves the file to the specified destination url.
*
* @param url The absolute url or server relative url of the destination file path to move to.
* @param moveOperations The bitwise MoveOperations value for how to move the file.
*/
File.prototype.moveTo = function (url, moveOperations) {
if (moveOperations === void 0) { moveOperations = MoveOperations.Overwrite; }
return this.clone(File, "moveTo(newurl='" + url + "',flags=" + moveOperations + ")", true).post();
};
/**
* Submits the file for content approval with the specified comment.
*
* @param comment The comment for the published file. Its length must be <= 1023.
*/
File.prototype.publish = function (comment) {
if (comment === void 0) { comment = ""; }
if (comment.length > 1023) {
throw new exceptions_1.MaxCommentLengthException();
}
return this.clone(File, "publish(comment='" + comment + "')", true).post();
};
/**
* Moves the file to the Recycle Bin and returns the identifier of the new Recycle Bin item.
*
* @returns The GUID of the recycled file.
*/
File.prototype.recycle = function () {
return this.clone(File, "recycle", true).post();
};
/**
* Reverts an existing checkout for the file.
*
*/
File.prototype.undoCheckout = function () {
return this.clone(File, "undoCheckout", true).post();
};
/**
* Removes the file from content approval or unpublish a major version.
*
* @param comment The comment for the unpublish operation. Its length must be <= 1023.
*/
File.prototype.unpublish = function (comment) {
if (comment === void 0) { comment = ""; }
if (comment.length > 1023) {
throw new exceptions_1.MaxCommentLengthException();
}
return this.clone(File, "unpublish(comment='" + comment + "')", true).post();
};
/**
* Gets the contents of the file as text. Not supported in batching.
*
*/
File.prototype.getText = function () {
return this.clone(File, "$value").get(new odata_1.TextFileParser(), { headers: { "binaryStringResponseBody": "true" } });
};
/**
* Gets the contents of the file as a blob, does not work in Node.js. Not supported in batching.
*
*/
File.prototype.getBlob = function () {
return this.clone(File, "$value").get(new odata_1.BlobFileParser(), { headers: { "binaryStringResponseBody": "true" } });
};
/**
* Gets the contents of a file as an ArrayBuffer, works in Node.js. Not supported in batching.
*/
File.prototype.getBuffer = function () {
return this.clone(File, "$value").get(new odata_1.BufferFileParser(), { headers: { "binaryStringResponseBody": "true" } });
};
/**
* Gets the contents of a file as an ArrayBuffer, works in Node.js. Not supported in batching.
*/
File.prototype.getJSON = function () {
return this.clone(File, "$value").get(new odata_1.JSONFileParser(), { headers: { "binaryStringResponseBody": "true" } });
};
/**
* Sets the content of a file, for large files use setContentChunked. Not supported in batching.
*
* @param content The file content
*
*/
File.prototype.setContent = function (content) {
var _this = this;
return this.clone(File, "$value").post({
body: content,
headers: {
"X-HTTP-Method": "PUT",
},
}).then(function (_) { return new File(_this); });
};
/**
* Gets the associated list item for this folder, loading the default properties
*/
File.prototype.getItem = function () {
var selects = [];
for (var _i = 0; _i < arguments.length; _i++) {
selects[_i] = arguments[_i];
}
var q = this.listItemAllFields;
return q.select.apply(q, selects).get().then(function (d) {
return util_1.Util.extend(new items_1.Item(odata_2.getEntityUrl(d)), d);
});
};
/**
* Sets the contents of a file using a chunked upload approach. Not supported in batching.
*
* @param file The file to upload
* @param progress A callback function which can be used to track the progress of the upload
* @param chunkSize The size of each file slice, in bytes (default: 10485760)
*/
File.prototype.setContentChunked = function (file, progress, chunkSize) {
if (chunkSize === void 0) { chunkSize = 10485760; }
if (typeof progress === "undefined") {
progress = function () { return null; };
}
var self = this;
var fileSize = file.size;
var blockCount = parseInt((file.size / chunkSize).toString(), 10) + ((file.size % chunkSize === 0) ? 1 : 0);
var uploadId = util_1.Util.getGUID();
// start the chain with the first fragment
progress({ blockNumber: 1, chunkSize: chunkSize, currentPointer: 0, fileSize: fileSize, stage: "starting", totalBlocks: blockCount });
var chain = self.startUpload(uploadId, file.slice(0, chunkSize));
var _loop_1 = function (i) {
chain = chain.then(function (pointer) {
progress({ blockNumber: i, chunkSize: chunkSize, currentPointer: pointer, fileSize: fileSize, stage: "continue", totalBlocks: blockCount });
return self.continueUpload(uploadId, pointer, file.slice(pointer, pointer + chunkSize));
});
};
// skip the first and last blocks
for (var i = 2; i < blockCount; i++) {
_loop_1(i);
}
return chain.then(function (pointer) {
progress({ blockNumber: blockCount, chunkSize: chunkSize, currentPointer: pointer, fileSize: fileSize, stage: "finishing", totalBlocks: blockCount });
return self.finishUpload(uploadId, pointer, file.slice(pointer));
}).then(function (_) {
return self;
});
};
/**
* Starts a new chunk upload session and uploads the first fragment.
* The current file content is not changed when this method completes.
* The method is idempotent (and therefore does not change the result) as long as you use the same values for uploadId and stream.
* The upload session ends either when you use the CancelUpload method or when you successfully
* complete the upload session by passing the rest of the file contents through the ContinueUpload and FinishUpload methods.
* The StartUpload and ContinueUpload methods return the size of the running total of uploaded data in bytes,
* so you can pass those return values to subsequent uses of ContinueUpload and FinishUpload.
* This method is currently available only on Office 365.
*
* @param uploadId The unique identifier of the upload session.
* @param fragment The file contents.
* @returns The size of the total uploaded data in bytes.
*/
File.prototype.startUpload = function (uploadId, fragment) {
return this.clone(File, "startUpload(uploadId=guid'" + uploadId + "')").postAs({ body: fragment }).then(function (n) { return parseFloat(n); });
};
/**
* Continues the chunk upload session with an additional fragment.
* The current file content is not changed.
* Use the uploadId value that was passed to the StartUpload method that started the upload session.
* This method is currently available only on Office 365.
*
* @param uploadId The unique identifier of the upload session.
* @param fileOffset The size of the offset into the file where the fragment starts.
* @param fragment The file contents.
* @returns The size of the total uploaded data in bytes.
*/
File.prototype.continueUpload = function (uploadId, fileOffset, fragment) {
return this.clone(File, "continueUpload(uploadId=guid'" + uploadId + "',fileOffset=" + fileOffset + ")").postAs({ body: fragment }).then(function (n) { return parseFloat(n); });
};
/**
* Uploads the last file fragment and commits the file. The current file content is changed when this method completes.
* Use the uploadId value that was passed to the StartUpload method that started the upload session.
* This method is currently available only on Office 365.
*
* @param uploadId The unique identifier of the upload session.
* @param fileOffset The size of the offset into the file where the fragment starts.
* @param fragment The file contents.
* @returns The newly uploaded file.
*/
File.prototype.finishUpload = function (uploadId, fileOffset, fragment) {
return this.clone(File, "finishUpload(uploadId=guid'" + uploadId + "',fileOffset=" + fileOffset + ")")
.postAs({ body: fragment }).then(function (response) {
return {
data: response,
file: new File(response.ServerRelativeUrl),
};
});
};
return File;
}(queryableshareable_1.QueryableShareableFile));
exports.File = File;
/**
* Describes a collection of Version objects
*
*/
var Versions = (function (_super) {
__extends(Versions, _super);
/**
* Creates a new instance of the File class
*
* @param baseUrl The url or Queryable which forms the parent of this fields collection
*/
function Versions(baseUrl, path) {
if (path === void 0) { path = "versions"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a version by id
*
* @param versionId The id of the version to retrieve
*/
Versions.prototype.getById = function (versionId) {
var v = new Version(this);
v.concat("(" + versionId + ")");
return v;
};
/**
* Deletes all the file version objects in the collection.
*
*/
Versions.prototype.deleteAll = function () {
return new Versions(this, "deleteAll").post();
};
/**
* Deletes the specified version of the file.
*
* @param versionId The ID of the file version to delete.
*/
Versions.prototype.deleteById = function (versionId) {
return this.clone(Versions, "deleteById(vid=" + versionId + ")", true).post();
};
/**
* Deletes the file version object with the specified version label.
*
* @param label The version label of the file version to delete, for example: 1.2
*/
Versions.prototype.deleteByLabel = function (label) {
return this.clone(Versions, "deleteByLabel(versionlabel='" + label + "')", true).post();
};
/**
* Creates a new file version from the file specified by the version label.
*
* @param label The version label of the file version to restore, for example: 1.2
*/
Versions.prototype.restoreByLabel = function (label) {
return this.clone(Versions, "restoreByLabel(versionlabel='" + label + "')", true).post();
};
return Versions;
}(queryable_1.QueryableCollection));
exports.Versions = Versions;
/**
* Describes a single Version instance
*
*/
var Version = (function (_super) {
__extends(Version, _super);
function Version() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Delete a specific version of a file.
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
Version.prototype.delete = function (eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.post({
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "DELETE",
},
});
};
return Version;
}(queryable_1.QueryableInstance));
exports.Version = Version;
var CheckinType;
(function (CheckinType) {
CheckinType[CheckinType["Minor"] = 0] = "Minor";
CheckinType[CheckinType["Major"] = 1] = "Major";
CheckinType[CheckinType["Overwrite"] = 2] = "Overwrite";
})(CheckinType = exports.CheckinType || (exports.CheckinType = {}));
var WebPartsPersonalizationScope;
(function (WebPartsPersonalizationScope) {
WebPartsPersonalizationScope[WebPartsPersonalizationScope["User"] = 0] = "User";
WebPartsPersonalizationScope[WebPartsPersonalizationScope["Shared"] = 1] = "Shared";
})(WebPartsPersonalizationScope = exports.WebPartsPersonalizationScope || (exports.WebPartsPersonalizationScope = {}));
var MoveOperations;
(function (MoveOperations) {
MoveOperations[MoveOperations["Overwrite"] = 1] = "Overwrite";
MoveOperations[MoveOperations["AllowBrokenThickets"] = 8] = "AllowBrokenThickets";
})(MoveOperations = exports.MoveOperations || (exports.MoveOperations = {}));
var TemplateFileType;
(function (TemplateFileType) {
TemplateFileType[TemplateFileType["StandardPage"] = 0] = "StandardPage";
TemplateFileType[TemplateFileType["WikiPage"] = 1] = "WikiPage";
TemplateFileType[TemplateFileType["FormPage"] = 2] = "FormPage";
})(TemplateFileType = exports.TemplateFileType || (exports.TemplateFileType = {}));
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 __());
};
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var queryable_1 = __webpack_require__(1);
var lists_1 = __webpack_require__(11);
var fields_1 = __webpack_require__(24);
var navigation_1 = __webpack_require__(25);
var sitegroups_1 = __webpack_require__(18);
var contenttypes_1 = __webpack_require__(16);
var folders_1 = __webpack_require__(9);
var roles_1 = __webpack_require__(17);
var files_1 = __webpack_require__(7);
var util_1 = __webpack_require__(0);
var lists_2 = __webpack_require__(11);
var siteusers_1 = __webpack_require__(30);
var usercustomactions_1 = __webpack_require__(19);
var odata_1 = __webpack_require__(2);
var features_1 = __webpack_require__(23);
var decorators_1 = __webpack_require__(51);
var queryableshareable_1 = __webpack_require__(12);
var relateditems_1 = __webpack_require__(46);
var Webs = (function (_super) {
__extends(Webs, _super);
function Webs(baseUrl, webPath) {
if (webPath === void 0) { webPath = "webs"; }
return _super.call(this, baseUrl, webPath) || this;
}
/**
* Adds a new web to the collection
*
* @param title The new web's title
* @param url The new web's relative url
* @param description The web web's description
* @param template The web's template
* @param language The language code to use for this web
* @param inheritPermissions If true permissions will be inherited from the partent web
* @param additionalSettings Will be passed as part of the web creation body
*/
Webs.prototype.add = function (title, url, description, template, language, inheritPermissions, additionalSettings) {
if (description === void 0) { description = ""; }
if (template === void 0) { template = "STS"; }
if (language === void 0) { language = 1033; }
if (inheritPermissions === void 0) { inheritPermissions = true; }
if (additionalSettings === void 0) { additionalSettings = {}; }
var props = util_1.Util.extend({
Description: description,
Language: language,
Title: title,
Url: url,
UseSamePermissionsAsParentSite: inheritPermissions,
WebTemplate: template,
}, additionalSettings);
var postBody = JSON.stringify({
"parameters": util_1.Util.extend({
"__metadata": { "type": "SP.WebCreationInformation" },
}, props),
});
return this.clone(Webs, "add", true).post({ body: postBody }).then(function (data) {
return {
data: data,
web: new Web(odata_1.extractOdataId(data).replace(/_api\/web\/?/i, "")),
};
});
};
return Webs;
}(queryable_1.QueryableCollection));
exports.Webs = Webs;
var WebInfos = (function (_super) {
__extends(WebInfos, _super);
function WebInfos(baseUrl, webPath) {
if (webPath === void 0) { webPath = "webinfos"; }
return _super.call(this, baseUrl, webPath) || this;
}
return WebInfos;
}(queryable_1.QueryableCollection));
exports.WebInfos = WebInfos;
/**
* Describes a web
*
*/
var Web = (function (_super) {
__extends(Web, _super);
function Web(baseUrl, path) {
if (path === void 0) { path = "_api/web"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Creates a new web instance from the given url by indexing the location of the /_api/
* segment. If this is not found the method creates a new web with the entire string as
* supplied.
*
* @param url
*/
Web.fromUrl = function (url, path) {
if (url === null) {
return new Web("");
}
var index = url.indexOf("_api/");
if (index > -1) {
return new Web(url.substr(0, index), path);
}
return new Web(url, path);
};
Object.defineProperty(Web.prototype, "webs", {
get: function () {
return new Webs(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "webinfos", {
get: function () {
return new WebInfos(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "contentTypes", {
/**
* Get the content types available in this web
*
*/
get: function () {
return new contenttypes_1.ContentTypes(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "lists", {
/**
* Get the lists in this web
*
*/
get: function () {
return new lists_1.Lists(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "fields", {
/**
* Gets the fields in this web
*
*/
get: function () {
return new fields_1.Fields(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "features", {
/**
* Gets the active features for this web
*
*/
get: function () {
return new features_1.Features(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "availablefields", {
/**
* Gets the available fields in this web
*
*/
get: function () {
return new fields_1.Fields(this, "availablefields");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "navigation", {
/**
* Get the navigation options in this web
*
*/
get: function () {
return new navigation_1.Navigation(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "siteUsers", {
/**
* Gets the site users
*
*/
get: function () {
return new siteusers_1.SiteUsers(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "siteGroups", {
/**
* Gets the site groups
*
*/
get: function () {
return new sitegroups_1.SiteGroups(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "currentUser", {
/**
* Gets the current user
*/
get: function () {
return new siteusers_1.CurrentUser(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "folders", {
/**
* Get the folders in this web
*
*/
get: function () {
return new folders_1.Folders(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "userCustomActions", {
/**
* Get all custom actions on a site
*
*/
get: function () {
return new usercustomactions_1.UserCustomActions(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "roleDefinitions", {
/**
* Gets the collection of RoleDefinition resources.
*
*/
get: function () {
return new roles_1.RoleDefinitions(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "relatedItems", {
/**
* Provides an interface to manage related items
*
*/
get: function () {
return relateditems_1.RelatedItemManagerImpl.FromUrl(this.toUrl());
},
enumerable: true,
configurable: true
});
/**
* Creates a new batch for requests within the context of context this web
*
*/
Web.prototype.createBatch = function () {
return new odata_1.ODataBatch(this.parentUrl);
};
Object.defineProperty(Web.prototype, "rootFolder", {
/**
* The root folder of the web
*/
get: function () {
return new folders_1.Folder(this, "rootFolder");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "associatedOwnerGroup", {
get: function () {
return new sitegroups_1.SiteGroup(this, "associatedownergroup");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "associatedMemberGroup", {
get: function () {
return new sitegroups_1.SiteGroup(this, "associatedmembergroup");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Web.prototype, "associatedVisitorGroup", {
get: function () {
return new sitegroups_1.SiteGroup(this, "associatedvisitorgroup");
},
enumerable: true,
configurable: true
});
/**
* Get a folder by server relative url
*
* @param folderRelativeUrl the server relative path to the folder (including /sites/ if applicable)
*/
Web.prototype.getFolderByServerRelativeUrl = function (folderRelativeUrl) {
return new folders_1.Folder(this, "getFolderByServerRelativeUrl('" + folderRelativeUrl + "')");
};
/**
* Get a file by server relative url
*
* @param fileRelativeUrl the server relative path to the file (including /sites/ if applicable)
*/
Web.prototype.getFileByServerRelativeUrl = function (fileRelativeUrl) {
return new files_1.File(this, "getFileByServerRelativeUrl('" + fileRelativeUrl + "')");
};
/**
* Get a list by server relative url (list's root folder)
*
* @param listRelativeUrl the server relative path to the list's root folder (including /sites/ if applicable)
*/
Web.prototype.getList = function (listRelativeUrl) {
return new lists_2.List(this, "getList('" + listRelativeUrl + "')");
};
/**
* Updates this web intance with the supplied properties
*
* @param properties A plain object hash of values to update for the web
*/
Web.prototype.update = function (properties) {
var _this = this;
var postBody = JSON.stringify(util_1.Util.extend({
"__metadata": { "type": "SP.Web" },
}, properties));
return this.post({
body: postBody,
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
return {
data: data,
web: _this,
};
});
};
/**
* Delete this web
*
*/
Web.prototype.delete = function () {
return _super.prototype.delete.call(this);
};
/**
* Applies the theme specified by the contents of each of the files specified in the arguments to the site.
*
* @param colorPaletteUrl Server-relative URL of the color palette file.
* @param fontSchemeUrl Server-relative URL of the font scheme.
* @param backgroundImageUrl Server-relative URL of the background image.
* @param shareGenerated true to store the generated theme files in the root site, or false to store them in this site.
*/
Web.prototype.applyTheme = function (colorPaletteUrl, fontSchemeUrl, backgroundImageUrl, shareGenerated) {
var postBody = JSON.stringify({
backgroundImageUrl: backgroundImageUrl,
colorPaletteUrl: colorPaletteUrl,
fontSchemeUrl: fontSchemeUrl,
shareGenerated: shareGenerated,
});
return this.clone(Web, "applytheme", true).post({ body: postBody });
};
/**
* Applies the specified site definition or site template to the Web site that has no template applied to it.
*
* @param template Name of the site definition or the name of the site template
*/
Web.prototype.applyWebTemplate = function (template) {
var q = this.clone(Web, "applywebtemplate", true);
q.concat("(@t)");
q.query.add("@t", template);
return q.post();
};
/**
* Returns whether the current user has the given set of permissions.
*
* @param perms The high and low permission range.
*/
Web.prototype.doesUserHavePermissions = function (perms) {
var q = this.clone(Web, "doesuserhavepermissions", true);
q.concat("(@p)");
q.query.add("@p", JSON.stringify(perms));
return q.get();
};
/**
* Checks whether the specified login name belongs to a valid user in the site. If the user doesn't exist, adds the user to the site.
*
* @param loginName The login name of the user (ex: i:0#.f|membership|[email protected])
*/
Web.prototype.ensureUser = function (loginName) {
var postBody = JSON.stringify({
logonName: loginName,
});
return this.clone(Web, "ensureuser", true).post({ body: postBody }).then(function (data) {
return {
data: data,
user: new siteusers_1.SiteUser(odata_1.extractOdataId(data)),
};
});
};
/**
* Returns a collection of site templates available for the site.
*
* @param language The LCID of the site templates to get.
* @param true to include language-neutral site templates; otherwise false
*/
Web.prototype.availableWebTemplates = function (language, includeCrossLanugage) {
if (language === void 0) { language = 1033; }
if (includeCrossLanugage === void 0) { includeCrossLanugage = true; }
return new queryable_1.QueryableCollection(this, "getavailablewebtemplates(lcid=" + language + ", doincludecrosslanguage=" + includeCrossLanugage + ")");
};
/**
* Returns the list gallery on the site.
*
* @param type The gallery type - WebTemplateCatalog = 111, WebPartCatalog = 113 ListTemplateCatalog = 114,
* MasterPageCatalog = 116, SolutionCatalog = 121, ThemeCatalog = 123, DesignCatalog = 124, AppDataCatalog = 125
*/
Web.prototype.getCatalog = function (type) {
return this.clone(Web, "getcatalog(" + type + ")", true).select("Id").get().then(function (data) {
return new lists_2.List(odata_1.extractOdataId(data));
});
};
/**
* Returns the collection of changes from the change log that have occurred within the list, based on the specified query.
*/
Web.prototype.getChanges = function (query) {
var postBody = JSON.stringify({ "query": util_1.Util.extend({ "__metadata": { "type": "SP.ChangeQuery" } }, query) });
return this.clone(Web, "getchanges", true).post({ body: postBody });
};
Object.defineProperty(Web.prototype, "customListTemplate", {
/**
* Gets the custom list templates for the site.
*
*/
get: function () {
return new queryable_1.QueryableCollection(this, "getcustomlisttemplates");
},
enumerable: true,
configurable: true
});
/**
* Returns the user corresponding to the specified member identifier for the current site.
*
* @param id The ID of the user.
*/
Web.prototype.getUserById = function (id) {
return new siteusers_1.SiteUser(this, "getUserById(" + id + ")");
};
/**
* Returns the name of the image file for the icon that is used to represent the specified file.
*
* @param filename The file name. If this parameter is empty, the server returns an empty string.
* @param size The size of the icon: 16x16 pixels = 0, 32x32 pixels = 1.
* @param progId The ProgID of the application that was used to create the file, in the form OLEServerName.ObjectName
*/
Web.prototype.mapToIcon = function (filename, size, progId) {
if (size === void 0) { size = 0; }
if (progId === void 0) { progId = ""; }
return this.clone(Web, "maptoicon(filename='" + filename + "', progid='" + progId + "', size=" + size + ")", true).get();
};
return Web;
}(queryableshareable_1.QueryableShareableWeb));
__decorate([
decorators_1.deprecated("This method will be removed in future releases. Please use the methods found in queryable securable.")
], Web.prototype, "doesUserHavePermissions", null);
exports.Web = Web;
/***/ }),
/* 9 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 queryable_1 = __webpack_require__(1);
var queryableshareable_1 = __webpack_require__(12);
var files_1 = __webpack_require__(7);
var util_1 = __webpack_require__(0);
var odata_1 = __webpack_require__(2);
var items_1 = __webpack_require__(10);
/**
* Describes a collection of Folder objects
*
*/
var Folders = (function (_super) {
__extends(Folders, _super);
/**
* Creates a new instance of the Folders class
*
* @param baseUrl The url or Queryable which forms the parent of this fields collection
*/
function Folders(baseUrl, path) {
if (path === void 0) { path = "folders"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a folder by folder name
*
*/
Folders.prototype.getByName = function (name) {
var f = new Folder(this);
f.concat("('" + name + "')");
return f;
};
/**
* Adds a new folder to the current folder (relative) or any folder (absolute)
*
* @param url The relative or absolute url where the new folder will be created. Urls starting with a forward slash are absolute.
* @returns The new Folder and the raw response.
*/
Folders.prototype.add = function (url) {
var _this = this;
return this.clone(Folders, "add('" + url + "')", true).post().then(function (response) {
return {
data: response,
folder: _this.getByName(url),
};
});
};
return Folders;
}(queryable_1.QueryableCollection));
exports.Folders = Folders;
/**
* Describes a single Folder instance
*
*/
var Folder = (function (_super) {
__extends(Folder, _super);
function Folder() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(Folder.prototype, "contentTypeOrder", {
/**
* Specifies the sequence in which content types are displayed.
*
*/
get: function () {
return new queryable_1.QueryableCollection(this, "contentTypeOrder");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "files", {
/**
* Gets this folder's files
*
*/
get: function () {
return new files_1.Files(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "folders", {
/**
* Gets this folder's sub folders
*
*/
get: function () {
return new Folders(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "listItemAllFields", {
/**
* Gets this folder's list item field values
*
*/
get: function () {
return new queryable_1.QueryableCollection(this, "listItemAllFields");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "parentFolder", {
/**
* Gets the parent folder, if available
*
*/
get: function () {
return new Folder(this, "parentFolder");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "properties", {
/**
* Gets this folder's properties
*
*/
get: function () {
return new queryable_1.QueryableInstance(this, "properties");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "serverRelativeUrl", {
/**
* Gets this folder's server relative url
*
*/
get: function () {
return new queryable_1.Queryable(this, "serverRelativeUrl");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Folder.prototype, "uniqueContentTypeOrder", {
/**
* Gets a value that specifies the content type order.
*
*/
get: function () {
return new queryable_1.QueryableCollection(this, "uniqueContentTypeOrder");
},
enumerable: true,
configurable: true
});
Folder.prototype.update = function (properties) {
var _this = this;
var postBody = JSON.stringify(util_1.Util.extend({
"__metadata": { "type": "SP.Folder" },
}, properties));
return this.post({
body: postBody,
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
return {
data: data,
folder: _this,
};
});
};
/**
* Delete this folder
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
Folder.prototype.delete = function (eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.clone(Folder, null, true).post({
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "DELETE",
},
});
};
/**
* Moves the folder to the Recycle Bin and returns the identifier of the new Recycle Bin item.
*/
Folder.prototype.recycle = function () {
return this.clone(Folder, "recycle", true).post();
};
/**
* Gets the associated list item for this folder, loading the default properties
*/
Folder.prototype.getItem = function () {
var selects = [];
for (var _i = 0; _i < arguments.length; _i++) {
selects[_i] = arguments[_i];
}
var q = this.listItemAllFields;
return q.select.apply(q, selects).get().then(function (d) {
return util_1.Util.extend(new items_1.Item(odata_1.getEntityUrl(d)), d);
});
};
return Folder;
}(queryableshareable_1.QueryableShareableFolder));
exports.Folder = Folder;
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 queryable_1 = __webpack_require__(1);
var queryableshareable_1 = __webpack_require__(12);
var folders_1 = __webpack_require__(9);
var files_1 = __webpack_require__(7);
var contenttypes_1 = __webpack_require__(16);
var util_1 = __webpack_require__(0);
var odata_1 = __webpack_require__(2);
var attachmentfiles_1 = __webpack_require__(42);
var lists_1 = __webpack_require__(11);
/**
* Describes a collection of Item objects
*
*/
var Items = (function (_super) {
__extends(Items, _super);
/**
* Creates a new instance of the Items class
*
* @param baseUrl The url or Queryable which forms the parent of this fields collection
*/
function Items(baseUrl, path) {
if (path === void 0) { path = "items"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets an Item by id
*
* @param id The integer id of the item to retrieve
*/
Items.prototype.getById = function (id) {
var i = new Item(this);
i.concat("(" + id + ")");
return i;
};
/**
* Skips the specified number of items (https://msdn.microsoft.com/en-us/library/office/fp142385.aspx#sectionSection6)
*
* @param skip The starting id where the page should start, use with top to specify pages
*/
Items.prototype.skip = function (skip) {
this._query.add("$skiptoken", encodeURIComponent("Paged=TRUE&p_ID=" + skip));
return this;
};
/**
* Gets a collection designed to aid in paging through data
*
*/
Items.prototype.getPaged = function () {
return this.getAs(new PagedItemCollectionParser());
};
//
/**
* Adds a new item to the collection
*
* @param properties The new items's properties
*/
Items.prototype.add = function (properties, listItemEntityTypeFullName) {
var _this = this;
if (properties === void 0) { properties = {}; }
if (listItemEntityTypeFullName === void 0) { listItemEntityTypeFullName = null; }
var removeDependency = this.addBatchDependency();
return this.ensureListItemEntityTypeName(listItemEntityTypeFullName).then(function (listItemEntityType) {
var postBody = JSON.stringify(util_1.Util.extend({
"__metadata": { "type": listItemEntityType },
}, properties));
var promise = _this.clone(Items, null, true).postAs({ body: postBody }).then(function (data) {
return {
data: data,
item: _this.getById(data.Id),
};
});
removeDependency();
return promise;
});
};
/**
* Ensures we have the proper list item entity type name, either from the value provided or from the list
*
* @param candidatelistItemEntityTypeFullName The potential type name
*/
Items.prototype.ensureListItemEntityTypeName = function (candidatelistItemEntityTypeFullName) {
return candidatelistItemEntityTypeFullName ?
Promise.resolve(candidatelistItemEntityTypeFullName) :
this.getParent(lists_1.List).getListItemEntityTypeFullName();
};
return Items;
}(queryable_1.QueryableCollection));
exports.Items = Items;
/**
* Descrines a single Item instance
*
*/
var Item = (function (_super) {
__extends(Item, _super);
function Item() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(Item.prototype, "attachmentFiles", {
/**
* Gets the set of attachments for this item
*
*/
get: function () {
return new attachmentfiles_1.AttachmentFiles(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "contentType", {
/**
* Gets the content type for this item
*
*/
get: function () {
return new contenttypes_1.ContentType(this, "ContentType");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "effectiveBasePermissions", {
/**
* Gets the effective base permissions for the item
*
*/
get: function () {
return new queryable_1.Queryable(this, "EffectiveBasePermissions");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "effectiveBasePermissionsForUI", {
/**
* Gets the effective base permissions for the item in a UI context
*
*/
get: function () {
return new queryable_1.Queryable(this, "EffectiveBasePermissionsForUI");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "fieldValuesAsHTML", {
/**
* Gets the field values for this list item in their HTML representation
*
*/
get: function () {
return new queryable_1.QueryableInstance(this, "FieldValuesAsHTML");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "fieldValuesAsText", {
/**
* Gets the field values for this list item in their text representation
*
*/
get: function () {
return new queryable_1.QueryableInstance(this, "FieldValuesAsText");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "fieldValuesForEdit", {
/**
* Gets the field values for this list item for use in editing controls
*
*/
get: function () {
return new queryable_1.QueryableInstance(this, "FieldValuesForEdit");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "folder", {
/**
* Gets the folder associated with this list item (if this item represents a folder)
*
*/
get: function () {
return new folders_1.Folder(this, "folder");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Item.prototype, "file", {
/**
* Gets the folder associated with this list item (if this item represents a folder)
*
*/
get: function () {
return new files_1.File(this, "file");
},
enumerable: true,
configurable: true
});
/**
* Updates this list intance with the supplied properties
*
* @param properties A plain object hash of values to update for the list
* @param eTag Value used in the IF-Match header, by default "*"
*/
Item.prototype.update = function (properties, eTag) {
var _this = this;
if (eTag === void 0) { eTag = "*"; }
return new Promise(function (resolve, reject) {
var removeDependency = _this.addBatchDependency();
var parentList = _this.getParent(queryable_1.QueryableInstance, _this.parentUrl.substr(0, _this.parentUrl.lastIndexOf("/")));
parentList.select("ListItemEntityTypeFullName").getAs().then(function (d) {
var postBody = JSON.stringify(util_1.Util.extend({
"__metadata": { "type": d.ListItemEntityTypeFullName },
}, properties));
removeDependency();
return _this.post({
body: postBody,
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "MERGE",
},
}, new ItemUpdatedParser()).then(function (data) {
resolve({
data: data,
item: _this,
});
});
}).catch(function (e) { return reject(e); });
});
};
/**
* Delete this item
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
Item.prototype.delete = function (eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.post({
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "DELETE",
},
});
};
/**
* Moves the list item to the Recycle Bin and returns the identifier of the new Recycle Bin item.
*/
Item.prototype.recycle = function () {
return this.clone(Item, "recycle", true).post();
};
/**
* Gets a string representation of the full URL to the WOPI frame.
* If there is no associated WOPI application, or no associated action, an empty string is returned.
*
* @param action Display mode: 0: view, 1: edit, 2: mobileView, 3: interactivePreview
*/
Item.prototype.getWopiFrameUrl = function (action) {
if (action === void 0) { action = 0; }
var i = this.clone(Item, "getWOPIFrameUrl(@action)", true);
i._query.add("@action", action);
return i.post().then(function (data) {
return data.GetWOPIFrameUrl;
});
};
/**
* Validates and sets the values of the specified collection of fields for the list item.
*
* @param formValues The fields to change and their new values.
* @param newDocumentUpdate true if the list item is a document being updated after upload; otherwise false.
*/
Item.prototype.validateUpdateListItem = function (formValues, newDocumentUpdate) {
if (newDocumentUpdate === void 0) { newDocumentUpdate = false; }
return this.clone(Item, "validateupdatelistitem", true).post({
body: JSON.stringify({ "formValues": formValues, bNewDocumentUpdate: newDocumentUpdate }),
});
};
return Item;
}(queryableshareable_1.QueryableShareableItem));
exports.Item = Item;
/**
* Provides paging functionality for list items
*/
var PagedItemCollection = (function () {
function PagedItemCollection(nextUrl, results) {
this.nextUrl = nextUrl;
this.results = results;
}
Object.defineProperty(PagedItemCollection.prototype, "hasNext", {
/**
* If true there are more results available in the set, otherwise there are not
*/
get: function () {
return typeof this.nextUrl === "string" && this.nextUrl.length > 0;
},
enumerable: true,
configurable: true
});
/**
* Gets the next set of results, or resolves to null if no results are available
*/
PagedItemCollection.prototype.getNext = function () {
if (this.hasNext) {
var items = new Items(this.nextUrl, null);
return items.getPaged();
}
return new Promise(function (r) { return r(null); });
};
return PagedItemCollection;
}());
exports.PagedItemCollection = PagedItemCollection;
var PagedItemCollectionParser = (function (_super) {
__extends(PagedItemCollectionParser, _super);
function PagedItemCollectionParser() {
return _super !== null && _super.apply(this, arguments) || this;
}
PagedItemCollectionParser.prototype.parse = function (r) {
var _this = this;
return new Promise(function (resolve, reject) {
if (_this.handleError(r, reject)) {
r.json().then(function (json) {
var nextUrl = json.hasOwnProperty("d") && json.d.hasOwnProperty("__next") ? json.d.__next : json["odata.nextLink"];
resolve(new PagedItemCollection(nextUrl, _this.parseODataJSON(json)));
});
}
});
};
return PagedItemCollectionParser;
}(odata_1.ODataParserBase));
var ItemUpdatedParser = (function (_super) {
__extends(ItemUpdatedParser, _super);
function ItemUpdatedParser() {
return _super !== null && _super.apply(this, arguments) || this;
}
ItemUpdatedParser.prototype.parse = function (r) {
var _this = this;
return new Promise(function (resolve, reject) {
if (_this.handleError(r, reject)) {
resolve({
"odata.etag": r.headers.get("etag"),
});
}
});
};
return ItemUpdatedParser;
}(odata_1.ODataParserBase));
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 items_1 = __webpack_require__(10);
var views_1 = __webpack_require__(49);
var contenttypes_1 = __webpack_require__(16);
var fields_1 = __webpack_require__(24);
var forms_1 = __webpack_require__(43);
var subscriptions_1 = __webpack_require__(47);
var queryable_1 = __webpack_require__(1);
var queryablesecurable_1 = __webpack_require__(26);
var util_1 = __webpack_require__(0);
var usercustomactions_1 = __webpack_require__(19);
var odata_1 = __webpack_require__(2);
var exceptions_1 = __webpack_require__(3);
var folders_1 = __webpack_require__(9);
/**
* Describes a collection of List objects
*
*/
var Lists = (function (_super) {
__extends(Lists, _super);
/**
* Creates a new instance of the Lists class
*
* @param baseUrl The url or Queryable which forms the parent of this fields collection
*/
function Lists(baseUrl, path) {
if (path === void 0) { path = "lists"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a list from the collection by title
*
* @param title The title of the list
*/
Lists.prototype.getByTitle = function (title) {
return new List(this, "getByTitle('" + title + "')");
};
/**
* Gets a list from the collection by guid id
*
* @param id The Id of the list (GUID)
*/
Lists.prototype.getById = function (id) {
var list = new List(this);
list.concat("('" + id + "')");
return list;
};
/**
* Adds a new list to the collection
*
* @param title The new list's title
* @param description The new list's description
* @param template The list template value
* @param enableContentTypes If true content types will be allowed and enabled, otherwise they will be disallowed and not enabled
* @param additionalSettings Will be passed as part of the list creation body
*/
Lists.prototype.add = function (title, description, template, enableContentTypes, additionalSettings) {
var _this = this;
if (description === void 0) { description = ""; }
if (template === void 0) { template = 100; }
if (enableContentTypes === void 0) { enableContentTypes = false; }
if (additionalSettings === void 0) { additionalSettings = {}; }
var addSettings = util_1.Util.extend({
"AllowContentTypes": enableContentTypes,
"BaseTemplate": template,
"ContentTypesEnabled": enableContentTypes,
"Description": description,
"Title": title,
"__metadata": { "type": "SP.List" },
}, additionalSettings);
return this.post({ body: JSON.stringify(addSettings) }).then(function (data) {
return { data: data, list: _this.getByTitle(addSettings.Title) };
});
};
/**
* Ensures that the specified list exists in the collection (note: this method not supported for batching)
*
* @param title The new list's title
* @param description The new list's description
* @param template The list template value
* @param enableContentTypes If true content types will be allowed and enabled, otherwise they will be disallowed and not enabled
* @param additionalSettings Will be passed as part of the list creation body or used to update an existing list
*/
Lists.prototype.ensure = function (title, description, template, enableContentTypes, additionalSettings) {
var _this = this;
if (description === void 0) { description = ""; }
if (template === void 0) { template = 100; }
if (enableContentTypes === void 0) { enableContentTypes = false; }
if (additionalSettings === void 0) { additionalSettings = {}; }
if (this.hasBatch) {
throw new exceptions_1.NotSupportedInBatchException("The ensure list method");
}
return new Promise(function (resolve, reject) {
var addOrUpdateSettings = util_1.Util.extend(additionalSettings, { Title: title, Description: description, ContentTypesEnabled: enableContentTypes }, true);
var list = _this.getByTitle(addOrUpdateSettings.Title);
list.get().then(function (_) {
list.update(addOrUpdateSettings).then(function (d) {
resolve({ created: false, data: d, list: _this.getByTitle(addOrUpdateSettings.Title) });
}).catch(function (e) { return reject(e); });
}).catch(function (_) {
_this.add(title, description, template, enableContentTypes, addOrUpdateSettings).then(function (r) {
resolve({ created: true, data: r.data, list: _this.getByTitle(addOrUpdateSettings.Title) });
}).catch(function (e) { return reject(e); });
});
});
};
/**
* Gets a list that is the default asset location for images or other files, which the users upload to their wiki pages.
*/
Lists.prototype.ensureSiteAssetsLibrary = function () {
return this.clone(Lists, "ensuresiteassetslibrary", true).post().then(function (json) {
return new List(odata_1.extractOdataId(json));
});
};
/**
* Gets a list that is the default location for wiki pages.
*/
Lists.prototype.ensureSitePagesLibrary = function () {
return this.clone(Lists, "ensuresitepageslibrary", true).post().then(function (json) {
return new List(odata_1.extractOdataId(json));
});
};
return Lists;
}(queryable_1.QueryableCollection));
exports.Lists = Lists;
/**
* Describes a single List instance
*
*/
var List = (function (_super) {
__extends(List, _super);
function List() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(List.prototype, "contentTypes", {
/**
* Gets the content types in this list
*
*/
get: function () {
return new contenttypes_1.ContentTypes(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "items", {
/**
* Gets the items in this list
*
*/
get: function () {
return new items_1.Items(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "views", {
/**
* Gets the views in this list
*
*/
get: function () {
return new views_1.Views(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "fields", {
/**
* Gets the fields in this list
*
*/
get: function () {
return new fields_1.Fields(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "forms", {
/**
* Gets the forms in this list
*
*/
get: function () {
return new forms_1.Forms(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "defaultView", {
/**
* Gets the default view of this list
*
*/
get: function () {
return new queryable_1.QueryableInstance(this, "DefaultView");
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "userCustomActions", {
/**
* Get all custom actions on a site collection
*
*/
get: function () {
return new usercustomactions_1.UserCustomActions(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "effectiveBasePermissions", {
/**
* Gets the effective base permissions of this list
*
*/
get: function () {
return new queryable_1.Queryable(this, "EffectiveBasePermissions");
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "eventReceivers", {
/**
* Gets the event receivers attached to this list
*
*/
get: function () {
return new queryable_1.QueryableCollection(this, "EventReceivers");
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "relatedFields", {
/**
* Gets the related fields of this list
*
*/
get: function () {
return new queryable_1.Queryable(this, "getRelatedFields");
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "informationRightsManagementSettings", {
/**
* Gets the IRM settings for this list
*
*/
get: function () {
return new queryable_1.Queryable(this, "InformationRightsManagementSettings");
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "subscriptions", {
/**
* Gets the webhook subscriptions of this list
*
*/
get: function () {
return new subscriptions_1.Subscriptions(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(List.prototype, "rootFolder", {
/**
* The root folder of the list
*/
get: function () {
return new folders_1.Folder(this, "rootFolder");
},
enumerable: true,
configurable: true
});
/**
* Gets a view by view guid id
*
*/
List.prototype.getView = function (viewId) {
return new views_1.View(this, "getView('" + viewId + "')");
};
/**
* Updates this list intance with the supplied properties
*
* @param properties A plain object hash of values to update for the list
* @param eTag Value used in the IF-Match header, by default "*"
*/
/* tslint:disable no-string-literal */
List.prototype.update = function (properties, eTag) {
var _this = this;
if (eTag === void 0) { eTag = "*"; }
var postBody = JSON.stringify(util_1.Util.extend({
"__metadata": { "type": "SP.List" },
}, properties));
return this.post({
body: postBody,
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
var retList = _this;
if (properties.hasOwnProperty("Title")) {
retList = _this.getParent(List, _this.parentUrl, "getByTitle('" + properties["Title"] + "')");
}
return {
data: data,
list: retList,
};
});
};
/* tslint:enable */
/**
* Delete this list
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
List.prototype.delete = function (eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.post({
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "DELETE",
},
});
};
/**
* Returns the collection of changes from the change log that have occurred within the list, based on the specified query.
*/
List.prototype.getChanges = function (query) {
return this.clone(List, "getchanges", true).post({
body: JSON.stringify({ "query": util_1.Util.extend({ "__metadata": { "type": "SP.ChangeQuery" } }, query) }),
});
};
/**
* Returns a collection of items from the list based on the specified query.
*
* @param CamlQuery The Query schema of Collaborative Application Markup
* Language (CAML) is used in various ways within the context of Microsoft SharePoint Foundation
* to define queries against list data.
* see:
*
* https://msdn.microsoft.com/en-us/library/office/ms467521.aspx
*
* @param expands A URI with a $expand System Query Option indicates that Entries associated with
* the Entry or Collection of Entries identified by the Resource Path
* section of the URI must be represented inline (i.e. eagerly loaded).
* see:
*
* https://msdn.microsoft.com/en-us/library/office/fp142385.aspx
*
* http://www.odata.org/documentation/odata-version-2-0/uri-conventions/#ExpandSystemQueryOption
*/
List.prototype.getItemsByCAMLQuery = function (query) {
var expands = [];
for (var _i = 1; _i < arguments.length; _i++) {
expands[_i - 1] = arguments[_i];
}
var q = this.clone(List, "getitems", true);
return q.expand.apply(q, expands).post({
body: JSON.stringify({ "query": util_1.Util.extend({ "__metadata": { "type": "SP.CamlQuery" } }, query) }),
});
};
/**
* See: https://msdn.microsoft.com/en-us/library/office/dn292554.aspx
*/
List.prototype.getListItemChangesSinceToken = function (query) {
return this.clone(List, "getlistitemchangessincetoken", true).post({
body: JSON.stringify({ "query": util_1.Util.extend({ "__metadata": { "type": "SP.ChangeLogItemQuery" } }, query) }),
}, { parse: function (r) { return r.text(); } });
};
/**
* Moves the list to the Recycle Bin and returns the identifier of the new Recycle Bin item.
*/
List.prototype.recycle = function () {
return this.clone(List, "recycle", true).post().then(function (data) {
if (data.hasOwnProperty("Recycle")) {
return data.Recycle;
}
else {
return data;
}
});
};
/**
* Renders list data based on the view xml provided
*/
List.prototype.renderListData = function (viewXml) {
var q = this.clone(List, "renderlistdata(@viewXml)");
q.query.add("@viewXml", "'" + viewXml + "'");
return q.post().then(function (data) {
// data will be a string, so we parse it again
data = JSON.parse(data);
if (data.hasOwnProperty("RenderListData")) {
return data.RenderListData;
}
else {
return data;
}
});
};
/**
* Gets the field values and field schema attributes for a list item.
*/
List.prototype.renderListFormData = function (itemId, formId, mode) {
return this.clone(List, "renderlistformdata(itemid=" + itemId + ", formid='" + formId + "', mode='" + mode + "')", true).post().then(function (data) {
// data will be a string, so we parse it again
data = JSON.parse(data);
if (data.hasOwnProperty("ListData")) {
return data.ListData;
}
else {
return data;
}
});
};
/**
* Reserves a list item ID for idempotent list item creation.
*/
List.prototype.reserveListItemId = function () {
return this.clone(List, "reservelistitemid", true).post().then(function (data) {
if (data.hasOwnProperty("ReserveListItemId")) {
return data.ReserveListItemId;
}
else {
return data;
}
});
};
/**
* Returns the ListItemEntityTypeFullName for this list, used when adding/updating list items. Does not support batching.
*
*/
List.prototype.getListItemEntityTypeFullName = function () {
return this.clone(List, null).select("ListItemEntityTypeFullName").getAs().then(function (o) { return o.ListItemEntityTypeFullName; });
};
return List;
}(queryablesecurable_1.QueryableSecurable));
exports.List = List;
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 util_1 = __webpack_require__(0);
var webs_1 = __webpack_require__(8);
var odata_1 = __webpack_require__(2);
var queryable_1 = __webpack_require__(1);
var queryablesecurable_1 = __webpack_require__(26);
var types_1 = __webpack_require__(13);
/**
* Internal helper class used to augment classes to include sharing functionality
*/
var QueryableShareable = (function (_super) {
__extends(QueryableShareable, _super);
function QueryableShareable() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a sharing link for the supplied
*
* @param kind The kind of link to share
* @param expiration The optional expiration for this link
*/
QueryableShareable.prototype.getShareLink = function (kind, expiration) {
if (expiration === void 0) { expiration = null; }
// date needs to be an ISO string or null
var expString = expiration !== null ? expiration.toISOString() : null;
// clone using the factory and send the request
return this.clone(QueryableShareable, "shareLink", true).postAs({
body: JSON.stringify({
request: {
createLink: true,
emailData: null,
settings: {
expiration: expString,
linkKind: kind,
},
},
}),
});
};
/**
* Shares this instance with the supplied users
*
* @param loginNames Resolved login names to share
* @param role The role
* @param requireSignin True to require the user is authenticated, otherwise false
* @param propagateAcl True to apply this share to all children
* @param emailData If supplied an email will be sent with the indicated properties
*/
QueryableShareable.prototype.shareWith = function (loginNames, role, requireSignin, propagateAcl, emailData) {
var _this = this;
if (requireSignin === void 0) { requireSignin = true; }
if (propagateAcl === void 0) { propagateAcl = false; }
// handle the multiple input types
if (!Array.isArray(loginNames)) {
loginNames = [loginNames];
}
var userStr = JSON.stringify(loginNames.map(function (login) { return { Key: login }; }));
var roleFilter = role === types_1.SharingRole.Edit ? types_1.RoleType.Contributor : types_1.RoleType.Reader;
// start by looking up the role definition id we need to set the roleValue
return webs_1.Web.fromUrl(this.toUrl()).roleDefinitions.select("Id").filter("RoleTypeKind eq " + roleFilter).get().then(function (def) {
if (!Array.isArray(def) || def.length < 1) {
throw new Error("Could not locate a role defintion with RoleTypeKind " + roleFilter);
}
var postBody = {
includeAnonymousLinkInEmail: requireSignin,
peoplePickerInput: userStr,
propagateAcl: propagateAcl,
roleValue: "role:" + def[0].Id,
useSimplifiedRoles: true,
};
if (typeof emailData !== "undefined") {
postBody = util_1.Util.extend(postBody, {
emailBody: emailData.body,
emailSubject: typeof emailData.subject !== "undefined" ? emailData.subject : "",
sendEmail: true,
});
}
return _this.clone(QueryableShareable, "shareObject", true).postAs({
body: JSON.stringify(postBody),
});
});
};
/**
* Shares an object based on the supplied options
*
* @param options The set of options to send to the ShareObject method
* @param bypass If true any processing is skipped and the options are sent directly to the ShareObject method
*/
QueryableShareable.prototype.shareObject = function (options, bypass) {
var _this = this;
if (bypass === void 0) { bypass = false; }
if (bypass) {
// if the bypass flag is set send the supplied parameters directly to the service
return this.sendShareObjectRequest(options);
}
// extend our options with some defaults
options = util_1.Util.extend(options, {
group: null,
includeAnonymousLinkInEmail: false,
propagateAcl: false,
useSimplifiedRoles: true,
}, true);
return this.getRoleValue(options.role, options.group).then(function (roleValue) {
// handle the multiple input types
if (!Array.isArray(options.loginNames)) {
options.loginNames = [options.loginNames];
}
var userStr = JSON.stringify(options.loginNames.map(function (login) { return { Key: login }; }));
var postBody = {
peoplePickerInput: userStr,
roleValue: roleValue,
url: options.url,
};
if (typeof options.emailData !== "undefined" && options.emailData !== null) {
postBody = util_1.Util.extend(postBody, {
emailBody: options.emailData.body,
emailSubject: typeof options.emailData.subject !== "undefined" ? options.emailData.subject : "Shared with you.",
sendEmail: true,
});
}
return _this.sendShareObjectRequest(postBody);
});
};
/**
* Calls the web's UnshareObject method
*
* @param url The url of the object to unshare
*/
QueryableShareable.prototype.unshareObjectWeb = function (url) {
return this.clone(QueryableShareable, "unshareObject", true).postAs({
body: JSON.stringify({
url: url,
}),
});
};
/**
* Checks Permissions on the list of Users and returns back role the users have on the Item.
*
* @param recipients The array of Entities for which Permissions need to be checked.
*/
QueryableShareable.prototype.checkPermissions = function (recipients) {
return this.clone(QueryableShareable, "checkPermissions", true).postAs({
body: JSON.stringify({
recipients: recipients,
}),
});
};
/**
* Get Sharing Information.
*
* @param request The SharingInformationRequest Object.
*/
QueryableShareable.prototype.getSharingInformation = function (request) {
if (request === void 0) { request = null; }
return this.clone(QueryableShareable, "getSharingInformation", true).postAs({
body: JSON.stringify({
request: request,
}),
});
};
/**
* Gets the sharing settings of an item.
*
* @param useSimplifiedRoles Determines whether to use simplified roles.
*/
QueryableShareable.prototype.getObjectSharingSettings = function (useSimplifiedRoles) {
if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; }
return this.clone(QueryableShareable, "getObjectSharingSettings", true).postAs({
body: JSON.stringify({
useSimplifiedRoles: useSimplifiedRoles,
}),
});
};
/**
* Unshares this object
*/
QueryableShareable.prototype.unshareObject = function () {
return this.clone(QueryableShareable, "unshareObject", true).postAs();
};
/**
* Deletes a link by type
*
* @param kind Deletes a sharing link by the kind of link
*/
QueryableShareable.prototype.deleteLinkByKind = function (kind) {
return this.clone(QueryableShareable, "deleteLinkByKind", true).post({
body: JSON.stringify({ linkKind: kind }),
});
};
/**
* Removes the specified link to the item.
*
* @param kind The kind of link to be deleted.
* @param shareId
*/
QueryableShareable.prototype.unshareLink = function (kind, shareId) {
if (shareId === void 0) { shareId = "00000000-0000-0000-0000-000000000000"; }
return this.clone(QueryableShareable, "unshareLink", true).post({
body: JSON.stringify({ linkKind: kind, shareId: shareId }),
});
};
/**
* Calculates the roleValue string used in the sharing query
*
* @param role The Sharing Role
* @param group The Group type
*/
QueryableShareable.prototype.getRoleValue = function (role, group) {
// we will give group precedence, because we had to make a choice
if (typeof group !== "undefined" && group !== null) {
switch (group) {
case types_1.RoleType.Contributor:
return webs_1.Web.fromUrl(this.toUrl()).associatedMemberGroup.select("Id").getAs().then(function (g) { return "group: " + g.Id; });
case types_1.RoleType.Reader:
case types_1.RoleType.Guest:
return webs_1.Web.fromUrl(this.toUrl()).associatedVisitorGroup.select("Id").getAs().then(function (g) { return "group: " + g.Id; });
default:
throw new Error("Could not determine role value for supplied value. Contributor, Reader, and Guest are supported");
}
}
else {
var roleFilter = role === types_1.SharingRole.Edit ? types_1.RoleType.Contributor : types_1.RoleType.Reader;
return webs_1.Web.fromUrl(this.toUrl()).roleDefinitions.select("Id").top(1).filter("RoleTypeKind eq " + roleFilter).getAs().then(function (def) {
if (def.length < 1) {
throw new Error("Could not locate associated role definition for supplied role. Edit and View are supported");
}
return "role: " + def[0].Id;
});
}
};
QueryableShareable.prototype.getShareObjectWeb = function (candidate) {
return Promise.resolve(webs_1.Web.fromUrl(candidate, "/_api/SP.Web.ShareObject"));
};
QueryableShareable.prototype.sendShareObjectRequest = function (options) {
return this.getShareObjectWeb(this.toUrl()).then(function (web) {
return web.expand("UsersWithAccessRequests", "GroupsSharedWith").as(QueryableShareable).post({
body: JSON.stringify(options),
});
});
};
return QueryableShareable;
}(queryable_1.Queryable));
exports.QueryableShareable = QueryableShareable;
var QueryableShareableWeb = (function (_super) {
__extends(QueryableShareableWeb, _super);
function QueryableShareableWeb() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Shares this web with the supplied users
* @param loginNames The resolved login names to share
* @param role The role to share this web
* @param emailData Optional email data
*/
QueryableShareableWeb.prototype.shareWith = function (loginNames, role, emailData) {
var _this = this;
if (role === void 0) { role = types_1.SharingRole.View; }
var dependency = this.addBatchDependency();
return webs_1.Web.fromUrl(this.toUrl(), "/_api/web/url").get().then(function (url) {
dependency();
return _this.shareObject(util_1.Util.combinePaths(url, "/_layouts/15/aclinv.aspx?forSharing=1&mbypass=1"), loginNames, role, emailData);
});
};
/**
* Provides direct access to the static web.ShareObject method
*
* @param url The url to share
* @param loginNames Resolved loginnames string[] of a single login name string
* @param roleValue Role value
* @param emailData Optional email data
* @param groupId Optional group id
* @param propagateAcl
* @param includeAnonymousLinkInEmail
* @param useSimplifiedRoles
*/
QueryableShareableWeb.prototype.shareObject = function (url, loginNames, role, emailData, group, propagateAcl, includeAnonymousLinkInEmail, useSimplifiedRoles) {
if (propagateAcl === void 0) { propagateAcl = false; }
if (includeAnonymousLinkInEmail === void 0) { includeAnonymousLinkInEmail = false; }
if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; }
return this.clone(QueryableShareable, null, true).shareObject({
emailData: emailData,
group: group,
includeAnonymousLinkInEmail: includeAnonymousLinkInEmail,
loginNames: loginNames,
propagateAcl: propagateAcl,
role: role,
url: url,
useSimplifiedRoles: useSimplifiedRoles,
});
};
/**
* Supplies a method to pass any set of arguments to ShareObject
*
* @param options The set of options to send to ShareObject
*/
QueryableShareableWeb.prototype.shareObjectRaw = function (options) {
return this.clone(QueryableShareable, null, true).shareObject(options, true);
};
/**
* Unshares the object
*
* @param url The url of the object to stop sharing
*/
QueryableShareableWeb.prototype.unshareObject = function (url) {
return this.clone(QueryableShareable, null, true).unshareObjectWeb(url);
};
return QueryableShareableWeb;
}(queryablesecurable_1.QueryableSecurable));
exports.QueryableShareableWeb = QueryableShareableWeb;
var QueryableShareableItem = (function (_super) {
__extends(QueryableShareableItem, _super);
function QueryableShareableItem() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a link suitable for sharing for this item
*
* @param kind The type of link to share
* @param expiration The optional expiration date
*/
QueryableShareableItem.prototype.getShareLink = function (kind, expiration) {
if (kind === void 0) { kind = types_1.SharingLinkKind.OrganizationView; }
if (expiration === void 0) { expiration = null; }
return this.clone(QueryableShareable, null, true).getShareLink(kind, expiration);
};
/**
* Shares this item with one or more users
*
* @param loginNames string or string[] of resolved login names to which this item will be shared
* @param role The role (View | Edit) applied to the share
* @param emailData Optional, if inlucded an email will be sent. Note subject currently has no effect.
*/
QueryableShareableItem.prototype.shareWith = function (loginNames, role, requireSignin, emailData) {
if (role === void 0) { role = types_1.SharingRole.View; }
if (requireSignin === void 0) { requireSignin = true; }
return this.clone(QueryableShareable, null, true).shareWith(loginNames, role, requireSignin, false, emailData);
};
/**
* Checks Permissions on the list of Users and returns back role the users have on the Item.
*
* @param recipients The array of Entities for which Permissions need to be checked.
*/
QueryableShareableItem.prototype.checkSharingPermissions = function (recipients) {
return this.clone(QueryableShareable, null, true).checkPermissions(recipients);
};
/**
* Get Sharing Information.
*
* @param request The SharingInformationRequest Object.
*/
QueryableShareableItem.prototype.getSharingInformation = function (request) {
if (request === void 0) { request = null; }
return this.clone(QueryableShareable, null, true).getSharingInformation(request);
};
/**
* Gets the sharing settings of an item.
*
* @param useSimplifiedRoles Determines whether to use simplified roles.
*/
QueryableShareableItem.prototype.getObjectSharingSettings = function (useSimplifiedRoles) {
if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; }
return this.clone(QueryableShareable, null, true).getObjectSharingSettings(useSimplifiedRoles);
};
/**
* Unshare this item
*/
QueryableShareableItem.prototype.unshare = function () {
return this.clone(QueryableShareable, null, true).unshareObject();
};
/**
* Deletes a sharing link by kind
*
* @param kind Deletes a sharing link by the kind of link
*/
QueryableShareableItem.prototype.deleteSharingLinkByKind = function (kind) {
return this.clone(QueryableShareable, null, true).deleteLinkByKind(kind);
};
/**
* Removes the specified link to the item.
*
* @param kind The kind of link to be deleted.
* @param shareId
*/
QueryableShareableItem.prototype.unshareLink = function (kind, shareId) {
return this.clone(QueryableShareable, null, true).unshareLink(kind, shareId);
};
return QueryableShareableItem;
}(queryablesecurable_1.QueryableSecurable));
exports.QueryableShareableItem = QueryableShareableItem;
var FileFolderShared = (function (_super) {
__extends(FileFolderShared, _super);
function FileFolderShared() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a link suitable for sharing
*
* @param kind The kind of link to get
* @param expiration Optional, an expiration for this link
*/
FileFolderShared.prototype.getShareLink = function (kind, expiration) {
if (kind === void 0) { kind = types_1.SharingLinkKind.OrganizationView; }
if (expiration === void 0) { expiration = null; }
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.getShareLink(kind, expiration);
});
};
/**
* Checks Permissions on the list of Users and returns back role the users have on the Item.
*
* @param recipients The array of Entities for which Permissions need to be checked.
*/
FileFolderShared.prototype.checkSharingPermissions = function (recipients) {
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.checkPermissions(recipients);
});
};
/**
* Get Sharing Information.
*
* @param request The SharingInformationRequest Object.
*/
FileFolderShared.prototype.getSharingInformation = function (request) {
if (request === void 0) { request = null; }
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.getSharingInformation(request);
});
};
/**
* Gets the sharing settings of an item.
*
* @param useSimplifiedRoles Determines whether to use simplified roles.
*/
FileFolderShared.prototype.getObjectSharingSettings = function (useSimplifiedRoles) {
if (useSimplifiedRoles === void 0) { useSimplifiedRoles = true; }
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.getObjectSharingSettings(useSimplifiedRoles);
});
};
/**
* Unshare this item
*/
FileFolderShared.prototype.unshare = function () {
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.unshareObject();
});
};
/**
* Deletes a sharing link by the kind of link
*
* @param kind The kind of link to be deleted.
*/
FileFolderShared.prototype.deleteSharingLinkByKind = function (kind) {
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.deleteLinkByKind(kind);
});
};
/**
* Removes the specified link to the item.
*
* @param kind The kind of link to be deleted.
* @param shareId The share id to delete
*/
FileFolderShared.prototype.unshareLink = function (kind, shareId) {
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.unshareLink(kind, shareId);
});
};
/**
* For files and folders we need to use the associated item end point
*/
FileFolderShared.prototype.getShareable = function () {
var _this = this;
// sharing only works on the item end point, not the file one - so we create a folder instance with the item url internally
return this.clone(QueryableShareableFile, "listItemAllFields", false).select("odata.editlink").get().then(function (d) {
var shareable = new QueryableShareable(odata_1.getEntityUrl(d));
// we need to handle batching
if (_this.hasBatch) {
shareable = shareable.inBatch(_this.batch);
}
return shareable;
});
};
return FileFolderShared;
}(queryable_1.QueryableInstance));
exports.FileFolderShared = FileFolderShared;
var QueryableShareableFile = (function (_super) {
__extends(QueryableShareableFile, _super);
function QueryableShareableFile() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Shares this item with one or more users
*
* @param loginNames string or string[] of resolved login names to which this item will be shared
* @param role The role (View | Edit) applied to the share
* @param shareEverything Share everything in this folder, even items with unique permissions.
* @param requireSignin If true the user must signin to view link, otherwise anyone with the link can access the resource
* @param emailData Optional, if inlucded an email will be sent. Note subject currently has no effect.
*/
QueryableShareableFile.prototype.shareWith = function (loginNames, role, requireSignin, emailData) {
if (role === void 0) { role = types_1.SharingRole.View; }
if (requireSignin === void 0) { requireSignin = true; }
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.shareWith(loginNames, role, requireSignin, false, emailData);
});
};
return QueryableShareableFile;
}(FileFolderShared));
exports.QueryableShareableFile = QueryableShareableFile;
var QueryableShareableFolder = (function (_super) {
__extends(QueryableShareableFolder, _super);
function QueryableShareableFolder() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Shares this item with one or more users
*
* @param loginNames string or string[] of resolved login names to which this item will be shared
* @param role The role (View | Edit) applied to the share
* @param shareEverything Share everything in this folder, even items with unique permissions.
* @param requireSignin If true the user must signin to view link, otherwise anyone with the link can access the resource
* @param emailData Optional, if inlucded an email will be sent. Note subject currently has no effect.
*/
QueryableShareableFolder.prototype.shareWith = function (loginNames, role, requireSignin, shareEverything, emailData) {
if (role === void 0) { role = types_1.SharingRole.View; }
if (requireSignin === void 0) { requireSignin = true; }
if (shareEverything === void 0) { shareEverything = false; }
var dependency = this.addBatchDependency();
return this.getShareable().then(function (shareable) {
dependency();
return shareable.shareWith(loginNames, role, requireSignin, shareEverything, emailData);
});
};
return QueryableShareableFolder;
}(FileFolderShared));
exports.QueryableShareableFolder = QueryableShareableFolder;
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// reference: https://msdn.microsoft.com/en-us/library/office/dn600183.aspx
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Determines the display mode of the given control or view
*/
var ControlMode;
(function (ControlMode) {
ControlMode[ControlMode["Display"] = 1] = "Display";
ControlMode[ControlMode["Edit"] = 2] = "Edit";
ControlMode[ControlMode["New"] = 3] = "New";
})(ControlMode = exports.ControlMode || (exports.ControlMode = {}));
/**
* Specifies the type of the field.
*/
var FieldTypes;
(function (FieldTypes) {
FieldTypes[FieldTypes["Invalid"] = 0] = "Invalid";
FieldTypes[FieldTypes["Integer"] = 1] = "Integer";
FieldTypes[FieldTypes["Text"] = 2] = "Text";
FieldTypes[FieldTypes["Note"] = 3] = "Note";
FieldTypes[FieldTypes["DateTime"] = 4] = "DateTime";
FieldTypes[FieldTypes["Counter"] = 5] = "Counter";
FieldTypes[FieldTypes["Choice"] = 6] = "Choice";
FieldTypes[FieldTypes["Lookup"] = 7] = "Lookup";
FieldTypes[FieldTypes["Boolean"] = 8] = "Boolean";
FieldTypes[FieldTypes["Number"] = 9] = "Number";
FieldTypes[FieldTypes["Currency"] = 10] = "Currency";
FieldTypes[FieldTypes["URL"] = 11] = "URL";
FieldTypes[FieldTypes["Computed"] = 12] = "Computed";
FieldTypes[FieldTypes["Threading"] = 13] = "Threading";
FieldTypes[FieldTypes["Guid"] = 14] = "Guid";
FieldTypes[FieldTypes["MultiChoice"] = 15] = "MultiChoice";
FieldTypes[FieldTypes["GridChoice"] = 16] = "GridChoice";
FieldTypes[FieldTypes["Calculated"] = 17] = "Calculated";
FieldTypes[FieldTypes["File"] = 18] = "File";
FieldTypes[FieldTypes["Attachments"] = 19] = "Attachments";
FieldTypes[FieldTypes["User"] = 20] = "User";
FieldTypes[FieldTypes["Recurrence"] = 21] = "Recurrence";
FieldTypes[FieldTypes["CrossProjectLink"] = 22] = "CrossProjectLink";
FieldTypes[FieldTypes["ModStat"] = 23] = "ModStat";
FieldTypes[FieldTypes["Error"] = 24] = "Error";
FieldTypes[FieldTypes["ContentTypeId"] = 25] = "ContentTypeId";
FieldTypes[FieldTypes["PageSeparator"] = 26] = "PageSeparator";
FieldTypes[FieldTypes["ThreadIndex"] = 27] = "ThreadIndex";
FieldTypes[FieldTypes["WorkflowStatus"] = 28] = "WorkflowStatus";
FieldTypes[FieldTypes["AllDayEvent"] = 29] = "AllDayEvent";
FieldTypes[FieldTypes["WorkflowEventType"] = 30] = "WorkflowEventType";
})(FieldTypes = exports.FieldTypes || (exports.FieldTypes = {}));
var DateTimeFieldFormatType;
(function (DateTimeFieldFormatType) {
DateTimeFieldFormatType[DateTimeFieldFormatType["DateOnly"] = 0] = "DateOnly";
DateTimeFieldFormatType[DateTimeFieldFormatType["DateTime"] = 1] = "DateTime";
})(DateTimeFieldFormatType = exports.DateTimeFieldFormatType || (exports.DateTimeFieldFormatType = {}));
/**
* Specifies the control settings while adding a field.
*/
var AddFieldOptions;
(function (AddFieldOptions) {
/**
* Specify that a new field added to the list must also be added to the default content type in the site collection
*/
AddFieldOptions[AddFieldOptions["DefaultValue"] = 0] = "DefaultValue";
/**
* Specify that a new field added to the list must also be added to the default content type in the site collection.
*/
AddFieldOptions[AddFieldOptions["AddToDefaultContentType"] = 1] = "AddToDefaultContentType";
/**
* Specify that a new field must not be added to any other content type
*/
AddFieldOptions[AddFieldOptions["AddToNoContentType"] = 2] = "AddToNoContentType";
/**
* Specify that a new field that is added to the specified list must also be added to all content types in the site collection
*/
AddFieldOptions[AddFieldOptions["AddToAllContentTypes"] = 4] = "AddToAllContentTypes";
/**
* Specify adding an internal field name hint for the purpose of avoiding possible database locking or field renaming operations
*/
AddFieldOptions[AddFieldOptions["AddFieldInternalNameHint"] = 8] = "AddFieldInternalNameHint";
/**
* Specify that a new field that is added to the specified list must also be added to the default list view
*/
AddFieldOptions[AddFieldOptions["AddFieldToDefaultView"] = 16] = "AddFieldToDefaultView";
/**
* Specify to confirm that no other field has the same display name
*/
AddFieldOptions[AddFieldOptions["AddFieldCheckDisplayName"] = 32] = "AddFieldCheckDisplayName";
})(AddFieldOptions = exports.AddFieldOptions || (exports.AddFieldOptions = {}));
var CalendarType;
(function (CalendarType) {
CalendarType[CalendarType["Gregorian"] = 1] = "Gregorian";
CalendarType[CalendarType["Japan"] = 3] = "Japan";
CalendarType[CalendarType["Taiwan"] = 4] = "Taiwan";
CalendarType[CalendarType["Korea"] = 5] = "Korea";
CalendarType[CalendarType["Hijri"] = 6] = "Hijri";
CalendarType[CalendarType["Thai"] = 7] = "Thai";
CalendarType[CalendarType["Hebrew"] = 8] = "Hebrew";
CalendarType[CalendarType["GregorianMEFrench"] = 9] = "GregorianMEFrench";
CalendarType[CalendarType["GregorianArabic"] = 10] = "GregorianArabic";
CalendarType[CalendarType["GregorianXLITEnglish"] = 11] = "GregorianXLITEnglish";
CalendarType[CalendarType["GregorianXLITFrench"] = 12] = "GregorianXLITFrench";
CalendarType[CalendarType["KoreaJapanLunar"] = 14] = "KoreaJapanLunar";
CalendarType[CalendarType["ChineseLunar"] = 15] = "ChineseLunar";
CalendarType[CalendarType["SakaEra"] = 16] = "SakaEra";
CalendarType[CalendarType["UmAlQura"] = 23] = "UmAlQura";
})(CalendarType = exports.CalendarType || (exports.CalendarType = {}));
var UrlFieldFormatType;
(function (UrlFieldFormatType) {
UrlFieldFormatType[UrlFieldFormatType["Hyperlink"] = 0] = "Hyperlink";
UrlFieldFormatType[UrlFieldFormatType["Image"] = 1] = "Image";
})(UrlFieldFormatType = exports.UrlFieldFormatType || (exports.UrlFieldFormatType = {}));
var PermissionKind;
(function (PermissionKind) {
/**
* Has no permissions on the Site. Not available through the user interface.
*/
PermissionKind[PermissionKind["EmptyMask"] = 0] = "EmptyMask";
/**
* View items in lists, documents in document libraries, and Web discussion comments.
*/
PermissionKind[PermissionKind["ViewListItems"] = 1] = "ViewListItems";
/**
* Add items to lists, documents to document libraries, and Web discussion comments.
*/
PermissionKind[PermissionKind["AddListItems"] = 2] = "AddListItems";
/**
* Edit items in lists, edit documents in document libraries, edit Web discussion comments
* in documents, and customize Web Part Pages in document libraries.
*/
PermissionKind[PermissionKind["EditListItems"] = 3] = "EditListItems";
/**
* Delete items from a list, documents from a document library, and Web discussion
* comments in documents.
*/
PermissionKind[PermissionKind["DeleteListItems"] = 4] = "DeleteListItems";
/**
* Approve a minor version of a list item or document.
*/
PermissionKind[PermissionKind["ApproveItems"] = 5] = "ApproveItems";
/**
* View the source of documents with server-side file handlers.
*/
PermissionKind[PermissionKind["OpenItems"] = 6] = "OpenItems";
/**
* View past versions of a list item or document.
*/
PermissionKind[PermissionKind["ViewVersions"] = 7] = "ViewVersions";
/**
* Delete past versions of a list item or document.
*/
PermissionKind[PermissionKind["DeleteVersions"] = 8] = "DeleteVersions";
/**
* Discard or check in a document which is checked out to another user.
*/
PermissionKind[PermissionKind["CancelCheckout"] = 9] = "CancelCheckout";
/**
* Create, change, and delete personal views of lists.
*/
PermissionKind[PermissionKind["ManagePersonalViews"] = 10] = "ManagePersonalViews";
/**
* Create and delete lists, add or remove columns in a list, and add or remove public views of a list.
*/
PermissionKind[PermissionKind["ManageLists"] = 12] = "ManageLists";
/**
* View forms, views, and application pages, and enumerate lists.
*/
PermissionKind[PermissionKind["ViewFormPages"] = 13] = "ViewFormPages";
/**
* Make content of a list or document library retrieveable for anonymous users through SharePoint search.
* The list permissions in the site do not change.
*/
PermissionKind[PermissionKind["AnonymousSearchAccessList"] = 14] = "AnonymousSearchAccessList";
/**
* Allow users to open a Site, list, or folder to access items inside that container.
*/
PermissionKind[PermissionKind["Open"] = 17] = "Open";
/**
* View pages in a Site.
*/
PermissionKind[PermissionKind["ViewPages"] = 18] = "ViewPages";
/**
* Add, change, or delete HTML pages or Web Part Pages, and edit the Site using
* a Windows SharePoint Services compatible editor.
*/
PermissionKind[PermissionKind["AddAndCustomizePages"] = 19] = "AddAndCustomizePages";
/**
* Apply a theme or borders to the entire Site.
*/
PermissionKind[PermissionKind["ApplyThemeAndBorder"] = 20] = "ApplyThemeAndBorder";
/**
* Apply a style sheet (.css file) to the Site.
*/
PermissionKind[PermissionKind["ApplyStyleSheets"] = 21] = "ApplyStyleSheets";
/**
* View reports on Site usage.
*/
PermissionKind[PermissionKind["ViewUsageData"] = 22] = "ViewUsageData";
/**
* Create a Site using Self-Service Site Creation.
*/
PermissionKind[PermissionKind["CreateSSCSite"] = 23] = "CreateSSCSite";
/**
* Create subsites such as team sites, Meeting Workspace sites, and Document Workspace sites.
*/
PermissionKind[PermissionKind["ManageSubwebs"] = 24] = "ManageSubwebs";
/**
* Create a group of users that can be used anywhere within the site collection.
*/
PermissionKind[PermissionKind["CreateGroups"] = 25] = "CreateGroups";
/**
* Create and change permission levels on the Site and assign permissions to users
* and groups.
*/
PermissionKind[PermissionKind["ManagePermissions"] = 26] = "ManagePermissions";
/**
* Enumerate files and folders in a Site using Microsoft Office SharePoint Designer
* and WebDAV interfaces.
*/
PermissionKind[PermissionKind["BrowseDirectories"] = 27] = "BrowseDirectories";
/**
* View information about users of the Site.
*/
PermissionKind[PermissionKind["BrowseUserInfo"] = 28] = "BrowseUserInfo";
/**
* Add or remove personal Web Parts on a Web Part Page.
*/
PermissionKind[PermissionKind["AddDelPrivateWebParts"] = 29] = "AddDelPrivateWebParts";
/**
* Update Web Parts to display personalized information.
*/
PermissionKind[PermissionKind["UpdatePersonalWebParts"] = 30] = "UpdatePersonalWebParts";
/**
* Grant the ability to perform all administration tasks for the Site as well as
* manage content, activate, deactivate, or edit properties of Site scoped Features
* through the object model or through the user interface (UI). When granted on the
* root Site of a Site Collection, activate, deactivate, or edit properties of
* site collection scoped Features through the object model. To browse to the Site
* Collection Features page and activate or deactivate Site Collection scoped Features
* through the UI, you must be a Site Collection administrator.
*/
PermissionKind[PermissionKind["ManageWeb"] = 31] = "ManageWeb";
/**
* Content of lists and document libraries in the Web site will be retrieveable for anonymous users through
* SharePoint search if the list or document library has AnonymousSearchAccessList set.
*/
PermissionKind[PermissionKind["AnonymousSearchAccessWebLists"] = 32] = "AnonymousSearchAccessWebLists";
/**
* Use features that launch client applications. Otherwise, users must work on documents
* locally and upload changes.
*/
PermissionKind[PermissionKind["UseClientIntegration"] = 37] = "UseClientIntegration";
/**
* Use SOAP, WebDAV, or Microsoft Office SharePoint Designer interfaces to access the Site.
*/
PermissionKind[PermissionKind["UseRemoteAPIs"] = 38] = "UseRemoteAPIs";
/**
* Manage alerts for all users of the Site.
*/
PermissionKind[PermissionKind["ManageAlerts"] = 39] = "ManageAlerts";
/**
* Create e-mail alerts.
*/
PermissionKind[PermissionKind["CreateAlerts"] = 40] = "CreateAlerts";
/**
* Allows a user to change his or her user information, such as adding a picture.
*/
PermissionKind[PermissionKind["EditMyUserInfo"] = 41] = "EditMyUserInfo";
/**
* Enumerate permissions on Site, list, folder, document, or list item.
*/
PermissionKind[PermissionKind["EnumeratePermissions"] = 63] = "EnumeratePermissions";
/**
* Has all permissions on the Site. Not available through the user interface.
*/
PermissionKind[PermissionKind["FullMask"] = 65] = "FullMask";
})(PermissionKind = exports.PermissionKind || (exports.PermissionKind = {}));
var PrincipalType;
(function (PrincipalType) {
PrincipalType[PrincipalType["None"] = 0] = "None";
PrincipalType[PrincipalType["User"] = 1] = "User";
PrincipalType[PrincipalType["DistributionList"] = 2] = "DistributionList";
PrincipalType[PrincipalType["SecurityGroup"] = 4] = "SecurityGroup";
PrincipalType[PrincipalType["SharePointGroup"] = 8] = "SharePointGroup";
PrincipalType[PrincipalType["All"] = 15] = "All";
})(PrincipalType = exports.PrincipalType || (exports.PrincipalType = {}));
var PrincipalSource;
(function (PrincipalSource) {
PrincipalSource[PrincipalSource["None"] = 0] = "None";
PrincipalSource[PrincipalSource["UserInfoList"] = 1] = "UserInfoList";
PrincipalSource[PrincipalSource["Windows"] = 2] = "Windows";
PrincipalSource[PrincipalSource["MembershipProvider"] = 4] = "MembershipProvider";
PrincipalSource[PrincipalSource["RoleProvider"] = 8] = "RoleProvider";
PrincipalSource[PrincipalSource["All"] = 15] = "All";
})(PrincipalSource = exports.PrincipalSource || (exports.PrincipalSource = {}));
var RoleType;
(function (RoleType) {
RoleType[RoleType["None"] = 0] = "None";
RoleType[RoleType["Guest"] = 1] = "Guest";
RoleType[RoleType["Reader"] = 2] = "Reader";
RoleType[RoleType["Contributor"] = 3] = "Contributor";
RoleType[RoleType["WebDesigner"] = 4] = "WebDesigner";
RoleType[RoleType["Administrator"] = 5] = "Administrator";
})(RoleType = exports.RoleType || (exports.RoleType = {}));
var PageType;
(function (PageType) {
PageType[PageType["Invalid"] = -1] = "Invalid";
PageType[PageType["DefaultView"] = 0] = "DefaultView";
PageType[PageType["NormalView"] = 1] = "NormalView";
PageType[PageType["DialogView"] = 2] = "DialogView";
PageType[PageType["View"] = 3] = "View";
PageType[PageType["DisplayForm"] = 4] = "DisplayForm";
PageType[PageType["DisplayFormDialog"] = 5] = "DisplayFormDialog";
PageType[PageType["EditForm"] = 6] = "EditForm";
PageType[PageType["EditFormDialog"] = 7] = "EditFormDialog";
PageType[PageType["NewForm"] = 8] = "NewForm";
PageType[PageType["NewFormDialog"] = 9] = "NewFormDialog";
PageType[PageType["SolutionForm"] = 10] = "SolutionForm";
PageType[PageType["PAGE_MAXITEMS"] = 11] = "PAGE_MAXITEMS";
})(PageType = exports.PageType || (exports.PageType = {}));
var SharingLinkKind;
(function (SharingLinkKind) {
/**
* Uninitialized link
*/
SharingLinkKind[SharingLinkKind["Uninitialized"] = 0] = "Uninitialized";
/**
* Direct link to the object being shared
*/
SharingLinkKind[SharingLinkKind["Direct"] = 1] = "Direct";
/**
* Organization-shareable link to the object being shared with view permissions
*/
SharingLinkKind[SharingLinkKind["OrganizationView"] = 2] = "OrganizationView";
/**
* Organization-shareable link to the object being shared with edit permissions
*/
SharingLinkKind[SharingLinkKind["OrganizationEdit"] = 3] = "OrganizationEdit";
/**
* View only anonymous link
*/
SharingLinkKind[SharingLinkKind["AnonymousView"] = 4] = "AnonymousView";
/**
* Read/Write anonymous link
*/
SharingLinkKind[SharingLinkKind["AnonymousEdit"] = 5] = "AnonymousEdit";
/**
* Flexible sharing Link where properties can change without affecting link URL
*/
SharingLinkKind[SharingLinkKind["Flexible"] = 6] = "Flexible";
})(SharingLinkKind = exports.SharingLinkKind || (exports.SharingLinkKind = {}));
;
/**
* Indicates the role of the sharing link
*/
var SharingRole;
(function (SharingRole) {
SharingRole[SharingRole["None"] = 0] = "None";
SharingRole[SharingRole["View"] = 1] = "View";
SharingRole[SharingRole["Edit"] = 2] = "Edit";
SharingRole[SharingRole["Owner"] = 3] = "Owner";
})(SharingRole = exports.SharingRole || (exports.SharingRole = {}));
var SharingOperationStatusCode;
(function (SharingOperationStatusCode) {
/**
* The share operation completed without errors.
*/
SharingOperationStatusCode[SharingOperationStatusCode["CompletedSuccessfully"] = 0] = "CompletedSuccessfully";
/**
* The share operation completed and generated requests for access.
*/
SharingOperationStatusCode[SharingOperationStatusCode["AccessRequestsQueued"] = 1] = "AccessRequestsQueued";
/**
* The share operation failed as there were no resolved users.
*/
SharingOperationStatusCode[SharingOperationStatusCode["NoResolvedUsers"] = -1] = "NoResolvedUsers";
/**
* The share operation failed due to insufficient permissions.
*/
SharingOperationStatusCode[SharingOperationStatusCode["AccessDenied"] = -2] = "AccessDenied";
/**
* The share operation failed when attempting a cross site share, which is not supported.
*/
SharingOperationStatusCode[SharingOperationStatusCode["CrossSiteRequestNotSupported"] = -3] = "CrossSiteRequestNotSupported";
/**
* The sharing operation failed due to an unknown error.
*/
SharingOperationStatusCode[SharingOperationStatusCode["UnknowError"] = -4] = "UnknowError";
/**
* The text you typed is too long. Please shorten it.
*/
SharingOperationStatusCode[SharingOperationStatusCode["EmailBodyTooLong"] = -5] = "EmailBodyTooLong";
/**
* The maximum number of unique scopes in the list has been exceeded.
*/
SharingOperationStatusCode[SharingOperationStatusCode["ListUniqueScopesExceeded"] = -6] = "ListUniqueScopesExceeded";
/**
* The share operation failed because a sharing capability is disabled in the site.
*/
SharingOperationStatusCode[SharingOperationStatusCode["CapabilityDisabled"] = -7] = "CapabilityDisabled";
/**
* The specified object for the share operation is not supported.
*/
SharingOperationStatusCode[SharingOperationStatusCode["ObjectNotSupported"] = -8] = "ObjectNotSupported";
/**
* A SharePoint group cannot contain another SharePoint group.
*/
SharingOperationStatusCode[SharingOperationStatusCode["NestedGroupsNotSupported"] = -9] = "NestedGroupsNotSupported";
})(SharingOperationStatusCode = exports.SharingOperationStatusCode || (exports.SharingOperationStatusCode = {}));
var SPSharedObjectType;
(function (SPSharedObjectType) {
SPSharedObjectType[SPSharedObjectType["Unknown"] = 0] = "Unknown";
SPSharedObjectType[SPSharedObjectType["File"] = 1] = "File";
SPSharedObjectType[SPSharedObjectType["Folder"] = 2] = "Folder";
SPSharedObjectType[SPSharedObjectType["Item"] = 3] = "Item";
SPSharedObjectType[SPSharedObjectType["List"] = 4] = "List";
SPSharedObjectType[SPSharedObjectType["Web"] = 5] = "Web";
SPSharedObjectType[SPSharedObjectType["Max"] = 6] = "Max";
})(SPSharedObjectType = exports.SPSharedObjectType || (exports.SPSharedObjectType = {}));
var SharingDomainRestrictionMode;
(function (SharingDomainRestrictionMode) {
SharingDomainRestrictionMode[SharingDomainRestrictionMode["None"] = 0] = "None";
SharingDomainRestrictionMode[SharingDomainRestrictionMode["AllowList"] = 1] = "AllowList";
SharingDomainRestrictionMode[SharingDomainRestrictionMode["BlockList"] = 2] = "BlockList";
})(SharingDomainRestrictionMode = exports.SharingDomainRestrictionMode || (exports.SharingDomainRestrictionMode = {}));
;
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var util_1 = __webpack_require__(0);
var collections_1 = __webpack_require__(6);
var pnplibconfig_1 = __webpack_require__(4);
/**
* A wrapper class to provide a consistent interface to browser based storage
*
*/
var PnPClientStorageWrapper = (function () {
/**
* Creates a new instance of the PnPClientStorageWrapper class
*
* @constructor
*/
function PnPClientStorageWrapper(store, defaultTimeoutMinutes) {
this.store = store;
this.defaultTimeoutMinutes = defaultTimeoutMinutes;
this.defaultTimeoutMinutes = (defaultTimeoutMinutes === void 0) ? -1 : defaultTimeoutMinutes;
this.enabled = this.test();
}
/**
* Get a value from storage, or null if that value does not exist
*
* @param key The key whose value we want to retrieve
*/
PnPClientStorageWrapper.prototype.get = function (key) {
if (!this.enabled) {
return null;
}
var o = this.store.getItem(key);
if (o == null) {
return null;
}
var persistable = JSON.parse(o);
if (new Date(persistable.expiration) <= new Date()) {
this.delete(key);
return null;
}
else {
return persistable.value;
}
};
/**
* Adds a value to the underlying storage
*
* @param key The key to use when storing the provided value
* @param o The value to store
* @param expire Optional, if provided the expiration of the item, otherwise the default is used
*/
PnPClientStorageWrapper.prototype.put = function (key, o, expire) {
if (this.enabled) {
this.store.setItem(key, this.createPersistable(o, expire));
}
};
/**
* Deletes a value from the underlying storage
*
* @param key The key of the pair we want to remove from storage
*/
PnPClientStorageWrapper.prototype.delete = function (key) {
if (this.enabled) {
this.store.removeItem(key);
}
};
/**
* Gets an item from the underlying storage, or adds it if it does not exist using the supplied getter function
*
* @param key The key to use when storing the provided value
* @param getter A function which will upon execution provide the desired value
* @param expire Optional, if provided the expiration of the item, otherwise the default is used
*/
PnPClientStorageWrapper.prototype.getOrPut = function (key, getter, expire) {
var _this = this;
if (!this.enabled) {
return getter();
}
return new Promise(function (resolve) {
var o = _this.get(key);
if (o == null) {
getter().then(function (d) {
_this.put(key, d, expire);
resolve(d);
});
}
else {
resolve(o);
}
});
};
/**
* Used to determine if the wrapped storage is available currently
*/
PnPClientStorageWrapper.prototype.test = function () {
var str = "test";
try {
this.store.setItem(str, str);
this.store.removeItem(str);
return true;
}
catch (e) {
return false;
}
};
/**
* Creates the persistable to store
*/
PnPClientStorageWrapper.prototype.createPersistable = function (o, expire) {
if (typeof expire === "undefined") {
// ensure we are by default inline with the global library setting
var defaultTimeout = pnplibconfig_1.RuntimeConfig.defaultCachingTimeoutSeconds;
if (this.defaultTimeoutMinutes > 0) {
defaultTimeout = this.defaultTimeoutMinutes * 60;
}
expire = util_1.Util.dateAdd(new Date(), "second", defaultTimeout);
}
return JSON.stringify({ expiration: expire, value: o });
};
return PnPClientStorageWrapper;
}());
exports.PnPClientStorageWrapper = PnPClientStorageWrapper;
/**
* A thin implementation of in-memory storage for use in nodejs
*/
var MemoryStorage = (function () {
function MemoryStorage(_store) {
if (_store === void 0) { _store = new collections_1.Dictionary(); }
this._store = _store;
}
Object.defineProperty(MemoryStorage.prototype, "length", {
get: function () {
return this._store.count();
},
enumerable: true,
configurable: true
});
MemoryStorage.prototype.clear = function () {
this._store.clear();
};
MemoryStorage.prototype.getItem = function (key) {
return this._store.get(key);
};
MemoryStorage.prototype.key = function (index) {
return this._store.getKeys()[index];
};
MemoryStorage.prototype.removeItem = function (key) {
this._store.remove(key);
};
MemoryStorage.prototype.setItem = function (key, data) {
this._store.add(key, data);
};
return MemoryStorage;
}());
/**
* A class that will establish wrappers for both local and session storage
*/
var PnPClientStorage = (function () {
/**
* Creates a new instance of the PnPClientStorage class
*
* @constructor
*/
function PnPClientStorage() {
this.local = typeof localStorage !== "undefined" ? new PnPClientStorageWrapper(localStorage) : new PnPClientStorageWrapper(new MemoryStorage());
this.session = typeof sessionStorage !== "undefined" ? new PnPClientStorageWrapper(sessionStorage) : new PnPClientStorageWrapper(new MemoryStorage());
}
return PnPClientStorage;
}());
exports.PnPClientStorage = PnPClientStorage;
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var digestcache_1 = __webpack_require__(38);
var util_1 = __webpack_require__(0);
var pnplibconfig_1 = __webpack_require__(4);
var exceptions_1 = __webpack_require__(3);
var HttpClient = (function () {
function HttpClient() {
this._impl = pnplibconfig_1.RuntimeConfig.fetchClientFactory();
this._digestCache = new digestcache_1.DigestCache(this);
}
HttpClient.prototype.fetch = function (url, options) {
var _this = this;
if (options === void 0) { options = {}; }
var opts = util_1.Util.extend(options, { cache: "no-cache", credentials: "same-origin" }, true);
var headers = new Headers();
// first we add the global headers so they can be overwritten by any passed in locally to this call
this.mergeHeaders(headers, pnplibconfig_1.RuntimeConfig.headers);
// second we add the local options so we can overwrite the globals
this.mergeHeaders(headers, options.headers);
// lastly we apply any default headers we need that may not exist
if (!headers.has("Accept")) {
headers.append("Accept", "application/json");
}
if (!headers.has("Content-Type")) {
headers.append("Content-Type", "application/json;odata=verbose;charset=utf-8");
}
if (!headers.has("X-ClientService-ClientTag")) {
headers.append("X-ClientService-ClientTag", "PnPCoreJS:2.0.6-beta.1");
}
opts = util_1.Util.extend(opts, { headers: headers });
if (opts.method && opts.method.toUpperCase() !== "GET") {
if (!headers.has("X-RequestDigest")) {
var index = url.indexOf("_api/");
if (index < 0) {
throw new exceptions_1.APIUrlException();
}
var webUrl = url.substr(0, index);
return this._digestCache.getDigest(webUrl)
.then(function (digest) {
headers.append("X-RequestDigest", digest);
return _this.fetchRaw(url, opts);
});
}
}
return this.fetchRaw(url, opts);
};
HttpClient.prototype.fetchRaw = function (url, options) {
var _this = this;
if (options === void 0) { options = {}; }
// here we need to normalize the headers
var rawHeaders = new Headers();
this.mergeHeaders(rawHeaders, options.headers);
options = util_1.Util.extend(options, { headers: rawHeaders });
var retry = function (ctx) {
_this._impl.fetch(url, options).then(function (response) { return ctx.resolve(response); }).catch(function (response) {
// grab our current delay
var delay = ctx.delay;
// Check if request was throttled - http status code 429
// Check is request failed due to server unavailable - http status code 503
if (response.status !== 429 && response.status !== 503) {
ctx.reject(response);
}
// Increment our counters.
ctx.delay *= 2;
ctx.attempts++;
// If we have exceeded the retry count, reject.
if (ctx.retryCount <= ctx.attempts) {
ctx.reject(response);
}
// Set our retry timeout for {delay} milliseconds.
setTimeout(util_1.Util.getCtxCallback(_this, retry, ctx), delay);
});
};
return new Promise(function (resolve, reject) {
var retryContext = {
attempts: 0,
delay: 100,
reject: reject,
resolve: resolve,
retryCount: 7,
};
retry.call(_this, retryContext);
});
};
HttpClient.prototype.get = function (url, options) {
if (options === void 0) { options = {}; }
var opts = util_1.Util.extend(options, { method: "GET" });
return this.fetch(url, opts);
};
HttpClient.prototype.post = function (url, options) {
if (options === void 0) { options = {}; }
var opts = util_1.Util.extend(options, { method: "POST" });
return this.fetch(url, opts);
};
HttpClient.prototype.patch = function (url, options) {
if (options === void 0) { options = {}; }
var opts = util_1.Util.extend(options, { method: "PATCH" });
return this.fetch(url, opts);
};
HttpClient.prototype.delete = function (url, options) {
if (options === void 0) { options = {}; }
var opts = util_1.Util.extend(options, { method: "DELETE" });
return this.fetch(url, opts);
};
HttpClient.prototype.mergeHeaders = function (target, source) {
if (typeof source !== "undefined" && source !== null) {
var temp = new Request("", { headers: source });
temp.headers.forEach(function (value, name) {
target.append(name, value);
});
}
};
return HttpClient;
}());
exports.HttpClient = HttpClient;
;
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 util_1 = __webpack_require__(0);
var queryable_1 = __webpack_require__(1);
/**
* Describes a collection of content types
*
*/
var ContentTypes = (function (_super) {
__extends(ContentTypes, _super);
/**
* Creates a new instance of the ContentTypes class
*
* @param baseUrl The url or Queryable which forms the parent of this content types collection
*/
function ContentTypes(baseUrl, path) {
if (path === void 0) { path = "contenttypes"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a ContentType by content type id
*/
ContentTypes.prototype.getById = function (id) {
var ct = new ContentType(this);
ct.concat("('" + id + "')");
return ct;
};
/**
* Adds an existing contenttype to a content type collection
*
* @param contentTypeId in the following format, for example: 0x010102
*/
ContentTypes.prototype.addAvailableContentType = function (contentTypeId) {
var _this = this;
var postBody = JSON.stringify({
"contentTypeId": contentTypeId,
});
return this.clone(ContentTypes, "addAvailableContentType", true).postAs({ body: postBody }).then(function (data) {
return {
contentType: _this.getById(data.id),
data: data,
};
});
};
/**
* Adds a new content type to the collection
*
* @param id The desired content type id for the new content type (also determines the parent content type)
* @param name The name of the content type
* @param description The description of the content type
* @param group The group in which to add the content type
* @param additionalSettings Any additional settings to provide when creating the content type
*
*/
ContentTypes.prototype.add = function (id, name, description, group, additionalSettings) {
var _this = this;
if (description === void 0) { description = ""; }
if (group === void 0) { group = "Custom Content Types"; }
if (additionalSettings === void 0) { additionalSettings = {}; }
var postBody = JSON.stringify(util_1.Util.extend({
"Description": description,
"Group": group,
"Id": { "StringValue": id },
"Name": name,
"__metadata": { "type": "SP.ContentType" },
}, additionalSettings));
return this.post({ body: postBody }).then(function (data) {
return { contentType: _this.getById(data.id), data: data };
});
};
return ContentTypes;
}(queryable_1.QueryableCollection));
exports.ContentTypes = ContentTypes;
/**
* Describes a single ContentType instance
*
*/
var ContentType = (function (_super) {
__extends(ContentType, _super);
function ContentType() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(ContentType.prototype, "fieldLinks", {
/**
* Gets the column (also known as field) references in the content type.
*/
get: function () {
return new FieldLinks(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(ContentType.prototype, "fields", {
/**
* Gets a value that specifies the collection of fields for the content type.
*/
get: function () {
return new queryable_1.QueryableCollection(this, "fields");
},
enumerable: true,
configurable: true
});
Object.defineProperty(ContentType.prototype, "parent", {
/**
* Gets the parent content type of the content type.
*/
get: function () {
return new ContentType(this, "parent");
},
enumerable: true,
configurable: true
});
Object.defineProperty(ContentType.prototype, "workflowAssociations", {
/**
* Gets a value that specifies the collection of workflow associations for the content type.
*/
get: function () {
return new queryable_1.QueryableCollection(this, "workflowAssociations");
},
enumerable: true,
configurable: true
});
/**
* Delete this content type
*/
ContentType.prototype.delete = function () {
return this.post({
headers: {
"X-HTTP-Method": "DELETE",
},
});
};
return ContentType;
}(queryable_1.QueryableInstance));
exports.ContentType = ContentType;
/**
* Represents a collection of field link instances
*/
var FieldLinks = (function (_super) {
__extends(FieldLinks, _super);
/**
* Creates a new instance of the ContentType class
*
* @param baseUrl The url or Queryable which forms the parent of this content type instance
*/
function FieldLinks(baseUrl, path) {
if (path === void 0) { path = "fieldlinks"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a FieldLink by GUID id
*
* @param id The GUID id of the field link
*/
FieldLinks.prototype.getById = function (id) {
var fl = new FieldLink(this);
fl.concat("(guid'" + id + "')");
return fl;
};
return FieldLinks;
}(queryable_1.QueryableCollection));
exports.FieldLinks = FieldLinks;
/**
* Represents a field link instance
*/
var FieldLink = (function (_super) {
__extends(FieldLink, _super);
function FieldLink() {
return _super !== null && _super.apply(this, arguments) || this;
}
return FieldLink;
}(queryable_1.QueryableInstance));
exports.FieldLink = FieldLink;
/***/ }),
/* 17 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 queryable_1 = __webpack_require__(1);
var sitegroups_1 = __webpack_require__(18);
var util_1 = __webpack_require__(0);
/**
* Describes a set of role assignments for the current scope
*
*/
var RoleAssignments = (function (_super) {
__extends(RoleAssignments, _super);
/**
* Creates a new instance of the RoleAssignments class
*
* @param baseUrl The url or Queryable which forms the parent of this fields collection
*/
function RoleAssignments(baseUrl, path) {
if (path === void 0) { path = "roleassignments"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Adds a new role assignment with the specified principal and role definitions to the collection.
*
* @param principalId The ID of the user or group to assign permissions to
* @param roleDefId The ID of the role definition that defines the permissions to assign
*
*/
RoleAssignments.prototype.add = function (principalId, roleDefId) {
return this.clone(RoleAssignments, "addroleassignment(principalid=" + principalId + ", roledefid=" + roleDefId + ")", true).post();
};
/**
* Removes the role assignment with the specified principal and role definition from the collection
*
* @param principalId The ID of the user or group in the role assignment.
* @param roleDefId The ID of the role definition in the role assignment
*
*/
RoleAssignments.prototype.remove = function (principalId, roleDefId) {
return this.clone(RoleAssignments, "removeroleassignment(principalid=" + principalId + ", roledefid=" + roleDefId + ")", true).post();
};
/**
* Gets the role assignment associated with the specified principal ID from the collection.
*
* @param id The id of the role assignment
*/
RoleAssignments.prototype.getById = function (id) {
var ra = new RoleAssignment(this);
ra.concat("(" + id + ")");
return ra;
};
return RoleAssignments;
}(queryable_1.QueryableCollection));
exports.RoleAssignments = RoleAssignments;
var RoleAssignment = (function (_super) {
__extends(RoleAssignment, _super);
function RoleAssignment() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(RoleAssignment.prototype, "groups", {
get: function () {
return new sitegroups_1.SiteGroups(this, "groups");
},
enumerable: true,
configurable: true
});
Object.defineProperty(RoleAssignment.prototype, "bindings", {
/**
* Get the role definition bindings for this role assignment
*
*/
get: function () {
return new RoleDefinitionBindings(this);
},
enumerable: true,
configurable: true
});
/**
* Delete this role assignment
*
*/
RoleAssignment.prototype.delete = function () {
return this.post({
headers: {
"X-HTTP-Method": "DELETE",
},
});
};
return RoleAssignment;
}(queryable_1.QueryableInstance));
exports.RoleAssignment = RoleAssignment;
var RoleDefinitions = (function (_super) {
__extends(RoleDefinitions, _super);
/**
* Creates a new instance of the RoleDefinitions class
*
* @param baseUrl The url or Queryable which forms the parent of this fields collection
* @param path
*
*/
function RoleDefinitions(baseUrl, path) {
if (path === void 0) { path = "roledefinitions"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets the role definition with the specified ID from the collection.
*
* @param id The ID of the role definition.
*
*/
RoleDefinitions.prototype.getById = function (id) {
return new RoleDefinition(this, "getById(" + id + ")");
};
/**
* Gets the role definition with the specified name.
*
* @param name The name of the role definition.
*
*/
RoleDefinitions.prototype.getByName = function (name) {
return new RoleDefinition(this, "getbyname('" + name + "')");
};
/**
* Gets the role definition with the specified type.
*
* @param name The name of the role definition.
*
*/
RoleDefinitions.prototype.getByType = function (roleTypeKind) {
return new RoleDefinition(this, "getbytype(" + roleTypeKind + ")");
};
/**
* Create a role definition
*
* @param name The new role definition's name
* @param description The new role definition's description
* @param order The order in which the role definition appears
* @param basePermissions The permissions mask for this role definition
*
*/
RoleDefinitions.prototype.add = function (name, description, order, basePermissions) {
var _this = this;
var postBody = JSON.stringify({
BasePermissions: util_1.Util.extend({ __metadata: { type: "SP.BasePermissions" } }, basePermissions),
Description: description,
Name: name,
Order: order,
__metadata: { "type": "SP.RoleDefinition" },
});
return this.post({ body: postBody }).then(function (data) {
return {
data: data,
definition: _this.getById(data.Id),
};
});
};
return RoleDefinitions;
}(queryable_1.QueryableCollection));
exports.RoleDefinitions = RoleDefinitions;
var RoleDefinition = (function (_super) {
__extends(RoleDefinition, _super);
function RoleDefinition() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Updates this web intance with the supplied properties
*
* @param properties A plain object hash of values to update for the web
*/
/* tslint:disable no-string-literal */
RoleDefinition.prototype.update = function (properties) {
var _this = this;
if (typeof properties.hasOwnProperty("BasePermissions") !== "undefined") {
properties["BasePermissions"] = util_1.Util.extend({ __metadata: { type: "SP.BasePermissions" } }, properties["BasePermissions"]);
}
var postBody = JSON.stringify(util_1.Util.extend({
"__metadata": { "type": "SP.RoleDefinition" },
}, properties));
return this.post({
body: postBody,
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
var retDef = _this;
if (properties.hasOwnProperty("Name")) {
var parent_1 = _this.getParent(RoleDefinitions, _this.parentUrl, "");
retDef = parent_1.getByName(properties["Name"]);
}
return {
data: data,
definition: retDef,
};
});
};
/* tslint:enable */
/**
* Delete this role definition
*
*/
RoleDefinition.prototype.delete = function () {
return this.post({
headers: {
"X-HTTP-Method": "DELETE",
},
});
};
return RoleDefinition;
}(queryable_1.QueryableInstance));
exports.RoleDefinition = RoleDefinition;
var RoleDefinitionBindings = (function (_super) {
__extends(RoleDefinitionBindings, _super);
function RoleDefinitionBindings(baseUrl, path) {
if (path === void 0) { path = "roledefinitionbindings"; }
return _super.call(this, baseUrl, path) || this;
}
return RoleDefinitionBindings;
}(queryable_1.QueryableCollection));
exports.RoleDefinitionBindings = RoleDefinitionBindings;
/***/ }),
/* 18 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 queryable_1 = __webpack_require__(1);
var siteusers_1 = __webpack_require__(30);
var util_1 = __webpack_require__(0);
/**
* Principal Type enum
*
*/
var PrincipalType;
(function (PrincipalType) {
PrincipalType[PrincipalType["None"] = 0] = "None";
PrincipalType[PrincipalType["User"] = 1] = "User";
PrincipalType[PrincipalType["DistributionList"] = 2] = "DistributionList";
PrincipalType[PrincipalType["SecurityGroup"] = 4] = "SecurityGroup";
PrincipalType[PrincipalType["SharePointGroup"] = 8] = "SharePointGroup";
PrincipalType[PrincipalType["All"] = 15] = "All";
})(PrincipalType = exports.PrincipalType || (exports.PrincipalType = {}));
/**
* Describes a collection of site groups
*
*/
var SiteGroups = (function (_super) {
__extends(SiteGroups, _super);
/**
* Creates a new instance of the SiteGroups class
*
* @param baseUrl The url or Queryable which forms the parent of this group collection
*/
function SiteGroups(baseUrl, path) {
if (path === void 0) { path = "sitegroups"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Adds a new group to the site collection
*
* @param props The group properties object of property names and values to be set for the group
*/
SiteGroups.prototype.add = function (properties) {
var _this = this;
var postBody = JSON.stringify(util_1.Util.extend({ "__metadata": { "type": "SP.Group" } }, properties));
return this.post({ body: postBody }).then(function (data) {
return {
data: data,
group: _this.getById(data.Id),
};
});
};
/**
* Gets a group from the collection by name
*
* @param groupName The name of the group to retrieve
*/
SiteGroups.prototype.getByName = function (groupName) {
return new SiteGroup(this, "getByName('" + groupName + "')");
};
/**
* Gets a group from the collection by id
*
* @param id The id of the group to retrieve
*/
SiteGroups.prototype.getById = function (id) {
var sg = new SiteGroup(this);
sg.concat("(" + id + ")");
return sg;
};
/**
* Removes the group with the specified member id from the collection
*
* @param id The id of the group to remove
*/
SiteGroups.prototype.removeById = function (id) {
return this.clone(SiteGroups, "removeById('" + id + "')", true).post();
};
/**
* Removes the cross-site group with the specified name from the collection
*
* @param loginName The name of the group to remove
*/
SiteGroups.prototype.removeByLoginName = function (loginName) {
return this.clone(SiteGroups, "removeByLoginName('" + loginName + "')", true).post();
};
return SiteGroups;
}(queryable_1.QueryableCollection));
exports.SiteGroups = SiteGroups;
/**
* Describes a single group
*
*/
var SiteGroup = (function (_super) {
__extends(SiteGroup, _super);
function SiteGroup() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(SiteGroup.prototype, "users", {
/**
* Gets the users for this group
*
*/
get: function () {
return new siteusers_1.SiteUsers(this, "users");
},
enumerable: true,
configurable: true
});
/**
* Updates this group instance with the supplied properties
*
* @param properties A GroupWriteableProperties object of property names and values to update for the group
*/
/* tslint:disable no-string-literal */
SiteGroup.prototype.update = function (properties) {
var _this = this;
var postBody = util_1.Util.extend({ "__metadata": { "type": "SP.Group" } }, properties);
return this.post({
body: JSON.stringify(postBody),
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
var retGroup = _this;
if (properties.hasOwnProperty("Title")) {
retGroup = _this.getParent(SiteGroup, _this.parentUrl, "getByName('" + properties["Title"] + "')");
}
return {
data: data,
group: retGroup,
};
});
};
return SiteGroup;
}(queryable_1.QueryableInstance));
exports.SiteGroup = SiteGroup;
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 queryable_1 = __webpack_require__(1);
var util_1 = __webpack_require__(0);
/**
* Describes a collection of user custom actions
*
*/
var UserCustomActions = (function (_super) {
__extends(UserCustomActions, _super);
/**
* Creates a new instance of the UserCustomActions class
*
* @param baseUrl The url or Queryable which forms the parent of this user custom actions collection
*/
function UserCustomActions(baseUrl, path) {
if (path === void 0) { path = "usercustomactions"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Returns the user custom action with the specified id
*
* @param id The GUID id of the user custom action to retrieve
*/
UserCustomActions.prototype.getById = function (id) {
var uca = new UserCustomAction(this);
uca.concat("('" + id + "')");
return uca;
};
/**
* Creates a user custom action
*
* @param properties The information object of property names and values which define the new user custom action
*
*/
UserCustomActions.prototype.add = function (properties) {
var _this = this;
var postBody = JSON.stringify(util_1.Util.extend({ __metadata: { "type": "SP.UserCustomAction" } }, properties));
return this.post({ body: postBody }).then(function (data) {
return {
action: _this.getById(data.Id),
data: data,
};
});
};
/**
* Deletes all user custom actions in the collection
*
*/
UserCustomActions.prototype.clear = function () {
return this.clone(UserCustomActions, "clear", true).post();
};
return UserCustomActions;
}(queryable_1.QueryableCollection));
exports.UserCustomActions = UserCustomActions;
/**
* Describes a single user custom action
*
*/
var UserCustomAction = (function (_super) {
__extends(UserCustomAction, _super);
function UserCustomAction() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Updates this user custom action with the supplied properties
*
* @param properties An information object of property names and values to update for this user custom action
*/
UserCustomAction.prototype.update = function (properties) {
var _this = this;
var postBody = JSON.stringify(util_1.Util.extend({
"__metadata": { "type": "SP.UserCustomAction" },
}, properties));
return this.post({
body: postBody,
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
return {
action: _this,
data: data,
};
});
};
/**
* Removes this user custom action
*
*/
UserCustomAction.prototype.delete = function () {
return _super.prototype.delete.call(this);
};
return UserCustomAction;
}(queryable_1.QueryableInstance));
exports.UserCustomAction = UserCustomAction;
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var storage = __webpack_require__(14);
var exceptions_1 = __webpack_require__(3);
/**
* A caching provider which can wrap other non-caching providers
*
*/
var CachingConfigurationProvider = (function () {
/**
* Creates a new caching configuration provider
* @constructor
* @param {IConfigurationProvider} wrappedProvider Provider which will be used to fetch the configuration
* @param {string} cacheKey Key that will be used to store cached items to the cache
* @param {IPnPClientStore} cacheStore OPTIONAL storage, which will be used to store cached settings.
*/
function CachingConfigurationProvider(wrappedProvider, cacheKey, cacheStore) {
this.wrappedProvider = wrappedProvider;
this.store = (cacheStore) ? cacheStore : this.selectPnPCache();
this.cacheKey = "_configcache_" + cacheKey;
}
/**
* Gets the wrapped configuration providers
*
* @return {IConfigurationProvider} Wrapped configuration provider
*/
CachingConfigurationProvider.prototype.getWrappedProvider = function () {
return this.wrappedProvider;
};
/**
* Loads the configuration values either from the cache or from the wrapped provider
*
* @return {Promise<TypedHash<string>>} Promise of loaded configuration values
*/
CachingConfigurationProvider.prototype.getConfiguration = function () {
var _this = this;
// Cache not available, pass control to the wrapped provider
if ((!this.store) || (!this.store.enabled)) {
return this.wrappedProvider.getConfiguration();
}
// Value is found in cache, return it directly
var cachedConfig = this.store.get(this.cacheKey);
if (cachedConfig) {
return new Promise(function (resolve) {
resolve(cachedConfig);
});
}
// Get and cache value from the wrapped provider
var providerPromise = this.wrappedProvider.getConfiguration();
providerPromise.then(function (providedConfig) {
_this.store.put(_this.cacheKey, providedConfig);
});
return providerPromise;
};
CachingConfigurationProvider.prototype.selectPnPCache = function () {
var pnpCache = new storage.PnPClientStorage();
if ((pnpCache.local) && (pnpCache.local.enabled)) {
return pnpCache.local;
}
if ((pnpCache.session) && (pnpCache.session.enabled)) {
return pnpCache.session;
}
throw new exceptions_1.NoCacheAvailableException();
};
return CachingConfigurationProvider;
}());
exports.default = CachingConfigurationProvider;
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Makes requests using the fetch API
*/
var FetchClient = (function () {
function FetchClient() {
}
FetchClient.prototype.fetch = function (url, options) {
return global.fetch(url, options);
};
return FetchClient;
}());
exports.FetchClient = FetchClient;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(32)))
/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var storage_1 = __webpack_require__(14);
var util_1 = __webpack_require__(0);
var pnplibconfig_1 = __webpack_require__(4);
var CachingOptions = (function () {
function CachingOptions(key) {
this.key = key;
this.expiration = util_1.Util.dateAdd(new Date(), "second", pnplibconfig_1.RuntimeConfig.defaultCachingTimeoutSeconds);
this.storeName = pnplibconfig_1.RuntimeConfig.defaultCachingStore;
}
Object.defineProperty(CachingOptions.prototype, "store", {
get: function () {
if (this.storeName === "local") {
return CachingOptions.storage.local;
}
else {
return CachingOptions.storage.session;
}
},
enumerable: true,
configurable: true
});
return CachingOptions;
}());
CachingOptions.storage = new storage_1.PnPClientStorage();
exports.CachingOptions = CachingOptions;
var CachingParserWrapper = (function () {
function CachingParserWrapper(_parser, _cacheOptions) {
this._parser = _parser;
this._cacheOptions = _cacheOptions;
}
CachingParserWrapper.prototype.parse = function (response) {
var _this = this;
// add this to the cache based on the options
return this._parser.parse(response).then(function (data) {
if (_this._cacheOptions.store !== null) {
_this._cacheOptions.store.put(_this._cacheOptions.key, data, _this._cacheOptions.expiration);
}
return data;
});
};
return CachingParserWrapper;
}());
exports.CachingParserWrapper = CachingParserWrapper;
/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 queryable_1 = __webpack_require__(1);
/**
* Describes a collection of List objects
*
*/
var Features = (function (_super) {
__extends(Features, _super);
/**
* Creates a new instance of the Lists class
*
* @param baseUrl The url or Queryable which forms the parent of this fields collection
*/
function Features(baseUrl, path) {
if (path === void 0) { path = "features"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a list from the collection by guid id
*
* @param id The Id of the feature (GUID)
*/
Features.prototype.getById = function (id) {
var feature = new Feature(this);
feature.concat("('" + id + "')");
return feature;
};
/**
* Adds a new list to the collection
*
* @param id The Id of the feature (GUID)
* @param force If true the feature activation will be forced
*/
Features.prototype.add = function (id, force) {
var _this = this;
if (force === void 0) { force = false; }
return this.clone(Features, "add", true).post({
body: JSON.stringify({
featdefScope: 0,
featureId: id,
force: force,
}),
}).then(function (data) {
return {
data: data,
feature: _this.getById(id),
};
});
};
/**
* Removes (deactivates) a feature from the collection
*
* @param id The Id of the feature (GUID)
* @param force If true the feature deactivation will be forced
*/
Features.prototype.remove = function (id, force) {
if (force === void 0) { force = false; }
return this.clone(Features, "remove", true).post({
body: JSON.stringify({
featureId: id,
force: force,
}),
});
};
return Features;
}(queryable_1.QueryableCollection));
exports.Features = Features;
var Feature = (function (_super) {
__extends(Feature, _super);
function Feature() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Removes (deactivates) a feature from the collection
*
* @param force If true the feature deactivation will be forced
*/
Feature.prototype.deactivate = function (force) {
var _this = this;
if (force === void 0) { force = false; }
var removeDependency = this.addBatchDependency();
var idGet = new Feature(this).select("DefinitionId");
return idGet.getAs().then(function (feature) {
var promise = _this.getParent(Features, _this.parentUrl, "", _this.batch).remove(feature.DefinitionId, force);
removeDependency();
return promise;
});
};
return Feature;
}(queryable_1.QueryableInstance));
exports.Feature = Feature;
/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 queryable_1 = __webpack_require__(1);
var util_1 = __webpack_require__(0);
var types_1 = __webpack_require__(13);
/**
* Describes a collection of Field objects
*
*/
var Fields = (function (_super) {
__extends(Fields, _super);
/**
* Creates a new instance of the Fields class
*
* @param baseUrl The url or Queryable which forms the parent of this fields collection
*/
function Fields(baseUrl, path) {
if (path === void 0) { path = "fields"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a field from the collection by title
*
* @param title The case-sensitive title of the field
*/
Fields.prototype.getByTitle = function (title) {
return new Field(this, "getByTitle('" + title + "')");
};
/**
* Gets a field from the collection by using internal name or title
*
* @param name The case-sensitive internal name or title of the field
*/
Fields.prototype.getByInternalNameOrTitle = function (name) {
return new Field(this, "getByInternalNameOrTitle('" + name + "')");
};
/**
* Gets a list from the collection by guid id
*
* @param title The Id of the list
*/
Fields.prototype.getById = function (id) {
var f = new Field(this);
f.concat("('" + id + "')");
return f;
};
/**
* Creates a field based on the specified schema
*/
Fields.prototype.createFieldAsXml = function (xml) {
var _this = this;
var info;
if (typeof xml === "string") {
info = { SchemaXml: xml };
}
else {
info = xml;
}
var postBody = JSON.stringify({
"parameters": util_1.Util.extend({
"__metadata": {
"type": "SP.XmlSchemaFieldCreationInformation",
},
}, info),
});
return this.clone(Fields, "createfieldasxml", true).postAs({ body: postBody }).then(function (data) {
return {
data: data,
field: _this.getById(data.Id),
};
});
};
/**
* Adds a new list to the collection
*
* @param title The new field's title
* @param fieldType The new field's type (ex: SP.FieldText)
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.add = function (title, fieldType, properties) {
var _this = this;
if (properties === void 0) { properties = {}; }
var postBody = JSON.stringify(util_1.Util.extend({
"Title": title,
"__metadata": { "type": fieldType },
}, properties));
return this.clone(Fields, null, true).postAs({ body: postBody }).then(function (data) {
return {
data: data,
field: _this.getById(data.Id),
};
});
};
/**
* Adds a new SP.FieldText to the collection
*
* @param title The field title
* @param maxLength The maximum number of characters allowed in the value of the field.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addText = function (title, maxLength, properties) {
if (maxLength === void 0) { maxLength = 255; }
var props = {
FieldTypeKind: 2,
MaxLength: maxLength,
};
return this.add(title, "SP.FieldText", util_1.Util.extend(props, properties));
};
/**
* Adds a new SP.FieldCalculated to the collection
*
* @param title The field title.
* @param formula The formula for the field.
* @param dateFormat The date and time format that is displayed in the field.
* @param outputType Specifies the output format for the field. Represents a FieldType value.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addCalculated = function (title, formula, dateFormat, outputType, properties) {
if (outputType === void 0) { outputType = types_1.FieldTypes.Text; }
var props = {
DateFormat: dateFormat,
FieldTypeKind: 17,
Formula: formula,
OutputType: outputType,
};
return this.add(title, "SP.FieldCalculated", util_1.Util.extend(props, properties));
};
/**
* Adds a new SP.FieldDateTime to the collection
*
* @param title The field title
* @param displayFormat The format of the date and time that is displayed in the field.
* @param calendarType Specifies the calendar type of the field.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addDateTime = function (title, displayFormat, calendarType, friendlyDisplayFormat, properties) {
if (displayFormat === void 0) { displayFormat = types_1.DateTimeFieldFormatType.DateOnly; }
if (calendarType === void 0) { calendarType = types_1.CalendarType.Gregorian; }
if (friendlyDisplayFormat === void 0) { friendlyDisplayFormat = 0; }
var props = {
DateTimeCalendarType: calendarType,
DisplayFormat: displayFormat,
FieldTypeKind: 4,
FriendlyDisplayFormat: friendlyDisplayFormat,
};
return this.add(title, "SP.FieldDateTime", util_1.Util.extend(props, properties));
};
/**
* Adds a new SP.FieldNumber to the collection
*
* @param title The field title
* @param minValue The field's minimum value
* @param maxValue The field's maximum value
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addNumber = function (title, minValue, maxValue, properties) {
var props = { FieldTypeKind: 9 };
if (typeof minValue !== "undefined") {
props = util_1.Util.extend({ MinimumValue: minValue }, props);
}
if (typeof maxValue !== "undefined") {
props = util_1.Util.extend({ MaximumValue: maxValue }, props);
}
return this.add(title, "SP.FieldNumber", util_1.Util.extend(props, properties));
};
/**
* Adds a new SP.FieldCurrency to the collection
*
* @param title The field title
* @param minValue The field's minimum value
* @param maxValue The field's maximum value
* @param currencyLocalId Specifies the language code identifier (LCID) used to format the value of the field
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*/
Fields.prototype.addCurrency = function (title, minValue, maxValue, currencyLocalId, properties) {
if (currencyLocalId === void 0) { currencyLocalId = 1033; }
var props = {
CurrencyLocaleId: currencyLocalId,
FieldTypeKind: 10,
};
if (typeof minValue !== "undefined") {
props = util_1.Util.extend({ MinimumValue: minValue }, props);
}
if (typeof maxValue !== "undefined") {
props = util_1.Util.extend({ MaximumValue: maxValue }, props);
}
return this.add(title, "SP.FieldCurrency", util_1.Util.extend(props, properties));
};
/**
* Adds a new SP.FieldMultiLineText to the collection
*
* @param title The field title
* @param numberOfLines Specifies the number of lines of text to display for the field.
* @param richText Specifies whether the field supports rich formatting.
* @param restrictedMode Specifies whether the field supports a subset of rich formatting.
* @param appendOnly Specifies whether all changes to the value of the field are displayed in list forms.
* @param allowHyperlink Specifies whether a hyperlink is allowed as a value of the field.
* @param properties Differ by type of field being created (see: https://msdn.microsoft.com/en-us/library/office/dn600182.aspx)
*
*/
Fields.prototype.addMultilineText = function (title, numberOfLines, richText, restrictedMode, appendOnly, allowHyperlink, properties) {
if (numberOfLines === void 0) { numberOfLines = 6; }
if (richText === void 0) { richText = true; }
if (restrictedMode === void 0) { restrictedMode = false; }
if (appendOnly === void 0) { appendOnly = false; }
if (allowHyperlink === void 0) { allowHyperlink = true; }
var props = {
AllowHyperlink: allowHyperlink,
AppendOnly: appendOnly,
FieldTypeKind: 3,
NumberOfLines: numberOfLines,
RestrictedMode: restrictedMode,
RichText: richText,
};
return this.add(title, "SP.FieldMultiLineText", util_1.Util.extend(props, properties));
};
/**
* Adds a new SP.FieldUrl to the collection
*
* @param title The field title
*/
Fields.prototype.addUrl = function (title, displayFormat, properties) {
if (displayFormat === void 0) { displayFormat = types_1.UrlFieldFormatType.Hyperlink; }
var props = {
DisplayFormat: displayFormat,
FieldTypeKind: 11,
};
return this.add(title, "SP.FieldUrl", util_1.Util.extend(props, properties));
};
return Fields;
}(queryable_1.QueryableCollection));
exports.Fields = Fields;
/**
* Describes a single of Field instance
*
*/
var Field = (function (_super) {
__extends(Field, _super);
function Field() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Updates this field intance with the supplied properties
*
* @param properties A plain object hash of values to update for the list
* @param fieldType The type value, required to update child field type properties
*/
Field.prototype.update = function (properties, fieldType) {
var _this = this;
if (fieldType === void 0) { fieldType = "SP.Field"; }
var postBody = JSON.stringify(util_1.Util.extend({
"__metadata": { "type": fieldType },
}, properties));
return this.post({
body: postBody,
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
return {
data: data,
field: _this,
};
});
};
/**
* Delete this fields
*
*/
Field.prototype.delete = function () {
return this.post({
headers: {
"X-HTTP-Method": "DELETE",
},
});
};
/**
* Sets the value of the ShowInDisplayForm property for this field.
*/
Field.prototype.setShowInDisplayForm = function (show) {
return this.clone(Field, "setshowindisplayform(" + show + ")", true).post();
};
/**
* Sets the value of the ShowInEditForm property for this field.
*/
Field.prototype.setShowInEditForm = function (show) {
return this.clone(Field, "setshowineditform(" + show + ")", true).post();
};
/**
* Sets the value of the ShowInNewForm property for this field.
*/
Field.prototype.setShowInNewForm = function (show) {
return this.clone(Field, "setshowinnewform(" + show + ")", true).post();
};
return Field;
}(queryable_1.QueryableInstance));
exports.Field = Field;
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 util_1 = __webpack_require__(0);
var queryable_1 = __webpack_require__(1);
/**
* Represents a collection of navigation nodes
*
*/
var NavigationNodes = (function (_super) {
__extends(NavigationNodes, _super);
function NavigationNodes() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a navigation node by id
*
* @param id The id of the node
*/
NavigationNodes.prototype.getById = function (id) {
var node = new NavigationNode(this);
node.concat("(" + id + ")");
return node;
};
/**
* Adds a new node to the collection
*
* @param title Display name of the node
* @param url The url of the node
* @param visible If true the node is visible, otherwise it is hidden (default: true)
*/
NavigationNodes.prototype.add = function (title, url, visible) {
var _this = this;
if (visible === void 0) { visible = true; }
var postBody = JSON.stringify({
IsVisible: visible,
Title: title,
Url: url,
"__metadata": { "type": "SP.NavigationNode" },
});
return this.clone(NavigationNodes, null, true).post({ body: postBody }).then(function (data) {
return {
data: data,
node: _this.getById(data.Id),
};
});
};
/**
* Moves a node to be after another node in the navigation
*
* @param nodeId Id of the node to move
* @param previousNodeId Id of the node after which we move the node specified by nodeId
*/
NavigationNodes.prototype.moveAfter = function (nodeId, previousNodeId) {
var postBody = JSON.stringify({
nodeId: nodeId,
previousNodeId: previousNodeId,
});
return this.clone(NavigationNodes, "MoveAfter", true).post({ body: postBody });
};
return NavigationNodes;
}(queryable_1.QueryableCollection));
exports.NavigationNodes = NavigationNodes;
var NavigationNode = (function (_super) {
__extends(NavigationNode, _super);
function NavigationNode() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(NavigationNode.prototype, "children", {
/**
* Represents the child nodes of this node
*/
get: function () {
return new NavigationNodes(this, "Children");
},
enumerable: true,
configurable: true
});
/**
* Updates this node based on the supplied properties
*
* @param properties The hash of key/value pairs to update
*/
NavigationNode.prototype.update = function (properties) {
var _this = this;
var postBody = JSON.stringify(util_1.Util.extend({
"__metadata": { "type": "SP.NavigationNode" },
}, properties));
return this.post({
body: postBody,
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
return {
data: data,
node: _this,
};
});
};
/**
* Deletes this node and any child nodes
*/
NavigationNode.prototype.delete = function () {
return _super.prototype.delete.call(this);
};
return NavigationNode;
}(queryable_1.QueryableInstance));
exports.NavigationNode = NavigationNode;
/**
* Exposes the navigation components
*
*/
var Navigation = (function (_super) {
__extends(Navigation, _super);
/**
* Creates a new instance of the Lists class
*
* @param baseUrl The url or Queryable which forms the parent of this fields collection
*/
function Navigation(baseUrl, path) {
if (path === void 0) { path = "navigation"; }
return _super.call(this, baseUrl, path) || this;
}
Object.defineProperty(Navigation.prototype, "quicklaunch", {
/**
* Gets the quicklaunch navigation for the current context
*
*/
get: function () {
return new NavigationNodes(this, "quicklaunch");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Navigation.prototype, "topNavigationBar", {
/**
* Gets the top bar navigation navigation for the current context
*
*/
get: function () {
return new NavigationNodes(this, "topnavigationbar");
},
enumerable: true,
configurable: true
});
return Navigation;
}(queryable_1.Queryable));
exports.Navigation = Navigation;
/***/ }),
/* 26 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 webs_1 = __webpack_require__(8);
var roles_1 = __webpack_require__(17);
var types_1 = __webpack_require__(13);
var queryable_1 = __webpack_require__(1);
var QueryableSecurable = (function (_super) {
__extends(QueryableSecurable, _super);
function QueryableSecurable() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(QueryableSecurable.prototype, "roleAssignments", {
/**
* Gets the set of role assignments for this item
*
*/
get: function () {
return new roles_1.RoleAssignments(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(QueryableSecurable.prototype, "firstUniqueAncestorSecurableObject", {
/**
* Gets the closest securable up the security hierarchy whose permissions are applied to this list item
*
*/
get: function () {
return new queryable_1.QueryableInstance(this, "FirstUniqueAncestorSecurableObject");
},
enumerable: true,
configurable: true
});
/**
* Gets the effective permissions for the user supplied
*
* @param loginName The claims username for the user (ex: i:0#.f|membership|[email protected])
*/
QueryableSecurable.prototype.getUserEffectivePermissions = function (loginName) {
var q = this.clone(queryable_1.Queryable, "getUserEffectivePermissions(@user)", true);
q.query.add("@user", "'" + encodeURIComponent(loginName) + "'");
return q.getAs();
};
/**
* Gets the effective permissions for the current user
*/
QueryableSecurable.prototype.getCurrentUserEffectivePermissions = function () {
var _this = this;
var w = webs_1.Web.fromUrl(this.toUrl());
return w.currentUser.select("LoginName").getAs().then(function (user) {
return _this.getUserEffectivePermissions(user.LoginName);
});
};
/**
* Breaks the security inheritance at this level optinally copying permissions and clearing subscopes
*
* @param copyRoleAssignments If true the permissions are copied from the current parent scope
* @param clearSubscopes Optional. true to make all child securable objects inherit role assignments from the current object
*/
QueryableSecurable.prototype.breakRoleInheritance = function (copyRoleAssignments, clearSubscopes) {
if (copyRoleAssignments === void 0) { copyRoleAssignments = false; }
if (clearSubscopes === void 0) { clearSubscopes = false; }
return this.clone(QueryableSecurable, "breakroleinheritance(copyroleassignments=" + copyRoleAssignments + ", clearsubscopes=" + clearSubscopes + ")", true).post();
};
/**
* Removes the local role assignments so that it re-inherit role assignments from the parent object.
*
*/
QueryableSecurable.prototype.resetRoleInheritance = function () {
return this.clone(QueryableSecurable, "resetroleinheritance", true).post();
};
/**
* Determines if a given user has the appropriate permissions
*
* @param loginName The user to check
* @param permission The permission being checked
*/
QueryableSecurable.prototype.userHasPermissions = function (loginName, permission) {
var _this = this;
return this.getUserEffectivePermissions(loginName).then(function (perms) {
return _this.hasPermissions(perms, permission);
});
};
/**
* Determines if the current user has the requested permissions
*
* @param permission The permission we wish to check
*/
QueryableSecurable.prototype.currentUserHasPermissions = function (permission) {
var _this = this;
return this.getCurrentUserEffectivePermissions().then(function (perms) {
return _this.hasPermissions(perms, permission);
});
};
/**
* Taken from sp.js, checks the supplied permissions against the mask
*
* @param value The security principal's permissions on the given object
* @param perm The permission checked against the value
*/
/* tslint:disable:no-bitwise */
QueryableSecurable.prototype.hasPermissions = function (value, perm) {
if (!perm) {
return true;
}
if (perm === types_1.PermissionKind.FullMask) {
return (value.High & 32767) === 32767 && value.Low === 65535;
}
perm = perm - 1;
var num = 1;
if (perm >= 0 && perm < 32) {
num = num << perm;
return 0 !== (value.Low & num);
}
else if (perm >= 32 && perm < 64) {
num = num << perm - 32;
return 0 !== (value.High & num);
}
return false;
};
return QueryableSecurable;
}(queryable_1.QueryableInstance));
exports.QueryableSecurable = QueryableSecurable;
/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 queryable_1 = __webpack_require__(1);
var util_1 = __webpack_require__(0);
/**
* Allows for the fluent construction of search queries
*/
var SearchQueryBuilder = (function () {
function SearchQueryBuilder(queryText, _query) {
if (queryText === void 0) { queryText = ""; }
if (_query === void 0) { _query = {}; }
this._query = _query;
if (typeof queryText === "string" && queryText.length > 0) {
this.extendQuery({ Querytext: queryText });
}
}
SearchQueryBuilder.create = function (queryText, queryTemplate) {
if (queryText === void 0) { queryText = ""; }
if (queryTemplate === void 0) { queryTemplate = {}; }
return new SearchQueryBuilder(queryText, queryTemplate);
};
SearchQueryBuilder.prototype.text = function (queryText) {
return this.extendQuery({ Querytext: queryText });
};
SearchQueryBuilder.prototype.template = function (template) {
return this.extendQuery({ QueryTemplate: template });
};
SearchQueryBuilder.prototype.sourceId = function (id) {
return this.extendQuery({ SourceId: id });
};
Object.defineProperty(SearchQueryBuilder.prototype, "enableInterleaving", {
get: function () {
return this.extendQuery({ EnableInterleaving: true });
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchQueryBuilder.prototype, "enableStemming", {
get: function () {
return this.extendQuery({ EnableStemming: true });
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchQueryBuilder.prototype, "trimDuplicates", {
get: function () {
return this.extendQuery({ TrimDuplicates: true });
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchQueryBuilder.prototype, "enableNicknames", {
get: function () {
return this.extendQuery({ EnableNicknames: true });
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchQueryBuilder.prototype, "enableFql", {
get: function () {
return this.extendQuery({ EnableFql: true });
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchQueryBuilder.prototype, "enablePhonetic", {
get: function () {
return this.extendQuery({ EnablePhonetic: true });
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchQueryBuilder.prototype, "bypassResultTypes", {
get: function () {
return this.extendQuery({ BypassResultTypes: true });
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchQueryBuilder.prototype, "processBestBets", {
get: function () {
return this.extendQuery({ ProcessBestBets: true });
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchQueryBuilder.prototype, "enableQueryRules", {
get: function () {
return this.extendQuery({ EnableQueryRules: true });
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchQueryBuilder.prototype, "enableSorting", {
get: function () {
return this.extendQuery({ EnableSorting: true });
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchQueryBuilder.prototype, "generateBlockRankLog", {
get: function () {
return this.extendQuery({ GenerateBlockRankLog: true });
},
enumerable: true,
configurable: true
});
SearchQueryBuilder.prototype.rankingModelId = function (id) {
return this.extendQuery({ RankingModelId: id });
};
SearchQueryBuilder.prototype.startRow = function (id) {
return this.extendQuery({ StartRow: id });
};
SearchQueryBuilder.prototype.rowLimit = function (id) {
return this.extendQuery({ RowLimit: id });
};
SearchQueryBuilder.prototype.rowsPerPage = function (id) {
return this.extendQuery({ RowsPerPage: id });
};
SearchQueryBuilder.prototype.selectProperties = function () {
var properties = [];
for (var _i = 0; _i < arguments.length; _i++) {
properties[_i] = arguments[_i];
}
return this.extendQuery({ SelectProperties: properties });
};
SearchQueryBuilder.prototype.culture = function (culture) {
return this.extendQuery({ Culture: culture });
};
SearchQueryBuilder.prototype.refinementFilters = function () {
var filters = [];
for (var _i = 0; _i < arguments.length; _i++) {
filters[_i] = arguments[_i];
}
return this.extendQuery({ RefinementFilters: filters });
};
SearchQueryBuilder.prototype.refiners = function (refiners) {
return this.extendQuery({ Refiners: refiners });
};
SearchQueryBuilder.prototype.hiddenConstraints = function (constraints) {
return this.extendQuery({ HiddenConstraints: constraints });
};
SearchQueryBuilder.prototype.sortList = function () {
var sorts = [];
for (var _i = 0; _i < arguments.length; _i++) {
sorts[_i] = arguments[_i];
}
return this.extendQuery({ SortList: sorts });
};
SearchQueryBuilder.prototype.timeout = function (milliseconds) {
return this.extendQuery({ Timeout: milliseconds });
};
SearchQueryBuilder.prototype.hithighlightedProperties = function () {
var properties = [];
for (var _i = 0; _i < arguments.length; _i++) {
properties[_i] = arguments[_i];
}
return this.extendQuery({ HithighlightedProperties: properties });
};
SearchQueryBuilder.prototype.clientType = function (clientType) {
return this.extendQuery({ ClientType: clientType });
};
SearchQueryBuilder.prototype.personalizationData = function (data) {
return this.extendQuery({ PersonalizationData: data });
};
SearchQueryBuilder.prototype.resultsURL = function (url) {
return this.extendQuery({ ResultsURL: url });
};
SearchQueryBuilder.prototype.queryTag = function () {
var tags = [];
for (var _i = 0; _i < arguments.length; _i++) {
tags[_i] = arguments[_i];
}
return this.extendQuery({ QueryTag: tags });
};
SearchQueryBuilder.prototype.properties = function () {
var properties = [];
for (var _i = 0; _i < arguments.length; _i++) {
properties[_i] = arguments[_i];
}
return this.extendQuery({ Properties: properties });
};
Object.defineProperty(SearchQueryBuilder.prototype, "processPersonalFavorites", {
get: function () {
return this.extendQuery({ ProcessPersonalFavorites: true });
},
enumerable: true,
configurable: true
});
SearchQueryBuilder.prototype.queryTemplatePropertiesUrl = function (url) {
return this.extendQuery({ QueryTemplatePropertiesUrl: url });
};
SearchQueryBuilder.prototype.reorderingRules = function () {
var rules = [];
for (var _i = 0; _i < arguments.length; _i++) {
rules[_i] = arguments[_i];
}
return this.extendQuery({ ReorderingRules: rules });
};
SearchQueryBuilder.prototype.hitHighlightedMultivaluePropertyLimit = function (limit) {
return this.extendQuery({ HitHighlightedMultivaluePropertyLimit: limit });
};
Object.defineProperty(SearchQueryBuilder.prototype, "enableOrderingHitHighlightedProperty", {
get: function () {
return this.extendQuery({ EnableOrderingHitHighlightedProperty: true });
},
enumerable: true,
configurable: true
});
SearchQueryBuilder.prototype.collapseSpecification = function (spec) {
return this.extendQuery({ CollapseSpecification: spec });
};
SearchQueryBuilder.prototype.uiLanguage = function (lang) {
return this.extendQuery({ UIlanguage: lang });
};
SearchQueryBuilder.prototype.desiredSnippetLength = function (len) {
return this.extendQuery({ DesiredSnippetLength: len });
};
SearchQueryBuilder.prototype.maxSnippetLength = function (len) {
return this.extendQuery({ MaxSnippetLength: len });
};
SearchQueryBuilder.prototype.summaryLength = function (len) {
return this.extendQuery({ SummaryLength: len });
};
SearchQueryBuilder.prototype.toSearchQuery = function () {
return this._query;
};
SearchQueryBuilder.prototype.extendQuery = function (part) {
this._query = util_1.Util.extend(this._query, part);
return this;
};
return SearchQueryBuilder;
}());
exports.SearchQueryBuilder = SearchQueryBuilder;
/**
* Describes the search API
*
*/
var Search = (function (_super) {
__extends(Search, _super);
/**
* Creates a new instance of the Search class
*
* @param baseUrl The url for the search context
* @param query The SearchQuery object to execute
*/
function Search(baseUrl, path) {
if (path === void 0) { path = "_api/search/postquery"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* .......
* @returns Promise
*/
Search.prototype.execute = function (query) {
var _this = this;
var formattedBody;
formattedBody = query;
if (formattedBody.SelectProperties) {
formattedBody.SelectProperties = { results: query.SelectProperties };
}
if (formattedBody.RefinementFilters) {
formattedBody.RefinementFilters = { results: query.RefinementFilters };
}
if (formattedBody.SortList) {
formattedBody.SortList = { results: query.SortList };
}
if (formattedBody.HithighlightedProperties) {
formattedBody.HithighlightedProperties = { results: query.HithighlightedProperties };
}
if (formattedBody.ReorderingRules) {
formattedBody.ReorderingRules = { results: query.ReorderingRules };
}
if (formattedBody.Properties) {
formattedBody.Properties = { results: query.Properties };
}
var postBody = JSON.stringify({
request: util_1.Util.extend({
"__metadata": { "type": "Microsoft.Office.Server.Search.REST.SearchRequest" },
}, formattedBody),
});
return this.post({ body: postBody }).then(function (data) { return new SearchResults(data, _this.toUrl(), query); });
};
return Search;
}(queryable_1.QueryableInstance));
exports.Search = Search;
/**
* Describes the SearchResults class, which returns the formatted and raw version of the query response
*/
var SearchResults = (function () {
/**
* Creates a new instance of the SearchResult class
*
*/
function SearchResults(rawResponse, _url, _query, _raw, _primary) {
if (_raw === void 0) { _raw = null; }
if (_primary === void 0) { _primary = null; }
this._url = _url;
this._query = _query;
this._raw = _raw;
this._primary = _primary;
this._raw = rawResponse.postquery ? rawResponse.postquery : rawResponse;
}
Object.defineProperty(SearchResults.prototype, "ElapsedTime", {
get: function () {
return this.RawSearchResults.ElapsedTime;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchResults.prototype, "RowCount", {
get: function () {
return this.RawSearchResults.PrimaryQueryResult.RelevantResults.RowCount;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchResults.prototype, "TotalRows", {
get: function () {
return this.RawSearchResults.PrimaryQueryResult.RelevantResults.TotalRows;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchResults.prototype, "TotalRowsIncludingDuplicates", {
get: function () {
return this.RawSearchResults.PrimaryQueryResult.RelevantResults.TotalRowsIncludingDuplicates;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchResults.prototype, "RawSearchResults", {
get: function () {
return this._raw;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SearchResults.prototype, "PrimarySearchResults", {
get: function () {
if (this._primary === null) {
this._primary = this.formatSearchResults(this._raw.PrimaryQueryResult.RelevantResults.Table.Rows);
}
return this._primary;
},
enumerable: true,
configurable: true
});
/**
* Gets a page of results
*
* @param pageNumber Index of the page to return. Used to determine StartRow
* @param pageSize Optional, items per page (default = 10)
*/
SearchResults.prototype.getPage = function (pageNumber, pageSize) {
// if we got all the available rows we don't have another page
if (this.TotalRows < this.RowCount) {
return Promise.resolve(null);
}
// if pageSize is supplied, then we use that regardless of any previous values
// otherwise get the previous RowLimit or default to 10
var rows = typeof pageSize !== "undefined" ? pageSize : this._query.hasOwnProperty("RowLimit") ? this._query.RowLimit : 10;
var query = util_1.Util.extend(this._query, {
RowLimit: rows,
StartRow: rows * (pageNumber - 1) + 1,
});
// we have reached the end
if (query.StartRow > this.TotalRows) {
return Promise.resolve(null);
}
var search = new Search(this._url, null);
return search.execute(query);
};
/**
* Formats a search results array
*
* @param rawResults The array to process
*/
SearchResults.prototype.formatSearchResults = function (rawResults) {
var results = new Array();
var tempResults = rawResults.results ? rawResults.results : rawResults;
for (var _i = 0, tempResults_1 = tempResults; _i < tempResults_1.length; _i++) {
var tempResult = tempResults_1[_i];
var cells = tempResult.Cells.results ? tempResult.Cells.results : tempResult.Cells;
results.push(cells.reduce(function (res, cell) {
Object.defineProperty(res, cell.Key, {
configurable: false,
enumerable: false,
value: cell.Value,
writable: false,
});
return res;
}, {}));
}
return results;
};
return SearchResults;
}());
exports.SearchResults = SearchResults;
/**
* defines the SortDirection enum
*/
var SortDirection;
(function (SortDirection) {
SortDirection[SortDirection["Ascending"] = 0] = "Ascending";
SortDirection[SortDirection["Descending"] = 1] = "Descending";
SortDirection[SortDirection["FQLFormula"] = 2] = "FQLFormula";
})(SortDirection = exports.SortDirection || (exports.SortDirection = {}));
/**
* defines the ReorderingRuleMatchType enum
*/
var ReorderingRuleMatchType;
(function (ReorderingRuleMatchType) {
ReorderingRuleMatchType[ReorderingRuleMatchType["ResultContainsKeyword"] = 0] = "ResultContainsKeyword";
ReorderingRuleMatchType[ReorderingRuleMatchType["TitleContainsKeyword"] = 1] = "TitleContainsKeyword";
ReorderingRuleMatchType[ReorderingRuleMatchType["TitleMatchesKeyword"] = 2] = "TitleMatchesKeyword";
ReorderingRuleMatchType[ReorderingRuleMatchType["UrlStartsWith"] = 3] = "UrlStartsWith";
ReorderingRuleMatchType[ReorderingRuleMatchType["UrlExactlyMatches"] = 4] = "UrlExactlyMatches";
ReorderingRuleMatchType[ReorderingRuleMatchType["ContentTypeIs"] = 5] = "ContentTypeIs";
ReorderingRuleMatchType[ReorderingRuleMatchType["FileExtensionMatches"] = 6] = "FileExtensionMatches";
ReorderingRuleMatchType[ReorderingRuleMatchType["ResultHasTag"] = 7] = "ResultHasTag";
ReorderingRuleMatchType[ReorderingRuleMatchType["ManualCondition"] = 8] = "ManualCondition";
})(ReorderingRuleMatchType = exports.ReorderingRuleMatchType || (exports.ReorderingRuleMatchType = {}));
/**
* Specifies the type value for the property
*/
var QueryPropertyValueType;
(function (QueryPropertyValueType) {
QueryPropertyValueType[QueryPropertyValueType["None"] = 0] = "None";
QueryPropertyValueType[QueryPropertyValueType["StringType"] = 1] = "StringType";
QueryPropertyValueType[QueryPropertyValueType["Int32TYpe"] = 2] = "Int32TYpe";
QueryPropertyValueType[QueryPropertyValueType["BooleanType"] = 3] = "BooleanType";
QueryPropertyValueType[QueryPropertyValueType["StringArrayType"] = 4] = "StringArrayType";
QueryPropertyValueType[QueryPropertyValueType["UnSupportedType"] = 5] = "UnSupportedType";
})(QueryPropertyValueType = exports.QueryPropertyValueType || (exports.QueryPropertyValueType = {}));
var SearchBuiltInSourceId = (function () {
function SearchBuiltInSourceId() {
}
return SearchBuiltInSourceId;
}());
SearchBuiltInSourceId.Documents = "e7ec8cee-ded8-43c9-beb5-436b54b31e84";
SearchBuiltInSourceId.ItemsMatchingContentType = "5dc9f503-801e-4ced-8a2c-5d1237132419";
SearchBuiltInSourceId.ItemsMatchingTag = "e1327b9c-2b8c-4b23-99c9-3730cb29c3f7";
SearchBuiltInSourceId.ItemsRelatedToCurrentUser = "48fec42e-4a92-48ce-8363-c2703a40e67d";
SearchBuiltInSourceId.ItemsWithSameKeywordAsThisItem = "5c069288-1d17-454a-8ac6-9c642a065f48";
SearchBuiltInSourceId.LocalPeopleResults = "b09a7990-05ea-4af9-81ef-edfab16c4e31";
SearchBuiltInSourceId.LocalReportsAndDataResults = "203fba36-2763-4060-9931-911ac8c0583b";
SearchBuiltInSourceId.LocalSharePointResults = "8413cd39-2156-4e00-b54d-11efd9abdb89";
SearchBuiltInSourceId.LocalVideoResults = "78b793ce-7956-4669-aa3b-451fc5defebf";
SearchBuiltInSourceId.Pages = "5e34578e-4d08-4edc-8bf3-002acf3cdbcc";
SearchBuiltInSourceId.Pictures = "38403c8c-3975-41a8-826e-717f2d41568a";
SearchBuiltInSourceId.Popular = "97c71db1-58ce-4891-8b64-585bc2326c12";
SearchBuiltInSourceId.RecentlyChangedItems = "ba63bbae-fa9c-42c0-b027-9a878f16557c";
SearchBuiltInSourceId.RecommendedItems = "ec675252-14fa-4fbe-84dd-8d098ed74181";
SearchBuiltInSourceId.Wiki = "9479bf85-e257-4318-b5a8-81a180f5faa1";
exports.SearchBuiltInSourceId = SearchBuiltInSourceId;
/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 queryable_1 = __webpack_require__(1);
var SearchSuggest = (function (_super) {
__extends(SearchSuggest, _super);
function SearchSuggest(baseUrl, path) {
if (path === void 0) { path = "_api/search/suggest"; }
return _super.call(this, baseUrl, path) || this;
}
SearchSuggest.prototype.execute = function (query) {
this.mapQueryToQueryString(query);
return this.get().then(function (response) { return new SearchSuggestResult(response); });
};
SearchSuggest.prototype.mapQueryToQueryString = function (query) {
this.query.add("querytext", "'" + query.querytext + "'");
if (query.hasOwnProperty("count")) {
this.query.add("inumberofquerysuggestions", query.count.toString());
}
if (query.hasOwnProperty("personalCount")) {
this.query.add("inumberofresultsuggestions", query.personalCount.toString());
}
if (query.hasOwnProperty("preQuery")) {
this.query.add("fprequerysuggestions", query.preQuery.toString());
}
if (query.hasOwnProperty("hitHighlighting")) {
this.query.add("fhithighlighting", query.hitHighlighting.toString());
}
if (query.hasOwnProperty("capitalize")) {
this.query.add("fcapitalizefirstletters", query.capitalize.toString());
}
if (query.hasOwnProperty("culture")) {
this.query.add("culture", query.culture.toString());
}
if (query.hasOwnProperty("stemming")) {
this.query.add("enablestemming", query.stemming.toString());
}
if (query.hasOwnProperty("includePeople")) {
this.query.add("showpeoplenamesuggestions", query.includePeople.toString());
}
if (query.hasOwnProperty("queryRules")) {
this.query.add("enablequeryrules", query.queryRules.toString());
}
if (query.hasOwnProperty("prefixMatch")) {
this.query.add("fprefixmatchallterms", query.prefixMatch.toString());
}
};
return SearchSuggest;
}(queryable_1.QueryableInstance));
exports.SearchSuggest = SearchSuggest;
var SearchSuggestResult = (function () {
function SearchSuggestResult(json) {
if (json.hasOwnProperty("suggest")) {
// verbose
this.PeopleNames = json.suggest.PeopleNames.results;
this.PersonalResults = json.suggest.PersonalResults.results;
this.Queries = json.suggest.Queries.results;
}
else {
this.PeopleNames = json.PeopleNames;
this.PersonalResults = json.PersonalResults;
this.Queries = json.Queries;
}
}
return SearchSuggestResult;
}());
exports.SearchSuggestResult = SearchSuggestResult;
/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 queryable_1 = __webpack_require__(1);
var webs_1 = __webpack_require__(8);
var usercustomactions_1 = __webpack_require__(19);
var odata_1 = __webpack_require__(2);
var features_1 = __webpack_require__(23);
/**
* Describes a site collection
*
*/
var Site = (function (_super) {
__extends(Site, _super);
/**
* Creates a new instance of the Site class
*
* @param baseUrl The url or Queryable which forms the parent of this site collection
*/
function Site(baseUrl, path) {
if (path === void 0) { path = "_api/site"; }
return _super.call(this, baseUrl, path) || this;
}
Object.defineProperty(Site.prototype, "rootWeb", {
/**
* Gets the root web of the site collection
*
*/
get: function () {
return new webs_1.Web(this, "rootweb");
},
enumerable: true,
configurable: true
});
Object.defineProperty(Site.prototype, "features", {
/**
* Gets the active features for this site collection
*
*/
get: function () {
return new features_1.Features(this);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Site.prototype, "userCustomActions", {
/**
* Gets all custom actions for this site collection
*
*/
get: function () {
return new usercustomactions_1.UserCustomActions(this);
},
enumerable: true,
configurable: true
});
/**
* Gets the context information for this site collection
*/
Site.prototype.getContextInfo = function () {
var q = new Site(this.parentUrl, "_api/contextinfo");
return q.post().then(function (data) {
if (data.hasOwnProperty("GetContextWebInformation")) {
var info = data.GetContextWebInformation;
info.SupportedSchemaVersions = info.SupportedSchemaVersions.results;
return info;
}
else {
return data;
}
});
};
/**
* Gets the document libraries on a site. Static method. (SharePoint Online only)
*
* @param absoluteWebUrl The absolute url of the web whose document libraries should be returned
*/
Site.prototype.getDocumentLibraries = function (absoluteWebUrl) {
var q = new queryable_1.Queryable("", "_api/sp.web.getdocumentlibraries(@v)");
q.query.add("@v", "'" + absoluteWebUrl + "'");
return q.get().then(function (data) {
if (data.hasOwnProperty("GetDocumentLibraries")) {
return data.GetDocumentLibraries;
}
else {
return data;
}
});
};
/**
* Gets the site url from a page url
*
* @param absolutePageUrl The absolute url of the page
*/
Site.prototype.getWebUrlFromPageUrl = function (absolutePageUrl) {
var q = new queryable_1.Queryable("", "_api/sp.web.getweburlfrompageurl(@v)");
q.query.add("@v", "'" + absolutePageUrl + "'");
return q.get().then(function (data) {
if (data.hasOwnProperty("GetWebUrlFromPageUrl")) {
return data.GetWebUrlFromPageUrl;
}
else {
return data;
}
});
};
/**
* Creates a new batch for requests within the context of this site collection
*
*/
Site.prototype.createBatch = function () {
return new odata_1.ODataBatch(this.parentUrl);
};
/**
* Opens a web by id (using POST)
*
* @param webId The GUID id of the web to open
*/
Site.prototype.openWebById = function (webId) {
return this.clone(Site, "openWebById('" + webId + "')", true).post().then(function (d) {
return {
data: d,
web: webs_1.Web.fromUrl(odata_1.extractOdataId(d)),
};
});
};
return Site;
}(queryable_1.QueryableInstance));
exports.Site = Site;
/***/ }),
/* 30 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 queryable_1 = __webpack_require__(1);
var sitegroups_1 = __webpack_require__(18);
var util_1 = __webpack_require__(0);
/**
* Describes a collection of all site collection users
*
*/
var SiteUsers = (function (_super) {
__extends(SiteUsers, _super);
/**
* Creates a new instance of the SiteUsers class
*
* @param baseUrl The url or Queryable which forms the parent of this user collection
*/
function SiteUsers(baseUrl, path) {
if (path === void 0) { path = "siteusers"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a user from the collection by email
*
* @param email The email address of the user to retrieve
*/
SiteUsers.prototype.getByEmail = function (email) {
return new SiteUser(this, "getByEmail('" + email + "')");
};
/**
* Gets a user from the collection by id
*
* @param id The id of the user to retrieve
*/
SiteUsers.prototype.getById = function (id) {
return new SiteUser(this, "getById(" + id + ")");
};
/**
* Gets a user from the collection by login name
*
* @param loginName The login name of the user to retrieve
*/
SiteUsers.prototype.getByLoginName = function (loginName) {
var su = new SiteUser(this);
su.concat("(@v)");
su.query.add("@v", "'" + encodeURIComponent(loginName) + "'");
return su;
};
/**
* Removes a user from the collection by id
*
* @param id The id of the user to remove
*/
SiteUsers.prototype.removeById = function (id) {
return this.clone(SiteUsers, "removeById(" + id + ")", true).post();
};
/**
* Removes a user from the collection by login name
*
* @param loginName The login name of the user to remove
*/
SiteUsers.prototype.removeByLoginName = function (loginName) {
var o = this.clone(SiteUsers, "removeByLoginName(@v)", true);
o.query.add("@v", "'" + encodeURIComponent(loginName) + "'");
return o.post();
};
/**
* Adds a user to a group
*
* @param loginName The login name of the user to add to the group
*
*/
SiteUsers.prototype.add = function (loginName) {
var _this = this;
return this.clone(SiteUsers, null, true).post({
body: JSON.stringify({ "__metadata": { "type": "SP.User" }, LoginName: loginName }),
}).then(function () { return _this.getByLoginName(loginName); });
};
return SiteUsers;
}(queryable_1.QueryableCollection));
exports.SiteUsers = SiteUsers;
/**
* Describes a single user
*
*/
var SiteUser = (function (_super) {
__extends(SiteUser, _super);
function SiteUser() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(SiteUser.prototype, "groups", {
/**
* Gets the groups for this user
*
*/
get: function () {
return new sitegroups_1.SiteGroups(this, "groups");
},
enumerable: true,
configurable: true
});
/**
* Updates this user instance with the supplied properties
*
* @param properties A plain object of property names and values to update for the user
*/
SiteUser.prototype.update = function (properties) {
var _this = this;
var postBody = util_1.Util.extend({ "__metadata": { "type": "SP.User" } }, properties);
return this.post({
body: JSON.stringify(postBody),
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
return {
data: data,
user: _this,
};
});
};
/**
* Delete this user
*
*/
SiteUser.prototype.delete = function () {
return this.post({
headers: {
"X-HTTP-Method": "DELETE",
},
});
};
return SiteUser;
}(queryable_1.QueryableInstance));
exports.SiteUser = SiteUser;
/**
* Represents the current user
*/
var CurrentUser = (function (_super) {
__extends(CurrentUser, _super);
function CurrentUser(baseUrl, path) {
if (path === void 0) { path = "currentuser"; }
return _super.call(this, baseUrl, path) || this;
}
return CurrentUser;
}(queryable_1.QueryableInstance));
exports.CurrentUser = CurrentUser;
/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 queryable_1 = __webpack_require__(1);
var util_1 = __webpack_require__(0);
var files_1 = __webpack_require__(7);
var odata_1 = __webpack_require__(2);
/**
* Allows for calling of the static SP.Utilities.Utility methods by supplying the method name
*/
var UtilityMethod = (function (_super) {
__extends(UtilityMethod, _super);
/**
* Creates a new instance of the Utility method class
*
* @param baseUrl The parent url provider
* @param methodName The static method name to call on the utility class
*/
function UtilityMethod(baseUrl, methodName) {
return _super.call(this, UtilityMethod.getBaseUrl(baseUrl), "_api/SP.Utilities.Utility." + methodName) || this;
}
UtilityMethod.getBaseUrl = function (candidate) {
if (typeof candidate === "string") {
return candidate;
}
var c = candidate;
var url = c.toUrl();
var index = url.indexOf("_api/");
if (index < 0) {
return url;
}
return url.substr(0, index);
};
UtilityMethod.prototype.excute = function (props) {
return this.postAs({
body: JSON.stringify(props),
});
};
/**
* Clones this queryable into a new queryable instance of T
* @param factory Constructor used to create the new instance
* @param additionalPath Any additional path to include in the clone
* @param includeBatch If true this instance's batch will be added to the cloned instance
*/
UtilityMethod.prototype.create = function (methodName, includeBatch) {
var clone = new UtilityMethod(this.parentUrl, methodName);
var target = this.query.get("@target");
if (target !== null) {
clone.query.add("@target", target);
}
if (includeBatch && this.hasBatch) {
clone = clone.inBatch(this.batch);
}
return clone;
};
/**
* Sends an email based on the supplied properties
*
* @param props The properties of the email to send
*/
UtilityMethod.prototype.sendEmail = function (props) {
var params = {
properties: {
Body: props.Body,
From: props.From,
Subject: props.Subject,
"__metadata": { "type": "SP.Utilities.EmailProperties" },
},
};
if (props.To && props.To.length > 0) {
params.properties = util_1.Util.extend(params.properties, {
To: { results: props.To },
});
}
if (props.CC && props.CC.length > 0) {
params.properties = util_1.Util.extend(params.properties, {
CC: { results: props.CC },
});
}
if (props.BCC && props.BCC.length > 0) {
params.properties = util_1.Util.extend(params.properties, {
BCC: { results: props.BCC },
});
}
if (props.AdditionalHeaders) {
params.properties = util_1.Util.extend(params.properties, {
AdditionalHeaders: props.AdditionalHeaders,
});
}
return this.create("SendEmail", true).excute(params);
};
UtilityMethod.prototype.getCurrentUserEmailAddresses = function () {
return this.create("GetCurrentUserEmailAddresses", true).excute({});
};
UtilityMethod.prototype.resolvePrincipal = function (input, scopes, sources, inputIsEmailOnly, addToUserInfoList, matchUserInfoList) {
if (matchUserInfoList === void 0) { matchUserInfoList = false; }
var params = {
addToUserInfoList: addToUserInfoList,
input: input,
inputIsEmailOnly: inputIsEmailOnly,
matchUserInfoList: matchUserInfoList,
scopes: scopes,
sources: sources,
};
return this.create("ResolvePrincipalInCurrentContext", true).excute(params);
};
UtilityMethod.prototype.searchPrincipals = function (input, scopes, sources, groupName, maxCount) {
var params = {
groupName: groupName,
input: input,
maxCount: maxCount,
scopes: scopes,
sources: sources,
};
return this.create("SearchPrincipalsUsingContextWeb", true).excute(params);
};
UtilityMethod.prototype.createEmailBodyForInvitation = function (pageAddress) {
var params = {
pageAddress: pageAddress,
};
return this.create("CreateEmailBodyForInvitation", true).excute(params);
};
UtilityMethod.prototype.expandGroupsToPrincipals = function (inputs, maxCount) {
if (maxCount === void 0) { maxCount = 30; }
var params = {
inputs: inputs,
maxCount: maxCount,
};
return this.create("ExpandGroupsToPrincipals", true).excute(params);
};
UtilityMethod.prototype.createWikiPage = function (info) {
return this.create("CreateWikiPageInContextWeb", true).excute({
parameters: info,
}).then(function (r) {
return {
data: r,
file: new files_1.File(odata_1.extractOdataId(r)),
};
});
};
return UtilityMethod;
}(queryable_1.Queryable));
exports.UtilityMethod = UtilityMethod;
/***/ }),
/* 32 */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || Function("return this")() || (1,eval)("this");
} catch(e) {
// This works if the window reference is available
if(typeof window === "object")
g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/* 33 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var collections_1 = __webpack_require__(6);
/**
* Class used to manage the current application settings
*
*/
var Settings = (function () {
/**
* Creates a new instance of the settings class
*
* @constructor
*/
function Settings() {
this._settings = new collections_1.Dictionary();
}
/**
* Adds a new single setting, or overwrites a previous setting with the same key
*
* @param {string} key The key used to store this setting
* @param {string} value The setting value to store
*/
Settings.prototype.add = function (key, value) {
this._settings.add(key, value);
};
/**
* Adds a JSON value to the collection as a string, you must use getJSON to rehydrate the object when read
*
* @param {string} key The key used to store this setting
* @param {any} value The setting value to store
*/
Settings.prototype.addJSON = function (key, value) {
this._settings.add(key, JSON.stringify(value));
};
/**
* Applies the supplied hash to the setting collection overwriting any existing value, or created new values
*
* @param {TypedHash<any>} hash The set of values to add
*/
Settings.prototype.apply = function (hash) {
var _this = this;
return new Promise(function (resolve, reject) {
try {
_this._settings.merge(hash);
resolve();
}
catch (e) {
reject(e);
}
});
};
/**
* Loads configuration settings into the collection from the supplied provider and returns a Promise
*
* @param {IConfigurationProvider} provider The provider from which we will load the settings
*/
Settings.prototype.load = function (provider) {
var _this = this;
return new Promise(function (resolve, reject) {
provider.getConfiguration().then(function (value) {
_this._settings.merge(value);
resolve();
}).catch(function (reason) {
reject(reason);
});
});
};
/**
* Gets a value from the configuration
*
* @param {string} key The key whose value we want to return. Returns null if the key does not exist
* @return {string} string value from the configuration
*/
Settings.prototype.get = function (key) {
return this._settings.get(key);
};
/**
* Gets a JSON value, rehydrating the stored string to the original object
*
* @param {string} key The key whose value we want to return. Returns null if the key does not exist
* @return {any} object from the configuration
*/
Settings.prototype.getJSON = function (key) {
var o = this.get(key);
if (typeof o === "undefined" || o === null) {
return o;
}
return JSON.parse(o);
};
return Settings;
}());
exports.Settings = Settings;
/***/ }),
/* 34 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var search_1 = __webpack_require__(27);
var searchsuggest_1 = __webpack_require__(28);
var site_1 = __webpack_require__(29);
var webs_1 = __webpack_require__(8);
var util_1 = __webpack_require__(0);
var userprofiles_1 = __webpack_require__(48);
var exceptions_1 = __webpack_require__(3);
var utilities_1 = __webpack_require__(31);
/**
* Root of the SharePoint REST module
*/
var SPRest = (function () {
function SPRest() {
}
/**
* Executes a search against this web context
*
* @param query The SearchQuery definition
*/
SPRest.prototype.searchSuggest = function (query) {
var finalQuery;
if (typeof query === "string") {
finalQuery = { querytext: query };
}
else {
finalQuery = query;
}
return new searchsuggest_1.SearchSuggest("").execute(finalQuery);
};
/**
* Executes a search against this web context
*
* @param query The SearchQuery definition
*/
SPRest.prototype.search = function (query) {
var finalQuery;
if (typeof query === "string") {
finalQuery = { Querytext: query };
}
else if (query instanceof search_1.SearchQueryBuilder) {
finalQuery = query.toSearchQuery();
}
else {
finalQuery = query;
}
return new search_1.Search("").execute(finalQuery);
};
Object.defineProperty(SPRest.prototype, "site", {
/**
* Begins a site collection scoped REST request
*
*/
get: function () {
return new site_1.Site("");
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRest.prototype, "web", {
/**
* Begins a web scoped REST request
*
*/
get: function () {
return new webs_1.Web("");
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPRest.prototype, "profiles", {
/**
* Access to user profile methods
*
*/
get: function () {
return new userprofiles_1.UserProfileQuery("");
},
enumerable: true,
configurable: true
});
/**
* Creates a new batch object for use with the Queryable.addToBatch method
*
*/
SPRest.prototype.createBatch = function () {
return this.web.createBatch();
};
Object.defineProperty(SPRest.prototype, "utility", {
/**
* Static utilities methods from SP.Utilities.Utility
*/
get: function () {
return new utilities_1.UtilityMethod("", "");
},
enumerable: true,
configurable: true
});
/**
* Begins a cross-domain, host site scoped REST request, for use in add-in webs
*
* @param addInWebUrl The absolute url of the add-in web
* @param hostWebUrl The absolute url of the host web
*/
SPRest.prototype.crossDomainSite = function (addInWebUrl, hostWebUrl) {
return this._cdImpl(site_1.Site, addInWebUrl, hostWebUrl, "site");
};
/**
* Begins a cross-domain, host web scoped REST request, for use in add-in webs
*
* @param addInWebUrl The absolute url of the add-in web
* @param hostWebUrl The absolute url of the host web
*/
SPRest.prototype.crossDomainWeb = function (addInWebUrl, hostWebUrl) {
return this._cdImpl(webs_1.Web, addInWebUrl, hostWebUrl, "web");
};
/**
* Implements the creation of cross domain REST urls
*
* @param factory The constructor of the object to create Site | Web
* @param addInWebUrl The absolute url of the add-in web
* @param hostWebUrl The absolute url of the host web
* @param urlPart String part to append to the url "site" | "web"
*/
SPRest.prototype._cdImpl = function (factory, addInWebUrl, hostWebUrl, urlPart) {
if (!util_1.Util.isUrlAbsolute(addInWebUrl)) {
throw new exceptions_1.UrlException("The addInWebUrl parameter must be an absolute url.");
}
if (!util_1.Util.isUrlAbsolute(hostWebUrl)) {
throw new exceptions_1.UrlException("The hostWebUrl parameter must be an absolute url.");
}
var url = util_1.Util.combinePaths(addInWebUrl, "_api/SP.AppContextSite(@target)");
var instance = new factory(url, urlPart);
instance.query.add("@target", "'" + encodeURIComponent(hostWebUrl) + "'");
return instance;
};
return SPRest;
}());
exports.SPRest = SPRest;
/***/ }),
/* 35 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(__webpack_require__(44));
var httpclient_1 = __webpack_require__(15);
exports.HttpClient = httpclient_1.HttpClient;
var sprequestexecutorclient_1 = __webpack_require__(40);
exports.SPRequestExecutorClient = sprequestexecutorclient_1.SPRequestExecutorClient;
var nodefetchclient_1 = __webpack_require__(39);
exports.NodeFetchClient = nodefetchclient_1.NodeFetchClient;
var fetchclient_1 = __webpack_require__(21);
exports.FetchClient = fetchclient_1.FetchClient;
__export(__webpack_require__(36));
var collections_1 = __webpack_require__(6);
exports.Dictionary = collections_1.Dictionary;
var util_1 = __webpack_require__(0);
exports.Util = util_1.Util;
__export(__webpack_require__(5));
__export(__webpack_require__(3));
/***/ }),
/* 36 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var cachingConfigurationProvider_1 = __webpack_require__(20);
exports.CachingConfigurationProvider = cachingConfigurationProvider_1.default;
var spListConfigurationProvider_1 = __webpack_require__(37);
exports.SPListConfigurationProvider = spListConfigurationProvider_1.default;
/***/ }),
/* 37 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var cachingConfigurationProvider_1 = __webpack_require__(20);
/**
* A configuration provider which loads configuration values from a SharePoint list
*
*/
var SPListConfigurationProvider = (function () {
/**
* Creates a new SharePoint list based configuration provider
* @constructor
* @param {string} webUrl Url of the SharePoint site, where the configuration list is located
* @param {string} listTitle Title of the SharePoint list, which contains the configuration settings (optional, default = "config")
*/
function SPListConfigurationProvider(sourceWeb, sourceListTitle) {
if (sourceListTitle === void 0) { sourceListTitle = "config"; }
this.sourceWeb = sourceWeb;
this.sourceListTitle = sourceListTitle;
}
Object.defineProperty(SPListConfigurationProvider.prototype, "web", {
/**
* Gets the url of the SharePoint site, where the configuration list is located
*
* @return {string} Url address of the site
*/
get: function () {
return this.sourceWeb;
},
enumerable: true,
configurable: true
});
Object.defineProperty(SPListConfigurationProvider.prototype, "listTitle", {
/**
* Gets the title of the SharePoint list, which contains the configuration settings
*
* @return {string} List title
*/
get: function () {
return this.sourceListTitle;
},
enumerable: true,
configurable: true
});
/**
* Loads the configuration values from the SharePoint list
*
* @return {Promise<TypedHash<string>>} Promise of loaded configuration values
*/
SPListConfigurationProvider.prototype.getConfiguration = function () {
return this.web.lists.getByTitle(this.listTitle).items.select("Title", "Value")
.getAs().then(function (data) {
return data.reduce(function (configuration, item) {
return Object.defineProperty(configuration, item.Title, {
configurable: false,
enumerable: false,
value: item.Value,
writable: false,
});
}, {});
});
};
/**
* Wraps the current provider in a cache enabled provider
*
* @return {CachingConfigurationProvider} Caching providers which wraps the current provider
*/
SPListConfigurationProvider.prototype.asCaching = function () {
var cacheKey = "splist_" + this.web.toUrl() + "+" + this.listTitle;
return new cachingConfigurationProvider_1.default(this, cacheKey);
};
return SPListConfigurationProvider;
}());
exports.default = SPListConfigurationProvider;
/***/ }),
/* 38 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var collections_1 = __webpack_require__(6);
var util_1 = __webpack_require__(0);
var odata_1 = __webpack_require__(2);
var CachedDigest = (function () {
function CachedDigest() {
}
return CachedDigest;
}());
exports.CachedDigest = CachedDigest;
// allows for the caching of digests across all HttpClient's which each have their own DigestCache wrapper.
var digests = new collections_1.Dictionary();
var DigestCache = (function () {
function DigestCache(_httpClient, _digests) {
if (_digests === void 0) { _digests = digests; }
this._httpClient = _httpClient;
this._digests = _digests;
}
DigestCache.prototype.getDigest = function (webUrl) {
var _this = this;
var cachedDigest = this._digests.get(webUrl);
if (cachedDigest !== null) {
var now = new Date();
if (now < cachedDigest.expiration) {
return Promise.resolve(cachedDigest.value);
}
}
var url = util_1.Util.combinePaths(webUrl, "/_api/contextinfo");
return this._httpClient.fetchRaw(url, {
cache: "no-cache",
credentials: "same-origin",
headers: {
"Accept": "application/json;odata=verbose",
"Content-type": "application/json;odata=verbose;charset=utf-8",
},
method: "POST",
}).then(function (response) {
var parser = new odata_1.ODataDefaultParser();
return parser.parse(response).then(function (d) { return d.GetContextWebInformation; });
}).then(function (data) {
var newCachedDigest = new CachedDigest();
newCachedDigest.value = data.FormDigestValue;
var seconds = data.FormDigestTimeoutSeconds;
var expiration = new Date();
expiration.setTime(expiration.getTime() + 1000 * seconds);
newCachedDigest.expiration = expiration;
_this._digests.add(webUrl, newCachedDigest);
return newCachedDigest.value;
});
};
DigestCache.prototype.clear = function () {
this._digests.clear();
};
return DigestCache;
}());
exports.DigestCache = DigestCache;
/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var exceptions_1 = __webpack_require__(3);
/**
* This module is substituted for the NodeFetchClient.ts during the packaging process. This helps to reduce the pnp.js file size by
* not including all of the node dependencies
*/
var NodeFetchClient = (function () {
function NodeFetchClient() {
}
/**
* Always throws an error that NodeFetchClient is not supported for use in the browser
*/
NodeFetchClient.prototype.fetch = function () {
throw new exceptions_1.NodeFetchClientUnsupportedException();
};
return NodeFetchClient;
}());
exports.NodeFetchClient = NodeFetchClient;
/***/ }),
/* 40 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var util_1 = __webpack_require__(0);
var exceptions_1 = __webpack_require__(3);
/**
* Makes requests using the SP.RequestExecutor library.
*/
var SPRequestExecutorClient = (function () {
function SPRequestExecutorClient() {
/**
* Converts a SharePoint REST API response to a fetch API response.
*/
this.convertToResponse = function (spResponse) {
var responseHeaders = new Headers();
for (var h in spResponse.headers) {
if (spResponse.headers[h]) {
responseHeaders.append(h, spResponse.headers[h]);
}
}
// issue #256, Cannot have an empty string body when creating a Response with status 204
var body = spResponse.statusCode === 204 ? null : spResponse.body;
return new Response(body, {
headers: responseHeaders,
status: spResponse.statusCode,
statusText: spResponse.statusText,
});
};
}
/**
* Fetches a URL using the SP.RequestExecutor library.
*/
SPRequestExecutorClient.prototype.fetch = function (url, options) {
var _this = this;
if (typeof SP === "undefined" || typeof SP.RequestExecutor === "undefined") {
throw new exceptions_1.SPRequestExecutorUndefinedException();
}
var addinWebUrl = url.substring(0, url.indexOf("/_api")), executor = new SP.RequestExecutor(addinWebUrl);
var headers = {}, iterator, temp;
if (options.headers && options.headers instanceof Headers) {
iterator = options.headers.entries();
temp = iterator.next();
while (!temp.done) {
headers[temp.value[0]] = temp.value[1];
temp = iterator.next();
}
}
else {
headers = options.headers;
}
return new Promise(function (resolve, reject) {
var requestOptions = {
error: function (error) {
reject(_this.convertToResponse(error));
},
headers: headers,
method: options.method,
success: function (response) {
resolve(_this.convertToResponse(response));
},
url: url,
};
if (options.body) {
requestOptions = util_1.Util.extend(requestOptions, { body: options.body });
}
else {
requestOptions = util_1.Util.extend(requestOptions, { binaryStringRequestBody: true });
}
executor.executeAsync(requestOptions);
});
};
return SPRequestExecutorClient;
}());
exports.SPRequestExecutorClient = SPRequestExecutorClient;
/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
var util_1 = __webpack_require__(0);
var storage_1 = __webpack_require__(14);
var configuration_1 = __webpack_require__(33);
var logging_1 = __webpack_require__(5);
var rest_1 = __webpack_require__(34);
var pnplibconfig_1 = __webpack_require__(4);
/**
* Root class of the Patterns and Practices namespace, provides an entry point to the library
*/
/**
* Utility methods
*/
exports.util = util_1.Util;
/**
* Provides access to the REST interface
*/
exports.sp = new rest_1.SPRest();
/**
* Provides access to local and session storage
*/
exports.storage = new storage_1.PnPClientStorage();
/**
* Global configuration instance to which providers can be added
*/
exports.config = new configuration_1.Settings();
/**
* Global logging instance to which subscribers can be registered and messages written
*/
exports.log = logging_1.Logger;
/**
* Allows for the configuration of the library
*/
exports.setup = pnplibconfig_1.setRuntimeConfig;
/**
* Expose a subset of classes from the library for public consumption
*/
__export(__webpack_require__(35));
// creating this class instead of directly assigning to default fixes issue #116
var Def = {
/**
* Global configuration instance to which providers can be added
*/
config: exports.config,
/**
* Global logging instance to which subscribers can be registered and messages written
*/
log: exports.log,
/**
* Provides access to local and session storage
*/
setup: exports.setup,
/**
* Provides access to the REST interface
*/
sp: exports.sp,
/**
* Provides access to local and session storage
*/
storage: exports.storage,
/**
* Utility methods
*/
util: exports.util,
};
/**
* Enables use of the import pnp from syntax
*/
exports.default = Def;
/***/ }),
/* 42 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 queryable_1 = __webpack_require__(1);
var odata_1 = __webpack_require__(2);
/**
* Describes a collection of Item objects
*
*/
var AttachmentFiles = (function (_super) {
__extends(AttachmentFiles, _super);
/**
* Creates a new instance of the AttachmentFiles class
*
* @param baseUrl The url or Queryable which forms the parent of this attachments collection
*/
function AttachmentFiles(baseUrl, path) {
if (path === void 0) { path = "AttachmentFiles"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a Attachment File by filename
*
* @param name The name of the file, including extension.
*/
AttachmentFiles.prototype.getByName = function (name) {
var f = new AttachmentFile(this);
f.concat("('" + name + "')");
return f;
};
/**
* Adds a new attachment to the collection. Not supported for batching.
*
* @param name The name of the file, including extension.
* @param content The Base64 file content.
*/
AttachmentFiles.prototype.add = function (name, content) {
var _this = this;
return this.clone(AttachmentFiles, "add(FileName='" + name + "')").post({
body: content,
}).then(function (response) {
return {
data: response,
file: _this.getByName(name),
};
});
};
/**
* Adds mjultiple new attachment to the collection. Not supported for batching.
*
* @files name The collection of files to add
*/
AttachmentFiles.prototype.addMultiple = function (files) {
var _this = this;
// add the files in series so we don't get update conflicts
return files.reduce(function (chain, file) { return chain.then(function () { return _this.clone(AttachmentFiles, "add(FileName='" + file.name + "')").post({
body: file.content,
}); }); }, Promise.resolve());
};
return AttachmentFiles;
}(queryable_1.QueryableCollection));
exports.AttachmentFiles = AttachmentFiles;
/**
* Describes a single attachment file instance
*
*/
var AttachmentFile = (function (_super) {
__extends(AttachmentFile, _super);
function AttachmentFile() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets the contents of the file as text
*
*/
AttachmentFile.prototype.getText = function () {
return this.clone(AttachmentFile, "$value").get(new odata_1.TextFileParser());
};
/**
* Gets the contents of the file as a blob, does not work in Node.js
*
*/
AttachmentFile.prototype.getBlob = function () {
return this.clone(AttachmentFile, "$value").get(new odata_1.BlobFileParser());
};
/**
* Gets the contents of a file as an ArrayBuffer, works in Node.js
*/
AttachmentFile.prototype.getBuffer = function () {
return this.clone(AttachmentFile, "$value").get(new odata_1.BufferFileParser());
};
/**
* Gets the contents of a file as an ArrayBuffer, works in Node.js
*/
AttachmentFile.prototype.getJSON = function () {
return this.clone(AttachmentFile, "$value").get(new odata_1.JSONFileParser());
};
/**
* Sets the content of a file. Not supported for batching
*
* @param content The value to set for the file contents
*/
AttachmentFile.prototype.setContent = function (content) {
var _this = this;
return this.clone(AttachmentFile, "$value").post({
body: content,
headers: {
"X-HTTP-Method": "PUT",
},
}).then(function (_) { return new AttachmentFile(_this); });
};
/**
* Delete this attachment file
*
* @param eTag Value used in the IF-Match header, by default "*"
*/
AttachmentFile.prototype.delete = function (eTag) {
if (eTag === void 0) { eTag = "*"; }
return this.post({
headers: {
"IF-Match": eTag,
"X-HTTP-Method": "DELETE",
},
});
};
return AttachmentFile;
}(queryable_1.QueryableInstance));
exports.AttachmentFile = AttachmentFile;
/***/ }),
/* 43 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 queryable_1 = __webpack_require__(1);
/**
* Describes a collection of Field objects
*
*/
var Forms = (function (_super) {
__extends(Forms, _super);
/**
* Creates a new instance of the Fields class
*
* @param baseUrl The url or Queryable which forms the parent of this fields collection
*/
function Forms(baseUrl, path) {
if (path === void 0) { path = "forms"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a form by id
*
* @param id The guid id of the item to retrieve
*/
Forms.prototype.getById = function (id) {
var i = new Form(this);
i.concat("('" + id + "')");
return i;
};
return Forms;
}(queryable_1.QueryableCollection));
exports.Forms = Forms;
/**
* Describes a single of Form instance
*
*/
var Form = (function (_super) {
__extends(Form, _super);
function Form() {
return _super !== null && _super.apply(this, arguments) || this;
}
return Form;
}(queryable_1.QueryableInstance));
exports.Form = Form;
/***/ }),
/* 44 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
__export(__webpack_require__(22));
var files_1 = __webpack_require__(7);
exports.CheckinType = files_1.CheckinType;
exports.WebPartsPersonalizationScope = files_1.WebPartsPersonalizationScope;
exports.MoveOperations = files_1.MoveOperations;
exports.TemplateFileType = files_1.TemplateFileType;
var folders_1 = __webpack_require__(9);
exports.Folder = folders_1.Folder;
exports.Folders = folders_1.Folders;
var items_1 = __webpack_require__(10);
exports.Item = items_1.Item;
exports.Items = items_1.Items;
exports.PagedItemCollection = items_1.PagedItemCollection;
var navigation_1 = __webpack_require__(25);
exports.NavigationNodes = navigation_1.NavigationNodes;
exports.NavigationNode = navigation_1.NavigationNode;
var lists_1 = __webpack_require__(11);
exports.List = lists_1.List;
exports.Lists = lists_1.Lists;
var odata_1 = __webpack_require__(2);
exports.extractOdataId = odata_1.extractOdataId;
exports.ODataParserBase = odata_1.ODataParserBase;
exports.ODataDefaultParser = odata_1.ODataDefaultParser;
exports.ODataRaw = odata_1.ODataRaw;
exports.ODataValue = odata_1.ODataValue;
exports.ODataEntity = odata_1.ODataEntity;
exports.ODataEntityArray = odata_1.ODataEntityArray;
exports.TextFileParser = odata_1.TextFileParser;
exports.BlobFileParser = odata_1.BlobFileParser;
exports.BufferFileParser = odata_1.BufferFileParser;
exports.JSONFileParser = odata_1.JSONFileParser;
var queryable_1 = __webpack_require__(1);
exports.Queryable = queryable_1.Queryable;
exports.QueryableInstance = queryable_1.QueryableInstance;
exports.QueryableCollection = queryable_1.QueryableCollection;
var roles_1 = __webpack_require__(17);
exports.RoleDefinitionBindings = roles_1.RoleDefinitionBindings;
var search_1 = __webpack_require__(27);
exports.Search = search_1.Search;
exports.SearchQueryBuilder = search_1.SearchQueryBuilder;
exports.SearchResults = search_1.SearchResults;
exports.SortDirection = search_1.SortDirection;
exports.ReorderingRuleMatchType = search_1.ReorderingRuleMatchType;
exports.QueryPropertyValueType = search_1.QueryPropertyValueType;
exports.SearchBuiltInSourceId = search_1.SearchBuiltInSourceId;
var searchsuggest_1 = __webpack_require__(28);
exports.SearchSuggest = searchsuggest_1.SearchSuggest;
exports.SearchSuggestResult = searchsuggest_1.SearchSuggestResult;
var site_1 = __webpack_require__(29);
exports.Site = site_1.Site;
__export(__webpack_require__(13));
var utilities_1 = __webpack_require__(31);
exports.UtilityMethod = utilities_1.UtilityMethod;
var webs_1 = __webpack_require__(8);
exports.Web = webs_1.Web;
/***/ }),
/* 45 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var caching_1 = __webpack_require__(22);
var httpclient_1 = __webpack_require__(15);
var logging_1 = __webpack_require__(5);
var util_1 = __webpack_require__(0);
/**
* Resolves the context's result value
*
* @param context The current context
*/
function returnResult(context) {
logging_1.Logger.log({
data: context.result,
level: logging_1.LogLevel.Verbose,
message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Returning result, see data property for value.",
});
return Promise.resolve(context.result);
}
/**
* Sets the result on the context
*/
function setResult(context, value) {
return new Promise(function (resolve) {
context.result = value;
context.hasResult = true;
resolve(context);
});
}
exports.setResult = setResult;
/**
* Invokes the next method in the provided context's pipeline
*
* @param c The current request context
*/
function next(c) {
if (c.pipeline.length < 1) {
return Promise.resolve(c);
}
return c.pipeline.shift()(c);
}
/**
* Executes the current request context's pipeline
*
* @param context Current context
*/
function pipe(context) {
return next(context)
.then(function (ctx) { return returnResult(ctx); })
.catch(function (e) {
logging_1.Logger.log({
data: e,
level: logging_1.LogLevel.Error,
message: "Error in request pipeline: " + e.message,
});
throw e;
});
}
exports.pipe = pipe;
/**
* decorator factory applied to methods in the pipeline to control behavior
*/
function requestPipelineMethod(alwaysRun) {
if (alwaysRun === void 0) { alwaysRun = false; }
return function (target, propertyKey, descriptor) {
var method = descriptor.value;
descriptor.value = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
// if we have a result already in the pipeline, pass it along and don't call the tagged method
if (!alwaysRun && args.length > 0 && args[0].hasOwnProperty("hasResult") && args[0].hasResult) {
logging_1.Logger.write("[" + args[0].requestId + "] (" + (new Date()).getTime() + ") Skipping request pipeline method " + propertyKey + ", existing result in pipeline.", logging_1.LogLevel.Verbose);
return Promise.resolve(args[0]);
}
// apply the tagged method
logging_1.Logger.write("[" + args[0].requestId + "] (" + (new Date()).getTime() + ") Calling request pipeline method " + propertyKey + ".", logging_1.LogLevel.Verbose);
// then chain the next method in the context's pipeline - allows for dynamic pipeline
return method.apply(target, args).then(function (ctx) { return next(ctx); });
};
};
}
exports.requestPipelineMethod = requestPipelineMethod;
/**
* Contains the methods used within the request pipeline
*/
var PipelineMethods = (function () {
function PipelineMethods() {
}
/**
* Logs the start of the request
*/
PipelineMethods.logStart = function (context) {
return new Promise(function (resolve) {
logging_1.Logger.log({
data: logging_1.Logger.activeLogLevel === logging_1.LogLevel.Info ? {} : context,
level: logging_1.LogLevel.Info,
message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Beginning " + context.verb + " request (" + context.requestAbsoluteUrl + ")",
});
resolve(context);
});
};
/**
* Handles caching of the request
*/
PipelineMethods.caching = function (context) {
return new Promise(function (resolve) {
// handle caching, if applicable
if (context.verb === "GET" && context.isCached) {
logging_1.Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Caching is enabled for request, checking cache...", logging_1.LogLevel.Info);
var cacheOptions = new caching_1.CachingOptions(context.requestAbsoluteUrl.toLowerCase());
if (typeof context.cachingOptions !== "undefined") {
cacheOptions = util_1.Util.extend(cacheOptions, context.cachingOptions);
}
// we may not have a valid store
if (cacheOptions.store !== null) {
// check if we have the data in cache and if so resolve the promise and return
var data = cacheOptions.store.get(cacheOptions.key);
if (data !== null) {
// ensure we clear any help batch dependency we are resolving from the cache
logging_1.Logger.log({
data: logging_1.Logger.activeLogLevel === logging_1.LogLevel.Info ? {} : data,
level: logging_1.LogLevel.Info,
message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Value returned from cache.",
});
context.batchDependency();
return setResult(context, data).then(function (ctx) { return resolve(ctx); });
}
}
logging_1.Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Value not found in cache.", logging_1.LogLevel.Info);
// if we don't then wrap the supplied parser in the caching parser wrapper
// and send things on their way
context.parser = new caching_1.CachingParserWrapper(context.parser, cacheOptions);
}
return resolve(context);
});
};
/**
* Sends the request
*/
PipelineMethods.send = function (context) {
return new Promise(function (resolve, reject) {
// send or batch the request
if (context.isBatched) {
// we are in a batch, so add to batch, remove dependency, and resolve with the batch's promise
var p = context.batch.add(context.requestAbsoluteUrl, context.verb, context.options, context.parser);
// we release the dependency here to ensure the batch does not execute until the request is added to the batch
context.batchDependency();
logging_1.Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Batching request in batch " + context.batch.batchId + ".", logging_1.LogLevel.Info);
// we set the result as the promise which will be resolved by the batch's execution
resolve(setResult(context, p));
}
else {
logging_1.Logger.write("[" + context.requestId + "] (" + (new Date()).getTime() + ") Sending request.", logging_1.LogLevel.Info);
// we are not part of a batch, so proceed as normal
var client = new httpclient_1.HttpClient();
var opts = util_1.Util.extend(context.options || {}, { method: context.verb });
client.fetch(context.requestAbsoluteUrl, opts)
.then(function (response) { return context.parser.parse(response); })
.then(function (result) { return setResult(context, result); })
.then(function (ctx) { return resolve(ctx); })
.catch(function (e) { return reject(e); });
}
});
};
/**
* Logs the end of the request
*/
PipelineMethods.logEnd = function (context) {
return new Promise(function (resolve) {
if (context.isBatched) {
logging_1.Logger.log({
data: logging_1.Logger.activeLogLevel === logging_1.LogLevel.Info ? {} : context,
level: logging_1.LogLevel.Info,
message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") " + context.verb + " request will complete in batch " + context.batch.batchId + ".",
});
}
else {
logging_1.Logger.log({
data: logging_1.Logger.activeLogLevel === logging_1.LogLevel.Info ? {} : context,
level: logging_1.LogLevel.Info,
message: "[" + context.requestId + "] (" + (new Date()).getTime() + ") Completing " + context.verb + " request.",
});
}
resolve(context);
});
};
Object.defineProperty(PipelineMethods, "default", {
get: function () {
return [
PipelineMethods.logStart,
PipelineMethods.caching,
PipelineMethods.send,
PipelineMethods.logEnd,
];
},
enumerable: true,
configurable: true
});
return PipelineMethods;
}());
__decorate([
requestPipelineMethod(true)
], PipelineMethods, "logStart", null);
__decorate([
requestPipelineMethod()
], PipelineMethods, "caching", null);
__decorate([
requestPipelineMethod()
], PipelineMethods, "send", null);
__decorate([
requestPipelineMethod(true)
], PipelineMethods, "logEnd", null);
exports.PipelineMethods = PipelineMethods;
/***/ }),
/* 46 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 queryable_1 = __webpack_require__(1);
var RelatedItemManagerImpl = (function (_super) {
__extends(RelatedItemManagerImpl, _super);
function RelatedItemManagerImpl(baseUrl, path) {
if (path === void 0) { path = "_api/SP.RelatedItemManager"; }
return _super.call(this, baseUrl, path) || this;
}
RelatedItemManagerImpl.FromUrl = function (url) {
if (url === null) {
return new RelatedItemManagerImpl("");
}
var index = url.indexOf("_api/");
if (index > -1) {
return new RelatedItemManagerImpl(url.substr(0, index));
}
return new RelatedItemManagerImpl(url);
};
RelatedItemManagerImpl.prototype.getRelatedItems = function (sourceListName, sourceItemId) {
var query = this.clone(RelatedItemManagerImpl, null, true);
query.concat(".GetRelatedItems");
return query.post({
body: JSON.stringify({
SourceItemID: sourceItemId,
SourceListName: sourceListName,
}),
});
};
RelatedItemManagerImpl.prototype.getPageOneRelatedItems = function (sourceListName, sourceItemId) {
var query = this.clone(RelatedItemManagerImpl, null, true);
query.concat(".GetPageOneRelatedItems");
return query.post({
body: JSON.stringify({
SourceItemID: sourceItemId,
SourceListName: sourceListName,
}),
});
};
RelatedItemManagerImpl.prototype.addSingleLink = function (sourceListName, sourceItemId, sourceWebUrl, targetListName, targetItemID, targetWebUrl, tryAddReverseLink) {
if (tryAddReverseLink === void 0) { tryAddReverseLink = false; }
var query = this.clone(RelatedItemManagerImpl, null, true);
query.concat(".AddSingleLink");
return query.post({
body: JSON.stringify({
SourceItemID: sourceItemId,
SourceListName: sourceListName,
SourceWebUrl: sourceWebUrl,
TargetItemID: targetItemID,
TargetListName: targetListName,
TargetWebUrl: targetWebUrl,
TryAddReverseLink: tryAddReverseLink,
}),
});
};
/**
* Adds a related item link from an item specified by list name and item id, to an item specified by url
*
* @param sourceListName The source list name or list id
* @param sourceItemId The source item id
* @param targetItemUrl The target item url
* @param tryAddReverseLink If set to true try to add the reverse link (will not return error if it fails)
*/
RelatedItemManagerImpl.prototype.addSingleLinkToUrl = function (sourceListName, sourceItemId, targetItemUrl, tryAddReverseLink) {
if (tryAddReverseLink === void 0) { tryAddReverseLink = false; }
var query = this.clone(RelatedItemManagerImpl, null, true);
query.concat(".AddSingleLinkToUrl");
return query.post({
body: JSON.stringify({
SourceItemID: sourceItemId,
SourceListName: sourceListName,
TargetItemUrl: targetItemUrl,
TryAddReverseLink: tryAddReverseLink,
}),
});
};
/**
* Adds a related item link from an item specified by url, to an item specified by list name and item id
*
* @param sourceItemUrl The source item url
* @param targetListName The target list name or list id
* @param targetItemId The target item id
* @param tryAddReverseLink If set to true try to add the reverse link (will not return error if it fails)
*/
RelatedItemManagerImpl.prototype.addSingleLinkFromUrl = function (sourceItemUrl, targetListName, targetItemId, tryAddReverseLink) {
if (tryAddReverseLink === void 0) { tryAddReverseLink = false; }
var query = this.clone(RelatedItemManagerImpl, null, true);
query.concat(".AddSingleLinkFromUrl");
return query.post({
body: JSON.stringify({
SourceItemUrl: sourceItemUrl,
TargetItemID: targetItemId,
TargetListName: targetListName,
TryAddReverseLink: tryAddReverseLink,
}),
});
};
RelatedItemManagerImpl.prototype.deleteSingleLink = function (sourceListName, sourceItemId, sourceWebUrl, targetListName, targetItemId, targetWebUrl, tryDeleteReverseLink) {
if (tryDeleteReverseLink === void 0) { tryDeleteReverseLink = false; }
var query = this.clone(RelatedItemManagerImpl, null, true);
query.concat(".DeleteSingleLink");
return query.post({
body: JSON.stringify({
SourceItemID: sourceItemId,
SourceListName: sourceListName,
SourceWebUrl: sourceWebUrl,
TargetItemID: targetItemId,
TargetListName: targetListName,
TargetWebUrl: targetWebUrl,
TryDeleteReverseLink: tryDeleteReverseLink,
}),
});
};
return RelatedItemManagerImpl;
}(queryable_1.Queryable));
exports.RelatedItemManagerImpl = RelatedItemManagerImpl;
/***/ }),
/* 47 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 queryable_1 = __webpack_require__(1);
/**
* Describes a collection of webhook subscriptions
*
*/
var Subscriptions = (function (_super) {
__extends(Subscriptions, _super);
/**
* Creates a new instance of the Subscriptions class
*
* @param baseUrl - The url or Queryable which forms the parent of this webhook subscriptions collection
*/
function Subscriptions(baseUrl, path) {
if (path === void 0) { path = "subscriptions"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Returns all the webhook subscriptions or the specified webhook subscription
*
* @param subscriptionId The id of a specific webhook subscription to retrieve, omit to retrieve all the webhook subscriptions
*/
Subscriptions.prototype.getById = function (subscriptionId) {
var subscription = new Subscription(this);
subscription.concat("('" + subscriptionId + "')");
return subscription;
};
/**
* Creates a new webhook subscription
*
* @param notificationUrl The url to receive the notifications
* @param expirationDate The date and time to expire the subscription in the form YYYY-MM-ddTHH:mm:ss+00:00 (maximum of 6 months)
* @param clientState A client specific string (defaults to pnp-js-core-subscription when omitted)
*/
Subscriptions.prototype.add = function (notificationUrl, expirationDate, clientState) {
var _this = this;
var postBody = JSON.stringify({
"clientState": clientState || "pnp-js-core-subscription",
"expirationDateTime": expirationDate,
"notificationUrl": notificationUrl,
"resource": this.toUrl(),
});
return this.post({ body: postBody, headers: { "Content-Type": "application/json" } }).then(function (result) {
return { data: result, subscription: _this.getById(result.id) };
});
};
return Subscriptions;
}(queryable_1.QueryableCollection));
exports.Subscriptions = Subscriptions;
/**
* Describes a single webhook subscription instance
*
*/
var Subscription = (function (_super) {
__extends(Subscription, _super);
function Subscription() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Renews this webhook subscription
*
* @param expirationDate The date and time to expire the subscription in the form YYYY-MM-ddTHH:mm:ss+00:00 (maximum of 6 months)
*/
Subscription.prototype.update = function (expirationDate) {
var _this = this;
var postBody = JSON.stringify({
"expirationDateTime": expirationDate,
});
return this.patch({ body: postBody, headers: { "Content-Type": "application/json" } }).then(function (data) {
return { data: data, subscription: _this };
});
};
/**
* Removes this webhook subscription
*
*/
Subscription.prototype.delete = function () {
return _super.prototype.delete.call(this);
};
return Subscription;
}(queryable_1.QueryableInstance));
exports.Subscription = Subscription;
/***/ }),
/* 48 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 queryable_1 = __webpack_require__(1);
var files_1 = __webpack_require__(52);
var odata_1 = __webpack_require__(2);
var UserProfileQuery = (function (_super) {
__extends(UserProfileQuery, _super);
/**
* Creates a new instance of the UserProfileQuery class
*
* @param baseUrl The url or Queryable which forms the parent of this user profile query
*/
function UserProfileQuery(baseUrl, path) {
if (path === void 0) { path = "_api/sp.userprofiles.peoplemanager"; }
var _this = _super.call(this, baseUrl, path) || this;
_this.profileLoader = new ProfileLoader(baseUrl);
return _this;
}
Object.defineProperty(UserProfileQuery.prototype, "editProfileLink", {
/**
* The url of the edit profile page for the current user
*/
get: function () {
return this.clone(UserProfileQuery, "EditProfileLink").getAs(odata_1.ODataValue());
},
enumerable: true,
configurable: true
});
Object.defineProperty(UserProfileQuery.prototype, "isMyPeopleListPublic", {
/**
* A boolean value that indicates whether the current user's "People I'm Following" list is public
*/
get: function () {
return this.clone(UserProfileQuery, "IsMyPeopleListPublic").getAs(odata_1.ODataValue());
},
enumerable: true,
configurable: true
});
/**
* A boolean value that indicates whether the current user is being followed by the specified user
*
* @param loginName The account name of the user
*/
UserProfileQuery.prototype.amIFollowedBy = function (loginName) {
var q = this.clone(UserProfileQuery, "amifollowedby(@v)", true);
q.query.add("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
/**
* A boolean value that indicates whether the current user is following the specified user
*
* @param loginName The account name of the user
*/
UserProfileQuery.prototype.amIFollowing = function (loginName) {
var q = this.clone(UserProfileQuery, "amifollowing(@v)", true);
q.query.add("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
/**
* Gets tags that the current user is following
*
* @param maxCount The maximum number of tags to retrieve (default is 20)
*/
UserProfileQuery.prototype.getFollowedTags = function (maxCount) {
if (maxCount === void 0) { maxCount = 20; }
return this.clone(UserProfileQuery, "getfollowedtags(" + maxCount + ")", true).get();
};
/**
* Gets the people who are following the specified user
*
* @param loginName The account name of the user
*/
UserProfileQuery.prototype.getFollowersFor = function (loginName) {
var q = this.clone(UserProfileQuery, "getfollowersfor(@v)", true);
q.query.add("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
Object.defineProperty(UserProfileQuery.prototype, "myFollowers", {
/**
* Gets the people who are following the current user
*
*/
get: function () {
return new queryable_1.QueryableCollection(this, "getmyfollowers");
},
enumerable: true,
configurable: true
});
Object.defineProperty(UserProfileQuery.prototype, "myProperties", {
/**
* Gets user properties for the current user
*
*/
get: function () {
return new UserProfileQuery(this, "getmyproperties");
},
enumerable: true,
configurable: true
});
/**
* Gets the people who the specified user is following
*
* @param loginName The account name of the user.
*/
UserProfileQuery.prototype.getPeopleFollowedBy = function (loginName) {
var q = this.clone(UserProfileQuery, "getpeoplefollowedby(@v)", true);
q.query.add("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
/**
* Gets user properties for the specified user.
*
* @param loginName The account name of the user.
*/
UserProfileQuery.prototype.getPropertiesFor = function (loginName) {
var q = this.clone(UserProfileQuery, "getpropertiesfor(@v)", true);
q.query.add("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
Object.defineProperty(UserProfileQuery.prototype, "trendingTags", {
/**
* Gets the 20 most popular hash tags over the past week, sorted so that the most popular tag appears first
*
*/
get: function () {
var q = this.clone(UserProfileQuery, null, true);
q.concat(".gettrendingtags");
return q.get();
},
enumerable: true,
configurable: true
});
/**
* Gets the specified user profile property for the specified user
*
* @param loginName The account name of the user
* @param propertyName The case-sensitive name of the property to get
*/
UserProfileQuery.prototype.getUserProfilePropertyFor = function (loginName, propertyName) {
var q = this.clone(UserProfileQuery, "getuserprofilepropertyfor(accountname=@v, propertyname='" + propertyName + "')", true);
q.query.add("@v", "'" + encodeURIComponent(loginName) + "'");
return q.get();
};
/**
* Removes the specified user from the user's list of suggested people to follow
*
* @param loginName The account name of the user
*/
UserProfileQuery.prototype.hideSuggestion = function (loginName) {
var q = this.clone(UserProfileQuery, "hidesuggestion(@v)", true);
q.query.add("@v", "'" + encodeURIComponent(loginName) + "'");
return q.post();
};
/**
* A boolean values that indicates whether the first user is following the second user
*
* @param follower The account name of the user who might be following the followee
* @param followee The account name of the user who might be followed by the follower
*/
UserProfileQuery.prototype.isFollowing = function (follower, followee) {
var q = this.clone(UserProfileQuery, null, true);
q.concat(".isfollowing(possiblefolloweraccountname=@v, possiblefolloweeaccountname=@y)");
q.query.add("@v", "'" + encodeURIComponent(follower) + "'");
q.query.add("@y", "'" + encodeURIComponent(followee) + "'");
return q.get();
};
/**
* Uploads and sets the user profile picture (Users can upload a picture to their own profile only). Not supported for batching.
*
* @param profilePicSource Blob data representing the user's picture in BMP, JPEG, or PNG format of up to 4.76MB
*/
UserProfileQuery.prototype.setMyProfilePic = function (profilePicSource) {
var _this = this;
return new Promise(function (resolve, reject) {
files_1.readBlobAsArrayBuffer(profilePicSource).then(function (buffer) {
var request = new UserProfileQuery(_this, "setmyprofilepicture");
request.post({
body: String.fromCharCode.apply(null, new Uint16Array(buffer)),
}).then(function (_) { return resolve(); });
}).catch(function (e) { return reject(e); });
});
};
/**
* Provisions one or more users' personal sites. (My Site administrator on SharePoint Online only)
*
* @param emails The email addresses of the users to provision sites for
*/
UserProfileQuery.prototype.createPersonalSiteEnqueueBulk = function () {
var emails = [];
for (var _i = 0; _i < arguments.length; _i++) {
emails[_i] = arguments[_i];
}
return this.profileLoader.createPersonalSiteEnqueueBulk(emails);
};
Object.defineProperty(UserProfileQuery.prototype, "ownerUserProfile", {
/**
* Gets the user profile of the site owner
*
*/
get: function () {
return this.profileLoader.ownerUserProfile;
},
enumerable: true,
configurable: true
});
Object.defineProperty(UserProfileQuery.prototype, "userProfile", {
/**
* Gets the user profile for the current user
*/
get: function () {
return this.profileLoader.userProfile;
},
enumerable: true,
configurable: true
});
/**
* Enqueues creating a personal site for this user, which can be used to share documents, web pages, and other files
*
* @param interactiveRequest true if interactively (web) initiated request, or false (default) if non-interactively (client) initiated request
*/
UserProfileQuery.prototype.createPersonalSite = function (interactiveRequest) {
if (interactiveRequest === void 0) { interactiveRequest = false; }
return this.profileLoader.createPersonalSite(interactiveRequest);
};
/**
* Sets the privacy settings for this profile
*
* @param share true to make all social data public; false to make all social data private
*/
UserProfileQuery.prototype.shareAllSocialData = function (share) {
return this.profileLoader.shareAllSocialData(share);
};
return UserProfileQuery;
}(queryable_1.QueryableInstance));
exports.UserProfileQuery = UserProfileQuery;
var ProfileLoader = (function (_super) {
__extends(ProfileLoader, _super);
/**
* Creates a new instance of the ProfileLoader class
*
* @param baseUrl The url or Queryable which forms the parent of this profile loader
*/
function ProfileLoader(baseUrl, path) {
if (path === void 0) { path = "_api/sp.userprofiles.profileloader.getprofileloader"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Provisions one or more users' personal sites. (My Site administrator on SharePoint Online only)
*
* @param emails The email addresses of the users to provision sites for
*/
ProfileLoader.prototype.createPersonalSiteEnqueueBulk = function (emails) {
return this.clone(ProfileLoader, "createpersonalsiteenqueuebulk").post({
body: JSON.stringify({ "emailIDs": emails }),
});
};
Object.defineProperty(ProfileLoader.prototype, "ownerUserProfile", {
/**
* Gets the user profile of the site owner.
*
*/
get: function () {
var q = this.getParent(ProfileLoader, this.parentUrl, "_api/sp.userprofiles.profileloader.getowneruserprofile");
if (this.hasBatch) {
q = q.inBatch(this.batch);
}
return q.postAs();
},
enumerable: true,
configurable: true
});
Object.defineProperty(ProfileLoader.prototype, "userProfile", {
/**
* Gets the user profile of the current user.
*
*/
get: function () {
return this.clone(ProfileLoader, "getuserprofile", true).postAs();
},
enumerable: true,
configurable: true
});
/**
* Enqueues creating a personal site for this user, which can be used to share documents, web pages, and other files.
*
* @param interactiveRequest true if interactively (web) initiated request, or false (default) if non-interactively (client) initiated request
*/
ProfileLoader.prototype.createPersonalSite = function (interactiveRequest) {
if (interactiveRequest === void 0) { interactiveRequest = false; }
return this.clone(ProfileLoader, "getuserprofile/createpersonalsiteenque(" + interactiveRequest + ")", true).post();
};
/**
* Sets the privacy settings for this profile
*
* @param share true to make all social data public; false to make all social data private.
*/
ProfileLoader.prototype.shareAllSocialData = function (share) {
return this.clone(ProfileLoader, "getuserprofile/shareallsocialdata(" + share + ")", true).post();
};
return ProfileLoader;
}(queryable_1.Queryable));
/***/ }),
/* 49 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 queryable_1 = __webpack_require__(1);
var util_1 = __webpack_require__(0);
/**
* Describes the views available in the current context
*
*/
var Views = (function (_super) {
__extends(Views, _super);
/**
* Creates a new instance of the Views class
*
* @param baseUrl The url or Queryable which forms the parent of this fields collection
*/
function Views(baseUrl, path) {
if (path === void 0) { path = "views"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a view by guid id
*
* @param id The GUID id of the view
*/
Views.prototype.getById = function (id) {
var v = new View(this);
v.concat("('" + id + "')");
return v;
};
/**
* Gets a view by title (case-sensitive)
*
* @param title The case-sensitive title of the view
*/
Views.prototype.getByTitle = function (title) {
return new View(this, "getByTitle('" + title + "')");
};
/**
* Adds a new view to the collection
*
* @param title The new views's title
* @param personalView True if this is a personal view, otherwise false, default = false
* @param additionalSettings Will be passed as part of the view creation body
*/
/*tslint:disable max-line-length */
Views.prototype.add = function (title, personalView, additionalSettings) {
var _this = this;
if (personalView === void 0) { personalView = false; }
if (additionalSettings === void 0) { additionalSettings = {}; }
var postBody = JSON.stringify(util_1.Util.extend({
"PersonalView": personalView,
"Title": title,
"__metadata": { "type": "SP.View" },
}, additionalSettings));
return this.clone(Views, null, true).postAs({ body: postBody }).then(function (data) {
return {
data: data,
view: _this.getById(data.Id),
};
});
};
return Views;
}(queryable_1.QueryableCollection));
exports.Views = Views;
/**
* Describes a single View instance
*
*/
var View = (function (_super) {
__extends(View, _super);
function View() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(View.prototype, "fields", {
get: function () {
return new ViewFields(this);
},
enumerable: true,
configurable: true
});
/**
* Updates this view intance with the supplied properties
*
* @param properties A plain object hash of values to update for the view
*/
View.prototype.update = function (properties) {
var _this = this;
var postBody = JSON.stringify(util_1.Util.extend({
"__metadata": { "type": "SP.View" },
}, properties));
return this.post({
body: postBody,
headers: {
"X-HTTP-Method": "MERGE",
},
}).then(function (data) {
return {
data: data,
view: _this,
};
});
};
/**
* Delete this view
*
*/
View.prototype.delete = function () {
return this.post({
headers: {
"X-HTTP-Method": "DELETE",
},
});
};
/**
* Returns the list view as HTML.
*
*/
View.prototype.renderAsHtml = function () {
return this.clone(queryable_1.Queryable, "renderashtml", true).get();
};
return View;
}(queryable_1.QueryableInstance));
exports.View = View;
var ViewFields = (function (_super) {
__extends(ViewFields, _super);
function ViewFields(baseUrl, path) {
if (path === void 0) { path = "viewfields"; }
return _super.call(this, baseUrl, path) || this;
}
/**
* Gets a value that specifies the XML schema that represents the collection.
*/
ViewFields.prototype.getSchemaXml = function () {
return this.clone(queryable_1.Queryable, "schemaxml", true).get();
};
/**
* Adds the field with the specified field internal name or display name to the collection.
*
* @param fieldTitleOrInternalName The case-sensitive internal name or display name of the field to add.
*/
ViewFields.prototype.add = function (fieldTitleOrInternalName) {
return this.clone(ViewFields, "addviewfield('" + fieldTitleOrInternalName + "')", true).post();
};
/**
* Moves the field with the specified field internal name to the specified position in the collection.
*
* @param fieldInternalName The case-sensitive internal name of the field to move.
* @param index The zero-based index of the new position for the field.
*/
ViewFields.prototype.move = function (fieldInternalName, index) {
return this.clone(ViewFields, "moveviewfieldto", true).post({
body: JSON.stringify({ "field": fieldInternalName, "index": index }),
});
};
/**
* Removes all the fields from the collection.
*/
ViewFields.prototype.removeAll = function () {
return this.clone(ViewFields, "removeallviewfields", true).post();
};
/**
* Removes the field with the specified field internal name from the collection.
*
* @param fieldInternalName The case-sensitive internal name of the field to remove from the view.
*/
ViewFields.prototype.remove = function (fieldInternalName) {
return this.clone(ViewFields, "removeviewfield('" + fieldInternalName + "')", true).post();
};
return ViewFields;
}(queryable_1.QueryableCollection));
exports.ViewFields = ViewFields;
/***/ }),
/* 50 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
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 queryable_1 = __webpack_require__(1);
var LimitedWebPartManager = (function (_super) {
__extends(LimitedWebPartManager, _super);
function LimitedWebPartManager() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(LimitedWebPartManager.prototype, "webparts", {
/**
* Gets the set of web part definitions contained by this web part manager
*
*/
get: function () {
return new WebPartDefinitions(this, "webparts");
},
enumerable: true,
configurable: true
});
/**
* Exports a webpart definition
*
* @param id the GUID id of the definition to export
*/
LimitedWebPartManager.prototype.export = function (id) {
return this.clone(LimitedWebPartManager, "ExportWebPart", true).post({
body: JSON.stringify({ webPartId: id }),
});
};
/**
* Imports a webpart
*
* @param xml webpart definition which must be valid XML in the .dwp or .webpart format
*/
LimitedWebPartManager.prototype.import = function (xml) {
return this.clone(LimitedWebPartManager, "ImportWebPart", true).post({
body: JSON.stringify({ webPartXml: xml }),
});
};
return LimitedWebPartManager;
}(queryable_1.Queryable));
exports.LimitedWebPartManager = LimitedWebPartManager;
var WebPartDefinitions = (function (_super) {
__extends(WebPartDefinitions, _super);
function WebPartDefinitions() {
return _super !== null && _super.apply(this, arguments) || this;
}
/**
* Gets a web part definition from the collection by id
*
* @param id GUID id of the web part definition to get
*/
WebPartDefinitions.prototype.getById = function (id) {
return new WebPartDefinition(this, "getbyid('" + id + "')");
};
return WebPartDefinitions;
}(queryable_1.QueryableCollection));
exports.WebPartDefinitions = WebPartDefinitions;
var WebPartDefinition = (function (_super) {
__extends(WebPartDefinition, _super);
function WebPartDefinition() {
return _super !== null && _super.apply(this, arguments) || this;
}
Object.defineProperty(WebPartDefinition.prototype, "webpart", {
/**
* Gets the webpart information associated with this definition
*/
get: function () {
return new WebPart(this);
},
enumerable: true,
configurable: true
});
/**
* Removes a webpart from a page, all settings will be lost
*/
WebPartDefinition.prototype.delete = function () {
return this.clone(WebPartDefinition, "DeleteWebPart", true).post();
};
return WebPartDefinition;
}(queryable_1.QueryableInstance));
exports.WebPartDefinition = WebPartDefinition;
var WebPart = (function (_super) {
__extends(WebPart, _super);
/**
* Creates a new instance of the WebPart class
*
* @param baseUrl The url or Queryable which forms the parent of this fields collection
* @param path Optional, if supplied will be appended to the supplied baseUrl
*/
function WebPart(baseUrl, path) {
if (path === void 0) { path = "webpart"; }
return _super.call(this, baseUrl, path) || this;
}
return WebPart;
}(queryable_1.QueryableInstance));
exports.WebPart = WebPart;
/***/ }),
/* 51 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var logging_1 = __webpack_require__(5);
function deprecated(message) {
return function (target, propertyKey, descriptor) {
var method = descriptor.value;
descriptor.value = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
logging_1.Logger.log({
data: {
descriptor: descriptor,
propertyKey: propertyKey,
target: target,
},
level: logging_1.LogLevel.Warning,
message: message,
});
return method.apply(this, args);
};
};
}
exports.deprecated = deprecated;
/***/ }),
/* 52 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
* Reads a blob as text
*
* @param blob The data to read
*/
function readBlobAsText(blob) {
return readBlobAs(blob, "string");
}
exports.readBlobAsText = readBlobAsText;
/**
* Reads a blob into an array buffer
*
* @param blob The data to read
*/
function readBlobAsArrayBuffer(blob) {
return readBlobAs(blob, "buffer");
}
exports.readBlobAsArrayBuffer = readBlobAsArrayBuffer;
/**
* Generic method to read blob's content
*
* @param blob The data to read
* @param mode The read mode
*/
function readBlobAs(blob, mode) {
return new Promise(function (resolve, reject) {
try {
var reader = new FileReader();
reader.onload = function (e) {
resolve(e.target.result);
};
switch (mode) {
case "string":
reader.readAsText(blob);
break;
case "buffer":
reader.readAsArrayBuffer(blob);
break;
}
}
catch (e) {
reject(e);
}
});
}
/***/ })
/******/ ]);
});
//# sourceMappingURL=pnp.js.map | maruilian11/cdnjs | ajax/libs/sp-pnp-js/2.0.6-beta.1/pnp.js | JavaScript | mit | 373,699 |
//// [invalidThisEmitInContextualObjectLiteral.ts]
interface IDef {
p1: (e:string) => void;
p2: () => (n: number) => any;
}
class TestController {
public m(def: IDef) { }
public p = this.m({
p1: e => { },
p2: () => { return vvvvvvvvv => this; },
});
}
//// [invalidThisEmitInContextualObjectLiteral.js]
var TestController = (function () {
function TestController() {
var _this = this;
this.p = this.m({
p1: function (e) { },
p2: function () { return function (vvvvvvvvv) { return _this; }; }
});
}
TestController.prototype.m = function (def) { };
return TestController;
}());
| mihailik/TypeScript | tests/baselines/reference/invalidThisEmitInContextualObjectLiteral.js | JavaScript | apache-2.0 | 667 |
var leafletDirective = angular.module("leaflet-directive", []);
leafletDirective.directive('leaflet', [
'$http', '$log', '$parse', '$rootScope', function ($http, $log, $parse, $rootScope) {
var defaults = {
maxZoom: 14,
minZoom: 1,
doubleClickZoom: true,
tileLayer: 'http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png',
tileLayerOptions: {
attribution: 'Tiles © Open Street Maps'
},
icon: {
url: 'http://cdn.leafletjs.com/leaflet-0.5.1/images/marker-icon.png',
retinaUrl: 'http://cdn.leafletjs.com/leaflet-0.5.1/images/[email protected]',
size: [25, 41],
anchor: [12, 40],
popup: [0, -40],
shadow: {
url: 'http://cdn.leafletjs.com/leaflet-0.5.1/images/marker-shadow.png',
retinaUrl: 'http://cdn.leafletjs.com/leaflet-0.5.1/images/marker-shadow.png',
size: [41, 41],
anchor: [12, 40]
}
},
path: {
weight: 10,
opacity: 1,
color: '#0000ff'
}
};
var str_inspect_hint = 'Add testing="testing" to <leaflet> tag to inspect this object';
return {
restrict: "E",
replace: true,
transclude: true,
scope: {
center: '=center',
maxBounds: '=maxbounds',
bounds: '=bounds',
marker: '=marker',
markers: '=markers',
defaults: '=defaults',
paths: '=paths',
tiles: '=tiles',
events: '=events'
},
template: '<div class="angular-leaflet-map"></div>',
link: function ($scope, element, attrs /*, ctrl */) {
var centerModel = {
lat:$parse("center.lat"),
lng:$parse("center.lng"),
zoom:$parse("center.zoom")
};
if (attrs.width) {
element.css('width', attrs.width);
}
if (attrs.height) {
element.css('height', attrs.height);
}
$scope.leaflet = {};
$scope.leaflet.maxZoom = !!(attrs.defaults && $scope.defaults && $scope.defaults.maxZoom) ?
parseInt($scope.defaults.maxZoom, 10) : defaults.maxZoom;
$scope.leaflet.minZoom = !!(attrs.defaults && $scope.defaults && $scope.defaults.minZoom) ?
parseInt($scope.defaults.minZoom, 10) : defaults.minZoom;
$scope.leaflet.doubleClickZoom = !!(attrs.defaults && $scope.defaults && (typeof($scope.defaults.doubleClickZoom) == "boolean") ) ? $scope.defaults.doubleClickZoom : defaults.doubleClickZoom;
var map = new L.Map(element[0], {
maxZoom: $scope.leaflet.maxZoom,
minZoom: $scope.leaflet.minZoom,
doubleClickZoom: $scope.leaflet.doubleClickZoom
});
map.setView([0, 0], 1);
$scope.leaflet.tileLayer = !!(attrs.defaults && $scope.defaults && $scope.defaults.tileLayer) ?
$scope.defaults.tileLayer : defaults.tileLayer;
$scope.leaflet.map = !!attrs.testing ? map : str_inspect_hint;
setupTiles();
setupCenter();
setupMaxBounds();
setupBounds();
setupMainMaerker();
setupMarkers();
setupPaths();
setupEvents();
// use of leafletDirectiveSetMap event is not encouraged. only use
// it when there is no easy way to bind data to the directive
$scope.$on('leafletDirectiveSetMap', function(event, message) {
var meth = message.shift();
map[meth].apply(map, message);
});
$scope.safeApply = function(fn) {
var phase = this.$root.$$phase;
if (phase == '$apply' || phase == '$digest') {
$scope.$eval(fn);
} else {
$scope.$apply(fn);
}
};
/*
* Event setup watches for callbacks set in the parent scope
*
* $scope.events = {
* dblclick: function(){
* // doThis()
* },
* click: function(){
* // doThat()
* }
* }
* */
function setupEvents(){
if ( typeof($scope.events) != 'object'){
return false;
}else{
for (var bind_to in $scope.events){
map.on(bind_to,$scope.events[bind_to]);
}
}
}
function setupTiles(){
// TODO build custom object for tiles, actually only the tile string
if ($scope.defaults && $scope.defaults.tileLayerOptions) {
for (var key in $scope.defaults.tileLayerOptions) {
defaults.tileLayerOptions[key] = $scope.defaults.tileLayerOptions[key];
}
}
if ($scope.tiles) {
if ($scope.tiles.tileLayer) {
$scope.leaflet.tileLayer = $scope.tiles.tileLayer;
}
if ($scope.tiles.tileLayerOptions.attribution) {
defaults.tileLayerOptions.attribution = $scope.tiles.tileLayerOptions.attribution;
}
}
var tileLayerObj = L.tileLayer(
$scope.leaflet.tileLayer, defaults.tileLayerOptions);
tileLayerObj.addTo(map);
$scope.leaflet.tileLayerObj = !!attrs.testing ? tileLayerObj : str_inspect_hint;
}
function setupMaxBounds() {
if (!$scope.maxBounds) {
return;
}
if ($scope.maxBounds.southWest && $scope.maxBounds.southWest.lat && $scope.maxBounds.southWest.lng && $scope.maxBounds.northEast && $scope.maxBounds.northEast.lat && $scope.maxBounds.northEast.lng) {
map.setMaxBounds(
new L.LatLngBounds(
new L.LatLng($scope.maxBounds.southWest.lat, $scope.maxBounds.southWest.lng),
new L.LatLng($scope.maxBounds.northEast.lat, $scope.maxBounds.northEast.lng)
)
);
$scope.$watch("maxBounds", function (maxBounds) {
if (maxBounds.southWest && maxBounds.northEast && maxBounds.southWest.lat && maxBounds.southWest.lng && maxBounds.northEast.lat && maxBounds.northEast.lng) {
map.setMaxBounds(
new L.LatLngBounds(
new L.LatLng(maxBounds.southWest.lat, maxBounds.southWest.lng),
new L.LatLng(maxBounds.northEast.lat, maxBounds.northEast.lng)
)
);
}
});
}
}
function tryFitBounds(bounds) {
if (bounds) {
var southWest = bounds.southWest;
var northEast = bounds.northEast;
if (southWest && northEast && southWest.lat && southWest.lng && northEast.lat && northEast.lng) {
var sw_latlng = new L.LatLng(southWest.lat, southWest.lng);
var ne_latlng = new L.LatLng(northEast.lat, northEast.lng);
map.fitBounds(new L.LatLngBounds(sw_latlng, ne_latlng));
}
}
}
function setupBounds() {
if (!$scope.bounds) {
return;
}
$scope.$watch('bounds', function (new_bounds) {
tryFitBounds(new_bounds);
});
}
function setupCenter() {
$scope.$watch("center", function (center) {
if (!center) {
$log.warn("[AngularJS - Leaflet] 'center' is undefined in the current scope, did you forget to initialize it?");
return;
}
if (center.lat && center.lng && center.zoom) {
map.setView([center.lat, center.lng], center.zoom);
} else if (center.autoDiscover === true) {
map.locate({ setView: true, maxZoom: $scope.leaflet.maxZoom });
}
}, true);
map.on("dragend", function (/* event */) {
$scope.safeApply(function (scope) {
centerModel.lat.assign(scope, map.getCenter().lat);
centerModel.lng.assign(scope, map.getCenter().lng);
});
});
map.on("zoomend", function (/* event */) {
if(angular.isUndefined($scope.center)){
$log.warn("[AngularJS - Leaflet] 'center' is undefined in the current scope, did you forget to initialize it?");
}
if (angular.isUndefined($scope.center) || $scope.center.zoom !== map.getZoom()) {
$scope.safeApply(function (s) {
centerModel.zoom.assign(s, map.getZoom());
centerModel.lat.assign(s, map.getCenter().lat);
centerModel.lng.assign(s, map.getCenter().lng);
});
}
});
}
function setupMainMaerker() {
var main_marker;
if (!$scope.marker) {
return;
}
main_marker = createMarker('marker', $scope.marker, map);
$scope.leaflet.marker = !!attrs.testing ? main_marker : str_inspect_hint;
main_marker.on('click', function(e) {
$rootScope.$broadcast('leafletDirectiveMainMarkerClick');
});
}
function setupMarkers() {
var markers = {};
$scope.leaflet.markers = !!attrs.testing ? markers : str_inspect_hint;
if (!$scope.markers) {
return;
}
function genMultiMarkersClickCallback(m_name) {
return function(e) {
$rootScope.$broadcast('leafletDirectiveMarkersClick', m_name);
};
}
for (var name in $scope.markers) {
markers[name] = createMarker(
'markers.'+name, $scope.markers[name], map);
markers[name].on('click', genMultiMarkersClickCallback(name));
}
$scope.$watch('markers', function(newMarkers) {
// Delete markers from the array
for (var name in markers) {
if (newMarkers[name] === undefined) {
delete markers[name];
}
}
// add new markers
for (var new_name in newMarkers) {
if (markers[new_name] === undefined) {
markers[new_name] = createMarker(
'markers.'+new_name, newMarkers[new_name], map);
markers[new_name].on('click', genMultiMarkersClickCallback(new_name));
}
}
}, true);
}
function createMarker(scope_watch_name, marker_data, map) {
var marker = buildMarker(marker_data);
map.addLayer(marker);
if (marker_data.focus === true) {
marker.openPopup();
}
marker.on("dragend", function () {
$scope.safeApply(function (scope) {
marker_data.lat = marker.getLatLng().lat;
marker_data.lng = marker.getLatLng().lng;
});
if (marker_data.message) {
marker.openPopup();
}
});
var clearWatch = $scope.$watch(scope_watch_name, function (data, old_data) {
if (!data) {
map.removeLayer(marker);
clearWatch();
return;
}
if (old_data) {
if (data.draggable !== undefined && data.draggable !== old_data.draggable) {
if (data.draggable === true) {
marker.dragging.enable();
} else {
marker.dragging.disable();
}
}
if (data.focus !== undefined && data.focus !== old_data.focus) {
if (data.focus === true) {
marker.openPopup();
} else {
marker.closePopup();
}
}
if (data.message !== undefined && data.message !== old_data.message) {
marker.bindPopup(data);
}
if (data.lat !== old_data.lat || data.lng !== old_data.lng) {
marker.setLatLng(new L.LatLng(data.lat, data.lng));
}
if (data.icon && data.icon !== old_data.icon) {
marker.setIcon(data.icon);
}
}
}, true);
return marker;
}
function buildMarker(data) {
var micon = null;
if (data.icon) {
micon = data.icon;
} else {
micon = buildIcon();
}
var marker = new L.marker(data,
{
icon: micon,
draggable: data.draggable ? true : false
}
);
if (data.message) {
marker.bindPopup(data.message);
}
return marker;
}
function buildIcon() {
return L.icon({
iconUrl: defaults.icon.url,
iconRetinaUrl: defaults.icon.retinaUrl,
iconSize: defaults.icon.size,
iconAnchor: defaults.icon.anchor,
popupAnchor: defaults.icon.popup,
shadowUrl: defaults.icon.shadow.url,
shadowRetinaUrl: defaults.icon.shadow.retinaUrl,
shadowSize: defaults.icon.shadow.size,
shadowAnchor: defaults.icon.shadow.anchor
});
}
function setupPaths() {
var paths = {};
$scope.leaflet.paths = !!attrs.testing ? paths : str_inspect_hint;
if (!$scope.paths) {
return;
}
$log.warn("[AngularJS - Leaflet] Creating polylines and adding them to the map will break the directive's scope's inspection in AngularJS Batarang");
for (var name in $scope.paths) {
paths[name] = createPath(name, $scope.paths[name], map);
}
$scope.$watch("paths", function (newPaths) {
for (var new_name in newPaths) {
if (paths[new_name] === undefined) {
paths[new_name] = createPath(new_name, newPaths[new_name], map);
}
}
// Delete paths from the array
for (var name in paths) {
if (newPaths[name] === undefined) {
delete paths[name];
}
}
}, true);
}
function createPath(name, scopePath, map) {
var polyline = new L.Polyline([], {
weight: defaults.path.weight,
color: defaults.path.color,
opacity: defaults.path.opacity
});
if (scopePath.latlngs !== undefined) {
var latlngs = convertToLeafletLatLngs(scopePath.latlngs);
polyline.setLatLngs(latlngs);
}
if (scopePath.weight !== undefined) {
polyline.setStyle({ weight: scopePath.weight });
}
if (scopePath.color !== undefined) {
polyline.setStyle({ color: scopePath.color });
}
if (scopePath.opacity !== undefined) {
polyline.setStyle({ opacity: scopePath.opacity });
}
map.addLayer(polyline);
var clearWatch = $scope.$watch('paths.' + name, function (data, oldData) {
if (!data) {
map.removeLayer(polyline);
clearWatch();
return;
}
if (oldData) {
if (data.latlngs !== undefined && data.latlngs !== oldData.latlngs) {
var latlngs = convertToLeafletLatLngs(data.latlngs);
polyline.setLatLngs(latlngs);
}
if (data.weight !== undefined && data.weight !== oldData.weight) {
polyline.setStyle({ weight: data.weight });
}
if (data.color !== undefined && data.color !== oldData.color) {
polyline.setStyle({ color: data.color });
}
if (data.opacity !== undefined && data.opacity !== oldData.opacity) {
polyline.setStyle({ opacity: data.opacity });
}
}
}, true);
return polyline;
}
function convertToLeafletLatLngs(latlngs) {
var leafletLatLngs = latlngs.filter(function (latlng) {
return !!latlng.lat && !!latlng.lng;
}).map(function (latlng) {
return new L.LatLng(latlng.lat, latlng.lng);
});
return leafletLatLngs;
}
}
};
}]);
| him2him2/cdnjs | ajax/libs/ui-leaflet/0.5.0/angular-leaflet-directive.js | JavaScript | mit | 19,188 |
/**
* AngularJS filter for Numeral.js: number formatting as a filter
* @version v2.0.1 - 2017-05-06
* @link https://github.com/baumandm/angular-numeraljs
* @author Dave Bauman <[email protected]>
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
"use strict";!function(a,b){"object"==typeof exports?module.exports=b(require("numeral")):"function"==typeof define&&define.amd?define(["numeral"],function(c){return a.ngNumeraljs=b(c)}):a.ngNumeraljs=b(a.numeral)}(this,function(a){return angular.module("ngNumeraljs",[]).provider("$numeraljsConfig",function(){var b={};this.defaultFormat=function(b){a.defaultFormat(b)},this.locale=function(b){a.locale(b)},this.namedFormat=function(a,c){b[a]=c},this.register=function(b,c,d){a.register(b,c,d)},this.$get=function(){return{customFormat:function(a){return b[a]||a},defaultFormat:this.defaultFormat,locale:this.locale,register:this.register,namedFormat:this.namedFormat}}}).filter("numeraljs",["$numeraljsConfig",function(b){return function(c,d){return null==c?c:(d=b.customFormat(d),a(c).format(d))}}])}); | baumandm/angular-numeraljs | dist/angular-numeraljs.min.js | JavaScript | mit | 1,075 |
/**
* Add your manual test filenames and display names below.
**/
var tests = [
{ href: "test-add.html", name: "Add Events" },
{ href: "test-delete.html", name: "Delete Events" },
{ href: "test-tracks.html", name: "Add Tracks" },
{ href: "test-vimeo.html", name: "Change Media to Vimeo" },
{ href: "test-youtube.html", name: "Change Media to YouTube" },
{ href: "test-save.html", name: "Save and Load" },
{ href: "test-share.html", name: "Share HTML5 project" },
{ href: "test-sharevimeo.html", name: "Share Vimeo project" },
{ href: "test-shareyoutube.html", name: "Share YouTube project" },
{ href: "test-export.html", name: "Export HTML5 project" }
].reverse();
| ScottDowne/popcorn.webmaker.org | public/test/manual-tests/tests.js | JavaScript | mit | 687 |
/*
Copyright (c) 2003-2010, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.html or http://ckeditor.com/license
*/
/**
* @file Horizontal Page Break
*/
// Register a plugin named "pagebreak".
CKEDITOR.plugins.add( 'pagebreak',
{
init : function( editor )
{
// Register the command.
editor.addCommand( 'pagebreak', CKEDITOR.plugins.pagebreakCmd );
// Register the toolbar button.
editor.ui.addButton( 'PageBreak',
{
label : editor.lang.pagebreak,
command : 'pagebreak'
});
// Add the style that renders our placeholder.
editor.addCss(
'img.cke_pagebreak' +
'{' +
'background-image: url(' + CKEDITOR.getUrl( this.path + 'images/pagebreak.gif' ) + ');' +
'background-position: center center;' +
'background-repeat: no-repeat;' +
'clear: both;' +
'display: block;' +
'float: none;' +
'width: 100%;' +
'border-top: #999999 1px dotted;' +
'border-bottom: #999999 1px dotted;' +
'height: 5px;' +
'}' );
},
afterInit : function( editor )
{
// Register a filter to displaying placeholders after mode change.
var dataProcessor = editor.dataProcessor,
dataFilter = dataProcessor && dataProcessor.dataFilter;
if ( dataFilter )
{
dataFilter.addRules(
{
elements :
{
div : function( element )
{
var attributes = element.attributes,
style = attributes && attributes.style,
child = style && element.children.length == 1 && element.children[ 0 ],
childStyle = child && ( child.name == 'span' ) && child.attributes.style;
if ( childStyle && ( /page-break-after\s*:\s*always/i ).test( style ) && ( /display\s*:\s*none/i ).test( childStyle ) )
return editor.createFakeParserElement( element, 'cke_pagebreak', 'div' );
}
}
});
}
},
requires : [ 'fakeobjects' ]
});
CKEDITOR.plugins.pagebreakCmd =
{
exec : function( editor )
{
// Create the element that represents a print break.
var breakObject = CKEDITOR.dom.element.createFromHtml( '<div style="page-break-after: always;"><span style="display: none;"> </span></div>' );
// Creates the fake image used for this element.
breakObject = editor.createFakeElement( breakObject, 'cke_pagebreak', 'div' );
var ranges = editor.getSelection().getRanges();
for ( var range, i = 0 ; i < ranges.length ; i++ )
{
range = ranges[ i ];
if ( i > 0 )
breakObject = breakObject.clone( true );
range.splitBlock( 'p' );
range.insertNode( breakObject );
}
}
};
| adefreitea/expidian | web/bundles/expidian/js/ckeditor/plugins/pagebreak/plugin.js | JavaScript | mit | 2,644 |
define(["dojo/_base/declare","./AnalogIndicatorBase"],
function(declare, AnalogIndicatorBase) {
return declare("dojox.gauges.AnalogArrowIndicator", [AnalogIndicatorBase],{
// summary:
// An indicator for the AnalogGauge that draws an arrow. The arrow is drawn on the angle that corresponds
// to the value of the indicator.
_getShapes: function(group){
// summary:
// Override of dojox.gauges.AnalogLineIndicator._getShapes
if(!this._gauge){
return null;
}
var color = this.color ? this.color : 'black';
var strokeColor = this.strokeColor ? this.strokeColor : color;
var stroke = { color: strokeColor, width: 1};
if (this.color.type && !this.strokeColor){
stroke.color = this.color.colors[0].color;
}
var x = Math.floor(this.width/2);
var head = this.width * 5;
var odd = (this.width & 1);
var shapes = [];
var points = [{x:-x, y:0},
{x:-x, y:-this.length+head},
{x:-2*x, y:-this.length+head},
{x:0, y:-this.length},
{x:2*x+odd,y:-this.length+head},
{x:x+odd, y:-this.length+head},
{x:x+odd, y:0},
{x:-x, y:0}];
shapes[0] = group.createPolyline(points)
.setStroke(stroke)
.setFill(color);
shapes[1] = group.createLine({ x1:-x, y1: 0, x2: -x, y2:-this.length+head })
.setStroke({color: this.highlight});
shapes[2] = group.createLine({ x1:-x-3, y1: -this.length+head, x2: 0, y2:-this.length })
.setStroke({color: this.highlight});
shapes[3] = group.createCircle({cx: 0, cy: 0, r: this.width})
.setStroke(stroke)
.setFill(color);
return shapes;
}
});
}); | avz-cmf/zaboy-middleware | www/js/dojox/gauges/AnalogArrowIndicator.js | JavaScript | gpl-3.0 | 1,598 |
/*
Copyright (c) 2003-2015, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'save', 'af', {
toolbar: 'Bewaar'
} );
| aodarc/flowers_room | styleguides/static/ckeditor/ckeditor/plugins/save/lang/af.js | JavaScript | mit | 212 |
define(
//begin v1.x content
{
"field-sat-relative+0": "เสาร์นี้",
"field-sat-relative+1": "เสาร์หน้า",
"field-dayperiod": "ช่วงวัน",
"field-sun-relative+-1": "อาทิตย์ที่แล้ว",
"field-mon-relative+-1": "จันทร์ที่แล้ว",
"field-minute": "นาที",
"field-day-relative+-1": "เมื่อวาน",
"field-weekday": "วันในสัปดาห์",
"field-day-relative+-2": "เมื่อวานซืน",
"months-standAlone-narrow": [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13"
],
"field-era": "สมัย",
"field-hour": "ชั่วโมง",
"field-sun-relative+0": "อาทิตย์นี้",
"field-sun-relative+1": "อาทิตย์หน้า",
"months-standAlone-abbr": [
"เมสเคอเรม",
"เตเกมท",
"เฮดาร์",
"ทาฮ์ซัส",
"เทอร์",
"เยคาทิท",
"เมกาบิต",
"เมียเซีย",
"เจนบอต",
"เซเน",
"ฮัมเล",
"เนแฮซ",
"พากูเมน"
],
"field-wed-relative+-1": "พุธที่แล้ว",
"field-day-relative+0": "วันนี้",
"field-day-relative+1": "พรุ่งนี้",
"field-day-relative+2": "มะรืนนี้",
"field-tue-relative+0": "อังคารนี้",
"field-zone": "เขตเวลา",
"field-tue-relative+1": "อังคารหน้า",
"field-week-relative+-1": "สัปดาห์ที่แล้ว",
"field-year-relative+0": "ปีนี้",
"field-year-relative+1": "ปีหน้า",
"field-sat-relative+-1": "เสาร์ที่แล้ว",
"field-year-relative+-1": "ปีที่แล้ว",
"field-year": "ปี",
"field-fri-relative+0": "ศุกร์นี้",
"field-fri-relative+1": "ศุกร์หน้า",
"months-standAlone-wide": [
"เมสเคอเรม",
"เตเกมท",
"เฮดาร์",
"ทาฮ์ซัส",
"เทอร์",
"เยคาทิท",
"เมกาบิต",
"เมียเซีย",
"เจนบอต",
"เซเน",
"ฮัมเล",
"เนแฮซ",
"พากูเมน"
],
"field-week": "สัปดาห์",
"field-week-relative+0": "สัปดาห์นี้",
"field-week-relative+1": "สัปดาห์หน้า",
"months-format-abbr": [
"เมสเคอเรม",
"เตเกมท",
"เฮดาร์",
"ทาฮ์ซัส",
"เทอร์",
"เยคาทิท",
"เมกาบิต",
"เมียเซีย",
"เจนบอต",
"เซเน",
"ฮัมเล",
"เนแฮซ",
"พากูเมน"
],
"field-month-relative+0": "เดือนนี้",
"field-month": "เดือน",
"field-month-relative+1": "เดือนหน้า",
"field-fri-relative+-1": "ศุกร์ที่แล้ว",
"field-second": "วินาที",
"field-tue-relative+-1": "อังคารที่แล้ว",
"field-day": "วัน",
"months-format-narrow": [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13"
],
"field-mon-relative+0": "จันทร์นี้",
"field-mon-relative+1": "จันทร์หน้า",
"field-thu-relative+0": "พฤหัสนี้",
"field-second-relative+0": "ขณะนี้",
"field-thu-relative+1": "พฤหัสหน้า",
"months-format-wide": [
"เมสเคอเรม",
"เตเกมท",
"เฮดาร์",
"ทาฮ์ซัส",
"เทอร์",
"เยคาทิท",
"เมกาบิต",
"เมียเซีย",
"เจนบอต",
"เซเน",
"ฮัมเล",
"เนแฮซ",
"พากูเมน"
],
"field-wed-relative+0": "พุธนี้",
"field-wed-relative+1": "พุธหน้า",
"field-month-relative+-1": "เดือนที่แล้ว",
"field-thu-relative+-1": "พฤหัสที่แล้ว"
}
//end v1.x content
); | srujant/MLNews | static/js/cesium/ThirdParty/dojo-release-1.10.4/dojo/cldr/nls/th/ethiopic.js | JavaScript | mit | 4,368 |
/* Copyright (c) 2006 Yahoo! Inc. All rights reserved. */
/**
* @class The Yahoo global namespace
*/
var YAHOO = function() {
return {
/**
* Yahoo presentation platform utils namespace
*/
util: {},
/**
* Yahoo presentation platform widgets namespace
*/
widget: {},
/**
* Yahoo presentation platform examples namespace
*/
example: {},
/**
* Returns the namespace specified and creates it if it doesn't exist
*
* YAHOO.namespace("property.package");
* YAHOO.namespace("YAHOO.property.package");
*
* Either of the above would create YAHOO.property, then
* YAHOO.property.package
*
* @param {String} sNameSpace String representation of the desired
* namespace
* @return {Object} A reference to the namespace object
*/
namespace: function( sNameSpace ) {
if (!sNameSpace || !sNameSpace.length) {
return null;
}
var levels = sNameSpace.split(".");
var currentNS = YAHOO;
// YAHOO is implied, so it is ignored if it is included
for (var i=(levels[0] == "YAHOO") ? 1 : 0; i<levels.length; ++i) {
currentNS[levels[i]] = currentNS[levels[i]] || {};
currentNS = currentNS[levels[i]];
}
return currentNS;
}
};
} ();
| ArrozAlba/huayra | srh/public/js/grid/calendar/YAHOO.js | JavaScript | gpl-2.0 | 1,547 |
/*
---
name: Picker.Date
description: Creates a DatePicker, can be used for picking years/months/days and time, or all of them
authors: Arian Stolwijk
requires: [Picker, Picker.Attach, Locale.en-US.DatePicker, More/Locale, More/Date]
provides: Picker.Date
...
*/
(function(){this.DatePicker=Picker.Date=new Class({Extends:Picker.Attach,options:{timePicker:false,timePickerOnly:false,timeWheelStep:1,yearPicker:true,yearsPerPage:20,startDay:1,rtl:false,startView:"days",openLastView:false,pickOnly:false,canAlwaysGoUp:["months","days"],updateAll:false,weeknumbers:false,months_abbr:null,days_abbr:null,years_title:function(f,e){var g=f.get("year");
return g+"-"+(g+e.yearsPerPage-1);},months_title:function(f,e){return f.get("year");},days_title:function(f,e){return f.format("%b %Y");},time_title:function(f,e){return(e.pickOnly=="time")?Locale.get("DatePicker.select_a_time"):f.format("%d %B, %Y");
}},initialize:function(g,f){this.parent(g,f);this.setOptions(f);f=this.options;["year","month","day","time"].some(function(h){if(f[h+"PickerOnly"]){f.pickOnly=h;
return true;}return false;});if(f.pickOnly){f[f.pickOnly+"Picker"]=true;f.startView=f.pickOnly;}var e=["days","months","years"];["month","year","decades"].some(function(j,h){return(f.startView==j)&&(f.startView=e[h]);
});f.canAlwaysGoUp=f.canAlwaysGoUp?Array.from(f.canAlwaysGoUp):[];if(f.minDate){if(!(f.minDate instanceof Date)){f.minDate=Date.parse(f.minDate);}f.minDate.clearTime();
}if(f.maxDate){if(!(f.maxDate instanceof Date)){f.maxDate=Date.parse(f.maxDate);}f.maxDate.clearTime();}if(!f.format){f.format=(f.pickOnly!="time")?Locale.get("Date.shortDate"):"";
if(f.timePicker){f.format=(f.format)+(f.format?" ":"")+Locale.get("Date.shortTime");}}this.addEvent("attached",function(l,k){if(!this.currentView||!f.openLastView){this.currentView=f.startView;
}this.date=c(new Date(),f.minDate,f.maxDate);var h=k.get("tag"),i;if(h=="input"){i=k;}else{var j=this.toggles.indexOf(k);if(this.inputs[j]){i=this.inputs[j];
}}this.getInputDate(i);this.input=i;this.setColumns(this.originalColumns);}.bind(this),true);},getInputDate:function(e){this.date=new Date();if(!e){return;
}var g=Date.parse(e.get("value"));if(g==null||!g.isValid()){var f=e.retrieve("datepicker:value");if(f){g=Date.parse(f);}}if(g!=null&&g.isValid()){this.date=g;
}},constructPicker:function(){this.parent();if(!this.options.rtl){this.previous=new Element("div.previous[html=«]").inject(this.header);this.next=new Element("div.next[html=»]").inject(this.header);
}else{this.next=new Element("div.previous[html=«]").inject(this.header);this.previous=new Element("div.next[html=»]").inject(this.header);}},hidePrevious:function(e,f){this[e?"next":"previous"].setStyle("display",f?"block":"none");
return this;},showPrevious:function(e){return this.hidePrevious(e,true);},setPreviousEvent:function(f,e){this[e?"next":"previous"].removeEvents("click");
if(f){this[e?"next":"previous"].addEvent("click",f);}return this;},hideNext:function(){return this.hidePrevious(true);},showNext:function(){return this.showPrevious(true);
},setNextEvent:function(e){return this.setPreviousEvent(e,true);},setColumns:function(h,e,g,i){var f=this.parent(h),j;if((e||this.currentView)&&(j="render"+(e||this.currentView).capitalize())&&this[j]){this[j](g||this.date.clone(),i);
}return f;},renderYears:function(g,j){var q=this.options,f=q.columns,o=q.yearsPerPage,e=[],h=[];this.dateElements=[];g=g.clone().decrement("year",g.get("year")%o);
var k=g.clone().decrement("year",Math.floor((f-1)/2)*o);for(var l=f;l--;){var p=k.clone();h.push(p);e.push(a.years(b.years(q,p.clone()),q,this.date.clone(),this.dateElements,function(i){if(q.pickOnly=="years"){this.select(i);
}else{this.renderMonths(i,"fade");}this.date=i;}.bind(this)));k.increment("year",o);}this.setColumnsContent(e,j);this.setTitle(h,q.years_title);var n=(q.minDate&&g.get("year")<=q.minDate.get("year")),m=(q.maxDate&&(g.get("year")+q.yearsPerPage)>=q.maxDate.get("year"));
this[(n?"hide":"show")+"Previous"]();this[(m?"hide":"show")+"Next"]();this.setPreviousEvent(function(){this.renderYears(g.decrement("year",o),"left");}.bind(this));
this.setNextEvent(function(){this.renderYears(g.increment("year",o),"right");}.bind(this));this.setTitleEvent(null);this.currentView="years";},renderMonths:function(g,j){var s=this.options,n=s.columns,f=[],h=[],k=g.clone().decrement("year",Math.floor((n-1)/2));
this.dateElements=[];for(var l=n;l--;){var r=k.clone();h.push(r);f.push(a.months(b.months(s,r.clone()),s,this.date.clone(),this.dateElements,function(i){if(s.pickOnly=="months"){this.select(i);
}else{this.renderDays(i,"fade");}this.date=i;}.bind(this)));k.increment("year",1);}this.setColumnsContent(f,j);this.setTitle(h,s.months_title);var p=g.get("year"),o=(s.minDate&&p<=s.minDate.get("year")),m=(s.maxDate&&p>=s.maxDate.get("year"));
this[(o?"hide":"show")+"Previous"]();this[(m?"hide":"show")+"Next"]();this.setPreviousEvent(function(){this.renderMonths(g.decrement("year",n),"left");
}.bind(this));this.setNextEvent(function(){this.renderMonths(g.increment("year",n),"right");}.bind(this));var e=s.yearPicker&&(s.pickOnly!="months"||s.canAlwaysGoUp.contains("months"));
var q=(e)?function(){this.renderYears(g,"fade");}.bind(this):null;this.setTitleEvent(q);this.currentView="months";},renderDays:function(h,k){var r=this.options,f=r.columns,g=[],j=[],m=h.clone().decrement("month",Math.floor((f-1)/2));
this.dateElements=[];for(var n=f;n--;){_date=m.clone();j.push(_date);g.push(a.days(b.days(r,_date.clone()),r,this.date.clone(),this.dateElements,function(i){if(r.pickOnly=="days"||!r.timePicker){this.select(i);
}else{this.renderTime(i,"fade");}this.date=i;}.bind(this)));m.increment("month",1);}this.setColumnsContent(g,k);this.setTitle(j,r.days_title);var l=h.format("%Y%m").toInt(),p=(r.minDate&&l<=r.minDate.format("%Y%m")),o=(r.maxDate&&l>=r.maxDate.format("%Y%m"));
this[(p?"hide":"show")+"Previous"]();this[(o?"hide":"show")+"Next"]();this.setPreviousEvent(function(){this.renderDays(h.decrement("month",f),"left");}.bind(this));
this.setNextEvent(function(){this.renderDays(h.increment("month",f),"right");}.bind(this));var e=r.pickOnly!="days"||r.canAlwaysGoUp.contains("days");var q=(e)?function(){this.renderMonths(h,"fade");
}.bind(this):null;this.setTitleEvent(q);this.currentView="days";},renderTime:function(i,j){var h=this.options;this.setTitle(i,h.time_title);var f=this.originalColumns=h.columns;
this.currentView=null;if(f!=1){this.setColumns(1);}this.setContent(a.time(h,i.clone(),function(k){this.select(k);}.bind(this)),j);this.hidePrevious().hideNext().setPreviousEvent(null).setNextEvent(null);
var g=h.pickOnly!="time"||h.canAlwaysGoUp.contains("time");var e=(g)?function(){this.setColumns(f,"days",i,"fade");}.bind(this):null;this.setTitleEvent(e);
this.currentView="time";},select:function(f,g){this.date=f;var h=f.format(this.options.format),i=f.strftime(),e=(!this.options.updateAll&&!g&&this.input)?[this.input]:this.inputs;
e.each(function(j){j.set("value",h).store("datepicker:value",i).fireEvent("change");},this);this.fireEvent("select",[f].concat(e));this.close();return this;
}});var b={years:function(f,e){var h=[];for(var g=0;g<f.yearsPerPage;g++){h.push(+e);e.increment("year",1);}return h;},months:function(f,e){var h=[];e.set("month",0);
for(var g=0;g<=11;g++){h.push(+e);e.increment("month",1);}return h;},days:function(f,e){var h=[];e.set("date",1);while(e.get("day")!=f.startDay){e.set("date",e.get("date")-1);
}for(var g=0;g<42;g++){h.push(+e);e.increment("day",1);}return h;}};var a={years:function(j,m,f,i,l){var e=new Element("div.years"),k=new Date(),h,g;j.each(function(o,p){var n=new Date(o),q=n.get("year");
g=".year.year"+p;if(q==k.get("year")){g+=".today";}if(q==f.get("year")){g+=".selected";}h=new Element("div"+g,{text:q}).inject(e);i.push({element:h,time:o});
if(d("year",n,m)){h.addClass("unavailable");}else{h.addEvent("click",l.pass(n));}});return e;},months:function(g,q,f,l,p){var o=new Date(),m=o.get("month"),k=o.get("year"),n=f.get("year"),e=new Element("div.months"),h=q.months_abbr||Locale.get("Date.months_abbr"),j,i;
g.each(function(s,t){var r=new Date(s),u=r.get("year");i=".month.month"+(t+1);if(t==m&&u==k){i+=".today";}if(t==f.get("month")&&u==n){i+=".selected";}j=new Element("div"+i,{text:h[t]}).inject(e);
l.push({element:j,time:s});if(d("month",r,q)){j.addClass("unavailable");}else{j.addEvent("click",p.pass(r));}});return e;},days:function(j,g,m,w,l){var v=new Date(j[14]).get("month"),k=new Date().toDateString(),e=m.toDateString(),n=g.weeknumbers,q=new Element("table.days"+(n?".weeknumbers":""),{role:"grid","aria-labelledby":this.titleID}),s=new Element("thead").inject(q),p=new Element("tbody").inject(q),x=new Element("tr.titles").inject(s),i=g.days_abbr||Locale.get("Date.days_abbr"),r,t,f,h,u,o=g.rtl?"top":"bottom";
if(n){new Element("th.title.day.weeknumber",{text:Locale.get("DatePicker.week")}).inject(x);}for(r=g.startDay;r<(g.startDay+7);r++){new Element("th.title.day.day"+(r%7),{text:i[(r%7)],role:"columnheader"}).inject(x,o);
}j.each(function(y,A){var z=new Date(y);if(A%7==0){h=new Element("tr.week.week"+(Math.floor(A/7))).set("role","row").inject(p);if(n){new Element("th.day.weeknumber",{text:z.get("week"),scope:"row",role:"rowheader"}).inject(h);
}}u=z.toDateString();t=".day.day"+z.get("day");if(u==k){t+=".today";}if(z.get("month")!=v){t+=".otherMonth";}f=new Element("td"+t,{text:z.getDate(),role:"gridcell"}).inject(h,o);
if(u==e){f.addClass("selected").set("aria-selected","true");}else{f.set("aria-selected","false");}w.push({element:f,time:y});if(d("date",z,g)){f.addClass("unavailable");
}else{f.addEvent("click",l.pass(z.clone()));}});return q;},time:function(g,f,h){var e=new Element("div.time"),j=(f.get("minutes")/g.timeWheelStep).round()*g.timeWheelStep;
if(j>=60){j=0;}f.set("minutes",j);var i=new Element("input.hour[type=text]",{title:Locale.get("DatePicker.use_mouse_wheel"),value:f.format("%H"),events:{click:function(l){l.target.focus();
l.stop();},mousewheel:function(l){l.stop();i.focus();var m=i.get("value").toInt();m=(l.wheel>0)?((m<23)?m+1:0):((m>0)?m-1:23);f.set("hours",m);i.set("value",f.format("%H"));
}.bind(this)},maxlength:2}).inject(e);var k=new Element("input.minutes[type=text]",{title:Locale.get("DatePicker.use_mouse_wheel"),value:f.format("%M"),events:{click:function(l){l.target.focus();
l.stop();},mousewheel:function(l){l.stop();k.focus();var m=k.get("value").toInt();m=(l.wheel>0)?((m<59)?(m+g.timeWheelStep):0):((m>0)?(m-g.timeWheelStep):(60-g.timeWheelStep));
if(m>=60){m=0;}f.set("minutes",m);k.set("value",f.format("%M"));}.bind(this)},maxlength:2}).inject(e);new Element("div.separator[text=:]").inject(e);new Element("input.ok[type=submit]",{value:Locale.get("DatePicker.time_confirm_button"),events:{click:function(l){l.stop();
f.set({hours:i.get("value").toInt(),minutes:k.get("value").toInt()});h(f.clone());}}}).inject(e);return e;}};Picker.Date.defineRenderer=function(e,f){a[e]=f;
return this;};var c=function(f,g,e){if(g&&f<g){return g;}if(e&&f>e){return e;}return f;};var d=function(k,g,o){var h=o.minDate,f=o.maxDate,n=o.availableDates,l,j,m,e;
if(!h&&!f&&!n){return false;}g.clearTime();if(k=="year"){l=g.get("year");return((h&&l<h.get("year"))||(f&&l>f.get("year"))||((n!=null&&!o.invertAvailable)&&(n[l]==null||Object.getLength(n[l])==0||Object.getLength(Object.filter(n[l],function(p){return(p.length>0);
}))==0)));}if(k=="month"){l=g.get("year");j=g.get("month")+1;e=g.format("%Y%m").toInt();return((h&&e<h.format("%Y%m").toInt())||(f&&e>f.format("%Y%m").toInt())||((n!=null&&!o.invertAvailable)&&(n[l]==null||n[l][j]==null||n[l][j].length==0)));
}l=g.get("year");j=g.get("month")+1;m=g.get("date");var i=(h&&g<h)||(h&&g>f);if(n!=null){i=i||n[l]==null||n[l][j]==null||!n[l][j].contains(m);if(o.invertAvailable){i=!i;
}}return i;};})(); | studiochakra/writopialab.com | components/com_roksprocket/fields/filters/js/Picker.Date.js | JavaScript | gpl-2.0 | 11,806 |
// Generated by CoffeeScript 1.12.0
/*
ExternalEditor
Kevin Gravier <[email protected]>
MIT
*/
(function() {
var ReadFileError,
extend = function(child, parent) { for (var key in parent) { if (hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
hasProp = {}.hasOwnProperty;
ReadFileError = (function(superClass) {
extend(ReadFileError, superClass);
ReadFileError.prototype.message = 'Failed to read temporary file';
function ReadFileError(original_error) {
this.original_error = original_error;
}
return ReadFileError;
})(Error);
module.exports = ReadFileError;
}).call(this);
| mo-norant/FinHeartBel | website/node_modules/external-editor/main/errors/ReadFileError.js | JavaScript | gpl-3.0 | 800 |
//// [classDeclarationBlockScoping1.ts]
class C {
}
{
class C {
}
}
//// [classDeclarationBlockScoping1.js]
var C = (function () {
function C() {
}
return C;
}());
{
var C_1 = (function () {
function C_1() {
}
return C_1;
}());
}
| yortus/TypeScript | tests/baselines/reference/classDeclarationBlockScoping1.js | JavaScript | apache-2.0 | 300 |
// Generated by CoffeeScript 1.4.0
(function() {
"use strict";
var UserCommand, exports, _ref,
__slice = [].slice;
var exports = (_ref = window.chat) != null ? _ref : window.chat = {};
/*
* Represents a user command, like /kick or /say.
*/
UserCommand = (function() {
function UserCommand(name, description) {
this.description = description;
this.name = name;
this.describe(this.description);
this._hasValidArgs = false;
}
/*
* Describe the command using the following format:
* * description - a description of what the command does; used with /help
* <command>
* * category - what category the command falls under. This is used with /help
* * params - what parameters the command takes, 'opt_<name>' for optional,
* '<name>...' for variable
*##
* * validateArgs - returns a truthy variable if the given arguments are valid.
* * requires - what the command requires to run (e.g. a connections to an IRC
* server)
* * usage - manually set a usage message, one will be generated if not specified
* * run - the function to call when the command is run
*/
UserCommand.prototype.describe = function(description) {
var _ref1, _ref2, _ref3, _ref4, _ref5, _ref6, _ref7;
if ((_ref1 = this._description) == null) {
this._description = description.description;
}
if ((_ref2 = this._params) == null) {
this._params = description.params;
}
if ((_ref3 = this._requires) == null) {
this._requires = description.requires;
}
if ((_ref4 = this._validateArgs) == null) {
this._validateArgs = description.validateArgs;
}
if ((_ref5 = this._usage) == null) {
this._usage = description.usage;
}
if ((_ref6 = this.run) == null) {
this.run = description.run;
}
return (_ref7 = this.category) != null ? _ref7 : this.category = description.category;
};
/*
* Try running the command. A command can fail to run if its requirements
* aren't met (e.g. needs a connection to the internet) or the specified
* arguments are invalid. In these cases a help message is displayed.
* @param {Context} context Which server/channel the command came from.
* @param {Object...} args Arguments for the command.
*/
UserCommand.prototype.tryToRun = function() {
var args, context;
context = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
this.setContext(context);
if (!this.canRun()) {
if (this.shouldDisplayFailedToRunMessage()) {
this.displayHelp();
}
return;
}
this.setArgs.apply(this, args);
if (this._hasValidArgs) {
return this.run();
} else {
return this.displayHelp();
}
};
UserCommand.prototype.setChat = function(chat) {
this.chat = chat;
};
UserCommand.prototype.setContext = function(context) {
this.win = this.chat.determineWindow(context);
if (this.win !== window.chat.NO_WINDOW) {
this.conn = this.win.conn;
return this.chan = this.win.target;
}
};
UserCommand.prototype.setArgs = function() {
var args;
args = 1 <= arguments.length ? __slice.call(arguments, 0) : [];
return this._hasValidArgs = this._tryToAssignArgs(args) && (!this._validateArgs || !!this._validateArgs());
};
UserCommand.prototype._tryToAssignArgs = function(args) {
var i, param, params, _i, _len;
this.args = [];
this._removeTrailingWhiteSpace(args);
if (!this._params) {
return args.length === 0;
}
this._resetParams();
this._truncateVariableArgs(args);
params = this._truncateExtraOptionalParams(args.length);
if (args.length !== params.length) {
return false;
}
for (i = _i = 0, _len = params.length; _i < _len; i = ++_i) {
param = params[i];
this[this._getParamName(param)] = args[i];
}
this.args = args;
return true;
};
UserCommand.prototype._resetParams = function() {
var param, _i, _len, _ref1, _results;
_ref1 = this._params;
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
param = _ref1[_i];
_results.push(this[this._getParamName(param)] = void 0);
}
return _results;
};
UserCommand.prototype._removeTrailingWhiteSpace = function(args) {
var i, _i, _ref1, _results;
_results = [];
for (i = _i = _ref1 = args.length - 1; _ref1 <= 0 ? _i <= 0 : _i >= 0; i = _ref1 <= 0 ? ++_i : --_i) {
if (args[i] === '') {
_results.push(args.splice(i, 1));
} else {
break;
}
}
return _results;
};
/*
* Join all arguments that fit under the variable argument param.
* Note: only the last argument is allowd to be variable.
*/
UserCommand.prototype._truncateVariableArgs = function(args) {
var _ref1;
if (args.length < this._params.length) {
return args;
}
if (this._isVariable(this._params[this._params.length - 1])) {
args[this._params.length - 1] = (_ref1 = args.slice(this._params.length - 1)) != null ? _ref1.join(' ') : void 0;
return args.length = this._params.length;
}
};
UserCommand.prototype._truncateExtraOptionalParams = function(numArgs) {
var extraParams, i, param, params, _i, _ref1;
extraParams = this._params.length - numArgs;
if (extraParams <= 0) {
return this._params;
}
params = [];
for (i = _i = _ref1 = this._params.length - 1; _ref1 <= 0 ? _i <= 0 : _i >= 0; i = _ref1 <= 0 ? ++_i : --_i) {
param = this._params[i];
if (extraParams > 0 && this._isOptional(param)) {
extraParams--;
} else {
params.splice(0, 0, param);
}
}
return params;
};
/*
* When a command can't run, determine if a helpful message should be
* displayed to the user.
*/
UserCommand.prototype.shouldDisplayFailedToRunMessage = function() {
if (this.win === window.chat.NO_WINDOW) {
return false;
}
return this.name !== 'say';
};
/*
* Commands can only run if their requirements are met (e.g. connected to the
* internet, in a channel, etc) and a run method is defined.
*/
UserCommand.prototype.canRun = function(opt_context) {
var requirement, _i, _len, _ref1;
if (opt_context) {
this.setContext(opt_context);
}
if (!this.run) {
return false;
}
if (!this._requires) {
return true;
}
_ref1 = this._requires;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
requirement = _ref1[_i];
if (!this._meetsRequirement(requirement)) {
return false;
}
}
return true;
};
UserCommand.prototype._meetsRequirement = function(requirement) {
var _ref1;
switch (requirement) {
case 'online':
return isOnline();
case 'connection':
return !!this.conn && isOnline();
case 'channel':
return !!this.chan;
default:
return ((_ref1 = this.conn) != null ? _ref1.irc.state : void 0) === requirement;
}
};
UserCommand.prototype.displayHelp = function(win) {
if (win == null) {
win = this.win;
}
return win.message('', html.escape(this.getHelp()), 'notice help');
};
UserCommand.prototype.getHelp = function() {
var descriptionText, usageText, _ref1;
descriptionText = this._description ? ", " + this._description : '';
if (this._usage) {
usageText = ' ' + this._usage;
}
if (usageText == null) {
usageText = ((_ref1 = this._params) != null ? _ref1.length : void 0) > 0 ? " " + (this._getUsage()) : '';
}
return this.name.toUpperCase() + usageText + descriptionText + '.';
};
UserCommand.prototype._getUsage = function() {
var param, paramDescription, paramName, _i, _len, _ref1;
paramDescription = [];
_ref1 = this._params;
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
param = _ref1[_i];
paramName = this._getParamName(param);
if (this._isOptional(param)) {
paramName = "[" + paramName + "]";
} else {
paramName = "<" + paramName + ">";
}
paramDescription.push(paramName);
}
return paramDescription.join(' ');
};
UserCommand.prototype._getParamName = function(param) {
if (this._isOptional(param)) {
param = param.slice(4);
}
if (this._isVariable(param)) {
param = param.slice(0, +(param.length - 4) + 1 || 9e9);
}
return param;
};
UserCommand.prototype._isOptional = function(param) {
return param.indexOf('opt_') === 0;
};
UserCommand.prototype._isVariable = function(param) {
return (param != null ? param.slice(param.length - 3) : void 0) === '...';
};
UserCommand.prototype.isOwnNick = function(nick) {
var _ref1;
if (nick == null) {
nick = this.nick;
}
return irc.util.nicksEqual((_ref1 = this.conn) != null ? _ref1.irc.nick : void 0, nick);
};
UserCommand.prototype.displayDirectMessage = function(nick, message) {
var _ref1;
if (nick == null) {
nick = this.nick;
}
if (message == null) {
message = this.message;
}
if (((_ref1 = this.conn) != null ? _ref1.windows[nick] : void 0) != null) {
return this._displayDirectMessageInPrivateChannel(nick, message);
} else {
return this._displayDirectMessageInline(nick, message);
}
};
/*
* Used with /msg. Displays the message in a private channel.
*/
UserCommand.prototype._displayDirectMessageInPrivateChannel = function(nick, message) {
var context;
context = {
server: this.conn.name,
channel: nick
};
return this.chat.displayMessage('privmsg', context, this.conn.irc.nick, message);
};
/*
* Used with /msg. Displays the private message in the current window.
* Direct messages always display inline until the user receives a response.
*/
UserCommand.prototype._displayDirectMessageInline = function(nick, message) {
return this.displayMessageWithStyle('privmsg', nick, message, 'direct');
};
UserCommand.prototype.displayMessage = function() {
var args, context, type, _ref1, _ref2;
type = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
context = {
server: (_ref1 = this.conn) != null ? _ref1.name : void 0,
channel: this.chan
};
return (_ref2 = this.chat).displayMessage.apply(_ref2, [type, context].concat(__slice.call(args)));
};
/*
* Displays a message with a custom style. This is useful for indicating that
* a message be rendered in a special way (e.g. no pretty formatting).
*/
UserCommand.prototype.displayMessageWithStyle = function() {
var args, e, style, type, _i, _ref1;
type = arguments[0], args = 3 <= arguments.length ? __slice.call(arguments, 1, _i = arguments.length - 1) : (_i = 1, []), style = arguments[_i++];
e = (function(func, args, ctor) {
ctor.prototype = func.prototype;
var child = new ctor, result = func.apply(child, args);
return Object(result) === result ? result : child;
})(Event, ['message', type].concat(__slice.call(args)), function(){});
e.setContext((_ref1 = this.conn) != null ? _ref1.name : void 0, this.chan);
e.addStyle(style);
return this.chat.emit(e.type, e);
};
UserCommand.prototype.handleCTCPRequest = function(nick, type) {
var delimiter, message;
this.displayDirectMessage(nick, "CTCP " + type);
delimiter = irc.CTCPHandler.DELIMITER;
message = delimiter + type + delimiter;
return this.conn.irc.doCommand('PRIVMSG', nick, message);
};
/*
* Used to set the arguments for MODE shortcut commands.
* @param {string} type E.g. /op, /voice, etc.
*/
UserCommand.prototype.setModeArgs = function(type) {
this.nicks = [this.nick];
this.target = this.chan;
return this.mode = type;
};
/*
* Determine if the given string is a valid mode expression.
* TODO: This can be improved. (e.g. ++ and +a++ shouldn't be valid)
* @param {string} mode E.g. +o, -o, +v, etc.
*/
UserCommand.prototype.isValidMode = function(mode) {
var _ref1;
return (_ref1 = mode != null ? mode[0] : void 0) === '+' || _ref1 === '-';
};
UserCommand.prototype.listInstalledScripts = function() {
var names;
names = this.chat.scriptHandler.getScriptNames();
if (names.length === 0) {
return "No scripts are currently installed";
} else {
return "Installed scripts: " + (getReadableList(names));
}
};
return UserCommand;
})();
exports.UserCommand = UserCommand;
}).call(this);
| wikijoss/circ | package/bin/chat/user_command.js | JavaScript | bsd-3-clause | 13,369 |
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else if (typeof module === 'object' && typeof module.exports === 'object') {
factory(require('jquery'));
} else {
factory(jQuery);
}
}(function (jQuery) {
// Amharic
jQuery.timeago.settings.strings = {
prefixAgo: null,
prefixFromNow: null,
suffixAgo: "በፊት",
suffixFromNow: "በኋላ",
seconds: "ከአንድ ደቂቃ በታች",
minute: "ከአንድ ደቂቃ ገደማ",
minutes: "ከ%d ደቂቃ",
hour: "ከአንድ ሰዓት ገደማ",
hours: "ከ%d ሰዓት ገደማ",
day: "ከአንድ ቀን",
days: "ከ%d ቀን",
month: "ከአንድ ወር ገደማ",
months: "ከ%d ወር",
year: "ከአንድ ዓመት ገደማ",
years: "ከ%d ዓመት",
wordSeparator: " ",
numbers: []
};
}));
| xin2015/DataCenter | src/DataCenter.Web/wwwroot/libs/timeago/locales/jquery.timeago.am.js | JavaScript | mit | 906 |
import { changeProperties } from './property_events';
import { set } from './property_set';
/**
Set a list of properties on an object. These properties are set inside
a single `beginPropertyChanges` and `endPropertyChanges` batch, so
observers will be buffered.
```javascript
let anObject = Ember.Object.create();
anObject.setProperties({
firstName: 'Stanley',
lastName: 'Stuart',
age: 21
});
```
@method setProperties
@param obj
@param {Object} properties
@return properties
@public
*/
export default function setProperties(obj, properties) {
if (!properties || typeof properties !== 'object') { return properties; }
changeProperties(() => {
let props = Object.keys(properties);
let propertyName;
for (let i = 0; i < props.length; i++) {
propertyName = props[i];
set(obj, propertyName, properties[propertyName]);
}
});
return properties;
}
| jherdman/ember.js | packages/ember-metal/lib/set_properties.js | JavaScript | mit | 921 |
/*
* JsSIP v3.0.2
* the Javascript SIP library
* Copyright: 2012-2017 José Luis Millán <[email protected]> (https://github.com/jmillan)
* Homepage: http://jssip.net
* License: MIT
*/
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.JsSIP = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var pkg = require('../package.json');
var C = {
USER_AGENT: pkg.title + ' ' + pkg.version,
// SIP scheme
SIP: 'sip',
SIPS: 'sips',
// End and Failure causes
causes: {
// Generic error causes
CONNECTION_ERROR: 'Connection Error',
REQUEST_TIMEOUT: 'Request Timeout',
SIP_FAILURE_CODE: 'SIP Failure Code',
INTERNAL_ERROR: 'Internal Error',
// SIP error causes
BUSY: 'Busy',
REJECTED: 'Rejected',
REDIRECTED: 'Redirected',
UNAVAILABLE: 'Unavailable',
NOT_FOUND: 'Not Found',
ADDRESS_INCOMPLETE: 'Address Incomplete',
INCOMPATIBLE_SDP: 'Incompatible SDP',
MISSING_SDP: 'Missing SDP',
AUTHENTICATION_ERROR: 'Authentication Error',
// Session error causes
BYE: 'Terminated',
WEBRTC_ERROR: 'WebRTC Error',
CANCELED: 'Canceled',
NO_ANSWER: 'No Answer',
EXPIRES: 'Expires',
NO_ACK: 'No ACK',
DIALOG_ERROR: 'Dialog Error',
USER_DENIED_MEDIA_ACCESS: 'User Denied Media Access',
BAD_MEDIA_DESCRIPTION: 'Bad Media Description',
RTP_TIMEOUT: 'RTP Timeout'
},
SIP_ERROR_CAUSES: {
REDIRECTED: [300,301,302,305,380],
BUSY: [486,600],
REJECTED: [403,603],
NOT_FOUND: [404,604],
UNAVAILABLE: [480,410,408,430],
ADDRESS_INCOMPLETE: [484, 424],
INCOMPATIBLE_SDP: [488,606],
AUTHENTICATION_ERROR:[401,407]
},
// SIP Methods
ACK: 'ACK',
BYE: 'BYE',
CANCEL: 'CANCEL',
INFO: 'INFO',
INVITE: 'INVITE',
MESSAGE: 'MESSAGE',
NOTIFY: 'NOTIFY',
OPTIONS: 'OPTIONS',
REGISTER: 'REGISTER',
REFER: 'REFER',
UPDATE: 'UPDATE',
SUBSCRIBE: 'SUBSCRIBE',
/* SIP Response Reasons
* DOC: http://www.iana.org/assignments/sip-parameters
* Copied from https://github.com/versatica/OverSIP/blob/master/lib/oversip/sip/constants.rb#L7
*/
REASON_PHRASE: {
100: 'Trying',
180: 'Ringing',
181: 'Call Is Being Forwarded',
182: 'Queued',
183: 'Session Progress',
199: 'Early Dialog Terminated', // draft-ietf-sipcore-199
200: 'OK',
202: 'Accepted', // RFC 3265
204: 'No Notification', //RFC 5839
300: 'Multiple Choices',
301: 'Moved Permanently',
302: 'Moved Temporarily',
305: 'Use Proxy',
380: 'Alternative Service',
400: 'Bad Request',
401: 'Unauthorized',
402: 'Payment Required',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
406: 'Not Acceptable',
407: 'Proxy Authentication Required',
408: 'Request Timeout',
410: 'Gone',
412: 'Conditional Request Failed', // RFC 3903
413: 'Request Entity Too Large',
414: 'Request-URI Too Long',
415: 'Unsupported Media Type',
416: 'Unsupported URI Scheme',
417: 'Unknown Resource-Priority', // RFC 4412
420: 'Bad Extension',
421: 'Extension Required',
422: 'Session Interval Too Small', // RFC 4028
423: 'Interval Too Brief',
424: 'Bad Location Information', // RFC 6442
428: 'Use Identity Header', // RFC 4474
429: 'Provide Referrer Identity', // RFC 3892
430: 'Flow Failed', // RFC 5626
433: 'Anonymity Disallowed', // RFC 5079
436: 'Bad Identity-Info', // RFC 4474
437: 'Unsupported Certificate', // RFC 4744
438: 'Invalid Identity Header', // RFC 4744
439: 'First Hop Lacks Outbound Support', // RFC 5626
440: 'Max-Breadth Exceeded', // RFC 5393
469: 'Bad Info Package', // draft-ietf-sipcore-info-events
470: 'Consent Needed', // RFC 5360
478: 'Unresolvable Destination', // Custom code copied from Kamailio.
480: 'Temporarily Unavailable',
481: 'Call/Transaction Does Not Exist',
482: 'Loop Detected',
483: 'Too Many Hops',
484: 'Address Incomplete',
485: 'Ambiguous',
486: 'Busy Here',
487: 'Request Terminated',
488: 'Not Acceptable Here',
489: 'Bad Event', // RFC 3265
491: 'Request Pending',
493: 'Undecipherable',
494: 'Security Agreement Required', // RFC 3329
500: 'JsSIP Internal Error',
501: 'Not Implemented',
502: 'Bad Gateway',
503: 'Service Unavailable',
504: 'Server Time-out',
505: 'Version Not Supported',
513: 'Message Too Large',
580: 'Precondition Failure', // RFC 3312
600: 'Busy Everywhere',
603: 'Decline',
604: 'Does Not Exist Anywhere',
606: 'Not Acceptable'
},
ALLOWED_METHODS: 'INVITE,ACK,CANCEL,BYE,UPDATE,MESSAGE,OPTIONS,REFER,INFO',
ACCEPTED_BODY_TYPES: 'application/sdp, application/dtmf-relay',
MAX_FORWARDS: 69,
SESSION_EXPIRES: 90,
MIN_SESSION_EXPIRES: 60
};
module.exports = C;
},{"../package.json":50}],2:[function(require,module,exports){
module.exports = Dialog;
var C = {
// Dialog states
STATUS_EARLY: 1,
STATUS_CONFIRMED: 2
};
/**
* Expose C object.
*/
Dialog.C = C;
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:Dialog');
var SIPMessage = require('./SIPMessage');
var JsSIP_C = require('./Constants');
var Transactions = require('./Transactions');
var Dialog_RequestSender = require('./Dialog/RequestSender');
// RFC 3261 12.1
function Dialog(owner, message, type, state) {
var contact;
this.uac_pending_reply = false;
this.uas_pending_reply = false;
if(!message.hasHeader('contact')) {
return {
error: 'unable to create a Dialog without Contact header field'
};
}
if(message instanceof SIPMessage.IncomingResponse) {
state = (message.status_code < 200) ? C.STATUS_EARLY : C.STATUS_CONFIRMED;
} else {
// Create confirmed dialog if state is not defined
state = state || C.STATUS_CONFIRMED;
}
contact = message.parseHeader('contact');
// RFC 3261 12.1.1
if(type === 'UAS') {
this.id = {
call_id: message.call_id,
local_tag: message.to_tag,
remote_tag: message.from_tag,
toString: function() {
return this.call_id + this.local_tag + this.remote_tag;
}
};
this.state = state;
this.remote_seqnum = message.cseq;
this.local_uri = message.parseHeader('to').uri;
this.remote_uri = message.parseHeader('from').uri;
this.remote_target = contact.uri;
this.route_set = message.getHeaders('record-route');
}
// RFC 3261 12.1.2
else if(type === 'UAC') {
this.id = {
call_id: message.call_id,
local_tag: message.from_tag,
remote_tag: message.to_tag,
toString: function() {
return this.call_id + this.local_tag + this.remote_tag;
}
};
this.state = state;
this.local_seqnum = message.cseq;
this.local_uri = message.parseHeader('from').uri;
this.remote_uri = message.parseHeader('to').uri;
this.remote_target = contact.uri;
this.route_set = message.getHeaders('record-route').reverse();
}
this.owner = owner;
owner.ua.dialogs[this.id.toString()] = this;
debug('new ' + type + ' dialog created with status ' + (this.state === C.STATUS_EARLY ? 'EARLY': 'CONFIRMED'));
}
Dialog.prototype = {
update: function(message, type) {
this.state = C.STATUS_CONFIRMED;
debug('dialog '+ this.id.toString() +' changed to CONFIRMED state');
if(type === 'UAC') {
// RFC 3261 13.2.2.4
this.route_set = message.getHeaders('record-route').reverse();
}
},
terminate: function() {
debug('dialog ' + this.id.toString() + ' deleted');
delete this.owner.ua.dialogs[this.id.toString()];
},
// RFC 3261 12.2.1.1
createRequest: function(method, extraHeaders, body) {
var cseq, request;
extraHeaders = extraHeaders && extraHeaders.slice() || [];
if(!this.local_seqnum) { this.local_seqnum = Math.floor(Math.random() * 10000); }
cseq = (method === JsSIP_C.CANCEL || method === JsSIP_C.ACK) ? this.local_seqnum : this.local_seqnum += 1;
request = new SIPMessage.OutgoingRequest(
method,
this.remote_target,
this.owner.ua, {
'cseq': cseq,
'call_id': this.id.call_id,
'from_uri': this.local_uri,
'from_tag': this.id.local_tag,
'to_uri': this.remote_uri,
'to_tag': this.id.remote_tag,
'route_set': this.route_set
}, extraHeaders, body);
request.dialog = this;
return request;
},
// RFC 3261 12.2.2
checkInDialogRequest: function(request) {
var self = this;
if(!this.remote_seqnum) {
this.remote_seqnum = request.cseq;
} else if(request.cseq < this.remote_seqnum) {
//Do not try to reply to an ACK request.
if (request.method !== JsSIP_C.ACK) {
request.reply(500);
}
return false;
} else if(request.cseq > this.remote_seqnum) {
this.remote_seqnum = request.cseq;
}
// RFC3261 14.2 Modifying an Existing Session -UAS BEHAVIOR-
if (request.method === JsSIP_C.INVITE || (request.method === JsSIP_C.UPDATE && request.body)) {
if (this.uac_pending_reply === true) {
request.reply(491);
} else if (this.uas_pending_reply === true) {
var retryAfter = (Math.random() * 10 | 0) + 1;
request.reply(500, null, ['Retry-After:'+ retryAfter]);
return false;
} else {
this.uas_pending_reply = true;
request.server_transaction.on('stateChanged', function stateChanged(){
if (this.state === Transactions.C.STATUS_ACCEPTED ||
this.state === Transactions.C.STATUS_COMPLETED ||
this.state === Transactions.C.STATUS_TERMINATED) {
request.server_transaction.removeListener('stateChanged', stateChanged);
self.uas_pending_reply = false;
}
});
}
// RFC3261 12.2.2 Replace the dialog`s remote target URI if the request is accepted
if(request.hasHeader('contact')) {
request.server_transaction.on('stateChanged', function(){
if (this.state === Transactions.C.STATUS_ACCEPTED) {
self.remote_target = request.parseHeader('contact').uri;
}
});
}
}
else if (request.method === JsSIP_C.NOTIFY) {
// RFC6665 3.2 Replace the dialog`s remote target URI if the request is accepted
if(request.hasHeader('contact')) {
request.server_transaction.on('stateChanged', function(){
if (this.state === Transactions.C.STATUS_COMPLETED) {
self.remote_target = request.parseHeader('contact').uri;
}
});
}
}
return true;
},
sendRequest: function(applicant, method, options) {
options = options || {};
var
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
body = options.body || null,
request = this.createRequest(method, extraHeaders, body),
request_sender = new Dialog_RequestSender(this, applicant, request);
request_sender.send();
// Return the instance of OutgoingRequest
return request;
},
receiveRequest: function(request) {
//Check in-dialog request
if(!this.checkInDialogRequest(request)) {
return;
}
this.owner.receiveRequest(request);
}
};
},{"./Constants":1,"./Dialog/RequestSender":3,"./SIPMessage":18,"./Transactions":21,"debug":34}],3:[function(require,module,exports){
module.exports = DialogRequestSender;
/**
* Dependencies.
*/
var JsSIP_C = require('../Constants');
var Transactions = require('../Transactions');
var RTCSession = require('../RTCSession');
var RequestSender = require('../RequestSender');
function DialogRequestSender(dialog, applicant, request) {
this.dialog = dialog;
this.applicant = applicant;
this.request = request;
// RFC3261 14.1 Modifying an Existing Session. UAC Behavior.
this.reattempt = false;
this.reattemptTimer = null;
}
DialogRequestSender.prototype = {
send: function() {
var
self = this,
request_sender = new RequestSender(this, this.dialog.owner.ua);
request_sender.send();
// RFC3261 14.2 Modifying an Existing Session -UAC BEHAVIOR-
if ((this.request.method === JsSIP_C.INVITE || (this.request.method === JsSIP_C.UPDATE && this.request.body)) &&
request_sender.clientTransaction.state !== Transactions.C.STATUS_TERMINATED) {
this.dialog.uac_pending_reply = true;
request_sender.clientTransaction.on('stateChanged', function stateChanged(){
if (this.state === Transactions.C.STATUS_ACCEPTED ||
this.state === Transactions.C.STATUS_COMPLETED ||
this.state === Transactions.C.STATUS_TERMINATED) {
request_sender.clientTransaction.removeListener('stateChanged', stateChanged);
self.dialog.uac_pending_reply = false;
}
});
}
},
onRequestTimeout: function() {
this.applicant.onRequestTimeout();
},
onTransportError: function() {
this.applicant.onTransportError();
},
receiveResponse: function(response) {
var self = this;
// RFC3261 12.2.1.2 408 or 481 is received for a request within a dialog.
if (response.status_code === 408 || response.status_code === 481) {
this.applicant.onDialogError(response);
} else if (response.method === JsSIP_C.INVITE && response.status_code === 491) {
if (this.reattempt) {
this.applicant.receiveResponse(response);
} else {
this.request.cseq.value = this.dialog.local_seqnum += 1;
this.reattemptTimer = setTimeout(function() {
if (self.applicant.owner.status !== RTCSession.C.STATUS_TERMINATED) {
self.reattempt = true;
self.request_sender.send();
}
}, 1000);
}
} else {
this.applicant.receiveResponse(response);
}
}
};
},{"../Constants":1,"../RTCSession":11,"../RequestSender":17,"../Transactions":21}],4:[function(require,module,exports){
module.exports = DigestAuthentication;
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:DigestAuthentication');
var debugerror = require('debug')('JsSIP:ERROR:DigestAuthentication');
debugerror.log = console.warn.bind(console);
var Utils = require('./Utils');
function DigestAuthentication(credentials) {
this.credentials = credentials;
this.cnonce = null;
this.nc = 0;
this.ncHex = '00000000';
this.algorithm = null;
this.realm = null;
this.nonce = null;
this.opaque = null;
this.stale = null;
this.qop = null;
this.method = null;
this.uri = null;
this.ha1 = null;
this.response = null;
}
DigestAuthentication.prototype.get = function(parameter) {
switch (parameter) {
case 'realm':
return this.realm;
case 'ha1':
return this.ha1;
default:
debugerror('get() | cannot get "%s" parameter', parameter);
return undefined;
}
};
/**
* Performs Digest authentication given a SIP request and the challenge
* received in a response to that request.
* Returns true if auth was successfully generated, false otherwise.
*/
DigestAuthentication.prototype.authenticate = function(request, challenge) {
var ha2, hex;
this.algorithm = challenge.algorithm;
this.realm = challenge.realm;
this.nonce = challenge.nonce;
this.opaque = challenge.opaque;
this.stale = challenge.stale;
if (this.algorithm) {
if (this.algorithm !== 'MD5') {
debugerror('authenticate() | challenge with Digest algorithm different than "MD5", authentication aborted');
return false;
}
} else {
this.algorithm = 'MD5';
}
if (!this.nonce) {
debugerror('authenticate() | challenge without Digest nonce, authentication aborted');
return false;
}
if (!this.realm) {
debugerror('authenticate() | challenge without Digest realm, authentication aborted');
return false;
}
// If no plain SIP password is provided.
if (!this.credentials.password) {
// If ha1 is not provided we cannot authenticate.
if (!this.credentials.ha1) {
debugerror('authenticate() | no plain SIP password nor ha1 provided, authentication aborted');
return false;
}
// If the realm does not match the stored realm we cannot authenticate.
if (this.credentials.realm !== this.realm) {
debugerror('authenticate() | no plain SIP password, and stored `realm` does not match the given `realm`, cannot authenticate [stored:"%s", given:"%s"]', this.credentials.realm, this.realm);
return false;
}
}
// 'qop' can contain a list of values (Array). Let's choose just one.
if (challenge.qop) {
if (challenge.qop.indexOf('auth') > -1) {
this.qop = 'auth';
} else if (challenge.qop.indexOf('auth-int') > -1) {
this.qop = 'auth-int';
} else {
// Otherwise 'qop' is present but does not contain 'auth' or 'auth-int', so abort here.
debugerror('authenticate() | challenge without Digest qop different than "auth" or "auth-int", authentication aborted');
return false;
}
} else {
this.qop = null;
}
// Fill other attributes.
this.method = request.method;
this.uri = request.ruri;
this.cnonce = Utils.createRandomToken(12);
this.nc += 1;
hex = Number(this.nc).toString(16);
this.ncHex = '00000000'.substr(0, 8-hex.length) + hex;
// nc-value = 8LHEX. Max value = 'FFFFFFFF'.
if (this.nc === 4294967296) {
this.nc = 1;
this.ncHex = '00000001';
}
// Calculate the Digest "response" value.
// If we have plain SIP password then regenerate ha1.
if (this.credentials.password) {
// HA1 = MD5(A1) = MD5(username:realm:password)
this.ha1 = Utils.calculateMD5(this.credentials.username + ':' + this.realm + ':' + this.credentials.password);
//
// Otherwise reuse the stored ha1.
} else {
this.ha1 = this.credentials.ha1;
}
if (this.qop === 'auth') {
// HA2 = MD5(A2) = MD5(method:digestURI)
ha2 = Utils.calculateMD5(this.method + ':' + this.uri);
// response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2)
this.response = Utils.calculateMD5(this.ha1 + ':' + this.nonce + ':' + this.ncHex + ':' + this.cnonce + ':auth:' + ha2);
} else if (this.qop === 'auth-int') {
// HA2 = MD5(A2) = MD5(method:digestURI:MD5(entityBody))
ha2 = Utils.calculateMD5(this.method + ':' + this.uri + ':' + Utils.calculateMD5(this.body ? this.body : ''));
// response = MD5(HA1:nonce:nonceCount:credentialsNonce:qop:HA2)
this.response = Utils.calculateMD5(this.ha1 + ':' + this.nonce + ':' + this.ncHex + ':' + this.cnonce + ':auth-int:' + ha2);
} else if (this.qop === null) {
// HA2 = MD5(A2) = MD5(method:digestURI)
ha2 = Utils.calculateMD5(this.method + ':' + this.uri);
// response = MD5(HA1:nonce:HA2)
this.response = Utils.calculateMD5(this.ha1 + ':' + this.nonce + ':' + ha2);
}
debug('authenticate() | response generated');
return true;
};
/**
* Return the Proxy-Authorization or WWW-Authorization header value.
*/
DigestAuthentication.prototype.toString = function() {
var auth_params = [];
if (!this.response) {
throw new Error('response field does not exist, cannot generate Authorization header');
}
auth_params.push('algorithm=' + this.algorithm);
auth_params.push('username="' + this.credentials.username + '"');
auth_params.push('realm="' + this.realm + '"');
auth_params.push('nonce="' + this.nonce + '"');
auth_params.push('uri="' + this.uri + '"');
auth_params.push('response="' + this.response + '"');
if (this.opaque) {
auth_params.push('opaque="' + this.opaque + '"');
}
if (this.qop) {
auth_params.push('qop=' + this.qop);
auth_params.push('cnonce="' + this.cnonce + '"');
auth_params.push('nc=' + this.ncHex);
}
return 'Digest ' + auth_params.join(', ');
};
},{"./Utils":25,"debug":34}],5:[function(require,module,exports){
/**
* @namespace Exceptions
* @memberOf JsSIP
*/
var Exceptions = {
/**
* Exception thrown when a valid parameter is given to the JsSIP.UA constructor.
* @class ConfigurationError
* @memberOf JsSIP.Exceptions
*/
ConfigurationError: (function(){
var exception = function(parameter, value) {
this.code = 1;
this.name = 'CONFIGURATION_ERROR';
this.parameter = parameter;
this.value = value;
this.message = (!this.value)? 'Missing parameter: '+ this.parameter : 'Invalid value '+ JSON.stringify(this.value) +' for parameter "'+ this.parameter +'"';
};
exception.prototype = new Error();
return exception;
}()),
InvalidStateError: (function(){
var exception = function(status) {
this.code = 2;
this.name = 'INVALID_STATE_ERROR';
this.status = status;
this.message = 'Invalid status: '+ status;
};
exception.prototype = new Error();
return exception;
}()),
NotSupportedError: (function(){
var exception = function(message) {
this.code = 3;
this.name = 'NOT_SUPPORTED_ERROR';
this.message = message;
};
exception.prototype = new Error();
return exception;
}()),
NotReadyError: (function(){
var exception = function(message) {
this.code = 4;
this.name = 'NOT_READY_ERROR';
this.message = message;
};
exception.prototype = new Error();
return exception;
}())
};
module.exports = Exceptions;
},{}],6:[function(require,module,exports){
module.exports = (function(){
/*
* Generated by PEG.js 0.7.0.
*
* http://pegjs.majda.cz/
*/
function quote(s) {
/*
* ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a
* string literal except for the closing quote character, backslash,
* carriage return, line separator, paragraph separator, and line feed.
* Any character may appear in the form of an escape sequence.
*
* For portability, we also escape escape all control and non-ASCII
* characters. Note that "\0" and "\v" escape sequences are not used
* because JSHint does not like the first and IE the second.
*/
return '"' + s
.replace(/\\/g, '\\\\') // backslash
.replace(/"/g, '\\"') // closing quote character
.replace(/\x08/g, '\\b') // backspace
.replace(/\t/g, '\\t') // horizontal tab
.replace(/\n/g, '\\n') // line feed
.replace(/\f/g, '\\f') // form feed
.replace(/\r/g, '\\r') // carriage return
.replace(/[\x00-\x07\x0B\x0E-\x1F\x80-\uFFFF]/g, escape)
+ '"';
}
var result = {
/*
* Parses the input with a generated parser. If the parsing is successfull,
* returns a value explicitly or implicitly specified by the grammar from
* which the parser was generated (see |PEG.buildParser|). If the parsing is
* unsuccessful, throws |PEG.parser.SyntaxError| describing the error.
*/
parse: function(input, startRule) {
var parseFunctions = {
"CRLF": parse_CRLF,
"DIGIT": parse_DIGIT,
"ALPHA": parse_ALPHA,
"HEXDIG": parse_HEXDIG,
"WSP": parse_WSP,
"OCTET": parse_OCTET,
"DQUOTE": parse_DQUOTE,
"SP": parse_SP,
"HTAB": parse_HTAB,
"alphanum": parse_alphanum,
"reserved": parse_reserved,
"unreserved": parse_unreserved,
"mark": parse_mark,
"escaped": parse_escaped,
"LWS": parse_LWS,
"SWS": parse_SWS,
"HCOLON": parse_HCOLON,
"TEXT_UTF8_TRIM": parse_TEXT_UTF8_TRIM,
"TEXT_UTF8char": parse_TEXT_UTF8char,
"UTF8_NONASCII": parse_UTF8_NONASCII,
"UTF8_CONT": parse_UTF8_CONT,
"LHEX": parse_LHEX,
"token": parse_token,
"token_nodot": parse_token_nodot,
"separators": parse_separators,
"word": parse_word,
"STAR": parse_STAR,
"SLASH": parse_SLASH,
"EQUAL": parse_EQUAL,
"LPAREN": parse_LPAREN,
"RPAREN": parse_RPAREN,
"RAQUOT": parse_RAQUOT,
"LAQUOT": parse_LAQUOT,
"COMMA": parse_COMMA,
"SEMI": parse_SEMI,
"COLON": parse_COLON,
"LDQUOT": parse_LDQUOT,
"RDQUOT": parse_RDQUOT,
"comment": parse_comment,
"ctext": parse_ctext,
"quoted_string": parse_quoted_string,
"quoted_string_clean": parse_quoted_string_clean,
"qdtext": parse_qdtext,
"quoted_pair": parse_quoted_pair,
"SIP_URI_noparams": parse_SIP_URI_noparams,
"SIP_URI": parse_SIP_URI,
"uri_scheme": parse_uri_scheme,
"uri_scheme_sips": parse_uri_scheme_sips,
"uri_scheme_sip": parse_uri_scheme_sip,
"userinfo": parse_userinfo,
"user": parse_user,
"user_unreserved": parse_user_unreserved,
"password": parse_password,
"hostport": parse_hostport,
"host": parse_host,
"hostname": parse_hostname,
"domainlabel": parse_domainlabel,
"toplabel": parse_toplabel,
"IPv6reference": parse_IPv6reference,
"IPv6address": parse_IPv6address,
"h16": parse_h16,
"ls32": parse_ls32,
"IPv4address": parse_IPv4address,
"dec_octet": parse_dec_octet,
"port": parse_port,
"uri_parameters": parse_uri_parameters,
"uri_parameter": parse_uri_parameter,
"transport_param": parse_transport_param,
"user_param": parse_user_param,
"method_param": parse_method_param,
"ttl_param": parse_ttl_param,
"maddr_param": parse_maddr_param,
"lr_param": parse_lr_param,
"other_param": parse_other_param,
"pname": parse_pname,
"pvalue": parse_pvalue,
"paramchar": parse_paramchar,
"param_unreserved": parse_param_unreserved,
"headers": parse_headers,
"header": parse_header,
"hname": parse_hname,
"hvalue": parse_hvalue,
"hnv_unreserved": parse_hnv_unreserved,
"Request_Response": parse_Request_Response,
"Request_Line": parse_Request_Line,
"Request_URI": parse_Request_URI,
"absoluteURI": parse_absoluteURI,
"hier_part": parse_hier_part,
"net_path": parse_net_path,
"abs_path": parse_abs_path,
"opaque_part": parse_opaque_part,
"uric": parse_uric,
"uric_no_slash": parse_uric_no_slash,
"path_segments": parse_path_segments,
"segment": parse_segment,
"param": parse_param,
"pchar": parse_pchar,
"scheme": parse_scheme,
"authority": parse_authority,
"srvr": parse_srvr,
"reg_name": parse_reg_name,
"query": parse_query,
"SIP_Version": parse_SIP_Version,
"INVITEm": parse_INVITEm,
"ACKm": parse_ACKm,
"OPTIONSm": parse_OPTIONSm,
"BYEm": parse_BYEm,
"CANCELm": parse_CANCELm,
"REGISTERm": parse_REGISTERm,
"SUBSCRIBEm": parse_SUBSCRIBEm,
"NOTIFYm": parse_NOTIFYm,
"REFERm": parse_REFERm,
"Method": parse_Method,
"Status_Line": parse_Status_Line,
"Status_Code": parse_Status_Code,
"extension_code": parse_extension_code,
"Reason_Phrase": parse_Reason_Phrase,
"Allow_Events": parse_Allow_Events,
"Call_ID": parse_Call_ID,
"Contact": parse_Contact,
"contact_param": parse_contact_param,
"name_addr": parse_name_addr,
"display_name": parse_display_name,
"contact_params": parse_contact_params,
"c_p_q": parse_c_p_q,
"c_p_expires": parse_c_p_expires,
"delta_seconds": parse_delta_seconds,
"qvalue": parse_qvalue,
"generic_param": parse_generic_param,
"gen_value": parse_gen_value,
"Content_Disposition": parse_Content_Disposition,
"disp_type": parse_disp_type,
"disp_param": parse_disp_param,
"handling_param": parse_handling_param,
"Content_Encoding": parse_Content_Encoding,
"Content_Length": parse_Content_Length,
"Content_Type": parse_Content_Type,
"media_type": parse_media_type,
"m_type": parse_m_type,
"discrete_type": parse_discrete_type,
"composite_type": parse_composite_type,
"extension_token": parse_extension_token,
"x_token": parse_x_token,
"m_subtype": parse_m_subtype,
"m_parameter": parse_m_parameter,
"m_value": parse_m_value,
"CSeq": parse_CSeq,
"CSeq_value": parse_CSeq_value,
"Expires": parse_Expires,
"Event": parse_Event,
"event_type": parse_event_type,
"From": parse_From,
"from_param": parse_from_param,
"tag_param": parse_tag_param,
"Max_Forwards": parse_Max_Forwards,
"Min_Expires": parse_Min_Expires,
"Name_Addr_Header": parse_Name_Addr_Header,
"Proxy_Authenticate": parse_Proxy_Authenticate,
"challenge": parse_challenge,
"other_challenge": parse_other_challenge,
"auth_param": parse_auth_param,
"digest_cln": parse_digest_cln,
"realm": parse_realm,
"realm_value": parse_realm_value,
"domain": parse_domain,
"URI": parse_URI,
"nonce": parse_nonce,
"nonce_value": parse_nonce_value,
"opaque": parse_opaque,
"stale": parse_stale,
"algorithm": parse_algorithm,
"qop_options": parse_qop_options,
"qop_value": parse_qop_value,
"Proxy_Require": parse_Proxy_Require,
"Record_Route": parse_Record_Route,
"rec_route": parse_rec_route,
"Reason": parse_Reason,
"reason_param": parse_reason_param,
"reason_cause": parse_reason_cause,
"Require": parse_Require,
"Route": parse_Route,
"route_param": parse_route_param,
"Subscription_State": parse_Subscription_State,
"substate_value": parse_substate_value,
"subexp_params": parse_subexp_params,
"event_reason_value": parse_event_reason_value,
"Subject": parse_Subject,
"Supported": parse_Supported,
"To": parse_To,
"to_param": parse_to_param,
"Via": parse_Via,
"via_param": parse_via_param,
"via_params": parse_via_params,
"via_ttl": parse_via_ttl,
"via_maddr": parse_via_maddr,
"via_received": parse_via_received,
"via_branch": parse_via_branch,
"response_port": parse_response_port,
"sent_protocol": parse_sent_protocol,
"protocol_name": parse_protocol_name,
"transport": parse_transport,
"sent_by": parse_sent_by,
"via_host": parse_via_host,
"via_port": parse_via_port,
"ttl": parse_ttl,
"WWW_Authenticate": parse_WWW_Authenticate,
"Session_Expires": parse_Session_Expires,
"s_e_expires": parse_s_e_expires,
"s_e_params": parse_s_e_params,
"s_e_refresher": parse_s_e_refresher,
"extension_header": parse_extension_header,
"header_value": parse_header_value,
"message_body": parse_message_body,
"uuid_URI": parse_uuid_URI,
"uuid": parse_uuid,
"hex4": parse_hex4,
"hex8": parse_hex8,
"hex12": parse_hex12,
"Refer_To": parse_Refer_To,
"Replaces": parse_Replaces,
"call_id": parse_call_id,
"replaces_param": parse_replaces_param,
"to_tag": parse_to_tag,
"from_tag": parse_from_tag,
"early_flag": parse_early_flag
};
if (startRule !== undefined) {
if (parseFunctions[startRule] === undefined) {
throw new Error("Invalid rule name: " + quote(startRule) + ".");
}
} else {
startRule = "CRLF";
}
var pos = 0;
var reportFailures = 0;
var rightmostFailuresPos = 0;
var rightmostFailuresExpected = [];
function padLeft(input, padding, length) {
var result = input;
var padLength = length - input.length;
for (var i = 0; i < padLength; i++) {
result = padding + result;
}
return result;
}
function escape(ch) {
var charCode = ch.charCodeAt(0);
var escapeChar;
var length;
if (charCode <= 0xFF) {
escapeChar = 'x';
length = 2;
} else {
escapeChar = 'u';
length = 4;
}
return '\\' + escapeChar + padLeft(charCode.toString(16).toUpperCase(), '0', length);
}
function matchFailed(failure) {
if (pos < rightmostFailuresPos) {
return;
}
if (pos > rightmostFailuresPos) {
rightmostFailuresPos = pos;
rightmostFailuresExpected = [];
}
rightmostFailuresExpected.push(failure);
}
function parse_CRLF() {
var result0;
if (input.substr(pos, 2) === "\r\n") {
result0 = "\r\n";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\r\\n\"");
}
}
return result0;
}
function parse_DIGIT() {
var result0;
if (/^[0-9]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[0-9]");
}
}
return result0;
}
function parse_ALPHA() {
var result0;
if (/^[a-zA-Z]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z]");
}
}
return result0;
}
function parse_HEXDIG() {
var result0;
if (/^[0-9a-fA-F]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[0-9a-fA-F]");
}
}
return result0;
}
function parse_WSP() {
var result0;
result0 = parse_SP();
if (result0 === null) {
result0 = parse_HTAB();
}
return result0;
}
function parse_OCTET() {
var result0;
if (/^[\0-\xFF]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\0-\\xFF]");
}
}
return result0;
}
function parse_DQUOTE() {
var result0;
if (/^["]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\"]");
}
}
return result0;
}
function parse_SP() {
var result0;
if (input.charCodeAt(pos) === 32) {
result0 = " ";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\" \"");
}
}
return result0;
}
function parse_HTAB() {
var result0;
if (input.charCodeAt(pos) === 9) {
result0 = "\t";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\t\"");
}
}
return result0;
}
function parse_alphanum() {
var result0;
if (/^[a-zA-Z0-9]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[a-zA-Z0-9]");
}
}
return result0;
}
function parse_reserved() {
var result0;
if (input.charCodeAt(pos) === 59) {
result0 = ";";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 64) {
result0 = "@";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 38) {
result0 = "&";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 61) {
result0 = "=";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 44) {
result0 = ",";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_unreserved() {
var result0;
result0 = parse_alphanum();
if (result0 === null) {
result0 = parse_mark();
}
return result0;
}
function parse_mark() {
var result0;
if (input.charCodeAt(pos) === 45) {
result0 = "-";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 95) {
result0 = "_";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 46) {
result0 = ".";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 33) {
result0 = "!";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 126) {
result0 = "~";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 42) {
result0 = "*";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 39) {
result0 = "'";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 40) {
result0 = "(";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 41) {
result0 = ")";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_escaped() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 37) {
result0 = "%";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result0 !== null) {
result1 = parse_HEXDIG();
if (result1 !== null) {
result2 = parse_HEXDIG();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, escaped) {return escaped.join(''); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_LWS() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
pos2 = pos;
result0 = [];
result1 = parse_WSP();
while (result1 !== null) {
result0.push(result1);
result1 = parse_WSP();
}
if (result0 !== null) {
result1 = parse_CRLF();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos2;
}
} else {
result0 = null;
pos = pos2;
}
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result2 = parse_WSP();
if (result2 !== null) {
result1 = [];
while (result2 !== null) {
result1.push(result2);
result2 = parse_WSP();
}
} else {
result1 = null;
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return " "; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_SWS() {
var result0;
result0 = parse_LWS();
result0 = result0 !== null ? result0 : "";
return result0;
}
function parse_HCOLON() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = [];
result1 = parse_SP();
if (result1 === null) {
result1 = parse_HTAB();
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_SP();
if (result1 === null) {
result1 = parse_HTAB();
}
}
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ':'; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_TEXT_UTF8_TRIM() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result1 = parse_TEXT_UTF8char();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_TEXT_UTF8char();
}
} else {
result0 = null;
}
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = [];
result3 = parse_LWS();
while (result3 !== null) {
result2.push(result3);
result3 = parse_LWS();
}
if (result2 !== null) {
result3 = parse_TEXT_UTF8char();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = [];
result3 = parse_LWS();
while (result3 !== null) {
result2.push(result3);
result3 = parse_LWS();
}
if (result2 !== null) {
result3 = parse_TEXT_UTF8char();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_TEXT_UTF8char() {
var result0;
if (/^[!-~]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[!-~]");
}
}
if (result0 === null) {
result0 = parse_UTF8_NONASCII();
}
return result0;
}
function parse_UTF8_NONASCII() {
var result0;
if (/^[\x80-\uFFFF]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\x80-\\uFFFF]");
}
}
return result0;
}
function parse_UTF8_CONT() {
var result0;
if (/^[\x80-\xBF]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\x80-\\xBF]");
}
}
return result0;
}
function parse_LHEX() {
var result0;
result0 = parse_DIGIT();
if (result0 === null) {
if (/^[a-f]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[a-f]");
}
}
}
return result0;
}
function parse_token() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
}
}
}
}
}
}
}
}
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
}
}
}
}
}
}
}
}
}
}
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_token_nodot() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
}
}
}
}
}
}
}
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
}
}
}
}
}
}
}
}
}
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_separators() {
var result0;
if (input.charCodeAt(pos) === 40) {
result0 = "(";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 41) {
result0 = ")";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 60) {
result0 = "<";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"<\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 62) {
result0 = ">";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\">\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 64) {
result0 = "@";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 44) {
result0 = ",";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 59) {
result0 = ";";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 92) {
result0 = "\\";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\\\\"");
}
}
if (result0 === null) {
result0 = parse_DQUOTE();
if (result0 === null) {
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 91) {
result0 = "[";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 93) {
result0 = "]";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 61) {
result0 = "=";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 123) {
result0 = "{";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"{\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 125) {
result0 = "}";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"}\"");
}
}
if (result0 === null) {
result0 = parse_SP();
if (result0 === null) {
result0 = parse_HTAB();
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_word() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 40) {
result1 = "(";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 41) {
result1 = ")";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 60) {
result1 = "<";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"<\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 62) {
result1 = ">";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\">\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 92) {
result1 = "\\";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"\\\\\"");
}
}
if (result1 === null) {
result1 = parse_DQUOTE();
if (result1 === null) {
if (input.charCodeAt(pos) === 47) {
result1 = "/";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 91) {
result1 = "[";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 93) {
result1 = "]";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 63) {
result1 = "?";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 123) {
result1 = "{";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"{\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 125) {
result1 = "}";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"}\"");
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_alphanum();
if (result1 === null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 33) {
result1 = "!";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 37) {
result1 = "%";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"%\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 95) {
result1 = "_";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 96) {
result1 = "`";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"`\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 39) {
result1 = "'";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"'\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 126) {
result1 = "~";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"~\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 40) {
result1 = "(";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 41) {
result1 = ")";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 60) {
result1 = "<";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"<\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 62) {
result1 = ">";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\">\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 92) {
result1 = "\\";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"\\\\\"");
}
}
if (result1 === null) {
result1 = parse_DQUOTE();
if (result1 === null) {
if (input.charCodeAt(pos) === 47) {
result1 = "/";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 91) {
result1 = "[";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 93) {
result1 = "]";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 63) {
result1 = "?";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 123) {
result1 = "{";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"{\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 125) {
result1 = "}";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"}\"");
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_STAR() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 42) {
result1 = "*";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"*\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "*"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_SLASH() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 47) {
result1 = "/";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "/"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_EQUAL() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "="; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_LPAREN() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 40) {
result1 = "(";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"(\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "("; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_RPAREN() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 41) {
result1 = ")";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\")\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ")"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_RAQUOT() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 62) {
result0 = ">";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\">\"");
}
}
if (result0 !== null) {
result1 = parse_SWS();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ">"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_LAQUOT() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 60) {
result1 = "<";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"<\"");
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "<"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_COMMA() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 44) {
result1 = ",";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ","; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_SEMI() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ";"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_COLON() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_SWS();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return ":"; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_LDQUOT() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
result1 = parse_DQUOTE();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "\""; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_RDQUOT() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_DQUOTE();
if (result0 !== null) {
result1 = parse_SWS();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {return "\""; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_comment() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_LPAREN();
if (result0 !== null) {
result1 = [];
result2 = parse_ctext();
if (result2 === null) {
result2 = parse_quoted_pair();
if (result2 === null) {
result2 = parse_comment();
}
}
while (result2 !== null) {
result1.push(result2);
result2 = parse_ctext();
if (result2 === null) {
result2 = parse_quoted_pair();
if (result2 === null) {
result2 = parse_comment();
}
}
}
if (result1 !== null) {
result2 = parse_RPAREN();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_ctext() {
var result0;
if (/^[!-']/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[!-']");
}
}
if (result0 === null) {
if (/^[*-[]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[*-[]");
}
}
if (result0 === null) {
if (/^[\]-~]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\]-~]");
}
}
if (result0 === null) {
result0 = parse_UTF8_NONASCII();
if (result0 === null) {
result0 = parse_LWS();
}
}
}
}
return result0;
}
function parse_quoted_string() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
result1 = parse_DQUOTE();
if (result1 !== null) {
result2 = [];
result3 = parse_qdtext();
if (result3 === null) {
result3 = parse_quoted_pair();
}
while (result3 !== null) {
result2.push(result3);
result3 = parse_qdtext();
if (result3 === null) {
result3 = parse_quoted_pair();
}
}
if (result2 !== null) {
result3 = parse_DQUOTE();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_quoted_string_clean() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_SWS();
if (result0 !== null) {
result1 = parse_DQUOTE();
if (result1 !== null) {
result2 = [];
result3 = parse_qdtext();
if (result3 === null) {
result3 = parse_quoted_pair();
}
while (result3 !== null) {
result2.push(result3);
result3 = parse_qdtext();
if (result3 === null) {
result3 = parse_quoted_pair();
}
}
if (result2 !== null) {
result3 = parse_DQUOTE();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
return input.substring(pos-1, offset+1); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_qdtext() {
var result0;
result0 = parse_LWS();
if (result0 === null) {
if (input.charCodeAt(pos) === 33) {
result0 = "!";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"!\"");
}
}
if (result0 === null) {
if (/^[#-[]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[#-[]");
}
}
if (result0 === null) {
if (/^[\]-~]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[\\]-~]");
}
}
if (result0 === null) {
result0 = parse_UTF8_NONASCII();
}
}
}
}
return result0;
}
function parse_quoted_pair() {
var result0, result1;
var pos0;
pos0 = pos;
if (input.charCodeAt(pos) === 92) {
result0 = "\\";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"\\\\\"");
}
}
if (result0 !== null) {
if (/^[\0-\t]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[\\0-\\t]");
}
}
if (result1 === null) {
if (/^[\x0B-\f]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[\\x0B-\\f]");
}
}
if (result1 === null) {
if (/^[\x0E-]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[\\x0E-]");
}
}
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_SIP_URI_noparams() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_uri_scheme();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_userinfo();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_hostport();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
try {
data.uri = new URI(data.scheme, data.user, data.host, data.port);
delete data.scheme;
delete data.user;
delete data.host;
delete data.host_type;
delete data.port;
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_SIP_URI() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_uri_scheme();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_userinfo();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_hostport();
if (result3 !== null) {
result4 = parse_uri_parameters();
if (result4 !== null) {
result5 = parse_headers();
result5 = result5 !== null ? result5 : "";
if (result5 !== null) {
result0 = [result0, result1, result2, result3, result4, result5];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var header;
try {
data.uri = new URI(data.scheme, data.user, data.host, data.port, data.uri_params, data.uri_headers);
delete data.scheme;
delete data.user;
delete data.host;
delete data.host_type;
delete data.port;
delete data.uri_params;
if (startRule === 'SIP_URI') { data = data.uri;}
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_uri_scheme() {
var result0;
result0 = parse_uri_scheme_sips();
if (result0 === null) {
result0 = parse_uri_scheme_sip();
}
return result0;
}
function parse_uri_scheme_sips() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 4).toLowerCase() === "sips") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"sips\"");
}
}
if (result0 !== null) {
result0 = (function(offset, scheme) {
data.scheme = scheme.toLowerCase(); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_uri_scheme_sip() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 3).toLowerCase() === "sip") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"sip\"");
}
}
if (result0 !== null) {
result0 = (function(offset, scheme) {
data.scheme = scheme.toLowerCase(); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_userinfo() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_user();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_password();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
if (input.charCodeAt(pos) === 64) {
result2 = "@";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.user = decodeURIComponent(input.substring(pos-1, offset));})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_user() {
var result0, result1;
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
result1 = parse_user_unreserved();
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
result1 = parse_user_unreserved();
}
}
}
} else {
result0 = null;
}
return result0;
}
function parse_user_unreserved() {
var result0;
if (input.charCodeAt(pos) === 38) {
result0 = "&";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 61) {
result0 = "=";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 44) {
result0 = ",";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 59) {
result0 = ";";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_password() {
var result0, result1;
var pos0;
pos0 = pos;
result0 = [];
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
if (input.charCodeAt(pos) === 38) {
result1 = "&";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 36) {
result1 = "$";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 44) {
result1 = ",";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
}
}
}
}
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
if (input.charCodeAt(pos) === 38) {
result1 = "&";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 36) {
result1 = "$";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 44) {
result1 = ",";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
}
}
}
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.password = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_hostport() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
result0 = parse_host();
if (result0 !== null) {
pos1 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_port();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos1;
}
} else {
result1 = null;
pos = pos1;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_host() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_hostname();
if (result0 === null) {
result0 = parse_IPv4address();
if (result0 === null) {
result0 = parse_IPv6reference();
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.host = input.substring(pos, offset).toLowerCase();
return data.host; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_hostname() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = [];
pos2 = pos;
result1 = parse_domainlabel();
if (result1 !== null) {
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
while (result1 !== null) {
result0.push(result1);
pos2 = pos;
result1 = parse_domainlabel();
if (result1 !== null) {
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
}
if (result0 !== null) {
result1 = parse_toplabel();
if (result1 !== null) {
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.host_type = 'domain';
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_domainlabel() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_alphanum();
if (result0 !== null) {
result1 = [];
result2 = parse_alphanum();
if (result2 === null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 95) {
result2 = "_";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
}
}
while (result2 !== null) {
result1.push(result2);
result2 = parse_alphanum();
if (result2 === null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 95) {
result2 = "_";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
}
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_toplabel() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_ALPHA();
if (result0 !== null) {
result1 = [];
result2 = parse_alphanum();
if (result2 === null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 95) {
result2 = "_";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
}
}
while (result2 !== null) {
result1.push(result2);
result2 = parse_alphanum();
if (result2 === null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 95) {
result2 = "_";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"_\"");
}
}
}
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_IPv6reference() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 91) {
result0 = "[";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result0 !== null) {
result1 = parse_IPv6address();
if (result1 !== null) {
if (input.charCodeAt(pos) === 93) {
result2 = "]";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.host_type = 'IPv6';
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_IPv6address() {
var result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11, result12;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
if (input.charCodeAt(pos) === 58) {
result5 = ":";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result5 !== null) {
result6 = parse_h16();
if (result6 !== null) {
if (input.charCodeAt(pos) === 58) {
result7 = ":";
pos++;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result7 !== null) {
result8 = parse_h16();
if (result8 !== null) {
if (input.charCodeAt(pos) === 58) {
result9 = ":";
pos++;
} else {
result9 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result9 !== null) {
result10 = parse_h16();
if (result10 !== null) {
if (input.charCodeAt(pos) === 58) {
result11 = ":";
pos++;
} else {
result11 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result11 !== null) {
result12 = parse_ls32();
if (result12 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11, result12];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_h16();
if (result7 !== null) {
if (input.charCodeAt(pos) === 58) {
result8 = ":";
pos++;
} else {
result8 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result8 !== null) {
result9 = parse_h16();
if (result9 !== null) {
if (input.charCodeAt(pos) === 58) {
result10 = ":";
pos++;
} else {
result10 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result10 !== null) {
result11 = parse_ls32();
if (result11 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10, result11];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_h16();
if (result7 !== null) {
if (input.charCodeAt(pos) === 58) {
result8 = ":";
pos++;
} else {
result8 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result8 !== null) {
result9 = parse_ls32();
if (result9 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_ls32();
if (result7 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_ls32();
if (result5 !== null) {
result0 = [result0, result1, result2, result3, result4, result5];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_ls32();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_ls32();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
if (input.substr(pos, 2) === "::") {
result0 = "::";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result0 !== null) {
result1 = parse_h16();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
if (input.substr(pos, 2) === "::") {
result1 = "::";
pos += 2;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
if (input.charCodeAt(pos) === 58) {
result5 = ":";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result5 !== null) {
result6 = parse_h16();
if (result6 !== null) {
if (input.charCodeAt(pos) === 58) {
result7 = ":";
pos++;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result7 !== null) {
result8 = parse_h16();
if (result8 !== null) {
if (input.charCodeAt(pos) === 58) {
result9 = ":";
pos++;
} else {
result9 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result9 !== null) {
result10 = parse_ls32();
if (result10 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9, result10];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
if (input.substr(pos, 2) === "::") {
result2 = "::";
pos += 2;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_h16();
if (result7 !== null) {
if (input.charCodeAt(pos) === 58) {
result8 = ":";
pos++;
} else {
result8 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result8 !== null) {
result9 = parse_ls32();
if (result9 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8, result9];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
if (input.substr(pos, 2) === "::") {
result3 = "::";
pos += 2;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
if (input.charCodeAt(pos) === 58) {
result5 = ":";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result5 !== null) {
result6 = parse_h16();
if (result6 !== null) {
if (input.charCodeAt(pos) === 58) {
result7 = ":";
pos++;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result7 !== null) {
result8 = parse_ls32();
if (result8 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos2;
}
} else {
result3 = null;
pos = pos2;
}
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
if (input.substr(pos, 2) === "::") {
result4 = "::";
pos += 2;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_ls32();
if (result7 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos2;
}
} else {
result3 = null;
pos = pos2;
}
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos2;
}
} else {
result4 = null;
pos = pos2;
}
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
if (input.substr(pos, 2) === "::") {
result5 = "::";
pos += 2;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result5 !== null) {
result6 = parse_ls32();
if (result6 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos2;
}
} else {
result3 = null;
pos = pos2;
}
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos2;
}
} else {
result4 = null;
pos = pos2;
}
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result5 = ":";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result5 !== null) {
result6 = parse_h16();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
result5 = result5 !== null ? result5 : "";
if (result5 !== null) {
if (input.substr(pos, 2) === "::") {
result6 = "::";
pos += 2;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result6 !== null) {
result7 = parse_h16();
if (result7 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
pos1 = pos;
result0 = parse_h16();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result2 = ":";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result2 !== null) {
result3 = parse_h16();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result3 = ":";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result3 !== null) {
result4 = parse_h16();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos2;
}
} else {
result3 = null;
pos = pos2;
}
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result4 = ":";
pos++;
} else {
result4 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result4 !== null) {
result5 = parse_h16();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos2;
}
} else {
result4 = null;
pos = pos2;
}
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result5 = ":";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result5 !== null) {
result6 = parse_h16();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
result5 = result5 !== null ? result5 : "";
if (result5 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 58) {
result6 = ":";
pos++;
} else {
result6 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result6 !== null) {
result7 = parse_h16();
if (result7 !== null) {
result6 = [result6, result7];
} else {
result6 = null;
pos = pos2;
}
} else {
result6 = null;
pos = pos2;
}
result6 = result6 !== null ? result6 : "";
if (result6 !== null) {
if (input.substr(pos, 2) === "::") {
result7 = "::";
pos += 2;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("\"::\"");
}
}
if (result7 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.host_type = 'IPv6';
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_h16() {
var result0, result1, result2, result3;
var pos0;
pos0 = pos;
result0 = parse_HEXDIG();
if (result0 !== null) {
result1 = parse_HEXDIG();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result2 = parse_HEXDIG();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_HEXDIG();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_ls32() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_h16();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_h16();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
result0 = parse_IPv4address();
}
return result0;
}
function parse_IPv4address() {
var result0, result1, result2, result3, result4, result5, result6;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_dec_octet();
if (result0 !== null) {
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 !== null) {
result2 = parse_dec_octet();
if (result2 !== null) {
if (input.charCodeAt(pos) === 46) {
result3 = ".";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result3 !== null) {
result4 = parse_dec_octet();
if (result4 !== null) {
if (input.charCodeAt(pos) === 46) {
result5 = ".";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result5 !== null) {
result6 = parse_dec_octet();
if (result6 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.host_type = 'IPv4';
return input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_dec_octet() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (input.substr(pos, 2) === "25") {
result0 = "25";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"25\"");
}
}
if (result0 !== null) {
if (/^[0-5]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[0-5]");
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 50) {
result0 = "2";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"2\"");
}
}
if (result0 !== null) {
if (/^[0-4]/.test(input.charAt(pos))) {
result1 = input.charAt(pos);
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("[0-4]");
}
}
if (result1 !== null) {
result2 = parse_DIGIT();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (input.charCodeAt(pos) === 49) {
result0 = "1";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"1\"");
}
}
if (result0 !== null) {
result1 = parse_DIGIT();
if (result1 !== null) {
result2 = parse_DIGIT();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
if (/^[1-9]/.test(input.charAt(pos))) {
result0 = input.charAt(pos);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("[1-9]");
}
}
if (result0 !== null) {
result1 = parse_DIGIT();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
result0 = parse_DIGIT();
}
}
}
}
return result0;
}
function parse_port() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_DIGIT();
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result1 = parse_DIGIT();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result2 = parse_DIGIT();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_DIGIT();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result4 = parse_DIGIT();
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, port) {
port = parseInt(port.join(''));
data.port = port;
return port; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_uri_parameters() {
var result0, result1, result2;
var pos0;
result0 = [];
pos0 = pos;
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 !== null) {
result2 = parse_uri_parameter();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos0;
}
} else {
result1 = null;
pos = pos0;
}
while (result1 !== null) {
result0.push(result1);
pos0 = pos;
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 !== null) {
result2 = parse_uri_parameter();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos0;
}
} else {
result1 = null;
pos = pos0;
}
}
return result0;
}
function parse_uri_parameter() {
var result0;
result0 = parse_transport_param();
if (result0 === null) {
result0 = parse_user_param();
if (result0 === null) {
result0 = parse_method_param();
if (result0 === null) {
result0 = parse_ttl_param();
if (result0 === null) {
result0 = parse_maddr_param();
if (result0 === null) {
result0 = parse_lr_param();
if (result0 === null) {
result0 = parse_other_param();
}
}
}
}
}
}
return result0;
}
function parse_transport_param() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 10).toLowerCase() === "transport=") {
result0 = input.substr(pos, 10);
pos += 10;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"transport=\"");
}
}
if (result0 !== null) {
if (input.substr(pos, 3).toLowerCase() === "udp") {
result1 = input.substr(pos, 3);
pos += 3;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"udp\"");
}
}
if (result1 === null) {
if (input.substr(pos, 3).toLowerCase() === "tcp") {
result1 = input.substr(pos, 3);
pos += 3;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"tcp\"");
}
}
if (result1 === null) {
if (input.substr(pos, 4).toLowerCase() === "sctp") {
result1 = input.substr(pos, 4);
pos += 4;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"sctp\"");
}
}
if (result1 === null) {
if (input.substr(pos, 3).toLowerCase() === "tls") {
result1 = input.substr(pos, 3);
pos += 3;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"tls\"");
}
}
if (result1 === null) {
result1 = parse_token();
}
}
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, transport) {
if(!data.uri_params) data.uri_params={};
data.uri_params['transport'] = transport.toLowerCase(); })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_user_param() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 5).toLowerCase() === "user=") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"user=\"");
}
}
if (result0 !== null) {
if (input.substr(pos, 5).toLowerCase() === "phone") {
result1 = input.substr(pos, 5);
pos += 5;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"phone\"");
}
}
if (result1 === null) {
if (input.substr(pos, 2).toLowerCase() === "ip") {
result1 = input.substr(pos, 2);
pos += 2;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"ip\"");
}
}
if (result1 === null) {
result1 = parse_token();
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, user) {
if(!data.uri_params) data.uri_params={};
data.uri_params['user'] = user.toLowerCase(); })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_method_param() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 7).toLowerCase() === "method=") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"method=\"");
}
}
if (result0 !== null) {
result1 = parse_Method();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, method) {
if(!data.uri_params) data.uri_params={};
data.uri_params['method'] = method; })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_ttl_param() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 4).toLowerCase() === "ttl=") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"ttl=\"");
}
}
if (result0 !== null) {
result1 = parse_ttl();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, ttl) {
if(!data.params) data.params={};
data.params['ttl'] = ttl; })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_maddr_param() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 6).toLowerCase() === "maddr=") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"maddr=\"");
}
}
if (result0 !== null) {
result1 = parse_host();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, maddr) {
if(!data.uri_params) data.uri_params={};
data.uri_params['maddr'] = maddr; })(pos0, result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_lr_param() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 2).toLowerCase() === "lr") {
result0 = input.substr(pos, 2);
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"lr\"");
}
}
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 !== null) {
result2 = parse_token();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
if(!data.uri_params) data.uri_params={};
data.uri_params['lr'] = undefined; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_other_param() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_pname();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 !== null) {
result2 = parse_pvalue();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, param, value) {
if(!data.uri_params) data.uri_params = {};
if (typeof value === 'undefined'){
value = undefined;
}
else {
value = value[1];
}
data.uri_params[param.toLowerCase()] = value;})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_pname() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_paramchar();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_paramchar();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, pname) {return pname.join(''); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_pvalue() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_paramchar();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_paramchar();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, pvalue) {return pvalue.join(''); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_paramchar() {
var result0;
result0 = parse_param_unreserved();
if (result0 === null) {
result0 = parse_unreserved();
if (result0 === null) {
result0 = parse_escaped();
}
}
return result0;
}
function parse_param_unreserved() {
var result0;
if (input.charCodeAt(pos) === 91) {
result0 = "[";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 93) {
result0 = "]";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 38) {
result0 = "&";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
}
}
}
}
}
}
return result0;
}
function parse_headers() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
pos0 = pos;
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 !== null) {
result1 = parse_header();
if (result1 !== null) {
result2 = [];
pos1 = pos;
if (input.charCodeAt(pos) === 38) {
result3 = "&";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result3 !== null) {
result4 = parse_header();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos1;
}
} else {
result3 = null;
pos = pos1;
}
while (result3 !== null) {
result2.push(result3);
pos1 = pos;
if (input.charCodeAt(pos) === 38) {
result3 = "&";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result3 !== null) {
result4 = parse_header();
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos1;
}
} else {
result3 = null;
pos = pos1;
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_header() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_hname();
if (result0 !== null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 !== null) {
result2 = parse_hvalue();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, hname, hvalue) {
hname = hname.join('').toLowerCase();
hvalue = hvalue.join('');
if(!data.uri_headers) data.uri_headers = {};
if (!data.uri_headers[hname]) {
data.uri_headers[hname] = [hvalue];
} else {
data.uri_headers[hname].push(hvalue);
}})(pos0, result0[0], result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_hname() {
var result0, result1;
result1 = parse_hnv_unreserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_hnv_unreserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
}
}
}
} else {
result0 = null;
}
return result0;
}
function parse_hvalue() {
var result0, result1;
result0 = [];
result1 = parse_hnv_unreserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_hnv_unreserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
}
}
}
return result0;
}
function parse_hnv_unreserved() {
var result0;
if (input.charCodeAt(pos) === 91) {
result0 = "[";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"[\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 93) {
result0 = "]";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"]\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
}
}
}
}
}
}
return result0;
}
function parse_Request_Response() {
var result0;
result0 = parse_Status_Line();
if (result0 === null) {
result0 = parse_Request_Line();
}
return result0;
}
function parse_Request_Line() {
var result0, result1, result2, result3, result4;
var pos0;
pos0 = pos;
result0 = parse_Method();
if (result0 !== null) {
result1 = parse_SP();
if (result1 !== null) {
result2 = parse_Request_URI();
if (result2 !== null) {
result3 = parse_SP();
if (result3 !== null) {
result4 = parse_SIP_Version();
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Request_URI() {
var result0;
result0 = parse_SIP_URI();
if (result0 === null) {
result0 = parse_absoluteURI();
}
return result0;
}
function parse_absoluteURI() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_scheme();
if (result0 !== null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 !== null) {
result2 = parse_hier_part();
if (result2 === null) {
result2 = parse_opaque_part();
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_hier_part() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
result0 = parse_net_path();
if (result0 === null) {
result0 = parse_abs_path();
}
if (result0 !== null) {
pos1 = pos;
if (input.charCodeAt(pos) === 63) {
result1 = "?";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result1 !== null) {
result2 = parse_query();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos1;
}
} else {
result1 = null;
pos = pos1;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_net_path() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (input.substr(pos, 2) === "//") {
result0 = "//";
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"//\"");
}
}
if (result0 !== null) {
result1 = parse_authority();
if (result1 !== null) {
result2 = parse_abs_path();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_abs_path() {
var result0, result1;
var pos0;
pos0 = pos;
if (input.charCodeAt(pos) === 47) {
result0 = "/";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result0 !== null) {
result1 = parse_path_segments();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_opaque_part() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_uric_no_slash();
if (result0 !== null) {
result1 = [];
result2 = parse_uric();
while (result2 !== null) {
result1.push(result2);
result2 = parse_uric();
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_uric() {
var result0;
result0 = parse_reserved();
if (result0 === null) {
result0 = parse_unreserved();
if (result0 === null) {
result0 = parse_escaped();
}
}
return result0;
}
function parse_uric_no_slash() {
var result0;
result0 = parse_unreserved();
if (result0 === null) {
result0 = parse_escaped();
if (result0 === null) {
if (input.charCodeAt(pos) === 59) {
result0 = ";";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 63) {
result0 = "?";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"?\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 64) {
result0 = "@";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 38) {
result0 = "&";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 61) {
result0 = "=";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 44) {
result0 = ",";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
}
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_path_segments() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_segment();
if (result0 !== null) {
result1 = [];
pos1 = pos;
if (input.charCodeAt(pos) === 47) {
result2 = "/";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result2 !== null) {
result3 = parse_segment();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
if (input.charCodeAt(pos) === 47) {
result2 = "/";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result2 !== null) {
result3 = parse_segment();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_segment() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = [];
result1 = parse_pchar();
while (result1 !== null) {
result0.push(result1);
result1 = parse_pchar();
}
if (result0 !== null) {
result1 = [];
pos1 = pos;
if (input.charCodeAt(pos) === 59) {
result2 = ";";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result2 !== null) {
result3 = parse_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
if (input.charCodeAt(pos) === 59) {
result2 = ";";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result2 !== null) {
result3 = parse_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_param() {
var result0, result1;
result0 = [];
result1 = parse_pchar();
while (result1 !== null) {
result0.push(result1);
result1 = parse_pchar();
}
return result0;
}
function parse_pchar() {
var result0;
result0 = parse_unreserved();
if (result0 === null) {
result0 = parse_escaped();
if (result0 === null) {
if (input.charCodeAt(pos) === 58) {
result0 = ":";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 64) {
result0 = "@";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 38) {
result0 = "&";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 61) {
result0 = "=";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 43) {
result0 = "+";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 36) {
result0 = "$";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result0 === null) {
if (input.charCodeAt(pos) === 44) {
result0 = ",";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
}
}
}
}
}
}
}
}
return result0;
}
function parse_scheme() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_ALPHA();
if (result0 !== null) {
result1 = [];
result2 = parse_ALPHA();
if (result2 === null) {
result2 = parse_DIGIT();
if (result2 === null) {
if (input.charCodeAt(pos) === 43) {
result2 = "+";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
}
}
}
}
while (result2 !== null) {
result1.push(result2);
result2 = parse_ALPHA();
if (result2 === null) {
result2 = parse_DIGIT();
if (result2 === null) {
if (input.charCodeAt(pos) === 43) {
result2 = "+";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 45) {
result2 = "-";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result2 === null) {
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
}
}
}
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.scheme= input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_authority() {
var result0;
result0 = parse_srvr();
if (result0 === null) {
result0 = parse_reg_name();
}
return result0;
}
function parse_srvr() {
var result0, result1;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_userinfo();
if (result0 !== null) {
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result1 = parse_hostport();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
result0 = result0 !== null ? result0 : "";
return result0;
}
function parse_reg_name() {
var result0, result1;
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
if (input.charCodeAt(pos) === 36) {
result1 = "$";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 44) {
result1 = ",";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 38) {
result1 = "&";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
}
}
}
}
}
}
}
}
}
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
if (input.charCodeAt(pos) === 36) {
result1 = "$";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"$\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 44) {
result1 = ",";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 59) {
result1 = ";";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\";\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 58) {
result1 = ":";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\":\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 38) {
result1 = "&";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"&\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 61) {
result1 = "=";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"=\"");
}
}
if (result1 === null) {
if (input.charCodeAt(pos) === 43) {
result1 = "+";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"+\"");
}
}
}
}
}
}
}
}
}
}
}
}
} else {
result0 = null;
}
return result0;
}
function parse_query() {
var result0, result1;
result0 = [];
result1 = parse_uric();
while (result1 !== null) {
result0.push(result1);
result1 = parse_uric();
}
return result0;
}
function parse_SIP_Version() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 3).toLowerCase() === "sip") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"SIP\"");
}
}
if (result0 !== null) {
if (input.charCodeAt(pos) === 47) {
result1 = "/";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"/\"");
}
}
if (result1 !== null) {
result3 = parse_DIGIT();
if (result3 !== null) {
result2 = [];
while (result3 !== null) {
result2.push(result3);
result3 = parse_DIGIT();
}
} else {
result2 = null;
}
if (result2 !== null) {
if (input.charCodeAt(pos) === 46) {
result3 = ".";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result3 !== null) {
result5 = parse_DIGIT();
if (result5 !== null) {
result4 = [];
while (result5 !== null) {
result4.push(result5);
result5 = parse_DIGIT();
}
} else {
result4 = null;
}
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.sip_version = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_INVITEm() {
var result0;
if (input.substr(pos, 6) === "INVITE") {
result0 = "INVITE";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"INVITE\"");
}
}
return result0;
}
function parse_ACKm() {
var result0;
if (input.substr(pos, 3) === "ACK") {
result0 = "ACK";
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"ACK\"");
}
}
return result0;
}
function parse_OPTIONSm() {
var result0;
if (input.substr(pos, 7) === "OPTIONS") {
result0 = "OPTIONS";
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"OPTIONS\"");
}
}
return result0;
}
function parse_BYEm() {
var result0;
if (input.substr(pos, 3) === "BYE") {
result0 = "BYE";
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"BYE\"");
}
}
return result0;
}
function parse_CANCELm() {
var result0;
if (input.substr(pos, 6) === "CANCEL") {
result0 = "CANCEL";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"CANCEL\"");
}
}
return result0;
}
function parse_REGISTERm() {
var result0;
if (input.substr(pos, 8) === "REGISTER") {
result0 = "REGISTER";
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"REGISTER\"");
}
}
return result0;
}
function parse_SUBSCRIBEm() {
var result0;
if (input.substr(pos, 9) === "SUBSCRIBE") {
result0 = "SUBSCRIBE";
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"SUBSCRIBE\"");
}
}
return result0;
}
function parse_NOTIFYm() {
var result0;
if (input.substr(pos, 6) === "NOTIFY") {
result0 = "NOTIFY";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"NOTIFY\"");
}
}
return result0;
}
function parse_REFERm() {
var result0;
if (input.substr(pos, 5) === "REFER") {
result0 = "REFER";
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"REFER\"");
}
}
return result0;
}
function parse_Method() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_INVITEm();
if (result0 === null) {
result0 = parse_ACKm();
if (result0 === null) {
result0 = parse_OPTIONSm();
if (result0 === null) {
result0 = parse_BYEm();
if (result0 === null) {
result0 = parse_CANCELm();
if (result0 === null) {
result0 = parse_REGISTERm();
if (result0 === null) {
result0 = parse_SUBSCRIBEm();
if (result0 === null) {
result0 = parse_NOTIFYm();
if (result0 === null) {
result0 = parse_REFERm();
if (result0 === null) {
result0 = parse_token();
}
}
}
}
}
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.method = input.substring(pos, offset);
return data.method; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Status_Line() {
var result0, result1, result2, result3, result4;
var pos0;
pos0 = pos;
result0 = parse_SIP_Version();
if (result0 !== null) {
result1 = parse_SP();
if (result1 !== null) {
result2 = parse_Status_Code();
if (result2 !== null) {
result3 = parse_SP();
if (result3 !== null) {
result4 = parse_Reason_Phrase();
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Status_Code() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_extension_code();
if (result0 !== null) {
result0 = (function(offset, status_code) {
data.status_code = parseInt(status_code.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_extension_code() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_DIGIT();
if (result0 !== null) {
result1 = parse_DIGIT();
if (result1 !== null) {
result2 = parse_DIGIT();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Reason_Phrase() {
var result0, result1;
var pos0;
pos0 = pos;
result0 = [];
result1 = parse_reserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
result1 = parse_UTF8_NONASCII();
if (result1 === null) {
result1 = parse_UTF8_CONT();
if (result1 === null) {
result1 = parse_SP();
if (result1 === null) {
result1 = parse_HTAB();
}
}
}
}
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_reserved();
if (result1 === null) {
result1 = parse_unreserved();
if (result1 === null) {
result1 = parse_escaped();
if (result1 === null) {
result1 = parse_UTF8_NONASCII();
if (result1 === null) {
result1 = parse_UTF8_CONT();
if (result1 === null) {
result1 = parse_SP();
if (result1 === null) {
result1 = parse_HTAB();
}
}
}
}
}
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.reason_phrase = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Allow_Events() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_event_type();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_event_type();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_event_type();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Call_ID() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_word();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 !== null) {
result2 = parse_word();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Contact() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
result0 = parse_STAR();
if (result0 === null) {
pos1 = pos;
result0 = parse_contact_param();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_contact_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_contact_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
}
if (result0 !== null) {
result0 = (function(offset) {
var idx, length;
length = data.multi_header.length;
for (idx = 0; idx < length; idx++) {
if (data.multi_header[idx].parsed === null) {
data = null;
break;
}
}
if (data !== null) {
data = data.multi_header;
} else {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_contact_param() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_SIP_URI_noparams();
if (result0 === null) {
result0 = parse_name_addr();
}
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_contact_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_contact_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var header;
if(!data.multi_header) data.multi_header = [];
try {
header = new NameAddrHeader(data.uri, data.display_name, data.params);
delete data.uri;
delete data.display_name;
delete data.params;
} catch(e) {
header = null;
}
data.multi_header.push( { 'possition': pos,
'offset': offset,
'parsed': header
});})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_name_addr() {
var result0, result1, result2, result3;
var pos0;
pos0 = pos;
result0 = parse_display_name();
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result1 = parse_LAQUOT();
if (result1 !== null) {
result2 = parse_SIP_URI();
if (result2 !== null) {
result3 = parse_RAQUOT();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_display_name() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_LWS();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_LWS();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 === null) {
result0 = parse_quoted_string();
}
if (result0 !== null) {
result0 = (function(offset, display_name) {
display_name = input.substring(pos, offset).trim();
if (display_name[0] === '\"') {
display_name = display_name.substring(1, display_name.length-1);
}
data.display_name = display_name; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_contact_params() {
var result0;
result0 = parse_c_p_q();
if (result0 === null) {
result0 = parse_c_p_expires();
if (result0 === null) {
result0 = parse_generic_param();
}
}
return result0;
}
function parse_c_p_q() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 1).toLowerCase() === "q") {
result0 = input.substr(pos, 1);
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"q\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_qvalue();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, q) {
if(!data.params) data.params = {};
data.params['q'] = q; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_c_p_expires() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 7).toLowerCase() === "expires") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"expires\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_delta_seconds();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, expires) {
if(!data.params) data.params = {};
data.params['expires'] = expires; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_delta_seconds() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_DIGIT();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_DIGIT();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, delta_seconds) {
return parseInt(delta_seconds.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_qvalue() {
var result0, result1, result2, result3, result4;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
if (input.charCodeAt(pos) === 48) {
result0 = "0";
pos++;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"0\"");
}
}
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 46) {
result1 = ".";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result1 !== null) {
result2 = parse_DIGIT();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_DIGIT();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result4 = parse_DIGIT();
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
result1 = [result1, result2, result3, result4];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
return parseFloat(input.substring(pos, offset)); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_generic_param() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_token();
if (result0 !== null) {
pos2 = pos;
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_gen_value();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, param, value) {
if(!data.params) data.params = {};
if (typeof value === 'undefined'){
value = undefined;
}
else {
value = value[1];
}
data.params[param.toLowerCase()] = value;})(pos0, result0[0], result0[1]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_gen_value() {
var result0;
result0 = parse_token();
if (result0 === null) {
result0 = parse_host();
if (result0 === null) {
result0 = parse_quoted_string();
}
}
return result0;
}
function parse_Content_Disposition() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_disp_type();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_disp_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_disp_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_disp_type() {
var result0;
if (input.substr(pos, 6).toLowerCase() === "render") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"render\"");
}
}
if (result0 === null) {
if (input.substr(pos, 7).toLowerCase() === "session") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"session\"");
}
}
if (result0 === null) {
if (input.substr(pos, 4).toLowerCase() === "icon") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"icon\"");
}
}
if (result0 === null) {
if (input.substr(pos, 5).toLowerCase() === "alert") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"alert\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
}
}
}
return result0;
}
function parse_disp_param() {
var result0;
result0 = parse_handling_param();
if (result0 === null) {
result0 = parse_generic_param();
}
return result0;
}
function parse_handling_param() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (input.substr(pos, 8).toLowerCase() === "handling") {
result0 = input.substr(pos, 8);
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"handling\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
if (input.substr(pos, 8).toLowerCase() === "optional") {
result2 = input.substr(pos, 8);
pos += 8;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"optional\"");
}
}
if (result2 === null) {
if (input.substr(pos, 8).toLowerCase() === "required") {
result2 = input.substr(pos, 8);
pos += 8;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"required\"");
}
}
if (result2 === null) {
result2 = parse_token();
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Content_Encoding() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Content_Length() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_DIGIT();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_DIGIT();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, length) {
data = parseInt(length.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Content_Type() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_media_type();
if (result0 !== null) {
result0 = (function(offset) {
data = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_media_type() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
result0 = parse_m_type();
if (result0 !== null) {
result1 = parse_SLASH();
if (result1 !== null) {
result2 = parse_m_subtype();
if (result2 !== null) {
result3 = [];
pos1 = pos;
result4 = parse_SEMI();
if (result4 !== null) {
result5 = parse_m_parameter();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
while (result4 !== null) {
result3.push(result4);
pos1 = pos;
result4 = parse_SEMI();
if (result4 !== null) {
result5 = parse_m_parameter();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_m_type() {
var result0;
result0 = parse_discrete_type();
if (result0 === null) {
result0 = parse_composite_type();
}
return result0;
}
function parse_discrete_type() {
var result0;
if (input.substr(pos, 4).toLowerCase() === "text") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"text\"");
}
}
if (result0 === null) {
if (input.substr(pos, 5).toLowerCase() === "image") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"image\"");
}
}
if (result0 === null) {
if (input.substr(pos, 5).toLowerCase() === "audio") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"audio\"");
}
}
if (result0 === null) {
if (input.substr(pos, 5).toLowerCase() === "video") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"video\"");
}
}
if (result0 === null) {
if (input.substr(pos, 11).toLowerCase() === "application") {
result0 = input.substr(pos, 11);
pos += 11;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"application\"");
}
}
if (result0 === null) {
result0 = parse_extension_token();
}
}
}
}
}
return result0;
}
function parse_composite_type() {
var result0;
if (input.substr(pos, 7).toLowerCase() === "message") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"message\"");
}
}
if (result0 === null) {
if (input.substr(pos, 9).toLowerCase() === "multipart") {
result0 = input.substr(pos, 9);
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"multipart\"");
}
}
if (result0 === null) {
result0 = parse_extension_token();
}
}
return result0;
}
function parse_extension_token() {
var result0;
result0 = parse_token();
if (result0 === null) {
result0 = parse_x_token();
}
return result0;
}
function parse_x_token() {
var result0, result1;
var pos0;
pos0 = pos;
if (input.substr(pos, 2).toLowerCase() === "x-") {
result0 = input.substr(pos, 2);
pos += 2;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"x-\"");
}
}
if (result0 !== null) {
result1 = parse_token();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_m_subtype() {
var result0;
result0 = parse_extension_token();
if (result0 === null) {
result0 = parse_token();
}
return result0;
}
function parse_m_parameter() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_m_value();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_m_value() {
var result0;
result0 = parse_token();
if (result0 === null) {
result0 = parse_quoted_string();
}
return result0;
}
function parse_CSeq() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_CSeq_value();
if (result0 !== null) {
result1 = parse_LWS();
if (result1 !== null) {
result2 = parse_Method();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_CSeq_value() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_DIGIT();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_DIGIT();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, cseq_value) {
data.value=parseInt(cseq_value.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Expires() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_delta_seconds();
if (result0 !== null) {
result0 = (function(offset, expires) {data = expires; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Event() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_event_type();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, event_type) {
data.event = event_type.join('').toLowerCase(); })(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_event_type() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_token_nodot();
if (result0 !== null) {
result1 = [];
pos1 = pos;
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result2 !== null) {
result3 = parse_token_nodot();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
if (input.charCodeAt(pos) === 46) {
result2 = ".";
pos++;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\".\"");
}
}
if (result2 !== null) {
result3 = parse_token_nodot();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_From() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_SIP_URI_noparams();
if (result0 === null) {
result0 = parse_name_addr();
}
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_from_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_from_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var tag = data.tag;
try {
data = new NameAddrHeader(data.uri, data.display_name, data.params);
if (tag) {data.setParam('tag',tag)}
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_from_param() {
var result0;
result0 = parse_tag_param();
if (result0 === null) {
result0 = parse_generic_param();
}
return result0;
}
function parse_tag_param() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 3).toLowerCase() === "tag") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"tag\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_token();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, tag) {data.tag = tag; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Max_Forwards() {
var result0, result1;
var pos0;
pos0 = pos;
result1 = parse_DIGIT();
if (result1 !== null) {
result0 = [];
while (result1 !== null) {
result0.push(result1);
result1 = parse_DIGIT();
}
} else {
result0 = null;
}
if (result0 !== null) {
result0 = (function(offset, forwards) {
data = parseInt(forwards.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Min_Expires() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_delta_seconds();
if (result0 !== null) {
result0 = (function(offset, min_expires) {data = min_expires; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Name_Addr_Header() {
var result0, result1, result2, result3, result4, result5, result6;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = [];
result1 = parse_display_name();
while (result1 !== null) {
result0.push(result1);
result1 = parse_display_name();
}
if (result0 !== null) {
result1 = parse_LAQUOT();
if (result1 !== null) {
result2 = parse_SIP_URI();
if (result2 !== null) {
result3 = parse_RAQUOT();
if (result3 !== null) {
result4 = [];
pos2 = pos;
result5 = parse_SEMI();
if (result5 !== null) {
result6 = parse_generic_param();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
while (result5 !== null) {
result4.push(result5);
pos2 = pos;
result5 = parse_SEMI();
if (result5 !== null) {
result6 = parse_generic_param();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
}
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
try {
data = new NameAddrHeader(data.uri, data.display_name, data.params);
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Proxy_Authenticate() {
var result0;
result0 = parse_challenge();
return result0;
}
function parse_challenge() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
if (input.substr(pos, 6).toLowerCase() === "digest") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"Digest\"");
}
}
if (result0 !== null) {
result1 = parse_LWS();
if (result1 !== null) {
result2 = parse_digest_cln();
if (result2 !== null) {
result3 = [];
pos1 = pos;
result4 = parse_COMMA();
if (result4 !== null) {
result5 = parse_digest_cln();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
while (result4 !== null) {
result3.push(result4);
pos1 = pos;
result4 = parse_COMMA();
if (result4 !== null) {
result5 = parse_digest_cln();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
if (result0 === null) {
result0 = parse_other_challenge();
}
return result0;
}
function parse_other_challenge() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = parse_LWS();
if (result1 !== null) {
result2 = parse_auth_param();
if (result2 !== null) {
result3 = [];
pos1 = pos;
result4 = parse_COMMA();
if (result4 !== null) {
result5 = parse_auth_param();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
while (result4 !== null) {
result3.push(result4);
pos1 = pos;
result4 = parse_COMMA();
if (result4 !== null) {
result5 = parse_auth_param();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_auth_param() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_token();
if (result2 === null) {
result2 = parse_quoted_string();
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_digest_cln() {
var result0;
result0 = parse_realm();
if (result0 === null) {
result0 = parse_domain();
if (result0 === null) {
result0 = parse_nonce();
if (result0 === null) {
result0 = parse_opaque();
if (result0 === null) {
result0 = parse_stale();
if (result0 === null) {
result0 = parse_algorithm();
if (result0 === null) {
result0 = parse_qop_options();
if (result0 === null) {
result0 = parse_auth_param();
}
}
}
}
}
}
}
return result0;
}
function parse_realm() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (input.substr(pos, 5).toLowerCase() === "realm") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"realm\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_realm_value();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_realm_value() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_quoted_string_clean();
if (result0 !== null) {
result0 = (function(offset, realm) { data.realm = realm; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_domain() {
var result0, result1, result2, result3, result4, result5, result6;
var pos0, pos1;
pos0 = pos;
if (input.substr(pos, 6).toLowerCase() === "domain") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"domain\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_LDQUOT();
if (result2 !== null) {
result3 = parse_URI();
if (result3 !== null) {
result4 = [];
pos1 = pos;
result6 = parse_SP();
if (result6 !== null) {
result5 = [];
while (result6 !== null) {
result5.push(result6);
result6 = parse_SP();
}
} else {
result5 = null;
}
if (result5 !== null) {
result6 = parse_URI();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos1;
}
} else {
result5 = null;
pos = pos1;
}
while (result5 !== null) {
result4.push(result5);
pos1 = pos;
result6 = parse_SP();
if (result6 !== null) {
result5 = [];
while (result6 !== null) {
result5.push(result6);
result6 = parse_SP();
}
} else {
result5 = null;
}
if (result5 !== null) {
result6 = parse_URI();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos1;
}
} else {
result5 = null;
pos = pos1;
}
}
if (result4 !== null) {
result5 = parse_RDQUOT();
if (result5 !== null) {
result0 = [result0, result1, result2, result3, result4, result5];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_URI() {
var result0;
result0 = parse_absoluteURI();
if (result0 === null) {
result0 = parse_abs_path();
}
return result0;
}
function parse_nonce() {
var result0, result1, result2;
var pos0;
pos0 = pos;
if (input.substr(pos, 5).toLowerCase() === "nonce") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"nonce\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_nonce_value();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_nonce_value() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_quoted_string_clean();
if (result0 !== null) {
result0 = (function(offset, nonce) { data.nonce=nonce; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_opaque() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 6).toLowerCase() === "opaque") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"opaque\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_quoted_string_clean();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, opaque) { data.opaque=opaque; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_stale() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
if (input.substr(pos, 5).toLowerCase() === "stale") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"stale\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
pos1 = pos;
if (input.substr(pos, 4).toLowerCase() === "true") {
result2 = input.substr(pos, 4);
pos += 4;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"true\"");
}
}
if (result2 !== null) {
result2 = (function(offset) { data.stale=true; })(pos1);
}
if (result2 === null) {
pos = pos1;
}
if (result2 === null) {
pos1 = pos;
if (input.substr(pos, 5).toLowerCase() === "false") {
result2 = input.substr(pos, 5);
pos += 5;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"false\"");
}
}
if (result2 !== null) {
result2 = (function(offset) { data.stale=false; })(pos1);
}
if (result2 === null) {
pos = pos1;
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_algorithm() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 9).toLowerCase() === "algorithm") {
result0 = input.substr(pos, 9);
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"algorithm\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
if (input.substr(pos, 3).toLowerCase() === "md5") {
result2 = input.substr(pos, 3);
pos += 3;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"MD5\"");
}
}
if (result2 === null) {
if (input.substr(pos, 8).toLowerCase() === "md5-sess") {
result2 = input.substr(pos, 8);
pos += 8;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"MD5-sess\"");
}
}
if (result2 === null) {
result2 = parse_token();
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, algorithm) {
data.algorithm=algorithm.toUpperCase(); })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_qop_options() {
var result0, result1, result2, result3, result4, result5, result6;
var pos0, pos1, pos2;
pos0 = pos;
if (input.substr(pos, 3).toLowerCase() === "qop") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"qop\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_LDQUOT();
if (result2 !== null) {
pos1 = pos;
result3 = parse_qop_value();
if (result3 !== null) {
result4 = [];
pos2 = pos;
if (input.charCodeAt(pos) === 44) {
result5 = ",";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result5 !== null) {
result6 = parse_qop_value();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
while (result5 !== null) {
result4.push(result5);
pos2 = pos;
if (input.charCodeAt(pos) === 44) {
result5 = ",";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\",\"");
}
}
if (result5 !== null) {
result6 = parse_qop_value();
if (result6 !== null) {
result5 = [result5, result6];
} else {
result5 = null;
pos = pos2;
}
} else {
result5 = null;
pos = pos2;
}
}
if (result4 !== null) {
result3 = [result3, result4];
} else {
result3 = null;
pos = pos1;
}
} else {
result3 = null;
pos = pos1;
}
if (result3 !== null) {
result4 = parse_RDQUOT();
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_qop_value() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 8).toLowerCase() === "auth-int") {
result0 = input.substr(pos, 8);
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"auth-int\"");
}
}
if (result0 === null) {
if (input.substr(pos, 4).toLowerCase() === "auth") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"auth\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
}
if (result0 !== null) {
result0 = (function(offset, qop_value) {
data.qop || (data.qop=[]);
data.qop.push(qop_value.toLowerCase()); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Proxy_Require() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Record_Route() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_rec_route();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_rec_route();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_rec_route();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var idx, length;
length = data.multi_header.length;
for (idx = 0; idx < length; idx++) {
if (data.multi_header[idx].parsed === null) {
data = null;
break;
}
}
if (data !== null) {
data = data.multi_header;
} else {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_rec_route() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_name_addr();
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var header;
if(!data.multi_header) data.multi_header = [];
try {
header = new NameAddrHeader(data.uri, data.display_name, data.params);
delete data.uri;
delete data.display_name;
delete data.params;
} catch(e) {
header = null;
}
data.multi_header.push( { 'possition': pos,
'offset': offset,
'parsed': header
});})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Reason() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 3).toLowerCase() === "sip") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"SIP\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_reason_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_reason_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, protocol) {
data.protocol = protocol.toLowerCase();
if (!data.params) data.params = {};
if (data.params.text && data.params.text[0] === '"') {
var text = data.params.text;
data.text = text.substring(1, text.length-1);
delete data.params.text;
}
})(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_reason_param() {
var result0;
result0 = parse_reason_cause();
if (result0 === null) {
result0 = parse_generic_param();
}
return result0;
}
function parse_reason_cause() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 5).toLowerCase() === "cause") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"cause\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result3 = parse_DIGIT();
if (result3 !== null) {
result2 = [];
while (result3 !== null) {
result2.push(result3);
result3 = parse_DIGIT();
}
} else {
result2 = null;
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, cause) {
data.cause = parseInt(cause.join(''));
})(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Require() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Route() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_route_param();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_route_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_route_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_route_param() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_name_addr();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Subscription_State() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_substate_value();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_subexp_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_subexp_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_substate_value() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 6).toLowerCase() === "active") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"active\"");
}
}
if (result0 === null) {
if (input.substr(pos, 7).toLowerCase() === "pending") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"pending\"");
}
}
if (result0 === null) {
if (input.substr(pos, 10).toLowerCase() === "terminated") {
result0 = input.substr(pos, 10);
pos += 10;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"terminated\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.state = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_subexp_params() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 6).toLowerCase() === "reason") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"reason\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_event_reason_value();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, reason) {
if (typeof reason !== 'undefined') data.reason = reason; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 7).toLowerCase() === "expires") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"expires\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_delta_seconds();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, expires) {
if (typeof expires !== 'undefined') data.expires = expires; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 11).toLowerCase() === "retry_after") {
result0 = input.substr(pos, 11);
pos += 11;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"retry_after\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_delta_seconds();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, retry_after) {
if (typeof retry_after !== 'undefined') data.retry_after = retry_after; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
if (result0 === null) {
result0 = parse_generic_param();
}
}
}
return result0;
}
function parse_event_reason_value() {
var result0;
if (input.substr(pos, 11).toLowerCase() === "deactivated") {
result0 = input.substr(pos, 11);
pos += 11;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"deactivated\"");
}
}
if (result0 === null) {
if (input.substr(pos, 9).toLowerCase() === "probation") {
result0 = input.substr(pos, 9);
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"probation\"");
}
}
if (result0 === null) {
if (input.substr(pos, 8).toLowerCase() === "rejected") {
result0 = input.substr(pos, 8);
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"rejected\"");
}
}
if (result0 === null) {
if (input.substr(pos, 7).toLowerCase() === "timeout") {
result0 = input.substr(pos, 7);
pos += 7;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"timeout\"");
}
}
if (result0 === null) {
if (input.substr(pos, 6).toLowerCase() === "giveup") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"giveup\"");
}
}
if (result0 === null) {
if (input.substr(pos, 10).toLowerCase() === "noresource") {
result0 = input.substr(pos, 10);
pos += 10;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"noresource\"");
}
}
if (result0 === null) {
if (input.substr(pos, 9).toLowerCase() === "invariant") {
result0 = input.substr(pos, 9);
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"invariant\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
}
}
}
}
}
}
return result0;
}
function parse_Subject() {
var result0;
result0 = parse_TEXT_UTF8_TRIM();
result0 = result0 !== null ? result0 : "";
return result0;
}
function parse_Supported() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_token();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
result0 = result0 !== null ? result0 : "";
return result0;
}
function parse_To() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_SIP_URI_noparams();
if (result0 === null) {
result0 = parse_name_addr();
}
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_to_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_to_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
var tag = data.tag;
try {
data = new NameAddrHeader(data.uri, data.display_name, data.params);
if (tag) {data.setParam('tag',tag)}
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_to_param() {
var result0;
result0 = parse_tag_param();
if (result0 === null) {
result0 = parse_generic_param();
}
return result0;
}
function parse_Via() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_via_param();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_via_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_COMMA();
if (result2 !== null) {
result3 = parse_via_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_via_param() {
var result0, result1, result2, result3, result4, result5;
var pos0, pos1;
pos0 = pos;
result0 = parse_sent_protocol();
if (result0 !== null) {
result1 = parse_LWS();
if (result1 !== null) {
result2 = parse_sent_by();
if (result2 !== null) {
result3 = [];
pos1 = pos;
result4 = parse_SEMI();
if (result4 !== null) {
result5 = parse_via_params();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
while (result4 !== null) {
result3.push(result4);
pos1 = pos;
result4 = parse_SEMI();
if (result4 !== null) {
result5 = parse_via_params();
if (result5 !== null) {
result4 = [result4, result5];
} else {
result4 = null;
pos = pos1;
}
} else {
result4 = null;
pos = pos1;
}
}
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_via_params() {
var result0;
result0 = parse_via_ttl();
if (result0 === null) {
result0 = parse_via_maddr();
if (result0 === null) {
result0 = parse_via_received();
if (result0 === null) {
result0 = parse_via_branch();
if (result0 === null) {
result0 = parse_response_port();
if (result0 === null) {
result0 = parse_generic_param();
}
}
}
}
}
return result0;
}
function parse_via_ttl() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 3).toLowerCase() === "ttl") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"ttl\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_ttl();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, via_ttl_value) {
data.ttl = via_ttl_value; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_via_maddr() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 5).toLowerCase() === "maddr") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"maddr\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_host();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, via_maddr) {
data.maddr = via_maddr; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_via_received() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 8).toLowerCase() === "received") {
result0 = input.substr(pos, 8);
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"received\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_IPv4address();
if (result2 === null) {
result2 = parse_IPv6address();
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, via_received) {
data.received = via_received; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_via_branch() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 6).toLowerCase() === "branch") {
result0 = input.substr(pos, 6);
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"branch\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_token();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, via_branch) {
data.branch = via_branch; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_response_port() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 5).toLowerCase() === "rport") {
result0 = input.substr(pos, 5);
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"rport\"");
}
}
if (result0 !== null) {
pos2 = pos;
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = [];
result3 = parse_DIGIT();
while (result3 !== null) {
result2.push(result3);
result3 = parse_DIGIT();
}
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
if(typeof response_port !== 'undefined')
data.rport = response_port.join(''); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_sent_protocol() {
var result0, result1, result2, result3, result4;
var pos0;
pos0 = pos;
result0 = parse_protocol_name();
if (result0 !== null) {
result1 = parse_SLASH();
if (result1 !== null) {
result2 = parse_token();
if (result2 !== null) {
result3 = parse_SLASH();
if (result3 !== null) {
result4 = parse_transport();
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_protocol_name() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 3).toLowerCase() === "sip") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"SIP\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
if (result0 !== null) {
result0 = (function(offset, via_protocol) {
data.protocol = via_protocol; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_transport() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 3).toLowerCase() === "udp") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"UDP\"");
}
}
if (result0 === null) {
if (input.substr(pos, 3).toLowerCase() === "tcp") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"TCP\"");
}
}
if (result0 === null) {
if (input.substr(pos, 3).toLowerCase() === "tls") {
result0 = input.substr(pos, 3);
pos += 3;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"TLS\"");
}
}
if (result0 === null) {
if (input.substr(pos, 4).toLowerCase() === "sctp") {
result0 = input.substr(pos, 4);
pos += 4;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"SCTP\"");
}
}
if (result0 === null) {
result0 = parse_token();
}
}
}
}
if (result0 !== null) {
result0 = (function(offset, via_transport) {
data.transport = via_transport; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_sent_by() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
result0 = parse_via_host();
if (result0 !== null) {
pos1 = pos;
result1 = parse_COLON();
if (result1 !== null) {
result2 = parse_via_port();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos1;
}
} else {
result1 = null;
pos = pos1;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_via_host() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_IPv4address();
if (result0 === null) {
result0 = parse_IPv6reference();
if (result0 === null) {
result0 = parse_hostname();
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.host = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_via_port() {
var result0, result1, result2, result3, result4;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_DIGIT();
result0 = result0 !== null ? result0 : "";
if (result0 !== null) {
result1 = parse_DIGIT();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result2 = parse_DIGIT();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result3 = parse_DIGIT();
result3 = result3 !== null ? result3 : "";
if (result3 !== null) {
result4 = parse_DIGIT();
result4 = result4 !== null ? result4 : "";
if (result4 !== null) {
result0 = [result0, result1, result2, result3, result4];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, via_sent_by_port) {
data.port = parseInt(via_sent_by_port.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_ttl() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_DIGIT();
if (result0 !== null) {
result1 = parse_DIGIT();
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result2 = parse_DIGIT();
result2 = result2 !== null ? result2 : "";
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, ttl) {
return parseInt(ttl.join('')); })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_WWW_Authenticate() {
var result0;
result0 = parse_challenge();
return result0;
}
function parse_Session_Expires() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_s_e_expires();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_s_e_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_s_e_params();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_s_e_expires() {
var result0;
var pos0;
pos0 = pos;
result0 = parse_delta_seconds();
if (result0 !== null) {
result0 = (function(offset, expires) { data.expires = expires; })(pos0, result0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_s_e_params() {
var result0;
result0 = parse_s_e_refresher();
if (result0 === null) {
result0 = parse_generic_param();
}
return result0;
}
function parse_s_e_refresher() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 9).toLowerCase() === "refresher") {
result0 = input.substr(pos, 9);
pos += 9;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"refresher\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
if (input.substr(pos, 3).toLowerCase() === "uac") {
result2 = input.substr(pos, 3);
pos += 3;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"uac\"");
}
}
if (result2 === null) {
if (input.substr(pos, 3).toLowerCase() === "uas") {
result2 = input.substr(pos, 3);
pos += 3;
} else {
result2 = null;
if (reportFailures === 0) {
matchFailed("\"uas\"");
}
}
}
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, s_e_refresher_value) { data.refresher = s_e_refresher_value.toLowerCase(); })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_extension_header() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_token();
if (result0 !== null) {
result1 = parse_HCOLON();
if (result1 !== null) {
result2 = parse_header_value();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_header_value() {
var result0, result1;
result0 = [];
result1 = parse_TEXT_UTF8char();
if (result1 === null) {
result1 = parse_UTF8_CONT();
if (result1 === null) {
result1 = parse_LWS();
}
}
while (result1 !== null) {
result0.push(result1);
result1 = parse_TEXT_UTF8char();
if (result1 === null) {
result1 = parse_UTF8_CONT();
if (result1 === null) {
result1 = parse_LWS();
}
}
}
return result0;
}
function parse_message_body() {
var result0, result1;
result0 = [];
result1 = parse_OCTET();
while (result1 !== null) {
result0.push(result1);
result1 = parse_OCTET();
}
return result0;
}
function parse_uuid_URI() {
var result0, result1;
var pos0;
pos0 = pos;
if (input.substr(pos, 5) === "uuid:") {
result0 = "uuid:";
pos += 5;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"uuid:\"");
}
}
if (result0 !== null) {
result1 = parse_uuid();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_uuid() {
var result0, result1, result2, result3, result4, result5, result6, result7, result8;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
result0 = parse_hex8();
if (result0 !== null) {
if (input.charCodeAt(pos) === 45) {
result1 = "-";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result1 !== null) {
result2 = parse_hex4();
if (result2 !== null) {
if (input.charCodeAt(pos) === 45) {
result3 = "-";
pos++;
} else {
result3 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result3 !== null) {
result4 = parse_hex4();
if (result4 !== null) {
if (input.charCodeAt(pos) === 45) {
result5 = "-";
pos++;
} else {
result5 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result5 !== null) {
result6 = parse_hex4();
if (result6 !== null) {
if (input.charCodeAt(pos) === 45) {
result7 = "-";
pos++;
} else {
result7 = null;
if (reportFailures === 0) {
matchFailed("\"-\"");
}
}
if (result7 !== null) {
result8 = parse_hex12();
if (result8 !== null) {
result0 = [result0, result1, result2, result3, result4, result5, result6, result7, result8];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, uuid) {
data = input.substring(pos+5, offset); })(pos0, result0[0]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_hex4() {
var result0, result1, result2, result3;
var pos0;
pos0 = pos;
result0 = parse_HEXDIG();
if (result0 !== null) {
result1 = parse_HEXDIG();
if (result1 !== null) {
result2 = parse_HEXDIG();
if (result2 !== null) {
result3 = parse_HEXDIG();
if (result3 !== null) {
result0 = [result0, result1, result2, result3];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_hex8() {
var result0, result1;
var pos0;
pos0 = pos;
result0 = parse_hex4();
if (result0 !== null) {
result1 = parse_hex4();
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_hex12() {
var result0, result1, result2;
var pos0;
pos0 = pos;
result0 = parse_hex4();
if (result0 !== null) {
result1 = parse_hex4();
if (result1 !== null) {
result2 = parse_hex4();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_Refer_To() {
var result0, result1, result2, result3;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_SIP_URI_noparams();
if (result0 === null) {
result0 = parse_name_addr();
}
if (result0 !== null) {
result1 = [];
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
while (result2 !== null) {
result1.push(result2);
pos2 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_generic_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos2;
}
} else {
result2 = null;
pos = pos2;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
try {
data = new NameAddrHeader(data.uri, data.display_name, data.params);
} catch(e) {
data = -1;
}})(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_Replaces() {
var result0, result1, result2, result3;
var pos0, pos1;
pos0 = pos;
result0 = parse_call_id();
if (result0 !== null) {
result1 = [];
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_replaces_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
while (result2 !== null) {
result1.push(result2);
pos1 = pos;
result2 = parse_SEMI();
if (result2 !== null) {
result3 = parse_replaces_param();
if (result3 !== null) {
result2 = [result2, result3];
} else {
result2 = null;
pos = pos1;
}
} else {
result2 = null;
pos = pos1;
}
}
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos0;
}
} else {
result0 = null;
pos = pos0;
}
return result0;
}
function parse_call_id() {
var result0, result1, result2;
var pos0, pos1, pos2;
pos0 = pos;
pos1 = pos;
result0 = parse_word();
if (result0 !== null) {
pos2 = pos;
if (input.charCodeAt(pos) === 64) {
result1 = "@";
pos++;
} else {
result1 = null;
if (reportFailures === 0) {
matchFailed("\"@\"");
}
}
if (result1 !== null) {
result2 = parse_word();
if (result2 !== null) {
result1 = [result1, result2];
} else {
result1 = null;
pos = pos2;
}
} else {
result1 = null;
pos = pos2;
}
result1 = result1 !== null ? result1 : "";
if (result1 !== null) {
result0 = [result0, result1];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset) {
data.call_id = input.substring(pos, offset); })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_replaces_param() {
var result0;
result0 = parse_to_tag();
if (result0 === null) {
result0 = parse_from_tag();
if (result0 === null) {
result0 = parse_early_flag();
if (result0 === null) {
result0 = parse_generic_param();
}
}
}
return result0;
}
function parse_to_tag() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 6) === "to-tag") {
result0 = "to-tag";
pos += 6;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"to-tag\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_token();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, to_tag) {
data.to_tag = to_tag; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_from_tag() {
var result0, result1, result2;
var pos0, pos1;
pos0 = pos;
pos1 = pos;
if (input.substr(pos, 8) === "from-tag") {
result0 = "from-tag";
pos += 8;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"from-tag\"");
}
}
if (result0 !== null) {
result1 = parse_EQUAL();
if (result1 !== null) {
result2 = parse_token();
if (result2 !== null) {
result0 = [result0, result1, result2];
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
} else {
result0 = null;
pos = pos1;
}
if (result0 !== null) {
result0 = (function(offset, from_tag) {
data.from_tag = from_tag; })(pos0, result0[2]);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function parse_early_flag() {
var result0;
var pos0;
pos0 = pos;
if (input.substr(pos, 10) === "early-only") {
result0 = "early-only";
pos += 10;
} else {
result0 = null;
if (reportFailures === 0) {
matchFailed("\"early-only\"");
}
}
if (result0 !== null) {
result0 = (function(offset) {
data.early_only = true; })(pos0);
}
if (result0 === null) {
pos = pos0;
}
return result0;
}
function cleanupExpected(expected) {
expected.sort();
var lastExpected = null;
var cleanExpected = [];
for (var i = 0; i < expected.length; i++) {
if (expected[i] !== lastExpected) {
cleanExpected.push(expected[i]);
lastExpected = expected[i];
}
}
return cleanExpected;
}
function computeErrorPosition() {
/*
* The first idea was to use |String.split| to break the input up to the
* error position along newlines and derive the line and column from
* there. However IE's |split| implementation is so broken that it was
* enough to prevent it.
*/
var line = 1;
var column = 1;
var seenCR = false;
for (var i = 0; i < Math.max(pos, rightmostFailuresPos); i++) {
var ch = input.charAt(i);
if (ch === "\n") {
if (!seenCR) { line++; }
column = 1;
seenCR = false;
} else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") {
line++;
column = 1;
seenCR = true;
} else {
column++;
seenCR = false;
}
}
return { line: line, column: column };
}
var URI = require('./URI');
var NameAddrHeader = require('./NameAddrHeader');
var data = {};
var result = parseFunctions[startRule]();
/*
* The parser is now in one of the following three states:
*
* 1. The parser successfully parsed the whole input.
*
* - |result !== null|
* - |pos === input.length|
* - |rightmostFailuresExpected| may or may not contain something
*
* 2. The parser successfully parsed only a part of the input.
*
* - |result !== null|
* - |pos < input.length|
* - |rightmostFailuresExpected| may or may not contain something
*
* 3. The parser did not successfully parse any part of the input.
*
* - |result === null|
* - |pos === 0|
* - |rightmostFailuresExpected| contains at least one failure
*
* All code following this comment (including called functions) must
* handle these states.
*/
if (result === null || pos !== input.length) {
var offset = Math.max(pos, rightmostFailuresPos);
var found = offset < input.length ? input.charAt(offset) : null;
var errorPosition = computeErrorPosition();
new this.SyntaxError(
cleanupExpected(rightmostFailuresExpected),
found,
offset,
errorPosition.line,
errorPosition.column
);
return -1;
}
return data;
},
/* Returns the parser source code. */
toSource: function() { return this._source; }
};
/* Thrown when a parser encounters a syntax error. */
result.SyntaxError = function(expected, found, offset, line, column) {
function buildMessage(expected, found) {
var expectedHumanized, foundHumanized;
switch (expected.length) {
case 0:
expectedHumanized = "end of input";
break;
case 1:
expectedHumanized = expected[0];
break;
default:
expectedHumanized = expected.slice(0, expected.length - 1).join(", ")
+ " or "
+ expected[expected.length - 1];
}
foundHumanized = found ? quote(found) : "end of input";
return "Expected " + expectedHumanized + " but " + foundHumanized + " found.";
}
this.name = "SyntaxError";
this.expected = expected;
this.found = found;
this.message = buildMessage(expected, found);
this.offset = offset;
this.line = line;
this.column = column;
};
result.SyntaxError.prototype = Error.prototype;
return result;
})();
},{"./NameAddrHeader":9,"./URI":24}],7:[function(require,module,exports){
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP');
var adapter = require('webrtc-adapter');
var pkg = require('../package.json');
debug('version %s', pkg.version);
var C = require('./Constants');
var Exceptions = require('./Exceptions');
var Utils = require('./Utils');
var UA = require('./UA');
var URI = require('./URI');
var NameAddrHeader = require('./NameAddrHeader');
var Grammar = require('./Grammar');
var WebSocketInterface = require('./WebSocketInterface');
/**
* Expose the JsSIP module.
*/
var JsSIP = module.exports = {
C: C,
Exceptions: Exceptions,
Utils: Utils,
UA: UA,
URI: URI,
NameAddrHeader: NameAddrHeader,
WebSocketInterface: WebSocketInterface,
Grammar: Grammar,
// Expose the debug module.
debug: require('debug'),
// Expose the adapter module.
adapter: adapter
};
Object.defineProperties(JsSIP, {
name: {
get: function() { return pkg.title; }
},
version: {
get: function() { return pkg.version; }
}
});
},{"../package.json":50,"./Constants":1,"./Exceptions":5,"./Grammar":6,"./NameAddrHeader":9,"./UA":23,"./URI":24,"./Utils":25,"./WebSocketInterface":26,"debug":34,"webrtc-adapter":41}],8:[function(require,module,exports){
module.exports = Message;
/**
* Dependencies.
*/
var util = require('util');
var events = require('events');
var JsSIP_C = require('./Constants');
var SIPMessage = require('./SIPMessage');
var Utils = require('./Utils');
var RequestSender = require('./RequestSender');
var Transactions = require('./Transactions');
var Exceptions = require('./Exceptions');
function Message(ua) {
this.ua = ua;
// Custom message empty object for high level use
this.data = {};
events.EventEmitter.call(this);
}
util.inherits(Message, events.EventEmitter);
Message.prototype.send = function(target, body, options) {
var request_sender, event, contentType, eventHandlers, extraHeaders,
originalTarget = target;
if (target === undefined || body === undefined) {
throw new TypeError('Not enough arguments');
}
// Check target validity
target = this.ua.normalizeTarget(target);
if (!target) {
throw new TypeError('Invalid target: '+ originalTarget);
}
// Get call options
options = options || {};
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [];
eventHandlers = options.eventHandlers || {};
contentType = options.contentType || 'text/plain';
this.content_type = contentType;
// Set event handlers
for (event in eventHandlers) {
this.on(event, eventHandlers[event]);
}
this.closed = false;
this.ua.applicants[this] = this;
extraHeaders.push('Content-Type: '+ contentType);
this.request = new SIPMessage.OutgoingRequest(JsSIP_C.MESSAGE, target, this.ua, null, extraHeaders);
if(body) {
this.request.body = body;
this.content = body;
} else {
this.content = null;
}
request_sender = new RequestSender(this, this.ua);
this.newMessage('local', this.request);
request_sender.send();
};
Message.prototype.receiveResponse = function(response) {
var cause;
if(this.closed) {
return;
}
switch(true) {
case /^1[0-9]{2}$/.test(response.status_code):
// Ignore provisional responses.
break;
case /^2[0-9]{2}$/.test(response.status_code):
delete this.ua.applicants[this];
this.emit('succeeded', {
originator: 'remote',
response: response
});
break;
default:
delete this.ua.applicants[this];
cause = Utils.sipErrorCause(response.status_code);
this.emit('failed', {
originator: 'remote',
response: response,
cause: cause
});
break;
}
};
Message.prototype.onRequestTimeout = function() {
if(this.closed) {
return;
}
this.emit('failed', {
originator: 'system',
cause: JsSIP_C.causes.REQUEST_TIMEOUT
});
};
Message.prototype.onTransportError = function() {
if(this.closed) {
return;
}
this.emit('failed', {
originator: 'system',
cause: JsSIP_C.causes.CONNECTION_ERROR
});
};
Message.prototype.close = function() {
this.closed = true;
delete this.ua.applicants[this];
};
Message.prototype.init_incoming = function(request) {
var transaction;
this.request = request;
this.content_type = request.getHeader('Content-Type');
if (request.body) {
this.content = request.body;
} else {
this.content = null;
}
this.newMessage('remote', request);
transaction = this.ua.transactions.nist[request.via_branch];
if (transaction && (transaction.state === Transactions.C.STATUS_TRYING || transaction.state === Transactions.C.STATUS_PROCEEDING)) {
request.reply(200);
}
};
/**
* Accept the incoming Message
* Only valid for incoming Messages
*/
Message.prototype.accept = function(options) {
options = options || {};
var
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
body = options.body;
if (this.direction !== 'incoming') {
throw new Exceptions.NotSupportedError('"accept" not supported for outgoing Message');
}
this.request.reply(200, null, extraHeaders, body);
};
/**
* Reject the incoming Message
* Only valid for incoming Messages
*/
Message.prototype.reject = function(options) {
options = options || {};
var
status_code = options.status_code || 480,
reason_phrase = options.reason_phrase,
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
body = options.body;
if (this.direction !== 'incoming') {
throw new Exceptions.NotSupportedError('"reject" not supported for outgoing Message');
}
if (status_code < 300 || status_code >= 700) {
throw new TypeError('Invalid status_code: '+ status_code);
}
this.request.reply(status_code, reason_phrase, extraHeaders, body);
};
/**
* Internal Callbacks
*/
Message.prototype.newMessage = function(originator, request) {
if (originator === 'remote') {
this.direction = 'incoming';
this.local_identity = request.to;
this.remote_identity = request.from;
} else if (originator === 'local'){
this.direction = 'outgoing';
this.local_identity = request.from;
this.remote_identity = request.to;
}
this.ua.newMessage({
originator: originator,
message: this,
request: request
});
};
},{"./Constants":1,"./Exceptions":5,"./RequestSender":17,"./SIPMessage":18,"./Transactions":21,"./Utils":25,"events":28,"util":32}],9:[function(require,module,exports){
module.exports = NameAddrHeader;
/**
* Dependencies.
*/
var URI = require('./URI');
var Grammar = require('./Grammar');
function NameAddrHeader(uri, display_name, parameters) {
var param;
// Checks
if(!uri || !(uri instanceof URI)) {
throw new TypeError('missing or invalid "uri" parameter');
}
// Initialize parameters
this.uri = uri;
this.parameters = {};
for (param in parameters) {
this.setParam(param, parameters[param]);
}
Object.defineProperties(this, {
display_name: {
get: function() { return display_name; },
set: function(value) {
display_name = (value === 0) ? '0' : value;
}
}
});
}
NameAddrHeader.prototype = {
setParam: function(key, value) {
if (key) {
this.parameters[key.toLowerCase()] = (typeof value === 'undefined' || value === null) ? null : value.toString();
}
},
getParam: function(key) {
if(key) {
return this.parameters[key.toLowerCase()];
}
},
hasParam: function(key) {
if(key) {
return (this.parameters.hasOwnProperty(key.toLowerCase()) && true) || false;
}
},
deleteParam: function(parameter) {
var value;
parameter = parameter.toLowerCase();
if (this.parameters.hasOwnProperty(parameter)) {
value = this.parameters[parameter];
delete this.parameters[parameter];
return value;
}
},
clearParams: function() {
this.parameters = {};
},
clone: function() {
return new NameAddrHeader(
this.uri.clone(),
this.display_name,
JSON.parse(JSON.stringify(this.parameters)));
},
toString: function() {
var body, parameter;
body = (this.display_name || this.display_name === 0) ? '"' + this.display_name + '" ' : '';
body += '<' + this.uri.toString() + '>';
for (parameter in this.parameters) {
body += ';' + parameter;
if (this.parameters[parameter] !== null) {
body += '='+ this.parameters[parameter];
}
}
return body;
}
};
/**
* Parse the given string and returns a NameAddrHeader instance or undefined if
* it is an invalid NameAddrHeader.
*/
NameAddrHeader.parse = function(name_addr_header) {
name_addr_header = Grammar.parse(name_addr_header,'Name_Addr_Header');
if (name_addr_header !== -1) {
return name_addr_header;
} else {
return undefined;
}
};
},{"./Grammar":6,"./URI":24}],10:[function(require,module,exports){
var Parser = {};
module.exports = Parser;
/**
* Dependencies.
*/
var debugerror = require('debug')('JsSIP:ERROR:Parser');
debugerror.log = console.warn.bind(console);
var Grammar = require('./Grammar');
var SIPMessage = require('./SIPMessage');
/**
* Extract and parse every header of a SIP message.
*/
function getHeader(data, headerStart) {
var
// 'start' position of the header.
start = headerStart,
// 'end' position of the header.
end = 0,
// 'partial end' position of the header.
partialEnd = 0;
//End of message.
if (data.substring(start, start + 2).match(/(^\r\n)/)) {
return -2;
}
while(end === 0) {
// Partial End of Header.
partialEnd = data.indexOf('\r\n', start);
// 'indexOf' returns -1 if the value to be found never occurs.
if (partialEnd === -1) {
return partialEnd;
}
if(!data.substring(partialEnd + 2, partialEnd + 4).match(/(^\r\n)/) && data.charAt(partialEnd + 2).match(/(^\s+)/)) {
// Not the end of the message. Continue from the next position.
start = partialEnd + 2;
} else {
end = partialEnd;
}
}
return end;
}
function parseHeader(message, data, headerStart, headerEnd) {
var header, idx, length, parsed,
hcolonIndex = data.indexOf(':', headerStart),
headerName = data.substring(headerStart, hcolonIndex).trim(),
headerValue = data.substring(hcolonIndex + 1, headerEnd).trim();
// If header-field is well-known, parse it.
switch(headerName.toLowerCase()) {
case 'via':
case 'v':
message.addHeader('via', headerValue);
if(message.getHeaders('via').length === 1) {
parsed = message.parseHeader('Via');
if(parsed) {
message.via = parsed;
message.via_branch = parsed.branch;
}
} else {
parsed = 0;
}
break;
case 'from':
case 'f':
message.setHeader('from', headerValue);
parsed = message.parseHeader('from');
if(parsed) {
message.from = parsed;
message.from_tag = parsed.getParam('tag');
}
break;
case 'to':
case 't':
message.setHeader('to', headerValue);
parsed = message.parseHeader('to');
if(parsed) {
message.to = parsed;
message.to_tag = parsed.getParam('tag');
}
break;
case 'record-route':
parsed = Grammar.parse(headerValue, 'Record_Route');
if (parsed === -1) {
parsed = undefined;
} else {
length = parsed.length;
for (idx = 0; idx < length; idx++) {
header = parsed[idx];
message.addHeader('record-route', headerValue.substring(header.possition, header.offset));
message.headers['Record-Route'][message.getHeaders('record-route').length - 1].parsed = header.parsed;
}
}
break;
case 'call-id':
case 'i':
message.setHeader('call-id', headerValue);
parsed = message.parseHeader('call-id');
if(parsed) {
message.call_id = headerValue;
}
break;
case 'contact':
case 'm':
parsed = Grammar.parse(headerValue, 'Contact');
if (parsed === -1) {
parsed = undefined;
} else {
length = parsed.length;
for (idx = 0; idx < length; idx++) {
header = parsed[idx];
message.addHeader('contact', headerValue.substring(header.possition, header.offset));
message.headers.Contact[message.getHeaders('contact').length - 1].parsed = header.parsed;
}
}
break;
case 'content-length':
case 'l':
message.setHeader('content-length', headerValue);
parsed = message.parseHeader('content-length');
break;
case 'content-type':
case 'c':
message.setHeader('content-type', headerValue);
parsed = message.parseHeader('content-type');
break;
case 'cseq':
message.setHeader('cseq', headerValue);
parsed = message.parseHeader('cseq');
if(parsed) {
message.cseq = parsed.value;
}
if(message instanceof SIPMessage.IncomingResponse) {
message.method = parsed.method;
}
break;
case 'max-forwards':
message.setHeader('max-forwards', headerValue);
parsed = message.parseHeader('max-forwards');
break;
case 'www-authenticate':
message.setHeader('www-authenticate', headerValue);
parsed = message.parseHeader('www-authenticate');
break;
case 'proxy-authenticate':
message.setHeader('proxy-authenticate', headerValue);
parsed = message.parseHeader('proxy-authenticate');
break;
case 'session-expires':
case 'x':
message.setHeader('session-expires', headerValue);
parsed = message.parseHeader('session-expires');
if (parsed) {
message.session_expires = parsed.expires;
message.session_expires_refresher = parsed.refresher;
}
break;
case 'refer-to':
case 'r':
message.setHeader('refer-to', headerValue);
parsed = message.parseHeader('refer-to');
if(parsed) {
message.refer_to = parsed;
}
break;
case 'replaces':
message.setHeader('replaces', headerValue);
parsed = message.parseHeader('replaces');
if(parsed) {
message.replaces = parsed;
}
break;
case 'event':
case 'o':
message.setHeader('event', headerValue);
parsed = message.parseHeader('event');
if(parsed) {
message.event = parsed;
}
break;
default:
// Do not parse this header.
message.setHeader(headerName, headerValue);
parsed = 0;
}
if (parsed === undefined) {
return {
error: 'error parsing header "'+ headerName +'"'
};
} else {
return true;
}
}
/**
* Parse SIP Message
*/
Parser.parseMessage = function(data, ua) {
var message, firstLine, contentLength, bodyStart, parsed,
headerStart = 0,
headerEnd = data.indexOf('\r\n');
if(headerEnd === -1) {
debugerror('parseMessage() | no CRLF found, not a SIP message');
return;
}
// Parse first line. Check if it is a Request or a Reply.
firstLine = data.substring(0, headerEnd);
parsed = Grammar.parse(firstLine, 'Request_Response');
if(parsed === -1) {
debugerror('parseMessage() | error parsing first line of SIP message: "' + firstLine + '"');
return;
} else if(!parsed.status_code) {
message = new SIPMessage.IncomingRequest(ua);
message.method = parsed.method;
message.ruri = parsed.uri;
} else {
message = new SIPMessage.IncomingResponse();
message.status_code = parsed.status_code;
message.reason_phrase = parsed.reason_phrase;
}
message.data = data;
headerStart = headerEnd + 2;
/* Loop over every line in data. Detect the end of each header and parse
* it or simply add to the headers collection.
*/
while(true) {
headerEnd = getHeader(data, headerStart);
// The SIP message has normally finished.
if(headerEnd === -2) {
bodyStart = headerStart + 2;
break;
}
// data.indexOf returned -1 due to a malformed message.
else if(headerEnd === -1) {
debugerror('parseMessage() | malformed message');
return;
}
parsed = parseHeader(message, data, headerStart, headerEnd);
if(parsed !== true) {
debugerror('parseMessage() |', parsed.error);
return;
}
headerStart = headerEnd + 2;
}
/* RFC3261 18.3.
* If there are additional bytes in the transport packet
* beyond the end of the body, they MUST be discarded.
*/
if(message.hasHeader('content-length')) {
contentLength = message.getHeader('content-length');
message.body = data.substr(bodyStart, contentLength);
} else {
message.body = data.substring(bodyStart);
}
return message;
};
},{"./Grammar":6,"./SIPMessage":18,"debug":34}],11:[function(require,module,exports){
/* globals RTCPeerConnection: false, RTCSessionDescription: false */
module.exports = RTCSession;
var C = {
// RTCSession states
STATUS_NULL: 0,
STATUS_INVITE_SENT: 1,
STATUS_1XX_RECEIVED: 2,
STATUS_INVITE_RECEIVED: 3,
STATUS_WAITING_FOR_ANSWER: 4,
STATUS_ANSWERED: 5,
STATUS_WAITING_FOR_ACK: 6,
STATUS_CANCELED: 7,
STATUS_TERMINATED: 8,
STATUS_CONFIRMED: 9
};
/**
* Expose C object.
*/
RTCSession.C = C;
/**
* Dependencies.
*/
var util = require('util');
var events = require('events');
var debug = require('debug')('JsSIP:RTCSession');
var debugerror = require('debug')('JsSIP:ERROR:RTCSession');
debugerror.log = console.warn.bind(console);
var sdp_transform = require('sdp-transform');
var JsSIP_C = require('./Constants');
var Exceptions = require('./Exceptions');
var Transactions = require('./Transactions');
var Utils = require('./Utils');
var Timers = require('./Timers');
var SIPMessage = require('./SIPMessage');
var Dialog = require('./Dialog');
var RequestSender = require('./RequestSender');
var RTCSession_Request = require('./RTCSession/Request');
var RTCSession_DTMF = require('./RTCSession/DTMF');
var RTCSession_ReferNotifier = require('./RTCSession/ReferNotifier');
var RTCSession_ReferSubscriber = require('./RTCSession/ReferSubscriber');
/**
* Local variables.
*/
var holdMediaTypes = ['audio', 'video'];
function RTCSession(ua) {
debug('new');
this.ua = ua;
this.status = C.STATUS_NULL;
this.dialog = null;
this.earlyDialogs = {};
this.connection = null; // The RTCPeerConnection instance (public attribute).
// RTCSession confirmation flag
this.is_confirmed = false;
// is late SDP being negotiated
this.late_sdp = false;
// Default rtcOfferConstraints and rtcAnswerConstrainsts (passed in connect() or answer()).
this.rtcOfferConstraints = null;
this.rtcAnswerConstraints = null;
// Local MediaStream.
this.localMediaStream = null;
this.localMediaStreamLocallyGenerated = false;
// Flag to indicate PeerConnection ready for new actions.
this.rtcReady = true;
// SIP Timers
this.timers = {
ackTimer: null,
expiresTimer: null,
invite2xxTimer: null,
userNoAnswerTimer: null
};
// Session info
this.direction = null;
this.local_identity = null;
this.remote_identity = null;
this.start_time = null;
this.end_time = null;
this.tones = null;
// Mute/Hold state
this.audioMuted = false;
this.videoMuted = false;
this.localHold = false;
this.remoteHold = false;
// Session Timers (RFC 4028)
this.sessionTimers = {
enabled: this.ua.configuration.session_timers,
defaultExpires: JsSIP_C.SESSION_EXPIRES,
currentExpires: null,
running: false,
refresher: false,
timer: null // A setTimeout.
};
// Map of ReferSubscriber instances indexed by the REFER's CSeq number
this.referSubscribers = {};
// Custom session empty object for high level use
this.data = {};
// Expose session failed/ended causes as a property of the RTCSession instance
this.causes = JsSIP_C.causes;
events.EventEmitter.call(this);
}
util.inherits(RTCSession, events.EventEmitter);
/**
* User API
*/
RTCSession.prototype.isInProgress = function() {
switch(this.status) {
case C.STATUS_NULL:
case C.STATUS_INVITE_SENT:
case C.STATUS_1XX_RECEIVED:
case C.STATUS_INVITE_RECEIVED:
case C.STATUS_WAITING_FOR_ANSWER:
return true;
default:
return false;
}
};
RTCSession.prototype.isEstablished = function() {
switch(this.status) {
case C.STATUS_ANSWERED:
case C.STATUS_WAITING_FOR_ACK:
case C.STATUS_CONFIRMED:
return true;
default:
return false;
}
};
RTCSession.prototype.isEnded = function() {
switch(this.status) {
case C.STATUS_CANCELED:
case C.STATUS_TERMINATED:
return true;
default:
return false;
}
};
RTCSession.prototype.isMuted = function() {
return {
audio: this.audioMuted,
video: this.videoMuted
};
};
RTCSession.prototype.isOnHold = function() {
return {
local: this.localHold,
remote: this.remoteHold
};
};
/**
* Check if RTCSession is ready for an outgoing re-INVITE or UPDATE with SDP.
*/
RTCSession.prototype.isReadyToReOffer = function() {
if (! this.rtcReady) {
debug('isReadyToReOffer() | internal WebRTC status not ready');
return false;
}
// No established yet.
if (! this.dialog) {
debug('isReadyToReOffer() | session not established yet');
return false;
}
// Another INVITE transaction is in progress
if (this.dialog.uac_pending_reply === true || this.dialog.uas_pending_reply === true) {
debug('isReadyToReOffer() | there is another INVITE/UPDATE transaction in progress');
return false;
}
return true;
};
RTCSession.prototype.connect = function(target, options, initCallback) {
debug('connect()');
options = options || {};
var event, requestParams,
originalTarget = target,
eventHandlers = options.eventHandlers || {},
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
mediaConstraints = options.mediaConstraints || {audio: true, video: true},
mediaStream = options.mediaStream || null,
pcConfig = options.pcConfig || {iceServers:[]},
rtcConstraints = options.rtcConstraints || null,
rtcOfferConstraints = options.rtcOfferConstraints || null;
this.rtcOfferConstraints = rtcOfferConstraints;
this.rtcAnswerConstraints = options.rtcAnswerConstraints || null;
// Session Timers.
if (this.sessionTimers.enabled) {
if (Utils.isDecimal(options.sessionTimersExpires)) {
if (options.sessionTimersExpires >= JsSIP_C.MIN_SESSION_EXPIRES) {
this.sessionTimers.defaultExpires = options.sessionTimersExpires;
}
else {
this.sessionTimers.defaultExpires = JsSIP_C.SESSION_EXPIRES;
}
}
}
this.data = options.data || this.data;
if (target === undefined) {
throw new TypeError('Not enough arguments');
}
// Check WebRTC support.
if (!window.RTCPeerConnection) {
throw new Exceptions.NotSupportedError('WebRTC not supported');
}
// Check target validity
target = this.ua.normalizeTarget(target);
if (!target) {
throw new TypeError('Invalid target: '+ originalTarget);
}
// Check Session Status
if (this.status !== C.STATUS_NULL) {
throw new Exceptions.InvalidStateError(this.status);
}
// Set event handlers
for (event in eventHandlers) {
this.on(event, eventHandlers[event]);
}
// Session parameter initialization
this.from_tag = Utils.newTag();
// Set anonymous property
this.anonymous = options.anonymous || false;
// OutgoingSession specific parameters
this.isCanceled = false;
requestParams = {from_tag: this.from_tag};
this.contact = this.ua.contact.toString({
anonymous: this.anonymous,
outbound: true
});
if (this.anonymous) {
requestParams.from_display_name = 'Anonymous';
requestParams.from_uri = 'sip:[email protected]';
extraHeaders.push('P-Preferred-Identity: '+ this.ua.configuration.uri.toString());
extraHeaders.push('Privacy: id');
}
extraHeaders.push('Contact: '+ this.contact);
extraHeaders.push('Content-Type: application/sdp');
if (this.sessionTimers.enabled) {
extraHeaders.push('Session-Expires: ' + this.sessionTimers.defaultExpires);
}
this.request = new SIPMessage.OutgoingRequest(JsSIP_C.INVITE, target, this.ua, requestParams, extraHeaders);
this.id = this.request.call_id + this.from_tag;
// Create a new RTCPeerConnection instance.
createRTCConnection.call(this, pcConfig, rtcConstraints);
// Save the session into the ua sessions collection.
this.ua.sessions[this.id] = this;
// Set internal properties
this.direction = 'outgoing';
this.local_identity = this.request.from;
this.remote_identity = this.request.to;
// User explicitly provided a newRTCSession callback for this session
if (initCallback) {
initCallback(this);
} else {
newRTCSession.call(this, 'local', this.request);
}
sendInitialRequest.call(this, mediaConstraints, rtcOfferConstraints, mediaStream);
};
RTCSession.prototype.init_incoming = function(request, initCallback) {
debug('init_incoming()');
var expires,
self = this,
contentType = request.getHeader('Content-Type');
// Check body and content type
if (request.body && (contentType !== 'application/sdp')) {
request.reply(415);
return;
}
// Session parameter initialization
this.status = C.STATUS_INVITE_RECEIVED;
this.from_tag = request.from_tag;
this.id = request.call_id + this.from_tag;
this.request = request;
this.contact = this.ua.contact.toString();
// Save the session into the ua sessions collection.
this.ua.sessions[this.id] = this;
// Get the Expires header value if exists
if (request.hasHeader('expires')) {
expires = request.getHeader('expires') * 1000;
}
/* Set the to_tag before
* replying a response code that will create a dialog.
*/
request.to_tag = Utils.newTag();
// An error on dialog creation will fire 'failed' event
if (! createDialog.call(this, request, 'UAS', true)) {
request.reply(500, 'Missing Contact header field');
return;
}
if (request.body) {
this.late_sdp = false;
}
else {
this.late_sdp = true;
}
this.status = C.STATUS_WAITING_FOR_ANSWER;
// Set userNoAnswerTimer
this.timers.userNoAnswerTimer = setTimeout(function() {
request.reply(408);
failed.call(self, 'local',null, JsSIP_C.causes.NO_ANSWER);
}, this.ua.configuration.no_answer_timeout
);
/* Set expiresTimer
* RFC3261 13.3.1
*/
if (expires) {
this.timers.expiresTimer = setTimeout(function() {
if(self.status === C.STATUS_WAITING_FOR_ANSWER) {
request.reply(487);
failed.call(self, 'system', null, JsSIP_C.causes.EXPIRES);
}
}, expires
);
}
// Set internal properties
this.direction = 'incoming';
this.local_identity = request.to;
this.remote_identity = request.from;
// A init callback was specifically defined
if (initCallback) {
initCallback(this);
// Fire 'newRTCSession' event.
} else {
newRTCSession.call(this, 'remote', request);
}
// The user may have rejected the call in the 'newRTCSession' event.
if (this.status === C.STATUS_TERMINATED) {
return;
}
// Reply 180.
request.reply(180, null, ['Contact: ' + self.contact]);
// Fire 'progress' event.
// TODO: Document that 'response' field in 'progress' event is null for
// incoming calls.
progress.call(self, 'local', null);
};
/**
* Answer the call.
*/
RTCSession.prototype.answer = function(options) {
debug('answer()');
options = options || {};
var idx, length, sdp, tracks,
peerHasAudioLine = false,
peerHasVideoLine = false,
peerOffersFullAudio = false,
peerOffersFullVideo = false,
self = this,
request = this.request,
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
mediaConstraints = options.mediaConstraints || {},
mediaStream = options.mediaStream || null,
pcConfig = options.pcConfig || {iceServers:[]},
rtcConstraints = options.rtcConstraints || null,
rtcAnswerConstraints = options.rtcAnswerConstraints || null;
this.rtcAnswerConstraints = rtcAnswerConstraints;
this.rtcOfferConstraints = options.rtcOfferConstraints || null;
// Session Timers.
if (this.sessionTimers.enabled) {
if (Utils.isDecimal(options.sessionTimersExpires)) {
if (options.sessionTimersExpires >= JsSIP_C.MIN_SESSION_EXPIRES) {
this.sessionTimers.defaultExpires = options.sessionTimersExpires;
}
else {
this.sessionTimers.defaultExpires = JsSIP_C.SESSION_EXPIRES;
}
}
}
this.data = options.data || this.data;
// Check Session Direction and Status
if (this.direction !== 'incoming') {
throw new Exceptions.NotSupportedError('"answer" not supported for outgoing RTCSession');
} else if (this.status !== C.STATUS_WAITING_FOR_ANSWER) {
throw new Exceptions.InvalidStateError(this.status);
}
this.status = C.STATUS_ANSWERED;
// An error on dialog creation will fire 'failed' event
if (! createDialog.call(this, request, 'UAS')) {
request.reply(500, 'Error creating dialog');
return;
}
clearTimeout(this.timers.userNoAnswerTimer);
extraHeaders.unshift('Contact: ' + self.contact);
// Determine incoming media from incoming SDP offer (if any).
sdp = request.parseSDP();
// Make sure sdp.media is an array, not the case if there is only one media
if (! Array.isArray(sdp.media)) {
sdp.media = [sdp.media];
}
// Go through all medias in SDP to find offered capabilities to answer with
idx = sdp.media.length;
while(idx--) {
var m = sdp.media[idx];
if (m.type === 'audio') {
peerHasAudioLine = true;
if (!m.direction || m.direction === 'sendrecv') {
peerOffersFullAudio = true;
}
}
if (m.type === 'video') {
peerHasVideoLine = true;
if (!m.direction || m.direction === 'sendrecv') {
peerOffersFullVideo = true;
}
}
}
// Remove audio from mediaStream if suggested by mediaConstraints
if (mediaStream && mediaConstraints.audio === false) {
tracks = mediaStream.getAudioTracks();
length = tracks.length;
for (idx=0; idx<length; idx++) {
mediaStream.removeTrack(tracks[idx]);
}
}
// Remove video from mediaStream if suggested by mediaConstraints
if (mediaStream && mediaConstraints.video === false) {
tracks = mediaStream.getVideoTracks();
length = tracks.length;
for (idx=0; idx<length; idx++) {
mediaStream.removeTrack(tracks[idx]);
}
}
// Set audio constraints based on incoming stream if not supplied
if (!mediaStream && mediaConstraints.audio === undefined) {
mediaConstraints.audio = peerOffersFullAudio;
}
// Set video constraints based on incoming stream if not supplied
if (!mediaStream && mediaConstraints.video === undefined) {
mediaConstraints.video = peerOffersFullVideo;
}
// Don't ask for audio if the incoming offer has no audio section
if (!mediaStream && !peerHasAudioLine) {
mediaConstraints.audio = false;
}
// Don't ask for video if the incoming offer has no video section
if (!mediaStream && !peerHasVideoLine) {
mediaConstraints.video = false;
}
// Create a new RTCPeerConnection instance.
// TODO: This may throw an error, should react.
createRTCConnection.call(this, pcConfig, rtcConstraints);
// If a local MediaStream is given use it.
if (mediaStream) {
userMediaSucceeded(mediaStream);
// If at least audio or video is requested prompt getUserMedia.
} else if (mediaConstraints.audio || mediaConstraints.video) {
self.localMediaStreamLocallyGenerated = true;
navigator.mediaDevices.getUserMedia(mediaConstraints)
.then(userMediaSucceeded)
.catch(function(error) {
userMediaFailed(error);
self.emit('getusermediafailed', error);
});
// Otherwise don't prompt getUserMedia.
} else {
userMediaSucceeded(null);
}
// User media succeeded
function userMediaSucceeded(stream) {
if (self.status === C.STATUS_TERMINATED) { return; }
self.localMediaStream = stream;
if (stream) {
self.connection.addStream(stream);
}
// If it's an incoming INVITE without SDP notify the app with the
// RTCPeerConnection so it can do stuff on it before generating the offer.
if (! self.request.body) {
self.emit('peerconnection', {
peerconnection: self.connection
});
}
if (! self.late_sdp) {
var e = {originator:'remote', type:'offer', sdp:request.body};
var offer = new RTCSessionDescription({type:'offer', sdp:e.sdp});
self.emit('sdp', e);
self.connection.setRemoteDescription(offer)
.then(remoteDescriptionSucceededOrNotNeeded)
.catch(function(error) {
request.reply(488);
failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_ERROR);
self.emit('peerconnection:setremotedescriptionfailed', error);
});
}
else {
remoteDescriptionSucceededOrNotNeeded();
}
}
// User media failed
function userMediaFailed() {
if (self.status === C.STATUS_TERMINATED) { return; }
request.reply(480);
failed.call(self, 'local', null, JsSIP_C.causes.USER_DENIED_MEDIA_ACCESS);
}
function remoteDescriptionSucceededOrNotNeeded() {
connecting.call(self, request);
if (! self.late_sdp) {
createLocalDescription.call(self, 'answer', rtcSucceeded, rtcFailed, rtcAnswerConstraints);
} else {
createLocalDescription.call(self, 'offer', rtcSucceeded, rtcFailed, self.rtcOfferConstraints);
}
}
function rtcSucceeded(desc) {
if (self.status === C.STATUS_TERMINATED) { return; }
// run for reply success callback
function replySucceeded() {
self.status = C.STATUS_WAITING_FOR_ACK;
setInvite2xxTimer.call(self, request, desc);
setACKTimer.call(self);
accepted.call(self, 'local');
}
// run for reply failure callback
function replyFailed() {
failed.call(self, 'system', null, JsSIP_C.causes.CONNECTION_ERROR);
}
handleSessionTimersInIncomingRequest.call(self, request, extraHeaders);
request.reply(200, null, extraHeaders,
desc,
replySucceeded,
replyFailed
);
}
function rtcFailed() {
if (self.status === C.STATUS_TERMINATED) { return; }
request.reply(500);
failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_ERROR);
}
};
/**
* Terminate the call.
*/
RTCSession.prototype.terminate = function(options) {
debug('terminate()');
options = options || {};
var cancel_reason, dialog,
cause = options.cause || JsSIP_C.causes.BYE,
status_code = options.status_code,
reason_phrase = options.reason_phrase,
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
body = options.body,
self = this;
// Check Session Status
if (this.status === C.STATUS_TERMINATED) {
throw new Exceptions.InvalidStateError(this.status);
}
switch(this.status) {
// - UAC -
case C.STATUS_NULL:
case C.STATUS_INVITE_SENT:
case C.STATUS_1XX_RECEIVED:
debug('canceling session');
if (status_code && (status_code < 200 || status_code >= 700)) {
throw new TypeError('Invalid status_code: '+ status_code);
} else if (status_code) {
reason_phrase = reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || '';
cancel_reason = 'SIP ;cause=' + status_code + ' ;text="' + reason_phrase + '"';
}
// Check Session Status
if (this.status === C.STATUS_NULL) {
this.isCanceled = true;
this.cancelReason = cancel_reason;
} else if (this.status === C.STATUS_INVITE_SENT) {
this.isCanceled = true;
this.cancelReason = cancel_reason;
} else if(this.status === C.STATUS_1XX_RECEIVED) {
this.request.cancel(cancel_reason);
}
this.status = C.STATUS_CANCELED;
failed.call(this, 'local', null, JsSIP_C.causes.CANCELED);
break;
// - UAS -
case C.STATUS_WAITING_FOR_ANSWER:
case C.STATUS_ANSWERED:
debug('rejecting session');
status_code = status_code || 480;
if (status_code < 300 || status_code >= 700) {
throw new TypeError('Invalid status_code: '+ status_code);
}
this.request.reply(status_code, reason_phrase, extraHeaders, body);
failed.call(this, 'local', null, JsSIP_C.causes.REJECTED);
break;
case C.STATUS_WAITING_FOR_ACK:
case C.STATUS_CONFIRMED:
debug('terminating session');
reason_phrase = options.reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || '';
if (status_code && (status_code < 200 || status_code >= 700)) {
throw new TypeError('Invalid status_code: '+ status_code);
} else if (status_code) {
extraHeaders.push('Reason: SIP ;cause=' + status_code + '; text="' + reason_phrase + '"');
}
/* RFC 3261 section 15 (Terminating a session):
*
* "...the callee's UA MUST NOT send a BYE on a confirmed dialog
* until it has received an ACK for its 2xx response or until the server
* transaction times out."
*/
if (this.status === C.STATUS_WAITING_FOR_ACK &&
this.direction === 'incoming' &&
this.request.server_transaction.state !== Transactions.C.STATUS_TERMINATED) {
// Save the dialog for later restoration
dialog = this.dialog;
// Send the BYE as soon as the ACK is received...
this.receiveRequest = function(request) {
if(request.method === JsSIP_C.ACK) {
sendRequest.call(this, JsSIP_C.BYE, {
extraHeaders: extraHeaders,
body: body
});
dialog.terminate();
}
};
// .., or when the INVITE transaction times out
this.request.server_transaction.on('stateChanged', function(){
if (this.state === Transactions.C.STATUS_TERMINATED) {
sendRequest.call(self, JsSIP_C.BYE, {
extraHeaders: extraHeaders,
body: body
});
dialog.terminate();
}
});
ended.call(this, 'local', null, cause);
// Restore the dialog into 'this' in order to be able to send the in-dialog BYE :-)
this.dialog = dialog;
// Restore the dialog into 'ua' so the ACK can reach 'this' session
this.ua.dialogs[dialog.id.toString()] = dialog;
} else {
sendRequest.call(this, JsSIP_C.BYE, {
extraHeaders: extraHeaders,
body: body
});
ended.call(this, 'local', null, cause);
}
}
};
RTCSession.prototype.close = function() {
debug('close()');
var idx;
if (this.status === C.STATUS_TERMINATED) {
return;
}
// Terminate RTC.
if (this.connection) {
try {
this.connection.close();
} catch(error) {
debugerror('close() | error closing the RTCPeerConnection: %o', error);
}
}
// Close local MediaStream if it was not given by the user.
if (this.localMediaStream && this.localMediaStreamLocallyGenerated) {
debug('close() | closing local MediaStream');
Utils.closeMediaStream(this.localMediaStream);
}
// Terminate signaling.
// Clear SIP timers
for(idx in this.timers) {
clearTimeout(this.timers[idx]);
}
// Clear Session Timers.
clearTimeout(this.sessionTimers.timer);
// Terminate confirmed dialog
if (this.dialog) {
this.dialog.terminate();
delete this.dialog;
}
// Terminate early dialogs
for(idx in this.earlyDialogs) {
this.earlyDialogs[idx].terminate();
delete this.earlyDialogs[idx];
}
this.status = C.STATUS_TERMINATED;
delete this.ua.sessions[this.id];
};
RTCSession.prototype.sendDTMF = function(tones, options) {
debug('sendDTMF() | tones: %s', tones);
var duration, interToneGap,
position = 0,
self = this;
options = options || {};
duration = options.duration || null;
interToneGap = options.interToneGap || null;
if (tones === undefined) {
throw new TypeError('Not enough arguments');
}
// Check Session Status
if (this.status !== C.STATUS_CONFIRMED && this.status !== C.STATUS_WAITING_FOR_ACK) {
throw new Exceptions.InvalidStateError(this.status);
}
// Convert to string
if(typeof tones === 'number') {
tones = tones.toString();
}
// Check tones
if (!tones || typeof tones !== 'string' || !tones.match(/^[0-9A-DR#*,]+$/i)) {
throw new TypeError('Invalid tones: '+ tones);
}
// Check duration
if (duration && !Utils.isDecimal(duration)) {
throw new TypeError('Invalid tone duration: '+ duration);
} else if (!duration) {
duration = RTCSession_DTMF.C.DEFAULT_DURATION;
} else if (duration < RTCSession_DTMF.C.MIN_DURATION) {
debug('"duration" value is lower than the minimum allowed, setting it to '+ RTCSession_DTMF.C.MIN_DURATION+ ' milliseconds');
duration = RTCSession_DTMF.C.MIN_DURATION;
} else if (duration > RTCSession_DTMF.C.MAX_DURATION) {
debug('"duration" value is greater than the maximum allowed, setting it to '+ RTCSession_DTMF.C.MAX_DURATION +' milliseconds');
duration = RTCSession_DTMF.C.MAX_DURATION;
} else {
duration = Math.abs(duration);
}
options.duration = duration;
// Check interToneGap
if (interToneGap && !Utils.isDecimal(interToneGap)) {
throw new TypeError('Invalid interToneGap: '+ interToneGap);
} else if (!interToneGap) {
interToneGap = RTCSession_DTMF.C.DEFAULT_INTER_TONE_GAP;
} else if (interToneGap < RTCSession_DTMF.C.MIN_INTER_TONE_GAP) {
debug('"interToneGap" value is lower than the minimum allowed, setting it to '+ RTCSession_DTMF.C.MIN_INTER_TONE_GAP +' milliseconds');
interToneGap = RTCSession_DTMF.C.MIN_INTER_TONE_GAP;
} else {
interToneGap = Math.abs(interToneGap);
}
if (this.tones) {
// Tones are already queued, just add to the queue
this.tones += tones;
return;
}
this.tones = tones;
// Send the first tone
_sendDTMF();
function _sendDTMF() {
var tone, timeout;
if (self.status === C.STATUS_TERMINATED || !self.tones || position >= self.tones.length) {
// Stop sending DTMF
self.tones = null;
return;
}
tone = self.tones[position];
position += 1;
if (tone === ',') {
timeout = 2000;
} else {
var dtmf = new RTCSession_DTMF(self);
options.eventHandlers = {
onFailed: function() { self.tones = null; }
};
dtmf.send(tone, options);
timeout = duration + interToneGap;
}
// Set timeout for the next tone
setTimeout(_sendDTMF, timeout);
}
};
/**
* Mute
*/
RTCSession.prototype.mute = function(options) {
debug('mute()');
options = options || {audio:true, video:false};
var
audioMuted = false,
videoMuted = false;
if (this.audioMuted === false && options.audio) {
audioMuted = true;
this.audioMuted = true;
toogleMuteAudio.call(this, true);
}
if (this.videoMuted === false && options.video) {
videoMuted = true;
this.videoMuted = true;
toogleMuteVideo.call(this, true);
}
if (audioMuted === true || videoMuted === true) {
onmute.call(this, {
audio: audioMuted,
video: videoMuted
});
}
};
/**
* Unmute
*/
RTCSession.prototype.unmute = function(options) {
debug('unmute()');
options = options || {audio:true, video:true};
var
audioUnMuted = false,
videoUnMuted = false;
if (this.audioMuted === true && options.audio) {
audioUnMuted = true;
this.audioMuted = false;
if (this.localHold === false) {
toogleMuteAudio.call(this, false);
}
}
if (this.videoMuted === true && options.video) {
videoUnMuted = true;
this.videoMuted = false;
if (this.localHold === false) {
toogleMuteVideo.call(this, false);
}
}
if (audioUnMuted === true || videoUnMuted === true) {
onunmute.call(this, {
audio: audioUnMuted,
video: videoUnMuted
});
}
};
/**
* Hold
*/
RTCSession.prototype.hold = function(options, done) {
debug('hold()');
options = options || {};
var self = this,
eventHandlers;
if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) {
return false;
}
if (this.localHold === true) {
return false;
}
if (! this.isReadyToReOffer()) {
return false;
}
this.localHold = true;
onhold.call(this, 'local');
eventHandlers = {
succeeded: function() {
if (done) { done(); }
},
failed: function() {
self.terminate({
cause: JsSIP_C.causes.WEBRTC_ERROR,
status_code: 500,
reason_phrase: 'Hold Failed'
});
}
};
if (options.useUpdate) {
sendUpdate.call(this, {
sdpOffer: true,
eventHandlers: eventHandlers,
extraHeaders: options.extraHeaders
});
} else {
sendReinvite.call(this, {
eventHandlers: eventHandlers,
extraHeaders: options.extraHeaders
});
}
return true;
};
RTCSession.prototype.unhold = function(options, done) {
debug('unhold()');
options = options || {};
var self = this,
eventHandlers;
if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) {
return false;
}
if (this.localHold === false) {
return false;
}
if (! this.isReadyToReOffer()) {
return false;
}
this.localHold = false;
onunhold.call(this, 'local');
eventHandlers = {
succeeded: function() {
if (done) { done(); }
},
failed: function() {
self.terminate({
cause: JsSIP_C.causes.WEBRTC_ERROR,
status_code: 500,
reason_phrase: 'Unhold Failed'
});
}
};
if (options.useUpdate) {
sendUpdate.call(this, {
sdpOffer: true,
eventHandlers: eventHandlers,
extraHeaders: options.extraHeaders
});
} else {
sendReinvite.call(this, {
eventHandlers: eventHandlers,
extraHeaders: options.extraHeaders
});
}
return true;
};
RTCSession.prototype.renegotiate = function(options, done) {
debug('renegotiate()');
options = options || {};
var self = this,
eventHandlers,
rtcOfferConstraints = options.rtcOfferConstraints || null;
if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) {
return false;
}
if (! this.isReadyToReOffer()) {
return false;
}
eventHandlers = {
succeeded: function() {
if (done) { done(); }
},
failed: function() {
self.terminate({
cause: JsSIP_C.causes.WEBRTC_ERROR,
status_code: 500,
reason_phrase: 'Media Renegotiation Failed'
});
}
};
setLocalMediaStatus.call(this);
if (options.useUpdate) {
sendUpdate.call(this, {
sdpOffer: true,
eventHandlers: eventHandlers,
rtcOfferConstraints: rtcOfferConstraints,
extraHeaders: options.extraHeaders
});
} else {
sendReinvite.call(this, {
eventHandlers: eventHandlers,
rtcOfferConstraints: rtcOfferConstraints,
extraHeaders: options.extraHeaders
});
}
return true;
};
/**
* Refer
*/
RTCSession.prototype.refer = function(target, options) {
debug('refer()');
var self = this,
originalTarget = target,
referSubscriber,
id;
if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) {
return false;
}
// Check target validity
target = this.ua.normalizeTarget(target);
if (!target) {
throw new TypeError('Invalid target: '+ originalTarget);
}
referSubscriber = new RTCSession_ReferSubscriber(this);
referSubscriber.sendRefer(target, options);
// Store in the map
id = referSubscriber.outgoingRequest.cseq;
this.referSubscribers[id] = referSubscriber;
// Listen for ending events so we can remove it from the map
referSubscriber.on('requestFailed', function() {
delete self.referSubscribers[id];
});
referSubscriber.on('accepted', function() {
delete self.referSubscribers[id];
});
referSubscriber.on('failed', function() {
delete self.referSubscribers[id];
});
return referSubscriber;
};
/**
* In dialog Request Reception
*/
RTCSession.prototype.receiveRequest = function(request) {
debug('receiveRequest()');
var contentType,
self = this;
if(request.method === JsSIP_C.CANCEL) {
/* RFC3261 15 States that a UAS may have accepted an invitation while a CANCEL
* was in progress and that the UAC MAY continue with the session established by
* any 2xx response, or MAY terminate with BYE. JsSIP does continue with the
* established session. So the CANCEL is processed only if the session is not yet
* established.
*/
/*
* Terminate the whole session in case the user didn't accept (or yet send the answer)
* nor reject the request opening the session.
*/
if(this.status === C.STATUS_WAITING_FOR_ANSWER || this.status === C.STATUS_ANSWERED) {
this.status = C.STATUS_CANCELED;
this.request.reply(487);
failed.call(this, 'remote', request, JsSIP_C.causes.CANCELED);
}
} else {
// Requests arriving here are in-dialog requests.
switch(request.method) {
case JsSIP_C.ACK:
if (this.status !== C.STATUS_WAITING_FOR_ACK) {
return;
}
// Update signaling status.
this.status = C.STATUS_CONFIRMED;
clearTimeout(this.timers.ackTimer);
clearTimeout(this.timers.invite2xxTimer);
if (this.late_sdp) {
if (!request.body) {
this.terminate({
cause: JsSIP_C.causes.MISSING_SDP,
status_code: 400
});
break;
}
var e = {originator:'remote', type:'answer', sdp:request.body};
var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp});
this.emit('sdp', e);
this.connection.setRemoteDescription(answer)
.then(function() {
if (!self.is_confirmed) {
confirmed.call(self, 'remote', request);
}
})
.catch(function(error) {
self.terminate({
cause: JsSIP_C.causes.BAD_MEDIA_DESCRIPTION,
status_code: 488
});
self.emit('peerconnection:setremotedescriptionfailed', error);
});
}
else {
if (!this.is_confirmed) {
confirmed.call(this, 'remote', request);
}
}
break;
case JsSIP_C.BYE:
if(this.status === C.STATUS_CONFIRMED) {
request.reply(200);
ended.call(this, 'remote', request, JsSIP_C.causes.BYE);
}
else if (this.status === C.STATUS_INVITE_RECEIVED) {
request.reply(200);
this.request.reply(487, 'BYE Received');
ended.call(this, 'remote', request, JsSIP_C.causes.BYE);
}
else {
request.reply(403, 'Wrong Status');
}
break;
case JsSIP_C.INVITE:
if(this.status === C.STATUS_CONFIRMED) {
if (request.hasHeader('replaces')) {
receiveReplaces.call(this, request);
} else {
receiveReinvite.call(this, request);
}
}
else {
request.reply(403, 'Wrong Status');
}
break;
case JsSIP_C.INFO:
if(this.status === C.STATUS_CONFIRMED || this.status === C.STATUS_WAITING_FOR_ACK || this.status === C.STATUS_INVITE_RECEIVED) {
contentType = request.getHeader('content-type');
if (contentType && (contentType.match(/^application\/dtmf-relay/i))) {
new RTCSession_DTMF(this).init_incoming(request);
}
else {
request.reply(415);
}
}
else {
request.reply(403, 'Wrong Status');
}
break;
case JsSIP_C.UPDATE:
if(this.status === C.STATUS_CONFIRMED) {
receiveUpdate.call(this, request);
}
else {
request.reply(403, 'Wrong Status');
}
break;
case JsSIP_C.REFER:
if(this.status === C.STATUS_CONFIRMED) {
receiveRefer.call(this, request);
}
else {
request.reply(403, 'Wrong Status');
}
break;
case JsSIP_C.NOTIFY:
if(this.status === C.STATUS_CONFIRMED) {
receiveNotify.call(this, request);
}
else {
request.reply(403, 'Wrong Status');
}
break;
default:
request.reply(501);
}
}
};
/**
* Session Callbacks
*/
RTCSession.prototype.onTransportError = function() {
debugerror('onTransportError()');
if(this.status !== C.STATUS_TERMINATED) {
this.terminate({
status_code: 500,
reason_phrase: JsSIP_C.causes.CONNECTION_ERROR,
cause: JsSIP_C.causes.CONNECTION_ERROR
});
}
};
RTCSession.prototype.onRequestTimeout = function() {
debug('onRequestTimeout');
if(this.status !== C.STATUS_TERMINATED) {
this.terminate({
status_code: 408,
reason_phrase: JsSIP_C.causes.REQUEST_TIMEOUT,
cause: JsSIP_C.causes.REQUEST_TIMEOUT
});
}
};
RTCSession.prototype.onDialogError = function() {
debugerror('onDialogError()');
if(this.status !== C.STATUS_TERMINATED) {
this.terminate({
status_code: 500,
reason_phrase: JsSIP_C.causes.DIALOG_ERROR,
cause: JsSIP_C.causes.DIALOG_ERROR
});
}
};
// Called from DTMF handler.
RTCSession.prototype.newDTMF = function(data) {
debug('newDTMF()');
this.emit('newDTMF', data);
};
RTCSession.prototype.resetLocalMedia = function() {
debug('resetLocalMedia()');
// Reset all but remoteHold.
this.localHold = false;
this.audioMuted = false;
this.videoMuted = false;
setLocalMediaStatus.call(this);
};
/**
* Private API.
*/
/**
* RFC3261 13.3.1.4
* Response retransmissions cannot be accomplished by transaction layer
* since it is destroyed when receiving the first 2xx answer
*/
function setInvite2xxTimer(request, body) {
var
self = this,
timeout = Timers.T1;
this.timers.invite2xxTimer = setTimeout(function invite2xxRetransmission() {
if (self.status !== C.STATUS_WAITING_FOR_ACK) {
return;
}
request.reply(200, null, ['Contact: '+ self.contact], body);
if (timeout < Timers.T2) {
timeout = timeout * 2;
if (timeout > Timers.T2) {
timeout = Timers.T2;
}
}
self.timers.invite2xxTimer = setTimeout(
invite2xxRetransmission, timeout
);
}, timeout);
}
/**
* RFC3261 14.2
* If a UAS generates a 2xx response and never receives an ACK,
* it SHOULD generate a BYE to terminate the dialog.
*/
function setACKTimer() {
var self = this;
this.timers.ackTimer = setTimeout(function() {
if(self.status === C.STATUS_WAITING_FOR_ACK) {
debug('no ACK received, terminating the session');
clearTimeout(self.timers.invite2xxTimer);
sendRequest.call(self, JsSIP_C.BYE);
ended.call(self, 'remote', null, JsSIP_C.causes.NO_ACK);
}
}, Timers.TIMER_H);
}
function createRTCConnection(pcConfig, rtcConstraints) {
var self = this;
this.connection = new RTCPeerConnection(pcConfig, rtcConstraints);
this.connection.addEventListener('iceconnectionstatechange', function() {
var state = self.connection.iceConnectionState;
// TODO: Do more with different states.
if (state === 'failed') {
self.terminate({
cause: JsSIP_C.causes.RTP_TIMEOUT,
status_code: 200,
reason_phrase: JsSIP_C.causes.RTP_TIMEOUT
});
}
});
}
function createLocalDescription(type, onSuccess, onFailure, constraints) {
debug('createLocalDescription()');
var self = this;
var connection = this.connection;
this.rtcReady = false;
if (type === 'offer') {
connection.createOffer(constraints)
.then(createSucceeded)
.catch(function(error) {
self.rtcReady = true;
if (onFailure) { onFailure(error); }
self.emit('peerconnection:createofferfailed', error);
});
}
else if (type === 'answer') {
connection.createAnswer(constraints)
.then(createSucceeded)
.catch(function(error) {
self.rtcReady = true;
if (onFailure) { onFailure(error); }
self.emit('peerconnection:createanswerfailed', error);
});
}
else {
throw new Error('createLocalDescription() | type must be "offer" or "answer", but "' +type+ '" was given');
}
// createAnswer or createOffer succeeded
function createSucceeded(desc) {
var listener;
connection.addEventListener('icecandidate', listener = function(event) {
var candidate = event.candidate;
if (! candidate) {
connection.removeEventListener('icecandidate', listener);
self.rtcReady = true;
if (onSuccess) {
var e = {originator:'local', type:type, sdp:connection.localDescription.sdp};
self.emit('sdp', e);
onSuccess(e.sdp);
}
onSuccess = null;
}
});
connection.setLocalDescription(desc)
.then(function() {
if (connection.iceGatheringState === 'complete') {
self.rtcReady = true;
if (onSuccess) {
var e = {originator:'local', type:type, sdp:connection.localDescription.sdp};
self.emit('sdp', e);
onSuccess(e.sdp);
onSuccess = null;
}
}
})
.catch(function(error) {
self.rtcReady = true;
if (onFailure) { onFailure(error); }
self.emit('peerconnection:setlocaldescriptionfailed', error);
});
}
}
/**
* Dialog Management
*/
function createDialog(message, type, early) {
var dialog, early_dialog,
local_tag = (type === 'UAS') ? message.to_tag : message.from_tag,
remote_tag = (type === 'UAS') ? message.from_tag : message.to_tag,
id = message.call_id + local_tag + remote_tag;
early_dialog = this.earlyDialogs[id];
// Early Dialog
if (early) {
if (early_dialog) {
return true;
} else {
early_dialog = new Dialog(this, message, type, Dialog.C.STATUS_EARLY);
// Dialog has been successfully created.
if(early_dialog.error) {
debug(early_dialog.error);
failed.call(this, 'remote', message, JsSIP_C.causes.INTERNAL_ERROR);
return false;
} else {
this.earlyDialogs[id] = early_dialog;
return true;
}
}
}
// Confirmed Dialog
else {
this.from_tag = message.from_tag;
this.to_tag = message.to_tag;
// In case the dialog is in _early_ state, update it
if (early_dialog) {
early_dialog.update(message, type);
this.dialog = early_dialog;
delete this.earlyDialogs[id];
return true;
}
// Otherwise, create a _confirmed_ dialog
dialog = new Dialog(this, message, type);
if(dialog.error) {
debug(dialog.error);
failed.call(this, 'remote', message, JsSIP_C.causes.INTERNAL_ERROR);
return false;
} else {
this.dialog = dialog;
return true;
}
}
}
/**
* In dialog INVITE Reception
*/
function receiveReinvite(request) {
debug('receiveReinvite()');
var
sdp, idx, direction, m,
self = this,
contentType = request.getHeader('Content-Type'),
hold = false,
rejected = false,
data = {
request: request,
callback: undefined,
reject: reject.bind(this)
};
function reject(options) {
options = options || {};
rejected = true;
var
status_code = options.status_code || 403,
reason_phrase = options.reason_phrase || '',
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [];
if (this.status !== C.STATUS_CONFIRMED) {
return false;
}
if (status_code < 300 || status_code >= 700) {
throw new TypeError('Invalid status_code: '+ status_code);
}
request.reply(status_code, reason_phrase, extraHeaders);
}
// Emit 'reinvite'.
this.emit('reinvite', data);
if (rejected) {
return;
}
if (request.body) {
this.late_sdp = false;
if (contentType !== 'application/sdp') {
debug('invalid Content-Type');
request.reply(415);
return;
}
sdp = request.parseSDP();
for (idx=0; idx < sdp.media.length; idx++) {
m = sdp.media[idx];
if (holdMediaTypes.indexOf(m.type) === -1) {
continue;
}
direction = m.direction || sdp.direction || 'sendrecv';
if (direction === 'sendonly' || direction === 'inactive') {
hold = true;
}
// If at least one of the streams is active don't emit 'hold'.
else {
hold = false;
break;
}
}
var e = {originator:'remote', type:'offer', sdp:request.body};
var offer = new RTCSessionDescription({type:'offer', sdp:e.sdp});
this.emit('sdp', e);
this.connection.setRemoteDescription(offer)
.then(doAnswer)
.catch(function(error) {
request.reply(488);
self.emit('peerconnection:setremotedescriptionfailed', error);
});
}
else {
this.late_sdp = true;
doAnswer();
}
function doAnswer() {
createSdp(
// onSuccess
function(sdp) {
var extraHeaders = ['Contact: ' + self.contact];
handleSessionTimersInIncomingRequest.call(self, request, extraHeaders);
if (self.late_sdp) {
sdp = mangleOffer.call(self, sdp);
}
request.reply(200, null, extraHeaders, sdp,
function() {
self.status = C.STATUS_WAITING_FOR_ACK;
setInvite2xxTimer.call(self, request, sdp);
setACKTimer.call(self);
}
);
// If callback is given execute it.
if (typeof data.callback === 'function') {
data.callback();
}
},
// onFailure
function() {
request.reply(500);
}
);
}
function createSdp(onSuccess, onFailure) {
if (! self.late_sdp) {
if (self.remoteHold === true && hold === false) {
self.remoteHold = false;
onunhold.call(self, 'remote');
} else if (self.remoteHold === false && hold === true) {
self.remoteHold = true;
onhold.call(self, 'remote');
}
createLocalDescription.call(self, 'answer', onSuccess, onFailure, self.rtcAnswerConstraints);
} else {
createLocalDescription.call(self, 'offer', onSuccess, onFailure, self.rtcOfferConstraints);
}
}
}
/**
* In dialog UPDATE Reception
*/
function receiveUpdate(request) {
debug('receiveUpdate()');
var
sdp, idx, direction, m,
self = this,
contentType = request.getHeader('Content-Type'),
rejected = false,
hold = false,
data = {
request: request,
callback: undefined,
reject: reject.bind(this)
};
function reject(options) {
options = options || {};
rejected = true;
var
status_code = options.status_code || 403,
reason_phrase = options.reason_phrase || '',
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [];
if (this.status !== C.STATUS_CONFIRMED) {
return false;
}
if (status_code < 300 || status_code >= 700) {
throw new TypeError('Invalid status_code: '+ status_code);
}
request.reply(status_code, reason_phrase, extraHeaders);
}
// Emit 'update'.
this.emit('update', data);
if (rejected) {
return;
}
if (! request.body) {
var extraHeaders = [];
handleSessionTimersInIncomingRequest.call(this, request, extraHeaders);
request.reply(200, null, extraHeaders);
return;
}
if (contentType !== 'application/sdp') {
debug('invalid Content-Type');
request.reply(415);
return;
}
sdp = request.parseSDP();
for (idx=0; idx < sdp.media.length; idx++) {
m = sdp.media[idx];
if (holdMediaTypes.indexOf(m.type) === -1) {
continue;
}
direction = m.direction || sdp.direction || 'sendrecv';
if (direction === 'sendonly' || direction === 'inactive') {
hold = true;
}
// If at least one of the streams is active don't emit 'hold'.
else {
hold = false;
break;
}
}
var e = {originator:'remote', type:'offer', sdp:request.body};
var offer = new RTCSessionDescription({type:'offer', sdp:e.sdp});
this.emit('sdp', e);
this.connection.setRemoteDescription(offer)
.then(function() {
if (self.remoteHold === true && hold === false) {
self.remoteHold = false;
onunhold.call(self, 'remote');
} else if (self.remoteHold === false && hold === true) {
self.remoteHold = true;
onhold.call(self, 'remote');
}
createLocalDescription.call(self, 'answer',
// success
function(sdp) {
var extraHeaders = ['Contact: ' + self.contact];
handleSessionTimersInIncomingRequest.call(self, request, extraHeaders);
request.reply(200, null, extraHeaders, sdp);
// If callback is given execute it.
if (typeof data.callback === 'function') {
data.callback();
}
},
// failure
function() {
request.reply(500);
}
);
})
.catch(function(error) {
request.reply(488);
self.emit('peerconnection:setremotedescriptionfailed', error);
});
}
/**
* In dialog Refer Reception
*/
function receiveRefer(request) {
debug('receiveRefer()');
var notifier,
self = this;
function accept(initCallback, options) {
var session, replaces;
options = options || {};
initCallback = (typeof initCallback === 'function')? initCallback : null;
if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) {
return false;
}
session = new RTCSession(this.ua);
session.on('progress', function(e) {
notifier.notify(e.response.status_code, e.response.reason_phrase);
});
session.on('accepted', function(e) {
notifier.notify(e.response.status_code, e.response.reason_phrase);
});
session.on('failed', function(e) {
if (e.message) {
notifier.notify(e.message.status_code, e.message.reason_phrase);
} else {
notifier.notify(487, e.cause);
}
});
// Consider the Replaces header present in the Refer-To URI
if (request.refer_to.uri.hasHeader('replaces')) {
replaces = decodeURIComponent(request.refer_to.uri.getHeader('replaces'));
options.extraHeaders = options.extraHeaders || [];
options.extraHeaders.push('Replaces: '+ replaces);
}
session.connect(request.refer_to.uri.toAor(), options, initCallback);
}
function reject() {
notifier.notify(603);
}
if (typeof request.refer_to === undefined) {
debug('no Refer-To header field present in REFER');
request.reply(400);
return;
}
if (request.refer_to.uri.scheme !== JsSIP_C.SIP) {
debug('Refer-To header field points to a non-SIP URI scheme');
request.reply(416);
return;
}
// reply before the transaction timer expires
request.reply(202);
notifier = new RTCSession_ReferNotifier(this, request.cseq);
// Emit 'refer'.
this.emit('refer', {
request: request,
accept: function(initCallback, options) { accept.call(self, initCallback, options); },
reject: function() { reject.call(self); }
});
}
/**
* In dialog Notify Reception
*/
function receiveNotify(request) {
debug('receiveNotify()');
if (typeof request.event === undefined) {
request.reply(400);
}
switch (request.event.event) {
case 'refer': {
var id = request.event.params.id;
var referSubscriber = this.referSubscribers[id];
if (!referSubscriber) {
request.reply(481, 'Subscription does not exist');
return;
}
referSubscriber.receiveNotify(request);
request.reply(200);
break;
}
default: {
request.reply(489);
}
}
}
/**
* INVITE with Replaces Reception
*/
function receiveReplaces(request) {
debug('receiveReplaces()');
var self = this;
function accept(initCallback) {
var session;
if (this.status !== C.STATUS_WAITING_FOR_ACK && this.status !== C.STATUS_CONFIRMED) {
return false;
}
session = new RTCSession(this.ua);
// terminate the current session when the new one is confirmed
session.on('confirmed', function() {
self.terminate();
});
session.init_incoming(request, initCallback);
}
function reject() {
debug('Replaced INVITE rejected by the user');
request.reply(486);
}
// Emit 'replace'.
this.emit('replaces', {
request: request,
accept: function(initCallback) { accept.call(self, initCallback); },
reject: function() { reject.call(self); }
});
}
/**
* Initial Request Sender
*/
function sendInitialRequest(mediaConstraints, rtcOfferConstraints, mediaStream) {
var self = this;
var request_sender = new RequestSender(self, this.ua);
this.receiveResponse = function(response) {
receiveInviteResponse.call(self, response);
};
// If a local MediaStream is given use it.
if (mediaStream) {
// Wait a bit so the app can set events such as 'peerconnection' and 'connecting'.
setTimeout(function() {
userMediaSucceeded(mediaStream);
});
// If at least audio or video is requested prompt getUserMedia.
} else if (mediaConstraints.audio || mediaConstraints.video) {
this.localMediaStreamLocallyGenerated = true;
navigator.mediaDevices.getUserMedia(mediaConstraints)
.then(userMediaSucceeded)
.catch(function(error)
{
userMediaFailed(error);
self.emit('getusermediafailed', error);
});
// Otherwise don't prompt getUserMedia.
} else {
userMediaSucceeded(null);
}
// User media succeeded
function userMediaSucceeded(stream) {
if (self.status === C.STATUS_TERMINATED) { return; }
self.localMediaStream = stream;
if (stream) {
self.connection.addStream(stream);
}
// Notify the app with the RTCPeerConnection so it can do stuff on it
// before generating the offer.
self.emit('peerconnection', {
peerconnection: self.connection
});
connecting.call(self, self.request);
createLocalDescription.call(self, 'offer', rtcSucceeded, rtcFailed, rtcOfferConstraints);
}
// User media failed
function userMediaFailed() {
if (self.status === C.STATUS_TERMINATED) { return; }
failed.call(self, 'local', null, JsSIP_C.causes.USER_DENIED_MEDIA_ACCESS);
}
function rtcSucceeded(desc) {
if (self.isCanceled || self.status === C.STATUS_TERMINATED) { return; }
self.request.body = desc;
self.status = C.STATUS_INVITE_SENT;
// Emit 'sending' so the app can mangle the body before the request
// is sent.
self.emit('sending', {
request: self.request
});
request_sender.send();
}
function rtcFailed() {
if (self.status === C.STATUS_TERMINATED) { return; }
failed.call(self, 'system', null, JsSIP_C.causes.WEBRTC_ERROR);
}
}
/**
* Reception of Response for Initial INVITE
*/
function receiveInviteResponse(response) {
debug('receiveInviteResponse()');
var cause, dialog, e,
self = this;
// Handle 2XX retransmissions and responses from forked requests
if (this.dialog && (response.status_code >=200 && response.status_code <=299)) {
/*
* If it is a retransmission from the endpoint that established
* the dialog, send an ACK
*/
if (this.dialog.id.call_id === response.call_id &&
this.dialog.id.local_tag === response.from_tag &&
this.dialog.id.remote_tag === response.to_tag) {
sendRequest.call(this, JsSIP_C.ACK);
return;
}
// If not, send an ACK and terminate
else {
dialog = new Dialog(this, response, 'UAC');
if (dialog.error !== undefined) {
debug(dialog.error);
return;
}
dialog.sendRequest({
owner: {status: C.STATUS_TERMINATED},
onRequestTimeout: function(){},
onTransportError: function(){},
onDialogError: function(){},
receiveResponse: function(){}
}, JsSIP_C.ACK);
dialog.sendRequest({
owner: {status: C.STATUS_TERMINATED},
onRequestTimeout: function(){},
onTransportError: function(){},
onDialogError: function(){},
receiveResponse: function(){}
}, JsSIP_C.BYE);
return;
}
}
// Proceed to cancellation if the user requested.
if(this.isCanceled) {
// Remove the flag. We are done.
this.isCanceled = false;
if(response.status_code >= 100 && response.status_code < 200) {
this.request.cancel(this.cancelReason);
} else if(response.status_code >= 200 && response.status_code < 299) {
acceptAndTerminate.call(this, response);
}
return;
}
if(this.status !== C.STATUS_INVITE_SENT && this.status !== C.STATUS_1XX_RECEIVED) {
return;
}
switch(true) {
case /^100$/.test(response.status_code):
this.status = C.STATUS_1XX_RECEIVED;
break;
case /^1[0-9]{2}$/.test(response.status_code):
// Do nothing with 1xx responses without To tag.
if (!response.to_tag) {
debug('1xx response received without to tag');
break;
}
// Create Early Dialog if 1XX comes with contact
if (response.hasHeader('contact')) {
// An error on dialog creation will fire 'failed' event
if(! createDialog.call(this, response, 'UAC', true)) {
break;
}
}
this.status = C.STATUS_1XX_RECEIVED;
progress.call(this, 'remote', response);
if (!response.body) {
break;
}
e = {originator:'remote', type:'pranswer', sdp:response.body};
this.emit('sdp', e);
var pranswer = new RTCSessionDescription({type:'pranswer', sdp:e.sdp});
this.connection.setRemoteDescription(pranswer)
.catch(function(error) {
self.emit('peerconnection:setremotedescriptionfailed', error);
});
break;
case /^2[0-9]{2}$/.test(response.status_code):
this.status = C.STATUS_CONFIRMED;
if(!response.body) {
acceptAndTerminate.call(this, response, 400, JsSIP_C.causes.MISSING_SDP);
failed.call(this, 'remote', response, JsSIP_C.causes.BAD_MEDIA_DESCRIPTION);
break;
}
// An error on dialog creation will fire 'failed' event
if (! createDialog.call(this, response, 'UAC')) {
break;
}
e = {originator:'remote', type:'answer', sdp:response.body};
this.emit('sdp', e);
var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp});
this.connection.setRemoteDescription(answer)
.then(function() {
// Handle Session Timers.
handleSessionTimersInIncomingResponse.call(self, response);
accepted.call(self, 'remote', response);
sendRequest.call(self, JsSIP_C.ACK);
confirmed.call(self, 'local', null);
})
.catch(function(error) {
acceptAndTerminate.call(self, response, 488, 'Not Acceptable Here');
failed.call(self, 'remote', response, JsSIP_C.causes.BAD_MEDIA_DESCRIPTION);
self.emit('peerconnection:setremotedescriptionfailed', error);
});
break;
default:
cause = Utils.sipErrorCause(response.status_code);
failed.call(this, 'remote', response, cause);
}
}
/**
* Send Re-INVITE
*/
function sendReinvite(options) {
debug('sendReinvite()');
options = options || {};
var
self = this,
extraHeaders = options.extraHeaders || [],
eventHandlers = options.eventHandlers || {},
rtcOfferConstraints = options.rtcOfferConstraints || this.rtcOfferConstraints || null,
succeeded = false;
extraHeaders.push('Contact: ' + this.contact);
extraHeaders.push('Content-Type: application/sdp');
// Session Timers.
if (this.sessionTimers.running) {
extraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + (this.sessionTimers.refresher ? 'uac' : 'uas'));
}
createLocalDescription.call(this, 'offer',
// success
function(sdp) {
sdp = mangleOffer.call(self, sdp);
var request = new RTCSession_Request(self, JsSIP_C.INVITE);
request.send({
extraHeaders: extraHeaders,
body: sdp,
eventHandlers: {
onSuccessResponse: function(response) {
onSucceeded(response);
succeeded = true;
},
onErrorResponse: function(response) {
onFailed(response);
},
onTransportError: function() {
self.onTransportError(); // Do nothing because session ends.
},
onRequestTimeout: function() {
self.onRequestTimeout(); // Do nothing because session ends.
},
onDialogError: function() {
self.onDialogError(); // Do nothing because session ends.
}
}
});
},
// failure
function() {
onFailed();
},
// RTC constraints.
rtcOfferConstraints
);
function onSucceeded(response) {
if (self.status === C.STATUS_TERMINATED) {
return;
}
sendRequest.call(self, JsSIP_C.ACK);
// If it is a 2XX retransmission exit now.
if (succeeded) { return; }
// Handle Session Timers.
handleSessionTimersInIncomingResponse.call(self, response);
// Must have SDP answer.
if(! response.body) {
onFailed();
return;
} else if (response.getHeader('Content-Type') !== 'application/sdp') {
onFailed();
return;
}
var e = {originator:'remote', type:'answer', sdp:response.body};
var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp});
self.emit('sdp', e);
self.connection.setRemoteDescription(answer)
.then(function() {
if (eventHandlers.succeeded) {
eventHandlers.succeeded(response);
}
})
.catch(function(error) {
onFailed();
self.emit('peerconnection:setremotedescriptionfailed', error);
});
}
function onFailed(response) {
if (eventHandlers.failed) {
eventHandlers.failed(response);
}
}
}
/**
* Send UPDATE
*/
function sendUpdate(options) {
debug('sendUpdate()');
options = options || {};
var
self = this,
extraHeaders = options.extraHeaders || [],
eventHandlers = options.eventHandlers || {},
rtcOfferConstraints = options.rtcOfferConstraints || this.rtcOfferConstraints || null,
sdpOffer = options.sdpOffer || false,
succeeded = false;
extraHeaders.push('Contact: ' + this.contact);
// Session Timers.
if (this.sessionTimers.running) {
extraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + (this.sessionTimers.refresher ? 'uac' : 'uas'));
}
if (sdpOffer) {
extraHeaders.push('Content-Type: application/sdp');
createLocalDescription.call(this, 'offer',
// success
function(sdp) {
sdp = mangleOffer.call(self, sdp);
var request = new RTCSession_Request(self, JsSIP_C.UPDATE);
request.send({
extraHeaders: extraHeaders,
body: sdp,
eventHandlers: {
onSuccessResponse: function(response) {
onSucceeded(response);
succeeded = true;
},
onErrorResponse: function(response) {
onFailed(response);
},
onTransportError: function() {
self.onTransportError(); // Do nothing because session ends.
},
onRequestTimeout: function() {
self.onRequestTimeout(); // Do nothing because session ends.
},
onDialogError: function() {
self.onDialogError(); // Do nothing because session ends.
}
}
});
},
// failure
function() {
onFailed();
},
// RTC constraints.
rtcOfferConstraints
);
}
// No SDP.
else {
var request = new RTCSession_Request(self, JsSIP_C.UPDATE);
request.send({
extraHeaders: extraHeaders,
eventHandlers: {
onSuccessResponse: function(response) {
onSucceeded(response);
},
onErrorResponse: function(response) {
onFailed(response);
},
onTransportError: function() {
self.onTransportError(); // Do nothing because session ends.
},
onRequestTimeout: function() {
self.onRequestTimeout(); // Do nothing because session ends.
},
onDialogError: function() {
self.onDialogError(); // Do nothing because session ends.
}
}
});
}
function onSucceeded(response) {
if (self.status === C.STATUS_TERMINATED) {
return;
}
// If it is a 2XX retransmission exit now.
if (succeeded) { return; }
// Handle Session Timers.
handleSessionTimersInIncomingResponse.call(self, response);
// Must have SDP answer.
if (sdpOffer) {
if(! response.body) {
onFailed();
return;
} else if (response.getHeader('Content-Type') !== 'application/sdp') {
onFailed();
return;
}
var e = {originator:'remote', type:'answer', sdp:response.body};
var answer = new RTCSessionDescription({type:'answer', sdp:e.sdp});
self.emit('sdp', e);
self.connection.setRemoteDescription(answer)
.then(function() {
if (eventHandlers.succeeded) {
eventHandlers.succeeded(response);
}
})
.catch(function(error) {
onFailed();
self.emit('peerconnection:setremotedescriptionfailed', error);
});
}
// No SDP answer.
else {
if (eventHandlers.succeeded) {
eventHandlers.succeeded(response);
}
}
}
function onFailed(response) {
if (eventHandlers.failed) { eventHandlers.failed(response); }
}
}
function acceptAndTerminate(response, status_code, reason_phrase) {
debug('acceptAndTerminate()');
var extraHeaders = [];
if (status_code) {
reason_phrase = reason_phrase || JsSIP_C.REASON_PHRASE[status_code] || '';
extraHeaders.push('Reason: SIP ;cause=' + status_code + '; text="' + reason_phrase + '"');
}
// An error on dialog creation will fire 'failed' event
if (this.dialog || createDialog.call(this, response, 'UAC')) {
sendRequest.call(this, JsSIP_C.ACK);
sendRequest.call(this, JsSIP_C.BYE, {
extraHeaders: extraHeaders
});
}
// Update session status.
this.status = C.STATUS_TERMINATED;
}
/**
* Send a generic in-dialog Request
*/
function sendRequest(method, options) {
debug('sendRequest()');
var request = new RTCSession_Request(this, method);
request.send(options);
}
/**
* Correctly set the SDP direction attributes if the call is on local hold
*/
function mangleOffer(sdp) {
var idx, length, m;
if (! this.localHold && ! this.remoteHold) {
return sdp;
}
sdp = sdp_transform.parse(sdp);
// Local hold.
if (this.localHold && ! this.remoteHold) {
debug('mangleOffer() | me on hold, mangling offer');
length = sdp.media.length;
for (idx=0; idx<length; idx++) {
m = sdp.media[idx];
if (holdMediaTypes.indexOf(m.type) === -1) {
continue;
}
if (!m.direction) {
m.direction = 'sendonly';
} else if (m.direction === 'sendrecv') {
m.direction = 'sendonly';
} else if (m.direction === 'recvonly') {
m.direction = 'inactive';
}
}
}
// Local and remote hold.
else if (this.localHold && this.remoteHold) {
debug('mangleOffer() | both on hold, mangling offer');
length = sdp.media.length;
for (idx=0; idx<length; idx++) {
m = sdp.media[idx];
if (holdMediaTypes.indexOf(m.type) === -1) {
continue;
}
m.direction = 'inactive';
}
}
// Remote hold.
else if (this.remoteHold) {
debug('mangleOffer() | remote on hold, mangling offer');
length = sdp.media.length;
for (idx=0; idx<length; idx++) {
m = sdp.media[idx];
if (holdMediaTypes.indexOf(m.type) === -1) {
continue;
}
if (!m.direction) {
m.direction = 'recvonly';
} else if (m.direction === 'sendrecv') {
m.direction = 'recvonly';
} else if (m.direction === 'recvonly') {
m.direction = 'inactive';
}
}
}
return sdp_transform.write(sdp);
}
function setLocalMediaStatus() {
var enableAudio = true,
enableVideo = true;
if (this.localHold || this.remoteHold) {
enableAudio = false;
enableVideo = false;
}
if (this.audioMuted) {
enableAudio = false;
}
if (this.videoMuted) {
enableVideo = false;
}
toogleMuteAudio.call(this, !enableAudio);
toogleMuteVideo.call(this, !enableVideo);
}
/**
* Handle SessionTimers for an incoming INVITE or UPDATE.
* @param {IncomingRequest} request
* @param {Array} responseExtraHeaders Extra headers for the 200 response.
*/
function handleSessionTimersInIncomingRequest(request, responseExtraHeaders) {
if (! this.sessionTimers.enabled) { return; }
var session_expires_refresher;
if (request.session_expires && request.session_expires >= JsSIP_C.MIN_SESSION_EXPIRES) {
this.sessionTimers.currentExpires = request.session_expires;
session_expires_refresher = request.session_expires_refresher || 'uas';
}
else {
this.sessionTimers.currentExpires = this.sessionTimers.defaultExpires;
session_expires_refresher = 'uas';
}
responseExtraHeaders.push('Session-Expires: ' + this.sessionTimers.currentExpires + ';refresher=' + session_expires_refresher);
this.sessionTimers.refresher = (session_expires_refresher === 'uas');
runSessionTimer.call(this);
}
/**
* Handle SessionTimers for an incoming response to INVITE or UPDATE.
* @param {IncomingResponse} response
*/
function handleSessionTimersInIncomingResponse(response) {
if (! this.sessionTimers.enabled) { return; }
var session_expires_refresher;
if (response.session_expires && response.session_expires >= JsSIP_C.MIN_SESSION_EXPIRES) {
this.sessionTimers.currentExpires = response.session_expires;
session_expires_refresher = response.session_expires_refresher || 'uac';
}
else {
this.sessionTimers.currentExpires = this.sessionTimers.defaultExpires;
session_expires_refresher = 'uac';
}
this.sessionTimers.refresher = (session_expires_refresher === 'uac');
runSessionTimer.call(this);
}
function runSessionTimer() {
var self = this;
var expires = this.sessionTimers.currentExpires;
this.sessionTimers.running = true;
clearTimeout(this.sessionTimers.timer);
// I'm the refresher.
if (this.sessionTimers.refresher) {
this.sessionTimers.timer = setTimeout(function() {
if (self.status === C.STATUS_TERMINATED) { return; }
debug('runSessionTimer() | sending session refresh request');
sendUpdate.call(self, {
eventHandlers: {
succeeded: function(response) {
handleSessionTimersInIncomingResponse.call(self, response);
}
}
});
}, expires * 500); // Half the given interval (as the RFC states).
}
// I'm not the refresher.
else {
this.sessionTimers.timer = setTimeout(function() {
if (self.status === C.STATUS_TERMINATED) { return; }
debugerror('runSessionTimer() | timer expired, terminating the session');
self.terminate({
cause: JsSIP_C.causes.REQUEST_TIMEOUT,
status_code: 408,
reason_phrase: 'Session Timer Expired'
});
}, expires * 1100);
}
}
function toogleMuteAudio(mute) {
var streamIdx, trackIdx, streamsLength, tracksLength, tracks,
localStreams = this.connection.getLocalStreams();
streamsLength = localStreams.length;
for (streamIdx = 0; streamIdx < streamsLength; streamIdx++) {
tracks = localStreams[streamIdx].getAudioTracks();
tracksLength = tracks.length;
for (trackIdx = 0; trackIdx < tracksLength; trackIdx++) {
tracks[trackIdx].enabled = !mute;
}
}
}
function toogleMuteVideo(mute) {
var streamIdx, trackIdx, streamsLength, tracksLength, tracks,
localStreams = this.connection.getLocalStreams();
streamsLength = localStreams.length;
for (streamIdx = 0; streamIdx < streamsLength; streamIdx++) {
tracks = localStreams[streamIdx].getVideoTracks();
tracksLength = tracks.length;
for (trackIdx = 0; trackIdx < tracksLength; trackIdx++) {
tracks[trackIdx].enabled = !mute;
}
}
}
function newRTCSession(originator, request) {
debug('newRTCSession');
this.ua.newRTCSession({
originator: originator,
session: this,
request: request
});
}
function connecting(request) {
debug('session connecting');
this.emit('connecting', {
request: request
});
}
function progress(originator, response) {
debug('session progress');
this.emit('progress', {
originator: originator,
response: response || null
});
}
function accepted(originator, message) {
debug('session accepted');
this.start_time = new Date();
this.emit('accepted', {
originator: originator,
response: message || null
});
}
function confirmed(originator, ack) {
debug('session confirmed');
this.is_confirmed = true;
this.emit('confirmed', {
originator: originator,
ack: ack || null
});
}
function ended(originator, message, cause) {
debug('session ended');
this.end_time = new Date();
this.close();
this.emit('ended', {
originator: originator,
message: message || null,
cause: cause
});
}
function failed(originator, message, cause) {
debug('session failed');
this.close();
this.emit('failed', {
originator: originator,
message: message || null,
cause: cause
});
}
function onhold(originator) {
debug('session onhold');
setLocalMediaStatus.call(this);
this.emit('hold', {
originator: originator
});
}
function onunhold(originator) {
debug('session onunhold');
setLocalMediaStatus.call(this);
this.emit('unhold', {
originator: originator
});
}
function onmute(options) {
debug('session onmute');
setLocalMediaStatus.call(this);
this.emit('muted', {
audio: options.audio,
video: options.video
});
}
function onunmute(options) {
debug('session onunmute');
setLocalMediaStatus.call(this);
this.emit('unmuted', {
audio: options.audio,
video: options.video
});
}
},{"./Constants":1,"./Dialog":2,"./Exceptions":5,"./RTCSession/DTMF":12,"./RTCSession/ReferNotifier":13,"./RTCSession/ReferSubscriber":14,"./RTCSession/Request":15,"./RequestSender":17,"./SIPMessage":18,"./Timers":20,"./Transactions":21,"./Utils":25,"debug":34,"events":28,"sdp-transform":37,"util":32}],12:[function(require,module,exports){
module.exports = DTMF;
var C = {
MIN_DURATION: 70,
MAX_DURATION: 6000,
DEFAULT_DURATION: 100,
MIN_INTER_TONE_GAP: 50,
DEFAULT_INTER_TONE_GAP: 500
};
/**
* Expose C object.
*/
DTMF.C = C;
/**
* Dependencies.
*/
var util = require('util');
var events = require('events');
var debug = require('debug')('JsSIP:RTCSession:DTMF');
var debugerror = require('debug')('JsSIP:ERROR:RTCSession:DTMF');
debugerror.log = console.warn.bind(console);
var JsSIP_C = require('../Constants');
var Exceptions = require('../Exceptions');
var RTCSession = require('../RTCSession');
function DTMF(session) {
this.owner = session;
this.direction = null;
this.tone = null;
this.duration = null;
events.EventEmitter.call(this);
}
util.inherits(DTMF, events.EventEmitter);
DTMF.prototype.send = function(tone, options) {
var extraHeaders, body;
if (tone === undefined) {
throw new TypeError('Not enough arguments');
}
this.direction = 'outgoing';
// Check RTCSession Status
if (this.owner.status !== RTCSession.C.STATUS_CONFIRMED &&
this.owner.status !== RTCSession.C.STATUS_WAITING_FOR_ACK) {
throw new Exceptions.InvalidStateError(this.owner.status);
}
// Get DTMF options
options = options || {};
extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : [];
this.eventHandlers = options.eventHandlers || {};
// Check tone type
if (typeof tone === 'string' ) {
tone = tone.toUpperCase();
} else if (typeof tone === 'number') {
tone = tone.toString();
} else {
throw new TypeError('Invalid tone: '+ tone);
}
// Check tone value
if (!tone.match(/^[0-9A-DR#*]$/)) {
throw new TypeError('Invalid tone: '+ tone);
} else {
this.tone = tone;
}
// Duration is checked/corrected in RTCSession
this.duration = options.duration;
extraHeaders.push('Content-Type: application/dtmf-relay');
body = 'Signal=' + this.tone + '\r\n';
body += 'Duration=' + this.duration;
this.owner.newDTMF({
originator: 'local',
dtmf: this,
request: this.request
});
this.owner.dialog.sendRequest(this, JsSIP_C.INFO, {
extraHeaders: extraHeaders,
body: body
});
};
DTMF.prototype.receiveResponse = function(response) {
switch(true) {
case /^1[0-9]{2}$/.test(response.status_code):
// Ignore provisional responses.
break;
case /^2[0-9]{2}$/.test(response.status_code):
this.emit('succeeded', {
originator: 'remote',
response: response
});
break;
default:
if (this.eventHandlers.onFailed) {
this.eventHandlers.onFailed();
}
this.emit('failed', {
originator: 'remote',
response: response
});
break;
}
};
DTMF.prototype.onRequestTimeout = function() {
debugerror('onRequestTimeout');
this.owner.onRequestTimeout();
};
DTMF.prototype.onTransportError = function() {
debugerror('onTransportError');
this.owner.onTransportError();
};
DTMF.prototype.onDialogError = function() {
debugerror('onDialogError');
this.owner.onDialogError();
};
DTMF.prototype.init_incoming = function(request) {
var body,
reg_tone = /^(Signal\s*?=\s*?)([0-9A-D#*]{1})(\s)?.*/,
reg_duration = /^(Duration\s?=\s?)([0-9]{1,4})(\s)?.*/;
this.direction = 'incoming';
this.request = request;
request.reply(200);
if (request.body) {
body = request.body.split('\n');
if (body.length >= 1) {
if (reg_tone.test(body[0])) {
this.tone = body[0].replace(reg_tone,'$2');
}
}
if (body.length >=2) {
if (reg_duration.test(body[1])) {
this.duration = parseInt(body[1].replace(reg_duration,'$2'), 10);
}
}
}
if (!this.duration) {
this.duration = C.DEFAULT_DURATION;
}
if (!this.tone) {
debug('invalid INFO DTMF received, discarded');
} else {
this.owner.newDTMF({
originator: 'remote',
dtmf: this,
request: request
});
}
};
},{"../Constants":1,"../Exceptions":5,"../RTCSession":11,"debug":34,"events":28,"util":32}],13:[function(require,module,exports){
module.exports = ReferNotifier;
var C = {
event_type: 'refer',
body_type: 'message/sipfrag;version=2.0',
expires: 300
};
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:RTCSession:ReferNotifier');
var JsSIP_C = require('../Constants');
var RTCSession_Request = require('./Request');
function ReferNotifier(session, id, expires) {
this.session = session;
this.id = id;
this.expires = expires || C.expires;
this.active = true;
// The creation of a Notifier results in an immediate NOTIFY
this.notify(100);
}
ReferNotifier.prototype.notify = function(code, reason) {
debug('notify()');
var state,
self = this;
if (this.active === false) {
return;
}
reason = reason || JsSIP_C.REASON_PHRASE[code] || '';
if (code >= 200) {
state = 'terminated;reason=noresource';
} else {
state = 'active;expires='+ this.expires;
}
// put this in a try/catch block
var request = new RTCSession_Request(this.session, JsSIP_C.NOTIFY);
request.send({
extraHeaders: [
'Event: '+ C.event_type +';id='+ self.id,
'Subscription-State: '+ state,
'Content-Type: '+ C.body_type
],
body: 'SIP/2.0 ' + code + ' ' + reason,
eventHandlers: {
// if a negative response is received, subscription is canceled
onErrorResponse: function() { self.active = false; }
}
});
};
},{"../Constants":1,"./Request":15,"debug":34}],14:[function(require,module,exports){
module.exports = ReferSubscriber;
var C = {
expires: 120
};
/**
* Dependencies.
*/
var util = require('util');
var events = require('events');
var debug = require('debug')('JsSIP:RTCSession:ReferSubscriber');
var JsSIP_C = require('../Constants');
var Grammar = require('../Grammar');
var RTCSession_Request = require('./Request');
function ReferSubscriber(session) {
this.session = session;
this.timer = null;
// Instance of REFER OutgoingRequest
this.outgoingRequest = null;
events.EventEmitter.call(this);
}
util.inherits(ReferSubscriber, events.EventEmitter);
ReferSubscriber.prototype.sendRefer = function(target, options) {
debug('sendRefer()');
var extraHeaders, eventHandlers, referTo,
replaces = null,
self = this;
// Get REFER options
options = options || {};
extraHeaders = options.extraHeaders ? options.extraHeaders.slice() : [];
eventHandlers = options.eventHandlers || {};
// Set event handlers
for (var event in eventHandlers) {
this.on(event, eventHandlers[event]);
}
// Replaces URI header field
if (options.replaces) {
replaces = options.replaces.request.call_id;
replaces += ';to-tag='+ options.replaces.to_tag;
replaces += ';from-tag='+ options.replaces.from_tag;
replaces = encodeURIComponent(replaces);
}
// Refer-To header field
referTo = 'Refer-To: <'+ target + (replaces?'?Replaces='+ replaces:'') +'>';
extraHeaders.push(referTo);
var request = new RTCSession_Request(this.session, JsSIP_C.REFER);
this.timer = setTimeout(function() {
removeSubscriber.call(self);
}, C.expires * 1000);
request.send({
extraHeaders: extraHeaders,
eventHandlers: {
onSuccessResponse: function(response) {
self.emit('requestSucceeded', {
response: response
});
},
onErrorResponse: function(response) {
self.emit('requestFailed', {
response: response,
cause: JsSIP_C.causes.REJECTED
});
},
onTransportError: function() {
removeSubscriber.call(self);
self.emit('requestFailed', {
response: null,
cause: JsSIP_C.causes.CONNECTION_ERROR
});
},
onRequestTimeout: function() {
removeSubscriber.call(self);
self.emit('requestFailed', {
response: null,
cause: JsSIP_C.causes.REQUEST_TIMEOUT
});
},
onDialogError: function() {
removeSubscriber.call(self);
self.emit('requestFailed', {
response: null,
cause: JsSIP_C.causes.DIALOG_ERROR
});
}
}
});
this.outgoingRequest = request.outgoingRequest;
};
ReferSubscriber.prototype.receiveNotify = function(request) {
debug('receiveNotify()');
var status_line;
if (!request.body) {
return;
}
status_line = Grammar.parse(request.body, 'Status_Line');
if(status_line === -1) {
debug('receiveNotify() | error parsing NOTIFY body: "' + request.body + '"');
return;
}
switch(true) {
case /^100$/.test(status_line.status_code):
this.emit('trying', {
request: request,
status_line: status_line
});
break;
case /^1[0-9]{2}$/.test(status_line.status_code):
this.emit('progress', {
request: request,
status_line: status_line
});
break;
case /^2[0-9]{2}$/.test(status_line.status_code):
removeSubscriber.call(this);
this.emit('accepted', {
request: request,
status_line: status_line
});
break;
default:
removeSubscriber.call(this);
this.emit('failed', {
request: request,
status_line: status_line
});
break;
}
};
// remove refer subscriber from the session
function removeSubscriber() {
console.log('removeSubscriber()');
clearTimeout(this.timer);
this.session.referSubscriber = null;
}
},{"../Constants":1,"../Grammar":6,"./Request":15,"debug":34,"events":28,"util":32}],15:[function(require,module,exports){
module.exports = Request;
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:RTCSession:Request');
var debugerror = require('debug')('JsSIP:ERROR:RTCSession:Request');
debugerror.log = console.warn.bind(console);
var JsSIP_C = require('../Constants');
var Exceptions = require('../Exceptions');
var RTCSession = require('../RTCSession');
function Request(session, method) {
debug('new | %s', method);
this.session = session;
this.method = method;
// Instance of OutgoingRequest
this.outgoingRequest = null;
// Check RTCSession Status
if (this.session.status !== RTCSession.C.STATUS_1XX_RECEIVED &&
this.session.status !== RTCSession.C.STATUS_WAITING_FOR_ANSWER &&
this.session.status !== RTCSession.C.STATUS_WAITING_FOR_ACK &&
this.session.status !== RTCSession.C.STATUS_CONFIRMED &&
this.session.status !== RTCSession.C.STATUS_TERMINATED) {
throw new Exceptions.InvalidStateError(this.session.status);
}
/*
* Allow sending BYE in TERMINATED status since the RTCSession
* could had been terminated before the ACK had arrived.
* RFC3261 Section 15, Paragraph 2
*/
else if (this.session.status === RTCSession.C.STATUS_TERMINATED && method !== JsSIP_C.BYE) {
throw new Exceptions.InvalidStateError(this.session.status);
}
}
Request.prototype.send = function(options) {
options = options || {};
var
extraHeaders = options.extraHeaders && options.extraHeaders.slice() || [],
body = options.body || null;
this.eventHandlers = options.eventHandlers || {};
this.outgoingRequest = this.session.dialog.sendRequest(this, this.method, {
extraHeaders: extraHeaders,
body: body
});
};
Request.prototype.receiveResponse = function(response) {
switch(true) {
case /^1[0-9]{2}$/.test(response.status_code):
debug('onProgressResponse');
if (this.eventHandlers.onProgressResponse) { this.eventHandlers.onProgressResponse(response); }
break;
case /^2[0-9]{2}$/.test(response.status_code):
debug('onSuccessResponse');
if (this.eventHandlers.onSuccessResponse) { this.eventHandlers.onSuccessResponse(response); }
break;
default:
debug('onErrorResponse');
if (this.eventHandlers.onErrorResponse) { this.eventHandlers.onErrorResponse(response); }
break;
}
};
Request.prototype.onRequestTimeout = function() {
debugerror('onRequestTimeout');
if (this.eventHandlers.onRequestTimeout) { this.eventHandlers.onRequestTimeout(); }
};
Request.prototype.onTransportError = function() {
debugerror('onTransportError');
if (this.eventHandlers.onTransportError) { this.eventHandlers.onTransportError(); }
};
Request.prototype.onDialogError = function() {
debugerror('onDialogError');
if (this.eventHandlers.onDialogError) { this.eventHandlers.onDialogError(); }
};
},{"../Constants":1,"../Exceptions":5,"../RTCSession":11,"debug":34}],16:[function(require,module,exports){
module.exports = Registrator;
/**
* Dependecies
*/
var debug = require('debug')('JsSIP:Registrator');
var Utils = require('./Utils');
var JsSIP_C = require('./Constants');
var SIPMessage = require('./SIPMessage');
var RequestSender = require('./RequestSender');
function Registrator(ua, transport) {
var reg_id=1; //Force reg_id to 1.
this.ua = ua;
this.transport = transport;
this.registrar = ua.configuration.registrar_server;
this.expires = ua.configuration.register_expires;
// Call-ID and CSeq values RFC3261 10.2
this.call_id = Utils.createRandomToken(22);
this.cseq = 0;
// this.to_uri
this.to_uri = ua.configuration.uri;
this.registrationTimer = null;
// Set status
this.registered = false;
// Contact header
this.contact = this.ua.contact.toString();
// sip.ice media feature tag (RFC 5768)
this.contact += ';+sip.ice';
// Custom headers for REGISTER and un-REGISTER.
this.extraHeaders = [];
// Custom Contact header params for REGISTER and un-REGISTER.
this.extraContactParams = '';
if(reg_id) {
this.contact += ';reg-id='+ reg_id;
this.contact += ';+sip.instance="<urn:uuid:'+ this.ua.configuration.instance_id+'>"';
}
}
Registrator.prototype = {
setExtraHeaders: function(extraHeaders) {
if (! Array.isArray(extraHeaders)) {
extraHeaders = [];
}
this.extraHeaders = extraHeaders.slice();
},
setExtraContactParams: function(extraContactParams) {
if (! (extraContactParams instanceof Object)) {
extraContactParams = {};
}
// Reset it.
this.extraContactParams = '';
for(var param_key in extraContactParams) {
var param_value = extraContactParams[param_key];
this.extraContactParams += (';' + param_key);
if (param_value) {
this.extraContactParams += ('=' + param_value);
}
}
},
register: function() {
var request_sender, cause, extraHeaders,
self = this;
extraHeaders = this.extraHeaders.slice();
extraHeaders.push('Contact: ' + this.contact + ';expires=' + this.expires + this.extraContactParams);
extraHeaders.push('Expires: '+ this.expires);
this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, {
'to_uri': this.to_uri,
'call_id': this.call_id,
'cseq': (this.cseq += 1)
}, extraHeaders);
request_sender = new RequestSender(this, this.ua);
this.receiveResponse = function(response) {
var contact, expires,
contacts = response.getHeaders('contact').length;
// Discard responses to older REGISTER/un-REGISTER requests.
if(response.cseq !== this.cseq) {
return;
}
// Clear registration timer
if (this.registrationTimer !== null) {
clearTimeout(this.registrationTimer);
this.registrationTimer = null;
}
switch(true) {
case /^1[0-9]{2}$/.test(response.status_code):
// Ignore provisional responses.
break;
case /^2[0-9]{2}$/.test(response.status_code):
if(response.hasHeader('expires')) {
expires = response.getHeader('expires');
}
// Search the Contact pointing to us and update the expires value accordingly.
if (!contacts) {
debug('no Contact header in response to REGISTER, response ignored');
break;
}
while(contacts--) {
contact = response.parseHeader('contact', contacts);
if(contact.uri.user === this.ua.contact.uri.user) {
expires = contact.getParam('expires');
break;
} else {
contact = null;
}
}
if (!contact) {
debug('no Contact header pointing to us, response ignored');
break;
}
if(!expires) {
expires = this.expires;
}
// Re-Register before the expiration interval has elapsed.
// For that, decrease the expires value. ie: 3 seconds
this.registrationTimer = setTimeout(function() {
self.registrationTimer = null;
self.register();
}, (expires * 1000) - 3000);
//Save gruu values
if (contact.hasParam('temp-gruu')) {
this.ua.contact.temp_gruu = contact.getParam('temp-gruu').replace(/"/g,'');
}
if (contact.hasParam('pub-gruu')) {
this.ua.contact.pub_gruu = contact.getParam('pub-gruu').replace(/"/g,'');
}
if (! this.registered) {
this.registered = true;
this.ua.registered({
response: response
});
}
break;
// Interval too brief RFC3261 10.2.8
case /^423$/.test(response.status_code):
if(response.hasHeader('min-expires')) {
// Increase our registration interval to the suggested minimum
this.expires = response.getHeader('min-expires');
// Attempt the registration again immediately
this.register();
} else { //This response MUST contain a Min-Expires header field
debug('423 response received for REGISTER without Min-Expires');
this.registrationFailure(response, JsSIP_C.causes.SIP_FAILURE_CODE);
}
break;
default:
cause = Utils.sipErrorCause(response.status_code);
this.registrationFailure(response, cause);
}
};
this.onRequestTimeout = function() {
this.registrationFailure(null, JsSIP_C.causes.REQUEST_TIMEOUT);
};
this.onTransportError = function() {
this.registrationFailure(null, JsSIP_C.causes.CONNECTION_ERROR);
};
request_sender.send();
},
unregister: function(options) {
var extraHeaders;
if(!this.registered) {
debug('already unregistered');
return;
}
options = options || {};
this.registered = false;
// Clear the registration timer.
if (this.registrationTimer !== null) {
clearTimeout(this.registrationTimer);
this.registrationTimer = null;
}
extraHeaders = this.extraHeaders.slice();
if(options.all) {
extraHeaders.push('Contact: *' + this.extraContactParams);
extraHeaders.push('Expires: 0');
this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, {
'to_uri': this.to_uri,
'call_id': this.call_id,
'cseq': (this.cseq += 1)
}, extraHeaders);
} else {
extraHeaders.push('Contact: '+ this.contact + ';expires=0' + this.extraContactParams);
extraHeaders.push('Expires: 0');
this.request = new SIPMessage.OutgoingRequest(JsSIP_C.REGISTER, this.registrar, this.ua, {
'to_uri': this.to_uri,
'call_id': this.call_id,
'cseq': (this.cseq += 1)
}, extraHeaders);
}
var request_sender = new RequestSender(this, this.ua);
this.receiveResponse = function(response) {
var cause;
switch(true) {
case /^1[0-9]{2}$/.test(response.status_code):
// Ignore provisional responses.
break;
case /^2[0-9]{2}$/.test(response.status_code):
this.unregistered(response);
break;
default:
cause = Utils.sipErrorCause(response.status_code);
this.unregistered(response, cause);
}
};
this.onRequestTimeout = function() {
this.unregistered(null, JsSIP_C.causes.REQUEST_TIMEOUT);
};
this.onTransportError = function() {
this.unregistered(null, JsSIP_C.causes.CONNECTION_ERROR);
};
request_sender.send();
},
registrationFailure: function(response, cause) {
this.ua.registrationFailed({
response: response || null,
cause: cause
});
if (this.registered) {
this.registered = false;
this.ua.unregistered({
response: response || null,
cause: cause
});
}
},
unregistered: function(response, cause) {
this.registered = false;
this.ua.unregistered({
response: response || null,
cause: cause || null
});
},
onTransportClosed: function() {
if (this.registrationTimer !== null) {
clearTimeout(this.registrationTimer);
this.registrationTimer = null;
}
if(this.registered) {
this.registered = false;
this.ua.unregistered({});
}
},
close: function() {
if (this.registered) {
this.unregister();
}
}
};
},{"./Constants":1,"./RequestSender":17,"./SIPMessage":18,"./Utils":25,"debug":34}],17:[function(require,module,exports){
module.exports = RequestSender;
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:RequestSender');
var JsSIP_C = require('./Constants');
var UA = require('./UA');
var DigestAuthentication = require('./DigestAuthentication');
var Transactions = require('./Transactions');
function RequestSender(applicant, ua) {
this.ua = ua;
this.applicant = applicant;
this.method = applicant.request.method;
this.request = applicant.request;
this.auth = null;
this.challenged = false;
this.staled = false;
// If ua is in closing process or even closed just allow sending Bye and ACK
if (ua.status === UA.C.STATUS_USER_CLOSED && (this.method !== JsSIP_C.BYE || this.method !== JsSIP_C.ACK)) {
this.onTransportError();
}
}
/**
* Create the client transaction and send the message.
*/
RequestSender.prototype = {
send: function() {
switch(this.method) {
case 'INVITE':
this.clientTransaction = new Transactions.InviteClientTransaction(this, this.request, this.ua.transport);
break;
case 'ACK':
this.clientTransaction = new Transactions.AckClientTransaction(this, this.request, this.ua.transport);
break;
default:
this.clientTransaction = new Transactions.NonInviteClientTransaction(this, this.request, this.ua.transport);
}
this.clientTransaction.send();
},
/**
* Callback fired when receiving a request timeout error from the client transaction.
* To be re-defined by the applicant.
*/
onRequestTimeout: function() {
this.applicant.onRequestTimeout();
},
/**
* Callback fired when receiving a transport error from the client transaction.
* To be re-defined by the applicant.
*/
onTransportError: function() {
this.applicant.onTransportError();
},
/**
* Called from client transaction when receiving a correct response to the request.
* Authenticate request if needed or pass the response back to the applicant.
*/
receiveResponse: function(response) {
var
cseq, challenge, authorization_header_name,
status_code = response.status_code;
/*
* Authentication
* Authenticate once. _challenged_ flag used to avoid infinite authentications.
*/
if ((status_code === 401 || status_code === 407) &&
(this.ua.configuration.password !== null || this.ua.configuration.ha1 !== null)) {
// Get and parse the appropriate WWW-Authenticate or Proxy-Authenticate header.
if (response.status_code === 401) {
challenge = response.parseHeader('www-authenticate');
authorization_header_name = 'authorization';
} else {
challenge = response.parseHeader('proxy-authenticate');
authorization_header_name = 'proxy-authorization';
}
// Verify it seems a valid challenge.
if (!challenge) {
debug(response.status_code + ' with wrong or missing challenge, cannot authenticate');
this.applicant.receiveResponse(response);
return;
}
if (!this.challenged || (!this.staled && challenge.stale === true)) {
if (!this.auth) {
this.auth = new DigestAuthentication({
username : this.ua.configuration.authorization_user,
password : this.ua.configuration.password,
realm : this.ua.configuration.realm,
ha1 : this.ua.configuration.ha1
});
}
// Verify that the challenge is really valid.
if (!this.auth.authenticate(this.request, challenge)) {
this.applicant.receiveResponse(response);
return;
}
this.challenged = true;
// Update ha1 and realm in the UA.
this.ua.set('realm', this.auth.get('realm'));
this.ua.set('ha1', this.auth.get('ha1'));
if (challenge.stale) {
this.staled = true;
}
if (response.method === JsSIP_C.REGISTER) {
cseq = this.applicant.cseq += 1;
} else if (this.request.dialog) {
cseq = this.request.dialog.local_seqnum += 1;
} else {
cseq = this.request.cseq + 1;
}
this.request = this.applicant.request = this.request.clone();
this.request.cseq = cseq;
this.request.setHeader('cseq', cseq +' '+ this.method);
this.request.setHeader(authorization_header_name, this.auth.toString());
this.send();
} else {
this.applicant.receiveResponse(response);
}
} else {
this.applicant.receiveResponse(response);
}
}
};
},{"./Constants":1,"./DigestAuthentication":4,"./Transactions":21,"./UA":23,"debug":34}],18:[function(require,module,exports){
module.exports = {
OutgoingRequest: OutgoingRequest,
IncomingRequest: IncomingRequest,
IncomingResponse: IncomingResponse
};
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:SIPMessage');
var sdp_transform = require('sdp-transform');
var JsSIP_C = require('./Constants');
var Utils = require('./Utils');
var NameAddrHeader = require('./NameAddrHeader');
var Grammar = require('./Grammar');
/**
* -param {String} method request method
* -param {String} ruri request uri
* -param {UA} ua
* -param {Object} params parameters that will have priority over ua.configuration parameters:
* <br>
* - cseq, call_id, from_tag, from_uri, from_display_name, to_uri, to_tag, route_set
* -param {Object} [headers] extra headers
* -param {String} [body]
*/
function OutgoingRequest(method, ruri, ua, params, extraHeaders, body) {
var
to,
from,
call_id,
cseq;
params = params || {};
// Mandatory parameters check
if(!method || !ruri || !ua) {
return null;
}
this.ua = ua;
this.headers = {};
this.method = method;
this.ruri = ruri;
this.body = body;
this.extraHeaders = extraHeaders && extraHeaders.slice() || [];
// Fill the Common SIP Request Headers
// Route
if (params.route_set) {
this.setHeader('route', params.route_set);
} else if (ua.configuration.use_preloaded_route) {
this.setHeader('route', '<' + ua.transport.sip_uri + ';lr>');
}
// Via
// Empty Via header. Will be filled by the client transaction.
this.setHeader('via', '');
// Max-Forwards
this.setHeader('max-forwards', JsSIP_C.MAX_FORWARDS);
// To
to = (params.to_display_name || params.to_display_name === 0) ? '"' + params.to_display_name + '" ' : '';
to += '<' + (params.to_uri || ruri) + '>';
to += params.to_tag ? ';tag=' + params.to_tag : '';
this.to = new NameAddrHeader.parse(to);
this.setHeader('to', to);
// From
if (params.from_display_name || params.from_display_name === 0) {
from = '"' + params.from_display_name + '" ';
} else if (ua.configuration.display_name) {
from = '"' + ua.configuration.display_name + '" ';
} else {
from = '';
}
from += '<' + (params.from_uri || ua.configuration.uri) + '>;tag=';
from += params.from_tag || Utils.newTag();
this.from = new NameAddrHeader.parse(from);
this.setHeader('from', from);
// Call-ID
call_id = params.call_id || (ua.configuration.jssip_id + Utils.createRandomToken(15));
this.call_id = call_id;
this.setHeader('call-id', call_id);
// CSeq
cseq = params.cseq || Math.floor(Math.random() * 10000);
this.cseq = cseq;
this.setHeader('cseq', cseq + ' ' + method);
}
OutgoingRequest.prototype = {
/**
* Replace the the given header by the given value.
* -param {String} name header name
* -param {String | Array} value header value
*/
setHeader: function(name, value) {
var regexp, idx;
// Remove the header from extraHeaders if present.
regexp = new RegExp('^\\s*'+ name +'\\s*:','i');
for (idx=0; idx<this.extraHeaders.length; idx++) {
if (regexp.test(this.extraHeaders[idx])) {
this.extraHeaders.splice(idx, 1);
}
}
this.headers[Utils.headerize(name)] = (Array.isArray(value)) ? value : [value];
},
/**
* Get the value of the given header name at the given position.
* -param {String} name header name
* -returns {String|undefined} Returns the specified header, null if header doesn't exist.
*/
getHeader: function(name) {
var regexp, idx,
length = this.extraHeaders.length,
header = this.headers[Utils.headerize(name)];
if(header) {
if(header[0]) {
return header[0];
}
} else {
regexp = new RegExp('^\\s*'+ name +'\\s*:','i');
for (idx=0; idx<length; idx++) {
header = this.extraHeaders[idx];
if (regexp.test(header)) {
return header.substring(header.indexOf(':')+1).trim();
}
}
}
return;
},
/**
* Get the header/s of the given name.
* -param {String} name header name
* -returns {Array} Array with all the headers of the specified name.
*/
getHeaders: function(name) {
var idx, length, regexp,
header = this.headers[Utils.headerize(name)],
result = [];
if (header) {
length = header.length;
for (idx = 0; idx < length; idx++) {
result.push(header[idx]);
}
return result;
} else {
length = this.extraHeaders.length;
regexp = new RegExp('^\\s*'+ name +'\\s*:','i');
for (idx=0; idx<length; idx++) {
header = this.extraHeaders[idx];
if (regexp.test(header)) {
result.push(header.substring(header.indexOf(':')+1).trim());
}
}
return result;
}
},
/**
* Verify the existence of the given header.
* -param {String} name header name
* -returns {boolean} true if header with given name exists, false otherwise
*/
hasHeader: function(name) {
var regexp, idx,
length = this.extraHeaders.length;
if (this.headers[Utils.headerize(name)]) {
return true;
} else {
regexp = new RegExp('^\\s*'+ name +'\\s*:','i');
for (idx=0; idx<length; idx++) {
if (regexp.test(this.extraHeaders[idx])) {
return true;
}
}
}
return false;
},
/**
* Parse the current body as a SDP and store the resulting object
* into this.sdp.
* -param {Boolean} force: Parse even if this.sdp already exists.
*
* Returns this.sdp.
*/
parseSDP: function(force) {
if (!force && this.sdp) {
return this.sdp;
} else {
this.sdp = sdp_transform.parse(this.body || '');
return this.sdp;
}
},
toString: function() {
var msg = '', header, length, idx,
supported = [];
msg += this.method + ' ' + this.ruri + ' SIP/2.0\r\n';
for (header in this.headers) {
length = this.headers[header].length;
for (idx = 0; idx < length; idx++) {
msg += header + ': ' + this.headers[header][idx] + '\r\n';
}
}
length = this.extraHeaders.length;
for (idx = 0; idx < length; idx++) {
msg += this.extraHeaders[idx].trim() +'\r\n';
}
// Supported
switch (this.method) {
case JsSIP_C.REGISTER:
supported.push('path', 'gruu');
break;
case JsSIP_C.INVITE:
if (this.ua.configuration.session_timers) {
supported.push('timer');
}
if (this.ua.contact.pub_gruu || this.ua.contact.temp_gruu) {
supported.push('gruu');
}
supported.push('ice','replaces');
break;
case JsSIP_C.UPDATE:
if (this.ua.configuration.session_timers) {
supported.push('timer');
}
supported.push('ice');
break;
}
supported.push('outbound');
// Allow
msg += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n';
msg += 'Supported: ' + supported +'\r\n';
msg += 'User-Agent: ' + JsSIP_C.USER_AGENT +'\r\n';
if (this.body) {
length = Utils.str_utf8_length(this.body);
msg += 'Content-Length: ' + length + '\r\n\r\n';
msg += this.body;
} else {
msg += 'Content-Length: 0\r\n\r\n';
}
return msg;
},
clone: function() {
var request = new OutgoingRequest(this.method, this.ruri, this.ua);
Object.keys(this.headers).forEach(function(name) {
request.headers[name] = this.headers[name].slice();
}, this);
request.body = this.body;
request.extraHeaders = this.extraHeaders && this.extraHeaders.slice() || [];
request.to = this.to;
request.from = this.from;
request.call_id = this.call_id;
request.cseq = this.cseq;
return request;
}
};
function IncomingMessage(){
this.data = null;
this.headers = null;
this.method = null;
this.via = null;
this.via_branch = null;
this.call_id = null;
this.cseq = null;
this.from = null;
this.from_tag = null;
this.to = null;
this.to_tag = null;
this.body = null;
this.sdp = null;
}
IncomingMessage.prototype = {
/**
* Insert a header of the given name and value into the last position of the
* header array.
*/
addHeader: function(name, value) {
var header = { raw: value };
name = Utils.headerize(name);
if(this.headers[name]) {
this.headers[name].push(header);
} else {
this.headers[name] = [header];
}
},
/**
* Get the value of the given header name at the given position.
*/
getHeader: function(name) {
var header = this.headers[Utils.headerize(name)];
if(header) {
if(header[0]) {
return header[0].raw;
}
} else {
return;
}
},
/**
* Get the header/s of the given name.
*/
getHeaders: function(name) {
var idx, length,
header = this.headers[Utils.headerize(name)],
result = [];
if(!header) {
return [];
}
length = header.length;
for (idx = 0; idx < length; idx++) {
result.push(header[idx].raw);
}
return result;
},
/**
* Verify the existence of the given header.
*/
hasHeader: function(name) {
return(this.headers[Utils.headerize(name)]) ? true : false;
},
/**
* Parse the given header on the given index.
* -param {String} name header name
* -param {Number} [idx=0] header index
* -returns {Object|undefined} Parsed header object, undefined if the header is not present or in case of a parsing error.
*/
parseHeader: function(name, idx) {
var header, value, parsed;
name = Utils.headerize(name);
idx = idx || 0;
if(!this.headers[name]) {
debug('header "' + name + '" not present');
return;
} else if(idx >= this.headers[name].length) {
debug('not so many "' + name + '" headers present');
return;
}
header = this.headers[name][idx];
value = header.raw;
if(header.parsed) {
return header.parsed;
}
//substitute '-' by '_' for grammar rule matching.
parsed = Grammar.parse(value, name.replace(/-/g, '_'));
if(parsed === -1) {
this.headers[name].splice(idx, 1); //delete from headers
debug('error parsing "' + name + '" header field with value "' + value + '"');
return;
} else {
header.parsed = parsed;
return parsed;
}
},
/**
* Message Header attribute selector. Alias of parseHeader.
* -param {String} name header name
* -param {Number} [idx=0] header index
* -returns {Object|undefined} Parsed header object, undefined if the header is not present or in case of a parsing error.
*
* -example
* message.s('via',3).port
*/
s: function(name, idx) {
return this.parseHeader(name, idx);
},
/**
* Replace the value of the given header by the value.
* -param {String} name header name
* -param {String} value header value
*/
setHeader: function(name, value) {
var header = { raw: value };
this.headers[Utils.headerize(name)] = [header];
},
/**
* Parse the current body as a SDP and store the resulting object
* into this.sdp.
* -param {Boolean} force: Parse even if this.sdp already exists.
*
* Returns this.sdp.
*/
parseSDP: function(force) {
if (!force && this.sdp) {
return this.sdp;
} else {
this.sdp = sdp_transform.parse(this.body || '');
return this.sdp;
}
},
toString: function() {
return this.data;
}
};
function IncomingRequest(ua) {
this.ua = ua;
this.headers = {};
this.ruri = null;
this.transport = null;
this.server_transaction = null;
}
IncomingRequest.prototype = new IncomingMessage();
/**
* Stateful reply.
* -param {Number} code status code
* -param {String} reason reason phrase
* -param {Object} headers extra headers
* -param {String} body body
* -param {Function} [onSuccess] onSuccess callback
* -param {Function} [onFailure] onFailure callback
*/
IncomingRequest.prototype.reply = function(code, reason, extraHeaders, body, onSuccess, onFailure) {
var rr, vias, length, idx, response,
supported = [],
to = this.getHeader('To'),
r = 0,
v = 0;
code = code || null;
reason = reason || null;
// Validate code and reason values
if (!code || (code < 100 || code > 699)) {
throw new TypeError('Invalid status_code: '+ code);
} else if (reason && typeof reason !== 'string' && !(reason instanceof String)) {
throw new TypeError('Invalid reason_phrase: '+ reason);
}
reason = reason || JsSIP_C.REASON_PHRASE[code] || '';
extraHeaders = extraHeaders && extraHeaders.slice() || [];
response = 'SIP/2.0 ' + code + ' ' + reason + '\r\n';
if(this.method === JsSIP_C.INVITE && code > 100 && code <= 200) {
rr = this.getHeaders('record-route');
length = rr.length;
for(r; r < length; r++) {
response += 'Record-Route: ' + rr[r] + '\r\n';
}
}
vias = this.getHeaders('via');
length = vias.length;
for(v; v < length; v++) {
response += 'Via: ' + vias[v] + '\r\n';
}
if(!this.to_tag && code > 100) {
to += ';tag=' + Utils.newTag();
} else if(this.to_tag && !this.s('to').hasParam('tag')) {
to += ';tag=' + this.to_tag;
}
response += 'To: ' + to + '\r\n';
response += 'From: ' + this.getHeader('From') + '\r\n';
response += 'Call-ID: ' + this.call_id + '\r\n';
response += 'CSeq: ' + this.cseq + ' ' + this.method + '\r\n';
length = extraHeaders.length;
for (idx = 0; idx < length; idx++) {
response += extraHeaders[idx].trim() +'\r\n';
}
// Supported
switch (this.method) {
case JsSIP_C.INVITE:
if (this.ua.configuration.session_timers) {
supported.push('timer');
}
if (this.ua.contact.pub_gruu || this.ua.contact.temp_gruu) {
supported.push('gruu');
}
supported.push('ice','replaces');
break;
case JsSIP_C.UPDATE:
if (this.ua.configuration.session_timers) {
supported.push('timer');
}
if (body) {
supported.push('ice');
}
supported.push('replaces');
}
supported.push('outbound');
// Allow and Accept
if (this.method === JsSIP_C.OPTIONS) {
response += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n';
response += 'Accept: '+ JsSIP_C.ACCEPTED_BODY_TYPES +'\r\n';
} else if (code === 405) {
response += 'Allow: '+ JsSIP_C.ALLOWED_METHODS +'\r\n';
} else if (code === 415 ) {
response += 'Accept: '+ JsSIP_C.ACCEPTED_BODY_TYPES +'\r\n';
}
response += 'Supported: ' + supported +'\r\n';
if(body) {
length = Utils.str_utf8_length(body);
response += 'Content-Type: application/sdp\r\n';
response += 'Content-Length: ' + length + '\r\n\r\n';
response += body;
} else {
response += 'Content-Length: ' + 0 + '\r\n\r\n';
}
this.server_transaction.receiveResponse(code, response, onSuccess, onFailure);
};
/**
* Stateless reply.
* -param {Number} code status code
* -param {String} reason reason phrase
*/
IncomingRequest.prototype.reply_sl = function(code, reason) {
var to, response,
v = 0,
vias = this.getHeaders('via'),
length = vias.length;
code = code || null;
reason = reason || null;
// Validate code and reason values
if (!code || (code < 100 || code > 699)) {
throw new TypeError('Invalid status_code: '+ code);
} else if (reason && typeof reason !== 'string' && !(reason instanceof String)) {
throw new TypeError('Invalid reason_phrase: '+ reason);
}
reason = reason || JsSIP_C.REASON_PHRASE[code] || '';
response = 'SIP/2.0 ' + code + ' ' + reason + '\r\n';
for(v; v < length; v++) {
response += 'Via: ' + vias[v] + '\r\n';
}
to = this.getHeader('To');
if(!this.to_tag && code > 100) {
to += ';tag=' + Utils.newTag();
} else if(this.to_tag && !this.s('to').hasParam('tag')) {
to += ';tag=' + this.to_tag;
}
response += 'To: ' + to + '\r\n';
response += 'From: ' + this.getHeader('From') + '\r\n';
response += 'Call-ID: ' + this.call_id + '\r\n';
response += 'CSeq: ' + this.cseq + ' ' + this.method + '\r\n';
response += 'Content-Length: ' + 0 + '\r\n\r\n';
this.transport.send(response);
};
function IncomingResponse() {
this.headers = {};
this.status_code = null;
this.reason_phrase = null;
}
IncomingResponse.prototype = new IncomingMessage();
},{"./Constants":1,"./Grammar":6,"./NameAddrHeader":9,"./Utils":25,"debug":34,"sdp-transform":37}],19:[function(require,module,exports){
module.exports = Socket;
/**
* Interface documentation: http://jssip.net/documentation/$last_version/api/socket/
*
* interface Socket {
* attribute String via_transport
* attribute String url
* attribute String sip_uri
*
* method connect();
* method disconnect();
* method send(data);
*
* attribute EventHandler onconnect
* attribute EventHandler ondisconnect
* attribute EventHandler ondata
* }
*
*/
/**
* Dependencies.
*/
var Utils = require('./Utils');
var Grammar = require('./Grammar');
var debugerror = require('debug')('JsSIP:ERROR:Socket');
debugerror.log = console.warn.bind(console);
function Socket() {}
Socket.isSocket = function(socket) {
// Ignore if an array is given
if (Array.isArray(socket)) {
return false;
}
if (typeof socket === 'undefined') {
debugerror('undefined JsSIP.Socket instance');
return false;
}
// Check Properties
try {
if (!Utils.isString(socket.url)) {
debugerror('missing or invalid JsSIP.Socket url property');
throw new Error();
}
if (!Utils.isString(socket.via_transport)) {
debugerror('missing or invalid JsSIP.Socket via_transport property');
throw new Error();
}
if (Grammar.parse(socket.sip_uri, 'SIP_URI') === -1) {
debugerror('missing or invalid JsSIP.Socket sip_uri property');
throw new Error();
}
} catch(e) {
return false;
}
// Check Methods
try {
['connect', 'disconnect', 'send'].forEach(function(method) {
if (!Utils.isFunction(socket[method])) {
debugerror('missing or invalid JsSIP.Socket method: ' + method);
throw new Error();
}
});
} catch(e) {
return false;
}
return true;
};
},{"./Grammar":6,"./Utils":25,"debug":34}],20:[function(require,module,exports){
var T1 = 500,
T2 = 4000,
T4 = 5000;
var Timers = {
T1: T1,
T2: T2,
T4: T4,
TIMER_B: 64 * T1,
TIMER_D: 0 * T1,
TIMER_F: 64 * T1,
TIMER_H: 64 * T1,
TIMER_I: 0 * T1,
TIMER_J: 0 * T1,
TIMER_K: 0 * T4,
TIMER_L: 64 * T1,
TIMER_M: 64 * T1,
PROVISIONAL_RESPONSE_INTERVAL: 60000 // See RFC 3261 Section 13.3.1.1
};
module.exports = Timers;
},{}],21:[function(require,module,exports){
module.exports = {
C: null,
NonInviteClientTransaction: NonInviteClientTransaction,
InviteClientTransaction: InviteClientTransaction,
AckClientTransaction: AckClientTransaction,
NonInviteServerTransaction: NonInviteServerTransaction,
InviteServerTransaction: InviteServerTransaction,
checkTransaction: checkTransaction
};
var C = {
// Transaction states
STATUS_TRYING: 1,
STATUS_PROCEEDING: 2,
STATUS_CALLING: 3,
STATUS_ACCEPTED: 4,
STATUS_COMPLETED: 5,
STATUS_TERMINATED: 6,
STATUS_CONFIRMED: 7,
// Transaction types
NON_INVITE_CLIENT: 'nict',
NON_INVITE_SERVER: 'nist',
INVITE_CLIENT: 'ict',
INVITE_SERVER: 'ist'
};
/**
* Expose C object.
*/
module.exports.C = C;
/**
* Dependencies.
*/
var util = require('util');
var events = require('events');
var debugnict = require('debug')('JsSIP:NonInviteClientTransaction');
var debugict = require('debug')('JsSIP:InviteClientTransaction');
var debugact = require('debug')('JsSIP:AckClientTransaction');
var debugnist = require('debug')('JsSIP:NonInviteServerTransaction');
var debugist = require('debug')('JsSIP:InviteServerTransaction');
var JsSIP_C = require('./Constants');
var Timers = require('./Timers');
function NonInviteClientTransaction(request_sender, request, transport) {
var via;
this.type = C.NON_INVITE_CLIENT;
this.transport = transport;
this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000);
this.request_sender = request_sender;
this.request = request;
via = 'SIP/2.0/' + transport.via_transport;
via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id;
this.request.setHeader('via', via);
this.request_sender.ua.newTransaction(this);
events.EventEmitter.call(this);
}
util.inherits(NonInviteClientTransaction, events.EventEmitter);
NonInviteClientTransaction.prototype.stateChanged = function(state) {
this.state = state;
this.emit('stateChanged');
};
NonInviteClientTransaction.prototype.send = function() {
var tr = this;
this.stateChanged(C.STATUS_TRYING);
this.F = setTimeout(function() {tr.timer_F();}, Timers.TIMER_F);
if(!this.transport.send(this.request)) {
this.onTransportError();
}
};
NonInviteClientTransaction.prototype.onTransportError = function() {
debugnict('transport error occurred, deleting transaction ' + this.id);
clearTimeout(this.F);
clearTimeout(this.K);
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
this.request_sender.onTransportError();
};
NonInviteClientTransaction.prototype.timer_F = function() {
debugnict('Timer F expired for transaction ' + this.id);
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
this.request_sender.onRequestTimeout();
};
NonInviteClientTransaction.prototype.timer_K = function() {
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
};
NonInviteClientTransaction.prototype.receiveResponse = function(response) {
var
tr = this,
status_code = response.status_code;
if(status_code < 200) {
switch(this.state) {
case C.STATUS_TRYING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_PROCEEDING);
this.request_sender.receiveResponse(response);
break;
}
} else {
switch(this.state) {
case C.STATUS_TRYING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_COMPLETED);
clearTimeout(this.F);
if(status_code === 408) {
this.request_sender.onRequestTimeout();
} else {
this.request_sender.receiveResponse(response);
}
this.K = setTimeout(function() {tr.timer_K();}, Timers.TIMER_K);
break;
case C.STATUS_COMPLETED:
break;
}
}
};
function InviteClientTransaction(request_sender, request, transport) {
var via,
tr = this;
this.type = C.INVITE_CLIENT;
this.transport = transport;
this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000);
this.request_sender = request_sender;
this.request = request;
via = 'SIP/2.0/' + transport.via_transport;
via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id;
this.request.setHeader('via', via);
this.request_sender.ua.newTransaction(this);
// TODO: Adding here the cancel() method is a hack that must be fixed.
// Add the cancel property to the request.
//Will be called from the request instance, not the transaction itself.
this.request.cancel = function(reason) {
tr.cancel_request(tr, reason);
};
events.EventEmitter.call(this);
}
util.inherits(InviteClientTransaction, events.EventEmitter);
InviteClientTransaction.prototype.stateChanged = function(state) {
this.state = state;
this.emit('stateChanged');
};
InviteClientTransaction.prototype.send = function() {
var tr = this;
this.stateChanged(C.STATUS_CALLING);
this.B = setTimeout(function() {
tr.timer_B();
}, Timers.TIMER_B);
if(!this.transport.send(this.request)) {
this.onTransportError();
}
};
InviteClientTransaction.prototype.onTransportError = function() {
clearTimeout(this.B);
clearTimeout(this.D);
clearTimeout(this.M);
if (this.state !== C.STATUS_ACCEPTED) {
debugict('transport error occurred, deleting transaction ' + this.id);
this.request_sender.onTransportError();
}
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
};
// RFC 6026 7.2
InviteClientTransaction.prototype.timer_M = function() {
debugict('Timer M expired for transaction ' + this.id);
if(this.state === C.STATUS_ACCEPTED) {
clearTimeout(this.B);
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
}
};
// RFC 3261 17.1.1
InviteClientTransaction.prototype.timer_B = function() {
debugict('Timer B expired for transaction ' + this.id);
if(this.state === C.STATUS_CALLING) {
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
this.request_sender.onRequestTimeout();
}
};
InviteClientTransaction.prototype.timer_D = function() {
debugict('Timer D expired for transaction ' + this.id);
clearTimeout(this.B);
this.stateChanged(C.STATUS_TERMINATED);
this.request_sender.ua.destroyTransaction(this);
};
InviteClientTransaction.prototype.sendACK = function(response) {
var tr = this;
this.ack = 'ACK ' + this.request.ruri + ' SIP/2.0\r\n';
this.ack += 'Via: ' + this.request.headers.Via.toString() + '\r\n';
if(this.request.headers.Route) {
this.ack += 'Route: ' + this.request.headers.Route.toString() + '\r\n';
}
this.ack += 'To: ' + response.getHeader('to') + '\r\n';
this.ack += 'From: ' + this.request.headers.From.toString() + '\r\n';
this.ack += 'Call-ID: ' + this.request.headers['Call-ID'].toString() + '\r\n';
this.ack += 'CSeq: ' + this.request.headers.CSeq.toString().split(' ')[0];
this.ack += ' ACK\r\n';
this.ack += 'Content-Length: 0\r\n\r\n';
this.D = setTimeout(function() {tr.timer_D();}, Timers.TIMER_D);
this.transport.send(this.ack);
};
InviteClientTransaction.prototype.cancel_request = function(tr, reason) {
var request = tr.request;
this.cancel = JsSIP_C.CANCEL + ' ' + request.ruri + ' SIP/2.0\r\n';
this.cancel += 'Via: ' + request.headers.Via.toString() + '\r\n';
if(this.request.headers.Route) {
this.cancel += 'Route: ' + request.headers.Route.toString() + '\r\n';
}
this.cancel += 'To: ' + request.headers.To.toString() + '\r\n';
this.cancel += 'From: ' + request.headers.From.toString() + '\r\n';
this.cancel += 'Call-ID: ' + request.headers['Call-ID'].toString() + '\r\n';
this.cancel += 'CSeq: ' + request.headers.CSeq.toString().split(' ')[0] +
' CANCEL\r\n';
if(reason) {
this.cancel += 'Reason: ' + reason + '\r\n';
}
this.cancel += 'Content-Length: 0\r\n\r\n';
// Send only if a provisional response (>100) has been received.
if(this.state === C.STATUS_PROCEEDING) {
this.transport.send(this.cancel);
}
};
InviteClientTransaction.prototype.receiveResponse = function(response) {
var
tr = this,
status_code = response.status_code;
if(status_code >= 100 && status_code <= 199) {
switch(this.state) {
case C.STATUS_CALLING:
this.stateChanged(C.STATUS_PROCEEDING);
this.request_sender.receiveResponse(response);
break;
case C.STATUS_PROCEEDING:
this.request_sender.receiveResponse(response);
break;
}
} else if(status_code >= 200 && status_code <= 299) {
switch(this.state) {
case C.STATUS_CALLING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_ACCEPTED);
this.M = setTimeout(function() {
tr.timer_M();
}, Timers.TIMER_M);
this.request_sender.receiveResponse(response);
break;
case C.STATUS_ACCEPTED:
this.request_sender.receiveResponse(response);
break;
}
} else if(status_code >= 300 && status_code <= 699) {
switch(this.state) {
case C.STATUS_CALLING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_COMPLETED);
this.sendACK(response);
this.request_sender.receiveResponse(response);
break;
case C.STATUS_COMPLETED:
this.sendACK(response);
break;
}
}
};
function AckClientTransaction(request_sender, request, transport) {
var via;
this.transport = transport;
this.id = 'z9hG4bK' + Math.floor(Math.random() * 10000000);
this.request_sender = request_sender;
this.request = request;
via = 'SIP/2.0/' + transport.via_transport;
via += ' ' + request_sender.ua.configuration.via_host + ';branch=' + this.id;
this.request.setHeader('via', via);
events.EventEmitter.call(this);
}
util.inherits(AckClientTransaction, events.EventEmitter);
AckClientTransaction.prototype.send = function() {
if(!this.transport.send(this.request)) {
this.onTransportError();
}
};
AckClientTransaction.prototype.onTransportError = function() {
debugact('transport error occurred for transaction ' + this.id);
this.request_sender.onTransportError();
};
function NonInviteServerTransaction(request, ua) {
this.type = C.NON_INVITE_SERVER;
this.id = request.via_branch;
this.request = request;
this.transport = request.transport;
this.ua = ua;
this.last_response = '';
request.server_transaction = this;
this.state = C.STATUS_TRYING;
ua.newTransaction(this);
events.EventEmitter.call(this);
}
util.inherits(NonInviteServerTransaction, events.EventEmitter);
NonInviteServerTransaction.prototype.stateChanged = function(state) {
this.state = state;
this.emit('stateChanged');
};
NonInviteServerTransaction.prototype.timer_J = function() {
debugnist('Timer J expired for transaction ' + this.id);
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
};
NonInviteServerTransaction.prototype.onTransportError = function() {
if (!this.transportError) {
this.transportError = true;
debugnist('transport error occurred, deleting transaction ' + this.id);
clearTimeout(this.J);
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
}
};
NonInviteServerTransaction.prototype.receiveResponse = function(status_code, response, onSuccess, onFailure) {
var tr = this;
if(status_code === 100) {
/* RFC 4320 4.1
* 'A SIP element MUST NOT
* send any provisional response with a
* Status-Code other than 100 to a non-INVITE request.'
*/
switch(this.state) {
case C.STATUS_TRYING:
this.stateChanged(C.STATUS_PROCEEDING);
if(!this.transport.send(response)) {
this.onTransportError();
}
break;
case C.STATUS_PROCEEDING:
this.last_response = response;
if(!this.transport.send(response)) {
this.onTransportError();
if (onFailure) {
onFailure();
}
} else if (onSuccess) {
onSuccess();
}
break;
}
} else if(status_code >= 200 && status_code <= 699) {
switch(this.state) {
case C.STATUS_TRYING:
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_COMPLETED);
this.last_response = response;
this.J = setTimeout(function() {
tr.timer_J();
}, Timers.TIMER_J);
if(!this.transport.send(response)) {
this.onTransportError();
if (onFailure) {
onFailure();
}
} else if (onSuccess) {
onSuccess();
}
break;
case C.STATUS_COMPLETED:
break;
}
}
};
function InviteServerTransaction(request, ua) {
this.type = C.INVITE_SERVER;
this.id = request.via_branch;
this.request = request;
this.transport = request.transport;
this.ua = ua;
this.last_response = '';
request.server_transaction = this;
this.state = C.STATUS_PROCEEDING;
ua.newTransaction(this);
this.resendProvisionalTimer = null;
request.reply(100);
events.EventEmitter.call(this);
}
util.inherits(InviteServerTransaction, events.EventEmitter);
InviteServerTransaction.prototype.stateChanged = function(state) {
this.state = state;
this.emit('stateChanged');
};
InviteServerTransaction.prototype.timer_H = function() {
debugist('Timer H expired for transaction ' + this.id);
if(this.state === C.STATUS_COMPLETED) {
debugist('ACK not received, dialog will be terminated');
}
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
};
InviteServerTransaction.prototype.timer_I = function() {
this.stateChanged(C.STATUS_TERMINATED);
};
// RFC 6026 7.1
InviteServerTransaction.prototype.timer_L = function() {
debugist('Timer L expired for transaction ' + this.id);
if(this.state === C.STATUS_ACCEPTED) {
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
}
};
InviteServerTransaction.prototype.onTransportError = function() {
if (!this.transportError) {
this.transportError = true;
debugist('transport error occurred, deleting transaction ' + this.id);
if (this.resendProvisionalTimer !== null) {
clearInterval(this.resendProvisionalTimer);
this.resendProvisionalTimer = null;
}
clearTimeout(this.L);
clearTimeout(this.H);
clearTimeout(this.I);
this.stateChanged(C.STATUS_TERMINATED);
this.ua.destroyTransaction(this);
}
};
InviteServerTransaction.prototype.resend_provisional = function() {
if(!this.transport.send(this.last_response)) {
this.onTransportError();
}
};
// INVITE Server Transaction RFC 3261 17.2.1
InviteServerTransaction.prototype.receiveResponse = function(status_code, response, onSuccess, onFailure) {
var tr = this;
if(status_code >= 100 && status_code <= 199) {
switch(this.state) {
case C.STATUS_PROCEEDING:
if(!this.transport.send(response)) {
this.onTransportError();
}
this.last_response = response;
break;
}
}
if(status_code > 100 && status_code <= 199 && this.state === C.STATUS_PROCEEDING) {
// Trigger the resendProvisionalTimer only for the first non 100 provisional response.
if(this.resendProvisionalTimer === null) {
this.resendProvisionalTimer = setInterval(function() {
tr.resend_provisional();}, Timers.PROVISIONAL_RESPONSE_INTERVAL);
}
} else if(status_code >= 200 && status_code <= 299) {
switch(this.state) {
case C.STATUS_PROCEEDING:
this.stateChanged(C.STATUS_ACCEPTED);
this.last_response = response;
this.L = setTimeout(function() {
tr.timer_L();
}, Timers.TIMER_L);
if (this.resendProvisionalTimer !== null) {
clearInterval(this.resendProvisionalTimer);
this.resendProvisionalTimer = null;
}
/* falls through */
case C.STATUS_ACCEPTED:
// Note that this point will be reached for proceeding tr.state also.
if(!this.transport.send(response)) {
this.onTransportError();
if (onFailure) {
onFailure();
}
} else if (onSuccess) {
onSuccess();
}
break;
}
} else if(status_code >= 300 && status_code <= 699) {
switch(this.state) {
case C.STATUS_PROCEEDING:
if (this.resendProvisionalTimer !== null) {
clearInterval(this.resendProvisionalTimer);
this.resendProvisionalTimer = null;
}
if(!this.transport.send(response)) {
this.onTransportError();
if (onFailure) {
onFailure();
}
} else {
this.stateChanged(C.STATUS_COMPLETED);
this.H = setTimeout(function() {
tr.timer_H();
}, Timers.TIMER_H);
if (onSuccess) {
onSuccess();
}
}
break;
}
}
};
/**
* INVITE:
* _true_ if retransmission
* _false_ new request
*
* ACK:
* _true_ ACK to non2xx response
* _false_ ACK must be passed to TU (accepted state)
* ACK to 2xx response
*
* CANCEL:
* _true_ no matching invite transaction
* _false_ matching invite transaction and no final response sent
*
* OTHER:
* _true_ retransmission
* _false_ new request
*/
function checkTransaction(ua, request) {
var tr;
switch(request.method) {
case JsSIP_C.INVITE:
tr = ua.transactions.ist[request.via_branch];
if(tr) {
switch(tr.state) {
case C.STATUS_PROCEEDING:
tr.transport.send(tr.last_response);
break;
// RFC 6026 7.1 Invite retransmission
//received while in C.STATUS_ACCEPTED state. Absorb it.
case C.STATUS_ACCEPTED:
break;
}
return true;
}
break;
case JsSIP_C.ACK:
tr = ua.transactions.ist[request.via_branch];
// RFC 6026 7.1
if(tr) {
if(tr.state === C.STATUS_ACCEPTED) {
return false;
} else if(tr.state === C.STATUS_COMPLETED) {
tr.state = C.STATUS_CONFIRMED;
tr.I = setTimeout(function() {tr.timer_I();}, Timers.TIMER_I);
return true;
}
}
// ACK to 2XX Response.
else {
return false;
}
break;
case JsSIP_C.CANCEL:
tr = ua.transactions.ist[request.via_branch];
if(tr) {
request.reply_sl(200);
if(tr.state === C.STATUS_PROCEEDING) {
return false;
} else {
return true;
}
} else {
request.reply_sl(481);
return true;
}
break;
default:
// Non-INVITE Server Transaction RFC 3261 17.2.2
tr = ua.transactions.nist[request.via_branch];
if(tr) {
switch(tr.state) {
case C.STATUS_TRYING:
break;
case C.STATUS_PROCEEDING:
case C.STATUS_COMPLETED:
tr.transport.send(tr.last_response);
break;
}
return true;
}
break;
}
}
},{"./Constants":1,"./Timers":20,"debug":34,"events":28,"util":32}],22:[function(require,module,exports){
module.exports = Transport;
/**
* Dependencies.
*/
var Socket = require('./Socket');
var debug = require('debug')('JsSIP:Transport');
var debugerror = require('debug')('JsSIP:ERROR:Transport');
/**
* Constants
*/
var C = {
// Transport status
STATUS_CONNECTED: 0,
STATUS_CONNECTING: 1,
STATUS_DISCONNECTED: 2,
// Socket status
SOCKET_STATUS_READY: 0,
SOCKET_STATUS_ERROR: 1,
// Recovery options
recovery_options: {
min_interval: 2, // minimum interval in seconds between recover attempts
max_interval: 30 // maximum interval in seconds between recover attempts
}
};
/*
* Manages one or multiple JsSIP.Socket instances.
* Is reponsible for transport recovery logic among all socket instances.
*
* @socket JsSIP::Socket instance
*/
function Transport(sockets, recovery_options) {
debug('new()');
this.status = C.STATUS_DISCONNECTED;
// current socket
this.socket = null;
// socket collection
this.sockets = [];
this.recovery_options = recovery_options || C.recovery_options;
this.recover_attempts = 0;
this.recovery_timer = null;
this.close_requested = false;
if (typeof sockets === 'undefined') {
throw new TypeError('Invalid argument.' +
' undefined \'sockets\' argument');
}
if (!(sockets instanceof Array)) {
sockets = [ sockets ];
}
sockets.forEach(function(socket) {
if (!Socket.isSocket(socket.socket)) {
throw new TypeError('Invalid argument.' +
' invalid \'JsSIP.Socket\' instance');
}
if (socket.weight && !Number(socket.weight)) {
throw new TypeError('Invalid argument.' +
' \'weight\' attribute is not a number');
}
this.sockets.push({
socket: socket.socket,
weight: socket.weight || 0,
status: C.SOCKET_STATUS_READY
});
}, this);
// read only properties
Object.defineProperties(this, {
via_transport: { get: function() { return this.socket.via_transport; } },
url: { get: function() { return this.socket.url; } },
sip_uri: { get: function() { return this.socket.sip_uri; } }
});
// get the socket with higher weight
getSocket.call(this);
}
/**
* Instance Methods
*/
Transport.prototype.connect = function() {
debug('connect()');
if (this.isConnected()) {
debug('Transport is already connected');
return;
} else if (this.isConnecting()) {
debug('Transport is connecting');
return;
}
this.close_requested = false;
this.status = C.STATUS_CONNECTING;
this.onconnecting({ socket:this.socket, attempts:this.recover_attempts });
if (!this.close_requested) {
// bind socket event callbacks
this.socket.onconnect = onConnect.bind(this);
this.socket.ondisconnect = onDisconnect.bind(this);
this.socket.ondata = onData.bind(this);
this.socket.connect();
}
return;
};
Transport.prototype.disconnect = function() {
debug('close()');
this.close_requested = true;
this.recover_attempts = 0;
this.status = C.STATUS_DISCONNECTED;
// clear recovery_timer
if (this.recovery_timer !== null) {
clearTimeout(this.recovery_timer);
this.recovery_timer = null;
}
// unbind socket event callbacks
this.socket.onconnect = function() {};
this.socket.ondisconnect = function() {};
this.socket.ondata = function() {};
this.socket.disconnect();
this.ondisconnect();
};
Transport.prototype.send = function(data) {
debug('send()');
if (!this.isConnected()) {
debugerror('unable to send message, transport is not connected');
return false;
}
var message = data.toString();
debug('sending message:\n\n' + message + '\n');
return this.socket.send(message);
};
Transport.prototype.isConnected = function() {
return this.status === C.STATUS_CONNECTED;
};
Transport.prototype.isConnecting = function() {
return this.status === C.STATUS_CONNECTING;
};
/**
* Socket Event Handlers
*/
function onConnect() {
this.recover_attempts = 0;
this.status = C.STATUS_CONNECTED;
// clear recovery_timer
if (this.recovery_timer !== null) {
clearTimeout(this.recovery_timer);
this.recovery_timer = null;
}
this.onconnect( {socket:this} );
}
function onDisconnect(error, code, reason) {
this.status = C.STATUS_DISCONNECTED;
this.ondisconnect({ socket:this.socket, error:error, code:code, reason:reason });
if (this.close_requested) {
return;
}
// update socket status
else {
this.sockets.forEach(function(socket) {
if (this.socket === socket.socket) {
socket.status = C.SOCKET_STATUS_ERROR;
}
}, this);
}
reconnect.call(this, error);
}
function onData(data) {
// CRLF Keep Alive response from server. Ignore it.
if(data === '\r\n') {
debug('received message with CRLF Keep Alive response');
return;
}
// binary message.
else if (typeof data !== 'string') {
try {
data = String.fromCharCode.apply(null, new Uint8Array(data));
} catch(evt) {
debug('received binary message failed to be converted into string,' +
' message discarded');
return;
}
debug('received binary message:\n\n' + data + '\n');
}
// text message.
else {
debug('received text message:\n\n' + data + '\n');
}
this.ondata({ transport:this, message:data });
}
function reconnect() {
var k,
self = this;
this.recover_attempts+=1;
k = Math.floor((Math.random() * Math.pow(2,this.recover_attempts)) +1);
if (k < this.recovery_options.min_interval) {
k = this.recovery_options.min_interval;
}
else if (k > this.recovery_options.max_interval) {
k = this.recovery_options.max_interval;
}
debug('reconnection attempt: '+ this.recover_attempts +
'. next connection attempt in '+ k +' seconds');
this.recovery_timer = setTimeout(function() {
if (!self.close_requested && !(self.isConnected() || self.isConnecting())) {
// get the next available socket with higher weight
getSocket.call(self);
// connect the socket
self.connect();
}
}, k * 1000);
}
/**
* get the next available socket with higher weight
*/
function getSocket() {
var candidates = [];
this.sockets.forEach(function(socket) {
if (socket.status === C.SOCKET_STATUS_ERROR) {
return; // continue the array iteration
} else if (candidates.length === 0) {
candidates.push(socket);
} else if (socket.weight > candidates[0].weight) {
candidates = [socket];
} else if (socket.weight === candidates[0].weight) {
candidates.push(socket);
}
});
if (candidates.length === 0) {
// all sockets have failed. reset sockets status
this.sockets.forEach(function(socket) {
socket.status = C.SOCKET_STATUS_READY;
});
// get next available socket
getSocket.call(this);
return;
}
var idx = Math.floor((Math.random()* candidates.length));
this.socket = candidates[idx].socket;
}
},{"./Socket":19,"debug":34}],23:[function(require,module,exports){
module.exports = UA;
var C = {
// UA status codes
STATUS_INIT : 0,
STATUS_READY: 1,
STATUS_USER_CLOSED: 2,
STATUS_NOT_READY: 3,
// UA error codes
CONFIGURATION_ERROR: 1,
NETWORK_ERROR: 2
};
/**
* Expose C object.
*/
UA.C = C;
/**
* Dependencies.
*/
var util = require('util');
var events = require('events');
var debug = require('debug')('JsSIP:UA');
var debugerror = require('debug')('JsSIP:ERROR:UA');
debugerror.log = console.warn.bind(console);
var JsSIP_C = require('./Constants');
var Registrator = require('./Registrator');
var RTCSession = require('./RTCSession');
var Message = require('./Message');
var Transactions = require('./Transactions');
var Transport = require('./Transport');
var Socket = require('./Socket');
var Utils = require('./Utils');
var Exceptions = require('./Exceptions');
var URI = require('./URI');
var Grammar = require('./Grammar');
var Parser = require('./Parser');
var SIPMessage = require('./SIPMessage');
var sanityCheck = require('./sanityCheck');
/**
* The User-Agent class.
* @class JsSIP.UA
* @param {Object} configuration Configuration parameters.
* @throws {JsSIP.Exceptions.ConfigurationError} If a configuration parameter is invalid.
* @throws {TypeError} If no configuration is given.
*/
function UA(configuration) {
debug('new() [configuration:%o]', configuration);
this.cache = {
credentials: {}
};
this.configuration = {};
this.dynConfiguration = {};
this.dialogs = {};
//User actions outside any session/dialog (MESSAGE)
this.applicants = {};
this.sessions = {};
this.transport = null;
this.contact = null;
this.status = C.STATUS_INIT;
this.error = null;
this.transactions = {
nist: {},
nict: {},
ist: {},
ict: {}
};
// Custom UA empty object for high level use
this.data = {};
this.closeTimer = null;
Object.defineProperties(this, {
transactionsCount: {
get: function() {
var type,
transactions = ['nist','nict','ist','ict'],
count = 0;
for (type in transactions) {
count += Object.keys(this.transactions[transactions[type]]).length;
}
return count;
}
},
nictTransactionsCount: {
get: function() {
return Object.keys(this.transactions.nict).length;
}
},
nistTransactionsCount: {
get: function() {
return Object.keys(this.transactions.nist).length;
}
},
ictTransactionsCount: {
get: function() {
return Object.keys(this.transactions.ict).length;
}
},
istTransactionsCount: {
get: function() {
return Object.keys(this.transactions.ist).length;
}
}
});
/**
* Load configuration
*/
if(configuration === undefined) {
throw new TypeError('Not enough arguments');
}
try {
this.loadConfig(configuration);
} catch(e) {
this.status = C.STATUS_NOT_READY;
this.error = C.CONFIGURATION_ERROR;
throw e;
}
// Initialize registrator
this._registrator = new Registrator(this);
events.EventEmitter.call(this);
}
util.inherits(UA, events.EventEmitter);
//=================
// High Level API
//=================
/**
* Connect to the server if status = STATUS_INIT.
* Resume UA after being closed.
*/
UA.prototype.start = function() {
debug('start()');
if (this.status === C.STATUS_INIT) {
this.transport.connect();
} else if(this.status === C.STATUS_USER_CLOSED) {
debug('restarting UA');
// disconnect
if (this.closeTimer !== null) {
clearTimeout(this.closeTimer);
this.closeTimer = null;
this.transport.disconnect();
}
// reconnect
this.status = C.STATUS_INIT;
this.transport.connect();
} else if (this.status === C.STATUS_READY) {
debug('UA is in READY status, not restarted');
} else {
debug('ERROR: connection is down, Auto-Recovery system is trying to reconnect');
}
// Set dynamic configuration.
this.dynConfiguration.register = this.configuration.register;
};
/**
* Register.
*/
UA.prototype.register = function() {
debug('register()');
this.dynConfiguration.register = true;
this._registrator.register();
};
/**
* Unregister.
*/
UA.prototype.unregister = function(options) {
debug('unregister()');
this.dynConfiguration.register = false;
this._registrator.unregister(options);
};
/**
* Get the Registrator instance.
*/
UA.prototype.registrator = function() {
return this._registrator;
};
/**
* Registration state.
*/
UA.prototype.isRegistered = function() {
if(this._registrator.registered) {
return true;
} else {
return false;
}
};
/**
* Connection state.
*/
UA.prototype.isConnected = function() {
return this.transport.isConnected();
};
/**
* Make an outgoing call.
*
* -param {String} target
* -param {Object} views
* -param {Object} [options]
*
* -throws {TypeError}
*
*/
UA.prototype.call = function(target, options) {
debug('call()');
var session;
session = new RTCSession(this);
session.connect(target, options);
return session;
};
/**
* Send a message.
*
* -param {String} target
* -param {String} body
* -param {Object} [options]
*
* -throws {TypeError}
*
*/
UA.prototype.sendMessage = function(target, body, options) {
debug('sendMessage()');
var message;
message = new Message(this);
message.send(target, body, options);
return message;
};
/**
* Terminate ongoing sessions.
*/
UA.prototype.terminateSessions = function(options) {
debug('terminateSessions()');
for(var idx in this.sessions) {
if (!this.sessions[idx].isEnded()) {
this.sessions[idx].terminate(options);
}
}
};
/**
* Gracefully close.
*
*/
UA.prototype.stop = function() {
debug('stop()');
var session;
var applicant;
var num_sessions;
var ua = this;
// Remove dynamic settings.
this.dynConfiguration = {};
if(this.status === C.STATUS_USER_CLOSED) {
debug('UA already closed');
return;
}
// Close registrator
this._registrator.close();
// If there are session wait a bit so CANCEL/BYE can be sent and their responses received.
num_sessions = Object.keys(this.sessions).length;
// Run _terminate_ on every Session
for(session in this.sessions) {
debug('closing session ' + session);
try { this.sessions[session].terminate(); } catch(error) {}
}
// Run _close_ on every applicant
for(applicant in this.applicants) {
try { this.applicants[applicant].close(); } catch(error) {}
}
this.status = C.STATUS_USER_CLOSED;
if (this.nistTransactionsCount === 0 &&
this.nictTransactionsCount === 0 &&
this.ictTransactionsCount === 0 &&
this.istTransactionsCount === 0 &&
num_sessions === 0) {
ua.transport.disconnect();
}
else {
this.closeTimer = setTimeout(function() {
ua.closeTimer = null;
ua.transport.disconnect();
}, 2000);
}
};
/**
* Normalice a string into a valid SIP request URI
* -param {String} target
* -returns {JsSIP.URI|undefined}
*/
UA.prototype.normalizeTarget = function(target) {
return Utils.normalizeTarget(target, this.configuration.hostport_params);
};
/**
* Allow retrieving configuration and autogenerated fields in runtime.
*/
UA.prototype.get = function(parameter) {
switch(parameter) {
case 'realm':
return this.configuration.realm;
case 'ha1':
return this.configuration.ha1;
default:
debugerror('get() | cannot get "%s" parameter in runtime', parameter);
return undefined;
}
return true;
};
/**
* Allow configuration changes in runtime.
* Returns true if the parameter could be set.
*/
UA.prototype.set = function(parameter, value) {
switch(parameter) {
case 'password': {
this.configuration.password = String(value);
break;
}
case 'realm': {
this.configuration.realm = String(value);
break;
}
case 'ha1': {
this.configuration.ha1 = String(value);
// Delete the plain SIP password.
this.configuration.password = null;
break;
}
case 'display_name': {
if (Grammar.parse('"' + value + '"', 'display_name') === -1) {
debugerror('set() | wrong "display_name"');
return false;
}
this.configuration.display_name = value;
break;
}
default:
debugerror('set() | cannot set "%s" parameter in runtime', parameter);
return false;
}
return true;
};
//===============================
// Private (For internal use)
//===============================
// UA.prototype.saveCredentials = function(credentials) {
// this.cache.credentials[credentials.realm] = this.cache.credentials[credentials.realm] || {};
// this.cache.credentials[credentials.realm][credentials.uri] = credentials;
// };
// UA.prototype.getCredentials = function(request) {
// var realm, credentials;
// realm = request.ruri.host;
// if (this.cache.credentials[realm] && this.cache.credentials[realm][request.ruri]) {
// credentials = this.cache.credentials[realm][request.ruri];
// credentials.method = request.method;
// }
// return credentials;
// };
//==========================
// Event Handlers
//==========================
/**
* new Transaction
*/
UA.prototype.newTransaction = function(transaction) {
this.transactions[transaction.type][transaction.id] = transaction;
this.emit('newTransaction', {
transaction: transaction
});
};
/**
* Transaction destroyed.
*/
UA.prototype.destroyTransaction = function(transaction) {
delete this.transactions[transaction.type][transaction.id];
this.emit('transactionDestroyed', {
transaction: transaction
});
};
/**
* new Message
*/
UA.prototype.newMessage = function(data) {
this.emit('newMessage', data);
};
/**
* new RTCSession
*/
UA.prototype.newRTCSession = function(data) {
this.emit('newRTCSession', data);
};
/**
* Registered
*/
UA.prototype.registered = function(data) {
this.emit('registered', data);
};
/**
* Unregistered
*/
UA.prototype.unregistered = function(data) {
this.emit('unregistered', data);
};
/**
* Registration Failed
*/
UA.prototype.registrationFailed = function(data) {
this.emit('registrationFailed', data);
};
//=========================
// receiveRequest
//=========================
/**
* Request reception
*/
UA.prototype.receiveRequest = function(request) {
var dialog, session, message, replaces,
method = request.method;
// Check that request URI points to us
if(request.ruri.user !== this.configuration.uri.user && request.ruri.user !== this.contact.uri.user) {
debug('Request-URI does not point to us');
if (request.method !== JsSIP_C.ACK) {
request.reply_sl(404);
}
return;
}
// Check request URI scheme
if(request.ruri.scheme === JsSIP_C.SIPS) {
request.reply_sl(416);
return;
}
// Check transaction
if(Transactions.checkTransaction(this, request)) {
return;
}
// Create the server transaction
if(method === JsSIP_C.INVITE) {
new Transactions.InviteServerTransaction(request, this);
} else if(method !== JsSIP_C.ACK && method !== JsSIP_C.CANCEL) {
new Transactions.NonInviteServerTransaction(request, this);
}
/* RFC3261 12.2.2
* Requests that do not change in any way the state of a dialog may be
* received within a dialog (for example, an OPTIONS request).
* They are processed as if they had been received outside the dialog.
*/
if(method === JsSIP_C.OPTIONS) {
request.reply(200);
} else if (method === JsSIP_C.MESSAGE) {
if (this.listeners('newMessage').length === 0) {
request.reply(405);
return;
}
message = new Message(this);
message.init_incoming(request);
} else if (method === JsSIP_C.INVITE) {
// Initial INVITE
if(!request.to_tag && this.listeners('newRTCSession').length === 0) {
request.reply(405);
return;
}
}
// Initial Request
if(!request.to_tag) {
switch(method) {
case JsSIP_C.INVITE:
if (window.RTCPeerConnection) { // TODO
if (request.hasHeader('replaces')) {
replaces = request.replaces;
dialog = this.findDialog(replaces.call_id, replaces.from_tag, replaces.to_tag);
if (dialog) {
session = dialog.owner;
if (!session.isEnded()) {
session.receiveRequest(request);
} else {
request.reply(603);
}
} else {
request.reply(481);
}
} else {
session = new RTCSession(this);
session.init_incoming(request);
}
} else {
debugerror('INVITE received but WebRTC is not supported');
request.reply(488);
}
break;
case JsSIP_C.BYE:
// Out of dialog BYE received
request.reply(481);
break;
case JsSIP_C.CANCEL:
session = this.findSession(request);
if (session) {
session.receiveRequest(request);
} else {
debug('received CANCEL request for a non existent session');
}
break;
case JsSIP_C.ACK:
/* Absorb it.
* ACK request without a corresponding Invite Transaction
* and without To tag.
*/
break;
default:
request.reply(405);
break;
}
}
// In-dialog request
else {
dialog = this.findDialog(request.call_id, request.from_tag, request.to_tag);
if(dialog) {
dialog.receiveRequest(request);
} else if (method === JsSIP_C.NOTIFY) {
session = this.findSession(request);
if(session) {
session.receiveRequest(request);
} else {
debug('received NOTIFY request for a non existent subscription');
request.reply(481, 'Subscription does not exist');
}
}
/* RFC3261 12.2.2
* Request with to tag, but no matching dialog found.
* Exception: ACK for an Invite request for which a dialog has not
* been created.
*/
else {
if(method !== JsSIP_C.ACK) {
request.reply(481);
}
}
}
};
//=================
// Utils
//=================
/**
* Get the session to which the request belongs to, if any.
*/
UA.prototype.findSession = function(request) {
var
sessionIDa = request.call_id + request.from_tag,
sessionA = this.sessions[sessionIDa],
sessionIDb = request.call_id + request.to_tag,
sessionB = this.sessions[sessionIDb];
if(sessionA) {
return sessionA;
} else if(sessionB) {
return sessionB;
} else {
return null;
}
};
/**
* Get the dialog to which the request belongs to, if any.
*/
UA.prototype.findDialog = function(call_id, from_tag, to_tag) {
var
id = call_id + from_tag + to_tag,
dialog = this.dialogs[id];
if(dialog) {
return dialog;
} else {
id = call_id + to_tag + from_tag;
dialog = this.dialogs[id];
if(dialog) {
return dialog;
} else {
return null;
}
}
};
UA.prototype.loadConfig = function(configuration) {
// Settings and default values
var parameter, value, checked_value, hostport_params, registrar_server,
settings = {
/* Host address
* Value to be set in Via sent_by and host part of Contact FQDN
*/
via_host: Utils.createRandomToken(12) + '.invalid',
// SIP Contact URI
contact_uri: null,
// SIP authentication password
password: null,
// SIP authentication realm
realm: null,
// SIP authentication HA1 hash
ha1: null,
// Registration parameters
register_expires: 600,
register: true,
registrar_server: null,
use_preloaded_route: false,
// Session parameters
no_answer_timeout: 60,
session_timers: true,
};
// Pre-Configuration
// Check Mandatory parameters
for(parameter in UA.configuration_check.mandatory) {
if(!configuration.hasOwnProperty(parameter)) {
throw new Exceptions.ConfigurationError(parameter);
} else {
value = configuration[parameter];
checked_value = UA.configuration_check.mandatory[parameter].call(this, value);
if (checked_value !== undefined) {
settings[parameter] = checked_value;
} else {
throw new Exceptions.ConfigurationError(parameter, value);
}
}
}
// Check Optional parameters
for(parameter in UA.configuration_check.optional) {
if(configuration.hasOwnProperty(parameter)) {
value = configuration[parameter];
/* If the parameter value is null, empty string, undefined, empty array
* or it's a number with NaN value, then apply its default value.
*/
if (Utils.isEmpty(value)) {
continue;
}
checked_value = UA.configuration_check.optional[parameter].call(this, value, configuration);
if (checked_value !== undefined) {
settings[parameter] = checked_value;
} else {
throw new Exceptions.ConfigurationError(parameter, value);
}
}
}
// Post Configuration Process
// Allow passing 0 number as display_name.
if (settings.display_name === 0) {
settings.display_name = '0';
}
// Instance-id for GRUU.
if (!settings.instance_id) {
settings.instance_id = Utils.newUUID();
}
// jssip_id instance parameter. Static random tag of length 5.
settings.jssip_id = Utils.createRandomToken(5);
// String containing settings.uri without scheme and user.
hostport_params = settings.uri.clone();
hostport_params.user = null;
settings.hostport_params = hostport_params.toString().replace(/^sip:/i, '');
// Transport
var sockets = [];
if (settings.sockets && Array.isArray(settings.sockets)) {
sockets = sockets.concat(settings.sockets);
}
if (sockets.length === 0) {
throw new Exceptions.ConfigurationError('sockets');
}
try {
this.transport = new Transport(sockets, { /* recovery options */
max_interval: settings.connection_recovery_max_interval,
min_interval: settings.connection_recovery_min_interval
});
// Transport event callbacks
this.transport.onconnecting = onTransportConnecting.bind(this);
this.transport.onconnect = onTransportConnect.bind(this);
this.transport.ondisconnect = onTransportDisconnect.bind(this);
this.transport.ondata = onTransportData.bind(this);
// transport options not needed here anymore
delete settings.connection_recovery_max_interval;
delete settings.connection_recovery_min_interval;
delete settings.sockets;
} catch (e) {
debugerror(e);
throw new Exceptions.ConfigurationError('sockets', sockets);
}
// Check whether authorization_user is explicitly defined.
// Take 'settings.uri.user' value if not.
if (!settings.authorization_user) {
settings.authorization_user = settings.uri.user;
}
// If no 'registrar_server' is set use the 'uri' value without user portion and
// without URI params/headers.
if (!settings.registrar_server) {
registrar_server = settings.uri.clone();
registrar_server.user = null;
registrar_server.clearParams();
registrar_server.clearHeaders();
settings.registrar_server = registrar_server;
}
// User no_answer_timeout.
settings.no_answer_timeout = settings.no_answer_timeout * 1000;
// Via Host
if (settings.contact_uri) {
settings.via_host = settings.contact_uri.host;
}
// Contact URI
else {
settings.contact_uri = new URI('sip', Utils.createRandomToken(8), settings.via_host, null, {transport: 'ws'});
}
this.contact = {
pub_gruu: null,
temp_gruu: null,
uri: settings.contact_uri,
toString: function(options) {
options = options || {};
var
anonymous = options.anonymous || null,
outbound = options.outbound || null,
contact = '<';
if (anonymous) {
contact += this.temp_gruu || 'sip:[email protected];transport=ws';
} else {
contact += this.pub_gruu || this.uri.toString();
}
if (outbound && (anonymous ? !this.temp_gruu : !this.pub_gruu)) {
contact += ';ob';
}
contact += '>';
return contact;
}
};
// Fill the value of the configuration_skeleton
for(parameter in settings) {
UA.configuration_skeleton[parameter].value = settings[parameter];
}
Object.defineProperties(this.configuration, UA.configuration_skeleton);
// Clean UA.configuration_skeleton
for(parameter in settings) {
UA.configuration_skeleton[parameter].value = '';
}
debug('configuration parameters after validation:');
for(parameter in settings) {
switch(parameter) {
case 'uri':
case 'registrar_server':
debug('- ' + parameter + ': ' + settings[parameter]);
break;
case 'password':
case 'ha1':
debug('- ' + parameter + ': ' + 'NOT SHOWN');
break;
default:
debug('- ' + parameter + ': ' + JSON.stringify(settings[parameter]));
}
}
return;
};
/**
* Configuration Object skeleton.
*/
UA.configuration_skeleton = (function() {
var
idx, parameter, writable,
skeleton = {},
parameters = [
// Internal parameters
'jssip_id',
'hostport_params',
// Mandatory user configurable parameters
'uri',
// Optional user configurable parameters
'authorization_user',
'contact_uri',
'display_name',
'instance_id',
'no_answer_timeout', // 30 seconds
'session_timers', // true
'password',
'realm',
'ha1',
'register_expires', // 600 seconds
'registrar_server',
'sockets',
'use_preloaded_route',
// Post-configuration generated parameters
'via_core_value',
'via_host'
];
var writable_parameters = [
'password', 'realm', 'ha1', 'display_name'
];
for(idx in parameters) {
parameter = parameters[idx];
if (writable_parameters.indexOf(parameter) !== -1) {
writable = true;
} else {
writable = false;
}
skeleton[parameter] = {
value: '',
writable: writable,
configurable: false
};
}
skeleton.register = {
value: '',
writable: true,
configurable: false
};
return skeleton;
}());
/**
* Configuration checker.
*/
UA.configuration_check = {
mandatory: {
uri: function(uri) {
var parsed;
if (!/^sip:/i.test(uri)) {
uri = JsSIP_C.SIP + ':' + uri;
}
parsed = URI.parse(uri);
if(!parsed) {
return;
} else if(!parsed.user) {
return;
} else {
return parsed;
}
}
},
optional: {
authorization_user: function(authorization_user) {
if(Grammar.parse('"'+ authorization_user +'"', 'quoted_string') === -1) {
return;
} else {
return authorization_user;
}
},
connection_recovery_max_interval: function(connection_recovery_max_interval) {
var value;
if(Utils.isDecimal(connection_recovery_max_interval)) {
value = Number(connection_recovery_max_interval);
if(value > 0) {
return value;
}
}
},
connection_recovery_min_interval: function(connection_recovery_min_interval) {
var value;
if(Utils.isDecimal(connection_recovery_min_interval)) {
value = Number(connection_recovery_min_interval);
if(value > 0) {
return value;
}
}
},
contact_uri: function(contact_uri) {
if (typeof contact_uri === 'string') {
var uri = Grammar.parse(contact_uri,'SIP_URI');
if (uri !== -1) {
return uri;
}
}
},
display_name: function(display_name) {
if (Grammar.parse('"' + display_name + '"', 'display_name') === -1) {
return;
} else {
return display_name;
}
},
instance_id: function(instance_id) {
if ((/^uuid:/i.test(instance_id))) {
instance_id = instance_id.substr(5);
}
if(Grammar.parse(instance_id, 'uuid') === -1) {
return;
} else {
return instance_id;
}
},
no_answer_timeout: function(no_answer_timeout) {
var value;
if (Utils.isDecimal(no_answer_timeout)) {
value = Number(no_answer_timeout);
if (value > 0) {
return value;
}
}
},
session_timers: function(session_timers) {
if (typeof session_timers === 'boolean') {
return session_timers;
}
},
password: function(password) {
return String(password);
},
realm: function(realm) {
return String(realm);
},
ha1: function(ha1) {
return String(ha1);
},
register: function(register) {
if (typeof register === 'boolean') {
return register;
}
},
register_expires: function(register_expires) {
var value;
if (Utils.isDecimal(register_expires)) {
value = Number(register_expires);
if (value > 0) {
return value;
}
}
},
registrar_server: function(registrar_server) {
var parsed;
if (!/^sip:/i.test(registrar_server)) {
registrar_server = JsSIP_C.SIP + ':' + registrar_server;
}
parsed = URI.parse(registrar_server);
if(!parsed) {
return;
} else if(parsed.user) {
return;
} else {
return parsed;
}
},
sockets: function(sockets) {
var idx, length;
/* Allow defining sockets parameter as:
* Socket: socket
* Array of Socket: [socket1, socket2]
* Array of Objects: [{socket: socket1, weight:1}, {socket: Socket2, weight:0}]
* Array of Objects and Socket: [{socket: socket1}, socket2]
*/
if (Socket.isSocket(sockets)) {
sockets = [{socket: sockets}];
} else if (Array.isArray(sockets) && sockets.length) {
length = sockets.length;
for (idx = 0; idx < length; idx++) {
if (Socket.isSocket(sockets[idx])) {
sockets[idx] = {socket: sockets[idx]};
}
}
} else {
return;
}
return sockets;
},
use_preloaded_route: function(use_preloaded_route) {
if (typeof use_preloaded_route === 'boolean') {
return use_preloaded_route;
}
}
}
};
/**
* Transport event handlers
*/
// Transport connecting event
function onTransportConnecting(data) {
this.emit('connecting', data);
}
// Transport connected event.
function onTransportConnect(data) {
if(this.status === C.STATUS_USER_CLOSED) {
return;
}
this.status = C.STATUS_READY;
this.error = null;
this.emit('connected', data);
if(this.dynConfiguration.register) {
this._registrator.register();
}
}
// Transport disconnected event.
function onTransportDisconnect(data) {
// Run _onTransportError_ callback on every client transaction using _transport_
var type, idx, length,
client_transactions = ['nict', 'ict', 'nist', 'ist'];
length = client_transactions.length;
for (type = 0; type < length; type++) {
for(idx in this.transactions[client_transactions[type]]) {
this.transactions[client_transactions[type]][idx].onTransportError();
}
}
this.emit('disconnected', data);
// Call registrator _onTransportClosed_
this._registrator.onTransportClosed();
if (this.status !== C.STATUS_USER_CLOSED) {
this.status = C.STATUS_NOT_READY;
this.error = C.NETWORK_ERROR;
}
}
// Transport data event
function onTransportData(data) {
var transaction,
transport = data.transport,
message = data.message;
message = Parser.parseMessage(message, this);
if (! message) {
return;
}
if (this.status === UA.C.STATUS_USER_CLOSED &&
message instanceof SIPMessage.IncomingRequest) {
return;
}
// Do some sanity check
if(! sanityCheck(message, this, transport)) {
return;
}
if(message instanceof SIPMessage.IncomingRequest) {
message.transport = transport;
this.receiveRequest(message);
} else if(message instanceof SIPMessage.IncomingResponse) {
/* Unike stated in 18.1.2, if a response does not match
* any transaction, it is discarded here and no passed to the core
* in order to be discarded there.
*/
switch(message.method) {
case JsSIP_C.INVITE:
transaction = this.transactions.ict[message.via_branch];
if(transaction) {
transaction.receiveResponse(message);
}
break;
case JsSIP_C.ACK:
// Just in case ;-)
break;
default:
transaction = this.transactions.nict[message.via_branch];
if(transaction) {
transaction.receiveResponse(message);
}
break;
}
}
}
},{"./Constants":1,"./Exceptions":5,"./Grammar":6,"./Message":8,"./Parser":10,"./RTCSession":11,"./Registrator":16,"./SIPMessage":18,"./Socket":19,"./Transactions":21,"./Transport":22,"./URI":24,"./Utils":25,"./sanityCheck":27,"debug":34,"events":28,"util":32}],24:[function(require,module,exports){
module.exports = URI;
/**
* Dependencies.
*/
var JsSIP_C = require('./Constants');
var Utils = require('./Utils');
var Grammar = require('./Grammar');
/**
* -param {String} [scheme]
* -param {String} [user]
* -param {String} host
* -param {String} [port]
* -param {Object} [parameters]
* -param {Object} [headers]
*
*/
function URI(scheme, user, host, port, parameters, headers) {
var param, header;
// Checks
if(!host) {
throw new TypeError('missing or invalid "host" parameter');
}
// Initialize parameters
scheme = scheme || JsSIP_C.SIP;
this.parameters = {};
this.headers = {};
for (param in parameters) {
this.setParam(param, parameters[param]);
}
for (header in headers) {
this.setHeader(header, headers[header]);
}
Object.defineProperties(this, {
scheme: {
get: function(){ return scheme; },
set: function(value){
scheme = value.toLowerCase();
}
},
user: {
get: function(){ return user; },
set: function(value){
user = value;
}
},
host: {
get: function(){ return host; },
set: function(value){
host = value.toLowerCase();
}
},
port: {
get: function(){ return port; },
set: function(value){
port = value === 0 ? value : (parseInt(value,10) || null);
}
}
});
}
URI.prototype = {
setParam: function(key, value) {
if(key) {
this.parameters[key.toLowerCase()] = (typeof value === 'undefined' || value === null) ? null : value.toString();
}
},
getParam: function(key) {
if(key) {
return this.parameters[key.toLowerCase()];
}
},
hasParam: function(key) {
if(key) {
return (this.parameters.hasOwnProperty(key.toLowerCase()) && true) || false;
}
},
deleteParam: function(parameter) {
var value;
parameter = parameter.toLowerCase();
if (this.parameters.hasOwnProperty(parameter)) {
value = this.parameters[parameter];
delete this.parameters[parameter];
return value;
}
},
clearParams: function() {
this.parameters = {};
},
setHeader: function(name, value) {
this.headers[Utils.headerize(name)] = (Array.isArray(value)) ? value : [value];
},
getHeader: function(name) {
if(name) {
return this.headers[Utils.headerize(name)];
}
},
hasHeader: function(name) {
if(name) {
return (this.headers.hasOwnProperty(Utils.headerize(name)) && true) || false;
}
},
deleteHeader: function(header) {
var value;
header = Utils.headerize(header);
if(this.headers.hasOwnProperty(header)) {
value = this.headers[header];
delete this.headers[header];
return value;
}
},
clearHeaders: function() {
this.headers = {};
},
clone: function() {
return new URI(
this.scheme,
this.user,
this.host,
this.port,
JSON.parse(JSON.stringify(this.parameters)),
JSON.parse(JSON.stringify(this.headers)));
},
toString: function(){
var header, parameter, idx, uri,
headers = [];
uri = this.scheme + ':';
if (this.user) {
uri += Utils.escapeUser(this.user) + '@';
}
uri += this.host;
if (this.port || this.port === 0) {
uri += ':' + this.port;
}
for (parameter in this.parameters) {
uri += ';' + parameter;
if (this.parameters[parameter] !== null) {
uri += '='+ this.parameters[parameter];
}
}
for(header in this.headers) {
for(idx = 0; idx < this.headers[header].length; idx++) {
headers.push(header + '=' + this.headers[header][idx]);
}
}
if (headers.length > 0) {
uri += '?' + headers.join('&');
}
return uri;
},
toAor: function(show_port){
var aor;
aor = this.scheme + ':';
if (this.user) {
aor += Utils.escapeUser(this.user) + '@';
}
aor += this.host;
if (show_port && (this.port || this.port === 0)) {
aor += ':' + this.port;
}
return aor;
}
};
/**
* Parse the given string and returns a JsSIP.URI instance or undefined if
* it is an invalid URI.
*/
URI.parse = function(uri) {
uri = Grammar.parse(uri,'SIP_URI');
if (uri !== -1) {
return uri;
} else {
return undefined;
}
};
},{"./Constants":1,"./Grammar":6,"./Utils":25}],25:[function(require,module,exports){
var Utils = {};
module.exports = Utils;
/**
* Dependencies.
*/
var JsSIP_C = require('./Constants');
var URI = require('./URI');
var Grammar = require('./Grammar');
Utils.str_utf8_length = function(string) {
return unescape(encodeURIComponent(string)).length;
};
Utils.isFunction = function(fn) {
if (fn !== undefined) {
return (Object.prototype.toString.call(fn) === '[object Function]')? true : false;
} else {
return false;
}
};
Utils.isString = function(str) {
if (str !== undefined) {
return (Object.prototype.toString.call(str) === '[object String]')? true : false;
} else {
return false;
}
};
Utils.isDecimal = function(num) {
return !isNaN(num) && (parseFloat(num) === parseInt(num,10));
};
Utils.isEmpty = function(value) {
if (value === null || value === '' || value === undefined || (Array.isArray(value) && value.length === 0) || (typeof(value) === 'number' && isNaN(value))) {
return true;
}
};
Utils.hasMethods = function(obj /*, method list as strings */){
var i = 1, methodName;
while((methodName = arguments[i++])){
if(this.isFunction(obj[methodName])) {
return false;
}
}
return true;
};
Utils.createRandomToken = function(size, base) {
var i, r,
token = '';
base = base || 32;
for( i=0; i < size; i++ ) {
r = Math.random() * base|0;
token += r.toString(base);
}
return token;
};
Utils.newTag = function() {
return Utils.createRandomToken(10);
};
// http://stackoverflow.com/users/109538/broofa
Utils.newUUID = function() {
var UUID = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
return UUID;
};
Utils.hostType = function(host) {
if (!host) {
return;
} else {
host = Grammar.parse(host,'host');
if (host !== -1) {
return host.host_type;
}
}
};
/**
* Normalize SIP URI.
* NOTE: It does not allow a SIP URI without username.
* Accepts 'sip', 'sips' and 'tel' URIs and convert them into 'sip'.
* Detects the domain part (if given) and properly hex-escapes the user portion.
* If the user portion has only 'tel' number symbols the user portion is clean of 'tel' visual separators.
*/
Utils.normalizeTarget = function(target, domain) {
var uri, target_array, target_user, target_domain;
// If no target is given then raise an error.
if (!target) {
return;
// If a URI instance is given then return it.
} else if (target instanceof URI) {
return target;
// If a string is given split it by '@':
// - Last fragment is the desired domain.
// - Otherwise append the given domain argument.
} else if (typeof target === 'string') {
target_array = target.split('@');
switch(target_array.length) {
case 1:
if (!domain) {
return;
}
target_user = target;
target_domain = domain;
break;
case 2:
target_user = target_array[0];
target_domain = target_array[1];
break;
default:
target_user = target_array.slice(0, target_array.length-1).join('@');
target_domain = target_array[target_array.length-1];
}
// Remove the URI scheme (if present).
target_user = target_user.replace(/^(sips?|tel):/i, '');
// Remove 'tel' visual separators if the user portion just contains 'tel' number symbols.
if (/^[\-\.\(\)]*\+?[0-9\-\.\(\)]+$/.test(target_user)) {
target_user = target_user.replace(/[\-\.\(\)]/g, '');
}
// Build the complete SIP URI.
target = JsSIP_C.SIP + ':' + Utils.escapeUser(target_user) + '@' + target_domain;
// Finally parse the resulting URI.
if ((uri = URI.parse(target))) {
return uri;
} else {
return;
}
} else {
return;
}
};
/**
* Hex-escape a SIP URI user.
*/
Utils.escapeUser = function(user) {
// Don't hex-escape ':' (%3A), '+' (%2B), '?' (%3F"), '/' (%2F).
return encodeURIComponent(decodeURIComponent(user)).replace(/%3A/ig, ':').replace(/%2B/ig, '+').replace(/%3F/ig, '?').replace(/%2F/ig, '/');
};
Utils.headerize = function(string) {
var exceptions = {
'Call-Id': 'Call-ID',
'Cseq': 'CSeq',
'Www-Authenticate': 'WWW-Authenticate'
},
name = string.toLowerCase().replace(/_/g,'-').split('-'),
hname = '',
parts = name.length, part;
for (part = 0; part < parts; part++) {
if (part !== 0) {
hname +='-';
}
hname += name[part].charAt(0).toUpperCase()+name[part].substring(1);
}
if (exceptions[hname]) {
hname = exceptions[hname];
}
return hname;
};
Utils.sipErrorCause = function(status_code) {
var cause;
for (cause in JsSIP_C.SIP_ERROR_CAUSES) {
if (JsSIP_C.SIP_ERROR_CAUSES[cause].indexOf(status_code) !== -1) {
return JsSIP_C.causes[cause];
}
}
return JsSIP_C.causes.SIP_FAILURE_CODE;
};
/**
* Generate a random Test-Net IP (http://tools.ietf.org/html/rfc5735)
*/
Utils.getRandomTestNetIP = function() {
function getOctet(from,to) {
return Math.floor(Math.random()*(to-from+1)+from);
}
return '192.0.2.' + getOctet(1, 254);
};
// MD5 (Message-Digest Algorithm) http://www.webtoolkit.info
Utils.calculateMD5 = function(string) {
function rotateLeft(lValue, iShiftBits) {
return (lValue<<iShiftBits) | (lValue>>>(32-iShiftBits));
}
function addUnsigned(lX,lY) {
var lX4,lY4,lX8,lY8,lResult;
lX8 = (lX & 0x80000000);
lY8 = (lY & 0x80000000);
lX4 = (lX & 0x40000000);
lY4 = (lY & 0x40000000);
lResult = (lX & 0x3FFFFFFF)+(lY & 0x3FFFFFFF);
if (lX4 & lY4) {
return (lResult ^ 0x80000000 ^ lX8 ^ lY8);
}
if (lX4 | lY4) {
if (lResult & 0x40000000) {
return (lResult ^ 0xC0000000 ^ lX8 ^ lY8);
} else {
return (lResult ^ 0x40000000 ^ lX8 ^ lY8);
}
} else {
return (lResult ^ lX8 ^ lY8);
}
}
function doF(x,y,z) {
return (x & y) | ((~x) & z);
}
function doG(x,y,z) {
return (x & z) | (y & (~z));
}
function doH(x,y,z) {
return (x ^ y ^ z);
}
function doI(x,y,z) {
return (y ^ (x | (~z)));
}
function doFF(a,b,c,d,x,s,ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(doF(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
}
function doGG(a,b,c,d,x,s,ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(doG(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
}
function doHH(a,b,c,d,x,s,ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(doH(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
}
function doII(a,b,c,d,x,s,ac) {
a = addUnsigned(a, addUnsigned(addUnsigned(doI(b, c, d), x), ac));
return addUnsigned(rotateLeft(a, s), b);
}
function convertToWordArray(string) {
var lWordCount;
var lMessageLength = string.length;
var lNumberOfWords_temp1=lMessageLength + 8;
var lNumberOfWords_temp2=(lNumberOfWords_temp1-(lNumberOfWords_temp1 % 64))/64;
var lNumberOfWords = (lNumberOfWords_temp2+1)*16;
var lWordArray = new Array(lNumberOfWords-1);
var lBytePosition = 0;
var lByteCount = 0;
while ( lByteCount < lMessageLength ) {
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = (lWordArray[lWordCount] | (string.charCodeAt(lByteCount)<<lBytePosition));
lByteCount++;
}
lWordCount = (lByteCount-(lByteCount % 4))/4;
lBytePosition = (lByteCount % 4)*8;
lWordArray[lWordCount] = lWordArray[lWordCount] | (0x80<<lBytePosition);
lWordArray[lNumberOfWords-2] = lMessageLength<<3;
lWordArray[lNumberOfWords-1] = lMessageLength>>>29;
return lWordArray;
}
function wordToHex(lValue) {
var wordToHexValue='',wordToHexValue_temp='',lByte,lCount;
for (lCount = 0;lCount<=3;lCount++) {
lByte = (lValue>>>(lCount*8)) & 255;
wordToHexValue_temp = '0' + lByte.toString(16);
wordToHexValue = wordToHexValue + wordToHexValue_temp.substr(wordToHexValue_temp.length-2,2);
}
return wordToHexValue;
}
function utf8Encode(string) {
string = string.replace(/\r\n/g, '\n');
var utftext = '';
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
var x=[];
var k,AA,BB,CC,DD,a,b,c,d;
var S11=7, S12=12, S13=17, S14=22;
var S21=5, S22=9 , S23=14, S24=20;
var S31=4, S32=11, S33=16, S34=23;
var S41=6, S42=10, S43=15, S44=21;
string = utf8Encode(string);
x = convertToWordArray(string);
a = 0x67452301; b = 0xEFCDAB89; c = 0x98BADCFE; d = 0x10325476;
for (k=0;k<x.length;k+=16) {
AA=a; BB=b; CC=c; DD=d;
a=doFF(a,b,c,d,x[k+0], S11,0xD76AA478);
d=doFF(d,a,b,c,x[k+1], S12,0xE8C7B756);
c=doFF(c,d,a,b,x[k+2], S13,0x242070DB);
b=doFF(b,c,d,a,x[k+3], S14,0xC1BDCEEE);
a=doFF(a,b,c,d,x[k+4], S11,0xF57C0FAF);
d=doFF(d,a,b,c,x[k+5], S12,0x4787C62A);
c=doFF(c,d,a,b,x[k+6], S13,0xA8304613);
b=doFF(b,c,d,a,x[k+7], S14,0xFD469501);
a=doFF(a,b,c,d,x[k+8], S11,0x698098D8);
d=doFF(d,a,b,c,x[k+9], S12,0x8B44F7AF);
c=doFF(c,d,a,b,x[k+10],S13,0xFFFF5BB1);
b=doFF(b,c,d,a,x[k+11],S14,0x895CD7BE);
a=doFF(a,b,c,d,x[k+12],S11,0x6B901122);
d=doFF(d,a,b,c,x[k+13],S12,0xFD987193);
c=doFF(c,d,a,b,x[k+14],S13,0xA679438E);
b=doFF(b,c,d,a,x[k+15],S14,0x49B40821);
a=doGG(a,b,c,d,x[k+1], S21,0xF61E2562);
d=doGG(d,a,b,c,x[k+6], S22,0xC040B340);
c=doGG(c,d,a,b,x[k+11],S23,0x265E5A51);
b=doGG(b,c,d,a,x[k+0], S24,0xE9B6C7AA);
a=doGG(a,b,c,d,x[k+5], S21,0xD62F105D);
d=doGG(d,a,b,c,x[k+10],S22,0x2441453);
c=doGG(c,d,a,b,x[k+15],S23,0xD8A1E681);
b=doGG(b,c,d,a,x[k+4], S24,0xE7D3FBC8);
a=doGG(a,b,c,d,x[k+9], S21,0x21E1CDE6);
d=doGG(d,a,b,c,x[k+14],S22,0xC33707D6);
c=doGG(c,d,a,b,x[k+3], S23,0xF4D50D87);
b=doGG(b,c,d,a,x[k+8], S24,0x455A14ED);
a=doGG(a,b,c,d,x[k+13],S21,0xA9E3E905);
d=doGG(d,a,b,c,x[k+2], S22,0xFCEFA3F8);
c=doGG(c,d,a,b,x[k+7], S23,0x676F02D9);
b=doGG(b,c,d,a,x[k+12],S24,0x8D2A4C8A);
a=doHH(a,b,c,d,x[k+5], S31,0xFFFA3942);
d=doHH(d,a,b,c,x[k+8], S32,0x8771F681);
c=doHH(c,d,a,b,x[k+11],S33,0x6D9D6122);
b=doHH(b,c,d,a,x[k+14],S34,0xFDE5380C);
a=doHH(a,b,c,d,x[k+1], S31,0xA4BEEA44);
d=doHH(d,a,b,c,x[k+4], S32,0x4BDECFA9);
c=doHH(c,d,a,b,x[k+7], S33,0xF6BB4B60);
b=doHH(b,c,d,a,x[k+10],S34,0xBEBFBC70);
a=doHH(a,b,c,d,x[k+13],S31,0x289B7EC6);
d=doHH(d,a,b,c,x[k+0], S32,0xEAA127FA);
c=doHH(c,d,a,b,x[k+3], S33,0xD4EF3085);
b=doHH(b,c,d,a,x[k+6], S34,0x4881D05);
a=doHH(a,b,c,d,x[k+9], S31,0xD9D4D039);
d=doHH(d,a,b,c,x[k+12],S32,0xE6DB99E5);
c=doHH(c,d,a,b,x[k+15],S33,0x1FA27CF8);
b=doHH(b,c,d,a,x[k+2], S34,0xC4AC5665);
a=doII(a,b,c,d,x[k+0], S41,0xF4292244);
d=doII(d,a,b,c,x[k+7], S42,0x432AFF97);
c=doII(c,d,a,b,x[k+14],S43,0xAB9423A7);
b=doII(b,c,d,a,x[k+5], S44,0xFC93A039);
a=doII(a,b,c,d,x[k+12],S41,0x655B59C3);
d=doII(d,a,b,c,x[k+3], S42,0x8F0CCC92);
c=doII(c,d,a,b,x[k+10],S43,0xFFEFF47D);
b=doII(b,c,d,a,x[k+1], S44,0x85845DD1);
a=doII(a,b,c,d,x[k+8], S41,0x6FA87E4F);
d=doII(d,a,b,c,x[k+15],S42,0xFE2CE6E0);
c=doII(c,d,a,b,x[k+6], S43,0xA3014314);
b=doII(b,c,d,a,x[k+13],S44,0x4E0811A1);
a=doII(a,b,c,d,x[k+4], S41,0xF7537E82);
d=doII(d,a,b,c,x[k+11],S42,0xBD3AF235);
c=doII(c,d,a,b,x[k+2], S43,0x2AD7D2BB);
b=doII(b,c,d,a,x[k+9], S44,0xEB86D391);
a=addUnsigned(a,AA);
b=addUnsigned(b,BB);
c=addUnsigned(c,CC);
d=addUnsigned(d,DD);
}
var temp = wordToHex(a)+wordToHex(b)+wordToHex(c)+wordToHex(d);
return temp.toLowerCase();
};
Utils.closeMediaStream = function(stream) {
if (!stream) {
return;
}
// Latest spec states that MediaStream has no stop() method and instead must
// call stop() on every MediaStreamTrack.
try {
var tracks, i, len;
if (stream.getTracks) {
tracks = stream.getTracks();
for (i = 0, len = tracks.length; i < len; i += 1) {
tracks[i].stop();
}
} else {
tracks = stream.getAudioTracks();
for (i = 0, len = tracks.length; i < len; i += 1) {
tracks[i].stop();
}
tracks = stream.getVideoTracks();
for (i = 0, len = tracks.length; i < len; i += 1) {
tracks[i].stop();
}
}
} catch (error) {
// Deprecated by the spec, but still in use.
// NOTE: In Temasys IE plugin stream.stop is a callable 'object'.
if (typeof stream.stop === 'function' || typeof stream.stop === 'object') {
stream.stop();
}
}
};
},{"./Constants":1,"./Grammar":6,"./URI":24}],26:[function(require,module,exports){
module.exports = WebSocketInterface;
/**
* Dependencies.
*/
var Grammar = require('./Grammar');
var debug = require('debug')('JsSIP:WebSocketInterface');
var debugerror = require('debug')('JsSIP:ERROR:WebSocketInterface');
debugerror.log = console.warn.bind(console);
function WebSocketInterface(url) {
debug('new() [url:"%s"]', url);
var sip_uri = null;
var via_transport = null;
this.ws = null;
// setting the 'scheme' alters the sip_uri too (used in SIP Route header field)
Object.defineProperties(this, {
via_transport: {
get: function() { return via_transport; },
set: function(transport) {
via_transport = transport.toUpperCase();
}
},
sip_uri: { get: function() { return sip_uri; }},
url: { get: function() { return url; }}
});
var parsed_url = Grammar.parse(url, 'absoluteURI');
if (parsed_url === -1) {
debugerror('invalid WebSocket URI: ' + url);
throw new TypeError('Invalid argument: ' + url);
} else if(parsed_url.scheme !== 'wss' && parsed_url.scheme !== 'ws') {
debugerror('invalid WebSocket URI scheme: ' + parsed_url.scheme);
throw new TypeError('Invalid argument: ' + url);
} else {
sip_uri = 'sip:' + parsed_url.host +
(parsed_url.port ? ':' + parsed_url.port : '') + ';transport=ws';
this.via_transport = parsed_url.scheme;
}
}
WebSocketInterface.prototype.connect = function () {
debug('connect()');
if (this.isConnected()) {
debug('WebSocket ' + this.url + ' is already connected');
return;
} else if (this.isConnecting()) {
debug('WebSocket ' + this.url + ' is connecting');
return;
}
if (this.ws) {
this.disconnect();
}
debug('connecting to WebSocket ' + this.url);
try {
this.ws = new WebSocket(this.url, 'sip');
this.ws.binaryType = 'arraybuffer';
this.ws.onopen = onOpen.bind(this);
this.ws.onclose = onClose.bind(this);
this.ws.onmessage = onMessage.bind(this);
this.ws.onerror = onError.bind(this);
} catch(e) {
onError.call(this, e);
}
};
WebSocketInterface.prototype.disconnect = function() {
debug('disconnect()');
if (this.ws) {
// unbind websocket event callbacks
this.ws.onopen = function() {};
this.ws.onclose = function() {};
this.ws.onmessage = function() {};
this.ws.onerror = function() {};
this.ws.close();
this.ws = null;
}
};
WebSocketInterface.prototype.send = function(message) {
debug('send()');
if (this.isConnected()) {
this.ws.send(message);
return true;
} else {
debugerror('unable to send message, WebSocket is not open');
return false;
}
};
WebSocketInterface.prototype.isConnected = function() {
return this.ws && this.ws.readyState === this.ws.OPEN;
};
WebSocketInterface.prototype.isConnecting = function() {
return this.ws && this.ws.readyState === this.ws.CONNECTING;
};
/**
* WebSocket Event Handlers
*/
function onOpen() {
debug('WebSocket ' + this.url + ' connected');
this.onconnect();
}
function onClose(e) {
debug('WebSocket ' + this.url + ' closed');
if (e.wasClean === false) {
debug('WebSocket abrupt disconnection');
}
this.ondisconnect(e.wasClean, e.code, e.reason);
}
function onMessage(e) {
debug('received WebSocket message');
this.ondata(e.data);
}
function onError(e) {
debugerror('WebSocket ' + this.url + ' error: '+ e);
}
},{"./Grammar":6,"debug":34}],27:[function(require,module,exports){
module.exports = sanityCheck;
/**
* Dependencies.
*/
var debug = require('debug')('JsSIP:sanityCheck');
var JsSIP_C = require('./Constants');
var SIPMessage = require('./SIPMessage');
var Utils = require('./Utils');
var message, ua, transport,
requests = [],
responses = [],
all = [];
requests.push(rfc3261_8_2_2_1);
requests.push(rfc3261_16_3_4);
requests.push(rfc3261_18_3_request);
requests.push(rfc3261_8_2_2_2);
responses.push(rfc3261_8_1_3_3);
responses.push(rfc3261_18_3_response);
all.push(minimumHeaders);
function sanityCheck(m, u, t) {
var len, pass;
message = m;
ua = u;
transport = t;
len = all.length;
while(len--) {
pass = all[len](message);
if(pass === false) {
return false;
}
}
if(message instanceof SIPMessage.IncomingRequest) {
len = requests.length;
while(len--) {
pass = requests[len](message);
if(pass === false) {
return false;
}
}
}
else if(message instanceof SIPMessage.IncomingResponse) {
len = responses.length;
while(len--) {
pass = responses[len](message);
if(pass === false) {
return false;
}
}
}
//Everything is OK
return true;
}
/*
* Sanity Check for incoming Messages
*
* Requests:
* - _rfc3261_8_2_2_1_ Receive a Request with a non supported URI scheme
* - _rfc3261_16_3_4_ Receive a Request already sent by us
* Does not look at via sent-by but at jssip_id, which is inserted as
* a prefix in all initial requests generated by the ua
* - _rfc3261_18_3_request_ Body Content-Length
* - _rfc3261_8_2_2_2_ Merged Requests
*
* Responses:
* - _rfc3261_8_1_3_3_ Multiple Via headers
* - _rfc3261_18_3_response_ Body Content-Length
*
* All:
* - Minimum headers in a SIP message
*/
// Sanity Check functions for requests
function rfc3261_8_2_2_1() {
if(message.s('to').uri.scheme !== 'sip') {
reply(416);
return false;
}
}
function rfc3261_16_3_4() {
if(!message.to_tag) {
if(message.call_id.substr(0, 5) === ua.configuration.jssip_id) {
reply(482);
return false;
}
}
}
function rfc3261_18_3_request() {
var len = Utils.str_utf8_length(message.body),
contentLength = message.getHeader('content-length');
if(len < contentLength) {
reply(400);
return false;
}
}
function rfc3261_8_2_2_2() {
var tr, idx,
fromTag = message.from_tag,
call_id = message.call_id,
cseq = message.cseq;
// Accept any in-dialog request.
if(message.to_tag) {
return;
}
// INVITE request.
if (message.method === JsSIP_C.INVITE) {
// If the branch matches the key of any IST then assume it is a retransmission
// and ignore the INVITE.
// TODO: we should reply the last response.
if (ua.transactions.ist[message.via_branch]) {
return false;
}
// Otherwise check whether it is a merged request.
else {
for(idx in ua.transactions.ist) {
tr = ua.transactions.ist[idx];
if(tr.request.from_tag === fromTag && tr.request.call_id === call_id && tr.request.cseq === cseq) {
reply(482);
return false;
}
}
}
}
// Non INVITE request.
else {
// If the branch matches the key of any NIST then assume it is a retransmission
// and ignore the request.
// TODO: we should reply the last response.
if (ua.transactions.nist[message.via_branch]) {
return false;
}
// Otherwise check whether it is a merged request.
else {
for(idx in ua.transactions.nist) {
tr = ua.transactions.nist[idx];
if(tr.request.from_tag === fromTag && tr.request.call_id === call_id && tr.request.cseq === cseq) {
reply(482);
return false;
}
}
}
}
}
// Sanity Check functions for responses
function rfc3261_8_1_3_3() {
if(message.getHeaders('via').length > 1) {
debug('more than one Via header field present in the response, dropping the response');
return false;
}
}
function rfc3261_18_3_response() {
var
len = Utils.str_utf8_length(message.body),
contentLength = message.getHeader('content-length');
if(len < contentLength) {
debug('message body length is lower than the value in Content-Length header field, dropping the response');
return false;
}
}
// Sanity Check functions for requests and responses
function minimumHeaders() {
var
mandatoryHeaders = ['from', 'to', 'call_id', 'cseq', 'via'],
idx = mandatoryHeaders.length;
while(idx--) {
if(!message.hasHeader(mandatoryHeaders[idx])) {
debug('missing mandatory header field : ' + mandatoryHeaders[idx] + ', dropping the response');
return false;
}
}
}
// Reply
function reply(status_code) {
var to,
response = 'SIP/2.0 ' + status_code + ' ' + JsSIP_C.REASON_PHRASE[status_code] + '\r\n',
vias = message.getHeaders('via'),
length = vias.length,
idx = 0;
for(idx; idx < length; idx++) {
response += 'Via: ' + vias[idx] + '\r\n';
}
to = message.getHeader('To');
if(!message.to_tag) {
to += ';tag=' + Utils.newTag();
}
response += 'To: ' + to + '\r\n';
response += 'From: ' + message.getHeader('From') + '\r\n';
response += 'Call-ID: ' + message.call_id + '\r\n';
response += 'CSeq: ' + message.cseq + ' ' + message.method + '\r\n';
response += '\r\n';
transport.send(response);
}
},{"./Constants":1,"./SIPMessage":18,"./Utils":25,"debug":34}],28:[function(require,module,exports){
// 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.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
},{}],29:[function(require,module,exports){
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],30:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
},{}],31:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
},{}],32:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = require('./support/isBuffer');
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = require('inherits');
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"./support/isBuffer":31,"_process":29,"inherits":30}],33:[function(require,module,exports){
/**
* 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 > 10000) {
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'
}
},{}],34:[function(require,module,exports){
(function (process){
/**
* 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 && typeof window.process !== 'undefined' && 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 && 'WebkitAppearance' in document.documentElement.style) ||
// is firebug? http://stackoverflow.com/a/398120/376773
(typeof window !== 'undefined' && window && window.console && (console.firebug || (console.exception && console.table))) ||
// is firefox >= v31?
// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
(typeof navigator !== 'undefined' && navigator && 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 && 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() {
try {
return exports.storage.debug;
} catch(e) {}
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
if (typeof process !== 'undefined' && 'env' in process) {
return process.env.DEBUG;
}
}
/**
* 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) {}
}
}).call(this,require('_process'))
},{"./debug":35,"_process":29}],35:[function(require,module,exports){
/**
* 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);
var split = (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;
}
},{"ms":33}],36:[function(require,module,exports){
var grammar = module.exports = {
v: [{
name: 'version',
reg: /^(\d*)$/
}],
o: [{ //o=- 20518 0 IN IP4 203.0.113.1
// NB: sessionId will be a String in most cases because it is huge
name: 'origin',
reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
format: "%s %s %d %s IP%d %s"
}],
// default parsing of these only (though some of these feel outdated)
s: [{ name: 'name' }],
i: [{ name: 'description' }],
u: [{ name: 'uri' }],
e: [{ name: 'email' }],
p: [{ name: 'phone' }],
z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
//k: [{}], // outdated thing ignored
t: [{ //t=0 0
name: 'timing',
reg: /^(\d*) (\d*)/,
names: ['start', 'stop'],
format: "%d %d"
}],
c: [{ //c=IN IP4 10.47.197.26
name: 'connection',
reg: /^IN IP(\d) (\S*)/,
names: ['version', 'ip'],
format: "IN IP%d %s"
}],
b: [{ //b=AS:4000
push: 'bandwidth',
reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
names: ['type', 'limit'],
format: "%s:%s"
}],
m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
// NB: special - pushes to session
// TODO: rtp/fmtp should be filtered by the payloads found here?
reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
names: ['type', 'port', 'protocol', 'payloads'],
format: "%s %d %s %s"
}],
a: [
{ //a=rtpmap:110 opus/48000/2
push: 'rtp',
reg: /^rtpmap:(\d*) ([\w\-\.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
names: ['payload', 'codec', 'rate', 'encoding'],
format: function (o) {
return (o.encoding) ?
"rtpmap:%d %s/%s/%s":
o.rate ?
"rtpmap:%d %s/%s":
"rtpmap:%d %s";
}
},
{
//a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
//a=fmtp:111 minptime=10; useinbandfec=1
push: 'fmtp',
reg: /^fmtp:(\d*) ([\S| ]*)/,
names: ['payload', 'config'],
format: "fmtp:%d %s"
},
{ //a=control:streamid=0
name: 'control',
reg: /^control:(.*)/,
format: "control:%s"
},
{ //a=rtcp:65179 IN IP4 193.84.77.194
name: 'rtcp',
reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
names: ['port', 'netType', 'ipVer', 'address'],
format: function (o) {
return (o.address != null) ?
"rtcp:%d %s IP%d %s":
"rtcp:%d";
}
},
{ //a=rtcp-fb:98 trr-int 100
push: 'rtcpFbTrrInt',
reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
names: ['payload', 'value'],
format: "rtcp-fb:%d trr-int %d"
},
{ //a=rtcp-fb:98 nack rpsi
push: 'rtcpFb',
reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
names: ['payload', 'type', 'subtype'],
format: function (o) {
return (o.subtype != null) ?
"rtcp-fb:%s %s %s":
"rtcp-fb:%s %s";
}
},
{ //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
//a=extmap:1/recvonly URI-gps-string
push: 'ext',
reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
names: ['value', 'uri', 'config'], // value may include "/direction" suffix
format: function (o) {
return (o.config != null) ?
"extmap:%s %s %s":
"extmap:%s %s";
}
},
{
//a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
push: 'crypto',
reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
names: ['id', 'suite', 'config', 'sessionConfig'],
format: function (o) {
return (o.sessionConfig != null) ?
"crypto:%d %s %s %s":
"crypto:%d %s %s";
}
},
{ //a=setup:actpass
name: 'setup',
reg: /^setup:(\w*)/,
format: "setup:%s"
},
{ //a=mid:1
name: 'mid',
reg: /^mid:([^\s]*)/,
format: "mid:%s"
},
{ //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
name: 'msid',
reg: /^msid:(.*)/,
format: "msid:%s"
},
{ //a=ptime:20
name: 'ptime',
reg: /^ptime:(\d*)/,
format: "ptime:%d"
},
{ //a=maxptime:60
name: 'maxptime',
reg: /^maxptime:(\d*)/,
format: "maxptime:%d"
},
{ //a=sendrecv
name: 'direction',
reg: /^(sendrecv|recvonly|sendonly|inactive)/
},
{ //a=ice-lite
name: 'icelite',
reg: /^(ice-lite)/
},
{ //a=ice-ufrag:F7gI
name: 'iceUfrag',
reg: /^ice-ufrag:(\S*)/,
format: "ice-ufrag:%s"
},
{ //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
name: 'icePwd',
reg: /^ice-pwd:(\S*)/,
format: "ice-pwd:%s"
},
{ //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
name: 'fingerprint',
reg: /^fingerprint:(\S*) (\S*)/,
names: ['type', 'hash'],
format: "fingerprint:%s %s"
},
{
//a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
//a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
//a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
//a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0
//a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0
push:'candidates',
reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,
names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation'],
format: function (o) {
var str = "candidate:%s %d %s %d %s %d typ %s";
str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
// NB: candidate has three optional chunks, so %void middles one if it's missing
str += (o.tcptype != null) ? " tcptype %s" : "%v";
if (o.generation != null) {
str += " generation %d";
}
return str;
}
},
{ //a=end-of-candidates (keep after the candidates line for readability)
name: 'endOfCandidates',
reg: /^(end-of-candidates)/
},
{ //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
name: 'remoteCandidates',
reg: /^remote-candidates:(.*)/,
format: "remote-candidates:%s"
},
{ //a=ice-options:google-ice
name: 'iceOptions',
reg: /^ice-options:(\S*)/,
format: "ice-options:%s"
},
{ //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
push: "ssrcs",
reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
names: ['id', 'attribute', 'value'],
format: "ssrc:%d %s:%s"
},
{ //a=ssrc-group:FEC 1 2
push: "ssrcGroups",
reg: /^ssrc-group:(\w*) (.*)/,
names: ['semantics', 'ssrcs'],
format: "ssrc-group:%s %s"
},
{ //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
name: "msidSemantic",
reg: /^msid-semantic:\s?(\w*) (\S*)/,
names: ['semantic', 'token'],
format: "msid-semantic: %s %s" // space after ":" is not accidental
},
{ //a=group:BUNDLE audio video
push: 'groups',
reg: /^group:(\w*) (.*)/,
names: ['type', 'mids'],
format: "group:%s %s"
},
{ //a=rtcp-mux
name: 'rtcpMux',
reg: /^(rtcp-mux)/
},
{ //a=rtcp-rsize
name: 'rtcpRsize',
reg: /^(rtcp-rsize)/
},
{ //a=sctpmap:5000 webrtc-datachannel 1024
name: 'sctpmap',
reg: /^sctpmap:([\w_\/]*) (\S*)(?: (\S*))?/,
names: ['sctpmapNumber', 'app', 'maxMessageSize'],
format: function (o) {
return (o.maxMessageSize != null) ?
"sctpmap:%s %s %s" :
"sctpmap:%s %s";
}
},
{ // any a= that we don't understand is kepts verbatim on media.invalid
push: 'invalid',
names: ["value"]
}
]
};
// set sensible defaults to avoid polluting the grammar with boring details
Object.keys(grammar).forEach(function (key) {
var objs = grammar[key];
objs.forEach(function (obj) {
if (!obj.reg) {
obj.reg = /(.*)/;
}
if (!obj.format) {
obj.format = "%s";
}
});
});
},{}],37:[function(require,module,exports){
var parser = require('./parser');
var writer = require('./writer');
exports.write = writer;
exports.parse = parser.parse;
exports.parseFmtpConfig = parser.parseFmtpConfig;
exports.parsePayloads = parser.parsePayloads;
exports.parseRemoteCandidates = parser.parseRemoteCandidates;
},{"./parser":38,"./writer":39}],38:[function(require,module,exports){
var toIntIfInt = function (v) {
return String(Number(v)) === v ? Number(v) : v;
};
var attachProperties = function (match, location, names, rawName) {
if (rawName && !names) {
location[rawName] = toIntIfInt(match[1]);
}
else {
for (var i = 0; i < names.length; i += 1) {
if (match[i+1] != null) {
location[names[i]] = toIntIfInt(match[i+1]);
}
}
}
};
var parseReg = function (obj, location, content) {
var needsBlank = obj.name && obj.names;
if (obj.push && !location[obj.push]) {
location[obj.push] = [];
}
else if (needsBlank && !location[obj.name]) {
location[obj.name] = {};
}
var keyLocation = obj.push ?
{} : // blank object that will be pushed
needsBlank ? location[obj.name] : location; // otherwise, named location or root
attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
if (obj.push) {
location[obj.push].push(keyLocation);
}
};
var grammar = require('./grammar');
var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
exports.parse = function (sdp) {
var session = {}
, media = []
, location = session; // points at where properties go under (one of the above)
// parse lines we understand
sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
var type = l[0];
var content = l.slice(2);
if (type === 'm') {
media.push({rtp: [], fmtp: []});
location = media[media.length-1]; // point at latest media line
}
for (var j = 0; j < (grammar[type] || []).length; j += 1) {
var obj = grammar[type][j];
if (obj.reg.test(content)) {
return parseReg(obj, location, content);
}
}
});
session.media = media; // link it up
return session;
};
var fmtpReducer = function (acc, expr) {
var s = expr.split(/=(.+)/, 2);
if (s.length === 2) {
acc[s[0]] = toIntIfInt(s[1]);
}
return acc;
};
exports.parseFmtpConfig = function (str) {
return str.split(/\;\s?/).reduce(fmtpReducer, {});
};
exports.parsePayloads = function (str) {
return str.split(' ').map(Number);
};
exports.parseRemoteCandidates = function (str) {
var candidates = [];
var parts = str.split(' ').map(toIntIfInt);
for (var i = 0; i < parts.length; i += 3) {
candidates.push({
component: parts[i],
ip: parts[i + 1],
port: parts[i + 2]
});
}
return candidates;
};
},{"./grammar":36}],39:[function(require,module,exports){
var grammar = require('./grammar');
// customized util.format - discards excess arguments and can void middle ones
var formatRegExp = /%[sdv%]/g;
var format = function (formatStr) {
var i = 1;
var args = arguments;
var len = args.length;
return formatStr.replace(formatRegExp, function (x) {
if (i >= len) {
return x; // missing argument
}
var arg = args[i];
i += 1;
switch (x) {
case '%%':
return '%';
case '%s':
return String(arg);
case '%d':
return Number(arg);
case '%v':
return '';
}
});
// NB: we discard excess arguments - they are typically undefined from makeLine
};
var makeLine = function (type, obj, location) {
var str = obj.format instanceof Function ?
(obj.format(obj.push ? location : location[obj.name])) :
obj.format;
var args = [type + '=' + str];
if (obj.names) {
for (var i = 0; i < obj.names.length; i += 1) {
var n = obj.names[i];
if (obj.name) {
args.push(location[obj.name][n]);
}
else { // for mLine and push attributes
args.push(location[obj.names[i]]);
}
}
}
else {
args.push(location[obj.name]);
}
return format.apply(null, args);
};
// RFC specified order
// TODO: extend this with all the rest
var defaultOuterOrder = [
'v', 'o', 's', 'i',
'u', 'e', 'p', 'c',
'b', 't', 'r', 'z', 'a'
];
var defaultInnerOrder = ['i', 'c', 'b', 'a'];
module.exports = function (session, opts) {
opts = opts || {};
// ensure certain properties exist
if (session.version == null) {
session.version = 0; // "v=0" must be there (only defined version atm)
}
if (session.name == null) {
session.name = " "; // "s= " must be there if no meaningful name set
}
session.media.forEach(function (mLine) {
if (mLine.payloads == null) {
mLine.payloads = "";
}
});
var outerOrder = opts.outerOrder || defaultOuterOrder;
var innerOrder = opts.innerOrder || defaultInnerOrder;
var sdp = [];
// loop through outerOrder for matching properties on session
outerOrder.forEach(function (type) {
grammar[type].forEach(function (obj) {
if (obj.name in session && session[obj.name] != null) {
sdp.push(makeLine(type, obj, session));
}
else if (obj.push in session && session[obj.push] != null) {
session[obj.push].forEach(function (el) {
sdp.push(makeLine(type, obj, el));
});
}
});
});
// then for each media line, follow the innerOrder
session.media.forEach(function (mLine) {
sdp.push(makeLine('m', grammar.m[0], mLine));
innerOrder.forEach(function (type) {
grammar[type].forEach(function (obj) {
if (obj.name in mLine && mLine[obj.name] != null) {
sdp.push(makeLine(type, obj, mLine));
}
else if (obj.push in mLine && mLine[obj.push] != null) {
mLine[obj.push].forEach(function (el) {
sdp.push(makeLine(type, obj, el));
});
}
});
});
});
return sdp.join('\r\n') + '\r\n';
};
},{"./grammar":36}],40:[function(require,module,exports){
/* eslint-env node */
'use strict';
// SDP helpers.
var SDPUtils = {};
// Generate an alphanumeric identifier for cname or mids.
// TODO: use UUIDs instead? https://gist.github.com/jed/982883
SDPUtils.generateIdentifier = function() {
return Math.random().toString(36).substr(2, 10);
};
// The RTCP CNAME used by all peerconnections from the same JS.
SDPUtils.localCName = SDPUtils.generateIdentifier();
// Splits SDP into lines, dealing with both CRLF and LF.
SDPUtils.splitLines = function(blob) {
return blob.trim().split('\n').map(function(line) {
return line.trim();
});
};
// Splits SDP into sessionpart and mediasections. Ensures CRLF.
SDPUtils.splitSections = function(blob) {
var parts = blob.split('\nm=');
return parts.map(function(part, index) {
return (index > 0 ? 'm=' + part : part).trim() + '\r\n';
});
};
// Returns lines that start with a certain prefix.
SDPUtils.matchPrefix = function(blob, prefix) {
return SDPUtils.splitLines(blob).filter(function(line) {
return line.indexOf(prefix) === 0;
});
};
// Parses an ICE candidate line. Sample input:
// candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8
// rport 55996"
SDPUtils.parseCandidate = function(line) {
var parts;
// Parse both variants.
if (line.indexOf('a=candidate:') === 0) {
parts = line.substring(12).split(' ');
} else {
parts = line.substring(10).split(' ');
}
var candidate = {
foundation: parts[0],
component: parts[1],
protocol: parts[2].toLowerCase(),
priority: parseInt(parts[3], 10),
ip: parts[4],
port: parseInt(parts[5], 10),
// skip parts[6] == 'typ'
type: parts[7]
};
for (var i = 8; i < parts.length; i += 2) {
switch (parts[i]) {
case 'raddr':
candidate.relatedAddress = parts[i + 1];
break;
case 'rport':
candidate.relatedPort = parseInt(parts[i + 1], 10);
break;
case 'tcptype':
candidate.tcpType = parts[i + 1];
break;
default: // Unknown extensions are silently ignored.
break;
}
}
return candidate;
};
// Translates a candidate object into SDP candidate attribute.
SDPUtils.writeCandidate = function(candidate) {
var sdp = [];
sdp.push(candidate.foundation);
sdp.push(candidate.component);
sdp.push(candidate.protocol.toUpperCase());
sdp.push(candidate.priority);
sdp.push(candidate.ip);
sdp.push(candidate.port);
var type = candidate.type;
sdp.push('typ');
sdp.push(type);
if (type !== 'host' && candidate.relatedAddress &&
candidate.relatedPort) {
sdp.push('raddr');
sdp.push(candidate.relatedAddress); // was: relAddr
sdp.push('rport');
sdp.push(candidate.relatedPort); // was: relPort
}
if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') {
sdp.push('tcptype');
sdp.push(candidate.tcpType);
}
return 'candidate:' + sdp.join(' ');
};
// Parses an rtpmap line, returns RTCRtpCoddecParameters. Sample input:
// a=rtpmap:111 opus/48000/2
SDPUtils.parseRtpMap = function(line) {
var parts = line.substr(9).split(' ');
var parsed = {
payloadType: parseInt(parts.shift(), 10) // was: id
};
parts = parts[0].split('/');
parsed.name = parts[0];
parsed.clockRate = parseInt(parts[1], 10); // was: clockrate
// was: channels
parsed.numChannels = parts.length === 3 ? parseInt(parts[2], 10) : 1;
return parsed;
};
// Generate an a=rtpmap line from RTCRtpCodecCapability or
// RTCRtpCodecParameters.
SDPUtils.writeRtpMap = function(codec) {
var pt = codec.payloadType;
if (codec.preferredPayloadType !== undefined) {
pt = codec.preferredPayloadType;
}
return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate +
(codec.numChannels !== 1 ? '/' + codec.numChannels : '') + '\r\n';
};
// Parses an a=extmap line (headerextension from RFC 5285). Sample input:
// a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
SDPUtils.parseExtmap = function(line) {
var parts = line.substr(9).split(' ');
return {
id: parseInt(parts[0], 10),
uri: parts[1]
};
};
// Generates a=extmap line from RTCRtpHeaderExtensionParameters or
// RTCRtpHeaderExtension.
SDPUtils.writeExtmap = function(headerExtension) {
return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) +
' ' + headerExtension.uri + '\r\n';
};
// Parses an ftmp line, returns dictionary. Sample input:
// a=fmtp:96 vbr=on;cng=on
// Also deals with vbr=on; cng=on
SDPUtils.parseFmtp = function(line) {
var parsed = {};
var kv;
var parts = line.substr(line.indexOf(' ') + 1).split(';');
for (var j = 0; j < parts.length; j++) {
kv = parts[j].trim().split('=');
parsed[kv[0].trim()] = kv[1];
}
return parsed;
};
// Generates an a=ftmp line from RTCRtpCodecCapability or RTCRtpCodecParameters.
SDPUtils.writeFmtp = function(codec) {
var line = '';
var pt = codec.payloadType;
if (codec.preferredPayloadType !== undefined) {
pt = codec.preferredPayloadType;
}
if (codec.parameters && Object.keys(codec.parameters).length) {
var params = [];
Object.keys(codec.parameters).forEach(function(param) {
params.push(param + '=' + codec.parameters[param]);
});
line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\r\n';
}
return line;
};
// Parses an rtcp-fb line, returns RTCPRtcpFeedback object. Sample input:
// a=rtcp-fb:98 nack rpsi
SDPUtils.parseRtcpFb = function(line) {
var parts = line.substr(line.indexOf(' ') + 1).split(' ');
return {
type: parts.shift(),
parameter: parts.join(' ')
};
};
// Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters.
SDPUtils.writeRtcpFb = function(codec) {
var lines = '';
var pt = codec.payloadType;
if (codec.preferredPayloadType !== undefined) {
pt = codec.preferredPayloadType;
}
if (codec.rtcpFeedback && codec.rtcpFeedback.length) {
// FIXME: special handling for trr-int?
codec.rtcpFeedback.forEach(function(fb) {
lines += 'a=rtcp-fb:' + pt + ' ' + fb.type +
(fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') +
'\r\n';
});
}
return lines;
};
// Parses an RFC 5576 ssrc media attribute. Sample input:
// a=ssrc:3735928559 cname:something
SDPUtils.parseSsrcMedia = function(line) {
var sp = line.indexOf(' ');
var parts = {
ssrc: parseInt(line.substr(7, sp - 7), 10)
};
var colon = line.indexOf(':', sp);
if (colon > -1) {
parts.attribute = line.substr(sp + 1, colon - sp - 1);
parts.value = line.substr(colon + 1);
} else {
parts.attribute = line.substr(sp + 1);
}
return parts;
};
// Extracts DTLS parameters from SDP media section or sessionpart.
// FIXME: for consistency with other functions this should only
// get the fingerprint line as input. See also getIceParameters.
SDPUtils.getDtlsParameters = function(mediaSection, sessionpart) {
var lines = SDPUtils.splitLines(mediaSection);
// Search in session part, too.
lines = lines.concat(SDPUtils.splitLines(sessionpart));
var fpLine = lines.filter(function(line) {
return line.indexOf('a=fingerprint:') === 0;
})[0].substr(14);
// Note: a=setup line is ignored since we use the 'auto' role.
var dtlsParameters = {
role: 'auto',
fingerprints: [{
algorithm: fpLine.split(' ')[0],
value: fpLine.split(' ')[1]
}]
};
return dtlsParameters;
};
// Serializes DTLS parameters to SDP.
SDPUtils.writeDtlsParameters = function(params, setupType) {
var sdp = 'a=setup:' + setupType + '\r\n';
params.fingerprints.forEach(function(fp) {
sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n';
});
return sdp;
};
// Parses ICE information from SDP media section or sessionpart.
// FIXME: for consistency with other functions this should only
// get the ice-ufrag and ice-pwd lines as input.
SDPUtils.getIceParameters = function(mediaSection, sessionpart) {
var lines = SDPUtils.splitLines(mediaSection);
// Search in session part, too.
lines = lines.concat(SDPUtils.splitLines(sessionpart));
var iceParameters = {
usernameFragment: lines.filter(function(line) {
return line.indexOf('a=ice-ufrag:') === 0;
})[0].substr(12),
password: lines.filter(function(line) {
return line.indexOf('a=ice-pwd:') === 0;
})[0].substr(10)
};
return iceParameters;
};
// Serializes ICE parameters to SDP.
SDPUtils.writeIceParameters = function(params) {
return 'a=ice-ufrag:' + params.usernameFragment + '\r\n' +
'a=ice-pwd:' + params.password + '\r\n';
};
// Parses the SDP media section and returns RTCRtpParameters.
SDPUtils.parseRtpParameters = function(mediaSection) {
var description = {
codecs: [],
headerExtensions: [],
fecMechanisms: [],
rtcp: []
};
var lines = SDPUtils.splitLines(mediaSection);
var mline = lines[0].split(' ');
for (var i = 3; i < mline.length; i++) { // find all codecs from mline[3..]
var pt = mline[i];
var rtpmapline = SDPUtils.matchPrefix(
mediaSection, 'a=rtpmap:' + pt + ' ')[0];
if (rtpmapline) {
var codec = SDPUtils.parseRtpMap(rtpmapline);
var fmtps = SDPUtils.matchPrefix(
mediaSection, 'a=fmtp:' + pt + ' ');
// Only the first a=fmtp:<pt> is considered.
codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {};
codec.rtcpFeedback = SDPUtils.matchPrefix(
mediaSection, 'a=rtcp-fb:' + pt + ' ')
.map(SDPUtils.parseRtcpFb);
description.codecs.push(codec);
// parse FEC mechanisms from rtpmap lines.
switch (codec.name.toUpperCase()) {
case 'RED':
case 'ULPFEC':
description.fecMechanisms.push(codec.name.toUpperCase());
break;
default: // only RED and ULPFEC are recognized as FEC mechanisms.
break;
}
}
}
SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(function(line) {
description.headerExtensions.push(SDPUtils.parseExtmap(line));
});
// FIXME: parse rtcp.
return description;
};
// Generates parts of the SDP media section describing the capabilities /
// parameters.
SDPUtils.writeRtpDescription = function(kind, caps) {
var sdp = '';
// Build the mline.
sdp += 'm=' + kind + ' ';
sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs.
sdp += ' UDP/TLS/RTP/SAVPF ';
sdp += caps.codecs.map(function(codec) {
if (codec.preferredPayloadType !== undefined) {
return codec.preferredPayloadType;
}
return codec.payloadType;
}).join(' ') + '\r\n';
sdp += 'c=IN IP4 0.0.0.0\r\n';
sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n';
// Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb.
caps.codecs.forEach(function(codec) {
sdp += SDPUtils.writeRtpMap(codec);
sdp += SDPUtils.writeFmtp(codec);
sdp += SDPUtils.writeRtcpFb(codec);
});
sdp += 'a=rtcp-mux\r\n';
caps.headerExtensions.forEach(function(extension) {
sdp += SDPUtils.writeExtmap(extension);
});
// FIXME: write fecMechanisms.
return sdp;
};
// Parses the SDP media section and returns an array of
// RTCRtpEncodingParameters.
SDPUtils.parseRtpEncodingParameters = function(mediaSection) {
var encodingParameters = [];
var description = SDPUtils.parseRtpParameters(mediaSection);
var hasRed = description.fecMechanisms.indexOf('RED') !== -1;
var hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1;
// filter a=ssrc:... cname:, ignore PlanB-msid
var ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
.map(function(line) {
return SDPUtils.parseSsrcMedia(line);
})
.filter(function(parts) {
return parts.attribute === 'cname';
});
var primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc;
var secondarySsrc;
var flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID')
.map(function(line) {
var parts = line.split(' ');
parts.shift();
return parts.map(function(part) {
return parseInt(part, 10);
});
});
if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) {
secondarySsrc = flows[0][1];
}
description.codecs.forEach(function(codec) {
if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) {
var encParam = {
ssrc: primarySsrc,
codecPayloadType: parseInt(codec.parameters.apt, 10),
rtx: {
payloadType: codec.payloadType,
ssrc: secondarySsrc
}
};
encodingParameters.push(encParam);
if (hasRed) {
encParam = JSON.parse(JSON.stringify(encParam));
encParam.fec = {
ssrc: secondarySsrc,
mechanism: hasUlpfec ? 'red+ulpfec' : 'red'
};
encodingParameters.push(encParam);
}
}
});
if (encodingParameters.length === 0 && primarySsrc) {
encodingParameters.push({
ssrc: primarySsrc
});
}
// we support both b=AS and b=TIAS but interpret AS as TIAS.
var bandwidth = SDPUtils.matchPrefix(mediaSection, 'b=');
if (bandwidth.length) {
if (bandwidth[0].indexOf('b=TIAS:') === 0) {
bandwidth = parseInt(bandwidth[0].substr(7), 10);
} else if (bandwidth[0].indexOf('b=AS:') === 0) {
bandwidth = parseInt(bandwidth[0].substr(5), 10);
}
encodingParameters.forEach(function(params) {
params.maxBitrate = bandwidth;
});
}
return encodingParameters;
};
SDPUtils.writeSessionBoilerplate = function() {
// FIXME: sess-id should be an NTP timestamp.
return 'v=0\r\n' +
'o=thisisadapterortc 8169639915646943137 2 IN IP4 127.0.0.1\r\n' +
's=-\r\n' +
't=0 0\r\n';
};
SDPUtils.writeMediaSection = function(transceiver, caps, type, stream) {
var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps);
// Map ICE parameters (ufrag, pwd) to SDP.
sdp += SDPUtils.writeIceParameters(
transceiver.iceGatherer.getLocalParameters());
// Map DTLS parameters to SDP.
sdp += SDPUtils.writeDtlsParameters(
transceiver.dtlsTransport.getLocalParameters(),
type === 'offer' ? 'actpass' : 'active');
sdp += 'a=mid:' + transceiver.mid + '\r\n';
if (transceiver.rtpSender && transceiver.rtpReceiver) {
sdp += 'a=sendrecv\r\n';
} else if (transceiver.rtpSender) {
sdp += 'a=sendonly\r\n';
} else if (transceiver.rtpReceiver) {
sdp += 'a=recvonly\r\n';
} else {
sdp += 'a=inactive\r\n';
}
// FIXME: for RTX there might be multiple SSRCs. Not implemented in Edge yet.
if (transceiver.rtpSender) {
var msid = 'msid:' + stream.id + ' ' +
transceiver.rtpSender.track.id + '\r\n';
sdp += 'a=' + msid;
sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
' ' + msid;
}
// FIXME: this should be written by writeRtpDescription.
sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
' cname:' + SDPUtils.localCName + '\r\n';
return sdp;
};
// Gets the direction from the mediaSection or the sessionpart.
SDPUtils.getDirection = function(mediaSection, sessionpart) {
// Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv.
var lines = SDPUtils.splitLines(mediaSection);
for (var i = 0; i < lines.length; i++) {
switch (lines[i]) {
case 'a=sendrecv':
case 'a=sendonly':
case 'a=recvonly':
case 'a=inactive':
return lines[i].substr(2);
default:
// FIXME: What should happen here?
}
}
if (sessionpart) {
return SDPUtils.getDirection(sessionpart);
}
return 'sendrecv';
};
// Expose public methods.
module.exports = SDPUtils;
},{}],41:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
// Shimming starts here.
(function() {
// Utils.
var logging = require('./utils').log;
var browserDetails = require('./utils').browserDetails;
// Export to the adapter global object visible in the browser.
module.exports.browserDetails = browserDetails;
module.exports.extractVersion = require('./utils').extractVersion;
module.exports.disableLog = require('./utils').disableLog;
// Uncomment the line below if you want logging to occur, including logging
// for the switch statement below. Can also be turned on in the browser via
// adapter.disableLog(false), but then logging from the switch statement below
// will not appear.
// require('./utils').disableLog(false);
// Browser shims.
var chromeShim = require('./chrome/chrome_shim') || null;
var edgeShim = require('./edge/edge_shim') || null;
var firefoxShim = require('./firefox/firefox_shim') || null;
var safariShim = require('./safari/safari_shim') || null;
// Shim browser if found.
switch (browserDetails.browser) {
case 'opera': // fallthrough as it uses chrome shims
case 'chrome':
if (!chromeShim || !chromeShim.shimPeerConnection) {
logging('Chrome shim is not included in this adapter release.');
return;
}
logging('adapter.js shimming chrome.');
// Export to the adapter global object visible in the browser.
module.exports.browserShim = chromeShim;
chromeShim.shimGetUserMedia();
chromeShim.shimMediaStream();
chromeShim.shimSourceObject();
chromeShim.shimPeerConnection();
chromeShim.shimOnTrack();
break;
case 'firefox':
if (!firefoxShim || !firefoxShim.shimPeerConnection) {
logging('Firefox shim is not included in this adapter release.');
return;
}
logging('adapter.js shimming firefox.');
// Export to the adapter global object visible in the browser.
module.exports.browserShim = firefoxShim;
firefoxShim.shimGetUserMedia();
firefoxShim.shimSourceObject();
firefoxShim.shimPeerConnection();
firefoxShim.shimOnTrack();
break;
case 'edge':
if (!edgeShim || !edgeShim.shimPeerConnection) {
logging('MS edge shim is not included in this adapter release.');
return;
}
logging('adapter.js shimming edge.');
// Export to the adapter global object visible in the browser.
module.exports.browserShim = edgeShim;
edgeShim.shimGetUserMedia();
edgeShim.shimPeerConnection();
break;
case 'safari':
if (!safariShim) {
logging('Safari shim is not included in this adapter release.');
return;
}
logging('adapter.js shimming safari.');
// Export to the adapter global object visible in the browser.
module.exports.browserShim = safariShim;
safariShim.shimGetUserMedia();
break;
default:
logging('Unsupported browser!');
}
})();
},{"./chrome/chrome_shim":42,"./edge/edge_shim":44,"./firefox/firefox_shim":46,"./safari/safari_shim":48,"./utils":49}],42:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var logging = require('../utils.js').log;
var browserDetails = require('../utils.js').browserDetails;
var chromeShim = {
shimMediaStream: function() {
window.MediaStream = window.MediaStream || window.webkitMediaStream;
},
shimOnTrack: function() {
if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
window.RTCPeerConnection.prototype)) {
Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
get: function() {
return this._ontrack;
},
set: function(f) {
var self = this;
if (this._ontrack) {
this.removeEventListener('track', this._ontrack);
this.removeEventListener('addstream', this._ontrackpoly);
}
this.addEventListener('track', this._ontrack = f);
this.addEventListener('addstream', this._ontrackpoly = function(e) {
// onaddstream does not fire when a track is added to an existing
// stream. But stream.onaddtrack is implemented so we use that.
e.stream.addEventListener('addtrack', function(te) {
var event = new Event('track');
event.track = te.track;
event.receiver = {track: te.track};
event.streams = [e.stream];
self.dispatchEvent(event);
});
e.stream.getTracks().forEach(function(track) {
var event = new Event('track');
event.track = track;
event.receiver = {track: track};
event.streams = [e.stream];
this.dispatchEvent(event);
}.bind(this));
}.bind(this));
}
});
}
},
shimSourceObject: function() {
if (typeof window === 'object') {
if (window.HTMLMediaElement &&
!('srcObject' in window.HTMLMediaElement.prototype)) {
// Shim the srcObject property, once, when HTMLMediaElement is found.
Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', {
get: function() {
return this._srcObject;
},
set: function(stream) {
var self = this;
// Use _srcObject as a private property for this shim
this._srcObject = stream;
if (this.src) {
URL.revokeObjectURL(this.src);
}
if (!stream) {
this.src = '';
return;
}
this.src = URL.createObjectURL(stream);
// We need to recreate the blob url when a track is added or
// removed. Doing it manually since we want to avoid a recursion.
stream.addEventListener('addtrack', function() {
if (self.src) {
URL.revokeObjectURL(self.src);
}
self.src = URL.createObjectURL(stream);
});
stream.addEventListener('removetrack', function() {
if (self.src) {
URL.revokeObjectURL(self.src);
}
self.src = URL.createObjectURL(stream);
});
}
});
}
}
},
shimPeerConnection: function() {
// The RTCPeerConnection object.
window.RTCPeerConnection = function(pcConfig, pcConstraints) {
// Translate iceTransportPolicy to iceTransports,
// see https://code.google.com/p/webrtc/issues/detail?id=4869
logging('PeerConnection');
if (pcConfig && pcConfig.iceTransportPolicy) {
pcConfig.iceTransports = pcConfig.iceTransportPolicy;
}
var pc = new webkitRTCPeerConnection(pcConfig, pcConstraints);
var origGetStats = pc.getStats.bind(pc);
pc.getStats = function(selector, successCallback, errorCallback) {
var self = this;
var args = arguments;
// If selector is a function then we are in the old style stats so just
// pass back the original getStats format to avoid breaking old users.
if (arguments.length > 0 && typeof selector === 'function') {
return origGetStats(selector, successCallback);
}
var fixChromeStats_ = function(response) {
var standardReport = {};
var reports = response.result();
reports.forEach(function(report) {
var standardStats = {
id: report.id,
timestamp: report.timestamp,
type: report.type
};
report.names().forEach(function(name) {
standardStats[name] = report.stat(name);
});
standardReport[standardStats.id] = standardStats;
});
return standardReport;
};
// shim getStats with maplike support
var makeMapStats = function(stats, legacyStats) {
var map = new Map(Object.keys(stats).map(function(key) {
return[key, stats[key]];
}));
legacyStats = legacyStats || stats;
Object.keys(legacyStats).forEach(function(key) {
map[key] = legacyStats[key];
});
return map;
};
if (arguments.length >= 2) {
var successCallbackWrapper_ = function(response) {
args[1](makeMapStats(fixChromeStats_(response)));
};
return origGetStats.apply(this, [successCallbackWrapper_,
arguments[0]]);
}
// promise-support
return new Promise(function(resolve, reject) {
if (args.length === 1 && typeof selector === 'object') {
origGetStats.apply(self, [
function(response) {
resolve(makeMapStats(fixChromeStats_(response)));
}, reject]);
} else {
// Preserve legacy chrome stats only on legacy access of stats obj
origGetStats.apply(self, [
function(response) {
resolve(makeMapStats(fixChromeStats_(response),
response.result()));
}, reject]);
}
}).then(successCallback, errorCallback);
};
return pc;
};
window.RTCPeerConnection.prototype = webkitRTCPeerConnection.prototype;
// wrap static methods. Currently just generateCertificate.
if (webkitRTCPeerConnection.generateCertificate) {
Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
get: function() {
return webkitRTCPeerConnection.generateCertificate;
}
});
}
['createOffer', 'createAnswer'].forEach(function(method) {
var nativeMethod = webkitRTCPeerConnection.prototype[method];
webkitRTCPeerConnection.prototype[method] = function() {
var self = this;
if (arguments.length < 1 || (arguments.length === 1 &&
typeof arguments[0] === 'object')) {
var opts = arguments.length === 1 ? arguments[0] : undefined;
return new Promise(function(resolve, reject) {
nativeMethod.apply(self, [resolve, reject, opts]);
});
}
return nativeMethod.apply(this, arguments);
};
});
// add promise support -- natively available in Chrome 51
if (browserDetails.version < 51) {
['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
.forEach(function(method) {
var nativeMethod = webkitRTCPeerConnection.prototype[method];
webkitRTCPeerConnection.prototype[method] = function() {
var args = arguments;
var self = this;
var promise = new Promise(function(resolve, reject) {
nativeMethod.apply(self, [args[0], resolve, reject]);
});
if (args.length < 2) {
return promise;
}
return promise.then(function() {
args[1].apply(null, []);
},
function(err) {
if (args.length >= 3) {
args[2].apply(null, [err]);
}
});
};
});
}
// shim implicit creation of RTCSessionDescription/RTCIceCandidate
['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
.forEach(function(method) {
var nativeMethod = webkitRTCPeerConnection.prototype[method];
webkitRTCPeerConnection.prototype[method] = function() {
arguments[0] = new ((method === 'addIceCandidate') ?
RTCIceCandidate : RTCSessionDescription)(arguments[0]);
return nativeMethod.apply(this, arguments);
};
});
// support for addIceCandidate(null or undefined)
var nativeAddIceCandidate =
RTCPeerConnection.prototype.addIceCandidate;
RTCPeerConnection.prototype.addIceCandidate = function() {
if (!arguments[0]) {
if (arguments[1]) {
arguments[1].apply(null);
}
return Promise.resolve();
}
return nativeAddIceCandidate.apply(this, arguments);
};
}
};
// Expose public methods.
module.exports = {
shimMediaStream: chromeShim.shimMediaStream,
shimOnTrack: chromeShim.shimOnTrack,
shimSourceObject: chromeShim.shimSourceObject,
shimPeerConnection: chromeShim.shimPeerConnection,
shimGetUserMedia: require('./getusermedia')
};
},{"../utils.js":49,"./getusermedia":43}],43:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var logging = require('../utils.js').log;
// Expose public methods.
module.exports = function() {
var constraintsToChrome_ = function(c) {
if (typeof c !== 'object' || c.mandatory || c.optional) {
return c;
}
var cc = {};
Object.keys(c).forEach(function(key) {
if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
return;
}
var r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]};
if (r.exact !== undefined && typeof r.exact === 'number') {
r.min = r.max = r.exact;
}
var oldname_ = function(prefix, name) {
if (prefix) {
return prefix + name.charAt(0).toUpperCase() + name.slice(1);
}
return (name === 'deviceId') ? 'sourceId' : name;
};
if (r.ideal !== undefined) {
cc.optional = cc.optional || [];
var oc = {};
if (typeof r.ideal === 'number') {
oc[oldname_('min', key)] = r.ideal;
cc.optional.push(oc);
oc = {};
oc[oldname_('max', key)] = r.ideal;
cc.optional.push(oc);
} else {
oc[oldname_('', key)] = r.ideal;
cc.optional.push(oc);
}
}
if (r.exact !== undefined && typeof r.exact !== 'number') {
cc.mandatory = cc.mandatory || {};
cc.mandatory[oldname_('', key)] = r.exact;
} else {
['min', 'max'].forEach(function(mix) {
if (r[mix] !== undefined) {
cc.mandatory = cc.mandatory || {};
cc.mandatory[oldname_(mix, key)] = r[mix];
}
});
}
});
if (c.advanced) {
cc.optional = (cc.optional || []).concat(c.advanced);
}
return cc;
};
var shimConstraints_ = function(constraints, func) {
constraints = JSON.parse(JSON.stringify(constraints));
if (constraints && constraints.audio) {
constraints.audio = constraintsToChrome_(constraints.audio);
}
if (constraints && typeof constraints.video === 'object') {
// Shim facingMode for mobile, where it defaults to "user".
var face = constraints.video.facingMode;
face = face && ((typeof face === 'object') ? face : {ideal: face});
if ((face && (face.exact === 'user' || face.exact === 'environment' ||
face.ideal === 'user' || face.ideal === 'environment')) &&
!(navigator.mediaDevices.getSupportedConstraints &&
navigator.mediaDevices.getSupportedConstraints().facingMode)) {
delete constraints.video.facingMode;
if (face.exact === 'environment' || face.ideal === 'environment') {
// Look for "back" in label, or use last cam (typically back cam).
return navigator.mediaDevices.enumerateDevices()
.then(function(devices) {
devices = devices.filter(function(d) {
return d.kind === 'videoinput';
});
var back = devices.find(function(d) {
return d.label.toLowerCase().indexOf('back') !== -1;
}) || (devices.length && devices[devices.length - 1]);
if (back) {
constraints.video.deviceId = face.exact ? {exact: back.deviceId} :
{ideal: back.deviceId};
}
constraints.video = constraintsToChrome_(constraints.video);
logging('chrome: ' + JSON.stringify(constraints));
return func(constraints);
});
}
}
constraints.video = constraintsToChrome_(constraints.video);
}
logging('chrome: ' + JSON.stringify(constraints));
return func(constraints);
};
var shimError_ = function(e) {
return {
name: {
PermissionDeniedError: 'NotAllowedError',
ConstraintNotSatisfiedError: 'OverconstrainedError'
}[e.name] || e.name,
message: e.message,
constraint: e.constraintName,
toString: function() {
return this.name + (this.message && ': ') + this.message;
}
};
};
var getUserMedia_ = function(constraints, onSuccess, onError) {
shimConstraints_(constraints, function(c) {
navigator.webkitGetUserMedia(c, onSuccess, function(e) {
onError(shimError_(e));
});
});
};
navigator.getUserMedia = getUserMedia_;
// Returns the result of getUserMedia as a Promise.
var getUserMediaPromise_ = function(constraints) {
return new Promise(function(resolve, reject) {
navigator.getUserMedia(constraints, resolve, reject);
});
};
if (!navigator.mediaDevices) {
navigator.mediaDevices = {
getUserMedia: getUserMediaPromise_,
enumerateDevices: function() {
return new Promise(function(resolve) {
var kinds = {audio: 'audioinput', video: 'videoinput'};
return MediaStreamTrack.getSources(function(devices) {
resolve(devices.map(function(device) {
return {label: device.label,
kind: kinds[device.kind],
deviceId: device.id,
groupId: ''};
}));
});
});
}
};
}
// A shim for getUserMedia method on the mediaDevices object.
// TODO(KaptenJansson) remove once implemented in Chrome stable.
if (!navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia = function(constraints) {
return getUserMediaPromise_(constraints);
};
} else {
// Even though Chrome 45 has navigator.mediaDevices and a getUserMedia
// function which returns a Promise, it does not accept spec-style
// constraints.
var origGetUserMedia = navigator.mediaDevices.getUserMedia.
bind(navigator.mediaDevices);
navigator.mediaDevices.getUserMedia = function(cs) {
return shimConstraints_(cs, function(c) {
return origGetUserMedia(c).then(function(stream) {
if (c.audio && !stream.getAudioTracks().length ||
c.video && !stream.getVideoTracks().length) {
stream.getTracks().forEach(function(track) {
track.stop();
});
throw new DOMException('', 'NotFoundError');
}
return stream;
}, function(e) {
return Promise.reject(shimError_(e));
});
});
};
}
// Dummy devicechange event methods.
// TODO(KaptenJansson) remove once implemented in Chrome stable.
if (typeof navigator.mediaDevices.addEventListener === 'undefined') {
navigator.mediaDevices.addEventListener = function() {
logging('Dummy mediaDevices.addEventListener called.');
};
}
if (typeof navigator.mediaDevices.removeEventListener === 'undefined') {
navigator.mediaDevices.removeEventListener = function() {
logging('Dummy mediaDevices.removeEventListener called.');
};
}
};
},{"../utils.js":49}],44:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var SDPUtils = require('sdp');
var browserDetails = require('../utils').browserDetails;
var edgeShim = {
shimPeerConnection: function() {
if (window.RTCIceGatherer) {
// ORTC defines an RTCIceCandidate object but no constructor.
// Not implemented in Edge.
if (!window.RTCIceCandidate) {
window.RTCIceCandidate = function(args) {
return args;
};
}
// ORTC does not have a session description object but
// other browsers (i.e. Chrome) that will support both PC and ORTC
// in the future might have this defined already.
if (!window.RTCSessionDescription) {
window.RTCSessionDescription = function(args) {
return args;
};
}
// this adds an additional event listener to MediaStrackTrack that signals
// when a tracks enabled property was changed.
var origMSTEnabled = Object.getOwnPropertyDescriptor(
MediaStreamTrack.prototype, 'enabled');
Object.defineProperty(MediaStreamTrack.prototype, 'enabled', {
set: function(value) {
origMSTEnabled.set.call(this, value);
var ev = new Event('enabled');
ev.enabled = value;
this.dispatchEvent(ev);
}
});
}
window.RTCPeerConnection = function(config) {
var self = this;
var _eventTarget = document.createDocumentFragment();
['addEventListener', 'removeEventListener', 'dispatchEvent']
.forEach(function(method) {
self[method] = _eventTarget[method].bind(_eventTarget);
});
this.onicecandidate = null;
this.onaddstream = null;
this.ontrack = null;
this.onremovestream = null;
this.onsignalingstatechange = null;
this.oniceconnectionstatechange = null;
this.onnegotiationneeded = null;
this.ondatachannel = null;
this.localStreams = [];
this.remoteStreams = [];
this.getLocalStreams = function() {
return self.localStreams;
};
this.getRemoteStreams = function() {
return self.remoteStreams;
};
this.localDescription = new RTCSessionDescription({
type: '',
sdp: ''
});
this.remoteDescription = new RTCSessionDescription({
type: '',
sdp: ''
});
this.signalingState = 'stable';
this.iceConnectionState = 'new';
this.iceGatheringState = 'new';
this.iceOptions = {
gatherPolicy: 'all',
iceServers: []
};
if (config && config.iceTransportPolicy) {
switch (config.iceTransportPolicy) {
case 'all':
case 'relay':
this.iceOptions.gatherPolicy = config.iceTransportPolicy;
break;
case 'none':
// FIXME: remove once implementation and spec have added this.
throw new TypeError('iceTransportPolicy "none" not supported');
default:
// don't set iceTransportPolicy.
break;
}
}
this.usingBundle = config && config.bundlePolicy === 'max-bundle';
if (config && config.iceServers) {
// Edge does not like
// 1) stun:
// 2) turn: that does not have all of turn:host:port?transport=udp
// 3) turn: with ipv6 addresses
var iceServers = JSON.parse(JSON.stringify(config.iceServers));
this.iceOptions.iceServers = iceServers.filter(function(server) {
if (server && server.urls) {
var urls = server.urls;
if (typeof urls === 'string') {
urls = [urls];
}
urls = urls.filter(function(url) {
return (url.indexOf('turn:') === 0 &&
url.indexOf('transport=udp') !== -1 &&
url.indexOf('turn:[') === -1) ||
(url.indexOf('stun:') === 0 &&
browserDetails.version >= 14393);
})[0];
return !!urls;
}
return false;
});
}
this._config = config;
// per-track iceGathers, iceTransports, dtlsTransports, rtpSenders, ...
// everything that is needed to describe a SDP m-line.
this.transceivers = [];
// since the iceGatherer is currently created in createOffer but we
// must not emit candidates until after setLocalDescription we buffer
// them in this array.
this._localIceCandidatesBuffer = [];
};
window.RTCPeerConnection.prototype._emitBufferedCandidates = function() {
var self = this;
var sections = SDPUtils.splitSections(self.localDescription.sdp);
// FIXME: need to apply ice candidates in a way which is async but
// in-order
this._localIceCandidatesBuffer.forEach(function(event) {
var end = !event.candidate || Object.keys(event.candidate).length === 0;
if (end) {
for (var j = 1; j < sections.length; j++) {
if (sections[j].indexOf('\r\na=end-of-candidates\r\n') === -1) {
sections[j] += 'a=end-of-candidates\r\n';
}
}
} else if (event.candidate.candidate.indexOf('typ endOfCandidates')
=== -1) {
sections[event.candidate.sdpMLineIndex + 1] +=
'a=' + event.candidate.candidate + '\r\n';
}
self.localDescription.sdp = sections.join('');
self.dispatchEvent(event);
if (self.onicecandidate !== null) {
self.onicecandidate(event);
}
if (!event.candidate && self.iceGatheringState !== 'complete') {
var complete = self.transceivers.every(function(transceiver) {
return transceiver.iceGatherer &&
transceiver.iceGatherer.state === 'completed';
});
if (complete) {
self.iceGatheringState = 'complete';
}
}
});
this._localIceCandidatesBuffer = [];
};
window.RTCPeerConnection.prototype.getConfiguration = function() {
return this._config;
};
window.RTCPeerConnection.prototype.addStream = function(stream) {
// Clone is necessary for local demos mostly, attaching directly
// to two different senders does not work (build 10547).
var clonedStream = stream.clone();
stream.getTracks().forEach(function(track, idx) {
var clonedTrack = clonedStream.getTracks()[idx];
track.addEventListener('enabled', function(event) {
clonedTrack.enabled = event.enabled;
});
});
this.localStreams.push(clonedStream);
this._maybeFireNegotiationNeeded();
};
window.RTCPeerConnection.prototype.removeStream = function(stream) {
var idx = this.localStreams.indexOf(stream);
if (idx > -1) {
this.localStreams.splice(idx, 1);
this._maybeFireNegotiationNeeded();
}
};
window.RTCPeerConnection.prototype.getSenders = function() {
return this.transceivers.filter(function(transceiver) {
return !!transceiver.rtpSender;
})
.map(function(transceiver) {
return transceiver.rtpSender;
});
};
window.RTCPeerConnection.prototype.getReceivers = function() {
return this.transceivers.filter(function(transceiver) {
return !!transceiver.rtpReceiver;
})
.map(function(transceiver) {
return transceiver.rtpReceiver;
});
};
// Determines the intersection of local and remote capabilities.
window.RTCPeerConnection.prototype._getCommonCapabilities =
function(localCapabilities, remoteCapabilities) {
var commonCapabilities = {
codecs: [],
headerExtensions: [],
fecMechanisms: []
};
localCapabilities.codecs.forEach(function(lCodec) {
for (var i = 0; i < remoteCapabilities.codecs.length; i++) {
var rCodec = remoteCapabilities.codecs[i];
if (lCodec.name.toLowerCase() === rCodec.name.toLowerCase() &&
lCodec.clockRate === rCodec.clockRate) {
// number of channels is the highest common number of channels
rCodec.numChannels = Math.min(lCodec.numChannels,
rCodec.numChannels);
// push rCodec so we reply with offerer payload type
commonCapabilities.codecs.push(rCodec);
// determine common feedback mechanisms
rCodec.rtcpFeedback = rCodec.rtcpFeedback.filter(function(fb) {
for (var j = 0; j < lCodec.rtcpFeedback.length; j++) {
if (lCodec.rtcpFeedback[j].type === fb.type &&
lCodec.rtcpFeedback[j].parameter === fb.parameter) {
return true;
}
}
return false;
});
// FIXME: also need to determine .parameters
// see https://github.com/openpeer/ortc/issues/569
break;
}
}
});
localCapabilities.headerExtensions
.forEach(function(lHeaderExtension) {
for (var i = 0; i < remoteCapabilities.headerExtensions.length;
i++) {
var rHeaderExtension = remoteCapabilities.headerExtensions[i];
if (lHeaderExtension.uri === rHeaderExtension.uri) {
commonCapabilities.headerExtensions.push(rHeaderExtension);
break;
}
}
});
// FIXME: fecMechanisms
return commonCapabilities;
};
// Create ICE gatherer, ICE transport and DTLS transport.
window.RTCPeerConnection.prototype._createIceAndDtlsTransports =
function(mid, sdpMLineIndex) {
var self = this;
var iceGatherer = new RTCIceGatherer(self.iceOptions);
var iceTransport = new RTCIceTransport(iceGatherer);
iceGatherer.onlocalcandidate = function(evt) {
var event = new Event('icecandidate');
event.candidate = {sdpMid: mid, sdpMLineIndex: sdpMLineIndex};
var cand = evt.candidate;
var end = !cand || Object.keys(cand).length === 0;
// Edge emits an empty object for RTCIceCandidateComplete‥
if (end) {
// polyfill since RTCIceGatherer.state is not implemented in
// Edge 10547 yet.
if (iceGatherer.state === undefined) {
iceGatherer.state = 'completed';
}
// Emit a candidate with type endOfCandidates to make the samples
// work. Edge requires addIceCandidate with this empty candidate
// to start checking. The real solution is to signal
// end-of-candidates to the other side when getting the null
// candidate but some apps (like the samples) don't do that.
event.candidate.candidate =
'candidate:1 1 udp 1 0.0.0.0 9 typ endOfCandidates';
} else {
// RTCIceCandidate doesn't have a component, needs to be added
cand.component = iceTransport.component === 'RTCP' ? 2 : 1;
event.candidate.candidate = SDPUtils.writeCandidate(cand);
}
// update local description.
var sections = SDPUtils.splitSections(self.localDescription.sdp);
if (event.candidate.candidate.indexOf('typ endOfCandidates')
=== -1) {
sections[event.candidate.sdpMLineIndex + 1] +=
'a=' + event.candidate.candidate + '\r\n';
} else {
sections[event.candidate.sdpMLineIndex + 1] +=
'a=end-of-candidates\r\n';
}
self.localDescription.sdp = sections.join('');
var complete = self.transceivers.every(function(transceiver) {
return transceiver.iceGatherer &&
transceiver.iceGatherer.state === 'completed';
});
// Emit candidate if localDescription is set.
// Also emits null candidate when all gatherers are complete.
switch (self.iceGatheringState) {
case 'new':
self._localIceCandidatesBuffer.push(event);
if (end && complete) {
self._localIceCandidatesBuffer.push(
new Event('icecandidate'));
}
break;
case 'gathering':
self._emitBufferedCandidates();
self.dispatchEvent(event);
if (self.onicecandidate !== null) {
self.onicecandidate(event);
}
if (complete) {
self.dispatchEvent(new Event('icecandidate'));
if (self.onicecandidate !== null) {
self.onicecandidate(new Event('icecandidate'));
}
self.iceGatheringState = 'complete';
}
break;
case 'complete':
// should not happen... currently!
break;
default: // no-op.
break;
}
};
iceTransport.onicestatechange = function() {
self._updateConnectionState();
};
var dtlsTransport = new RTCDtlsTransport(iceTransport);
dtlsTransport.ondtlsstatechange = function() {
self._updateConnectionState();
};
dtlsTransport.onerror = function() {
// onerror does not set state to failed by itself.
dtlsTransport.state = 'failed';
self._updateConnectionState();
};
return {
iceGatherer: iceGatherer,
iceTransport: iceTransport,
dtlsTransport: dtlsTransport
};
};
// Start the RTP Sender and Receiver for a transceiver.
window.RTCPeerConnection.prototype._transceive = function(transceiver,
send, recv) {
var params = this._getCommonCapabilities(transceiver.localCapabilities,
transceiver.remoteCapabilities);
if (send && transceiver.rtpSender) {
params.encodings = transceiver.sendEncodingParameters;
params.rtcp = {
cname: SDPUtils.localCName
};
if (transceiver.recvEncodingParameters.length) {
params.rtcp.ssrc = transceiver.recvEncodingParameters[0].ssrc;
}
transceiver.rtpSender.send(params);
}
if (recv && transceiver.rtpReceiver) {
// remove RTX field in Edge 14942
if (transceiver.kind === 'video'
&& transceiver.recvEncodingParameters) {
transceiver.recvEncodingParameters.forEach(function(p) {
delete p.rtx;
});
}
params.encodings = transceiver.recvEncodingParameters;
params.rtcp = {
cname: transceiver.cname
};
if (transceiver.sendEncodingParameters.length) {
params.rtcp.ssrc = transceiver.sendEncodingParameters[0].ssrc;
}
transceiver.rtpReceiver.receive(params);
}
};
window.RTCPeerConnection.prototype.setLocalDescription =
function(description) {
var self = this;
var sections;
var sessionpart;
if (description.type === 'offer') {
// FIXME: What was the purpose of this empty if statement?
// if (!this._pendingOffer) {
// } else {
if (this._pendingOffer) {
// VERY limited support for SDP munging. Limited to:
// * changing the order of codecs
sections = SDPUtils.splitSections(description.sdp);
sessionpart = sections.shift();
sections.forEach(function(mediaSection, sdpMLineIndex) {
var caps = SDPUtils.parseRtpParameters(mediaSection);
self._pendingOffer[sdpMLineIndex].localCapabilities = caps;
});
this.transceivers = this._pendingOffer;
delete this._pendingOffer;
}
} else if (description.type === 'answer') {
sections = SDPUtils.splitSections(self.remoteDescription.sdp);
sessionpart = sections.shift();
var isIceLite = SDPUtils.matchPrefix(sessionpart,
'a=ice-lite').length > 0;
sections.forEach(function(mediaSection, sdpMLineIndex) {
var transceiver = self.transceivers[sdpMLineIndex];
var iceGatherer = transceiver.iceGatherer;
var iceTransport = transceiver.iceTransport;
var dtlsTransport = transceiver.dtlsTransport;
var localCapabilities = transceiver.localCapabilities;
var remoteCapabilities = transceiver.remoteCapabilities;
var rejected = mediaSection.split('\n', 1)[0]
.split(' ', 2)[1] === '0';
if (!rejected && !transceiver.isDatachannel) {
var remoteIceParameters = SDPUtils.getIceParameters(
mediaSection, sessionpart);
if (isIceLite) {
var cands = SDPUtils.matchPrefix(mediaSection, 'a=candidate:')
.map(function(cand) {
return SDPUtils.parseCandidate(cand);
})
.filter(function(cand) {
return cand.component === '1';
});
// ice-lite only includes host candidates in the SDP so we can
// use setRemoteCandidates (which implies an
// RTCIceCandidateComplete)
if (cands.length) {
iceTransport.setRemoteCandidates(cands);
}
}
var remoteDtlsParameters = SDPUtils.getDtlsParameters(
mediaSection, sessionpart);
if (isIceLite) {
remoteDtlsParameters.role = 'server';
}
if (!self.usingBundle || sdpMLineIndex === 0) {
iceTransport.start(iceGatherer, remoteIceParameters,
isIceLite ? 'controlling' : 'controlled');
dtlsTransport.start(remoteDtlsParameters);
}
// Calculate intersection of capabilities.
var params = self._getCommonCapabilities(localCapabilities,
remoteCapabilities);
// Start the RTCRtpSender. The RTCRtpReceiver for this
// transceiver has already been started in setRemoteDescription.
self._transceive(transceiver,
params.codecs.length > 0,
false);
}
});
}
this.localDescription = {
type: description.type,
sdp: description.sdp
};
switch (description.type) {
case 'offer':
this._updateSignalingState('have-local-offer');
break;
case 'answer':
this._updateSignalingState('stable');
break;
default:
throw new TypeError('unsupported type "' + description.type +
'"');
}
// If a success callback was provided, emit ICE candidates after it
// has been executed. Otherwise, emit callback after the Promise is
// resolved.
var hasCallback = arguments.length > 1 &&
typeof arguments[1] === 'function';
if (hasCallback) {
var cb = arguments[1];
window.setTimeout(function() {
cb();
if (self.iceGatheringState === 'new') {
self.iceGatheringState = 'gathering';
}
self._emitBufferedCandidates();
}, 0);
}
var p = Promise.resolve();
p.then(function() {
if (!hasCallback) {
if (self.iceGatheringState === 'new') {
self.iceGatheringState = 'gathering';
}
// Usually candidates will be emitted earlier.
window.setTimeout(self._emitBufferedCandidates.bind(self), 500);
}
});
return p;
};
window.RTCPeerConnection.prototype.setRemoteDescription =
function(description) {
var self = this;
var stream = new MediaStream();
var receiverList = [];
var sections = SDPUtils.splitSections(description.sdp);
var sessionpart = sections.shift();
var isIceLite = SDPUtils.matchPrefix(sessionpart,
'a=ice-lite').length > 0;
this.usingBundle = SDPUtils.matchPrefix(sessionpart,
'a=group:BUNDLE ').length > 0;
sections.forEach(function(mediaSection, sdpMLineIndex) {
var lines = SDPUtils.splitLines(mediaSection);
var mline = lines[0].substr(2).split(' ');
var kind = mline[0];
var rejected = mline[1] === '0';
var direction = SDPUtils.getDirection(mediaSection, sessionpart);
var mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:');
if (mid.length) {
mid = mid[0].substr(6);
} else {
mid = SDPUtils.generateIdentifier();
}
// Reject datachannels which are not implemented yet.
if (kind === 'application' && mline[2] === 'DTLS/SCTP') {
self.transceivers[sdpMLineIndex] = {
mid: mid,
isDatachannel: true
};
return;
}
var transceiver;
var iceGatherer;
var iceTransport;
var dtlsTransport;
var rtpSender;
var rtpReceiver;
var sendEncodingParameters;
var recvEncodingParameters;
var localCapabilities;
var track;
// FIXME: ensure the mediaSection has rtcp-mux set.
var remoteCapabilities = SDPUtils.parseRtpParameters(mediaSection);
var remoteIceParameters;
var remoteDtlsParameters;
if (!rejected) {
remoteIceParameters = SDPUtils.getIceParameters(mediaSection,
sessionpart);
remoteDtlsParameters = SDPUtils.getDtlsParameters(mediaSection,
sessionpart);
remoteDtlsParameters.role = 'client';
}
recvEncodingParameters =
SDPUtils.parseRtpEncodingParameters(mediaSection);
var cname;
// Gets the first SSRC. Note that with RTX there might be multiple
// SSRCs.
var remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
.map(function(line) {
return SDPUtils.parseSsrcMedia(line);
})
.filter(function(obj) {
return obj.attribute === 'cname';
})[0];
if (remoteSsrc) {
cname = remoteSsrc.value;
}
var isComplete = SDPUtils.matchPrefix(mediaSection,
'a=end-of-candidates', sessionpart).length > 0;
var cands = SDPUtils.matchPrefix(mediaSection, 'a=candidate:')
.map(function(cand) {
return SDPUtils.parseCandidate(cand);
})
.filter(function(cand) {
return cand.component === '1';
});
if (description.type === 'offer' && !rejected) {
var transports = self.usingBundle && sdpMLineIndex > 0 ? {
iceGatherer: self.transceivers[0].iceGatherer,
iceTransport: self.transceivers[0].iceTransport,
dtlsTransport: self.transceivers[0].dtlsTransport
} : self._createIceAndDtlsTransports(mid, sdpMLineIndex);
if (isComplete) {
transports.iceTransport.setRemoteCandidates(cands);
}
localCapabilities = RTCRtpReceiver.getCapabilities(kind);
// filter RTX until additional stuff needed for RTX is implemented
// in adapter.js
localCapabilities.codecs = localCapabilities.codecs.filter(
function(codec) {
return codec.name !== 'rtx';
});
sendEncodingParameters = [{
ssrc: (2 * sdpMLineIndex + 2) * 1001
}];
rtpReceiver = new RTCRtpReceiver(transports.dtlsTransport, kind);
track = rtpReceiver.track;
receiverList.push([track, rtpReceiver]);
// FIXME: not correct when there are multiple streams but that is
// not currently supported in this shim.
stream.addTrack(track);
// FIXME: look at direction.
if (self.localStreams.length > 0 &&
self.localStreams[0].getTracks().length >= sdpMLineIndex) {
var localTrack;
if (kind === 'audio') {
localTrack = self.localStreams[0].getAudioTracks()[0];
} else if (kind === 'video') {
localTrack = self.localStreams[0].getVideoTracks()[0];
}
if (localTrack) {
rtpSender = new RTCRtpSender(localTrack,
transports.dtlsTransport);
}
}
self.transceivers[sdpMLineIndex] = {
iceGatherer: transports.iceGatherer,
iceTransport: transports.iceTransport,
dtlsTransport: transports.dtlsTransport,
localCapabilities: localCapabilities,
remoteCapabilities: remoteCapabilities,
rtpSender: rtpSender,
rtpReceiver: rtpReceiver,
kind: kind,
mid: mid,
cname: cname,
sendEncodingParameters: sendEncodingParameters,
recvEncodingParameters: recvEncodingParameters
};
// Start the RTCRtpReceiver now. The RTPSender is started in
// setLocalDescription.
self._transceive(self.transceivers[sdpMLineIndex],
false,
direction === 'sendrecv' || direction === 'sendonly');
} else if (description.type === 'answer' && !rejected) {
transceiver = self.transceivers[sdpMLineIndex];
iceGatherer = transceiver.iceGatherer;
iceTransport = transceiver.iceTransport;
dtlsTransport = transceiver.dtlsTransport;
rtpSender = transceiver.rtpSender;
rtpReceiver = transceiver.rtpReceiver;
sendEncodingParameters = transceiver.sendEncodingParameters;
localCapabilities = transceiver.localCapabilities;
self.transceivers[sdpMLineIndex].recvEncodingParameters =
recvEncodingParameters;
self.transceivers[sdpMLineIndex].remoteCapabilities =
remoteCapabilities;
self.transceivers[sdpMLineIndex].cname = cname;
if ((isIceLite || isComplete) && cands.length) {
iceTransport.setRemoteCandidates(cands);
}
if (!self.usingBundle || sdpMLineIndex === 0) {
iceTransport.start(iceGatherer, remoteIceParameters,
'controlling');
dtlsTransport.start(remoteDtlsParameters);
}
self._transceive(transceiver,
direction === 'sendrecv' || direction === 'recvonly',
direction === 'sendrecv' || direction === 'sendonly');
if (rtpReceiver &&
(direction === 'sendrecv' || direction === 'sendonly')) {
track = rtpReceiver.track;
receiverList.push([track, rtpReceiver]);
stream.addTrack(track);
} else {
// FIXME: actually the receiver should be created later.
delete transceiver.rtpReceiver;
}
}
});
this.remoteDescription = {
type: description.type,
sdp: description.sdp
};
switch (description.type) {
case 'offer':
this._updateSignalingState('have-remote-offer');
break;
case 'answer':
this._updateSignalingState('stable');
break;
default:
throw new TypeError('unsupported type "' + description.type +
'"');
}
if (stream.getTracks().length) {
self.remoteStreams.push(stream);
window.setTimeout(function() {
var event = new Event('addstream');
event.stream = stream;
self.dispatchEvent(event);
if (self.onaddstream !== null) {
window.setTimeout(function() {
self.onaddstream(event);
}, 0);
}
receiverList.forEach(function(item) {
var track = item[0];
var receiver = item[1];
var trackEvent = new Event('track');
trackEvent.track = track;
trackEvent.receiver = receiver;
trackEvent.streams = [stream];
self.dispatchEvent(event);
if (self.ontrack !== null) {
window.setTimeout(function() {
self.ontrack(trackEvent);
}, 0);
}
});
}, 0);
}
if (arguments.length > 1 && typeof arguments[1] === 'function') {
window.setTimeout(arguments[1], 0);
}
return Promise.resolve();
};
window.RTCPeerConnection.prototype.close = function() {
this.transceivers.forEach(function(transceiver) {
/* not yet
if (transceiver.iceGatherer) {
transceiver.iceGatherer.close();
}
*/
if (transceiver.iceTransport) {
transceiver.iceTransport.stop();
}
if (transceiver.dtlsTransport) {
transceiver.dtlsTransport.stop();
}
if (transceiver.rtpSender) {
transceiver.rtpSender.stop();
}
if (transceiver.rtpReceiver) {
transceiver.rtpReceiver.stop();
}
});
// FIXME: clean up tracks, local streams, remote streams, etc
this._updateSignalingState('closed');
};
// Update the signaling state.
window.RTCPeerConnection.prototype._updateSignalingState =
function(newState) {
this.signalingState = newState;
var event = new Event('signalingstatechange');
this.dispatchEvent(event);
if (this.onsignalingstatechange !== null) {
this.onsignalingstatechange(event);
}
};
// Determine whether to fire the negotiationneeded event.
window.RTCPeerConnection.prototype._maybeFireNegotiationNeeded =
function() {
// Fire away (for now).
var event = new Event('negotiationneeded');
this.dispatchEvent(event);
if (this.onnegotiationneeded !== null) {
this.onnegotiationneeded(event);
}
};
// Update the connection state.
window.RTCPeerConnection.prototype._updateConnectionState = function() {
var self = this;
var newState;
var states = {
'new': 0,
closed: 0,
connecting: 0,
checking: 0,
connected: 0,
completed: 0,
failed: 0
};
this.transceivers.forEach(function(transceiver) {
states[transceiver.iceTransport.state]++;
states[transceiver.dtlsTransport.state]++;
});
// ICETransport.completed and connected are the same for this purpose.
states.connected += states.completed;
newState = 'new';
if (states.failed > 0) {
newState = 'failed';
} else if (states.connecting > 0 || states.checking > 0) {
newState = 'connecting';
} else if (states.disconnected > 0) {
newState = 'disconnected';
} else if (states.new > 0) {
newState = 'new';
} else if (states.connected > 0 || states.completed > 0) {
newState = 'connected';
}
if (newState !== self.iceConnectionState) {
self.iceConnectionState = newState;
var event = new Event('iceconnectionstatechange');
this.dispatchEvent(event);
if (this.oniceconnectionstatechange !== null) {
this.oniceconnectionstatechange(event);
}
}
};
window.RTCPeerConnection.prototype.createOffer = function() {
var self = this;
if (this._pendingOffer) {
throw new Error('createOffer called while there is a pending offer.');
}
var offerOptions;
if (arguments.length === 1 && typeof arguments[0] !== 'function') {
offerOptions = arguments[0];
} else if (arguments.length === 3) {
offerOptions = arguments[2];
}
var tracks = [];
var numAudioTracks = 0;
var numVideoTracks = 0;
// Default to sendrecv.
if (this.localStreams.length) {
numAudioTracks = this.localStreams[0].getAudioTracks().length;
numVideoTracks = this.localStreams[0].getVideoTracks().length;
}
// Determine number of audio and video tracks we need to send/recv.
if (offerOptions) {
// Reject Chrome legacy constraints.
if (offerOptions.mandatory || offerOptions.optional) {
throw new TypeError(
'Legacy mandatory/optional constraints not supported.');
}
if (offerOptions.offerToReceiveAudio !== undefined) {
numAudioTracks = offerOptions.offerToReceiveAudio;
}
if (offerOptions.offerToReceiveVideo !== undefined) {
numVideoTracks = offerOptions.offerToReceiveVideo;
}
}
if (this.localStreams.length) {
// Push local streams.
this.localStreams[0].getTracks().forEach(function(track) {
tracks.push({
kind: track.kind,
track: track,
wantReceive: track.kind === 'audio' ?
numAudioTracks > 0 : numVideoTracks > 0
});
if (track.kind === 'audio') {
numAudioTracks--;
} else if (track.kind === 'video') {
numVideoTracks--;
}
});
}
// Create M-lines for recvonly streams.
while (numAudioTracks > 0 || numVideoTracks > 0) {
if (numAudioTracks > 0) {
tracks.push({
kind: 'audio',
wantReceive: true
});
numAudioTracks--;
}
if (numVideoTracks > 0) {
tracks.push({
kind: 'video',
wantReceive: true
});
numVideoTracks--;
}
}
var sdp = SDPUtils.writeSessionBoilerplate();
var transceivers = [];
tracks.forEach(function(mline, sdpMLineIndex) {
// For each track, create an ice gatherer, ice transport,
// dtls transport, potentially rtpsender and rtpreceiver.
var track = mline.track;
var kind = mline.kind;
var mid = SDPUtils.generateIdentifier();
var transports = self.usingBundle && sdpMLineIndex > 0 ? {
iceGatherer: transceivers[0].iceGatherer,
iceTransport: transceivers[0].iceTransport,
dtlsTransport: transceivers[0].dtlsTransport
} : self._createIceAndDtlsTransports(mid, sdpMLineIndex);
var localCapabilities = RTCRtpSender.getCapabilities(kind);
// filter RTX until additional stuff needed for RTX is implemented
// in adapter.js
localCapabilities.codecs = localCapabilities.codecs.filter(
function(codec) {
return codec.name !== 'rtx';
});
localCapabilities.codecs.forEach(function(codec) {
// work around https://bugs.chromium.org/p/webrtc/issues/detail?id=6552
// by adding level-asymmetry-allowed=1
if (codec.name === 'H264' &&
codec.parameters['level-asymmetry-allowed'] === undefined) {
codec.parameters['level-asymmetry-allowed'] = '1';
}
});
var rtpSender;
var rtpReceiver;
// generate an ssrc now, to be used later in rtpSender.send
var sendEncodingParameters = [{
ssrc: (2 * sdpMLineIndex + 1) * 1001
}];
if (track) {
rtpSender = new RTCRtpSender(track, transports.dtlsTransport);
}
if (mline.wantReceive) {
rtpReceiver = new RTCRtpReceiver(transports.dtlsTransport, kind);
}
transceivers[sdpMLineIndex] = {
iceGatherer: transports.iceGatherer,
iceTransport: transports.iceTransport,
dtlsTransport: transports.dtlsTransport,
localCapabilities: localCapabilities,
remoteCapabilities: null,
rtpSender: rtpSender,
rtpReceiver: rtpReceiver,
kind: kind,
mid: mid,
sendEncodingParameters: sendEncodingParameters,
recvEncodingParameters: null
};
});
if (this.usingBundle) {
sdp += 'a=group:BUNDLE ' + transceivers.map(function(t) {
return t.mid;
}).join(' ') + '\r\n';
}
tracks.forEach(function(mline, sdpMLineIndex) {
var transceiver = transceivers[sdpMLineIndex];
sdp += SDPUtils.writeMediaSection(transceiver,
transceiver.localCapabilities, 'offer', self.localStreams[0]);
});
this._pendingOffer = transceivers;
var desc = new RTCSessionDescription({
type: 'offer',
sdp: sdp
});
if (arguments.length && typeof arguments[0] === 'function') {
window.setTimeout(arguments[0], 0, desc);
}
return Promise.resolve(desc);
};
window.RTCPeerConnection.prototype.createAnswer = function() {
var self = this;
var sdp = SDPUtils.writeSessionBoilerplate();
if (this.usingBundle) {
sdp += 'a=group:BUNDLE ' + this.transceivers.map(function(t) {
return t.mid;
}).join(' ') + '\r\n';
}
this.transceivers.forEach(function(transceiver) {
if (transceiver.isDatachannel) {
sdp += 'm=application 0 DTLS/SCTP 5000\r\n' +
'c=IN IP4 0.0.0.0\r\n' +
'a=mid:' + transceiver.mid + '\r\n';
return;
}
// Calculate intersection of capabilities.
var commonCapabilities = self._getCommonCapabilities(
transceiver.localCapabilities,
transceiver.remoteCapabilities);
sdp += SDPUtils.writeMediaSection(transceiver, commonCapabilities,
'answer', self.localStreams[0]);
});
var desc = new RTCSessionDescription({
type: 'answer',
sdp: sdp
});
if (arguments.length && typeof arguments[0] === 'function') {
window.setTimeout(arguments[0], 0, desc);
}
return Promise.resolve(desc);
};
window.RTCPeerConnection.prototype.addIceCandidate = function(candidate) {
if (!candidate) {
this.transceivers.forEach(function(transceiver) {
transceiver.iceTransport.addRemoteCandidate({});
});
} else {
var mLineIndex = candidate.sdpMLineIndex;
if (candidate.sdpMid) {
for (var i = 0; i < this.transceivers.length; i++) {
if (this.transceivers[i].mid === candidate.sdpMid) {
mLineIndex = i;
break;
}
}
}
var transceiver = this.transceivers[mLineIndex];
if (transceiver) {
var cand = Object.keys(candidate.candidate).length > 0 ?
SDPUtils.parseCandidate(candidate.candidate) : {};
// Ignore Chrome's invalid candidates since Edge does not like them.
if (cand.protocol === 'tcp' && (cand.port === 0 || cand.port === 9)) {
return;
}
// Ignore RTCP candidates, we assume RTCP-MUX.
if (cand.component !== '1') {
return;
}
// A dirty hack to make samples work.
if (cand.type === 'endOfCandidates') {
cand = {};
}
transceiver.iceTransport.addRemoteCandidate(cand);
// update the remoteDescription.
var sections = SDPUtils.splitSections(this.remoteDescription.sdp);
sections[mLineIndex + 1] += (cand.type ? candidate.candidate.trim()
: 'a=end-of-candidates') + '\r\n';
this.remoteDescription.sdp = sections.join('');
}
}
if (arguments.length > 1 && typeof arguments[1] === 'function') {
window.setTimeout(arguments[1], 0);
}
return Promise.resolve();
};
window.RTCPeerConnection.prototype.getStats = function() {
var promises = [];
this.transceivers.forEach(function(transceiver) {
['rtpSender', 'rtpReceiver', 'iceGatherer', 'iceTransport',
'dtlsTransport'].forEach(function(method) {
if (transceiver[method]) {
promises.push(transceiver[method].getStats());
}
});
});
var cb = arguments.length > 1 && typeof arguments[1] === 'function' &&
arguments[1];
return new Promise(function(resolve) {
// shim getStats with maplike support
var results = new Map();
Promise.all(promises).then(function(res) {
res.forEach(function(result) {
Object.keys(result).forEach(function(id) {
results.set(id, result[id]);
results[id] = result[id];
});
});
if (cb) {
window.setTimeout(cb, 0, results);
}
resolve(results);
});
});
};
}
};
// Expose public methods.
module.exports = {
shimPeerConnection: edgeShim.shimPeerConnection,
shimGetUserMedia: require('./getusermedia')
};
},{"../utils":49,"./getusermedia":45,"sdp":40}],45:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
// Expose public methods.
module.exports = function() {
var shimError_ = function(e) {
return {
name: {PermissionDeniedError: 'NotAllowedError'}[e.name] || e.name,
message: e.message,
constraint: e.constraint,
toString: function() {
return this.name;
}
};
};
// getUserMedia error shim.
var origGetUserMedia = navigator.mediaDevices.getUserMedia.
bind(navigator.mediaDevices);
navigator.mediaDevices.getUserMedia = function(c) {
return origGetUserMedia(c).catch(function(e) {
return Promise.reject(shimError_(e));
});
};
};
},{}],46:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var browserDetails = require('../utils').browserDetails;
var firefoxShim = {
shimOnTrack: function() {
if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
window.RTCPeerConnection.prototype)) {
Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
get: function() {
return this._ontrack;
},
set: function(f) {
if (this._ontrack) {
this.removeEventListener('track', this._ontrack);
this.removeEventListener('addstream', this._ontrackpoly);
}
this.addEventListener('track', this._ontrack = f);
this.addEventListener('addstream', this._ontrackpoly = function(e) {
e.stream.getTracks().forEach(function(track) {
var event = new Event('track');
event.track = track;
event.receiver = {track: track};
event.streams = [e.stream];
this.dispatchEvent(event);
}.bind(this));
}.bind(this));
}
});
}
},
shimSourceObject: function() {
// Firefox has supported mozSrcObject since FF22, unprefixed in 42.
if (typeof window === 'object') {
if (window.HTMLMediaElement &&
!('srcObject' in window.HTMLMediaElement.prototype)) {
// Shim the srcObject property, once, when HTMLMediaElement is found.
Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', {
get: function() {
return this.mozSrcObject;
},
set: function(stream) {
this.mozSrcObject = stream;
}
});
}
}
},
shimPeerConnection: function() {
if (typeof window !== 'object' || !(window.RTCPeerConnection ||
window.mozRTCPeerConnection)) {
return; // probably media.peerconnection.enabled=false in about:config
}
// The RTCPeerConnection object.
if (!window.RTCPeerConnection) {
window.RTCPeerConnection = function(pcConfig, pcConstraints) {
if (browserDetails.version < 38) {
// .urls is not supported in FF < 38.
// create RTCIceServers with a single url.
if (pcConfig && pcConfig.iceServers) {
var newIceServers = [];
for (var i = 0; i < pcConfig.iceServers.length; i++) {
var server = pcConfig.iceServers[i];
if (server.hasOwnProperty('urls')) {
for (var j = 0; j < server.urls.length; j++) {
var newServer = {
url: server.urls[j]
};
if (server.urls[j].indexOf('turn') === 0) {
newServer.username = server.username;
newServer.credential = server.credential;
}
newIceServers.push(newServer);
}
} else {
newIceServers.push(pcConfig.iceServers[i]);
}
}
pcConfig.iceServers = newIceServers;
}
}
return new mozRTCPeerConnection(pcConfig, pcConstraints);
};
window.RTCPeerConnection.prototype = mozRTCPeerConnection.prototype;
// wrap static methods. Currently just generateCertificate.
if (mozRTCPeerConnection.generateCertificate) {
Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
get: function() {
return mozRTCPeerConnection.generateCertificate;
}
});
}
window.RTCSessionDescription = mozRTCSessionDescription;
window.RTCIceCandidate = mozRTCIceCandidate;
}
// shim away need for obsolete RTCIceCandidate/RTCSessionDescription.
['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
.forEach(function(method) {
var nativeMethod = RTCPeerConnection.prototype[method];
RTCPeerConnection.prototype[method] = function() {
arguments[0] = new ((method === 'addIceCandidate') ?
RTCIceCandidate : RTCSessionDescription)(arguments[0]);
return nativeMethod.apply(this, arguments);
};
});
// support for addIceCandidate(null or undefined)
var nativeAddIceCandidate =
RTCPeerConnection.prototype.addIceCandidate;
RTCPeerConnection.prototype.addIceCandidate = function() {
if (!arguments[0]) {
if (arguments[1]) {
arguments[1].apply(null);
}
return Promise.resolve();
}
return nativeAddIceCandidate.apply(this, arguments);
};
if (browserDetails.version < 48) {
// shim getStats with maplike support
var makeMapStats = function(stats) {
var map = new Map();
Object.keys(stats).forEach(function(key) {
map.set(key, stats[key]);
map[key] = stats[key];
});
return map;
};
var nativeGetStats = RTCPeerConnection.prototype.getStats;
RTCPeerConnection.prototype.getStats = function(selector, onSucc, onErr) {
return nativeGetStats.apply(this, [selector || null])
.then(function(stats) {
return makeMapStats(stats);
})
.then(onSucc, onErr);
};
}
}
};
// Expose public methods.
module.exports = {
shimOnTrack: firefoxShim.shimOnTrack,
shimSourceObject: firefoxShim.shimSourceObject,
shimPeerConnection: firefoxShim.shimPeerConnection,
shimGetUserMedia: require('./getusermedia')
};
},{"../utils":49,"./getusermedia":47}],47:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var logging = require('../utils').log;
var browserDetails = require('../utils').browserDetails;
// Expose public methods.
module.exports = function() {
var shimError_ = function(e) {
return {
name: {
SecurityError: 'NotAllowedError',
PermissionDeniedError: 'NotAllowedError'
}[e.name] || e.name,
message: {
'The operation is insecure.': 'The request is not allowed by the ' +
'user agent or the platform in the current context.'
}[e.message] || e.message,
constraint: e.constraint,
toString: function() {
return this.name + (this.message && ': ') + this.message;
}
};
};
// getUserMedia constraints shim.
var getUserMedia_ = function(constraints, onSuccess, onError) {
var constraintsToFF37_ = function(c) {
if (typeof c !== 'object' || c.require) {
return c;
}
var require = [];
Object.keys(c).forEach(function(key) {
if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
return;
}
var r = c[key] = (typeof c[key] === 'object') ?
c[key] : {ideal: c[key]};
if (r.min !== undefined ||
r.max !== undefined || r.exact !== undefined) {
require.push(key);
}
if (r.exact !== undefined) {
if (typeof r.exact === 'number') {
r. min = r.max = r.exact;
} else {
c[key] = r.exact;
}
delete r.exact;
}
if (r.ideal !== undefined) {
c.advanced = c.advanced || [];
var oc = {};
if (typeof r.ideal === 'number') {
oc[key] = {min: r.ideal, max: r.ideal};
} else {
oc[key] = r.ideal;
}
c.advanced.push(oc);
delete r.ideal;
if (!Object.keys(r).length) {
delete c[key];
}
}
});
if (require.length) {
c.require = require;
}
return c;
};
constraints = JSON.parse(JSON.stringify(constraints));
if (browserDetails.version < 38) {
logging('spec: ' + JSON.stringify(constraints));
if (constraints.audio) {
constraints.audio = constraintsToFF37_(constraints.audio);
}
if (constraints.video) {
constraints.video = constraintsToFF37_(constraints.video);
}
logging('ff37: ' + JSON.stringify(constraints));
}
return navigator.mozGetUserMedia(constraints, onSuccess, function(e) {
onError(shimError_(e));
});
};
// Returns the result of getUserMedia as a Promise.
var getUserMediaPromise_ = function(constraints) {
return new Promise(function(resolve, reject) {
getUserMedia_(constraints, resolve, reject);
});
};
// Shim for mediaDevices on older versions.
if (!navigator.mediaDevices) {
navigator.mediaDevices = {getUserMedia: getUserMediaPromise_,
addEventListener: function() { },
removeEventListener: function() { }
};
}
navigator.mediaDevices.enumerateDevices =
navigator.mediaDevices.enumerateDevices || function() {
return new Promise(function(resolve) {
var infos = [
{kind: 'audioinput', deviceId: 'default', label: '', groupId: ''},
{kind: 'videoinput', deviceId: 'default', label: '', groupId: ''}
];
resolve(infos);
});
};
if (browserDetails.version < 41) {
// Work around http://bugzil.la/1169665
var orgEnumerateDevices =
navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);
navigator.mediaDevices.enumerateDevices = function() {
return orgEnumerateDevices().then(undefined, function(e) {
if (e.name === 'NotFoundError') {
return [];
}
throw e;
});
};
}
if (browserDetails.version < 49) {
var origGetUserMedia = navigator.mediaDevices.getUserMedia.
bind(navigator.mediaDevices);
navigator.mediaDevices.getUserMedia = function(c) {
return origGetUserMedia(c).then(function(stream) {
// Work around https://bugzil.la/802326
if (c.audio && !stream.getAudioTracks().length ||
c.video && !stream.getVideoTracks().length) {
stream.getTracks().forEach(function(track) {
track.stop();
});
throw new DOMException('The object can not be found here.',
'NotFoundError');
}
return stream;
}, function(e) {
return Promise.reject(shimError_(e));
});
};
}
navigator.getUserMedia = function(constraints, onSuccess, onError) {
if (browserDetails.version < 44) {
return getUserMedia_(constraints, onSuccess, onError);
}
// Replace Firefox 44+'s deprecation warning with unprefixed version.
console.warn('navigator.getUserMedia has been replaced by ' +
'navigator.mediaDevices.getUserMedia');
navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);
};
};
},{"../utils":49}],48:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
'use strict';
var safariShim = {
// TODO: DrAlex, should be here, double check against LayoutTests
// shimOnTrack: function() { },
// TODO: once the back-end for the mac port is done, add.
// TODO: check for webkitGTK+
// shimPeerConnection: function() { },
shimGetUserMedia: function() {
navigator.getUserMedia = navigator.webkitGetUserMedia;
}
};
// Expose public methods.
module.exports = {
shimGetUserMedia: safariShim.shimGetUserMedia
// TODO
// shimOnTrack: safariShim.shimOnTrack,
// shimPeerConnection: safariShim.shimPeerConnection
};
},{}],49:[function(require,module,exports){
/*
* Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
/* eslint-env node */
'use strict';
var logDisabled_ = true;
// Utility methods.
var utils = {
disableLog: function(bool) {
if (typeof bool !== 'boolean') {
return new Error('Argument type: ' + typeof bool +
'. Please use a boolean.');
}
logDisabled_ = bool;
return (bool) ? 'adapter.js logging disabled' :
'adapter.js logging enabled';
},
log: function() {
if (typeof window === 'object') {
if (logDisabled_) {
return;
}
if (typeof console !== 'undefined' && typeof console.log === 'function') {
console.log.apply(console, arguments);
}
}
},
/**
* Extract browser version out of the provided user agent string.
*
* @param {!string} uastring userAgent string.
* @param {!string} expr Regular expression used as match criteria.
* @param {!number} pos position in the version string to be returned.
* @return {!number} browser version.
*/
extractVersion: function(uastring, expr, pos) {
var match = uastring.match(expr);
return match && match.length >= pos && parseInt(match[pos], 10);
},
/**
* Browser detector.
*
* @return {object} result containing browser and version
* properties.
*/
detectBrowser: function() {
// Returned result object.
var result = {};
result.browser = null;
result.version = null;
// Fail early if it's not a browser
if (typeof window === 'undefined' || !window.navigator) {
result.browser = 'Not a browser.';
return result;
}
// Firefox.
if (navigator.mozGetUserMedia) {
result.browser = 'firefox';
result.version = this.extractVersion(navigator.userAgent,
/Firefox\/([0-9]+)\./, 1);
// all webkit-based browsers
} else if (navigator.webkitGetUserMedia) {
// Chrome, Chromium, Webview, Opera, all use the chrome shim for now
if (window.webkitRTCPeerConnection) {
result.browser = 'chrome';
result.version = this.extractVersion(navigator.userAgent,
/Chrom(e|ium)\/([0-9]+)\./, 2);
// Safari or unknown webkit-based
// for the time being Safari has support for MediaStreams but not webRTC
} else {
// Safari UA substrings of interest for reference:
// - webkit version: AppleWebKit/602.1.25 (also used in Op,Cr)
// - safari UI version: Version/9.0.3 (unique to Safari)
// - safari UI webkit version: Safari/601.4.4 (also used in Op,Cr)
//
// if the webkit version and safari UI webkit versions are equals,
// ... this is a stable version.
//
// only the internal webkit version is important today to know if
// media streams are supported
//
if (navigator.userAgent.match(/Version\/(\d+).(\d+)/)) {
result.browser = 'safari';
result.version = this.extractVersion(navigator.userAgent,
/AppleWebKit\/([0-9]+)\./, 1);
// unknown webkit-based browser
} else {
result.browser = 'Unsupported webkit-based browser ' +
'with GUM support but no WebRTC support.';
return result;
}
}
// Edge.
} else if (navigator.mediaDevices &&
navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) {
result.browser = 'edge';
result.version = this.extractVersion(navigator.userAgent,
/Edge\/(\d+).(\d+)$/, 2);
// Default fallthrough: not supported.
} else {
result.browser = 'Not a supported browser.';
return result;
}
return result;
}
};
// Export.
module.exports = {
log: utils.log,
disableLog: utils.disableLog,
browserDetails: utils.detectBrowser(),
extractVersion: utils.extractVersion
};
},{}],50:[function(require,module,exports){
module.exports={
"name": "jssip",
"title": "JsSIP",
"description": "the Javascript SIP library",
"version": "3.0.2",
"homepage": "http://jssip.net",
"author": "José Luis Millán <[email protected]> (https://github.com/jmillan)",
"contributors": [
"Iñaki Baz Castillo <[email protected]> (https://github.com/ibc)",
"Saúl Ibarra Corretgé <[email protected]> (https://github.com/saghul)"
],
"main": "lib/JsSIP.js",
"keywords": [
"sip",
"websocket",
"webrtc",
"node",
"browser",
"library"
],
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/versatica/JsSIP.git"
},
"bugs": {
"url": "https://github.com/versatica/JsSIP/issues"
},
"dependencies": {
"debug": "^2.3.3",
"sdp-transform": "^1.6.2",
"webrtc-adapter": "^2.0.8"
},
"devDependencies": {
"browserify": "^13.1.1",
"gulp": "git+https://github.com/gulpjs/gulp.git#4.0",
"gulp-expect-file": "0.0.7",
"gulp-header": "1.8.8",
"gulp-jshint": "^2.0.4",
"gulp-nodeunit-runner": "^0.2.2",
"gulp-rename": "^1.2.2",
"gulp-uglify": "^2.0.0",
"gulp-util": "^3.0.7",
"jshint": "^2.9.4",
"jshint-stylish": "^2.2.1",
"pegjs": "0.7.0",
"vinyl-buffer": "^1.0.0",
"vinyl-source-stream": "^1.1.0"
},
"scripts": {
"test": "gulp test"
}
}
},{}]},{},[7])(7)
}); | tonytomov/cdnjs | ajax/libs/jssip/3.0.3/jssip.js | JavaScript | mit | 798,200 |
var five = require("../lib/johnny-five.js");
var board = new five.Board();
board.on("ready", function() {
var temperature = new five.Temperature({
controller: "MPL115A2"
});
temperature.on("data", function() {
console.log("temperature");
console.log(" celsius : ", this.celsius);
console.log(" fahrenheit : ", this.fahrenheit);
console.log(" kelvin : ", this.kelvin);
console.log("--------------------------------------");
});
});
// @markdown
// - [MPL115A2 - I2C Barometric Pressure/Temperature Sensor](https://www.adafruit.com/product/992)
// @markdown
| manorius/printing_with_node | node_modules/johnny-five/eg/temperature-mpl115a2.js | JavaScript | mit | 607 |
ej.addCulture( "az-Latn-AZ", {
name: "az-Latn-AZ",
englishName: "Azerbaijani (Latin, Azerbaijan)",
nativeName: "Azərbaycan dili (Azərbaycan)",
language: "az-Latn",
numberFormat: {
",": " ",
".": ",",
percent: {
pattern: ["-n%","n%"],
",": " ",
".": ","
},
currency: {
pattern: ["-n $","n $"],
",": " ",
".": ",",
symbol: "manat"
}
},
calendars: {
standard: {
"/": ".",
firstDay: 1,
days: {
names: ["bazar","Bazar ertəsi","çərşənbə axşamı","çərşənbə","Cümə axşamı","Cümə","şənbə"],
namesAbbr: ["B","Be","Ça","Ç","Ca","C","Ş"],
namesShort: ["B","Be","Ça","Ç","Ca","C","Ş"]
},
months: {
names: ["yanvar","fevral","mart","aprel","may","iyun","iyul","avgust","sentyabr","oktyabr","noyabr","dekabr",""],
namesAbbr: ["Yan","Fev","Mar","Apr","May","İyun","İyul","Avg","Sen","Okt","Noy","Dek",""]
},
AM: null,
PM: null,
patterns: {
d: "dd.MM.yyyy",
D: "dd MMMM yyyy'-cü il'",
t: "HH:mm",
T: "HH:mm:ss",
f: "dd MMMM yyyy'-cü il' HH:mm",
F: "dd MMMM yyyy'-cü il' HH:mm:ss",
M: "d MMMM"
}
},
Hijri: {
name: "Hijri",
"/": ".",
firstDay: 1,
days: {
names: ["Bazar","Bazar ertəsi","Çərşənbə axşamı","Çərşənbə","Cümə axşamı","Cümə","Şənbə"],
namesAbbr: ["B","Be","Ça","Ç","Ca","C","Ş"],
namesShort: ["B","Be","Ça","Ç","Ca","C","Ş"]
},
months: {
names: ["Məhərrəm","Səfər","Rəbiüləvvəl","Rəbiülaxır","Cəmadiyələvvəl","Cəmadiyəlaxır","Rəcəb","Şaban","Ramazan","Şəvval","Zilqədə","Zilhiccə",""],
namesAbbr: ["Məhərrəm","Səfər","Rəbiüləvvəl","Rəbiülaxır","Cəmadiyələvvəl","Cəmadiyəlaxır","Rəcəb","Şaban","Ramazan","Şəvval","Zilqədə","Zilhiccə",""]
},
AM: null,
PM: null,
twoDigitYearMax: 1451,
patterns: {
d: "dd.MM.yyyy",
D: "d MMMM yyyy",
t: "HH:mm",
T: "HH:mm:ss",
f: "d MMMM yyyy HH:mm",
F: "d MMMM yyyy HH:mm:ss",
M: "d MMMM"
},
convert: {
// Adapted to Script from System.Globalization.HijriCalendar
ticks1970: 62135596800000,
// number of days leading up to each month
monthDays: [0, 30, 59, 89, 118, 148, 177, 207, 236, 266, 295, 325, 355],
minDate: -42521673600000,
maxDate: 253402300799999,
// The number of days to add or subtract from the calendar to accommodate the variances
// in the start and the end of Ramadan and to accommodate the date difference between
// countries/regions. May be dynamically adjusted based on user preference, but should
// remain in the range of -2 to 2, inclusive.
hijriAdjustment: 0,
toGregorian: function(hyear, hmonth, hday) {
var daysSinceJan0101 = this.daysToYear(hyear) + this.monthDays[hmonth] + hday - 1 - this.hijriAdjustment;
// 86400000 = ticks per day
var gdate = new Date(daysSinceJan0101 * 86400000 - this.ticks1970);
// adjust for timezone, because we are interested in the gregorian date for the same timezone
// but ticks in javascript is always from GMT, unlike the server were ticks counts from the base
// date in the current timezone.
gdate.setMinutes(gdate.getMinutes() + gdate.getTimezoneOffset());
return gdate;
},
fromGregorian: function(gdate) {
if ((gdate < this.minDate) || (gdate > this.maxDate)) return null;
var ticks = this.ticks1970 + (gdate-0) - gdate.getTimezoneOffset() * 60000,
daysSinceJan0101 = Math.floor(ticks / 86400000) + 1 + this.hijriAdjustment;
// very particular formula determined by someone smart, adapted from the server-side implementation.
// it approximates the hijri year.
var hday, hmonth, hyear = Math.floor(((daysSinceJan0101 - 227013) * 30) / 10631) + 1,
absDays = this.daysToYear(hyear),
daysInYear = this.isLeapYear(hyear) ? 355 : 354;
// hyear is just approximate, it may need adjustment up or down by 1.
if (daysSinceJan0101 < absDays) {
hyear--;
absDays -= daysInYear;
}
else if (daysSinceJan0101 === absDays) {
hyear--;
absDays = this.daysToYear(hyear);
}
else {
if (daysSinceJan0101 > (absDays + daysInYear)) {
absDays += daysInYear;
hyear++;
}
}
// determine month by looking at how many days into the hyear we are
// monthDays contains the number of days up to each month.
hmonth = 0;
var daysIntoYear = daysSinceJan0101 - absDays;
while (hmonth <= 11 && daysIntoYear > this.monthDays[hmonth]) {
hmonth++;
}
hmonth--;
hday = daysIntoYear - this.monthDays[hmonth];
return [hyear, hmonth, hday];
},
daysToYear: function(year) {
// calculates how many days since Jan 1, 0001
var yearsToYear30 = Math.floor((year - 1) / 30) * 30,
yearsInto30 = year - yearsToYear30 - 1,
days = Math.floor((yearsToYear30 * 10631) / 30) + 227013;
while (yearsInto30 > 0) {
days += (this.isLeapYear(yearsInto30) ? 355 : 354);
yearsInto30--;
}
return days;
},
isLeapYear: function(year) {
return ((((year * 11) + 14) % 30) < 11);
}
}
}
}
}); | Asaf-S/jsdelivr | files/syncfusion-ej-global/15.1.41/i18n/ej.culture.az-Latn-AZ.js | JavaScript | mit | 6,524 |
/* Norwegian initialisation for the jQuery UI date picker plugin. */
/* Written by Naimdjon Takhirov ([email protected]). */
jQuery(function($){
$.datepicker.regional['no'] = {
closeText: 'Lukk',
prevText: '«Forrige',
nextText: 'Neste»',
currentText: 'I dag',
monthNames: ['januar','februar','mars','april','mai','juni','juli','august','september','oktober','november','desember'],
monthNamesShort: ['jan','feb','mar','apr','mai','jun','jul','aug','sep','okt','nov','des'],
dayNamesShort: ['søn','man','tir','ons','tor','fre','lør'],
dayNames: ['søndag','mandag','tirsdag','onsdag','torsdag','fredag','lørdag'],
dayNamesMin: ['sø','ma','ti','on','to','fr','lø'],
weekHeader: 'Uke',
dateFormat: 'dd.mm.yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''
};
$.datepicker.setDefaults($.datepicker.regional['no']);
});
| olek1984/dremboard | wp-content/plugins/wp-maintenance-mode/js/i18n/jquery.ui.datepicker-no.js | JavaScript | gpl-2.0 | 946 |
/**
* @fileoverview Rule to check for tabs inside a file
* @author Gyandeep Singh
*/
"use strict";
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const regex = /\t/;
//------------------------------------------------------------------------------
// Public Interface
//------------------------------------------------------------------------------
module.exports = {
meta: {
docs: {
description: "disallow all tabs",
category: "Stylistic Issues",
recommended: false
},
schema: []
},
create(context) {
return {
Program(node) {
context.getSourceLines().forEach((line, index) => {
const match = regex.exec(line);
if (match) {
context.report({
node,
loc: {
line: index + 1,
column: match.index + 1
},
message: "Unexpected tab character."
});
}
});
}
};
}
};
| decaf-emu/huehuetenango | static/node_modules/eslint/lib/rules/no-tabs.js | JavaScript | apache-2.0 | 1,321 |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var cordovaConfig = require("./cordova-config");
describe('parseConfig function', function () {
it('should return {} when the config does not contain a widget', function () {
var result = cordovaConfig.parseConfig({});
expect(result).toEqual({});
});
it('should return a CordovaProject without id or version if config.$ does not exist', function () {
var result = cordovaConfig.parseConfig({
widget: {
name: ['thename'],
}
});
expect(result).toEqual({
name: 'thename',
});
});
it('should return a CordovaProject on success', function () {
var result = cordovaConfig.parseConfig({
widget: {
name: ['thename'],
$: {
id: 'theid',
version: 'theversion'
}
}
});
expect(result).toEqual({
name: 'thename',
id: 'theid',
version: 'theversion'
});
});
});
/*
describe('buildCordovaConfig', () => {
it('should read the config.xml file', (done) => {
let fs: any = jest.genMockFromModule('fs');
fs.readFile = jest.fn().mockReturnValue('blah');
jest.mock('xml2js', function() {
return {
Parser: function() {
return {
parseString: function (data, cb) {
cb(null, 'parseConfigData');
}
};
}
};
});
function daCallback() {
expect(fs.readfile).toHaveBeenCalledWith('config.xml');
done();
}
cordovaConfig.buildCordovaConfig(daCallback, daCallback);
});
});
*/
| vivadaniele/spid-ionic-sdk | node_modules/@ionic/app-scripts/dist/util/cordova-config.spec.js | JavaScript | bsd-3-clause | 1,753 |
define(["./_base", "dojo/_base/lang", "./matrix"],
function (g, lang, m){
function eq(/* Number */ a, /* Number */ b){
// summary:
// compare two FP numbers for equality
return Math.abs(a - b) <= 1e-6 * (Math.abs(a) + Math.abs(b)); // Boolean
}
function calcFromValues(/* Number */ r1, /* Number */ m1, /* Number */ r2, /* Number */ m2){
// summary:
// uses two close FP ration and their original magnitudes to approximate the result
if(!isFinite(r1)){
return r2; // Number
}else if(!isFinite(r2)){
return r1; // Number
}
m1 = Math.abs(m1); m2 = Math.abs(m2);
return (m1 * r1 + m2 * r2) / (m1 + m2); // Number
}
function transpose(matrix){
// matrix: dojox/gfx/matrix.Matrix2D
// a 2D matrix-like object
var M = new m.Matrix2D(matrix);
return lang.mixin(M, {dx: 0, dy: 0, xy: M.yx, yx: M.xy}); // dojox/gfx/matrix.Matrix2D
}
function scaleSign(/* dojox/gfx/matrix.Matrix2D */ matrix){
return (matrix.xx * matrix.yy < 0 || matrix.xy * matrix.yx > 0) ? -1 : 1; // Number
}
function eigenvalueDecomposition(matrix){
// matrix: dojox/gfx/matrix.Matrix2D
// a 2D matrix-like object
var M = m.normalize(matrix),
b = -M.xx - M.yy,
c = M.xx * M.yy - M.xy * M.yx,
d = Math.sqrt(b * b - 4 * c),
l1 = -(b + (b < 0 ? -d : d)) / 2,
l2 = c / l1,
vx1 = M.xy / (l1 - M.xx), vy1 = 1,
vx2 = M.xy / (l2 - M.xx), vy2 = 1;
if(eq(l1, l2)){
vx1 = 1, vy1 = 0, vx2 = 0, vy2 = 1;
}
if(!isFinite(vx1)){
vx1 = 1, vy1 = (l1 - M.xx) / M.xy;
if(!isFinite(vy1)){
vx1 = (l1 - M.yy) / M.yx, vy1 = 1;
if(!isFinite(vx1)){
vx1 = 1, vy1 = M.yx / (l1 - M.yy);
}
}
}
if(!isFinite(vx2)){
vx2 = 1, vy2 = (l2 - M.xx) / M.xy;
if(!isFinite(vy2)){
vx2 = (l2 - M.yy) / M.yx, vy2 = 1;
if(!isFinite(vx2)){
vx2 = 1, vy2 = M.yx / (l2 - M.yy);
}
}
}
var d1 = Math.sqrt(vx1 * vx1 + vy1 * vy1),
d2 = Math.sqrt(vx2 * vx2 + vy2 * vy2);
if(!isFinite(vx1 /= d1)){ vx1 = 0; }
if(!isFinite(vy1 /= d1)){ vy1 = 0; }
if(!isFinite(vx2 /= d2)){ vx2 = 0; }
if(!isFinite(vy2 /= d2)){ vy2 = 0; }
return { // Object
value1: l1,
value2: l2,
vector1: {x: vx1, y: vy1},
vector2: {x: vx2, y: vy2}
};
}
function decomposeSR(/* dojox/gfx/matrix.Matrix2D */ M, /* Object */ result){
// summary:
// decomposes a matrix into [scale, rotate]; no checks are done.
var sign = scaleSign(M),
a = result.angle1 = (Math.atan2(M.yx, M.yy) + Math.atan2(-sign * M.xy, sign * M.xx)) / 2,
cos = Math.cos(a), sin = Math.sin(a);
result.sx = calcFromValues(M.xx / cos, cos, -M.xy / sin, sin);
result.sy = calcFromValues(M.yy / cos, cos, M.yx / sin, sin);
return result; // Object
}
function decomposeRS(/* dojox/gfx/matrix.Matrix2D */ M, /* Object */ result){
// summary:
// decomposes a matrix into [rotate, scale]; no checks are done
var sign = scaleSign(M),
a = result.angle2 = (Math.atan2(sign * M.yx, sign * M.xx) + Math.atan2(-M.xy, M.yy)) / 2,
cos = Math.cos(a), sin = Math.sin(a);
result.sx = calcFromValues(M.xx / cos, cos, M.yx / sin, sin);
result.sy = calcFromValues(M.yy / cos, cos, -M.xy / sin, sin);
return result; // Object
}
return g.decompose = function(matrix){
// summary:
// Decompose a 2D matrix into translation, scaling, and rotation components.
// description:
// This function decompose a matrix into four logical components:
// translation, rotation, scaling, and one more rotation using SVD.
// The components should be applied in following order:
// | [translate, rotate(angle2), scale, rotate(angle1)]
// matrix: dojox/gfx/matrix.Matrix2D
// a 2D matrix-like object
var M = m.normalize(matrix),
result = {dx: M.dx, dy: M.dy, sx: 1, sy: 1, angle1: 0, angle2: 0};
// detect case: [scale]
if(eq(M.xy, 0) && eq(M.yx, 0)){
return lang.mixin(result, {sx: M.xx, sy: M.yy}); // Object
}
// detect case: [scale, rotate]
if(eq(M.xx * M.yx, -M.xy * M.yy)){
return decomposeSR(M, result); // Object
}
// detect case: [rotate, scale]
if(eq(M.xx * M.xy, -M.yx * M.yy)){
return decomposeRS(M, result); // Object
}
// do SVD
var MT = transpose(M),
u = eigenvalueDecomposition([M, MT]),
v = eigenvalueDecomposition([MT, M]),
U = new m.Matrix2D({xx: u.vector1.x, xy: u.vector2.x, yx: u.vector1.y, yy: u.vector2.y}),
VT = new m.Matrix2D({xx: v.vector1.x, xy: v.vector1.y, yx: v.vector2.x, yy: v.vector2.y}),
S = new m.Matrix2D([m.invert(U), M, m.invert(VT)]);
decomposeSR(VT, result);
S.xx *= result.sx;
S.yy *= result.sy;
decomposeRS(U, result);
S.xx *= result.sx;
S.yy *= result.sy;
return lang.mixin(result, {sx: S.xx, sy: S.yy}); // Object
};
});
| avz-cmf/zaboy-middleware | www/js/dojox/gfx/decompose.js | JavaScript | gpl-3.0 | 4,688 |
'use strict';
if (self.importScripts) {
importScripts('/resources/testharness.js');
}
setup({
allow_uncaught_exception: true
});
//
// Straightforward unhandledrejection tests
//
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
p = Promise.reject(e);
}, 'unhandledrejection: from Promise.reject');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
p = new Promise(function(_, reject) {
reject(e);
});
}, 'unhandledrejection: from a synchronous rejection in new Promise');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
p = new Promise(function(_, reject) {
queueTask(function() {
reject(e);
});
});
}, 'unhandledrejection: from a task-delayed rejection');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
p = new Promise(function(_, reject) {
setTimeout(function() {
reject(e);
}, 1);
});
}, 'unhandledrejection: from a setTimeout-delayed rejection');
async_test(function(t) {
var e = new Error();
var e2 = new Error();
var promise2;
onUnhandledSucceed(t, e2, function() { return promise2; });
var unreached = t.unreached_func('promise should not be fulfilled');
promise2 = Promise.reject(e).then(unreached, function(reason) {
t.step(function() {
assert_equals(reason, e);
});
throw e2;
});
}, 'unhandledrejection: from a throw in a rejection handler chained off of Promise.reject');
async_test(function(t) {
var e = new Error();
var e2 = new Error();
var promise2;
onUnhandledSucceed(t, e2, function() { return promise2; });
var unreached = t.unreached_func('promise should not be fulfilled');
promise2 = new Promise(function(_, reject) {
setTimeout(function() {
reject(e);
}, 1);
}).then(unreached, function(reason) {
t.step(function() {
assert_equals(reason, e);
});
throw e2;
});
}, 'unhandledrejection: from a throw in a rejection handler chained off of a setTimeout-delayed rejection');
async_test(function(t) {
var e = new Error();
var e2 = new Error();
var promise2;
onUnhandledSucceed(t, e2, function() { return promise2; });
var promise = new Promise(function(_, reject) {
setTimeout(function() {
reject(e);
mutationObserverMicrotask(function() {
var unreached = t.unreached_func('promise should not be fulfilled');
promise2 = promise.then(unreached, function(reason) {
t.step(function() {
assert_equals(reason, e);
});
throw e2;
});
});
}, 1);
});
}, 'unhandledrejection: from a throw in a rejection handler attached one microtask after a setTimeout-delayed rejection');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
p = Promise.resolve().then(function() {
return Promise.reject(e);
});
}, 'unhandledrejection: from returning a Promise.reject-created rejection in a fulfillment handler');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
p = Promise.resolve().then(function() {
throw e;
});
}, 'unhandledrejection: from a throw in a fulfillment handler');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
p = Promise.resolve().then(function() {
return new Promise(function(_, reject) {
setTimeout(function() {
reject(e);
}, 1);
});
});
}, 'unhandledrejection: from returning a setTimeout-delayed rejection in a fulfillment handler');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
p = Promise.all([Promise.reject(e)]);
}, 'unhandledrejection: from Promise.reject, indirected through Promise.all');
async_test(function(t) {
var p;
var unhandled = function(ev) {
if (ev.promise === p) {
t.step(function() {
assert_equals(ev.reason.name, 'InvalidStateError');
assert_equals(ev.promise, p);
});
t.done();
}
};
addEventListener('unhandledrejection', unhandled);
ensureCleanup(t, unhandled);
p = createImageBitmap(new Blob());
}, 'unhandledrejection: from createImageBitmap which is UA triggered');
//
// Negative unhandledrejection/rejectionhandled tests with immediate attachment
//
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
var unreached = t.unreached_func('promise should not be fulfilled');
p = Promise.reject(e).then(unreached, function() {});
}, 'no unhandledrejection/rejectionhandled: rejection handler attached synchronously to a promise from Promise.reject');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
var unreached = t.unreached_func('promise should not be fulfilled');
p = Promise.all([Promise.reject(e)]).then(unreached, function() {});
}, 'no unhandledrejection/rejectionhandled: rejection handler attached synchronously to a promise from ' +
'Promise.reject, indirecting through Promise.all');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
var unreached = t.unreached_func('promise should not be fulfilled');
p = new Promise(function(_, reject) {
reject(e);
}).then(unreached, function() {});
}, 'no unhandledrejection/rejectionhandled: rejection handler attached synchronously to a synchronously-rejected ' +
'promise created with new Promise');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
var unreached = t.unreached_func('promise should not be fulfilled');
p = Promise.resolve().then(function() {
throw e;
}).then(unreached, function(reason) {
t.step(function() {
assert_equals(reason, e);
});
});
}, 'no unhandledrejection/rejectionhandled: rejection handler attached synchronously to a promise created from ' +
'throwing in a fulfillment handler');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
var unreached = t.unreached_func('promise should not be fulfilled');
p = Promise.resolve().then(function() {
return Promise.reject(e);
}).then(unreached, function(reason) {
t.step(function() {
assert_equals(reason, e);
});
});
}, 'no unhandledrejection/rejectionhandled: rejection handler attached synchronously to a promise created from ' +
'returning a Promise.reject-created promise in a fulfillment handler');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
var unreached = t.unreached_func('promise should not be fulfilled');
p = Promise.resolve().then(function() {
return new Promise(function(_, reject) {
setTimeout(function() {
reject(e);
}, 1);
});
}).then(unreached, function(reason) {
t.step(function() {
assert_equals(reason, e);
});
});
}, 'no unhandledrejection/rejectionhandled: rejection handler attached synchronously to a promise created from ' +
'returning a setTimeout-delayed rejection in a fulfillment handler');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
queueTask(function() {
p = Promise.resolve().then(function() {
return Promise.reject(e);
})
.catch(function() {});
});
}, 'no unhandledrejection/rejectionhandled: all inside a queued task, a rejection handler attached synchronously to ' +
'a promise created from returning a Promise.reject-created promise in a fulfillment handler');
async_test(function(t) {
var p;
onUnhandledFail(t, function() { return p; });
var unreached = t.unreached_func('promise should not be fulfilled');
p = createImageBitmap(new Blob()).then(unreached, function() {});
}, 'no unhandledrejection/rejectionhandled: rejection handler attached synchronously to a promise created from ' +
'createImageBitmap');
//
// Negative unhandledrejection/rejectionhandled tests with microtask-delayed attachment
//
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
p = Promise.reject(e);
mutationObserverMicrotask(function() {
var unreached = t.unreached_func('promise should not be fulfilled');
p.then(unreached, function() {});
});
}, 'delayed handling: a microtask delay before attaching a handler prevents both events (Promise.reject-created ' +
'promise)');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
p = new Promise(function(_, reject) {
reject(e);
});
mutationObserverMicrotask(function() {
var unreached = t.unreached_func('promise should not be fulfilled');
p.then(unreached, function() {});
});
}, 'delayed handling: a microtask delay before attaching a handler prevents both events (immediately-rejected new ' +
'Promise-created promise)');
async_test(function(t) {
var e = new Error();
var p1;
var p2;
onUnhandledFail(t, function() { return p1; });
onUnhandledFail(t, function() { return p2; });
p1 = new Promise(function(_, reject) {
mutationObserverMicrotask(function() {
reject(e);
});
});
p2 = Promise.all([p1]);
mutationObserverMicrotask(function() {
var unreached = t.unreached_func('promise should not be fulfilled');
p2.then(unreached, function() {});
});
}, 'delayed handling: a microtask delay before attaching the handler, and before rejecting the promise, indirected ' +
'through Promise.all');
//
// Negative unhandledrejection/rejectionhandled tests with nested-microtask-delayed attachment
//
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
p = Promise.reject(e);
mutationObserverMicrotask(function() {
Promise.resolve().then(function() {
mutationObserverMicrotask(function() {
Promise.resolve().then(function() {
p.catch(function() {});
});
});
});
});
}, 'microtask nesting: attaching a handler inside a combination of mutationObserverMicrotask + promise microtasks');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
queueTask(function() {
p = Promise.reject(e);
mutationObserverMicrotask(function() {
Promise.resolve().then(function() {
mutationObserverMicrotask(function() {
Promise.resolve().then(function() {
p.catch(function() {});
});
});
});
});
});
}, 'microtask nesting: attaching a handler inside a combination of mutationObserverMicrotask + promise microtasks, ' +
'all inside a queueTask');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
setTimeout(function() {
p = Promise.reject(e);
mutationObserverMicrotask(function() {
Promise.resolve().then(function() {
mutationObserverMicrotask(function() {
Promise.resolve().then(function() {
p.catch(function() {});
});
});
});
});
}, 0);
}, 'microtask nesting: attaching a handler inside a combination of mutationObserverMicrotask + promise microtasks, ' +
'all inside a setTimeout');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
p = Promise.reject(e);
Promise.resolve().then(function() {
mutationObserverMicrotask(function() {
Promise.resolve().then(function() {
mutationObserverMicrotask(function() {
p.catch(function() {});
});
});
});
});
}, 'microtask nesting: attaching a handler inside a combination of promise microtasks + mutationObserverMicrotask');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
queueTask(function() {
p = Promise.reject(e);
Promise.resolve().then(function() {
mutationObserverMicrotask(function() {
Promise.resolve().then(function() {
mutationObserverMicrotask(function() {
p.catch(function() {});
});
});
});
});
});
}, 'microtask nesting: attaching a handler inside a combination of promise microtasks + mutationObserverMicrotask, ' +
'all inside a queueTask');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
setTimeout(function() {
p = Promise.reject(e);
Promise.resolve().then(function() {
mutationObserverMicrotask(function() {
Promise.resolve().then(function() {
mutationObserverMicrotask(function() {
p.catch(function() {});
});
});
});
});
}, 0);
}, 'microtask nesting: attaching a handler inside a combination of promise microtasks + mutationObserverMicrotask, ' +
'all inside a setTimeout');
// For workers, queueTask() involves posting tasks to other threads, so
// the following tests don't work there.
if ('document' in self) {
//
// Negative unhandledrejection/rejectionhandled tests with task-delayed attachment
//
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
var _reject;
p = new Promise(function(_, reject) {
_reject = reject;
});
_reject(e);
queueTask(function() {
var unreached = t.unreached_func('promise should not be fulfilled');
p.then(unreached, function() {});
});
}, 'delayed handling: a task delay before attaching a handler prevents unhandledrejection');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
p = Promise.reject(e);
queueTask(function() {
Promise.resolve().then(function() {
p.catch(function() {});
});
});
}, 'delayed handling: queueTask after promise creation/rejection, plus promise microtasks, is not too late to ' +
'attach a rejection handler');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
queueTask(function() {
Promise.resolve().then(function() {
Promise.resolve().then(function() {
Promise.resolve().then(function() {
Promise.resolve().then(function() {
p.catch(function() {});
});
});
});
});
});
p = Promise.reject(e);
}, 'delayed handling: queueTask before promise creation/rejection, plus many promise microtasks, is not too ' +
'late to attach a rejection handler');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledFail(t, function() { return p; });
p = Promise.reject(e);
queueTask(function() {
Promise.resolve().then(function() {
Promise.resolve().then(function() {
Promise.resolve().then(function() {
Promise.resolve().then(function() {
p.catch(function() {});
});
});
});
});
});
}, 'delayed handling: queueTask after promise creation/rejection, plus many promise microtasks, is not too ' +
'late to attach a rejection handler');
}
//
// Positive unhandledrejection/rejectionhandled tests with delayed attachment
//
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
var _reject;
p = new Promise(function(_, reject) {
_reject = reject;
});
_reject(e);
queueTask(function() {
queueTask(function() {
var unreached = t.unreached_func('promise should not be fulfilled');
p.then(unreached, function() {});
});
});
}, 'delayed handling: a nested-task delay before attaching a handler causes unhandledrejection');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
p = Promise.reject(e);
queueTask(function() {
queueTask(function() {
Promise.resolve().then(function() {
p.catch(function() {});
});
});
});
}, 'delayed handling: a nested-queueTask after promise creation/rejection, plus promise microtasks, is too ' +
'late to attach a rejection handler');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
queueTask(function() {
queueTask(function() {
Promise.resolve().then(function() {
Promise.resolve().then(function() {
Promise.resolve().then(function() {
Promise.resolve().then(function() {
p.catch(function() {});
});
});
});
});
});
});
p = Promise.reject(e);
}, 'delayed handling: a nested-queueTask before promise creation/rejection, plus many promise microtasks, is ' +
'too late to attach a rejection handler');
async_test(function(t) {
var e = new Error();
var p;
onUnhandledSucceed(t, e, function() { return p; });
p = Promise.reject(e);
queueTask(function() {
queueTask(function() {
Promise.resolve().then(function() {
Promise.resolve().then(function() {
Promise.resolve().then(function() {
Promise.resolve().then(function() {
p.catch(function() {});
});
});
});
});
});
});
}, 'delayed handling: a nested-queueTask after promise creation/rejection, plus many promise microtasks, is ' +
'too late to attach a rejection handler');
async_test(function(t) {
var unhandledPromises = [];
var unhandledReasons = [];
var e = new Error();
var p;
var unhandled = function(ev) {
if (ev.promise === p) {
t.step(function() {
unhandledPromises.push(ev.promise);
unhandledReasons.push(ev.reason);
});
}
};
var handled = function(ev) {
if (ev.promise === p) {
t.step(function() {
assert_array_equals(unhandledPromises, [p]);
assert_array_equals(unhandledReasons, [e]);
assert_equals(ev.promise, p);
assert_equals(ev.reason, e);
});
}
};
addEventListener('unhandledrejection', unhandled);
addEventListener('rejectionhandled', handled);
ensureCleanup(t, unhandled, handled);
p = new Promise(function() {
throw e;
});
setTimeout(function() {
var unreached = t.unreached_func('promise should not be fulfilled');
p.then(unreached, function(reason) {
assert_equals(reason, e);
setTimeout(function() { t.done(); }, 10);
});
}, 10);
}, 'delayed handling: delaying handling by setTimeout(,10) will cause both events to fire');
async_test(function(t) {
var unhandledPromises = [];
var unhandledReasons = [];
var p;
var unhandled = function(ev) {
if (ev.promise === p) {
t.step(function() {
unhandledPromises.push(ev.promise);
unhandledReasons.push(ev.reason.name);
});
}
};
var handled = function(ev) {
if (ev.promise === p) {
t.step(function() {
assert_array_equals(unhandledPromises, [p]);
assert_array_equals(unhandledReasons, ['InvalidStateError']);
assert_equals(ev.promise, p);
assert_equals(ev.reason.name, 'InvalidStateError');
});
}
};
addEventListener('unhandledrejection', unhandled);
addEventListener('rejectionhandled', handled);
ensureCleanup(t, unhandled, handled);
p = createImageBitmap(new Blob());
setTimeout(function() {
var unreached = t.unreached_func('promise should not be fulfilled');
p.then(unreached, function(reason) {
assert_equals(reason.name, 'InvalidStateError');
setTimeout(function() { t.done(); }, 10);
});
}, 10);
}, 'delayed handling: delaying handling rejected promise created from createImageBitmap will cause both events to fire');
//
// Miscellaneous tests about integration with the rest of the platform
//
async_test(function(t) {
var e = new Error();
var l = function(ev) {
var order = [];
mutationObserverMicrotask(function() {
order.push(1);
});
setTimeout(function() {
order.push(2);
t.step(function() {
assert_array_equals(order, [1, 2]);
});
t.done();
}, 1);
};
addEventListener('unhandledrejection', l);
ensureCleanup(t, l);
Promise.reject(e);
}, 'mutationObserverMicrotask vs. queueTask ordering is not disturbed inside unhandledrejection events');
// For workers, queueTask() involves posting tasks to other threads, so
// the following tests don't work there.
if ('document' in self) {
// For the next two see https://github.com/domenic/unhandled-rejections-browser-spec/issues/2#issuecomment-121121695
// and the following comments.
async_test(function(t) {
var sequenceOfEvents = [];
addEventListener('unhandledrejection', l);
ensureCleanup(t, l);
var p1 = Promise.reject();
var p2;
queueTask(function() {
p2 = Promise.reject();
queueTask(function() {
sequenceOfEvents.push('queueTask');
checkSequence();
});
});
function l(ev) {
if (ev.promise === p1 || ev.promise === p2) {
sequenceOfEvents.push(ev.promise);
checkSequence();
}
}
function checkSequence() {
if (sequenceOfEvents.length === 3) {
t.step(function() {
assert_array_equals(sequenceOfEvents, [p1, 'queueTask', p2]);
});
t.done();
}
}
}, 'queueTask ordering vs. the task queued for unhandled rejection notification (1)');
async_test(function(t) {
var sequenceOfEvents = [];
addEventListener('unhandledrejection', l);
ensureCleanup(t, l);
var p2;
queueTask(function() {
p2 = Promise.reject();
queueTask(function() {
sequenceOfEvents.push('queueTask');
checkSequence();
});
});
function l(ev) {
if (ev.promise == p2) {
sequenceOfEvents.push(ev.promise);
checkSequence();
}
}
function checkSequence() {
if (sequenceOfEvents.length === 2) {
t.step(function() {
assert_array_equals(sequenceOfEvents, ['queueTask', p2]);
});
t.done();
}
}
}, 'queueTask ordering vs. the task queued for unhandled rejection notification (2)');
async_test(function(t) {
var sequenceOfEvents = [];
addEventListener('unhandledrejection', unhandled);
addEventListener('rejectionhandled', handled);
ensureCleanup(t, unhandled, handled);
var p = Promise.reject();
function unhandled(ev) {
if (ev.promise === p) {
sequenceOfEvents.push('unhandled');
checkSequence();
setTimeout(function() {
queueTask(function() {
sequenceOfEvents.push('task before catch');
checkSequence();
});
p.catch(function() {
sequenceOfEvents.push('catch');
checkSequence();
});
queueTask(function() {
sequenceOfEvents.push('task after catch');
checkSequence();
});
sequenceOfEvents.push('after catch');
checkSequence();
}, 10);
}
}
function handled(ev) {
if (ev.promise === p) {
sequenceOfEvents.push('handled');
checkSequence();
}
}
function checkSequence() {
if (sequenceOfEvents.length === 6) {
t.step(function() {
assert_array_equals(sequenceOfEvents,
['unhandled', 'after catch', 'catch', 'task before catch', 'handled', 'task after catch']);
});
t.done();
}
}
}, 'rejectionhandled is dispatched from a queued task, and not immediately');
}
//
// HELPERS
//
// This function queues a task in "DOM manipulation task source" in window
// context, but not in workers.
function queueTask(f) {
if ('document' in self) {
var d = document.createElement("details");
d.ontoggle = function() {
f();
};
d.setAttribute("open", "");
} else {
// We need to fix this to use something that can queue tasks in
// "DOM manipulation task source" to ensure the order is correct
var channel = new MessageChannel();
channel.port1.onmessage = function() { channel.port1.close(); f(); };
channel.port2.postMessage('abusingpostmessageforfunandprofit');
channel.port2.close();
}
}
function mutationObserverMicrotask(f) {
if ('document' in self) {
var observer = new MutationObserver(function() { f(); });
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
node.data = 'foo';
} else {
// We don't have mutation observers on workers, so just post a promise-based
// microtask.
Promise.resolve().then(function() { f(); });
}
}
function onUnhandledSucceed(t, expectedReason, expectedPromiseGetter) {
var l = function(ev) {
if (ev.promise === expectedPromiseGetter()) {
t.step(function() {
assert_equals(ev.reason, expectedReason);
assert_equals(ev.promise, expectedPromiseGetter());
});
t.done();
}
};
addEventListener('unhandledrejection', l);
ensureCleanup(t, l);
}
function onUnhandledFail(t, expectedPromiseGetter) {
var unhandled = function(evt) {
if (evt.promise === expectedPromiseGetter()) {
t.step(function() {
assert_unreached('unhandledrejection event is not supposed to be triggered');
});
}
};
var handled = function(evt) {
if (evt.promise === expectedPromiseGetter()) {
t.step(function() {
assert_unreached('rejectionhandled event is not supposed to be triggered');
});
}
};
addEventListener('unhandledrejection', unhandled);
addEventListener('rejectionhandled', handled);
ensureCleanup(t, unhandled, handled);
setTimeout(function() {
t.done();
}, 10);
}
function ensureCleanup(t, unhandled, handled) {
t.add_cleanup(function() {
if (unhandled)
removeEventListener('unhandledrejection', unhandled);
if (handled)
removeEventListener('rejectionhandled', handled);
});
}
done();
| scheib/chromium | third_party/blink/web_tests/external/wpt/html/webappapis/scripting/processing-model-2/unhandled-promise-rejections/support/promise-rejection-events.js | JavaScript | bsd-3-clause | 26,469 |
// This file contains methods responsible for removing a node.
import { hooks } from "./lib/removal-hooks";
export function remove() {
this._assertUnremoved();
this.resync();
if (this._callRemovalHooks()) {
this._markRemoved();
return;
}
this.shareCommentsWithSiblings();
this._remove();
this._markRemoved();
}
export function _callRemovalHooks() {
for (let fn of (hooks: Array<Function>)) {
if (fn(this, this.parentPath)) return true;
}
}
export function _remove() {
if (Array.isArray(this.container)) {
this.container.splice(this.key, 1);
this.updateSiblingKeys(this.key, -1);
} else {
this._replaceWith(null);
}
}
export function _markRemoved() {
this.shouldSkip = true;
this.removed = true;
this.node = null;
}
export function _assertUnremoved() {
if (this.removed) {
throw this.buildCodeFrameError("NodePath has been removed so is read-only.");
}
}
| forivall/tacoscript | packages/comal-traverse/src/path/removal.js | JavaScript | mit | 934 |
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var numPings = 0;
chrome.extension.onRequest.addListener(function(data) {
if (data != "ping")
chrome.test.fail("Unexpected request: " + JSON.stringify(data));
if (++numPings == 2)
chrome.test.notifyPass();
});
chrome.test.getConfig(function(config) {
var test_file_url = "http://localhost:PORT/files/extensions/test_file.html"
.replace(/PORT/, config.testServer.port);
// Add a window.
var w = window.open(test_file_url);
// Add an iframe.
var iframe = document.createElement("iframe");
iframe.src = test_file_url;
document.getElementById("iframeContainer").appendChild(iframe);
});
| plxaye/chromium | src/chrome/test/data/extensions/api_test/content_scripts/extension_process/background.js | JavaScript | apache-2.0 | 789 |
exports.setupMockScopes = function (nock) { var scopes = []; var scope; scope =
nock('https://login.live.com:443')
.post('/accesstoken.srf', "grant_type=client_credentials&client_id=ms-app%3A%2F%2Fs-1-15-2-145565886-1510793020-2797717260-1526195933-3912359816-44086043-2211002316&client_secret=FF9yfJLxSH3uI32wNKGye643bAZ4zBz7&scope=notify.windows.com")
.reply(200, "{\"token_type\":\"bearer\",\"access_token\":\"EgAaAQMAAAAEgAAACoAAnbulrnfYRgTGFe6tudBvFCf/ng+gabEI1++PZpSEktmcoU3/Tj9tEKuZj4Q1eV+UJhR4DWtNgnpVgBq9CkTQfEyCqZ/kUWtlAk98dwXfsmFJMI5FL/AvPnD2CCNiXtuTNCs/HB10Hbr1ZTemjbdby5Ht8AIhQqr9Cz7KI6sZM5eJAFoAiQAAAAAAaoEORO9LJFHvSyRR60gEAA0ANjcuMTg1LjE0OC44AAAAAABcAG1zLWFwcDovL3MtMS0xNS0yLTE0NTU2NTg4Ni0xNTEwNzkzMDIwLTI3OTc3MTcyNjAtMTUyNjE5NTkzMy0zOTEyMzU5ODE2LTQ0MDg2MDQzLTIyMTEwMDIzMTYA\",\"expires_in\":86400}", { 'cache-control': 'no-store',
'content-length': '436',
'content-type': 'application/json',
server: 'Microsoft-IIS/7.5',
ppserver: 'PPV: 30 H: BAYIDSLGN1I33 V: 0',
date: 'Wed, 20 Feb 2013 04:07:10 GMT',
connection: 'close' });
scopes.push(scope);scope =
nock('https://bn1.notify.windows.com:443')
.post('/?token=AgYAAACFGdWBiRCTypHebfvngI7DuNBXWuGjdiczDOZ7bSgkbCRrD2M1b10CpzCmipzknHbU4nLzapQbooXzJ%2fVwHAfSl%2fWMk8OsetohEVMlsIicoLP99rDg7g2AdENA99DZoAU%3d', "<tile><visual><binding template=\"TileWideSmallImageAndText01\"><image id=\"1\" src=\"http://textParam1.com\" alt=\"http://textParam2.com\"/><text id=\"1\">http://textParam3.com</text></binding></visual></tile>")
.reply(200, "", { 'content-length': '0',
'x-wns-notificationstatus': 'received',
'x-wns-msg-id': '72C92964293B8020',
'x-wns-debug-trace': 'BN1WNS1011837',
date: 'Wed, 20 Feb 2013 04:07:12 GMT' });
scopes.push(scope);return scopes; }; | beat-at-hartwig/wns | test/nock/TileWideSmallImageAndText01-success.js | JavaScript | apache-2.0 | 1,750 |
/*! DataTables 1.10.7
* ©2008-2015 SpryMedia Ltd - datatables.net/license
*/
(function(Ea,Q,k){var P=function(h){function W(a){var b,c,e={};h.each(a,function(d){if((b=d.match(/^([^A-Z]+?)([A-Z])/))&&-1!=="a aa ai ao as b fn i m o s ".indexOf(b[1]+" "))c=d.replace(b[0],b[2].toLowerCase()),e[c]=d,"o"===b[1]&&W(a[d])});a._hungarianMap=e}function H(a,b,c){a._hungarianMap||W(a);var e;h.each(b,function(d){e=a._hungarianMap[d];if(e!==k&&(c||b[e]===k))"o"===e.charAt(0)?(b[e]||(b[e]={}),h.extend(!0,b[e],b[d]),H(a[e],b[e],c)):b[e]=b[d]})}function P(a){var b=m.defaults.oLanguage,c=a.sZeroRecords;
!a.sEmptyTable&&(c&&"No data available in table"===b.sEmptyTable)&&E(a,a,"sZeroRecords","sEmptyTable");!a.sLoadingRecords&&(c&&"Loading..."===b.sLoadingRecords)&&E(a,a,"sZeroRecords","sLoadingRecords");a.sInfoThousands&&(a.sThousands=a.sInfoThousands);(a=a.sDecimal)&&db(a)}function eb(a){A(a,"ordering","bSort");A(a,"orderMulti","bSortMulti");A(a,"orderClasses","bSortClasses");A(a,"orderCellsTop","bSortCellsTop");A(a,"order","aaSorting");A(a,"orderFixed","aaSortingFixed");A(a,"paging","bPaginate");
A(a,"pagingType","sPaginationType");A(a,"pageLength","iDisplayLength");A(a,"searching","bFilter");if(a=a.aoSearchCols)for(var b=0,c=a.length;b<c;b++)a[b]&&H(m.models.oSearch,a[b])}function fb(a){A(a,"orderable","bSortable");A(a,"orderData","aDataSort");A(a,"orderSequence","asSorting");A(a,"orderDataType","sortDataType");var b=a.aDataSort;b&&!h.isArray(b)&&(a.aDataSort=[b])}function gb(a){var a=a.oBrowser,b=h("<div/>").css({position:"absolute",top:0,left:0,height:1,width:1,overflow:"hidden"}).append(h("<div/>").css({position:"absolute",
top:1,left:1,width:100,overflow:"scroll"}).append(h('<div class="test"/>').css({width:"100%",height:10}))).appendTo("body"),c=b.find(".test");a.bScrollOversize=100===c[0].offsetWidth;a.bScrollbarLeft=1!==Math.round(c.offset().left);b.remove()}function hb(a,b,c,e,d,f){var g,j=!1;c!==k&&(g=c,j=!0);for(;e!==d;)a.hasOwnProperty(e)&&(g=j?b(g,a[e],e,a):a[e],j=!0,e+=f);return g}function Fa(a,b){var c=m.defaults.column,e=a.aoColumns.length,c=h.extend({},m.models.oColumn,c,{nTh:b?b:Q.createElement("th"),sTitle:c.sTitle?
c.sTitle:b?b.innerHTML:"",aDataSort:c.aDataSort?c.aDataSort:[e],mData:c.mData?c.mData:e,idx:e});a.aoColumns.push(c);c=a.aoPreSearchCols;c[e]=h.extend({},m.models.oSearch,c[e]);ka(a,e,h(b).data())}function ka(a,b,c){var b=a.aoColumns[b],e=a.oClasses,d=h(b.nTh);if(!b.sWidthOrig){b.sWidthOrig=d.attr("width")||null;var f=(d.attr("style")||"").match(/width:\s*(\d+[pxem%]+)/);f&&(b.sWidthOrig=f[1])}c!==k&&null!==c&&(fb(c),H(m.defaults.column,c),c.mDataProp!==k&&!c.mData&&(c.mData=c.mDataProp),c.sType&&
(b._sManualType=c.sType),c.className&&!c.sClass&&(c.sClass=c.className),h.extend(b,c),E(b,c,"sWidth","sWidthOrig"),c.iDataSort!==k&&(b.aDataSort=[c.iDataSort]),E(b,c,"aDataSort"));var g=b.mData,j=R(g),i=b.mRender?R(b.mRender):null,c=function(a){return"string"===typeof a&&-1!==a.indexOf("@")};b._bAttrSrc=h.isPlainObject(g)&&(c(g.sort)||c(g.type)||c(g.filter));b.fnGetData=function(a,b,c){var e=j(a,b,k,c);return i&&b?i(e,b,a,c):e};b.fnSetData=function(a,b,c){return S(g)(a,b,c)};"number"!==typeof g&&
(a._rowReadObject=!0);a.oFeatures.bSort||(b.bSortable=!1,d.addClass(e.sSortableNone));a=-1!==h.inArray("asc",b.asSorting);c=-1!==h.inArray("desc",b.asSorting);!b.bSortable||!a&&!c?(b.sSortingClass=e.sSortableNone,b.sSortingClassJUI=""):a&&!c?(b.sSortingClass=e.sSortableAsc,b.sSortingClassJUI=e.sSortJUIAscAllowed):!a&&c?(b.sSortingClass=e.sSortableDesc,b.sSortingClassJUI=e.sSortJUIDescAllowed):(b.sSortingClass=e.sSortable,b.sSortingClassJUI=e.sSortJUI)}function X(a){if(!1!==a.oFeatures.bAutoWidth){var b=
a.aoColumns;Ga(a);for(var c=0,e=b.length;c<e;c++)b[c].nTh.style.width=b[c].sWidth}b=a.oScroll;(""!==b.sY||""!==b.sX)&&Y(a);w(a,null,"column-sizing",[a])}function la(a,b){var c=Z(a,"bVisible");return"number"===typeof c[b]?c[b]:null}function $(a,b){var c=Z(a,"bVisible"),c=h.inArray(b,c);return-1!==c?c:null}function aa(a){return Z(a,"bVisible").length}function Z(a,b){var c=[];h.map(a.aoColumns,function(a,d){a[b]&&c.push(d)});return c}function Ha(a){var b=a.aoColumns,c=a.aoData,e=m.ext.type.detect,d,
f,g,j,i,h,l,q,n;d=0;for(f=b.length;d<f;d++)if(l=b[d],n=[],!l.sType&&l._sManualType)l.sType=l._sManualType;else if(!l.sType){g=0;for(j=e.length;g<j;g++){i=0;for(h=c.length;i<h;i++){n[i]===k&&(n[i]=x(a,i,d,"type"));q=e[g](n[i],a);if(!q&&g!==e.length-1)break;if("html"===q)break}if(q){l.sType=q;break}}l.sType||(l.sType="string")}}function ib(a,b,c,e){var d,f,g,j,i,o,l=a.aoColumns;if(b)for(d=b.length-1;0<=d;d--){o=b[d];var q=o.targets!==k?o.targets:o.aTargets;h.isArray(q)||(q=[q]);f=0;for(g=q.length;f<
g;f++)if("number"===typeof q[f]&&0<=q[f]){for(;l.length<=q[f];)Fa(a);e(q[f],o)}else if("number"===typeof q[f]&&0>q[f])e(l.length+q[f],o);else if("string"===typeof q[f]){j=0;for(i=l.length;j<i;j++)("_all"==q[f]||h(l[j].nTh).hasClass(q[f]))&&e(j,o)}}if(c){d=0;for(a=c.length;d<a;d++)e(d,c[d])}}function K(a,b,c,e){var d=a.aoData.length,f=h.extend(!0,{},m.models.oRow,{src:c?"dom":"data"});f._aData=b;a.aoData.push(f);for(var b=a.aoColumns,f=0,g=b.length;f<g;f++)c&&Ia(a,d,f,x(a,d,f)),b[f].sType=null;a.aiDisplayMaster.push(d);
(c||!a.oFeatures.bDeferRender)&&Ja(a,d,c,e);return d}function ma(a,b){var c;b instanceof h||(b=h(b));return b.map(function(b,d){c=na(a,d);return K(a,c.data,d,c.cells)})}function x(a,b,c,e){var d=a.iDraw,f=a.aoColumns[c],g=a.aoData[b]._aData,j=f.sDefaultContent,c=f.fnGetData(g,e,{settings:a,row:b,col:c});if(c===k)return a.iDrawError!=d&&null===j&&(I(a,0,"Requested unknown parameter "+("function"==typeof f.mData?"{function}":"'"+f.mData+"'")+" for row "+b,4),a.iDrawError=d),j;if((c===g||null===c)&&
null!==j)c=j;else if("function"===typeof c)return c.call(g);return null===c&&"display"==e?"":c}function Ia(a,b,c,e){a.aoColumns[c].fnSetData(a.aoData[b]._aData,e,{settings:a,row:b,col:c})}function Ka(a){return h.map(a.match(/(\\.|[^\.])+/g),function(a){return a.replace(/\\./g,".")})}function R(a){if(h.isPlainObject(a)){var b={};h.each(a,function(a,c){c&&(b[a]=R(c))});return function(a,c,f,g){var j=b[c]||b._;return j!==k?j(a,c,f,g):a}}if(null===a)return function(a){return a};if("function"===typeof a)return function(b,
c,f,g){return a(b,c,f,g)};if("string"===typeof a&&(-1!==a.indexOf(".")||-1!==a.indexOf("[")||-1!==a.indexOf("("))){var c=function(a,b,f){var g,j;if(""!==f){j=Ka(f);for(var i=0,h=j.length;i<h;i++){f=j[i].match(ba);g=j[i].match(T);if(f){j[i]=j[i].replace(ba,"");""!==j[i]&&(a=a[j[i]]);g=[];j.splice(0,i+1);j=j.join(".");i=0;for(h=a.length;i<h;i++)g.push(c(a[i],b,j));a=f[0].substring(1,f[0].length-1);a=""===a?g:g.join(a);break}else if(g){j[i]=j[i].replace(T,"");a=a[j[i]]();continue}if(null===a||a[j[i]]===
k)return k;a=a[j[i]]}}return a};return function(b,d){return c(b,d,a)}}return function(b){return b[a]}}function S(a){if(h.isPlainObject(a))return S(a._);if(null===a)return function(){};if("function"===typeof a)return function(b,e,d){a(b,"set",e,d)};if("string"===typeof a&&(-1!==a.indexOf(".")||-1!==a.indexOf("[")||-1!==a.indexOf("("))){var b=function(a,e,d){var d=Ka(d),f;f=d[d.length-1];for(var g,j,i=0,h=d.length-1;i<h;i++){g=d[i].match(ba);j=d[i].match(T);if(g){d[i]=d[i].replace(ba,"");a[d[i]]=[];
f=d.slice();f.splice(0,i+1);g=f.join(".");j=0;for(h=e.length;j<h;j++)f={},b(f,e[j],g),a[d[i]].push(f);return}j&&(d[i]=d[i].replace(T,""),a=a[d[i]](e));if(null===a[d[i]]||a[d[i]]===k)a[d[i]]={};a=a[d[i]]}if(f.match(T))a[f.replace(T,"")](e);else a[f.replace(ba,"")]=e};return function(c,e){return b(c,e,a)}}return function(b,e){b[a]=e}}function La(a){return D(a.aoData,"_aData")}function oa(a){a.aoData.length=0;a.aiDisplayMaster.length=0;a.aiDisplay.length=0}function pa(a,b,c){for(var e=-1,d=0,f=a.length;d<
f;d++)a[d]==b?e=d:a[d]>b&&a[d]--; -1!=e&&c===k&&a.splice(e,1)}function ca(a,b,c,e){var d=a.aoData[b],f,g=function(c,f){for(;c.childNodes.length;)c.removeChild(c.firstChild);c.innerHTML=x(a,b,f,"display")};if("dom"===c||(!c||"auto"===c)&&"dom"===d.src)d._aData=na(a,d,e,e===k?k:d._aData).data;else{var j=d.anCells;if(j)if(e!==k)g(j[e],e);else{c=0;for(f=j.length;c<f;c++)g(j[c],c)}}d._aSortData=null;d._aFilterData=null;g=a.aoColumns;if(e!==k)g[e].sType=null;else{c=0;for(f=g.length;c<f;c++)g[c].sType=null;
Ma(d)}}function na(a,b,c,e){var d=[],f=b.firstChild,g,j=0,i,o=a.aoColumns,l=a._rowReadObject,e=e||l?{}:[],q=function(a,b){if("string"===typeof a){var c=a.indexOf("@");-1!==c&&(c=a.substring(c+1),S(a)(e,b.getAttribute(c)))}},a=function(a){if(c===k||c===j)g=o[j],i=h.trim(a.innerHTML),g&&g._bAttrSrc?(S(g.mData._)(e,i),q(g.mData.sort,a),q(g.mData.type,a),q(g.mData.filter,a)):l?(g._setter||(g._setter=S(g.mData)),g._setter(e,i)):e[j]=i;j++};if(f)for(;f;){b=f.nodeName.toUpperCase();if("TD"==b||"TH"==b)a(f),
d.push(f);f=f.nextSibling}else{d=b.anCells;f=0;for(b=d.length;f<b;f++)a(d[f])}return{data:e,cells:d}}function Ja(a,b,c,e){var d=a.aoData[b],f=d._aData,g=[],j,i,h,l,q;if(null===d.nTr){j=c||Q.createElement("tr");d.nTr=j;d.anCells=g;j._DT_RowIndex=b;Ma(d);l=0;for(q=a.aoColumns.length;l<q;l++){h=a.aoColumns[l];i=c?e[l]:Q.createElement(h.sCellType);g.push(i);if(!c||h.mRender||h.mData!==l)i.innerHTML=x(a,b,l,"display");h.sClass&&(i.className+=" "+h.sClass);h.bVisible&&!c?j.appendChild(i):!h.bVisible&&c&&
i.parentNode.removeChild(i);h.fnCreatedCell&&h.fnCreatedCell.call(a.oInstance,i,x(a,b,l),f,b,l)}w(a,"aoRowCreatedCallback",null,[j,f,b])}d.nTr.setAttribute("role","row")}function Ma(a){var b=a.nTr,c=a._aData;if(b){c.DT_RowId&&(b.id=c.DT_RowId);if(c.DT_RowClass){var e=c.DT_RowClass.split(" ");a.__rowc=a.__rowc?Na(a.__rowc.concat(e)):e;h(b).removeClass(a.__rowc.join(" ")).addClass(c.DT_RowClass)}c.DT_RowAttr&&h(b).attr(c.DT_RowAttr);c.DT_RowData&&h(b).data(c.DT_RowData)}}function jb(a){var b,c,e,d,
f,g=a.nTHead,j=a.nTFoot,i=0===h("th, td",g).length,o=a.oClasses,l=a.aoColumns;i&&(d=h("<tr/>").appendTo(g));b=0;for(c=l.length;b<c;b++)f=l[b],e=h(f.nTh).addClass(f.sClass),i&&e.appendTo(d),a.oFeatures.bSort&&(e.addClass(f.sSortingClass),!1!==f.bSortable&&(e.attr("tabindex",a.iTabIndex).attr("aria-controls",a.sTableId),Oa(a,f.nTh,b))),f.sTitle!=e.html()&&e.html(f.sTitle),Pa(a,"header")(a,e,f,o);i&&da(a.aoHeader,g);h(g).find(">tr").attr("role","row");h(g).find(">tr>th, >tr>td").addClass(o.sHeaderTH);
h(j).find(">tr>th, >tr>td").addClass(o.sFooterTH);if(null!==j){a=a.aoFooter[0];b=0;for(c=a.length;b<c;b++)f=l[b],f.nTf=a[b].cell,f.sClass&&h(f.nTf).addClass(f.sClass)}}function ea(a,b,c){var e,d,f,g=[],j=[],i=a.aoColumns.length,o;if(b){c===k&&(c=!1);e=0;for(d=b.length;e<d;e++){g[e]=b[e].slice();g[e].nTr=b[e].nTr;for(f=i-1;0<=f;f--)!a.aoColumns[f].bVisible&&!c&&g[e].splice(f,1);j.push([])}e=0;for(d=g.length;e<d;e++){if(a=g[e].nTr)for(;f=a.firstChild;)a.removeChild(f);f=0;for(b=g[e].length;f<b;f++)if(o=
i=1,j[e][f]===k){a.appendChild(g[e][f].cell);for(j[e][f]=1;g[e+i]!==k&&g[e][f].cell==g[e+i][f].cell;)j[e+i][f]=1,i++;for(;g[e][f+o]!==k&&g[e][f].cell==g[e][f+o].cell;){for(c=0;c<i;c++)j[e+c][f+o]=1;o++}h(g[e][f].cell).attr("rowspan",i).attr("colspan",o)}}}}function M(a){var b=w(a,"aoPreDrawCallback","preDraw",[a]);if(-1!==h.inArray(!1,b))C(a,!1);else{var b=[],c=0,e=a.asStripeClasses,d=e.length,f=a.oLanguage,g=a.iInitDisplayStart,j="ssp"==B(a),i=a.aiDisplay;a.bDrawing=!0;g!==k&&-1!==g&&(a._iDisplayStart=
j?g:g>=a.fnRecordsDisplay()?0:g,a.iInitDisplayStart=-1);var g=a._iDisplayStart,o=a.fnDisplayEnd();if(a.bDeferLoading)a.bDeferLoading=!1,a.iDraw++,C(a,!1);else if(j){if(!a.bDestroying&&!kb(a))return}else a.iDraw++;if(0!==i.length){f=j?a.aoData.length:o;for(j=j?0:g;j<f;j++){var l=i[j],q=a.aoData[l];null===q.nTr&&Ja(a,l);l=q.nTr;if(0!==d){var n=e[c%d];q._sRowStripe!=n&&(h(l).removeClass(q._sRowStripe).addClass(n),q._sRowStripe=n)}w(a,"aoRowCallback",null,[l,q._aData,c,j]);b.push(l);c++}}else c=f.sZeroRecords,
1==a.iDraw&&"ajax"==B(a)?c=f.sLoadingRecords:f.sEmptyTable&&0===a.fnRecordsTotal()&&(c=f.sEmptyTable),b[0]=h("<tr/>",{"class":d?e[0]:""}).append(h("<td />",{valign:"top",colSpan:aa(a),"class":a.oClasses.sRowEmpty}).html(c))[0];w(a,"aoHeaderCallback","header",[h(a.nTHead).children("tr")[0],La(a),g,o,i]);w(a,"aoFooterCallback","footer",[h(a.nTFoot).children("tr")[0],La(a),g,o,i]);e=h(a.nTBody);e.children().detach();e.append(h(b));w(a,"aoDrawCallback","draw",[a]);a.bSorted=!1;a.bFiltered=!1;a.bDrawing=
!1}}function N(a,b){var c=a.oFeatures,e=c.bFilter;c.bSort&&lb(a);e?fa(a,a.oPreviousSearch):a.aiDisplay=a.aiDisplayMaster.slice();!0!==b&&(a._iDisplayStart=0);a._drawHold=b;M(a);a._drawHold=!1}function mb(a){var b=a.oClasses,c=h(a.nTable),c=h("<div/>").insertBefore(c),e=a.oFeatures,d=h("<div/>",{id:a.sTableId+"_wrapper","class":b.sWrapper+(a.nTFoot?"":" "+b.sNoFooter)});a.nHolding=c[0];a.nTableWrapper=d[0];a.nTableReinsertBefore=a.nTable.nextSibling;for(var f=a.sDom.split(""),g,j,i,o,l,q,n=0;n<f.length;n++){g=
null;j=f[n];if("<"==j){i=h("<div/>")[0];o=f[n+1];if("'"==o||'"'==o){l="";for(q=2;f[n+q]!=o;)l+=f[n+q],q++;"H"==l?l=b.sJUIHeader:"F"==l&&(l=b.sJUIFooter);-1!=l.indexOf(".")?(o=l.split("."),i.id=o[0].substr(1,o[0].length-1),i.className=o[1]):"#"==l.charAt(0)?i.id=l.substr(1,l.length-1):i.className=l;n+=q}d.append(i);d=h(i)}else if(">"==j)d=d.parent();else if("l"==j&&e.bPaginate&&e.bLengthChange)g=nb(a);else if("f"==j&&e.bFilter)g=ob(a);else if("r"==j&&e.bProcessing)g=pb(a);else if("t"==j)g=qb(a);else if("i"==
j&&e.bInfo)g=rb(a);else if("p"==j&&e.bPaginate)g=sb(a);else if(0!==m.ext.feature.length){i=m.ext.feature;q=0;for(o=i.length;q<o;q++)if(j==i[q].cFeature){g=i[q].fnInit(a);break}}g&&(i=a.aanFeatures,i[j]||(i[j]=[]),i[j].push(g),d.append(g))}c.replaceWith(d)}function da(a,b){var c=h(b).children("tr"),e,d,f,g,j,i,o,l,q,n;a.splice(0,a.length);f=0;for(i=c.length;f<i;f++)a.push([]);f=0;for(i=c.length;f<i;f++){e=c[f];for(d=e.firstChild;d;){if("TD"==d.nodeName.toUpperCase()||"TH"==d.nodeName.toUpperCase()){l=
1*d.getAttribute("colspan");q=1*d.getAttribute("rowspan");l=!l||0===l||1===l?1:l;q=!q||0===q||1===q?1:q;g=0;for(j=a[f];j[g];)g++;o=g;n=1===l?!0:!1;for(j=0;j<l;j++)for(g=0;g<q;g++)a[f+g][o+j]={cell:d,unique:n},a[f+g].nTr=e}d=d.nextSibling}}}function qa(a,b,c){var e=[];c||(c=a.aoHeader,b&&(c=[],da(c,b)));for(var b=0,d=c.length;b<d;b++)for(var f=0,g=c[b].length;f<g;f++)if(c[b][f].unique&&(!e[f]||!a.bSortCellsTop))e[f]=c[b][f].cell;return e}function ra(a,b,c){w(a,"aoServerParams","serverParams",[b]);
if(b&&h.isArray(b)){var e={},d=/(.*?)\[\]$/;h.each(b,function(a,b){var c=b.name.match(d);c?(c=c[0],e[c]||(e[c]=[]),e[c].push(b.value)):e[b.name]=b.value});b=e}var f,g=a.ajax,j=a.oInstance,i=function(b){w(a,null,"xhr",[a,b,a.jqXHR]);c(b)};if(h.isPlainObject(g)&&g.data){f=g.data;var o=h.isFunction(f)?f(b,a):f,b=h.isFunction(f)&&o?o:h.extend(!0,b,o);delete g.data}o={data:b,success:function(b){var c=b.error||b.sError;c&&I(a,0,c);a.json=b;i(b)},dataType:"json",cache:!1,type:a.sServerMethod,error:function(b,
c){var f=w(a,null,"xhr",[a,null,a.jqXHR]);-1===h.inArray(!0,f)&&("parsererror"==c?I(a,0,"Invalid JSON response",1):4===b.readyState&&I(a,0,"Ajax error",7));C(a,!1)}};a.oAjaxData=b;w(a,null,"preXhr",[a,b]);a.fnServerData?a.fnServerData.call(j,a.sAjaxSource,h.map(b,function(a,b){return{name:b,value:a}}),i,a):a.sAjaxSource||"string"===typeof g?a.jqXHR=h.ajax(h.extend(o,{url:g||a.sAjaxSource})):h.isFunction(g)?a.jqXHR=g.call(j,b,i,a):(a.jqXHR=h.ajax(h.extend(o,g)),g.data=f)}function kb(a){return a.bAjaxDataGet?
(a.iDraw++,C(a,!0),ra(a,tb(a),function(b){ub(a,b)}),!1):!0}function tb(a){var b=a.aoColumns,c=b.length,e=a.oFeatures,d=a.oPreviousSearch,f=a.aoPreSearchCols,g,j=[],i,o,l,q=U(a);g=a._iDisplayStart;i=!1!==e.bPaginate?a._iDisplayLength:-1;var n=function(a,b){j.push({name:a,value:b})};n("sEcho",a.iDraw);n("iColumns",c);n("sColumns",D(b,"sName").join(","));n("iDisplayStart",g);n("iDisplayLength",i);var k={draw:a.iDraw,columns:[],order:[],start:g,length:i,search:{value:d.sSearch,regex:d.bRegex}};for(g=
0;g<c;g++)o=b[g],l=f[g],i="function"==typeof o.mData?"function":o.mData,k.columns.push({data:i,name:o.sName,searchable:o.bSearchable,orderable:o.bSortable,search:{value:l.sSearch,regex:l.bRegex}}),n("mDataProp_"+g,i),e.bFilter&&(n("sSearch_"+g,l.sSearch),n("bRegex_"+g,l.bRegex),n("bSearchable_"+g,o.bSearchable)),e.bSort&&n("bSortable_"+g,o.bSortable);e.bFilter&&(n("sSearch",d.sSearch),n("bRegex",d.bRegex));e.bSort&&(h.each(q,function(a,b){k.order.push({column:b.col,dir:b.dir});n("iSortCol_"+a,b.col);
n("sSortDir_"+a,b.dir)}),n("iSortingCols",q.length));b=m.ext.legacy.ajax;return null===b?a.sAjaxSource?j:k:b?j:k}function ub(a,b){var c=sa(a,b),e=b.sEcho!==k?b.sEcho:b.draw,d=b.iTotalRecords!==k?b.iTotalRecords:b.recordsTotal,f=b.iTotalDisplayRecords!==k?b.iTotalDisplayRecords:b.recordsFiltered;if(e){if(1*e<a.iDraw)return;a.iDraw=1*e}oa(a);a._iRecordsTotal=parseInt(d,10);a._iRecordsDisplay=parseInt(f,10);e=0;for(d=c.length;e<d;e++)K(a,c[e]);a.aiDisplay=a.aiDisplayMaster.slice();a.bAjaxDataGet=!1;
M(a);a._bInitComplete||ta(a,b);a.bAjaxDataGet=!0;C(a,!1)}function sa(a,b){var c=h.isPlainObject(a.ajax)&&a.ajax.dataSrc!==k?a.ajax.dataSrc:a.sAjaxDataProp;return"data"===c?b.aaData||b[c]:""!==c?R(c)(b):b}function ob(a){var b=a.oClasses,c=a.sTableId,e=a.oLanguage,d=a.oPreviousSearch,f=a.aanFeatures,g='<input type="search" class="'+b.sFilterInput+'"/>',j=e.sSearch,j=j.match(/_INPUT_/)?j.replace("_INPUT_",g):j+g,b=h("<div/>",{id:!f.f?c+"_filter":null,"class":b.sFilter}).append(h("<label/>").append(j)),
f=function(){var b=!this.value?"":this.value;b!=d.sSearch&&(fa(a,{sSearch:b,bRegex:d.bRegex,bSmart:d.bSmart,bCaseInsensitive:d.bCaseInsensitive}),a._iDisplayStart=0,M(a))},g=null!==a.searchDelay?a.searchDelay:"ssp"===B(a)?400:0,i=h("input",b).val(d.sSearch).attr("placeholder",e.sSearchPlaceholder).bind("keyup.DT search.DT input.DT paste.DT cut.DT",g?ua(f,g):f).bind("keypress.DT",function(a){if(13==a.keyCode)return!1}).attr("aria-controls",c);h(a.nTable).on("search.dt.DT",function(b,c){if(a===c)try{i[0]!==
Q.activeElement&&i.val(d.sSearch)}catch(f){}});return b[0]}function fa(a,b,c){var e=a.oPreviousSearch,d=a.aoPreSearchCols,f=function(a){e.sSearch=a.sSearch;e.bRegex=a.bRegex;e.bSmart=a.bSmart;e.bCaseInsensitive=a.bCaseInsensitive};Ha(a);if("ssp"!=B(a)){vb(a,b.sSearch,c,b.bEscapeRegex!==k?!b.bEscapeRegex:b.bRegex,b.bSmart,b.bCaseInsensitive);f(b);for(b=0;b<d.length;b++)wb(a,d[b].sSearch,b,d[b].bEscapeRegex!==k?!d[b].bEscapeRegex:d[b].bRegex,d[b].bSmart,d[b].bCaseInsensitive);xb(a)}else f(b);a.bFiltered=
!0;w(a,null,"search",[a])}function xb(a){for(var b=m.ext.search,c=a.aiDisplay,e,d,f=0,g=b.length;f<g;f++){for(var j=[],i=0,h=c.length;i<h;i++)d=c[i],e=a.aoData[d],b[f](a,e._aFilterData,d,e._aData,i)&&j.push(d);c.length=0;c.push.apply(c,j)}}function wb(a,b,c,e,d,f){if(""!==b)for(var g=a.aiDisplay,e=Qa(b,e,d,f),d=g.length-1;0<=d;d--)b=a.aoData[g[d]]._aFilterData[c],e.test(b)||g.splice(d,1)}function vb(a,b,c,e,d,f){var e=Qa(b,e,d,f),d=a.oPreviousSearch.sSearch,f=a.aiDisplayMaster,g;0!==m.ext.search.length&&
(c=!0);g=yb(a);if(0>=b.length)a.aiDisplay=f.slice();else{if(g||c||d.length>b.length||0!==b.indexOf(d)||a.bSorted)a.aiDisplay=f.slice();b=a.aiDisplay;for(c=b.length-1;0<=c;c--)e.test(a.aoData[b[c]]._sFilterRow)||b.splice(c,1)}}function Qa(a,b,c,e){a=b?a:va(a);c&&(a="^(?=.*?"+h.map(a.match(/"[^"]+"|[^ ]+/g)||[""],function(a){if('"'===a.charAt(0))var b=a.match(/^"(.*)"$/),a=b?b[1]:a;return a.replace('"',"")}).join(")(?=.*?")+").*$");return RegExp(a,e?"i":"")}function va(a){return a.replace(Yb,"\\$1")}
function yb(a){var b=a.aoColumns,c,e,d,f,g,j,i,h,l=m.ext.type.search;c=!1;e=0;for(f=a.aoData.length;e<f;e++)if(h=a.aoData[e],!h._aFilterData){j=[];d=0;for(g=b.length;d<g;d++)c=b[d],c.bSearchable?(i=x(a,e,d,"filter"),l[c.sType]&&(i=l[c.sType](i)),null===i&&(i=""),"string"!==typeof i&&i.toString&&(i=i.toString())):i="",i.indexOf&&-1!==i.indexOf("&")&&(wa.innerHTML=i,i=Zb?wa.textContent:wa.innerText),i.replace&&(i=i.replace(/[\r\n]/g,"")),j.push(i);h._aFilterData=j;h._sFilterRow=j.join(" ");c=!0}return c}
function zb(a){return{search:a.sSearch,smart:a.bSmart,regex:a.bRegex,caseInsensitive:a.bCaseInsensitive}}function Ab(a){return{sSearch:a.search,bSmart:a.smart,bRegex:a.regex,bCaseInsensitive:a.caseInsensitive}}function rb(a){var b=a.sTableId,c=a.aanFeatures.i,e=h("<div/>",{"class":a.oClasses.sInfo,id:!c?b+"_info":null});c||(a.aoDrawCallback.push({fn:Bb,sName:"information"}),e.attr("role","status").attr("aria-live","polite"),h(a.nTable).attr("aria-describedby",b+"_info"));return e[0]}function Bb(a){var b=
a.aanFeatures.i;if(0!==b.length){var c=a.oLanguage,e=a._iDisplayStart+1,d=a.fnDisplayEnd(),f=a.fnRecordsTotal(),g=a.fnRecordsDisplay(),j=g?c.sInfo:c.sInfoEmpty;g!==f&&(j+=" "+c.sInfoFiltered);j+=c.sInfoPostFix;j=Cb(a,j);c=c.fnInfoCallback;null!==c&&(j=c.call(a.oInstance,a,e,d,f,g,j));h(b).html(j)}}function Cb(a,b){var c=a.fnFormatNumber,e=a._iDisplayStart+1,d=a._iDisplayLength,f=a.fnRecordsDisplay(),g=-1===d;return b.replace(/_START_/g,c.call(a,e)).replace(/_END_/g,c.call(a,a.fnDisplayEnd())).replace(/_MAX_/g,
c.call(a,a.fnRecordsTotal())).replace(/_TOTAL_/g,c.call(a,f)).replace(/_PAGE_/g,c.call(a,g?1:Math.ceil(e/d))).replace(/_PAGES_/g,c.call(a,g?1:Math.ceil(f/d)))}function ga(a){var b,c,e=a.iInitDisplayStart,d=a.aoColumns,f;c=a.oFeatures;if(a.bInitialised){mb(a);jb(a);ea(a,a.aoHeader);ea(a,a.aoFooter);C(a,!0);c.bAutoWidth&&Ga(a);b=0;for(c=d.length;b<c;b++)f=d[b],f.sWidth&&(f.nTh.style.width=s(f.sWidth));N(a);d=B(a);"ssp"!=d&&("ajax"==d?ra(a,[],function(c){var f=sa(a,c);for(b=0;b<f.length;b++)K(a,f[b]);
a.iInitDisplayStart=e;N(a);C(a,!1);ta(a,c)},a):(C(a,!1),ta(a)))}else setTimeout(function(){ga(a)},200)}function ta(a,b){a._bInitComplete=!0;b&&X(a);w(a,"aoInitComplete","init",[a,b])}function Ra(a,b){var c=parseInt(b,10);a._iDisplayLength=c;Sa(a);w(a,null,"length",[a,c])}function nb(a){for(var b=a.oClasses,c=a.sTableId,e=a.aLengthMenu,d=h.isArray(e[0]),f=d?e[0]:e,e=d?e[1]:e,d=h("<select/>",{name:c+"_length","aria-controls":c,"class":b.sLengthSelect}),g=0,j=f.length;g<j;g++)d[0][g]=new Option(e[g],
f[g]);var i=h("<div><label/></div>").addClass(b.sLength);a.aanFeatures.l||(i[0].id=c+"_length");i.children().append(a.oLanguage.sLengthMenu.replace("_MENU_",d[0].outerHTML));h("select",i).val(a._iDisplayLength).bind("change.DT",function(){Ra(a,h(this).val());M(a)});h(a.nTable).bind("length.dt.DT",function(b,c,f){a===c&&h("select",i).val(f)});return i[0]}function sb(a){var b=a.sPaginationType,c=m.ext.pager[b],e="function"===typeof c,d=function(a){M(a)},b=h("<div/>").addClass(a.oClasses.sPaging+b)[0],
f=a.aanFeatures;e||c.fnInit(a,b,d);f.p||(b.id=a.sTableId+"_paginate",a.aoDrawCallback.push({fn:function(a){if(e){var b=a._iDisplayStart,i=a._iDisplayLength,h=a.fnRecordsDisplay(),l=-1===i,b=l?0:Math.ceil(b/i),i=l?1:Math.ceil(h/i),h=c(b,i),q,l=0;for(q=f.p.length;l<q;l++)Pa(a,"pageButton")(a,f.p[l],l,h,b,i)}else c.fnUpdate(a,d)},sName:"pagination"}));return b}function Ta(a,b,c){var e=a._iDisplayStart,d=a._iDisplayLength,f=a.fnRecordsDisplay();0===f||-1===d?e=0:"number"===typeof b?(e=b*d,e>f&&(e=0)):
"first"==b?e=0:"previous"==b?(e=0<=d?e-d:0,0>e&&(e=0)):"next"==b?e+d<f&&(e+=d):"last"==b?e=Math.floor((f-1)/d)*d:I(a,0,"Unknown paging action: "+b,5);b=a._iDisplayStart!==e;a._iDisplayStart=e;b&&(w(a,null,"page",[a]),c&&M(a));return b}function pb(a){return h("<div/>",{id:!a.aanFeatures.r?a.sTableId+"_processing":null,"class":a.oClasses.sProcessing}).html(a.oLanguage.sProcessing).insertBefore(a.nTable)[0]}function C(a,b){a.oFeatures.bProcessing&&h(a.aanFeatures.r).css("display",b?"block":"none");w(a,
null,"processing",[a,b])}function qb(a){var b=h(a.nTable);b.attr("role","grid");var c=a.oScroll;if(""===c.sX&&""===c.sY)return a.nTable;var e=c.sX,d=c.sY,f=a.oClasses,g=b.children("caption"),j=g.length?g[0]._captionSide:null,i=h(b[0].cloneNode(!1)),o=h(b[0].cloneNode(!1)),l=b.children("tfoot");c.sX&&"100%"===b.attr("width")&&b.removeAttr("width");l.length||(l=null);c=h("<div/>",{"class":f.sScrollWrapper}).append(h("<div/>",{"class":f.sScrollHead}).css({overflow:"hidden",position:"relative",border:0,
width:e?!e?null:s(e):"100%"}).append(h("<div/>",{"class":f.sScrollHeadInner}).css({"box-sizing":"content-box",width:c.sXInner||"100%"}).append(i.removeAttr("id").css("margin-left",0).append("top"===j?g:null).append(b.children("thead"))))).append(h("<div/>",{"class":f.sScrollBody}).css({overflow:"auto",height:!d?null:s(d),width:!e?null:s(e)}).append(b));l&&c.append(h("<div/>",{"class":f.sScrollFoot}).css({overflow:"hidden",border:0,width:e?!e?null:s(e):"100%"}).append(h("<div/>",{"class":f.sScrollFootInner}).append(o.removeAttr("id").css("margin-left",
0).append("bottom"===j?g:null).append(b.children("tfoot")))));var b=c.children(),q=b[0],f=b[1],n=l?b[2]:null;if(e)h(f).on("scroll.DT",function(){var a=this.scrollLeft;q.scrollLeft=a;l&&(n.scrollLeft=a)});a.nScrollHead=q;a.nScrollBody=f;a.nScrollFoot=n;a.aoDrawCallback.push({fn:Y,sName:"scrolling"});return c[0]}function Y(a){var b=a.oScroll,c=b.sX,e=b.sXInner,d=b.sY,f=b.iBarWidth,g=h(a.nScrollHead),j=g[0].style,i=g.children("div"),o=i[0].style,l=i.children("table"),i=a.nScrollBody,q=h(i),n=i.style,
k=h(a.nScrollFoot).children("div"),p=k.children("table"),m=h(a.nTHead),r=h(a.nTable),t=r[0],O=t.style,L=a.nTFoot?h(a.nTFoot):null,ha=a.oBrowser,w=ha.bScrollOversize,v,u,y,x,z,A=[],B=[],C=[],D,E=function(a){a=a.style;a.paddingTop="0";a.paddingBottom="0";a.borderTopWidth="0";a.borderBottomWidth="0";a.height=0};r.children("thead, tfoot").remove();z=m.clone().prependTo(r);v=m.find("tr");y=z.find("tr");z.find("th, td").removeAttr("tabindex");L&&(x=L.clone().prependTo(r),u=L.find("tr"),x=x.find("tr"));
c||(n.width="100%",g[0].style.width="100%");h.each(qa(a,z),function(b,c){D=la(a,b);c.style.width=a.aoColumns[D].sWidth});L&&G(function(a){a.style.width=""},x);b.bCollapse&&""!==d&&(n.height=q[0].offsetHeight+m[0].offsetHeight+"px");g=r.outerWidth();if(""===c){if(O.width="100%",w&&(r.find("tbody").height()>i.offsetHeight||"scroll"==q.css("overflow-y")))O.width=s(r.outerWidth()-f)}else""!==e?O.width=s(e):g==q.width()&&q.height()<r.height()?(O.width=s(g-f),r.outerWidth()>g-f&&(O.width=s(g))):O.width=
s(g);g=r.outerWidth();G(E,y);G(function(a){C.push(a.innerHTML);A.push(s(h(a).css("width")))},y);G(function(a,b){a.style.width=A[b]},v);h(y).height(0);L&&(G(E,x),G(function(a){B.push(s(h(a).css("width")))},x),G(function(a,b){a.style.width=B[b]},u),h(x).height(0));G(function(a,b){a.innerHTML='<div class="dataTables_sizing" style="height:0;overflow:hidden;">'+C[b]+"</div>";a.style.width=A[b]},y);L&&G(function(a,b){a.innerHTML="";a.style.width=B[b]},x);if(r.outerWidth()<g){u=i.scrollHeight>i.offsetHeight||
"scroll"==q.css("overflow-y")?g+f:g;if(w&&(i.scrollHeight>i.offsetHeight||"scroll"==q.css("overflow-y")))O.width=s(u-f);(""===c||""!==e)&&I(a,1,"Possible column misalignment",6)}else u="100%";n.width=s(u);j.width=s(u);L&&(a.nScrollFoot.style.width=s(u));!d&&w&&(n.height=s(t.offsetHeight+f));d&&b.bCollapse&&(n.height=s(d),b=c&&t.offsetWidth>i.offsetWidth?f:0,t.offsetHeight<i.offsetHeight&&(n.height=s(t.offsetHeight+b)));b=r.outerWidth();l[0].style.width=s(b);o.width=s(b);l=r.height()>i.clientHeight||
"scroll"==q.css("overflow-y");ha="padding"+(ha.bScrollbarLeft?"Left":"Right");o[ha]=l?f+"px":"0px";L&&(p[0].style.width=s(b),k[0].style.width=s(b),k[0].style[ha]=l?f+"px":"0px");q.scroll();if((a.bSorted||a.bFiltered)&&!a._drawHold)i.scrollTop=0}function G(a,b,c){for(var e=0,d=0,f=b.length,g,j;d<f;){g=b[d].firstChild;for(j=c?c[d].firstChild:null;g;)1===g.nodeType&&(c?a(g,j,e):a(g,e),e++),g=g.nextSibling,j=c?j.nextSibling:null;d++}}function Ga(a){var b=a.nTable,c=a.aoColumns,e=a.oScroll,d=e.sY,f=e.sX,
g=e.sXInner,j=c.length,e=Z(a,"bVisible"),i=h("th",a.nTHead),o=b.getAttribute("width"),l=b.parentNode,k=!1,n,m;(n=b.style.width)&&-1!==n.indexOf("%")&&(o=n);for(n=0;n<e.length;n++)m=c[e[n]],null!==m.sWidth&&(m.sWidth=Db(m.sWidthOrig,l),k=!0);if(!k&&!f&&!d&&j==aa(a)&&j==i.length)for(n=0;n<j;n++)c[n].sWidth=s(i.eq(n).width());else{j=h(b).clone().css("visibility","hidden").removeAttr("id");j.find("tbody tr").remove();var p=h("<tr/>").appendTo(j.find("tbody"));j.find("tfoot th, tfoot td").css("width",
"");i=qa(a,j.find("thead")[0]);for(n=0;n<e.length;n++)m=c[e[n]],i[n].style.width=null!==m.sWidthOrig&&""!==m.sWidthOrig?s(m.sWidthOrig):"";if(a.aoData.length)for(n=0;n<e.length;n++)k=e[n],m=c[k],h(Eb(a,k)).clone(!1).append(m.sContentPadding).appendTo(p);j.appendTo(l);f&&g?j.width(g):f?(j.css("width","auto"),j.width()<l.offsetWidth&&j.width(l.offsetWidth)):d?j.width(l.offsetWidth):o&&j.width(o);Fb(a,j[0]);if(f){for(n=g=0;n<e.length;n++)m=c[e[n]],d=h(i[n]).outerWidth(),g+=null===m.sWidthOrig?d:parseInt(m.sWidth,
10)+d-h(i[n]).width();j.width(s(g));b.style.width=s(g)}for(n=0;n<e.length;n++)if(m=c[e[n]],d=h(i[n]).width())m.sWidth=s(d);b.style.width=s(j.css("width"));j.remove()}o&&(b.style.width=s(o));if((o||f)&&!a._reszEvt)b=function(){h(Ea).bind("resize.DT-"+a.sInstance,ua(function(){X(a)}))},a.oBrowser.bScrollOversize?setTimeout(b,1E3):b(),a._reszEvt=!0}function ua(a,b){var c=b!==k?b:200,e,d;return function(){var b=this,g=+new Date,j=arguments;e&&g<e+c?(clearTimeout(d),d=setTimeout(function(){e=k;a.apply(b,
j)},c)):(e=g,a.apply(b,j))}}function Db(a,b){if(!a)return 0;var c=h("<div/>").css("width",s(a)).appendTo(b||Q.body),e=c[0].offsetWidth;c.remove();return e}function Fb(a,b){var c=a.oScroll;if(c.sX||c.sY)c=!c.sX?c.iBarWidth:0,b.style.width=s(h(b).outerWidth()-c)}function Eb(a,b){var c=Gb(a,b);if(0>c)return null;var e=a.aoData[c];return!e.nTr?h("<td/>").html(x(a,c,b,"display"))[0]:e.anCells[b]}function Gb(a,b){for(var c,e=-1,d=-1,f=0,g=a.aoData.length;f<g;f++)c=x(a,f,b,"display")+"",c=c.replace($b,""),
c.length>e&&(e=c.length,d=f);return d}function s(a){return null===a?"0px":"number"==typeof a?0>a?"0px":a+"px":a.match(/\d$/)?a+"px":a}function Hb(){var a=m.__scrollbarWidth;if(a===k){var b=h("<p/>").css({position:"absolute",top:0,left:0,width:"100%",height:150,padding:0,overflow:"scroll",visibility:"hidden"}).appendTo("body"),a=b[0].offsetWidth-b[0].clientWidth;m.__scrollbarWidth=a;b.remove()}return a}function U(a){var b,c,e=[],d=a.aoColumns,f,g,j,i;b=a.aaSortingFixed;c=h.isPlainObject(b);var o=[];
f=function(a){a.length&&!h.isArray(a[0])?o.push(a):o.push.apply(o,a)};h.isArray(b)&&f(b);c&&b.pre&&f(b.pre);f(a.aaSorting);c&&b.post&&f(b.post);for(a=0;a<o.length;a++){i=o[a][0];f=d[i].aDataSort;b=0;for(c=f.length;b<c;b++)g=f[b],j=d[g].sType||"string",o[a]._idx===k&&(o[a]._idx=h.inArray(o[a][1],d[g].asSorting)),e.push({src:i,col:g,dir:o[a][1],index:o[a]._idx,type:j,formatter:m.ext.type.order[j+"-pre"]})}return e}function lb(a){var b,c,e=[],d=m.ext.type.order,f=a.aoData,g=0,j,i=a.aiDisplayMaster,h;
Ha(a);h=U(a);b=0;for(c=h.length;b<c;b++)j=h[b],j.formatter&&g++,Ib(a,j.col);if("ssp"!=B(a)&&0!==h.length){b=0;for(c=i.length;b<c;b++)e[i[b]]=b;g===h.length?i.sort(function(a,b){var c,d,g,j,i=h.length,k=f[a]._aSortData,m=f[b]._aSortData;for(g=0;g<i;g++)if(j=h[g],c=k[j.col],d=m[j.col],c=c<d?-1:c>d?1:0,0!==c)return"asc"===j.dir?c:-c;c=e[a];d=e[b];return c<d?-1:c>d?1:0}):i.sort(function(a,b){var c,g,j,i,k=h.length,m=f[a]._aSortData,r=f[b]._aSortData;for(j=0;j<k;j++)if(i=h[j],c=m[i.col],g=r[i.col],i=d[i.type+
"-"+i.dir]||d["string-"+i.dir],c=i(c,g),0!==c)return c;c=e[a];g=e[b];return c<g?-1:c>g?1:0})}a.bSorted=!0}function Jb(a){for(var b,c,e=a.aoColumns,d=U(a),a=a.oLanguage.oAria,f=0,g=e.length;f<g;f++){c=e[f];var j=c.asSorting;b=c.sTitle.replace(/<.*?>/g,"");var i=c.nTh;i.removeAttribute("aria-sort");c.bSortable&&(0<d.length&&d[0].col==f?(i.setAttribute("aria-sort","asc"==d[0].dir?"ascending":"descending"),c=j[d[0].index+1]||j[0]):c=j[0],b+="asc"===c?a.sSortAscending:a.sSortDescending);i.setAttribute("aria-label",
b)}}function Ua(a,b,c,e){var d=a.aaSorting,f=a.aoColumns[b].asSorting,g=function(a,b){var c=a._idx;c===k&&(c=h.inArray(a[1],f));return c+1<f.length?c+1:b?null:0};"number"===typeof d[0]&&(d=a.aaSorting=[d]);c&&a.oFeatures.bSortMulti?(c=h.inArray(b,D(d,"0")),-1!==c?(b=g(d[c],!0),null===b&&1===d.length&&(b=0),null===b?d.splice(c,1):(d[c][1]=f[b],d[c]._idx=b)):(d.push([b,f[0],0]),d[d.length-1]._idx=0)):d.length&&d[0][0]==b?(b=g(d[0]),d.length=1,d[0][1]=f[b],d[0]._idx=b):(d.length=0,d.push([b,f[0]]),d[0]._idx=
0);N(a);"function"==typeof e&&e(a)}function Oa(a,b,c,e){var d=a.aoColumns[c];Va(b,{},function(b){!1!==d.bSortable&&(a.oFeatures.bProcessing?(C(a,!0),setTimeout(function(){Ua(a,c,b.shiftKey,e);"ssp"!==B(a)&&C(a,!1)},0)):Ua(a,c,b.shiftKey,e))})}function xa(a){var b=a.aLastSort,c=a.oClasses.sSortColumn,e=U(a),d=a.oFeatures,f,g;if(d.bSort&&d.bSortClasses){d=0;for(f=b.length;d<f;d++)g=b[d].src,h(D(a.aoData,"anCells",g)).removeClass(c+(2>d?d+1:3));d=0;for(f=e.length;d<f;d++)g=e[d].src,h(D(a.aoData,"anCells",
g)).addClass(c+(2>d?d+1:3))}a.aLastSort=e}function Ib(a,b){var c=a.aoColumns[b],e=m.ext.order[c.sSortDataType],d;e&&(d=e.call(a.oInstance,a,b,$(a,b)));for(var f,g=m.ext.type.order[c.sType+"-pre"],j=0,i=a.aoData.length;j<i;j++)if(c=a.aoData[j],c._aSortData||(c._aSortData=[]),!c._aSortData[b]||e)f=e?d[j]:x(a,j,b,"sort"),c._aSortData[b]=g?g(f):f}function ya(a){if(a.oFeatures.bStateSave&&!a.bDestroying){var b={time:+new Date,start:a._iDisplayStart,length:a._iDisplayLength,order:h.extend(!0,[],a.aaSorting),
search:zb(a.oPreviousSearch),columns:h.map(a.aoColumns,function(b,e){return{visible:b.bVisible,search:zb(a.aoPreSearchCols[e])}})};w(a,"aoStateSaveParams","stateSaveParams",[a,b]);a.oSavedState=b;a.fnStateSaveCallback.call(a.oInstance,a,b)}}function Kb(a){var b,c,e=a.aoColumns;if(a.oFeatures.bStateSave){var d=a.fnStateLoadCallback.call(a.oInstance,a);if(d&&d.time&&(b=w(a,"aoStateLoadParams","stateLoadParams",[a,d]),-1===h.inArray(!1,b)&&(b=a.iStateDuration,!(0<b&&d.time<+new Date-1E3*b)&&e.length===
d.columns.length))){a.oLoadedState=h.extend(!0,{},d);d.start!==k&&(a._iDisplayStart=d.start,a.iInitDisplayStart=d.start);d.length!==k&&(a._iDisplayLength=d.length);d.order!==k&&(a.aaSorting=[],h.each(d.order,function(b,c){a.aaSorting.push(c[0]>=e.length?[0,c[1]]:c)}));d.search!==k&&h.extend(a.oPreviousSearch,Ab(d.search));b=0;for(c=d.columns.length;b<c;b++){var f=d.columns[b];f.visible!==k&&(e[b].bVisible=f.visible);f.search!==k&&h.extend(a.aoPreSearchCols[b],Ab(f.search))}w(a,"aoStateLoaded","stateLoaded",
[a,d])}}}function za(a){var b=m.settings,a=h.inArray(a,D(b,"nTable"));return-1!==a?b[a]:null}function I(a,b,c,e){c="DataTables warning: "+(null!==a?"table id="+a.sTableId+" - ":"")+c;e&&(c+=". For more information about this error, please see http://datatables.net/tn/"+e);if(b)Ea.console&&console.log&&console.log(c);else if(b=m.ext,b=b.sErrMode||b.errMode,w(a,null,"error",[a,e,c]),"alert"==b)alert(c);else{if("throw"==b)throw Error(c);"function"==typeof b&&b(a,e,c)}}function E(a,b,c,e){h.isArray(c)?
h.each(c,function(c,f){h.isArray(f)?E(a,b,f[0],f[1]):E(a,b,f)}):(e===k&&(e=c),b[c]!==k&&(a[e]=b[c]))}function Lb(a,b,c){var e,d;for(d in b)b.hasOwnProperty(d)&&(e=b[d],h.isPlainObject(e)?(h.isPlainObject(a[d])||(a[d]={}),h.extend(!0,a[d],e)):a[d]=c&&"data"!==d&&"aaData"!==d&&h.isArray(e)?e.slice():e);return a}function Va(a,b,c){h(a).bind("click.DT",b,function(b){a.blur();c(b)}).bind("keypress.DT",b,function(a){13===a.which&&(a.preventDefault(),c(a))}).bind("selectstart.DT",function(){return!1})}function z(a,
b,c,e){c&&a[b].push({fn:c,sName:e})}function w(a,b,c,e){var d=[];b&&(d=h.map(a[b].slice().reverse(),function(b){return b.fn.apply(a.oInstance,e)}));null!==c&&(b=h.Event(c+".dt"),h(a.nTable).trigger(b,e),d.push(b.result));return d}function Sa(a){var b=a._iDisplayStart,c=a.fnDisplayEnd(),e=a._iDisplayLength;b>=c&&(b=c-e);b-=b%e;if(-1===e||0>b)b=0;a._iDisplayStart=b}function Pa(a,b){var c=a.renderer,e=m.ext.renderer[b];return h.isPlainObject(c)&&c[b]?e[c[b]]||e._:"string"===typeof c?e[c]||e._:e._}function B(a){return a.oFeatures.bServerSide?
"ssp":a.ajax||a.sAjaxSource?"ajax":"dom"}function Wa(a,b){var c=[],c=Mb.numbers_length,e=Math.floor(c/2);b<=c?c=V(0,b):a<=e?(c=V(0,c-2),c.push("ellipsis"),c.push(b-1)):(a>=b-1-e?c=V(b-(c-2),b):(c=V(a-e+2,a+e-1),c.push("ellipsis"),c.push(b-1)),c.splice(0,0,"ellipsis"),c.splice(0,0,0));c.DT_el="span";return c}function db(a){h.each({num:function(b){return Aa(b,a)},"num-fmt":function(b){return Aa(b,a,Xa)},"html-num":function(b){return Aa(b,a,Ba)},"html-num-fmt":function(b){return Aa(b,a,Ba,Xa)}},function(b,
c){u.type.order[b+a+"-pre"]=c;b.match(/^html\-/)&&(u.type.search[b+a]=u.type.search.html)})}function Nb(a){return function(){var b=[za(this[m.ext.iApiIndex])].concat(Array.prototype.slice.call(arguments));return m.ext.internal[a].apply(this,b)}}var m,u,t,r,v,Ya={},Ob=/[\r\n]/g,Ba=/<.*?>/g,ac=/^[\w\+\-]/,bc=/[\w\+\-]$/,Yb=RegExp("(\\/|\\.|\\*|\\+|\\?|\\||\\(|\\)|\\[|\\]|\\{|\\}|\\\\|\\$|\\^|\\-)","g"),Xa=/[',$\u00a3\u20ac\u00a5%\u2009\u202F\u20BD\u20a9\u20BArfk]/gi,J=function(a){return!a||!0===a||
"-"===a?!0:!1},Pb=function(a){var b=parseInt(a,10);return!isNaN(b)&&isFinite(a)?b:null},Qb=function(a,b){Ya[b]||(Ya[b]=RegExp(va(b),"g"));return"string"===typeof a&&"."!==b?a.replace(/\./g,"").replace(Ya[b],"."):a},Za=function(a,b,c){var e="string"===typeof a;if(J(a))return!0;b&&e&&(a=Qb(a,b));c&&e&&(a=a.replace(Xa,""));return!isNaN(parseFloat(a))&&isFinite(a)},Rb=function(a,b,c){return J(a)?!0:!(J(a)||"string"===typeof a)?null:Za(a.replace(Ba,""),b,c)?!0:null},D=function(a,b,c){var e=[],d=0,f=a.length;
if(c!==k)for(;d<f;d++)a[d]&&a[d][b]&&e.push(a[d][b][c]);else for(;d<f;d++)a[d]&&e.push(a[d][b]);return e},ia=function(a,b,c,e){var d=[],f=0,g=b.length;if(e!==k)for(;f<g;f++)a[b[f]][c]&&d.push(a[b[f]][c][e]);else for(;f<g;f++)d.push(a[b[f]][c]);return d},V=function(a,b){var c=[],e;b===k?(b=0,e=a):(e=b,b=a);for(var d=b;d<e;d++)c.push(d);return c},Sb=function(a){for(var b=[],c=0,e=a.length;c<e;c++)a[c]&&b.push(a[c]);return b},Na=function(a){var b=[],c,e,d=a.length,f,g=0;e=0;a:for(;e<d;e++){c=a[e];for(f=
0;f<g;f++)if(b[f]===c)continue a;b.push(c);g++}return b},A=function(a,b,c){a[b]!==k&&(a[c]=a[b])},ba=/\[.*?\]$/,T=/\(\)$/,wa=h("<div>")[0],Zb=wa.textContent!==k,$b=/<.*?>/g;m=function(a){this.$=function(a,b){return this.api(!0).$(a,b)};this._=function(a,b){return this.api(!0).rows(a,b).data()};this.api=function(a){return a?new t(za(this[u.iApiIndex])):new t(this)};this.fnAddData=function(a,b){var c=this.api(!0),e=h.isArray(a)&&(h.isArray(a[0])||h.isPlainObject(a[0]))?c.rows.add(a):c.row.add(a);(b===
k||b)&&c.draw();return e.flatten().toArray()};this.fnAdjustColumnSizing=function(a){var b=this.api(!0).columns.adjust(),c=b.settings()[0],e=c.oScroll;a===k||a?b.draw(!1):(""!==e.sX||""!==e.sY)&&Y(c)};this.fnClearTable=function(a){var b=this.api(!0).clear();(a===k||a)&&b.draw()};this.fnClose=function(a){this.api(!0).row(a).child.hide()};this.fnDeleteRow=function(a,b,c){var e=this.api(!0),a=e.rows(a),d=a.settings()[0],h=d.aoData[a[0][0]];a.remove();b&&b.call(this,d,h);(c===k||c)&&e.draw();return h};
this.fnDestroy=function(a){this.api(!0).destroy(a)};this.fnDraw=function(a){this.api(!0).draw(a)};this.fnFilter=function(a,b,c,e,d,h){d=this.api(!0);null===b||b===k?d.search(a,c,e,h):d.column(b).search(a,c,e,h);d.draw()};this.fnGetData=function(a,b){var c=this.api(!0);if(a!==k){var e=a.nodeName?a.nodeName.toLowerCase():"";return b!==k||"td"==e||"th"==e?c.cell(a,b).data():c.row(a).data()||null}return c.data().toArray()};this.fnGetNodes=function(a){var b=this.api(!0);return a!==k?b.row(a).node():b.rows().nodes().flatten().toArray()};
this.fnGetPosition=function(a){var b=this.api(!0),c=a.nodeName.toUpperCase();return"TR"==c?b.row(a).index():"TD"==c||"TH"==c?(a=b.cell(a).index(),[a.row,a.columnVisible,a.column]):null};this.fnIsOpen=function(a){return this.api(!0).row(a).child.isShown()};this.fnOpen=function(a,b,c){return this.api(!0).row(a).child(b,c).show().child()[0]};this.fnPageChange=function(a,b){var c=this.api(!0).page(a);(b===k||b)&&c.draw(!1)};this.fnSetColumnVis=function(a,b,c){a=this.api(!0).column(a).visible(b);(c===
k||c)&&a.columns.adjust().draw()};this.fnSettings=function(){return za(this[u.iApiIndex])};this.fnSort=function(a){this.api(!0).order(a).draw()};this.fnSortListener=function(a,b,c){this.api(!0).order.listener(a,b,c)};this.fnUpdate=function(a,b,c,e,d){var h=this.api(!0);c===k||null===c?h.row(b).data(a):h.cell(b,c).data(a);(d===k||d)&&h.columns.adjust();(e===k||e)&&h.draw();return 0};this.fnVersionCheck=u.fnVersionCheck;var b=this,c=a===k,e=this.length;c&&(a={});this.oApi=this.internal=u.internal;for(var d in m.ext.internal)d&&
(this[d]=Nb(d));this.each(function(){var d={},d=1<e?Lb(d,a,!0):a,g=0,j,i=this.getAttribute("id"),o=!1,l=m.defaults,q=h(this);if("table"!=this.nodeName.toLowerCase())I(null,0,"Non-table node initialisation ("+this.nodeName+")",2);else{eb(l);fb(l.column);H(l,l,!0);H(l.column,l.column,!0);H(l,h.extend(d,q.data()));var n=m.settings,g=0;for(j=n.length;g<j;g++){var r=n[g];if(r.nTable==this||r.nTHead.parentNode==this||r.nTFoot&&r.nTFoot.parentNode==this){g=d.bRetrieve!==k?d.bRetrieve:l.bRetrieve;if(c||g)return r.oInstance;
if(d.bDestroy!==k?d.bDestroy:l.bDestroy){r.oInstance.fnDestroy();break}else{I(r,0,"Cannot reinitialise DataTable",3);return}}if(r.sTableId==this.id){n.splice(g,1);break}}if(null===i||""===i)this.id=i="DataTables_Table_"+m.ext._unique++;var p=h.extend(!0,{},m.models.oSettings,{sDestroyWidth:q[0].style.width,sInstance:i,sTableId:i});p.nTable=this;p.oApi=b.internal;p.oInit=d;n.push(p);p.oInstance=1===b.length?b:q.dataTable();eb(d);d.oLanguage&&P(d.oLanguage);d.aLengthMenu&&!d.iDisplayLength&&(d.iDisplayLength=
h.isArray(d.aLengthMenu[0])?d.aLengthMenu[0][0]:d.aLengthMenu[0]);d=Lb(h.extend(!0,{},l),d);E(p.oFeatures,d,"bPaginate bLengthChange bFilter bSort bSortMulti bInfo bProcessing bAutoWidth bSortClasses bServerSide bDeferRender".split(" "));E(p,d,["asStripeClasses","ajax","fnServerData","fnFormatNumber","sServerMethod","aaSorting","aaSortingFixed","aLengthMenu","sPaginationType","sAjaxSource","sAjaxDataProp","iStateDuration","sDom","bSortCellsTop","iTabIndex","fnStateLoadCallback","fnStateSaveCallback",
"renderer","searchDelay",["iCookieDuration","iStateDuration"],["oSearch","oPreviousSearch"],["aoSearchCols","aoPreSearchCols"],["iDisplayLength","_iDisplayLength"],["bJQueryUI","bJUI"]]);E(p.oScroll,d,[["sScrollX","sX"],["sScrollXInner","sXInner"],["sScrollY","sY"],["bScrollCollapse","bCollapse"]]);E(p.oLanguage,d,"fnInfoCallback");z(p,"aoDrawCallback",d.fnDrawCallback,"user");z(p,"aoServerParams",d.fnServerParams,"user");z(p,"aoStateSaveParams",d.fnStateSaveParams,"user");z(p,"aoStateLoadParams",
d.fnStateLoadParams,"user");z(p,"aoStateLoaded",d.fnStateLoaded,"user");z(p,"aoRowCallback",d.fnRowCallback,"user");z(p,"aoRowCreatedCallback",d.fnCreatedRow,"user");z(p,"aoHeaderCallback",d.fnHeaderCallback,"user");z(p,"aoFooterCallback",d.fnFooterCallback,"user");z(p,"aoInitComplete",d.fnInitComplete,"user");z(p,"aoPreDrawCallback",d.fnPreDrawCallback,"user");i=p.oClasses;d.bJQueryUI?(h.extend(i,m.ext.oJUIClasses,d.oClasses),d.sDom===l.sDom&&"lfrtip"===l.sDom&&(p.sDom='<"H"lfr>t<"F"ip>'),p.renderer)?
h.isPlainObject(p.renderer)&&!p.renderer.header&&(p.renderer.header="jqueryui"):p.renderer="jqueryui":h.extend(i,m.ext.classes,d.oClasses);q.addClass(i.sTable);if(""!==p.oScroll.sX||""!==p.oScroll.sY)p.oScroll.iBarWidth=Hb();!0===p.oScroll.sX&&(p.oScroll.sX="100%");p.iInitDisplayStart===k&&(p.iInitDisplayStart=d.iDisplayStart,p._iDisplayStart=d.iDisplayStart);null!==d.iDeferLoading&&(p.bDeferLoading=!0,g=h.isArray(d.iDeferLoading),p._iRecordsDisplay=g?d.iDeferLoading[0]:d.iDeferLoading,p._iRecordsTotal=
g?d.iDeferLoading[1]:d.iDeferLoading);var t=p.oLanguage;h.extend(!0,t,d.oLanguage);""!==t.sUrl&&(h.ajax({dataType:"json",url:t.sUrl,success:function(a){P(a);H(l.oLanguage,a);h.extend(true,t,a);ga(p)},error:function(){ga(p)}}),o=!0);null===d.asStripeClasses&&(p.asStripeClasses=[i.sStripeOdd,i.sStripeEven]);var g=p.asStripeClasses,s=q.children("tbody").find("tr").eq(0);-1!==h.inArray(!0,h.map(g,function(a){return s.hasClass(a)}))&&(h("tbody tr",this).removeClass(g.join(" ")),p.asDestroyStripes=g.slice());
n=[];g=this.getElementsByTagName("thead");0!==g.length&&(da(p.aoHeader,g[0]),n=qa(p));if(null===d.aoColumns){r=[];g=0;for(j=n.length;g<j;g++)r.push(null)}else r=d.aoColumns;g=0;for(j=r.length;g<j;g++)Fa(p,n?n[g]:null);ib(p,d.aoColumnDefs,r,function(a,b){ka(p,a,b)});if(s.length){var u=function(a,b){return a.getAttribute("data-"+b)!==null?b:null};h.each(na(p,s[0]).cells,function(a,b){var c=p.aoColumns[a];if(c.mData===a){var d=u(b,"sort")||u(b,"order"),e=u(b,"filter")||u(b,"search");if(d!==null||e!==
null){c.mData={_:a+".display",sort:d!==null?a+".@data-"+d:k,type:d!==null?a+".@data-"+d:k,filter:e!==null?a+".@data-"+e:k};ka(p,a)}}})}var v=p.oFeatures;d.bStateSave&&(v.bStateSave=!0,Kb(p,d),z(p,"aoDrawCallback",ya,"state_save"));if(d.aaSorting===k){n=p.aaSorting;g=0;for(j=n.length;g<j;g++)n[g][1]=p.aoColumns[g].asSorting[0]}xa(p);v.bSort&&z(p,"aoDrawCallback",function(){if(p.bSorted){var a=U(p),b={};h.each(a,function(a,c){b[c.src]=c.dir});w(p,null,"order",[p,a,b]);Jb(p)}});z(p,"aoDrawCallback",
function(){(p.bSorted||B(p)==="ssp"||v.bDeferRender)&&xa(p)},"sc");gb(p);g=q.children("caption").each(function(){this._captionSide=q.css("caption-side")});j=q.children("thead");0===j.length&&(j=h("<thead/>").appendTo(this));p.nTHead=j[0];j=q.children("tbody");0===j.length&&(j=h("<tbody/>").appendTo(this));p.nTBody=j[0];j=q.children("tfoot");if(0===j.length&&0<g.length&&(""!==p.oScroll.sX||""!==p.oScroll.sY))j=h("<tfoot/>").appendTo(this);0===j.length||0===j.children().length?q.addClass(i.sNoFooter):
0<j.length&&(p.nTFoot=j[0],da(p.aoFooter,p.nTFoot));if(d.aaData)for(g=0;g<d.aaData.length;g++)K(p,d.aaData[g]);else(p.bDeferLoading||"dom"==B(p))&&ma(p,h(p.nTBody).children("tr"));p.aiDisplay=p.aiDisplayMaster.slice();p.bInitialised=!0;!1===o&&ga(p)}});b=null;return this};var Tb=[],y=Array.prototype,cc=function(a){var b,c,e=m.settings,d=h.map(e,function(a){return a.nTable});if(a){if(a.nTable&&a.oApi)return[a];if(a.nodeName&&"table"===a.nodeName.toLowerCase())return b=h.inArray(a,d),-1!==b?[e[b]]:
null;if(a&&"function"===typeof a.settings)return a.settings().toArray();"string"===typeof a?c=h(a):a instanceof h&&(c=a)}else return[];if(c)return c.map(function(){b=h.inArray(this,d);return-1!==b?e[b]:null}).toArray()};t=function(a,b){if(!(this instanceof t))return new t(a,b);var c=[],e=function(a){(a=cc(a))&&c.push.apply(c,a)};if(h.isArray(a))for(var d=0,f=a.length;d<f;d++)e(a[d]);else e(a);this.context=Na(c);b&&this.push.apply(this,b.toArray?b.toArray():b);this.selector={rows:null,cols:null,opts:null};
t.extend(this,this,Tb)};m.Api=t;t.prototype={any:function(){return 0!==this.flatten().length},concat:y.concat,context:[],each:function(a){for(var b=0,c=this.length;b<c;b++)a.call(this,this[b],b,this);return this},eq:function(a){var b=this.context;return b.length>a?new t(b[a],this[a]):null},filter:function(a){var b=[];if(y.filter)b=y.filter.call(this,a,this);else for(var c=0,e=this.length;c<e;c++)a.call(this,this[c],c,this)&&b.push(this[c]);return new t(this.context,b)},flatten:function(){var a=[];
return new t(this.context,a.concat.apply(a,this.toArray()))},join:y.join,indexOf:y.indexOf||function(a,b){for(var c=b||0,e=this.length;c<e;c++)if(this[c]===a)return c;return-1},iterator:function(a,b,c,e){var d=[],f,g,h,i,o,l=this.context,q,n,m=this.selector;"string"===typeof a&&(e=c,c=b,b=a,a=!1);g=0;for(h=l.length;g<h;g++){var p=new t(l[g]);if("table"===b)f=c.call(p,l[g],g),f!==k&&d.push(f);else if("columns"===b||"rows"===b)f=c.call(p,l[g],this[g],g),f!==k&&d.push(f);else if("column"===b||"column-rows"===
b||"row"===b||"cell"===b){n=this[g];"column-rows"===b&&(q=Ca(l[g],m.opts));i=0;for(o=n.length;i<o;i++)f=n[i],f="cell"===b?c.call(p,l[g],f.row,f.column,g,i):c.call(p,l[g],f,g,i,q),f!==k&&d.push(f)}}return d.length||e?(a=new t(l,a?d.concat.apply([],d):d),b=a.selector,b.rows=m.rows,b.cols=m.cols,b.opts=m.opts,a):this},lastIndexOf:y.lastIndexOf||function(a,b){return this.indexOf.apply(this.toArray.reverse(),arguments)},length:0,map:function(a){var b=[];if(y.map)b=y.map.call(this,a,this);else for(var c=
0,e=this.length;c<e;c++)b.push(a.call(this,this[c],c));return new t(this.context,b)},pluck:function(a){return this.map(function(b){return b[a]})},pop:y.pop,push:y.push,reduce:y.reduce||function(a,b){return hb(this,a,b,0,this.length,1)},reduceRight:y.reduceRight||function(a,b){return hb(this,a,b,this.length-1,-1,-1)},reverse:y.reverse,selector:null,shift:y.shift,sort:y.sort,splice:y.splice,toArray:function(){return y.slice.call(this)},to$:function(){return h(this)},toJQuery:function(){return h(this)},
unique:function(){return new t(this.context,Na(this))},unshift:y.unshift};t.extend=function(a,b,c){if(c.length&&b&&(b instanceof t||b.__dt_wrapper)){var e,d,f,g=function(a,b,c){return function(){var d=b.apply(a,arguments);t.extend(d,d,c.methodExt);return d}};e=0;for(d=c.length;e<d;e++)f=c[e],b[f.name]="function"===typeof f.val?g(a,f.val,f):h.isPlainObject(f.val)?{}:f.val,b[f.name].__dt_wrapper=!0,t.extend(a,b[f.name],f.propExt)}};t.register=r=function(a,b){if(h.isArray(a))for(var c=0,e=a.length;c<
e;c++)t.register(a[c],b);else for(var d=a.split("."),f=Tb,g,j,c=0,e=d.length;c<e;c++){g=(j=-1!==d[c].indexOf("()"))?d[c].replace("()",""):d[c];var i;a:{i=0;for(var o=f.length;i<o;i++)if(f[i].name===g){i=f[i];break a}i=null}i||(i={name:g,val:{},methodExt:[],propExt:[]},f.push(i));c===e-1?i.val=b:f=j?i.methodExt:i.propExt}};t.registerPlural=v=function(a,b,c){t.register(a,c);t.register(b,function(){var a=c.apply(this,arguments);return a===this?this:a instanceof t?a.length?h.isArray(a[0])?new t(a.context,
a[0]):a[0]:k:a})};r("tables()",function(a){var b;if(a){b=t;var c=this.context;if("number"===typeof a)a=[c[a]];else var e=h.map(c,function(a){return a.nTable}),a=h(e).filter(a).map(function(){var a=h.inArray(this,e);return c[a]}).toArray();b=new b(a)}else b=this;return b});r("table()",function(a){var a=this.tables(a),b=a.context;return b.length?new t(b[0]):a});v("tables().nodes()","table().node()",function(){return this.iterator("table",function(a){return a.nTable},1)});v("tables().body()","table().body()",
function(){return this.iterator("table",function(a){return a.nTBody},1)});v("tables().header()","table().header()",function(){return this.iterator("table",function(a){return a.nTHead},1)});v("tables().footer()","table().footer()",function(){return this.iterator("table",function(a){return a.nTFoot},1)});v("tables().containers()","table().container()",function(){return this.iterator("table",function(a){return a.nTableWrapper},1)});r("draw()",function(a){return this.iterator("table",function(b){N(b,
!1===a)})});r("page()",function(a){return a===k?this.page.info().page:this.iterator("table",function(b){Ta(b,a)})});r("page.info()",function(){if(0===this.context.length)return k;var a=this.context[0],b=a._iDisplayStart,c=a._iDisplayLength,e=a.fnRecordsDisplay(),d=-1===c;return{page:d?0:Math.floor(b/c),pages:d?1:Math.ceil(e/c),start:b,end:a.fnDisplayEnd(),length:c,recordsTotal:a.fnRecordsTotal(),recordsDisplay:e}});r("page.len()",function(a){return a===k?0!==this.context.length?this.context[0]._iDisplayLength:
k:this.iterator("table",function(b){Ra(b,a)})});var Ub=function(a,b,c){if(c){var e=new t(a);e.one("draw",function(){c(e.ajax.json())})}"ssp"==B(a)?N(a,b):(C(a,!0),ra(a,[],function(c){oa(a);for(var c=sa(a,c),e=0,g=c.length;e<g;e++)K(a,c[e]);N(a,b);C(a,!1)}))};r("ajax.json()",function(){var a=this.context;if(0<a.length)return a[0].json});r("ajax.params()",function(){var a=this.context;if(0<a.length)return a[0].oAjaxData});r("ajax.reload()",function(a,b){return this.iterator("table",function(c){Ub(c,
!1===b,a)})});r("ajax.url()",function(a){var b=this.context;if(a===k){if(0===b.length)return k;b=b[0];return b.ajax?h.isPlainObject(b.ajax)?b.ajax.url:b.ajax:b.sAjaxSource}return this.iterator("table",function(b){h.isPlainObject(b.ajax)?b.ajax.url=a:b.ajax=a})});r("ajax.url().load()",function(a,b){return this.iterator("table",function(c){Ub(c,!1===b,a)})});var $a=function(a,b,c,e,d){var f=[],g,j,i,o,l,q;i=typeof b;if(!b||"string"===i||"function"===i||b.length===k)b=[b];i=0;for(o=b.length;i<o;i++){j=
b[i]&&b[i].split?b[i].split(","):[b[i]];l=0;for(q=j.length;l<q;l++)(g=c("string"===typeof j[l]?h.trim(j[l]):j[l]))&&g.length&&f.push.apply(f,g)}a=u.selector[a];if(a.length){i=0;for(o=a.length;i<o;i++)f=a[i](e,d,f)}return f},ab=function(a){a||(a={});a.filter&&a.search===k&&(a.search=a.filter);return h.extend({search:"none",order:"current",page:"all"},a)},bb=function(a){for(var b=0,c=a.length;b<c;b++)if(0<a[b].length)return a[0]=a[b],a[0].length=1,a.length=1,a.context=[a.context[b]],a;a.length=0;return a},
Ca=function(a,b){var c,e,d,f=[],g=a.aiDisplay;c=a.aiDisplayMaster;var j=b.search;e=b.order;d=b.page;if("ssp"==B(a))return"removed"===j?[]:V(0,c.length);if("current"==d){c=a._iDisplayStart;for(e=a.fnDisplayEnd();c<e;c++)f.push(g[c])}else if("current"==e||"applied"==e)f="none"==j?c.slice():"applied"==j?g.slice():h.map(c,function(a){return-1===h.inArray(a,g)?a:null});else if("index"==e||"original"==e){c=0;for(e=a.aoData.length;c<e;c++)"none"==j?f.push(c):(d=h.inArray(c,g),(-1===d&&"removed"==j||0<=d&&
"applied"==j)&&f.push(c))}return f};r("rows()",function(a,b){a===k?a="":h.isPlainObject(a)&&(b=a,a="");var b=ab(b),c=this.iterator("table",function(c){var d=b;return $a("row",a,function(a){var b=Pb(a);if(b!==null&&!d)return[b];var j=Ca(c,d);if(b!==null&&h.inArray(b,j)!==-1)return[b];if(!a)return j;if(typeof a==="function")return h.map(j,function(b){var d=c.aoData[b];return a(b,d._aData,d.nTr)?b:null});b=Sb(ia(c.aoData,j,"nTr"));return a.nodeName&&h.inArray(a,b)!==-1?[a._DT_RowIndex]:h(b).filter(a).map(function(){return this._DT_RowIndex}).toArray()},
c,d)},1);c.selector.rows=a;c.selector.opts=b;return c});r("rows().nodes()",function(){return this.iterator("row",function(a,b){return a.aoData[b].nTr||k},1)});r("rows().data()",function(){return this.iterator(!0,"rows",function(a,b){return ia(a.aoData,b,"_aData")},1)});v("rows().cache()","row().cache()",function(a){return this.iterator("row",function(b,c){var e=b.aoData[c];return"search"===a?e._aFilterData:e._aSortData},1)});v("rows().invalidate()","row().invalidate()",function(a){return this.iterator("row",
function(b,c){ca(b,c,a)})});v("rows().indexes()","row().index()",function(){return this.iterator("row",function(a,b){return b},1)});v("rows().remove()","row().remove()",function(){var a=this;return this.iterator("row",function(b,c,e){var d=b.aoData;d.splice(c,1);for(var f=0,g=d.length;f<g;f++)null!==d[f].nTr&&(d[f].nTr._DT_RowIndex=f);h.inArray(c,b.aiDisplay);pa(b.aiDisplayMaster,c);pa(b.aiDisplay,c);pa(a[e],c,!1);Sa(b)})});r("rows.add()",function(a){var b=this.iterator("table",function(b){var c,
f,g,h=[];f=0;for(g=a.length;f<g;f++)c=a[f],c.nodeName&&"TR"===c.nodeName.toUpperCase()?h.push(ma(b,c)[0]):h.push(K(b,c));return h},1),c=this.rows(-1);c.pop();c.push.apply(c,b.toArray());return c});r("row()",function(a,b){return bb(this.rows(a,b))});r("row().data()",function(a){var b=this.context;if(a===k)return b.length&&this.length?b[0].aoData[this[0]]._aData:k;b[0].aoData[this[0]]._aData=a;ca(b[0],this[0],"data");return this});r("row().node()",function(){var a=this.context;return a.length&&this.length?
a[0].aoData[this[0]].nTr||null:null});r("row.add()",function(a){a instanceof h&&a.length&&(a=a[0]);var b=this.iterator("table",function(b){return a.nodeName&&"TR"===a.nodeName.toUpperCase()?ma(b,a)[0]:K(b,a)});return this.row(b[0])});var cb=function(a,b){var c=a.context;c.length&&(c=c[0].aoData[b!==k?b:a[0]],c._details&&(c._details.remove(),c._detailsShow=k,c._details=k))},Vb=function(a,b){var c=a.context;if(c.length&&a.length){var e=c[0].aoData[a[0]];if(e._details){(e._detailsShow=b)?e._details.insertAfter(e.nTr):
e._details.detach();var d=c[0],f=new t(d),g=d.aoData;f.off("draw.dt.DT_details column-visibility.dt.DT_details destroy.dt.DT_details");0<D(g,"_details").length&&(f.on("draw.dt.DT_details",function(a,b){d===b&&f.rows({page:"current"}).eq(0).each(function(a){a=g[a];a._detailsShow&&a._details.insertAfter(a.nTr)})}),f.on("column-visibility.dt.DT_details",function(a,b){if(d===b)for(var c,e=aa(b),f=0,h=g.length;f<h;f++)c=g[f],c._details&&c._details.children("td[colspan]").attr("colspan",e)}),f.on("destroy.dt.DT_details",
function(a,b){if(d===b)for(var c=0,e=g.length;c<e;c++)g[c]._details&&cb(f,c)}))}}};r("row().child()",function(a,b){var c=this.context;if(a===k)return c.length&&this.length?c[0].aoData[this[0]]._details:k;if(!0===a)this.child.show();else if(!1===a)cb(this);else if(c.length&&this.length){var e=c[0],c=c[0].aoData[this[0]],d=[],f=function(a,b){if(h.isArray(a)||a instanceof h)for(var c=0,k=a.length;c<k;c++)f(a[c],b);else a.nodeName&&"tr"===a.nodeName.toLowerCase()?d.push(a):(c=h("<tr><td/></tr>").addClass(b),
h("td",c).addClass(b).html(a)[0].colSpan=aa(e),d.push(c[0]))};f(a,b);c._details&&c._details.remove();c._details=h(d);c._detailsShow&&c._details.insertAfter(c.nTr)}return this});r(["row().child.show()","row().child().show()"],function(){Vb(this,!0);return this});r(["row().child.hide()","row().child().hide()"],function(){Vb(this,!1);return this});r(["row().child.remove()","row().child().remove()"],function(){cb(this);return this});r("row().child.isShown()",function(){var a=this.context;return a.length&&
this.length?a[0].aoData[this[0]]._detailsShow||!1:!1});var dc=/^(.+):(name|visIdx|visible)$/,Wb=function(a,b,c,e,d){for(var c=[],e=0,f=d.length;e<f;e++)c.push(x(a,d[e],b));return c};r("columns()",function(a,b){a===k?a="":h.isPlainObject(a)&&(b=a,a="");var b=ab(b),c=this.iterator("table",function(c){var d=a,f=b,g=c.aoColumns,j=D(g,"sName"),i=D(g,"nTh");return $a("column",d,function(a){var b=Pb(a);if(a==="")return V(g.length);if(b!==null)return[b>=0?b:g.length+b];if(typeof a==="function"){var d=Ca(c,
f);return h.map(g,function(b,f){return a(f,Wb(c,f,0,0,d),i[f])?f:null})}var k=typeof a==="string"?a.match(dc):"";if(k)switch(k[2]){case "visIdx":case "visible":b=parseInt(k[1],10);if(b<0){var m=h.map(g,function(a,b){return a.bVisible?b:null});return[m[m.length+b]]}return[la(c,b)];case "name":return h.map(j,function(a,b){return a===k[1]?b:null})}else return h(i).filter(a).map(function(){return h.inArray(this,i)}).toArray()},c,f)},1);c.selector.cols=a;c.selector.opts=b;return c});v("columns().header()",
"column().header()",function(){return this.iterator("column",function(a,b){return a.aoColumns[b].nTh},1)});v("columns().footer()","column().footer()",function(){return this.iterator("column",function(a,b){return a.aoColumns[b].nTf},1)});v("columns().data()","column().data()",function(){return this.iterator("column-rows",Wb,1)});v("columns().dataSrc()","column().dataSrc()",function(){return this.iterator("column",function(a,b){return a.aoColumns[b].mData},1)});v("columns().cache()","column().cache()",
function(a){return this.iterator("column-rows",function(b,c,e,d,f){return ia(b.aoData,f,"search"===a?"_aFilterData":"_aSortData",c)},1)});v("columns().nodes()","column().nodes()",function(){return this.iterator("column-rows",function(a,b,c,e,d){return ia(a.aoData,d,"anCells",b)},1)});v("columns().visible()","column().visible()",function(a,b){return this.iterator("column",function(c,e){if(a===k)return c.aoColumns[e].bVisible;var d=c.aoColumns,f=d[e],g=c.aoData,j,i,m;if(a!==k&&f.bVisible!==a){if(a){var l=
h.inArray(!0,D(d,"bVisible"),e+1);j=0;for(i=g.length;j<i;j++)m=g[j].nTr,d=g[j].anCells,m&&m.insertBefore(d[e],d[l]||null)}else h(D(c.aoData,"anCells",e)).detach();f.bVisible=a;ea(c,c.aoHeader);ea(c,c.aoFooter);if(b===k||b)X(c),(c.oScroll.sX||c.oScroll.sY)&&Y(c);w(c,null,"column-visibility",[c,e,a]);ya(c)}})});v("columns().indexes()","column().index()",function(a){return this.iterator("column",function(b,c){return"visible"===a?$(b,c):c},1)});r("columns.adjust()",function(){return this.iterator("table",
function(a){X(a)},1)});r("column.index()",function(a,b){if(0!==this.context.length){var c=this.context[0];if("fromVisible"===a||"toData"===a)return la(c,b);if("fromData"===a||"toVisible"===a)return $(c,b)}});r("column()",function(a,b){return bb(this.columns(a,b))});r("cells()",function(a,b,c){h.isPlainObject(a)&&(a.row===k?(c=a,a=null):(c=b,b=null));h.isPlainObject(b)&&(c=b,b=null);if(null===b||b===k)return this.iterator("table",function(b){var d=a,e=ab(c),f=b.aoData,g=Ca(b,e),i=Sb(ia(f,g,"anCells")),
j=h([].concat.apply([],i)),l,m=b.aoColumns.length,o,r,t,s,u,v;return $a("cell",d,function(a){var c=typeof a==="function";if(a===null||a===k||c){o=[];r=0;for(t=g.length;r<t;r++){l=g[r];for(s=0;s<m;s++){u={row:l,column:s};if(c){v=b.aoData[l];a(u,x(b,l,s),v.anCells?v.anCells[s]:null)&&o.push(u)}else o.push(u)}}return o}return h.isPlainObject(a)?[a]:j.filter(a).map(function(a,b){l=b.parentNode._DT_RowIndex;return{row:l,column:h.inArray(b,f[l].anCells)}}).toArray()},b,e)});var e=this.columns(b,c),d=this.rows(a,
c),f,g,j,i,m,l=this.iterator("table",function(a,b){f=[];g=0;for(j=d[b].length;g<j;g++){i=0;for(m=e[b].length;i<m;i++)f.push({row:d[b][g],column:e[b][i]})}return f},1);h.extend(l.selector,{cols:b,rows:a,opts:c});return l});v("cells().nodes()","cell().node()",function(){return this.iterator("cell",function(a,b,c){return(a=a.aoData[b].anCells)?a[c]:k},1)});r("cells().data()",function(){return this.iterator("cell",function(a,b,c){return x(a,b,c)},1)});v("cells().cache()","cell().cache()",function(a){a=
"search"===a?"_aFilterData":"_aSortData";return this.iterator("cell",function(b,c,e){return b.aoData[c][a][e]},1)});v("cells().render()","cell().render()",function(a){return this.iterator("cell",function(b,c,e){return x(b,c,e,a)},1)});v("cells().indexes()","cell().index()",function(){return this.iterator("cell",function(a,b,c){return{row:b,column:c,columnVisible:$(a,c)}},1)});v("cells().invalidate()","cell().invalidate()",function(a){return this.iterator("cell",function(b,c,e){ca(b,c,a,e)})});r("cell()",
function(a,b,c){return bb(this.cells(a,b,c))});r("cell().data()",function(a){var b=this.context,c=this[0];if(a===k)return b.length&&c.length?x(b[0],c[0].row,c[0].column):k;Ia(b[0],c[0].row,c[0].column,a);ca(b[0],c[0].row,"data",c[0].column);return this});r("order()",function(a,b){var c=this.context;if(a===k)return 0!==c.length?c[0].aaSorting:k;"number"===typeof a?a=[[a,b]]:h.isArray(a[0])||(a=Array.prototype.slice.call(arguments));return this.iterator("table",function(b){b.aaSorting=a.slice()})});
r("order.listener()",function(a,b,c){return this.iterator("table",function(e){Oa(e,a,b,c)})});r(["columns().order()","column().order()"],function(a){var b=this;return this.iterator("table",function(c,e){var d=[];h.each(b[e],function(b,c){d.push([c,a])});c.aaSorting=d})});r("search()",function(a,b,c,e){var d=this.context;return a===k?0!==d.length?d[0].oPreviousSearch.sSearch:k:this.iterator("table",function(d){d.oFeatures.bFilter&&fa(d,h.extend({},d.oPreviousSearch,{sSearch:a+"",bRegex:null===b?!1:
b,bSmart:null===c?!0:c,bCaseInsensitive:null===e?!0:e}),1)})});v("columns().search()","column().search()",function(a,b,c,e){return this.iterator("column",function(d,f){var g=d.aoPreSearchCols;if(a===k)return g[f].sSearch;d.oFeatures.bFilter&&(h.extend(g[f],{sSearch:a+"",bRegex:null===b?!1:b,bSmart:null===c?!0:c,bCaseInsensitive:null===e?!0:e}),fa(d,d.oPreviousSearch,1))})});r("state()",function(){return this.context.length?this.context[0].oSavedState:null});r("state.clear()",function(){return this.iterator("table",
function(a){a.fnStateSaveCallback.call(a.oInstance,a,{})})});r("state.loaded()",function(){return this.context.length?this.context[0].oLoadedState:null});r("state.save()",function(){return this.iterator("table",function(a){ya(a)})});m.versionCheck=m.fnVersionCheck=function(a){for(var b=m.version.split("."),a=a.split("."),c,e,d=0,f=a.length;d<f;d++)if(c=parseInt(b[d],10)||0,e=parseInt(a[d],10)||0,c!==e)return c>e;return!0};m.isDataTable=m.fnIsDataTable=function(a){var b=h(a).get(0),c=!1;h.each(m.settings,
function(a,d){var f=d.nScrollHead?h("table",d.nScrollHead)[0]:null,g=d.nScrollFoot?h("table",d.nScrollFoot)[0]:null;if(d.nTable===b||f===b||g===b)c=!0});return c};m.tables=m.fnTables=function(a){return h.map(m.settings,function(b){if(!a||a&&h(b.nTable).is(":visible"))return b.nTable})};m.util={throttle:ua,escapeRegex:va};m.camelToHungarian=H;r("$()",function(a,b){var c=this.rows(b).nodes(),c=h(c);return h([].concat(c.filter(a).toArray(),c.find(a).toArray()))});h.each(["on","one","off"],function(a,
b){r(b+"()",function(){var a=Array.prototype.slice.call(arguments);a[0].match(/\.dt\b/)||(a[0]+=".dt");var e=h(this.tables().nodes());e[b].apply(e,a);return this})});r("clear()",function(){return this.iterator("table",function(a){oa(a)})});r("settings()",function(){return new t(this.context,this.context)});r("init()",function(){var a=this.context;return a.length?a[0].oInit:null});r("data()",function(){return this.iterator("table",function(a){return D(a.aoData,"_aData")}).flatten()});r("destroy()",
function(a){a=a||!1;return this.iterator("table",function(b){var c=b.nTableWrapper.parentNode,e=b.oClasses,d=b.nTable,f=b.nTBody,g=b.nTHead,j=b.nTFoot,i=h(d),f=h(f),k=h(b.nTableWrapper),l=h.map(b.aoData,function(a){return a.nTr}),q;b.bDestroying=!0;w(b,"aoDestroyCallback","destroy",[b]);a||(new t(b)).columns().visible(!0);k.unbind(".DT").find(":not(tbody *)").unbind(".DT");h(Ea).unbind(".DT-"+b.sInstance);d!=g.parentNode&&(i.children("thead").detach(),i.append(g));j&&d!=j.parentNode&&(i.children("tfoot").detach(),
i.append(j));i.detach();k.detach();b.aaSorting=[];b.aaSortingFixed=[];xa(b);h(l).removeClass(b.asStripeClasses.join(" "));h("th, td",g).removeClass(e.sSortable+" "+e.sSortableAsc+" "+e.sSortableDesc+" "+e.sSortableNone);b.bJUI&&(h("th span."+e.sSortIcon+", td span."+e.sSortIcon,g).detach(),h("th, td",g).each(function(){var a=h("div."+e.sSortJUIWrapper,this);h(this).append(a.contents());a.detach()}));!a&&c&&c.insertBefore(d,b.nTableReinsertBefore);f.children().detach();f.append(l);i.css("width",b.sDestroyWidth).removeClass(e.sTable);
(q=b.asDestroyStripes.length)&&f.children().each(function(a){h(this).addClass(b.asDestroyStripes[a%q])});c=h.inArray(b,m.settings);-1!==c&&m.settings.splice(c,1)})});h.each(["column","row","cell"],function(a,b){r(b+"s().every()",function(a){return this.iterator(b,function(e,d,f){a.call((new t(e))[b](d,f))})})});r("i18n()",function(a,b,c){var e=this.context[0],a=R(a)(e.oLanguage);a===k&&(a=b);c!==k&&h.isPlainObject(a)&&(a=a[c]!==k?a[c]:a._);return a.replace("%d",c)});m.version="1.10.7";m.settings=
[];m.models={};m.models.oSearch={bCaseInsensitive:!0,sSearch:"",bRegex:!1,bSmart:!0};m.models.oRow={nTr:null,anCells:null,_aData:[],_aSortData:null,_aFilterData:null,_sFilterRow:null,_sRowStripe:"",src:null};m.models.oColumn={idx:null,aDataSort:null,asSorting:null,bSearchable:null,bSortable:null,bVisible:null,_sManualType:null,_bAttrSrc:!1,fnCreatedCell:null,fnGetData:null,fnSetData:null,mData:null,mRender:null,nTh:null,nTf:null,sClass:null,sContentPadding:null,sDefaultContent:null,sName:null,sSortDataType:"std",
sSortingClass:null,sSortingClassJUI:null,sTitle:null,sType:null,sWidth:null,sWidthOrig:null};m.defaults={aaData:null,aaSorting:[[0,"asc"]],aaSortingFixed:[],ajax:null,aLengthMenu:[10,25,50,100],aoColumns:null,aoColumnDefs:null,aoSearchCols:[],asStripeClasses:null,bAutoWidth:!0,bDeferRender:!1,bDestroy:!1,bFilter:!0,bInfo:!0,bJQueryUI:!1,bLengthChange:!0,bPaginate:!0,bProcessing:!1,bRetrieve:!1,bScrollCollapse:!1,bServerSide:!1,bSort:!0,bSortMulti:!0,bSortCellsTop:!1,bSortClasses:!0,bStateSave:!1,
fnCreatedRow:null,fnDrawCallback:null,fnFooterCallback:null,fnFormatNumber:function(a){return a.toString().replace(/\B(?=(\d{3})+(?!\d))/g,this.oLanguage.sThousands)},fnHeaderCallback:null,fnInfoCallback:null,fnInitComplete:null,fnPreDrawCallback:null,fnRowCallback:null,fnServerData:null,fnServerParams:null,fnStateLoadCallback:function(a){try{return JSON.parse((-1===a.iStateDuration?sessionStorage:localStorage).getItem("DataTables_"+a.sInstance+"_"+location.pathname))}catch(b){}},fnStateLoadParams:null,
fnStateLoaded:null,fnStateSaveCallback:function(a,b){try{(-1===a.iStateDuration?sessionStorage:localStorage).setItem("DataTables_"+a.sInstance+"_"+location.pathname,JSON.stringify(b))}catch(c){}},fnStateSaveParams:null,iStateDuration:7200,iDeferLoading:null,iDisplayLength:10,iDisplayStart:0,iTabIndex:0,oClasses:{},oLanguage:{oAria:{sSortAscending:": activate to sort column ascending",sSortDescending:": activate to sort column descending"},oPaginate:{sFirst:"First",sLast:"Last",sNext:"Next",sPrevious:"Previous"},
sEmptyTable:"No data available in table",sInfo:"Showing _START_ to _END_ of _TOTAL_ entries",sInfoEmpty:"Showing 0 to 0 of 0 entries",sInfoFiltered:"(filtered from _MAX_ total entries)",sInfoPostFix:"",sDecimal:"",sThousands:",",sLengthMenu:"Show _MENU_ entries",sLoadingRecords:"Loading...",sProcessing:"Processing...",sSearch:"Search:",sSearchPlaceholder:"",sUrl:"",sZeroRecords:"No matching records found"},oSearch:h.extend({},m.models.oSearch),sAjaxDataProp:"data",sAjaxSource:null,sDom:"lfrtip",searchDelay:null,
sPaginationType:"simple_numbers",sScrollX:"",sScrollXInner:"",sScrollY:"",sServerMethod:"GET",renderer:null};W(m.defaults);m.defaults.column={aDataSort:null,iDataSort:-1,asSorting:["asc","desc"],bSearchable:!0,bSortable:!0,bVisible:!0,fnCreatedCell:null,mData:null,mRender:null,sCellType:"td",sClass:"",sContentPadding:"",sDefaultContent:null,sName:"",sSortDataType:"std",sTitle:null,sType:null,sWidth:null};W(m.defaults.column);m.models.oSettings={oFeatures:{bAutoWidth:null,bDeferRender:null,bFilter:null,
bInfo:null,bLengthChange:null,bPaginate:null,bProcessing:null,bServerSide:null,bSort:null,bSortMulti:null,bSortClasses:null,bStateSave:null},oScroll:{bCollapse:null,iBarWidth:0,sX:null,sXInner:null,sY:null},oLanguage:{fnInfoCallback:null},oBrowser:{bScrollOversize:!1,bScrollbarLeft:!1},ajax:null,aanFeatures:[],aoData:[],aiDisplay:[],aiDisplayMaster:[],aoColumns:[],aoHeader:[],aoFooter:[],oPreviousSearch:{},aoPreSearchCols:[],aaSorting:null,aaSortingFixed:[],asStripeClasses:null,asDestroyStripes:[],
sDestroyWidth:0,aoRowCallback:[],aoHeaderCallback:[],aoFooterCallback:[],aoDrawCallback:[],aoRowCreatedCallback:[],aoPreDrawCallback:[],aoInitComplete:[],aoStateSaveParams:[],aoStateLoadParams:[],aoStateLoaded:[],sTableId:"",nTable:null,nTHead:null,nTFoot:null,nTBody:null,nTableWrapper:null,bDeferLoading:!1,bInitialised:!1,aoOpenRows:[],sDom:null,searchDelay:null,sPaginationType:"two_button",iStateDuration:0,aoStateSave:[],aoStateLoad:[],oSavedState:null,oLoadedState:null,sAjaxSource:null,sAjaxDataProp:null,
bAjaxDataGet:!0,jqXHR:null,json:k,oAjaxData:k,fnServerData:null,aoServerParams:[],sServerMethod:null,fnFormatNumber:null,aLengthMenu:null,iDraw:0,bDrawing:!1,iDrawError:-1,_iDisplayLength:10,_iDisplayStart:0,_iRecordsTotal:0,_iRecordsDisplay:0,bJUI:null,oClasses:{},bFiltered:!1,bSorted:!1,bSortCellsTop:null,oInit:null,aoDestroyCallback:[],fnRecordsTotal:function(){return"ssp"==B(this)?1*this._iRecordsTotal:this.aiDisplayMaster.length},fnRecordsDisplay:function(){return"ssp"==B(this)?1*this._iRecordsDisplay:
this.aiDisplay.length},fnDisplayEnd:function(){var a=this._iDisplayLength,b=this._iDisplayStart,c=b+a,e=this.aiDisplay.length,d=this.oFeatures,f=d.bPaginate;return d.bServerSide?!1===f||-1===a?b+e:Math.min(b+a,this._iRecordsDisplay):!f||c>e||-1===a?e:c},oInstance:null,sInstance:null,iTabIndex:0,nScrollHead:null,nScrollFoot:null,aLastSort:[],oPlugins:{}};m.ext=u={buttons:{},classes:{},errMode:"alert",feature:[],search:[],selector:{cell:[],column:[],row:[]},internal:{},legacy:{ajax:null},pager:{},renderer:{pageButton:{},
header:{}},order:{},type:{detect:[],search:{},order:{}},_unique:0,fnVersionCheck:m.fnVersionCheck,iApiIndex:0,oJUIClasses:{},sVersion:m.version};h.extend(u,{afnFiltering:u.search,aTypes:u.type.detect,ofnSearch:u.type.search,oSort:u.type.order,afnSortData:u.order,aoFeatures:u.feature,oApi:u.internal,oStdClasses:u.classes,oPagination:u.pager});h.extend(m.ext.classes,{sTable:"dataTable",sNoFooter:"no-footer",sPageButton:"paginate_button",sPageButtonActive:"current",sPageButtonDisabled:"disabled",sStripeOdd:"odd",
sStripeEven:"even",sRowEmpty:"dataTables_empty",sWrapper:"dataTables_wrapper",sFilter:"dataTables_filter",sInfo:"dataTables_info",sPaging:"dataTables_paginate paging_",sLength:"dataTables_length",sProcessing:"dataTables_processing",sSortAsc:"sorting_asc",sSortDesc:"sorting_desc",sSortable:"sorting",sSortableAsc:"sorting_asc_disabled",sSortableDesc:"sorting_desc_disabled",sSortableNone:"sorting_disabled",sSortColumn:"sorting_",sFilterInput:"",sLengthSelect:"",sScrollWrapper:"dataTables_scroll",sScrollHead:"dataTables_scrollHead",
sScrollHeadInner:"dataTables_scrollHeadInner",sScrollBody:"dataTables_scrollBody",sScrollFoot:"dataTables_scrollFoot",sScrollFootInner:"dataTables_scrollFootInner",sHeaderTH:"",sFooterTH:"",sSortJUIAsc:"",sSortJUIDesc:"",sSortJUI:"",sSortJUIAscAllowed:"",sSortJUIDescAllowed:"",sSortJUIWrapper:"",sSortIcon:"",sJUIHeader:"",sJUIFooter:""});var Da="",Da="",F=Da+"ui-state-default",ja=Da+"css_right ui-icon ui-icon-",Xb=Da+"fg-toolbar ui-toolbar ui-widget-header ui-helper-clearfix";h.extend(m.ext.oJUIClasses,
m.ext.classes,{sPageButton:"fg-button ui-button "+F,sPageButtonActive:"ui-state-disabled",sPageButtonDisabled:"ui-state-disabled",sPaging:"dataTables_paginate fg-buttonset ui-buttonset fg-buttonset-multi ui-buttonset-multi paging_",sSortAsc:F+" sorting_asc",sSortDesc:F+" sorting_desc",sSortable:F+" sorting",sSortableAsc:F+" sorting_asc_disabled",sSortableDesc:F+" sorting_desc_disabled",sSortableNone:F+" sorting_disabled",sSortJUIAsc:ja+"triangle-1-n",sSortJUIDesc:ja+"triangle-1-s",sSortJUI:ja+"carat-2-n-s",
sSortJUIAscAllowed:ja+"carat-1-n",sSortJUIDescAllowed:ja+"carat-1-s",sSortJUIWrapper:"DataTables_sort_wrapper",sSortIcon:"DataTables_sort_icon",sScrollHead:"dataTables_scrollHead "+F,sScrollFoot:"dataTables_scrollFoot "+F,sHeaderTH:F,sFooterTH:F,sJUIHeader:Xb+" ui-corner-tl ui-corner-tr",sJUIFooter:Xb+" ui-corner-bl ui-corner-br"});var Mb=m.ext.pager;h.extend(Mb,{simple:function(){return["previous","next"]},full:function(){return["first","previous","next","last"]},simple_numbers:function(a,b){return["previous",
Wa(a,b),"next"]},full_numbers:function(a,b){return["first","previous",Wa(a,b),"next","last"]},_numbers:Wa,numbers_length:7});h.extend(!0,m.ext.renderer,{pageButton:{_:function(a,b,c,e,d,f){var g=a.oClasses,j=a.oLanguage.oPaginate,i,k,l=0,m=function(b,e){var n,r,t,s,u=function(b){Ta(a,b.data.action,true)};n=0;for(r=e.length;n<r;n++){s=e[n];if(h.isArray(s)){t=h("<"+(s.DT_el||"div")+"/>").appendTo(b);m(t,s)}else{k=i="";switch(s){case "ellipsis":b.append('<span class="ellipsis">…</span>');break;
case "first":i=j.sFirst;k=s+(d>0?"":" "+g.sPageButtonDisabled);break;case "previous":i=j.sPrevious;k=s+(d>0?"":" "+g.sPageButtonDisabled);break;case "next":i=j.sNext;k=s+(d<f-1?"":" "+g.sPageButtonDisabled);break;case "last":i=j.sLast;k=s+(d<f-1?"":" "+g.sPageButtonDisabled);break;default:i=s+1;k=d===s?g.sPageButtonActive:""}if(i){t=h("<a>",{"class":g.sPageButton+" "+k,"aria-controls":a.sTableId,"data-dt-idx":l,tabindex:a.iTabIndex,id:c===0&&typeof s==="string"?a.sTableId+"_"+s:null}).html(i).appendTo(b);
Va(t,{action:s},u);l++}}}},n;try{n=h(Q.activeElement).data("dt-idx")}catch(r){}m(h(b).empty(),e);n&&h(b).find("[data-dt-idx="+n+"]").focus()}}});h.extend(m.ext.type.detect,[function(a,b){var c=b.oLanguage.sDecimal;return Za(a,c)?"num"+c:null},function(a){if(a&&!(a instanceof Date)&&(!ac.test(a)||!bc.test(a)))return null;var b=Date.parse(a);return null!==b&&!isNaN(b)||J(a)?"date":null},function(a,b){var c=b.oLanguage.sDecimal;return Za(a,c,!0)?"num-fmt"+c:null},function(a,b){var c=b.oLanguage.sDecimal;
return Rb(a,c)?"html-num"+c:null},function(a,b){var c=b.oLanguage.sDecimal;return Rb(a,c,!0)?"html-num-fmt"+c:null},function(a){return J(a)||"string"===typeof a&&-1!==a.indexOf("<")?"html":null}]);h.extend(m.ext.type.search,{html:function(a){return J(a)?a:"string"===typeof a?a.replace(Ob," ").replace(Ba,""):""},string:function(a){return J(a)?a:"string"===typeof a?a.replace(Ob," "):a}});var Aa=function(a,b,c,e){if(0!==a&&(!a||"-"===a))return-Infinity;b&&(a=Qb(a,b));a.replace&&(c&&(a=a.replace(c,"")),
e&&(a=a.replace(e,"")));return 1*a};h.extend(u.type.order,{"date-pre":function(a){return Date.parse(a)||0},"html-pre":function(a){return J(a)?"":a.replace?a.replace(/<.*?>/g,"").toLowerCase():a+""},"string-pre":function(a){return J(a)?"":"string"===typeof a?a.toLowerCase():!a.toString?"":a.toString()},"string-asc":function(a,b){return a<b?-1:a>b?1:0},"string-desc":function(a,b){return a<b?1:a>b?-1:0}});db("");h.extend(!0,m.ext.renderer,{header:{_:function(a,b,c,e){h(a.nTable).on("order.dt.DT",function(d,
f,g,h){if(a===f){d=c.idx;b.removeClass(c.sSortingClass+" "+e.sSortAsc+" "+e.sSortDesc).addClass(h[d]=="asc"?e.sSortAsc:h[d]=="desc"?e.sSortDesc:c.sSortingClass)}})},jqueryui:function(a,b,c,e){h("<div/>").addClass(e.sSortJUIWrapper).append(b.contents()).append(h("<span/>").addClass(e.sSortIcon+" "+c.sSortingClassJUI)).appendTo(b);h(a.nTable).on("order.dt.DT",function(d,f,g,h){if(a===f){d=c.idx;b.removeClass(e.sSortAsc+" "+e.sSortDesc).addClass(h[d]=="asc"?e.sSortAsc:h[d]=="desc"?e.sSortDesc:c.sSortingClass);
b.find("span."+e.sSortIcon).removeClass(e.sSortJUIAsc+" "+e.sSortJUIDesc+" "+e.sSortJUI+" "+e.sSortJUIAscAllowed+" "+e.sSortJUIDescAllowed).addClass(h[d]=="asc"?e.sSortJUIAsc:h[d]=="desc"?e.sSortJUIDesc:c.sSortingClassJUI)}})}}});m.render={number:function(a,b,c,e){return{display:function(d){if("number"!==typeof d&&"string"!==typeof d)return d;var f=0>d?"-":"",d=Math.abs(parseFloat(d)),g=parseInt(d,10),d=c?b+(d-g).toFixed(c).substring(2):"";return f+(e||"")+g.toString().replace(/\B(?=(\d{3})+(?!\d))/g,
a)+d}}}};h.extend(m.ext.internal,{_fnExternApiFunc:Nb,_fnBuildAjax:ra,_fnAjaxUpdate:kb,_fnAjaxParameters:tb,_fnAjaxUpdateDraw:ub,_fnAjaxDataSrc:sa,_fnAddColumn:Fa,_fnColumnOptions:ka,_fnAdjustColumnSizing:X,_fnVisibleToColumnIndex:la,_fnColumnIndexToVisible:$,_fnVisbleColumns:aa,_fnGetColumns:Z,_fnColumnTypes:Ha,_fnApplyColumnDefs:ib,_fnHungarianMap:W,_fnCamelToHungarian:H,_fnLanguageCompat:P,_fnBrowserDetect:gb,_fnAddData:K,_fnAddTr:ma,_fnNodeToDataIndex:function(a,b){return b._DT_RowIndex!==k?b._DT_RowIndex:
null},_fnNodeToColumnIndex:function(a,b,c){return h.inArray(c,a.aoData[b].anCells)},_fnGetCellData:x,_fnSetCellData:Ia,_fnSplitObjNotation:Ka,_fnGetObjectDataFn:R,_fnSetObjectDataFn:S,_fnGetDataMaster:La,_fnClearTable:oa,_fnDeleteIndex:pa,_fnInvalidate:ca,_fnGetRowElements:na,_fnCreateTr:Ja,_fnBuildHead:jb,_fnDrawHead:ea,_fnDraw:M,_fnReDraw:N,_fnAddOptionsHtml:mb,_fnDetectHeader:da,_fnGetUniqueThs:qa,_fnFeatureHtmlFilter:ob,_fnFilterComplete:fa,_fnFilterCustom:xb,_fnFilterColumn:wb,_fnFilter:vb,_fnFilterCreateSearch:Qa,
_fnEscapeRegex:va,_fnFilterData:yb,_fnFeatureHtmlInfo:rb,_fnUpdateInfo:Bb,_fnInfoMacros:Cb,_fnInitialise:ga,_fnInitComplete:ta,_fnLengthChange:Ra,_fnFeatureHtmlLength:nb,_fnFeatureHtmlPaginate:sb,_fnPageChange:Ta,_fnFeatureHtmlProcessing:pb,_fnProcessingDisplay:C,_fnFeatureHtmlTable:qb,_fnScrollDraw:Y,_fnApplyToChildren:G,_fnCalculateColumnWidths:Ga,_fnThrottle:ua,_fnConvertToWidth:Db,_fnScrollingWidthAdjust:Fb,_fnGetWidestNode:Eb,_fnGetMaxLenString:Gb,_fnStringToCss:s,_fnScrollBarWidth:Hb,_fnSortFlatten:U,
_fnSort:lb,_fnSortAria:Jb,_fnSortListener:Ua,_fnSortAttachListener:Oa,_fnSortingClasses:xa,_fnSortData:Ib,_fnSaveState:ya,_fnLoadState:Kb,_fnSettingsFromNode:za,_fnLog:I,_fnMap:E,_fnBindAction:Va,_fnCallbackReg:z,_fnCallbackFire:w,_fnLengthOverflow:Sa,_fnRenderer:Pa,_fnDataSource:B,_fnRowAttributes:Ma,_fnCalculateEnd:function(){}});h.fn.dataTable=m;h.fn.dataTableSettings=m.settings;h.fn.dataTableExt=m.ext;h.fn.DataTable=function(a){return h(this).dataTable(a).api()};h.each(m,function(a,b){h.fn.DataTable[a]=
b});return h.fn.dataTable};"function"===typeof define&&define.amd?define("datatables",["jquery"],P):"object"===typeof exports?module.exports=P(require("jquery")):jQuery&&!jQuery.fn.dataTable&&P(jQuery)})(window,document); | georgesks/digirey | ws/assets/vendors/datatable/js/jquery.dataTables.min.js | JavaScript | mit | 79,882 |
export default function absFloor(number) {
if (number < 0) {
// -0 -> 0
return Math.ceil(number) || 0;
} else {
return Math.floor(number);
}
}
| hieupham0206/yii-cloudteam-app | vendor/bower/moment/src/lib/utils/abs-floor.js | JavaScript | bsd-3-clause | 179 |
var knex = require('knex'),
config = require('../../config'),
dbConfig = config.database,
knexInstance;
function configureDriver(client) {
var pg;
if (client === 'pg' || client === 'postgres' || client === 'postgresql') {
try {
pg = require('pg');
} catch (e) {
pg = require('pg.js');
}
// By default PostgreSQL returns data as strings along with an OID that identifies
// its type. We're setting the parser to convert OID 20 (int8) into a javascript
// integer.
pg.types.setTypeParser(20, function (val) {
return val === null ? null : parseInt(val, 10);
});
}
}
if (!knexInstance && dbConfig && dbConfig.client) {
configureDriver(dbConfig.client);
knexInstance = knex(dbConfig);
}
module.exports = knexInstance;
| bromagosa/pugemaltren | ghost/core/server/data/db/connection.js | JavaScript | mit | 857 |
'use strict';
function registerExports(gulpInst, tasks) {
var taskNames = Object.keys(tasks);
if (taskNames.length) {
taskNames.forEach(register);
}
function register(taskName) {
var task = tasks[taskName];
if (typeof task !== 'function') {
return;
}
gulpInst.task(taskName, task);
}
}
module.exports = registerExports;
| devatworkgit/revenuemasters | themes/custom/revenuemasters/node_modules/gulp-cli/lib/shared/registerExports.js | JavaScript | gpl-2.0 | 362 |
/**
* @license
* Copyright 2014 The Lovefield Project Authors. All Rights Reserved.
*
* 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.
*/
goog.provide('lf.proc.QueryTask');
goog.require('goog.Promise');
goog.require('lf.TransactionType');
goog.require('lf.cache.Journal');
goog.require('lf.proc.PhysicalQueryPlan');
goog.require('lf.proc.Task');
goog.require('lf.query.SelectContext');
goog.require('lf.service');
/**
* A QueryTask represents a collection of queries that should be executed as
* part of a single transaction.
* @implements {lf.proc.Task}
* @constructor
* @struct
*
* @param {!lf.Global} global
* @param {!Array<!lf.proc.TaskItem>} items
*/
lf.proc.QueryTask = function(global, items) {
/** @protected {!lf.Global} */
this.global = global;
/** @private {!lf.BackStore} */
this.backStore_ = global.getService(lf.service.BACK_STORE);
/** @protected {!Array<!lf.query.Context>} */
this.queries = items.map(function(item) {
return item.context;
});
/** @private {!Array<!lf.proc.PhysicalQueryPlan>} */
this.plans_ = items.map(function(item) {
return item.plan;
});
/** @private {!lf.structs.Set<!lf.schema.Table>} */
this.combinedScope_ = lf.proc.PhysicalQueryPlan.getCombinedScope(this.plans_);
/** @private {!lf.TransactionType} */
this.txType_ = this.detectType_();
/** @private {!goog.promise.Resolver.<!Array<!lf.proc.Relation>>} */
this.resolver_ = goog.Promise.withResolver();
};
/**
* @return {!lf.TransactionType}
* @private
*/
lf.proc.QueryTask.prototype.detectType_ = function() {
var txType = this.queries.some(
function(query) {
return !(query instanceof lf.query.SelectContext);
}) ? lf.TransactionType.READ_WRITE : lf.TransactionType.READ_ONLY;
return txType;
};
/** @override */
lf.proc.QueryTask.prototype.exec = function() {
var journal = new lf.cache.Journal(this.global, this.combinedScope_);
var results = [];
var remainingPlans = this.plans_.slice();
var queries = this.queries;
/** @return {!IThenable} */
var sequentiallyExec = function() {
var plan = remainingPlans.shift();
if (plan) {
var queryContext = queries[results.length];
return plan.getRoot().exec(journal, queryContext).then(
function(relations) {
results.push(relations[0]);
return sequentiallyExec();
});
}
return goog.Promise.resolve();
};
return sequentiallyExec().then(function() {
var tx = this.backStore_.createTx(this.txType_, journal);
return tx.commit();
}.bind(this)).then(function() {
this.onSuccess(results);
return results;
}.bind(this), function(e) {
journal.rollback();
throw e;
});
};
/** @override */
lf.proc.QueryTask.prototype.getType = function() {
return this.txType_;
};
/** @override */
lf.proc.QueryTask.prototype.getScope = function() {
return this.combinedScope_;
};
/** @override */
lf.proc.QueryTask.prototype.getResolver = function() {
return this.resolver_;
};
/** @override */
lf.proc.QueryTask.prototype.getId = function() {
return goog.getUid(this);
};
/** @override */
lf.proc.QueryTask.prototype.getPriority = goog.abstractMethod;
/**
* Executes after all queries have finished successfully. Default implementation
* is a no-op. Subclasses should override this method as necessary.
* @param {!Array<!lf.proc.Relation>} results The results of all queries run by
* this task.
* @protected
*/
lf.proc.QueryTask.prototype.onSuccess = function(results) {
// Default implementation is a no-op.
};
| vasopikof/lovefield | lib/proc/query_task.js | JavaScript | apache-2.0 | 4,078 |
// Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
// License: GNU General Public License v3. See license.txt
wn.pages['latest-updates'].onload = function(wrapper) {
wn.ui.make_app_page({
parent: wrapper,
title: wn._('Latest Updates'),
single_column: true
});
var parent = $(wrapper).find(".layout-main");
parent.html('<div class="progress progress-striped active">\
<div class="progress-bar" style="width: 100%;"></div></div>')
return wn.call({
method:"home.page.latest_updates.latest_updates.get",
callback: function(r) {
parent.empty();
$("<p class='help'>"+wn._("Report issues at")+
"<a href='https://github.com/webnotes/erpnext/issues'>"+wn._("GitHub Issues")+"</a></p>\
<hr><h3>"+wn._("Commit Log")+"</h3>")
.appendTo(parent);
var $tbody = $('<table class="table table-bordered"><tbody></tbody></table>')
.appendTo(parent).find("tbody");
$.each(r.message, function(i, log) {
if(log.message.indexOf("minor")===-1
&& log.message.indexOf("docs")===-1
&& log.message.indexOf("[")!==-1) {
log.message = log.message.replace(/(\[[^\]]*\])/g,
function(match, p1, offset, string) {
match = match.toLowerCase();
var color_class = "";
$.each(["bug", "fix"], function(i, v) {
if(!color_class && match.indexOf(v)!==-1)
color_class = "label-danger";
});
return '<span class="label ' + color_class +'">' + p1.slice(1,-1) + '</span> '
});
log.repo = log.repo==="lib" ? "wnframework" : "erpnext";
$(repl('<tr>\
<td><b><a href="https://github.com/webnotes/%(repo)s/commit/%(commit)s" \
target="_blank">%(message)s</b>\
<br><span class="text-muted">By %(author)s on %(date)s</span></td></tr>', log)).appendTo($tbody);
}
})
}
})
}; | saurabh6790/test-med-app | home/page/latest_updates/latest_updates.js | JavaScript | agpl-3.0 | 1,829 |
/** @license MIT License (c) copyright B Cavalier & J Hann */
/**
* wire/dojo/events plugin
* wire plugin that can connect event handlers after an object is
* initialized, and disconnect them when an object is destroyed.
* This implementation uses dojo.connect and dojo.disconnect to do
* the work of connecting and disconnecting event handlers.
*
* wire is part of the cujo.js family of libraries (http://cujojs.com/)
*
* Licensed under the MIT License at:
* http://www.opensource.org/licenses/mit-license.php
*/
define(['when', '../lib/connection', 'dojo', 'dojo/_base/event'],
function(when, connection, events) {
return {
wire$plugin: function eventsPlugin(/*, options*/) {
var connectHandles = [];
function handleConnection(source, eventName, handler) {
connectHandles.push(events.connect(source, eventName, handler));
}
function connect(source, connect, options, wire) {
return connection.parse(source, connect, options, wire, handleConnection);
}
/*
Function: connectFacet
Setup connections for each specified in the connects param. Each key
in connects is a reference, and the corresponding value is an object
whose keys are event names, and whose values are methods of object to
invoke. For example:
connect: {
"refToOtherThing": {
"eventOrMethodOfOtherThing": "myOwnMethod"
},
"dom!myButton": {
"onclick": "_handleButtonClick"
},
"dijit!myWidget": {
"onChange": "_handleValueChange"
}
"myOwnEventOrMethod": {
"refToOtherThing": "methodOfOtherThing"
}
}
Parameters:
factory - wiring factory
object - object being wired, will be the target of connected events
connects - specification of events to connect, see examples above.
*/
function connectFacet(wire, facet) {
var promises, connects;
promises = [];
connects = facet.options;
for(var ref in connects) {
promises.push(connect(facet, ref, connects[ref], wire));
}
return when.all(promises);
}
return {
context: {
destroy: function(resolver) {
for (var i = connectHandles.length - 1; i >= 0; i--){
events.disconnect(connectHandles[i]);
}
resolver.resolve();
}
},
facets: {
connect: {
connect: function(resolver, facet, wire) {
resolver.resolve(connectFacet(wire, facet));
}
}
}
};
}
};
}); | sedesigner2nd/AngularticsPinwheel | labs/architecture-examples/cujo/bower_components/wire/dojo/events.js | JavaScript | mit | 2,497 |
/*!***************************************************
* mark.js v8.7.0
* https://github.com/julmot/mark.js
* Copyright (c) 2014–2017, Julian Motz
* Released under the MIT license https://git.io/vwTVl
*****************************************************/
"use strict";
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
(function (factory, window, document) {
if (typeof define === "function" && define.amd) {
define([], function () {
return factory(window, document);
});
} else if ((typeof module === "undefined" ? "undefined" : _typeof(module)) === "object" && module.exports) {
module.exports = factory(window, document);
} else {
factory(window, document);
}
})(function (window, document) {
var Mark = function () {
function Mark(ctx) {
_classCallCheck(this, Mark);
this.ctx = ctx;
this.ie = false;
var ua = window.navigator.userAgent;
if (ua.indexOf("MSIE") > -1 || ua.indexOf("Trident") > -1) {
this.ie = true;
}
}
_createClass(Mark, [{
key: "log",
value: function log(msg) {
var level = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : "debug";
var log = this.opt.log;
if (!this.opt.debug) {
return;
}
if ((typeof log === "undefined" ? "undefined" : _typeof(log)) === "object" && typeof log[level] === "function") {
log[level]("mark.js: " + msg);
}
}
}, {
key: "escapeStr",
value: function escapeStr(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
}, {
key: "createRegExp",
value: function createRegExp(str) {
str = this.escapeStr(str);
if (Object.keys(this.opt.synonyms).length) {
str = this.createSynonymsRegExp(str);
}
if (this.opt.ignoreJoiners) {
str = this.setupIgnoreJoinersRegExp(str);
}
if (this.opt.diacritics) {
str = this.createDiacriticsRegExp(str);
}
str = this.createMergedBlanksRegExp(str);
if (this.opt.ignoreJoiners) {
str = this.createIgnoreJoinersRegExp(str);
}
str = this.createAccuracyRegExp(str);
return str;
}
}, {
key: "createSynonymsRegExp",
value: function createSynonymsRegExp(str) {
var syn = this.opt.synonyms,
sens = this.opt.caseSensitive ? "" : "i";
for (var index in syn) {
if (syn.hasOwnProperty(index)) {
var value = syn[index],
k1 = this.escapeStr(index),
k2 = this.escapeStr(value);
str = str.replace(new RegExp("(" + k1 + "|" + k2 + ")", "gm" + sens), "(" + k1 + "|" + k2 + ")");
}
}
return str;
}
}, {
key: "setupIgnoreJoinersRegExp",
value: function setupIgnoreJoinersRegExp(str) {
return str.replace(/[^(|)\\]/g, function (val, indx, original) {
var nextChar = original.charAt(indx + 1);
if (/[(|)\\]/.test(nextChar) || nextChar === "") {
return val;
} else {
return val + "\0";
}
});
}
}, {
key: "createIgnoreJoinersRegExp",
value: function createIgnoreJoinersRegExp(str) {
return str.split("\0").join("[\\u00ad|\\u200b|\\u200c|\\u200d]?");
}
}, {
key: "createDiacriticsRegExp",
value: function createDiacriticsRegExp(str) {
var sens = this.opt.caseSensitive ? "" : "i",
dct = this.opt.caseSensitive ? ["aàáâãäåāąă", "AÀÁÂÃÄÅĀĄĂ", "cçćč", "CÇĆČ", "dđď", "DĐĎ", "eèéêëěēę", "EÈÉÊËĚĒĘ", "iìíîïī", "IÌÍÎÏĪ", "lł", "LŁ", "nñňń", "NÑŇŃ", "oòóôõöøō", "OÒÓÔÕÖØŌ", "rř", "RŘ", "sšśș", "SŠŚȘ", "tťț", "TŤȚ", "uùúûüůū", "UÙÚÛÜŮŪ", "yÿý", "YŸÝ", "zžżź", "ZŽŻŹ"] : ["aÀÁÂÃÄÅàáâãäåĀāąĄăĂ", "cÇçćĆčČ", "dđĐďĎ", "eÈÉÊËèéêëěĚĒēęĘ", "iÌÍÎÏìíîïĪī", "lłŁ", "nÑñňŇńŃ", "oÒÓÔÕÖØòóôõöøŌō", "rřŘ", "sŠšśŚșȘ", "tťŤțȚ", "uÙÚÛÜùúûüůŮŪū", "yŸÿýÝ", "zŽžżŻźŹ"];
var handled = [];
str.split("").forEach(function (ch) {
dct.every(function (dct) {
if (dct.indexOf(ch) !== -1) {
if (handled.indexOf(dct) > -1) {
return false;
}
str = str.replace(new RegExp("[" + dct + "]", "gm" + sens), "[" + dct + "]");
handled.push(dct);
}
return true;
});
});
return str;
}
}, {
key: "createMergedBlanksRegExp",
value: function createMergedBlanksRegExp(str) {
return str.replace(/[\s]+/gmi, "[\\s]+");
}
}, {
key: "createAccuracyRegExp",
value: function createAccuracyRegExp(str) {
var _this = this;
var acc = this.opt.accuracy,
val = typeof acc === "string" ? acc : acc.value,
ls = typeof acc === "string" ? [] : acc.limiters,
lsJoin = "";
ls.forEach(function (limiter) {
lsJoin += "|" + _this.escapeStr(limiter);
});
switch (val) {
case "partially":
default:
return "()(" + str + ")";
case "complementary":
return "()([^\\s" + lsJoin + "]*" + str + "[^\\s" + lsJoin + "]*)";
case "exactly":
return "(^|\\s" + lsJoin + ")(" + str + ")(?=$|\\s" + lsJoin + ")";
}
}
}, {
key: "getSeparatedKeywords",
value: function getSeparatedKeywords(sv) {
var _this2 = this;
var stack = [];
sv.forEach(function (kw) {
if (!_this2.opt.separateWordSearch) {
if (kw.trim() && stack.indexOf(kw) === -1) {
stack.push(kw);
}
} else {
kw.split(" ").forEach(function (kwSplitted) {
if (kwSplitted.trim() && stack.indexOf(kwSplitted) === -1) {
stack.push(kwSplitted);
}
});
}
});
return {
"keywords": stack.sort(function (a, b) {
return b.length - a.length;
}),
"length": stack.length
};
}
}, {
key: "getTextNodes",
value: function getTextNodes(cb) {
var _this3 = this;
var val = "",
nodes = [];
this.iterator.forEachNode(NodeFilter.SHOW_TEXT, function (node) {
nodes.push({
start: val.length,
end: (val += node.textContent).length,
node: node
});
}, function (node) {
if (_this3.matchesExclude(node.parentNode)) {
return NodeFilter.FILTER_REJECT;
} else {
return NodeFilter.FILTER_ACCEPT;
}
}, function () {
cb({
value: val,
nodes: nodes
});
});
}
}, {
key: "matchesExclude",
value: function matchesExclude(el) {
return DOMIterator.matches(el, this.opt.exclude.concat(["script", "style", "title", "head", "html"]));
}
}, {
key: "wrapRangeInTextNode",
value: function wrapRangeInTextNode(node, start, end) {
var hEl = !this.opt.element ? "mark" : this.opt.element,
startNode = node.splitText(start),
ret = startNode.splitText(end - start);
var repl = document.createElement(hEl);
repl.setAttribute("data-markjs", "true");
if (this.opt.className) {
repl.setAttribute("class", this.opt.className);
}
repl.textContent = startNode.textContent;
startNode.parentNode.replaceChild(repl, startNode);
return ret;
}
}, {
key: "wrapRangeInMappedTextNode",
value: function wrapRangeInMappedTextNode(dict, start, end, filterCb, eachCb) {
var _this4 = this;
dict.nodes.every(function (n, i) {
var sibl = dict.nodes[i + 1];
if (typeof sibl === "undefined" || sibl.start > start) {
var _ret = function () {
if (!filterCb(n.node)) {
return {
v: false
};
}
var s = start - n.start,
e = (end > n.end ? n.end : end) - n.start,
startStr = dict.value.substr(0, n.start),
endStr = dict.value.substr(e + n.start);
n.node = _this4.wrapRangeInTextNode(n.node, s, e);
dict.value = startStr + endStr;
dict.nodes.forEach(function (k, j) {
if (j >= i) {
if (dict.nodes[j].start > 0 && j !== i) {
dict.nodes[j].start -= e;
}
dict.nodes[j].end -= e;
}
});
end -= e;
eachCb(n.node.previousSibling, n.start);
if (end > n.end) {
start = n.end;
} else {
return {
v: false
};
}
}();
if ((typeof _ret === "undefined" ? "undefined" : _typeof(_ret)) === "object") return _ret.v;
}
return true;
});
}
}, {
key: "wrapMatches",
value: function wrapMatches(regex, ignoreGroups, filterCb, eachCb, endCb) {
var _this5 = this;
var matchIdx = ignoreGroups === 0 ? 0 : ignoreGroups + 1;
this.getTextNodes(function (dict) {
dict.nodes.forEach(function (node) {
node = node.node;
var match = void 0;
while ((match = regex.exec(node.textContent)) !== null && match[matchIdx] !== "") {
if (!filterCb(match[matchIdx], node)) {
continue;
}
var pos = match.index;
if (matchIdx !== 0) {
for (var i = 1; i < matchIdx; i++) {
pos += match[i].length;
}
}
node = _this5.wrapRangeInTextNode(node, pos, pos + match[matchIdx].length);
eachCb(node.previousSibling);
regex.lastIndex = 0;
}
});
endCb();
});
}
}, {
key: "wrapMatchesAcrossElements",
value: function wrapMatchesAcrossElements(regex, ignoreGroups, filterCb, eachCb, endCb) {
var _this6 = this;
var matchIdx = ignoreGroups === 0 ? 0 : ignoreGroups + 1;
this.getTextNodes(function (dict) {
var match = void 0;
while ((match = regex.exec(dict.value)) !== null && match[matchIdx] !== "") {
var start = match.index;
if (matchIdx !== 0) {
for (var i = 1; i < matchIdx; i++) {
start += match[i].length;
}
}
var end = start + match[matchIdx].length;
_this6.wrapRangeInMappedTextNode(dict, start, end, function (node) {
return filterCb(match[matchIdx], node);
}, function (node, lastIndex) {
regex.lastIndex = lastIndex;
eachCb(node);
});
}
endCb();
});
}
}, {
key: "unwrapMatches",
value: function unwrapMatches(node) {
var parent = node.parentNode;
var docFrag = document.createDocumentFragment();
while (node.firstChild) {
docFrag.appendChild(node.removeChild(node.firstChild));
}
parent.replaceChild(docFrag, node);
if (!this.ie) {
parent.normalize();
} else {
this.normalizeTextNode(parent);
}
}
}, {
key: "normalizeTextNode",
value: function normalizeTextNode(node) {
if (!node) {
return;
}
if (node.nodeType === 3) {
while (node.nextSibling && node.nextSibling.nodeType === 3) {
node.nodeValue += node.nextSibling.nodeValue;
node.parentNode.removeChild(node.nextSibling);
}
} else {
this.normalizeTextNode(node.firstChild);
}
this.normalizeTextNode(node.nextSibling);
}
}, {
key: "markRegExp",
value: function markRegExp(regexp, opt) {
var _this7 = this;
this.opt = opt;
this.log("Searching with expression \"" + regexp + "\"");
var totalMatches = 0,
fn = "wrapMatches";
var eachCb = function eachCb(element) {
totalMatches++;
_this7.opt.each(element);
};
if (this.opt.acrossElements) {
fn = "wrapMatchesAcrossElements";
}
this[fn](regexp, this.opt.ignoreGroups, function (match, node) {
return _this7.opt.filter(node, match, totalMatches);
}, eachCb, function () {
if (totalMatches === 0) {
_this7.opt.noMatch(regexp);
}
_this7.opt.done(totalMatches);
});
}
}, {
key: "mark",
value: function mark(sv, opt) {
var _this8 = this;
this.opt = opt;
var totalMatches = 0,
fn = "wrapMatches";
var _getSeparatedKeywords = this.getSeparatedKeywords(typeof sv === "string" ? [sv] : sv),
kwArr = _getSeparatedKeywords.keywords,
kwArrLen = _getSeparatedKeywords.length,
sens = this.opt.caseSensitive ? "" : "i",
handler = function handler(kw) {
var regex = new RegExp(_this8.createRegExp(kw), "gm" + sens),
matches = 0;
_this8.log("Searching with expression \"" + regex + "\"");
_this8[fn](regex, 1, function (term, node) {
return _this8.opt.filter(node, kw, totalMatches, matches);
}, function (element) {
matches++;
totalMatches++;
_this8.opt.each(element);
}, function () {
if (matches === 0) {
_this8.opt.noMatch(kw);
}
if (kwArr[kwArrLen - 1] === kw) {
_this8.opt.done(totalMatches);
} else {
handler(kwArr[kwArr.indexOf(kw) + 1]);
}
});
};
if (this.opt.acrossElements) {
fn = "wrapMatchesAcrossElements";
}
if (kwArrLen === 0) {
this.opt.done(totalMatches);
} else {
handler(kwArr[0]);
}
}
}, {
key: "unmark",
value: function unmark(opt) {
var _this9 = this;
this.opt = opt;
var sel = this.opt.element ? this.opt.element : "*";
sel += "[data-markjs]";
if (this.opt.className) {
sel += "." + this.opt.className;
}
this.log("Removal selector \"" + sel + "\"");
this.iterator.forEachNode(NodeFilter.SHOW_ELEMENT, function (node) {
_this9.unwrapMatches(node);
}, function (node) {
var matchesSel = DOMIterator.matches(node, sel),
matchesExclude = _this9.matchesExclude(node);
if (!matchesSel || matchesExclude) {
return NodeFilter.FILTER_REJECT;
} else {
return NodeFilter.FILTER_ACCEPT;
}
}, this.opt.done);
}
}, {
key: "opt",
set: function set(val) {
this._opt = _extends({}, {
"element": "",
"className": "",
"exclude": [],
"iframes": false,
"separateWordSearch": true,
"diacritics": true,
"synonyms": {},
"accuracy": "partially",
"acrossElements": false,
"caseSensitive": false,
"ignoreJoiners": false,
"ignoreGroups": 0,
"each": function each() {},
"noMatch": function noMatch() {},
"filter": function filter() {
return true;
},
"done": function done() {},
"debug": false,
"log": window.console
}, val);
},
get: function get() {
return this._opt;
}
}, {
key: "iterator",
get: function get() {
if (!this._iterator) {
this._iterator = new DOMIterator(this.ctx, this.opt.iframes, this.opt.exclude);
}
return this._iterator;
}
}]);
return Mark;
}();
var DOMIterator = function () {
function DOMIterator(ctx) {
var iframes = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
var exclude = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : [];
_classCallCheck(this, DOMIterator);
this.ctx = ctx;
this.iframes = iframes;
this.exclude = exclude;
}
_createClass(DOMIterator, [{
key: "getContexts",
value: function getContexts() {
var ctx = void 0,
filteredCtx = [];
if (typeof this.ctx === "undefined" || !this.ctx) {
ctx = [];
} else if (NodeList.prototype.isPrototypeOf(this.ctx)) {
ctx = Array.prototype.slice.call(this.ctx);
} else if (Array.isArray(this.ctx)) {
ctx = this.ctx;
} else if (typeof this.ctx === "string") {
ctx = Array.prototype.slice.call(document.querySelectorAll(this.ctx));
} else {
ctx = [this.ctx];
}
ctx.forEach(function (ctx) {
var isDescendant = filteredCtx.filter(function (contexts) {
return contexts.contains(ctx);
}).length > 0;
if (filteredCtx.indexOf(ctx) === -1 && !isDescendant) {
filteredCtx.push(ctx);
}
});
return filteredCtx;
}
}, {
key: "getIframeContents",
value: function getIframeContents(ifr, successFn) {
var errorFn = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : function () {};
var doc = void 0;
try {
var ifrWin = ifr.contentWindow;
doc = ifrWin.document;
if (!ifrWin || !doc) {
throw new Error("iframe inaccessible");
}
} catch (e) {
errorFn();
}
if (doc) {
successFn(doc);
}
}
}, {
key: "onIframeReady",
value: function onIframeReady(ifr, successFn, errorFn) {
var _this10 = this;
try {
(function () {
var ifrWin = ifr.contentWindow,
bl = "about:blank",
compl = "complete",
isBlank = function isBlank() {
var src = ifr.getAttribute("src").trim(),
href = ifrWin.location.href;
return href === bl && src !== bl && src;
},
observeOnload = function observeOnload() {
var listener = function listener() {
try {
if (!isBlank()) {
ifr.removeEventListener("load", listener);
_this10.getIframeContents(ifr, successFn, errorFn);
}
} catch (e) {
errorFn();
}
};
ifr.addEventListener("load", listener);
};
if (ifrWin.document.readyState === compl) {
if (isBlank()) {
observeOnload();
} else {
_this10.getIframeContents(ifr, successFn, errorFn);
}
} else {
observeOnload();
}
})();
} catch (e) {
errorFn();
}
}
}, {
key: "waitForIframes",
value: function waitForIframes(ctx, done) {
var _this11 = this;
var eachCalled = 0;
this.forEachIframe(ctx, function () {
return true;
}, function (ifr) {
eachCalled++;
_this11.waitForIframes(ifr.querySelector("html"), function () {
if (! --eachCalled) {
done();
}
});
}, function (handled) {
if (!handled) {
done();
}
});
}
}, {
key: "forEachIframe",
value: function forEachIframe(ctx, filter, each) {
var _this12 = this;
var end = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : function () {};
var ifr = ctx.querySelectorAll("iframe"),
open = ifr.length,
handled = 0;
ifr = Array.prototype.slice.call(ifr);
var checkEnd = function checkEnd() {
if (--open <= 0) {
end(handled);
}
};
if (!open) {
checkEnd();
}
ifr.forEach(function (ifr) {
if (DOMIterator.matches(ifr, _this12.exclude)) {
checkEnd();
} else {
_this12.onIframeReady(ifr, function (con) {
if (filter(ifr)) {
handled++;
each(con);
}
checkEnd();
}, checkEnd);
}
});
}
}, {
key: "createIterator",
value: function createIterator(ctx, whatToShow, filter) {
return document.createNodeIterator(ctx, whatToShow, filter, false);
}
}, {
key: "createInstanceOnIframe",
value: function createInstanceOnIframe(contents) {
return new DOMIterator(contents.querySelector("html"), this.iframes);
}
}, {
key: "compareNodeIframe",
value: function compareNodeIframe(node, prevNode, ifr) {
var compCurr = node.compareDocumentPosition(ifr),
prev = Node.DOCUMENT_POSITION_PRECEDING;
if (compCurr & prev) {
if (prevNode !== null) {
var compPrev = prevNode.compareDocumentPosition(ifr),
after = Node.DOCUMENT_POSITION_FOLLOWING;
if (compPrev & after) {
return true;
}
} else {
return true;
}
}
return false;
}
}, {
key: "getIteratorNode",
value: function getIteratorNode(itr) {
var prevNode = itr.previousNode();
var node = void 0;
if (prevNode === null) {
node = itr.nextNode();
} else {
node = itr.nextNode() && itr.nextNode();
}
return {
prevNode: prevNode,
node: node
};
}
}, {
key: "checkIframeFilter",
value: function checkIframeFilter(node, prevNode, currIfr, ifr) {
var key = false,
handled = false;
ifr.forEach(function (ifrDict, i) {
if (ifrDict.val === currIfr) {
key = i;
handled = ifrDict.handled;
}
});
if (this.compareNodeIframe(node, prevNode, currIfr)) {
if (key === false && !handled) {
ifr.push({
val: currIfr,
handled: true
});
} else if (key !== false && !handled) {
ifr[key].handled = true;
}
return true;
}
if (key === false) {
ifr.push({
val: currIfr,
handled: false
});
}
return false;
}
}, {
key: "handleOpenIframes",
value: function handleOpenIframes(ifr, whatToShow, eCb, fCb) {
var _this13 = this;
ifr.forEach(function (ifrDict) {
if (!ifrDict.handled) {
_this13.getIframeContents(ifrDict.val, function (con) {
_this13.createInstanceOnIframe(con).forEachNode(whatToShow, eCb, fCb);
});
}
});
}
}, {
key: "iterateThroughNodes",
value: function iterateThroughNodes(whatToShow, ctx, eachCb, filterCb, doneCb) {
var _this14 = this;
var itr = this.createIterator(ctx, whatToShow, filterCb);
var ifr = [],
elements = [],
node = void 0,
prevNode = void 0,
retrieveNodes = function retrieveNodes() {
var _getIteratorNode = _this14.getIteratorNode(itr);
prevNode = _getIteratorNode.prevNode;
node = _getIteratorNode.node;
return node;
};
while (retrieveNodes()) {
if (this.iframes) {
this.forEachIframe(ctx, function (currIfr) {
return _this14.checkIframeFilter(node, prevNode, currIfr, ifr);
}, function (con) {
_this14.createInstanceOnIframe(con).forEachNode(whatToShow, eachCb, filterCb);
});
}
elements.push(node);
}
elements.forEach(function (node) {
eachCb(node);
});
if (this.iframes) {
this.handleOpenIframes(ifr, whatToShow, eachCb, filterCb);
}
doneCb();
}
}, {
key: "forEachNode",
value: function forEachNode(whatToShow, each, filter) {
var _this15 = this;
var done = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : function () {};
var contexts = this.getContexts();
var open = contexts.length;
if (!open) {
done();
}
contexts.forEach(function (ctx) {
var ready = function ready() {
_this15.iterateThroughNodes(whatToShow, ctx, each, filter, function () {
if (--open <= 0) {
done();
}
});
};
if (_this15.iframes) {
_this15.waitForIframes(ctx, ready);
} else {
ready();
}
});
}
}], [{
key: "matches",
value: function matches(element, selector) {
var selectors = typeof selector === "string" ? [selector] : selector,
fn = element.matches || element.matchesSelector || element.msMatchesSelector || element.mozMatchesSelector || element.oMatchesSelector || element.webkitMatchesSelector;
if (fn) {
var match = false;
selectors.every(function (sel) {
if (fn.call(element, sel)) {
match = true;
return false;
}
return true;
});
return match;
} else {
return false;
}
}
}]);
return DOMIterator;
}();
window.Mark = function (ctx) {
var _this16 = this;
var instance = new Mark(ctx);
this.mark = function (sv, opt) {
instance.mark(sv, opt);
return _this16;
};
this.markRegExp = function (sv, opt) {
instance.markRegExp(sv, opt);
return _this16;
};
this.unmark = function (opt) {
instance.unmark(opt);
return _this16;
};
return this;
};
return window.Mark;
}, window, document);
| Asaf-S/jsdelivr | files/mark.js/8.7.0/mark.js | JavaScript | mit | 35,152 |
/**
* @author Kyle-Larson https://github.com/Kyle-Larson
*
* Loader loads FBX file and generates Group representing FBX scene.
* Requires FBX file to be >= 7.0 and in ASCII format.
*
* Supports:
* Mesh Generation (Positional Data)
* Normal Data (Per Vertex Drawing Instance)
* UV Data (Per Vertex Drawing Instance)
* Skinning
* Animation
* - Separated Animations based on stacks.
* - Skeletal & Non-Skeletal Animations
*
* Needs Support:
* Indexed Buffers
* PreRotation support.
*/
( function () {
/**
* Generates a loader for loading FBX files from URL and parsing into
* a THREE.Group.
* @param {THREE.LoadingManager} manager - Loading Manager for loader to use.
*/
THREE.FBXLoader = function ( manager ) {
THREE.Loader.call( this );
this.manager = ( manager !== undefined ) ? manager : THREE.DefaultLoadingManager;
this.fileLoader = new THREE.FileLoader( this.manager );
this.textureLoader = new THREE.TextureLoader( this.manager );
};
Object.assign( THREE.FBXLoader.prototype, THREE.Loader.prototype );
THREE.FBXLoader.prototype.constructor = THREE.FBXLoader;
Object.assign( THREE.FBXLoader.prototype, {
/**
* Loads an ASCII FBX file from URL and parses into a THREE.Group.
* THREE.Group will have an animations property of AnimationClips
* of the different animations exported with the FBX.
* @param {string} url - URL of the FBX file.
* @param {function(THREE.Group):void} onLoad - Callback for when FBX file is loaded and parsed.
* @param {function(ProgressEvent):void} onProgress - Callback fired periodically when file is being retrieved from server.
* @param {function(Event):void} onError - Callback fired when error occurs (Currently only with retrieving file, not with parsing errors).
*/
load: function ( url, onLoad, onProgress, onError ) {
var self = this;
var resourceDirectory = url.split( /[\\\/]/ );
resourceDirectory.pop();
resourceDirectory = resourceDirectory.join( '/' );
this.fileLoader.load( url, function ( text ) {
if ( ! isFbxFormatASCII( text ) ) {
console.error( 'FBXLoader: FBX Binary format not supported.' );
self.manager.itemError( url );
return;
}
if ( getFbxVersion( text ) < 7000 ) {
console.error( 'FBXLoader: FBX version not supported for file at ' + url + ', FileVersion: ' + getFbxVersion( text ) );
self.manager.itemError( url );
return;
}
var scene = self.parse( text, resourceDirectory );
onLoad( scene );
}, onProgress, onError );
},
/**
* Parses an ASCII FBX file and returns a THREE.Group.
* THREE.Group will have an animations property of AnimationClips
* of the different animations within the FBX file.
* @param {string} FBXText - Contents of FBX file to parse.
* @param {string} resourceDirectory - Directory to load external assets (e.g. textures ) from.
* @returns {THREE.Group}
*/
parse: function ( FBXText, resourceDirectory ) {
var loader = this;
var FBXTree = new TextParser().parse( FBXText );
var connections = parseConnections( FBXTree );
var textures = parseTextures( FBXTree );
var materials = parseMaterials( FBXTree, textures, connections );
var deformerMap = parseDeformers( FBXTree, connections );
var geometryMap = parseGeometries( FBXTree, connections, deformerMap );
var sceneGraph = parseScene( FBXTree, connections, deformerMap, geometryMap, materials );
return sceneGraph;
/**
* @typedef {{value: number}} FBXValue
*/
/**
* @typedef {{value: {x: string, y: string, z: string}}} FBXVector3
*/
/**
* @typedef {{properties: {a: string}}} FBXArrayNode
*/
/**
* @typedef {{properties: {MappingInformationType: string, ReferenceInformationType: string }, subNodes: Object<string, FBXArrayNode>}} FBXMappedArrayNode
*/
/**
* @typedef {{id: number, name: string, properties: {FileName: string}}} FBXTextureNode
*/
/**
* @typedef {{id: number, attrName: string, properties: {ShadingModel: string, Diffuse: FBXVector3, Specular: FBXVector3, Shininess: FBXValue, Emissive: FBXVector3, EmissiveFactor: FBXValue, Opacity: FBXValue}}} FBXMaterialNode
*/
/**
* @typedef {{subNodes: {Indexes: FBXArrayNode, Weights: FBXArrayNode, Transform: FBXArrayNode, TransformLink: FBXArrayNode}, properties: { Mode: string }}} FBXSubDeformerNode
*/
/**
* @typedef {{id: number, attrName: string, attrType: string, subNodes: {Vertices: FBXArrayNode, PolygonVertexIndex: FBXArrayNode, LayerElementNormal: FBXMappedArrayNode[], LayerElementMaterial: FBXMappedArrayNode[], LayerElementUV: FBXMappedArrayNode[]}}} FBXGeometryNode
*/
/**
* @typedef {{id: number, attrName: string, attrType: string, properties: {Lcl_Translation: FBXValue, Lcl_Rotation: FBXValue, Lcl_Scaling: FBXValue}}} FBXModelNode
*/
/**
* Parses map of relationships between objects.
* @param {{Connections: { properties: { connections: [number, number, string][]}}}} FBXTree
* @returns {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>}
*/
function parseConnections( FBXTree ) {
/**
* @type {Map<number, { parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>}
*/
var connectionMap = new Map();
if ( 'Connections' in FBXTree ) {
/**
* @type {[number, number, string][]}
*/
var connectionArray = FBXTree.Connections.properties.connections;
connectionArray.forEach( function ( connection ) {
if ( ! connectionMap.has( connection[ 0 ] ) ) {
connectionMap.set( connection[ 0 ], {
parents: [],
children: []
} );
}
var parentRelationship = { ID: connection[ 1 ], relationship: connection[ 2 ] };
connectionMap.get( connection[ 0 ] ).parents.push( parentRelationship );
if ( ! connectionMap.has( connection[ 1 ] ) ) {
connectionMap.set( connection[ 1 ], {
parents: [],
children: []
} );
}
var childRelationship = { ID: connection[ 0 ], relationship: connection[ 2 ] };
connectionMap.get( connection[ 1 ] ).children.push( childRelationship );
} );
}
return connectionMap;
}
/**
* Parses map of textures referenced in FBXTree.
* @param {{Objects: {subNodes: {Texture: Object.<string, FBXTextureNode>}}}} FBXTree
* @returns {Map<number, THREE.Texture>}
*/
function parseTextures( FBXTree ) {
/**
* @type {Map<number, THREE.Texture>}
*/
var textureMap = new Map();
if ( 'Texture' in FBXTree.Objects.subNodes ) {
var textureNodes = FBXTree.Objects.subNodes.Texture;
for ( var nodeID in textureNodes ) {
var texture = parseTexture( textureNodes[ nodeID ] );
textureMap.set( parseInt( nodeID ), texture );
}
}
return textureMap;
/**
* @param {textureNode} textureNode - Node to get texture information from.
* @returns {THREE.Texture}
*/
function parseTexture( textureNode ) {
var FBX_ID = textureNode.id;
var name = textureNode.name;
var filePath = textureNode.properties.FileName;
var split = filePath.split( /[\\\/]/ );
if ( split.length > 0 ) {
var fileName = split[ split.length - 1 ];
} else {
var fileName = filePath;
}
/**
* @type {THREE.Texture}
*/
var texture = loader.textureLoader.load( resourceDirectory + '/' + fileName );
texture.name = name;
texture.FBX_ID = FBX_ID;
return texture;
}
}
/**
* Parses map of Material information.
* @param {{Objects: {subNodes: {Material: Object.<number, FBXMaterialNode>}}}} FBXTree
* @param {Map<number, THREE.Texture>} textureMap
* @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
* @returns {Map<number, THREE.Material>}
*/
function parseMaterials( FBXTree, textureMap, connections ) {
var materialMap = new Map();
if ( 'Material' in FBXTree.Objects.subNodes ) {
var materialNodes = FBXTree.Objects.subNodes.Material;
for ( var nodeID in materialNodes ) {
var material = parseMaterial( materialNodes[ nodeID ], textureMap, connections );
materialMap.set( parseInt( nodeID ), material );
}
}
return materialMap;
/**
* Takes information from Material node and returns a generated THREE.Material
* @param {FBXMaterialNode} materialNode
* @param {Map<number, THREE.Texture>} textureMap
* @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
* @returns {THREE.Material}
*/
function parseMaterial( materialNode, textureMap, connections ) {
var FBX_ID = materialNode.id;
var name = materialNode.attrName;
var type = materialNode.properties.ShadingModel;
var children = connections.get( FBX_ID ).children;
var parameters = parseParameters( materialNode.properties, textureMap, children );
var material;
switch ( type ) {
case 'phong':
material = new THREE.MeshPhongMaterial();
break;
case 'lambert':
material = new THREE.MeshLambertMaterial();
break;
default:
console.warn( 'No implementation given for material type ' + type + ' in FBXLoader.js. Defaulting to basic material' );
material = new THREE.MeshBasicMaterial( { color: 0x3300ff } );
break;
}
material.setValues( parameters );
material.name = name;
return material;
/**
* @typedef {{Diffuse: FBXVector3, Specular: FBXVector3, Shininess: FBXValue, Emissive: FBXVector3, EmissiveFactor: FBXValue, Opacity: FBXValue}} FBXMaterialProperties
*/
/**
* @typedef {{color: THREE.Color=, specular: THREE.Color=, shininess: number=, emissive: THREE.Color=, emissiveIntensity: number=, opacity: number=, transparent: boolean=, map: THREE.Texture=}} THREEMaterialParameterPack
*/
/**
* @param {FBXMaterialProperties} properties
* @param {Map<number, THREE.Texture>} textureMap
* @param {{ID: number, relationship: string}[]} childrenRelationships
* @returns {THREEMaterialParameterPack}
*/
function parseParameters( properties, textureMap, childrenRelationships ) {
var parameters = {};
if ( properties.Diffuse ) {
parameters.color = parseColor( properties.Diffuse );
}
if ( properties.Specular ) {
parameters.specular = parseColor( properties.Specular );
}
if ( properties.Shininess ) {
parameters.shininess = properties.Shininess.value;
}
if ( properties.Emissive ) {
parameters.emissive = parseColor( properties.Emissive );
}
if ( properties.EmissiveFactor ) {
parameters.emissiveIntensity = properties.EmissiveFactor.value;
}
if ( properties.Opacity ) {
parameters.opacity = properties.Opacity.value;
}
if ( parameters.opacity < 1.0 ) {
parameters.transparent = true;
}
childrenRelationships.forEach( function ( relationship ) {
var type = relationship.relationship;
switch ( type ) {
case " \"AmbientColor":
//TODO: Support AmbientColor textures
break;
case " \"DiffuseColor":
parameters.map = textureMap.get( relationship.ID );
break;
default:
console.warn( 'Unknown texture application of type ' + type + ', skipping texture' );
break;
}
} );
return parameters;
}
}
}
/**
* Generates map of Skeleton-like objects for use later when generating and binding skeletons.
* @param {{Objects: {subNodes: {Deformer: Object.<number, FBXSubDeformerNode>}}}} FBXTree
* @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
* @returns {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}>}
*/
function parseDeformers( FBXTree, connections ) {
var skeletonMap = new Map();
if ( 'Deformer' in FBXTree.Objects.subNodes ) {
var DeformerNodes = FBXTree.Objects.subNodes.Deformer;
for ( var nodeID in DeformerNodes ) {
var deformerNode = DeformerNodes[ nodeID ];
if ( deformerNode.attrType === 'Skin' ) {
var conns = connections.get( parseInt( nodeID ) );
var skeleton = parseSkeleton( conns, DeformerNodes );
skeleton.FBX_ID = parseInt( nodeID );
skeletonMap.set( parseInt( nodeID ), skeleton );
}
}
}
return skeletonMap;
/**
* Generates a "Skeleton Representation" of FBX nodes based on an FBX Skin Deformer's connections and an object containing SubDeformer nodes.
* @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} connections
* @param {Object.<number, FBXSubDeformerNode>} DeformerNodes
* @returns {{map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}}
*/
function parseSkeleton( connections, DeformerNodes ) {
var subDeformers = new Map();
var subDeformerArray = [];
connections.children.forEach( function ( child ) {
var subDeformerNode = DeformerNodes[ child.ID ];
var subDeformer = {
FBX_ID: child.ID,
indices: parseIntArray( subDeformerNode.subNodes.Indexes.properties.a ),
weights: parseFloatArray( subDeformerNode.subNodes.Weights.properties.a ),
transform: parseMatrixArray( subDeformerNode.subNodes.Transform.properties.a ),
transformLink: parseMatrixArray( subDeformerNode.subNodes.TransformLink.properties.a ),
linkMode: subDeformerNode.properties.Mode
};
subDeformers.set( child.ID, subDeformer );
subDeformerArray.push( subDeformer );
} );
return {
map: subDeformers,
array: subDeformerArray,
bones: []
};
}
}
/**
* Generates Buffer geometries from geometry information in FBXTree, and generates map of THREE.BufferGeometries
* @param {{Objects: {subNodes: {Geometry: Object.<number, FBXGeometryNode}}}} FBXTree
* @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
* @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}>} deformerMap
* @returns {Map<number, THREE.BufferGeometry>}
*/
function parseGeometries( FBXTree, connections, deformerMap ) {
var geometryMap = new Map();
if ( 'Geometry' in FBXTree.Objects.subNodes ) {
var geometryNodes = FBXTree.Objects.subNodes.Geometry;
for ( var nodeID in geometryNodes ) {
var relationships = connections.get( parseInt( nodeID ) );
var geo = parseGeometry( geometryNodes[ nodeID ], relationships, deformerMap );
geometryMap.set( parseInt( nodeID ), geo );
}
}
return geometryMap;
/**
* Generates BufferGeometry from FBXGeometryNode.
* @param {FBXGeometryNode} geometryNode
* @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships
* @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[]}>} deformerMap
* @returns {THREE.BufferGeometry}
*/
function parseGeometry( geometryNode, relationships, deformerMap ) {
switch ( geometryNode.attrType ) {
case 'Mesh':
return parseMeshGeometry( geometryNode, relationships, deformerMap );
break;
case 'NurbsCurve':
return parseNurbsGeometry( geometryNode, relationships, deformerMap );
break;
}
/**
* Specialty function for parsing Mesh based Geometry Nodes.
* @param {FBXGeometryNode} geometryNode
* @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships - Object representing relationships between specific geometry node and other nodes.
* @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[]}>} deformerMap - Map object of deformers and subDeformers by ID.
* @returns {THREE.BufferGeometry}
*/
function parseMeshGeometry( geometryNode, relationships, deformerMap ) {
var FBX_ID = geometryNode.id;
var name = geometryNode.attrName;
for ( var i = 0; i < relationships.children.length; ++ i ) {
if ( deformerMap.has( relationships.children[ i ].ID ) ) {
var deformer = deformerMap.get( relationships.children[ i ].ID );
break;
}
}
var geometry = genGeometry( geometryNode, deformer );
return geometry;
/**
* @param {{map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[]}} deformer - Skeleton representation for geometry instance.
* @returns {THREE.BufferGeometry}
*/
function genGeometry( geometryNode, deformer ) {
var geometry = new Geometry();
//First, each index is going to be its own vertex.
var vertexBuffer = parseFloatArray( geometryNode.subNodes.Vertices.properties.a );
var indexBuffer = parseIntArray( geometryNode.subNodes.PolygonVertexIndex.properties.a );
if ( 'LayerElementNormal' in geometryNode.subNodes ) {
var normalInfo = getNormals( geometryNode );
}
if ( 'LayerElementUV' in geometryNode.subNodes ) {
var uvInfo = getUVs( geometryNode );
}
if ( 'LayerElementMaterial' in geometryNode.subNodes ) {
var materialInfo = getMaterials( geometryNode );
}
var faceVertexBuffer = [];
var polygonIndex = 0;
for ( var polygonVertexIndex = 0; polygonVertexIndex < indexBuffer.length; ++ polygonVertexIndex ) {
var endOfFace;
var vertexIndex = indexBuffer[ polygonVertexIndex ];
if ( indexBuffer[ polygonVertexIndex ] < 0 ) {
vertexIndex = vertexIndex ^ - 1;
indexBuffer[ polygonVertexIndex ] = vertexIndex;
endOfFace = true;
}
var vertex = new Vertex();
var weightIndices = [];
var weights = [];
vertex.position.fromArray( vertexBuffer, vertexIndex * 3 );
// If we have a deformer for this geometry, get the skinIndex and skinWeights for this object.
// They are stored as vertex indices on each deformer, and we need them as deformer indices
// for each vertex.
if ( deformer ) {
for ( var j = 0; j < deformer.array.length; ++ j ) {
var index = deformer.array[ j ].indices.findIndex( function ( index ) {
return index === indexBuffer[ polygonVertexIndex ];
} );
if ( index !== - 1 ) {
weights.push( deformer.array[ j ].weights[ index ] );
weightIndices.push( j );
}
}
if ( weights.length > 4 ) {
console.warn( 'FBXLoader: Vertex has more than 4 skinning weights assigned to vertex. Deleting additional weights.' );
var WIndex = [ 0, 0, 0, 0 ];
var Weight = [ 0, 0, 0, 0 ];
for ( var polygonVertexIndex = 0; polygonVertexIndex < weights.length; ++ polygonVertexIndex ) {
var currentWeight = weights[ polygonVertexIndex ];
var currentIndex = weightIndices[ polygonVertexIndex ];
for ( var j = 0; j < Weight.length; ++ j ) {
if ( currentWeight > Weight[ j ] ) {
var tmp = Weight[ j ];
Weight[ j ] = currentWeight;
currentWeight = tmp;
tmp = WIndex[ j ];
WIndex[ j ] = currentIndex;
currentIndex = tmp;
}
}
}
weightIndices = WIndex;
weights = Weight;
}
for ( var i = weights.length; i < 4; i ++ ) {
weights[ i ] = 0;
weightIndices[ i ] = 0;
}
vertex.skinWeights.fromArray( weights );
vertex.skinIndices.fromArray( weightIndices );
//vertex.skinWeights.normalize();
}
if ( normalInfo ) {
vertex.normal.fromArray( getData( polygonVertexIndex, polygonIndex, vertexIndex, normalInfo ) );
}
if ( uvInfo ) {
vertex.uv.fromArray( getData( polygonVertexIndex, polygonIndex, vertexIndex, uvInfo ) );
}
//Add vertex to face buffer.
faceVertexBuffer.push( vertex );
// If index was negative to start with, we have finished this individual face
// and can generate the face data to the geometry.
if ( endOfFace ) {
var face = new Face();
var materials = getData( polygonVertexIndex, polygonIndex, vertexIndex, materialInfo );
face.genTrianglesFromVertices( faceVertexBuffer );
face.materialIndex = materials[ 0 ];
geometry.faces.push( face );
faceVertexBuffer = [];
polygonIndex ++;
endOfFace = false;
}
}
/**
* @type {{vertexBuffer: number[], normalBuffer: number[], uvBuffer: number[], skinIndexBuffer: number[], skinWeightBuffer: number[], materialIndexBuffer: number[]}}
*/
var bufferInfo = geometry.flattenToBuffers();
var geo = new THREE.BufferGeometry();
geo.name = geometryNode.name;
geo.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( bufferInfo.vertexBuffer ), 3 ) );
if ( bufferInfo.normalBuffer.length > 0 ) {
geo.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( bufferInfo.normalBuffer ), 3 ) );
}
if ( bufferInfo.uvBuffer.length > 0 ) {
geo.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( bufferInfo.uvBuffer ), 2 ) );
}
if ( deformer ) {
geo.addAttribute( 'skinIndex', new THREE.BufferAttribute( new Float32Array( bufferInfo.skinIndexBuffer ), 4 ) );
geo.addAttribute( 'skinWeight', new THREE.BufferAttribute( new Float32Array( bufferInfo.skinWeightBuffer ), 4 ) );
geo.FBX_Deformer = deformer;
}
// Convert the material indices of each vertex into rendering groups on the geometry.
var prevMaterialIndex = bufferInfo.materialIndexBuffer[ 0 ];
var startIndex = 0;
for ( var materialBufferIndex = 0; materialBufferIndex < bufferInfo.materialIndexBuffer.length; ++ materialBufferIndex ) {
if ( bufferInfo.materialIndexBuffer[ materialBufferIndex ] !== prevMaterialIndex ) {
geo.addGroup( startIndex, materialBufferIndex - startIndex, prevMaterialIndex );
startIndex = materialBufferIndex;
prevMaterialIndex = bufferInfo.materialIndexBuffer[ materialBufferIndex ];
}
}
return geo;
/**
* Parses normal information for geometry.
* @param {FBXGeometryNode} geometryNode
* @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
*/
function getNormals( geometryNode ) {
var NormalNode = geometryNode.subNodes.LayerElementNormal[ 0 ];
var mappingType = NormalNode.properties.MappingInformationType;
var referenceType = NormalNode.properties.ReferenceInformationType;
var buffer = parseFloatArray( NormalNode.subNodes.Normals.properties.a );
var indexBuffer = [];
if ( referenceType === 'IndexToDirect' ) {
indexBuffer = parseIntArray( NormalNode.subNodes.NormalIndex.properties.a );
}
return {
dataSize: 3,
buffer: buffer,
indices: indexBuffer,
mappingType: mappingType,
referenceType: referenceType
};
}
/**
* Parses UV information for geometry.
* @param {FBXGeometryNode} geometryNode
* @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
*/
function getUVs( geometryNode ) {
var UVNode = geometryNode.subNodes.LayerElementUV[ 0 ];
var mappingType = UVNode.properties.MappingInformationType;
var referenceType = UVNode.properties.ReferenceInformationType;
var buffer = parseFloatArray( UVNode.subNodes.UV.properties.a );
var indexBuffer = [];
if ( referenceType === 'IndexToDirect' ) {
indexBuffer = parseIntArray( UVNode.subNodes.UVIndex.properties.a );
}
return {
dataSize: 2,
buffer: buffer,
indices: indexBuffer,
mappingType: mappingType,
referenceType: referenceType
};
}
/**
* Parses material application information for geometry.
* @param {FBXGeometryNode}
* @returns {{dataSize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}}
*/
function getMaterials( geometryNode ) {
var MaterialNode = geometryNode.subNodes.LayerElementMaterial[ 0 ];
var mappingType = MaterialNode.properties.MappingInformationType;
var referenceType = MaterialNode.properties.ReferenceInformationType;
var materialIndexBuffer = parseIntArray( MaterialNode.subNodes.Materials.properties.a );
// Since materials are stored as indices, there's a bit of a mismatch between FBX and what
// we expect. So we create an intermediate buffer that points to the index in the buffer,
// for conforming with the other functions we've written for other data.
var materialIndices = [];
materialIndexBuffer.forEach( function ( materialIndex, index ) {
materialIndices.push( index );
} );
return {
dataSize: 1,
buffer: materialIndexBuffer,
indices: materialIndices,
mappingType: mappingType,
referenceType: referenceType
};
}
/**
* Function uses the infoObject and given indices to return value array of object.
* @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
* @param {number} polygonIndex - Index of polygon in geometry.
* @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
* @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
* @returns {number[]}
*/
function getData( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
var GetData = {
ByPolygonVertex: {
/**
* Function uses the infoObject and given indices to return value array of object.
* @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
* @param {number} polygonIndex - Index of polygon in geometry.
* @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
* @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
* @returns {number[]}
*/
Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
return infoObject.buffer.slice( ( polygonVertexIndex * infoObject.dataSize ), ( polygonVertexIndex * infoObject.dataSize ) + infoObject.dataSize );
},
/**
* Function uses the infoObject and given indices to return value array of object.
* @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
* @param {number} polygonIndex - Index of polygon in geometry.
* @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
* @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
* @returns {number[]}
*/
IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
var index = infoObject.indices[ polygonVertexIndex ];
return infoObject.buffer.slice( ( index * infoObject.dataSize ), ( index * infoObject.dataSize ) + infoObject.dataSize );
}
},
ByPolygon: {
/**
* Function uses the infoObject and given indices to return value array of object.
* @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
* @param {number} polygonIndex - Index of polygon in geometry.
* @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
* @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
* @returns {number[]}
*/
Direct: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
return infoObject.buffer.slice( polygonIndex * infoObject.dataSize, polygonIndex * infoObject.dataSize + infoObject.dataSize );
},
/**
* Function uses the infoObject and given indices to return value array of object.
* @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
* @param {number} polygonIndex - Index of polygon in geometry.
* @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
* @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
* @returns {number[]}
*/
IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
var index = infoObject.indices[ polygonIndex ];
return infoObject.buffer.slice( index * infoObject.dataSize, index * infoObject.dataSize + infoObject.dataSize );
}
},
AllSame: {
/**
* Function uses the infoObject and given indices to return value array of object.
* @param {number} polygonVertexIndex - Index of vertex in draw order (which index of the index buffer refers to this vertex).
* @param {number} polygonIndex - Index of polygon in geometry.
* @param {number} vertexIndex - Index of vertex inside vertex buffer (used because some data refers to old index buffer that we don't use anymore).
* @param {{datasize: number, buffer: number[], indices: number[], mappingType: string, referenceType: string}} infoObject - Object containing data and how to access data.
* @returns {number[]}
*/
IndexToDirect: function ( polygonVertexIndex, polygonIndex, vertexIndex, infoObject ) {
return infoObject.buffer.slice( infoObject.indices[ 0 ] * infoObject.dataSize, infoObject.indices[ 0 ] * infoObject.dataSize + infoObject.dataSize );
}
}
};
return GetData[ infoObject.mappingType ][ infoObject.referenceType ]( polygonVertexIndex, polygonIndex, vertexIndex, infoObject );
}
}
}
/**
* Specialty function for parsing NurbsCurve based Geometry Nodes.
* @param {FBXGeometryNode} geometryNode
* @param {{parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}} relationships
* @returns {THREE.BufferGeometry}
*/
function parseNurbsGeometry( geometryNode, relationships ) {
if ( THREE.NURBSCurve === undefined ) {
console.error( "THREE.FBXLoader relies on THREE.NURBSCurve for any nurbs present in the model. Nurbs will show up as empty geometry." );
return new THREE.BufferGeometry();
}
var order = parseInt( geometryNode.properties.Order );
if ( isNaN( order ) ) {
console.error( "FBXLoader: Invalid Order " + geometryNode.properties.Order + " given for geometry ID: " + geometryNode.id );
return new THREE.BufferGeometry();
}
var knots = parseFloatArray( geometryNode.subNodes.KnotVector.properties.a );
var controlPoints = [];
var pointsValues = parseFloatArray( geometryNode.subNodes.Points.properties.a );
for ( var i = 0; i < pointsValues.length; i += 4 ) {
controlPoints.push( new THREE.Vector4( pointsValues[ i ], pointsValues[ i + 1 ], pointsValues[ i + 2 ], pointsValues[ i + 3 ] ) );
}
if ( geometryNode.properties.Form === 'Closed' ) {
controlPoints.push( controlPoints[ 0 ] );
}
var curve = new THREE.NURBSCurve( order - 1, knots, controlPoints );
var vertices = curve.getPoints( controlPoints.length * 1.5 );
var vertexBuffer = [];
vertices.forEach( function ( position ) {
var array = position.toArray();
vertexBuffer = vertexBuffer.concat( array );
} );
var geometry = new THREE.BufferGeometry();
geometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( vertexBuffer ), 3 ) );
return geometry;
}
}
}
/**
* Finally generates Scene graph and Scene graph Objects.
* @param {{Objects: {subNodes: {Model: Object.<number, FBXModelNode>}}}} FBXTree
* @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
* @param {Map<number, {map: Map<number, {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}>, array: {FBX_ID: number, indices: number[], weights: number[], transform: number[], transformLink: number[], linkMode: string}[], skeleton: THREE.Skeleton|null}>} deformerMap
* @param {Map<number, THREE.BufferGeometry>} geometryMap
* @param {Map<number, THREE.Material>} materialMap
* @returns {THREE.Group}
*/
function parseScene( FBXTree, connections, deformerMap, geometryMap, materialMap ) {
var sceneGraph = new THREE.Group();
var ModelNode = FBXTree.Objects.subNodes.Model;
/**
* @type {Array.<THREE.Object3D>}
*/
var modelArray = [];
/**
* @type {Map.<number, THREE.Object3D>}
*/
var modelMap = new Map();
for ( var nodeID in ModelNode ) {
var id = parseInt( nodeID );
var node = ModelNode[ nodeID ];
var conns = connections.get( id );
var model = null;
for ( var i = 0; i < conns.parents.length; ++ i ) {
deformerMap.forEach( function ( deformer ) {
if ( deformer.map.has( conns.parents[ i ].ID ) ) {
model = new THREE.Bone();
var index = deformer.array.findIndex( function ( subDeformer ) {
return subDeformer.FBX_ID === conns.parents[ i ].ID;
} );
deformer.bones[ index ] = model;
}
} );
}
if ( ! model ) {
switch ( node.attrType ) {
case "Mesh":
/**
* @type {?THREE.BufferGeometry}
*/
var geometry = null;
/**
* @type {THREE.MultiMaterial|THREE.Material}
*/
var material = null;
/**
* @type {Array.<THREE.Material>}
*/
var materials = [];
conns.children.forEach( function ( child ) {
if ( geometryMap.has( child.ID ) ) {
geometry = geometryMap.get( child.ID );
}
if ( materialMap.has( child.ID ) ) {
materials.push( materialMap.get( child.ID ) );
}
} );
if ( materials.length > 1 ) {
material = new THREE.MultiMaterial( materials );
} else if ( materials.length > 0 ) {
material = materials[ 0 ];
} else {
material = new THREE.MeshBasicMaterial( { color: 0x3300ff } );
}
if ( geometry.FBX_Deformer ) {
materials.forEach( function ( material ) {
material.skinning = true;
} );
material.skinning = true;
model = new THREE.SkinnedMesh( geometry, material );
} else {
model = new THREE.Mesh( geometry, material );
}
break;
case "NurbsCurve":
var geometry = null;
conns.children.forEach( function ( child ) {
if ( geometryMap.has( child.ID ) ) {
geometry = geometryMap.get( child.ID );
}
} );
// FBX does not list materials for Nurbs lines, so we'll just put our own in here.
material = new THREE.LineBasicMaterial( { color: 0x3300ff, linewidth: 5 } );
model = new THREE.Line( geometry, material );
break;
default:
model = new THREE.Object3D();
break;
}
}
model.name = node.attrName.replace( /:/, '' ).replace( /_/, '' ).replace( /-/, '' );
model.FBX_ID = id;
modelArray.push( model );
modelMap.set( id, model );
}
modelArray.forEach( function ( model ) {
var node = ModelNode[ model.FBX_ID ];
if ( 'Lcl_Translation' in node.properties ) {
model.position.fromArray( parseFloatArray( node.properties.Lcl_Translation.value ) );
}
if ( 'Lcl_Rotation' in node.properties ) {
var rotation = parseFloatArray( node.properties.Lcl_Rotation.value ).map( function ( value ) {
return value * Math.PI / 180;
} );
rotation.push( 'ZYX' );
model.rotation.fromArray( rotation );
}
if ( 'Lcl_Scaling' in node.properties ) {
model.scale.fromArray( parseFloatArray( node.properties.Lcl_Scaling.value ) );
}
var conns = connections.get( model.FBX_ID );
for ( var parentIndex = 0; parentIndex < conns.parents.length; parentIndex ++ ) {
var pIndex = modelArray.findIndex( function ( mod ) {
return mod.FBX_ID === conns.parents[ parentIndex ].ID;
} );
if ( pIndex > - 1 ) {
modelArray[ pIndex ].add( model );
break;
}
}
if ( model.parent === null ) {
sceneGraph.add( model );
}
} );
// Now with the bones created, we can update the skeletons and bind them to the skinned meshes.
sceneGraph.updateMatrixWorld( true );
// Put skeleton into bind pose.
var BindPoseNode = FBXTree.Objects.subNodes.Pose;
for ( var nodeID in BindPoseNode ) {
if ( BindPoseNode[ nodeID ].attrType === 'BindPose' ) {
BindPoseNode = BindPoseNode[ nodeID ];
break;
}
}
if ( BindPoseNode ) {
var PoseNode = BindPoseNode.subNodes.PoseNode;
var worldMatrices = new Map();
PoseNode.forEach( function ( node ) {
var rawMatWrd = parseMatrixArray( node.subNodes.Matrix.properties.a );
worldMatrices.set( parseInt( node.id ), rawMatWrd );
} );
}
deformerMap.forEach( function ( deformer, FBX_ID ) {
deformer.array.forEach( function ( subDeformer, subDeformerIndex ) {
/**
* @type {THREE.Bone}
*/
var bone = deformer.bones[ subDeformerIndex ];
if ( ! worldMatrices.has( bone.FBX_ID ) ) {
return;
}
var mat = worldMatrices.get( bone.FBX_ID );
bone.matrixWorld.copy( mat );
} );
// Now that skeleton is in bind pose, bind to model.
deformer.skeleton = new THREE.Skeleton( deformer.bones );
var conns = connections.get( FBX_ID );
conns.parents.forEach( function ( parent ) {
if ( geometryMap.has( parent.ID ) ) {
var geoID = parent.ID;
var geoConns = connections.get( geoID );
for ( var i = 0; i < geoConns.parents.length; ++ i ) {
if ( modelMap.has( geoConns.parents[ i ].ID ) ) {
var model = modelMap.get( geoConns.parents[ i ].ID );
//ASSERT model typeof SkinnedMesh
model.bind( deformer.skeleton, model.matrixWorld );
break;
}
}
}
} );
} );
// Skeleton is now bound, we are now free to set up the
// scene graph.
modelArray.forEach( function ( model ) {
var node = ModelNode[ model.FBX_ID ];
if ( 'Lcl_Translation' in node.properties ) {
model.position.fromArray( parseFloatArray( node.properties.Lcl_Translation.value ) );
}
if ( 'Lcl_Rotation' in node.properties ) {
var rotation = parseFloatArray( node.properties.Lcl_Rotation.value ).map( function ( value ) {
return value * Math.PI / 180;
} );
rotation.push( 'ZYX' );
model.rotation.fromArray( rotation );
}
if ( 'Lcl_Scaling' in node.properties ) {
model.scale.fromArray( parseFloatArray( node.properties.Lcl_Scaling.value ) );
}
} );
// Silly hack with the animation parsing. We're gonna pretend the scene graph has a skeleton
// to attach animations to, since FBXs treat animations as animations for the entire scene,
// not just for individual objects.
sceneGraph.skeleton = {
bones: modelArray
};
var animations = parseAnimations( FBXTree, connections, sceneGraph );
addAnimations( sceneGraph, animations );
return sceneGraph;
}
/**
* Parses animation information from FBXTree and generates an AnimationInfoObject.
* @param {{Objects: {subNodes: {AnimationCurveNode: any, AnimationCurve: any, AnimationLayer: any, AnimationStack: any}}}} FBXTree
* @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
*/
function parseAnimations( FBXTree, connections, sceneGraph ) {
var rawNodes = FBXTree.Objects.subNodes.AnimationCurveNode;
var rawCurves = FBXTree.Objects.subNodes.AnimationCurve;
var rawLayers = FBXTree.Objects.subNodes.AnimationLayer;
var rawStacks = FBXTree.Objects.subNodes.AnimationStack;
/**
* @type {{
curves: Map<number, {
T: {
id: number;
attr: string;
internalID: number;
attrX: boolean;
attrY: boolean;
attrZ: boolean;
containerBoneID: number;
containerID: number;
curves: {
x: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
y: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
z: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
};
},
R: {
id: number;
attr: string;
internalID: number;
attrX: boolean;
attrY: boolean;
attrZ: boolean;
containerBoneID: number;
containerID: number;
curves: {
x: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
y: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
z: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
};
},
S: {
id: number;
attr: string;
internalID: number;
attrX: boolean;
attrY: boolean;
attrZ: boolean;
containerBoneID: number;
containerID: number;
curves: {
x: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
y: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
z: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
};
}
}>,
layers: Map<number, {
T: {
id: number;
attr: string;
internalID: number;
attrX: boolean;
attrY: boolean;
attrZ: boolean;
containerBoneID: number;
containerID: number;
curves: {
x: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
y: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
z: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
},
},
R: {
id: number;
attr: string;
internalID: number;
attrX: boolean;
attrY: boolean;
attrZ: boolean;
containerBoneID: number;
containerID: number;
curves: {
x: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
y: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
z: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
},
},
S: {
id: number;
attr: string;
internalID: number;
attrX: boolean;
attrY: boolean;
attrZ: boolean;
containerBoneID: number;
containerID: number;
curves: {
x: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
y: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
z: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
},
}
}[]>,
stacks: Map<number, {
name: string,
layers: {
T: {
id: number;
attr: string;
internalID: number;
attrX: boolean;
attrY: boolean;
attrZ: boolean;
containerBoneID: number;
containerID: number;
curves: {
x: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
y: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
z: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
};
};
R: {
id: number;
attr: string;
internalID: number;
attrX: boolean;
attrY: boolean;
attrZ: boolean;
containerBoneID: number;
containerID: number;
curves: {
x: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
y: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
z: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
};
};
S: {
id: number;
attr: string;
internalID: number;
attrX: boolean;
attrY: boolean;
attrZ: boolean;
containerBoneID: number;
containerID: number;
curves: {
x: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
y: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
z: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
};
};
}[][],
length: number,
frames: number }>,
length: number,
fps: number,
frames: number
}}
*/
var returnObject = {
curves: new Map(),
layers: new Map(),
stacks: new Map(),
length: 0,
fps: 30,
frames: 0
};
/**
* @type {Array.<{
id: number;
attr: string;
internalID: number;
attrX: boolean;
attrY: boolean;
attrZ: boolean;
containerBoneID: number;
containerID: number;
}>}
*/
var animationCurveNodes = [];
for ( var nodeID in rawNodes ) {
if ( nodeID.match( /\d+/ ) ) {
var animationNode = parseAnimationNode( FBXTree, rawNodes[ nodeID ], connections, sceneGraph );
animationCurveNodes.push( animationNode );
}
}
/**
* @type {Map.<number, {
id: number,
attr: string,
internalID: number,
attrX: boolean,
attrY: boolean,
attrZ: boolean,
containerBoneID: number,
containerID: number,
curves: {
x: {
version: any,
id: number,
internalID: number,
times: number[],
values: number[],
attrFlag: number[],
attrData: number[],
},
y: {
version: any,
id: number,
internalID: number,
times: number[],
values: number[],
attrFlag: number[],
attrData: number[],
},
z: {
version: any,
id: number,
internalID: number,
times: number[],
values: number[],
attrFlag: number[],
attrData: number[],
}
}
}>}
*/
var tmpMap = new Map();
for ( var animationCurveNodeIndex = 0; animationCurveNodeIndex < animationCurveNodes.length; ++ animationCurveNodeIndex ) {
if ( animationCurveNodes[ animationCurveNodeIndex ] === null ) {
continue;
}
tmpMap.set( animationCurveNodes[ animationCurveNodeIndex ].id, animationCurveNodes[ animationCurveNodeIndex ] );
}
/**
* @type {{
version: any,
id: number,
internalID: number,
times: number[],
values: number[],
attrFlag: number[],
attrData: number[],
}[]}
*/
var animationCurves = [];
for ( nodeID in rawCurves ) {
if ( nodeID.match( /\d+/ ) ) {
var animationCurve = parseAnimationCurve( rawCurves[ nodeID ] );
animationCurves.push( animationCurve );
var firstParentConn = connections.get( animationCurve.id ).parents[ 0 ];
var firstParentID = firstParentConn.ID;
var firstParentRelationship = firstParentConn.relationship;
var axis = '';
if ( firstParentRelationship.match( /X/ ) ) {
axis = 'x';
} else if ( firstParentRelationship.match( /Y/ ) ) {
axis = 'y';
} else if ( firstParentRelationship.match( /Z/ ) ) {
axis = 'z';
} else {
continue;
}
tmpMap.get( firstParentID ).curves[ axis ] = animationCurve;
}
}
tmpMap.forEach( function ( curveNode ) {
var id = curveNode.containerBoneID;
if ( ! returnObject.curves.has( id ) ) {
returnObject.curves.set( id, { T: null, R: null, S: null } );
}
returnObject.curves.get( id )[ curveNode.attr ] = curveNode;
} );
for ( var nodeID in rawLayers ) {
/**
* @type {{
T: {
id: number;
attr: string;
internalID: number;
attrX: boolean;
attrY: boolean;
attrZ: boolean;
containerBoneID: number;
containerID: number;
curves: {
x: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
y: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
z: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
},
},
R: {
id: number;
attr: string;
internalID: number;
attrX: boolean;
attrY: boolean;
attrZ: boolean;
containerBoneID: number;
containerID: number;
curves: {
x: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
y: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
z: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
},
},
S: {
id: number;
attr: string;
internalID: number;
attrX: boolean;
attrY: boolean;
attrZ: boolean;
containerBoneID: number;
containerID: number;
curves: {
x: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
y: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
z: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
},
}
}[]}
*/
var layer = [];
var children = connections.get( parseInt( nodeID ) ).children;
for ( var childIndex = 0; childIndex < children.length; childIndex ++ ) {
// Skip lockInfluenceWeights
if ( tmpMap.has( children[ childIndex ].ID ) ) {
var curveNode = tmpMap.get( children[ childIndex ].ID );
var boneID = curveNode.containerBoneID;
if ( layer[ boneID ] === undefined ) {
layer[ boneID ] = {
T: null,
R: null,
S: null
};
}
layer[ boneID ][ curveNode.attr ] = curveNode;
}
}
returnObject.layers.set( parseInt( nodeID ), layer );
}
for ( var nodeID in rawStacks ) {
var layers = [];
var children = connections.get( parseInt( nodeID ) ).children;
var maxTimeStamp = 0;
var minTimeStamp = Number.MAX_VALUE;
for ( var childIndex = 0; childIndex < children.length; ++ childIndex ) {
if ( returnObject.layers.has( children[ childIndex ].ID ) ) {
var currentLayer = returnObject.layers.get( children[ childIndex ].ID );
layers.push( currentLayer );
currentLayer.forEach( function ( layer ) {
if ( layer ) {
getCurveNodeMaxMinTimeStamps( layer );
}
/**
* Sets the maxTimeStamp and minTimeStamp variables if it has timeStamps that are either larger or smaller
* than the max or min respectively.
* @param {{
T: {
id: number,
attr: string,
internalID: number,
attrX: boolean,
attrY: boolean,
attrZ: boolean,
containerBoneID: number,
containerID: number,
curves: {
x: {
version: any,
id: number,
internalID: number,
times: number[],
values: number[],
attrFlag: number[],
attrData: number[],
},
y: {
version: any,
id: number,
internalID: number,
times: number[],
values: number[],
attrFlag: number[],
attrData: number[],
},
z: {
version: any,
id: number,
internalID: number,
times: number[],
values: number[],
attrFlag: number[],
attrData: number[],
},
},
},
R: {
id: number,
attr: string,
internalID: number,
attrX: boolean,
attrY: boolean,
attrZ: boolean,
containerBoneID: number,
containerID: number,
curves: {
x: {
version: any,
id: number,
internalID: number,
times: number[],
values: number[],
attrFlag: number[],
attrData: number[],
},
y: {
version: any,
id: number,
internalID: number,
times: number[],
values: number[],
attrFlag: number[],
attrData: number[],
},
z: {
version: any,
id: number,
internalID: number,
times: number[],
values: number[],
attrFlag: number[],
attrData: number[],
},
},
},
S: {
id: number,
attr: string,
internalID: number,
attrX: boolean,
attrY: boolean,
attrZ: boolean,
containerBoneID: number,
containerID: number,
curves: {
x: {
version: any,
id: number,
internalID: number,
times: number[],
values: number[],
attrFlag: number[],
attrData: number[],
},
y: {
version: any,
id: number,
internalID: number,
times: number[],
values: number[],
attrFlag: number[],
attrData: number[],
},
z: {
version: any,
id: number,
internalID: number,
times: number[],
values: number[],
attrFlag: number[],
attrData: number[],
},
},
},
}} layer
*/
function getCurveNodeMaxMinTimeStamps( layer ) {
/**
* Sets the maxTimeStamp and minTimeStamp if one of the curve's time stamps
* exceeds the maximum or minimum.
* @param {{
x: {
version: any,
id: number,
internalID: number,
times: number[],
values: number[],
attrFlag: number[],
attrData: number[],
},
y: {
version: any,
id: number,
internalID: number,
times: number[],
values: number[],
attrFlag: number[],
attrData: number[],
},
z: {
version: any,
id: number,
internalID: number,
times: number[],
values: number[],
attrFlag: number[],
attrData: number[],
}
}} curve
*/
function getCurveMaxMinTimeStamp( curve ) {
/**
* Sets the maxTimeStamp and minTimeStamp if one of its timestamps exceeds the maximum or minimum.
* @param {{times: number[]}} axis
*/
function getCurveAxisMaxMinTimeStamps( axis ) {
maxTimeStamp = axis.times[ axis.times.length - 1 ] > maxTimeStamp ? axis.times[ axis.times.length - 1 ] : maxTimeStamp;
minTimeStamp = axis.times[ 0 ] < minTimeStamp ? axis.times[ 0 ] : minTimeStamp;
}
if ( curve.x ) {
getCurveAxisMaxMinTimeStamps( curve.x );
}
if ( curve.y ) {
getCurveAxisMaxMinTimeStamps( curve.y );
}
if ( curve.z ) {
getCurveAxisMaxMinTimeStamps( curve.z );
}
}
if ( layer.R ) {
getCurveMaxMinTimeStamp( layer.R.curves );
}
if ( layer.S ) {
getCurveMaxMinTimeStamp( layer.S.curves );
}
if ( layer.T ) {
getCurveMaxMinTimeStamp( layer.T.curves );
}
}
} );
}
}
// Do we have an animation clip with actual length?
if ( maxTimeStamp > minTimeStamp ) {
returnObject.stacks.set( parseInt( nodeID ), {
name: rawStacks[ nodeID ].attrName,
layers: layers,
length: maxTimeStamp - minTimeStamp,
frames: ( maxTimeStamp - minTimeStamp ) * 30
} );
}
}
return returnObject;
/**
* @param {Object} FBXTree
* @param {{id: number, attrName: string, properties: Object<string, any>}} animationCurveNode
* @param {Map<number, {parents: {ID: number, relationship: string}[], children: {ID: number, relationship: string}[]}>} connections
* @param {{skeleton: {bones: {FBX_ID: number}[]}}} sceneGraph
*/
function parseAnimationNode( FBXTree, animationCurveNode, connections, sceneGraph ) {
var returnObject = {
/**
* @type {number}
*/
id: animationCurveNode.id,
/**
* @type {string}
*/
attr: animationCurveNode.attrName,
/**
* @type {number}
*/
internalID: animationCurveNode.id,
/**
* @type {boolean}
*/
attrX: false,
/**
* @type {boolean}
*/
attrY: false,
/**
* @type {boolean}
*/
attrZ: false,
/**
* @type {number}
*/
containerBoneID: - 1,
/**
* @type {number}
*/
containerID: - 1,
curves: {
x: null,
y: null,
z: null
}
};
if ( returnObject.attr.match( /S|R|T/ ) ) {
for ( var attributeKey in animationCurveNode.properties ) {
if ( attributeKey.match( /X/ ) ) {
returnObject.attrX = true;
}
if ( attributeKey.match( /Y/ ) ) {
returnObject.attrY = true;
}
if ( attributeKey.match( /Z/ ) ) {
returnObject.attrZ = true;
}
}
} else {
return null;
}
var conns = connections.get( returnObject.id );
var containerIndices = conns.parents;
for ( var containerIndicesIndex = containerIndices.length - 1; containerIndicesIndex >= 0; -- containerIndicesIndex ) {
var boneID = sceneGraph.skeleton.bones.findIndex( function ( bone ) {
return bone.FBX_ID === containerIndices[ containerIndicesIndex ].ID;
} );
if ( boneID > - 1 ) {
returnObject.containerBoneID = boneID;
returnObject.containerID = containerIndices[ containerIndicesIndex ].ID;
break;
}
}
return returnObject;
}
/**
* @param {{id: number, subNodes: {KeyTime: {properties: {a: string}}, KeyValueFloat: {properties: {a: string}}, KeyAttrFlags: {properties: {a: string}}, KeyAttrDataFloat: {properties: {a: string}}}}} animationCurve
*/
function parseAnimationCurve( animationCurve ) {
return {
version: null,
id: animationCurve.id,
internalID: animationCurve.id,
times: parseFloatArray( animationCurve.subNodes.KeyTime.properties.a ).map( function ( time ) {
return ConvertFBXTimeToSeconds( time );
} ),
values: parseFloatArray( animationCurve.subNodes.KeyValueFloat.properties.a ),
attrFlag: parseIntArray( animationCurve.subNodes.KeyAttrFlags.properties.a ),
attrData: parseFloatArray( animationCurve.subNodes.KeyAttrDataFloat.properties.a )
};
}
}
/**
* @param {{
curves: Map<number, {
T: {
id: number;
attr: string;
internalID: number;
attrX: boolean;
attrY: boolean;
attrZ: boolean;
containerBoneID: number;
containerID: number;
curves: {
x: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
y: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
z: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
};
};
R: {
id: number;
attr: string;
internalID: number;
attrX: boolean;
attrY: boolean;
attrZ: boolean;
containerBoneID: number;
containerID: number;
curves: {
x: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
y: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
z: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
};
};
S: {
id: number;
attr: string;
internalID: number;
attrX: boolean;
attrY: boolean;
attrZ: boolean;
containerBoneID: number;
containerID: number;
curves: {
x: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
y: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
z: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
};
};
}>;
layers: Map<number, {
T: {
id: number;
attr: string;
internalID: number;
attrX: boolean;
attrY: boolean;
attrZ: boolean;
containerBoneID: number;
containerID: number;
curves: {
x: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
y: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
z: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
};
};
R: {
id: number;
attr: string;
internalID: number;
attrX: boolean;
attrY: boolean;
attrZ: boolean;
containerBoneID: number;
containerID: number;
curves: {
x: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
y: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
z: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
};
};
S: {
id: number;
attr: string;
internalID: number;
attrX: boolean;
attrY: boolean;
attrZ: boolean;
containerBoneID: number;
containerID: number;
curves: {
x: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
y: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
z: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
};
};
}[]>;
stacks: Map<number, {
name: string;
layers: {
T: {
id: number;
attr: string;
internalID: number;
attrX: boolean;
attrY: boolean;
attrZ: boolean;
containerBoneID: number;
containerID: number;
curves: {
x: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
y: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
z: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
};
};
R: {
id: number;
attr: string;
internalID: number;
attrX: boolean;
attrY: boolean;
attrZ: boolean;
containerBoneID: number;
containerID: number;
curves: {
x: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
y: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
z: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
};
};
S: {
id: number;
attr: string;
internalID: number;
attrX: boolean;
attrY: boolean;
attrZ: boolean;
containerBoneID: number;
containerID: number;
curves: {
x: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
y: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
z: {
version: any;
id: number;
internalID: number;
times: number[];
values: number[];
attrFlag: number[];
attrData: number[];
};
};
};
}[][];
length: number;
frames: number;
}>;
length: number;
fps: number;
frames: number;
}} animations,
* @param {{skeleton: { bones: THREE.Bone[]}}} group
*/
function addAnimations( group, animations ) {
if ( group.animations === undefined ) {
group.animations = [];
}
animations.stacks.forEach( function ( stack ) {
var animationData = {
name: stack.name,
fps: 30,
length: stack.length,
hierarchy: []
};
var bones = group.skeleton.bones;
bones.forEach( function ( bone ) {
var name = bone.name.replace( /.*:/, '' );
var parentIndex = bones.findIndex( function ( parentBone ) {
return bone.parent === parentBone;
} );
animationData.hierarchy.push( { parent: parentIndex, name: name, keys: [] } );
} );
for ( var frame = 0; frame < stack.frames; frame ++ ) {
bones.forEach( function ( bone, boneIndex ) {
var animationNode = stack.layers[ 0 ][ boneIndex ];
animationData.hierarchy.forEach( function ( node ) {
if ( node.name === bone.name ) {
node.keys.push( generateKey( animationNode, bone, frame ) );
}
} );
} );
}
group.animations.push( THREE.AnimationClip.parseAnimation( animationData, bones ) );
/**
* @param {THREE.Bone} bone
*/
function generateKey( animationNode, bone, frame ) {
var key = {
time: frame / animations.fps,
pos: bone.position.toArray(),
rot: bone.quaternion.toArray(),
scl: bone.scale.toArray()
};
if ( animationNode === undefined ) {
return key;
}
try {
if ( hasCurve( animationNode, 'T' ) && hasKeyOnFrame( animationNode.T, frame ) ) {
key.pos = [ animationNode.T.curves.x.values[ frame ], animationNode.T.curves.y.values[ frame ], animationNode.T.curves.z.values[ frame ] ];
}
if ( hasCurve( animationNode, 'R' ) && hasKeyOnFrame( animationNode.R, frame ) ) {
var rotationX = degreeToRadian( animationNode.R.curves.x.values[ frame ] );
var rotationY = degreeToRadian( animationNode.R.curves.y.values[ frame ] );
var rotationZ = degreeToRadian( animationNode.R.curves.z.values[ frame ] );
var euler = new THREE.Euler( rotationX, rotationY, rotationZ, 'ZYX' );
key.rot = new THREE.Quaternion().setFromEuler( euler ).toArray();
}
if ( hasCurve( animationNode, 'S' ) && hasKeyOnFrame( animationNode.S, frame ) ) {
key.scl = [ animationNode.S.curves.x.values[ frame ], animationNode.S.curves.y.values[ frame ], animationNode.S.curves.z.values[ frame ] ];
}
} catch ( error ) {
// Curve is not fully plotted.
console.log( bone );
console.log( error );
}
return key;
function hasCurve( animationNode, attribute ) {
if ( animationNode === undefined ) {
return false;
}
var attributeNode = animationNode[ attribute ];
if ( ! attributeNode ) {
return false;
}
return [ 'x', 'y', 'z' ].every( function ( key ) {
return attributeNode.curves[ key ] !== undefined;
} );
}
function hasKeyOnFrame( attributeNode, frame ) {
return [ 'x', 'y', 'z' ].every( function ( key ) {
return isKeyExistOnFrame( attributeNode.curves[ key ], frame );
function isKeyExistOnFrame( curve, frame ) {
return curve.values[ frame ] !== undefined;
}
} );
}
}
} );
}
// UTILS
/**
* Parses Vector3 property from FBXTree. Property is given as .value.x, .value.y, etc.
* @param {FBXVector3} property - Property to parse as Vector3.
* @returns {THREE.Vector3}
*/
function parseVector3( property ) {
return new THREE.Vector3( parseFloat( property.value.x ), parseFloat( property.value.y ), parseFloat( property.value.z ) );
}
/**
* Parses Color property from FBXTree. Property is given as .value.x, .value.y, etc.
* @param {FBXVector3} property - Property to parse as Color.
* @returns {THREE.Color}
*/
function parseColor( property ) {
return new THREE.Color().fromArray( parseVector3( property ).toArray() );
}
}
} );
/**
* An instance of a Vertex with data for drawing vertices to the screen.
* @constructor
*/
function Vertex() {
/**
* Position of the vertex.
* @type {THREE.Vector3}
*/
this.position = new THREE.Vector3( );
/**
* Normal of the vertex
* @type {THREE.Vector3}
*/
this.normal = new THREE.Vector3( );
/**
* UV coordinates of the vertex.
* @type {THREE.Vector2}
*/
this.uv = new THREE.Vector2( );
/**
* Indices of the bones vertex is influenced by.
* @type {THREE.Vector4}
*/
this.skinIndices = new THREE.Vector4( 0, 0, 0, 0 );
/**
* Weights that each bone influences the vertex.
* @type {THREE.Vector4}
*/
this.skinWeights = new THREE.Vector4( 0, 0, 0, 0 );
}
Object.assign( Vertex.prototype, {
copy: function ( target ) {
var returnVar = target || new Vertex();
returnVar.position.copy( this.position );
returnVar.normal.copy( this.normal );
returnVar.uv.copy( this.uv );
returnVar.skinIndices.copy( this.skinIndices );
returnVar.skinWeights.copy( this.skinWeights );
return returnVar;
},
flattenToBuffers: function () {
var vertexBuffer = this.position.toArray();
var normalBuffer = this.normal.toArray();
var uvBuffer = this.uv.toArray();
var skinIndexBuffer = this.skinIndices.toArray();
var skinWeightBuffer = this.skinWeights.toArray();
return {
vertexBuffer: vertexBuffer,
normalBuffer: normalBuffer,
uvBuffer: uvBuffer,
skinIndexBuffer: skinIndexBuffer,
skinWeightBuffer: skinWeightBuffer,
};
}
} );
/**
* @constructor
*/
function Triangle() {
/**
* @type {{position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}
*/
this.vertices = [ ];
}
Object.assign( Triangle.prototype, {
copy: function ( target ) {
var returnVar = target || new Triangle();
for ( var i = 0; i < this.vertices.length; ++ i ) {
this.vertices[ i ].copy( returnVar.vertices[ i ] );
}
return returnVar;
},
flattenToBuffers: function () {
var vertexBuffer = [];
var normalBuffer = [];
var uvBuffer = [];
var skinIndexBuffer = [];
var skinWeightBuffer = [];
this.vertices.forEach( function ( vertex ) {
var flatVertex = vertex.flattenToBuffers();
vertexBuffer = vertexBuffer.concat( flatVertex.vertexBuffer );
normalBuffer = normalBuffer.concat( flatVertex.normalBuffer );
uvBuffer = uvBuffer.concat( flatVertex.uvBuffer );
skinIndexBuffer = skinIndexBuffer.concat( flatVertex.skinIndexBuffer );
skinWeightBuffer = skinWeightBuffer.concat( flatVertex.skinWeightBuffer );
} );
return {
vertexBuffer: vertexBuffer,
normalBuffer: normalBuffer,
uvBuffer: uvBuffer,
skinIndexBuffer: skinIndexBuffer,
skinWeightBuffer: skinWeightBuffer,
};
}
} );
/**
* @constructor
*/
function Face() {
/**
* @type {{vertices: {position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}[]}
*/
this.triangles = [ ];
this.materialIndex = 0;
}
Object.assign( Face.prototype, {
copy: function ( target ) {
var returnVar = target || new Face();
for ( var i = 0; i < this.triangles.length; ++ i ) {
this.triangles[ i ].copy( returnVar.triangles[ i ] );
}
returnVar.materialIndex = this.materialIndex;
return returnVar;
},
genTrianglesFromVertices: function ( vertexArray ) {
for ( var i = 2; i < vertexArray.length; ++ i ) {
var triangle = new Triangle();
triangle.vertices[ 0 ] = vertexArray[ 0 ];
triangle.vertices[ 1 ] = vertexArray[ i - 1 ];
triangle.vertices[ 2 ] = vertexArray[ i ];
this.triangles.push( triangle );
}
},
flattenToBuffers: function () {
var vertexBuffer = [];
var normalBuffer = [];
var uvBuffer = [];
var skinIndexBuffer = [];
var skinWeightBuffer = [];
var materialIndexBuffer = [];
var materialIndex = this.materialIndex;
this.triangles.forEach( function ( triangle ) {
var flatTriangle = triangle.flattenToBuffers();
vertexBuffer = vertexBuffer.concat( flatTriangle.vertexBuffer );
normalBuffer = normalBuffer.concat( flatTriangle.normalBuffer );
uvBuffer = uvBuffer.concat( flatTriangle.uvBuffer );
skinIndexBuffer = skinIndexBuffer.concat( flatTriangle.skinIndexBuffer );
skinWeightBuffer = skinWeightBuffer.concat( flatTriangle.skinWeightBuffer );
materialIndexBuffer = materialIndexBuffer.concat( [ materialIndex, materialIndex, materialIndex ] );
} );
return {
vertexBuffer: vertexBuffer,
normalBuffer: normalBuffer,
uvBuffer: uvBuffer,
skinIndexBuffer: skinIndexBuffer,
skinWeightBuffer: skinWeightBuffer,
materialIndexBuffer: materialIndexBuffer
};
}
} );
/**
* @constructor
*/
function Geometry() {
/**
* @type {{triangles: {vertices: {position: THREE.Vector3, normal: THREE.Vector3, uv: THREE.Vector2, skinIndices: THREE.Vector4, skinWeights: THREE.Vector4}[]}[], materialIndex: number}[]}
*/
this.faces = [ ];
/**
* @type {{}|THREE.Skeleton}
*/
this.skeleton = null;
}
Object.assign( Geometry.prototype, {
/**
* @returns {{vertexBuffer: number[], normalBuffer: number[], uvBuffer: number[], skinIndexBuffer: number[], skinWeightBuffer: number[], materialIndexBuffer: number[]}}
*/
flattenToBuffers: function () {
var vertexBuffer = [];
var normalBuffer = [];
var uvBuffer = [];
var skinIndexBuffer = [];
var skinWeightBuffer = [];
var materialIndexBuffer = [];
this.faces.forEach( function ( face ) {
var flatFace = face.flattenToBuffers();
vertexBuffer = vertexBuffer.concat( flatFace.vertexBuffer );
normalBuffer = normalBuffer.concat( flatFace.normalBuffer );
uvBuffer = uvBuffer.concat( flatFace.uvBuffer );
skinIndexBuffer = skinIndexBuffer.concat( flatFace.skinIndexBuffer );
skinWeightBuffer = skinWeightBuffer.concat( flatFace.skinWeightBuffer );
materialIndexBuffer = materialIndexBuffer.concat( flatFace.materialIndexBuffer );
} );
return {
vertexBuffer: vertexBuffer,
normalBuffer: normalBuffer,
uvBuffer: uvBuffer,
skinIndexBuffer: skinIndexBuffer,
skinWeightBuffer: skinWeightBuffer,
materialIndexBuffer: materialIndexBuffer
};
}
} );
function TextParser() {}
Object.assign( TextParser.prototype, {
getPrevNode: function () {
return this.nodeStack[ this.currentIndent - 2 ];
},
getCurrentNode: function () {
return this.nodeStack[ this.currentIndent - 1 ];
},
getCurrentProp: function () {
return this.currentProp;
},
pushStack: function ( node ) {
this.nodeStack.push( node );
this.currentIndent += 1;
},
popStack: function () {
this.nodeStack.pop();
this.currentIndent -= 1;
},
setCurrentProp: function ( val, name ) {
this.currentProp = val;
this.currentPropName = name;
},
// ----------parse ---------------------------------------------------
parse: function ( text ) {
this.currentIndent = 0;
this.allNodes = new FBXTree();
this.nodeStack = [];
this.currentProp = [];
this.currentPropName = '';
var split = text.split( "\n" );
for ( var line in split ) {
var l = split[ line ];
// short cut
if ( l.match( /^[\s\t]*;/ ) ) {
continue;
} // skip comment line
if ( l.match( /^[\s\t]*$/ ) ) {
continue;
} // skip empty line
// beginning of node
var beginningOfNodeExp = new RegExp( "^\\t{" + this.currentIndent + "}(\\w+):(.*){", '' );
var match = l.match( beginningOfNodeExp );
if ( match ) {
var nodeName = match[ 1 ].trim().replace( /^"/, '' ).replace( /"$/, "" );
var nodeAttrs = match[ 2 ].split( ',' ).map( function ( element ) {
return element.trim().replace( /^"/, '' ).replace( /"$/, '' );
} );
this.parseNodeBegin( l, nodeName, nodeAttrs || null );
continue;
}
// node's property
var propExp = new RegExp( "^\\t{" + ( this.currentIndent ) + "}(\\w+):[\\s\\t\\r\\n](.*)" );
var match = l.match( propExp );
if ( match ) {
var propName = match[ 1 ].replace( /^"/, '' ).replace( /"$/, "" ).trim();
var propValue = match[ 2 ].replace( /^"/, '' ).replace( /"$/, "" ).trim();
this.parseNodeProperty( l, propName, propValue );
continue;
}
// end of node
var endOfNodeExp = new RegExp( "^\\t{" + ( this.currentIndent - 1 ) + "}}" );
if ( l.match( endOfNodeExp ) ) {
this.nodeEnd();
continue;
}
// for special case,
//
// Vertices: *8670 {
// a: 0.0356229953467846,13.9599733352661,-0.399196773.....(snip)
// -0.0612030513584614,13.960485458374,-0.409748703241348,-0.10.....
// 0.12490539252758,13.7450733184814,-0.454119384288788,0.09272.....
// 0.0836158767342567,13.5432004928589,-0.435397416353226,0.028.....
//
// these case the lines must contiue with previous line
if ( l.match( /^[^\s\t}]/ ) ) {
this.parseNodePropertyContinued( l );
}
}
return this.allNodes;
},
parseNodeBegin: function ( line, nodeName, nodeAttrs ) {
// var nodeName = match[1];
var node = { 'name': nodeName, properties: {}, 'subNodes': {} };
var attrs = this.parseNodeAttr( nodeAttrs );
var currentNode = this.getCurrentNode();
// a top node
if ( this.currentIndent === 0 ) {
this.allNodes.add( nodeName, node );
} else {
// a subnode
// already exists subnode, then append it
if ( nodeName in currentNode.subNodes ) {
var tmp = currentNode.subNodes[ nodeName ];
// console.log( "duped entry found\nkey: " + nodeName + "\nvalue: " + propValue );
if ( this.isFlattenNode( currentNode.subNodes[ nodeName ] ) ) {
if ( attrs.id === '' ) {
currentNode.subNodes[ nodeName ] = [];
currentNode.subNodes[ nodeName ].push( tmp );
} else {
currentNode.subNodes[ nodeName ] = {};
currentNode.subNodes[ nodeName ][ tmp.id ] = tmp;
}
}
if ( attrs.id === '' ) {
currentNode.subNodes[ nodeName ].push( node );
} else {
currentNode.subNodes[ nodeName ][ attrs.id ] = node;
}
} else if ( typeof attrs.id === 'number' || attrs.id.match( /^\d+$/ ) ) {
currentNode.subNodes[ nodeName ] = {};
currentNode.subNodes[ nodeName ][ attrs.id ] = node;
} else {
currentNode.subNodes[ nodeName ] = node;
}
}
// for this ↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
// NodeAttribute: 1001463072, "NodeAttribute::", "LimbNode" {
if ( nodeAttrs ) {
node.id = attrs.id;
node.attrName = attrs.name;
node.attrType = attrs.type;
}
this.pushStack( node );
},
parseNodeAttr: function ( attrs ) {
var id = attrs[ 0 ];
if ( attrs[ 0 ] !== "" ) {
id = parseInt( attrs[ 0 ] );
if ( isNaN( id ) ) {
// PolygonVertexIndex: *16380 {
id = attrs[ 0 ];
}
}
var name;
var type;
if ( attrs.length > 1 ) {
name = attrs[ 1 ].replace( /^(\w+)::/, '' );
type = attrs[ 2 ];
}
return { id: id, name: name || '', type: type || '' };
},
parseNodeProperty: function ( line, propName, propValue ) {
var currentNode = this.getCurrentNode();
var parentName = currentNode.name;
// special case parent node's is like "Properties70"
// these chilren nodes must treat with careful
if ( parentName !== undefined ) {
var propMatch = parentName.match( /Properties(\d)+/ );
if ( propMatch ) {
this.parseNodeSpecialProperty( line, propName, propValue );
return;
}
}
// special case Connections
if ( propName == 'C' ) {
var connProps = propValue.split( ',' ).slice( 1 );
var from = parseInt( connProps[ 0 ] );
var to = parseInt( connProps[ 1 ] );
var rest = propValue.split( ',' ).slice( 3 );
propName = 'connections';
propValue = [ from, to ];
propValue = propValue.concat( rest );
if ( currentNode.properties[ propName ] === undefined ) {
currentNode.properties[ propName ] = [];
}
}
// special case Connections
if ( propName == 'Node' ) {
var id = parseInt( propValue );
currentNode.properties.id = id;
currentNode.id = id;
}
// already exists in properties, then append this
if ( propName in currentNode.properties ) {
// console.log( "duped entry found\nkey: " + propName + "\nvalue: " + propValue );
if ( Array.isArray( currentNode.properties[ propName ] ) ) {
currentNode.properties[ propName ].push( propValue );
} else {
currentNode.properties[ propName ] += propValue;
}
} else {
// console.log( propName + ": " + propValue );
if ( Array.isArray( currentNode.properties[ propName ] ) ) {
currentNode.properties[ propName ].push( propValue );
} else {
currentNode.properties[ propName ] = propValue;
}
}
this.setCurrentProp( currentNode.properties, propName );
},
// TODO:
parseNodePropertyContinued: function ( line ) {
this.currentProp[ this.currentPropName ] += line;
},
parseNodeSpecialProperty: function ( line, propName, propValue ) {
// split this
// P: "Lcl Scaling", "Lcl Scaling", "", "A",1,1,1
// into array like below
// ["Lcl Scaling", "Lcl Scaling", "", "A", "1,1,1" ]
var props = propValue.split( '",' ).map( function ( element ) {
return element.trim().replace( /^\"/, '' ).replace( /\s/, '_' );
} );
var innerPropName = props[ 0 ];
var innerPropType1 = props[ 1 ];
var innerPropType2 = props[ 2 ];
var innerPropFlag = props[ 3 ];
var innerPropValue = props[ 4 ];
/*
if ( innerPropValue === undefined ) {
innerPropValue = props[3];
}
*/
// cast value in its type
switch ( innerPropType1 ) {
case "int":
innerPropValue = parseInt( innerPropValue );
break;
case "double":
innerPropValue = parseFloat( innerPropValue );
break;
case "ColorRGB":
case "Vector3D":
var tmp = innerPropValue.split( ',' );
innerPropValue = new THREE.Vector3( tmp[ 0 ], tmp[ 1 ], tmp[ 2 ] );
break;
}
// CAUTION: these props must append to parent's parent
this.getPrevNode().properties[ innerPropName ] = {
'type': innerPropType1,
'type2': innerPropType2,
'flag': innerPropFlag,
'value': innerPropValue
};
this.setCurrentProp( this.getPrevNode().properties, innerPropName );
},
nodeEnd: function () {
this.popStack();
},
/* ---------------------------------------------------------------- */
/* util */
isFlattenNode: function ( node ) {
return ( 'subNodes' in node && 'properties' in node ) ? true : false;
}
} );
function FBXTree() {}
Object.assign( FBXTree.prototype, {
add: function ( key, val ) {
this[ key ] = val;
},
searchConnectionParent: function ( id ) {
if ( this.__cache_search_connection_parent === undefined ) {
this.__cache_search_connection_parent = [];
}
if ( this.__cache_search_connection_parent[ id ] !== undefined ) {
return this.__cache_search_connection_parent[ id ];
} else {
this.__cache_search_connection_parent[ id ] = [];
}
var conns = this.Connections.properties.connections;
var results = [];
for ( var i = 0; i < conns.length; ++ i ) {
if ( conns[ i ][ 0 ] == id ) {
// 0 means scene root
var res = conns[ i ][ 1 ] === 0 ? - 1 : conns[ i ][ 1 ];
results.push( res );
}
}
if ( results.length > 0 ) {
this.__cache_search_connection_parent[ id ] = this.__cache_search_connection_parent[ id ].concat( results );
return results;
} else {
this.__cache_search_connection_parent[ id ] = [ - 1 ];
return [ - 1 ];
}
},
searchConnectionChildren: function ( id ) {
if ( this.__cache_search_connection_children === undefined ) {
this.__cache_search_connection_children = [];
}
if ( this.__cache_search_connection_children[ id ] !== undefined ) {
return this.__cache_search_connection_children[ id ];
} else {
this.__cache_search_connection_children[ id ] = [];
}
var conns = this.Connections.properties.connections;
var res = [];
for ( var i = 0; i < conns.length; ++ i ) {
if ( conns[ i ][ 1 ] == id ) {
// 0 means scene root
res.push( conns[ i ][ 0 ] === 0 ? - 1 : conns[ i ][ 0 ] );
// there may more than one kid, then search to the end
}
}
if ( res.length > 0 ) {
this.__cache_search_connection_children[ id ] = this.__cache_search_connection_children[ id ].concat( res );
return res;
} else {
this.__cache_search_connection_children[ id ] = [ ];
return [ ];
}
},
searchConnectionType: function ( id, to ) {
var key = id + ',' + to; // TODO: to hash
if ( this.__cache_search_connection_type === undefined ) {
this.__cache_search_connection_type = {};
}
if ( this.__cache_search_connection_type[ key ] !== undefined ) {
return this.__cache_search_connection_type[ key ];
} else {
this.__cache_search_connection_type[ key ] = '';
}
var conns = this.Connections.properties.connections;
for ( var i = 0; i < conns.length; ++ i ) {
if ( conns[ i ][ 0 ] == id && conns[ i ][ 1 ] == to ) {
// 0 means scene root
this.__cache_search_connection_type[ key ] = conns[ i ][ 2 ];
return conns[ i ][ 2 ];
}
}
this.__cache_search_connection_type[ id ] = null;
return null;
}
} );
/**
* @returns {boolean}
*/
function isFbxFormatASCII( text ) {
var CORRECT = [ 'K', 'a', 'y', 'd', 'a', 'r', 'a', '\\', 'F', 'B', 'X', '\\', 'B', 'i', 'n', 'a', 'r', 'y', '\\', '\\' ];
var cursor = 0;
var read = function ( offset ) {
var result = text[ offset - 1 ];
text = text.slice( cursor + offset );
cursor ++;
return result;
};
for ( var i = 0; i < CORRECT.length; ++ i ) {
var num = read( 1 );
if ( num == CORRECT[ i ] ) {
return false;
}
}
return true;
}
/**
* @returns {number}
*/
function getFbxVersion( text ) {
var versionRegExp = /FBXVersion: (\d+)/;
var match = text.match( versionRegExp );
if ( match ) {
var version = parseInt( match[ 1 ] );
return version;
}
throw new Error( 'FBXLoader: Cannot find the version number for the file given.' );
}
/**
* Converts FBX ticks into real time seconds.
* @param {number} time - FBX tick timestamp to convert.
* @returns {number} - FBX tick in real world time.
*/
function ConvertFBXTimeToSeconds( time ) {
// Constant is FBX ticks per second.
return time / 46186158000;
}
/**
* Parses comma separated list of float numbers and returns them in an array.
* @example
* // Returns [ 5.6, 9.4, 2.5, 1.4 ]
* parseFloatArray( "5.6,9.4,2.5,1.4" )
* @returns {number[]}
*/
function parseFloatArray( floatString ) {
return floatString.split( ',' ).map( function ( stringValue ) {
return parseFloat( stringValue );
} );
}
/**
* Parses comma separated list of int numbers and returns them in an array.
* @example
* // Returns [ 5, 8, 2, 3 ]
* parseFloatArray( "5,8,2,3" )
* @returns {number[]}
*/
function parseIntArray( intString ) {
return intString.split( ',' ).map( function ( stringValue ) {
return parseInt( stringValue );
} );
}
function parseMatrixArray( floatString ) {
return new THREE.Matrix4().fromArray( parseFloatArray( floatString ) );
}
/**
* Converts number from degrees into radians.
* @param {number} value
* @returns {number}
*/
function degreeToRadian( value ) {
return value * Math.PI / 180;
}
} )();
| skftn/waveDIM | waveDIM/static/js/three_utils/js/loaders/FBXLoader2.js | JavaScript | mit | 100,527 |
var vows = require("vows"),
load = require("../load"),
assert = require("../assert");
var suite = vows.describe("d3.layout.tree");
suite.addBatch({
"tree": {
topic: load("layout/tree").expression("d3.layout.tree"),
"computes a simple tree layout": function(tree) {
var t = tree();
assert.deepEqual(t.nodes({
name: "1",
children: [
{name: "1-1"},
{name: "1-2"},
{name: "1-3"}
]
}).map(layout), [
{name: "1", depth: 0, x: 0.5, y: 0},
{name: "1-1", depth: 1, x: 0.16666666666666666, y: 1},
{name: "1-2", depth: 1, x: 0.5, y: 1},
{name: "1-3", depth: 1, x: 0.8333333333333333, y: 1}
]);
},
"can handle an empty children array": function(tree) {
var t = tree();
assert.deepEqual(t.nodes({children: []}).map(layout), [
{depth: 0, x: 0.5, y: 0}
]);
assert.deepEqual(t.nodes({children: [
{children: []},
{children: [{}]},
{children: [{}]}
]}).map(layout), [
{depth: 0, x: 0.5, y: 0},
{depth: 1, x: 0.125, y: 0.5},
{depth: 1, x: 0.375, y: 0.5},
{depth: 2, x: 0.375, y: 1},
{depth: 1, x: 0.875, y: 0.5},
{depth: 2, x: 0.875, y: 1}
]);
},
"can handle a single node": function(tree) {
var t = tree();
assert.deepEqual(t.nodes({}).map(layout), [
{depth: 0, x: 0.5, y: 0}
]);
}
}
});
function layout(node) {
delete node.children;
delete node.parent;
return node;
}
suite.export(module);
| angrycactus/dkan | webroot/profiles/dkan/libraries/d3/test/layout/tree-test.js | JavaScript | gpl-2.0 | 1,577 |
// Copyright JS Foundation and other contributors, http://js.foundation
//
// 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 sum = 0;
for (var i = 0; i < 10; i++)
for (var j = 0; j < 20; j++)
{
if (j > 9)
continue;
sum += 1;
}
assert(sum === 100);
| grgustaf/jerryscript | tests/jerry-test-suite/12/12.07/12.07-002.js | JavaScript | apache-2.0 | 779 |
'use strict';
/**
* @description
* Private service to sanitize uris for links and images. Used by $compile and $sanitize.
*/
function $$SanitizeUriProvider() {
var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
imgSrcSanitizationWhitelist = /^\s*(https?|ftp|file):|data:image\//;
/**
* @description
* Retrieves or overrides the default regular expression that is used for whitelisting of safe
* urls during a[href] sanitization.
*
* The sanitization is a security measure aimed at prevent XSS attacks via html links.
*
* Any url about to be assigned to a[href] via data-binding is first normalized and turned into
* an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
* regular expression. If a match is found, the original url is written into the dom. Otherwise,
* the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
*
* @param {RegExp=} regexp New regexp to whitelist urls with.
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
* chaining otherwise.
*/
this.aHrefSanitizationWhitelist = function(regexp) {
if (isDefined(regexp)) {
aHrefSanitizationWhitelist = regexp;
return this;
}
return aHrefSanitizationWhitelist;
};
/**
* @description
* Retrieves or overrides the default regular expression that is used for whitelisting of safe
* urls during img[src] sanitization.
*
* The sanitization is a security measure aimed at prevent XSS attacks via html links.
*
* Any url about to be assigned to img[src] via data-binding is first normalized and turned into
* an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
* regular expression. If a match is found, the original url is written into the dom. Otherwise,
* the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
*
* @param {RegExp=} regexp New regexp to whitelist urls with.
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
* chaining otherwise.
*/
this.imgSrcSanitizationWhitelist = function(regexp) {
if (isDefined(regexp)) {
imgSrcSanitizationWhitelist = regexp;
return this;
}
return imgSrcSanitizationWhitelist;
};
this.$get = function() {
return function sanitizeUri(uri, isImage) {
var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
var normalizedVal;
// NOTE: urlResolve() doesn't support IE < 8 so we don't sanitize for that case.
if (!msie || msie >= 8 ) {
normalizedVal = urlResolve(uri).href;
if (normalizedVal !== '' && !normalizedVal.match(regex)) {
return 'unsafe:'+normalizedVal;
}
}
return uri;
};
};
}
| ericsteele/retrospec.js | test/input/projects/angular.js/fef0cfc/src/ng/sanitizeUri.js | JavaScript | mit | 2,916 |
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareLaptopMac = (props) => (
<SvgIcon {...props}>
<path d="M20 18c1.1 0 1.99-.9 1.99-2L22 5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v11c0 1.1.9 2 2 2H0c0 1.1.9 2 2 2h20c1.1 0 2-.9 2-2h-4zM4 5h16v11H4V5zm8 14c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z"/>
</SvgIcon>
);
HardwareLaptopMac = pure(HardwareLaptopMac);
HardwareLaptopMac.displayName = 'HardwareLaptopMac';
HardwareLaptopMac.muiName = 'SvgIcon';
export default HardwareLaptopMac;
| frnk94/material-ui | src/svg-icons/hardware/laptop-mac.js | JavaScript | mit | 553 |
module.exports = ChainInstance;
function ChainInstance(chain, cb) {
var instances = null;
var loading = false;
var queue = [];
var load = function () {
loading = true;
chain.run(function (err, items) {
instances = items;
return next();
});
};
var promise = function(hwd, next) {
return function () {
if (!loading) {
load();
}
queue.push({ hwd: hwd, args: arguments });
return calls;
};
};
var next = function () {
if (queue.length === 0) return;
var item = queue.shift();
item.hwd.apply(calls, item.args);
};
var calls = {
filter: promise(function (cb) {
instances = instances.filter(cb);
return next();
}),
forEach: promise(function (cb) {
instances.forEach(cb);
return next();
}),
sort: promise(function (cb) {
instances.sort(cb);
return next();
}),
count: promise(function (cb) {
cb(instances.length);
return next();
}),
get: promise(function (cb) {
cb(instances);
return next();
}),
save: promise(function (cb) {
var saveNext = function (i) {
if (i >= instances.length) {
if (typeof cb === "function") {
cb();
}
return next();
}
return instances[i].save(function (err) {
if (err) {
if (typeof cb === "function") {
cb(err);
}
return next();
}
return saveNext(i + 1);
});
};
return saveNext(0);
})
};
if (typeof cb === "function") {
return calls.forEach(cb);
}
return calls;
}
| wp3xpp/awesomeFreeMind-nodejs | www/node_modules/orm/lib/ChainInstance.js | JavaScript | mit | 1,495 |
YUI.add('editor-lists', function (Y, NAME) {
/**
* Handles list manipulation inside the Editor. Adds keyboard manipulation and execCommand support.
* Adds overrides for the <a href="Plugin.ExecCommand.html#method_COMMANDS.insertorderedlist">insertorderedlist</a>
* and <a href="Plugin.ExecCommand.html#method_COMMANDS.insertunorderedlist">insertunorderedlist</a> execCommands.
* @class Plugin.EditorLists
* @constructor
* @extends Base
* @module editor
* @submodule editor-lists
*/
var EditorLists = function() {
EditorLists.superclass.constructor.apply(this, arguments);
}, LI = 'li', OL = 'ol', UL = 'ul', HOST = 'host';
Y.extend(EditorLists, Y.Base, {
/**
* Listener for host's nodeChange event and captures the tabkey interaction only when inside a list node.
* @private
* @method _onNodeChange
* @param {Event} e The Event facade passed from the host.
*/
_onNodeChange: function(e) {
var inst = this.get(HOST).getInstance(), li,
newList, sTab, par, moved = false, tag, focusEnd = false;
if (e.changedType === 'tab') {
if (e.changedNode.test(LI + ', ' + LI + ' *')) {
Y.log('Overriding TAB to move lists around', 'info', 'editorLists');
e.changedEvent.halt();
e.preventDefault();
li = e.changedNode;
sTab = e.changedEvent.shiftKey;
par = li.ancestor(OL + ',' + UL);
tag = UL;
if (par.get('tagName').toLowerCase() === OL) {
tag = OL;
}
Y.log('ShiftKey: ' + sTab, 'info', 'editorLists');
if (!li.test(LI)) {
li = li.ancestor(LI);
}
if (sTab) {
if (li.ancestor(LI)) {
Y.log('Shifting list up one level', 'info', 'editorLists');
li.ancestor(LI).insert(li, 'after');
moved = true;
focusEnd = true;
}
} else {
//li.setStyle('border', '1px solid red');
if (li.previous(LI)) {
Y.log('Shifting list down one level', 'info', 'editorLists');
newList = inst.Node.create('<' + tag + '></' + tag + '>');
li.previous(LI).append(newList);
newList.append(li);
moved = true;
}
}
}
if (moved) {
if (!li.test(LI)) {
li = li.ancestor(LI);
}
li.all(EditorLists.REMOVE).remove();
if (Y.UA.ie) {
li = li.append(EditorLists.NON).one(EditorLists.NON_SEL);
}
//Selection here..
Y.log('Selecting the new node', 'info', 'editorLists');
(new inst.EditorSelection()).selectNode(li, true, focusEnd);
}
}
},
initializer: function() {
this.get(HOST).on('nodeChange', Y.bind(this._onNodeChange, this));
}
}, {
/**
* The non element placeholder, used for positioning the cursor and filling empty items
* @property NON
* @static
*/
NON: '<span class="yui-non"> </span>',
/**
* The selector query to get all non elements
* @property NONSEL
* @static
*/
NON_SEL: 'span.yui-non',
/**
* The items to removed from a list when a list item is moved, currently removes BR nodes
* @property REMOVE
* @static
*/
REMOVE: 'br',
/**
* editorLists
* @property NAME
* @static
*/
NAME: 'editorLists',
/**
* lists
* @property NS
* @static
*/
NS: 'lists',
ATTRS: {
host: {
value: false
}
}
});
Y.namespace('Plugin');
Y.Plugin.EditorLists = EditorLists;
}, '@VERSION@', {"requires": ["editor-base"]});
| chauncey/there-be-docs | static/yui3/editor-lists/editor-lists-debug.js | JavaScript | mit | 4,484 |
var path = require('path');
var fs = require('fs');
var spawn = require('child_process').spawn;
function noop() {}
exports.noop = noop;
if (process.env.HTTP2_LOG) {
var logOutput = process.stderr;
if (process.stderr.isTTY) {
var bin = path.resolve(path.dirname(require.resolve('bunyan')), '..', 'bin', 'bunyan');
if(bin && fs.existsSync(bin)) {
logOutput = spawn(bin, ['-o', 'short'], {
stdio: [null, process.stderr, process.stderr]
}).stdin;
}
}
exports.createLogger = function(name) {
return require('bunyan').createLogger({
name: name,
stream: logOutput,
level: process.env.HTTP2_LOG,
serializers: require('../lib/http').serializers
});
};
exports.log = exports.createLogger('test');
exports.clientLog = exports.createLogger('client');
exports.serverLog = exports.createLogger('server');
} else {
exports.createLogger = function() {
return exports.log;
};
exports.log = exports.clientLog = exports.serverLog = {
fatal: noop,
error: noop,
warn : noop,
info : noop,
debug: noop,
trace: noop,
child: function() { return this; }
};
}
exports.callNTimes = function callNTimes(limit, done) {
if (limit === 0) {
done();
} else {
var i = 0;
return function() {
i += 1;
if (i === limit) {
done();
}
};
}
};
// Concatenate an array of buffers into a new buffer
exports.concat = function concat(buffers) {
var size = 0;
for (var i = 0; i < buffers.length; i++) {
size += buffers[i].length;
}
var concatenated = new Buffer(size);
for (var cursor = 0, j = 0; j < buffers.length; cursor += buffers[j].length, j++) {
buffers[j].copy(concatenated, cursor);
}
return concatenated;
};
exports.random = function random(min, max) {
return min + Math.floor(Math.random() * (max - min + 1));
};
// Concatenate an array of buffers and then cut them into random size buffers
exports.shuffleBuffers = function shuffleBuffers(buffers) {
var concatenated = exports.concat(buffers), output = [], written = 0;
while (written < concatenated.length) {
var chunk_size = Math.min(concatenated.length - written, Math.ceil(Math.random()*20));
output.push(concatenated.slice(written, written + chunk_size));
written += chunk_size;
}
return output;
};
| BobRazoswki/ddp | wp-content/themes/ddp/config/node_modules/gulp-connect/node_modules/http2/test/util.js | JavaScript | gpl-2.0 | 2,341 |
/*
* file.js: Transport for outputting to a local log file
*
* (C) 2010 Charlie Robbins
* MIT LICENCE
*
*/
var events = require('events'),
fs = require('fs'),
path = require('path'),
util = require('util'),
async = require('async'),
colors = require('colors'),
common = require('../common'),
Transport = require('./transport').Transport,
isWritable = require('isstream').isWritable,
Stream = require('stream').Stream;
//
// ### function File (options)
// #### @options {Object} Options for this instance.
// Constructor function for the File transport object responsible
// for persisting log messages and metadata to one or more files.
//
var File = exports.File = function (options) {
Transport.call(this, options);
//
// Helper function which throws an `Error` in the event
// that any of the rest of the arguments is present in `options`.
//
function throwIf (target /*, illegal... */) {
Array.prototype.slice.call(arguments, 1).forEach(function (name) {
if (options[name]) {
throw new Error('Cannot set ' + name + ' and ' + target + 'together');
}
});
}
if (options.filename || options.dirname) {
throwIf('filename or dirname', 'stream');
this._basename = this.filename = options.filename
? path.basename(options.filename)
: 'winston.log';
this.dirname = options.dirname || path.dirname(options.filename);
this.options = options.options || { flags: 'a' };
//
// "24 bytes" is maybe a good value for logging lines.
//
this.options.highWaterMark = this.options.highWaterMark || 24;
}
else if (options.stream) {
throwIf('stream', 'filename', 'maxsize');
this._stream = options.stream;
this._isStreams2 = isWritable(this._stream);
//
// We need to listen for drain events when
// write() returns false. This can make node
// mad at times.
//
this._stream.setMaxListeners(Infinity);
}
else {
throw new Error('Cannot log to file without filename or stream.');
}
this.json = options.json !== false;
this.logstash = options.logstash || false;
this.colorize = options.colorize || false;
this.maxsize = options.maxsize || null;
this.rotationFormat = options.rotationFormat || false;
this.maxFiles = options.maxFiles || null;
this.prettyPrint = options.prettyPrint || false;
this.label = options.label || null;
this.timestamp = options.timestamp != null ? options.timestamp : true;
this.eol = options.eol || '\n';
this.tailable = options.tailable || false;
this.depth = options.depth || null;
this.showLevel = options.showLevel === undefined ? true : options.showLevel;
if (this.json) {
this.stringify = options.stringify;
}
//
// Internal state variables representing the number
// of files this instance has created and the current
// size (in bytes) of the current logfile.
//
this._size = 0;
this._created = 0;
this._buffer = [];
this._draining = false;
this._opening = false;
};
//
// Inherit from `winston.Transport`.
//
util.inherits(File, Transport);
//
// Expose the name of this Transport on the prototype
//
File.prototype.name = 'file';
//
// ### function log (level, msg, [meta], callback)
// #### @level {string} Level at which to log the message.
// #### @msg {string} Message to log
// #### @meta {Object} **Optional** Additional metadata to attach
// #### @callback {function} Continuation to respond to when complete.
// Core logging method exposed to Winston. Metadata is optional.
//
File.prototype.log = function (level, msg, meta, callback) {
if (this.silent) {
return callback(null, true);
}
var self = this;
if (typeof msg !== 'string') {
msg = '' + msg;
}
var output = common.log({
level: level,
message: msg,
meta: meta,
json: this.json,
logstash: this.logstash,
colorize: this.colorize,
prettyPrint: this.prettyPrint,
timestamp: this.timestamp,
stringify: this.stringify,
label: this.label,
depth: this.depth,
formatter: this.formatter,
humanReadableUnhandledException: this.humanReadableUnhandledException
}) + this.eol;
if (!this.filename) {
//
// If there is no `filename` on this instance then it was configured
// with a raw `WriteableStream` instance and we should not perform any
// size restrictions.
//
this._write(output, callback);
this._size += output.length;
this._lazyDrain();
}
else {
this.open(function (err) {
if (err) {
//
// If there was an error enqueue the message
//
return self._buffer.push([output, callback]);
}
self._write(output, callback);
self._size += output.length;
self._lazyDrain();
});
}
};
//
// ### function _write (data, cb)
// #### @data {String|Buffer} Data to write to the instance's stream.
// #### @cb {function} Continuation to respond to when complete.
// Write to the stream, ensure execution of a callback on completion.
//
File.prototype._write = function(data, callback) {
if (this._isStreams2) {
this._stream.write(data);
return callback && process.nextTick(function () {
callback(null, true);
});
}
// If this is a file write stream, we could use the builtin
// callback functionality, however, the stream is not guaranteed
// to be an fs.WriteStream.
var ret = this._stream.write(data);
if (!callback) return;
if (ret === false) {
return this._stream.once('drain', function() {
callback(null, true);
});
}
process.nextTick(function () {
callback(null, true);
});
};
//
// ### function query (options, callback)
// #### @options {Object} Loggly-like query options for this instance.
// #### @callback {function} Continuation to respond to when complete.
// Query the transport. Options object is optional.
//
File.prototype.query = function (options, callback) {
if (typeof options === 'function') {
callback = options;
options = {};
}
var file = path.join(this.dirname, this.filename),
options = this.normalizeQuery(options),
buff = '',
results = [],
row = 0;
var stream = fs.createReadStream(file, {
encoding: 'utf8'
});
stream.on('error', function (err) {
if (stream.readable) {
stream.destroy();
}
if (!callback) return;
return err.code !== 'ENOENT'
? callback(err)
: callback(null, results);
});
stream.on('data', function (data) {
var data = (buff + data).split(/\n+/),
l = data.length - 1,
i = 0;
for (; i < l; i++) {
if (!options.start || row >= options.start) {
add(data[i]);
}
row++;
}
buff = data[l];
});
stream.on('close', function () {
if (buff) add(buff, true);
if (options.order === 'desc') {
results = results.reverse();
}
if (callback) callback(null, results);
});
function add(buff, attempt) {
try {
var log = JSON.parse(buff);
if (check(log)) push(log);
} catch (e) {
if (!attempt) {
stream.emit('error', e);
}
}
}
function push(log) {
if (options.rows && results.length >= options.rows) {
if (stream.readable) {
stream.destroy();
}
return;
}
if (options.fields) {
var obj = {};
options.fields.forEach(function (key) {
obj[key] = log[key];
});
log = obj;
}
results.push(log);
}
function check(log) {
if (!log) return;
if (typeof log !== 'object') return;
var time = new Date(log.timestamp);
if ((options.from && time < options.from)
|| (options.until && time > options.until)) {
return;
}
return true;
}
};
//
// ### function stream (options)
// #### @options {Object} Stream options for this instance.
// Returns a log stream for this transport. Options object is optional.
//
File.prototype.stream = function (options) {
var file = path.join(this.dirname, this.filename),
options = options || {},
stream = new Stream;
var tail = {
file: file,
start: options.start
};
stream.destroy = common.tailFile(tail, function (err, line) {
if(err){
return stream.emit('error',err);
}
try {
stream.emit('data', line);
line = JSON.parse(line);
stream.emit('log', line);
} catch (e) {
stream.emit('error', e);
}
});
return stream;
};
//
// ### function open (callback)
// #### @callback {function} Continuation to respond to when complete
// Checks to see if a new file needs to be created based on the `maxsize`
// (if any) and the current size of the file used.
//
File.prototype.open = function (callback) {
if (this.opening) {
//
// If we are already attempting to open the next
// available file then respond with a value indicating
// that the message should be buffered.
//
return callback(true);
}
else if (!this._stream || (this.maxsize && this._size >= this.maxsize)) {
//
// If we dont have a stream or have exceeded our size, then create
// the next stream and respond with a value indicating that
// the message should be buffered.
//
callback(true);
return this._createStream();
}
//
// Otherwise we have a valid (and ready) stream.
//
callback();
};
//
// ### function close ()
// Closes the stream associated with this instance.
//
File.prototype.close = function () {
var self = this;
if (this._stream) {
this._stream.end();
this._stream.destroySoon();
this._stream.once('drain', function () {
self.emit('flush');
self.emit('closed');
});
}
};
//
// ### function flush ()
// Flushes any buffered messages to the current `stream`
// used by this instance.
//
File.prototype.flush = function () {
var self = this;
// If nothing to flush, there will be no "flush" event from native stream
// Thus, the "open" event will never be fired (see _createStream.createAndFlush function)
// That means, self.opening will never set to false and no logs will be written to disk
if (!this._buffer.length) {
return self.emit('flush');
}
//
// Iterate over the `_buffer` of enqueued messaged
// and then write them to the newly created stream.
//
this._buffer.forEach(function (item) {
var str = item[0],
callback = item[1];
process.nextTick(function () {
self._write(str, callback);
self._size += str.length;
});
});
//
// Quickly truncate the `_buffer` once the write operations
// have been started
//
self._buffer.length = 0;
//
// When the stream has drained we have flushed
// our buffer.
//
self._stream.once('drain', function () {
self.emit('flush');
self.emit('logged');
});
};
//
// ### @private function _createStream ()
// Attempts to open the next appropriate file for this instance
// based on the common state (such as `maxsize` and `_basename`).
//
File.prototype._createStream = function () {
var self = this;
this.opening = true;
(function checkFile (target) {
var fullname = path.join(self.dirname, target);
//
// Creates the `WriteStream` and then flushes any
// buffered messages.
//
function createAndFlush (size) {
if (self._stream) {
self._stream.end();
self._stream.destroySoon();
}
self._size = size;
self.filename = target;
self._stream = fs.createWriteStream(fullname, self.options);
self._isStreams2 = isWritable(self._stream);
//
// We need to listen for drain events when
// write() returns false. This can make node
// mad at times.
//
self._stream.setMaxListeners(Infinity);
//
// When the current stream has finished flushing
// then we can be sure we have finished opening
// and thus can emit the `open` event.
//
self.once('flush', function () {
// Because "flush" event is based on native stream "drain" event,
// logs could be written inbetween "self.flush()" and here
// Therefore, we need to flush again to make sure everything is flushed
self.flush();
self.opening = false;
self.emit('open', fullname);
});
//
// Remark: It is possible that in the time it has taken to find the
// next logfile to be written more data than `maxsize` has been buffered,
// but for sensible limits (10s - 100s of MB) this seems unlikely in less
// than one second.
//
self.flush();
}
fs.stat(fullname, function (err, stats) {
if (err) {
if (err.code !== 'ENOENT') {
return self.emit('error', err);
}
return createAndFlush(0);
}
if (!stats || (self.maxsize && stats.size >= self.maxsize)) {
//
// If `stats.size` is greater than the `maxsize` for
// this instance then try again
//
return self._incFile(function() {
checkFile(self._getFile());
});
}
createAndFlush(stats.size);
});
})(this._getFile());
};
File.prototype._incFile = function (callback) {
var ext = path.extname(this._basename),
basename = path.basename(this._basename, ext),
oldest,
target;
if (!this.tailable) {
this._created += 1;
this._checkMaxFilesIncrementing(ext, basename, callback);
}
else {
this._checkMaxFilesTailable(ext, basename, callback);
}
};
//
// ### @private function _getFile ()
// Gets the next filename to use for this instance
// in the case that log filesizes are being capped.
//
File.prototype._getFile = function () {
var ext = path.extname(this._basename),
basename = path.basename(this._basename, ext);
//
// Caveat emptor (indexzero): rotationFormat() was broken by design
// when combined with max files because the set of files to unlink
// is never stored.
//
return !this.tailable && this._created
? basename + (this.rotationFormat ? this.rotationFormat() : this._created) + ext
: basename + ext;
};
//
// ### @private function _checkMaxFilesIncrementing ()
// Increment the number of files created or
// checked by this instance.
//
File.prototype._checkMaxFilesIncrementing = function (ext, basename, callback) {
var oldest, target;
// Check for maxFiles option and delete file
if (!this.maxFiles || this._created < this.maxFiles) {
return callback();
}
oldest = this._created - this.maxFiles;
target = path.join(this.dirname, basename + (oldest === 0 ? oldest : '') + ext);
fs.unlink(target, callback);
};
//
// ### @private function _checkMaxFilesTailable ()
//
// Roll files forward based on integer, up to maxFiles.
// e.g. if base if file.log and it becomes oversized, roll
// to file1.log, and allow file.log to be re-used. If
// file is oversized again, roll file1.log to file2.log,
// roll file.log to file1.log, and so on.
File.prototype._checkMaxFilesTailable = function (ext, basename, callback) {
var tasks = [],
self = this;
if (!this.maxFiles)
return;
for (var x = this.maxFiles - 1; x > 0; x--) {
tasks.push(function (i) {
return function (cb) {
var tmppath = path.join(self.dirname, basename + (i - 1) + ext);
fs.exists(tmppath, function (exists) {
if (!exists) {
return cb(null);
}
fs.rename(tmppath, path.join(self.dirname, basename + i + ext), cb);
});
};
}(x));
}
async.series(tasks, function (err) {
fs.rename(
path.join(self.dirname, basename + ext),
path.join(self.dirname, basename + 1 + ext),
callback
);
});
};
//
// ### @private function _lazyDrain ()
// Lazily attempts to emit the `logged` event when `this.stream` has
// drained. This is really just a simple mutex that only works because
// Node.js is single-threaded.
//
File.prototype._lazyDrain = function () {
var self = this;
if (!this._draining && this._stream) {
this._draining = true;
this._stream.once('drain', function () {
this._draining = false;
self.emit('logged');
});
}
};
| littleredshack/socketbi | server/node_modules/winston/lib/winston/transports/file.js | JavaScript | mit | 16,320 |
/** PURE_IMPORTS_START PURE_IMPORTS_END */
export function hostReportError(err) {
setTimeout(function () { throw err; }, 0);
}
//# sourceMappingURL=hostReportError.js.map
| BigBoss424/portfolio | v8/development/node_modules/rxjs/_esm5/internal/util/hostReportError.js | JavaScript | apache-2.0 | 176 |
// generated from ldml/main/*.xml, xpath: ldml/numbers
({
'decimal':",",
'group':".",
'list':";",
'percentSign':"%",
'nativeZeroDigit':"0",
'patternDigit':"#",
'plusSign':"+",
'minusSign':"-",
'exponential':"E",
'perMille':"‰",
'infinity':"∞",
'nan':"NaN",
'decimalFormat':"#,##0.###",
'scientificFormat':"#E0",
'percentFormat':"% #,##0",
'currencyFormat':"#,##0.00 ¤"
})
| ozoneplatform/owf-framework | web-app/js-lib/dojo-release-1.5.0-src/dojo/cldr/nls/tr/number.js | JavaScript | apache-2.0 | 395 |
/**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule RelayRecordState
* @flow
* @typechecks
*/
'use strict';
export type RecordState = $Enum<typeof RelayRecordState>;
var RelayRecordState = {
/**
* Record exists (either fetched from the server or produced by a local,
* optimistic update).
*/
EXISTENT: 'EXISTENT',
/**
* Record is known not to exist (either as the result of a mutation, or
* because the server returned `null` when queried for the record).
*/
NONEXISTENT: 'NONEXISTENT',
/**
* Record State is unknown because it has not yet been fetched from the
* server.
*/
UNKNOWN: 'UNKNOWN',
};
module.exports = RelayRecordState;
| quazzie/relay | src/store/RelayRecordState.js | JavaScript | bsd-3-clause | 949 |
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule PerformanceOverlay
* @flow
*/
'use strict';
var PerformanceLogger = require('PerformanceLogger');
var React = require('React');
var StyleSheet = require('StyleSheet');
var Text = require('Text');
var View = require('View');
var PerformanceOverlay = React.createClass({
render: function() {
var perfLogs = PerformanceLogger.getTimespans();
var items = [];
for (var key in perfLogs) {
if (perfLogs[key].totalTime) {
var unit = (key === 'BundleSize') ? 'b' : 'ms';
items.push(
<View style={styles.row} key={key}>
<Text style={[styles.text, styles.label]}>{key}</Text>
<Text style={[styles.text, styles.totalTime]}>
{perfLogs[key].totalTime + unit}
</Text>
</View>
);
}
}
return (
<View style={styles.container}>
{items}
</View>
);
}
});
var styles = StyleSheet.create({
container: {
height: 100,
paddingTop: 10,
},
label: {
flex: 1,
},
row: {
flexDirection: 'row',
paddingHorizontal: 10,
},
text: {
color: 'white',
fontSize: 12,
},
totalTime: {
paddingRight: 100,
},
});
module.exports = PerformanceOverlay;
| paulunits/tiptap | node_modules/react-native/Libraries/Inspector/PerformanceOverlay.js | JavaScript | mit | 1,546 |
var crypto = require('crypto');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var pgPass = require('pgpass');
var TypeOverrides = require('./type-overrides');
var ConnectionParameters = require('./connection-parameters');
var Query = require('./query');
var defaults = require('./defaults');
var Connection = require('./connection');
var Client = function(config) {
EventEmitter.call(this);
this.connectionParameters = new ConnectionParameters(config);
this.user = this.connectionParameters.user;
this.database = this.connectionParameters.database;
this.port = this.connectionParameters.port;
this.host = this.connectionParameters.host;
this.password = this.connectionParameters.password;
var c = config || {};
this._types = new TypeOverrides(c.types);
this.connection = c.connection || new Connection({
stream: c.stream,
ssl: this.connectionParameters.ssl
});
this.queryQueue = [];
this.binary = c.binary || defaults.binary;
this.encoding = 'utf8';
this.processID = null;
this.secretKey = null;
this.ssl = this.connectionParameters.ssl || false;
};
util.inherits(Client, EventEmitter);
Client.prototype.connect = function(callback) {
var self = this;
var con = this.connection;
if(this.host && this.host.indexOf('/') === 0) {
con.connect(this.host + '/.s.PGSQL.' + this.port);
} else {
con.connect(this.port, this.host);
}
//once connection is established send startup message
con.on('connect', function() {
if(self.ssl) {
con.requestSsl();
} else {
con.startup(self.getStartupConf());
}
});
con.on('sslconnect', function() {
con.startup(self.getStartupConf());
});
function checkPgPass(cb) {
return function(msg) {
if (null !== self.password) {
cb(msg);
} else {
pgPass(self.connectionParameters, function(pass){
if (undefined !== pass) {
self.connectionParameters.password = self.password = pass;
}
cb(msg);
});
}
};
}
//password request handling
con.on('authenticationCleartextPassword', checkPgPass(function() {
con.password(self.password);
}));
//password request handling
con.on('authenticationMD5Password', checkPgPass(function(msg) {
var inner = Client.md5(self.password + self.user);
var outer = Client.md5(Buffer.concat([new Buffer(inner), msg.salt]));
var md5password = "md5" + outer;
con.password(md5password);
}));
con.once('backendKeyData', function(msg) {
self.processID = msg.processID;
self.secretKey = msg.secretKey;
});
//hook up query handling events to connection
//after the connection initially becomes ready for queries
con.once('readyForQuery', function() {
//delegate rowDescription to active query
con.on('rowDescription', function(msg) {
self.activeQuery.handleRowDescription(msg);
});
//delegate dataRow to active query
con.on('dataRow', function(msg) {
self.activeQuery.handleDataRow(msg);
});
//delegate portalSuspended to active query
con.on('portalSuspended', function(msg) {
self.activeQuery.handlePortalSuspended(con);
});
//deletagate emptyQuery to active query
con.on('emptyQuery', function(msg) {
self.activeQuery.handleEmptyQuery(con);
});
//delegate commandComplete to active query
con.on('commandComplete', function(msg) {
self.activeQuery.handleCommandComplete(msg, con);
});
//if a prepared statement has a name and properly parses
//we track that its already been executed so we don't parse
//it again on the same client
con.on('parseComplete', function(msg) {
if(self.activeQuery.name) {
con.parsedStatements[self.activeQuery.name] = true;
}
});
con.on('copyInResponse', function(msg) {
self.activeQuery.handleCopyInResponse(self.connection);
});
con.on('copyData', function (msg) {
self.activeQuery.handleCopyData(msg, self.connection);
});
con.on('notification', function(msg) {
self.emit('notification', msg);
});
//process possible callback argument to Client#connect
if (callback) {
callback(null, self);
//remove callback for proper error handling
//after the connect event
callback = null;
}
self.emit('connect');
});
con.on('readyForQuery', function() {
var activeQuery = self.activeQuery;
self.activeQuery = null;
self.readyForQuery = true;
self._pulseQueryQueue();
if(activeQuery) {
activeQuery.handleReadyForQuery();
}
});
con.on('error', function(error) {
if(self.activeQuery) {
var activeQuery = self.activeQuery;
self.activeQuery = null;
return activeQuery.handleError(error, con);
}
if(!callback) {
return self.emit('error', error);
}
callback(error);
callback = null;
});
con.once('end', function() {
if ( callback ) {
// haven't received a connection message yet !
var err = new Error('Connection terminated');
callback(err);
callback = null;
return;
}
if(self.activeQuery) {
var disconnectError = new Error('Connection terminated');
self.activeQuery.handleError(disconnectError, con);
self.activeQuery = null;
}
self.emit('end');
});
con.on('notice', function(msg) {
self.emit('notice', msg);
});
};
Client.prototype.getStartupConf = function() {
var params = this.connectionParameters;
var data = {
user: params.user,
database: params.database
};
var appName = params.application_name || params.fallback_application_name;
if (appName) {
data.application_name = appName;
}
return data;
};
Client.prototype.cancel = function(client, query) {
if(client.activeQuery == query) {
var con = this.connection;
if(this.host && this.host.indexOf('/') === 0) {
con.connect(this.host + '/.s.PGSQL.' + this.port);
} else {
con.connect(this.port, this.host);
}
//once connection is established send cancel message
con.on('connect', function() {
con.cancel(client.processID, client.secretKey);
});
} else if(client.queryQueue.indexOf(query) != -1) {
client.queryQueue.splice(client.queryQueue.indexOf(query), 1);
}
};
Client.prototype.setTypeParser = function(oid, format, parseFn) {
return this._types.setTypeParser(oid, format, parseFn);
};
Client.prototype.getTypeParser = function(oid, format) {
return this._types.getTypeParser(oid, format);
};
// Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c
Client.prototype.escapeIdentifier = function(str) {
var escaped = '"';
for(var i = 0; i < str.length; i++) {
var c = str[i];
if(c === '"') {
escaped += c + c;
} else {
escaped += c;
}
}
escaped += '"';
return escaped;
};
// Ported from PostgreSQL 9.2.4 source code in src/interfaces/libpq/fe-exec.c
Client.prototype.escapeLiteral = function(str) {
var hasBackslash = false;
var escaped = '\'';
for(var i = 0; i < str.length; i++) {
var c = str[i];
if(c === '\'') {
escaped += c + c;
} else if (c === '\\') {
escaped += c + c;
hasBackslash = true;
} else {
escaped += c;
}
}
escaped += '\'';
if(hasBackslash === true) {
escaped = ' E' + escaped;
}
return escaped;
};
Client.prototype._pulseQueryQueue = function() {
if(this.readyForQuery===true) {
this.activeQuery = this.queryQueue.shift();
if(this.activeQuery) {
this.readyForQuery = false;
this.hasExecuted = true;
this.activeQuery.submit(this.connection);
} else if(this.hasExecuted) {
this.activeQuery = null;
this.emit('drain');
}
}
};
Client.prototype.copyFrom = function (text) {
throw new Error("For PostgreSQL COPY TO/COPY FROM support npm install pg-copy-streams");
};
Client.prototype.copyTo = function (text) {
throw new Error("For PostgreSQL COPY TO/COPY FROM support npm install pg-copy-streams");
};
Client.prototype.query = function(config, values, callback) {
//can take in strings, config object or query object
var query = (typeof config.submit == 'function') ? config :
new Query(config, values, callback);
if(this.binary && !query.binary) {
query.binary = true;
}
if(query._result) {
query._result._getTypeParser = this._types.getTypeParser.bind(this._types);
}
this.queryQueue.push(query);
this._pulseQueryQueue();
return query;
};
Client.prototype.end = function() {
this.connection.end();
};
Client.md5 = function(string) {
return crypto.createHash('md5').update(string).digest('hex');
};
// expose a Query constructor
Client.Query = Query;
module.exports = Client;
| DianaVashti/talented-baboon | testApp/node_modules/pg/lib/client.js | JavaScript | mit | 8,813 |
tinyMCE.addI18n('ja.emotions_dlg',{
title:"\u30B9\u30DE\u30A4\u30EA\u30FC\u306E\u633F\u5165",
desc:"\u30B9\u30DE\u30A4\u30EA\u30FC",
cool:"Cool",
cry:"Cry",
embarassed:"Embarassed",
foot_in_mouth:"Foot in mouth",
frown:"Frown",
innocent:"Innocent",
kiss:"Kiss",
laughing:"Laughing",
money_mouth:"Money mouth",
sealed:"Sealed",
smile:"Smile",
surprised:"Surprised",
tongue_out:"Tongue out",
undecided:"Undecided",
wink:"Wink",
yell:"Yell"
}); | griggsk/Library-a-la-Carte | vendor/plugins/tiny_mce/public/javascripts/tiny_mce/plugins/emotions/langs/ja_dlg.js | JavaScript | agpl-3.0 | 460 |
/**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* 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.
*/
import {dev} from '../log';
/** @const {string} */
const TAG = 'lru-cache';
/**
* @template T
*/
export class LruCache {
/**
* @param {number} capacity
*/
constructor(capacity) {
/** @private @const {number} */
this.capacity_ = capacity;
/** @private {number} */
this.size_ = 0;
/**
* An incrementing counter to define the last access.
* @private {number}
*/
this.access_ = 0;
/** @private {!Object<(number|string), {payload: T, access: number}>} */
this.cache_ = Object.create(null);
}
/**
* Returns whether key is cached.
*
* @param {number|string} key
* @return {boolean}
*/
has(key) {
return !!this.cache_[key];
}
/**
* @param {number|string} key
* @return {T} The cached payload.
*/
get(key) {
const cacheable = this.cache_[key];
if (cacheable) {
cacheable.access = ++this.access_;
return cacheable.payload;
}
return undefined;
}
/**
* @param {number|string} key
* @param {T} payload The payload to cache.
*/
put(key, payload) {
if (!this.has(key)) {
this.size_++;
}
this.cache_[key] = {payload, access: this.access_};
this.evict_();
}
/**
* Evicts the oldest cache entry, if we've exceeded capacity.
*/
evict_() {
if (this.size_ <= this.capacity_) {
return;
}
dev().warn(TAG, 'Trimming LRU cache');
const cache = this.cache_;
let oldest = this.access_ + 1;
let oldestKey;
for (const key in cache) {
const {access} = cache[key];
if (access < oldest) {
oldest = access;
oldestKey = key;
}
}
if (oldestKey !== undefined) {
delete cache[oldestKey];
this.size_--;
}
}
}
| lannka/amphtml | src/utils/lru-cache.js | JavaScript | apache-2.0 | 2,381 |
/*************************************************************
*
* MathJax/fonts/HTML-CSS/TeX/png/Main/Bold/LatinExtendedA.js
*
* Defines the image size data needed for the HTML-CSS OutputJax
* to display mathematics using fallback images when the fonts
* are not availble to the client browser.
*
* ---------------------------------------------------------------------
*
* Copyright (c) 2009-2013 The MathJax Consortium
*
* 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
*
* 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.
*
*/
MathJax.OutputJax["HTML-CSS"].defineImageData({
"MathJax_Main-bold": {
0x131: [ // LATIN SMALL LETTER DOTLESS I
[3,3,0],[4,4,0],[4,5,0],[5,5,0],[6,6,0],[7,8,0],[8,9,0],[9,11,0],
[11,13,0],[12,15,0],[15,18,0],[17,21,0],[21,25,0],[24,30,0]
]
}
});
MathJax.Ajax.loadComplete(MathJax.OutputJax["HTML-CSS"].imgDir+"/Main/Bold"+
MathJax.OutputJax["HTML-CSS"].imgPacked+"/LatinExtendedA.js");
| AndrewSyktyvkar/Math | wysivig/MathJax/fonts/HTML-CSS/TeX/png/Main/Bold/unpacked/LatinExtendedA.js | JavaScript | bsd-3-clause | 1,440 |
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
/**
* MUI CSS/JS main module
* @module main
*/
(function(win) {
'use strict';
// return if library has been loaded already
if (win._muiLoadedJS) return;
else win._muiLoadedJS = true;
// load dependencies
var jqLite = require('src/js/lib/jqLite'),
dropdown = require('src/js/dropdown'),
overlay = require('src/js/overlay'),
ripple = require('src/js/ripple'),
select = require('src/js/select'),
tabs = require('src/js/tabs'),
textfield = require('src/js/textfield');
// expose api
win.mui = {
overlay: overlay,
tabs: tabs.api
};
// init libraries
jqLite.ready(function() {
textfield.initListeners();
select.initListeners();
ripple.initListeners();
dropdown.initListeners();
tabs.initListeners();
});
})(window);
},{"src/js/dropdown":6,"src/js/lib/jqLite":7,"src/js/overlay":8,"src/js/ripple":9,"src/js/select":10,"src/js/tabs":11,"src/js/textfield":12}],2:[function(require,module,exports){
/**
* MUI config module
* @module config
*/
/** Define module API */
module.exports = {
/** Use debug mode */
debug: true
};
},{}],3:[function(require,module,exports){
/**
* MUI CSS/JS form helpers module
* @module lib/forms.py
*/
'use strict';
var wrapperPadding = 15, // from CSS
inputHeight = 32, // from CSS
rowHeight = 42, // from CSS
menuPadding = 8; // from CSS
/**
* Menu position/size/scroll helper
* @returns {Object} Object with keys 'height', 'top', 'scrollTop'
*/
function getMenuPositionalCSSFn(wrapperEl, numRows, selectedRow) {
var viewHeight = document.documentElement.clientHeight;
// determine 'height'
var h = numRows * rowHeight + 2 * menuPadding,
height = Math.min(h, viewHeight);
// determine 'top'
var top, initTop, minTop, maxTop;
initTop = (menuPadding + rowHeight) - (wrapperPadding + inputHeight);
initTop -= selectedRow * rowHeight;
minTop = -1 * wrapperEl.getBoundingClientRect().top;
maxTop = (viewHeight - height) + minTop;
top = Math.min(Math.max(initTop, minTop), maxTop);
// determine 'scrollTop'
var scrollTop = 0,
scrollIdeal,
scrollMax;
if (h > viewHeight) {
scrollIdeal = (menuPadding + (selectedRow + 1) * rowHeight) -
(-1 * top + wrapperPadding + inputHeight);
scrollMax = numRows * rowHeight + 2 * menuPadding - height;
scrollTop = Math.min(scrollIdeal, scrollMax);
}
return {
'height': height + 'px',
'top': top + 'px',
'scrollTop': scrollTop
};
}
/** Define module API */
module.exports = {
getMenuPositionalCSS: getMenuPositionalCSSFn
};
},{}],4:[function(require,module,exports){
/**
* MUI CSS/JS jqLite module
* @module lib/jqLite
*/
'use strict';
/**
* Add a class to an element.
* @param {Element} element - The DOM element.
* @param {string} cssClasses - Space separated list of class names.
*/
function jqLiteAddClass(element, cssClasses) {
if (!cssClasses || !element.setAttribute) return;
var existingClasses = _getExistingClasses(element),
splitClasses = cssClasses.split(' '),
cssClass;
for (var i=0; i < splitClasses.length; i++) {
cssClass = splitClasses[i].trim();
if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
existingClasses += cssClass + ' ';
}
}
element.setAttribute('class', existingClasses.trim());
}
/**
* Get or set CSS properties.
* @param {Element} element - The DOM element.
* @param {string} [name] - The property name.
* @param {string} [value] - The property value.
*/
function jqLiteCss(element, name, value) {
// Return full style object
if (name === undefined) {
return getComputedStyle(element);
}
var nameType = jqLiteType(name);
// Set multiple values
if (nameType === 'object') {
for (var key in name) element.style[_camelCase(key)] = name[key];
return;
}
// Set a single value
if (nameType === 'string' && value !== undefined) {
element.style[_camelCase(name)] = value;
}
var styleObj = getComputedStyle(element),
isArray = (jqLiteType(name) === 'array');
// Read single value
if (!isArray) return _getCurrCssProp(element, name, styleObj);
// Read multiple values
var outObj = {},
key;
for (var i=0; i < name.length; i++) {
key = name[i];
outObj[key] = _getCurrCssProp(element, key, styleObj);
}
return outObj;
}
/**
* Check if element has class.
* @param {Element} element - The DOM element.
* @param {string} cls - The class name string.
*/
function jqLiteHasClass(element, cls) {
if (!cls || !element.getAttribute) return false;
return (_getExistingClasses(element).indexOf(' ' + cls + ' ') > -1);
}
/**
* Return the type of a variable.
* @param {} somevar - The JavaScript variable.
*/
function jqLiteType(somevar) {
// handle undefined
if (somevar === undefined) return 'undefined';
// handle others (of type [object <Type>])
var typeStr = Object.prototype.toString.call(somevar);
if (typeStr.indexOf('[object ') === 0) {
return typeStr.slice(8, -1).toLowerCase();
} else {
throw new Error("MUI: Could not understand type: " + typeStr);
}
}
/**
* Attach an event handler to a DOM element
* @param {Element} element - The DOM element.
* @param {string} events - Space separated event names.
* @param {Function} callback - The callback function.
* @param {Boolean} useCapture - Use capture flag.
*/
function jqLiteOn(element, events, callback, useCapture) {
useCapture = (useCapture === undefined) ? false : useCapture;
var cache = element._muiEventCache = element._muiEventCache || {};
events.split(' ').map(function(event) {
// add to DOM
element.addEventListener(event, callback, useCapture);
// add to cache
cache[event] = cache[event] || [];
cache[event].push([callback, useCapture]);
});
}
/**
* Remove an event handler from a DOM element
* @param {Element} element - The DOM element.
* @param {string} events - Space separated event names.
* @param {Function} callback - The callback function.
* @param {Boolean} useCapture - Use capture flag.
*/
function jqLiteOff(element, events, callback, useCapture) {
useCapture = (useCapture === undefined) ? false : useCapture;
// remove from cache
var cache = element._muiEventCache = element._muiEventCache || {},
argsList,
args,
i;
events.split(' ').map(function(event) {
argsList = cache[event] || [];
i = argsList.length;
while (i--) {
args = argsList[i];
// remove all events if callback is undefined
if (callback === undefined ||
(args[0] === callback && args[1] === useCapture)) {
// remove from cache
argsList.splice(i, 1);
// remove from DOM
element.removeEventListener(event, args[0], args[1]);
}
}
});
}
/**
* Attach an event hander which will only execute once per element per event
* @param {Element} element - The DOM element.
* @param {string} events - Space separated event names.
* @param {Function} callback - The callback function.
* @param {Boolean} useCapture - Use capture flag.
*/
function jqLiteOne(element, events, callback, useCapture) {
events.split(' ').map(function(event) {
jqLiteOn(element, event, function onFn(ev) {
// execute callback
if (callback) callback.apply(this, arguments);
// remove wrapper
jqLiteOff(element, event, onFn);
}, useCapture);
});
}
/**
* Get or set horizontal scroll position
* @param {Element} element - The DOM element
* @param {number} [value] - The scroll position
*/
function jqLiteScrollLeft(element, value) {
var win = window;
// get
if (value === undefined) {
if (element === win) {
var docEl = document.documentElement;
return (win.pageXOffset || docEl.scrollLeft) - (docEl.clientLeft || 0);
} else {
return element.scrollLeft;
}
}
// set
if (element === win) win.scrollTo(value, jqLiteScrollTop(win));
else element.scrollLeft = value;
}
/**
* Get or set vertical scroll position
* @param {Element} element - The DOM element
* @param {number} value - The scroll position
*/
function jqLiteScrollTop(element, value) {
var win = window;
// get
if (value === undefined) {
if (element === win) {
var docEl = document.documentElement;
return (win.pageYOffset || docEl.scrollTop) - (docEl.clientTop || 0);
} else {
return element.scrollTop;
}
}
// set
if (element === win) win.scrollTo(jqLiteScrollLeft(win), value);
else element.scrollTop = value;
}
/**
* Return object representing top/left offset and element height/width.
* @param {Element} element - The DOM element.
*/
function jqLiteOffset(element) {
var win = window,
rect = element.getBoundingClientRect(),
scrollTop = jqLiteScrollTop(win),
scrollLeft = jqLiteScrollLeft(win);
return {
top: rect.top + scrollTop,
left: rect.left + scrollLeft,
height: rect.height,
width: rect.width
};
}
/**
* Attach a callback to the DOM ready event listener
* @param {Function} fn - The callback function.
*/
function jqLiteReady(fn) {
var done = false,
top = true,
doc = document,
win = doc.defaultView,
root = doc.documentElement,
add = doc.addEventListener ? 'addEventListener' : 'attachEvent',
rem = doc.addEventListener ? 'removeEventListener' : 'detachEvent',
pre = doc.addEventListener ? '' : 'on';
var init = function(e) {
if (e.type == 'readystatechange' && doc.readyState != 'complete') {
return;
}
(e.type == 'load' ? win : doc)[rem](pre + e.type, init, false);
if (!done && (done = true)) fn.call(win, e.type || e);
};
var poll = function() {
try { root.doScroll('left'); } catch(e) { setTimeout(poll, 50); return; }
init('poll');
};
if (doc.readyState == 'complete') {
fn.call(win, 'lazy');
} else {
if (doc.createEventObject && root.doScroll) {
try { top = !win.frameElement; } catch(e) { }
if (top) poll();
}
doc[add](pre + 'DOMContentLoaded', init, false);
doc[add](pre + 'readystatechange', init, false);
win[add](pre + 'load', init, false);
}
}
/**
* Remove classes from a DOM element
* @param {Element} element - The DOM element.
* @param {string} cssClasses - Space separated list of class names.
*/
function jqLiteRemoveClass(element, cssClasses) {
if (!cssClasses || !element.setAttribute) return;
var existingClasses = _getExistingClasses(element),
splitClasses = cssClasses.split(' '),
cssClass;
for (var i=0; i < splitClasses.length; i++) {
cssClass = splitClasses[i].trim();
while (existingClasses.indexOf(' ' + cssClass + ' ') >= 0) {
existingClasses = existingClasses.replace(' ' + cssClass + ' ', ' ');
}
}
element.setAttribute('class', existingClasses.trim());
}
// ------------------------------
// Utilities
// ------------------------------
var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g,
MOZ_HACK_REGEXP = /^moz([A-Z])/,
ESCAPE_REGEXP = /([.*+?^=!:${}()|\[\]\/\\])/g;
function _getExistingClasses(element) {
var classes = (element.getAttribute('class') || '').replace(/[\n\t]/g, '');
return ' ' + classes + ' ';
}
function _camelCase(name) {
return name.
replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
}).
replace(MOZ_HACK_REGEXP, 'Moz$1');
}
function _escapeRegExp(string) {
return string.replace(ESCAPE_REGEXP, "\\$1");
}
function _getCurrCssProp(elem, name, computed) {
var ret;
// try computed style
ret = computed.getPropertyValue(name);
// try style attribute (if element is not attached to document)
if (ret === '' && !elem.ownerDocument) ret = elem.style[_camelCase(name)];
return ret;
}
/**
* Module API
*/
module.exports = {
/** Add classes */
addClass: jqLiteAddClass,
/** Get or set CSS properties */
css: jqLiteCss,
/** Check for class */
hasClass: jqLiteHasClass,
/** Remove event handlers */
off: jqLiteOff,
/** Return offset values */
offset: jqLiteOffset,
/** Add event handlers */
on: jqLiteOn,
/** Add an execute-once event handler */
one: jqLiteOne,
/** DOM ready event handler */
ready: jqLiteReady,
/** Remove classes */
removeClass: jqLiteRemoveClass,
/** Check JavaScript variable instance type */
type: jqLiteType,
/** Get or set horizontal scroll position */
scrollLeft: jqLiteScrollLeft,
/** Get or set vertical scroll position */
scrollTop: jqLiteScrollTop
};
},{}],5:[function(require,module,exports){
/**
* MUI CSS/JS utilities module
* @module lib/util
*/
'use strict';
var config = require('../config'),
jqLite = require('./jqLite'),
nodeInsertedCallbacks = [],
scrollLock = 0,
scrollLockCls = 'mui-body--scroll-lock',
scrollLockPos,
_supportsPointerEvents;
/**
* Logging function
*/
function logFn() {
var win = window;
if (config.debug && typeof win.console !== "undefined") {
try {
win.console.log.apply(win.console, arguments);
} catch (a) {
var e = Array.prototype.slice.call(arguments);
win.console.log(e.join("\n"));
}
}
}
/**
* Load CSS text in new stylesheet
* @param {string} cssText - The css text.
*/
function loadStyleFn(cssText) {
var doc = document,
head;
// copied from jQuery
head = doc.head ||
doc.getElementsByTagName('head')[0] ||
doc.documentElement;
var e = doc.createElement('style');
e.type = 'text/css';
if (e.styleSheet) e.styleSheet.cssText = cssText;
else e.appendChild(doc.createTextNode(cssText));
// add to document
head.insertBefore(e, head.firstChild);
return e;
}
/**
* Raise an error
* @param {string} msg - The error message.
*/
function raiseErrorFn(msg, useConsole) {
if (useConsole) {
if (typeof console !== 'undefined') console.error('MUI Warning: ' + msg);
} else {
throw new Error('MUI: ' + msg);
}
}
/**
* Register callbacks on muiNodeInserted event
* @param {function} callbackFn - The callback function.
*/
function onNodeInsertedFn(callbackFn) {
nodeInsertedCallbacks.push(callbackFn);
// initalize listeners
if (nodeInsertedCallbacks._initialized === undefined) {
var doc = document,
events = 'animationstart mozAnimationStart webkitAnimationStart';
jqLite.on(doc, events, animationHandlerFn);
nodeInsertedCallbacks._initialized = true;
}
}
/**
* Execute muiNodeInserted callbacks
* @param {Event} ev - The DOM event.
*/
function animationHandlerFn(ev) {
// check animation name
if (ev.animationName !== 'mui-node-inserted') return;
var el = ev.target;
// iterate through callbacks
for (var i=nodeInsertedCallbacks.length - 1; i >= 0; i--) {
nodeInsertedCallbacks[i](el);
}
}
/**
* Convert Classname object, with class as key and true/false as value, to an
* class string.
* @param {Object} classes The classes
* @return {String} class string
*/
function classNamesFn(classes) {
var cs = '';
for (var i in classes) {
cs += (classes[i]) ? i + ' ' : '';
}
return cs.trim();
}
/**
* Check if client supports pointer events.
*/
function supportsPointerEventsFn() {
// check cache
if (_supportsPointerEvents !== undefined) return _supportsPointerEvents;
var element = document.createElement('x');
element.style.cssText = 'pointer-events:auto';
_supportsPointerEvents = (element.style.pointerEvents === 'auto');
return _supportsPointerEvents;
}
/**
* Create callback closure.
* @param {Object} instance - The object instance.
* @param {String} funcName - The name of the callback function.
*/
function callbackFn(instance, funcName) {
return function() {instance[funcName].apply(instance, arguments);};
}
/**
* Dispatch event.
* @param {Element} element - The DOM element.
* @param {String} eventType - The event type.
* @param {Boolean} bubbles=true - If true, event bubbles.
* @param {Boolean} cancelable=true = If true, event is cancelable
* @param {Object} [data] - Data to add to event object
*/
function dispatchEventFn(element, eventType, bubbles, cancelable, data) {
var ev = document.createEvent('HTMLEvents'),
bubbles = (bubbles !== undefined) ? bubbles : true,
cancelable = (cancelable !== undefined) ? cancelable : true,
k;
ev.initEvent(eventType, bubbles, cancelable);
// add data to event object
if (data) for (k in data) ev[k] = data[k];
// dispatch
if (element) element.dispatchEvent(ev);
return ev;
}
/**
* Turn on window scroll lock.
*/
function enableScrollLockFn() {
// increment counter
scrollLock += 1
// add lock
if (scrollLock === 1) {
var win = window,
doc = document;
scrollLockPos = {left: jqLite.scrollLeft(win), top: jqLite.scrollTop(win)};
jqLite.addClass(doc.body, scrollLockCls);
win.scrollTo(scrollLockPos.left, scrollLockPos.top);
}
}
/**
* Turn off window scroll lock.
* @param {Boolean} resetPos - Reset scroll position to original value.
*/
function disableScrollLockFn(resetPos) {
// ignore
if (scrollLock === 0) return;
// decrement counter
scrollLock -= 1
// remove lock
if (scrollLock === 0) {
var win = window,
doc = document;
jqLite.removeClass(doc.body, scrollLockCls);
if (resetPos) win.scrollTo(scrollLockPos.left, scrollLockPos.top);
}
}
/**
* requestAnimationFrame polyfilled
* @param {Function} callback - The callback function
*/
function requestAnimationFrameFn(callback) {
var fn = window.requestAnimationFrame;
if (fn) fn(callback);
else setTimeout(callback, 0);
}
/**
* Define the module API
*/
module.exports = {
/** Create callback closures */
callback: callbackFn,
/** Classnames object to string */
classNames: classNamesFn,
/** Disable scroll lock */
disableScrollLock: disableScrollLockFn,
/** Dispatch event */
dispatchEvent: dispatchEventFn,
/** Enable scroll lock */
enableScrollLock: enableScrollLockFn,
/** Log messages to the console when debug is turned on */
log: logFn,
/** Load CSS text as new stylesheet */
loadStyle: loadStyleFn,
/** Register muiNodeInserted handler */
onNodeInserted: onNodeInsertedFn,
/** Raise MUI error */
raiseError: raiseErrorFn,
/** Request animation frame */
requestAnimationFrame: requestAnimationFrameFn,
/** Support Pointer Events check */
supportsPointerEvents: supportsPointerEventsFn
};
},{"../config":2,"./jqLite":4}],6:[function(require,module,exports){
/**
* MUI CSS/JS dropdown module
* @module dropdowns
*/
'use strict';
var jqLite = require('./lib/jqLite'),
util = require('./lib/util'),
attrKey = 'data-mui-toggle',
attrSelector = '[data-mui-toggle="dropdown"]',
openClass = 'mui--is-open',
menuClass = 'mui-dropdown__menu';
/**
* Initialize toggle element.
* @param {Element} toggleEl - The toggle element.
*/
function initialize(toggleEl) {
// check flag
if (toggleEl._muiDropdown === true) return;
else toggleEl._muiDropdown = true;
// use type "button" to prevent form submission by default
if (!toggleEl.hasAttribute('type')) toggleEl.type = 'button';
// attach click handler
jqLite.on(toggleEl, 'click', clickHandler);
}
/**
* Handle click events on dropdown toggle element.
* @param {Event} ev - The DOM event
*/
function clickHandler(ev) {
// only left clicks
if (ev.button !== 0) return;
var toggleEl = this;
// exit if toggle button is disabled
if (toggleEl.getAttribute('disabled') !== null) return;
// toggle dropdown
toggleDropdown(toggleEl);
}
/**
* Toggle the dropdown.
* @param {Element} toggleEl - The dropdown toggle element.
*/
function toggleDropdown(toggleEl) {
var wrapperEl = toggleEl.parentNode,
menuEl = toggleEl.nextElementSibling,
doc = wrapperEl.ownerDocument;
// exit if no menu element
if (!menuEl || !jqLite.hasClass(menuEl, menuClass)) {
return util.raiseError('Dropdown menu element not found');
}
// method to close dropdown
function closeDropdownFn() {
jqLite.removeClass(menuEl, openClass);
// remove event handlers
jqLite.off(doc, 'click', closeDropdownFn);
}
// method to open dropdown
function openDropdownFn() {
// position menu element below toggle button
var wrapperRect = wrapperEl.getBoundingClientRect(),
toggleRect = toggleEl.getBoundingClientRect();
var top = toggleRect.top - wrapperRect.top + toggleRect.height;
jqLite.css(menuEl, 'top', top + 'px');
// add open class to wrapper
jqLite.addClass(menuEl, openClass);
// close dropdown when user clicks outside of menu
setTimeout(function() {jqLite.on(doc, 'click', closeDropdownFn);}, 0);
}
// toggle dropdown
if (jqLite.hasClass(menuEl, openClass)) closeDropdownFn();
else openDropdownFn();
}
/** Define module API */
module.exports = {
/** Initialize module listeners */
initListeners: function() {
var doc = document;
// markup elements available when method is called
var elList = doc.querySelectorAll(attrSelector);
for (var i=elList.length - 1; i >= 0; i--) initialize(elList[i]);
// listen for new elements
util.onNodeInserted(function(el) {
if (el.getAttribute(attrKey) === 'dropdown') initialize(el);
});
}
};
},{"./lib/jqLite":4,"./lib/util":5}],7:[function(require,module,exports){
module.exports=require(4)
},{}],8:[function(require,module,exports){
/**
* MUI CSS/JS overlay module
* @module overlay
*/
'use strict';
var util = require('./lib/util'),
jqLite = require('./lib/jqLite'),
overlayId = 'mui-overlay',
bodyClass = 'mui--overflow-hidden',
iosRegex = /(iPad|iPhone|iPod)/g;
/**
* Turn overlay on/off.
* @param {string} action - Turn overlay "on"/"off".
* @param {object} [options]
* @config {boolean} [keyboard] - If true, close when escape key is pressed.
* @config {boolean} [static] - If false, close when backdrop is clicked.
* @config {Function} [onclose] - Callback function to execute on close
* @param {Element} [childElement] - Child element to add to overlay.
*/
function overlayFn(action) {
var overlayEl;
if (action === 'on') {
// extract arguments
var arg, options, childElement;
// pull options and childElement from arguments
for (var i=arguments.length - 1; i > 0; i--) {
arg = arguments[i];
if (jqLite.type(arg) === 'object') options = arg;
if (arg instanceof Element && arg.nodeType === 1) childElement = arg;
}
// option defaults
options = options || {};
if (options.keyboard === undefined) options.keyboard = true;
if (options.static === undefined) options.static = false;
// execute method
overlayEl = overlayOn(options, childElement);
} else if (action === 'off') {
overlayEl = overlayOff();
} else {
// raise error
util.raiseError("Expecting 'on' or 'off'");
}
return overlayEl;
}
/**
* Turn on overlay.
* @param {object} options - Overlay options.
* @param {Element} childElement - The child element.
*/
function overlayOn(options, childElement) {
var bodyEl = document.body,
overlayEl = document.getElementById(overlayId);
// add overlay
util.enableScrollLock();
//jqLite.addClass(bodyEl, bodyClass);
if (!overlayEl) {
// create overlayEl
overlayEl = document.createElement('div');
overlayEl.setAttribute('id', overlayId);
// add child element
if (childElement) overlayEl.appendChild(childElement);
bodyEl.appendChild(overlayEl);
} else {
// remove existing children
while (overlayEl.firstChild) overlayEl.removeChild(overlayEl.firstChild);
// add child element
if (childElement) overlayEl.appendChild(childElement);
}
// iOS bugfix
if (iosRegex.test(navigator.userAgent)) {
jqLite.css(overlayEl, 'cursor', 'pointer');
}
// handle options
if (options.keyboard) addKeyupHandler();
else removeKeyupHandler();
if (options.static) removeClickHandler(overlayEl);
else addClickHandler(overlayEl);
// attach options
overlayEl.muiOptions = options;
return overlayEl;
}
/**
* Turn off overlay.
*/
function overlayOff() {
var overlayEl = document.getElementById(overlayId),
callbackFn;
if (overlayEl) {
// remove children
while (overlayEl.firstChild) overlayEl.removeChild(overlayEl.firstChild);
// remove overlay element
overlayEl.parentNode.removeChild(overlayEl);
// callback reference
callbackFn = overlayEl.muiOptions.onclose;
// remove click handler
removeClickHandler(overlayEl);
}
util.disableScrollLock();
// remove keyup handler
removeKeyupHandler();
// execute callback
if (callbackFn) callbackFn();
return overlayEl;
}
/**
* Add keyup handler.
*/
function addKeyupHandler() {
jqLite.on(document, 'keyup', onKeyup);
}
/**
* Remove keyup handler.
*/
function removeKeyupHandler() {
jqLite.off(document, 'keyup', onKeyup);
}
/**
* Teardown overlay when escape key is pressed.
*/
function onKeyup(ev) {
if (ev.keyCode === 27) overlayOff();
}
/**
* Add click handler.
*/
function addClickHandler(overlayEl) {
jqLite.on(overlayEl, 'click', onClick);
}
/**
* Remove click handler.
*/
function removeClickHandler(overlayEl) {
jqLite.off(overlayEl, 'click', onClick);
}
/**
* Teardown overlay when backdrop is clicked.
*/
function onClick(ev) {
if (ev.target.id === overlayId) overlayOff();
}
/** Define module API */
module.exports = overlayFn;
},{"./lib/jqLite":4,"./lib/util":5}],9:[function(require,module,exports){
/**
* MUI CSS/JS ripple module
* @module ripple
*/
'use strict';
var jqLite = require('./lib/jqLite'),
util = require('./lib/util'),
btnClass = 'mui-btn',
btnFABClass = 'mui-btn--fab',
rippleClass = 'mui-ripple-effect',
supportsTouch = 'ontouchstart' in document.documentElement,
mouseDownEvents = (supportsTouch) ? 'touchstart' : 'mousedown',
mouseUpEvents = (supportsTouch) ? 'touchend' : 'mouseup mouseleave',
animationDuration = 600;
/**
* Add ripple effects to button element.
* @param {Element} buttonEl - The button element.
*/
function initialize(buttonEl) {
// check flag
if (buttonEl._muiRipple === true) return;
else buttonEl._muiRipple = true;
// exit if element is INPUT (doesn't support absolute positioned children)
if (buttonEl.tagName === 'INPUT') return;
// attach event handler
jqLite.on(buttonEl, mouseDownEvents, mouseDownHandler);
}
/**
* MouseDown Event handler.
* @param {Event} ev - The DOM event
*/
function mouseDownHandler(ev) {
// only left clicks
if (ev.type === 'mousedown' && ev.button !== 0) return;
var buttonEl = this;
// exit if button is disabled
if (buttonEl.disabled === true) return;
// add mouseup event to button once
if (!buttonEl.muiMouseUp) {
jqLite.on(buttonEl, mouseUpEvents, mouseUpHandler);
buttonEl.muiMouseUp = true;
}
// create ripple element
var rippleEl = createRippleEl(ev, buttonEl);
buttonEl.appendChild(rippleEl);
// animate in
util.requestAnimationFrame(function() {
jqLite.addClass(rippleEl, 'mui--animate-in mui--active');
});
}
/**
* MouseUp event handler.
* @param {Event} ev - The DOM event
*/
function mouseUpHandler(ev) {
var children = this.children,
i = children.length,
rippleEls = [],
el;
// animate out ripples
while (i--) {
el = children[i];
if (jqLite.hasClass(el, rippleClass)) {
jqLite.addClass(el, 'mui--animate-out');
rippleEls.push(el);
}
}
// remove ripples after animation
if (rippleEls.length) {
setTimeout(function() {
var i = rippleEls.length,
el,
parentNode;
// remove elements
while (i--) {
el = rippleEls[i];
parentNode = el.parentNode;
if (parentNode) parentNode.removeChild(el);
}
}, animationDuration);
}
}
/**
* Create ripple element
* @param {Element} - buttonEl - The button element.
*/
function createRippleEl(ev, buttonEl) {
// get (x, y) position of click
var offset = jqLite.offset(buttonEl),
clickEv = (ev.type === 'touchstart') ? ev.touches[0] : ev,
xPos = clickEv.pageX - offset.left,
yPos = clickEv.pageY - offset.top,
diameter,
radius,
rippleEl;
// calculate diameter
diameter = Math.sqrt(offset.width * offset.width +
offset.height * offset.height) * 2;
// create element
rippleEl = document.createElement('div'),
rippleEl.className = rippleClass;
radius = diameter / 2;
jqLite.css(rippleEl, {
height: diameter + 'px',
width: diameter + 'px',
top: yPos - radius + 'px',
left: xPos - radius + 'px'
});
return rippleEl;
}
/** Define module API */
module.exports = {
/** Initialize module listeners */
initListeners: function() {
var doc = document;
// markup elements available when method is called
var elList = doc.getElementsByClassName(btnClass);
for (var i=elList.length - 1; i >= 0; i--) initialize(elList[i]);
// listen for new elements
util.onNodeInserted(function(el) {
if (jqLite.hasClass(el, btnClass)) initialize(el);
});
}
};
},{"./lib/jqLite":4,"./lib/util":5}],10:[function(require,module,exports){
/**
* MUI CSS/JS select module
* @module forms/select
*/
'use strict';
var jqLite = require('./lib/jqLite'),
util = require('./lib/util'),
formlib = require('./lib/forms'),
wrapperClass = 'mui-select',
cssSelector = '.mui-select > select',
menuClass = 'mui-select__menu',
selectedClass = 'mui--is-selected',
doc = document,
win = window;
/**
* Initialize select element.
* @param {Element} selectEl - The select element.
*/
function initialize(selectEl) {
// check flag
if (selectEl._muiSelect === true) return;
else selectEl._muiSelect = true;
// use default behavior on touch devices
if ('ontouchstart' in doc.documentElement) return;
// initialize element
new Select(selectEl);
}
/**
* Creates a new Select object
* @class
*/
function Select(selectEl) {
// instance variables
this.selectEl = selectEl;
this.wrapperEl = selectEl.parentNode;
this.useDefault = false; // currently unused but let's keep just in case
// attach event handlers
jqLite.on(selectEl, 'mousedown', util.callback(this, 'mousedownHandler'));
jqLite.on(selectEl, 'focus', util.callback(this, 'focusHandler'));
jqLite.on(selectEl, 'click', util.callback(this, 'clickHandler'));
// make wrapper focusable and fix firefox bug
this.wrapperEl.tabIndex = -1;
var callbackFn = util.callback(this, 'wrapperFocusHandler');
jqLite.on(this.wrapperEl, 'focus', callbackFn);
}
/**
* Disable default dropdown on mousedown.
* @param {Event} ev - The DOM event
*/
Select.prototype.mousedownHandler = function(ev) {
if (ev.button !== 0 || this.useDefault === true) return;
ev.preventDefault();
}
/**
* Handle focus event on select element.
* @param {Event} ev - The DOM event
*/
Select.prototype.focusHandler = function(ev) {
// check flag
if (this.useDefault === true) return;
var selectEl = this.selectEl,
wrapperEl = this.wrapperEl,
tabIndex = selectEl.tabIndex,
keydownFn = util.callback(this, 'keydownHandler');
// attach keydown handler
jqLite.on(doc, 'keydown', keydownFn);
// disable tabfocus once
selectEl.tabIndex = -1;
jqLite.one(wrapperEl, 'blur', function() {
selectEl.tabIndex = tabIndex;
jqLite.off(doc, 'keydown', keydownFn);
});
// defer focus to parent
wrapperEl.focus();
}
/**
* Handle keydown events on doc
**/
Select.prototype.keydownHandler = function(ev) {
var keyCode = ev.keyCode;
// spacebar, down, up
if (keyCode === 32 || keyCode === 38 || keyCode === 40) {
// prevent win scroll
ev.preventDefault();
if (this.selectEl.disabled !== true) this.renderMenu();
}
}
/**
* Handle focus event on wrapper element.
*/
Select.prototype.wrapperFocusHandler = function() {
// firefox bugfix
if (this.selectEl.disabled) return this.wrapperEl.blur();
}
/**
* Handle click events on select element.
* @param {Event} ev - The DOM event
*/
Select.prototype.clickHandler = function(ev) {
// only left clicks
if (ev.button !== 0) return;
this.renderMenu();
}
/**
* Render options dropdown.
*/
Select.prototype.renderMenu = function() {
// check and reset flag
if (this.useDefault === true) return this.useDefault = false;
new Menu(this.wrapperEl, this.selectEl);
}
/**
* Creates a new Menu
* @class
*/
function Menu(wrapperEl, selectEl) {
// add scroll lock
util.enableScrollLock();
// instance variables
this.indexMap = {};
this.origIndex = null;
this.currentIndex = null;
this.selectEl = selectEl;
this.menuEl = this._createMenuEl(wrapperEl, selectEl);
this.clickCallbackFn = util.callback(this, 'clickHandler');
this.keydownCallbackFn = util.callback(this, 'keydownHandler');
this.destroyCallbackFn = util.callback(this, 'destroy');
// add to DOM
wrapperEl.appendChild(this.menuEl);
jqLite.scrollTop(this.menuEl, this.menuEl._muiScrollTop);
// blur active element
setTimeout(function() {
// ie10 bugfix
if (doc.activeElement.nodeName.toLowerCase() !== "body") {
doc.activeElement.blur();
}
}, 0);
// attach event handlers
jqLite.on(this.menuEl, 'click', this.clickCallbackFn);
jqLite.on(doc, 'keydown', this.keydownCallbackFn);
jqLite.on(win, 'resize', this.destroyCallbackFn);
// attach event handler after current event loop exits
var fn = this.destroyCallbackFn;
setTimeout(function() {jqLite.on(doc, 'click', fn);}, 0);
}
/**
* Create menu element
* @param {Element} selectEl - The select element
*/
Menu.prototype._createMenuEl = function(wrapperEl, selectEl) {
var menuEl = doc.createElement('div'),
childEls = selectEl.children,
indexNum = 0,
indexMap = this.indexMap,
selectedRow = 0,
loopEl,
rowEl,
optionEls,
inGroup,
i,
iMax,
j,
jMax;
menuEl.className = menuClass;
for (i=0, iMax=childEls.length; i < iMax; i++) {
loopEl = childEls[i];
if (loopEl.tagName === 'OPTGROUP') {
// add row item to menu
rowEl = doc.createElement('div');
rowEl.textContent = loopEl.label;
rowEl.className = 'mui-optgroup__label';
menuEl.appendChild(rowEl);
inGroup = true;
optionEls = loopEl.children;
} else {
inGroup = false;
optionEls = [loopEl];
}
// loop through option elements
for (j=0, jMax=optionEls.length; j < jMax; j++) {
loopEl = optionEls[j];
// add row item to menu
rowEl = doc.createElement('div');
rowEl.textContent = loopEl.textContent;
rowEl._muiIndex = indexNum;
// handle selected options
if (loopEl.selected) {
rowEl.className = selectedClass;
selectedRow = menuEl.children.length;
}
// handle optgroup options
if (inGroup) jqLite.addClass(rowEl, 'mui-optgroup__option');
menuEl.appendChild(rowEl);
// add to index map
indexMap[indexNum] = rowEl;
indexNum += 1;
}
}
// save indices
var selectedIndex = selectEl.selectedIndex;
this.origIndex = selectedIndex;
this.currentIndex = selectedIndex;
// set position
var props = formlib.getMenuPositionalCSS(
wrapperEl,
menuEl.children.length,
selectedRow
);
jqLite.css(menuEl, props);
menuEl._muiScrollTop = props.scrollTop;
return menuEl;
}
/**
* Handle keydown events on doc element.
* @param {Event} ev - The DOM event
*/
Menu.prototype.keydownHandler = function(ev) {
var keyCode = ev.keyCode;
// tab
if (keyCode === 9) return this.destroy();
// escape | up | down | enter
if (keyCode === 27 || keyCode === 40 || keyCode === 38 || keyCode === 13) {
ev.preventDefault();
}
if (keyCode === 27) {
this.destroy();
} else if (keyCode === 40) {
this.increment();
} else if (keyCode === 38) {
this.decrement();
} else if (keyCode === 13) {
this.selectCurrent();
this.destroy();
}
}
/**
* Handle click events on menu element.
* @param {Event} ev - The DOM event
*/
Menu.prototype.clickHandler = function(ev) {
// don't allow events to bubble
ev.stopPropagation();
var index = ev.target._muiIndex;
// ignore clicks on non-items
if (index === undefined) return;
// select option
this.currentIndex = index;
this.selectCurrent();
// destroy menu
this.destroy();
}
/**
* Increment selected item
*/
Menu.prototype.increment = function() {
if (this.currentIndex === this.selectEl.length - 1) return;
// un-select old row
jqLite.removeClass(this.indexMap[this.currentIndex], selectedClass);
// select new row
this.currentIndex += 1;
jqLite.addClass(this.indexMap[this.currentIndex], selectedClass);
}
/**
* Decrement selected item
*/
Menu.prototype.decrement = function() {
if (this.currentIndex === 0) return;
// un-select old row
jqLite.removeClass(this.indexMap[this.currentIndex], selectedClass);
// select new row
this.currentIndex -= 1;
jqLite.addClass(this.indexMap[this.currentIndex], selectedClass);
}
/**
* Select current item
*/
Menu.prototype.selectCurrent = function() {
if (this.currentIndex !== this.origIndex) {
this.selectEl.selectedIndex = this.currentIndex;
// trigger change event
util.dispatchEvent(this.selectEl, 'change');
}
}
/**
* Destroy menu and detach event handlers
*/
Menu.prototype.destroy = function() {
// remove element and focus element
var parentNode = this.menuEl.parentNode;
if (parentNode) parentNode.removeChild(this.menuEl);
this.selectEl.focus();
// remove scroll lock
util.disableScrollLock(true);
// remove event handlers
jqLite.off(this.menuEl, 'click', this.clickCallbackFn);
jqLite.off(doc, 'keydown', this.keydownCallbackFn);
jqLite.off(doc, 'click', this.destroyCallbackFn);
jqLite.off(win, 'resize', this.destroyCallbackFn);
}
/** Define module API */
module.exports = {
/** Initialize module listeners */
initListeners: function() {
// markup elements available when method is called
var elList = doc.querySelectorAll(cssSelector);
for (var i=elList.length - 1; i >= 0; i--) initialize(elList[i]);
// listen for new elements
util.onNodeInserted(function(el) {
if (el.tagName === 'SELECT' &&
jqLite.hasClass(el.parentNode, wrapperClass)) {
initialize(el);
}
});
}
};
},{"./lib/forms":3,"./lib/jqLite":4,"./lib/util":5}],11:[function(require,module,exports){
/**
* MUI CSS/JS tabs module
* @module tabs
*/
'use strict';
var jqLite = require('./lib/jqLite'),
util = require('./lib/util'),
attrKey = 'data-mui-toggle',
attrSelector = '[' + attrKey + '="tab"]',
controlsAttrKey = 'data-mui-controls',
activeClass = 'mui--is-active',
showstartKey = 'mui.tabs.showstart',
showendKey = 'mui.tabs.showend',
hidestartKey = 'mui.tabs.hidestart',
hideendKey = 'mui.tabs.hideend';
/**
* Initialize the toggle element
* @param {Element} toggleEl - The toggle element.
*/
function initialize(toggleEl) {
// check flag
if (toggleEl._muiTabs === true) return;
else toggleEl._muiTabs = true;
// attach click handler
jqLite.on(toggleEl, 'click', clickHandler);
}
/**
* Handle clicks on the toggle element.
* @param {Event} ev - The DOM event.
*/
function clickHandler(ev) {
// only left clicks
if (ev.button !== 0) return;
var toggleEl = this;
// exit if toggle element is disabled
if (toggleEl.getAttribute('disabled') !== null) return;
activateTab(toggleEl);
}
/**
* Activate the tab controlled by the toggle element.
* @param {Element} toggleEl - The toggle element.
*/
function activateTab(currToggleEl) {
var currTabEl = currToggleEl.parentNode,
currPaneId = currToggleEl.getAttribute(controlsAttrKey),
currPaneEl = document.getElementById(currPaneId),
prevTabEl,
prevPaneEl,
prevPaneId,
prevToggleEl,
currData,
prevData,
ev1,
ev2,
cssSelector;
// exit if already active
if (jqLite.hasClass(currTabEl, activeClass)) return;
// raise error if pane doesn't exist
if (!currPaneEl) util.raiseError('Tab pane "' + currPaneId + '" not found');
// get previous pane
prevPaneEl = getActiveSibling(currPaneEl);
prevPaneId = prevPaneEl.id;
// get previous toggle and tab elements
cssSelector = '[' + controlsAttrKey + '="' + prevPaneId + '"]';
prevToggleEl = document.querySelectorAll(cssSelector)[0];
prevTabEl = prevToggleEl.parentNode;
// define event data
currData = {paneId: currPaneId, relatedPaneId: prevPaneId};
prevData = {paneId: prevPaneId, relatedPaneId: currPaneId};
// dispatch 'hidestart', 'showstart' events
ev1 = util.dispatchEvent(prevToggleEl, hidestartKey, true, true, prevData);
ev2 = util.dispatchEvent(currToggleEl, showstartKey, true, true, currData);
// let events bubble
setTimeout(function() {
// exit if either event was canceled
if (ev1.defaultPrevented || ev2.defaultPrevented) return;
// de-activate previous
if (prevTabEl) jqLite.removeClass(prevTabEl, activeClass);
if (prevPaneEl) jqLite.removeClass(prevPaneEl, activeClass);
// activate current
jqLite.addClass(currTabEl, activeClass);
jqLite.addClass(currPaneEl, activeClass);
// dispatch 'hideend', 'showend' events
util.dispatchEvent(prevToggleEl, hideendKey, true, false, prevData);
util.dispatchEvent(currToggleEl, showendKey, true, false, currData);
}, 0);
}
/**
* Get previous active sibling.
* @param {Element} el - The anchor element.
*/
function getActiveSibling(el) {
var elList = el.parentNode.children,
q = elList.length,
activeEl = null,
tmpEl;
while (q-- && !activeEl) {
tmpEl = elList[q];
if (tmpEl !== el && jqLite.hasClass(tmpEl, activeClass)) activeEl = tmpEl
}
return activeEl;
}
/** Define module API */
module.exports = {
/** Initialize module listeners */
initListeners: function() {
// markup elements available when method is called
var elList = document.querySelectorAll(attrSelector);
for (var i=elList.length - 1; i >= 0; i--) initialize(elList[i]);
// TODO: listen for new elements
util.onNodeInserted(function(el) {
if (el.getAttribute(attrKey) === 'tab') initialize(el);
});
},
/** External API */
api: {
activate: function(paneId) {
var cssSelector = '[' + controlsAttrKey + '=' + paneId + ']',
toggleEl = document.querySelectorAll(cssSelector);
if (!toggleEl.length) {
util.raiseError('Tab control for pane "' + paneId + '" not found');
}
activateTab(toggleEl[0]);
}
}
};
},{"./lib/jqLite":4,"./lib/util":5}],12:[function(require,module,exports){
/**
* MUI CSS/JS form-control module
* @module forms/form-control
*/
'use strict';
var jqLite = require('./lib/jqLite'),
util = require('./lib/util'),
cssSelector = '.mui-textfield > input, .mui-textfield > textarea',
emptyClass = 'mui--is-empty',
notEmptyClass = 'mui--is-not-empty',
dirtyClass = 'mui--is-dirty',
floatingLabelClass = 'mui-textfield--float-label';
/**
* Initialize input element.
* @param {Element} inputEl - The input element.
*/
function initialize(inputEl) {
// check flag
if (inputEl._muiTextfield === true) return;
else inputEl._muiTextfield = true;
if (inputEl.value.length) jqLite.addClass(inputEl, notEmptyClass);
else jqLite.addClass(inputEl, emptyClass);
jqLite.on(inputEl, 'input change', inputHandler);
// add dirty class on focus
jqLite.on(inputEl, 'focus', function(){jqLite.addClass(this, dirtyClass);});
}
/**
* Handle input events.
*/
function inputHandler() {
var inputEl = this;
if (inputEl.value.length) {
jqLite.removeClass(inputEl, emptyClass);
jqLite.addClass(inputEl, notEmptyClass);
} else {
jqLite.removeClass(inputEl, notEmptyClass);
jqLite.addClass(inputEl, emptyClass)
}
jqLite.addClass(inputEl, dirtyClass);
}
/** Define module API */
module.exports = {
/** Initialize input elements */
initialize: initialize,
/** Initialize module listeners */
initListeners: function() {
var doc = document;
// markup elements available when method is called
var elList = doc.querySelectorAll(cssSelector);
for (var i=elList.length - 1; i >= 0; i--) initialize(elList[i]);
// listen for new elements
util.onNodeInserted(function(el) {
if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') initialize(el);
});
// add transition css for floating labels
setTimeout(function() {
var css = '.mui-textfield.mui-textfield--float-label > label {' + [
'-webkit-transition',
'-moz-transition',
'-o-transition',
'transition',
''
].join(':all .15s ease-out;') + '}';
util.loadStyle(css);
}, 150);
// pointer-events shim for floating labels
if (util.supportsPointerEvents() === false) {
jqLite.on(document, 'click', function(ev) {
var targetEl = ev.target;
if (targetEl.tagName === 'LABEL' &&
jqLite.hasClass(targetEl.parentNode, floatingLabelClass)) {
var inputEl = targetEl.previousElementSibling;
if (inputEl) inputEl.focus();
}
});
}
}
};
},{"./lib/jqLite":4,"./lib/util":5}]},{},[1]) | joeyparrish/cdnjs | ajax/libs/muicss/0.7.4/js/mui.js | JavaScript | mit | 46,197 |
define([
'INST' /* INST */,
'i18n!submissions',
'jquery' /* $ */,
'str/htmlEscape',
'jquery.ajaxJSON' /* ajaxJSON */,
'jqueryui/dialog',
'jqueryui/progressbar' /* /\.progressbar/ */
], function(INST, I18n, $, htmlEscape) {
INST.downloadSubmissions = function(url) {
var cancelled = false;
var title = ENV.SUBMISSION_DOWNLOAD_DIALOG_TITLE;
title = title || I18n.t('#submissions.download_submissions',
'Download Assignment Submissions');
$("#download_submissions_dialog").dialog({
title: title,
close: function() {
cancelled = true;
}
});
$("#download_submissions_dialog .progress").progressbar({value: 0});
var checkForChange = function() {
if(cancelled || $("#download_submissions_dialog:visible").length == 0) { return; }
$("#download_submissions_dialog .status_loader").css('visibility', 'visible');
var lastProgress = null;
$.ajaxJSON(url, 'GET', {}, function(data) {
if(data && data.attachment) {
var attachment = data.attachment;
if(attachment.workflow_state == 'zipped') {
$("#download_submissions_dialog .progress").progressbar('value', 100);
var message = I18n.t("#submissions.finished_redirecting", "Finished! Redirecting to File...");
var link = "<a href=\"" + htmlEscape(url) + "\"><b> " + htmlEscape(I18n.t("#submissions.click_to_download", "Click here to download %{size_of_file}", {size_of_file: attachment.readable_size})) + "</b></a>"
$("#download_submissions_dialog .status").html(htmlEscape(message) + "<br>" + $.raw(link));
$("#download_submissions_dialog .status_loader").css('visibility', 'hidden');
location.href = url;
return;
} else {
var progress = parseInt(attachment.file_state, 10);
if(isNaN(progress)) { progress = 0; }
progress += 5
$("#download_submissions_dialog .progress").progressbar('value', progress);
var message = null;
if(progress >= 95){
message = I18n.t("#submissions.creating_zip", "Creating zip file...");
} else {
message = I18n.t("#submissions.gathering_files_progress", "Gathering Files (%{progress})...", {progress: I18n.toPercentage(progress)});
}
$("#download_submissions_dialog .status").text(message);
if(progress <= 5 || progress == lastProgress) {
$.ajaxJSON(url + "&compile=1", 'GET', {}, function() {}, function() {});
}
lastProgress = progress;
}
}
$("#download_submissions_dialog .status_loader").css('visibility', 'hidden');
setTimeout(checkForChange, 3000);
}, function(data) {
$("#download_submissions_dialog .status_loader").css('visibility', 'hidden');
setTimeout(checkForChange, 1000);
});
}
checkForChange();
};
});
| dgynn/canvas-lms | public/javascripts/submission_download.js | JavaScript | agpl-3.0 | 2,986 |
//// [decoratorMetadataForMethodWithNoReturnTypeAnnotation01.ts]
declare var decorator: any;
class MyClass {
constructor(test: string, test2: number) {
}
@decorator
doSomething() {
}
}
//// [decoratorMetadataForMethodWithNoReturnTypeAnnotation01.js]
var MyClass = (function () {
function MyClass(test, test2) {
}
MyClass.prototype.doSomething = function () {
};
Object.defineProperty(MyClass.prototype, "doSomething",
__decorate([
decorator,
__metadata('design:type', Function),
__metadata('design:paramtypes', []),
__metadata('design:returntype', void 0)
], MyClass.prototype, "doSomething", Object.getOwnPropertyDescriptor(MyClass.prototype, "doSomething")));
return MyClass;
})();
| sassson/TypeScript | tests/baselines/reference/decoratorMetadataForMethodWithNoReturnTypeAnnotation01.js | JavaScript | apache-2.0 | 820 |
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
var args = slice.call(arguments), resultSelector = args.pop();
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
}
function done (i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
}, observer.onError.bind(observer), function () {
done(i);
}));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
});
};
| misterwolfs/viamonastero | wp-content/themes/roots-master/node_modules/bower/node_modules/insight/node_modules/inquirer/node_modules/rx/src/core/linq/observable/combinelatest.js | JavaScript | gpl-2.0 | 2,286 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.