repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/charcode/html_entity.dart
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source is governed by a // BSD-style license that can be found in the LICENSE file. /// Character codes based on HTML 4.01 character entity names. /// /// For each entity name, e.g., `nbsp`, /// a constant with that name prefixed by `$` is defined /// for that entity's code point. /// /// The HTML entities include the non-ASCII Latin-1 characters and /// symbols, mathematical symbols and Greek litters. /// /// The five characters that are ASCII /// are exported from the `ascii.dart` library. /// /// Three names conflict with `ascii.dart`: `$minus`, `$sub` and `$tilde`. /// If importing both libraries, these three should be hidden from one of the /// libraries. library charcode.htmlentity.dollar_lowercase; export 'ascii.dart' show $quot, $amp, $apos, $lt, $gt; /// no-break space (non-breaking space) const int $nbsp = 0x00A0; /// inverted exclamation mark ('¡') const int $iexcl = 0x00A1; /// cent sign ('¢') const int $cent = 0x00A2; /// pound sign ('£') const int $pound = 0x00A3; /// currency sign ('¤') const int $curren = 0x00A4; /// yen sign (yuan sign) ('¥') const int $yen = 0x00A5; /// broken bar (broken vertical bar) ('¦') const int $brvbar = 0x00A6; /// section sign ('§') const int $sect = 0x00A7; /// diaeresis (spacing diaeresis); see Germanic umlaut ('¨') const int $uml = 0x00A8; /// copyright symbol ('©') const int $copy = 0x00A9; /// feminine ordinal indicator ('ª') const int $ordf = 0x00AA; /// left-pointing double angle quotation mark (left pointing guillemet) ('«') const int $laquo = 0x00AB; /// not sign ('¬') const int $not = 0x00AC; /// soft hyphen (discretionary hyphen) const int $shy = 0x00AD; /// registered sign (registered trademark symbol) ('®') const int $reg = 0x00AE; /// macron (spacing macron, overline, APL overbar) ('¯') const int $macr = 0x00AF; /// degree symbol ('°') const int $deg = 0x00B0; /// plus-minus sign (plus-or-minus sign) ('±') const int $plusmn = 0x00B1; /// superscript two (superscript digit two, squared) ('²') const int $sup2 = 0x00B2; /// superscript three (superscript digit three, cubed) ('³') const int $sup3 = 0x00B3; /// acute accent (spacing acute) ('´') const int $acute = 0x00B4; /// micro sign ('µ') const int $micro = 0x00B5; /// pilcrow sign (paragraph sign) ('¶') const int $para = 0x00B6; /// middle dot (Georgian comma, Greek middle dot) ('·') const int $middot = 0x00B7; /// cedilla (spacing cedilla) ('¸') const int $cedil = 0x00B8; /// superscript one (superscript digit one) ('¹') const int $sup1 = 0x00B9; /// masculine ordinal indicator ('º') const int $ordm = 0x00BA; /// right-pointing double angle quotation mark (right pointing guillemet) ('»') const int $raquo = 0x00BB; /// vulgar fraction one quarter (fraction one quarter) ('¼') const int $frac14 = 0x00BC; /// vulgar fraction one half (fraction one half) ('½') const int $frac12 = 0x00BD; /// vulgar fraction three quarters (fraction three quarters) ('¾') const int $frac34 = 0x00BE; /// inverted question mark (turned question mark) ('¿') const int $iquest = 0x00BF; /// Latin capital letter A with grave accent (Latin capital letter A grave) ('À') const int $Agrave = 0x00C0; /// Latin capital letter A with acute accent ('Á') const int $Aacute = 0x00C1; /// Latin capital letter A with circumflex ('Â') const int $Acirc = 0x00C2; /// Latin capital letter A with tilde ('Ã') const int $Atilde = 0x00C3; /// Latin capital letter A with diaeresis ('Ä') const int $Auml = 0x00C4; /// Latin capital letter A with ring above (Latin capital letter A ring) ('Å') const int $Aring = 0x00C5; /// Latin capital letter AE (Latin capital ligature AE) ('Æ') const int $AElig = 0x00C6; /// Latin capital letter C with cedilla ('Ç') const int $Ccedil = 0x00C7; /// Latin capital letter E with grave accent ('È') const int $Egrave = 0x00C8; /// Latin capital letter E with acute accent ('É') const int $Eacute = 0x00C9; /// Latin capital letter E with circumflex ('Ê') const int $Ecirc = 0x00CA; /// Latin capital letter E with diaeresis ('Ë') const int $Euml = 0x00CB; /// Latin capital letter I with grave accent ('Ì') const int $Igrave = 0x00CC; /// Latin capital letter I with acute accent ('Í') const int $Iacute = 0x00CD; /// Latin capital letter I with circumflex ('Î') const int $Icirc = 0x00CE; /// Latin capital letter I with diaeresis ('Ï') const int $Iuml = 0x00CF; /// Latin capital letter Eth ('Ð') const int $ETH = 0x00D0; /// Latin capital letter N with tilde ('Ñ') const int $Ntilde = 0x00D1; /// Latin capital letter O with grave accent ('Ò') const int $Ograve = 0x00D2; /// Latin capital letter O with acute accent ('Ó') const int $Oacute = 0x00D3; /// Latin capital letter O with circumflex ('Ô') const int $Ocirc = 0x00D4; /// Latin capital letter O with tilde ('Õ') const int $Otilde = 0x00D5; /// Latin capital letter O with diaeresis ('Ö') const int $Ouml = 0x00D6; /// multiplication sign ('×') const int $times = 0x00D7; /// Latin capital letter O with stroke (Latin capital letter O slash) ('Ø') const int $Oslash = 0x00D8; /// Latin capital letter U with grave accent ('Ù') const int $Ugrave = 0x00D9; /// Latin capital letter U with acute accent ('Ú') const int $Uacute = 0x00DA; /// Latin capital letter U with circumflex ('Û') const int $Ucirc = 0x00DB; /// Latin capital letter U with diaeresis ('Ü') const int $Uuml = 0x00DC; /// Latin capital letter Y with acute accent ('Ý') const int $Yacute = 0x00DD; /// Latin capital letter THORN ('Þ') const int $THORN = 0x00DE; /// Latin small letter sharp s (ess-zed); see German Eszett ('ß') const int $szlig = 0x00DF; /// Latin small letter a with grave accent ('à') const int $agrave = 0x00E0; /// Latin small letter a with acute accent ('á') const int $aacute = 0x00E1; /// Latin small letter a with circumflex ('â') const int $acirc = 0x00E2; /// Latin small letter a with tilde ('ã') const int $atilde = 0x00E3; /// Latin small letter a with diaeresis ('ä') const int $auml = 0x00E4; /// Latin small letter a with ring above ('å') const int $aring = 0x00E5; /// Latin small letter ae (Latin small ligature ae) ('æ') const int $aelig = 0x00E6; /// Latin small letter c with cedilla ('ç') const int $ccedil = 0x00E7; /// Latin small letter e with grave accent ('è') const int $egrave = 0x00E8; /// Latin small letter e with acute accent ('é') const int $eacute = 0x00E9; /// Latin small letter e with circumflex ('ê') const int $ecirc = 0x00EA; /// Latin small letter e with diaeresis ('ë') const int $euml = 0x00EB; /// Latin small letter i with grave accent ('ì') const int $igrave = 0x00EC; /// Latin small letter i with acute accent ('í') const int $iacute = 0x00ED; /// Latin small letter i with circumflex ('î') const int $icirc = 0x00EE; /// Latin small letter i with diaeresis ('ï') const int $iuml = 0x00EF; /// Latin small letter eth ('ð') const int $eth = 0x00F0; /// Latin small letter n with tilde ('ñ') const int $ntilde = 0x00F1; /// Latin small letter o with grave accent ('ò') const int $ograve = 0x00F2; /// Latin small letter o with acute accent ('ó') const int $oacute = 0x00F3; /// Latin small letter o with circumflex ('ô') const int $ocirc = 0x00F4; /// Latin small letter o with tilde ('õ') const int $otilde = 0x00F5; /// Latin small letter o with diaeresis ('ö') const int $ouml = 0x00F6; /// division sign (obelus) ('÷') const int $divide = 0x00F7; /// Latin small letter o with stroke (Latin small letter o slash) ('ø') const int $oslash = 0x00F8; /// Latin small letter u with grave accent ('ù') const int $ugrave = 0x00F9; /// Latin small letter u with acute accent ('ú') const int $uacute = 0x00FA; /// Latin small letter u with circumflex ('û') const int $ucirc = 0x00FB; /// Latin small letter u with diaeresis ('ü') const int $uuml = 0x00FC; /// Latin small letter y with acute accent ('ý') const int $yacute = 0x00FD; /// Latin small letter thorn ('þ') const int $thorn = 0x00FE; /// Latin small letter y with diaeresis ('ÿ') const int $yuml = 0x00FF; /// Latin capital ligature oe ('Œ') const int $OElig = 0x0152; /// Latin small ligature oe ('œ') const int $oelig = 0x0153; /// Latin capital letter s with caron ('Š') const int $Scaron = 0x0160; /// Latin small letter s with caron ('š') const int $scaron = 0x0161; /// Latin capital letter y with diaeresis ('Ÿ') const int $Yuml = 0x0178; /// Latin small letter f with hook (function, florin) ('ƒ') const int $fnof = 0x0192; /// modifier letter circumflex accent ('ˆ') const int $circ = 0x02C6; /// small tilde ('˜') const int $tilde = 0x02DC; /// Greek capital letter Alpha ('Α') const int $Alpha = 0x0391; /// Greek capital letter Beta ('Β') const int $Beta = 0x0392; /// Greek capital letter Gamma ('Γ') const int $Gamma = 0x0393; /// Greek capital letter Delta ('Δ') const int $Delta = 0x0394; /// Greek capital letter Epsilon ('Ε') const int $Epsilon = 0x0395; /// Greek capital letter Zeta ('Ζ') const int $Zeta = 0x0396; /// Greek capital letter Eta ('Η') const int $Eta = 0x0397; /// Greek capital letter Theta ('Θ') const int $Theta = 0x0398; /// Greek capital letter Iota ('Ι') const int $Iota = 0x0399; /// Greek capital letter Kappa ('Κ') const int $Kappa = 0x039A; /// Greek capital letter Lambda ('Λ') const int $Lambda = 0x039B; /// Greek capital letter Mu ('Μ') const int $Mu = 0x039C; /// Greek capital letter Nu ('Ν') const int $Nu = 0x039D; /// Greek capital letter Xi ('Ξ') const int $Xi = 0x039E; /// Greek capital letter Omicron ('Ο') const int $Omicron = 0x039F; /// Greek capital letter Pi ('Π') const int $Pi = 0x03A0; /// Greek capital letter Rho ('Ρ') const int $Rho = 0x03A1; /// Greek capital letter Sigma ('Σ') const int $Sigma = 0x03A3; /// Greek capital letter Tau ('Τ') const int $Tau = 0x03A4; /// Greek capital letter Upsilon ('Υ') const int $Upsilon = 0x03A5; /// Greek capital letter Phi ('Φ') const int $Phi = 0x03A6; /// Greek capital letter Chi ('Χ') const int $Chi = 0x03A7; /// Greek capital letter Psi ('Ψ') const int $Psi = 0x03A8; /// Greek capital letter Omega ('Ω') const int $Omega = 0x03A9; /// Greek small letter alpha ('α') const int $alpha = 0x03B1; /// Greek small letter beta ('β') const int $beta = 0x03B2; /// Greek small letter gamma ('γ') const int $gamma = 0x03B3; /// Greek small letter delta ('δ') const int $delta = 0x03B4; /// Greek small letter epsilon ('ε') const int $epsilon = 0x03B5; /// Greek small letter zeta ('ζ') const int $zeta = 0x03B6; /// Greek small letter eta ('η') const int $eta = 0x03B7; /// Greek small letter theta ('θ') const int $theta = 0x03B8; /// Greek small letter iota ('ι') const int $iota = 0x03B9; /// Greek small letter kappa ('κ') const int $kappa = 0x03BA; /// Greek small letter lambda ('λ') const int $lambda = 0x03BB; /// Greek small letter mu ('μ') const int $mu = 0x03BC; /// Greek small letter nu ('ν') const int $nu = 0x03BD; /// Greek small letter xi ('ξ') const int $xi = 0x03BE; /// Greek small letter omicron ('ο') const int $omicron = 0x03BF; /// Greek small letter pi ('π') const int $pi = 0x03C0; /// Greek small letter rho ('ρ') const int $rho = 0x03C1; /// Greek small letter final sigma ('ς') const int $sigmaf = 0x03C2; /// Greek small letter sigma ('σ') const int $sigma = 0x03C3; /// Greek small letter tau ('τ') const int $tau = 0x03C4; /// Greek small letter upsilon ('υ') const int $upsilon = 0x03C5; /// Greek small letter phi ('φ') const int $phi = 0x03C6; /// Greek small letter chi ('χ') const int $chi = 0x03C7; /// Greek small letter psi ('ψ') const int $psi = 0x03C8; /// Greek small letter omega ('ω') const int $omega = 0x03C9; /// Greek theta symbol ('ϑ') const int $thetasym = 0x03D1; /// Greek Upsilon with hook symbol ('ϒ') const int $upsih = 0x03D2; /// Greek pi symbol ('ϖ') const int $piv = 0x03D6; /// en space const int $ensp = 0x2002; /// em space const int $emsp = 0x2003; /// thin space const int $thinsp = 0x2009; /// zero-width non-joiner const int $zwnj = 0x200C; /// zero-width joiner const int $zwj = 0x200D; /// left-to-right mark const int $lrm = 0x200E; /// right-to-left mark const int $rlm = 0x200F; /// en dash ('–') const int $ndash = 0x2013; /// em dash ('—') const int $mdash = 0x2014; /// left single quotation mark ('‘') const int $lsquo = 0x2018; /// right single quotation mark ('’') const int $rsquo = 0x2019; /// single low-9 quotation mark ('‚') const int $sbquo = 0x201A; /// left double quotation mark ('“') const int $ldquo = 0x201C; /// right double quotation mark ('”') const int $rdquo = 0x201D; /// double low-9 quotation mark ('„') const int $bdquo = 0x201E; /// dagger, obelisk ('†') const int $dagger = 0x2020; /// double dagger, double obelisk ('‡') const int $Dagger = 0x2021; /// bullet (black small circle) ('•') const int $bull = 0x2022; /// horizontal ellipsis (three dot leader) ('…') const int $hellip = 0x2026; /// per mille sign ('‰') const int $permil = 0x2030; /// prime (minutes, feet) ('′') const int $prime = 0x2032; /// double prime (seconds, inches) ('″') const int $Prime = 0x2033; /// single left-pointing angle quotation mark ('‹') const int $lsaquo = 0x2039; /// single right-pointing angle quotation mark ('›') const int $rsaquo = 0x203A; /// overline (spacing overscore) ('‾') const int $oline = 0x203E; /// fraction slash (solidus) ('⁄') const int $frasl = 0x2044; /// euro sign ('€') const int $euro = 0x20AC; /// black-letter capital I (imaginary part) ('ℑ') const int $image = 0x2111; /// script capital P (power set, Weierstrass p) ('℘') const int $weierp = 0x2118; /// black-letter capital R (real part symbol) ('ℜ') const int $real = 0x211C; /// trademark symbol ('™') const int $trade = 0x2122; /// alef symbol (first transfinite cardinal) ('ℵ') const int $alefsym = 0x2135; /// leftwards arrow ('←') const int $larr = 0x2190; /// upwards arrow ('↑') const int $uarr = 0x2191; /// rightwards arrow ('→') const int $rarr = 0x2192; /// downwards arrow ('↓') const int $darr = 0x2193; /// left right arrow ('↔') const int $harr = 0x2194; /// downwards arrow with corner leftwards (carriage return) ('↵') const int $crarr = 0x21B5; /// leftwards double arrow ('⇐') const int $lArr = 0x21D0; /// upwards double arrow ('⇑') const int $uArr = 0x21D1; /// rightwards double arrow ('⇒') const int $rArr = 0x21D2; /// downwards double arrow ('⇓') const int $dArr = 0x21D3; /// left right double arrow ('⇔') const int $hArr = 0x21D4; /// for all ('∀') const int $forall = 0x2200; /// partial differential ('∂') const int $part = 0x2202; /// there exists ('∃') const int $exist = 0x2203; /// empty set (null set); see also U+8960, ⌀ ('∅') const int $empty = 0x2205; /// del or nabla (vector differential operator) ('∇') const int $nabla = 0x2207; /// element of ('∈') const int $isin = 0x2208; /// not an element of ('∉') const int $notin = 0x2209; /// contains as member ('∋') const int $ni = 0x220B; /// n-ary product (product sign) ('∏') const int $prod = 0x220F; /// n-ary summation ('∑') const int $sum = 0x2211; /// minus sign ('−') const int $minus = 0x2212; /// asterisk operator ('∗') const int $lowast = 0x2217; /// square root (radical sign) ('√') const int $radic = 0x221A; /// proportional to ('∝') const int $prop = 0x221D; /// infinity ('∞') const int $infin = 0x221E; /// angle ('∠') const int $ang = 0x2220; /// logical and (wedge) ('∧') const int $and = 0x2227; /// logical or (vee) ('∨') const int $or = 0x2228; /// intersection (cap) ('∩') const int $cap = 0x2229; /// union (cup) ('∪') const int $cup = 0x222A; /// integral ('∫') const int $int = 0x222B; /// therefore sign ('∴') const int $there4 = 0x2234; /// tilde operator (varies with, similar to) ('∼') const int $sim = 0x223C; /// congruent to ('≅') const int $cong = 0x2245; /// almost equal to (asymptotic to) ('≈') const int $asymp = 0x2248; /// not equal to ('≠') const int $ne = 0x2260; /// identical to; sometimes used for 'equivalent to' ('≡') const int $equiv = 0x2261; /// less-than or equal to ('≤') const int $le = 0x2264; /// greater-than or equal to ('≥') const int $ge = 0x2265; /// subset of ('⊂') const int $sub = 0x2282; /// superset of ('⊃') const int $sup = 0x2283; /// not a subset of ('⊄') const int $nsub = 0x2284; /// subset of or equal to ('⊆') const int $sube = 0x2286; /// superset of or equal to ('⊇') const int $supe = 0x2287; /// circled plus (direct sum) ('⊕') const int $oplus = 0x2295; /// circled times (vector product) ('⊗') const int $otimes = 0x2297; /// up tack (orthogonal to, perpendicular) ('⊥') const int $perp = 0x22A5; /// dot operator ('⋅') const int $sdot = 0x22C5; /// vertical ellipsis ('⋮') const int $vellip = 0x22EE; /// left ceiling (APL upstile) ('⌈') const int $lceil = 0x2308; /// right ceiling ('⌉') const int $rceil = 0x2309; /// left floor (APL downstile) ('⌊') const int $lfloor = 0x230A; /// right floor ('⌋') const int $rfloor = 0x230B; /// left-pointing angle bracket (bra) ('〈') const int $lang = 0x2329; /// right-pointing angle bracket (ket) ('〉') const int $rang = 0x232A; /// lozenge ('◊') const int $loz = 0x25CA; /// black spade suit ('♠') const int $spades = 0x2660; /// black club suit (shamrock) ('♣') const int $clubs = 0x2663; /// black heart suit (valentine) ('♥') const int $hearts = 0x2665; /// black diamond suit ('♦') const int $diams = 0x2666;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/logging/logging.dart
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'src/log_record.dart'; import 'src/logger.dart'; export 'src/level.dart'; export 'src/log_record.dart'; export 'src/logger.dart'; /// Handler callback to process log entries as they are added to a [Logger]. @Deprecated('Will be removed in 1.0.0') typedef LoggerHandler = void Function(LogRecord record);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/logging
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/logging/src/logger.dart
import 'dart:async'; import 'dart:collection'; import 'level.dart'; import 'log_record.dart'; /// Whether to allow fine-grain logging and configuration of loggers in a /// hierarchy. /// /// When false, all hierarchical logging instead is merged in the root logger. bool hierarchicalLoggingEnabled = false; /// Automatically record stack traces for any message of this level or above. /// /// Because this is expensive, this is off by default. Level recordStackTraceAtLevel = Level.OFF; /// The default [Level]. const defaultLevel = Level.INFO; /// Use a [Logger] to log debug messages. /// /// [Logger]s are named using a hierarchical dot-separated name convention. class Logger { /// Simple name of this logger. final String name; /// The full name of this logger, which includes the parent's full name. String get fullName => (parent == null || parent.name == '') ? name : '${parent.fullName}.$name'; /// Parent of this logger in the hierarchy of loggers. final Logger parent; /// Logging [Level] used for entries generated on this logger. Level _level; final Map<String, Logger> _children; /// Children in the hierarchy of loggers, indexed by their simple names. final Map<String, Logger> children; /// Controller used to notify when log entries are added to this logger. StreamController<LogRecord> _controller; /// Singleton constructor. Calling `new Logger(name)` will return the same /// actual instance whenever it is called with the same string name. factory Logger(String name) => _loggers.putIfAbsent(name, () => Logger._named(name)); /// Creates a new detached [Logger]. /// /// Returns a new [Logger] instance (unlike `new Logger`, which returns a /// [Logger] singleton), which doesn't have any parent or children, /// and is not a part of the global hierarchical loggers structure. /// /// It can be useful when you just need a local short-living logger, /// which you'd like to be garbage-collected later. factory Logger.detached(String name) => Logger._internal(name, null, <String, Logger>{}); factory Logger._named(String name) { if (name.startsWith('.')) { throw ArgumentError("name shouldn't start with a '.'"); } // Split hierarchical names (separated with '.'). var dot = name.lastIndexOf('.'); Logger parent; String thisName; if (dot == -1) { if (name != '') parent = Logger(''); thisName = name; } else { parent = Logger(name.substring(0, dot)); thisName = name.substring(dot + 1); } return Logger._internal(thisName, parent, <String, Logger>{}); } Logger._internal(this.name, this.parent, Map<String, Logger> children) : _children = children, children = UnmodifiableMapView(children) { if (parent == null) { _level = defaultLevel; } else { parent._children[name] = this; } } /// Effective level considering the levels established in this logger's /// parents (when [hierarchicalLoggingEnabled] is true). Level get level { Level effectiveLevel; if (parent == null) { // We're either the root logger or a detached logger. Return our own // level. effectiveLevel = _level; } else if (!hierarchicalLoggingEnabled) { effectiveLevel = root._level; } else { effectiveLevel = _level ?? parent.level; } assert(effectiveLevel != null); return effectiveLevel; } /// Override the level for this particular [Logger] and its children. set level(Level value) { if (!hierarchicalLoggingEnabled && parent != null) { throw UnsupportedError( 'Please set "hierarchicalLoggingEnabled" to true if you want to ' 'change the level on a non-root logger.'); } _level = value; } /// Returns a stream of messages added to this [Logger]. /// /// You can listen for messages using the standard stream APIs, for instance: /// /// ```dart /// logger.onRecord.listen((record) { ... }); /// ``` Stream<LogRecord> get onRecord => _getStream(); void clearListeners() { if (hierarchicalLoggingEnabled || parent == null) { if (_controller != null) { _controller.close(); _controller = null; } } else { root.clearListeners(); } } /// Whether a message for [value]'s level is loggable in this logger. bool isLoggable(Level value) => (value >= level); /// Adds a log record for a [message] at a particular [logLevel] if /// `isLoggable(logLevel)` is true. /// /// Use this method to create log entries for user-defined levels. To record a /// message at a predefined level (e.g. [Level.INFO], [Level.WARNING], etc) /// you can use their specialized methods instead (e.g. [info], [warning], /// etc). /// /// If [message] is a [Function], it will be lazy evaluated. Additionally, if /// [message] or its evaluated value is not a [String], then 'toString()' will /// be called on the object and the result will be logged. The log record will /// contain a field holding the original object. /// /// The log record will also contain a field for the zone in which this call /// was made. This can be advantageous if a log listener wants to handler /// records of different zones differently (e.g. group log records by HTTP /// request if each HTTP request handler runs in it's own zone). void log(Level logLevel, message, [Object error, StackTrace stackTrace, Zone zone]) { Object object; if (isLoggable(logLevel)) { if (message is Function) { message = message(); } String msg; if (message is String) { msg = message; } else { msg = message.toString(); object = message; } if (stackTrace == null && logLevel >= recordStackTraceAtLevel) { stackTrace = StackTrace.current; error ??= 'autogenerated stack trace for $logLevel $msg'; } zone ??= Zone.current; var record = LogRecord(logLevel, msg, fullName, error, stackTrace, zone, object); if (parent == null) { _publish(record); } else if (!hierarchicalLoggingEnabled) { root._publish(record); } else { var target = this; while (target != null) { target._publish(record); target = target.parent; } } } } /// Log message at level [Level.FINEST]. void finest(message, [Object error, StackTrace stackTrace]) => log(Level.FINEST, message, error, stackTrace); /// Log message at level [Level.FINER]. void finer(message, [Object error, StackTrace stackTrace]) => log(Level.FINER, message, error, stackTrace); /// Log message at level [Level.FINE]. void fine(message, [Object error, StackTrace stackTrace]) => log(Level.FINE, message, error, stackTrace); /// Log message at level [Level.CONFIG]. void config(message, [Object error, StackTrace stackTrace]) => log(Level.CONFIG, message, error, stackTrace); /// Log message at level [Level.INFO]. void info(message, [Object error, StackTrace stackTrace]) => log(Level.INFO, message, error, stackTrace); /// Log message at level [Level.WARNING]. void warning(message, [Object error, StackTrace stackTrace]) => log(Level.WARNING, message, error, stackTrace); /// Log message at level [Level.SEVERE]. void severe(message, [Object error, StackTrace stackTrace]) => log(Level.SEVERE, message, error, stackTrace); /// Log message at level [Level.SHOUT]. void shout(message, [Object error, StackTrace stackTrace]) => log(Level.SHOUT, message, error, stackTrace); Stream<LogRecord> _getStream() { if (hierarchicalLoggingEnabled || parent == null) { _controller ??= StreamController<LogRecord>.broadcast(sync: true); return _controller.stream; } else { return root._getStream(); } } void _publish(LogRecord record) { if (_controller != null) { _controller.add(record); } } /// Top-level root [Logger]. static final Logger root = Logger(''); /// All [Logger]s in the system. static final Map<String, Logger> _loggers = <String, Logger>{}; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/logging
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/logging/src/log_record.dart
import 'dart:async'; import 'level.dart'; import 'logger.dart'; /// A log entry representation used to propagate information from [Logger] to /// individual handlers. class LogRecord { final Level level; final String message; /// Non-string message passed to Logger. final Object object; /// Logger where this record is stored. final String loggerName; /// Time when this record was created. final DateTime time; /// Unique sequence number greater than all log records created before it. final int sequenceNumber; static int _nextNumber = 0; /// Associated error (if any) when recording errors messages. final Object error; /// Associated stackTrace (if any) when recording errors messages. final StackTrace stackTrace; /// Zone of the calling code which resulted in this LogRecord. final Zone zone; LogRecord(this.level, this.message, this.loggerName, [this.error, this.stackTrace, this.zone, this.object]) : time = DateTime.now(), sequenceNumber = LogRecord._nextNumber++; @override String toString() => '[${level.name}] $loggerName: $message'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/logging
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/logging/src/level.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// [Level]s to control logging output. Logging can be enabled to include all /// levels above certain [Level]. [Level]s are ordered using an integer /// value [Level.value]. The predefined [Level] constants below are sorted as /// follows (in descending order): [Level.SHOUT], [Level.SEVERE], /// [Level.WARNING], [Level.INFO], [Level.CONFIG], [Level.FINE], [Level.FINER], /// [Level.FINEST], and [Level.ALL]. /// /// We recommend using one of the predefined logging levels. If you define your /// own level, make sure you use a value between those used in [Level.ALL] and /// [Level.OFF]. class Level implements Comparable<Level> { final String name; /// Unique value for this level. Used to order levels, so filtering can /// exclude messages whose level is under certain value. final int value; const Level(this.name, this.value); /// Special key to turn on logging for all levels ([value] = 0). static const Level ALL = Level('ALL', 0); /// Special key to turn off all logging ([value] = 2000). static const Level OFF = Level('OFF', 2000); /// Key for highly detailed tracing ([value] = 300). static const Level FINEST = Level('FINEST', 300); /// Key for fairly detailed tracing ([value] = 400). static const Level FINER = Level('FINER', 400); /// Key for tracing information ([value] = 500). static const Level FINE = Level('FINE', 500); /// Key for static configuration messages ([value] = 700). static const Level CONFIG = Level('CONFIG', 700); /// Key for informational messages ([value] = 800). static const Level INFO = Level('INFO', 800); /// Key for potential problems ([value] = 900). static const Level WARNING = Level('WARNING', 900); /// Key for serious failures ([value] = 1000). static const Level SEVERE = Level('SEVERE', 1000); /// Key for extra debugging loudness ([value] = 1200). static const Level SHOUT = Level('SHOUT', 1200); static const List<Level> LEVELS = [ ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, SHOUT, OFF ]; @override bool operator ==(Object other) => other is Level && value == other.value; bool operator <(Level other) => value < other.value; bool operator <=(Level other) => value <= other.value; bool operator >(Level other) => value > other.value; bool operator >=(Level other) => value >= other.value; @override int compareTo(Level other) => value - other.value; @override int get hashCode => value; @override String toString() => name; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_parser/http_parser.dart
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. export 'src/authentication_challenge.dart'; export 'src/case_insensitive_map.dart'; export 'src/chunked_coding.dart'; export 'src/http_date.dart'; export 'src/media_type.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_parser
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_parser/src/chunked_coding.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:convert'; import 'chunked_coding/decoder.dart'; import 'chunked_coding/encoder.dart'; export 'chunked_coding/decoder.dart' hide chunkedCodingDecoder; export 'chunked_coding/encoder.dart' hide chunkedCodingEncoder; /// The canonical instance of [ChunkedCodingCodec]. const chunkedCoding = ChunkedCodingCodec._(); /// A codec that encodes and decodes the [chunked transfer coding][]. /// /// [chunked transfer coding]: https://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.6.1 /// /// The [encoder] creates a *single* chunked message for each call to /// [ChunkedCodingEncoder.convert] or /// [ChunkedCodingEncoder.startChunkedConversion]. This means that it will /// always add an end-of-message footer once conversion has finished. It doesn't /// support generating chunk extensions or trailing headers. /// /// Similarly, the [decoder] decodes a *single* chunked message into a stream of /// byte arrays that must be concatenated to get the full list (like most Dart /// byte streams). It doesn't support decoding a stream that contains multiple /// chunked messages, nor does it support a stream that contains chunked data /// mixed with other types of data. /// /// Currently, [decoder] will fail to parse chunk extensions and trailing /// headers. It may be updated to silently ignore them in the future. class ChunkedCodingCodec extends Codec<List<int>, List<int>> { @override ChunkedCodingEncoder get encoder => chunkedCodingEncoder; @override ChunkedCodingDecoder get decoder => chunkedCodingDecoder; const ChunkedCodingCodec._(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_parser
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_parser/src/media_type.dart
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:collection/collection.dart'; import 'package:string_scanner/string_scanner.dart'; import 'case_insensitive_map.dart'; import 'scan.dart'; import 'utils.dart'; /// A regular expression matching a character that needs to be backslash-escaped /// in a quoted string. final _escapedChar = RegExp(r'["\x00-\x1F\x7F]'); /// A class representing an HTTP media type, as used in Accept and Content-Type /// headers. /// /// This is immutable; new instances can be created based on an old instance by /// calling [change]. class MediaType { /// The primary identifier of the MIME type. /// /// This is always lowercase. final String type; /// The secondary identifier of the MIME type. /// /// This is always lowercase. final String subtype; /// The parameters to the media type. /// /// This map is immutable and the keys are case-insensitive. final Map<String, String> parameters; /// The media type's MIME type. String get mimeType => '$type/$subtype'; /// Parses a media type. /// /// This will throw a FormatError if the media type is invalid. factory MediaType.parse(String mediaType) => // This parsing is based on sections 3.6 and 3.7 of the HTTP spec: // http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html. wrapFormatException('media type', mediaType, () { final scanner = StringScanner(mediaType); scanner.scan(whitespace); scanner.expect(token); final type = scanner.lastMatch[0]; scanner.expect('/'); scanner.expect(token); final subtype = scanner.lastMatch[0]; scanner.scan(whitespace); final parameters = <String, String>{}; while (scanner.scan(';')) { scanner.scan(whitespace); scanner.expect(token); final attribute = scanner.lastMatch[0]; scanner.expect('='); String value; if (scanner.scan(token)) { value = scanner.lastMatch[0]; } else { value = expectQuotedString(scanner); } scanner.scan(whitespace); parameters[attribute] = value; } scanner.expectDone(); return MediaType(type, subtype, parameters); }); MediaType(String type, String subtype, [Map<String, String> parameters]) : type = type.toLowerCase(), subtype = subtype.toLowerCase(), parameters = UnmodifiableMapView( parameters == null ? {} : CaseInsensitiveMap.from(parameters)); /// Returns a copy of this [MediaType] with some fields altered. /// /// [type] and [subtype] alter the corresponding fields. [mimeType] is parsed /// and alters both the [type] and [subtype] fields; it cannot be passed along /// with [type] or [subtype]. /// /// [parameters] overwrites and adds to the corresponding field. If /// [clearParameters] is passed, it replaces the corresponding field entirely /// instead. MediaType change( {String type, String subtype, String mimeType, Map<String, String> parameters, bool clearParameters = false}) { if (mimeType != null) { if (type != null) { throw ArgumentError('You may not pass both [type] and [mimeType].'); } else if (subtype != null) { throw ArgumentError('You may not pass both [subtype] and ' '[mimeType].'); } final segments = mimeType.split('/'); if (segments.length != 2) { throw FormatException('Invalid mime type "$mimeType".'); } type = segments[0]; subtype = segments[1]; } type ??= this.type; subtype ??= this.subtype; parameters ??= {}; if (!clearParameters) { final newParameters = parameters; parameters = Map.from(this.parameters); parameters.addAll(newParameters); } return MediaType(type, subtype, parameters); } /// Converts the media type to a string. /// /// This will produce a valid HTTP media type. @override String toString() { final buffer = StringBuffer()..write(type)..write('/')..write(subtype); parameters.forEach((attribute, value) { buffer.write('; $attribute='); if (nonToken.hasMatch(value)) { buffer ..write('"') ..write( value.replaceAllMapped(_escapedChar, (match) => '\\${match[0]}')) ..write('"'); } else { buffer.write(value); } }); return buffer.toString(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_parser
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_parser/src/scan.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:string_scanner/string_scanner.dart'; /// An HTTP token. final token = RegExp(r'[^()<>@,;:"\\/[\]?={} \t\x00-\x1F\x7F]+'); /// Linear whitespace. final _lws = RegExp(r'(?:\r\n)?[ \t]+'); /// A quoted string. final _quotedString = RegExp(r'"(?:[^"\x00-\x1F\x7F]|\\.)*"'); /// A quoted pair. final _quotedPair = RegExp(r'\\(.)'); /// A character that is *not* a valid HTTP token. final nonToken = RegExp(r'[()<>@,;:"\\/\[\]?={} \t\x00-\x1F\x7F]'); /// A regular expression matching any number of [_lws] productions in a row. final whitespace = RegExp('(?:${_lws.pattern})*'); /// Parses a list of elements, as in `1#element` in the HTTP spec. /// /// [scanner] is used to parse the elements, and [parseElement] is used to parse /// each one individually. The values returned by [parseElement] are collected /// in a list and returned. /// /// Once this is finished, [scanner] will be at the next non-LWS character in /// the string, or the end of the string. List<T> parseList<T>(StringScanner scanner, T Function() parseElement) { final result = <T>[]; // Consume initial empty values. while (scanner.scan(',')) { scanner.scan(whitespace); } result.add(parseElement()); scanner.scan(whitespace); while (scanner.scan(',')) { scanner.scan(whitespace); // Empty elements are allowed, but excluded from the results. if (scanner.matches(',') || scanner.isDone) continue; result.add(parseElement()); scanner.scan(whitespace); } return result; } /// Parses a single quoted string, and returns its contents. /// /// If [name] is passed, it's used to describe the expected value if it's not /// found. String expectQuotedString(StringScanner scanner, {String name}) { name ??= 'quoted string'; scanner.expect(_quotedString, name: name); final string = scanner.lastMatch[0]; return string .substring(1, string.length - 1) .replaceAllMapped(_quotedPair, (match) => match[1]); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_parser
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_parser/src/authentication_challenge.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:collection'; import 'package:string_scanner/string_scanner.dart'; import 'case_insensitive_map.dart'; import 'scan.dart'; import 'utils.dart'; /// A single challenge in a WWW-Authenticate header, parsed as per [RFC 2617][]. /// /// [RFC 2617]: http://tools.ietf.org/html/rfc2617 /// /// Each WWW-Authenticate header contains one or more challenges, representing /// valid ways to authenticate with the server. class AuthenticationChallenge { /// The scheme describing the type of authentication that's required, for /// example "basic" or "digest". /// /// This is normalized to always be lower-case. final String scheme; /// The parameters describing how to authenticate. /// /// The semantics of these parameters are scheme-specific. The keys of this /// map are case-insensitive. final Map<String, String> parameters; /// Parses a WWW-Authenticate header, which should contain one or more /// challenges. /// /// Throws a [FormatException] if the header is invalid. static List<AuthenticationChallenge> parseHeader(String header) => wrapFormatException('authentication header', header, () { final scanner = StringScanner(header); scanner.scan(whitespace); final challenges = parseList(scanner, () { final scheme = _scanScheme(scanner, whitespaceName: '" " or "="'); // Manually parse the inner list. We need to do some lookahead to // disambiguate between an auth param and another challenge. final params = <String, String>{}; // Consume initial empty values. while (scanner.scan(',')) { scanner.scan(whitespace); } _scanAuthParam(scanner, params); var beforeComma = scanner.position; while (scanner.scan(',')) { scanner.scan(whitespace); // Empty elements are allowed, but excluded from the results. if (scanner.matches(',') || scanner.isDone) continue; scanner.expect(token, name: 'a token'); final name = scanner.lastMatch[0]; scanner.scan(whitespace); // If there's no "=", then this is another challenge rather than a // parameter for the current challenge. if (!scanner.scan('=')) { scanner.position = beforeComma; break; } scanner.scan(whitespace); if (scanner.scan(token)) { params[name] = scanner.lastMatch[0]; } else { params[name] = expectQuotedString(scanner, name: 'a token or a quoted string'); } scanner.scan(whitespace); beforeComma = scanner.position; } return AuthenticationChallenge(scheme, params); }); scanner.expectDone(); return challenges; }); /// Parses a single WWW-Authenticate challenge value. /// /// Throws a [FormatException] if the challenge is invalid. factory AuthenticationChallenge.parse(String challenge) => wrapFormatException('authentication challenge', challenge, () { final scanner = StringScanner(challenge); scanner.scan(whitespace); final scheme = _scanScheme(scanner); final params = <String, String>{}; parseList(scanner, () => _scanAuthParam(scanner, params)); scanner.expectDone(); return AuthenticationChallenge(scheme, params); }); /// Scans a single scheme name and asserts that it's followed by a space. /// /// If [whitespaceName] is passed, it's used as the name for exceptions thrown /// due to invalid trailing whitespace. static String _scanScheme(StringScanner scanner, {String whitespaceName}) { scanner.expect(token, name: 'a token'); final scheme = scanner.lastMatch[0].toLowerCase(); scanner.scan(whitespace); // The spec specifically requires a space between the scheme and its // params. if (scanner.lastMatch == null || !scanner.lastMatch[0].contains(' ')) { scanner.expect(' ', name: whitespaceName); } return scheme; } /// Scans a single authentication parameter and stores its result in [params]. static void _scanAuthParam(StringScanner scanner, Map params) { scanner.expect(token, name: 'a token'); final name = scanner.lastMatch[0]; scanner.scan(whitespace); scanner.expect('='); scanner.scan(whitespace); if (scanner.scan(token)) { params[name] = scanner.lastMatch[0]; } else { params[name] = expectQuotedString(scanner, name: 'a token or a quoted string'); } scanner.scan(whitespace); } /// Creates a new challenge value with [scheme] and [parameters]. AuthenticationChallenge(this.scheme, Map<String, String> parameters) : parameters = UnmodifiableMapView(CaseInsensitiveMap.from(parameters)); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_parser
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_parser/src/case_insensitive_map.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:collection/collection.dart'; /// A map from case-insensitive strings to values. /// /// Much of HTTP is case-insensitive, so this is useful to have pre-defined. class CaseInsensitiveMap<V> extends CanonicalizedMap<String, String, V> { CaseInsensitiveMap() : super((key) => key.toLowerCase(), isValidKey: (key) => key != null); CaseInsensitiveMap.from(Map<String, V> other) : super.from(other, (key) => key.toLowerCase(), isValidKey: (key) => key != null); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_parser
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_parser/src/utils.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:source_span/source_span.dart'; /// Runs [body] and wraps any format exceptions it produces. /// /// [name] should describe the type of thing being parsed, and [value] should be /// its actual value. T wrapFormatException<T>(String name, String value, T Function() body) { try { return body(); } on SourceSpanFormatException catch (error) { throw SourceSpanFormatException( 'Invalid $name: ${error.message}', error.span, error.source); } on FormatException catch (error) { throw FormatException( 'Invalid $name "$value": ${error.message}', error.source, error.offset); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_parser
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_parser/src/http_date.dart
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:string_scanner/string_scanner.dart'; import 'utils.dart'; const _weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']; const _months = [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ]; final _shortWeekdayRegExp = RegExp(r'Mon|Tue|Wed|Thu|Fri|Sat|Sun'); final _longWeekdayRegExp = RegExp(r'Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday'); final _monthRegExp = RegExp(r'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec'); final _digitRegExp = RegExp(r'\d+'); /// Return a HTTP-formatted string representation of [date]. /// /// This follows [RFC 822](http://tools.ietf.org/html/rfc822) as updated by /// [RFC 1123](http://tools.ietf.org/html/rfc1123). String formatHttpDate(DateTime date) { date = date.toUtc(); final buffer = StringBuffer() ..write(_weekdays[date.weekday - 1]) ..write(', ') ..write(date.day <= 9 ? '0' : '') ..write(date.day.toString()) ..write(' ') ..write(_months[date.month - 1]) ..write(' ') ..write(date.year.toString()) ..write(date.hour <= 9 ? ' 0' : ' ') ..write(date.hour.toString()) ..write(date.minute <= 9 ? ':0' : ':') ..write(date.minute.toString()) ..write(date.second <= 9 ? ':0' : ':') ..write(date.second.toString()) ..write(' GMT'); return buffer.toString(); } /// Parses an HTTP-formatted date into a UTC [DateTime]. /// /// This follows [RFC 2616](http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3). /// It will throw a [FormatException] if [date] is invalid. DateTime parseHttpDate(String date) => wrapFormatException('HTTP date', date, () { final scanner = StringScanner(date); if (scanner.scan(_longWeekdayRegExp)) { // RFC 850 starts with a long weekday. scanner.expect(', '); final day = _parseInt(scanner, 2); scanner.expect('-'); final month = _parseMonth(scanner); scanner.expect('-'); final year = 1900 + _parseInt(scanner, 2); scanner.expect(' '); final time = _parseTime(scanner); scanner.expect(' GMT'); scanner.expectDone(); return _makeDateTime(year, month, day, time); } // RFC 1123 and asctime both start with a short weekday. scanner.expect(_shortWeekdayRegExp); if (scanner.scan(', ')) { // RFC 1123 follows the weekday with a comma. final day = _parseInt(scanner, 2); scanner.expect(' '); final month = _parseMonth(scanner); scanner.expect(' '); final year = _parseInt(scanner, 4); scanner.expect(' '); final time = _parseTime(scanner); scanner.expect(' GMT'); scanner.expectDone(); return _makeDateTime(year, month, day, time); } // asctime follows the weekday with a space. scanner.expect(' '); final month = _parseMonth(scanner); scanner.expect(' '); final day = scanner.scan(' ') ? _parseInt(scanner, 1) : _parseInt(scanner, 2); scanner.expect(' '); final time = _parseTime(scanner); scanner.expect(' '); final year = _parseInt(scanner, 4); scanner.expectDone(); return _makeDateTime(year, month, day, time); }); /// Parses a short-form month name to a form accepted by [DateTime]. int _parseMonth(StringScanner scanner) { scanner.expect(_monthRegExp); // DateTime uses 1-indexed months. return _months.indexOf(scanner.lastMatch[0]) + 1; } /// Parses an int an enforces that it has exactly [digits] digits. int _parseInt(StringScanner scanner, int digits) { scanner.expect(_digitRegExp); if (scanner.lastMatch[0].length != digits) { scanner.error('expected a $digits-digit number.'); } return int.parse(scanner.lastMatch[0]); } /// Parses an timestamp of the form "HH:MM:SS" on a 24-hour clock. DateTime _parseTime(StringScanner scanner) { final hours = _parseInt(scanner, 2); if (hours >= 24) scanner.error('hours may not be greater than 24.'); scanner.expect(':'); final minutes = _parseInt(scanner, 2); if (minutes >= 60) scanner.error('minutes may not be greater than 60.'); scanner.expect(':'); final seconds = _parseInt(scanner, 2); if (seconds >= 60) scanner.error('seconds may not be greater than 60.'); return DateTime(1, 1, 1, hours, minutes, seconds); } /// Returns a UTC [DateTime] from the given components. /// /// Validates that [day] is a valid day for [month]. If it's not, throws a /// [FormatException]. DateTime _makeDateTime(int year, int month, int day, DateTime time) { final dateTime = DateTime.utc(year, month, day, time.hour, time.minute, time.second); // If [day] was too large, it will cause [month] to overflow. if (dateTime.month != month) { throw FormatException("invalid day '$day' for month '$month'."); } return dateTime; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_parser/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_parser/src/chunked_coding/decoder.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:convert'; import 'dart:math' as math; import 'dart:typed_data'; import 'package:charcode/ascii.dart'; import 'package:typed_data/typed_data.dart'; /// The canonical instance of [ChunkedCodingDecoder]. const chunkedCodingDecoder = ChunkedCodingDecoder._(); /// A converter that decodes byte arrays into chunks with size tags. class ChunkedCodingDecoder extends Converter<List<int>, List<int>> { const ChunkedCodingDecoder._(); @override List<int> convert(List<int> input) { final sink = _Sink(null); final output = sink._decode(input, 0, input.length); if (sink._state == _State.end) return output; throw FormatException('Input ended unexpectedly.', input, input.length); } @override ByteConversionSink startChunkedConversion(Sink<List<int>> sink) => _Sink(sink); } /// A conversion sink for the chunked transfer encoding. class _Sink extends ByteConversionSinkBase { /// The underlying sink to which decoded byte arrays will be passed. final Sink<List<int>> _sink; /// The current state of the sink's parsing. var _state = _State.boundary; /// The size of the chunk being parsed, or `null` if the size hasn't been /// parsed yet. int _size; _Sink(this._sink); @override void add(List<int> chunk) => addSlice(chunk, 0, chunk.length, false); @override void addSlice(List<int> chunk, int start, int end, bool isLast) { RangeError.checkValidRange(start, end, chunk.length); final output = _decode(chunk, start, end); if (output.isNotEmpty) _sink.add(output); if (isLast) _close(chunk, end); } @override void close() => _close(); /// Like [close], but includes [chunk] and [index] in the [FormatException] if /// one is thrown. void _close([List<int> chunk, int index]) { if (_state != _State.end) { throw FormatException('Input ended unexpectedly.', chunk, index); } _sink.close(); } /// Decodes the data in [bytes] from [start] to [end]. Uint8List _decode(List<int> bytes, int start, int end) { /// Throws a [FormatException] if `bytes[start] != $char`. Uses [name] to /// describe the character in the exception text. void assertCurrentChar(int char, String name) { if (bytes[start] != char) { throw FormatException('Expected $name.', bytes, start); } } final buffer = Uint8Buffer(); while (start != end) { switch (_state) { case _State.boundary: _size = _digitForByte(bytes, start); _state = _State.size; start++; break; case _State.size: if (bytes[start] == $cr) { _state = _State.sizeBeforeLF; } else { // Shift four bits left since a single hex digit contains four bits // of information. _size = (_size << 4) + _digitForByte(bytes, start); } start++; break; case _State.sizeBeforeLF: assertCurrentChar($lf, 'LF'); _state = _size == 0 ? _State.endBeforeCR : _State.body; start++; break; case _State.body: final chunkEnd = math.min(end, start + _size); buffer.addAll(bytes, start, chunkEnd); _size -= chunkEnd - start; start = chunkEnd; if (_size == 0) _state = _State.bodyBeforeCR; break; case _State.bodyBeforeCR: assertCurrentChar($cr, 'CR'); _state = _State.bodyBeforeLF; start++; break; case _State.bodyBeforeLF: assertCurrentChar($lf, 'LF'); _state = _State.boundary; start++; break; case _State.endBeforeCR: assertCurrentChar($cr, 'CR'); _state = _State.endBeforeLF; start++; break; case _State.endBeforeLF: assertCurrentChar($lf, 'LF'); _state = _State.end; start++; break; case _State.end: throw FormatException('Expected no more data.', bytes, start); } } return buffer.buffer.asUint8List(0, buffer.length); } /// Returns the hex digit (0 through 15) corresponding to the byte at index /// [index] in [bytes]. /// /// If the given byte isn't a hexadecimal ASCII character, throws a /// [FormatException]. int _digitForByte(List<int> bytes, int index) { // If the byte is a numeral, get its value. XOR works because 0 in ASCII is // `0b110000` and the other numerals come after it in ascending order and // take up at most four bits. // // We check for digits first because it ensures there's only a single branch // for 10 out of 16 of the expected cases. We don't count the `digit >= 0` // check because branch prediction will always work on it for valid data. final byte = bytes[index]; final digit = $0 ^ byte; if (digit <= 9) { if (digit >= 0) return digit; } else { // If the byte is an uppercase letter, convert it to lowercase. This works // because uppercase letters in ASCII are exactly `0b100000 = 0x20` less // than lowercase letters, so if we ensure that that bit is 1 we ensure // that the letter is lowercase. final letter = 0x20 | byte; if ($a <= letter && letter <= $f) return letter - $a + 10; } throw FormatException( 'Invalid hexadecimal byte 0x${byte.toRadixString(16).toUpperCase()}.', bytes, index); } } /// An enumeration of states that [_Sink] can exist in when decoded a chunked /// message. class _State { /// The parser has fully parsed one chunk and is expecting the header for the /// next chunk. /// /// Transitions to [size]. static const boundary = _State._('boundary'); /// The parser has parsed at least one digit of the chunk size header, but has /// not yet parsed the `CR LF` sequence that indicates the end of that header. /// /// Transitions to [sizeBeforeLF]. static const size = _State._('size'); /// The parser has parsed the chunk size header and the CR character after it, /// but not the LF. /// /// Transitions to [body] or [bodyBeforeCR]. static const sizeBeforeLF = _State._('size before LF'); /// The parser has parsed a chunk header and possibly some of the body, but /// still needs to consume more bytes. /// /// Transitions to [bodyBeforeCR]. static const body = _State._('body'); // The parser has parsed all the bytes in a chunk body but not the CR LF // sequence that follows it. // // Transitions to [bodyBeforeLF]. static const bodyBeforeCR = _State._('body before CR'); // The parser has parsed all the bytes in a chunk body and the CR that follows // it, but not the LF after that. // // Transitions to [bounday]. static const bodyBeforeLF = _State._('body before LF'); /// The parser has parsed the final empty chunk but not the CR LF sequence /// that follows it. /// /// Transitions to [endBeforeLF]. static const endBeforeCR = _State._('end before CR'); /// The parser has parsed the final empty chunk and the CR that follows it, /// but not the LF after that. /// /// Transitions to [end]. static const endBeforeLF = _State._('end before LF'); /// The parser has parsed the final empty chunk as well as the CR LF that /// follows, and expects no more data. static const end = _State._('end'); final String _name; const _State._(this._name); @override String toString() => _name; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_parser/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_parser/src/chunked_coding/encoder.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:convert'; import 'dart:typed_data'; import 'package:charcode/ascii.dart'; /// The canonical instance of [ChunkedCodingEncoder]. const chunkedCodingEncoder = ChunkedCodingEncoder._(); /// The chunk indicating that the chunked message has finished. final _doneChunk = Uint8List.fromList([$0, $cr, $lf, $cr, $lf]); /// A converter that encodes byte arrays into chunks with size tags. class ChunkedCodingEncoder extends Converter<List<int>, List<int>> { const ChunkedCodingEncoder._(); @override List<int> convert(List<int> input) => _convert(input, 0, input.length, isLast: true); @override ByteConversionSink startChunkedConversion(Sink<List<int>> sink) => _Sink(sink); } /// A conversion sink for the chunked transfer encoding. class _Sink extends ByteConversionSinkBase { /// The underlying sink to which encoded byte arrays will be passed. final Sink<List<int>> _sink; _Sink(this._sink); @override void add(List<int> chunk) { _sink.add(_convert(chunk, 0, chunk.length)); } @override void addSlice(List<int> chunk, int start, int end, bool isLast) { RangeError.checkValidRange(start, end, chunk.length); _sink.add(_convert(chunk, start, end, isLast: isLast)); if (isLast) _sink.close(); } @override void close() { _sink.add(_doneChunk); _sink.close(); } } /// Returns a new list a chunked transfer encoding header followed by the slice /// of [bytes] from [start] to [end]. /// /// If [isLast] is `true`, this adds the footer that indicates that the chunked /// message is complete. List<int> _convert(List<int> bytes, int start, int end, {bool isLast = false}) { if (end == start) return isLast ? _doneChunk : const []; final size = end - start; final sizeInHex = size.toRadixString(16); final footerSize = isLast ? _doneChunk.length : 0; // Add 4 for the CRLF sequences that follow the size header and the bytes. final list = Uint8List(sizeInHex.length + 4 + size + footerSize); list.setRange(0, sizeInHex.length, sizeInHex.codeUnits); var cursor = sizeInHex.length; list[cursor++] = $cr; list[cursor++] = $lf; list.setRange(cursor, cursor + end - start, bytes, start); cursor += end - start; list[cursor++] = $cr; list[cursor++] = $lf; if (isLast) { list.setRange(list.length - footerSize, list.length, _doneChunk); } return list; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf_web_socket/shelf_web_socket.dart
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'package:shelf/shelf.dart'; import 'package:web_socket_channel/web_socket_channel.dart'; import 'src/web_socket_handler.dart'; typedef _BinaryFunction = void Function(Null, Null); /// Creates a Shelf handler that upgrades HTTP requests to WebSocket /// connections. /// /// Only valid WebSocket upgrade requests are upgraded. If a request doesn't /// look like a WebSocket upgrade request, a 404 Not Found is returned; if a /// request looks like an upgrade request but is invalid, a 400 Bad Request is /// returned; and if a request is a valid upgrade request but has an origin that /// doesn't match [allowedOrigins] (see below), a 403 Forbidden is returned. /// This means that this can be placed first in a [Cascade] and only upgrade /// requests will be handled. /// /// The [onConnection] must take a [WebSocketChannel] as its first argument. It /// may also take a string, the [WebSocket subprotocol][], as its second /// argument. The subprotocol is determined by looking at the client's /// `Sec-WebSocket-Protocol` header and selecting the first entry that also /// appears in [protocols]. If no subprotocols are shared between the client and /// the server, `null` will be passed instead. Note that if [onConnection] takes /// two arguments, [protocols] must be passed. /// /// [WebSocket subprotocol]: https://tools.ietf.org/html/rfc6455#section-1.9 /// /// If [allowedOrigins] is passed, browser connections will only be accepted if /// they're made by a script from one of the given origins. This ensures that /// malicious scripts running in the browser are unable to fake a WebSocket /// handshake. Note that non-browser programs can still make connections freely. /// See also the WebSocket spec's discussion of [origin considerations][]. /// /// [origin considerations]: https://tools.ietf.org/html/rfc6455#section-10.2 /// /// If [pingInterval] is specified, it will get passed to the created /// channel instance, enabling round-trip disconnect detection. /// See [WebSocketChannel] for more details. Handler webSocketHandler(Function onConnection, {Iterable<String> protocols, Iterable<String> allowedOrigins, Duration pingInterval}) { if (protocols != null) protocols = protocols.toSet(); if (allowedOrigins != null) { allowedOrigins = allowedOrigins.map((origin) => origin.toLowerCase()).toSet(); } if (onConnection is! _BinaryFunction) { if (protocols != null) { throw new ArgumentError("If protocols is non-null, onConnection must " "take two arguments, the WebSocket and the protocol."); } var innerOnConnection = onConnection; onConnection = (webSocket, _) => innerOnConnection(webSocket); } return new WebSocketHandler( onConnection, protocols, allowedOrigins, pingInterval) .handle; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf_web_socket
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/shelf_web_socket/src/web_socket_handler.dart
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:convert'; import 'package:shelf/shelf.dart'; import 'package:web_socket_channel/web_socket_channel.dart'; /// A class that exposes a handler for upgrading WebSocket requests. class WebSocketHandler { /// The function to call when a request is upgraded. final Function _onConnection; /// The set of protocols the user supports, or `null`. final Set<String> _protocols; /// The set of allowed browser origin connections, or `null`.. final Set<String> _allowedOrigins; /// The ping interval used for verifying connection, or `null`. final Duration _pingInterval; WebSocketHandler(this._onConnection, this._protocols, this._allowedOrigins, this._pingInterval); /// The [Handler]. Response handle(Request request) { if (request.method != 'GET') return _notFound(); var connection = request.headers['Connection']; if (connection == null) return _notFound(); var tokens = connection.toLowerCase().split(',').map((token) => token.trim()); if (!tokens.contains('upgrade')) return _notFound(); var upgrade = request.headers['Upgrade']; if (upgrade == null) return _notFound(); if (upgrade.toLowerCase() != 'websocket') return _notFound(); var version = request.headers['Sec-WebSocket-Version']; if (version == null) { return _badRequest('missing Sec-WebSocket-Version header.'); } else if (version != '13') { return _notFound(); } if (request.protocolVersion != '1.1') { return _badRequest('unexpected HTTP version ' '"${request.protocolVersion}".'); } var key = request.headers['Sec-WebSocket-Key']; if (key == null) return _badRequest('missing Sec-WebSocket-Key header.'); if (!request.canHijack) { throw new ArgumentError("webSocketHandler may only be used with a server " "that supports request hijacking."); } // The Origin header is always set by browser connections. By filtering out // unexpected origins, we ensure that malicious JavaScript is unable to fake // a WebSocket handshake. var origin = request.headers['Origin']; if (origin != null && _allowedOrigins != null && !_allowedOrigins.contains(origin.toLowerCase())) { return _forbidden('invalid origin "$origin".'); } var protocol = _chooseProtocol(request); request.hijack((channel) { var sink = utf8.encoder.startChunkedConversion(channel.sink); sink.add("HTTP/1.1 101 Switching Protocols\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Accept: ${WebSocketChannel.signKey(key)}\r\n"); if (protocol != null) sink.add("Sec-WebSocket-Protocol: $protocol\r\n"); sink.add("\r\n"); _onConnection( new WebSocketChannel(channel, pingInterval: _pingInterval), protocol); }); // [request.hijack] is guaranteed to throw a [HijackException], so we'll // never get here. assert(false); return null; } /// Selects a subprotocol to use for the given connection. /// /// If no matching protocol can be found, returns `null`. String _chooseProtocol(Request request) { var protocols = request.headers['Sec-WebSocket-Protocol']; if (protocols == null) return null; for (var protocol in protocols.split(',')) { protocol = protocol.trim(); if (_protocols.contains(protocol)) return protocol; } return null; } /// Returns a 404 Not Found response. Response _notFound() => _htmlResponse( 404, "404 Not Found", "Only WebSocket connections are supported."); /// Returns a 400 Bad Request response. /// /// [message] will be HTML-escaped before being included in the response body. Response _badRequest(String message) => _htmlResponse( 400, "400 Bad Request", "Invalid WebSocket upgrade request: $message"); /// Returns a 403 Forbidden response. /// /// [message] will be HTML-escaped before being included in the response body. Response _forbidden(String message) => _htmlResponse( 403, "403 Forbidden", "WebSocket upgrade refused: $message"); /// Creates an HTTP response with the given [statusCode] and an HTML body with /// [title] and [message]. /// /// [title] and [message] will be automatically HTML-escaped. Response _htmlResponse(int statusCode, String title, String message) { title = htmlEscape.convert(title); message = htmlEscape.convert(message); return new Response(statusCode, body: """ <!doctype html> <html> <head><title>$title</title></head> <body> <h1>$title</h1> <p>$message</p> </body> </html> """, headers: {'content-type': 'text/html'}); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_multi_server/http_multi_server.dart
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io'; import 'package:async/async.dart'; import 'src/multi_headers.dart'; import 'src/utils.dart'; /// The error code for an error caused by a port already being in use. final _addressInUseErrno = _computeAddressInUseErrno(); int _computeAddressInUseErrno() { if (Platform.isWindows) return 10048; if (Platform.isMacOS) return 48; assert(Platform.isLinux); return 98; } /// An implementation of `dart:io`'s [HttpServer] that wraps multiple servers /// and forwards methods to all of them. /// /// This is useful for serving the same application on multiple network /// interfaces while still having a unified way of controlling the servers. In /// particular, it supports serving on both the IPv4 and IPv6 loopback addresses /// using [HttpMultiServer.loopback]. class HttpMultiServer extends StreamView<HttpRequest> implements HttpServer { /// The wrapped servers. final Set<HttpServer> _servers; /// Returns the default value of the `Server` header for all responses /// generated by each server. /// /// If the wrapped servers have different default values, it's not defined /// which value is returned. @override String get serverHeader => _servers.first.serverHeader; @override set serverHeader(String value) { for (var server in _servers) { server.serverHeader = value; } } /// Returns the default set of headers added to all response objects. /// /// If the wrapped servers have different default headers, it's not defined /// which header is returned for accessor methods. @override final HttpHeaders defaultResponseHeaders; @override Duration get idleTimeout => _servers.first.idleTimeout; @override set idleTimeout(Duration value) { for (var server in _servers) { server.idleTimeout = value; } } @override bool get autoCompress => _servers.first.autoCompress; @override set autoCompress(bool value) { for (var server in _servers) { server.autoCompress = value; } } /// Returns the port that one of the wrapped servers is listening on. /// /// If the wrapped servers are listening on different ports, it's not defined /// which port is returned. @override int get port => _servers.first.port; /// Returns the address that one of the wrapped servers is listening on. /// /// If the wrapped servers are listening on different addresses, it's not /// defined which address is returned. @override InternetAddress get address => _servers.first.address; @override set sessionTimeout(int value) { for (var server in _servers) { server.sessionTimeout = value; } } /// Creates an [HttpMultiServer] wrapping [servers]. /// /// All [servers] should have the same configuration and none should be /// listened to when this is called. HttpMultiServer(Iterable<HttpServer> servers) : _servers = servers.toSet(), defaultResponseHeaders = MultiHeaders( servers.map((server) => server.defaultResponseHeaders)), super(StreamGroup.merge(servers)); /// Creates an [HttpServer] listening on all available loopback addresses for /// this computer. /// /// See [HttpServer.bind]. static Future<HttpServer> loopback(int port, {int backlog, bool v6Only = false, bool shared = false}) { backlog ??= 0; return _loopback( port, (address, port) => HttpServer.bind(address, port, backlog: backlog, v6Only: v6Only, shared: shared)); } /// Like [loopback], but supports HTTPS requests. /// /// See [HttpServer.bindSecure]. static Future<HttpServer> loopbackSecure(int port, SecurityContext context, {int backlog, bool v6Only = false, bool requestClientCertificate = false, bool shared = false}) { backlog ??= 0; return _loopback( port, (address, port) => HttpServer.bindSecure(address, port, context, backlog: backlog, v6Only: v6Only, shared: shared, requestClientCertificate: requestClientCertificate)); } /// Bind an [HttpServer] with handling for special addresses 'localhost' and /// 'any'. /// /// For address 'localhost' behaves like [loopback]. For 'any' listens on /// [InternetAddress.anyIPv6] which listens on all hostnames for both IPv4 and /// IPV6. For any other address forwards directly to `HttpServer.bind` where /// the IPvX support may vary. /// /// See [HttpServer.bind]. static Future<HttpServer> bind(dynamic address, int port, {int backlog = 0, bool v6Only = false, bool shared = false}) { if (address == 'localhost') { return HttpMultiServer.loopback(port, backlog: backlog, v6Only: v6Only, shared: shared); } if (address == 'any') { return HttpServer.bind(InternetAddress.anyIPv6, port, backlog: backlog, v6Only: v6Only, shared: shared); } return HttpServer.bind(address, port, backlog: backlog, v6Only: v6Only, shared: shared); } /// A helper method for initializing loopback servers. /// /// [bind] should forward to either [HttpServer.bind] or /// [HttpServer.bindSecure]. static Future<HttpServer> _loopback( int port, Future<HttpServer> Function(InternetAddress, int port) bind, [int remainingRetries]) async { remainingRetries ??= 5; if (!await supportsIPv4) { return await bind(InternetAddress.loopbackIPv6, port); } var v4Server = await bind(InternetAddress.loopbackIPv4, port); if (!await supportsIPv6) return v4Server; try { // Reuse the IPv4 server's port so that if [port] is 0, both servers use // the same ephemeral port. var v6Server = await bind(InternetAddress.loopbackIPv6, v4Server.port); return HttpMultiServer([v4Server, v6Server]); } on SocketException catch (error) { // If there is already a server listening we'll lose the reference on a // rethrow. await v4Server.close(); if (error.osError.errorCode != _addressInUseErrno) rethrow; if (port != 0) rethrow; if (remainingRetries == 0) rethrow; // A port being available on IPv4 doesn't necessarily mean that the same // port is available on IPv6. If it's not (which is rare in practice), // we try again until we find one that's available on both. return await _loopback(port, bind, remainingRetries - 1); } } @override Future close({bool force = false}) => Future.wait(_servers.map((server) => server.close(force: force))); /// Returns an HttpConnectionsInfo object summarizing the total number of /// current connections handled by all the servers. @override HttpConnectionsInfo connectionsInfo() { var info = HttpConnectionsInfo(); for (var server in _servers) { var subInfo = server.connectionsInfo(); info.total += subInfo.total; info.active += subInfo.active; info.idle += subInfo.idle; info.closing += subInfo.closing; } return info; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_multi_server
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_multi_server/src/multi_headers.dart
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:io'; /// A class that delegates header access and setting to many [HttpHeaders] /// instances. class MultiHeaders implements HttpHeaders { /// The wrapped headers. final Set<HttpHeaders> _headers; @override bool get chunkedTransferEncoding => _headers.first.chunkedTransferEncoding; @override set chunkedTransferEncoding(bool value) { for (var headers in _headers) { headers.chunkedTransferEncoding = value; } } @override int get contentLength => _headers.first.contentLength; @override set contentLength(int value) { for (var headers in _headers) { headers.contentLength = value; } } @override ContentType get contentType => _headers.first.contentType; @override set contentType(ContentType value) { for (var headers in _headers) { headers.contentType = value; } } @override DateTime get date => _headers.first.date; @override set date(DateTime value) { for (var headers in _headers) { headers.date = value; } } @override DateTime get expires => _headers.first.expires; @override set expires(DateTime value) { for (var headers in _headers) { headers.expires = value; } } @override String get host => _headers.first.host; @override set host(String value) { for (var headers in _headers) { headers.host = value; } } @override DateTime get ifModifiedSince => _headers.first.ifModifiedSince; @override set ifModifiedSince(DateTime value) { for (var headers in _headers) { headers.ifModifiedSince = value; } } @override bool get persistentConnection => _headers.first.persistentConnection; @override set persistentConnection(bool value) { for (var headers in _headers) { headers.persistentConnection = value; } } @override int get port => _headers.first.port; @override set port(int value) { for (var headers in _headers) { headers.port = value; } } MultiHeaders(Iterable<HttpHeaders> headers) : _headers = headers.toSet(); @override void add(String name, Object value, {bool preserveHeaderCase = false}) { for (var headers in _headers) { headers.add(name, value); } } @override void forEach(void Function(String name, List<String> values) f) => _headers.first.forEach(f); @override void noFolding(String name) { for (var headers in _headers) { headers.noFolding(name); } } @override void remove(String name, Object value) { for (var headers in _headers) { headers.remove(name, value); } } @override void removeAll(String name) { for (var headers in _headers) { headers.removeAll(name); } } @override void set(String name, Object value, {bool preserveHeaderCase = false}) { for (var headers in _headers) { headers.set(name, value); } } @override String value(String name) => _headers.first.value(name); @override List<String> operator [](String name) => _headers.first[name]; @override void clear() { for (var headers in _headers) { headers.clear(); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_multi_server
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/http_multi_server/src/utils.dart
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:async'; import 'dart:io'; /// Returns whether this computer supports binding to IPv6 addresses. final Future<bool> supportsIPv6 = () async { try { var socket = await ServerSocket.bind(InternetAddress.loopbackIPv6, 0); await socket.close(); return true; } on SocketException catch (_) { return false; } }(); /// Returns whether this computer supports binding to IPv4 addresses. final Future<bool> supportsIPv4 = () async { try { var socket = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); await socket.close(); return true; } on SocketException catch (_) { return false; } }();
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/protobuf.dart
// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library protobuf; import 'dart:collection' show ListBase, MapBase; import 'dart:convert' show base64Decode, base64Encode, jsonEncode, jsonDecode, Utf8Codec; import 'dart:math' as math; import 'dart:typed_data' show TypedData, Uint8List, ByteData, Endian; import 'package:fixnum/fixnum.dart' show Int64; import 'src/protobuf/json_parsing_context.dart'; import 'src/protobuf/permissive_compare.dart'; import 'src/protobuf/type_registry.dart'; export 'src/protobuf/type_registry.dart' show TypeRegistry; part 'src/protobuf/coded_buffer.dart'; part 'src/protobuf/coded_buffer_reader.dart'; part 'src/protobuf/coded_buffer_writer.dart'; part 'src/protobuf/builder_info.dart'; part 'src/protobuf/event_plugin.dart'; part 'src/protobuf/exceptions.dart'; part 'src/protobuf/extension.dart'; part 'src/protobuf/extension_field_set.dart'; part 'src/protobuf/extension_registry.dart'; part 'src/protobuf/field_error.dart'; part 'src/protobuf/field_info.dart'; part 'src/protobuf/field_set.dart'; part 'src/protobuf/field_type.dart'; part 'src/protobuf/generated_message.dart'; part 'src/protobuf/generated_service.dart'; part 'src/protobuf/json.dart'; part 'src/protobuf/pb_list.dart'; part 'src/protobuf/pb_map.dart'; part 'src/protobuf/protobuf_enum.dart'; part 'src/protobuf/proto3_json.dart'; part 'src/protobuf/readonly_message.dart'; part 'src/protobuf/rpc_client.dart'; part 'src/protobuf/unknown_field_set.dart'; part 'src/protobuf/utils.dart'; part 'src/protobuf/unpack.dart'; part 'src/protobuf/wire_format.dart'; // TODO(sra): Remove this method when clients upgrade to protoc 0.3.5 Int64 makeLongInt(int n) => Int64(n); // TODO(sra): Use Int64.parse() when available - see http://dartbug.com/21915. Int64 parseLongInt(String text) { if (text.startsWith('0x')) return Int64.parseHex(text.substring(2)); if (text.startsWith('+0x')) return Int64.parseHex(text.substring(3)); if (text.startsWith('-0x')) return -Int64.parseHex(text.substring(3)); return Int64.parseInt(text); } const _utf8 = Utf8Codec(allowMalformed: true);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/meta.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Provides metadata about GeneratedMessage and ProtobufEnum to /// dart-protoc-plugin. (Experimental API; subject to change.) library protobuf.meta; // List of names which cannot be used in a subclass of GeneratedMessage. const GeneratedMessage_reservedNames = <String>[ '==', 'GeneratedMessage', 'Object', 'addExtension', 'check', 'clear', 'clearExtension', 'clearField', 'clone', 'copyWith', 'createEmptyInstance', 'createMapField', 'createRepeatedField', 'eventPlugin', 'extensionsAreInitialized', 'freeze', 'fromBuffer', 'fromJson', 'getDefaultForField', 'getExtension', 'getField', 'getFieldOrNull', 'getTagNumber', 'hasExtension', 'hasField', 'hasRequiredFields', 'hashCode', 'info_', 'isFrozen', 'isInitialized', 'mergeFromBuffer', 'mergeFromCodedBufferReader', 'mergeFromJson', 'mergeFromJsonMap', 'mergeFromMessage', 'mergeFromProto3Json', 'mergeUnknownFields', 'noSuchMethod', 'runtimeType', 'setExtension', 'setField', 'toBuilder', 'toDebugString', 'toProto3Json', 'toString', 'unknownFields', 'writeToBuffer', 'writeToCodedBufferWriter', 'writeToJson', 'writeToJsonMap', r'$_defaultFor', r'$_ensure', r'$_get', r'$_getI64', r'$_getList', r'$_getMap', r'$_getN', r'$_getB', r'$_getBF', r'$_getI', r'$_getIZ', r'$_getS', r'$_getSZ', r'$_has', r'$_setBool', r'$_setBytes', r'$_setDouble', r'$_setFloat', r'$_setInt64', r'$_setSignedInt32', r'$_setString', r'$_setUnsignedInt32', r'$_whichOneof', ]; // List of names which cannot be used in a subclass of ProtobufEnum. const ProtobufEnum_reservedNames = <String>[ '==', 'Object', 'ProtobufEnum', 'hashCode', 'initByValue', 'noSuchMethod', 'runtimeType', 'toString' ];
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/extension.dart
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; /// An object representing an extension field. class Extension<T> extends FieldInfo<T> { final String extendee; Extension(this.extendee, String name, int tagNumber, int fieldType, {dynamic defaultOrMaker, CreateBuilderFunc subBuilder, ValueOfFunc valueOf, List<ProtobufEnum> enumValues, String protoName}) : super(name, tagNumber, null, fieldType, defaultOrMaker: defaultOrMaker, subBuilder: subBuilder, valueOf: valueOf, enumValues: enumValues, protoName: protoName); Extension.repeated(this.extendee, String name, int tagNumber, int fieldType, {CheckFunc<T> check, CreateBuilderFunc subBuilder, ValueOfFunc valueOf, List<ProtobufEnum> enumValues, String protoName}) : super.repeated(name, tagNumber, null, fieldType, check, subBuilder, valueOf: valueOf, enumValues: enumValues, protoName: protoName); @override int get hashCode => extendee.hashCode * 31 + tagNumber; @override bool operator ==(other) { if (other is! Extension) return false; Extension o = other; return extendee == o.extendee && tagNumber == o.tagNumber; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/pb_list.dart
// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; typedef CheckFunc<E> = void Function(E x); class FrozenPbList<E> extends PbListBase<E> { FrozenPbList._(List<E> wrappedList) : super._(wrappedList); factory FrozenPbList.from(PbList<E> other) => FrozenPbList._(other._wrappedList); UnsupportedError _unsupported(String method) => UnsupportedError('Cannot call $method on an unmodifiable list'); @override void operator []=(int index, E value) => throw _unsupported('set'); @override set length(int newLength) => throw _unsupported('set length'); @override void setAll(int at, Iterable<E> iterable) => throw _unsupported('setAll'); @override void add(E value) => throw _unsupported('add'); @override void addAll(Iterable<E> iterable) => throw _unsupported('addAll'); @override void insert(int index, E element) => throw _unsupported('insert'); @override void insertAll(int at, Iterable<E> iterable) => throw _unsupported('insertAll'); @override bool remove(Object element) => throw _unsupported('remove'); @override void removeWhere(bool Function(E element) test) => throw _unsupported('removeWhere'); @override void retainWhere(bool Function(E element) test) => throw _unsupported('retainWhere'); @override void sort([Comparator<E> compare]) => throw _unsupported('sort'); @override void shuffle([math.Random random]) => throw _unsupported('shuffle'); @override void clear() => throw _unsupported('clear'); @override E removeAt(int index) => throw _unsupported('removeAt'); @override E removeLast() => throw _unsupported('removeLast'); @override void setRange(int start, int end, Iterable<E> iterable, [int skipCount = 0]) => throw _unsupported('setRange'); @override void removeRange(int start, int end) => throw _unsupported('removeRange'); @override void replaceRange(int start, int end, Iterable<E> iterable) => throw _unsupported('replaceRange'); @override void fillRange(int start, int end, [E fillValue]) => throw _unsupported('fillRange'); } class PbList<E> extends PbListBase<E> { PbList({check = _checkNotNull}) : super._noList(check: check); PbList.from(List from) : super._from(from); @Deprecated('Instead use the default constructor with a check function.' 'This constructor will be removed in the next major version.') PbList.forFieldType(int fieldType) : super._noList(check: getCheckFunction(fieldType)); /// Freezes the list by converting to [FrozenPbList]. FrozenPbList<E> toFrozenPbList() => FrozenPbList<E>.from(this); /// Adds [value] at the end of the list, extending the length by one. /// Throws an [UnsupportedError] if the list is not extendable. @override void add(E value) { check(value); _wrappedList.add(value); } /// Appends all elements of the [collection] to the end of list. /// Extends the length of the list by the length of [collection]. /// Throws an [UnsupportedError] if the list is not extendable. @override void addAll(Iterable<E> collection) { collection.forEach(check); _wrappedList.addAll(collection); } /// Returns an [Iterable] of the objects in this list in reverse order. @override Iterable<E> get reversed => _wrappedList.reversed; /// Sorts this list according to the order specified by the [compare] /// function. @override void sort([int Function(E a, E b) compare]) => _wrappedList.sort(compare); /// Shuffles the elements of this list randomly. @override void shuffle([math.Random random]) => _wrappedList.shuffle(random); /// Removes all objects from this list; the length of the list becomes zero. @override void clear() => _wrappedList.clear(); /// Inserts a new element in the list. /// The element must be valid (and not nullable) for the PbList type. @override void insert(int index, E element) { check(element); _wrappedList.insert(index, element); } /// Inserts all elements of [iterable] at position [index] in the list. /// /// Elements in [iterable] must be valid and not nullable for the PbList type. @override void insertAll(int index, Iterable<E> iterable) { iterable.forEach(check); _wrappedList.insertAll(index, iterable); } /// Overwrites elements of `this` with elements of [iterable] starting at /// position [index] in the list. /// /// Elements in [iterable] must be valid and not nullable for the PbList type. @override void setAll(int index, Iterable<E> iterable) { iterable.forEach(check); _wrappedList.setAll(index, iterable); } /// Removes the first occurrence of [value] from this list. @override bool remove(Object value) => _wrappedList.remove(value); /// Removes the object at position [index] from this list. @override E removeAt(int index) => _wrappedList.removeAt(index); /// Pops and returns the last object in this list. @override E removeLast() => _wrappedList.removeLast(); /// Removes all objects from this list that satisfy [test]. @override void removeWhere(bool Function(E element) test) => _wrappedList.removeWhere(test); /// Removes all objects from this list that fail to satisfy [test]. @override void retainWhere(bool Function(E element) test) => _wrappedList.retainWhere(test); /// Copies [:end - start:] elements of the [from] array, starting from /// [skipCount], into [:this:], starting at [start]. /// Throws an [UnsupportedError] if the list is not extendable. @override void setRange(int start, int end, Iterable<E> from, [int skipCount = 0]) { // NOTE: In case `take()` returns less than `end - start` elements, the // _wrappedList will fail with a `StateError`. from.skip(skipCount).take(end - start).forEach(check); _wrappedList.setRange(start, end, from, skipCount); } /// Removes the objects in the range [start] inclusive to [end] exclusive. @override void removeRange(int start, int end) => _wrappedList.removeRange(start, end); /// Sets the objects in the range [start] inclusive to [end] exclusive to the /// given [fillValue]. @override void fillRange(int start, int end, [E fillValue]) { check(fillValue); _wrappedList.fillRange(start, end, fillValue); } /// Removes the objects in the range [start] inclusive to [end] exclusive and /// inserts the contents of [replacement] in its place. @override void replaceRange(int start, int end, Iterable<E> replacement) { final values = replacement.toList(); replacement.forEach(check); _wrappedList.replaceRange(start, end, values); } } abstract class PbListBase<E> extends ListBase<E> { final List<E> _wrappedList; final CheckFunc<E> check; PbListBase._(this._wrappedList, {this.check = _checkNotNull}); PbListBase._noList({this.check = _checkNotNull}) : _wrappedList = <E>[] { assert(check != null); } PbListBase._from(List from) // TODO(sra): Should this be validated? : _wrappedList = List<E>.from(from), check = _checkNotNull; @override bool operator ==(other) => (other is PbListBase) && _areListsEqual(other, this); @override int get hashCode => _HashUtils._hashObjects(_wrappedList); /// Returns an [Iterator] for the list. @override Iterator<E> get iterator => _wrappedList.iterator; /// Returns a new lazy [Iterable] with elements that are created by calling /// `f` on each element of this `PbListBase` in iteration order. @override Iterable<T> map<T>(T Function(E e) f) => _wrappedList.map<T>(f); /// Returns a new lazy [Iterable] with all elements that satisfy the predicate /// [test]. @override Iterable<E> where(bool Function(E element) test) => _wrappedList.where(test); /// Expands each element of this [Iterable] into zero or more elements. @override Iterable<T> expand<T>(Iterable<T> Function(E element) f) => _wrappedList.expand(f); /// Returns true if the collection contains an element equal to [element]. @override bool contains(Object element) => _wrappedList.contains(element); /// Applies the function [f] to each element of this list in iteration order. @override void forEach(void Function(E element) f) { _wrappedList.forEach(f); } /// Reduces a collection to a single value by iteratively combining elements /// of the collection using the provided function. @override E reduce(E Function(E value, E element) combine) => _wrappedList.reduce(combine); /// Reduces a collection to a single value by iteratively combining each /// element of the collection with an existing value. @override T fold<T>(T initialValue, T Function(T previousValue, E element) combine) => _wrappedList.fold(initialValue, combine); /// Checks whether every element of this iterable satisfies [test]. @override bool every(bool Function(E element) test) => _wrappedList.every(test); /// Converts each element to a [String] and concatenates the strings. @override String join([String separator = '']) => _wrappedList.join(separator); /// Checks whether any element of this iterable satisfies [test]. @override bool any(bool Function(E element) test) => _wrappedList.any(test); /// Creates a [List] containing the elements of this [Iterable]. @override List<E> toList({bool growable = true}) => _wrappedList.toList(growable: growable); /// Creates a [Set] containing the same elements as this iterable. @override Set<E> toSet() => _wrappedList.toSet(); /// Returns `true` if there are no elements in this collection. @override bool get isEmpty => _wrappedList.isEmpty; /// Returns `true` if there is at least one element in this collection. @override bool get isNotEmpty => _wrappedList.isNotEmpty; /// Returns a lazy iterable of the [count] first elements of this iterable. @override Iterable<E> take(int count) => _wrappedList.take(count); /// Returns a lazy iterable of the leading elements satisfying [test]. @override Iterable<E> takeWhile(bool Function(E value) test) => _wrappedList.takeWhile(test); /// Returns an [Iterable] that provides all but the first [count] elements. @override Iterable<E> skip(int count) => _wrappedList.skip(count); /// Returns an `Iterable` that skips leading elements while [test] is /// satisfied. @override Iterable<E> skipWhile(bool Function(E value) test) => _wrappedList.skipWhile(test); /// Returns the first element. @override E get first => _wrappedList.first; /// Returns the last element. @override E get last => _wrappedList.last; /// Checks that this iterable has only one element, and returns that element. @override E get single => _wrappedList.single; /// Returns the first element that satisfies the given predicate [test]. @override E firstWhere(bool Function(E element) test, {E Function() orElse}) => _wrappedList.firstWhere(test, orElse: orElse); /// Returns the last element that satisfies the given predicate [test]. @override E lastWhere(bool Function(E element) test, {E Function() orElse}) => _wrappedList.lastWhere(test, orElse: orElse); /// Returns the single element that satisfies [test]. // TODO(jakobr): Implement once Dart 2 corelib changes have landed. //E singleWhere(bool test(E element), {E orElse()}) => // _wrappedList.singleWhere(test, orElse: orElse); /// Returns the [index]th element. @override E elementAt(int index) => _wrappedList.elementAt(index); /// Returns a string representation of (some of) the elements of `this`. @override String toString() => _wrappedList.toString(); /// Returns the element at the given [index] in the list or throws an /// [IndexOutOfRangeException] if [index] is out of bounds. @override E operator [](int index) => _wrappedList[index]; /// Returns the number of elements in this collection. @override int get length => _wrappedList.length; // TODO(jakobr): E instead of Object once dart-lang/sdk#31311 is fixed. /// Returns the first index of [element] in this list. @override int indexOf(Object element, [int start = 0]) => _wrappedList.indexOf(element, start); // TODO(jakobr): E instead of Object once dart-lang/sdk#31311 is fixed. /// Returns the last index of [element] in this list. @override int lastIndexOf(Object element, [int start]) => _wrappedList.lastIndexOf(element, start); /// Returns a new list containing the objects from [start] inclusive to [end] /// exclusive. @override List<E> sublist(int start, [int end]) => _wrappedList.sublist(start, end); /// Returns an [Iterable] that iterates over the objects in the range [start] /// inclusive to [end] exclusive. @override Iterable<E> getRange(int start, int end) => _wrappedList.getRange(start, end); /// Returns an unmodifiable [Map] view of `this`. @override Map<int, E> asMap() => _wrappedList.asMap(); /// Sets the entry at the given [index] in the list to [value]. /// Throws an [IndexOutOfRangeException] if [index] is out of bounds. @override void operator []=(int index, E value) { check(value); _wrappedList[index] = value; } /// Unsupported -- violated non-null constraint imposed by protobufs. /// /// Changes the length of the list. If [newLength] is greater than the current /// [length], entries are initialized to [:null:]. Throws an /// [UnsupportedError] if the list is not extendable. @override set length(int newLength) { if (newLength > length) { throw UnsupportedError('Extending protobuf lists is not supported'); } _wrappedList.length = newLength; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/pb_map.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; class PbMap<K, V> extends MapBase<K, V> { final int keyFieldType; final int valueFieldType; static const int _keyFieldNumber = 1; static const int _valueFieldNumber = 2; final Map<K, V> _wrappedMap; final BuilderInfo _entryBuilderInfo; bool _isReadonly = false; _FieldSet _entryFieldSet() => _FieldSet(null, _entryBuilderInfo, null); PbMap(this.keyFieldType, this.valueFieldType, this._entryBuilderInfo) : _wrappedMap = <K, V>{}; PbMap.unmodifiable(PbMap other) : keyFieldType = other.keyFieldType, valueFieldType = other.valueFieldType, _wrappedMap = Map.unmodifiable(other._wrappedMap), _entryBuilderInfo = other._entryBuilderInfo, _isReadonly = other._isReadonly; @override V operator [](Object key) => _wrappedMap[key]; @override void operator []=(K key, V value) { if (_isReadonly) { throw UnsupportedError('Attempted to change a read-only map field'); } _checkNotNull(key); _checkNotNull(value); _wrappedMap[key] = value; } /// A [PbMap] is equal to another [PbMap] with equal key/value /// pairs in any order. @override bool operator ==(other) { if (identical(other, this)) { return true; } if (other is! PbMap) { return false; } if (other.length != length) { return false; } for (final key in keys) { if (!other.containsKey(key)) { return false; } } for (final key in keys) { if (other[key] != this[key]) { return false; } } return true; } /// A [PbMap] is equal to another [PbMap] with equal key/value /// pairs in any order. Then, the `hashCode` is guaranteed to be the same. @override int get hashCode { return _wrappedMap.entries .fold(0, (h, entry) => h ^ _HashUtils._hash2(entry.key, entry.value)); } @override void clear() { if (_isReadonly) { throw UnsupportedError('Attempted to change a read-only map field'); } _wrappedMap.clear(); } @override Iterable<K> get keys => _wrappedMap.keys; @override V remove(Object key) { if (_isReadonly) { throw UnsupportedError('Attempted to change a read-only map field'); } return _wrappedMap.remove(key); } @Deprecated('This function was not intended to be public. ' 'It will be removed from the public api in next major version. ') void add(CodedBufferReader input, [ExtensionRegistry registry]) { _mergeEntry(input, registry); } void _mergeEntry(CodedBufferReader input, [ExtensionRegistry registry]) { var length = input.readInt32(); var oldLimit = input._currentLimit; input._currentLimit = input._bufferPos + length; var entryFieldSet = _entryFieldSet(); _mergeFromCodedBufferReader(entryFieldSet, input, registry); input.checkLastTagWas(0); input._currentLimit = oldLimit; var key = entryFieldSet._$get<K>(0, null); var value = entryFieldSet._$get<V>(1, null); _wrappedMap[key] = value; } void _checkNotNull(Object val) { if (val == null) { throw ArgumentError("Can't add a null to a map field"); } } PbMap freeze() { _isReadonly = true; if (_isGroupOrMessage(valueFieldType)) { for (var subMessage in values as Iterable<GeneratedMessage>) { subMessage.freeze(); } } return this; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/exceptions.dart
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; class InvalidProtocolBufferException implements Exception { final String message; InvalidProtocolBufferException._(this.message); @override String toString() => 'InvalidProtocolBufferException: $message'; InvalidProtocolBufferException.invalidEndTag() : this._('Protocol message end-group tag did not match expected tag.'); InvalidProtocolBufferException.invalidTag() : this._('Protocol message contained an invalid tag (zero).'); InvalidProtocolBufferException.invalidWireType() : this._('Protocol message tag had invalid wire type.'); InvalidProtocolBufferException.malformedVarint() : this._('CodedBufferReader encountered a malformed varint.'); InvalidProtocolBufferException.recursionLimitExceeded() : this._(''' Protocol message had too many levels of nesting. May be malicious. Use CodedBufferReader.setRecursionLimit() to increase the depth limit. '''); InvalidProtocolBufferException.truncatedMessage() : this._(''' While parsing a protocol message, the input ended unexpectedly in the middle of a field. This could mean either than the input has been truncated or that an embedded message misreported its own length. '''); InvalidProtocolBufferException.wrongAnyMessage( String anyTypeName, unpackerTypeName) : this._(''' The type of the Any message ($anyTypeName) does not match the given unpacker ($unpackerTypeName). '''); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/coded_buffer_reader.dart
// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; class CodedBufferReader { static const int DEFAULT_RECURSION_LIMIT = 64; static const int DEFAULT_SIZE_LIMIT = 64 << 20; final Uint8List _buffer; int _bufferPos = 0; int _currentLimit = -1; int _lastTag = 0; int _recursionDepth = 0; final int _recursionLimit; final int _sizeLimit; CodedBufferReader(List<int> buffer, {int recursionLimit = DEFAULT_RECURSION_LIMIT, int sizeLimit = DEFAULT_SIZE_LIMIT}) : _buffer = buffer is Uint8List ? buffer : Uint8List.fromList(buffer), _recursionLimit = recursionLimit, _sizeLimit = math.min(sizeLimit, buffer.length) { _currentLimit = _sizeLimit; } void checkLastTagWas(int value) { if (_lastTag != value) { throw InvalidProtocolBufferException.invalidEndTag(); } } bool isAtEnd() => _bufferPos >= _currentLimit; void _withLimit(int byteLimit, callback) { if (byteLimit < 0) { throw ArgumentError( 'CodedBufferReader encountered an embedded string or message' ' which claimed to have negative size.'); } byteLimit += _bufferPos; var oldLimit = _currentLimit; if ((oldLimit != -1 && byteLimit > oldLimit) || byteLimit > _sizeLimit) { throw InvalidProtocolBufferException.truncatedMessage(); } _currentLimit = byteLimit; callback(); _currentLimit = oldLimit; } void _checkLimit(int increment) { assert(_currentLimit != -1); _bufferPos += increment; if (_bufferPos > _currentLimit) { throw InvalidProtocolBufferException.truncatedMessage(); } } void readGroup(int fieldNumber, GeneratedMessage message, ExtensionRegistry extensionRegistry) { if (_recursionDepth >= _recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } ++_recursionDepth; message.mergeFromCodedBufferReader(this, extensionRegistry); checkLastTagWas(makeTag(fieldNumber, WIRETYPE_END_GROUP)); --_recursionDepth; } UnknownFieldSet readUnknownFieldSetGroup(int fieldNumber) { if (_recursionDepth >= _recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } ++_recursionDepth; var unknownFieldSet = UnknownFieldSet(); unknownFieldSet.mergeFromCodedBufferReader(this); checkLastTagWas(makeTag(fieldNumber, WIRETYPE_END_GROUP)); --_recursionDepth; return unknownFieldSet; } void readMessage( GeneratedMessage message, ExtensionRegistry extensionRegistry) { var length = readInt32(); if (_recursionDepth >= _recursionLimit) { throw InvalidProtocolBufferException.recursionLimitExceeded(); } if (length < 0) { throw ArgumentError( 'CodedBufferReader encountered an embedded string or message' ' which claimed to have negative size.'); } var oldLimit = _currentLimit; _currentLimit = _bufferPos + length; if (_currentLimit > oldLimit) { throw InvalidProtocolBufferException.truncatedMessage(); } ++_recursionDepth; message.mergeFromCodedBufferReader(this, extensionRegistry); checkLastTagWas(0); --_recursionDepth; _currentLimit = oldLimit; } int readEnum() => readInt32(); int readInt32() => _readRawVarint32(true); Int64 readInt64() => _readRawVarint64(); int readUint32() => _readRawVarint32(false); Int64 readUint64() => _readRawVarint64(); int readSint32() => _decodeZigZag32(readUint32()); Int64 readSint64() => _decodeZigZag64(readUint64()); int readFixed32() => _readByteData(4).getUint32(0, Endian.little); Int64 readFixed64() => readSfixed64(); int readSfixed32() => _readByteData(4).getInt32(0, Endian.little); Int64 readSfixed64() { var data = _readByteData(8); var view = Uint8List.view(data.buffer, data.offsetInBytes, 8); return Int64.fromBytes(view); } bool readBool() => _readRawVarint32(true) != 0; List<int> readBytes() { var length = readInt32(); _checkLimit(length); return Uint8List.view( _buffer.buffer, _buffer.offsetInBytes + _bufferPos - length, length); } String readString() => _utf8.decode(readBytes()); double readFloat() => _readByteData(4).getFloat32(0, Endian.little); double readDouble() => _readByteData(8).getFloat64(0, Endian.little); int readTag() { if (isAtEnd()) { _lastTag = 0; return 0; } _lastTag = readUint32(); if (getTagFieldNumber(_lastTag) == 0) { throw InvalidProtocolBufferException.invalidTag(); } return _lastTag; } static int _decodeZigZag32(int value) { if ((value & 0x1) == 1) { return -(value >> 1) - 1; } else { return value >> 1; } } static Int64 _decodeZigZag64(Int64 value) { if ((value & 0x1) == 1) value = -value; return value >> 1; } int _readRawVarintByte() { _checkLimit(1); return _buffer[_bufferPos - 1]; } int _readRawVarint32(bool signed) { // Read up to 10 bytes. // We use a local [bufferPos] variable to avoid repeatedly loading/store the // this._bufferpos field. var bufferPos = _bufferPos; var bytes = _currentLimit - bufferPos; if (bytes > 10) bytes = 10; var result = 0; for (var i = 0; i < bytes; i++) { var byte = _buffer[bufferPos++]; result |= (byte & 0x7f) << (i * 7); if ((byte & 0x80) == 0) { result &= 0xffffffff; _bufferPos = bufferPos; return signed ? result - 2 * (0x80000000 & result) : result; } } _bufferPos = bufferPos; throw InvalidProtocolBufferException.malformedVarint(); } Int64 _readRawVarint64() { var lo = 0; var hi = 0; // Read low 28 bits. for (var i = 0; i < 4; i++) { var byte = _readRawVarintByte(); lo |= (byte & 0x7f) << (i * 7); if ((byte & 0x80) == 0) return Int64.fromInts(hi, lo); } // Read middle 7 bits: 4 low belong to low part above, // 3 remaining belong to hi. var byte = _readRawVarintByte(); lo |= (byte & 0xf) << 28; hi = (byte >> 4) & 0x7; if ((byte & 0x80) == 0) { return Int64.fromInts(hi, lo); } // Read remaining bits of hi. for (var i = 0; i < 5; i++) { var byte = _readRawVarintByte(); hi |= (byte & 0x7f) << ((i * 7) + 3); if ((byte & 0x80) == 0) return Int64.fromInts(hi, lo); } throw InvalidProtocolBufferException.malformedVarint(); } ByteData _readByteData(int sizeInBytes) { _checkLimit(sizeInBytes); return ByteData.view(_buffer.buffer, _buffer.offsetInBytes + _bufferPos - sizeInBytes, sizeInBytes); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/readonly_message.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; /// Modifies a GeneratedMessage so that it's read-only. abstract class ReadonlyMessageMixin { BuilderInfo get info_; void addExtension(Extension extension, var value) => _readonly('addExtension'); void clear() => _readonly('clear'); void clearExtension(Extension extension) => _readonly('clearExtension'); void clearField(int tagNumber) => _readonly('clearField'); List<T> createRepeatedField<T>(int tagNumber, FieldInfo<T> fi) { _readonly('createRepeatedField'); return null; // not reached } void mergeFromBuffer(List<int> input, [ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) => _readonly('mergeFromBuffer'); void mergeFromCodedBufferReader(CodedBufferReader input, [ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) => _readonly('mergeFromCodedBufferReader'); void mergeFromJson(String data, [ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) => _readonly('mergeFromJson'); void mergeFromJsonMap(Map<String, dynamic> json, [ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) => _readonly('mergeFromJsonMap'); void mergeFromMessage(GeneratedMessage other) => _readonly('mergeFromMessage'); void mergeUnknownFields(UnknownFieldSet unknownFieldSet) => _readonly('mergeUnknownFields'); void setExtension(Extension extension, var value) => _readonly('setExtension'); void setField(int tagNumber, var value, [int fieldType]) => _readonly('setField'); void _readonly(String methodName) { var messageType = info_.qualifiedMessageName; frozenMessageModificationHandler(messageType, methodName); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/permissive_compare.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Returns true if [a] and [b] are the same ignoring case and all instances of /// `-` and `_`. /// /// This is specialized code for comparing enum names. /// Works only for ascii strings containing letters and `_` and `-`. bool permissiveCompare(String a, String b) { const dash = 45; const underscore = 95; var i = 0; var j = 0; while (true) { int ca, cb; do { ca = i < a.length ? a.codeUnitAt(i++) : -1; } while (ca == dash || ca == underscore); do { cb = j < b.length ? b.codeUnitAt(j++) : -1; } while (cb == dash || cb == underscore); if (ca == cb) { if (ca == -1) return true; // Both at end continue; } if (ca ^ cb != 0x20 || !_isAsciiLetter(ca)) { return false; } } } bool _isAsciiLetter(int char) { const lowerA = 97; const lowerZ = 122; const capitalA = 65; char |= lowerA ^ capitalA; return lowerA <= char && char <= lowerZ; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/field_info.dart
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; /// An object representing a protobuf message field. class FieldInfo<T> { FrozenPbList<T> _emptyList; /// Name of this field as the `json_name` reported by protoc. /// /// This will typically be in camel case. final String name; /// The name of this field as written in the proto-definition. /// /// This will typically consist of words separated with underscores. final String protoName; final int tagNumber; final int index; // index of the field's value. Null for extensions. final int type; // Constructs the default value of a field. // (Only used for repeated fields where check is null.) final MakeDefaultFunc makeDefault; // Creates an empty message or group when decoding a message. // Not used for other types. // see GeneratedMessage._getEmptyMessage final CreateBuilderFunc subBuilder; // List of all enum enumValues. // (Not used for other types.) final List<ProtobufEnum> enumValues; // Looks up the enum value given its integer code. // (Not used for other types.) // see GeneratedMessage._getValueOfFunc final ValueOfFunc valueOf; // Verifies an item being added to a repeated field // (Not used for non-repeated fields.) final CheckFunc<T> check; FieldInfo(this.name, this.tagNumber, this.index, this.type, {dynamic defaultOrMaker, this.subBuilder, this.valueOf, this.enumValues, String protoName}) : makeDefault = findMakeDefault(type, defaultOrMaker), check = null, protoName = protoName ?? _unCamelCase(name), assert(type != 0), assert(!_isGroupOrMessage(type) || subBuilder != null || _isMapField(type)), assert(!_isEnum(type) || valueOf != null); // Represents a field that has been removed by a program transformation. FieldInfo.dummy(this.index) : name = '<removed field>', protoName = '<removed field>', tagNumber = 0, type = 0, makeDefault = null, valueOf = null, check = null, enumValues = null, subBuilder = null; FieldInfo.repeated(this.name, this.tagNumber, this.index, this.type, this.check, this.subBuilder, {this.valueOf, this.enumValues, String protoName}) : makeDefault = (() => PbList<T>(check: check)), protoName = protoName ?? _unCamelCase(name) { assert(name != null); assert(tagNumber != null); assert(_isRepeated(type)); assert(check != null); assert(!_isEnum(type) || valueOf != null); } static MakeDefaultFunc findMakeDefault(int type, dynamic defaultOrMaker) { if (defaultOrMaker == null) return PbFieldType._defaultForType(type); if (defaultOrMaker is MakeDefaultFunc) return defaultOrMaker; return () => defaultOrMaker; } /// Returns `true` if this represents a dummy field standing in for a field /// that has been removed by a program transformation. bool get _isDummy => tagNumber == 0; bool get isRequired => _isRequired(type); bool get isRepeated => _isRepeated(type); bool get isGroupOrMessage => _isGroupOrMessage(type); bool get isEnum => _isEnum(type); bool get isMapField => _isMapField(type); /// Returns a read-only default value for a field. /// (Unlike getField, doesn't create a repeated field.) dynamic get readonlyDefault { if (isRepeated) { return _emptyList ??= FrozenPbList._([]); } return makeDefault(); } /// Returns true if the field's value is okay to transmit. /// That is, it doesn't contain any required fields that aren't initialized. bool _hasRequiredValues(value) { if (value == null) return !isRequired; // missing is okay if optional if (!_isGroupOrMessage(type)) return true; // primitive and present if (!isRepeated) { // A required message: recurse. GeneratedMessage message = value; return message._fieldSet._hasRequiredValues(); } List<GeneratedMessage> list = value; if (list.isEmpty) return true; // For message types that (recursively) contain no required fields, // short-circuit the loop. if (!list[0]._fieldSet._hasRequiredFields) return true; // Recurse on each item in the list. return list.every((GeneratedMessage m) => m._fieldSet._hasRequiredValues()); } /// Appends the dotted path to each required field that's missing a value. void _appendInvalidFields(List<String> problems, value, String prefix) { if (value == null) { if (isRequired) problems.add('$prefix$name'); } else if (!_isGroupOrMessage(type)) { // primitive and present } else if (!isRepeated) { // Required message/group: recurse. GeneratedMessage message = value; message._fieldSet._appendInvalidFields(problems, '$prefix$name.'); } else { final list = value as List<GeneratedMessage>; if (list.isEmpty) return; // For message types that (recursively) contain no required fields, // short-circuit the loop. if (!list[0]._fieldSet._hasRequiredFields) return; // Recurse on each item in the list. var position = 0; for (var message in list) { message._fieldSet ._appendInvalidFields(problems, '$prefix$name[$position].'); position++; } } } /// Creates a repeated field to be attached to the given message. /// /// Delegates actual list creation to the message, so that it can /// be overridden by a mixin. List<T> _createRepeatedField(GeneratedMessage m) { assert(isRepeated); return m.createRepeatedField<T>(tagNumber, this); } /// Same as above, but allow a tighter typed List to be created. List<S> _createRepeatedFieldWithType<S extends T>(GeneratedMessage m) { assert(isRepeated); return m.createRepeatedField<S>(tagNumber, this); } /// Convenience method to thread this FieldInfo's reified type parameter to /// _FieldSet._ensureRepeatedField. List<T> _ensureRepeatedField(_FieldSet fs) { return fs._ensureRepeatedField<T>(this); } @override String toString() => name; } final RegExp _upperCase = RegExp('[A-Z]'); String _unCamelCase(String name) { return name.replaceAllMapped( _upperCase, (match) => '_${match.group(0).toLowerCase()}'); } class MapFieldInfo<K, V> extends FieldInfo<PbMap<K, V>> { final int keyFieldType; final int valueFieldType; /// Creates a new empty instance of the value type. /// /// `null` if the value type is not a Message type. final CreateBuilderFunc valueCreator; final BuilderInfo mapEntryBuilderInfo; MapFieldInfo( String name, int tagNumber, int index, int type, this.keyFieldType, this.valueFieldType, this.mapEntryBuilderInfo, this.valueCreator, {String protoName}) : super(name, tagNumber, index, type, defaultOrMaker: () => PbMap<K, V>(keyFieldType, valueFieldType, mapEntryBuilderInfo), protoName: protoName) { assert(name != null); assert(tagNumber != null); assert(_isMapField(type)); assert(!_isEnum(type) || valueOf != null); } FieldInfo get valueFieldInfo => mapEntryBuilderInfo.fieldInfo[PbMap._valueFieldNumber]; Map<K, V> _ensureMapField(_FieldSet fs) { return fs._ensureMapField<K, V>(this); } Map<K, V> _createMapField(GeneratedMessage m) { assert(isMapField); return m.createMapField<K, V>(tagNumber, this); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/type_registry.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import '../../protobuf.dart'; /// A TypeRegistry is used to resolve Any messages in the proto3 JSON conversion. /// /// You must provide a TypeRegistry containing all message types used in /// Any message fields, or the JSON conversion will fail because data /// in Any message fields is unrecognizable. You don't need to supply a /// TypeRegistry if you don't use Any message fields. class TypeRegistry { final Map<String, BuilderInfo> _mapping; /// Constructs a new TypeRegistry recognizing the given types of messages. /// /// You can use an empty message of the given type to represent the type. Eg: /// /// ```dart /// TypeRegistry([Foo(), Bar()]); /// ``` TypeRegistry(Iterable<GeneratedMessage> types) : _mapping = Map.fromEntries(types.map((message) => MapEntry(message.info_.qualifiedMessageName, message.info_))); const TypeRegistry.empty() : _mapping = const {}; BuilderInfo lookup(String qualifiedName) { return _mapping[qualifiedName]; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/field_set.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; typedef FrozenMessageErrorHandler = void Function(String messageName, [String methodName]); void defaultFrozenMessageModificationHandler(String messageName, [String methodName]) { if (methodName != null) { throw UnsupportedError( 'Attempted to call $methodName on a read-only message ($messageName)'); } throw UnsupportedError( 'Attempted to change a read-only message ($messageName)'); } /// Invoked when an attempt is made to modify a frozen message. /// /// This handler can log the attempt, throw an exception, or ignore the attempt /// altogether. /// /// If the handler returns normally, the modification is allowed, and execution /// proceeds as if the message was writable. FrozenMessageErrorHandler _frozenMessageModificationHandler = defaultFrozenMessageModificationHandler; FrozenMessageErrorHandler get frozenMessageModificationHandler => _frozenMessageModificationHandler; set frozenMessageModificationHandler(FrozenMessageErrorHandler value) { _hashCodesCanBeMemoized = false; _frozenMessageModificationHandler = value; } /// Indicator for whether the FieldSet hashCodes can be memoized. /// /// HashCode memoization relies on the [defaultFrozenMessageModificationHandler] /// behavior--that is, after freezing, field set values can't ever be changed. /// This keeps track of whether an application has ever modified the /// [FrozenMessageErrorHandler] used, not allowing hashCodes to be memoized if /// it ever changed. bool _hashCodesCanBeMemoized = true; /// All the data in a GeneratedMessage. /// /// These fields and methods are in a separate class to avoid /// polymorphic access due to inheritance. This turns out to /// be faster when compiled to JavaScript. class _FieldSet { final GeneratedMessage _message; final BuilderInfo _meta; final EventPlugin _eventPlugin; /// The value of each non-extension field in a fixed-length array. /// The index of a field can be found in [FieldInfo.index]. /// A null entry indicates that the field has no value. final List _values; /// Contains all the extension fields, or null if there aren't any. _ExtensionFieldSet _extensions; /// Contains all the unknown fields, or null if there aren't any. UnknownFieldSet _unknownFields; /// Encodes whether `this` has been frozen, and if so, also memoizes the /// hash code. /// /// Will always be a `bool` or `int`. /// /// If the message is mutable: `false` /// If the message is frozen and no hash code has been computed: `true` /// If the message is frozen and a hash code has been computed: the hash /// code as an `int`. Object _frozenState = false; /// Returns the value of [_frozenState] as if it were a boolean indicator /// for whether `this` is read-only (has been frozen). /// /// If the value is not a `bool`, then it must contain the memoized hash code /// value, in which case the proto must be read-only. bool get _isReadOnly => _frozenState is bool ? _frozenState : true; /// Returns the value of [_frozenState] if it contains the pre-computed value /// of the hashCode for the frozen field sets. /// /// Computing the hashCode of a proto object can be very expensive for large /// protos. Frozen protos don't allow any mutations, which means the contents /// of the field set should be stable. /// /// If [_frozenState] contains a boolean, the hashCode hasn't been memoized, /// so it will return null. int get _memoizedHashCode => _frozenState is int ? _frozenState : null; // Maps a oneof decl index to the tag number which is currently set. If the // index is not present, the oneof field is unset. final Map<int, int> _oneofCases; _FieldSet(this._message, BuilderInfo meta, this._eventPlugin) : _meta = meta, _values = _makeValueList(meta.byIndex.length), _oneofCases = meta.oneofs.isEmpty ? null : <int, int>{}; static List _makeValueList(int length) { if (length == 0) return _zeroList; return List(length); } // Use a fixed length list and not a constant list to ensure that _values // always has the same implementation type. static final List _zeroList = List(0); // Metadata about multiple fields String get _messageName => _meta.qualifiedMessageName; bool get _hasRequiredFields => _meta.hasRequiredFields; /// The FieldInfo for each non-extension field. Iterable<FieldInfo> get _infos => _meta.fieldInfo.values; /// The FieldInfo for each non-extension field in tag order. Iterable<FieldInfo> get _infosSortedByTag => _meta.sortedByTag; /// Returns true if we should send events to the plugin. bool get _hasObservers => _eventPlugin != null && _eventPlugin.hasObservers; bool get _hasExtensions => _extensions != null; bool get _hasUnknownFields => _unknownFields != null; _ExtensionFieldSet _ensureExtensions() { if (!_hasExtensions) _extensions = _ExtensionFieldSet(this); return _extensions; } UnknownFieldSet _ensureUnknownFields() { if (_unknownFields == null) { if (_isReadOnly) return UnknownFieldSet.emptyUnknownFieldSet; _unknownFields = UnknownFieldSet(); } return _unknownFields; } // Metadata about single fields /// Returns FieldInfo for a non-extension field, or null if not found. FieldInfo _nonExtensionInfo(int tagNumber) => _meta.fieldInfo[tagNumber]; /// Returns FieldInfo for a non-extension field. FieldInfo _nonExtensionInfoByIndex(int index) => _meta.byIndex[index]; /// Returns the FieldInfo for a regular or extension field. /// throws ArgumentException if no info is found. FieldInfo _ensureInfo(int tagNumber) { var fi = _getFieldInfoOrNull(tagNumber); if (fi != null) return fi; throw ArgumentError('tag $tagNumber not defined in $_messageName'); } /// Returns the FieldInfo for a regular or extension field. FieldInfo _getFieldInfoOrNull(int tagNumber) { var fi = _nonExtensionInfo(tagNumber); if (fi != null) return fi; if (!_hasExtensions) return null; return _extensions._getInfoOrNull(tagNumber); } void _markReadOnly() { if (_isReadOnly) return; _frozenState = true; for (var field in _meta.sortedByTag) { if (field.isRepeated) { final entries = _values[field.index]; if (entries == null) continue; if (field.isGroupOrMessage) { for (var subMessage in entries as List<GeneratedMessage>) { subMessage.freeze(); } } _values[field.index] = entries.toFrozenPbList(); } else if (field.isMapField) { PbMap map = _values[field.index]; if (map == null) continue; _values[field.index] = map.freeze(); } else if (field.isGroupOrMessage) { final entry = _values[field.index]; if (entry != null) { (entry as GeneratedMessage).freeze(); } } } if (_hasExtensions) { _ensureExtensions()._markReadOnly(); } if (_hasUnknownFields) { _ensureUnknownFields()._markReadOnly(); } } void _ensureWritable() { if (_isReadOnly) frozenMessageModificationHandler(_messageName); } // Single-field operations /// Gets a field with full error-checking. /// /// Works for both extended and non-extended fields. /// Creates repeated fields (unless read-only). /// Suitable for public API. dynamic _getField(int tagNumber) { var fi = _nonExtensionInfo(tagNumber); if (fi != null) { var value = _values[fi.index]; if (value != null) return value; return _getDefault(fi); } if (_hasExtensions) { var fi = _extensions._getInfoOrNull(tagNumber); if (fi != null) { return _extensions._getFieldOrDefault(fi); } } throw ArgumentError('tag $tagNumber not defined in $_messageName'); } dynamic _getDefault(FieldInfo fi) { if (!fi.isRepeated) return fi.makeDefault(); if (_isReadOnly) return fi.readonlyDefault; // TODO(skybrian) we could avoid this by generating another // method for repeated fields: // msg.mutableFoo().add(123); var value = fi._createRepeatedField(_message); _setNonExtensionFieldUnchecked(fi, value); return value; } List<T> _getDefaultList<T>(FieldInfo<T> fi) { assert(fi.isRepeated); if (_isReadOnly) return List.unmodifiable(const []); // TODO(skybrian) we could avoid this by generating another // method for repeated fields: // msg.mutableFoo().add(123); var value = fi._createRepeatedFieldWithType<T>(_message); _setNonExtensionFieldUnchecked(fi, value); return value; } Map<K, V> _getDefaultMap<K, V>(MapFieldInfo<K, V> fi) { assert(fi.isMapField); if (_isReadOnly) { return PbMap<K, V>.unmodifiable(PbMap<K, V>( fi.keyFieldType, fi.valueFieldType, fi.mapEntryBuilderInfo)); } var value = fi._createMapField(_message); _setNonExtensionFieldUnchecked(fi, value); return value; } dynamic _getFieldOrNullByTag(int tagNumber) { var fi = _getFieldInfoOrNull(tagNumber); if (fi == null) return null; return _getFieldOrNull(fi); } /// Returns the field's value or null if not set. /// /// Works for both extended and non-extend fields. /// Works for both repeated and non-repeated fields. dynamic _getFieldOrNull(FieldInfo fi) { if (fi.index != null) return _values[fi.index]; if (!_hasExtensions) return null; return _extensions._getFieldOrNull(fi); } bool _hasField(int tagNumber) { var fi = _nonExtensionInfo(tagNumber); if (fi != null) return _$has(fi.index); if (!_hasExtensions) return false; return _extensions._hasField(tagNumber); } void _clearField(int tagNumber) { _ensureWritable(); var fi = _nonExtensionInfo(tagNumber); if (fi != null) { // clear a non-extension field if (_hasObservers) _eventPlugin.beforeClearField(fi); _values[fi.index] = null; if (_meta.oneofs.containsKey(fi.tagNumber)) { _oneofCases.remove(_meta.oneofs[fi.tagNumber]); } var oneofIndex = _meta.oneofs[fi.tagNumber]; if (oneofIndex != null) _oneofCases[oneofIndex] = 0; return; } if (_hasExtensions) { var fi = _extensions._getInfoOrNull(tagNumber); if (fi != null) { _extensions._clearField(fi); return; } } // neither a regular field nor an extension. // TODO(skybrian) throw? } /// Sets a non-repeated field with error-checking. /// /// Works for both extended and non-extended fields. /// Suitable for public API. void _setField(int tagNumber, value) { if (value == null) throw ArgumentError('value is null'); var fi = _nonExtensionInfo(tagNumber); if (fi == null) { if (!_hasExtensions) { throw ArgumentError('tag $tagNumber not defined in $_messageName'); } _extensions._setField(tagNumber, value); return; } if (fi.isRepeated) { throw ArgumentError(_setFieldFailedMessage( fi, value, 'repeating field (use get + .add())')); } _validateField(fi, value); _setNonExtensionFieldUnchecked(fi, value); } /// Sets a non-repeated field without validating it. /// /// Works for both extended and non-extended fields. /// Suitable for decoders that do their own validation. void _setFieldUnchecked(FieldInfo fi, value) { assert(fi != null); assert(!fi.isRepeated); if (fi.index == null) { _ensureExtensions() .._addInfoUnchecked(fi) .._setFieldUnchecked(fi, value); } else { _setNonExtensionFieldUnchecked(fi, value); } } /// Returns the list to use for adding to a repeated field. /// /// Works for both extended and non-extended fields. /// Creates and stores the repeated field if it doesn't exist. /// If it's an extension and the list doesn't exist, validates and stores it. /// Suitable for decoders. List<T> _ensureRepeatedField<T>(FieldInfo<T> fi) { assert(!_isReadOnly); assert(fi.isRepeated); if (fi.index == null) { return _ensureExtensions()._ensureRepeatedField(fi); } var value = _getFieldOrNull(fi); if (value != null) return value as List<T>; var newValue = fi._createRepeatedField(_message); _setNonExtensionFieldUnchecked(fi, newValue); return newValue; } PbMap<K, V> _ensureMapField<K, V>(MapFieldInfo<K, V> fi) { assert(!_isReadOnly); assert(fi.isMapField); assert(fi.index != null); // Map fields are not allowed to be extensions. var value = _getFieldOrNull(fi); if (value != null) return value as Map<K, V>; var newValue = fi._createMapField(_message); _setNonExtensionFieldUnchecked(fi, newValue); return newValue; } /// Sets a non-extended field and fires events. void _setNonExtensionFieldUnchecked(FieldInfo fi, value) { var tag = fi.tagNumber; var oneofIndex = _meta.oneofs[tag]; if (oneofIndex != null) { _clearField(_oneofCases[oneofIndex]); _oneofCases[oneofIndex] = tag; } // It is important that the callback to the observers is not moved to the // beginning of this method but happens just before the value is set. // Otherwise the observers will be notified about 'clearField' and // 'setField' events in an incorrect order. if (_hasObservers) { _eventPlugin.beforeSetField(fi, value); } _values[fi.index] = value; } // Generated method implementations /// The implementation of a generated getter. T _$get<T>(int index, T defaultValue) { var value = _values[index]; if (value != null) return value as T; if (defaultValue != null) return defaultValue; return _getDefault(_nonExtensionInfoByIndex(index)) as T; } /// The implementation of a generated getter for a default value determined by /// the field definition value. Common case for submessages. dynamic type /// pushes the type check to the caller. dynamic _$getND(int index) { var value = _values[index]; if (value != null) return value; return _getDefault(_nonExtensionInfoByIndex(index)); } T _$ensure<T>(int index) { if (!_$has(index)) { dynamic value = _nonExtensionInfoByIndex(index).subBuilder(); _$set(index, value); return value; } // The implicit downcast at the return is always correct by construction // from the protoc generator. See `GeneratedMessage.$_getN` for details. return _$getND(index); } /// The implementation of a generated getter for repeated fields. List<T> _$getList<T>(int index) { var value = _values[index]; if (value != null) return value as List<T>; return _getDefaultList<T>(_nonExtensionInfoByIndex(index)); } /// The implementation of a generated getter for map fields. Map<K, V> _$getMap<K, V>(int index) { var value = _values[index]; if (value != null) return value as Map<K, V>; return _getDefaultMap<K, V>(_nonExtensionInfoByIndex(index)); } /// The implementation of a generated getter for `bool` fields. bool _$getB(int index, bool defaultValue) { var value = _values[index]; if (value == null) { if (defaultValue != null) return defaultValue; value = _getDefault(_nonExtensionInfoByIndex(index)); } bool result = value; return result; } /// The implementation of a generated getter for `bool` fields that default to /// `false`. bool _$getBF(int index) { var value = _values[index]; if (value == null) return false; bool result = value; return result; } /// The implementation of a generated getter for int fields. int _$getI(int index, int defaultValue) { var value = _values[index]; if (value == null) { if (defaultValue != null) return defaultValue; value = _getDefault(_nonExtensionInfoByIndex(index)); } int result = value; return result; } /// The implementation of a generated getter for `int` fields (int32, uint32, /// fixed32, sfixed32) that default to `0`. int _$getIZ(int index) { var value = _values[index]; if (value == null) return 0; int result = value; return result; } /// The implementation of a generated getter for String fields. String _$getS(int index, String defaultValue) { var value = _values[index]; if (value == null) { if (defaultValue != null) return defaultValue; value = _getDefault(_nonExtensionInfoByIndex(index)); } String result = value; return result; } /// The implementation of a generated getter for String fields that default to /// the empty string. String _$getSZ(int index) { var value = _values[index]; if (value == null) return ''; String result = value; return result; } /// The implementation of a generated getter for Int64 fields. Int64 _$getI64(int index) { var value = _values[index]; value ??= _getDefault(_nonExtensionInfoByIndex(index)); Int64 result = value; return result; } /// The implementation of a generated 'has' method. bool _$has(int index) { var value = _values[index]; if (value == null) return false; if (value is List) return value.isNotEmpty; return true; } /// The implementation of a generated setter. /// /// In production, does no validation other than a null check. /// Only handles non-repeated, non-extension fields. /// Also, doesn't handle enums or messages which need per-type validation. void _$set(int index, value) { assert(!_nonExtensionInfoByIndex(index).isRepeated); assert(_$check(index, value)); _ensureWritable(); if (value == null) { _$check(index, value); // throw exception for null value } if (_hasObservers) { _eventPlugin.beforeSetField(_nonExtensionInfoByIndex(index), value); } var tag = _meta.byIndex[index].tagNumber; var oneofIndex = _meta.oneofs[tag]; if (oneofIndex != null) { _clearField(_oneofCases[oneofIndex]); _oneofCases[oneofIndex] = tag; } _values[index] = value; } bool _$check(int index, var newValue) { _validateField(_nonExtensionInfoByIndex(index), newValue); return true; // Allows use in an assertion. } // Bulk operations reading or writing multiple fields void _clear() { _ensureWritable(); if (_unknownFields != null) { _unknownFields.clear(); } if (_hasObservers) { for (var fi in _infos) { if (_values[fi.index] != null) { _eventPlugin.beforeClearField(fi); } } if (_hasExtensions) { for (var key in _extensions._tagNumbers) { var fi = _extensions._getInfoOrNull(key); _eventPlugin.beforeClearField(fi); } } } if (_values.isNotEmpty) _values.fillRange(0, _values.length, null); if (_hasExtensions) _extensions._clearValues(); } bool _equals(_FieldSet o) { if (_meta != o._meta) return false; for (var i = 0; i < _values.length; i++) { if (!_equalFieldValues(_values[i], o._values[i])) return false; } if (!_hasExtensions || !_extensions._hasValues) { // Check if other extensions are logically empty. // (Don't create them unnecessarily.) if (o._hasExtensions && o._extensions._hasValues) { return false; } } else { if (!_extensions._equalValues(o._extensions)) return false; } if (_unknownFields == null || _unknownFields.isEmpty) { // Check if other unknown fields is logically empty. // (Don't create them unnecessarily.) if (o._unknownFields != null && o._unknownFields.isNotEmpty) return false; } else { // Check if the other unknown fields has the same fields. if (_unknownFields != o._unknownFields) return false; } return true; } bool _equalFieldValues(left, right) { if (left != null && right != null) return _deepEquals(left, right); var val = left ?? right; // Two uninitialized fields are equal. if (val == null) return true; // One field is null. We are comparing an initialized field // with its default value. // An empty repeated field is the same as uninitialized. // This is because accessing a repeated field automatically creates it. // We don't want reading a field to change equality comparisons. if (val is List && val.isEmpty) return true; // For now, initialized and uninitialized fields are different. // TODO(skybrian) consider other cases; should we compare with the // default value or not? return false; } /// Calculates a hash code based on the contents of the protobuf. /// /// The hash may change when any field changes (recursively). /// Therefore, protobufs used as map keys shouldn't be changed. /// /// If the protobuf contents have been frozen, and the /// [FrozenMessageErrorHandler] has not been changed from the default /// behavior, the hashCode can be memoized to speed up performance. int get _hashCode { if (_hashCodesCanBeMemoized && _memoizedHashCode != null) { return _memoizedHashCode; } // Hashes the value of one field (recursively). int hashField(int hash, FieldInfo fi, value) { if (value is List && value.isEmpty) { return hash; // It's either repeated or an empty byte array. } hash = _HashUtils._combine(hash, fi.tagNumber); if (_isBytes(fi.type)) { // Bytes are represented as a List<int> (Usually with byte-data). // We special case that to match our equality semantics. hash = _HashUtils._combine(hash, _HashUtils._hashObjects(value)); } else if (!_isEnum(fi.type)) { hash = _HashUtils._combine(hash, value.hashCode); } else if (fi.isRepeated) { hash = _HashUtils._hashObjects(value.map((enm) => enm.value)); } else { ProtobufEnum enm = value; hash = _HashUtils._combine(hash, enm.value); } return hash; } int hashEachField(int hash) { //non-extension fields hash = _infosSortedByTag.where((fi) => _values[fi.index] != null).fold( hash, (int h, FieldInfo fi) => hashField(h, fi, _values[fi.index])); if (!_hasExtensions) return hash; hash = _sorted(_extensions._tagNumbers).fold(hash, (int h, int tagNumber) { var fi = _extensions._getInfoOrNull(tagNumber); return hashField(h, fi, _extensions._getFieldOrNull(fi)); }); return hash; } // Hash with descriptor. var hash = _HashUtils._combine(0, _meta.hashCode); // Hash with fields. hash = hashEachField(hash); // Hash with unknown fields. if (_hasUnknownFields) { hash = _HashUtils._combine(hash, _unknownFields.hashCode); } if (_isReadOnly && _hashCodesCanBeMemoized) { _frozenState = hash; } return hash; } void writeString(StringBuffer out, String indent) { void renderValue(key, value) { if (value is GeneratedMessage) { out.write('$indent$key: {\n'); value._fieldSet.writeString(out, '$indent '); out.write('$indent}\n'); } else if (value is MapEntry) { out.write('$indent$key: {${value.key} : ${value.value}} \n'); } else { out.write('$indent$key: $value\n'); } } void writeFieldValue(fieldValue, String name) { if (fieldValue == null) return; if (fieldValue is ByteData) { // TODO(skybrian): possibly unused. Delete? final value = fieldValue.getUint64(0, Endian.little); renderValue(name, value); } else if (fieldValue is PbListBase) { for (var value in fieldValue) { renderValue(name, value); } } else if (fieldValue is PbMap) { for (var entry in fieldValue.entries) { renderValue(name, entry); } } else { renderValue(name, fieldValue); } } _infosSortedByTag .forEach((FieldInfo fi) => writeFieldValue(_values[fi.index], fi.name)); if (_hasExtensions) { _extensions._info.keys.toList() ..sort() ..forEach((int tagNumber) => writeFieldValue( _extensions._values[tagNumber], '[${_extensions._info[tagNumber].name}]')); } if (_hasUnknownFields) { out.write(_unknownFields.toString()); } else { out.write(UnknownFieldSet().toString()); } } /// Merges the contents of the [other] into this message. /// /// Singular fields that are set in [other] overwrite the corresponding fields /// in this message. Repeated fields are appended. Singular sub-messages are /// recursively merged. void _mergeFromMessage(_FieldSet other) { // TODO(https://github.com/dart-lang/protobuf/issues/60): Recognize // when [this] and [other] are the same protobuf (e.g. from cloning). In // this case, we can merge the non-extension fields without field lookups or // validation checks. for (var fi in other._infosSortedByTag) { var value = other._values[fi.index]; if (value != null) _mergeField(fi, value, isExtension: false); } if (other._hasExtensions) { var others = other._extensions; for (var tagNumber in others._tagNumbers) { var extension = others._getInfoOrNull(tagNumber); var value = others._getFieldOrNull(extension); _mergeField(extension, value, isExtension: true); } } if (other._hasUnknownFields) { _ensureUnknownFields().mergeFromUnknownFieldSet(other._unknownFields); } } void _mergeField(FieldInfo otherFi, fieldValue, {bool isExtension}) { var tagNumber = otherFi.tagNumber; // Determine the FieldInfo to use. // Don't allow regular fields to be overwritten by extensions. var fi = _nonExtensionInfo(tagNumber); if (fi == null && isExtension) { // This will overwrite any existing extension field info. fi = otherFi; } var mustClone = _isGroupOrMessage(otherFi.type); if (fi.isMapField) { MapFieldInfo f = fi; mustClone = _isGroupOrMessage(f.valueFieldType); PbMap map = f._ensureMapField(this); if (mustClone) { for (MapEntry entry in fieldValue.entries) { map[entry.key] = (entry.value as GeneratedMessage).deepCopy(); } } else { map.addAll(fieldValue); } return; } if (fi.isRepeated) { if (mustClone) { // fieldValue must be a PbListBase of GeneratedMessage. PbListBase<GeneratedMessage> pbList = fieldValue; var repeatedFields = fi._ensureRepeatedField(this); for (var i = 0; i < pbList.length; ++i) { repeatedFields.add(pbList[i].deepCopy()); } } else { // fieldValue must be at least a PbListBase. PbListBase pbList = fieldValue; fi._ensureRepeatedField(this).addAll(pbList); } return; } if (otherFi.isGroupOrMessage) { final currentFi = isExtension ? _ensureExtensions()._getFieldOrNull(fi) : _values[fi.index]; if (currentFi == null) { fieldValue = (fieldValue as GeneratedMessage).deepCopy(); } else { fieldValue = currentFi..mergeFromMessage(fieldValue); } } if (isExtension) { _ensureExtensions()._setFieldAndInfo(fi, fieldValue); } else { _validateField(fi, fieldValue); _setNonExtensionFieldUnchecked(fi, fieldValue); } } // Error-checking /// Checks the value for a field that's about to be set. void _validateField(FieldInfo fi, var newValue) { _ensureWritable(); var message = _getFieldError(fi.type, newValue); if (message != null) { throw ArgumentError(_setFieldFailedMessage(fi, newValue, message)); } } String _setFieldFailedMessage(FieldInfo fi, var value, String detail) { return 'Illegal to set field ${fi.name} (${fi.tagNumber}) of $_messageName' ' to value ($value): $detail'; } bool _hasRequiredValues() { if (!_hasRequiredFields) return true; for (var fi in _infos) { var value = _values[fi.index]; if (!fi._hasRequiredValues(value)) return false; } return _hasRequiredExtensionValues(); } bool _hasRequiredExtensionValues() { if (!_hasExtensions) return true; for (var fi in _extensions._infos) { var value = _extensions._getFieldOrNull(fi); if (!fi._hasRequiredValues(value)) return false; } return true; // No problems found. } /// Adds the path to each uninitialized field to the list. void _appendInvalidFields(List<String> problems, String prefix) { if (!_hasRequiredFields) return; for (var fi in _infos) { var value = _values[fi.index]; fi._appendInvalidFields(problems, value, prefix); } // TODO(skybrian): search extensions as well // https://github.com/dart-lang/protobuf/issues/46 } /// Makes a shallow copy of all values from [original] to this. /// /// Map fields and repeated fields are copied. void _shallowCopyValues(_FieldSet original) { _values.setRange(0, original._values.length, original._values); for (var index = 0; index < _meta.byIndex.length; index++) { var fieldInfo = _meta.byIndex[index]; if (fieldInfo.isMapField) { PbMap map = _values[index]; if (map != null) { _values[index] = (fieldInfo as MapFieldInfo)._createMapField(_message) ..addAll(map); } } else if (fieldInfo.isRepeated) { PbListBase list = _values[index]; if (list != null) { _values[index] = fieldInfo._createRepeatedField(_message) ..addAll(list); } } } if (original._hasExtensions) { _ensureExtensions()._shallowCopyValues(original._extensions); } if (original._hasUnknownFields) { _ensureUnknownFields()._fields?.addAll(original._unknownFields._fields); } _oneofCases?.addAll(original._oneofCases); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/generated_message.dart
// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; typedef CreateBuilderFunc = GeneratedMessage Function(); typedef MakeDefaultFunc = Function(); typedef ValueOfFunc = ProtobufEnum Function(int value); /// The base class for all protobuf message types. /// /// The protoc plugin generates subclasses providing type-specific /// properties and methods. /// /// Public properties and methods added here should also be added to /// GeneratedMessage_reservedNames and should be unlikely to be used in /// a proto file. abstract class GeneratedMessage { _FieldSet _fieldSet; GeneratedMessage() { _fieldSet = _FieldSet(this, info_, eventPlugin); if (eventPlugin != null) eventPlugin.attach(this); } GeneratedMessage.fromBuffer( List<int> input, ExtensionRegistry extensionRegistry) { _fieldSet = _FieldSet(this, info_, eventPlugin); if (eventPlugin != null) eventPlugin.attach(this); mergeFromBuffer(input, extensionRegistry); } GeneratedMessage.fromJson(String input, ExtensionRegistry extensionRegistry) { _fieldSet = _FieldSet(this, info_, eventPlugin); if (eventPlugin != null) eventPlugin.attach(this); mergeFromJson(input, extensionRegistry); } // Overridden by subclasses. BuilderInfo get info_; /// Subclasses can override this getter to be notified of changes /// to protobuf fields. EventPlugin get eventPlugin => null; /// Creates a deep copy of the fields in this message. /// (The generated code uses [mergeFromMessage].) @Deprecated('Using this can add significant size overhead to your binary. ' 'Use [GeneratedMessageGenericExtensions.deepCopy] instead. ' 'Will be removed in next major version') GeneratedMessage clone(); /// Creates an empty instance of the same message type as this. GeneratedMessage createEmptyInstance(); UnknownFieldSet get unknownFields => _fieldSet._ensureUnknownFields(); /// Make this message read-only. /// /// Marks this message, and any sub-messages, as read-only. GeneratedMessage freeze() { _fieldSet._markReadOnly(); return this; } /// Returns `true` if this message is marked read-only. Otherwise `false`. /// /// Even when `false`, some sub-message could be read-only. /// /// If `true` all sub-messages are frozen. bool get isFrozen => _fieldSet._isReadOnly; /// Returns a writable, shallow copy of this message. /// /// Sub messages will be shared with [this] and will still be frozen if [this] /// is frozen. /// /// The lists representing repeated fields are copied. But their elements will /// be shared with the corresponding list in [this]. /// /// Similarly for map fields, the maps will be copied, but share the elements. // TODO(nichite, sigurdm): Consider returning an actual builder object that // lazily creates builders. GeneratedMessage toBuilder() { final result = createEmptyInstance(); result._fieldSet._shallowCopyValues(_fieldSet); return result; } /// Apply [updates] to a copy of this message. /// /// Makes a writable shawwol copy of this message, applies the [updates] to /// it, and marks the copy read-only before returning it. @Deprecated('Using this can add significant size overhead to your binary. ' 'Use [GeneratedMessageGenericExtensions.rebuild] instead. ' 'Will be removed in next major version') GeneratedMessage copyWith(void Function(GeneratedMessage) updates) { final builder = toBuilder(); updates(builder); return builder.freeze(); } bool hasRequiredFields() => info_.hasRequiredFields; /// Returns [:true:] if all required fields in the message and all embedded /// messages are set, false otherwise. bool isInitialized() => _fieldSet._hasRequiredValues(); /// Clears all data that was set in this message. /// /// After calling [clear], [getField] will still return default values for /// unset fields. void clear() => _fieldSet._clear(); // TODO(antonm): move to getters. int getTagNumber(String fieldName) => info_.tagNumber(fieldName); @override bool operator ==(other) { if (identical(this, other)) return true; return other is GeneratedMessage ? _fieldSet._equals(other._fieldSet) : false; } /// Calculates a hash code based on the contents of the protobuf. /// /// The hash may change when any field changes (recursively). /// Therefore, protobufs used as map keys shouldn't be changed. @override int get hashCode => _fieldSet._hashCode; /// Returns a String representation of this message. /// /// This representation is similar to, but not quite, the Protocol Buffer /// TextFormat. Each field is printed on its own line. Sub-messages are /// indented two spaces farther than their parent messages. /// /// Note that this format is absolutely subject to change, and should only /// ever be used for debugging. @override String toString() => toDebugString(); /// Returns a String representation of this message. /// /// This generates the same output as [toString], but can be used by mixins /// to compose debug strings with additional information. String toDebugString() { var out = StringBuffer(); _fieldSet.writeString(out, ''); return out.toString(); } void check() { if (!isInitialized()) { var invalidFields = <String>[]; _fieldSet._appendInvalidFields(invalidFields, ''); var missingFields = (invalidFields..sort()).join(', '); throw StateError('Message missing required fields: $missingFields'); } } Uint8List writeToBuffer() { var out = CodedBufferWriter(); writeToCodedBufferWriter(out); return out.toBuffer(); } void writeToCodedBufferWriter(CodedBufferWriter output) => _writeToCodedBufferWriter(_fieldSet, output); void mergeFromCodedBufferReader(CodedBufferReader input, [ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) => _mergeFromCodedBufferReader(_fieldSet, input, extensionRegistry); /// Merges serialized protocol buffer data into this message. /// /// For each field in [input] that is already present in this message: /// /// * If it's a repeated field, this appends to the end of our list. /// * Else, if it's a scalar, this overwrites our field. /// * Else, (it's a non-repeated sub-message), this recursively merges into /// the existing sub-message. void mergeFromBuffer(List<int> input, [ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) { var codedInput = CodedBufferReader(input); _mergeFromCodedBufferReader(_fieldSet, codedInput, extensionRegistry); codedInput.checkLastTagWas(0); } // JSON support. /// Returns the JSON encoding of this message as a Dart [Map]. /// /// The encoding is described in [GeneratedMessage.writeToJson]. Map<String, dynamic> writeToJsonMap() => _writeToJsonMap(_fieldSet); /// Returns a JSON string that encodes this message. /// /// Each message (top level or nested) is represented as an object delimited /// by curly braces. Within a message, elements are indexed by tag number /// (surrounded by quotes). Repeated elements are represented as arrays. /// /// Boolean values, strings, and floating-point values are represented as /// literals. Values with a 32-bit integer datatype are represented as integer /// literals; values with a 64-bit integer datatype (regardless of their /// actual runtime value) are represented as strings. Enumerated values are /// represented as their integer value. /// /// For the proto3 JSON format use: [toProto3JSON]. String writeToJson() => jsonEncode(writeToJsonMap()); /// Returns an Object representing Proto3 JSON serialization of [this]. /// /// The key for each field is be the camel-cased name of the field. /// /// Well-known types and their special JSON encoding are supported. /// If a well-known type cannot be encoded (eg. a `google.protobuf.Timestamp` /// with negative `nanoseconds`) an error is thrown. /// /// Extensions and unknown fields are not encoded. /// /// The [typeRegistry] is be used for encoding `Any` messages. If an `Any` /// message encoding a type not in [typeRegistry] is encountered, an /// error is thrown. Object toProto3Json( {TypeRegistry typeRegistry = const TypeRegistry.empty()}) => _writeToProto3Json(_fieldSet, typeRegistry); /// Merges field values from [json], a JSON object using proto3 encoding. /// /// Well-known types and their special JSON encoding are supported. /// /// If [ignoreUnknownFields] is `false` (the default) an /// [FormatException] is be thrown if an unknown field or enum name /// is encountered. Otherwise the unknown field or enum is ignored. /// /// If [supportNamesWithUnderscores] is `true` (the default) field names in /// the JSON can be represented as either camel-case JSON-names or names with /// underscores. /// If `false` only the JSON names are supported. /// /// If [permissiveEnums] is `true` (default `false`) enum values in the /// JSON will be matched without case insensitivity and ignoring `-`s and `_`. /// This allows JSON values like `camelCase` and `kebab-case` to match the /// enum values `CAMEL_CASE` and `KEBAB_CASE`. /// In case of ambiguities between the enum values, the first matching value /// will be found. /// /// The [typeRegistry] is be used for decoding `Any` messages. If an `Any` /// message encoding a type not in [typeRegistry] is encountered, a /// [FormatException] is thrown. /// /// If the JSON is otherwise not formatted correctly (a String where a /// number was expected etc.) a [FormatException] is thrown. void mergeFromProto3Json(Object json, {TypeRegistry typeRegistry = const TypeRegistry.empty(), bool ignoreUnknownFields = false, bool supportNamesWithUnderscores = true, bool permissiveEnums = false}) => _mergeFromProto3Json(json, _fieldSet, typeRegistry, ignoreUnknownFields, supportNamesWithUnderscores, permissiveEnums); /// Merges field values from [data], a JSON object, encoded as described by /// [GeneratedMessage.writeToJson]. /// /// For the proto3 JSON format use: [mergeFromProto3JSON]. void mergeFromJson(String data, [ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) { /// Disable lazy creation of Dart objects for a dart2js speedup. /// This is a slight regression on the Dart VM. /// TODO(skybrian) we could skip the reviver if we're running /// on the Dart VM for a slight speedup. final jsonMap = jsonDecode(data, reviver: _emptyReviver) as Map<String, dynamic>; _mergeFromJsonMap(_fieldSet, jsonMap, extensionRegistry); } static dynamic _emptyReviver(k, v) => v; /// Merges field values from a JSON object represented as a Dart map. /// /// The encoding is described in [GeneratedMessage.writeToJson]. void mergeFromJsonMap(Map<String, dynamic> json, [ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY]) { _mergeFromJsonMap(_fieldSet, json, extensionRegistry); } /// Adds an extension field value to a repeated field. /// /// The backing [List] will be created if necessary. /// If the list already exists, the old extension won't be overwritten. void addExtension(Extension extension, var value) { if (!extension.isRepeated) { throw ArgumentError( 'Cannot add to a non-repeated field (use setExtension())'); } _fieldSet._ensureExtensions().._ensureRepeatedField(extension).add(value); } /// Clears an extension field and also removes the extension. void clearExtension(Extension extension) { if (_fieldSet._hasExtensions) { _fieldSet._extensions._clearFieldAndInfo(extension); } } /// Clears the contents of a given field. /// /// If it's an extension field, the Extension will be kept. /// The tagNumber should be a valid tag or extension. void clearField(int tagNumber) => _fieldSet._clearField(tagNumber); int $_whichOneof(int oneofIndex) => _fieldSet._oneofCases[oneofIndex] ?? 0; bool extensionsAreInitialized() => _fieldSet._hasRequiredExtensionValues(); /// Returns the value of [extension]. /// /// If not set, returns the extension's default value. dynamic getExtension(Extension extension) { return _fieldSet._ensureExtensions()._getFieldOrDefault(extension); } /// Returns the value of the field associated with [tagNumber], or the /// default value if it is not set. dynamic getField(int tagNumber) => _fieldSet._getField(tagNumber); /// Creates List implementing a mutable repeated field. /// /// Mixins may override this method to change the List type. To ensure /// that the protobuf can be encoded correctly, the returned List must /// validate all items added to it. This can most easily be done /// using the FieldInfo.check function. List<T> createRepeatedField<T>(int tagNumber, FieldInfo<T> fi) { return PbList<T>(check: fi.check); } /// Creates a Map representing a map field. Map<K, V> createMapField<K, V>(int tagNumber, MapFieldInfo<K, V> fi) { return PbMap<K, V>( fi.keyFieldType, fi.valueFieldType, fi.mapEntryBuilderInfo); } /// Returns the value of a field, ignoring any defaults. /// /// For unset or cleared fields, returns null. /// Also returns null for unknown tag numbers. dynamic getFieldOrNull(int tagNumber) => _fieldSet._getFieldOrNullByTag(tagNumber); /// Returns the default value for the given field. /// /// For repeated fields, returns an immutable empty list /// (unlike [getField]). For all other fields, returns /// the same thing that getField() would for a cleared field. dynamic getDefaultForField(int tagNumber) => _fieldSet._ensureInfo(tagNumber).readonlyDefault; /// Returns [:true:] if a value of [extension] is present. bool hasExtension(Extension extension) => _fieldSet._hasExtensions && _fieldSet._extensions._getFieldOrNull(extension) != null; /// Returns [:true:] if this message has a field associated with [tagNumber]. bool hasField(int tagNumber) => _fieldSet._hasField(tagNumber); /// Merges the contents of the [other] into this message. /// /// Singular fields that are set in [other] overwrite the corresponding fields /// in this message. Repeated fields are appended. Singular sub-messages are /// recursively merged. void mergeFromMessage(GeneratedMessage other) => _fieldSet._mergeFromMessage(other._fieldSet); void mergeUnknownFields(UnknownFieldSet unknownFieldSet) => _fieldSet ._ensureUnknownFields() .mergeFromUnknownFieldSet(unknownFieldSet); /// Sets the value of a non-repeated extension field to [value]. void setExtension(Extension extension, value) { if (value == null) throw ArgumentError('value is null'); if (_isRepeated(extension.type)) { throw ArgumentError(_fieldSet._setFieldFailedMessage( extension, value, 'repeating field (use get + .add())')); } _fieldSet._ensureExtensions()._setFieldAndInfo(extension, value); } /// Sets the value of a field by its [tagNumber]. /// /// Throws an [:ArgumentError:] if [value] does not match the type /// associated with [tagNumber]. /// /// Throws an [:ArgumentError:] if [value] is [:null:]. To clear a field of /// it's current value, use [clearField] instead. void setField(int tagNumber, value) { _fieldSet._setField(tagNumber, value); return; // ignore: dead_code return; // ignore: dead_code } /// For generated code only. T $_get<T>(int index, T defaultValue) => _fieldSet._$get<T>(index, defaultValue); /// For generated code only. T $_getN<T>(int index) { // The implicit downcast at the return is always correct by construction // from the protoc generator. dart2js will omit the implicit downcast when // compiling with `-O3` or higher. We should introduce some way to // communicate that the downcast cannot fail to the other compilers. // // TODO(sra): With NNDB we will need to add 'as T', and a dart2js annotation // (to be implemented) to omit the 'as' check. return _fieldSet._$getND(index); } /// For generated code only. T $_ensure<T>(int index) { return _fieldSet._$ensure<T>(index); } /// For generated code only. List<T> $_getList<T>(int index) => _fieldSet._$getList<T>(index); /// For generated code only. Map<K, V> $_getMap<K, V>(int index) => _fieldSet._$getMap<K, V>(index); /// For generated code only. bool $_getB(int index, bool defaultValue) => _fieldSet._$getB(index, defaultValue); /// For generated code only. bool $_getBF(int index) => _fieldSet._$getBF(index); /// For generated code only. int $_getI(int index, int defaultValue) => _fieldSet._$getI(index, defaultValue); /// For generated code only. int $_getIZ(int index) => _fieldSet._$getIZ(index); /// For generated code only. String $_getS(int index, String defaultValue) => _fieldSet._$getS(index, defaultValue); /// For generated code only. String $_getSZ(int index) => _fieldSet._$getSZ(index); /// For generated code only. Int64 $_getI64(int index) => _fieldSet._$getI64(index); /// For generated code only. bool $_has(int index) => _fieldSet._$has(index); /// For generated code only. void $_setBool(int index, bool value) => _fieldSet._$set(index, value); /// For generated code only. void $_setBytes(int index, List<int> value) => _fieldSet._$set(index, value); /// For generated code only. void $_setString(int index, String value) => _fieldSet._$set(index, value); /// For generated code only. void $_setFloat(int index, double value) { if (value == null || !_isFloat32(value)) { _fieldSet._$check(index, value); } _fieldSet._$set(index, value); } /// For generated code only. void $_setDouble(int index, double value) => _fieldSet._$set(index, value); /// For generated code only. void $_setSignedInt32(int index, int value) { if (value == null || !_isSigned32(value)) { _fieldSet._$check(index, value); } _fieldSet._$set(index, value); } /// For generated code only. void $_setUnsignedInt32(int index, int value) { if (value == null || !_isUnsigned32(value)) { _fieldSet._$check(index, value); } _fieldSet._$set(index, value); } /// For generated code only. void $_setInt64(int index, Int64 value) => _fieldSet._$set(index, value); // Support for generating a read-only default singleton instance. static final Map<Function, Function> _defaultMakers = {}; static T Function() _defaultMakerFor<T extends GeneratedMessage>( T Function() createFn) { return _defaultMakers[createFn] ??= _createDefaultMakerFor<T>(createFn); } static T Function() _createDefaultMakerFor<T extends GeneratedMessage>( T Function() createFn) { T defaultValue; T defaultMaker() { return defaultValue ??= createFn()..freeze(); } return defaultMaker; } /// For generated code only. static T $_defaultFor<T extends GeneratedMessage>(T Function() createFn) => _defaultMakerFor<T>(createFn)(); } /// The package name of a protobuf message. class PackageName { final String name; const PackageName(this.name); String get prefix => name == '' ? '' : '$name.'; } extension GeneratedMessageGenericExtensions<T extends GeneratedMessage> on T { /// Apply [updates] to a copy of this message. /// /// Throws an [ArgumentError] if `this` is not already frozen. /// /// Makes a writable shallow copy of this message, applies the [updates] to /// it, and marks the copy read-only before returning it. T rebuild(void Function(T) updates) { if (!isFrozen) { throw ArgumentError('Rebuilding only works on frozen messages.'); } final t = toBuilder(); updates(t); return t..freeze(); } /// Returns a writable deep copy of this message. T deepCopy() => info_.createEmptyInstance()..mergeFromMessage(this); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/unknown_field_set.dart
// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; class UnknownFieldSet { static final UnknownFieldSet emptyUnknownFieldSet = UnknownFieldSet() .._markReadOnly(); final Map<int, UnknownFieldSetField> _fields = <int, UnknownFieldSetField>{}; UnknownFieldSet(); UnknownFieldSet._clone(UnknownFieldSet unknownFieldSet) { mergeFromUnknownFieldSet(unknownFieldSet); } UnknownFieldSet clone() => UnknownFieldSet._clone(this); bool get isEmpty => _fields.isEmpty; bool get isNotEmpty => _fields.isNotEmpty; bool _isReadOnly = false; Map<int, UnknownFieldSetField> asMap() => Map.from(_fields); void clear() { _ensureWritable('clear'); _fields.clear(); } UnknownFieldSetField getField(int tagNumber) => _fields[tagNumber]; bool hasField(int tagNumber) => _fields.containsKey(tagNumber); void addField(int number, UnknownFieldSetField field) { _ensureWritable('addField'); _checkFieldNumber(number); _fields[number] = field; } void mergeField(int number, UnknownFieldSetField field) { _ensureWritable('mergeField'); _getField(number) ..varints.addAll(field.varints) ..fixed32s.addAll(field.fixed32s) ..fixed64s.addAll(field.fixed64s) ..lengthDelimited.addAll(field.lengthDelimited) ..groups.addAll(field.groups); } bool mergeFieldFromBuffer(int tag, CodedBufferReader input) { _ensureWritable('mergeFieldFromBuffer'); var number = getTagFieldNumber(tag); switch (getTagWireType(tag)) { case WIRETYPE_VARINT: mergeVarintField(number, input.readInt64()); return true; case WIRETYPE_FIXED64: mergeFixed64Field(number, input.readFixed64()); return true; case WIRETYPE_LENGTH_DELIMITED: mergeLengthDelimitedField(number, input.readBytes()); return true; case WIRETYPE_START_GROUP: var subGroup = input.readUnknownFieldSetGroup(number); mergeGroupField(number, subGroup); return true; case WIRETYPE_END_GROUP: return false; case WIRETYPE_FIXED32: mergeFixed32Field(number, input.readFixed32()); return true; default: throw InvalidProtocolBufferException.invalidWireType(); } } void mergeFromCodedBufferReader(CodedBufferReader input) { _ensureWritable('mergeFromCodedBufferReader'); while (true) { var tag = input.readTag(); if (tag == 0 || !mergeFieldFromBuffer(tag, input)) { break; } } } void mergeFromUnknownFieldSet(UnknownFieldSet other) { _ensureWritable('mergeFromUnknownFieldSet'); for (var key in other._fields.keys) { mergeField(key, other._fields[key]); } } void _checkFieldNumber(int number) { if (number == 0) { throw ArgumentError('Zero is not a valid field number.'); } } void mergeFixed32Field(int number, int value) { _ensureWritable('mergeFixed32Field'); _getField(number).addFixed32(value); } void mergeFixed64Field(int number, Int64 value) { _ensureWritable('mergeFixed64Field'); _getField(number).addFixed64(value); } void mergeGroupField(int number, UnknownFieldSet value) { _ensureWritable('mergeGroupField'); _getField(number).addGroup(value); } void mergeLengthDelimitedField(int number, List<int> value) { _ensureWritable('mergeLengthDelimitedField'); _getField(number).addLengthDelimited(value); } void mergeVarintField(int number, Int64 value) { _ensureWritable('mergeVarintField'); _getField(number).addVarint(value); } UnknownFieldSetField _getField(int number) { _checkFieldNumber(number); if (_isReadOnly) assert(_fields.containsKey(number)); return _fields.putIfAbsent(number, () => UnknownFieldSetField()); } @override bool operator ==(other) { if (other is! UnknownFieldSet) return false; UnknownFieldSet o = other; return _areMapsEqual(o._fields, _fields); } @override int get hashCode { var hash = 0; _fields.forEach((int number, Object value) { hash = 0x1fffffff & ((37 * hash) + number); hash = 0x1fffffff & ((53 * hash) + value.hashCode); }); return hash; } @override String toString() => _toString(''); String _toString(String indent) { var stringBuffer = StringBuffer(); for (var tag in _sorted(_fields.keys)) { var field = _fields[tag]; for (var value in field.values) { if (value is UnknownFieldSet) { stringBuffer ..write('${indent}${tag}: {\n') ..write(value._toString('$indent ')) ..write('${indent}}\n'); } else { if (value is ByteData) { // TODO(antonm): fix for longs. value = value.getUint64(0, Endian.little); } stringBuffer.write('${indent}${tag}: ${value}\n'); } } } return stringBuffer.toString(); } void writeToCodedBufferWriter(CodedBufferWriter output) { for (var key in _fields.keys) { _fields[key].writeTo(key, output); } } void _markReadOnly() { if (_isReadOnly) return; _fields.values.forEach((UnknownFieldSetField f) => f._markReadOnly()); _isReadOnly = true; } void _ensureWritable(String methodName) { if (_isReadOnly) { frozenMessageModificationHandler('UnknownFieldSet', methodName); } } } class UnknownFieldSetField { List<List<int>> _lengthDelimited = <List<int>>[]; List<Int64> _varints = <Int64>[]; List<int> _fixed32s = <int>[]; List<Int64> _fixed64s = <Int64>[]; List<UnknownFieldSet> _groups = <UnknownFieldSet>[]; List<List<int>> get lengthDelimited => _lengthDelimited; List<Int64> get varints => _varints; List<int> get fixed32s => _fixed32s; List<Int64> get fixed64s => _fixed64s; List<UnknownFieldSet> get groups => _groups; bool _isReadOnly = false; void _markReadOnly() { if (_isReadOnly) return; _isReadOnly = true; _lengthDelimited = List.unmodifiable(_lengthDelimited); _varints = List.unmodifiable(_varints); _fixed32s = List.unmodifiable(_fixed32s); _fixed64s = List.unmodifiable(_fixed64s); _groups = List.unmodifiable(_groups); } @override bool operator ==(other) { if (other is! UnknownFieldSetField) return false; UnknownFieldSetField o = other; if (lengthDelimited.length != o.lengthDelimited.length) return false; for (var i = 0; i < lengthDelimited.length; i++) { if (!_areListsEqual(o.lengthDelimited[i], lengthDelimited[i])) { return false; } } if (!_areListsEqual(o.varints, varints)) return false; if (!_areListsEqual(o.fixed32s, fixed32s)) return false; if (!_areListsEqual(o.fixed64s, fixed64s)) return false; if (!_areListsEqual(o.groups, groups)) return false; return true; } @override int get hashCode { var hash = 0; for (final value in lengthDelimited) { for (var i = 0; i < value.length; i++) { hash = 0x1fffffff & (hash + value[i]); hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10)); hash = hash ^ (hash >> 6); } hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3)); hash = hash ^ (hash >> 11); hash = 0x1fffffff & (hash + ((0x00003fff & hash) << 15)); } for (final value in varints) { hash = 0x1fffffff & (hash + (7 * value.hashCode)); } for (final value in fixed32s) { hash = 0x1fffffff & (hash + (37 * value.hashCode)); } for (final value in fixed64s) { hash = 0x1fffffff & (hash + (53 * value.hashCode)); } for (final value in groups) { hash = 0x1fffffff & (hash + value.hashCode); } return hash; } List get values => [] ..addAll(lengthDelimited) ..addAll(varints) ..addAll(fixed32s) ..addAll(fixed64s) ..addAll(groups); void writeTo(int fieldNumber, CodedBufferWriter output) { void write(type, value) { output.writeField(fieldNumber, type, value); } write(PbFieldType._REPEATED_UINT64, varints); write(PbFieldType._REPEATED_FIXED32, fixed32s); write(PbFieldType._REPEATED_FIXED64, fixed64s); write(PbFieldType._REPEATED_BYTES, lengthDelimited); write(PbFieldType._REPEATED_GROUP, groups); } void addGroup(UnknownFieldSet value) { groups.add(value); } void addLengthDelimited(List<int> value) { lengthDelimited.add(value); } void addFixed32(int value) { fixed32s.add(value); } void addFixed64(Int64 value) { fixed64s.add(value); } void addVarint(Int64 value) { varints.add(value); } bool hasRequiredFields() => false; bool isInitialized() => true; int get length => values.length; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/generated_service.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; /// Server side context. class ServerContext { // TODO: Place server specific information in this class. } /// The implementation of a Service API. /// /// The protoc plugin generates subclasses (with names ending with ServiceBase) /// that extend GeneratedService and dispatch requests by method. abstract class GeneratedService { /// Creates a message object that can deserialize a request. GeneratedMessage createRequest(String methodName); /// Dispatches the call. The request object should come from [createRequest]. Future<GeneratedMessage> handleCall( ServerContext ctx, String methodName, GeneratedMessage request); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/rpc_client.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; /// Client side context. class ClientContext { /// The desired timeout of the RPC call. final Duration timeout; ClientContext({this.timeout}); } /// Client-side transport for making calls to a service. /// /// Subclasses implement whatever serialization and networking is needed /// to make a call. They should serialize the request to binary or JSON as /// appropriate and merge the response into the supplied emptyResponse /// before returning it. /// /// The protoc plugin generates a client-side stub for each service that /// takes an RpcClient as a constructor parameter. abstract class RpcClient { /// Sends a request to a server and returns the reply. /// /// The implementation should serialize the request as binary or JSON, as /// appropriate. It should merge the reply into [emptyResponse] and /// return it. Future<T> invoke<T extends GeneratedMessage>( ClientContext ctx, String serviceName, String methodName, GeneratedMessage request, T emptyResponse); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/json.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; Map<String, dynamic> _writeToJsonMap(_FieldSet fs) { dynamic convertToMap(dynamic fieldValue, int fieldType) { var baseType = PbFieldType._baseType(fieldType); if (_isRepeated(fieldType)) { return List.from(fieldValue.map((e) => convertToMap(e, baseType))); } switch (baseType) { case PbFieldType._BOOL_BIT: case PbFieldType._STRING_BIT: case PbFieldType._FLOAT_BIT: case PbFieldType._DOUBLE_BIT: case PbFieldType._INT32_BIT: case PbFieldType._SINT32_BIT: case PbFieldType._UINT32_BIT: case PbFieldType._FIXED32_BIT: case PbFieldType._SFIXED32_BIT: return fieldValue; case PbFieldType._BYTES_BIT: // Encode 'bytes' as a base64-encoded string. return base64Encode(fieldValue as List<int>); case PbFieldType._ENUM_BIT: return fieldValue.value; // assume |value| < 2^52 case PbFieldType._INT64_BIT: case PbFieldType._SINT64_BIT: case PbFieldType._SFIXED64_BIT: return fieldValue.toString(); case PbFieldType._UINT64_BIT: case PbFieldType._FIXED64_BIT: return fieldValue.toStringUnsigned(); case PbFieldType._GROUP_BIT: case PbFieldType._MESSAGE_BIT: return fieldValue.writeToJsonMap(); default: throw 'Unknown type $fieldType'; } } List _writeMap(dynamic fieldValue, MapFieldInfo fi) => List.from(fieldValue.entries.map((MapEntry e) => { '${PbMap._keyFieldNumber}': convertToMap(e.key, fi.keyFieldType), '${PbMap._valueFieldNumber}': convertToMap(e.value, fi.valueFieldType) })); var result = <String, dynamic>{}; for (var fi in fs._infosSortedByTag) { var value = fs._values[fi.index]; if (value == null || (value is List && value.isEmpty)) { continue; // It's missing, repeated, or an empty byte array. } if (_isMapField(fi.type)) { result['${fi.tagNumber}'] = _writeMap(value, fi); continue; } result['${fi.tagNumber}'] = convertToMap(value, fi.type); } if (fs._hasExtensions) { for (var tagNumber in _sorted(fs._extensions._tagNumbers)) { var value = fs._extensions._values[tagNumber]; if (value is List && value.isEmpty) { continue; // It's repeated or an empty byte array. } var fi = fs._extensions._getInfoOrNull(tagNumber); result['$tagNumber'] = convertToMap(value, fi.type); } } return result; } // Merge fields from a previously decoded JSON object. // (Called recursively on nested messages.) void _mergeFromJsonMap( _FieldSet fs, Map<String, dynamic> json, ExtensionRegistry registry) { var keys = json.keys; var meta = fs._meta; for (var key in keys) { var fi = meta.byTagAsString[key]; if (fi == null) { if (registry == null) continue; // Unknown tag; skip fi = registry.getExtension(fs._messageName, int.parse(key)); if (fi == null) continue; // Unknown tag; skip } if (fi.isMapField) { _appendJsonMap(fs, json[key], fi, registry); } else if (fi.isRepeated) { _appendJsonList(fs, json[key], fi, registry); } else { _setJsonField(fs, json[key], fi, registry); } } } void _appendJsonList( _FieldSet fs, List jsonList, FieldInfo fi, ExtensionRegistry registry) { var repeated = fi._ensureRepeatedField(fs); // Micro optimization. Using "for in" generates the following and iterator // alloc: // for (t1 = J.get$iterator$ax(json), t2 = fi.tagNumber, t3 = fi.type, // t4 = J.getInterceptor$ax(repeated); t1.moveNext$0();) for (var i = 0, len = jsonList.length; i < len; i++) { var value = jsonList[i]; var convertedValue = _convertJsonValue(fs, value, fi.tagNumber, fi.type, registry); if (convertedValue != null) { repeated.add(convertedValue); } } } void _appendJsonMap( _FieldSet fs, List jsonList, MapFieldInfo fi, ExtensionRegistry registry) { PbMap map = fi._ensureMapField(fs); for (Map<String, dynamic> jsonEntry in jsonList) { var entryFieldSet = map._entryFieldSet(); final convertedKey = _convertJsonValue( entryFieldSet, jsonEntry['${PbMap._keyFieldNumber}'], PbMap._keyFieldNumber, fi.keyFieldType, registry); final convertedValue = _convertJsonValue( entryFieldSet, jsonEntry['${PbMap._valueFieldNumber}'], PbMap._valueFieldNumber, fi.valueFieldType, registry); map[convertedKey] = convertedValue; } } void _setJsonField( _FieldSet fs, json, FieldInfo fi, ExtensionRegistry registry) { var value = _convertJsonValue(fs, json, fi.tagNumber, fi.type, registry); if (value == null) return; // _convertJsonValue throws exception when it fails to do conversion. // Therefore we run _validateField for debug builds only to validate // correctness of conversion. assert(() { fs._validateField(fi, value); return true; }()); fs._setFieldUnchecked(fi, value); } /// Converts [value] from the Json format to the Dart data type /// suitable for inserting into the corresponding [GeneratedMessage] field. /// /// Returns the converted value. This function returns [null] if the caller /// should ignore the field value, because it is an unknown enum value. /// This function throws [ArgumentError] if it cannot convert the value. dynamic _convertJsonValue(_FieldSet fs, value, int tagNumber, int fieldType, ExtensionRegistry registry) { String expectedType; // for exception message switch (PbFieldType._baseType(fieldType)) { case PbFieldType._BOOL_BIT: if (value is bool) { return value; } else if (value is String) { if (value == 'true') { return true; } else if (value == 'false') { return false; } } else if (value is num) { if (value == 1) { return true; } else if (value == 0) { return false; } } expectedType = 'bool (true, false, "true", "false", 1, 0)'; break; case PbFieldType._BYTES_BIT: if (value is String) { return base64Decode(value); } expectedType = 'Base64 String'; break; case PbFieldType._STRING_BIT: if (value is String) { return value; } expectedType = 'String'; break; case PbFieldType._FLOAT_BIT: case PbFieldType._DOUBLE_BIT: // Allow quoted values, although we don't emit them. if (value is double) { return value; } else if (value is num) { return value.toDouble(); } else if (value is String) { return double.parse(value); } expectedType = 'num or stringified num'; break; case PbFieldType._ENUM_BIT: // Allow quoted values, although we don't emit them. if (value is String) { value = int.parse(value); } if (value is int) { // The following call will return null if the enum value is unknown. // In that case, we want the caller to ignore this value, so we return // null from this method as well. return fs._meta._decodeEnum(tagNumber, registry, value); } expectedType = 'int or stringified int'; break; case PbFieldType._INT32_BIT: case PbFieldType._SINT32_BIT: case PbFieldType._UINT32_BIT: case PbFieldType._FIXED32_BIT: case PbFieldType._SFIXED32_BIT: if (value is int) return value; if (value is String) return int.parse(value); expectedType = 'int or stringified int'; break; case PbFieldType._INT64_BIT: case PbFieldType._SINT64_BIT: case PbFieldType._UINT64_BIT: case PbFieldType._FIXED64_BIT: case PbFieldType._SFIXED64_BIT: if (value is int) return Int64(value); if (value is String) return Int64.parseInt(value); expectedType = 'int or stringified int'; break; case PbFieldType._GROUP_BIT: case PbFieldType._MESSAGE_BIT: if (value is Map) { Map<String, dynamic> messageValue = value; var subMessage = fs._meta._makeEmptyMessage(tagNumber, registry); _mergeFromJsonMap(subMessage._fieldSet, messageValue, registry); return subMessage; } expectedType = 'nested message or group'; break; default: throw ArgumentError('Unknown type $fieldType'); } throw ArgumentError('Expected type $expectedType, got $value'); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/coded_buffer.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; void _writeToCodedBufferWriter(_FieldSet fs, CodedBufferWriter out) { // Sorting by tag number isn't required, but it sometimes enables // performance optimizations for the receiver. See: // https://developers.google.com/protocol-buffers/docs/encoding?hl=en#order for (var fi in fs._infosSortedByTag) { var value = fs._values[fi.index]; if (value == null) continue; out.writeField(fi.tagNumber, fi.type, value); } if (fs._hasExtensions) { for (var tagNumber in _sorted(fs._extensions._tagNumbers)) { var fi = fs._extensions._getInfoOrNull(tagNumber); out.writeField(tagNumber, fi.type, fs._extensions._getFieldOrNull(fi)); } } if (fs._hasUnknownFields) { fs._unknownFields.writeToCodedBufferWriter(out); } } void _mergeFromCodedBufferReader( _FieldSet fs, CodedBufferReader input, ExtensionRegistry registry) { assert(registry != null); while (true) { var tag = input.readTag(); if (tag == 0) return; var wireType = tag & 0x7; var tagNumber = tag >> 3; var fi = fs._nonExtensionInfo(tagNumber); fi ??= registry.getExtension(fs._messageName, tagNumber); if (fi == null || !_wireTypeMatches(fi.type, wireType)) { if (!fs._ensureUnknownFields().mergeFieldFromBuffer(tag, input)) { return; } continue; } // Ignore required/optional packed/unpacked. var fieldType = fi.type; fieldType &= ~(PbFieldType._PACKED_BIT | PbFieldType._REQUIRED_BIT); switch (fieldType) { case PbFieldType._OPTIONAL_BOOL: fs._setFieldUnchecked(fi, input.readBool()); break; case PbFieldType._OPTIONAL_BYTES: fs._setFieldUnchecked(fi, input.readBytes()); break; case PbFieldType._OPTIONAL_STRING: fs._setFieldUnchecked(fi, input.readString()); break; case PbFieldType._OPTIONAL_FLOAT: fs._setFieldUnchecked(fi, input.readFloat()); break; case PbFieldType._OPTIONAL_DOUBLE: fs._setFieldUnchecked(fi, input.readDouble()); break; case PbFieldType._OPTIONAL_ENUM: var rawValue = input.readEnum(); var value = fs._meta._decodeEnum(tagNumber, registry, rawValue); if (value == null) { var unknown = fs._ensureUnknownFields(); unknown.mergeVarintField(tagNumber, Int64(rawValue)); } else { fs._setFieldUnchecked(fi, value); } break; case PbFieldType._OPTIONAL_GROUP: var subMessage = fs._meta._makeEmptyMessage(tagNumber, registry); var oldValue = fs._getFieldOrNull(fi); if (oldValue != null) { subMessage.mergeFromMessage(oldValue); } input.readGroup(tagNumber, subMessage, registry); fs._setFieldUnchecked(fi, subMessage); break; case PbFieldType._OPTIONAL_INT32: fs._setFieldUnchecked(fi, input.readInt32()); break; case PbFieldType._OPTIONAL_INT64: fs._setFieldUnchecked(fi, input.readInt64()); break; case PbFieldType._OPTIONAL_SINT32: fs._setFieldUnchecked(fi, input.readSint32()); break; case PbFieldType._OPTIONAL_SINT64: fs._setFieldUnchecked(fi, input.readSint64()); break; case PbFieldType._OPTIONAL_UINT32: fs._setFieldUnchecked(fi, input.readUint32()); break; case PbFieldType._OPTIONAL_UINT64: fs._setFieldUnchecked(fi, input.readUint64()); break; case PbFieldType._OPTIONAL_FIXED32: fs._setFieldUnchecked(fi, input.readFixed32()); break; case PbFieldType._OPTIONAL_FIXED64: fs._setFieldUnchecked(fi, input.readFixed64()); break; case PbFieldType._OPTIONAL_SFIXED32: fs._setFieldUnchecked(fi, input.readSfixed32()); break; case PbFieldType._OPTIONAL_SFIXED64: fs._setFieldUnchecked(fi, input.readSfixed64()); break; case PbFieldType._OPTIONAL_MESSAGE: var subMessage = fs._meta._makeEmptyMessage(tagNumber, registry); var oldValue = fs._getFieldOrNull(fi); if (oldValue != null) { subMessage.mergeFromMessage(oldValue); } input.readMessage(subMessage, registry); fs._setFieldUnchecked(fi, subMessage); break; case PbFieldType._REPEATED_BOOL: _readPackable(fs, input, wireType, fi, input.readBool); break; case PbFieldType._REPEATED_BYTES: fs._ensureRepeatedField(fi).add(input.readBytes()); break; case PbFieldType._REPEATED_STRING: fs._ensureRepeatedField(fi).add(input.readString()); break; case PbFieldType._REPEATED_FLOAT: _readPackable(fs, input, wireType, fi, input.readFloat); break; case PbFieldType._REPEATED_DOUBLE: _readPackable(fs, input, wireType, fi, input.readDouble); break; case PbFieldType._REPEATED_ENUM: _readPackableToListEnum(fs, input, wireType, fi, tagNumber, registry); break; case PbFieldType._REPEATED_GROUP: var subMessage = fs._meta._makeEmptyMessage(tagNumber, registry); input.readGroup(tagNumber, subMessage, registry); fs._ensureRepeatedField(fi).add(subMessage); break; case PbFieldType._REPEATED_INT32: _readPackable(fs, input, wireType, fi, input.readInt32); break; case PbFieldType._REPEATED_INT64: _readPackable(fs, input, wireType, fi, input.readInt64); break; case PbFieldType._REPEATED_SINT32: _readPackable(fs, input, wireType, fi, input.readSint32); break; case PbFieldType._REPEATED_SINT64: _readPackable(fs, input, wireType, fi, input.readSint64); break; case PbFieldType._REPEATED_UINT32: _readPackable(fs, input, wireType, fi, input.readUint32); break; case PbFieldType._REPEATED_UINT64: _readPackable(fs, input, wireType, fi, input.readUint64); break; case PbFieldType._REPEATED_FIXED32: _readPackable(fs, input, wireType, fi, input.readFixed32); break; case PbFieldType._REPEATED_FIXED64: _readPackable(fs, input, wireType, fi, input.readFixed64); break; case PbFieldType._REPEATED_SFIXED32: _readPackable(fs, input, wireType, fi, input.readSfixed32); break; case PbFieldType._REPEATED_SFIXED64: _readPackable(fs, input, wireType, fi, input.readSfixed64); break; case PbFieldType._REPEATED_MESSAGE: var subMessage = fs._meta._makeEmptyMessage(tagNumber, registry); input.readMessage(subMessage, registry); fs._ensureRepeatedField(fi).add(subMessage); break; case PbFieldType._MAP: fs._ensureMapField(fi)._mergeEntry(input, registry); break; default: throw 'Unknown field type $fieldType'; } } } void _readPackable(_FieldSet fs, CodedBufferReader input, int wireType, FieldInfo fi, Function readFunc) { void readToList(List list) => list.add(readFunc()); _readPackableToList(fs, input, wireType, fi, readToList); } void _readPackableToListEnum(_FieldSet fs, CodedBufferReader input, int wireType, FieldInfo fi, int tagNumber, ExtensionRegistry registry) { void readToList(List list) { var rawValue = input.readEnum(); var value = fs._meta._decodeEnum(tagNumber, registry, rawValue); if (value == null) { var unknown = fs._ensureUnknownFields(); unknown.mergeVarintField(tagNumber, Int64(rawValue)); } else { list.add(value); } } _readPackableToList(fs, input, wireType, fi, readToList); } void _readPackableToList(_FieldSet fs, CodedBufferReader input, int wireType, FieldInfo fi, Function readToList) { var list = fs._ensureRepeatedField(fi); if (wireType == WIRETYPE_LENGTH_DELIMITED) { // Packed. input._withLimit(input.readInt32(), () { while (!input.isAtEnd()) { readToList(list); } }); } else { // Not packed. readToList(list); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/protobuf_enum.dart
// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; /// A base class for all Protocol Buffer enum types. /// /// All Protocol Buffer [:enum:] classes inherit from ProtobufEnum. For /// example, given the following enum defined in a .proto file: /// /// message MyMessage { /// enum Color { /// RED = 0; /// GREEN = 1; /// BLUE = 2; /// }; /// // ... /// } /// /// the generated Dart file will include a [:MyMessage_Color:] class that /// [:extends ProtobufEnum:]. It will also include a [:const MyMessage_Color:] /// for each of the three values defined. Here are some examples: /// /// MyMessage_Color.RED // => a MyMessage_Color instance /// MyMessage_Color.GREEN.value // => 1 /// MyMessage_Color.GREEN.name // => "GREEN" class ProtobufEnum { /// This enum's integer value, as specified in the .proto file. final int value; /// This enum's name, as specified in the .proto file. final String name; /// Returns a new constant ProtobufEnum using [value] and [name]. const ProtobufEnum(this.value, this.name); /// Returns a Map for all of the [ProtobufEnum]s in [byIndex], mapping each /// [ProtobufEnum]'s [value] to the [ProtobufEnum]. static Map<int, T> initByValue<T extends ProtobufEnum>(List<T> byIndex) { var byValue = <int, T>{}; for (var v in byIndex) { byValue[v.value] = v; } return byValue; } // Subclasses will typically have a private constructor and a fixed set of // instances, so `Object.operator==()` will work, and does not need to // be overridden explicitly. @override bool operator ==(Object o); @override int get hashCode => value; /// Returns this enum's [name]. @override String toString() => name; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/json_parsing_context.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. class JsonParsingContext { // A list of indices into maps and lists pointing to the current root. final List<String> _path = <String>[]; final bool ignoreUnknownFields; final bool supportNamesWithUnderscores; final bool permissiveEnums; JsonParsingContext(this.ignoreUnknownFields, this.supportNamesWithUnderscores, this.permissiveEnums); void addMapIndex(String index) { _path.add(index); } void addListIndex(int index) { _path.add(index.toString()); } void popIndex() { _path.removeLast(); } /// Returns a FormatException indicating the indices to the current [path]. Exception parseException(String message, Object source) { var formattedPath = _path.map((s) => '[\"$s\"]').join(); return FormatException( 'Protobuf JSON decoding failed at: root$formattedPath. $message', source); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/field_type.dart
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; bool _isRepeated(int fieldType) => (fieldType & PbFieldType._REPEATED_BIT) != 0; bool _isRequired(int fieldType) => (fieldType & PbFieldType._REQUIRED_BIT) != 0; bool _isEnum(int fieldType) => PbFieldType._baseType(fieldType) == PbFieldType._ENUM_BIT; bool _isBytes(int fieldType) => PbFieldType._baseType(fieldType) == PbFieldType._BYTES_BIT; bool _isGroupOrMessage(int fieldType) => (fieldType & (PbFieldType._GROUP_BIT | PbFieldType._MESSAGE_BIT)) != 0; bool _isMapField(int fieldType) => (fieldType & PbFieldType._MAP_BIT) != 0; /// Defines constants and functions for dealing with fieldType bits. class PbFieldType { /// Returns the base field type without any of the required, repeated /// and packed bits. static int _baseType(int fieldType) => fieldType & ~(_REQUIRED_BIT | _REPEATED_BIT | _PACKED_BIT | _MAP_BIT); static MakeDefaultFunc _defaultForType(int type) { switch (type) { case _OPTIONAL_BOOL: case _REQUIRED_BOOL: return _BOOL_FALSE; case _OPTIONAL_BYTES: case _REQUIRED_BYTES: return _BYTES_EMPTY; case _OPTIONAL_STRING: case _REQUIRED_STRING: return _STRING_EMPTY; case _OPTIONAL_FLOAT: case _REQUIRED_FLOAT: case _OPTIONAL_DOUBLE: case _REQUIRED_DOUBLE: return _DOUBLE_ZERO; case _OPTIONAL_INT32: case _REQUIRED_INT32: case _OPTIONAL_INT64: case _REQUIRED_INT64: case _OPTIONAL_SINT32: case _REQUIRED_SINT32: case _OPTIONAL_SINT64: case _REQUIRED_SINT64: case _OPTIONAL_UINT32: case _REQUIRED_UINT32: case _OPTIONAL_UINT64: case _REQUIRED_UINT64: case _OPTIONAL_FIXED32: case _REQUIRED_FIXED32: case _OPTIONAL_FIXED64: case _REQUIRED_FIXED64: case _OPTIONAL_SFIXED32: case _REQUIRED_SFIXED32: case _OPTIONAL_SFIXED64: case _REQUIRED_SFIXED64: return _INT_ZERO; default: return null; } } // Closures commonly used by initializers. static String _STRING_EMPTY() => ''; static List<int> _BYTES_EMPTY() => <int>[]; static bool _BOOL_FALSE() => false; static int _INT_ZERO() => 0; static double _DOUBLE_ZERO() => 0.0; static const int _REQUIRED_BIT = 0x1; static const int _REPEATED_BIT = 0x2; static const int _PACKED_BIT = 0x4; static const int _BOOL_BIT = 0x10; static const int _BYTES_BIT = 0x20; static const int _STRING_BIT = 0x40; static const int _DOUBLE_BIT = 0x80; static const int _FLOAT_BIT = 0x100; static const int _ENUM_BIT = 0x200; static const int _GROUP_BIT = 0x400; static const int _INT32_BIT = 0x800; static const int _INT64_BIT = 0x1000; static const int _SINT32_BIT = 0x2000; static const int _SINT64_BIT = 0x4000; static const int _UINT32_BIT = 0x8000; static const int _UINT64_BIT = 0x10000; static const int _FIXED32_BIT = 0x20000; static const int _FIXED64_BIT = 0x40000; static const int _SFIXED32_BIT = 0x80000; static const int _SFIXED64_BIT = 0x100000; static const int _MESSAGE_BIT = 0x200000; static const int _MAP_BIT = 0x400000; static const int _OPTIONAL_BOOL = _BOOL_BIT; static const int _OPTIONAL_BYTES = _BYTES_BIT; static const int _OPTIONAL_STRING = _STRING_BIT; static const int _OPTIONAL_FLOAT = _FLOAT_BIT; static const int _OPTIONAL_DOUBLE = _DOUBLE_BIT; static const int _OPTIONAL_ENUM = _ENUM_BIT; static const int _OPTIONAL_GROUP = _GROUP_BIT; static const int _OPTIONAL_INT32 = _INT32_BIT; static const int _OPTIONAL_INT64 = _INT64_BIT; static const int _OPTIONAL_SINT32 = _SINT32_BIT; static const int _OPTIONAL_SINT64 = _SINT64_BIT; static const int _OPTIONAL_UINT32 = _UINT32_BIT; static const int _OPTIONAL_UINT64 = _UINT64_BIT; static const int _OPTIONAL_FIXED32 = _FIXED32_BIT; static const int _OPTIONAL_FIXED64 = _FIXED64_BIT; static const int _OPTIONAL_SFIXED32 = _SFIXED32_BIT; static const int _OPTIONAL_SFIXED64 = _SFIXED64_BIT; static const int _OPTIONAL_MESSAGE = _MESSAGE_BIT; static const int _REQUIRED_BOOL = _REQUIRED_BIT | _BOOL_BIT; static const int _REQUIRED_BYTES = _REQUIRED_BIT | _BYTES_BIT; static const int _REQUIRED_STRING = _REQUIRED_BIT | _STRING_BIT; static const int _REQUIRED_FLOAT = _REQUIRED_BIT | _FLOAT_BIT; static const int _REQUIRED_DOUBLE = _REQUIRED_BIT | _DOUBLE_BIT; static const int _REQUIRED_ENUM = _REQUIRED_BIT | _ENUM_BIT; static const int _REQUIRED_GROUP = _REQUIRED_BIT | _GROUP_BIT; static const int _REQUIRED_INT32 = _REQUIRED_BIT | _INT32_BIT; static const int _REQUIRED_INT64 = _REQUIRED_BIT | _INT64_BIT; static const int _REQUIRED_SINT32 = _REQUIRED_BIT | _SINT32_BIT; static const int _REQUIRED_SINT64 = _REQUIRED_BIT | _SINT64_BIT; static const int _REQUIRED_UINT32 = _REQUIRED_BIT | _UINT32_BIT; static const int _REQUIRED_UINT64 = _REQUIRED_BIT | _UINT64_BIT; static const int _REQUIRED_FIXED32 = _REQUIRED_BIT | _FIXED32_BIT; static const int _REQUIRED_FIXED64 = _REQUIRED_BIT | _FIXED64_BIT; static const int _REQUIRED_SFIXED32 = _REQUIRED_BIT | _SFIXED32_BIT; static const int _REQUIRED_SFIXED64 = _REQUIRED_BIT | _SFIXED64_BIT; static const int _REQUIRED_MESSAGE = _REQUIRED_BIT | _MESSAGE_BIT; static const int _REPEATED_BOOL = _REPEATED_BIT | _BOOL_BIT; static const int _REPEATED_BYTES = _REPEATED_BIT | _BYTES_BIT; static const int _REPEATED_STRING = _REPEATED_BIT | _STRING_BIT; static const int _REPEATED_FLOAT = _REPEATED_BIT | _FLOAT_BIT; static const int _REPEATED_DOUBLE = _REPEATED_BIT | _DOUBLE_BIT; static const int _REPEATED_ENUM = _REPEATED_BIT | _ENUM_BIT; static const int _REPEATED_GROUP = _REPEATED_BIT | _GROUP_BIT; static const int _REPEATED_INT32 = _REPEATED_BIT | _INT32_BIT; static const int _REPEATED_INT64 = _REPEATED_BIT | _INT64_BIT; static const int _REPEATED_SINT32 = _REPEATED_BIT | _SINT32_BIT; static const int _REPEATED_SINT64 = _REPEATED_BIT | _SINT64_BIT; static const int _REPEATED_UINT32 = _REPEATED_BIT | _UINT32_BIT; static const int _REPEATED_UINT64 = _REPEATED_BIT | _UINT64_BIT; static const int _REPEATED_FIXED32 = _REPEATED_BIT | _FIXED32_BIT; static const int _REPEATED_FIXED64 = _REPEATED_BIT | _FIXED64_BIT; static const int _REPEATED_SFIXED32 = _REPEATED_BIT | _SFIXED32_BIT; static const int _REPEATED_SFIXED64 = _REPEATED_BIT | _SFIXED64_BIT; static const int _REPEATED_MESSAGE = _REPEATED_BIT | _MESSAGE_BIT; static const int _PACKED_BOOL = _REPEATED_BIT | _PACKED_BIT | _BOOL_BIT; static const int _PACKED_FLOAT = _REPEATED_BIT | _PACKED_BIT | _FLOAT_BIT; static const int _PACKED_DOUBLE = _REPEATED_BIT | _PACKED_BIT | _DOUBLE_BIT; static const int _PACKED_ENUM = _REPEATED_BIT | _PACKED_BIT | _ENUM_BIT; static const int _PACKED_INT32 = _REPEATED_BIT | _PACKED_BIT | _INT32_BIT; static const int _PACKED_INT64 = _REPEATED_BIT | _PACKED_BIT | _INT64_BIT; static const int _PACKED_SINT32 = _REPEATED_BIT | _PACKED_BIT | _SINT32_BIT; static const int _PACKED_SINT64 = _REPEATED_BIT | _PACKED_BIT | _SINT64_BIT; static const int _PACKED_UINT32 = _REPEATED_BIT | _PACKED_BIT | _UINT32_BIT; static const int _PACKED_UINT64 = _REPEATED_BIT | _PACKED_BIT | _UINT64_BIT; static const int _PACKED_FIXED32 = _REPEATED_BIT | _PACKED_BIT | _FIXED32_BIT; static const int _PACKED_FIXED64 = _REPEATED_BIT | _PACKED_BIT | _FIXED64_BIT; static const int _PACKED_SFIXED32 = _REPEATED_BIT | _PACKED_BIT | _SFIXED32_BIT; static const int _PACKED_SFIXED64 = _REPEATED_BIT | _PACKED_BIT | _SFIXED64_BIT; static const int _MAP = _MAP_BIT | _MESSAGE_BIT; // Short names for use in generated code. // _O_ptional. static const int OB = _OPTIONAL_BOOL; static const int OY = _OPTIONAL_BYTES; static const int OS = _OPTIONAL_STRING; static const int OF = _OPTIONAL_FLOAT; static const int OD = _OPTIONAL_DOUBLE; static const int OE = _OPTIONAL_ENUM; static const int OG = _OPTIONAL_GROUP; static const int O3 = _OPTIONAL_INT32; static const int O6 = _OPTIONAL_INT64; static const int OS3 = _OPTIONAL_SINT32; static const int OS6 = _OPTIONAL_SINT64; static const int OU3 = _OPTIONAL_UINT32; static const int OU6 = _OPTIONAL_UINT64; static const int OF3 = _OPTIONAL_FIXED32; static const int OF6 = _OPTIONAL_FIXED64; static const int OSF3 = _OPTIONAL_SFIXED32; static const int OSF6 = _OPTIONAL_SFIXED64; static const int OM = _OPTIONAL_MESSAGE; // re_Q_uired. static const int QB = _REQUIRED_BOOL; static const int QY = _REQUIRED_BYTES; static const int QS = _REQUIRED_STRING; static const int QF = _REQUIRED_FLOAT; static const int QD = _REQUIRED_DOUBLE; static const int QE = _REQUIRED_ENUM; static const int QG = _REQUIRED_GROUP; static const int Q3 = _REQUIRED_INT32; static const int Q6 = _REQUIRED_INT64; static const int QS3 = _REQUIRED_SINT32; static const int QS6 = _REQUIRED_SINT64; static const int QU3 = _REQUIRED_UINT32; static const int QU6 = _REQUIRED_UINT64; static const int QF3 = _REQUIRED_FIXED32; static const int QF6 = _REQUIRED_FIXED64; static const int QSF3 = _REQUIRED_SFIXED32; static const int QSF6 = _REQUIRED_SFIXED64; static const int QM = _REQUIRED_MESSAGE; // re_P_eated. static const int PB = _REPEATED_BOOL; static const int PY = _REPEATED_BYTES; static const int PS = _REPEATED_STRING; static const int PF = _REPEATED_FLOAT; static const int PD = _REPEATED_DOUBLE; static const int PE = _REPEATED_ENUM; static const int PG = _REPEATED_GROUP; static const int P3 = _REPEATED_INT32; static const int P6 = _REPEATED_INT64; static const int PS3 = _REPEATED_SINT32; static const int PS6 = _REPEATED_SINT64; static const int PU3 = _REPEATED_UINT32; static const int PU6 = _REPEATED_UINT64; static const int PF3 = _REPEATED_FIXED32; static const int PF6 = _REPEATED_FIXED64; static const int PSF3 = _REPEATED_SFIXED32; static const int PSF6 = _REPEATED_SFIXED64; static const int PM = _REPEATED_MESSAGE; // pac_K_ed. static const int KB = _PACKED_BOOL; static const int KE = _PACKED_ENUM; static const int KF = _PACKED_FLOAT; static const int KD = _PACKED_DOUBLE; static const int K3 = _PACKED_INT32; static const int K6 = _PACKED_INT64; static const int KS3 = _PACKED_SINT32; static const int KS6 = _PACKED_SINT64; static const int KU3 = _PACKED_UINT32; static const int KU6 = _PACKED_UINT64; static const int KF3 = _PACKED_FIXED32; static const int KF6 = _PACKED_FIXED64; static const int KSF3 = _PACKED_SFIXED32; static const int KSF6 = _PACKED_SFIXED64; static const int M = _MAP; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/event_plugin.dart
part of protobuf; /// An EventPlugin receives callbacks when the fields of a GeneratedMessage /// change. /// /// A GeneratedMessage mixin can install a plugin by overriding the eventPlugin /// property. The intent is provide mechanism, not policy; each mixin defines /// its own public API, perhaps using streams. /// /// This is a low-level, synchronous API. Event handlers are called in the /// middle of protobuf changes. To avoid exposing half-finished changes /// to user code, plugins should buffer events and send them asynchronously. /// (See event_mixin.dart for an example.) abstract class EventPlugin { /// Initializes the plugin. /// /// GeneratedMessage calls this once in its constructors. void attach(GeneratedMessage parent); /// If false, GeneratedMessage will skip calls to event handlers. bool get hasObservers; /// Called before setting a field. /// /// For repeated fields, this will be called when the list is created. /// (For example in getField and merge methods.) void beforeSetField(FieldInfo fi, newValue); /// Called before clearing a field. void beforeClearField(FieldInfo fi); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/field_error.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; /// Returns the error message for an invalid field value, /// or null if it's valid. /// /// For enums, group, and message fields, this check is only approximate, /// because the exact type isn't included in [fieldType]. String _getFieldError(int fieldType, var value) { switch (PbFieldType._baseType(fieldType)) { case PbFieldType._BOOL_BIT: if (value is! bool) return 'not type bool'; return null; case PbFieldType._BYTES_BIT: if (value is! List) return 'not List'; return null; case PbFieldType._STRING_BIT: if (value is! String) return 'not type String'; return null; case PbFieldType._FLOAT_BIT: if (value is! double) return 'not type double'; if (!_isFloat32(value)) return 'out of range for float'; return null; case PbFieldType._DOUBLE_BIT: if (value is! double) return 'not type double'; return null; case PbFieldType._ENUM_BIT: if (value is! ProtobufEnum) return 'not type ProtobufEnum'; return null; case PbFieldType._INT32_BIT: case PbFieldType._SINT32_BIT: case PbFieldType._SFIXED32_BIT: if (value is! int) return 'not type int'; if (!_isSigned32(value)) return 'out of range for signed 32-bit int'; return null; case PbFieldType._UINT32_BIT: case PbFieldType._FIXED32_BIT: if (value is! int) return 'not type int'; if (!_isUnsigned32(value)) return 'out of range for unsigned 32-bit int'; return null; case PbFieldType._INT64_BIT: case PbFieldType._SINT64_BIT: case PbFieldType._UINT64_BIT: case PbFieldType._FIXED64_BIT: case PbFieldType._SFIXED64_BIT: // We always use the full range of the same Dart type. // It's up to the caller to treat the Int64 as signed or unsigned. // See: https://github.com/dart-lang/protobuf/issues/44 if (value is! Int64) return 'not Int64'; return null; case PbFieldType._GROUP_BIT: case PbFieldType._MESSAGE_BIT: if (value is! GeneratedMessage) return 'not a GeneratedMessage'; return null; default: return 'field has unknown type $fieldType'; } } // entry points for generated code // generated checkItem for message, group, enum calls this void checkItemFailed(val, String className) { throw ArgumentError('Value ($val) is not an instance of ${className}'); } /// Returns a function for validating items in a repeated field. /// /// For most types this is a not-null check, except for floats, and signed and /// unsigned 32 bit ints where there also is a range check. CheckFunc getCheckFunction(int fieldType) { switch (fieldType & ~0x7) { case PbFieldType._BOOL_BIT: case PbFieldType._BYTES_BIT: case PbFieldType._STRING_BIT: case PbFieldType._DOUBLE_BIT: case PbFieldType._ENUM_BIT: case PbFieldType._GROUP_BIT: case PbFieldType._MESSAGE_BIT: case PbFieldType._INT64_BIT: case PbFieldType._SINT64_BIT: case PbFieldType._SFIXED64_BIT: case PbFieldType._UINT64_BIT: case PbFieldType._FIXED64_BIT: // We always use the full range of the same Dart type. // It's up to the caller to treat the Int64 as signed or unsigned. // See: https://github.com/dart-lang/protobuf/issues/44 return _checkNotNull; case PbFieldType._FLOAT_BIT: return _checkFloat; case PbFieldType._INT32_BIT: case PbFieldType._SINT32_BIT: case PbFieldType._SFIXED32_BIT: return _checkSigned32; case PbFieldType._UINT32_BIT: case PbFieldType._FIXED32_BIT: return _checkUnsigned32; } throw ArgumentError('check function not implemented: ${fieldType}'); } // check functions for repeated fields void _checkNotNull(Object val) { if (val == null) { throw ArgumentError("Can't add a null to a repeated field"); } } void _checkFloat(Object val) { if (!_isFloat32(val)) throw _createFieldRangeError(val, 'a float'); } void _checkSigned32(Object val) { if (!_isSigned32(val)) throw _createFieldRangeError(val, 'a signed int32'); } void _checkUnsigned32(Object val) { if (!_isUnsigned32(val)) { throw _createFieldRangeError(val, 'an unsigned int32'); } } RangeError _createFieldRangeError(val, String wantedType) => RangeError('Value ($val) is not ${wantedType}'); bool _isSigned32(int value) => (-2147483648 <= value) && (value <= 2147483647); bool _isUnsigned32(int value) => (0 <= value) && (value <= 4294967295); bool _isFloat32(double value) => value.isNaN || value.isInfinite || (-3.4028234663852886E38 <= value) && (value <= 3.4028234663852886E38);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/wire_format.dart
// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; const int TAG_TYPE_BITS = 3; const int TAG_TYPE_MASK = (1 << TAG_TYPE_BITS) - 1; const int WIRETYPE_VARINT = 0; const int WIRETYPE_FIXED64 = 1; const int WIRETYPE_LENGTH_DELIMITED = 2; const int WIRETYPE_START_GROUP = 3; const int WIRETYPE_END_GROUP = 4; const int WIRETYPE_FIXED32 = 5; int getTagFieldNumber(int tag) => tag >> TAG_TYPE_BITS; int getTagWireType(int tag) => tag & TAG_TYPE_MASK; int makeTag(int fieldNumber, int tag) => (fieldNumber << TAG_TYPE_BITS) | tag; /// Returns true if the wireType can be merged into the given fieldType. bool _wireTypeMatches(int fieldType, int wireType) { switch (PbFieldType._baseType(fieldType)) { case PbFieldType._BOOL_BIT: case PbFieldType._ENUM_BIT: case PbFieldType._INT32_BIT: case PbFieldType._INT64_BIT: case PbFieldType._SINT32_BIT: case PbFieldType._SINT64_BIT: case PbFieldType._UINT32_BIT: case PbFieldType._UINT64_BIT: return wireType == WIRETYPE_VARINT || wireType == WIRETYPE_LENGTH_DELIMITED; case PbFieldType._FLOAT_BIT: case PbFieldType._FIXED32_BIT: case PbFieldType._SFIXED32_BIT: return wireType == WIRETYPE_FIXED32 || wireType == WIRETYPE_LENGTH_DELIMITED; case PbFieldType._DOUBLE_BIT: case PbFieldType._FIXED64_BIT: case PbFieldType._SFIXED64_BIT: return wireType == WIRETYPE_FIXED64 || wireType == WIRETYPE_LENGTH_DELIMITED; case PbFieldType._BYTES_BIT: case PbFieldType._STRING_BIT: case PbFieldType._MESSAGE_BIT: return wireType == WIRETYPE_LENGTH_DELIMITED; case PbFieldType._GROUP_BIT: return wireType == WIRETYPE_START_GROUP; default: return false; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/utils.dart
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; // TODO(antonm): reconsider later if PbList should take care of equality. bool _deepEquals(lhs, rhs) { // Some GeneratedMessages implement Map, so test this first. if (lhs is GeneratedMessage) return lhs == rhs; if (rhs is GeneratedMessage) return false; if ((lhs is List) && (rhs is List)) return _areListsEqual(lhs, rhs); if ((lhs is Map) && (rhs is Map)) return _areMapsEqual(lhs, rhs); if ((lhs is ByteData) && (rhs is ByteData)) { return _areByteDataEqual(lhs, rhs); } return lhs == rhs; } bool _areListsEqual(List lhs, List rhs) { if (lhs.length != rhs.length) return false; for (var i = 0; i < lhs.length; i++) { if (!_deepEquals(lhs[i], rhs[i])) return false; } return true; } bool _areMapsEqual(Map lhs, Map rhs) { if (lhs.length != rhs.length) return false; return lhs.keys.every((key) => _deepEquals(lhs[key], rhs[key])); } bool _areByteDataEqual(ByteData lhs, ByteData rhs) { Uint8List asBytes(d) => Uint8List.view(d.buffer, d.offsetInBytes, d.lengthInBytes); return _areListsEqual(asBytes(lhs), asBytes(rhs)); } @Deprecated('This function was not intended to be public. ' 'It will be removed from the public api in next major version. ') List<T> sorted<T>(Iterable<T> list) => List.from(list)..sort(); List<T> _sorted<T>(Iterable<T> list) => List.from(list)..sort(); class _HashUtils { // Jenkins hash functions copied from https://github.com/google/quiver-dart/blob/master/lib/src/core/hash.dart. static int _combine(int hash, int value) { hash = 0x1fffffff & (hash + value); hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10)); return hash ^ (hash >> 6); } static int _finish(int hash) { hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3)); hash = hash ^ (hash >> 11); return 0x1fffffff & (hash + ((0x00003fff & hash) << 15)); } /// Generates a hash code for multiple [objects]. static int _hashObjects(Iterable objects) => _finish(objects.fold(0, (h, i) => _combine(h, i.hashCode))); /// Generates a hash code for two objects. static int _hash2(a, b) => _finish(_combine(_combine(0, a.hashCode), b.hashCode)); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/unpack.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; /// Unpacks the message in [value] into [instance]. /// /// Throws a [InvalidProtocolBufferException] if [typeUrl] does not correspond /// with the type of [instance]. /// /// This is a helper method for `Any.unpackInto`. void unpackIntoHelper<T extends GeneratedMessage>( List<int> value, T instance, String typeUrl, {ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY}) { // From "google/protobuf/any.proto": // // The pack methods provided by protobuf library will by default use // 'type.googleapis.com/full.type.name' as the type URL and the unpack // methods only use the fully qualified type name after the last '/' // in the type URL, for example "foo.bar.com/x/y.z" will yield type // name "y.z". if (!canUnpackIntoHelper(instance, typeUrl)) { var typeName = instance.info_.qualifiedMessageName; throw InvalidProtocolBufferException.wrongAnyMessage( _typeNameFromUrl(typeUrl), typeName); } instance.mergeFromBuffer(value, extensionRegistry); } /// Returns `true` if the type of [instance] is described by /// `typeUrl`. /// /// This is a helper method for `Any.canUnpackInto`. bool canUnpackIntoHelper(GeneratedMessage instance, String typeUrl) { return instance.info_.qualifiedMessageName == _typeNameFromUrl(typeUrl); } String _typeNameFromUrl(String typeUrl) { var index = typeUrl.lastIndexOf('/'); return index == -1 ? '' : typeUrl.substring(index + 1); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/proto3_json.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; Object _writeToProto3Json(_FieldSet fs, TypeRegistry typeRegistry) { String convertToMapKey(dynamic key, int keyType) { var baseType = PbFieldType._baseType(keyType); assert(!_isRepeated(keyType)); switch (baseType) { case PbFieldType._BOOL_BIT: return key ? 'true' : 'false'; case PbFieldType._STRING_BIT: return key; case PbFieldType._UINT64_BIT: return (key as Int64).toStringUnsigned(); case PbFieldType._INT32_BIT: case PbFieldType._SINT32_BIT: case PbFieldType._UINT32_BIT: case PbFieldType._FIXED32_BIT: case PbFieldType._SFIXED32_BIT: case PbFieldType._INT64_BIT: case PbFieldType._SINT64_BIT: case PbFieldType._SFIXED64_BIT: case PbFieldType._FIXED64_BIT: return key.toString(); default: throw StateError('Not a valid key type $keyType'); } } Object valueToProto3Json(dynamic fieldValue, int fieldType) { if (fieldValue == null) return null; if (_isGroupOrMessage(fieldType)) { return _writeToProto3Json( (fieldValue as GeneratedMessage)._fieldSet, typeRegistry); } else if (_isEnum(fieldType)) { return (fieldValue as ProtobufEnum).name; } else { var baseType = PbFieldType._baseType(fieldType); switch (baseType) { case PbFieldType._BOOL_BIT: return fieldValue ? true : false; case PbFieldType._STRING_BIT: return fieldValue; case PbFieldType._INT32_BIT: case PbFieldType._SINT32_BIT: case PbFieldType._UINT32_BIT: case PbFieldType._FIXED32_BIT: case PbFieldType._SFIXED32_BIT: return fieldValue; case PbFieldType._INT64_BIT: case PbFieldType._SINT64_BIT: case PbFieldType._SFIXED64_BIT: case PbFieldType._FIXED64_BIT: return fieldValue.toString(); case PbFieldType._FLOAT_BIT: case PbFieldType._DOUBLE_BIT: double value = fieldValue; if (value.isNaN) return 'NaN'; if (value.isInfinite) { if (value.isNegative) { return '-Infinity'; } else { return 'Infinity'; } } return value; case PbFieldType._UINT64_BIT: return (fieldValue as Int64).toStringUnsigned(); case PbFieldType._BYTES_BIT: return base64Encode(fieldValue); default: throw StateError( 'Invariant violation: unexpected value type $fieldType'); } } } if (fs._meta.toProto3Json != null) { return fs._meta.toProto3Json(fs._message, typeRegistry); } var result = <String, dynamic>{}; for (var fieldInfo in fs._infosSortedByTag) { var value = fs._values[fieldInfo.index]; if (value == null || (value is List && value.isEmpty)) { continue; // It's missing, repeated, or an empty byte array. } dynamic jsonValue; if (fieldInfo.isMapField) { jsonValue = (value as PbMap).map((key, entryValue) { var mapEntryInfo = fieldInfo as MapFieldInfo; return MapEntry(convertToMapKey(key, mapEntryInfo.keyFieldType), valueToProto3Json(entryValue, mapEntryInfo.valueFieldType)); }); } else if (fieldInfo.isRepeated) { jsonValue = (value as PbListBase) .map((element) => valueToProto3Json(element, fieldInfo.type)) .toList(); } else { jsonValue = valueToProto3Json(value, fieldInfo.type); } result[fieldInfo.name] = jsonValue; } // Extensions and unknown fields are not encoded by proto3 JSON. return result; } void _mergeFromProto3Json( Object json, _FieldSet fieldSet, TypeRegistry typeRegistry, bool ignoreUnknownFields, bool supportNamesWithUnderscores, bool permissiveEnums) { var context = JsonParsingContext( ignoreUnknownFields, supportNamesWithUnderscores, permissiveEnums); void recursionHelper(Object json, _FieldSet fieldSet) { int tryParse32Bit(String s) { return int.tryParse(s) ?? (throw context.parseException('expected integer', s)); } int check32BitSigned(int n) { if (n < -2147483648 || n > 2147483647) { throw context.parseException('expected 32 bit unsigned integer', n); } return n; } int check32BitUnsigned(int n) { if (n < 0 || n > 0xFFFFFFFF) { throw context.parseException('expected 32 bit unsigned integer', n); } return n; } Int64 tryParse64Bit(String s) { Int64 result; try { result = Int64.parseInt(s); } on FormatException { throw context.parseException('expected integer', json); } return result; } Object convertProto3JsonValue(Object value, FieldInfo fieldInfo) { if (value == null) { return fieldInfo.makeDefault(); } var fieldType = fieldInfo.type; switch (PbFieldType._baseType(fieldType)) { case PbFieldType._BOOL_BIT: if (value is bool) { return value; } throw context.parseException('Expected bool value', json); case PbFieldType._BYTES_BIT: if (value is String) { Uint8List result; try { result = base64Decode(value); } on FormatException { throw context.parseException( 'Expected bytes encoded as base64 String', json); } return result; } throw context.parseException( 'Expected bytes encoded as base64 String', value); case PbFieldType._STRING_BIT: if (value is String) { return value; } throw context.parseException('Expected String value', value); case PbFieldType._FLOAT_BIT: case PbFieldType._DOUBLE_BIT: if (value is double) { return value; } else if (value is num) { return value.toDouble(); } else if (value is String) { return double.tryParse(value) ?? (throw context.parseException( 'Expected String to encode a double', value)); } throw context.parseException( 'Expected a double represented as a String or number', value); case PbFieldType._ENUM_BIT: if (value is String) { // TODO(sigurdm): Do we want to avoid linear search here? Measure... final result = permissiveEnums ? fieldInfo.enumValues.firstWhere( (e) => permissiveCompare(e.name, value), orElse: () => null) : fieldInfo.enumValues .firstWhere((e) => e.name == value, orElse: () => null); if ((result != null) || ignoreUnknownFields) return result; throw context.parseException('Unknown enum value', value); } else if (value is int) { return fieldInfo.valueOf(value) ?? (ignoreUnknownFields ? null : (throw context.parseException( 'Unknown enum value', value))); } throw context.parseException( 'Expected enum as a string or integer', value); case PbFieldType._UINT32_BIT: int result; if (value is int) { result = value; } else if (value is String) { result = tryParse32Bit(value); } else { throw context.parseException( 'Expected int or stringified int', value); } return check32BitUnsigned(result); case PbFieldType._INT32_BIT: case PbFieldType._SINT32_BIT: case PbFieldType._FIXED32_BIT: case PbFieldType._SFIXED32_BIT: int result; if (value is int) { result = value; } else if (value is String) { result = tryParse32Bit(value); } else { throw context.parseException( 'Expected int or stringified int', value); } check32BitSigned(result); return result; case PbFieldType._UINT64_BIT: Int64 result; if (value is int) { result = Int64(value); } else if (value is String) { result = tryParse64Bit(value); } else { throw context.parseException( 'Expected int or stringified int', value); } return result; case PbFieldType._INT64_BIT: case PbFieldType._SINT64_BIT: case PbFieldType._FIXED64_BIT: case PbFieldType._SFIXED64_BIT: if (value is int) return Int64(value); if (value is String) { Int64 result; try { result = Int64.parseInt(value); } on FormatException { throw context.parseException( 'Expected int or stringified int', value); } return result; } throw context.parseException( 'Expected int or stringified int', value); case PbFieldType._GROUP_BIT: case PbFieldType._MESSAGE_BIT: var subMessage = fieldInfo.subBuilder(); recursionHelper(value, subMessage._fieldSet); return subMessage; default: throw StateError('Unknown type $fieldType'); } } Object decodeMapKey(String key, int fieldType) { switch (PbFieldType._baseType(fieldType)) { case PbFieldType._BOOL_BIT: switch (key) { case 'true': return true; case 'false': return false; default: throw context.parseException( 'Wrong boolean key, should be one of ("true", "false")', key); } // ignore: dead_code throw StateError('(Should have been) unreachable statement'); case PbFieldType._STRING_BIT: return key; case PbFieldType._UINT64_BIT: // TODO(sigurdm): We do not throw on negative values here. // That would probably require going via bignum. return tryParse64Bit(key); case PbFieldType._INT64_BIT: case PbFieldType._SINT64_BIT: case PbFieldType._SFIXED64_BIT: case PbFieldType._FIXED64_BIT: return tryParse64Bit(key); case PbFieldType._INT32_BIT: case PbFieldType._SINT32_BIT: case PbFieldType._FIXED32_BIT: case PbFieldType._SFIXED32_BIT: return check32BitSigned(tryParse32Bit(key)); case PbFieldType._UINT32_BIT: return check32BitUnsigned(tryParse32Bit(key)); default: throw StateError('Not a valid key type $fieldType'); } } if (json == null) { // `null` represents the default value. Do nothing more. return; } var info = fieldSet._meta; final wellKnownConverter = info.fromProto3Json; if (wellKnownConverter != null) { wellKnownConverter(fieldSet._message, json, typeRegistry, context); } else { if (json is Map) { var byName = info.byName; json.forEach((key, value) { if (key is! String) { throw context.parseException('Key was not a String', key); } context.addMapIndex(key); var fieldInfo = byName[key]; if (fieldInfo == null && supportNamesWithUnderscores) { // We don't optimize for field names with underscores, instead do a // linear search for the index. fieldInfo = byName.values.firstWhere( (FieldInfo info) => info.protoName == key, orElse: () => null); } if (fieldInfo == null) { if (ignoreUnknownFields) { return; } else { throw context.parseException('Unknown field name \'$key\'', key); } } if (_isMapField(fieldInfo.type)) { if (value is Map) { MapFieldInfo mapFieldInfo = fieldInfo; Map fieldValues = fieldSet._ensureMapField(fieldInfo); value.forEach((subKey, subValue) { if (subKey is! String) { throw context.parseException('Expected a String key', subKey); } context.addMapIndex(subKey); final result = fieldValues[ decodeMapKey(subKey, mapFieldInfo.keyFieldType)] = convertProto3JsonValue( subValue, mapFieldInfo.valueFieldInfo); context.popIndex(); return result; }); } else { throw context.parseException('Expected a map', value); } } else if (_isRepeated(fieldInfo.type)) { if (value == null) { // `null` is accepted as the empty list []. fieldSet._ensureRepeatedField(fieldInfo); } else if (value is List) { var values = fieldSet._ensureRepeatedField(fieldInfo); for (var i = 0; i < value.length; i++) { final entry = value[i]; context.addListIndex(i); values.add(convertProto3JsonValue(entry, fieldInfo)); context.popIndex(); } } else { throw context.parseException('Expected a list', value); } } else if (_isGroupOrMessage(fieldInfo.type)) { // TODO(sigurdm) consider a cleaner separation between parsing and merging. GeneratedMessage parsedSubMessage = convertProto3JsonValue(value, fieldInfo); GeneratedMessage original = fieldSet._values[fieldInfo.index]; if (original == null) { fieldSet._values[fieldInfo.index] = parsedSubMessage; } else { original.mergeFromMessage(parsedSubMessage); } } else { fieldSet._setFieldUnchecked( fieldInfo, convertProto3JsonValue(value, fieldInfo)); } context.popIndex(); }); } else { throw context.parseException('Expected JSON object', json); } } } recursionHelper(json, fieldSet); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/extension_field_set.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; class _ExtensionFieldSet { final _FieldSet _parent; final Map<int, Extension> _info = <int, Extension>{}; final Map<int, dynamic> _values = <int, dynamic>{}; bool _isReadOnly = false; _ExtensionFieldSet(this._parent); Extension _getInfoOrNull(int tagNumber) => _info[tagNumber]; dynamic _getFieldOrDefault(Extension fi) { if (fi.isRepeated) return _getList(fi); _validateInfo(fi); // TODO(skybrian) seems unnecessary to add info? // I think this was originally here for repeated extensions. _addInfoUnchecked(fi); var value = _getFieldOrNull(fi); if (value == null) { _checkNotInUnknown(fi); return fi.makeDefault(); } return value; } bool _hasField(int tagNumber) { var value = _values[tagNumber]; if (value == null) return false; if (value is List) return value.isNotEmpty; return true; } /// Ensures that the list exists and an extension is present. /// /// If it doesn't exist, creates the list and saves the extension. /// Suitable for public API and decoders. List<T> _ensureRepeatedField<T>(Extension<T> fi) { assert(!_isReadOnly); assert(fi.isRepeated); assert(fi.extendee == '' || fi.extendee == _parent._messageName); var list = _values[fi.tagNumber]; if (list != null) return list as List<T>; return _addInfoAndCreateList(fi); } List<T> _getList<T>(Extension<T> fi) { var value = _values[fi.tagNumber]; if (value != null) return value as List<T>; _checkNotInUnknown(fi); if (_isReadOnly) return List<T>.unmodifiable(const []); return _addInfoAndCreateList(fi); } List _addInfoAndCreateList(Extension fi) { _validateInfo(fi); var newList = fi._createRepeatedField(_parent._message); _addInfoUnchecked(fi); _setFieldUnchecked(fi, newList); return newList; } dynamic _getFieldOrNull(Extension extension) => _values[extension.tagNumber]; void _clearFieldAndInfo(Extension fi) { _clearField(fi); _info.remove(fi.tagNumber); } void _clearField(Extension fi) { _ensureWritable(); _validateInfo(fi); if (_parent._hasObservers) _parent._eventPlugin.beforeClearField(fi); _values.remove(fi.tagNumber); } /// Sets a value for a non-repeated extension that has already been added. /// Does error-checking. void _setField(int tagNumber, value) { var fi = _getInfoOrNull(tagNumber); if (fi == null) { throw ArgumentError( 'tag $tagNumber not defined in $_parent._messageName'); } if (fi.isRepeated) { throw ArgumentError(_parent._setFieldFailedMessage( fi, value, 'repeating field (use get + .add())')); } _ensureWritable(); _parent._validateField(fi, value); _setFieldUnchecked(fi, value); } /// Sets a non-repeated value and extension. /// Overwrites any existing extension. void _setFieldAndInfo(Extension fi, value) { _ensureWritable(); if (fi.isRepeated) { throw ArgumentError(_parent._setFieldFailedMessage( fi, value, 'repeating field (use get + .add())')); } _ensureWritable(); _validateInfo(fi); _parent._validateField(fi, value); _addInfoUnchecked(fi); _setFieldUnchecked(fi, value); } void _ensureWritable() { if (_isReadOnly) frozenMessageModificationHandler(_parent._messageName); } void _validateInfo(Extension fi) { if (fi.extendee != _parent._messageName) { throw ArgumentError( 'Extension $fi not legal for message ${_parent._messageName}'); } } void _addInfoUnchecked(Extension fi) { assert(fi.extendee == _parent._messageName); _info[fi.tagNumber] = fi; } void _setFieldUnchecked(Extension fi, value) { if (_parent._hasObservers) { _parent._eventPlugin.beforeSetField(fi, value); } _values[fi.tagNumber] = value; } // Bulk operations Iterable<int> get _tagNumbers => _values.keys; Iterable<Extension> get _infos => _info.values; bool get _hasValues => _values.isNotEmpty; bool _equalValues(_ExtensionFieldSet other) => other != null && _areMapsEqual(_values, other._values); void _clearValues() => _values.clear(); /// Makes a shallow copy of all values from [original] to this. /// /// Repeated fields are copied. /// Extensions cannot contain map fields. void _shallowCopyValues(_ExtensionFieldSet original) { for (var tagNumber in original._tagNumbers) { var extension = original._getInfoOrNull(tagNumber); _addInfoUnchecked(extension); final value = original._getFieldOrNull(extension); if (value == null) continue; if (extension.isRepeated) { assert(value is PbListBase); _ensureRepeatedField(extension)..addAll(value); } else { _setFieldUnchecked(extension, value); } } } void _markReadOnly() { if (_isReadOnly) return; _isReadOnly = true; for (var field in _info.values) { if (field.isRepeated) { final entries = _values[field.tagNumber]; if (entries == null) continue; if (field.isGroupOrMessage) { for (var subMessage in entries as List<GeneratedMessage>) { subMessage.freeze(); } } _values[field.tagNumber] = entries.toFrozenPbList(); } else if (field.isGroupOrMessage) { final entry = _values[field.tagNumber]; if (entry != null) { (entry as GeneratedMessage).freeze(); } } } } void _checkNotInUnknown(Extension extension) { if (_parent._hasUnknownFields && _parent._unknownFields.hasField(extension.tagNumber)) { throw StateError( 'Trying to get $extension that is present as an unknown field. ' 'Parse the message with this extension in the extension registry or ' 'use `ExtensionRegistry.reparseMessage`.'); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/coded_buffer_writer.dart
// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; /// Writer used for converting [GeneratedMessage]s into binary /// representation. /// /// Note that it is impossible to serialize protobuf messages using a one pass /// streaming serialization as some values are serialized using /// length-delimited representation, which means that they are represented as /// a varint encoded length followed by specified number of bytes of data. /// /// Due to this [CodedBufferWritter] maintains two output buffers: /// [_outputChunks] which contains all continuously written bytes and /// [_splices] which describes additional bytes to splice in-between /// [_outputChunks] bytes. /// class CodedBufferWriter { /// Array of splices representing the data written into the writer. /// Each element might be one of: /// * a TypedData object - represents a sequence of bytes that need to be /// emitted into the result as-is; /// * a positive integer - a number of bytes to copy from [_outputChunks] /// into resulting buffer; /// * a non-positive integer - a positive number that needs to be emitted /// into result buffer as a varint; final List<dynamic> _splices = <dynamic>[]; /// Number of bytes written into [_outputChunk] and [_outputChunks] since /// the last splice was recorded. int _lastSplicePos = 0; /// Size of the [_outputChunk]. static const _chunkLength = 512; /// Current chunk used to write data into. Once it is full it is /// pushed into [_outputChunks] and a new one is allocated. Uint8List _outputChunk; /// Number of bytes written into the [_outputChunk]. int _bytesInChunk = 0; /// ByteData pointing to [_outputChunk]. Used to write primitive values /// more efficiently. ByteData _outputChunkAsByteData; /// Array of pairs <Uint8List chunk, int bytesInChunk> - chunks are /// pushed into this array once they are full. final List<dynamic> _outputChunks = <dynamic>[]; /// Total amount of bytes used in all chunks. int _outputChunksBytes = 0; /// Total amount of bytes written into this writer. int _bytesTotal = 0; int get lengthInBytes => _bytesTotal; CodedBufferWriter() { // Initialize [_outputChunk]. _commitChunk(true); } void writeField(int fieldNumber, int fieldType, fieldValue) { final valueType = fieldType & ~0x07; if ((fieldType & PbFieldType._PACKED_BIT) != 0) { if (!fieldValue.isEmpty) { _writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); final mark = _startLengthDelimited(); for (var value in fieldValue) { _writeValueAs(valueType, value); } _endLengthDelimited(mark); } return; } final wireFormat = _wireTypes[_valueTypeIndex(valueType)]; if ((fieldType & PbFieldType._MAP_BIT) != 0) { final keyWireFormat = _wireTypes[_valueTypeIndex(fieldValue.keyFieldType)]; final valueWireFormat = _wireTypes[_valueTypeIndex(fieldValue.valueFieldType)]; fieldValue.forEach((key, value) { _writeTag(fieldNumber, WIRETYPE_LENGTH_DELIMITED); final mark = _startLengthDelimited(); _writeValue( PbMap._keyFieldNumber, fieldValue.keyFieldType, key, keyWireFormat); _writeValue(PbMap._valueFieldNumber, fieldValue.valueFieldType, value, valueWireFormat); _endLengthDelimited(mark); }); return; } if ((fieldType & PbFieldType._REPEATED_BIT) != 0) { for (var i = 0; i < fieldValue.length; i++) { _writeValue(fieldNumber, valueType, fieldValue[i], wireFormat); } return; } _writeValue(fieldNumber, valueType, fieldValue, wireFormat); } Uint8List toBuffer() { var result = Uint8List(_bytesTotal); writeTo(result); return result; } /// Serializes everything written to this writer so far to [buffer], starting /// from [offset] in [buffer]. Returns `true` on success. bool writeTo(Uint8List buffer, [int offset = 0]) { if (buffer.length - offset < _bytesTotal) { return false; } // Move the current output chunk into _outputChunks and commit the current // splice for uniformity. _commitChunk(false); _commitSplice(); var outPos = offset; // Output position in the buffer. var chunkIndex = 0, chunkPos = 0; // Position within _outputChunks. for (var i = 0; i < _splices.length; i++) { final action = _splices[i]; if (action is int) { if (action <= 0) { // action is a positive varint to be emitted into the output buffer. var v = 0 - action; // Note: 0 - action to avoid -0.0 in JS. while (v >= 0x80) { buffer[outPos++] = 0x80 | (v & 0x7f); v >>= 7; } buffer[outPos++] = v; } else { // action is an amount of bytes to copy from _outputChunks into the // buffer. var bytesToCopy = action; while (bytesToCopy > 0) { final Uint8List chunk = _outputChunks[chunkIndex]; final int bytesInChunk = _outputChunks[chunkIndex + 1]; // Copy at most bytesToCopy bytes from the current chunk. final leftInChunk = bytesInChunk - chunkPos; final bytesToCopyFromChunk = leftInChunk > bytesToCopy ? bytesToCopy : leftInChunk; final endPos = chunkPos + bytesToCopyFromChunk; while (chunkPos < endPos) { buffer[outPos++] = chunk[chunkPos++]; } bytesToCopy -= bytesToCopyFromChunk; // Move to the next chunk if the current one is exhausted. if (chunkPos == bytesInChunk) { chunkIndex += 2; chunkPos = 0; } } } } else { // action is a TypedData containing bytes to emit into the output // buffer. outPos = _copyInto(buffer, outPos, action); } } return true; } /// Move the current [_outputChunk] into [_outputChunks]. /// /// If [allocateNew] is [true] then allocate a new chunk, otherwise /// set [_outputChunk] to null. void _commitChunk(bool allocateNew) { if (_bytesInChunk != 0) { _outputChunks.add(_outputChunk); _outputChunks.add(_bytesInChunk); _outputChunksBytes += _bytesInChunk; } if (allocateNew) { _outputChunk = Uint8List(_chunkLength); _bytesInChunk = 0; _outputChunkAsByteData = ByteData.view(_outputChunk.buffer); } else { _outputChunk = _outputChunkAsByteData = null; _bytesInChunk = 0; } } /// Check if [count] bytes would fit into the current chunk. If they will /// not then allocate a new [_outputChunk]. /// /// [count] is assumed to be small enough to fit into the newly allocated /// chunk. void _ensureBytes(int count) { if ((_bytesInChunk + count) > _chunkLength) { _commitChunk(true); } } /// Record number of bytes written into output chunks since last splice. /// /// This is used before reserving space for an unknown varint splice or /// adding a TypedData array splice. void _commitSplice() { final pos = _bytesInChunk + _outputChunksBytes; final bytes = pos - _lastSplicePos; if (bytes > 0) { _splices.add(bytes); } _lastSplicePos = pos; } /// Add TypedData splice - these bytes would be directly copied into the /// output buffer by [writeTo]. void writeRawBytes(TypedData value) { _commitSplice(); _splices.add(value); _bytesTotal += value.lengthInBytes; } /// Start writing a length-delimited data. /// /// This reserves the space for varint splice in the splices array and /// return its index. Once the writing is finished [_endLengthDelimited] /// would be called with this index - which would put the actual amount /// of bytes written into the reserved slice space. int _startLengthDelimited() { _commitSplice(); var index = _splices.length; // Reserve a space for a splice and use it to record the current number of // bytes written so that we can compute the length of data later in // _endLengthDelimited. _splices.add(_bytesTotal); return index; } void _endLengthDelimited(int index) { final int writtenSizeInBytes = _bytesTotal - _splices[index]; // Note: 0 - writtenSizeInBytes to avoid -0.0 in JavaScript. _splices[index] = 0 - writtenSizeInBytes; _bytesTotal += _varint32LengthInBytes(writtenSizeInBytes); } int _varint32LengthInBytes(int value) { value &= 0xFFFFFFFF; if (value < 0x80) return 1; if (value < 0x4000) return 2; if (value < 0x200000) return 3; if (value < 0x10000000) return 4; return 5; } void _writeVarint32(int value) { _ensureBytes(5); var i = _bytesInChunk; while (value >= 0x80) { _outputChunk[i++] = 0x80 | (value & 0x7f); value >>= 7; } _outputChunk[i++] = value; _bytesTotal += (i - _bytesInChunk); _bytesInChunk = i; } void _writeVarint64(Int64 value) { _ensureBytes(10); var i = _bytesInChunk; var lo = value.toUnsigned(32).toInt(); var hi = (value >> 32).toUnsigned(32).toInt(); while (hi > 0 || lo >= 0x80) { _outputChunk[i++] = 0x80 | (lo & 0x7f); lo = (lo >> 7) | ((hi & 0x7f) << 25); hi >>= 7; } _outputChunk[i++] = lo; _bytesTotal += (i - _bytesInChunk); _bytesInChunk = i; } void _writeDouble(double value) { if (value.isNaN) { _writeInt32(0x00000000); _writeInt32(0x7ff80000); return; } _ensureBytes(8); _outputChunkAsByteData.setFloat64(_bytesInChunk, value, Endian.little); _bytesInChunk += 8; _bytesTotal += 8; } void _writeFloat(double value) { const MIN_FLOAT_DENORM = 1.401298464324817E-45; const MAX_FLOAT = 3.4028234663852886E38; if (value.isNaN) { _writeInt32(0x7fc00000); } else if (value.abs() < MIN_FLOAT_DENORM) { _writeInt32(value.isNegative ? 0x80000000 : 0x00000000); } else if (value.isInfinite || value.abs() > MAX_FLOAT) { _writeInt32(value.isNegative ? 0xff800000 : 0x7f800000); } else { const sz = 4; _ensureBytes(sz); _outputChunkAsByteData.setFloat32(_bytesInChunk, value, Endian.little); _bytesInChunk += sz; _bytesTotal += sz; } } void _writeInt32(int value) { const sizeInBytes = 4; _ensureBytes(sizeInBytes); _outputChunkAsByteData.setInt32( _bytesInChunk, value & 0xFFFFFFFF, Endian.little); _bytesInChunk += sizeInBytes; _bytesTotal += sizeInBytes; } void _writeInt64(Int64 value) { _writeInt32(value.toUnsigned(32).toInt()); _writeInt32((value >> 32).toUnsigned(32).toInt()); } void _writeValueAs(int valueType, dynamic value) { switch (valueType) { case PbFieldType._BOOL_BIT: _writeVarint32(value ? 1 : 0); break; case PbFieldType._BYTES_BIT: _writeBytesNoTag( value is TypedData ? value : Uint8List.fromList(value)); break; case PbFieldType._STRING_BIT: _writeBytesNoTag(_utf8.encode(value)); break; case PbFieldType._DOUBLE_BIT: _writeDouble(value); break; case PbFieldType._FLOAT_BIT: _writeFloat(value); break; case PbFieldType._ENUM_BIT: _writeVarint32(value.value & 0xffffffff); break; case PbFieldType._GROUP_BIT: value.writeToCodedBufferWriter(this); break; case PbFieldType._INT32_BIT: _writeVarint64(Int64(value)); break; case PbFieldType._INT64_BIT: _writeVarint64(value); break; case PbFieldType._SINT32_BIT: _writeVarint32(_encodeZigZag32(value)); break; case PbFieldType._SINT64_BIT: _writeVarint64(_encodeZigZag64(value)); break; case PbFieldType._UINT32_BIT: _writeVarint32(value); break; case PbFieldType._UINT64_BIT: _writeVarint64(value); break; case PbFieldType._FIXED32_BIT: _writeInt32(value); break; case PbFieldType._FIXED64_BIT: _writeInt64(value); break; case PbFieldType._SFIXED32_BIT: _writeInt32(value); break; case PbFieldType._SFIXED64_BIT: _writeInt64(value); break; case PbFieldType._MESSAGE_BIT: final mark = _startLengthDelimited(); value.writeToCodedBufferWriter(this); _endLengthDelimited(mark); break; } } void _writeBytesNoTag(dynamic value) { writeInt32NoTag(value.length); writeRawBytes(value); } void _writeTag(int fieldNumber, int wireFormat) { writeInt32NoTag(makeTag(fieldNumber, wireFormat)); } void _writeValue( int fieldNumber, int valueType, dynamic value, int wireFormat) { _writeTag(fieldNumber, wireFormat); _writeValueAs(valueType, value); if (valueType == PbFieldType._GROUP_BIT) { _writeTag(fieldNumber, WIRETYPE_END_GROUP); } } void writeInt32NoTag(int value) { _writeVarint32(value & 0xFFFFFFFF); } /// Copy bytes from the given typed data array into the output buffer. /// /// Has a specialization for Uint8List for performance. int _copyInto(Uint8List buffer, int pos, TypedData value) { if (value is Uint8List) { var len = value.length; for (var j = 0; j < len; j++) { buffer[pos++] = value[j]; } return pos; } else { var len = value.lengthInBytes; var u8 = Uint8List.view( value.buffer, value.offsetInBytes, value.lengthInBytes); for (var j = 0; j < len; j++) { buffer[pos++] = u8[j]; } return pos; } } /// This function maps a power-of-2 value (2^0 .. 2^31) to a unique value /// in the 0..31 range. /// /// For more details see "Using de Bruijn Sequences to Index a 1 in /// a Computer Word"[1] /// /// Note: this is guaranteed to work after compilation to JavaScript /// where multiplication becomes a floating point multiplication. /// /// [1] http://supertech.csail.mit.edu/papers/debruijn.pdf static int _valueTypeIndex(int powerOf2) => ((0x077CB531 * powerOf2) >> 27) & 31; /// Precomputed indices for all FbFieldType._XYZ_BIT values: /// /// _XYZ_BIT_INDEX = _valueTypeIndex(FbFieldType._XYZ_BIT) /// static const _BOOL_BIT_INDEX = 14; static const _BYTES_BIT_INDEX = 29; static const _STRING_BIT_INDEX = 27; static const _DOUBLE_BIT_INDEX = 23; static const _FLOAT_BIT_INDEX = 15; static const _ENUM_BIT_INDEX = 31; static const _GROUP_BIT_INDEX = 30; static const _INT32_BIT_INDEX = 28; static const _INT64_BIT_INDEX = 25; static const _SINT32_BIT_INDEX = 18; static const _SINT64_BIT_INDEX = 5; static const _UINT32_BIT_INDEX = 11; static const _UINT64_BIT_INDEX = 22; static const _FIXED32_BIT_INDEX = 13; static const _FIXED64_BIT_INDEX = 26; static const _SFIXED32_BIT_INDEX = 21; static const _SFIXED64_BIT_INDEX = 10; static const _MESSAGE_BIT_INDEX = 20; /// Mapping from value types to wire-types indexed by _valueTypeIndex(...). static final Uint8List _wireTypes = Uint8List(32) ..[_BOOL_BIT_INDEX] = WIRETYPE_VARINT ..[_BYTES_BIT_INDEX] = WIRETYPE_LENGTH_DELIMITED ..[_STRING_BIT_INDEX] = WIRETYPE_LENGTH_DELIMITED ..[_DOUBLE_BIT_INDEX] = WIRETYPE_FIXED64 ..[_FLOAT_BIT_INDEX] = WIRETYPE_FIXED32 ..[_ENUM_BIT_INDEX] = WIRETYPE_VARINT ..[_GROUP_BIT_INDEX] = WIRETYPE_START_GROUP ..[_INT32_BIT_INDEX] = WIRETYPE_VARINT ..[_INT64_BIT_INDEX] = WIRETYPE_VARINT ..[_SINT32_BIT_INDEX] = WIRETYPE_VARINT ..[_SINT64_BIT_INDEX] = WIRETYPE_VARINT ..[_UINT32_BIT_INDEX] = WIRETYPE_VARINT ..[_UINT64_BIT_INDEX] = WIRETYPE_VARINT ..[_FIXED32_BIT_INDEX] = WIRETYPE_FIXED32 ..[_FIXED64_BIT_INDEX] = WIRETYPE_FIXED64 ..[_SFIXED32_BIT_INDEX] = WIRETYPE_FIXED32 ..[_SFIXED64_BIT_INDEX] = WIRETYPE_FIXED64 ..[_MESSAGE_BIT_INDEX] = WIRETYPE_LENGTH_DELIMITED; } int _encodeZigZag32(int value) => (value << 1) ^ (value >> 31); Int64 _encodeZigZag64(Int64 value) => (value << 1) ^ (value >> 63);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/extension_registry.dart
// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; /// A collection of [Extension] objects, organized by the message type they /// extend. class ExtensionRegistry { final Map<String, Map<int, Extension>> _extensions = <String, Map<int, Extension>>{}; static const ExtensionRegistry EMPTY = _EmptyExtensionRegistry(); /// Stores an [extension] in the registry. void add(Extension extension) { var map = _extensions.putIfAbsent(extension.extendee, () => <int, Extension>{}); map[extension.tagNumber] = extension; } /// Stores all [extensions] in the registry. void addAll(Iterable<Extension> extensions) { extensions.forEach(add); } /// Retrieves an extension from the registry that adds tag number [tagNumber] /// to the [messageName] message type. Extension getExtension(String messageName, int tagNumber) { var map = _extensions[messageName]; if (map != null) { return map[tagNumber]; } return null; } /// Returns a shallow copy of [message], with all extensions in [this] parsed /// from the unknown fields of [message] and of every nested submessage. /// /// Extensions already present in [message] will be preserved. /// /// If [message] is frozen, the result will be as well. /// /// Returns the original message if no new extensions are parsed. /// /// Throws an [InvalidProtocolBufferException] if the parsed extensions are /// malformed. /// /// Using this method to retrieve extensions is more expensive overall than /// using an [ExtensionRegistry] with all the needed extensions when doing /// [GeneratedMessage.fromBuffer]. /// /// Example: /// /// `sample.proto` /// ```proto /// syntax = "proto2"; /// /// message Foo { /// extensions 1 to max; /// } /// /// extend Foo { /// optional string val1 = 1; /// optional string val2 = 2; /// } /// ``` /// `main.dart` /// ``` /// import 'package:protobuf/protobuf.dart'; /// import 'package:test/test.dart'; /// import 'src/generated/sample.pb.dart'; /// /// void main() { /// ExtensionRegistry r1 = ExtensionRegistry()..add(Sample.val1); /// ExtensionRegistry r2 = ExtensionRegistry()..add(Sample.val2); /// Foo original = Foo()..setExtension(Sample.val1, 'a')..setExtension(Sample.val2, 'b'); /// Foo withUnknownFields = Foo.fromBuffer(original.writeToBuffer()); /// Foo reparsed1 = r1.reparseMessage(withUnknownFields); /// Foo reparsed2 = r2.reparseMessage(reparsed1); /// expect(withUnknownFields.hasExtension(Sample.val1), isFalse); /// expect(withUnknownFields.hasExtension(Sample.val2), isFalse); /// expect(reparsed1.hasExtension(Sample.val1), isTrue); /// expect(reparsed1.hasExtension(Sample.val2), isFalse); /// expect(reparsed2.hasExtension(Sample.val1), isTrue); /// expect(reparsed2.hasExtension(Sample.val2), isTrue); /// } /// ``` T reparseMessage<T extends GeneratedMessage>(T message) => _reparseMessage(message, this); } T _reparseMessage<T extends GeneratedMessage>( T message, ExtensionRegistry extensionRegistry) { T result; T ensureResult() { if (result == null) { result ??= message.createEmptyInstance(); result._fieldSet._shallowCopyValues(message._fieldSet); } return result; } UnknownFieldSet resultUnknownFields; UnknownFieldSet ensureUnknownFields() => resultUnknownFields ??= ensureResult()._fieldSet._unknownFields; var messageUnknownFields = message._fieldSet._unknownFields; if (messageUnknownFields != null) { var codedBufferWriter = CodedBufferWriter(); extensionRegistry._extensions[message.info_.qualifiedMessageName] ?.forEach((tagNumber, extension) { final unknownField = messageUnknownFields._fields[tagNumber]; if (unknownField != null) { unknownField.writeTo(tagNumber, codedBufferWriter); ensureUnknownFields()._fields.remove(tagNumber); } }); if (codedBufferWriter.toBuffer().isNotEmpty) { ensureResult() .mergeFromBuffer(codedBufferWriter.toBuffer(), extensionRegistry); } } message._fieldSet._meta.byIndex.forEach((FieldInfo field) { PbList resultEntries; PbList ensureEntries() => resultEntries ??= ensureResult()._fieldSet._values[field.index]; PbMap resultMap; PbMap ensureMap() => resultMap ??= ensureResult()._fieldSet._values[field.index]; if (field.isRepeated) { final messageEntries = message._fieldSet._values[field.index]; if (messageEntries == null) return; if (field.isGroupOrMessage) { for (var i = 0; i < messageEntries.length; i++) { final GeneratedMessage entry = messageEntries[i]; final reparsedEntry = _reparseMessage(entry, extensionRegistry); if (!identical(entry, reparsedEntry)) { ensureEntries()[i] = reparsedEntry; } } } } else if (field is MapFieldInfo) { final messageMap = message._fieldSet._values[field.index]; if (messageMap == null) return; if (_isGroupOrMessage(field.valueFieldType)) { for (var key in messageMap.keys) { final GeneratedMessage value = messageMap[key]; final reparsedValue = _reparseMessage(value, extensionRegistry); if (!identical(value, reparsedValue)) { ensureMap()[key] = reparsedValue; } } } } else if (field.isGroupOrMessage) { final messageSubField = message._fieldSet._values[field.index]; if (messageSubField == null) return; final reparsedSubField = _reparseMessage<GeneratedMessage>(messageSubField, extensionRegistry); if (!identical(messageSubField, reparsedSubField)) { ensureResult()._fieldSet._values[field.index] = reparsedSubField; } } }); if (result != null && message.isFrozen) { result.freeze(); } return result ?? message; } class _EmptyExtensionRegistry implements ExtensionRegistry { const _EmptyExtensionRegistry(); @override Map<String, Map<int, Extension>> get _extensions => const <String, Map<int, Extension>>{}; @override void add(Extension extension) { throw UnsupportedError('Immutable ExtensionRegistry'); } @override void addAll(Iterable<Extension> extensions) { throw UnsupportedError('Immutable ExtensionRegistry'); } @override Extension getExtension(String messageName, int tagNumber) => null; @override T reparseMessage<T extends GeneratedMessage>(T message) => _reparseMessage(message, this); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/builder_info.dart
// Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. part of protobuf; /// Per-message type setup. class BuilderInfo { /// The fully qualified name of this message. final String qualifiedMessageName; final List<FieldInfo> byIndex = <FieldInfo>[]; final Map<int, FieldInfo> fieldInfo = <int, FieldInfo>{}; final Map<String, FieldInfo> byTagAsString = <String, FieldInfo>{}; final Map<String, FieldInfo> byName = <String, FieldInfo>{}; // Maps a tag number to the corresponding oneof index (if any). final Map<int, int> oneofs = <int, int>{}; bool hasExtensions = false; bool hasRequiredFields = true; List<FieldInfo> _sortedByTag; // For well-known types. final Object Function(GeneratedMessage message, TypeRegistry typeRegistry) toProto3Json; final Function(GeneratedMessage targetMessage, Object json, TypeRegistry typeRegistry, JsonParsingContext context) fromProto3Json; final CreateBuilderFunc createEmptyInstance; BuilderInfo(String messageName, {PackageName package = const PackageName(''), this.createEmptyInstance, this.toProto3Json, this.fromProto3Json}) : qualifiedMessageName = '${package.prefix}$messageName'; void add<T>( int tagNumber, String name, int fieldType, dynamic defaultOrMaker, CreateBuilderFunc subBuilder, ValueOfFunc valueOf, List<ProtobufEnum> enumValues, {String protoName}) { var index = byIndex.length; final fieldInfo = (tagNumber == 0) ? FieldInfo.dummy(index) : FieldInfo<T>(name, tagNumber, index, fieldType, defaultOrMaker: defaultOrMaker, subBuilder: subBuilder, valueOf: valueOf, enumValues: enumValues, protoName: protoName); _addField(fieldInfo); } void addMapField<K, V>( int tagNumber, String name, int keyFieldType, int valueFieldType, BuilderInfo mapEntryBuilderInfo, CreateBuilderFunc valueCreator, {String protoName}) { var index = byIndex.length; _addField(MapFieldInfo<K, V>(name, tagNumber, index, PbFieldType.M, keyFieldType, valueFieldType, mapEntryBuilderInfo, valueCreator, protoName: protoName)); } void addRepeated<T>( int tagNumber, String name, int fieldType, CheckFunc<T> check, CreateBuilderFunc subBuilder, ValueOfFunc valueOf, List<ProtobufEnum> enumValues, {String protoName}) { var index = byIndex.length; _addField(FieldInfo<T>.repeated( name, tagNumber, index, fieldType, check, subBuilder, valueOf: valueOf, enumValues: enumValues, protoName: protoName)); } void _addField(FieldInfo fi) { byIndex.add(fi); assert(byIndex[fi.index] == fi); // Fields with tag number 0 are considered dummy fields added to avoid // index calculations add up. They should not be reflected in the following // maps. if (!fi._isDummy) { fieldInfo[fi.tagNumber] = fi; byTagAsString['${fi.tagNumber}'] = fi; byName[fi.name] = fi; } } void a<T>(int tagNumber, String name, int fieldType, {dynamic defaultOrMaker, CreateBuilderFunc subBuilder, ValueOfFunc valueOf, List<ProtobufEnum> enumValues, String protoName}) { add<T>(tagNumber, name, fieldType, defaultOrMaker, subBuilder, valueOf, enumValues, protoName: protoName); } /// Adds PbFieldType.OS String with no default value to reduce generated /// code size. void aOS(int tagNumber, String name, {String protoName}) { add<String>(tagNumber, name, PbFieldType.OS, null, null, null, null, protoName: protoName); } /// Adds PbFieldType.PS String with no default value. void pPS(int tagNumber, String name, {String protoName}) { addRepeated<String>(tagNumber, name, PbFieldType.PS, getCheckFunction(PbFieldType.PS), null, null, null, protoName: protoName); } /// Adds PbFieldType.QS String with no default value. void aQS(int tagNumber, String name, {String protoName}) { add<String>(tagNumber, name, PbFieldType.QS, null, null, null, null, protoName: protoName); } /// Adds Int64 field with Int64.ZERO default. void aInt64(int tagNumber, String name, {String protoName}) { add<Int64>(tagNumber, name, PbFieldType.O6, Int64.ZERO, null, null, null, protoName: protoName); } /// Adds a boolean with no default value. void aOB(int tagNumber, String name, {String protoName}) { add<bool>(tagNumber, name, PbFieldType.OB, null, null, null, null, protoName: protoName); } // Enum. void e<T>(int tagNumber, String name, int fieldType, {dynamic defaultOrMaker, ValueOfFunc valueOf, List<ProtobufEnum> enumValues, String protoName}) { add<T>( tagNumber, name, fieldType, defaultOrMaker, null, valueOf, enumValues, protoName: protoName); } // Repeated, not a message, group, or enum. void p<T>(int tagNumber, String name, int fieldType, {String protoName}) { assert(!_isGroupOrMessage(fieldType) && !_isEnum(fieldType)); addRepeated<T>(tagNumber, name, fieldType, getCheckFunction(fieldType), null, null, null, protoName: protoName); } // Repeated message, group, or enum. void pc<T>(int tagNumber, String name, int fieldType, {CreateBuilderFunc subBuilder, ValueOfFunc valueOf, List<ProtobufEnum> enumValues, String protoName}) { assert(_isGroupOrMessage(fieldType) || _isEnum(fieldType)); addRepeated<T>(tagNumber, name, fieldType, _checkNotNull, subBuilder, valueOf, enumValues, protoName: protoName); } void aOM<T extends GeneratedMessage>(int tagNumber, String name, {T Function() subBuilder, String protoName}) { add<T>( tagNumber, name, PbFieldType.OM, GeneratedMessage._defaultMakerFor<T>(subBuilder), subBuilder, null, null, protoName: protoName); } void aQM<T extends GeneratedMessage>(int tagNumber, String name, {T Function() subBuilder, String protoName}) { add<T>( tagNumber, name, PbFieldType.QM, GeneratedMessage._defaultMakerFor<T>(subBuilder), subBuilder, null, null, protoName: protoName); } // oneof declarations. void oo(int oneofIndex, List<int> tags) { tags.forEach((int tag) => oneofs[tag] = oneofIndex); } // Map field. void m<K, V>(int tagNumber, String name, {String entryClassName, int keyFieldType, int valueFieldType, CreateBuilderFunc valueCreator, ValueOfFunc valueOf, List<ProtobufEnum> enumValues, PackageName packageName = const PackageName(''), String protoName}) { var mapEntryBuilderInfo = BuilderInfo(entryClassName, package: packageName) ..add(PbMap._keyFieldNumber, 'key', keyFieldType, null, null, null, null) ..add(PbMap._valueFieldNumber, 'value', valueFieldType, null, valueCreator, valueOf, enumValues); addMapField<K, V>(tagNumber, name, keyFieldType, valueFieldType, mapEntryBuilderInfo, valueCreator, protoName: protoName); } bool containsTagNumber(int tagNumber) => fieldInfo.containsKey(tagNumber); dynamic defaultValue(int tagNumber) { var func = makeDefault(tagNumber); return func == null ? null : func(); } // Returns the field name for a given tag number, for debugging purposes. String fieldName(int tagNumber) { var i = fieldInfo[tagNumber]; return i != null ? i.name : null; } int fieldType(int tagNumber) { var i = fieldInfo[tagNumber]; return i != null ? i.type : null; } MakeDefaultFunc makeDefault(int tagNumber) { var i = fieldInfo[tagNumber]; return i != null ? i.makeDefault : null; } CreateBuilderFunc subBuilder(int tagNumber) { var i = fieldInfo[tagNumber]; return i != null ? i.subBuilder : null; } int tagNumber(String fieldName) { var i = byName[fieldName]; return i != null ? i.tagNumber : null; } ValueOfFunc valueOfFunc(int tagNumber) { var i = fieldInfo[tagNumber]; return i != null ? i.valueOf : null; } /// The FieldInfo for each field in tag number order. List<FieldInfo> get sortedByTag => _sortedByTag ??= _computeSortedByTag(); /// The message name. Also see [qualifiedMessageName]. String get messageName { final lastDot = qualifiedMessageName.lastIndexOf('.'); return lastDot == -1 ? qualifiedMessageName : qualifiedMessageName.substring(lastDot + 1); } List<FieldInfo> _computeSortedByTag() { // TODO(skybrian): perhaps the code generator should insert the FieldInfos // in tag number order, to avoid sorting them? return List<FieldInfo>.from(fieldInfo.values, growable: false) ..sort((FieldInfo a, FieldInfo b) => a.tagNumber.compareTo(b.tagNumber)); } GeneratedMessage _makeEmptyMessage( int tagNumber, ExtensionRegistry extensionRegistry) { var subBuilderFunc = subBuilder(tagNumber); if (subBuilderFunc == null && extensionRegistry != null) { subBuilderFunc = extensionRegistry .getExtension(qualifiedMessageName, tagNumber) .subBuilder; } return subBuilderFunc(); } ProtobufEnum _decodeEnum( int tagNumber, ExtensionRegistry registry, int rawValue) { var f = valueOfFunc(tagNumber); if (f == null && registry != null) { f = registry.getExtension(qualifiedMessageName, tagNumber).valueOf; } return f(rawValue); } } /// Annotation for marking accessors that belong together. class TagNumber { final int tagNumber; /// Annotation for marking accessors that belong together. /// /// Allows tooling to associate related accessors. /// [tagNumber] is the protobuf tagnumber associated with the annotated /// accessor. const TagNumber(this.tagNumber); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/mixins/map_mixin.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library protobuf.mixins.map; import 'package:protobuf/protobuf.dart' show BuilderInfo; /// Note that this class does not claim to implement [Map]. Instead, this needs /// to be specified using a dart_options.imports clause specifying MapMixin as a /// parent mixin to PbMapMixin. /// /// Since PbMapMixin is built in, this is done automatically, so this mixin can /// be enabled by specifying only a dart_options.mixin option. abstract class PbMapMixin { // GeneratedMessage properties and methods used by this mixin. BuilderInfo get info_; void clear(); int getTagNumber(String fieldName); dynamic getField(int tagNumber); void setField(int tagNumber, var value); dynamic operator [](key) { if (key is! String) return null; var tag = getTagNumber(key); if (tag == null) return null; return getField(tag); } operator []=(key, val) { var tag = getTagNumber(key as String); if (tag == null) { throw ArgumentError( "field '${key}' not found in ${info_.qualifiedMessageName}"); } setField(tag, val); } Iterable<String> get keys => info_.byName.keys; bool containsKey(Object key) => info_.byName.containsKey(key); int get length => info_.byName.length; dynamic remove(key) { throw UnsupportedError( 'remove() not supported by ${info_.qualifiedMessageName}'); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/mixins/event_mixin.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. library protobuf.mixins.event; import 'dart:async' show StreamController, scheduleMicrotask; import 'dart:collection' show UnmodifiableListView; import 'package:protobuf/protobuf.dart' show GeneratedMessage, FieldInfo, EventPlugin; /// Provides a stream of changes to fields in a GeneratedMessage. /// (Experimental.) /// /// This mixin is enabled via an option in /// dart_options.proto in dart-protoc-plugin. abstract class PbEventMixin { final eventPlugin = EventBuffer(); /// A stream of changes to fields in the GeneratedMessage. /// /// Events are buffered and delivered via a microtask or in /// the next call to [deliverChanges], whichever happens first. Stream<List<PbFieldChange>> get changes => eventPlugin.changes; /// Delivers buffered field change events synchronously, /// instead of waiting for the microtask to run. void deliverChanges() => eventPlugin.deliverChanges(); } /// A change to a field in a GeneratedMessage. class PbFieldChange { final GeneratedMessage message; final FieldInfo info; final oldValue; final newValue; PbFieldChange(this.message, this.info, this.oldValue, this.newValue); int get tag => info.tagNumber; } /// A buffering implementation of event delivery. /// (Loosely based on package:observe's ChangeNotifier.) class EventBuffer extends EventPlugin { // An EventBuffer is created for each GeneratedMessage, so // initialization should be fast; create fields lazily. GeneratedMessage _parent; StreamController<List<PbFieldChange>> _controller; // If _buffer is non-null, at least one event is in the buffer // and a microtask has been scheduled to empty it. List<PbFieldChange> _buffer; @override void attach(GeneratedMessage newParent) { assert(_parent == null); assert(newParent != null); _parent = newParent; } Stream<List<PbFieldChange>> get changes { _controller ??= StreamController.broadcast(sync: true); return _controller.stream; } @override bool get hasObservers => _controller != null && _controller.hasListener; void deliverChanges() { var records = _buffer; _buffer = null; if (records != null && hasObservers) { _controller.add(UnmodifiableListView<PbFieldChange>(records)); } } void addEvent(PbFieldChange change) { if (!hasObservers) return; if (_buffer == null) { _buffer = <PbFieldChange>[]; scheduleMicrotask(deliverChanges); } _buffer.add(change); } @override void beforeSetField(FieldInfo fi, newValue) { var oldValue = _parent.getFieldOrNull(fi.tagNumber); oldValue ??= fi.readonlyDefault; if (identical(oldValue, newValue)) return; addEvent(PbFieldChange(_parent, fi, oldValue, newValue)); } @override void beforeClearField(FieldInfo fi) { var oldValue = _parent.getFieldOrNull(fi.tagNumber); if (oldValue == null) return; var newValue = fi.readonlyDefault; addEvent(PbFieldChange(_parent, fi, oldValue, newValue)); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/protobuf/src/protobuf/mixins/well_known.dart
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:convert'; import 'package:fixnum/fixnum.dart'; import '../json_parsing_context.dart'; import '../../../protobuf.dart'; import '../type_registry.dart'; abstract class AnyMixin implements GeneratedMessage { String get typeUrl; set typeUrl(String value); List<int> get value; set value(List<int> value); /// Returns `true` if the encoded message matches the type of [instance]. /// /// Can be used with a default instance: /// `any.canUnpackInto(Message.getDefault())` bool canUnpackInto(GeneratedMessage instance) { return canUnpackIntoHelper(instance, typeUrl); } /// Unpacks the message in [value] into [instance]. /// /// Throws a [InvalidProtocolBufferException] if [typeUrl] does not correspond /// to the type of [instance]. /// /// A typical usage would be `any.unpackInto(Message())`. /// /// Returns [instance]. T unpackInto<T extends GeneratedMessage>(T instance, {ExtensionRegistry extensionRegistry = ExtensionRegistry.EMPTY}) { unpackIntoHelper(value, instance, typeUrl, extensionRegistry: extensionRegistry); return instance; } /// Updates [target] to be the packed representation of [message]. /// /// The [typeUrl] will be [typeUrlPrefix]/`fullName` where `fullName` is /// the fully qualified name of the type of [message]. static void packIntoAny(AnyMixin target, GeneratedMessage message, {String typeUrlPrefix = 'type.googleapis.com'}) { target.value = message.writeToBuffer(); target.typeUrl = '${typeUrlPrefix}/${message.info_.qualifiedMessageName}'; } // From google/protobuf/any.proto: // JSON // ==== // The JSON representation of an `Any` value uses the regular // representation of the deserialized, embedded message, with an // additional field `@type` which contains the type URL. Example: // // package google.profile; // message Person { // string first_name = 1; // string last_name = 2; // } // // { // "@type": "type.googleapis.com/google.profile.Person", // "firstName": <string>, // "lastName": <string> // } // // If the embedded message type is well-known and has a custom JSON // representation, that representation will be embedded adding a field // `value` which holds the custom JSON in addition to the `@type` // field. Example (for message [google.protobuf.Duration][]): // // { // "@type": "type.googleapis.com/google.protobuf.Duration", // "value": "1.212s" // } static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry) { var any = message as AnyMixin; var info = typeRegistry.lookup(_typeNameFromUrl(any.typeUrl)); if (info == null) { throw ArgumentError( 'The type of the Any message (${any.typeUrl}) is not in the given typeRegistry.'); } var unpacked = info.createEmptyInstance()..mergeFromBuffer(any.value); var proto3Json = unpacked.toProto3Json(); if (info.toProto3Json == null) { var map = proto3Json as Map<String, dynamic>; map['@type'] = any.typeUrl; return map; } else { return {'@type': any.typeUrl, 'value': proto3Json}; } } static void fromProto3JsonHelper(GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context) { if (json is! Map<String, dynamic>) { throw context.parseException( 'Expected Any message encoded as {@type,...},', json); } final object = json as Map<String, dynamic>; final typeUrl = object['@type']; if (typeUrl is String) { var any = message as AnyMixin; var info = typeRegistry.lookup(_typeNameFromUrl(typeUrl)); if (info == null) { throw context.parseException( 'Decoding Any of type ${typeUrl} not in TypeRegistry $typeRegistry', json); } Object subJson = info.fromProto3Json == null // TODO(sigurdm): avoid cloning [object] here. ? (Map<String, dynamic>.from(object)..remove('@type')) : object['value']; // TODO(sigurdm): We lose [context.path]. var packedMessage = info.createEmptyInstance() ..mergeFromProto3Json(subJson, typeRegistry: typeRegistry, supportNamesWithUnderscores: context.supportNamesWithUnderscores, ignoreUnknownFields: context.ignoreUnknownFields, permissiveEnums: context.permissiveEnums); any.value = packedMessage.writeToBuffer(); any.typeUrl = typeUrl; } else { throw context.parseException('Expected a string', json); } } } String _typeNameFromUrl(String typeUrl) { var index = typeUrl.lastIndexOf('/'); return index < 0 ? '' : typeUrl.substring(index + 1); } abstract class TimestampMixin { static final RegExp finalGroupsOfThreeZeroes = RegExp(r'(?:000)*$'); Int64 get seconds; set seconds(Int64 value); int get nanos; set nanos(int value); /// Converts an instance to [DateTime]. /// /// The result is in UTC time zone and has microsecond precision, as /// [DateTime] does not support nanosecond precision. DateTime toDateTime() => DateTime.fromMicrosecondsSinceEpoch( seconds.toInt() * Duration.microsecondsPerSecond + nanos ~/ 1000, isUtc: true); /// Updates [target] to be the time at [datetime]. /// /// Time zone information will not be preserved. static void setFromDateTime(TimestampMixin target, DateTime dateTime) { var micros = dateTime.microsecondsSinceEpoch; target.seconds = Int64(micros ~/ Duration.microsecondsPerSecond); target.nanos = (micros % Duration.microsecondsPerSecond).toInt() * 1000; } static String _twoDigits(int n) { if (n >= 10) return '${n}'; return '0${n}'; } static final DateTime _minTimestamp = DateTime.utc(1); static final DateTime _maxTimestamp = DateTime.utc(9999, 13, 31, 23, 59, 59); // From google/protobuf/timestamp.proto: // # JSON Mapping // // In JSON format, the Timestamp type is encoded as a string in the // [RFC 3339](https://www.ietf.org/rfc/rfc3339.txt) format. That is, the // format is "{year}-{month}-{day}T{hour}:{min}:{sec}[.{frac_sec}]Z" // where {year} is always expressed using four digits while {month}, {day}, // {hour}, {min}, and {sec} are zero-padded to two digits each. The fractional // seconds, which can go up to 9 digits (i.e. up to 1 nanosecond resolution), // are optional. The "Z" suffix indicates the timezone ("UTC"); the timezone // is required. A proto3 JSON serializer should always use UTC (as indicated by // "Z") when printing the Timestamp type and a proto3 JSON parser should be // able to accept both UTC and other timezones (as indicated by an offset). // // For example, "2017-01-15T01:30:15.01Z" encodes 15.01 seconds past // 01:30 UTC on January 15, 2017. static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry) { var timestamp = message as TimestampMixin; var dateTime = timestamp.toDateTime(); if (timestamp.nanos < 0) { throw ArgumentError( 'Timestamp with negative `nanos`: ${timestamp.nanos}'); } if (timestamp.nanos > 999999999) { throw ArgumentError( 'Timestamp with `nanos` out of range: ${timestamp.nanos}'); } if (dateTime.isBefore(_minTimestamp) || dateTime.isAfter(_maxTimestamp)) { throw ArgumentError('Timestamp Must be from 0001-01-01T00:00:00Z to ' '9999-12-31T23:59:59Z inclusive. Was: ${dateTime.toIso8601String()}'); } // Because [DateTime] doesn't have nano-second precision, we cannot use // dateTime.toIso8601String(). var y = '${dateTime.year}'.padLeft(4, '0'); var m = _twoDigits(dateTime.month); var d = _twoDigits(dateTime.day); var h = _twoDigits(dateTime.hour); var min = _twoDigits(dateTime.minute); var sec = _twoDigits(dateTime.second); var secFrac = ''; if (timestamp.nanos > 0) { secFrac = '.' + timestamp.nanos .toString() .padLeft(9, '0') .replaceFirst(finalGroupsOfThreeZeroes, ''); } return '$y-$m-${d}T$h:$min:$sec${secFrac}Z'; } static void fromProto3JsonHelper(GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context) { if (json is String) { var jsonWithoutFracSec = json; var nanos = 0; Match fracSecsMatch = RegExp(r'\.(\d+)').firstMatch(json); if (fracSecsMatch != null) { var fracSecs = fracSecsMatch[1]; if (fracSecs.length > 9) { throw context.parseException( 'Timestamp can have at most than 9 decimal digits', json); } nanos = int.parse(fracSecs.padRight(9, '0')); jsonWithoutFracSec = json.replaceRange(fracSecsMatch.start, fracSecsMatch.end, ''); } var dateTimeWithoutFractionalSeconds = DateTime.tryParse(jsonWithoutFracSec) ?? (throw context.parseException( 'Timestamp not well formatted. ', json)); var timestamp = message as TimestampMixin; setFromDateTime(timestamp, dateTimeWithoutFractionalSeconds); timestamp.nanos = nanos; } else { throw context.parseException( 'Expected timestamp represented as String', json); } } } abstract class DurationMixin { Int64 get seconds; set seconds(Int64 value); int get nanos; set nanos(int value); static final RegExp finalZeroes = RegExp(r'0+$'); static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry) { var duration = message as DurationMixin; var secFrac = duration.nanos // nanos and seconds should always have the same sign. .abs() .toString() .padLeft(9, '0') .replaceFirst(finalZeroes, ''); var secPart = secFrac == '' ? '' : '.$secFrac'; return '${duration.seconds}${secPart}s'; } static final RegExp durationPattern = RegExp(r'(-?\d*)(?:\.(\d*))?s$'); static void fromProto3JsonHelper(GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context) { var duration = message as DurationMixin; if (json is String) { var match = durationPattern.matchAsPrefix(json); if (match == null) { throw context.parseException( 'Expected a String of the form `<seconds>.<nanos>s`', json); } else { var secondsString = match[1]; var seconds = secondsString == '' ? Int64.ZERO : Int64.parseInt(secondsString); duration.seconds = seconds; var nanos = int.parse((match[2] ?? '').padRight(9, '0')); duration.nanos = seconds < 0 ? -nanos : nanos; } } else { throw context.parseException( 'Expected a String of the form `<seconds>.<nanos>s`', json); } } } abstract class StructMixin implements GeneratedMessage { Map<String, ValueMixin> get fields; static const _fieldsFieldTagNumber = 1; // From google/protobuf/struct.proto: // The JSON representation for `Struct` is JSON object. static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry) { var struct = message as StructMixin; return struct.fields.map((key, value) => MapEntry(key, ValueMixin.toProto3JsonHelper(value, typeRegistry))); } static void fromProto3JsonHelper(GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context) { if (json is Map) { // Check for emptiness to avoid setting `.fields` if there are no // values. if (json.isNotEmpty) { var fields = (message as StructMixin).fields; var valueCreator = (message.info_.fieldInfo[_fieldsFieldTagNumber] as MapFieldInfo) .valueCreator; json.forEach((key, value) { if (key is! String) { throw context.parseException('Expected String key', json); } ValueMixin v = valueCreator(); context.addMapIndex(key); ValueMixin.fromProto3JsonHelper(v, value, typeRegistry, context); context.popIndex(); fields[key] = v; }); } } else { throw context.parseException( 'Expected a JSON object literal (map)', json); } } } abstract class ValueMixin implements GeneratedMessage { bool hasNullValue(); ProtobufEnum get nullValue; set nullValue(covariant ProtobufEnum value); bool hasNumberValue(); double get numberValue; set numberValue(double v); bool hasStringValue(); String get stringValue; set stringValue(String v); bool hasBoolValue(); bool get boolValue; set boolValue(bool v); bool hasStructValue(); StructMixin get structValue; set structValue(covariant StructMixin v); bool hasListValue(); ListValueMixin get listValue; set listValue(covariant ListValueMixin v); // From google/protobuf/struct.proto: // The JSON representation for `Value` is JSON value static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry) { var value = message as ValueMixin; // This would ideally be a switch, but we cannot import the enum we are // switching over. if (value.hasNullValue()) { return null; } else if (value.hasNumberValue()) { return value.numberValue; } else if (value.hasStringValue()) { return value.stringValue; } else if (value.hasBoolValue()) { return value.boolValue; } else if (value.hasStructValue()) { return StructMixin.toProto3JsonHelper(value.structValue, typeRegistry); } else if (value.hasListValue()) { return ListValueMixin.toProto3JsonHelper(value.listValue, typeRegistry); } else { throw ArgumentError('Serializing google.protobuf.Value with no value'); } } static void fromProto3JsonHelper(GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context) { var value = message as ValueMixin; if (json == null) { // Rely on the getter retrieving the default to provide an instance. value.nullValue = value.nullValue; } else if (json is num) { value.numberValue = json.toDouble(); } else if (json is String) { value.stringValue = json; } else if (json is bool) { value.boolValue = json; } else if (json is Map) { // Clone because the default instance is frozen. var structValue = value.structValue.deepCopy(); StructMixin.fromProto3JsonHelper( structValue, json, typeRegistry, context); value.structValue = structValue; } else if (json is List) { // Clone because the default instance is frozen. var listValue = value.listValue.deepCopy(); ListValueMixin.fromProto3JsonHelper( listValue, json, typeRegistry, context); value.listValue = listValue; } else { throw context.parseException( 'Expected a json-value (Map, List, String, number, bool or null)', json); } } } abstract class ListValueMixin implements GeneratedMessage { List<ValueMixin> get values; // From google/protobuf/struct.proto: // The JSON representation for `ListValue` is JSON array. static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry) { var list = message as ListValueMixin; return list.values .map((value) => ValueMixin.toProto3JsonHelper(value, typeRegistry)) .toList(); } static const _valueFieldTagNumber = 1; static void fromProto3JsonHelper(GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context) { var list = message as ListValueMixin; if (json is List) { var subBuilder = message.info_.subBuilder(_valueFieldTagNumber); for (var i = 0; i < json.length; i++) { Object element = json[i]; ValueMixin v = subBuilder(); context.addListIndex(i); ValueMixin.fromProto3JsonHelper(v, element, typeRegistry, context); context.popIndex(); list.values.add(v); } } else { throw context.parseException('Expected a json-List', json); } } } abstract class FieldMaskMixin { List<String> get paths; // From google/protobuf/field_mask.proto: // # JSON Encoding of Field Masks // // In JSON, a field mask is encoded as a single string where paths are // separated by a comma. Fields name in each path are converted // to/from lower-camel naming conventions. static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry) { var fieldMask = message as FieldMaskMixin; for (var path in fieldMask.paths) { if (path.contains(RegExp('[A-Z]|_[^a-z]'))) { throw ArgumentError( 'Bad fieldmask $path. Does not round-trip to json.'); } } return fieldMask.paths.map(_toCamelCase).join(','); } static void fromProto3JsonHelper(GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context) { if (json is String) { if (json.contains('_')) { throw context.parseException( 'Invalid Character `_` in FieldMask', json); } if (json == '') { // The empty string splits to a single value. So this is a special case. return; } (message as FieldMaskMixin).paths ..addAll(json.split(',').map(_fromCamelCase)); } else { throw context.parseException( 'Expected String formatted as FieldMask', json); } } static String _toCamelCase(String name) { return name.replaceAllMapped( RegExp('_([a-z])'), (Match m) => '${m.group(1).toUpperCase()}'); } static String _fromCamelCase(String name) { return name.replaceAllMapped( RegExp('[A-Z]'), (Match m) => '_${m.group(0).toLowerCase()}'); } } abstract class DoubleValueMixin { double get value; set value(double value); // From google/protobuf/wrappers.proto: // The JSON representation for `DoubleValue` is JSON number. static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry) { return (message as DoubleValueMixin).value; } static void fromProto3JsonHelper(GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context) { if (json is num) { (message as DoubleValueMixin).value = json.toDouble(); } else if (json is String) { (message as DoubleValueMixin).value = double.tryParse(json) ?? (throw context.parseException( 'Expected string to encode a double', json)); } else { throw context.parseException( 'Expected a double as a String or number', json); } } } abstract class FloatValueMixin { double get value; set value(double value); // From google/protobuf/wrappers.proto: // The JSON representation for `FloatValue` is JSON number. static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry) { return (message as FloatValueMixin).value; } static void fromProto3JsonHelper(GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context) { if (json is num) { (message as FloatValueMixin).value = json.toDouble(); } else if (json is String) { (message as FloatValueMixin).value = double.tryParse(json) ?? (throw context.parseException( 'Expected a float as a String or number', json)); } else { throw context.parseException( 'Expected a float as a String or number', json); } } } abstract class Int64ValueMixin { Int64 get value; set value(Int64 value); // From google/protobuf/wrappers.proto: // The JSON representation for `Int64Value` is JSON string. static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry) { return (message as Int64ValueMixin).value.toString(); } static void fromProto3JsonHelper(GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context) { if (json is int) { (message as Int64ValueMixin).value = Int64(json); } else if (json is String) { try { (message as Int64ValueMixin).value = Int64.parseInt(json); } on FormatException { throw context.parseException('Expected string to encode integer', json); } } else { throw context.parseException( 'Expected an integer encoded as a String or number', json); } } } abstract class UInt64ValueMixin { Int64 get value; set value(Int64 value); // From google/protobuf/wrappers.proto: // The JSON representation for `UInt64Value` is JSON string. static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry) { return (message as UInt64ValueMixin).value.toStringUnsigned(); } static void fromProto3JsonHelper(GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context) { if (json is int) { (message as UInt64ValueMixin).value = Int64(json); } else if (json is String) { try { (message as UInt64ValueMixin).value = Int64.parseInt(json); } on FormatException { throw context.parseException( 'Expected string to encode unsigned integer', json); } } else { throw context.parseException( 'Expected an unsigned integer as a String or integer', json); } } } abstract class Int32ValueMixin { int get value; set value(int value); // From google/protobuf/wrappers.proto: // The JSON representation for `Int32Value` is JSON number. static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry) { return (message as Int32ValueMixin).value; } static void fromProto3JsonHelper(GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context) { if (json is int) { (message as Int32ValueMixin).value = json; } else if (json is String) { (message as Int32ValueMixin).value = int.tryParse(json) ?? (throw context.parseException( 'Expected string to encode integer', json)); } else { throw context.parseException( 'Expected an integer encoded as a String or number', json); } } } abstract class UInt32ValueMixin { int get value; set value(int value); static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry) { return (message as UInt32ValueMixin).value; } // From google/protobuf/wrappers.proto: // The JSON representation for `UInt32Value` is JSON number. static void fromProto3JsonHelper(GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context) { if (json is int) { (message as UInt32ValueMixin).value = json; } else if (json is String) { (message as UInt32ValueMixin).value = int.tryParse(json) ?? (throw context.parseException( 'Expected String to encode an integer', json)); } else { throw context.parseException( 'Expected an unsigned integer as a String or integer', json); } } } abstract class BoolValueMixin { bool get value; set value(bool value); // From google/protobuf/wrappers.proto: // The JSON representation for `BoolValue` is JSON `true` and `false` static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry) { return (message as BoolValueMixin).value; } static void fromProto3JsonHelper(GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context) { if (json is bool) { (message as BoolValueMixin).value = json; } else { throw context.parseException('Expected a bool', json); } } } abstract class StringValueMixin { String get value; set value(String value); // From google/protobuf/wrappers.proto: // The JSON representation for `StringValue` is JSON string. static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry) { return (message as StringValueMixin).value; } static void fromProto3JsonHelper(GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context) { if (json is String) { (message as StringValueMixin).value = json; } else { throw context.parseException('Expected a String', json); } } } abstract class BytesValueMixin { List<int> get value; set value(List<int> value); // From google/protobuf/wrappers.proto: // The JSON representation for `BytesValue` is JSON string. static Object toProto3JsonHelper( GeneratedMessage message, TypeRegistry typeRegistry) { return base64.encode((message as BytesValueMixin).value); } static void fromProto3JsonHelper(GeneratedMessage message, Object json, TypeRegistry typeRegistry, JsonParsingContext context) { if (json is String) { try { (message as BytesValueMixin).value = base64.decode(json); } on FormatException { throw context.parseException( 'Expected bytes encoded as base64 String', json); } } else { throw context.parseException( 'Expected bytes encoded as base64 String', json); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path/path.dart
// Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// A comprehensive, cross-platform path manipulation library. /// /// The path library was designed to be imported with a prefix, though you don't /// have to if you don't want to: /// /// import 'package:path/path.dart' as p; /// /// The most common way to use the library is through the top-level functions. /// These manipulate path strings based on your current working directory and /// the path style (POSIX, Windows, or URLs) of the host platform. For example: /// /// p.join('directory', 'file.txt'); /// /// This calls the top-level [join] function to join "directory" and "file.txt" /// using the current platform's directory separator. /// /// If you want to work with paths for a specific platform regardless of the /// underlying platform that the program is running on, you can create a /// [Context] and give it an explicit [Style]: /// /// var context = p.Context(style: Style.windows); /// context.join('directory', 'file.txt'); /// /// This will join "directory" and "file.txt" using the Windows path separator, /// even when the program is run on a POSIX machine. import 'src/context.dart'; import 'src/style.dart'; export 'src/context.dart' hide createInternal; export 'src/path_exception.dart'; export 'src/path_map.dart'; export 'src/path_set.dart'; export 'src/style.dart'; /// A default context for manipulating POSIX paths. final Context posix = Context(style: Style.posix); /// A default context for manipulating Windows paths. final Context windows = Context(style: Style.windows); /// A default context for manipulating URLs. /// /// URL path equality is undefined for paths that differ only in their /// percent-encoding or only in the case of their host segment. final Context url = Context(style: Style.url); /// The system path context. /// /// This differs from a context created with [new Context] in that its /// [Context.current] is always the current working directory, rather than being /// set once when the context is created. final Context context = createInternal(); /// Returns the [Style] of the current context. /// /// This is the style that all top-level path functions will use. Style get style => context.style; /// Gets the path to the current working directory. /// /// In the browser, this means the current URL, without the last file segment. String get current { // If the current working directory gets deleted out from under the program, // accessing it will throw an IO exception. In order to avoid transient // errors, if we already have a cached working directory, catch the error and // use that. Uri uri; try { uri = Uri.base; } on Exception { if (_current != null) return _current; rethrow; } // Converting the base URI to a file path is pretty slow, and the base URI // rarely changes in practice, so we cache the result here. if (uri == _currentUriBase) return _current; _currentUriBase = uri; if (Style.platform == Style.url) { _current = uri.resolve('.').toString(); } else { final path = uri.toFilePath(); // Remove trailing '/' or '\' unless it is the only thing left // (for instance the root on Linux). final lastIndex = path.length - 1; assert(path[lastIndex] == '/' || path[lastIndex] == '\\'); _current = lastIndex == 0 ? path : path.substring(0, lastIndex); } return _current; } /// The last value returned by [Uri.base]. /// /// This is used to cache the current working directory. Uri _currentUriBase; /// The last known value of the current working directory. /// /// This is cached because [current] is called frequently but rarely actually /// changes. String _current; /// Gets the path separator for the current platform. This is `\` on Windows /// and `/` on other platforms (including the browser). String get separator => context.separator; /// Creates a new path by appending the given path parts to [current]. /// Equivalent to [join()] with [current] as the first argument. Example: /// /// p.absolute('path', 'to/foo'); // -> '/your/current/dir/path/to/foo' String absolute(String part1, [String part2, String part3, String part4, String part5, String part6, String part7]) => context.absolute(part1, part2, part3, part4, part5, part6, part7); /// Gets the part of [path] after the last separator. /// /// p.basename('path/to/foo.dart'); // -> 'foo.dart' /// p.basename('path/to'); // -> 'to' /// /// Trailing separators are ignored. /// /// p.basename('path/to/'); // -> 'to' String basename(String path) => context.basename(path); /// Gets the part of [path] after the last separator, and without any trailing /// file extension. /// /// p.basenameWithoutExtension('path/to/foo.dart'); // -> 'foo' /// /// Trailing separators are ignored. /// /// p.basenameWithoutExtension('path/to/foo.dart/'); // -> 'foo' String basenameWithoutExtension(String path) => context.basenameWithoutExtension(path); /// Gets the part of [path] before the last separator. /// /// p.dirname('path/to/foo.dart'); // -> 'path/to' /// p.dirname('path/to'); // -> 'path' /// /// Trailing separators are ignored. /// /// p.dirname('path/to/'); // -> 'path' /// /// If an absolute path contains no directories, only a root, then the root /// is returned. /// /// p.dirname('/'); // -> '/' (posix) /// p.dirname('c:\'); // -> 'c:\' (windows) /// /// If a relative path has no directories, then '.' is returned. /// /// p.dirname('foo'); // -> '.' /// p.dirname(''); // -> '.' String dirname(String path) => context.dirname(path); /// Gets the file extension of [path]: the portion of [basename] from the last /// `.` to the end (including the `.` itself). /// /// p.extension('path/to/foo.dart'); // -> '.dart' /// p.extension('path/to/foo'); // -> '' /// p.extension('path.to/foo'); // -> '' /// p.extension('path/to/foo.dart.js'); // -> '.js' /// /// If the file name starts with a `.`, then that is not considered the /// extension: /// /// p.extension('~/.bashrc'); // -> '' /// p.extension('~/.notes.txt'); // -> '.txt' /// /// Takes an optional parameter `level` which makes possible to return /// multiple extensions having `level` number of dots. If `level` exceeds the /// number of dots, the full extension is returned. The value of `level` must /// be greater than 0, else `RangeError` is thrown. /// /// p.extension('foo.bar.dart.js', 2); // -> '.dart.js /// p.extension('foo.bar.dart.js', 3); // -> '.bar.dart.js' /// p.extension('foo.bar.dart.js', 10); // -> '.bar.dart.js' /// p.extension('path/to/foo.bar.dart.js', 2); // -> '.dart.js' String extension(String path, [int level = 1]) => context.extension(path, level); /// Returns the root of [path], if it's absolute, or the empty string if it's /// relative. /// /// // Unix /// p.rootPrefix('path/to/foo'); // -> '' /// p.rootPrefix('/path/to/foo'); // -> '/' /// /// // Windows /// p.rootPrefix(r'path\to\foo'); // -> '' /// p.rootPrefix(r'C:\path\to\foo'); // -> r'C:\' /// p.rootPrefix(r'\\server\share\a\b'); // -> r'\\server\share' /// /// // URL /// p.rootPrefix('path/to/foo'); // -> '' /// p.rootPrefix('https://dart.dev/path/to/foo'); /// // -> 'https://dart.dev' String rootPrefix(String path) => context.rootPrefix(path); /// Returns `true` if [path] is an absolute path and `false` if it is a /// relative path. /// /// On POSIX systems, absolute paths start with a `/` (forward slash). On /// Windows, an absolute path starts with `\\`, or a drive letter followed by /// `:/` or `:\`. For URLs, absolute paths either start with a protocol and /// optional hostname (e.g. `https://dart.dev`, `file://`) or with a `/`. /// /// URLs that start with `/` are known as "root-relative", since they're /// relative to the root of the current URL. Since root-relative paths are still /// absolute in every other sense, [isAbsolute] will return true for them. They /// can be detected using [isRootRelative]. bool isAbsolute(String path) => context.isAbsolute(path); /// Returns `true` if [path] is a relative path and `false` if it is absolute. /// On POSIX systems, absolute paths start with a `/` (forward slash). On /// Windows, an absolute path starts with `\\`, or a drive letter followed by /// `:/` or `:\`. bool isRelative(String path) => context.isRelative(path); /// Returns `true` if [path] is a root-relative path and `false` if it's not. /// /// URLs that start with `/` are known as "root-relative", since they're /// relative to the root of the current URL. Since root-relative paths are still /// absolute in every other sense, [isAbsolute] will return true for them. They /// can be detected using [isRootRelative]. /// /// No POSIX and Windows paths are root-relative. bool isRootRelative(String path) => context.isRootRelative(path); /// Joins the given path parts into a single path using the current platform's /// [separator]. Example: /// /// p.join('path', 'to', 'foo'); // -> 'path/to/foo' /// /// If any part ends in a path separator, then a redundant separator will not /// be added: /// /// p.join('path/', 'to', 'foo'); // -> 'path/to/foo /// /// If a part is an absolute path, then anything before that will be ignored: /// /// p.join('path', '/to', 'foo'); // -> '/to/foo' String join(String part1, [String part2, String part3, String part4, String part5, String part6, String part7, String part8]) => context.join(part1, part2, part3, part4, part5, part6, part7, part8); /// Joins the given path parts into a single path using the current platform's /// [separator]. Example: /// /// p.joinAll(['path', 'to', 'foo']); // -> 'path/to/foo' /// /// If any part ends in a path separator, then a redundant separator will not /// be added: /// /// p.joinAll(['path/', 'to', 'foo']); // -> 'path/to/foo /// /// If a part is an absolute path, then anything before that will be ignored: /// /// p.joinAll(['path', '/to', 'foo']); // -> '/to/foo' /// /// For a fixed number of parts, [join] is usually terser. String joinAll(Iterable<String> parts) => context.joinAll(parts); /// Splits [path] into its components using the current platform's [separator]. /// /// p.split('path/to/foo'); // -> ['path', 'to', 'foo'] /// /// The path will *not* be normalized before splitting. /// /// p.split('path/../foo'); // -> ['path', '..', 'foo'] /// /// If [path] is absolute, the root directory will be the first element in the /// array. Example: /// /// // Unix /// p.split('/path/to/foo'); // -> ['/', 'path', 'to', 'foo'] /// /// // Windows /// p.split(r'C:\path\to\foo'); // -> [r'C:\', 'path', 'to', 'foo'] /// p.split(r'\\server\share\path\to\foo'); /// // -> [r'\\server\share', 'foo', 'bar', 'baz'] /// /// // Browser /// p.split('https://dart.dev/path/to/foo'); /// // -> ['https://dart.dev', 'path', 'to', 'foo'] List<String> split(String path) => context.split(path); /// Canonicalizes [path]. /// /// This is guaranteed to return the same path for two different input paths /// if and only if both input paths point to the same location. Unlike /// [normalize], it returns absolute paths when possible and canonicalizes /// ASCII case on Windows. /// /// Note that this does not resolve symlinks. /// /// If you want a map that uses path keys, it's probably more efficient to /// pass [equals] and [hash] to [new HashMap] than it is to canonicalize every /// key. String canonicalize(String path) => context.canonicalize(path); /// Normalizes [path], simplifying it by handling `..`, and `.`, and /// removing redundant path separators whenever possible. /// /// Note that this is *not* guaranteed to return the same result for two /// equivalent input paths. For that, see [canonicalize]. Or, if you're using /// paths as map keys, pass [equals] and [hash] to [new HashMap]. /// /// p.normalize('path/./to/..//file.text'); // -> 'path/file.txt' String normalize(String path) => context.normalize(path); /// Attempts to convert [path] to an equivalent relative path from the current /// directory. /// /// // Given current directory is /root/path: /// p.relative('/root/path/a/b.dart'); // -> 'a/b.dart' /// p.relative('/root/other.dart'); // -> '../other.dart' /// /// If the [from] argument is passed, [path] is made relative to that instead. /// /// p.relative('/root/path/a/b.dart', from: '/root/path'); // -> 'a/b.dart' /// p.relative('/root/other.dart', from: '/root/path'); /// // -> '../other.dart' /// /// If [path] and/or [from] are relative paths, they are assumed to be relative /// to the current directory. /// /// Since there is no relative path from one drive letter to another on Windows, /// or from one hostname to another for URLs, this will return an absolute path /// in those cases. /// /// // Windows /// p.relative(r'D:\other', from: r'C:\home'); // -> 'D:\other' /// /// // URL /// p.relative('https://dart.dev', from: 'https://pub.dev'); /// // -> 'https://dart.dev' String relative(String path, {String from}) => context.relative(path, from: from); /// Returns `true` if [child] is a path beneath `parent`, and `false` otherwise. /// /// p.isWithin('/root/path', '/root/path/a'); // -> true /// p.isWithin('/root/path', '/root/other'); // -> false /// p.isWithin('/root/path', '/root/path') // -> false bool isWithin(String parent, String child) => context.isWithin(parent, child); /// Returns `true` if [path1] points to the same location as [path2], and /// `false` otherwise. /// /// The [hash] function returns a hash code that matches these equality /// semantics. bool equals(String path1, String path2) => context.equals(path1, path2); /// Returns a hash code for [path] such that, if [equals] returns `true` for two /// paths, their hash codes are the same. /// /// Note that the same path may have different hash codes on different platforms /// or with different [current] directories. int hash(String path) => context.hash(path); /// Removes a trailing extension from the last part of [path]. /// /// p.withoutExtension('path/to/foo.dart'); // -> 'path/to/foo' String withoutExtension(String path) => context.withoutExtension(path); /// Returns [path] with the trailing extension set to [extension]. /// /// If [path] doesn't have a trailing extension, this just adds [extension] to /// the end. /// /// p.setExtension('path/to/foo.dart', '.js') // -> 'path/to/foo.js' /// p.setExtension('path/to/foo.dart.js', '.map') /// // -> 'path/to/foo.dart.map' /// p.setExtension('path/to/foo', '.js') // -> 'path/to/foo.js' String setExtension(String path, String extension) => context.setExtension(path, extension); /// Returns the path represented by [uri], which may be a [String] or a [Uri]. /// /// For POSIX and Windows styles, [uri] must be a `file:` URI. For the URL /// style, this will just convert [uri] to a string. /// /// // POSIX /// p.fromUri('file:///path/to/foo') // -> '/path/to/foo' /// /// // Windows /// p.fromUri('file:///C:/path/to/foo') // -> r'C:\path\to\foo' /// /// // URL /// p.fromUri('https://dart.dev/path/to/foo') /// // -> 'https://dart.dev/path/to/foo' /// /// If [uri] is relative, a relative path will be returned. /// /// p.fromUri('path/to/foo'); // -> 'path/to/foo' String fromUri(uri) => context.fromUri(uri); /// Returns the URI that represents [path]. /// /// For POSIX and Windows styles, this will return a `file:` URI. For the URL /// style, this will just convert [path] to a [Uri]. /// /// // POSIX /// p.toUri('/path/to/foo') /// // -> Uri.parse('file:///path/to/foo') /// /// // Windows /// p.toUri(r'C:\path\to\foo') /// // -> Uri.parse('file:///C:/path/to/foo') /// /// // URL /// p.toUri('https://dart.dev/path/to/foo') /// // -> Uri.parse('https://dart.dev/path/to/foo') /// /// If [path] is relative, a relative URI will be returned. /// /// p.toUri('path/to/foo') // -> Uri.parse('path/to/foo') Uri toUri(String path) => context.toUri(path); /// Returns a terse, human-readable representation of [uri]. /// /// [uri] can be a [String] or a [Uri]. If it can be made relative to the /// current working directory, that's done. Otherwise, it's returned as-is. This /// gracefully handles non-`file:` URIs for [Style.posix] and [Style.windows]. /// /// The returned value is meant for human consumption, and may be either URI- /// or path-formatted. /// /// // POSIX at "/root/path" /// p.prettyUri('file:///root/path/a/b.dart'); // -> 'a/b.dart' /// p.prettyUri('https://dart.dev/'); // -> 'https://dart.dev' /// /// // Windows at "C:\root\path" /// p.prettyUri('file:///C:/root/path/a/b.dart'); // -> r'a\b.dart' /// p.prettyUri('https://dart.dev/'); // -> 'https://dart.dev' /// /// // URL at "https://dart.dev/root/path" /// p.prettyUri('https://dart.dev/root/path/a/b.dart'); // -> r'a/b.dart' /// p.prettyUri('file:///root/path'); // -> 'file:///root/path' String prettyUri(uri) => context.prettyUri(uri);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path/src/style.dart
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'context.dart'; import 'style/posix.dart'; import 'style/url.dart'; import 'style/windows.dart'; /// An enum type describing a "flavor" of path. abstract class Style { /// POSIX-style paths use "/" (forward slash) as separators. Absolute paths /// start with "/". Used by UNIX, Linux, Mac OS X, and others. static final Style posix = PosixStyle(); /// Windows paths use `\` (backslash) as separators. Absolute paths start with /// a drive letter followed by a colon (example, `C:`) or two backslashes /// (`\\`) for UNC paths. static final Style windows = WindowsStyle(); /// URLs aren't filesystem paths, but they're supported to make it easier to /// manipulate URL paths in the browser. /// /// URLs use "/" (forward slash) as separators. Absolute paths either start /// with a protocol and optional hostname (e.g. `https://dart.dev`, /// `file://`) or with "/". static final Style url = UrlStyle(); /// The style of the host platform. /// /// When running on the command line, this will be [windows] or [posix] based /// on the host operating system. On a browser, this will be [url]. static final Style platform = _getPlatformStyle(); /// Gets the type of the host platform. static Style _getPlatformStyle() { // If we're running a Dart file in the browser from a `file:` URI, // [Uri.base] will point to a file. If we're running on the standalone, // it will point to a directory. We can use that fact to determine which // style to use. if (Uri.base.scheme != 'file') return Style.url; if (!Uri.base.path.endsWith('/')) return Style.url; if (Uri(path: 'a/b').toFilePath() == 'a\\b') return Style.windows; return Style.posix; } /// The name of this path style. Will be "posix" or "windows". String get name; /// A [Context] that uses this style. Context get context => Context(style: this); @Deprecated('Most Style members will be removed in path 2.0.') String get separator; @Deprecated('Most Style members will be removed in path 2.0.') Pattern get separatorPattern; @Deprecated('Most Style members will be removed in path 2.0.') Pattern get needsSeparatorPattern; @Deprecated('Most Style members will be removed in path 2.0.') Pattern get rootPattern; @Deprecated('Most Style members will be removed in path 2.0.') Pattern get relativeRootPattern; @Deprecated('Most style members will be removed in path 2.0.') String getRoot(String path); @Deprecated('Most style members will be removed in path 2.0.') String getRelativeRoot(String path); @Deprecated('Most style members will be removed in path 2.0.') String pathFromUri(Uri uri); @Deprecated('Most style members will be removed in path 2.0.') Uri relativePathToUri(String path); @Deprecated('Most style members will be removed in path 2.0.') Uri absolutePathToUri(String path); @override String toString() => name; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path/src/parsed_path.dart
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'internal_style.dart'; import 'style.dart'; class ParsedPath { /// The [InternalStyle] that was used to parse this path. InternalStyle style; /// The absolute root portion of the path, or `null` if the path is relative. /// On POSIX systems, this will be `null` or "/". On Windows, it can be /// `null`, "//" for a UNC path, or something like "C:\" for paths with drive /// letters. String root; /// Whether this path is root-relative. /// /// See [Context.isRootRelative]. bool isRootRelative; /// The path-separated parts of the path. All but the last will be /// directories. List<String> parts; /// The path separators preceding each part. /// /// The first one will be an empty string unless the root requires a separator /// between it and the path. The last one will be an empty string unless the /// path ends with a trailing separator. List<String> separators; /// The file extension of the last non-empty part, or "" if it doesn't have /// one. String extension([int level]) => _splitExtension(level)[1]; /// `true` if this is an absolute path. bool get isAbsolute => root != null; factory ParsedPath.parse(String path, InternalStyle style) { // Remove the root prefix, if any. final root = style.getRoot(path); final isRootRelative = style.isRootRelative(path); if (root != null) path = path.substring(root.length); // Split the parts on path separators. final parts = <String>[]; final separators = <String>[]; var start = 0; if (path.isNotEmpty && style.isSeparator(path.codeUnitAt(0))) { separators.add(path[0]); start = 1; } else { separators.add(''); } for (var i = start; i < path.length; i++) { if (style.isSeparator(path.codeUnitAt(i))) { parts.add(path.substring(start, i)); separators.add(path[i]); start = i + 1; } } // Add the final part, if any. if (start < path.length) { parts.add(path.substring(start)); separators.add(''); } return ParsedPath._(style, root, isRootRelative, parts, separators); } ParsedPath._( this.style, this.root, this.isRootRelative, this.parts, this.separators); String get basename { final copy = clone(); copy.removeTrailingSeparators(); if (copy.parts.isEmpty) return root ?? ''; return copy.parts.last; } String get basenameWithoutExtension => _splitExtension()[0]; bool get hasTrailingSeparator => parts.isNotEmpty && (parts.last == '' || separators.last != ''); void removeTrailingSeparators() { while (parts.isNotEmpty && parts.last == '') { parts.removeLast(); separators.removeLast(); } if (separators.isNotEmpty) separators[separators.length - 1] = ''; } void normalize({bool canonicalize = false}) { // Handle '.', '..', and empty parts. var leadingDoubles = 0; final newParts = <String>[]; for (var part in parts) { if (part == '.' || part == '') { // Do nothing. Ignore it. } else if (part == '..') { // Pop the last part off. if (newParts.isNotEmpty) { newParts.removeLast(); } else { // Backed out past the beginning, so preserve the "..". leadingDoubles++; } } else { newParts.add(canonicalize ? style.canonicalizePart(part) : part); } } // A relative path can back out from the start directory. if (!isAbsolute) { newParts.insertAll(0, List.filled(leadingDoubles, '..')); } // If we collapsed down to nothing, do ".". if (newParts.isEmpty && !isAbsolute) { newParts.add('.'); } // Canonicalize separators. final newSeparators = List<String>.generate( newParts.length, (_) => style.separator, growable: true); newSeparators.insert( 0, isAbsolute && newParts.isNotEmpty && style.needsSeparator(root) ? style.separator : ''); parts = newParts; separators = newSeparators; // Normalize the Windows root if needed. if (root != null && style == Style.windows) { if (canonicalize) root = root.toLowerCase(); root = root.replaceAll('/', '\\'); } removeTrailingSeparators(); } @override String toString() { final builder = StringBuffer(); if (root != null) builder.write(root); for (var i = 0; i < parts.length; i++) { builder.write(separators[i]); builder.write(parts[i]); } builder.write(separators.last); return builder.toString(); } /// Returns k-th last index of the `character` in the `path`. /// /// If `k` exceeds the count of `character`s in `path`, the left most index /// of the `character` is returned. int _kthLastIndexOf(String path, String character, int k) { var count = 0, leftMostIndexedCharacter = 0; for (var index = path.length - 1; index >= 0; --index) { if (path[index] == character) { leftMostIndexedCharacter = index; ++count; if (count == k) { return index; } } } return leftMostIndexedCharacter; } /// Splits the last non-empty part of the path into a `[basename, extension]` /// pair. /// /// Takes an optional parameter `level` which makes possible to return /// multiple extensions having `level` number of dots. If `level` exceeds the /// number of dots, the path is split at the first most dot. The value of /// `level` must be greater than 0, else `RangeError` is thrown. /// /// Returns a two-element list. The first is the name of the file without any /// extension. The second is the extension or "" if it has none. List<String> _splitExtension([int level = 1]) { if (level == null) throw ArgumentError.notNull('level'); if (level <= 0) { throw RangeError.value( level, 'level', "level's value must be greater than 0"); } final file = parts.lastWhere((p) => p != '', orElse: () => null); if (file == null) return ['', '']; if (file == '..') return ['..', '']; final lastDot = _kthLastIndexOf(file, '.', level); // If there is no dot, or it's the first character, like '.bashrc', it // doesn't count. if (lastDot <= 0) return [file, '']; return [file.substring(0, lastDot), file.substring(lastDot)]; } ParsedPath clone() => ParsedPath._( style, root, isRootRelative, List.from(parts), List.from(separators)); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path/src/path_set.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:collection'; import '../path.dart' as p; /// A set containing paths, compared using [equals] and [hash]. class PathSet extends IterableBase<String> implements Set<String> { /// The set to which we forward implementation methods. final Set<String> _inner; /// Creates an empty [PathSet] whose contents are compared using /// `context.equals` and `context.hash`. /// /// The [context] defaults to the current path context. PathSet({p.Context context}) : _inner = _create(context); /// Creates a [PathSet] with the same contents as [other] whose elements are /// compared using `context.equals` and `context.hash`. /// /// The [context] defaults to the current path context. If multiple elements /// in [other] represent the same logical path, the first value will be /// used. PathSet.of(Iterable<String> other, {p.Context context}) : _inner = _create(context)..addAll(other); /// Creates a set that uses [context] for equality and hashing. static Set<String> _create(p.Context context) { context ??= p.context; return LinkedHashSet( equals: (path1, path2) { if (path1 == null) return path2 == null; if (path2 == null) return false; return context.equals(path1, path2); }, hashCode: (path) => path == null ? 0 : context.hash(path), isValidKey: (path) => path is String || path == null); } // Normally we'd use DelegatingSetView from the collection package to // implement these, but we want to avoid adding dependencies from path because // it's so widely used that even brief version skew can be very painful. @override Iterator<String> get iterator => _inner.iterator; @override int get length => _inner.length; @override bool add(String value) => _inner.add(value); @override void addAll(Iterable<String> elements) => _inner.addAll(elements); @override Set<T> cast<T>() => _inner.cast<T>(); @override void clear() => _inner.clear(); @override bool contains(Object element) => _inner.contains(element); @override bool containsAll(Iterable<Object> other) => _inner.containsAll(other); @override Set<String> difference(Set<Object> other) => _inner.difference(other); @override Set<String> intersection(Set<Object> other) => _inner.intersection(other); @override String lookup(Object element) => _inner.lookup(element); @override bool remove(Object value) => _inner.remove(value); @override void removeAll(Iterable<Object> elements) => _inner.removeAll(elements); @override void removeWhere(bool Function(String) test) => _inner.removeWhere(test); @override void retainAll(Iterable<Object> elements) => _inner.retainAll(elements); @override void retainWhere(bool Function(String) test) => _inner.retainWhere(test); @override Set<String> union(Set<String> other) => _inner.union(other); @override Set<String> toSet() => _inner.toSet(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path/src/characters.dart
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// This library contains character-code definitions. const plus = 0x2b; const minus = 0x2d; const period = 0x2e; const slash = 0x2f; const zero = 0x30; const nine = 0x39; const colon = 0x3a; const upperA = 0x41; const upperZ = 0x5a; const lowerA = 0x61; const lowerZ = 0x7a; const backslash = 0x5c;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path/src/path_exception.dart
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// An exception class that's thrown when a path operation is unable to be /// computed accurately. class PathException implements Exception { String message; PathException(this.message); @override String toString() => 'PathException: $message'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path/src/path_map.dart
// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:collection'; import '../path.dart' as p; /// A map whose keys are paths, compared using [equals] and [hash]. class PathMap<V> extends MapView<String, V> { /// Creates an empty [PathMap] whose keys are compared using `context.equals` /// and `context.hash`. /// /// The [context] defaults to the current path context. PathMap({p.Context context}) : super(_create(context)); /// Creates a [PathMap] with the same keys and values as [other] whose keys /// are compared using `context.equals` and `context.hash`. /// /// The [context] defaults to the current path context. If multiple keys in /// [other] represent the same logical path, the last key's value will be /// used. PathMap.of(Map<String, V> other, {p.Context context}) : super(_create(context)..addAll(other)); /// Creates a map that uses [context] for equality and hashing. static Map<String, V> _create<V>(p.Context context) { context ??= p.context; return LinkedHashMap( equals: (path1, path2) { if (path1 == null) return path2 == null; if (path2 == null) return false; return context.equals(path1, path2); }, hashCode: (path) => path == null ? 0 : context.hash(path), isValidKey: (path) => path is String || path == null); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path/src/internal_style.dart
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'context.dart'; import 'style.dart'; /// The internal interface for the [Style] type. /// /// Users should be able to pass around instances of [Style] like an enum, but /// the members that [Context] uses should be hidden from them. Those members /// are defined on this class instead. abstract class InternalStyle extends Style { /// The default path separator for this style. /// /// On POSIX, this is `/`. On Windows, it's `\`. @override String get separator; /// Returns whether [path] contains a separator. bool containsSeparator(String path); /// Returns whether [codeUnit] is the character code of a separator. bool isSeparator(int codeUnit); /// Returns whether this path component needs a separator after it. /// /// Windows and POSIX styles just need separators when the previous component /// doesn't already end in a separator, but the URL always needs to place a /// separator between the root and the first component, even if the root /// already ends in a separator character. For example, to join "file://" and /// "usr", an additional "/" is needed (making "file:///usr"). bool needsSeparator(String path); /// Returns the number of characters of the root part. /// /// Returns 0 if the path is relative and 1 if the path is root-relative. /// /// If [withDrive] is `true`, this should include the drive letter for `file:` /// URLs. Non-URL styles may ignore the parameter. int rootLength(String path, {bool withDrive = false}); /// Gets the root prefix of [path] if path is absolute. If [path] is relative, /// returns `null`. @override String getRoot(String path) { final length = rootLength(path); if (length > 0) return path.substring(0, length); return isRootRelative(path) ? path[0] : null; } /// Returns whether [path] is root-relative. /// /// If [path] is relative or absolute and not root-relative, returns `false`. bool isRootRelative(String path); /// Returns the path represented by [uri] in this style. @override String pathFromUri(Uri uri); /// Returns the URI that represents the relative path made of [parts]. @override Uri relativePathToUri(String path) { final segments = context.split(path); // Ensure that a trailing slash in the path produces a trailing slash in the // URL. if (isSeparator(path.codeUnitAt(path.length - 1))) segments.add(''); return Uri(pathSegments: segments); } /// Returns the URI that represents [path], which is assumed to be absolute. @override Uri absolutePathToUri(String path); /// Returns whether [codeUnit1] and [codeUnit2] are considered equivalent for /// this style. bool codeUnitsEqual(int codeUnit1, int codeUnit2) => codeUnit1 == codeUnit2; /// Returns whether [path1] and [path2] are equivalent. /// /// This only needs to handle character-by-character comparison; it can assume /// the paths are normalized and contain no `..` components. bool pathsEqual(String path1, String path2) => path1 == path2; int canonicalizeCodeUnit(int codeUnit) => codeUnit; String canonicalizePart(String part) => part; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path/src/utils.dart
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'characters.dart' as chars; /// Returns whether [char] is the code for an ASCII letter (uppercase or /// lowercase). bool isAlphabetic(int char) => (char >= chars.upperA && char <= chars.upperZ) || (char >= chars.lowerA && char <= chars.lowerZ); /// Returns whether [char] is the code for an ASCII digit. bool isNumeric(int char) => char >= chars.zero && char <= chars.nine; /// Returns whether [path] has a URL-formatted Windows drive letter beginning at /// [index]. bool isDriveLetter(String path, int index) { if (path.length < index + 2) return false; if (!isAlphabetic(path.codeUnitAt(index))) return false; if (path.codeUnitAt(index + 1) != chars.colon) return false; if (path.length == index + 2) return true; return path.codeUnitAt(index + 2) == chars.slash; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path/src/context.dart
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:math' as math; import '../path.dart' as p; import 'characters.dart' as chars; import 'internal_style.dart'; import 'parsed_path.dart'; import 'path_exception.dart'; import 'style.dart'; Context createInternal() => Context._internal(); /// An instantiable class for manipulating paths. Unlike the top-level /// functions, this lets you explicitly select what platform the paths will use. class Context { /// Creates a new path context for the given style and current directory. /// /// If [style] is omitted, it uses the host operating system's path style. If /// only [current] is omitted, it defaults ".". If *both* [style] and /// [current] are omitted, [current] defaults to the real current working /// directory. /// /// On the browser, [style] defaults to [Style.url] and [current] defaults to /// the current URL. factory Context({Style style, String current}) { if (current == null) { if (style == null) { current = p.current; } else { current = '.'; } } if (style == null) { style = Style.platform; } else if (style is! InternalStyle) { throw ArgumentError('Only styles defined by the path package are ' 'allowed.'); } return Context._(style as InternalStyle, current); } /// Create a [Context] to be used internally within path. Context._internal() : style = Style.platform as InternalStyle, _current = null; Context._(this.style, this._current); /// The style of path that this context works with. final InternalStyle style; /// The current directory given when Context was created. If null, current /// directory is evaluated from 'p.current'. final String _current; /// The current directory that relative paths are relative to. String get current => _current ?? p.current; /// Gets the path separator for the context's [style]. On Mac and Linux, /// this is `/`. On Windows, it's `\`. String get separator => style.separator; /// Creates a new path by appending the given path parts to [current]. /// Equivalent to [join()] with [current] as the first argument. Example: /// /// var context = Context(current: '/root'); /// context.absolute('path', 'to', 'foo'); // -> '/root/path/to/foo' /// /// If [current] isn't absolute, this won't return an absolute path. String absolute(String part1, [String part2, String part3, String part4, String part5, String part6, String part7]) { _validateArgList( 'absolute', [part1, part2, part3, part4, part5, part6, part7]); // If there's a single absolute path, just return it. This is a lot faster // for the common case of `p.absolute(path)`. if (part2 == null && isAbsolute(part1) && !isRootRelative(part1)) { return part1; } return join(current, part1, part2, part3, part4, part5, part6, part7); } /// Gets the part of [path] after the last separator on the context's /// platform. /// /// context.basename('path/to/foo.dart'); // -> 'foo.dart' /// context.basename('path/to'); // -> 'to' /// /// Trailing separators are ignored. /// /// context.basename('path/to/'); // -> 'to' String basename(String path) => _parse(path).basename; /// Gets the part of [path] after the last separator on the context's /// platform, and without any trailing file extension. /// /// context.basenameWithoutExtension('path/to/foo.dart'); // -> 'foo' /// /// Trailing separators are ignored. /// /// context.basenameWithoutExtension('path/to/foo.dart/'); // -> 'foo' String basenameWithoutExtension(String path) => _parse(path).basenameWithoutExtension; /// Gets the part of [path] before the last separator. /// /// context.dirname('path/to/foo.dart'); // -> 'path/to' /// context.dirname('path/to'); // -> 'path' /// /// Trailing separators are ignored. /// /// context.dirname('path/to/'); // -> 'path' String dirname(String path) { final parsed = _parse(path); parsed.removeTrailingSeparators(); if (parsed.parts.isEmpty) return parsed.root ?? '.'; if (parsed.parts.length == 1) return parsed.root ?? '.'; parsed.parts.removeLast(); parsed.separators.removeLast(); parsed.removeTrailingSeparators(); return parsed.toString(); } /// Gets the file extension of [path]: the portion of [basename] from the last /// `.` to the end (including the `.` itself). /// /// context.extension('path/to/foo.dart'); // -> '.dart' /// context.extension('path/to/foo'); // -> '' /// context.extension('path.to/foo'); // -> '' /// context.extension('path/to/foo.dart.js'); // -> '.js' /// /// If the file name starts with a `.`, then it is not considered an /// extension: /// /// context.extension('~/.bashrc'); // -> '' /// context.extension('~/.notes.txt'); // -> '.txt' /// /// Takes an optional parameter `level` which makes possible to return /// multiple extensions having `level` number of dots. If `level` exceeds the /// number of dots, the full extension is returned. The value of `level` must /// be greater than 0, else `RangeError` is thrown. /// /// context.extension('foo.bar.dart.js', 2); // -> '.dart.js /// context.extension('foo.bar.dart.js', 3); // -> '.bar.dart.js' /// context.extension('foo.bar.dart.js', 10); // -> '.bar.dart.js' /// context.extension('path/to/foo.bar.dart.js', 2); // -> '.dart.js' String extension(String path, [int level = 1]) => _parse(path).extension(level); /// Returns the root of [path] if it's absolute, or an empty string if it's /// relative. /// /// // Unix /// context.rootPrefix('path/to/foo'); // -> '' /// context.rootPrefix('/path/to/foo'); // -> '/' /// /// // Windows /// context.rootPrefix(r'path\to\foo'); // -> '' /// context.rootPrefix(r'C:\path\to\foo'); // -> r'C:\' /// context.rootPrefix(r'\\server\share\a\b'); // -> r'\\server\share' /// /// // URL /// context.rootPrefix('path/to/foo'); // -> '' /// context.rootPrefix('https://dart.dev/path/to/foo'); /// // -> 'https://dart.dev' String rootPrefix(String path) => path.substring(0, style.rootLength(path)); /// Returns `true` if [path] is an absolute path and `false` if it is a /// relative path. /// /// On POSIX systems, absolute paths start with a `/` (forward slash). On /// Windows, an absolute path starts with `\\`, or a drive letter followed by /// `:/` or `:\`. For URLs, absolute paths either start with a protocol and /// optional hostname (e.g. `https://dart.dev`, `file://`) or with a `/`. /// /// URLs that start with `/` are known as "root-relative", since they're /// relative to the root of the current URL. Since root-relative paths are /// still absolute in every other sense, [isAbsolute] will return true for /// them. They can be detected using [isRootRelative]. bool isAbsolute(String path) => style.rootLength(path) > 0; /// Returns `true` if [path] is a relative path and `false` if it is absolute. /// On POSIX systems, absolute paths start with a `/` (forward slash). On /// Windows, an absolute path starts with `\\`, or a drive letter followed by /// `:/` or `:\`. bool isRelative(String path) => !isAbsolute(path); /// Returns `true` if [path] is a root-relative path and `false` if it's not. /// /// URLs that start with `/` are known as "root-relative", since they're /// relative to the root of the current URL. Since root-relative paths are /// still absolute in every other sense, [isAbsolute] will return true for /// them. They can be detected using [isRootRelative]. /// /// No POSIX and Windows paths are root-relative. bool isRootRelative(String path) => style.isRootRelative(path); /// Joins the given path parts into a single path. Example: /// /// context.join('path', 'to', 'foo'); // -> 'path/to/foo' /// /// If any part ends in a path separator, then a redundant separator will not /// be added: /// /// context.join('path/', 'to', 'foo'); // -> 'path/to/foo /// /// If a part is an absolute path, then anything before that will be ignored: /// /// context.join('path', '/to', 'foo'); // -> '/to/foo' /// String join(String part1, [String part2, String part3, String part4, String part5, String part6, String part7, String part8]) { final parts = <String>[ part1, part2, part3, part4, part5, part6, part7, part8 ]; _validateArgList('join', parts); return joinAll(parts.where((part) => part != null)); } /// Joins the given path parts into a single path. Example: /// /// context.joinAll(['path', 'to', 'foo']); // -> 'path/to/foo' /// /// If any part ends in a path separator, then a redundant separator will not /// be added: /// /// context.joinAll(['path/', 'to', 'foo']); // -> 'path/to/foo /// /// If a part is an absolute path, then anything before that will be ignored: /// /// context.joinAll(['path', '/to', 'foo']); // -> '/to/foo' /// /// For a fixed number of parts, [join] is usually terser. String joinAll(Iterable<String> parts) { final buffer = StringBuffer(); var needsSeparator = false; var isAbsoluteAndNotRootRelative = false; for (var part in parts.where((part) => part != '')) { if (isRootRelative(part) && isAbsoluteAndNotRootRelative) { // If the new part is root-relative, it preserves the previous root but // replaces the path after it. final parsed = _parse(part); final path = buffer.toString(); parsed.root = path.substring(0, style.rootLength(path, withDrive: true)); if (style.needsSeparator(parsed.root)) { parsed.separators[0] = style.separator; } buffer.clear(); buffer.write(parsed.toString()); } else if (isAbsolute(part)) { isAbsoluteAndNotRootRelative = !isRootRelative(part); // An absolute path discards everything before it. buffer.clear(); buffer.write(part); } else { if (part.isNotEmpty && style.containsSeparator(part[0])) { // The part starts with a separator, so we don't need to add one. } else if (needsSeparator) { buffer.write(separator); } buffer.write(part); } // Unless this part ends with a separator, we'll need to add one before // the next part. needsSeparator = style.needsSeparator(part); } return buffer.toString(); } /// Splits [path] into its components using the current platform's /// [separator]. Example: /// /// context.split('path/to/foo'); // -> ['path', 'to', 'foo'] /// /// The path will *not* be normalized before splitting. /// /// context.split('path/../foo'); // -> ['path', '..', 'foo'] /// /// If [path] is absolute, the root directory will be the first element in the /// array. Example: /// /// // Unix /// context.split('/path/to/foo'); // -> ['/', 'path', 'to', 'foo'] /// /// // Windows /// context.split(r'C:\path\to\foo'); // -> [r'C:\', 'path', 'to', 'foo'] /// context.split(r'\\server\share\path\to\foo'); /// // -> [r'\\server\share', 'foo', 'bar', 'baz'] /// /// // Browser /// context.split('https://dart.dev/path/to/foo'); /// // -> ['https://dart.dev', 'path', 'to', 'foo'] List<String> split(String path) { final parsed = _parse(path); // Filter out empty parts that exist due to multiple separators in a row. parsed.parts = parsed.parts.where((part) => part.isNotEmpty).toList(); if (parsed.root != null) parsed.parts.insert(0, parsed.root); return parsed.parts; } /// Canonicalizes [path]. /// /// This is guaranteed to return the same path for two different input paths /// if and only if both input paths point to the same location. Unlike /// [normalize], it returns absolute paths when possible and canonicalizes /// ASCII case on Windows. /// /// Note that this does not resolve symlinks. /// /// If you want a map that uses path keys, it's probably more efficient to /// pass [equals] and [hash] to [new HashMap] than it is to canonicalize every /// key. String canonicalize(String path) { path = absolute(path); if (style != Style.windows && !_needsNormalization(path)) return path; final parsed = _parse(path); parsed.normalize(canonicalize: true); return parsed.toString(); } /// Normalizes [path], simplifying it by handling `..`, and `.`, and /// removing redundant path separators whenever possible. /// /// Note that this is *not* guaranteed to return the same result for two /// equivalent input paths. For that, see [canonicalize]. Or, if you're using /// paths as map keys, pass [equals] and [hash] to [new HashMap]. /// /// context.normalize('path/./to/..//file.text'); // -> 'path/file.txt' String normalize(String path) { if (!_needsNormalization(path)) return path; final parsed = _parse(path); parsed.normalize(); return parsed.toString(); } /// Returns whether [path] needs to be normalized. bool _needsNormalization(String path) { var start = 0; final codeUnits = path.codeUnits; int previousPrevious; int previous; // Skip past the root before we start looking for snippets that need // normalization. We want to normalize "//", but not when it's part of // "http://". final root = style.rootLength(path); if (root != 0) { start = root; previous = chars.slash; // On Windows, the root still needs to be normalized if it contains a // forward slash. if (style == Style.windows) { for (var i = 0; i < root; i++) { if (codeUnits[i] == chars.slash) return true; } } } for (var i = start; i < codeUnits.length; i++) { final codeUnit = codeUnits[i]; if (style.isSeparator(codeUnit)) { // Forward slashes in Windows paths are normalized to backslashes. if (style == Style.windows && codeUnit == chars.slash) return true; // Multiple separators are normalized to single separators. if (previous != null && style.isSeparator(previous)) return true; // Single dots and double dots are normalized to directory traversals. // // This can return false positives for ".../", but that's unlikely // enough that it's probably not going to cause performance issues. if (previous == chars.period && (previousPrevious == null || previousPrevious == chars.period || style.isSeparator(previousPrevious))) { return true; } } previousPrevious = previous; previous = codeUnit; } // Empty paths are normalized to ".". if (previous == null) return true; // Trailing separators are removed. if (style.isSeparator(previous)) return true; // Single dots and double dots are normalized to directory traversals. if (previous == chars.period && (previousPrevious == null || style.isSeparator(previousPrevious) || previousPrevious == chars.period)) { return true; } return false; } /// Attempts to convert [path] to an equivalent relative path relative to /// [current]. /// /// var context = Context(current: '/root/path'); /// context.relative('/root/path/a/b.dart'); // -> 'a/b.dart' /// context.relative('/root/other.dart'); // -> '../other.dart' /// /// If the [from] argument is passed, [path] is made relative to that instead. /// /// context.relative('/root/path/a/b.dart', /// from: '/root/path'); // -> 'a/b.dart' /// context.relative('/root/other.dart', /// from: '/root/path'); // -> '../other.dart' /// /// If [path] and/or [from] are relative paths, they are assumed to be /// relative to [current]. /// /// Since there is no relative path from one drive letter to another on /// Windows, this will return an absolute path in that case. /// /// context.relative(r'D:\other', from: r'C:\other'); // -> 'D:\other' /// /// This will also return an absolute path if an absolute [path] is passed to /// a context with a relative path for [current]. /// /// var context = Context(r'some/relative/path'); /// context.relative(r'/absolute/path'); // -> '/absolute/path' /// /// If [current] is relative, it may be impossible to determine a path from /// [from] to [path]. For example, if [current] and [path] are "." and [from] /// is "/", no path can be determined. In this case, a [PathException] will be /// thrown. String relative(String path, {String from}) { // Avoid expensive computation if the path is already relative. if (from == null && isRelative(path)) return normalize(path); from = from == null ? current : absolute(from); // We can't determine the path from a relative path to an absolute path. if (isRelative(from) && isAbsolute(path)) { return normalize(path); } // If the given path is relative, resolve it relative to the context's // current directory. if (isRelative(path) || isRootRelative(path)) { path = absolute(path); } // If the path is still relative and `from` is absolute, we're unable to // find a path from `from` to `path`. if (isRelative(path) && isAbsolute(from)) { throw PathException('Unable to find a path to "$path" from "$from".'); } final fromParsed = _parse(from)..normalize(); final pathParsed = _parse(path)..normalize(); if (fromParsed.parts.isNotEmpty && fromParsed.parts[0] == '.') { return pathParsed.toString(); } // If the root prefixes don't match (for example, different drive letters // on Windows), then there is no relative path, so just return the absolute // one. In Windows, drive letters are case-insenstive and we allow // calculation of relative paths, even if a path has not been normalized. if (fromParsed.root != pathParsed.root && ((fromParsed.root == null || pathParsed.root == null) || !style.pathsEqual(fromParsed.root, pathParsed.root))) { return pathParsed.toString(); } // Strip off their common prefix. while (fromParsed.parts.isNotEmpty && pathParsed.parts.isNotEmpty && style.pathsEqual(fromParsed.parts[0], pathParsed.parts[0])) { fromParsed.parts.removeAt(0); fromParsed.separators.removeAt(1); pathParsed.parts.removeAt(0); pathParsed.separators.removeAt(1); } // If there are any directories left in the from path, we need to walk up // out of them. If a directory left in the from path is '..', it cannot // be cancelled by adding a '..'. if (fromParsed.parts.isNotEmpty && fromParsed.parts[0] == '..') { throw PathException('Unable to find a path to "$path" from "$from".'); } pathParsed.parts.insertAll(0, List.filled(fromParsed.parts.length, '..')); pathParsed.separators[0] = ''; pathParsed.separators .insertAll(1, List.filled(fromParsed.parts.length, style.separator)); // Corner case: the paths completely collapsed. if (pathParsed.parts.isEmpty) return '.'; // Corner case: path was '.' and some '..' directories were added in front. // Don't add a final '/.' in that case. if (pathParsed.parts.length > 1 && pathParsed.parts.last == '.') { pathParsed.parts.removeLast(); pathParsed.separators ..removeLast() ..removeLast() ..add(''); } // Make it relative. pathParsed.root = ''; pathParsed.removeTrailingSeparators(); return pathParsed.toString(); } /// Returns `true` if [child] is a path beneath `parent`, and `false` /// otherwise. /// /// path.isWithin('/root/path', '/root/path/a'); // -> true /// path.isWithin('/root/path', '/root/other'); // -> false /// path.isWithin('/root/path', '/root/path'); // -> false bool isWithin(String parent, String child) => _isWithinOrEquals(parent, child) == _PathRelation.within; /// Returns `true` if [path1] points to the same location as [path2], and /// `false` otherwise. /// /// The [hash] function returns a hash code that matches these equality /// semantics. bool equals(String path1, String path2) => _isWithinOrEquals(path1, path2) == _PathRelation.equal; /// Compares two paths and returns an enum value indicating their relationship /// to one another. /// /// This never returns [_PathRelation.inconclusive]. _PathRelation _isWithinOrEquals(String parent, String child) { // Make both paths the same level of relative. We're only able to do the // quick comparison if both paths are in the same format, and making a path // absolute is faster than making it relative. final parentIsAbsolute = isAbsolute(parent); final childIsAbsolute = isAbsolute(child); if (parentIsAbsolute && !childIsAbsolute) { child = absolute(child); if (style.isRootRelative(parent)) parent = absolute(parent); } else if (childIsAbsolute && !parentIsAbsolute) { parent = absolute(parent); if (style.isRootRelative(child)) child = absolute(child); } else if (childIsAbsolute && parentIsAbsolute) { final childIsRootRelative = style.isRootRelative(child); final parentIsRootRelative = style.isRootRelative(parent); if (childIsRootRelative && !parentIsRootRelative) { child = absolute(child); } else if (parentIsRootRelative && !childIsRootRelative) { parent = absolute(parent); } } final result = _isWithinOrEqualsFast(parent, child); if (result != _PathRelation.inconclusive) return result; String relative; try { relative = this.relative(child, from: parent); } on PathException catch (_) { // If no relative path from [parent] to [child] is found, [child] // definitely isn't a child of [parent]. return _PathRelation.different; } if (!isRelative(relative)) return _PathRelation.different; if (relative == '.') return _PathRelation.equal; if (relative == '..') return _PathRelation.different; return (relative.length >= 3 && relative.startsWith('..') && style.isSeparator(relative.codeUnitAt(2))) ? _PathRelation.different : _PathRelation.within; } /// An optimized implementation of [_isWithinOrEquals] that doesn't handle a /// few complex cases. _PathRelation _isWithinOrEqualsFast(String parent, String child) { // Normally we just bail when we see "." path components, but we can handle // a single dot easily enough. if (parent == '.') parent = ''; final parentRootLength = style.rootLength(parent); final childRootLength = style.rootLength(child); // If the roots aren't the same length, we know both paths are absolute or // both are root-relative, and thus that the roots are meaningfully // different. // // isWithin("C:/bar", "//foo/bar/baz") //=> false // isWithin("http://example.com/", "http://google.com/bar") //=> false if (parentRootLength != childRootLength) return _PathRelation.different; // Make sure that the roots are textually the same as well. // // isWithin("C:/bar", "D:/bar/baz") //=> false // isWithin("http://example.com/", "http://example.org/bar") //=> false for (var i = 0; i < parentRootLength; i++) { final parentCodeUnit = parent.codeUnitAt(i); final childCodeUnit = child.codeUnitAt(i); if (!style.codeUnitsEqual(parentCodeUnit, childCodeUnit)) { return _PathRelation.different; } } // Start by considering the last code unit as a separator, since // semantically we're starting at a new path component even if we're // comparing relative paths. var lastCodeUnit = chars.slash; /// The index of the last separator in [parent]. int lastParentSeparator; // Iterate through both paths as long as they're semantically identical. var parentIndex = parentRootLength; var childIndex = childRootLength; while (parentIndex < parent.length && childIndex < child.length) { var parentCodeUnit = parent.codeUnitAt(parentIndex); var childCodeUnit = child.codeUnitAt(childIndex); if (style.codeUnitsEqual(parentCodeUnit, childCodeUnit)) { if (style.isSeparator(parentCodeUnit)) { lastParentSeparator = parentIndex; } lastCodeUnit = parentCodeUnit; parentIndex++; childIndex++; continue; } // Ignore multiple separators in a row. if (style.isSeparator(parentCodeUnit) && style.isSeparator(lastCodeUnit)) { lastParentSeparator = parentIndex; parentIndex++; continue; } else if (style.isSeparator(childCodeUnit) && style.isSeparator(lastCodeUnit)) { childIndex++; continue; } // If a dot comes after a separator, it may be a directory traversal // operator. To check that, we need to know if it's followed by either // "/" or "./". Otherwise, it's just a normal non-matching character. // // isWithin("foo/./bar", "foo/bar/baz") //=> true // isWithin("foo/bar/../baz", "foo/bar/.foo") //=> false if (parentCodeUnit == chars.period && style.isSeparator(lastCodeUnit)) { parentIndex++; // We've hit "/." at the end of the parent path, which we can ignore, // since the paths were equivalent up to this point. if (parentIndex == parent.length) break; parentCodeUnit = parent.codeUnitAt(parentIndex); // We've hit "/./", which we can ignore. if (style.isSeparator(parentCodeUnit)) { lastParentSeparator = parentIndex; parentIndex++; continue; } // We've hit "/..", which may be a directory traversal operator that // we can't handle on the fast track. if (parentCodeUnit == chars.period) { parentIndex++; if (parentIndex == parent.length || style.isSeparator(parent.codeUnitAt(parentIndex))) { return _PathRelation.inconclusive; } } // If this isn't a directory traversal, fall through so we hit the // normal handling for mismatched paths. } // This is the same logic as above, but for the child path instead of the // parent. if (childCodeUnit == chars.period && style.isSeparator(lastCodeUnit)) { childIndex++; if (childIndex == child.length) break; childCodeUnit = child.codeUnitAt(childIndex); if (style.isSeparator(childCodeUnit)) { childIndex++; continue; } if (childCodeUnit == chars.period) { childIndex++; if (childIndex == child.length || style.isSeparator(child.codeUnitAt(childIndex))) { return _PathRelation.inconclusive; } } } // If we're here, we've hit two non-matching, non-significant characters. // As long as the remainders of the two paths don't have any unresolved // ".." components, we can be confident that [child] is not within // [parent]. final childDirection = _pathDirection(child, childIndex); if (childDirection != _PathDirection.belowRoot) { return _PathRelation.inconclusive; } final parentDirection = _pathDirection(parent, parentIndex); if (parentDirection != _PathDirection.belowRoot) { return _PathRelation.inconclusive; } return _PathRelation.different; } // If the child is shorter than the parent, it's probably not within the // parent. The only exception is if the parent has some weird ".." stuff // going on, in which case we do the slow check. // // isWithin("foo/bar/baz", "foo/bar") //=> false // isWithin("foo/bar/baz/../..", "foo/bar") //=> true if (childIndex == child.length) { if (parentIndex == parent.length || style.isSeparator(parent.codeUnitAt(parentIndex))) { lastParentSeparator = parentIndex; } else { lastParentSeparator ??= math.max(0, parentRootLength - 1); } final direction = _pathDirection(parent, lastParentSeparator ?? parentRootLength - 1); if (direction == _PathDirection.atRoot) return _PathRelation.equal; return direction == _PathDirection.aboveRoot ? _PathRelation.inconclusive : _PathRelation.different; } // We've reached the end of the parent path, which means it's time to make a // decision. Before we do, though, we'll check the rest of the child to see // what that tells us. final direction = _pathDirection(child, childIndex); // If there are no more components in the child, then it's the same as // the parent. // // isWithin("foo/bar", "foo/bar") //=> false // isWithin("foo/bar", "foo/bar//") //=> false // equals("foo/bar", "foo/bar") //=> true // equals("foo/bar", "foo/bar//") //=> true if (direction == _PathDirection.atRoot) return _PathRelation.equal; // If there are unresolved ".." components in the child, no decision we make // will be valid. We'll abort and do the slow check instead. // // isWithin("foo/bar", "foo/bar/..") //=> false // isWithin("foo/bar", "foo/bar/baz/bang/../../..") //=> false // isWithin("foo/bar", "foo/bar/baz/bang/../../../bar/baz") //=> true if (direction == _PathDirection.aboveRoot) { return _PathRelation.inconclusive; } // The child is within the parent if and only if we're on a separator // boundary. // // isWithin("foo/bar", "foo/bar/baz") //=> true // isWithin("foo/bar/", "foo/bar/baz") //=> true // isWithin("foo/bar", "foo/barbaz") //=> false return (style.isSeparator(child.codeUnitAt(childIndex)) || style.isSeparator(lastCodeUnit)) ? _PathRelation.within : _PathRelation.different; } // Returns a [_PathDirection] describing the path represented by [codeUnits] // starting at [index]. // // This ignores leading separators. // // pathDirection("foo") //=> below root // pathDirection("foo/bar/../baz") //=> below root // pathDirection("//foo/bar/baz") //=> below root // pathDirection("/") //=> at root // pathDirection("foo/..") //=> at root // pathDirection("foo/../baz") //=> reaches root // pathDirection("foo/../..") //=> above root // pathDirection("foo/../../foo/bar/baz") //=> above root _PathDirection _pathDirection(String path, int index) { var depth = 0; var reachedRoot = false; var i = index; while (i < path.length) { // Ignore initial separators or doubled separators. while (i < path.length && style.isSeparator(path.codeUnitAt(i))) { i++; } // If we're at the end, stop. if (i == path.length) break; // Move through the path component to the next separator. final start = i; while (i < path.length && !style.isSeparator(path.codeUnitAt(i))) { i++; } // See if the path component is ".", "..", or a name. if (i - start == 1 && path.codeUnitAt(start) == chars.period) { // Don't change the depth. } else if (i - start == 2 && path.codeUnitAt(start) == chars.period && path.codeUnitAt(start + 1) == chars.period) { // ".." backs out a directory. depth--; // If we work back beyond the root, stop. if (depth < 0) break; // Record that we reached the root so we don't return // [_PathDirection.belowRoot]. if (depth == 0) reachedRoot = true; } else { // Step inside a directory. depth++; } // If we're at the end, stop. if (i == path.length) break; // Move past the separator. i++; } if (depth < 0) return _PathDirection.aboveRoot; if (depth == 0) return _PathDirection.atRoot; if (reachedRoot) return _PathDirection.reachesRoot; return _PathDirection.belowRoot; } /// Returns a hash code for [path] that matches the semantics of [equals]. /// /// Note that the same path may have different hash codes in different /// [Context]s. int hash(String path) { // Make [path] absolute to ensure that equivalent relative and absolute // paths have the same hash code. path = absolute(path); final result = _hashFast(path); if (result != null) return result; final parsed = _parse(path); parsed.normalize(); return _hashFast(parsed.toString()); } /// An optimized implementation of [hash] that doesn't handle internal `..` /// components. /// /// This will handle `..` components that appear at the beginning of the path. int _hashFast(String path) { var hash = 4603; var beginning = true; var wasSeparator = true; for (var i = 0; i < path.length; i++) { final codeUnit = style.canonicalizeCodeUnit(path.codeUnitAt(i)); // Take advantage of the fact that collisions are allowed to ignore // separators entirely. This lets us avoid worrying about cases like // multiple trailing slashes. if (style.isSeparator(codeUnit)) { wasSeparator = true; continue; } if (codeUnit == chars.period && wasSeparator) { // If a dot comes after a separator, it may be a directory traversal // operator. To check that, we need to know if it's followed by either // "/" or "./". Otherwise, it's just a normal character. // // hash("foo/./bar") == hash("foo/bar") // We've hit "/." at the end of the path, which we can ignore. if (i + 1 == path.length) break; final next = path.codeUnitAt(i + 1); // We can just ignore "/./", since they don't affect the semantics of // the path. if (style.isSeparator(next)) continue; // If the path ends with "/.." or contains "/../", we need to // canonicalize it before we can hash it. We make an exception for ".."s // at the beginning of the path, since those may appear even in a // canonicalized path. if (!beginning && next == chars.period && (i + 2 == path.length || style.isSeparator(path.codeUnitAt(i + 2)))) { return null; } } // Make sure [hash] stays under 32 bits even after multiplication. hash &= 0x3FFFFFF; hash *= 33; hash ^= codeUnit; wasSeparator = false; beginning = false; } return hash; } /// Removes a trailing extension from the last part of [path]. /// /// context.withoutExtension('path/to/foo.dart'); // -> 'path/to/foo' String withoutExtension(String path) { final parsed = _parse(path); for (var i = parsed.parts.length - 1; i >= 0; i--) { if (parsed.parts[i].isNotEmpty) { parsed.parts[i] = parsed.basenameWithoutExtension; break; } } return parsed.toString(); } /// Returns [path] with the trailing extension set to [extension]. /// /// If [path] doesn't have a trailing extension, this just adds [extension] to /// the end. /// /// context.setExtension('path/to/foo.dart', '.js') /// // -> 'path/to/foo.js' /// context.setExtension('path/to/foo.dart.js', '.map') /// // -> 'path/to/foo.dart.map' /// context.setExtension('path/to/foo', '.js') /// // -> 'path/to/foo.js' String setExtension(String path, String extension) => withoutExtension(path) + extension; /// Returns the path represented by [uri], which may be a [String] or a [Uri]. /// /// For POSIX and Windows styles, [uri] must be a `file:` URI. For the URL /// style, this will just convert [uri] to a string. /// /// // POSIX /// context.fromUri('file:///path/to/foo') /// // -> '/path/to/foo' /// /// // Windows /// context.fromUri('file:///C:/path/to/foo') /// // -> r'C:\path\to\foo' /// /// // URL /// context.fromUri('https://dart.dev/path/to/foo') /// // -> 'https://dart.dev/path/to/foo' /// /// If [uri] is relative, a relative path will be returned. /// /// path.fromUri('path/to/foo'); // -> 'path/to/foo' String fromUri(uri) => style.pathFromUri(_parseUri(uri)); /// Returns the URI that represents [path]. /// /// For POSIX and Windows styles, this will return a `file:` URI. For the URL /// style, this will just convert [path] to a [Uri]. /// /// // POSIX /// context.toUri('/path/to/foo') /// // -> Uri.parse('file:///path/to/foo') /// /// // Windows /// context.toUri(r'C:\path\to\foo') /// // -> Uri.parse('file:///C:/path/to/foo') /// /// // URL /// context.toUri('https://dart.dev/path/to/foo') /// // -> Uri.parse('https://dart.dev/path/to/foo') Uri toUri(String path) { if (isRelative(path)) { return style.relativePathToUri(path); } else { return style.absolutePathToUri(join(current, path)); } } /// Returns a terse, human-readable representation of [uri]. /// /// [uri] can be a [String] or a [Uri]. If it can be made relative to the /// current working directory, that's done. Otherwise, it's returned as-is. /// This gracefully handles non-`file:` URIs for [Style.posix] and /// [Style.windows]. /// /// The returned value is meant for human consumption, and may be either URI- /// or path-formatted. /// /// // POSIX /// var context = Context(current: '/root/path'); /// context.prettyUri('file:///root/path/a/b.dart'); // -> 'a/b.dart' /// context.prettyUri('https://dart.dev/'); // -> 'https://dart.dev' /// /// // Windows /// var context = Context(current: r'C:\root\path'); /// context.prettyUri('file:///C:/root/path/a/b.dart'); // -> r'a\b.dart' /// context.prettyUri('https://dart.dev/'); // -> 'https://dart.dev' /// /// // URL /// var context = Context(current: 'https://dart.dev/root/path'); /// context.prettyUri('https://dart.dev/root/path/a/b.dart'); /// // -> r'a/b.dart' /// context.prettyUri('file:///root/path'); // -> 'file:///root/path' String prettyUri(uri) { final typedUri = _parseUri(uri); if (typedUri.scheme == 'file' && style == Style.url) { return typedUri.toString(); } else if (typedUri.scheme != 'file' && typedUri.scheme != '' && style != Style.url) { return typedUri.toString(); } final path = normalize(fromUri(typedUri)); final rel = relative(path); // Only return a relative path if it's actually shorter than the absolute // path. This avoids ugly things like long "../" chains to get to the root // and then go back down. return split(rel).length > split(path).length ? path : rel; } ParsedPath _parse(String path) => ParsedPath.parse(path, style); } /// Parses argument if it's a [String] or returns it intact if it's a [Uri]. /// /// Throws an [ArgumentError] otherwise. Uri _parseUri(uri) { if (uri is String) return Uri.parse(uri); if (uri is Uri) return uri; throw ArgumentError.value(uri, 'uri', 'Value must be a String or a Uri'); } /// Validates that there are no non-null arguments following a null one and /// throws an appropriate [ArgumentError] on failure. void _validateArgList(String method, List<String> args) { for (var i = 1; i < args.length; i++) { // Ignore nulls hanging off the end. if (args[i] == null || args[i - 1] != null) continue; int numArgs; for (numArgs = args.length; numArgs >= 1; numArgs--) { if (args[numArgs - 1] != null) break; } // Show the arguments. final message = StringBuffer(); message.write('$method('); message.write(args .take(numArgs) .map((arg) => arg == null ? 'null' : '"$arg"') .join(', ')); message.write('): part ${i - 1} was null, but part $i was not.'); throw ArgumentError(message.toString()); } } /// An enum of possible return values for [Context._pathDirection]. class _PathDirection { /// The path contains enough ".." components that at some point it reaches /// above its original root. /// /// Note that this applies even if the path ends beneath its original root. It /// takes precendence over any other return values that may apple. static const aboveRoot = _PathDirection('above root'); /// The path contains enough ".." components that it ends at its original /// root. static const atRoot = _PathDirection('at root'); /// The path contains enough ".." components that at some point it reaches its /// original root, but it ends beneath that root. static const reachesRoot = _PathDirection('reaches root'); /// The path never reaches to or above its original root. static const belowRoot = _PathDirection('below root'); final String name; const _PathDirection(this.name); @override String toString() => name; } /// An enum of possible return values for [Context._isWithinOrEquals]. class _PathRelation { /// The first path is a proper parent of the second. /// /// For example, `foo` is a proper parent of `foo/bar`, but not of `foo`. static const within = _PathRelation('within'); /// The two paths are equivalent. /// /// For example, `foo//bar` is equivalent to `foo/bar`. static const equal = _PathRelation('equal'); /// The first path is neither a parent of nor equal to the second. static const different = _PathRelation('different'); /// We couldn't quickly determine any information about the paths' /// relationship to each other. /// /// Only returned by [Context._isWithinOrEqualsFast]. static const inconclusive = _PathRelation('inconclusive'); final String name; const _PathRelation(this.name); @override String toString() => name; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path/src/style/windows.dart
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import '../characters.dart' as chars; import '../internal_style.dart'; import '../parsed_path.dart'; import '../utils.dart'; // `0b100000` can be bitwise-ORed with uppercase ASCII letters to get their // lowercase equivalents. const _asciiCaseBit = 0x20; /// The style for Windows paths. class WindowsStyle extends InternalStyle { WindowsStyle(); @override final name = 'windows'; @override final separator = '\\'; final separators = const ['/', '\\']; // Deprecated properties. @override final separatorPattern = RegExp(r'[/\\]'); @override final needsSeparatorPattern = RegExp(r'[^/\\]$'); @override final rootPattern = RegExp(r'^(\\\\[^\\]+\\[^\\/]+|[a-zA-Z]:[/\\])'); @override final relativeRootPattern = RegExp(r'^[/\\](?![/\\])'); @override bool containsSeparator(String path) => path.contains('/'); @override bool isSeparator(int codeUnit) => codeUnit == chars.slash || codeUnit == chars.backslash; @override bool needsSeparator(String path) { if (path.isEmpty) return false; return !isSeparator(path.codeUnitAt(path.length - 1)); } @override int rootLength(String path, {bool withDrive = false}) { if (path.isEmpty) return 0; if (path.codeUnitAt(0) == chars.slash) return 1; if (path.codeUnitAt(0) == chars.backslash) { if (path.length < 2 || path.codeUnitAt(1) != chars.backslash) return 1; // The path is a network share. Search for up to two '\'s, as they are // the server and share - and part of the root part. var index = path.indexOf('\\', 2); if (index > 0) { index = path.indexOf('\\', index + 1); if (index > 0) return index; } return path.length; } // If the path is of the form 'C:/' or 'C:\', with C being any letter, it's // a root part. if (path.length < 3) return 0; // Check for the letter. if (!isAlphabetic(path.codeUnitAt(0))) return 0; // Check for the ':'. if (path.codeUnitAt(1) != chars.colon) return 0; // Check for either '/' or '\'. if (!isSeparator(path.codeUnitAt(2))) return 0; return 3; } @override bool isRootRelative(String path) => rootLength(path) == 1; @override String getRelativeRoot(String path) { final length = rootLength(path); if (length == 1) return path[0]; return null; } @override String pathFromUri(Uri uri) { if (uri.scheme != '' && uri.scheme != 'file') { throw ArgumentError("Uri $uri must have scheme 'file:'."); } var path = uri.path; if (uri.host == '') { // Drive-letter paths look like "file:///C:/path/to/file". The // replaceFirst removes the extra initial slash. Otherwise, leave the // slash to match IE's interpretation of "/foo" as a root-relative path. if (path.length >= 3 && path.startsWith('/') && isDriveLetter(path, 1)) { path = path.replaceFirst('/', ''); } } else { // Network paths look like "file://hostname/path/to/file". path = '\\\\${uri.host}$path'; } return Uri.decodeComponent(path.replaceAll('/', '\\')); } @override Uri absolutePathToUri(String path) { final parsed = ParsedPath.parse(path, this); if (parsed.root.startsWith(r'\\')) { // Network paths become "file://server/share/path/to/file". // The root is of the form "\\server\share". We want "server" to be the // URI host, and "share" to be the first element of the path. final rootParts = parsed.root.split('\\').where((part) => part != ''); parsed.parts.insert(0, rootParts.last); if (parsed.hasTrailingSeparator) { // If the path has a trailing slash, add a single empty component so the // URI has a trailing slash as well. parsed.parts.add(''); } return Uri( scheme: 'file', host: rootParts.first, pathSegments: parsed.parts); } else { // Drive-letter paths become "file:///C:/path/to/file". // If the path is a bare root (e.g. "C:\"), [parsed.parts] will currently // be empty. We add an empty component so the URL constructor produces // "file:///C:/", with a trailing slash. We also add an empty component if // the URL otherwise has a trailing slash. if (parsed.parts.isEmpty || parsed.hasTrailingSeparator) { parsed.parts.add(''); } // Get rid of the trailing "\" in "C:\" because the URI constructor will // add a separator on its own. parsed.parts .insert(0, parsed.root.replaceAll('/', '').replaceAll('\\', '')); return Uri(scheme: 'file', pathSegments: parsed.parts); } } @override bool codeUnitsEqual(int codeUnit1, int codeUnit2) { if (codeUnit1 == codeUnit2) return true; /// Forward slashes and backslashes are equivalent on Windows. if (codeUnit1 == chars.slash) return codeUnit2 == chars.backslash; if (codeUnit1 == chars.backslash) return codeUnit2 == chars.slash; // If this check fails, the code units are definitely different. If it // succeeds *and* either codeUnit is an ASCII letter, they're equivalent. if (codeUnit1 ^ codeUnit2 != _asciiCaseBit) return false; // Now we just need to verify that one of the code units is an ASCII letter. final upperCase1 = codeUnit1 | _asciiCaseBit; return upperCase1 >= chars.lowerA && upperCase1 <= chars.lowerZ; } @override bool pathsEqual(String path1, String path2) { if (identical(path1, path2)) return true; if (path1.length != path2.length) return false; for (var i = 0; i < path1.length; i++) { if (!codeUnitsEqual(path1.codeUnitAt(i), path2.codeUnitAt(i))) { return false; } } return true; } @override int canonicalizeCodeUnit(int codeUnit) { if (codeUnit == chars.slash) return chars.backslash; if (codeUnit < chars.upperA) return codeUnit; if (codeUnit > chars.upperZ) return codeUnit; return codeUnit | _asciiCaseBit; } @override String canonicalizePart(String part) => part.toLowerCase(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path/src/style/posix.dart
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import '../characters.dart' as chars; import '../internal_style.dart'; import '../parsed_path.dart'; /// The style for POSIX paths. class PosixStyle extends InternalStyle { PosixStyle(); @override final name = 'posix'; @override final separator = '/'; final separators = const ['/']; // Deprecated properties. @override final separatorPattern = RegExp(r'/'); @override final needsSeparatorPattern = RegExp(r'[^/]$'); @override final rootPattern = RegExp(r'^/'); @override final relativeRootPattern = null; @override bool containsSeparator(String path) => path.contains('/'); @override bool isSeparator(int codeUnit) => codeUnit == chars.slash; @override bool needsSeparator(String path) => path.isNotEmpty && !isSeparator(path.codeUnitAt(path.length - 1)); @override int rootLength(String path, {bool withDrive = false}) { if (path.isNotEmpty && isSeparator(path.codeUnitAt(0))) return 1; return 0; } @override bool isRootRelative(String path) => false; @override String getRelativeRoot(String path) => null; @override String pathFromUri(Uri uri) { if (uri.scheme == '' || uri.scheme == 'file') { return Uri.decodeComponent(uri.path); } throw ArgumentError("Uri $uri must have scheme 'file:'."); } @override Uri absolutePathToUri(String path) { final parsed = ParsedPath.parse(path, this); if (parsed.parts.isEmpty) { // If the path is a bare root (e.g. "/"), [components] will // currently be empty. We add two empty components so the URL constructor // produces "file:///", with a trailing slash. parsed.parts.addAll(['', '']); } else if (parsed.hasTrailingSeparator) { // If the path has a trailing slash, add a single empty component so the // URI has a trailing slash as well. parsed.parts.add(''); } return Uri(scheme: 'file', pathSegments: parsed.parts); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/path/src/style/url.dart
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import '../characters.dart' as chars; import '../internal_style.dart'; import '../utils.dart'; /// The style for URL paths. class UrlStyle extends InternalStyle { UrlStyle(); @override final name = 'url'; @override final separator = '/'; final separators = const ['/']; // Deprecated properties. @override final separatorPattern = RegExp(r'/'); @override final needsSeparatorPattern = RegExp(r'(^[a-zA-Z][-+.a-zA-Z\d]*://|[^/])$'); @override final rootPattern = RegExp(r'[a-zA-Z][-+.a-zA-Z\d]*://[^/]*'); @override final relativeRootPattern = RegExp(r'^/'); @override bool containsSeparator(String path) => path.contains('/'); @override bool isSeparator(int codeUnit) => codeUnit == chars.slash; @override bool needsSeparator(String path) { if (path.isEmpty) return false; // A URL that doesn't end in "/" always needs a separator. if (!isSeparator(path.codeUnitAt(path.length - 1))) return true; // A URI that's just "scheme://" needs an extra separator, despite ending // with "/". return path.endsWith('://') && rootLength(path) == path.length; } @override int rootLength(String path, {bool withDrive = false}) { if (path.isEmpty) return 0; if (isSeparator(path.codeUnitAt(0))) return 1; for (var i = 0; i < path.length; i++) { final codeUnit = path.codeUnitAt(i); if (isSeparator(codeUnit)) return 0; if (codeUnit == chars.colon) { if (i == 0) return 0; // The root part is up until the next '/', or the full path. Skip ':' // (and '//' if it exists) and search for '/' after that. if (path.startsWith('//', i + 1)) i += 3; final index = path.indexOf('/', i); if (index <= 0) return path.length; // file: URLs sometimes consider Windows drive letters part of the root. // See https://url.spec.whatwg.org/#file-slash-state. if (!withDrive || path.length < index + 3) return index; if (!path.startsWith('file://')) return index; if (!isDriveLetter(path, index + 1)) return index; return path.length == index + 3 ? index + 3 : index + 4; } } return 0; } @override bool isRootRelative(String path) => path.isNotEmpty && isSeparator(path.codeUnitAt(0)); @override String getRelativeRoot(String path) => isRootRelative(path) ? '/' : null; @override String pathFromUri(Uri uri) => uri.toString(); @override Uri relativePathToUri(String path) => Uri.parse(path); @override Uri absolutePathToUri(String path) => Uri.parse(path); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/uuid/uuid_util.dart
library uuid_util; import 'dart:math'; class UuidUtil { /// Math.Random()-based RNG. All platforms, fast, not cryptographically strong. Optional Seed passable. static List<int> mathRNG({int seed = -1}) { var b = List<int>(16); var rand = (seed == -1) ? Random() : Random(seed); for (var i = 0; i < 16; i++) { b[i] = rand.nextInt(256); } (seed == -1) ? b.shuffle() : b.shuffle(Random(seed)); return b; } /// Crypto-Strong RNG. All platforms, unknown speed, cryptographically strong (theoretically) static List<int> cryptoRNG() { var b = List<int>(16); var rand = Random.secure(); for (var i = 0; i < 16; i++) { b[i] = rand.nextInt(256); } return b; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/uuid/uuid.dart
library uuid; import 'uuid_util.dart'; import 'package:crypto/crypto.dart' as crypto; import 'package:convert/convert.dart' as convert; /// uuid for Dart /// Author: Yulian Kuncheff /// Released under MIT License. class Uuid { // RFC4122 provided namespaces for v3 and v5 namespace based UUIDs static const NAMESPACE_DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; static const NAMESPACE_URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; static const NAMESPACE_OID = '6ba7b812-9dad-11d1-80b4-00c04fd430c8'; static const NAMESPACE_X500 = '6ba7b814-9dad-11d1-80b4-00c04fd430c8'; static const NAMESPACE_NIL = '00000000-0000-0000-0000-000000000000'; var _seedBytes, _nodeId, _clockSeq, _lastMSecs = 0, _lastNSecs = 0; Function _globalRNG; List<String> _byteToHex; Map<String, int> _hexToByte; Uuid({Map<String, dynamic> options}) { options = (options != null) ? options : {}; _byteToHex = List<String>(256); _hexToByte = <String, int>{}; // Easy number <-> hex conversion for (var i = 0; i < 256; i++) { var hex = <int>[]; hex.add(i); _byteToHex[i] = convert.hex.encode(hex); _hexToByte[_byteToHex[i]] = i; } // Sets initial seedBytes, node, and clock seq based on mathRNG. var v1PositionalArgs = (options['v1rngPositionalArgs'] != null) ? options['v1rngPositionalArgs'] : []; var v1NamedArgs = (options['v1rngNamedArgs'] != null) ? options['v1rngNamedArgs'] as Map<Symbol, dynamic> : const <Symbol, dynamic>{}; _seedBytes = (options['v1rng'] != null) ? Function.apply(options['v1rng'], v1PositionalArgs, v1NamedArgs) : UuidUtil.mathRNG(); // Set the globalRNG function to mathRNG with the option to set an alternative globally var gPositionalArgs = (options['grngPositionalArgs'] != null) ? options['grngPositionalArgs'] : []; var gNamedArgs = (options['grngNamedArgs'] != null) ? options['grngNamedArgs'] as Map<Symbol, dynamic> : const <Symbol, dynamic>{}; _globalRNG = () { return (options['grng'] != null) ? Function.apply(options['grng'], gPositionalArgs, gNamedArgs) : UuidUtil.mathRNG(); }; // Per 4.5, create a 48-bit node id (47 random bits + multicast bit = 1) _nodeId = [ _seedBytes[0] | 0x01, _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5] ]; // Per 4.2.2, randomize (14 bit) clockseq _clockSeq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3ffff; } ///Parses the provided [uuid] into a list of byte values. /// Can optionally be provided a [buffer] to write into and /// a positional [offset] for where to start inputting into the buffer. List<int> parse(String uuid, {List<int> buffer, int offset = 0}) { var i = offset, ii = 0; // Create a 16 item buffer if one hasn't been provided. buffer = (buffer != null) ? buffer : List<int>(16); // Convert to lowercase and replace all hex with bytes then // string.replaceAll() does a lot of work that I don't need, and a manual // regex gives me more control. final regex = RegExp('[0-9a-f]{2}'); for (Match match in regex.allMatches(uuid.toLowerCase())) { if (ii < 16) { var hex = uuid.toLowerCase().substring(match.start, match.end); buffer[i + ii++] = _hexToByte[hex]; } } // Zero out any left over bytes if the string was too short. while (ii < 16) { buffer[i + ii++] = 0; } return buffer; } /// Unparses a [buffer] of bytes and outputs a proper UUID string. /// An optional [offset] is allowed if you want to start at a different point /// in the buffer. String unparse(List<int> buffer, {int offset = 0}) { var i = offset; return '${_byteToHex[buffer[i++]]}${_byteToHex[buffer[i++]]}' '${_byteToHex[buffer[i++]]}${_byteToHex[buffer[i++]]}-' '${_byteToHex[buffer[i++]]}${_byteToHex[buffer[i++]]}-' '${_byteToHex[buffer[i++]]}${_byteToHex[buffer[i++]]}-' '${_byteToHex[buffer[i++]]}${_byteToHex[buffer[i++]]}-' '${_byteToHex[buffer[i++]]}${_byteToHex[buffer[i++]]}' '${_byteToHex[buffer[i++]]}${_byteToHex[buffer[i++]]}' '${_byteToHex[buffer[i++]]}${_byteToHex[buffer[i++]]}'; } /// v1() Generates a time-based version 1 UUID /// /// By default it will generate a string based off current time, and will /// return a string. /// /// If an optional [buffer] list is provided, it will put the byte data into /// that buffer and return a buffer. /// /// Optionally an [offset] can be provided with a start position in the buffer. /// /// The first argument is an options map that takes various configuration /// options detailed in the readme. /// /// http://tools.ietf.org/html/rfc4122.html#section-4.2.2 String v1({Map<String, dynamic> options}) { var i = 0; var buf = List<int>(16); options = (options != null) ? options : {}; var clockSeq = (options['clockSeq'] != null) ? options['clockSeq'] : _clockSeq; // UUID timestamps are 100 nano-second units since the Gregorian epoch, // (1582-10-15 00:00). Time is handled internally as 'msecs' (integer // milliseconds) and 'nsecs' (100-nanoseconds offset from msecs) since unix // epoch, 1970-01-01 00:00. var mSecs = (options['mSecs'] != null) ? options['mSecs'] : (DateTime.now()).millisecondsSinceEpoch; // Per 4.2.1.2, use count of uuid's generated during the current clock // cycle to simulate higher resolution clock var nSecs = (options['nSecs'] != null) ? options['nSecs'] : _lastNSecs + 1; // Time since last uuid creation (in msecs) var dt = (mSecs - _lastMSecs) + (nSecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression if (dt < 0 && options['clockSeq'] == null) { clockSeq = clockSeq + 1 & 0x3fff; } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new // time interval if ((dt < 0 || mSecs > _lastMSecs) && options['nSecs'] == null) { nSecs = 0; } // Per 4.2.1.2 Throw error if too many uuids are requested if (nSecs >= 10000) { throw Exception('uuid.v1(): Can\'t create more than 10M uuids/sec'); } _lastMSecs = mSecs; _lastNSecs = nSecs; _clockSeq = clockSeq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch mSecs += 12219292800000; // time Low var tl = ((mSecs & 0xfffffff) * 10000 + nSecs) % 0x100000000; buf[i++] = tl >> 24 & 0xff; buf[i++] = tl >> 16 & 0xff; buf[i++] = tl >> 8 & 0xff; buf[i++] = tl & 0xff; // time mid var tmh = (mSecs / 0x100000000 * 10000).floor() & 0xfffffff; buf[i++] = tmh >> 8 & 0xff; buf[i++] = tmh & 0xff; // time high and version buf[i++] = tmh >> 24 & 0xf | 0x10; // include version buf[i++] = tmh >> 16 & 0xff; // clockSeq high and reserved (Per 4.2.2 - include variant) buf[i++] = (clockSeq & 0x3F00) >> 8 | 0x80; // clockSeq low buf[i++] = clockSeq & 0xff; // node var node = (options['node'] != null) ? options['node'] : _nodeId; for (var n = 0; n < 6; n++) { buf[i + n] = node[n]; } return unparse(buf); } /// v1buffer() Generates a time-based version 1 UUID /// /// By default it will generate a string based off current time, and will /// place the result into the provided [buffer]. The [buffer] will also be returned.. /// /// Optionally an [offset] can be provided with a start position in the buffer. /// /// The first argument is an options map that takes various configuration /// options detailed in the readme. /// /// http://tools.ietf.org/html/rfc4122.html#section-4.2.2 List<int> v1buffer( List<int> buffer, { Map<String, dynamic> options, int offset = 0, }) { var _buf = parse(v1(options: options)); if (buffer != null) { buffer.setRange(offset, offset + 16, _buf); } return buffer; } /// v4() Generates a RNG version 4 UUID /// /// By default it will generate a string based mathRNG, and will return /// a string. If you wish to use crypto-strong RNG, pass in UuidUtil.cryptoRNG /// /// The first argument is an options map that takes various configuration /// options detailed in the readme. /// /// http://tools.ietf.org/html/rfc4122.html#section-4.4 String v4({Map<String, dynamic> options}) { options = (options != null) ? options : <String, dynamic>{}; // Use the built-in RNG or a custom provided RNG var positionalArgs = (options['positionalArgs'] != null) ? options['positionalArgs'] : []; var namedArgs = (options['namedArgs'] != null) ? options['namedArgs'] as Map<Symbol, dynamic> : const <Symbol, dynamic>{}; var rng = (options['rng'] != null) ? Function.apply(options['rng'], positionalArgs, namedArgs) : _globalRNG(); // Use provided values over RNG var rnds = (options['random'] != null) ? options['random'] : rng; // per 4.4, set bits for version and clockSeq high and reserved rnds[6] = (rnds[6] & 0x0f) | 0x40; rnds[8] = (rnds[8] & 0x3f) | 0x80; return unparse(rnds); } /// v4buffer() Generates a RNG version 4 UUID /// /// By default it will generate a string based off mathRNG, and will /// place the result into the provided [buffer]. The [buffer] will also be returned. /// If you wish to have crypto-strong RNG, pass in UuidUtil.cryptoRNG. /// /// Optionally an [offset] can be provided with a start position in the buffer. /// /// The first argument is an options map that takes various configuration /// options detailed in the readme. /// /// http://tools.ietf.org/html/rfc4122.html#section-4.4 List<int> v4buffer( List<int> buffer, { Map<String, dynamic> options, int offset = 0, }) { var _buf = parse(v4(options: options)); if (buffer != null) { buffer.setRange(offset, offset + 16, _buf); } return buffer; } /// v5() Generates a namspace & name-based version 5 UUID /// /// By default it will generate a string based on a provided uuid namespace and /// name, and will return a string. /// /// The first argument is an options map that takes various configuration /// options detailed in the readme. /// /// http://tools.ietf.org/html/rfc4122.html#section-4.4 String v5(String namespace, String name, {Map<String, dynamic> options}) { options = (options != null) ? options : {}; // Check if user wants a random namespace generated by v4() or a NIL namespace. var useRandom = (options['randomNamespace'] != null) ? options['randomNamespace'] : true; // If useRandom is true, generate UUIDv4, else use NIL var blankNS = useRandom ? v4() : NAMESPACE_NIL; // Use provided namespace, or use whatever is decided by options. namespace = (namespace != null) ? namespace : blankNS; // Use provided name, name = (name != null) ? name : ''; // Convert namespace UUID to Byte List var bytes = parse(namespace); // Convert name to a list of bytes var nameBytes = <int>[]; for (var singleChar in name.codeUnits) { nameBytes.add(singleChar); } // Generate SHA1 using namespace concatenated with name List hashBytes = crypto.sha1.convert(List.from(bytes)..addAll(nameBytes)).bytes; // per 4.4, set bits for version and clockSeq high and reserved hashBytes[6] = (hashBytes[6] & 0x0f) | 0x50; hashBytes[8] = (hashBytes[8] & 0x3f) | 0x80; return unparse(hashBytes); } /// v5buffer() Generates a RNG version 4 UUID /// /// By default it will generate a string based off current time, and will /// place the result into the provided [buffer]. The [buffer] will also be returned.. /// /// Optionally an [offset] can be provided with a start position in the buffer. /// /// The first argument is an options map that takes various configuration /// options detailed in the readme. /// /// http://tools.ietf.org/html/rfc4122.html#section-4.4 List<int> v5buffer( String namespace, String name, List<int> buffer, { Map<String, dynamic> options, int offset = 0, }) { var _buf = parse(v5(namespace, name, options: options)); if (buffer != null) { buffer.setRange(offset, offset + 16, _buf); } return buffer; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html/dom.dart
/// A simple tree API that results from parsing html. Intended to be compatible /// with dart:html, but it is missing many types and APIs. library dom; // TODO(jmesserly): lots to do here. Originally I wanted to generate this using // our Blink IDL generator, but another idea is to directly use the excellent // http://dom.spec.whatwg.org/ and http://html.spec.whatwg.org/ and just // implement that. import 'dart:collection'; import 'package:source_span/source_span.dart'; import 'dom_parsing.dart'; import 'parser.dart'; import 'src/constants.dart'; import 'src/css_class_set.dart'; import 'src/list_proxy.dart'; import 'src/query_selector.dart' as query; import 'src/token.dart'; import 'src/tokenizer.dart'; export 'src/css_class_set.dart' show CssClassSet; // TODO(jmesserly): this needs to be replaced by an AttributeMap for attributes // that exposes namespace info. class AttributeName implements Comparable { /// The namespace prefix, e.g. `xlink`. final String prefix; /// The attribute name, e.g. `title`. final String name; /// The namespace url, e.g. `http://www.w3.org/1999/xlink` final String namespace; const AttributeName(this.prefix, this.name, this.namespace); @override String toString() { // Implement: // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-end.html#serializing-html-fragments // If we get here we know we are xml, xmlns, or xlink, because of // [HtmlParser.adjustForeignAttriubtes] is the only place we create // an AttributeName. return prefix != null ? '$prefix:$name' : name; } @override int get hashCode { var h = prefix.hashCode; h = 37 * (h & 0x1FFFFF) + name.hashCode; h = 37 * (h & 0x1FFFFF) + namespace.hashCode; return h & 0x3FFFFFFF; } @override int compareTo(other) { // Not sure about this sort order if (other is! AttributeName) return 1; var cmp = (prefix ?? '').compareTo((other.prefix ?? '')); if (cmp != 0) return cmp; cmp = name.compareTo(other.name); if (cmp != 0) return cmp; return namespace.compareTo(other.namespace); } @override bool operator ==(x) { if (x is! AttributeName) return false; return prefix == x.prefix && name == x.name && namespace == x.namespace; } } // http://dom.spec.whatwg.org/#parentnode abstract class _ParentNode implements Node { // TODO(jmesserly): this is only a partial implementation /// Seaches for the first descendant node matching the given selectors, using /// a preorder traversal. /// /// NOTE: Not all selectors from /// [selectors level 4](http://dev.w3.org/csswg/selectors-4/) /// are implemented. For example, nth-child does not implement An+B syntax /// and *-of-type is not implemented. If a selector is not implemented this /// method will throw [UniplmentedError]. Element querySelector(String selector) => query.querySelector(this, selector); /// Returns all descendant nodes matching the given selectors, using a /// preorder traversal. /// /// NOTE: Not all selectors from /// [selectors level 4](http://dev.w3.org/csswg/selectors-4/) /// are implemented. For example, nth-child does not implement An+B syntax /// and *-of-type is not implemented. If a selector is not implemented this /// method will throw [UniplmentedError]. List<Element> querySelectorAll(String selector) => query.querySelectorAll(this, selector); } // http://dom.spec.whatwg.org/#interface-nonelementparentnode abstract class _NonElementParentNode implements _ParentNode { // TODO(jmesserly): could be faster, should throw on invalid id. Element getElementById(String id) => querySelector('#$id'); } // This doesn't exist as an interface in the spec, but it's useful to merge // common methods from these: // http://dom.spec.whatwg.org/#interface-document // http://dom.spec.whatwg.org/#element abstract class _ElementAndDocument implements _ParentNode { // TODO(jmesserly): could be faster, should throw on invalid tag/class names. List<Element> getElementsByTagName(String localName) => querySelectorAll(localName); List<Element> getElementsByClassName(String classNames) => querySelectorAll(classNames.splitMapJoin(' ', onNonMatch: (m) => m.isNotEmpty ? '.$m' : m, onMatch: (m) => '')); } /// Really basic implementation of a DOM-core like Node. abstract class Node { static const int ATTRIBUTE_NODE = 2; static const int CDATA_SECTION_NODE = 4; static const int COMMENT_NODE = 8; static const int DOCUMENT_FRAGMENT_NODE = 11; static const int DOCUMENT_NODE = 9; static const int DOCUMENT_TYPE_NODE = 10; static const int ELEMENT_NODE = 1; static const int ENTITY_NODE = 6; static const int ENTITY_REFERENCE_NODE = 5; static const int NOTATION_NODE = 12; static const int PROCESSING_INSTRUCTION_NODE = 7; static const int TEXT_NODE = 3; /// The parent of the current node (or null for the document node). Node parentNode; /// The parent element of this node. /// /// Returns null if this node either does not have a parent or its parent is /// not an element. Element get parent => parentNode is Element ? parentNode : null; // TODO(jmesserly): should move to Element. /// A map holding name, value pairs for attributes of the node. /// /// Note that attribute order needs to be stable for serialization, so we use /// a LinkedHashMap. Each key is a [String] or [AttributeName]. LinkedHashMap<dynamic, String> attributes = LinkedHashMap(); /// A list of child nodes of the current node. This must /// include all elements but not necessarily other node types. final NodeList nodes = NodeList._(); List<Element> _elements; // TODO(jmesserly): consider using an Expando for this, and put it in // dom_parsing. Need to check the performance affect. /// The source span of this node, if it was created by the [HtmlParser]. FileSpan sourceSpan; /// The attribute spans if requested. Otherwise null. LinkedHashMap<dynamic, FileSpan> _attributeSpans; LinkedHashMap<dynamic, FileSpan> _attributeValueSpans; Node._() { nodes._parent = this; } /// If [sourceSpan] is available, this contains the spans of each attribute. /// The span of an attribute is the entire attribute, including the name and /// quotes (if any). For example, the span of "attr" in `<a attr="value">` /// would be the text `attr="value"`. LinkedHashMap<dynamic, FileSpan> get attributeSpans { _ensureAttributeSpans(); return _attributeSpans; } /// If [sourceSpan] is available, this contains the spans of each attribute's /// value. Unlike [attributeSpans], this span will inlcude only the value. /// For example, the value span of "attr" in `<a attr="value">` would be the /// text `value`. LinkedHashMap<dynamic, FileSpan> get attributeValueSpans { _ensureAttributeSpans(); return _attributeValueSpans; } List<Element> get children => _elements ??= FilteredElementList(this); /// Returns a copy of this node. /// /// If [deep] is `true`, then all of this node's children and decendents are /// copied as well. If [deep] is `false`, then only this node is copied. Node clone(bool deep); int get nodeType; // http://domparsing.spec.whatwg.org/#extensions-to-the-element-interface String get _outerHtml { var str = StringBuffer(); _addOuterHtml(str); return str.toString(); } String get _innerHtml { var str = StringBuffer(); _addInnerHtml(str); return str.toString(); } // Implemented per: http://dom.spec.whatwg.org/#dom-node-textcontent String get text => null; set text(String value) {} void append(Node node) => nodes.add(node); Node get firstChild => nodes.isNotEmpty ? nodes[0] : null; void _addOuterHtml(StringBuffer str); void _addInnerHtml(StringBuffer str) { for (var child in nodes) { child._addOuterHtml(str); } } Node remove() { // TODO(jmesserly): is parent == null an error? if (parentNode != null) { parentNode.nodes.remove(this); } return this; } /// Insert [node] as a child of the current node, before [refNode] in the /// list of child nodes. Raises [UnsupportedOperationException] if [refNode] /// is not a child of the current node. If refNode is null, this adds to the /// end of the list. void insertBefore(Node node, Node refNode) { if (refNode == null) { nodes.add(node); } else { nodes.insert(nodes.indexOf(refNode), node); } } /// Replaces this node with another node. Node replaceWith(Node otherNode) { if (parentNode == null) { throw UnsupportedError('Node must have a parent to replace it.'); } parentNode.nodes[parentNode.nodes.indexOf(this)] = otherNode; return this; } // TODO(jmesserly): should this be a property or remove? /// Return true if the node has children or text. bool hasContent() => nodes.isNotEmpty; /// Move all the children of the current node to [newParent]. /// This is needed so that trees that don't store text as nodes move the /// text in the correct way. void reparentChildren(Node newParent) { newParent.nodes.addAll(nodes); nodes.clear(); } bool hasChildNodes() => nodes.isNotEmpty; bool contains(Node node) => nodes.contains(node); /// Initialize [attributeSpans] using [sourceSpan]. void _ensureAttributeSpans() { if (_attributeSpans != null) return; _attributeSpans = LinkedHashMap<dynamic, FileSpan>(); _attributeValueSpans = LinkedHashMap<dynamic, FileSpan>(); if (sourceSpan == null) return; var tokenizer = HtmlTokenizer(sourceSpan.text, generateSpans: true, attributeSpans: true); tokenizer.moveNext(); var token = tokenizer.current as StartTagToken; if (token.attributeSpans == null) return; // no attributes for (var attr in token.attributeSpans) { var offset = sourceSpan.start.offset; _attributeSpans[attr.name] = sourceSpan.file.span(offset + attr.start, offset + attr.end); if (attr.startValue != null) { _attributeValueSpans[attr.name] = sourceSpan.file .span(offset + attr.startValue, offset + attr.endValue); } } } Node _clone(Node shallowClone, bool deep) { if (deep) { for (var child in nodes) { shallowClone.append(child.clone(true)); } } return shallowClone; } } class Document extends Node with _ParentNode, _NonElementParentNode, _ElementAndDocument { Document() : super._(); factory Document.html(String html) => parse(html); @override int get nodeType => Node.DOCUMENT_NODE; // TODO(jmesserly): optmize this if needed Element get documentElement => querySelector('html'); Element get head => documentElement.querySelector('head'); Element get body => documentElement.querySelector('body'); /// Returns a fragment of HTML or XML that represents the element and its /// contents. // TODO(jmesserly): this API is not specified in: // <http://domparsing.spec.whatwg.org/> nor is it in dart:html, instead // only Element has outerHtml. However it is quite useful. Should we move it // to dom_parsing, where we keep other custom APIs? String get outerHtml => _outerHtml; @override String toString() => '#document'; @override void _addOuterHtml(StringBuffer str) => _addInnerHtml(str); @override Document clone(bool deep) => _clone(Document(), deep); Element createElement(String tag) => Element.tag(tag); // TODO(jmesserly): this is only a partial implementation of: // http://dom.spec.whatwg.org/#dom-document-createelementns Element createElementNS(String namespaceUri, String tag) { if (namespaceUri == '') namespaceUri = null; return Element._(tag, namespaceUri); } DocumentFragment createDocumentFragment() => DocumentFragment(); } class DocumentFragment extends Node with _ParentNode, _NonElementParentNode { DocumentFragment() : super._(); factory DocumentFragment.html(String html) => parseFragment(html); @override int get nodeType => Node.DOCUMENT_FRAGMENT_NODE; /// Returns a fragment of HTML or XML that represents the element and its /// contents. // TODO(jmesserly): this API is not specified in: // <http://domparsing.spec.whatwg.org/> nor is it in dart:html, instead // only Element has outerHtml. However it is quite useful. Should we move it // to dom_parsing, where we keep other custom APIs? String get outerHtml => _outerHtml; @override String toString() => '#document-fragment'; @override DocumentFragment clone(bool deep) => _clone(DocumentFragment(), deep); @override void _addOuterHtml(StringBuffer str) => _addInnerHtml(str); @override String get text => _getText(this); @override set text(String value) => _setText(this, value); } class DocumentType extends Node { final String name; final String publicId; final String systemId; DocumentType(this.name, this.publicId, this.systemId) : super._(); @override int get nodeType => Node.DOCUMENT_TYPE_NODE; @override String toString() { if (publicId != null || systemId != null) { // TODO(jmesserly): the html5 serialization spec does not add these. But // it seems useful, and the parser can handle it, so for now keeping it. var pid = publicId ?? ''; var sid = systemId ?? ''; return '<!DOCTYPE $name "$pid" "$sid">'; } else { return '<!DOCTYPE $name>'; } } @override void _addOuterHtml(StringBuffer str) { str.write(toString()); } @override DocumentType clone(bool deep) => DocumentType(name, publicId, systemId); } class Text extends Node { /// The text node's data, stored as either a String or StringBuffer. /// We support storing a StringBuffer here to support fast [appendData]. /// It will flatten back to a String on read. dynamic _data; Text(String data) : _data = data ?? '', super._(); @override int get nodeType => Node.TEXT_NODE; String get data => _data = _data.toString(); set data(String value) { _data = value ?? ''; } @override String toString() => '"$data"'; @override void _addOuterHtml(StringBuffer str) => writeTextNodeAsHtml(str, this); @override Text clone(bool deep) => Text(data); void appendData(String data) { if (_data is! StringBuffer) _data = StringBuffer(_data); StringBuffer sb = _data; sb.write(data); } @override String get text => data; @override set text(String value) { data = value; } } // TODO(jmesserly): Elements should have a pointer back to their document class Element extends Node with _ParentNode, _ElementAndDocument { final String namespaceUri; /// The [local name](http://dom.spec.whatwg.org/#concept-element-local-name) /// of this element. final String localName; // TODO(jmesserly): consider using an Expando for this, and put it in // dom_parsing. Need to check the performance affect. /// The source span of the end tag this element, if it was created by the /// [HtmlParser]. May be `null` if does not have an implicit end tag. FileSpan endSourceSpan; Element._(this.localName, [this.namespaceUri]) : super._(); Element.tag(this.localName) : namespaceUri = Namespaces.html, super._(); static final _startTagRegexp = RegExp('<(\\w+)'); static final _customParentTagMap = const { 'body': 'html', 'head': 'html', 'caption': 'table', 'td': 'tr', 'colgroup': 'table', 'col': 'colgroup', 'tr': 'tbody', 'tbody': 'table', 'tfoot': 'table', 'thead': 'table', 'track': 'audio', }; // TODO(jmesserly): this is from dart:html _ElementFactoryProvider... // TODO(jmesserly): have a look at fixing some things in dart:html, in // particular: is the parent tag map complete? Is it faster without regexp? // TODO(jmesserly): for our version we can do something smarter in the parser. // All we really need is to set the correct parse state. factory Element.html(String html) { // TODO(jacobr): this method can be made more robust and performant. // 1) Cache the dummy parent elements required to use innerHTML rather than // creating them every call. // 2) Verify that the html does not contain leading or trailing text nodes. // 3) Verify that the html does not contain both <head> and <body> tags. // 4) Detatch the created element from its dummy parent. var parentTag = 'div'; String tag; final match = _startTagRegexp.firstMatch(html); if (match != null) { tag = match.group(1).toLowerCase(); if (_customParentTagMap.containsKey(tag)) { parentTag = _customParentTagMap[tag]; } } var fragment = parseFragment(html, container: parentTag); Element element; if (fragment.children.length == 1) { element = fragment.children[0]; } else if (parentTag == 'html' && fragment.children.length == 2) { // You'll always get a head and a body when starting from html. element = fragment.children[tag == 'head' ? 0 : 1]; } else { throw ArgumentError('HTML had ${fragment.children.length} ' 'top level elements but 1 expected'); } element.remove(); return element; } @override int get nodeType => Node.ELEMENT_NODE; // TODO(jmesserly): we can make this faster Element get previousElementSibling { if (parentNode == null) return null; var siblings = parentNode.nodes; for (var i = siblings.indexOf(this) - 1; i >= 0; i--) { var s = siblings[i]; if (s is Element) return s; } return null; } Element get nextElementSibling { if (parentNode == null) return null; var siblings = parentNode.nodes; for (var i = siblings.indexOf(this) + 1; i < siblings.length; i++) { var s = siblings[i]; if (s is Element) return s; } return null; } @override String toString() { var prefix = Namespaces.getPrefix(namespaceUri); return "<${prefix == null ? '' : '$prefix '}$localName>"; } @override String get text => _getText(this); @override set text(String value) => _setText(this, value); /// Returns a fragment of HTML or XML that represents the element and its /// contents. String get outerHtml => _outerHtml; /// Returns a fragment of HTML or XML that represents the element's contents. /// Can be set, to replace the contents of the element with nodes parsed from /// the given string. String get innerHtml => _innerHtml; // TODO(jmesserly): deprecate in favor of: // <https://api.dartlang.org/apidocs/channels/stable/#dart-dom-html.Element@id_setInnerHtml> set innerHtml(String value) { nodes.clear(); // TODO(jmesserly): should be able to get the same effect by adding the // fragment directly. nodes.addAll(parseFragment(value, container: localName).nodes); } @override void _addOuterHtml(StringBuffer str) { // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-end.html#serializing-html-fragments // Element is the most complicated one. str.write('<'); str.write(_getSerializationPrefix(namespaceUri)); str.write(localName); if (attributes.isNotEmpty) { attributes.forEach((key, v) { // Note: AttributeName.toString handles serialization of attribute // namespace, if needed. str.write(' '); str.write(key); str.write('="'); str.write(htmlSerializeEscape(v, attributeMode: true)); str.write('"'); }); } str.write('>'); if (nodes.isNotEmpty) { if (localName == 'pre' || localName == 'textarea' || localName == 'listing') { final first = nodes[0]; if (first is Text && first.data.startsWith('\n')) { // These nodes will remove a leading \n at parse time, so if we still // have one, it means we started with two. Add it back. str.write('\n'); } } _addInnerHtml(str); } // void elements must not have an end tag // http://dev.w3.org/html5/markup/syntax.html#void-elements if (!isVoidElement(localName)) str.write('</$localName>'); } static String _getSerializationPrefix(String uri) { if (uri == null || uri == Namespaces.html || uri == Namespaces.mathml || uri == Namespaces.svg) { return ''; } var prefix = Namespaces.getPrefix(uri); // TODO(jmesserly): the spec doesn't define "qualified name". // I'm not sure if this is correct, but it should parse reasonably. return prefix == null ? '' : '$prefix:'; } @override Element clone(bool deep) { var result = Element._(localName, namespaceUri) ..attributes = LinkedHashMap.from(attributes); return _clone(result, deep); } // http://dom.spec.whatwg.org/#dom-element-id String get id { var result = attributes['id']; return result ?? ''; } set id(String value) { attributes['id'] = '$value'; } // http://dom.spec.whatwg.org/#dom-element-classname String get className { var result = attributes['class']; return result ?? ''; } set className(String value) { attributes['class'] = '$value'; } /// The set of CSS classes applied to this element. /// /// This set makes it easy to add, remove or toggle the classes applied to /// this element. /// /// element.classes.add('selected'); /// element.classes.toggle('isOnline'); /// element.classes.remove('selected'); CssClassSet get classes => ElementCssClassSet(this); } class Comment extends Node { String data; Comment(this.data) : super._(); @override int get nodeType => Node.COMMENT_NODE; @override String toString() => '<!-- $data -->'; @override void _addOuterHtml(StringBuffer str) { str.write('<!--$data-->'); } @override Comment clone(bool deep) => Comment(data); @override String get text => data; @override set text(String value) { data = value; } } // TODO(jmesserly): fix this to extend one of the corelib classes if possible. // (The requirement to remove the node from the old node list makes it tricky.) // TODO(jmesserly): is there any way to share code with the _NodeListImpl? class NodeList extends ListProxy<Node> { // Note: this is conceptually final, but because of circular reference // between Node and NodeList we initialize it after construction. Node _parent; NodeList._(); Node _setParent(Node node) { // Note: we need to remove the node from its previous parent node, if any, // before updating its parent pointer to point at our parent. node.remove(); node.parentNode = _parent; return node; } @override void add(Node value) { if (value is DocumentFragment) { addAll(value.nodes); } else { super.add(_setParent(value)); } } void addLast(Node value) => add(value); @override void addAll(Iterable<Node> collection) { // Note: we need to be careful if collection is another NodeList. // In particular: // 1. we need to copy the items before updating their parent pointers, // _flattenDocFragments does a copy internally. // 2. we should update parent pointers in reverse order. That way they // are removed from the original NodeList (if any) from the end, which // is faster. var list = _flattenDocFragments(collection); for (var node in list.reversed) { _setParent(node); } super.addAll(list); } @override void insert(int index, Node value) { if (value is DocumentFragment) { insertAll(index, value.nodes); } else { super.insert(index, _setParent(value)); } } @override Node removeLast() => super.removeLast()..parentNode = null; @override Node removeAt(int i) => super.removeAt(i)..parentNode = null; @override void clear() { for (var node in this) { node.parentNode = null; } super.clear(); } @override void operator []=(int index, Node value) { if (value is DocumentFragment) { removeAt(index); insertAll(index, value.nodes); } else { this[index].parentNode = null; super[index] = _setParent(value); } } // TODO(jmesserly): These aren't implemented in DOM _NodeListImpl, see // http://code.google.com/p/dart/issues/detail?id=5371 @override void setRange(int start, int rangeLength, Iterable<Node> from, [int startFrom = 0]) { var fromVar = from as List<Node>; if (fromVar is NodeList) { // Note: this is presumed to make a copy fromVar = fromVar.sublist(startFrom, startFrom + rangeLength); } // Note: see comment in [addAll]. We need to be careful about the order of // operations if [from] is also a NodeList. for (var i = rangeLength - 1; i >= 0; i--) { this[start + i] = fromVar[startFrom + i]; } } @override void replaceRange(int start, int end, Iterable<Node> newContents) { removeRange(start, end); insertAll(start, newContents); } @override void removeRange(int start, int rangeLength) { for (var i = start; i < rangeLength; i++) { this[i].parentNode = null; } super.removeRange(start, rangeLength); } @override void removeWhere(bool Function(Node) test) { for (var node in where(test)) { node.parentNode = null; } super.removeWhere(test); } @override void retainWhere(bool Function(Node) test) { for (var node in where((n) => !test(n))) { node.parentNode = null; } super.retainWhere(test); } @override void insertAll(int index, Iterable<Node> collection) { // Note: we need to be careful how we copy nodes. See note in addAll. var list = _flattenDocFragments(collection); for (var node in list.reversed) { _setParent(node); } super.insertAll(index, list); } List<Node> _flattenDocFragments(Iterable<Node> collection) { // Note: this function serves two purposes: // * it flattens document fragments // * it creates a copy of [collections] when `collection is NodeList`. var result = <Node>[]; for (var node in collection) { if (node is DocumentFragment) { result.addAll(node.nodes); } else { result.add(node); } } return result; } } /// An indexable collection of a node's descendants in the document tree, /// filtered so that only elements are in the collection. // TODO(jmesserly): this was copied from dart:html // TODO(jmesserly): "implements List<Element>" is a workaround for analyzer bug. class FilteredElementList extends IterableBase<Element> with ListMixin<Element> implements List<Element> { final List<Node> _childNodes; /// Creates a collection of the elements that descend from a node. /// /// Example usage: /// /// var filteredElements = new FilteredElementList(query("#container")); /// // filteredElements is [a, b, c]. FilteredElementList(Node node) : _childNodes = node.nodes; // We can't memoize this, since it's possible that children will be messed // with externally to this class. // // TODO(nweiz): we don't always need to create a new list. For example // forEach, every, any, ... could directly work on the _childNodes. List<Element> get _filtered => _childNodes.whereType<Element>().toList(); @override void forEach(void Function(Element) f) { _filtered.forEach(f); } @override void operator []=(int index, Element value) { this[index].replaceWith(value); } @override set length(int newLength) { final len = length; if (newLength >= len) { return; } else if (newLength < 0) { throw ArgumentError('Invalid list length'); } removeRange(newLength, len); } @override String join([String separator = '']) => _filtered.join(separator); @override void add(Element value) { _childNodes.add(value); } @override void addAll(Iterable<Element> iterable) { for (var element in iterable) { add(element); } } @override bool contains(Object element) { return element is Element && _childNodes.contains(element); } @override Iterable<Element> get reversed => _filtered.reversed; @override void sort([int Function(Element, Element) compare]) { throw UnsupportedError('TODO(jacobr): should we impl?'); } @override void setRange(int start, int end, Iterable<Element> iterable, [int skipCount = 0]) { throw UnimplementedError(); } @override void fillRange(int start, int end, [Element fillValue]) { throw UnimplementedError(); } @override void replaceRange(int start, int end, Iterable<Element> iterable) { throw UnimplementedError(); } @override void removeRange(int start, int end) { _filtered.sublist(start, end).forEach((el) => el.remove()); } @override void clear() { // Currently, ElementList#clear clears even non-element nodes, so we follow // that behavior. _childNodes.clear(); } @override Element removeLast() { final result = last; if (result != null) { result.remove(); } return result; } @override Iterable<T> map<T>(T Function(Element) f) => _filtered.map(f); @override Iterable<Element> where(bool Function(Element) f) => _filtered.where(f); @override Iterable<T> expand<T>(Iterable<T> Function(Element) f) => _filtered.expand(f); @override void insert(int index, Element value) { _childNodes.insert(index, value); } @override void insertAll(int index, Iterable<Element> iterable) { _childNodes.insertAll(index, iterable); } @override Element removeAt(int index) { final result = this[index]; result.remove(); return result; } @override bool remove(Object element) { if (element is! Element) return false; for (var i = 0; i < length; i++) { var indexElement = this[i]; if (identical(indexElement, element)) { indexElement.remove(); return true; } } return false; } @override Element reduce(Element Function(Element, Element) combine) { return _filtered.reduce(combine); } @override T fold<T>( T initialValue, T Function(T previousValue, Element element) combine) { return _filtered.fold(initialValue, combine); } @override bool every(bool Function(Element) f) => _filtered.every(f); @override bool any(bool Function(Element) f) => _filtered.any(f); @override List<Element> toList({bool growable = true}) => List<Element>.from(this, growable: growable); @override Set<Element> toSet() => Set<Element>.from(this); @override Element firstWhere(bool Function(Element) test, {Element Function() orElse}) { return _filtered.firstWhere(test, orElse: orElse); } @override Element lastWhere(bool Function(Element) test, {Element Function() orElse}) { return _filtered.lastWhere(test, orElse: orElse); } @override Element singleWhere(bool Function(Element) test, {Element Function() orElse}) { if (orElse != null) throw UnimplementedError('orElse'); return _filtered.singleWhere(test); } @override Element elementAt(int index) { return this[index]; } @override bool get isEmpty => _filtered.isEmpty; @override int get length => _filtered.length; @override Element operator [](int index) => _filtered[index]; @override Iterator<Element> get iterator => _filtered.iterator; @override List<Element> sublist(int start, [int end]) => _filtered.sublist(start, end); @override Iterable<Element> getRange(int start, int end) => _filtered.getRange(start, end); // TODO(sigmund): this should be typed Element, but we currently run into a // bug where ListMixin<E>.indexOf() expects Object as the argument. @override int indexOf(Object element, [int start = 0]) => _filtered.indexOf(element, start); // TODO(sigmund): this should be typed Element, but we currently run into a // bug where ListMixin<E>.lastIndexOf() expects Object as the argument. @override int lastIndexOf(Object element, [int start]) { start ??= length - 1; return _filtered.lastIndexOf(element, start); } @override Element get first => _filtered.first; @override Element get last => _filtered.last; @override Element get single => _filtered.single; } // http://dom.spec.whatwg.org/#dom-node-textcontent // For Element and DocumentFragment String _getText(Node node) => (_ConcatTextVisitor()..visit(node)).toString(); void _setText(Node node, String value) { node.nodes.clear(); node.append(Text(value)); } class _ConcatTextVisitor extends TreeVisitor { final _str = StringBuffer(); @override String toString() => _str.toString(); @override void visitText(Text node) { _str.write(node.data); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html/dom_parsing.dart
/// This library contains extra APIs that aren't in the DOM, but are useful /// when interacting with the parse tree. library dom_parsing; import 'dom.dart'; import 'src/constants.dart' show rcdataElements; /// A simple tree visitor for the DOM nodes. class TreeVisitor { void visit(Node node) { switch (node.nodeType) { case Node.ELEMENT_NODE: return visitElement(node); case Node.TEXT_NODE: return visitText(node); case Node.COMMENT_NODE: return visitComment(node); case Node.DOCUMENT_FRAGMENT_NODE: return visitDocumentFragment(node); case Node.DOCUMENT_NODE: return visitDocument(node); case Node.DOCUMENT_TYPE_NODE: return visitDocumentType(node); default: throw UnsupportedError('DOM node type ${node.nodeType}'); } } void visitChildren(Node node) { // Allow for mutations (remove works) while iterating. for (var child in node.nodes.toList()) { visit(child); } } /// The fallback handler if the more specific visit method hasn't been /// overriden. Only use this from a subclass of [TreeVisitor], otherwise /// call [visit] instead. void visitNodeFallback(Node node) => visitChildren(node); void visitDocument(Document node) => visitNodeFallback(node); void visitDocumentType(DocumentType node) => visitNodeFallback(node); void visitText(Text node) => visitNodeFallback(node); // TODO(jmesserly): visit attributes. void visitElement(Element node) => visitNodeFallback(node); void visitComment(Comment node) => visitNodeFallback(node); void visitDocumentFragment(DocumentFragment node) => visitNodeFallback(node); } /// Converts the DOM tree into an HTML string with code markup suitable for /// displaying the HTML's source code with CSS colors for different parts of the /// markup. See also [CodeMarkupVisitor]. String htmlToCodeMarkup(Node node) { return (CodeMarkupVisitor()..visit(node)).toString(); } /// Converts the DOM tree into an HTML string with code markup suitable for /// displaying the HTML's source code with CSS colors for different parts of the /// markup. See also [htmlToCodeMarkup]. class CodeMarkupVisitor extends TreeVisitor { final StringBuffer _str; CodeMarkupVisitor() : _str = StringBuffer(); @override String toString() => _str.toString(); @override void visitDocument(Document node) { _str.write('<pre>'); visitChildren(node); _str.write('</pre>'); } @override void visitDocumentType(DocumentType node) { _str.write('<code class="markup doctype">&lt;!DOCTYPE ${node.name}>' '</code>'); } @override void visitText(Text node) { writeTextNodeAsHtml(_str, node); } @override void visitElement(Element node) { final tag = node.localName; _str.write('&lt;<code class="markup element-name">$tag</code>'); if (node.attributes.isNotEmpty) { node.attributes.forEach((key, v) { v = htmlSerializeEscape(v, attributeMode: true); _str.write(' <code class="markup attribute-name">$key</code>' '=<code class="markup attribute-value">"$v"</code>'); }); } if (node.nodes.isNotEmpty) { _str.write('>'); visitChildren(node); } else if (isVoidElement(tag)) { _str.write('>'); return; } _str.write('&lt;/<code class="markup element-name">$tag</code>>'); } @override void visitComment(Comment node) { var data = htmlSerializeEscape(node.data); _str.write('<code class="markup comment">&lt;!--$data--></code>'); } } // TODO(jmesserly): reconcile this with dart:web htmlEscape. // This one might be more useful, as it is HTML5 spec compliant. /// Escapes [text] for use in the /// [HTML fragment serialization algorithm][1]. In particular, as described /// in the [specification][2]: /// /// - Replace any occurrence of the `&` character by the string `&amp;`. /// - Replace any occurrences of the U+00A0 NO-BREAK SPACE character by the /// string `&nbsp;`. /// - If the algorithm was invoked in [attributeMode], replace any occurrences /// of the `"` character by the string `&quot;`. /// - If the algorithm was not invoked in [attributeMode], replace any /// occurrences of the `<` character by the string `&lt;`, and any occurrences /// of the `>` character by the string `&gt;`. /// /// [1]: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-end.html#serializing-html-fragments /// [2]: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-end.html#escapingString String htmlSerializeEscape(String text, {bool attributeMode = false}) { // TODO(jmesserly): is it faster to build up a list of codepoints? // StringBuffer seems cleaner assuming Dart can unbox 1-char strings. StringBuffer result; for (var i = 0; i < text.length; i++) { var ch = text[i]; String replace; switch (ch) { case '&': replace = '&amp;'; break; case '\u00A0' /*NO-BREAK SPACE*/ : replace = '&nbsp;'; break; case '"': if (attributeMode) replace = '&quot;'; break; case '<': if (!attributeMode) replace = '&lt;'; break; case '>': if (!attributeMode) replace = '&gt;'; break; } if (replace != null) { result ??= StringBuffer(text.substring(0, i)); result.write(replace); } else if (result != null) { result.write(ch); } } return result != null ? result.toString() : text; } /// Returns true if this tag name is a void element. /// This method is useful to a pretty printer, because void elements must not /// have an end tag. /// See also: <http://dev.w3.org/html5/markup/syntax.html#void-elements>. bool isVoidElement(String tagName) { switch (tagName) { case 'area': case 'base': case 'br': case 'col': case 'command': case 'embed': case 'hr': case 'img': case 'input': case 'keygen': case 'link': case 'meta': case 'param': case 'source': case 'track': case 'wbr': return true; } return false; } /// Serialize text node according to: /// <http://www.whatwg.org/specs/web-apps/current-work/multipage/the-end.html#html-fragment-serialization-algorithm> void writeTextNodeAsHtml(StringBuffer str, Text node) { // Don't escape text for certain elements, notably <script>. final parent = node.parentNode; if (parent is Element) { var tag = parent.localName; if (rcdataElements.contains(tag) || tag == 'plaintext') { str.write(node.data); return; } } str.write(htmlSerializeEscape(node.data)); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html/parser.dart
/// This library has a parser for HTML5 documents, that lets you parse HTML /// easily from a script or server side application: /// /// import 'package:html/parser.dart' show parse; /// import 'package:html/dom.dart'; /// main() { /// var document = parse( /// '<body>Hello world! <a href="www.html5rocks.com">HTML5 rocks!'); /// print(document.outerHtml); /// } /// /// The resulting document you get back has a DOM-like API for easy tree /// traversal and manipulation. library parser; import 'dart:collection'; import 'dart:math'; import 'package:source_span/source_span.dart'; import 'dom.dart'; import 'src/constants.dart'; import 'src/encoding_parser.dart'; import 'src/token.dart'; import 'src/tokenizer.dart'; import 'src/treebuilder.dart'; import 'src/utils.dart'; /// Parse the [input] html5 document into a tree. The [input] can be /// a [String], [List<int>] of bytes or an [HtmlTokenizer]. /// /// If [input] is not a [HtmlTokenizer], you can optionally specify the file's /// [encoding], which must be a string. If specified that encoding will be /// used regardless of any BOM or later declaration (such as in a meta element). /// /// Set [generateSpans] if you want to generate [SourceSpan]s, otherwise the /// [Node.sourceSpan] property will be `null`. When using [generateSpans] you /// can additionally pass [sourceUrl] to indicate where the [input] was /// extracted from. Document parse(input, {String encoding, bool generateSpans = false, String sourceUrl}) { var p = HtmlParser(input, encoding: encoding, generateSpans: generateSpans, sourceUrl: sourceUrl); return p.parse(); } /// Parse the [input] html5 document fragment into a tree. The [input] can be /// a [String], [List<int>] of bytes or an [HtmlTokenizer]. The [container] /// element can optionally be specified, otherwise it defaults to "div". /// /// If [input] is not a [HtmlTokenizer], you can optionally specify the file's /// [encoding], which must be a string. If specified, that encoding will be used, /// regardless of any BOM or later declaration (such as in a meta element). /// /// Set [generateSpans] if you want to generate [SourceSpan]s, otherwise the /// [Node.sourceSpan] property will be `null`. When using [generateSpans] you can /// additionally pass [sourceUrl] to indicate where the [input] was extracted /// from. DocumentFragment parseFragment(input, {String container = 'div', String encoding, bool generateSpans = false, String sourceUrl}) { var p = HtmlParser(input, encoding: encoding, generateSpans: generateSpans, sourceUrl: sourceUrl); return p.parseFragment(container); } /// Parser for HTML, which generates a tree structure from a stream of /// (possibly malformed) characters. class HtmlParser { /// Raise an exception on the first error encountered. final bool strict; /// True to generate [SourceSpan]s for the [Node.sourceSpan] property. final bool generateSpans; final HtmlTokenizer tokenizer; final TreeBuilder tree; final List<ParseError> errors = <ParseError>[]; String container; bool firstStartTag = false; // TODO(jmesserly): use enum? /// "quirks" / "limited quirks" / "no quirks" String compatMode = 'no quirks'; /// innerHTML container when parsing document fragment. String innerHTML; Phase phase; Phase lastPhase; Phase originalPhase; Phase beforeRCDataPhase; bool framesetOK; // These fields hold the different phase singletons. At any given time one // of them will be active. InitialPhase _initialPhase; BeforeHtmlPhase _beforeHtmlPhase; BeforeHeadPhase _beforeHeadPhase; InHeadPhase _inHeadPhase; AfterHeadPhase _afterHeadPhase; InBodyPhase _inBodyPhase; TextPhase _textPhase; InTablePhase _inTablePhase; InTableTextPhase _inTableTextPhase; InCaptionPhase _inCaptionPhase; InColumnGroupPhase _inColumnGroupPhase; InTableBodyPhase _inTableBodyPhase; InRowPhase _inRowPhase; InCellPhase _inCellPhase; InSelectPhase _inSelectPhase; InSelectInTablePhase _inSelectInTablePhase; InForeignContentPhase _inForeignContentPhase; AfterBodyPhase _afterBodyPhase; InFramesetPhase _inFramesetPhase; AfterFramesetPhase _afterFramesetPhase; AfterAfterBodyPhase _afterAfterBodyPhase; AfterAfterFramesetPhase _afterAfterFramesetPhase; /// Create an HtmlParser and configure the [tree] builder and [strict] mode. /// The [input] can be a [String], [List<int>] of bytes or an [HtmlTokenizer]. /// /// If [input] is not a [HtmlTokenizer], you can specify a few more arguments. /// /// The [encoding] must be a string that indicates the encoding. If specified, /// that encoding will be used, regardless of any BOM or later declaration /// (such as in a meta element). /// /// Set [parseMeta] to false if you want to disable parsing the meta element. /// /// Set [lowercaseElementName] or [lowercaseAttrName] to false to disable the /// automatic conversion of element and attribute names to lower case. Note /// that standard way to parse HTML is to lowercase, which is what the browser /// DOM will do if you request [Node.outerHTML], for example. HtmlParser(input, {String encoding, bool parseMeta = true, bool lowercaseElementName = true, bool lowercaseAttrName = true, this.strict = false, this.generateSpans = false, String sourceUrl, TreeBuilder tree}) : tree = tree ?? TreeBuilder(true), tokenizer = (input is HtmlTokenizer ? input : HtmlTokenizer(input, encoding: encoding, parseMeta: parseMeta, lowercaseElementName: lowercaseElementName, lowercaseAttrName: lowercaseAttrName, generateSpans: generateSpans, sourceUrl: sourceUrl)) { tokenizer.parser = this; _initialPhase = InitialPhase(this); _beforeHtmlPhase = BeforeHtmlPhase(this); _beforeHeadPhase = BeforeHeadPhase(this); _inHeadPhase = InHeadPhase(this); // TODO(jmesserly): html5lib did not implement the no script parsing mode // More information here: // http://www.whatwg.org/specs/web-apps/current-work/multipage/parsing.html#scripting-flag // http://www.whatwg.org/specs/web-apps/current-work/multipage/tree-construction.html#parsing-main-inheadnoscript // "inHeadNoscript": new InHeadNoScriptPhase(this); _afterHeadPhase = AfterHeadPhase(this); _inBodyPhase = InBodyPhase(this); _textPhase = TextPhase(this); _inTablePhase = InTablePhase(this); _inTableTextPhase = InTableTextPhase(this); _inCaptionPhase = InCaptionPhase(this); _inColumnGroupPhase = InColumnGroupPhase(this); _inTableBodyPhase = InTableBodyPhase(this); _inRowPhase = InRowPhase(this); _inCellPhase = InCellPhase(this); _inSelectPhase = InSelectPhase(this); _inSelectInTablePhase = InSelectInTablePhase(this); _inForeignContentPhase = InForeignContentPhase(this); _afterBodyPhase = AfterBodyPhase(this); _inFramesetPhase = InFramesetPhase(this); _afterFramesetPhase = AfterFramesetPhase(this); _afterAfterBodyPhase = AfterAfterBodyPhase(this); _afterAfterFramesetPhase = AfterAfterFramesetPhase(this); } bool get innerHTMLMode => innerHTML != null; /// Parse an html5 document into a tree. /// After parsing, [errors] will be populated with parse errors, if any. Document parse() { innerHTML = null; _parse(); return tree.getDocument(); } /// Parse an html5 document fragment into a tree. /// Pass a [container] to change the type of the containing element. /// After parsing, [errors] will be populated with parse errors, if any. DocumentFragment parseFragment([String container = 'div']) { if (container == null) throw ArgumentError('container'); innerHTML = container.toLowerCase(); _parse(); return tree.getFragment(); } void _parse() { reset(); while (true) { try { mainLoop(); break; } on ReparseException catch (_) { // Note: this happens if we start parsing but the character encoding // changes. So we should only need to restart very early in the parse. reset(); } } } void reset() { tokenizer.reset(); tree.reset(); firstStartTag = false; errors.clear(); // "quirks" / "limited quirks" / "no quirks" compatMode = 'no quirks'; if (innerHTMLMode) { if (cdataElements.contains(innerHTML)) { tokenizer.state = tokenizer.rcdataState; } else if (rcdataElements.contains(innerHTML)) { tokenizer.state = tokenizer.rawtextState; } else if (innerHTML == 'plaintext') { tokenizer.state = tokenizer.plaintextState; } else { // state already is data state // tokenizer.state = tokenizer.dataState; } phase = _beforeHtmlPhase; _beforeHtmlPhase.insertHtmlElement(); resetInsertionMode(); } else { phase = _initialPhase; } lastPhase = null; beforeRCDataPhase = null; framesetOK = true; } bool isHTMLIntegrationPoint(Element element) { if (element.localName == 'annotation-xml' && element.namespaceUri == Namespaces.mathml) { var enc = element.attributes['encoding']; if (enc != null) enc = asciiUpper2Lower(enc); return enc == 'text/html' || enc == 'application/xhtml+xml'; } else { return htmlIntegrationPointElements .contains(Pair(element.namespaceUri, element.localName)); } } bool isMathMLTextIntegrationPoint(Element element) { return mathmlTextIntegrationPointElements .contains(Pair(element.namespaceUri, element.localName)); } bool inForeignContent(Token token, int type) { if (tree.openElements.isEmpty) return false; var node = tree.openElements.last; if (node.namespaceUri == tree.defaultNamespace) return false; if (isMathMLTextIntegrationPoint(node)) { if (type == TokenKind.startTag && (token as StartTagToken).name != 'mglyph' && (token as StartTagToken).name != 'malignmark') { return false; } if (type == TokenKind.characters || type == TokenKind.spaceCharacters) { return false; } } if (node.localName == 'annotation-xml' && type == TokenKind.startTag && (token as StartTagToken).name == 'svg') { return false; } if (isHTMLIntegrationPoint(node)) { if (type == TokenKind.startTag || type == TokenKind.characters || type == TokenKind.spaceCharacters) { return false; } } return true; } void mainLoop() { while (tokenizer.moveNext()) { var token = tokenizer.current; var newToken = token; int type; while (newToken != null) { type = newToken.kind; // Note: avoid "is" test here, see http://dartbug.com/4795 if (type == TokenKind.parseError) { ParseErrorToken error = newToken; parseError(error.span, error.data, error.messageParams); newToken = null; } else { var localPhase = phase; if (inForeignContent(token, type)) { localPhase = _inForeignContentPhase; } switch (type) { case TokenKind.characters: newToken = localPhase.processCharacters(newToken); break; case TokenKind.spaceCharacters: newToken = localPhase.processSpaceCharacters(newToken); break; case TokenKind.startTag: newToken = localPhase.processStartTag(newToken); break; case TokenKind.endTag: newToken = localPhase.processEndTag(newToken); break; case TokenKind.comment: newToken = localPhase.processComment(newToken); break; case TokenKind.doctype: newToken = localPhase.processDoctype(newToken); break; } } } if (token is StartTagToken) { if (token.selfClosing && !token.selfClosingAcknowledged) { parseError(token.span, 'non-void-element-with-trailing-solidus', {'name': token.name}); } } } // When the loop finishes it's EOF var reprocess = true; var reprocessPhases = []; while (reprocess) { reprocessPhases.add(phase); reprocess = phase.processEOF(); if (reprocess) { assert(!reprocessPhases.contains(phase)); } } } /// The last span available. Used for EOF errors if we don't have something /// better. SourceSpan get _lastSpan { if (tokenizer.stream.fileInfo == null) return null; var pos = tokenizer.stream.position; return tokenizer.stream.fileInfo.location(pos).pointSpan(); } void parseError(SourceSpan span, String errorcode, [Map datavars = const {}]) { if (!generateSpans && span == null) { span = _lastSpan; } var err = ParseError(errorcode, span, datavars); errors.add(err); if (strict) throw err; } void adjustMathMLAttributes(StartTagToken token) { var orig = token.data.remove('definitionurl'); if (orig != null) { token.data['definitionURL'] = orig; } } void adjustSVGAttributes(StartTagToken token) { final replacements = const { 'attributename': 'attributeName', 'attributetype': 'attributeType', 'basefrequency': 'baseFrequency', 'baseprofile': 'baseProfile', 'calcmode': 'calcMode', 'clippathunits': 'clipPathUnits', 'contentscripttype': 'contentScriptType', 'contentstyletype': 'contentStyleType', 'diffuseconstant': 'diffuseConstant', 'edgemode': 'edgeMode', 'externalresourcesrequired': 'externalResourcesRequired', 'filterres': 'filterRes', 'filterunits': 'filterUnits', 'glyphref': 'glyphRef', 'gradienttransform': 'gradientTransform', 'gradientunits': 'gradientUnits', 'kernelmatrix': 'kernelMatrix', 'kernelunitlength': 'kernelUnitLength', 'keypoints': 'keyPoints', 'keysplines': 'keySplines', 'keytimes': 'keyTimes', 'lengthadjust': 'lengthAdjust', 'limitingconeangle': 'limitingConeAngle', 'markerheight': 'markerHeight', 'markerunits': 'markerUnits', 'markerwidth': 'markerWidth', 'maskcontentunits': 'maskContentUnits', 'maskunits': 'maskUnits', 'numoctaves': 'numOctaves', 'pathlength': 'pathLength', 'patterncontentunits': 'patternContentUnits', 'patterntransform': 'patternTransform', 'patternunits': 'patternUnits', 'pointsatx': 'pointsAtX', 'pointsaty': 'pointsAtY', 'pointsatz': 'pointsAtZ', 'preservealpha': 'preserveAlpha', 'preserveaspectratio': 'preserveAspectRatio', 'primitiveunits': 'primitiveUnits', 'refx': 'refX', 'refy': 'refY', 'repeatcount': 'repeatCount', 'repeatdur': 'repeatDur', 'requiredextensions': 'requiredExtensions', 'requiredfeatures': 'requiredFeatures', 'specularconstant': 'specularConstant', 'specularexponent': 'specularExponent', 'spreadmethod': 'spreadMethod', 'startoffset': 'startOffset', 'stddeviation': 'stdDeviation', 'stitchtiles': 'stitchTiles', 'surfacescale': 'surfaceScale', 'systemlanguage': 'systemLanguage', 'tablevalues': 'tableValues', 'targetx': 'targetX', 'targety': 'targetY', 'textlength': 'textLength', 'viewbox': 'viewBox', 'viewtarget': 'viewTarget', 'xchannelselector': 'xChannelSelector', 'ychannelselector': 'yChannelSelector', 'zoomandpan': 'zoomAndPan' }; for (var originalName in token.data.keys.toList()) { var svgName = replacements[originalName]; if (svgName != null) { token.data[svgName] = token.data.remove(originalName); } } } void adjustForeignAttributes(StartTagToken token) { // TODO(jmesserly): I don't like mixing non-string objects with strings in // the Node.attributes Map. Is there another solution? final replacements = const { 'xlink:actuate': AttributeName('xlink', 'actuate', Namespaces.xlink), 'xlink:arcrole': AttributeName('xlink', 'arcrole', Namespaces.xlink), 'xlink:href': AttributeName('xlink', 'href', Namespaces.xlink), 'xlink:role': AttributeName('xlink', 'role', Namespaces.xlink), 'xlink:show': AttributeName('xlink', 'show', Namespaces.xlink), 'xlink:title': AttributeName('xlink', 'title', Namespaces.xlink), 'xlink:type': AttributeName('xlink', 'type', Namespaces.xlink), 'xml:base': AttributeName('xml', 'base', Namespaces.xml), 'xml:lang': AttributeName('xml', 'lang', Namespaces.xml), 'xml:space': AttributeName('xml', 'space', Namespaces.xml), 'xmlns': AttributeName(null, 'xmlns', Namespaces.xmlns), 'xmlns:xlink': AttributeName('xmlns', 'xlink', Namespaces.xmlns) }; for (var originalName in token.data.keys.toList()) { var foreignName = replacements[originalName]; if (foreignName != null) { token.data[foreignName] = token.data.remove(originalName); } } } void resetInsertionMode() { // The name of this method is mostly historical. (It's also used in the // specification.) for (var node in tree.openElements.reversed) { var nodeName = node.localName; var last = node == tree.openElements[0]; if (last) { assert(innerHTMLMode); nodeName = innerHTML; } // Check for conditions that should only happen in the innerHTML // case switch (nodeName) { case 'select': case 'colgroup': case 'head': case 'html': assert(innerHTMLMode); break; } if (!last && node.namespaceUri != tree.defaultNamespace) { continue; } switch (nodeName) { case 'select': phase = _inSelectPhase; return; case 'td': phase = _inCellPhase; return; case 'th': phase = _inCellPhase; return; case 'tr': phase = _inRowPhase; return; case 'tbody': phase = _inTableBodyPhase; return; case 'thead': phase = _inTableBodyPhase; return; case 'tfoot': phase = _inTableBodyPhase; return; case 'caption': phase = _inCaptionPhase; return; case 'colgroup': phase = _inColumnGroupPhase; return; case 'table': phase = _inTablePhase; return; case 'head': phase = _inBodyPhase; return; case 'body': phase = _inBodyPhase; return; case 'frameset': phase = _inFramesetPhase; return; case 'html': phase = _beforeHeadPhase; return; } } phase = _inBodyPhase; } /// Generic RCDATA/RAWTEXT Parsing algorithm /// [contentType] - RCDATA or RAWTEXT void parseRCDataRawtext(Token token, String contentType) { assert(contentType == 'RAWTEXT' || contentType == 'RCDATA'); tree.insertElement(token); if (contentType == 'RAWTEXT') { tokenizer.state = tokenizer.rawtextState; } else { tokenizer.state = tokenizer.rcdataState; } originalPhase = phase; phase = _textPhase; } } /// Base class for helper object that implements each phase of processing. class Phase { // Order should be (they can be omitted): // * EOF // * Comment // * Doctype // * SpaceCharacters // * Characters // * StartTag // - startTag* methods // * EndTag // - endTag* methods final HtmlParser parser; final TreeBuilder tree; Phase(this.parser) : tree = parser.tree; bool processEOF() { throw UnimplementedError(); } Token processComment(CommentToken token) { // For most phases the following is correct. Where it's not it will be // overridden. tree.insertComment(token, tree.openElements.last); return null; } Token processDoctype(DoctypeToken token) { parser.parseError(token.span, 'unexpected-doctype'); return null; } Token processCharacters(CharactersToken token) { tree.insertText(token.data, token.span); return null; } Token processSpaceCharacters(SpaceCharactersToken token) { tree.insertText(token.data, token.span); return null; } Token processStartTag(StartTagToken token) { throw UnimplementedError(); } Token startTagHtml(StartTagToken token) { if (parser.firstStartTag == false && token.name == 'html') { parser.parseError(token.span, 'non-html-root'); } // XXX Need a check here to see if the first start tag token emitted is // this token... If it's not, invoke parser.parseError(). tree.openElements[0].sourceSpan = token.span; token.data.forEach((attr, value) { tree.openElements[0].attributes.putIfAbsent(attr, () => value); }); parser.firstStartTag = false; return null; } Token processEndTag(EndTagToken token) { throw UnimplementedError(); } /// Helper method for popping openElements. void popOpenElementsUntil(EndTagToken token) { var name = token.name; var node = tree.openElements.removeLast(); while (node.localName != name) { node = tree.openElements.removeLast(); } if (node != null) { node.endSourceSpan = token.span; } } } class InitialPhase extends Phase { InitialPhase(parser) : super(parser); @override Token processSpaceCharacters(SpaceCharactersToken token) { return null; } @override Token processComment(CommentToken token) { tree.insertComment(token, tree.document); return null; } @override Token processDoctype(DoctypeToken token) { var name = token.name; var publicId = token.publicId; var systemId = token.systemId; var correct = token.correct; if ((name != 'html' || publicId != null || systemId != null && systemId != 'about:legacy-compat')) { parser.parseError(token.span, 'unknown-doctype'); } publicId ??= ''; tree.insertDoctype(token); if (publicId != '') { publicId = asciiUpper2Lower(publicId); } if (!correct || token.name != 'html' || startsWithAny(publicId, const [ '+//silmaril//dtd html pro v0r11 19970101//', '-//advasoft ltd//dtd html 3.0 aswedit + extensions//', '-//as//dtd html 3.0 aswedit + extensions//', '-//ietf//dtd html 2.0 level 1//', '-//ietf//dtd html 2.0 level 2//', '-//ietf//dtd html 2.0 strict level 1//', '-//ietf//dtd html 2.0 strict level 2//', '-//ietf//dtd html 2.0 strict//', '-//ietf//dtd html 2.0//', '-//ietf//dtd html 2.1e//', '-//ietf//dtd html 3.0//', '-//ietf//dtd html 3.2 final//', '-//ietf//dtd html 3.2//', '-//ietf//dtd html 3//', '-//ietf//dtd html level 0//', '-//ietf//dtd html level 1//', '-//ietf//dtd html level 2//', '-//ietf//dtd html level 3//', '-//ietf//dtd html strict level 0//', '-//ietf//dtd html strict level 1//', '-//ietf//dtd html strict level 2//', '-//ietf//dtd html strict level 3//', '-//ietf//dtd html strict//', '-//ietf//dtd html//', '-//metrius//dtd metrius presentational//', '-//microsoft//dtd internet explorer 2.0 html strict//', '-//microsoft//dtd internet explorer 2.0 html//', '-//microsoft//dtd internet explorer 2.0 tables//', '-//microsoft//dtd internet explorer 3.0 html strict//', '-//microsoft//dtd internet explorer 3.0 html//', '-//microsoft//dtd internet explorer 3.0 tables//', '-//netscape comm. corp.//dtd html//', '-//netscape comm. corp.//dtd strict html//', "-//o'reilly and associates//dtd html 2.0//", "-//o'reilly and associates//dtd html extended 1.0//", "-//o'reilly and associates//dtd html extended relaxed 1.0//", '-//softquad software//dtd hotmetal pro 6.0::19990601::extensions to html 4.0//', '-//softquad//dtd hotmetal pro 4.0::19971010::extensions to html 4.0//', '-//spyglass//dtd html 2.0 extended//', '-//sq//dtd html 2.0 hotmetal + extensions//', '-//sun microsystems corp.//dtd hotjava html//', '-//sun microsystems corp.//dtd hotjava strict html//', '-//w3c//dtd html 3 1995-03-24//', '-//w3c//dtd html 3.2 draft//', '-//w3c//dtd html 3.2 final//', '-//w3c//dtd html 3.2//', '-//w3c//dtd html 3.2s draft//', '-//w3c//dtd html 4.0 frameset//', '-//w3c//dtd html 4.0 transitional//', '-//w3c//dtd html experimental 19960712//', '-//w3c//dtd html experimental 970421//', '-//w3c//dtd w3 html//', '-//w3o//dtd w3 html 3.0//', '-//webtechs//dtd mozilla html 2.0//', '-//webtechs//dtd mozilla html//' ]) || const [ '-//w3o//dtd w3 html strict 3.0//en//', '-/w3c/dtd html 4.0 transitional/en', 'html' ].contains(publicId) || startsWithAny(publicId, const [ '-//w3c//dtd html 4.01 frameset//', '-//w3c//dtd html 4.01 transitional//' ]) && systemId == null || systemId != null && systemId.toLowerCase() == 'http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd') { parser.compatMode = 'quirks'; } else if (startsWithAny(publicId, const [ '-//w3c//dtd xhtml 1.0 frameset//', '-//w3c//dtd xhtml 1.0 transitional//' ]) || startsWithAny(publicId, const [ '-//w3c//dtd html 4.01 frameset//', '-//w3c//dtd html 4.01 transitional//' ]) && systemId != null) { parser.compatMode = 'limited quirks'; } parser.phase = parser._beforeHtmlPhase; return null; } void anythingElse() { parser.compatMode = 'quirks'; parser.phase = parser._beforeHtmlPhase; } @override Token processCharacters(CharactersToken token) { parser.parseError(token.span, 'expected-doctype-but-got-chars'); anythingElse(); return token; } @override Token processStartTag(StartTagToken token) { parser.parseError( token.span, 'expected-doctype-but-got-start-tag', {'name': token.name}); anythingElse(); return token; } @override Token processEndTag(EndTagToken token) { parser.parseError( token.span, 'expected-doctype-but-got-end-tag', {'name': token.name}); anythingElse(); return token; } @override bool processEOF() { parser.parseError(parser._lastSpan, 'expected-doctype-but-got-eof'); anythingElse(); return true; } } class BeforeHtmlPhase extends Phase { BeforeHtmlPhase(parser) : super(parser); // helper methods void insertHtmlElement() { tree.insertRoot( StartTagToken('html', data: LinkedHashMap<dynamic, String>())); parser.phase = parser._beforeHeadPhase; } // other @override bool processEOF() { insertHtmlElement(); return true; } @override Token processComment(CommentToken token) { tree.insertComment(token, tree.document); return null; } @override Token processSpaceCharacters(SpaceCharactersToken token) { return null; } @override Token processCharacters(CharactersToken token) { insertHtmlElement(); return token; } @override @override Token processStartTag(StartTagToken token) { if (token.name == 'html') { parser.firstStartTag = true; } insertHtmlElement(); return token; } @override Token processEndTag(EndTagToken token) { switch (token.name) { case 'head': case 'body': case 'html': case 'br': insertHtmlElement(); return token; default: parser.parseError( token.span, 'unexpected-end-tag-before-html', {'name': token.name}); return null; } } } class BeforeHeadPhase extends Phase { BeforeHeadPhase(parser) : super(parser); @override Token processStartTag(StartTagToken token) { switch (token.name) { case 'html': return startTagHtml(token); case 'head': startTagHead(token); return null; default: return startTagOther(token); } } @override Token processEndTag(EndTagToken token) { switch (token.name) { case 'head': case 'body': case 'html': case 'br': return endTagImplyHead(token); default: endTagOther(token); return null; } } @override bool processEOF() { startTagHead(StartTagToken('head', data: LinkedHashMap<dynamic, String>())); return true; } @override Token processSpaceCharacters(SpaceCharactersToken token) { return null; } @override Token processCharacters(CharactersToken token) { startTagHead(StartTagToken('head', data: LinkedHashMap<dynamic, String>())); return token; } @override Token startTagHtml(StartTagToken token) { return parser._inBodyPhase.processStartTag(token); } void startTagHead(StartTagToken token) { tree.insertElement(token); tree.headPointer = tree.openElements.last; parser.phase = parser._inHeadPhase; } Token startTagOther(StartTagToken token) { startTagHead(StartTagToken('head', data: LinkedHashMap<dynamic, String>())); return token; } Token endTagImplyHead(EndTagToken token) { startTagHead(StartTagToken('head', data: LinkedHashMap<dynamic, String>())); return token; } void endTagOther(EndTagToken token) { parser.parseError( token.span, 'end-tag-after-implied-root', {'name': token.name}); } } class InHeadPhase extends Phase { InHeadPhase(parser) : super(parser); @override Token processStartTag(StartTagToken token) { switch (token.name) { case 'html': return startTagHtml(token); case 'title': startTagTitle(token); return null; case 'noscript': case 'noframes': case 'style': startTagNoScriptNoFramesStyle(token); return null; case 'script': startTagScript(token); return null; case 'base': case 'basefont': case 'bgsound': case 'command': case 'link': startTagBaseLinkCommand(token); return null; case 'meta': startTagMeta(token); return null; case 'head': startTagHead(token); return null; default: return startTagOther(token); } } @override Token processEndTag(EndTagToken token) { switch (token.name) { case 'head': endTagHead(token); return null; case 'br': case 'html': case 'body': return endTagHtmlBodyBr(token); default: endTagOther(token); return null; } } // the real thing @override bool processEOF() { anythingElse(); return true; } @override Token processCharacters(CharactersToken token) { anythingElse(); return token; } @override Token startTagHtml(StartTagToken token) { return parser._inBodyPhase.processStartTag(token); } void startTagHead(StartTagToken token) { parser.parseError(token.span, 'two-heads-are-not-better-than-one'); } void startTagBaseLinkCommand(StartTagToken token) { tree.insertElement(token); tree.openElements.removeLast(); token.selfClosingAcknowledged = true; } void startTagMeta(StartTagToken token) { tree.insertElement(token); tree.openElements.removeLast(); token.selfClosingAcknowledged = true; var attributes = token.data; if (!parser.tokenizer.stream.charEncodingCertain) { var charset = attributes['charset']; var content = attributes['content']; if (charset != null) { parser.tokenizer.stream.changeEncoding(charset); } else if (content != null) { var data = EncodingBytes(content); var codec = ContentAttrParser(data).parse(); parser.tokenizer.stream.changeEncoding(codec); } } } void startTagTitle(StartTagToken token) { parser.parseRCDataRawtext(token, 'RCDATA'); } void startTagNoScriptNoFramesStyle(StartTagToken token) { // Need to decide whether to implement the scripting-disabled case parser.parseRCDataRawtext(token, 'RAWTEXT'); } void startTagScript(StartTagToken token) { tree.insertElement(token); parser.tokenizer.state = parser.tokenizer.scriptDataState; parser.originalPhase = parser.phase; parser.phase = parser._textPhase; } Token startTagOther(StartTagToken token) { anythingElse(); return token; } void endTagHead(EndTagToken token) { var node = parser.tree.openElements.removeLast(); assert(node.localName == 'head'); node.endSourceSpan = token.span; parser.phase = parser._afterHeadPhase; } Token endTagHtmlBodyBr(EndTagToken token) { anythingElse(); return token; } void endTagOther(EndTagToken token) { parser.parseError(token.span, 'unexpected-end-tag', {'name': token.name}); } void anythingElse() { endTagHead(EndTagToken('head')); } } // XXX If we implement a parser for which scripting is disabled we need to // implement this phase. // // class InHeadNoScriptPhase extends Phase { class AfterHeadPhase extends Phase { AfterHeadPhase(parser) : super(parser); @override Token processStartTag(StartTagToken token) { switch (token.name) { case 'html': return startTagHtml(token); case 'body': startTagBody(token); return null; case 'frameset': startTagFrameset(token); return null; case 'base': case 'basefont': case 'bgsound': case 'link': case 'meta': case 'noframes': case 'script': case 'style': case 'title': startTagFromHead(token); return null; case 'head': startTagHead(token); return null; default: return startTagOther(token); } } @override Token processEndTag(EndTagToken token) { switch (token.name) { case 'body': case 'html': case 'br': return endTagHtmlBodyBr(token); default: endTagOther(token); return null; } } @override bool processEOF() { anythingElse(); return true; } @override Token processCharacters(CharactersToken token) { anythingElse(); return token; } @override Token startTagHtml(StartTagToken token) { return parser._inBodyPhase.processStartTag(token); } void startTagBody(StartTagToken token) { parser.framesetOK = false; tree.insertElement(token); parser.phase = parser._inBodyPhase; } void startTagFrameset(StartTagToken token) { tree.insertElement(token); parser.phase = parser._inFramesetPhase; } void startTagFromHead(StartTagToken token) { parser.parseError(token.span, 'unexpected-start-tag-out-of-my-head', {'name': token.name}); tree.openElements.add(tree.headPointer); parser._inHeadPhase.processStartTag(token); for (var node in tree.openElements.reversed) { if (node.localName == 'head') { tree.openElements.remove(node); break; } } } void startTagHead(StartTagToken token) { parser.parseError(token.span, 'unexpected-start-tag', {'name': token.name}); } Token startTagOther(StartTagToken token) { anythingElse(); return token; } Token endTagHtmlBodyBr(EndTagToken token) { anythingElse(); return token; } void endTagOther(EndTagToken token) { parser.parseError(token.span, 'unexpected-end-tag', {'name': token.name}); } void anythingElse() { tree.insertElement( StartTagToken('body', data: LinkedHashMap<dynamic, String>())); parser.phase = parser._inBodyPhase; parser.framesetOK = true; } } typedef TokenProccessor = Token Function(Token token); class InBodyPhase extends Phase { bool dropNewline = false; // http://www.whatwg.org/specs/web-apps/current-work///parsing-main-inbody // the really-really-really-very crazy mode InBodyPhase(parser) : super(parser); @override Token processStartTag(StartTagToken token) { switch (token.name) { case 'html': return startTagHtml(token); case 'base': case 'basefont': case 'bgsound': case 'command': case 'link': case 'meta': case 'noframes': case 'script': case 'style': case 'title': return startTagProcessInHead(token); case 'body': startTagBody(token); return null; case 'frameset': startTagFrameset(token); return null; case 'address': case 'article': case 'aside': case 'blockquote': case 'center': case 'details': case 'dir': case 'div': case 'dl': case 'fieldset': case 'figcaption': case 'figure': case 'footer': case 'header': case 'hgroup': case 'menu': case 'nav': case 'ol': case 'p': case 'section': case 'summary': case 'ul': startTagCloseP(token); return null; // headingElements case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': startTagHeading(token); return null; case 'pre': case 'listing': startTagPreListing(token); return null; case 'form': startTagForm(token); return null; case 'li': case 'dd': case 'dt': startTagListItem(token); return null; case 'plaintext': startTagPlaintext(token); return null; case 'a': startTagA(token); return null; case 'b': case 'big': case 'code': case 'em': case 'font': case 'i': case 's': case 'small': case 'strike': case 'strong': case 'tt': case 'u': startTagFormatting(token); return null; case 'nobr': startTagNobr(token); return null; case 'button': return startTagButton(token); case 'applet': case 'marquee': case 'object': startTagAppletMarqueeObject(token); return null; case 'xmp': startTagXmp(token); return null; case 'table': startTagTable(token); return null; case 'area': case 'br': case 'embed': case 'img': case 'keygen': case 'wbr': startTagVoidFormatting(token); return null; case 'param': case 'source': case 'track': startTagParamSource(token); return null; case 'input': startTagInput(token); return null; case 'hr': startTagHr(token); return null; case 'image': startTagImage(token); return null; case 'isindex': startTagIsIndex(token); return null; case 'textarea': startTagTextarea(token); return null; case 'iframe': startTagIFrame(token); return null; case 'noembed': case 'noscript': startTagRawtext(token); return null; case 'select': startTagSelect(token); return null; case 'rp': case 'rt': startTagRpRt(token); return null; case 'option': case 'optgroup': startTagOpt(token); return null; case 'math': startTagMath(token); return null; case 'svg': startTagSvg(token); return null; case 'caption': case 'col': case 'colgroup': case 'frame': case 'head': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': startTagMisplaced(token); return null; default: return startTagOther(token); } } @override Token processEndTag(EndTagToken token) { switch (token.name) { case 'body': endTagBody(token); return null; case 'html': return endTagHtml(token); case 'address': case 'article': case 'aside': case 'blockquote': case 'button': case 'center': case 'details': case 'dir': case 'div': case 'dl': case 'fieldset': case 'figcaption': case 'figure': case 'footer': case 'header': case 'hgroup': case 'listing': case 'menu': case 'nav': case 'ol': case 'pre': case 'section': case 'summary': case 'ul': endTagBlock(token); return null; case 'form': endTagForm(token); return null; case 'p': endTagP(token); return null; case 'dd': case 'dt': case 'li': endTagListItem(token); return null; // headingElements case 'h1': case 'h2': case 'h3': case 'h4': case 'h5': case 'h6': endTagHeading(token); return null; case 'a': case 'b': case 'big': case 'code': case 'em': case 'font': case 'i': case 'nobr': case 's': case 'small': case 'strike': case 'strong': case 'tt': case 'u': endTagFormatting(token); return null; case 'applet': case 'marquee': case 'object': endTagAppletMarqueeObject(token); return null; case 'br': endTagBr(token); return null; default: endTagOther(token); return null; } } bool isMatchingFormattingElement(Element node1, Element node2) { if (node1.localName != node2.localName || node1.namespaceUri != node2.namespaceUri) { return false; } else if (node1.attributes.length != node2.attributes.length) { return false; } else { for (var key in node1.attributes.keys) { if (node1.attributes[key] != node2.attributes[key]) { return false; } } } return true; } // helper void addFormattingElement(token) { tree.insertElement(token); var element = tree.openElements.last; var matchingElements = []; for (Node node in tree.activeFormattingElements.reversed) { if (node == Marker) { break; } else if (isMatchingFormattingElement(node, element)) { matchingElements.add(node); } } assert(matchingElements.length <= 3); if (matchingElements.length == 3) { tree.activeFormattingElements.remove(matchingElements.last); } tree.activeFormattingElements.add(element); } // the real deal @override bool processEOF() { for (var node in tree.openElements.reversed) { switch (node.localName) { case 'dd': case 'dt': case 'li': case 'p': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': case 'body': case 'html': continue; } parser.parseError(node.sourceSpan, 'expected-closing-tag-but-got-eof'); break; } //Stop parsing return false; } void processSpaceCharactersDropNewline(StringToken token) { // Sometimes (start of <pre>, <listing>, and <textarea> blocks) we // want to drop leading newlines var data = token.data; dropNewline = false; if (data.startsWith('\n')) { var lastOpen = tree.openElements.last; if (const ['pre', 'listing', 'textarea'].contains(lastOpen.localName) && !lastOpen.hasContent()) { data = data.substring(1); } } if (data.isNotEmpty) { tree.reconstructActiveFormattingElements(); tree.insertText(data, token.span); } } @override Token processCharacters(CharactersToken token) { if (token.data == '\u0000') { //The tokenizer should always emit null on its own return null; } tree.reconstructActiveFormattingElements(); tree.insertText(token.data, token.span); if (parser.framesetOK && !allWhitespace(token.data)) { parser.framesetOK = false; } return null; } @override Token processSpaceCharacters(SpaceCharactersToken token) { if (dropNewline) { processSpaceCharactersDropNewline(token); } else { tree.reconstructActiveFormattingElements(); tree.insertText(token.data, token.span); } return null; } Token startTagProcessInHead(StartTagToken token) { return parser._inHeadPhase.processStartTag(token); } void startTagBody(StartTagToken token) { parser.parseError(token.span, 'unexpected-start-tag', {'name': 'body'}); if (tree.openElements.length == 1 || tree.openElements[1].localName != 'body') { assert(parser.innerHTMLMode); } else { parser.framesetOK = false; token.data.forEach((attr, value) { tree.openElements[1].attributes.putIfAbsent(attr, () => value); }); } } void startTagFrameset(StartTagToken token) { parser.parseError(token.span, 'unexpected-start-tag', {'name': 'frameset'}); if ((tree.openElements.length == 1 || tree.openElements[1].localName != 'body')) { assert(parser.innerHTMLMode); } else if (parser.framesetOK) { if (tree.openElements[1].parentNode != null) { tree.openElements[1].parentNode.nodes.remove(tree.openElements[1]); } while (tree.openElements.last.localName != 'html') { tree.openElements.removeLast(); } tree.insertElement(token); parser.phase = parser._inFramesetPhase; } } void startTagCloseP(StartTagToken token) { if (tree.elementInScope('p', variant: 'button')) { endTagP(EndTagToken('p')); } tree.insertElement(token); } void startTagPreListing(StartTagToken token) { if (tree.elementInScope('p', variant: 'button')) { endTagP(EndTagToken('p')); } tree.insertElement(token); parser.framesetOK = false; dropNewline = true; } void startTagForm(StartTagToken token) { if (tree.formPointer != null) { parser.parseError(token.span, 'unexpected-start-tag', {'name': 'form'}); } else { if (tree.elementInScope('p', variant: 'button')) { endTagP(EndTagToken('p')); } tree.insertElement(token); tree.formPointer = tree.openElements.last; } } void startTagListItem(StartTagToken token) { parser.framesetOK = false; final stopNamesMap = const { 'li': ['li'], 'dt': ['dt', 'dd'], 'dd': ['dt', 'dd'] }; var stopNames = stopNamesMap[token.name]; for (var node in tree.openElements.reversed) { if (stopNames.contains(node.localName)) { parser.phase.processEndTag(EndTagToken(node.localName)); break; } if (specialElements.contains(getElementNameTuple(node)) && !const ['address', 'div', 'p'].contains(node.localName)) { break; } } if (tree.elementInScope('p', variant: 'button')) { parser.phase.processEndTag(EndTagToken('p')); } tree.insertElement(token); } void startTagPlaintext(StartTagToken token) { if (tree.elementInScope('p', variant: 'button')) { endTagP(EndTagToken('p')); } tree.insertElement(token); parser.tokenizer.state = parser.tokenizer.plaintextState; } void startTagHeading(StartTagToken token) { if (tree.elementInScope('p', variant: 'button')) { endTagP(EndTagToken('p')); } if (headingElements.contains(tree.openElements.last.localName)) { parser .parseError(token.span, 'unexpected-start-tag', {'name': token.name}); tree.openElements.removeLast(); } tree.insertElement(token); } void startTagA(StartTagToken token) { var afeAElement = tree.elementInActiveFormattingElements('a'); if (afeAElement != null) { parser.parseError(token.span, 'unexpected-start-tag-implies-end-tag', {'startName': 'a', 'endName': 'a'}); endTagFormatting(EndTagToken('a')); tree.openElements.remove(afeAElement); tree.activeFormattingElements.remove(afeAElement); } tree.reconstructActiveFormattingElements(); addFormattingElement(token); } void startTagFormatting(StartTagToken token) { tree.reconstructActiveFormattingElements(); addFormattingElement(token); } void startTagNobr(StartTagToken token) { tree.reconstructActiveFormattingElements(); if (tree.elementInScope('nobr')) { parser.parseError(token.span, 'unexpected-start-tag-implies-end-tag', {'startName': 'nobr', 'endName': 'nobr'}); processEndTag(EndTagToken('nobr')); // XXX Need tests that trigger the following tree.reconstructActiveFormattingElements(); } addFormattingElement(token); } Token startTagButton(StartTagToken token) { if (tree.elementInScope('button')) { parser.parseError(token.span, 'unexpected-start-tag-implies-end-tag', {'startName': 'button', 'endName': 'button'}); processEndTag(EndTagToken('button')); return token; } else { tree.reconstructActiveFormattingElements(); tree.insertElement(token); parser.framesetOK = false; } return null; } void startTagAppletMarqueeObject(StartTagToken token) { tree.reconstructActiveFormattingElements(); tree.insertElement(token); tree.activeFormattingElements.add(Marker); parser.framesetOK = false; } void startTagXmp(StartTagToken token) { if (tree.elementInScope('p', variant: 'button')) { endTagP(EndTagToken('p')); } tree.reconstructActiveFormattingElements(); parser.framesetOK = false; parser.parseRCDataRawtext(token, 'RAWTEXT'); } void startTagTable(StartTagToken token) { if (parser.compatMode != 'quirks') { if (tree.elementInScope('p', variant: 'button')) { processEndTag(EndTagToken('p')); } } tree.insertElement(token); parser.framesetOK = false; parser.phase = parser._inTablePhase; } void startTagVoidFormatting(StartTagToken token) { tree.reconstructActiveFormattingElements(); tree.insertElement(token); tree.openElements.removeLast(); token.selfClosingAcknowledged = true; parser.framesetOK = false; } void startTagInput(StartTagToken token) { var savedFramesetOK = parser.framesetOK; startTagVoidFormatting(token); if (asciiUpper2Lower(token.data['type']) == 'hidden') { //input type=hidden doesn't change framesetOK parser.framesetOK = savedFramesetOK; } } void startTagParamSource(StartTagToken token) { tree.insertElement(token); tree.openElements.removeLast(); token.selfClosingAcknowledged = true; } void startTagHr(StartTagToken token) { if (tree.elementInScope('p', variant: 'button')) { endTagP(EndTagToken('p')); } tree.insertElement(token); tree.openElements.removeLast(); token.selfClosingAcknowledged = true; parser.framesetOK = false; } void startTagImage(StartTagToken token) { // No really... parser.parseError(token.span, 'unexpected-start-tag-treated-as', {'originalName': 'image', 'newName': 'img'}); processStartTag( StartTagToken('img', data: token.data, selfClosing: token.selfClosing)); } void startTagIsIndex(StartTagToken token) { parser.parseError(token.span, 'deprecated-tag', {'name': 'isindex'}); if (tree.formPointer != null) { return; } var formAttrs = <dynamic, String>{}; var dataAction = token.data['action']; if (dataAction != null) { formAttrs['action'] = dataAction; } processStartTag(StartTagToken('form', data: formAttrs)); processStartTag( StartTagToken('hr', data: LinkedHashMap<dynamic, String>())); processStartTag( StartTagToken('label', data: LinkedHashMap<dynamic, String>())); // XXX Localization ... var prompt = token.data['prompt']; prompt ??= 'This is a searchable index. Enter search keywords: '; processCharacters(CharactersToken(prompt)); var attributes = LinkedHashMap<dynamic, String>.from(token.data); attributes.remove('action'); attributes.remove('prompt'); attributes['name'] = 'isindex'; processStartTag(StartTagToken('input', data: attributes, selfClosing: token.selfClosing)); processEndTag(EndTagToken('label')); processStartTag( StartTagToken('hr', data: LinkedHashMap<dynamic, String>())); processEndTag(EndTagToken('form')); } void startTagTextarea(StartTagToken token) { tree.insertElement(token); parser.tokenizer.state = parser.tokenizer.rcdataState; dropNewline = true; parser.framesetOK = false; } void startTagIFrame(StartTagToken token) { parser.framesetOK = false; startTagRawtext(token); } /// iframe, noembed noframes, noscript(if scripting enabled). void startTagRawtext(StartTagToken token) { parser.parseRCDataRawtext(token, 'RAWTEXT'); } void startTagOpt(StartTagToken token) { if (tree.openElements.last.localName == 'option') { parser.phase.processEndTag(EndTagToken('option')); } tree.reconstructActiveFormattingElements(); parser.tree.insertElement(token); } void startTagSelect(StartTagToken token) { tree.reconstructActiveFormattingElements(); tree.insertElement(token); parser.framesetOK = false; if (parser._inTablePhase == parser.phase || parser._inCaptionPhase == parser.phase || parser._inColumnGroupPhase == parser.phase || parser._inTableBodyPhase == parser.phase || parser._inRowPhase == parser.phase || parser._inCellPhase == parser.phase) { parser.phase = parser._inSelectInTablePhase; } else { parser.phase = parser._inSelectPhase; } } void startTagRpRt(StartTagToken token) { if (tree.elementInScope('ruby')) { tree.generateImpliedEndTags(); var last = tree.openElements.last; if (last.localName != 'ruby') { parser.parseError(last.sourceSpan, 'undefined-error'); } } tree.insertElement(token); } void startTagMath(StartTagToken token) { tree.reconstructActiveFormattingElements(); parser.adjustMathMLAttributes(token); parser.adjustForeignAttributes(token); token.namespace = Namespaces.mathml; tree.insertElement(token); //Need to get the parse error right for the case where the token //has a namespace not equal to the xmlns attribute if (token.selfClosing) { tree.openElements.removeLast(); token.selfClosingAcknowledged = true; } } void startTagSvg(StartTagToken token) { tree.reconstructActiveFormattingElements(); parser.adjustSVGAttributes(token); parser.adjustForeignAttributes(token); token.namespace = Namespaces.svg; tree.insertElement(token); //Need to get the parse error right for the case where the token //has a namespace not equal to the xmlns attribute if (token.selfClosing) { tree.openElements.removeLast(); token.selfClosingAcknowledged = true; } } /// Elements that should be children of other elements that have a /// different insertion mode; here they are ignored /// "caption", "col", "colgroup", "frame", "frameset", "head", /// "option", "optgroup", "tbody", "td", "tfoot", "th", "thead", /// "tr", "noscript" void startTagMisplaced(StartTagToken token) { parser.parseError( token.span, 'unexpected-start-tag-ignored', {'name': token.name}); } Token startTagOther(StartTagToken token) { tree.reconstructActiveFormattingElements(); tree.insertElement(token); return null; } void endTagP(EndTagToken token) { if (!tree.elementInScope('p', variant: 'button')) { startTagCloseP( StartTagToken('p', data: LinkedHashMap<dynamic, String>())); parser.parseError(token.span, 'unexpected-end-tag', {'name': 'p'}); endTagP(EndTagToken('p')); } else { tree.generateImpliedEndTags('p'); if (tree.openElements.last.localName != 'p') { parser.parseError(token.span, 'unexpected-end-tag', {'name': 'p'}); } popOpenElementsUntil(token); } } void endTagBody(EndTagToken token) { if (!tree.elementInScope('body')) { parser.parseError(token.span, 'undefined-error'); return; } else if (tree.openElements.last.localName == 'body') { tree.openElements.last.endSourceSpan = token.span; } else { for (var node in slice(tree.openElements, 2)) { switch (node.localName) { case 'dd': case 'dt': case 'li': case 'optgroup': case 'option': case 'p': case 'rp': case 'rt': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': case 'body': case 'html': continue; } // Not sure this is the correct name for the parse error parser.parseError(token.span, 'expected-one-end-tag-but-got-another', {'gotName': 'body', 'expectedName': node.localName}); break; } } parser.phase = parser._afterBodyPhase; } Token endTagHtml(EndTagToken token) { //We repeat the test for the body end tag token being ignored here if (tree.elementInScope('body')) { endTagBody(EndTagToken('body')); return token; } return null; } void endTagBlock(EndTagToken token) { //Put us back in the right whitespace handling mode if (token.name == 'pre') { dropNewline = false; } var inScope = tree.elementInScope(token.name); if (inScope) { tree.generateImpliedEndTags(); } if (tree.openElements.last.localName != token.name) { parser.parseError(token.span, 'end-tag-too-early', {'name': token.name}); } if (inScope) { popOpenElementsUntil(token); } } void endTagForm(EndTagToken token) { var node = tree.formPointer; tree.formPointer = null; if (node == null || !tree.elementInScope(node)) { parser.parseError(token.span, 'unexpected-end-tag', {'name': 'form'}); } else { tree.generateImpliedEndTags(); if (tree.openElements.last != node) { parser.parseError( token.span, 'end-tag-too-early-ignored', {'name': 'form'}); } tree.openElements.remove(node); node.endSourceSpan = token.span; } } void endTagListItem(EndTagToken token) { String variant; if (token.name == 'li') { variant = 'list'; } else { variant = null; } if (!tree.elementInScope(token.name, variant: variant)) { parser.parseError(token.span, 'unexpected-end-tag', {'name': token.name}); } else { tree.generateImpliedEndTags(token.name); if (tree.openElements.last.localName != token.name) { parser .parseError(token.span, 'end-tag-too-early', {'name': token.name}); } popOpenElementsUntil(token); } } void endTagHeading(EndTagToken token) { for (var item in headingElements) { if (tree.elementInScope(item)) { tree.generateImpliedEndTags(); break; } } if (tree.openElements.last.localName != token.name) { parser.parseError(token.span, 'end-tag-too-early', {'name': token.name}); } for (var item in headingElements) { if (tree.elementInScope(item)) { var node = tree.openElements.removeLast(); while (!headingElements.contains(node.localName)) { node = tree.openElements.removeLast(); } if (node != null) { node.endSourceSpan = token.span; } break; } } } /// The much-feared adoption agency algorithm. void endTagFormatting(EndTagToken token) { // http://www.whatwg.org/specs/web-apps/current-work/multipage/tree-construction.html#adoptionAgency // TODO(jmesserly): the comments here don't match the numbered steps in the // updated spec. This needs a pass over it to verify that it still matches. // In particular the html5lib Python code skiped "step 4", I'm not sure why. // XXX Better parseError messages appreciated. var outerLoopCounter = 0; while (outerLoopCounter < 8) { outerLoopCounter += 1; // Step 1 paragraph 1 var formattingElement = tree.elementInActiveFormattingElements(token.name); if (formattingElement == null || (tree.openElements.contains(formattingElement) && !tree.elementInScope(formattingElement.localName))) { parser.parseError( token.span, 'adoption-agency-1.1', {'name': token.name}); return; // Step 1 paragraph 2 } else if (!tree.openElements.contains(formattingElement)) { parser.parseError( token.span, 'adoption-agency-1.2', {'name': token.name}); tree.activeFormattingElements.remove(formattingElement); return; } // Step 1 paragraph 3 if (formattingElement != tree.openElements.last) { parser.parseError( token.span, 'adoption-agency-1.3', {'name': token.name}); } // Step 2 // Start of the adoption agency algorithm proper var afeIndex = tree.openElements.indexOf(formattingElement); Node furthestBlock; for (var element in slice(tree.openElements, afeIndex)) { if (specialElements.contains(getElementNameTuple(element))) { furthestBlock = element; break; } } // Step 3 if (furthestBlock == null) { var element = tree.openElements.removeLast(); while (element != formattingElement) { element = tree.openElements.removeLast(); } if (element != null) { element.endSourceSpan = token.span; } tree.activeFormattingElements.remove(element); return; } var commonAncestor = tree.openElements[afeIndex - 1]; // Step 5 // The bookmark is supposed to help us identify where to reinsert // nodes in step 12. We have to ensure that we reinsert nodes after // the node before the active formatting element. Note the bookmark // can move in step 7.4 var bookmark = tree.activeFormattingElements.indexOf(formattingElement); // Step 6 var lastNode = furthestBlock; var node = furthestBlock; var innerLoopCounter = 0; var index = tree.openElements.indexOf(node); while (innerLoopCounter < 3) { innerLoopCounter += 1; // Node is element before node in open elements index -= 1; node = tree.openElements[index]; if (!tree.activeFormattingElements.contains(node)) { tree.openElements.remove(node); continue; } // Step 6.3 if (node == formattingElement) { break; } // Step 6.4 if (lastNode == furthestBlock) { bookmark = (tree.activeFormattingElements.indexOf(node) + 1); } // Step 6.5 //cite = node.parent var clone = node.clone(false); // Replace node with clone tree.activeFormattingElements[ tree.activeFormattingElements.indexOf(node)] = clone; tree.openElements[tree.openElements.indexOf(node)] = clone; node = clone; // Step 6.6 // Remove lastNode from its parents, if any if (lastNode.parentNode != null) { lastNode.parentNode.nodes.remove(lastNode); } node.nodes.add(lastNode); // Step 7.7 lastNode = node; // End of inner loop } // Step 7 // Foster parent lastNode if commonAncestor is a // table, tbody, tfoot, thead, or tr we need to foster parent the // lastNode if (lastNode.parentNode != null) { lastNode.parentNode.nodes.remove(lastNode); } if (const ['table', 'tbody', 'tfoot', 'thead', 'tr'] .contains(commonAncestor.localName)) { var nodePos = tree.getTableMisnestedNodePosition(); nodePos[0].insertBefore(lastNode, nodePos[1]); } else { commonAncestor.nodes.add(lastNode); } // Step 8 var clone = formattingElement.clone(false); // Step 9 furthestBlock.reparentChildren(clone); // Step 10 furthestBlock.nodes.add(clone); // Step 11 tree.activeFormattingElements.remove(formattingElement); tree.activeFormattingElements .insert(min(bookmark, tree.activeFormattingElements.length), clone); // Step 12 tree.openElements.remove(formattingElement); tree.openElements .insert(tree.openElements.indexOf(furthestBlock) + 1, clone); } } void endTagAppletMarqueeObject(EndTagToken token) { if (tree.elementInScope(token.name)) { tree.generateImpliedEndTags(); } if (tree.openElements.last.localName != token.name) { parser.parseError(token.span, 'end-tag-too-early', {'name': token.name}); } if (tree.elementInScope(token.name)) { popOpenElementsUntil(token); tree.clearActiveFormattingElements(); } } void endTagBr(EndTagToken token) { parser.parseError(token.span, 'unexpected-end-tag-treated-as', {'originalName': 'br', 'newName': 'br element'}); tree.reconstructActiveFormattingElements(); tree.insertElement( StartTagToken('br', data: LinkedHashMap<dynamic, String>())); tree.openElements.removeLast(); } void endTagOther(EndTagToken token) { for (var node in tree.openElements.reversed) { if (node.localName == token.name) { tree.generateImpliedEndTags(token.name); if (tree.openElements.last.localName != token.name) { parser.parseError( token.span, 'unexpected-end-tag', {'name': token.name}); } while (tree.openElements.removeLast() != node) { // noop } node.endSourceSpan = token.span; break; } else { if (specialElements.contains(getElementNameTuple(node))) { parser.parseError( token.span, 'unexpected-end-tag', {'name': token.name}); break; } } } } } class TextPhase extends Phase { TextPhase(parser) : super(parser); // "Tried to process start tag %s in RCDATA/RAWTEXT mode"%token.name @override // ignore: missing_return Token processStartTag(StartTagToken token) { assert(false); } @override Token processEndTag(EndTagToken token) { if (token.name == 'script') { endTagScript(token); return null; } endTagOther(token); return null; } @override Token processCharacters(CharactersToken token) { tree.insertText(token.data, token.span); return null; } @override bool processEOF() { var last = tree.openElements.last; parser.parseError(last.sourceSpan, 'expected-named-closing-tag-but-got-eof', {'name': last.localName}); tree.openElements.removeLast(); parser.phase = parser.originalPhase; return true; } void endTagScript(EndTagToken token) { var node = tree.openElements.removeLast(); assert(node.localName == 'script'); parser.phase = parser.originalPhase; //The rest of this method is all stuff that only happens if //document.write works } void endTagOther(EndTagToken token) { tree.openElements.removeLast(); parser.phase = parser.originalPhase; } } class InTablePhase extends Phase { // http://www.whatwg.org/specs/web-apps/current-work///in-table InTablePhase(parser) : super(parser); @override Token processStartTag(StartTagToken token) { switch (token.name) { case 'html': return startTagHtml(token); case 'caption': startTagCaption(token); return null; case 'colgroup': startTagColgroup(token); return null; case 'col': return startTagCol(token); case 'tbody': case 'tfoot': case 'thead': startTagRowGroup(token); return null; case 'td': case 'th': case 'tr': return startTagImplyTbody(token); case 'table': return startTagTable(token); case 'style': case 'script': return startTagStyleScript(token); case 'input': startTagInput(token); return null; case 'form': startTagForm(token); return null; default: startTagOther(token); return null; } } @override Token processEndTag(EndTagToken token) { switch (token.name) { case 'table': endTagTable(token); return null; case 'body': case 'caption': case 'col': case 'colgroup': case 'html': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': endTagIgnore(token); return null; default: endTagOther(token); return null; } } // helper methods void clearStackToTableContext() { // 'clear the stack back to a table context' while (tree.openElements.last.localName != 'table' && tree.openElements.last.localName != 'html') { //parser.parseError(token.span, "unexpected-implied-end-tag-in-table", // {"name": tree.openElements.last.name}) tree.openElements.removeLast(); } // When the current node is <html> it's an innerHTML case } // processing methods @override bool processEOF() { var last = tree.openElements.last; if (last.localName != 'html') { parser.parseError(last.sourceSpan, 'eof-in-table'); } else { assert(parser.innerHTMLMode); } //Stop parsing return false; } @override Token processSpaceCharacters(SpaceCharactersToken token) { var originalPhase = parser.phase; parser.phase = parser._inTableTextPhase; parser._inTableTextPhase.originalPhase = originalPhase; parser.phase.processSpaceCharacters(token); return null; } @override Token processCharacters(CharactersToken token) { var originalPhase = parser.phase; parser.phase = parser._inTableTextPhase; parser._inTableTextPhase.originalPhase = originalPhase; parser.phase.processCharacters(token); return null; } void insertText(CharactersToken token) { // If we get here there must be at least one non-whitespace character // Do the table magic! tree.insertFromTable = true; parser._inBodyPhase.processCharacters(token); tree.insertFromTable = false; } void startTagCaption(StartTagToken token) { clearStackToTableContext(); tree.activeFormattingElements.add(Marker); tree.insertElement(token); parser.phase = parser._inCaptionPhase; } void startTagColgroup(StartTagToken token) { clearStackToTableContext(); tree.insertElement(token); parser.phase = parser._inColumnGroupPhase; } Token startTagCol(StartTagToken token) { startTagColgroup( StartTagToken('colgroup', data: LinkedHashMap<dynamic, String>())); return token; } void startTagRowGroup(StartTagToken token) { clearStackToTableContext(); tree.insertElement(token); parser.phase = parser._inTableBodyPhase; } Token startTagImplyTbody(StartTagToken token) { startTagRowGroup( StartTagToken('tbody', data: LinkedHashMap<dynamic, String>())); return token; } Token startTagTable(StartTagToken token) { parser.parseError(token.span, 'unexpected-start-tag-implies-end-tag', {'startName': 'table', 'endName': 'table'}); parser.phase.processEndTag(EndTagToken('table')); if (!parser.innerHTMLMode) { return token; } return null; } Token startTagStyleScript(StartTagToken token) { return parser._inHeadPhase.processStartTag(token); } void startTagInput(StartTagToken token) { if (asciiUpper2Lower(token.data['type']) == 'hidden') { parser.parseError(token.span, 'unexpected-hidden-input-in-table'); tree.insertElement(token); // XXX associate with form tree.openElements.removeLast(); } else { startTagOther(token); } } void startTagForm(StartTagToken token) { parser.parseError(token.span, 'unexpected-form-in-table'); if (tree.formPointer == null) { tree.insertElement(token); tree.formPointer = tree.openElements.last; tree.openElements.removeLast(); } } void startTagOther(StartTagToken token) { parser.parseError(token.span, 'unexpected-start-tag-implies-table-voodoo', {'name': token.name}); // Do the table magic! tree.insertFromTable = true; parser._inBodyPhase.processStartTag(token); tree.insertFromTable = false; } void endTagTable(EndTagToken token) { if (tree.elementInScope('table', variant: 'table')) { tree.generateImpliedEndTags(); var last = tree.openElements.last; if (last.localName != 'table') { parser.parseError(token.span, 'end-tag-too-early-named', {'gotName': 'table', 'expectedName': last.localName}); } while (tree.openElements.last.localName != 'table') { tree.openElements.removeLast(); } var node = tree.openElements.removeLast(); node.endSourceSpan = token.span; parser.resetInsertionMode(); } else { // innerHTML case assert(parser.innerHTMLMode); parser.parseError(token.span, 'undefined-error'); } } void endTagIgnore(EndTagToken token) { parser.parseError(token.span, 'unexpected-end-tag', {'name': token.name}); } void endTagOther(EndTagToken token) { parser.parseError(token.span, 'unexpected-end-tag-implies-table-voodoo', {'name': token.name}); // Do the table magic! tree.insertFromTable = true; parser._inBodyPhase.processEndTag(token); tree.insertFromTable = false; } } class InTableTextPhase extends Phase { Phase originalPhase; List<StringToken> characterTokens; InTableTextPhase(HtmlParser parser) : characterTokens = <StringToken>[], super(parser); void flushCharacters() { if (characterTokens.isEmpty) return; // TODO(sigmund,jmesserly): remove '' (dartbug.com/8480) var data = characterTokens.map((t) => t.data).join(''); FileSpan span; if (parser.generateSpans) { span = characterTokens[0].span.expand(characterTokens.last.span); } if (!allWhitespace(data)) { parser._inTablePhase.insertText(CharactersToken(data)..span = span); } else if (data.isNotEmpty) { tree.insertText(data, span); } characterTokens = <StringToken>[]; } @override Token processComment(CommentToken token) { flushCharacters(); parser.phase = originalPhase; return token; } @override bool processEOF() { flushCharacters(); parser.phase = originalPhase; return true; } @override Token processCharacters(CharactersToken token) { if (token.data == '\u0000') { return null; } characterTokens.add(token); return null; } @override Token processSpaceCharacters(SpaceCharactersToken token) { //pretty sure we should never reach here characterTokens.add(token); // XXX assert(false); return null; } @override Token processStartTag(StartTagToken token) { flushCharacters(); parser.phase = originalPhase; return token; } @override Token processEndTag(EndTagToken token) { flushCharacters(); parser.phase = originalPhase; return token; } } class InCaptionPhase extends Phase { // http://www.whatwg.org/specs/web-apps/current-work///in-caption InCaptionPhase(parser) : super(parser); @override Token processStartTag(StartTagToken token) { switch (token.name) { case 'html': return startTagHtml(token); case 'caption': case 'col': case 'colgroup': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': return startTagTableElement(token); default: return startTagOther(token); } } @override Token processEndTag(EndTagToken token) { switch (token.name) { case 'caption': endTagCaption(token); return null; case 'table': return endTagTable(token); case 'body': case 'col': case 'colgroup': case 'html': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': endTagIgnore(token); return null; default: return endTagOther(token); } } bool ignoreEndTagCaption() { return !tree.elementInScope('caption', variant: 'table'); } @override bool processEOF() { parser._inBodyPhase.processEOF(); return false; } @override Token processCharacters(CharactersToken token) { return parser._inBodyPhase.processCharacters(token); } Token startTagTableElement(StartTagToken token) { parser.parseError(token.span, 'undefined-error'); //XXX Have to duplicate logic here to find out if the tag is ignored var ignoreEndTag = ignoreEndTagCaption(); parser.phase.processEndTag(EndTagToken('caption')); if (!ignoreEndTag) { return token; } return null; } Token startTagOther(StartTagToken token) { return parser._inBodyPhase.processStartTag(token); } void endTagCaption(EndTagToken token) { if (!ignoreEndTagCaption()) { // AT this code is quite similar to endTagTable in "InTable" tree.generateImpliedEndTags(); if (tree.openElements.last.localName != 'caption') { parser.parseError(token.span, 'expected-one-end-tag-but-got-another', { 'gotName': 'caption', 'expectedName': tree.openElements.last.localName }); } while (tree.openElements.last.localName != 'caption') { tree.openElements.removeLast(); } var node = tree.openElements.removeLast(); node.endSourceSpan = token.span; tree.clearActiveFormattingElements(); parser.phase = parser._inTablePhase; } else { // innerHTML case assert(parser.innerHTMLMode); parser.parseError(token.span, 'undefined-error'); } } Token endTagTable(EndTagToken token) { parser.parseError(token.span, 'undefined-error'); var ignoreEndTag = ignoreEndTagCaption(); parser.phase.processEndTag(EndTagToken('caption')); if (!ignoreEndTag) { return token; } return null; } void endTagIgnore(EndTagToken token) { parser.parseError(token.span, 'unexpected-end-tag', {'name': token.name}); } Token endTagOther(EndTagToken token) { return parser._inBodyPhase.processEndTag(token); } } class InColumnGroupPhase extends Phase { // http://www.whatwg.org/specs/web-apps/current-work///in-column InColumnGroupPhase(parser) : super(parser); @override Token processStartTag(StartTagToken token) { switch (token.name) { case 'html': return startTagHtml(token); case 'col': startTagCol(token); return null; default: return startTagOther(token); } } @override Token processEndTag(EndTagToken token) { switch (token.name) { case 'colgroup': endTagColgroup(token); return null; case 'col': endTagCol(token); return null; default: return endTagOther(token); } } bool ignoreEndTagColgroup() { return tree.openElements.last.localName == 'html'; } @override bool processEOF() { var ignoreEndTag = ignoreEndTagColgroup(); if (ignoreEndTag) { assert(parser.innerHTMLMode); return false; } else { endTagColgroup(EndTagToken('colgroup')); return true; } } @override Token processCharacters(CharactersToken token) { var ignoreEndTag = ignoreEndTagColgroup(); endTagColgroup(EndTagToken('colgroup')); return ignoreEndTag ? null : token; } void startTagCol(StartTagToken token) { tree.insertElement(token); tree.openElements.removeLast(); } Token startTagOther(StartTagToken token) { var ignoreEndTag = ignoreEndTagColgroup(); endTagColgroup(EndTagToken('colgroup')); return ignoreEndTag ? null : token; } void endTagColgroup(EndTagToken token) { if (ignoreEndTagColgroup()) { // innerHTML case assert(parser.innerHTMLMode); parser.parseError(token.span, 'undefined-error'); } else { var node = tree.openElements.removeLast(); node.endSourceSpan = token.span; parser.phase = parser._inTablePhase; } } void endTagCol(EndTagToken token) { parser.parseError(token.span, 'no-end-tag', {'name': 'col'}); } Token endTagOther(EndTagToken token) { var ignoreEndTag = ignoreEndTagColgroup(); endTagColgroup(EndTagToken('colgroup')); return ignoreEndTag ? null : token; } } class InTableBodyPhase extends Phase { // http://www.whatwg.org/specs/web-apps/current-work///in-table0 InTableBodyPhase(parser) : super(parser); @override Token processStartTag(StartTagToken token) { switch (token.name) { case 'html': return startTagHtml(token); case 'tr': startTagTr(token); return null; case 'td': case 'th': return startTagTableCell(token); case 'caption': case 'col': case 'colgroup': case 'tbody': case 'tfoot': case 'thead': return startTagTableOther(token); default: return startTagOther(token); } } @override Token processEndTag(EndTagToken token) { switch (token.name) { case 'tbody': case 'tfoot': case 'thead': endTagTableRowGroup(token); return null; case 'table': return endTagTable(token); case 'body': case 'caption': case 'col': case 'colgroup': case 'html': case 'td': case 'th': case 'tr': endTagIgnore(token); return null; default: return endTagOther(token); } } // helper methods void clearStackToTableBodyContext() { var tableTags = const ['tbody', 'tfoot', 'thead', 'html']; while (!tableTags.contains(tree.openElements.last.localName)) { //XXX parser.parseError(token.span, "unexpected-implied-end-tag-in-table", // {"name": tree.openElements.last.name}) tree.openElements.removeLast(); } if (tree.openElements.last.localName == 'html') { assert(parser.innerHTMLMode); } } // the rest @override bool processEOF() { parser._inTablePhase.processEOF(); return false; } @override Token processSpaceCharacters(SpaceCharactersToken token) { return parser._inTablePhase.processSpaceCharacters(token); } @override Token processCharacters(CharactersToken token) { return parser._inTablePhase.processCharacters(token); } void startTagTr(StartTagToken token) { clearStackToTableBodyContext(); tree.insertElement(token); parser.phase = parser._inRowPhase; } Token startTagTableCell(StartTagToken token) { parser.parseError( token.span, 'unexpected-cell-in-table-body', {'name': token.name}); startTagTr(StartTagToken('tr', data: LinkedHashMap<dynamic, String>())); return token; } Token startTagTableOther(token) => endTagTable(token); Token startTagOther(StartTagToken token) { return parser._inTablePhase.processStartTag(token); } void endTagTableRowGroup(EndTagToken token) { if (tree.elementInScope(token.name, variant: 'table')) { clearStackToTableBodyContext(); var node = tree.openElements.removeLast(); node.endSourceSpan = token.span; parser.phase = parser._inTablePhase; } else { parser.parseError( token.span, 'unexpected-end-tag-in-table-body', {'name': token.name}); } } Token endTagTable(TagToken token) { // XXX AT Any ideas on how to share this with endTagTable? if (tree.elementInScope('tbody', variant: 'table') || tree.elementInScope('thead', variant: 'table') || tree.elementInScope('tfoot', variant: 'table')) { clearStackToTableBodyContext(); endTagTableRowGroup(EndTagToken(tree.openElements.last.localName)); return token; } else { // innerHTML case assert(parser.innerHTMLMode); parser.parseError(token.span, 'undefined-error'); } return null; } void endTagIgnore(EndTagToken token) { parser.parseError( token.span, 'unexpected-end-tag-in-table-body', {'name': token.name}); } Token endTagOther(EndTagToken token) { return parser._inTablePhase.processEndTag(token); } } class InRowPhase extends Phase { // http://www.whatwg.org/specs/web-apps/current-work///in-row InRowPhase(parser) : super(parser); @override Token processStartTag(StartTagToken token) { switch (token.name) { case 'html': return startTagHtml(token); case 'td': case 'th': startTagTableCell(token); return null; case 'caption': case 'col': case 'colgroup': case 'tbody': case 'tfoot': case 'thead': case 'tr': return startTagTableOther(token); default: return startTagOther(token); } } @override Token processEndTag(EndTagToken token) { switch (token.name) { case 'tr': endTagTr(token); return null; case 'table': return endTagTable(token); case 'tbody': case 'tfoot': case 'thead': return endTagTableRowGroup(token); case 'body': case 'caption': case 'col': case 'colgroup': case 'html': case 'td': case 'th': endTagIgnore(token); return null; default: return endTagOther(token); } } // helper methods (XXX unify this with other table helper methods) void clearStackToTableRowContext() { while (true) { var last = tree.openElements.last; if (last.localName == 'tr' || last.localName == 'html') break; parser.parseError( last.sourceSpan, 'unexpected-implied-end-tag-in-table-row', {'name': tree.openElements.last.localName}); tree.openElements.removeLast(); } } bool ignoreEndTagTr() { return !tree.elementInScope('tr', variant: 'table'); } // the rest @override bool processEOF() { parser._inTablePhase.processEOF(); return false; } @override Token processSpaceCharacters(SpaceCharactersToken token) { return parser._inTablePhase.processSpaceCharacters(token); } @override Token processCharacters(CharactersToken token) { return parser._inTablePhase.processCharacters(token); } void startTagTableCell(StartTagToken token) { clearStackToTableRowContext(); tree.insertElement(token); parser.phase = parser._inCellPhase; tree.activeFormattingElements.add(Marker); } Token startTagTableOther(StartTagToken token) { var ignoreEndTag = ignoreEndTagTr(); endTagTr(EndTagToken('tr')); // XXX how are we sure it's always ignored in the innerHTML case? return ignoreEndTag ? null : token; } Token startTagOther(StartTagToken token) { return parser._inTablePhase.processStartTag(token); } void endTagTr(EndTagToken token) { if (!ignoreEndTagTr()) { clearStackToTableRowContext(); var node = tree.openElements.removeLast(); node.endSourceSpan = token.span; parser.phase = parser._inTableBodyPhase; } else { // innerHTML case assert(parser.innerHTMLMode); parser.parseError(token.span, 'undefined-error'); } } Token endTagTable(EndTagToken token) { var ignoreEndTag = ignoreEndTagTr(); endTagTr(EndTagToken('tr')); // Reprocess the current tag if the tr end tag was not ignored // XXX how are we sure it's always ignored in the innerHTML case? return ignoreEndTag ? null : token; } Token endTagTableRowGroup(EndTagToken token) { if (tree.elementInScope(token.name, variant: 'table')) { endTagTr(EndTagToken('tr')); return token; } else { parser.parseError(token.span, 'undefined-error'); return null; } } void endTagIgnore(EndTagToken token) { parser.parseError( token.span, 'unexpected-end-tag-in-table-row', {'name': token.name}); } Token endTagOther(EndTagToken token) { return parser._inTablePhase.processEndTag(token); } } class InCellPhase extends Phase { // http://www.whatwg.org/specs/web-apps/current-work///in-cell InCellPhase(parser) : super(parser); @override Token processStartTag(StartTagToken token) { switch (token.name) { case 'html': return startTagHtml(token); case 'caption': case 'col': case 'colgroup': case 'tbody': case 'td': case 'tfoot': case 'th': case 'thead': case 'tr': return startTagTableOther(token); default: return startTagOther(token); } } @override Token processEndTag(EndTagToken token) { switch (token.name) { case 'td': case 'th': endTagTableCell(token); return null; case 'body': case 'caption': case 'col': case 'colgroup': case 'html': endTagIgnore(token); return null; case 'table': case 'tbody': case 'tfoot': case 'thead': case 'tr': return endTagImply(token); default: return endTagOther(token); } } // helper void closeCell() { if (tree.elementInScope('td', variant: 'table')) { endTagTableCell(EndTagToken('td')); } else if (tree.elementInScope('th', variant: 'table')) { endTagTableCell(EndTagToken('th')); } } // the rest @override bool processEOF() { parser._inBodyPhase.processEOF(); return false; } @override Token processCharacters(CharactersToken token) { return parser._inBodyPhase.processCharacters(token); } Token startTagTableOther(StartTagToken token) { if (tree.elementInScope('td', variant: 'table') || tree.elementInScope('th', variant: 'table')) { closeCell(); return token; } else { // innerHTML case assert(parser.innerHTMLMode); parser.parseError(token.span, 'undefined-error'); return null; } } Token startTagOther(StartTagToken token) { return parser._inBodyPhase.processStartTag(token); } void endTagTableCell(EndTagToken token) { if (tree.elementInScope(token.name, variant: 'table')) { tree.generateImpliedEndTags(token.name); if (tree.openElements.last.localName != token.name) { parser.parseError( token.span, 'unexpected-cell-end-tag', {'name': token.name}); popOpenElementsUntil(token); } else { var node = tree.openElements.removeLast(); node.endSourceSpan = token.span; } tree.clearActiveFormattingElements(); parser.phase = parser._inRowPhase; } else { parser.parseError(token.span, 'unexpected-end-tag', {'name': token.name}); } } void endTagIgnore(EndTagToken token) { parser.parseError(token.span, 'unexpected-end-tag', {'name': token.name}); } Token endTagImply(EndTagToken token) { if (tree.elementInScope(token.name, variant: 'table')) { closeCell(); return token; } else { // sometimes innerHTML case parser.parseError(token.span, 'undefined-error'); } return null; } Token endTagOther(EndTagToken token) { return parser._inBodyPhase.processEndTag(token); } } class InSelectPhase extends Phase { InSelectPhase(parser) : super(parser); @override Token processStartTag(StartTagToken token) { switch (token.name) { case 'html': return startTagHtml(token); case 'option': startTagOption(token); return null; case 'optgroup': startTagOptgroup(token); return null; case 'select': startTagSelect(token); return null; case 'input': case 'keygen': case 'textarea': return startTagInput(token); case 'script': return startTagScript(token); default: return startTagOther(token); } } @override Token processEndTag(EndTagToken token) { switch (token.name) { case 'option': endTagOption(token); return null; case 'optgroup': endTagOptgroup(token); return null; case 'select': endTagSelect(token); return null; default: endTagOther(token); return null; } } // http://www.whatwg.org/specs/web-apps/current-work///in-select @override bool processEOF() { var last = tree.openElements.last; if (last.localName != 'html') { parser.parseError(last.sourceSpan, 'eof-in-select'); } else { assert(parser.innerHTMLMode); } return false; } @override Token processCharacters(CharactersToken token) { if (token.data == '\u0000') { return null; } tree.insertText(token.data, token.span); return null; } void startTagOption(StartTagToken token) { // We need to imply </option> if <option> is the current node. if (tree.openElements.last.localName == 'option') { tree.openElements.removeLast(); } tree.insertElement(token); } void startTagOptgroup(StartTagToken token) { if (tree.openElements.last.localName == 'option') { tree.openElements.removeLast(); } if (tree.openElements.last.localName == 'optgroup') { tree.openElements.removeLast(); } tree.insertElement(token); } void startTagSelect(StartTagToken token) { parser.parseError(token.span, 'unexpected-select-in-select'); endTagSelect(EndTagToken('select')); } Token startTagInput(StartTagToken token) { parser.parseError(token.span, 'unexpected-input-in-select'); if (tree.elementInScope('select', variant: 'select')) { endTagSelect(EndTagToken('select')); return token; } else { assert(parser.innerHTMLMode); } return null; } Token startTagScript(StartTagToken token) { return parser._inHeadPhase.processStartTag(token); } Token startTagOther(StartTagToken token) { parser.parseError( token.span, 'unexpected-start-tag-in-select', {'name': token.name}); return null; } void endTagOption(EndTagToken token) { if (tree.openElements.last.localName == 'option') { var node = tree.openElements.removeLast(); node.endSourceSpan = token.span; } else { parser.parseError( token.span, 'unexpected-end-tag-in-select', {'name': 'option'}); } } void endTagOptgroup(EndTagToken token) { // </optgroup> implicitly closes <option> if (tree.openElements.last.localName == 'option' && tree.openElements[tree.openElements.length - 2].localName == 'optgroup') { tree.openElements.removeLast(); } // It also closes </optgroup> if (tree.openElements.last.localName == 'optgroup') { var node = tree.openElements.removeLast(); node.endSourceSpan = token.span; // But nothing else } else { parser.parseError( token.span, 'unexpected-end-tag-in-select', {'name': 'optgroup'}); } } void endTagSelect(EndTagToken token) { if (tree.elementInScope('select', variant: 'select')) { popOpenElementsUntil(token); parser.resetInsertionMode(); } else { // innerHTML case assert(parser.innerHTMLMode); parser.parseError(token.span, 'undefined-error'); } } void endTagOther(EndTagToken token) { parser.parseError( token.span, 'unexpected-end-tag-in-select', {'name': token.name}); } } class InSelectInTablePhase extends Phase { InSelectInTablePhase(parser) : super(parser); @override Token processStartTag(StartTagToken token) { switch (token.name) { case 'caption': case 'table': case 'tbody': case 'tfoot': case 'thead': case 'tr': case 'td': case 'th': return startTagTable(token); default: return startTagOther(token); } } @override Token processEndTag(EndTagToken token) { switch (token.name) { case 'caption': case 'table': case 'tbody': case 'tfoot': case 'thead': case 'tr': case 'td': case 'th': return endTagTable(token); default: return endTagOther(token); } } @override bool processEOF() { parser._inSelectPhase.processEOF(); return false; } @override Token processCharacters(CharactersToken token) { return parser._inSelectPhase.processCharacters(token); } Token startTagTable(StartTagToken token) { parser.parseError( token.span, 'unexpected-table-element-start-tag-in-select-in-table', {'name': token.name}); endTagOther(EndTagToken('select')); return token; } Token startTagOther(StartTagToken token) { return parser._inSelectPhase.processStartTag(token); } Token endTagTable(EndTagToken token) { parser.parseError( token.span, 'unexpected-table-element-end-tag-in-select-in-table', {'name': token.name}); if (tree.elementInScope(token.name, variant: 'table')) { endTagOther(EndTagToken('select')); return token; } return null; } Token endTagOther(EndTagToken token) { return parser._inSelectPhase.processEndTag(token); } } class InForeignContentPhase extends Phase { // TODO(jmesserly): this is sorted so we could binary search. static const breakoutElements = [ 'b', 'big', 'blockquote', 'body', 'br', 'center', 'code', 'dd', 'div', 'dl', 'dt', 'em', 'embed', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'hr', 'i', 'img', 'li', 'listing', 'menu', 'meta', 'nobr', 'ol', 'p', 'pre', 'ruby', 's', 'small', 'span', 'strike', 'strong', 'sub', 'sup', 'table', 'tt', 'u', 'ul', 'var' ]; InForeignContentPhase(parser) : super(parser); void adjustSVGTagNames(token) { final replacements = const { 'altglyph': 'altGlyph', 'altglyphdef': 'altGlyphDef', 'altglyphitem': 'altGlyphItem', 'animatecolor': 'animateColor', 'animatemotion': 'animateMotion', 'animatetransform': 'animateTransform', 'clippath': 'clipPath', 'feblend': 'feBlend', 'fecolormatrix': 'feColorMatrix', 'fecomponenttransfer': 'feComponentTransfer', 'fecomposite': 'feComposite', 'feconvolvematrix': 'feConvolveMatrix', 'fediffuselighting': 'feDiffuseLighting', 'fedisplacementmap': 'feDisplacementMap', 'fedistantlight': 'feDistantLight', 'feflood': 'feFlood', 'fefunca': 'feFuncA', 'fefuncb': 'feFuncB', 'fefuncg': 'feFuncG', 'fefuncr': 'feFuncR', 'fegaussianblur': 'feGaussianBlur', 'feimage': 'feImage', 'femerge': 'feMerge', 'femergenode': 'feMergeNode', 'femorphology': 'feMorphology', 'feoffset': 'feOffset', 'fepointlight': 'fePointLight', 'fespecularlighting': 'feSpecularLighting', 'fespotlight': 'feSpotLight', 'fetile': 'feTile', 'feturbulence': 'feTurbulence', 'foreignobject': 'foreignObject', 'glyphref': 'glyphRef', 'lineargradient': 'linearGradient', 'radialgradient': 'radialGradient', 'textpath': 'textPath' }; var replace = replacements[token.name]; if (replace != null) { token.name = replace; } } @override Token processCharacters(CharactersToken token) { if (token.data == '\u0000') { token.replaceData('\uFFFD'); } else if (parser.framesetOK && !allWhitespace(token.data)) { parser.framesetOK = false; } return super.processCharacters(token); } @override Token processStartTag(StartTagToken token) { var currentNode = tree.openElements.last; if (breakoutElements.contains(token.name) || (token.name == 'font' && (token.data.containsKey('color') || token.data.containsKey('face') || token.data.containsKey('size')))) { parser.parseError(token.span, 'unexpected-html-element-in-foreign-content', {'name': token.name}); while (tree.openElements.last.namespaceUri != tree.defaultNamespace && !parser.isHTMLIntegrationPoint(tree.openElements.last) && !parser.isMathMLTextIntegrationPoint(tree.openElements.last)) { tree.openElements.removeLast(); } return token; } else { if (currentNode.namespaceUri == Namespaces.mathml) { parser.adjustMathMLAttributes(token); } else if (currentNode.namespaceUri == Namespaces.svg) { adjustSVGTagNames(token); parser.adjustSVGAttributes(token); } parser.adjustForeignAttributes(token); token.namespace = currentNode.namespaceUri; tree.insertElement(token); if (token.selfClosing) { tree.openElements.removeLast(); token.selfClosingAcknowledged = true; } return null; } } @override Token processEndTag(EndTagToken token) { var nodeIndex = tree.openElements.length - 1; var node = tree.openElements.last; if (asciiUpper2Lower(node.localName) != token.name) { parser.parseError(token.span, 'unexpected-end-tag', {'name': token.name}); } Token newToken; while (true) { if (asciiUpper2Lower(node.localName) == token.name) { //XXX this isn't in the spec but it seems necessary if (parser.phase == parser._inTableTextPhase) { InTableTextPhase inTableText = parser.phase; inTableText.flushCharacters(); parser.phase = inTableText.originalPhase; } while (tree.openElements.removeLast() != node) { assert(tree.openElements.isNotEmpty); } newToken = null; break; } nodeIndex -= 1; node = tree.openElements[nodeIndex]; if (node.namespaceUri != tree.defaultNamespace) { continue; } else { newToken = parser.phase.processEndTag(token); break; } } return newToken; } } class AfterBodyPhase extends Phase { AfterBodyPhase(parser) : super(parser); @override Token processStartTag(StartTagToken token) { if (token.name == 'html') return startTagHtml(token); return startTagOther(token); } @override Token processEndTag(EndTagToken token) { if (token.name == 'html') { endTagHtml(token); return null; } return endTagOther(token); } //Stop parsing @override bool processEOF() => false; @override Token processComment(CommentToken token) { // This is needed because data is to be appended to the <html> element // here and not to whatever is currently open. tree.insertComment(token, tree.openElements[0]); return null; } @override Token processCharacters(CharactersToken token) { parser.parseError(token.span, 'unexpected-char-after-body'); parser.phase = parser._inBodyPhase; return token; } @override Token startTagHtml(StartTagToken token) { return parser._inBodyPhase.processStartTag(token); } Token startTagOther(StartTagToken token) { parser.parseError( token.span, 'unexpected-start-tag-after-body', {'name': token.name}); parser.phase = parser._inBodyPhase; return token; } void endTagHtml(Token token) { for (var node in tree.openElements.reversed) { if (node.localName == 'html') { node.endSourceSpan = token.span; break; } } if (parser.innerHTMLMode) { parser.parseError(token.span, 'unexpected-end-tag-after-body-innerhtml'); } else { parser.phase = parser._afterAfterBodyPhase; } } Token endTagOther(EndTagToken token) { parser.parseError( token.span, 'unexpected-end-tag-after-body', {'name': token.name}); parser.phase = parser._inBodyPhase; return token; } } class InFramesetPhase extends Phase { // http://www.whatwg.org/specs/web-apps/current-work///in-frameset InFramesetPhase(parser) : super(parser); @override Token processStartTag(StartTagToken token) { switch (token.name) { case 'html': return startTagHtml(token); case 'frameset': startTagFrameset(token); return null; case 'frame': startTagFrame(token); return null; case 'noframes': return startTagNoframes(token); default: return startTagOther(token); } } @override Token processEndTag(EndTagToken token) { switch (token.name) { case 'frameset': endTagFrameset(token); return null; default: endTagOther(token); return null; } } @override bool processEOF() { var last = tree.openElements.last; if (last.localName != 'html') { parser.parseError(last.sourceSpan, 'eof-in-frameset'); } else { assert(parser.innerHTMLMode); } return false; } @override Token processCharacters(CharactersToken token) { parser.parseError(token.span, 'unexpected-char-in-frameset'); return null; } void startTagFrameset(StartTagToken token) { tree.insertElement(token); } void startTagFrame(StartTagToken token) { tree.insertElement(token); tree.openElements.removeLast(); } Token startTagNoframes(StartTagToken token) { return parser._inBodyPhase.processStartTag(token); } Token startTagOther(StartTagToken token) { parser.parseError( token.span, 'unexpected-start-tag-in-frameset', {'name': token.name}); return null; } void endTagFrameset(EndTagToken token) { if (tree.openElements.last.localName == 'html') { // innerHTML case parser.parseError( token.span, 'unexpected-frameset-in-frameset-innerhtml'); } else { var node = tree.openElements.removeLast(); node.endSourceSpan = token.span; } if (!parser.innerHTMLMode && tree.openElements.last.localName != 'frameset') { // If we're not in innerHTML mode and the the current node is not a // "frameset" element (anymore) then switch. parser.phase = parser._afterFramesetPhase; } } void endTagOther(EndTagToken token) { parser.parseError( token.span, 'unexpected-end-tag-in-frameset', {'name': token.name}); } } class AfterFramesetPhase extends Phase { // http://www.whatwg.org/specs/web-apps/current-work///after3 AfterFramesetPhase(parser) : super(parser); @override Token processStartTag(StartTagToken token) { switch (token.name) { case 'html': return startTagHtml(token); case 'noframes': return startTagNoframes(token); default: startTagOther(token); return null; } } @override Token processEndTag(EndTagToken token) { switch (token.name) { case 'html': endTagHtml(token); return null; default: endTagOther(token); return null; } } // Stop parsing @override bool processEOF() => false; @override Token processCharacters(CharactersToken token) { parser.parseError(token.span, 'unexpected-char-after-frameset'); return null; } Token startTagNoframes(StartTagToken token) { return parser._inHeadPhase.processStartTag(token); } void startTagOther(StartTagToken token) { parser.parseError(token.span, 'unexpected-start-tag-after-frameset', {'name': token.name}); } void endTagHtml(EndTagToken token) { parser.phase = parser._afterAfterFramesetPhase; } void endTagOther(EndTagToken token) { parser.parseError( token.span, 'unexpected-end-tag-after-frameset', {'name': token.name}); } } class AfterAfterBodyPhase extends Phase { AfterAfterBodyPhase(parser) : super(parser); @override Token processStartTag(StartTagToken token) { if (token.name == 'html') return startTagHtml(token); return startTagOther(token); } @override bool processEOF() => false; @override Token processComment(CommentToken token) { tree.insertComment(token, tree.document); return null; } @override Token processSpaceCharacters(SpaceCharactersToken token) { return parser._inBodyPhase.processSpaceCharacters(token); } @override Token processCharacters(CharactersToken token) { parser.parseError(token.span, 'expected-eof-but-got-char'); parser.phase = parser._inBodyPhase; return token; } @override Token startTagHtml(StartTagToken token) { return parser._inBodyPhase.processStartTag(token); } Token startTagOther(StartTagToken token) { parser.parseError( token.span, 'expected-eof-but-got-start-tag', {'name': token.name}); parser.phase = parser._inBodyPhase; return token; } @override Token processEndTag(EndTagToken token) { parser.parseError( token.span, 'expected-eof-but-got-end-tag', {'name': token.name}); parser.phase = parser._inBodyPhase; return token; } } class AfterAfterFramesetPhase extends Phase { AfterAfterFramesetPhase(parser) : super(parser); @override Token processStartTag(StartTagToken token) { switch (token.name) { case 'html': return startTagHtml(token); case 'noframes': return startTagNoFrames(token); default: startTagOther(token); return null; } } @override bool processEOF() => false; @override Token processComment(CommentToken token) { tree.insertComment(token, tree.document); return null; } @override Token processSpaceCharacters(SpaceCharactersToken token) { return parser._inBodyPhase.processSpaceCharacters(token); } @override Token processCharacters(CharactersToken token) { parser.parseError(token.span, 'expected-eof-but-got-char'); return null; } @override Token startTagHtml(StartTagToken token) { return parser._inBodyPhase.processStartTag(token); } Token startTagNoFrames(StartTagToken token) { return parser._inHeadPhase.processStartTag(token); } void startTagOther(StartTagToken token) { parser.parseError( token.span, 'expected-eof-but-got-start-tag', {'name': token.name}); } @override Token processEndTag(EndTagToken token) { parser.parseError( token.span, 'expected-eof-but-got-end-tag', {'name': token.name}); return null; } } /// Error in parsed document. class ParseError implements SourceSpanException { final String errorCode; @override final SourceSpan span; final Map data; ParseError(this.errorCode, this.span, this.data); int get line => span.start.line; int get column => span.start.column; /// Gets the human readable error message for this error. Use /// [span.getLocationMessage] or [toString] to get a message including span /// information. If there is a file associated with the span, both /// [span.getLocationMessage] and [toString] are equivalent. Otherwise, /// [span.getLocationMessage] will not show any source url information, but /// [toString] will include 'ParserError:' as a prefix. @override String get message => formatStr(errorMessages[errorCode], data); @override String toString({color}) { var res = span.message(message, color: color); return span.sourceUrl == null ? 'ParserError on $res' : 'On $res'; } } /// Convenience function to get the pair of namespace and localName. Pair<String, String> getElementNameTuple(Element e) { var ns = e.namespaceUri ?? Namespaces.html; return Pair(ns, e.localName); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html/src/tokenizer.dart
library tokenizer; import 'dart:collection'; import 'package:html/parser.dart' show HtmlParser; import 'constants.dart'; import 'html_input_stream.dart'; import 'token.dart'; import 'utils.dart'; // Group entities by their first character, for faster lookups // TODO(jmesserly): we could use a better data structure here like a trie, if // we had it implemented in Dart. Map<String, List<String>> entitiesByFirstChar = (() { var result = <String, List<String>>{}; for (var k in entities.keys) { result.putIfAbsent(k[0], () => []).add(k); } return result; })(); // TODO(jmesserly): lots of ways to make this faster: // - use char codes everywhere instead of 1-char strings // - use switch instead of contains, indexOf // - use switch instead of the sequential if tests // - avoid string concat /// This class takes care of tokenizing HTML. class HtmlTokenizer implements Iterator<Token> { // TODO(jmesserly): a lot of these could be made private final HtmlInputStream stream; final bool lowercaseElementName; final bool lowercaseAttrName; /// True to generate spans in for [Token.span]. final bool generateSpans; /// True to generate spans for attributes. final bool attributeSpans; /// This reference to the parser is used for correct CDATA handling. /// The [HtmlParser] will set this at construction time. HtmlParser parser; final Queue<Token> tokenQueue; /// Holds the token that is currently being processed. Token currentToken; /// Holds a reference to the method to be invoked for the next parser state. // TODO(jmesserly): the type should be "Predicate" but a dart2js checked mode // bug prevents us from doing that. See http://dartbug.com/12465 Function state; final StringBuffer _buffer = StringBuffer(); int _lastOffset; // TODO(jmesserly): ideally this would be a LinkedHashMap and we wouldn't add // an item until it's ready. But the code doesn't have a clear notion of when // it's "done" with the attribute. List<TagAttribute> _attributes; Set<String> _attributeNames; HtmlTokenizer(doc, {String encoding, bool parseMeta = true, this.lowercaseElementName = true, this.lowercaseAttrName = true, this.generateSpans = false, String sourceUrl, this.attributeSpans = false}) : stream = HtmlInputStream(doc, encoding, parseMeta, generateSpans, sourceUrl), tokenQueue = Queue() { reset(); } TagToken get currentTagToken => currentToken; DoctypeToken get currentDoctypeToken => currentToken; StringToken get currentStringToken => currentToken; Token _current; @override Token get current => _current; final StringBuffer _attributeName = StringBuffer(); final StringBuffer _attributeValue = StringBuffer(); void _markAttributeEnd(int offset) { _attributes.last.value = '$_attributeValue'; if (attributeSpans) _attributes.last.end = stream.position + offset; } void _markAttributeValueStart(int offset) { if (attributeSpans) _attributes.last.startValue = stream.position + offset; } void _markAttributeValueEnd(int offset) { if (attributeSpans) _attributes.last.endValue = stream.position + offset; _markAttributeEnd(offset); } // Note: we could track the name span here, if we need it. void _markAttributeNameEnd(int offset) => _markAttributeEnd(offset); void _addAttribute(String name) { _attributes ??= []; _attributeName.clear(); _attributeName.write(name); _attributeValue.clear(); var attr = TagAttribute(); _attributes.add(attr); if (attributeSpans) attr.start = stream.position - name.length; } /// This is where the magic happens. /// /// We do our usually processing through the states and when we have a token /// to return we yield the token which pauses processing until the next token /// is requested. @override bool moveNext() { // Start processing. When EOF is reached state will return false; // instead of true and the loop will terminate. while (stream.errors.isEmpty && tokenQueue.isEmpty) { if (!state()) { _current = null; return false; } } if (stream.errors.isNotEmpty) { _current = ParseErrorToken(stream.errors.removeFirst()); } else { assert(tokenQueue.isNotEmpty); _current = tokenQueue.removeFirst(); } return true; } /// Resets the tokenizer state. Calling this does not reset the [stream] or /// the [parser]. void reset() { _lastOffset = 0; tokenQueue.clear(); currentToken = null; _buffer.clear(); _attributes = null; _attributeNames = null; state = dataState; } /// Adds a token to the queue. Sets the span if needed. void _addToken(Token token) { if (generateSpans && token.span == null) { var offset = stream.position; token.span = stream.fileInfo.span(_lastOffset, offset); if (token is! ParseErrorToken) { _lastOffset = offset; } } tokenQueue.add(token); } /// This function returns either U+FFFD or the character based on the /// decimal or hexadecimal representation. It also discards ";" if present. /// If not present it will add a [ParseErrorToken]. String consumeNumberEntity(bool isHex) { var allowed = isDigit; var radix = 10; if (isHex) { allowed = isHexDigit; radix = 16; } var charStack = []; // Consume all the characters that are in range while making sure we // don't hit an EOF. var c = stream.char(); while (allowed(c) && c != eof) { charStack.add(c); c = stream.char(); } // Convert the set of characters consumed to an int. var charAsInt = int.parse(charStack.join(), radix: radix); // Certain characters get replaced with others var char = replacementCharacters[charAsInt]; if (char != null) { _addToken(ParseErrorToken('illegal-codepoint-for-numeric-entity', messageParams: {'charAsInt': charAsInt})); } else if ((0xD800 <= charAsInt && charAsInt <= 0xDFFF) || (charAsInt > 0x10FFFF)) { char = '\uFFFD'; _addToken(ParseErrorToken('illegal-codepoint-for-numeric-entity', messageParams: {'charAsInt': charAsInt})); } else { // Should speed up this check somehow (e.g. move the set to a constant) if ((0x0001 <= charAsInt && charAsInt <= 0x0008) || (0x000E <= charAsInt && charAsInt <= 0x001F) || (0x007F <= charAsInt && charAsInt <= 0x009F) || (0xFDD0 <= charAsInt && charAsInt <= 0xFDEF) || const [ 0x000B, 0xFFFE, 0xFFFF, 0x1FFFE, 0x1FFFF, 0x2FFFE, 0x2FFFF, 0x3FFFE, 0x3FFFF, 0x4FFFE, 0x4FFFF, 0x5FFFE, 0x5FFFF, 0x6FFFE, 0x6FFFF, 0x7FFFE, 0x7FFFF, 0x8FFFE, 0x8FFFF, 0x9FFFE, 0x9FFFF, 0xAFFFE, 0xAFFFF, 0xBFFFE, 0xBFFFF, 0xCFFFE, 0xCFFFF, 0xDFFFE, 0xDFFFF, 0xEFFFE, 0xEFFFF, 0xFFFFE, 0xFFFFF, 0x10FFFE, 0x10FFFF ].contains(charAsInt)) { _addToken(ParseErrorToken('illegal-codepoint-for-numeric-entity', messageParams: {'charAsInt': charAsInt})); } char = String.fromCharCodes([charAsInt]); } // Discard the ; if present. Otherwise, put it back on the queue and // invoke parseError on parser. if (c != ';') { _addToken(ParseErrorToken('numeric-entity-without-semicolon')); stream.unget(c); } return char; } void consumeEntity({String allowedChar, bool fromAttribute = false}) { // Initialise to the default output for when no entity is matched var output = '&'; var charStack = [stream.char()]; if (isWhitespace(charStack[0]) || charStack[0] == '<' || charStack[0] == '&' || charStack[0] == eof || allowedChar == charStack[0]) { stream.unget(charStack[0]); } else if (charStack[0] == '#') { // Read the next character to see if it's hex or decimal var hex = false; charStack.add(stream.char()); if (charStack.last == 'x' || charStack.last == 'X') { hex = true; charStack.add(stream.char()); } // charStack.last should be the first digit if (hex && isHexDigit(charStack.last) || (!hex && isDigit(charStack.last))) { // At least one digit found, so consume the whole number stream.unget(charStack.last); output = consumeNumberEntity(hex); } else { // No digits found _addToken(ParseErrorToken('expected-numeric-entity')); stream.unget(charStack.removeLast()); output = '&${charStack.join()}'; } } else { // At this point in the process might have named entity. Entities // are stored in the global variable "entities". // // Consume characters and compare to these to a substring of the // entity names in the list until the substring no longer matches. var filteredEntityList = entitiesByFirstChar[charStack[0]] ?? const []; while (charStack.last != eof) { var name = charStack.join(); filteredEntityList = filteredEntityList.where((e) => e.startsWith(name)).toList(); if (filteredEntityList.isEmpty) { break; } charStack.add(stream.char()); } // At this point we have a string that starts with some characters // that may match an entity String entityName; // Try to find the longest entity the string will match to take care // of &noti for instance. int entityLen; for (entityLen = charStack.length - 1; entityLen > 1; entityLen--) { var possibleEntityName = charStack.sublist(0, entityLen).join(); if (entities.containsKey(possibleEntityName)) { entityName = possibleEntityName; break; } } if (entityName != null) { var lastChar = entityName[entityName.length - 1]; if (lastChar != ';') { _addToken(ParseErrorToken('named-entity-without-semicolon')); } if (lastChar != ';' && fromAttribute && (isLetterOrDigit(charStack[entityLen]) || charStack[entityLen] == '=')) { stream.unget(charStack.removeLast()); output = '&${charStack.join()}'; } else { output = entities[entityName]; stream.unget(charStack.removeLast()); output = '$output${slice(charStack, entityLen).join()}'; } } else { _addToken(ParseErrorToken('expected-named-entity')); stream.unget(charStack.removeLast()); output = '&${charStack.join()}'; } } if (fromAttribute) { _attributeValue.write(output); } else { Token token; if (isWhitespace(output)) { token = SpaceCharactersToken(output); } else { token = CharactersToken(output); } _addToken(token); } } /// This method replaces the need for "entityInAttributeValueState". void processEntityInAttribute(String allowedChar) { consumeEntity(allowedChar: allowedChar, fromAttribute: true); } /// This method is a generic handler for emitting the tags. It also sets /// the state to "data" because that's what's needed after a token has been /// emitted. void emitCurrentToken() { var token = currentToken; // Add token to the queue to be yielded if (token is TagToken) { if (lowercaseElementName) { token.name = asciiUpper2Lower(token.name); } if (token is EndTagToken) { if (_attributes != null) { _addToken(ParseErrorToken('attributes-in-end-tag')); } if (token.selfClosing) { _addToken(ParseErrorToken('this-closing-flag-on-end-tag')); } } else if (token is StartTagToken) { // HTML5 specific normalizations to the token stream. // Convert the list into a map where first key wins. token.data = LinkedHashMap<Object, String>(); if (_attributes != null) { for (var attr in _attributes) { token.data.putIfAbsent(attr.name, () => attr.value); } if (attributeSpans) token.attributeSpans = _attributes; } } _attributes = null; _attributeNames = null; } _addToken(token); state = dataState; } // Below are the various tokenizer states worked out. bool dataState() { var data = stream.char(); if (data == '&') { state = entityDataState; } else if (data == '<') { state = tagOpenState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); _addToken(CharactersToken('\u0000')); } else if (data == eof) { // Tokenization ends. return false; } else if (isWhitespace(data)) { // Directly after emitting a token you switch back to the "data // state". At that point spaceCharacters are important so they are // emitted separately. _addToken(SpaceCharactersToken( '$data${stream.charsUntil(spaceCharacters, true)}')); // No need to update lastFourChars here, since the first space will // have already been appended to lastFourChars and will have broken // any <!-- or --> sequences } else { var chars = stream.charsUntil('&<\u0000'); _addToken(CharactersToken('$data$chars')); } return true; } bool entityDataState() { consumeEntity(); state = dataState; return true; } bool rcdataState() { var data = stream.char(); if (data == '&') { state = characterReferenceInRcdata; } else if (data == '<') { state = rcdataLessThanSignState; } else if (data == eof) { // Tokenization ends. return false; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); _addToken(CharactersToken('\uFFFD')); } else if (isWhitespace(data)) { // Directly after emitting a token you switch back to the "data // state". At that point spaceCharacters are important so they are // emitted separately. _addToken(SpaceCharactersToken( '$data${stream.charsUntil(spaceCharacters, true)}')); } else { var chars = stream.charsUntil('&<'); _addToken(CharactersToken('$data$chars')); } return true; } bool characterReferenceInRcdata() { consumeEntity(); state = rcdataState; return true; } bool rawtextState() { var data = stream.char(); if (data == '<') { state = rawtextLessThanSignState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); _addToken(CharactersToken('\uFFFD')); } else if (data == eof) { // Tokenization ends. return false; } else { var chars = stream.charsUntil('<\u0000'); _addToken(CharactersToken('$data$chars')); } return true; } bool scriptDataState() { var data = stream.char(); if (data == '<') { state = scriptDataLessThanSignState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); _addToken(CharactersToken('\uFFFD')); } else if (data == eof) { // Tokenization ends. return false; } else { var chars = stream.charsUntil('<\u0000'); _addToken(CharactersToken('$data$chars')); } return true; } bool plaintextState() { var data = stream.char(); if (data == eof) { // Tokenization ends. return false; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); _addToken(CharactersToken('\uFFFD')); } else { _addToken(CharactersToken('$data${stream.charsUntil("\u0000")}')); } return true; } bool tagOpenState() { var data = stream.char(); if (data == '!') { state = markupDeclarationOpenState; } else if (data == '/') { state = closeTagOpenState; } else if (isLetter(data)) { currentToken = StartTagToken(data); state = tagNameState; } else if (data == '>') { // XXX In theory it could be something besides a tag name. But // do we really care? _addToken(ParseErrorToken('expected-tag-name-but-got-right-bracket')); _addToken(CharactersToken('<>')); state = dataState; } else if (data == '?') { // XXX In theory it could be something besides a tag name. But // do we really care? _addToken(ParseErrorToken('expected-tag-name-but-got-question-mark')); stream.unget(data); state = bogusCommentState; } else { // XXX _addToken(ParseErrorToken('expected-tag-name')); _addToken(CharactersToken('<')); stream.unget(data); state = dataState; } return true; } bool closeTagOpenState() { var data = stream.char(); if (isLetter(data)) { currentToken = EndTagToken(data); state = tagNameState; } else if (data == '>') { _addToken(ParseErrorToken('expected-closing-tag-but-got-right-bracket')); state = dataState; } else if (data == eof) { _addToken(ParseErrorToken('expected-closing-tag-but-got-eof')); _addToken(CharactersToken('</')); state = dataState; } else { // XXX data can be _'_... _addToken(ParseErrorToken('expected-closing-tag-but-got-char', messageParams: {'data': data})); stream.unget(data); state = bogusCommentState; } return true; } bool tagNameState() { var data = stream.char(); if (isWhitespace(data)) { state = beforeAttributeNameState; } else if (data == '>') { emitCurrentToken(); } else if (data == eof) { _addToken(ParseErrorToken('eof-in-tag-name')); state = dataState; } else if (data == '/') { state = selfClosingStartTagState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); currentTagToken.name = '${currentTagToken.name}\uFFFD'; } else { currentTagToken.name = '${currentTagToken.name}$data'; // (Don't use charsUntil here, because tag names are // very short and it's faster to not do anything fancy) } return true; } bool rcdataLessThanSignState() { var data = stream.char(); if (data == '/') { _buffer.clear(); state = rcdataEndTagOpenState; } else { _addToken(CharactersToken('<')); stream.unget(data); state = rcdataState; } return true; } bool rcdataEndTagOpenState() { var data = stream.char(); if (isLetter(data)) { _buffer.write(data); state = rcdataEndTagNameState; } else { _addToken(CharactersToken('</')); stream.unget(data); state = rcdataState; } return true; } bool _tokenIsAppropriate() { // TODO(jmesserly): this should use case insensitive compare instead. return currentToken is TagToken && currentTagToken.name.toLowerCase() == '$_buffer'.toLowerCase(); } bool rcdataEndTagNameState() { var appropriate = _tokenIsAppropriate(); var data = stream.char(); if (isWhitespace(data) && appropriate) { currentToken = EndTagToken('$_buffer'); state = beforeAttributeNameState; } else if (data == '/' && appropriate) { currentToken = EndTagToken('$_buffer'); state = selfClosingStartTagState; } else if (data == '>' && appropriate) { currentToken = EndTagToken('$_buffer'); emitCurrentToken(); state = dataState; } else if (isLetter(data)) { _buffer.write(data); } else { _addToken(CharactersToken('</$_buffer')); stream.unget(data); state = rcdataState; } return true; } bool rawtextLessThanSignState() { var data = stream.char(); if (data == '/') { _buffer.clear(); state = rawtextEndTagOpenState; } else { _addToken(CharactersToken('<')); stream.unget(data); state = rawtextState; } return true; } bool rawtextEndTagOpenState() { var data = stream.char(); if (isLetter(data)) { _buffer.write(data); state = rawtextEndTagNameState; } else { _addToken(CharactersToken('</')); stream.unget(data); state = rawtextState; } return true; } bool rawtextEndTagNameState() { var appropriate = _tokenIsAppropriate(); var data = stream.char(); if (isWhitespace(data) && appropriate) { currentToken = EndTagToken('$_buffer'); state = beforeAttributeNameState; } else if (data == '/' && appropriate) { currentToken = EndTagToken('$_buffer'); state = selfClosingStartTagState; } else if (data == '>' && appropriate) { currentToken = EndTagToken('$_buffer'); emitCurrentToken(); state = dataState; } else if (isLetter(data)) { _buffer.write(data); } else { _addToken(CharactersToken('</$_buffer')); stream.unget(data); state = rawtextState; } return true; } bool scriptDataLessThanSignState() { var data = stream.char(); if (data == '/') { _buffer.clear(); state = scriptDataEndTagOpenState; } else if (data == '!') { _addToken(CharactersToken('<!')); state = scriptDataEscapeStartState; } else { _addToken(CharactersToken('<')); stream.unget(data); state = scriptDataState; } return true; } bool scriptDataEndTagOpenState() { var data = stream.char(); if (isLetter(data)) { _buffer.write(data); state = scriptDataEndTagNameState; } else { _addToken(CharactersToken('</')); stream.unget(data); state = scriptDataState; } return true; } bool scriptDataEndTagNameState() { var appropriate = _tokenIsAppropriate(); var data = stream.char(); if (isWhitespace(data) && appropriate) { currentToken = EndTagToken('$_buffer'); state = beforeAttributeNameState; } else if (data == '/' && appropriate) { currentToken = EndTagToken('$_buffer'); state = selfClosingStartTagState; } else if (data == '>' && appropriate) { currentToken = EndTagToken('$_buffer'); emitCurrentToken(); state = dataState; } else if (isLetter(data)) { _buffer.write(data); } else { _addToken(CharactersToken('</$_buffer')); stream.unget(data); state = scriptDataState; } return true; } bool scriptDataEscapeStartState() { var data = stream.char(); if (data == '-') { _addToken(CharactersToken('-')); state = scriptDataEscapeStartDashState; } else { stream.unget(data); state = scriptDataState; } return true; } bool scriptDataEscapeStartDashState() { var data = stream.char(); if (data == '-') { _addToken(CharactersToken('-')); state = scriptDataEscapedDashDashState; } else { stream.unget(data); state = scriptDataState; } return true; } bool scriptDataEscapedState() { var data = stream.char(); if (data == '-') { _addToken(CharactersToken('-')); state = scriptDataEscapedDashState; } else if (data == '<') { state = scriptDataEscapedLessThanSignState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); _addToken(CharactersToken('\uFFFD')); } else if (data == eof) { state = dataState; } else { var chars = stream.charsUntil('<-\u0000'); _addToken(CharactersToken('$data$chars')); } return true; } bool scriptDataEscapedDashState() { var data = stream.char(); if (data == '-') { _addToken(CharactersToken('-')); state = scriptDataEscapedDashDashState; } else if (data == '<') { state = scriptDataEscapedLessThanSignState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); _addToken(CharactersToken('\uFFFD')); state = scriptDataEscapedState; } else if (data == eof) { state = dataState; } else { _addToken(CharactersToken(data)); state = scriptDataEscapedState; } return true; } bool scriptDataEscapedDashDashState() { var data = stream.char(); if (data == '-') { _addToken(CharactersToken('-')); } else if (data == '<') { state = scriptDataEscapedLessThanSignState; } else if (data == '>') { _addToken(CharactersToken('>')); state = scriptDataState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); _addToken(CharactersToken('\uFFFD')); state = scriptDataEscapedState; } else if (data == eof) { state = dataState; } else { _addToken(CharactersToken(data)); state = scriptDataEscapedState; } return true; } bool scriptDataEscapedLessThanSignState() { var data = stream.char(); if (data == '/') { _buffer.clear(); state = scriptDataEscapedEndTagOpenState; } else if (isLetter(data)) { _addToken(CharactersToken('<$data')); _buffer.clear(); _buffer.write(data); state = scriptDataDoubleEscapeStartState; } else { _addToken(CharactersToken('<')); stream.unget(data); state = scriptDataEscapedState; } return true; } bool scriptDataEscapedEndTagOpenState() { var data = stream.char(); if (isLetter(data)) { _buffer.clear(); _buffer.write(data); state = scriptDataEscapedEndTagNameState; } else { _addToken(CharactersToken('</')); stream.unget(data); state = scriptDataEscapedState; } return true; } bool scriptDataEscapedEndTagNameState() { var appropriate = _tokenIsAppropriate(); var data = stream.char(); if (isWhitespace(data) && appropriate) { currentToken = EndTagToken('$_buffer'); state = beforeAttributeNameState; } else if (data == '/' && appropriate) { currentToken = EndTagToken('$_buffer'); state = selfClosingStartTagState; } else if (data == '>' && appropriate) { currentToken = EndTagToken('$_buffer'); emitCurrentToken(); state = dataState; } else if (isLetter(data)) { _buffer.write(data); } else { _addToken(CharactersToken('</$_buffer')); stream.unget(data); state = scriptDataEscapedState; } return true; } bool scriptDataDoubleEscapeStartState() { var data = stream.char(); if (isWhitespace(data) || data == '/' || data == '>') { _addToken(CharactersToken(data)); if ('$_buffer'.toLowerCase() == 'script') { state = scriptDataDoubleEscapedState; } else { state = scriptDataEscapedState; } } else if (isLetter(data)) { _addToken(CharactersToken(data)); _buffer.write(data); } else { stream.unget(data); state = scriptDataEscapedState; } return true; } bool scriptDataDoubleEscapedState() { var data = stream.char(); if (data == '-') { _addToken(CharactersToken('-')); state = scriptDataDoubleEscapedDashState; } else if (data == '<') { _addToken(CharactersToken('<')); state = scriptDataDoubleEscapedLessThanSignState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); _addToken(CharactersToken('\uFFFD')); } else if (data == eof) { _addToken(ParseErrorToken('eof-in-script-in-script')); state = dataState; } else { _addToken(CharactersToken(data)); } return true; } bool scriptDataDoubleEscapedDashState() { var data = stream.char(); if (data == '-') { _addToken(CharactersToken('-')); state = scriptDataDoubleEscapedDashDashState; } else if (data == '<') { _addToken(CharactersToken('<')); state = scriptDataDoubleEscapedLessThanSignState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); _addToken(CharactersToken('\uFFFD')); state = scriptDataDoubleEscapedState; } else if (data == eof) { _addToken(ParseErrorToken('eof-in-script-in-script')); state = dataState; } else { _addToken(CharactersToken(data)); state = scriptDataDoubleEscapedState; } return true; } // TODO(jmesserly): report bug in original code // (was "Dash" instead of "DashDash") bool scriptDataDoubleEscapedDashDashState() { var data = stream.char(); if (data == '-') { _addToken(CharactersToken('-')); } else if (data == '<') { _addToken(CharactersToken('<')); state = scriptDataDoubleEscapedLessThanSignState; } else if (data == '>') { _addToken(CharactersToken('>')); state = scriptDataState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); _addToken(CharactersToken('\uFFFD')); state = scriptDataDoubleEscapedState; } else if (data == eof) { _addToken(ParseErrorToken('eof-in-script-in-script')); state = dataState; } else { _addToken(CharactersToken(data)); state = scriptDataDoubleEscapedState; } return true; } bool scriptDataDoubleEscapedLessThanSignState() { var data = stream.char(); if (data == '/') { _addToken(CharactersToken('/')); _buffer.clear(); state = scriptDataDoubleEscapeEndState; } else { stream.unget(data); state = scriptDataDoubleEscapedState; } return true; } bool scriptDataDoubleEscapeEndState() { var data = stream.char(); if (isWhitespace(data) || data == '/' || data == '>') { _addToken(CharactersToken(data)); if ('$_buffer'.toLowerCase() == 'script') { state = scriptDataEscapedState; } else { state = scriptDataDoubleEscapedState; } } else if (isLetter(data)) { _addToken(CharactersToken(data)); _buffer.write(data); } else { stream.unget(data); state = scriptDataDoubleEscapedState; } return true; } bool beforeAttributeNameState() { var data = stream.char(); if (isWhitespace(data)) { stream.charsUntil(spaceCharacters, true); } else if (isLetter(data)) { _addAttribute(data); state = attributeNameState; } else if (data == '>') { emitCurrentToken(); } else if (data == '/') { state = selfClosingStartTagState; } else if (data == eof) { _addToken(ParseErrorToken('expected-attribute-name-but-got-eof')); state = dataState; } else if ("'\"=<".contains(data)) { _addToken(ParseErrorToken('invalid-character-in-attribute-name')); _addAttribute(data); state = attributeNameState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); _addAttribute('\uFFFD'); state = attributeNameState; } else { _addAttribute(data); state = attributeNameState; } return true; } bool attributeNameState() { var data = stream.char(); var leavingThisState = true; var emitToken = false; if (data == '=') { state = beforeAttributeValueState; } else if (isLetter(data)) { _attributeName.write(data); _attributeName.write(stream.charsUntil(asciiLetters, true)); leavingThisState = false; } else if (data == '>') { // XXX If we emit here the attributes are converted to a dict // without being checked and when the code below runs we error // because data is a dict not a list emitToken = true; } else if (isWhitespace(data)) { state = afterAttributeNameState; } else if (data == '/') { state = selfClosingStartTagState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); _attributeName.write('\uFFFD'); leavingThisState = false; } else if (data == eof) { _addToken(ParseErrorToken('eof-in-attribute-name')); state = dataState; } else if ("'\"<".contains(data)) { _addToken(ParseErrorToken('invalid-character-in-attribute-name')); _attributeName.write(data); leavingThisState = false; } else { _attributeName.write(data); leavingThisState = false; } if (leavingThisState) { _markAttributeNameEnd(-1); // Attributes are not dropped at this stage. That happens when the // start tag token is emitted so values can still be safely appended // to attributes, but we do want to report the parse error in time. var attrName = _attributeName.toString(); if (lowercaseAttrName) { attrName = asciiUpper2Lower(attrName); } _attributes.last.name = attrName; _attributeNames ??= {}; if (_attributeNames.contains(attrName)) { _addToken(ParseErrorToken('duplicate-attribute')); } _attributeNames.add(attrName); // XXX Fix for above XXX if (emitToken) { emitCurrentToken(); } } return true; } bool afterAttributeNameState() { var data = stream.char(); if (isWhitespace(data)) { stream.charsUntil(spaceCharacters, true); } else if (data == '=') { state = beforeAttributeValueState; } else if (data == '>') { emitCurrentToken(); } else if (isLetter(data)) { _addAttribute(data); state = attributeNameState; } else if (data == '/') { state = selfClosingStartTagState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); _addAttribute('\uFFFD'); state = attributeNameState; } else if (data == eof) { _addToken(ParseErrorToken('expected-end-of-tag-but-got-eof')); state = dataState; } else if ("'\"<".contains(data)) { _addToken(ParseErrorToken('invalid-character-after-attribute-name')); _addAttribute(data); state = attributeNameState; } else { _addAttribute(data); state = attributeNameState; } return true; } bool beforeAttributeValueState() { var data = stream.char(); if (isWhitespace(data)) { stream.charsUntil(spaceCharacters, true); } else if (data == '"') { _markAttributeValueStart(0); state = attributeValueDoubleQuotedState; } else if (data == '&') { state = attributeValueUnQuotedState; stream.unget(data); _markAttributeValueStart(0); } else if (data == "'") { _markAttributeValueStart(0); state = attributeValueSingleQuotedState; } else if (data == '>') { _addToken( ParseErrorToken('expected-attribute-value-but-got-right-bracket')); emitCurrentToken(); } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); _markAttributeValueStart(-1); _attributeValue.write('\uFFFD'); state = attributeValueUnQuotedState; } else if (data == eof) { _addToken(ParseErrorToken('expected-attribute-value-but-got-eof')); state = dataState; } else if ('=<`'.contains(data)) { _addToken(ParseErrorToken('equals-in-unquoted-attribute-value')); _markAttributeValueStart(-1); _attributeValue.write(data); state = attributeValueUnQuotedState; } else { _markAttributeValueStart(-1); _attributeValue.write(data); state = attributeValueUnQuotedState; } return true; } bool attributeValueDoubleQuotedState() { var data = stream.char(); if (data == '"') { _markAttributeValueEnd(-1); _markAttributeEnd(0); state = afterAttributeValueState; } else if (data == '&') { processEntityInAttribute('"'); } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); _attributeValue.write('\uFFFD'); } else if (data == eof) { _addToken(ParseErrorToken('eof-in-attribute-value-double-quote')); _markAttributeValueEnd(-1); state = dataState; } else { _attributeValue.write(data); _attributeValue.write(stream.charsUntil('"&')); } return true; } bool attributeValueSingleQuotedState() { var data = stream.char(); if (data == "'") { _markAttributeValueEnd(-1); _markAttributeEnd(0); state = afterAttributeValueState; } else if (data == '&') { processEntityInAttribute("'"); } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); _attributeValue.write('\uFFFD'); } else if (data == eof) { _addToken(ParseErrorToken('eof-in-attribute-value-single-quote')); _markAttributeValueEnd(-1); state = dataState; } else { _attributeValue.write(data); _attributeValue.write(stream.charsUntil("\'&")); } return true; } bool attributeValueUnQuotedState() { var data = stream.char(); if (isWhitespace(data)) { _markAttributeValueEnd(-1); state = beforeAttributeNameState; } else if (data == '&') { processEntityInAttribute('>'); } else if (data == '>') { _markAttributeValueEnd(-1); emitCurrentToken(); } else if (data == eof) { _addToken(ParseErrorToken('eof-in-attribute-value-no-quotes')); _markAttributeValueEnd(-1); state = dataState; } else if ('"\'=<`'.contains(data)) { _addToken( ParseErrorToken('unexpected-character-in-unquoted-attribute-value')); _attributeValue.write(data); } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); _attributeValue.write('\uFFFD'); } else { _attributeValue.write(data); _attributeValue.write(stream.charsUntil("&>\"\'=<`$spaceCharacters")); } return true; } bool afterAttributeValueState() { var data = stream.char(); if (isWhitespace(data)) { state = beforeAttributeNameState; } else if (data == '>') { emitCurrentToken(); } else if (data == '/') { state = selfClosingStartTagState; } else if (data == eof) { _addToken(ParseErrorToken('unexpected-EOF-after-attribute-value')); stream.unget(data); state = dataState; } else { _addToken(ParseErrorToken('unexpected-character-after-attribute-value')); stream.unget(data); state = beforeAttributeNameState; } return true; } bool selfClosingStartTagState() { var data = stream.char(); if (data == '>') { currentTagToken.selfClosing = true; emitCurrentToken(); } else if (data == eof) { _addToken(ParseErrorToken('unexpected-EOF-after-solidus-in-tag')); stream.unget(data); state = dataState; } else { _addToken(ParseErrorToken('unexpected-character-after-soldius-in-tag')); stream.unget(data); state = beforeAttributeNameState; } return true; } bool bogusCommentState() { // Make a new comment token and give it as value all the characters // until the first > or EOF (charsUntil checks for EOF automatically) // and emit it. var data = stream.charsUntil('>'); data = data.replaceAll('\u0000', '\uFFFD'); _addToken(CommentToken(data)); // Eat the character directly after the bogus comment which is either a // ">" or an EOF. stream.char(); state = dataState; return true; } bool markupDeclarationOpenState() { var charStack = [stream.char()]; if (charStack.last == '-') { charStack.add(stream.char()); if (charStack.last == '-') { currentToken = CommentToken(); state = commentStartState; return true; } } else if (charStack.last == 'd' || charStack.last == 'D') { var matched = true; for (var expected in const ['oO', 'cC', 'tT', 'yY', 'pP', 'eE']) { var char = stream.char(); charStack.add(char); if (char == eof || !expected.contains(char)) { matched = false; break; } } if (matched) { currentToken = DoctypeToken(correct: true); state = doctypeState; return true; } } else if (charStack.last == '[' && parser != null && parser.tree.openElements.isNotEmpty && parser.tree.openElements.last.namespaceUri != parser.tree.defaultNamespace) { var matched = true; for (var expected in const ['C', 'D', 'A', 'T', 'A', '[']) { charStack.add(stream.char()); if (charStack.last != expected) { matched = false; break; } } if (matched) { state = cdataSectionState; return true; } } _addToken(ParseErrorToken('expected-dashes-or-doctype')); while (charStack.isNotEmpty) { stream.unget(charStack.removeLast()); } state = bogusCommentState; return true; } bool commentStartState() { var data = stream.char(); if (data == '-') { state = commentStartDashState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); currentStringToken.add('\uFFFD'); } else if (data == '>') { _addToken(ParseErrorToken('incorrect-comment')); _addToken(currentToken); state = dataState; } else if (data == eof) { _addToken(ParseErrorToken('eof-in-comment')); _addToken(currentToken); state = dataState; } else { currentStringToken.add(data); state = commentState; } return true; } bool commentStartDashState() { var data = stream.char(); if (data == '-') { state = commentEndState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); currentStringToken.add('-\uFFFD'); } else if (data == '>') { _addToken(ParseErrorToken('incorrect-comment')); _addToken(currentToken); state = dataState; } else if (data == eof) { _addToken(ParseErrorToken('eof-in-comment')); _addToken(currentToken); state = dataState; } else { currentStringToken.add('-').add(data); state = commentState; } return true; } bool commentState() { var data = stream.char(); if (data == '-') { state = commentEndDashState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); currentStringToken.add('\uFFFD'); } else if (data == eof) { _addToken(ParseErrorToken('eof-in-comment')); _addToken(currentToken); state = dataState; } else { currentStringToken.add(data).add(stream.charsUntil('-\u0000')); } return true; } bool commentEndDashState() { var data = stream.char(); if (data == '-') { state = commentEndState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); currentStringToken.add('-\uFFFD'); state = commentState; } else if (data == eof) { _addToken(ParseErrorToken('eof-in-comment-end-dash')); _addToken(currentToken); state = dataState; } else { currentStringToken.add('-').add(data); state = commentState; } return true; } bool commentEndState() { var data = stream.char(); if (data == '>') { _addToken(currentToken); state = dataState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); currentStringToken.add('--\uFFFD'); state = commentState; } else if (data == '!') { _addToken( ParseErrorToken('unexpected-bang-after-double-dash-in-comment')); state = commentEndBangState; } else if (data == '-') { _addToken( ParseErrorToken('unexpected-dash-after-double-dash-in-comment')); currentStringToken.add(data); } else if (data == eof) { _addToken(ParseErrorToken('eof-in-comment-double-dash')); _addToken(currentToken); state = dataState; } else { // XXX _addToken(ParseErrorToken('unexpected-char-in-comment')); currentStringToken.add('--').add(data); state = commentState; } return true; } bool commentEndBangState() { var data = stream.char(); if (data == '>') { _addToken(currentToken); state = dataState; } else if (data == '-') { currentStringToken.add('--!'); state = commentEndDashState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); currentStringToken.add('--!\uFFFD'); state = commentState; } else if (data == eof) { _addToken(ParseErrorToken('eof-in-comment-end-bang-state')); _addToken(currentToken); state = dataState; } else { currentStringToken.add('--!').add(data); state = commentState; } return true; } bool doctypeState() { var data = stream.char(); if (isWhitespace(data)) { state = beforeDoctypeNameState; } else if (data == eof) { _addToken(ParseErrorToken('expected-doctype-name-but-got-eof')); currentDoctypeToken.correct = false; _addToken(currentToken); state = dataState; } else { _addToken(ParseErrorToken('need-space-after-doctype')); stream.unget(data); state = beforeDoctypeNameState; } return true; } bool beforeDoctypeNameState() { var data = stream.char(); if (isWhitespace(data)) { return true; } else if (data == '>') { _addToken(ParseErrorToken('expected-doctype-name-but-got-right-bracket')); currentDoctypeToken.correct = false; _addToken(currentToken); state = dataState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); currentDoctypeToken.name = '\uFFFD'; state = doctypeNameState; } else if (data == eof) { _addToken(ParseErrorToken('expected-doctype-name-but-got-eof')); currentDoctypeToken.correct = false; _addToken(currentToken); state = dataState; } else { currentDoctypeToken.name = data; state = doctypeNameState; } return true; } bool doctypeNameState() { var data = stream.char(); if (isWhitespace(data)) { currentDoctypeToken.name = asciiUpper2Lower(currentDoctypeToken.name); state = afterDoctypeNameState; } else if (data == '>') { currentDoctypeToken.name = asciiUpper2Lower(currentDoctypeToken.name); _addToken(currentToken); state = dataState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); currentDoctypeToken.name = '${currentDoctypeToken.name}\uFFFD'; state = doctypeNameState; } else if (data == eof) { _addToken(ParseErrorToken('eof-in-doctype-name')); currentDoctypeToken.correct = false; currentDoctypeToken.name = asciiUpper2Lower(currentDoctypeToken.name); _addToken(currentToken); state = dataState; } else { currentDoctypeToken.name = '${currentDoctypeToken.name}$data'; } return true; } bool afterDoctypeNameState() { var data = stream.char(); if (isWhitespace(data)) { return true; } else if (data == '>') { _addToken(currentToken); state = dataState; } else if (data == eof) { currentDoctypeToken.correct = false; stream.unget(data); _addToken(ParseErrorToken('eof-in-doctype')); _addToken(currentToken); state = dataState; } else { if (data == 'p' || data == 'P') { // TODO(jmesserly): would be nice to have a helper for this. var matched = true; for (var expected in const ['uU', 'bB', 'lL', 'iI', 'cC']) { data = stream.char(); if (data == eof || !expected.contains(data)) { matched = false; break; } } if (matched) { state = afterDoctypePublicKeywordState; return true; } } else if (data == 's' || data == 'S') { var matched = true; for (var expected in const ['yY', 'sS', 'tT', 'eE', 'mM']) { data = stream.char(); if (data == eof || !expected.contains(data)) { matched = false; break; } } if (matched) { state = afterDoctypeSystemKeywordState; return true; } } // All the characters read before the current 'data' will be // [a-zA-Z], so they're garbage in the bogus doctype and can be // discarded; only the latest character might be '>' or EOF // and needs to be ungetted stream.unget(data); _addToken(ParseErrorToken('expected-space-or-right-bracket-in-doctype', messageParams: {'data': data})); currentDoctypeToken.correct = false; state = bogusDoctypeState; } return true; } bool afterDoctypePublicKeywordState() { var data = stream.char(); if (isWhitespace(data)) { state = beforeDoctypePublicIdentifierState; } else if (data == "'" || data == '"') { _addToken(ParseErrorToken('unexpected-char-in-doctype')); stream.unget(data); state = beforeDoctypePublicIdentifierState; } else if (data == eof) { _addToken(ParseErrorToken('eof-in-doctype')); currentDoctypeToken.correct = false; _addToken(currentToken); state = dataState; } else { stream.unget(data); state = beforeDoctypePublicIdentifierState; } return true; } bool beforeDoctypePublicIdentifierState() { var data = stream.char(); if (isWhitespace(data)) { return true; } else if (data == '"') { currentDoctypeToken.publicId = ''; state = doctypePublicIdentifierDoubleQuotedState; } else if (data == "'") { currentDoctypeToken.publicId = ''; state = doctypePublicIdentifierSingleQuotedState; } else if (data == '>') { _addToken(ParseErrorToken('unexpected-end-of-doctype')); currentDoctypeToken.correct = false; _addToken(currentToken); state = dataState; } else if (data == eof) { _addToken(ParseErrorToken('eof-in-doctype')); currentDoctypeToken.correct = false; _addToken(currentToken); state = dataState; } else { _addToken(ParseErrorToken('unexpected-char-in-doctype')); currentDoctypeToken.correct = false; state = bogusDoctypeState; } return true; } bool doctypePublicIdentifierDoubleQuotedState() { var data = stream.char(); if (data == '"') { state = afterDoctypePublicIdentifierState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); currentDoctypeToken.publicId = '${currentDoctypeToken.publicId}\uFFFD'; } else if (data == '>') { _addToken(ParseErrorToken('unexpected-end-of-doctype')); currentDoctypeToken.correct = false; _addToken(currentToken); state = dataState; } else if (data == eof) { _addToken(ParseErrorToken('eof-in-doctype')); currentDoctypeToken.correct = false; _addToken(currentToken); state = dataState; } else { currentDoctypeToken.publicId = '${currentDoctypeToken.publicId}$data'; } return true; } bool doctypePublicIdentifierSingleQuotedState() { var data = stream.char(); if (data == "'") { state = afterDoctypePublicIdentifierState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); currentDoctypeToken.publicId = '${currentDoctypeToken.publicId}\uFFFD'; } else if (data == '>') { _addToken(ParseErrorToken('unexpected-end-of-doctype')); currentDoctypeToken.correct = false; _addToken(currentToken); state = dataState; } else if (data == eof) { _addToken(ParseErrorToken('eof-in-doctype')); currentDoctypeToken.correct = false; _addToken(currentToken); state = dataState; } else { currentDoctypeToken.publicId = '${currentDoctypeToken.publicId}$data'; } return true; } bool afterDoctypePublicIdentifierState() { var data = stream.char(); if (isWhitespace(data)) { state = betweenDoctypePublicAndSystemIdentifiersState; } else if (data == '>') { _addToken(currentToken); state = dataState; } else if (data == '"') { _addToken(ParseErrorToken('unexpected-char-in-doctype')); currentDoctypeToken.systemId = ''; state = doctypeSystemIdentifierDoubleQuotedState; } else if (data == "'") { _addToken(ParseErrorToken('unexpected-char-in-doctype')); currentDoctypeToken.systemId = ''; state = doctypeSystemIdentifierSingleQuotedState; } else if (data == eof) { _addToken(ParseErrorToken('eof-in-doctype')); currentDoctypeToken.correct = false; _addToken(currentToken); state = dataState; } else { _addToken(ParseErrorToken('unexpected-char-in-doctype')); currentDoctypeToken.correct = false; state = bogusDoctypeState; } return true; } bool betweenDoctypePublicAndSystemIdentifiersState() { var data = stream.char(); if (isWhitespace(data)) { return true; } else if (data == '>') { _addToken(currentToken); state = dataState; } else if (data == '"') { currentDoctypeToken.systemId = ''; state = doctypeSystemIdentifierDoubleQuotedState; } else if (data == "'") { currentDoctypeToken.systemId = ''; state = doctypeSystemIdentifierSingleQuotedState; } else if (data == eof) { _addToken(ParseErrorToken('eof-in-doctype')); currentDoctypeToken.correct = false; _addToken(currentToken); state = dataState; } else { _addToken(ParseErrorToken('unexpected-char-in-doctype')); currentDoctypeToken.correct = false; state = bogusDoctypeState; } return true; } bool afterDoctypeSystemKeywordState() { var data = stream.char(); if (isWhitespace(data)) { state = beforeDoctypeSystemIdentifierState; } else if (data == "'" || data == '"') { _addToken(ParseErrorToken('unexpected-char-in-doctype')); stream.unget(data); state = beforeDoctypeSystemIdentifierState; } else if (data == eof) { _addToken(ParseErrorToken('eof-in-doctype')); currentDoctypeToken.correct = false; _addToken(currentToken); state = dataState; } else { stream.unget(data); state = beforeDoctypeSystemIdentifierState; } return true; } bool beforeDoctypeSystemIdentifierState() { var data = stream.char(); if (isWhitespace(data)) { return true; } else if (data == '"') { currentDoctypeToken.systemId = ''; state = doctypeSystemIdentifierDoubleQuotedState; } else if (data == "'") { currentDoctypeToken.systemId = ''; state = doctypeSystemIdentifierSingleQuotedState; } else if (data == '>') { _addToken(ParseErrorToken('unexpected-char-in-doctype')); currentDoctypeToken.correct = false; _addToken(currentToken); state = dataState; } else if (data == eof) { _addToken(ParseErrorToken('eof-in-doctype')); currentDoctypeToken.correct = false; _addToken(currentToken); state = dataState; } else { _addToken(ParseErrorToken('unexpected-char-in-doctype')); currentDoctypeToken.correct = false; state = bogusDoctypeState; } return true; } bool doctypeSystemIdentifierDoubleQuotedState() { var data = stream.char(); if (data == '"') { state = afterDoctypeSystemIdentifierState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); currentDoctypeToken.systemId = '${currentDoctypeToken.systemId}\uFFFD'; } else if (data == '>') { _addToken(ParseErrorToken('unexpected-end-of-doctype')); currentDoctypeToken.correct = false; _addToken(currentToken); state = dataState; } else if (data == eof) { _addToken(ParseErrorToken('eof-in-doctype')); currentDoctypeToken.correct = false; _addToken(currentToken); state = dataState; } else { currentDoctypeToken.systemId = '${currentDoctypeToken.systemId}$data'; } return true; } bool doctypeSystemIdentifierSingleQuotedState() { var data = stream.char(); if (data == "'") { state = afterDoctypeSystemIdentifierState; } else if (data == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); currentDoctypeToken.systemId = '${currentDoctypeToken.systemId}\uFFFD'; } else if (data == '>') { _addToken(ParseErrorToken('unexpected-end-of-doctype')); currentDoctypeToken.correct = false; _addToken(currentToken); state = dataState; } else if (data == eof) { _addToken(ParseErrorToken('eof-in-doctype')); currentDoctypeToken.correct = false; _addToken(currentToken); state = dataState; } else { currentDoctypeToken.systemId = '${currentDoctypeToken.systemId}$data'; } return true; } bool afterDoctypeSystemIdentifierState() { var data = stream.char(); if (isWhitespace(data)) { return true; } else if (data == '>') { _addToken(currentToken); state = dataState; } else if (data == eof) { _addToken(ParseErrorToken('eof-in-doctype')); currentDoctypeToken.correct = false; _addToken(currentToken); state = dataState; } else { _addToken(ParseErrorToken('unexpected-char-in-doctype')); state = bogusDoctypeState; } return true; } bool bogusDoctypeState() { var data = stream.char(); if (data == '>') { _addToken(currentToken); state = dataState; } else if (data == eof) { // XXX EMIT stream.unget(data); _addToken(currentToken); state = dataState; } return true; } bool cdataSectionState() { var data = <String>[]; var matchedEnd = 0; while (true) { var ch = stream.char(); if (ch == eof) { break; } // Deal with null here rather than in the parser if (ch == '\u0000') { _addToken(ParseErrorToken('invalid-codepoint')); ch = '\uFFFD'; } data.add(ch); // TODO(jmesserly): it'd be nice if we had an easier way to match the end, // perhaps with a "peek" API. if (ch == ']' && matchedEnd < 2) { matchedEnd++; } else if (ch == '>' && matchedEnd == 2) { // Remove "]]>" from the end. data.removeLast(); data.removeLast(); data.removeLast(); break; } else { matchedEnd = 0; } } if (data.isNotEmpty) { _addToken(CharactersToken(data.join())); } state = dataState; return true; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html/src/css_class_set.dart
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // TODO(jmesserly): everything in this file is copied straight from "dart:html". library html.dom.src; import 'dart:collection'; import 'package:html/dom.dart'; class ElementCssClassSet extends _CssClassSetImpl { final Element _element; ElementCssClassSet(this._element); @override Set<String> readClasses() { var s = LinkedHashSet<String>(); var classname = _element.className; for (var name in classname.split(' ')) { var trimmed = name.trim(); if (trimmed.isNotEmpty) { s.add(trimmed); } } return s; } @override void writeClasses(Set<String> s) { _element.className = s.join(' '); } } /// A Set that stores the CSS class names for an element. abstract class CssClassSet implements Set<String> { /// Adds the class [value] to the element if it is not on it, removes it if it /// is. /// /// If [shouldAdd] is true, then we always add that [value] to the element. If /// [shouldAdd] is false then we always remove [value] from the element. bool toggle(String value, [bool shouldAdd]); /// Returns [:true:] if classes cannot be added or removed from this /// [:CssClassSet:]. bool get frozen; /// Determine if this element contains the class [value]. /// /// This is the Dart equivalent of jQuery's /// [hasClass](http://api.jquery.com/hasClass/). @override bool contains(Object value); /// Add the class [value] to element. /// /// This is the Dart equivalent of jQuery's /// [addClass](http://api.jquery.com/addClass/). /// /// If this corresponds to one element. Returns true if [value] was added to /// the set, otherwise false. /// /// If this corresponds to many elements, null is always returned. @override bool add(String value); /// Remove the class [value] from element, and return true on successful /// removal. /// /// This is the Dart equivalent of jQuery's /// [removeClass](http://api.jquery.com/removeClass/). @override bool remove(Object value); /// Add all classes specified in [iterable] to element. /// /// This is the Dart equivalent of jQuery's /// [addClass](http://api.jquery.com/addClass/). @override void addAll(Iterable<String> iterable); /// Remove all classes specified in [iterable] from element. /// /// This is the Dart equivalent of jQuery's /// [removeClass](http://api.jquery.com/removeClass/). @override void removeAll(Iterable<Object> iterable); /// Toggles all classes specified in [iterable] on element. /// /// Iterate through [iterable]'s items, and add it if it is not on it, or /// remove it if it is. This is the Dart equivalent of jQuery's /// [toggleClass](http://api.jquery.com/toggleClass/). /// If [shouldAdd] is true, then we always add all the classes in [iterable] /// element. If [shouldAdd] is false then we always remove all the classes in /// [iterable] from the element. void toggleAll(Iterable<String> iterable, [bool shouldAdd]); } abstract class _CssClassSetImpl extends SetBase<String> implements CssClassSet { @override String toString() { return readClasses().join(' '); } /// Adds the class [value] to the element if it is not on it, removes it if it /// is. /// /// If [shouldAdd] is true, then we always add that [value] to the element. If /// [shouldAdd] is false then we always remove [value] from the element. @override bool toggle(String value, [bool shouldAdd]) { var s = readClasses(); var result = false; shouldAdd ??= !s.contains(value); if (shouldAdd) { s.add(value); result = true; } else { s.remove(value); } writeClasses(s); return result; } /// Returns [:true:] if classes cannot be added or removed from this /// [:CssClassSet:]. @override bool get frozen => false; @override Iterator<String> get iterator => readClasses().iterator; @override int get length => readClasses().length; // interface Set - BEGIN /// Determine if this element contains the class [value]. /// /// This is the Dart equivalent of jQuery's /// [hasClass](http://api.jquery.com/hasClass/). @override bool contains(Object value) => readClasses().contains(value); /// Lookup from the Set interface. Not interesting for a String set. @override String lookup(Object value) => contains(value) ? value as String : null; @override Set<String> toSet() => readClasses().toSet(); /// Add the class [value] to element. /// /// This is the Dart equivalent of jQuery's /// [addClass](http://api.jquery.com/addClass/). @override bool add(String value) { // TODO - figure out if we need to do any validation here // or if the browser natively does enough. return _modify((s) => s.add(value)); } /// Remove the class [value] from element, and return true on successful /// removal. /// /// This is the Dart equivalent of jQuery's /// [removeClass](http://api.jquery.com/removeClass/). @override bool remove(Object value) { if (value is! String) return false; var s = readClasses(); var result = s.remove(value); writeClasses(s); return result; } /// Toggles all classes specified in [iterable] on element. /// /// Iterate through [iterable]'s items, and add it if it is not on it, or /// remove it if it is. This is the Dart equivalent of jQuery's /// [toggleClass](http://api.jquery.com/toggleClass/). /// If [shouldAdd] is true, then we always add all the classes in [iterable] /// element. If [shouldAdd] is false then we always remove all the classes in /// [iterable] from the element. @override void toggleAll(Iterable<String> iterable, [bool shouldAdd]) { iterable.forEach((e) => toggle(e, shouldAdd)); } /// Helper method used to modify the set of css classes on this element. /// /// f - callback with: /// s - a Set of all the css class name currently on this element. /// /// After f returns, the modified set is written to the /// className property of this element. bool _modify(bool Function(Set<String>) f) { var s = readClasses(); var ret = f(s); writeClasses(s); return ret; } /// Read the class names from the Element class property, /// and put them into a set (duplicates are discarded). /// This is intended to be overridden by specific implementations. Set<String> readClasses(); /// Join all the elements of a set into one string and write /// back to the element. /// This is intended to be overridden by specific implementations. void writeClasses(Set<String> s); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html/src/html_input_stream.dart
import 'dart:collection'; import 'dart:convert' show ascii, utf8; import 'package:source_span/source_span.dart'; import 'constants.dart'; import 'encoding_parser.dart'; import 'utils.dart'; /// Provides a unicode stream of characters to the HtmlTokenizer. /// /// This class takes care of character encoding and removing or replacing /// incorrect byte-sequences and also provides column and line tracking. class HtmlInputStream { /// Number of bytes to use when looking for a meta element with /// encoding information. static const int numBytesMeta = 512; /// Encoding to use if no other information can be found. static const String defaultEncoding = 'utf-8'; /// The name of the character encoding. String charEncodingName; /// True if we are certain about [charEncodingName], false for tenative. bool charEncodingCertain = true; final bool generateSpans; /// Location where the contents of the stream were found. final String sourceUrl; List<int> _rawBytes; /// Raw UTF-16 codes, used if a Dart String is passed in. List<int> _rawChars; Queue<String> errors; SourceFile fileInfo; List<int> _lineStarts; List<int> _chars; int _offset; /// Initialises the HtmlInputStream. /// /// HtmlInputStream(source, [encoding]) -> Normalized stream from source /// for use by html5lib. /// /// [source] can be either a [String] or a [List<int>] containing the raw /// bytes, or a file if [consoleSupport] is initialized. /// /// The optional encoding parameter must be a string that indicates /// the encoding. If specified, that encoding will be used, /// regardless of any BOM or later declaration (such as in a meta /// element) /// /// [parseMeta] - Look for a <meta> element containing encoding information HtmlInputStream(source, [String encoding, bool parseMeta = true, this.generateSpans = false, this.sourceUrl]) : charEncodingName = codecName(encoding) { if (source is String) { _rawChars = source.codeUnits; charEncodingName = 'utf-8'; charEncodingCertain = true; } else if (source is List<int>) { _rawBytes = source; } else { throw ArgumentError.value( source, 'source', 'Must be a String or List<int>.'); } // Detect encoding iff no explicit "transport level" encoding is supplied if (charEncodingName == null) { detectEncoding(parseMeta); } reset(); } void reset() { errors = Queue<String>(); _offset = 0; _lineStarts = <int>[0]; _chars = <int>[]; _rawChars ??= _decodeBytes(charEncodingName, _rawBytes); var skipNewline = false; var wasSurrogatePair = false; for (var i = 0; i < _rawChars.length; i++) { var c = _rawChars[i]; if (skipNewline) { skipNewline = false; if (c == NEWLINE) continue; } final isSurrogatePair = _isSurrogatePair(_rawChars, i); if (!isSurrogatePair && !wasSurrogatePair) { if (_invalidUnicode(c)) { errors.add('invalid-codepoint'); if (0xD800 <= c && c <= 0xDFFF) { c = 0xFFFD; } } } wasSurrogatePair = isSurrogatePair; if (c == RETURN) { skipNewline = true; c = NEWLINE; } _chars.add(c); if (c == NEWLINE) _lineStarts.add(_chars.length); } // Free decoded characters if they aren't needed anymore. if (_rawBytes != null) _rawChars = null; // TODO(sigmund): Don't parse the file at all if spans aren't being // generated. fileInfo = SourceFile.decoded(_chars, url: sourceUrl); } void detectEncoding([bool parseMeta = true]) { // First look for a BOM // This will also read past the BOM if present charEncodingName = detectBOM(); charEncodingCertain = true; // If there is no BOM need to look for meta elements with encoding // information if (charEncodingName == null && parseMeta) { charEncodingName = detectEncodingMeta(); charEncodingCertain = false; } // If all else fails use the default encoding if (charEncodingName == null) { charEncodingCertain = false; charEncodingName = defaultEncoding; } // Substitute for equivalent encodings: if (charEncodingName.toLowerCase() == 'iso-8859-1') { charEncodingName = 'windows-1252'; } } void changeEncoding(String newEncoding) { if (_rawBytes == null) { // We should never get here -- if encoding is certain we won't try to // change it. throw StateError('cannot change encoding when parsing a String.'); } newEncoding = codecName(newEncoding); if (const ['utf-16', 'utf-16-be', 'utf-16-le'].contains(newEncoding)) { newEncoding = 'utf-8'; } if (newEncoding == null) { return; } else if (newEncoding == charEncodingName) { charEncodingCertain = true; } else { charEncodingName = newEncoding; charEncodingCertain = true; _rawChars = null; reset(); throw ReparseException( 'Encoding changed from $charEncodingName to $newEncoding'); } } /// Attempts to detect at BOM at the start of the stream. If /// an encoding can be determined from the BOM return the name of the /// encoding otherwise return null. String detectBOM() { // Try detecting the BOM using bytes from the string if (_hasUtf8Bom(_rawBytes)) { return 'utf-8'; } return null; } /// Report the encoding declared by the meta element. String detectEncodingMeta() { var parser = EncodingParser(slice(_rawBytes, 0, numBytesMeta)); var encoding = parser.getEncoding(); if (const ['utf-16', 'utf-16-be', 'utf-16-le'].contains(encoding)) { encoding = 'utf-8'; } return encoding; } /// Returns the current offset in the stream, i.e. the number of codepoints /// since the start of the file. int get position => _offset; /// Read one character from the stream or queue if available. Return /// EOF when EOF is reached. String char() { if (_offset >= _chars.length) return eof; return _isSurrogatePair(_chars, _offset) ? String.fromCharCodes([_chars[_offset++], _chars[_offset++]]) : String.fromCharCodes([_chars[_offset++]]); } String peekChar() { if (_offset >= _chars.length) return eof; return _isSurrogatePair(_chars, _offset) ? String.fromCharCodes([_chars[_offset], _chars[_offset + 1]]) : String.fromCharCodes([_chars[_offset]]); } // Whether the current and next chars indicate a surrogate pair. bool _isSurrogatePair(List<int> chars, int i) { return i + 1 < chars.length && _isLeadSurrogate(chars[i]) && _isTrailSurrogate(chars[i + 1]); } // Is then code (a 16-bit unsigned integer) a UTF-16 lead surrogate. bool _isLeadSurrogate(int code) => (code & 0xFC00) == 0xD800; // Is then code (a 16-bit unsigned integer) a UTF-16 trail surrogate. bool _isTrailSurrogate(int code) => (code & 0xFC00) == 0xDC00; /// Returns a string of characters from the stream up to but not /// including any character in 'characters' or EOF. String charsUntil(String characters, [bool opposite = false]) { var start = _offset; String c; while ((c = peekChar()) != null && characters.contains(c) == opposite) { _offset += c.codeUnits.length; } return String.fromCharCodes(_chars.sublist(start, _offset)); } void unget(String ch) { // Only one character is allowed to be ungotten at once - it must // be consumed again before any further call to unget if (ch != null) { _offset -= ch.codeUnits.length; assert(peekChar() == ch); } } } // TODO(jmesserly): the Python code used a regex to check for this. But // Dart doesn't let you create a regexp with invalid characters. bool _invalidUnicode(int c) { if (0x0001 <= c && c <= 0x0008) return true; if (0x000E <= c && c <= 0x001F) return true; if (0x007F <= c && c <= 0x009F) return true; if (0xD800 <= c && c <= 0xDFFF) return true; if (0xFDD0 <= c && c <= 0xFDEF) return true; switch (c) { case 0x000B: case 0xFFFE: case 0xFFFF: case 0x01FFFE: case 0x01FFFF: case 0x02FFFE: case 0x02FFFF: case 0x03FFFE: case 0x03FFFF: case 0x04FFFE: case 0x04FFFF: case 0x05FFFE: case 0x05FFFF: case 0x06FFFE: case 0x06FFFF: case 0x07FFFE: case 0x07FFFF: case 0x08FFFE: case 0x08FFFF: case 0x09FFFE: case 0x09FFFF: case 0x0AFFFE: case 0x0AFFFF: case 0x0BFFFE: case 0x0BFFFF: case 0x0CFFFE: case 0x0CFFFF: case 0x0DFFFE: case 0x0DFFFF: case 0x0EFFFE: case 0x0EFFFF: case 0x0FFFFE: case 0x0FFFFF: case 0x10FFFE: case 0x10FFFF: return true; } return false; } /// Return the python codec name corresponding to an encoding or null if the /// string doesn't correspond to a valid encoding. String codecName(String encoding) { final asciiPunctuation = RegExp( '[\u0009-\u000D\u0020-\u002F\u003A-\u0040\u005B-\u0060\u007B-\u007E]'); if (encoding == null) return null; var canonicalName = encoding.replaceAll(asciiPunctuation, '').toLowerCase(); return encodings[canonicalName]; } /// Returns true if the [bytes] starts with a UTF-8 byte order mark. /// Since UTF-8 doesn't have byte order, it's somewhat of a misnomer, but it is /// used in HTML to detect the UTF- bool _hasUtf8Bom(List<int> bytes, [int offset = 0, int length]) { var end = length != null ? offset + length : bytes.length; return (offset + 3) <= end && bytes[offset] == 0xEF && bytes[offset + 1] == 0xBB && bytes[offset + 2] == 0xBF; } /// Decodes the [bytes] with the provided [encoding] and returns a list for /// the codepoints. Supports the major unicode encodings as well as ascii and /// and windows-1252 encodings. List<int> _decodeBytes(String encoding, List<int> bytes) { switch (encoding) { case 'ascii': return ascii.decode(bytes).codeUnits; case 'utf-8': // NOTE: To match the behavior of the other decode functions, we eat the // UTF-8 BOM here. This is the default behavior of `utf8.decode`. return utf8.decode(bytes).codeUnits; default: throw ArgumentError('Encoding $encoding not supported'); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html/src/encoding_parser.dart
import 'constants.dart'; import 'html_input_stream.dart'; // TODO(jmesserly): I converted StopIteration to StateError("No more elements"). // Seems strange to throw this from outside of an iterator though. /// String-like object with an associated position and various extra methods /// If the position is ever greater than the string length then an exception is /// raised. class EncodingBytes { final String _bytes; int __position = -1; EncodingBytes(this._bytes); int get _length => _bytes.length; String _next() { var p = __position = __position + 1; if (p >= _length) { throw StateError('No more elements'); } else if (p < 0) { throw RangeError(p); } return _bytes[p]; } String _previous() { var p = __position; if (p >= _length) { throw StateError('No more elements'); } else if (p < 0) { throw RangeError(p); } __position = p = p - 1; return _bytes[p]; } set _position(int value) { if (__position >= _length) { throw StateError('No more elements'); } __position = value; } int get _position { if (__position >= _length) { throw StateError('No more elements'); } if (__position >= 0) { return __position; } else { return 0; } } String get _currentByte => _bytes[_position]; /// Skip past a list of characters. Defaults to skipping [isWhitespace]. String _skipChars([_CharPredicate skipChars]) { skipChars ??= isWhitespace; var p = _position; // use property for the error-checking while (p < _length) { var c = _bytes[p]; if (!skipChars(c)) { __position = p; return c; } p += 1; } __position = p; return null; } String _skipUntil(_CharPredicate untilChars) { var p = _position; while (p < _length) { var c = _bytes[p]; if (untilChars(c)) { __position = p; return c; } p += 1; } return null; } /// Look for a sequence of bytes at the start of a string. If the bytes /// are found return true and advance the position to the byte after the /// match. Otherwise return false and leave the position alone. bool _matchBytes(String bytes) { var p = _position; if (_bytes.length < p + bytes.length) { return false; } var data = _bytes.substring(p, p + bytes.length); if (data == bytes) { _position += bytes.length; return true; } return false; } /// Look for the next sequence of bytes matching a given sequence. If /// a match is found advance the position to the last byte of the match bool _jumpTo(String bytes) { var newPosition = _bytes.indexOf(bytes, _position); if (newPosition >= 0) { __position = newPosition + bytes.length - 1; return true; } else { throw StateError('No more elements'); } } String _slice(int start, [int end]) { end ??= _length; if (end < 0) end += _length; return _bytes.substring(start, end); } } typedef _MethodHandler = bool Function(); class _DispatchEntry { final String pattern; final _MethodHandler handler; _DispatchEntry(this.pattern, this.handler); } /// Mini parser for detecting character encoding from meta elements. class EncodingParser { final EncodingBytes _data; String _encoding; /// [bytes] - the data to work on for encoding detection. EncodingParser(List<int> bytes) // Note: this is intentionally interpreting bytes as codepoints. : _data = EncodingBytes(String.fromCharCodes(bytes).toLowerCase()); String getEncoding() { final methodDispatch = [ _DispatchEntry('<!--', _handleComment), _DispatchEntry('<meta', _handleMeta), _DispatchEntry('</', _handlePossibleEndTag), _DispatchEntry('<!', _handleOther), _DispatchEntry('<?', _handleOther), _DispatchEntry('<', _handlePossibleStartTag), ]; try { for (;;) { for (var dispatch in methodDispatch) { if (_data._matchBytes(dispatch.pattern)) { var keepParsing = dispatch.handler(); if (keepParsing) break; // We found an encoding. Stop. return _encoding; } } _data._position += 1; } } on StateError catch (_) { // Catch this here to match behavior of Python's StopIteration // TODO(jmesserly): refactor to not use exceptions } return _encoding; } /// Skip over comments. bool _handleComment() => _data._jumpTo('-->'); bool _handleMeta() { if (!isWhitespace(_data._currentByte)) { // if we have <meta not followed by a space so just keep going return true; } // We have a valid meta element we want to search for attributes while (true) { // Try to find the next attribute after the current position var attr = _getAttribute(); if (attr == null) return true; if (attr[0] == 'charset') { var tentativeEncoding = attr[1]; var codec = codecName(tentativeEncoding); if (codec != null) { _encoding = codec; return false; } } else if (attr[0] == 'content') { var contentParser = ContentAttrParser(EncodingBytes(attr[1])); var tentativeEncoding = contentParser.parse(); var codec = codecName(tentativeEncoding); if (codec != null) { _encoding = codec; return false; } } } } bool _handlePossibleStartTag() => _handlePossibleTag(false); bool _handlePossibleEndTag() { _data._next(); return _handlePossibleTag(true); } bool _handlePossibleTag(bool endTag) { if (!isLetter(_data._currentByte)) { //If the next byte is not an ascii letter either ignore this //fragment (possible start tag case) or treat it according to //handleOther if (endTag) { _data._previous(); _handleOther(); } return true; } var c = _data._skipUntil(_isSpaceOrAngleBracket); if (c == '<') { // return to the first step in the overall "two step" algorithm // reprocessing the < byte _data._previous(); } else { //Read all attributes var attr = _getAttribute(); while (attr != null) { attr = _getAttribute(); } } return true; } bool _handleOther() => _data._jumpTo('>'); /// Return a name,value pair for the next attribute in the stream, /// if one is found, or null List<String> _getAttribute() { // Step 1 (skip chars) var c = _data._skipChars((x) => x == '/' || isWhitespace(x)); // Step 2 if (c == '>' || c == null) { return null; } // Step 3 var attrName = []; var attrValue = []; // Step 4 attribute name while (true) { if (c == null) { return null; } else if (c == '=' && attrName.isNotEmpty) { break; } else if (isWhitespace(c)) { // Step 6! c = _data._skipChars(); c = _data._next(); break; } else if (c == '/' || c == '>') { return [attrName.join(), '']; } else if (isLetter(c)) { attrName.add(c.toLowerCase()); } else { attrName.add(c); } // Step 5 c = _data._next(); } // Step 7 if (c != '=') { _data._previous(); return [attrName.join(), '']; } // Step 8 _data._next(); // Step 9 c = _data._skipChars(); // Step 10 if (c == "'" || c == '"') { // 10.1 var quoteChar = c; while (true) { // 10.2 c = _data._next(); if (c == quoteChar) { // 10.3 _data._next(); return [attrName.join(), attrValue.join()]; } else if (isLetter(c)) { // 10.4 attrValue.add(c.toLowerCase()); } else { // 10.5 attrValue.add(c); } } } else if (c == '>') { return [attrName.join(), '']; } else if (c == null) { return null; } else if (isLetter(c)) { attrValue.add(c.toLowerCase()); } else { attrValue.add(c); } // Step 11 while (true) { c = _data._next(); if (_isSpaceOrAngleBracket(c)) { return [attrName.join(), attrValue.join()]; } else if (c == null) { return null; } else if (isLetter(c)) { attrValue.add(c.toLowerCase()); } else { attrValue.add(c); } } } } class ContentAttrParser { final EncodingBytes data; ContentAttrParser(this.data); String parse() { try { // Check if the attr name is charset // otherwise return data._jumpTo('charset'); data._position += 1; data._skipChars(); if (data._currentByte != '=') { // If there is no = sign keep looking for attrs return null; } data._position += 1; data._skipChars(); // Look for an encoding between matching quote marks if (data._currentByte == '"' || data._currentByte == "'") { var quoteMark = data._currentByte; data._position += 1; var oldPosition = data._position; if (data._jumpTo(quoteMark)) { return data._slice(oldPosition, data._position); } else { return null; } } else { // Unquoted value var oldPosition = data._position; try { data._skipUntil(isWhitespace); return data._slice(oldPosition, data._position); } on StateError catch (_) { //Return the whole remaining value return data._slice(oldPosition); } } } on StateError catch (_) { return null; } } } bool _isSpaceOrAngleBracket(String char) { return char == '>' || char == '<' || isWhitespace(char); } typedef _CharPredicate = bool Function(String char);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html/src/token.dart
/// This library contains token types used by the html5 tokenizer. library token; import 'dart:collection'; import 'package:source_span/source_span.dart'; /// An html5 token. abstract class Token { FileSpan span; int get kind; } abstract class TagToken extends Token { String name; bool selfClosing; TagToken(this.name, this.selfClosing); } class StartTagToken extends TagToken { /// The tag's attributes. A map from the name to the value, where the name /// can be a [String] or [AttributeName]. LinkedHashMap<dynamic, String> data; /// The attribute spans if requested. Otherwise null. List<TagAttribute> attributeSpans; bool selfClosingAcknowledged; /// The namespace. This is filled in later during tree building. String namespace; StartTagToken(String name, {this.data, bool selfClosing = false, this.selfClosingAcknowledged = false, this.namespace}) : super(name, selfClosing); @override int get kind => TokenKind.startTag; } class EndTagToken extends TagToken { EndTagToken(String name, {bool selfClosing = false}) : super(name, selfClosing); @override int get kind => TokenKind.endTag; } abstract class StringToken extends Token { StringBuffer _buffer; String _string; String get data { if (_string == null) { _string = _buffer.toString(); _buffer = null; } return _string; } StringToken(string) : _string = string, _buffer = string == null ? StringBuffer() : null; StringToken add(String data) { _buffer.write(data); return this; } } class ParseErrorToken extends StringToken { /// Extra information that goes along with the error message. Map messageParams; ParseErrorToken(String data, {this.messageParams}) : super(data); @override int get kind => TokenKind.parseError; } class CharactersToken extends StringToken { CharactersToken([String data]) : super(data); @override int get kind => TokenKind.characters; /// Replaces the token's [data]. This should only be used to wholly replace /// data, not to append data. void replaceData(String newData) { _string = newData; _buffer = null; } } class SpaceCharactersToken extends StringToken { SpaceCharactersToken([String data]) : super(data); @override int get kind => TokenKind.spaceCharacters; } class CommentToken extends StringToken { CommentToken([String data]) : super(data); @override int get kind => TokenKind.comment; } class DoctypeToken extends Token { String publicId; String systemId; String name = ''; bool correct; DoctypeToken({this.publicId, this.systemId, this.correct = false}); @override int get kind => TokenKind.doctype; } /// These are used by the tokenizer to build up the attribute map. /// They're also used by [StartTagToken.attributeSpans] if attribute spans are /// requested. class TagAttribute { String name; String value; // The spans of the attribute. This is not used unless we are computing an // attribute span on demand. int start; int end; int startValue; int endValue; TagAttribute(); } class TokenKind { static const int spaceCharacters = 0; static const int characters = 1; static const int startTag = 2; static const int endTag = 3; static const int comment = 4; static const int doctype = 5; static const int parseError = 6; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html/src/constants.dart
import 'utils.dart'; // TODO(jmesserly): fix up the const lists. For the bigger ones, we need faster // lookup than linear search "contains". In the Python code they were // frozensets. final String eof = null; class ReparseException implements Exception { final String message; ReparseException(this.message); @override String toString() => 'ReparseException: $message'; } // TODO(jmesserly): assuming the programmatic name is not important, it would be // good to make these "static const" fields on an ErrorMessage class. /// These are error messages emitted by [HtmlParser]. The values use Python /// style string formatting, as implemented by [formatStr]. That function only /// supports the subset of format functionality used here. const Map<String, String> errorMessages = { 'null-character': 'Null character in input stream, replaced with U+FFFD.', 'invalid-codepoint': 'Invalid codepoint in stream.', 'incorrectly-placed-solidus': 'Solidus (/) incorrectly placed in tag.', 'incorrect-cr-newline-entity': 'Incorrect CR newline entity, replaced with LF.', 'illegal-windows-1252-entity': 'Entity used with illegal number (windows-1252 reference).', 'cant-convert-numeric-entity': "Numeric entity couldn't be converted to character " '(codepoint U+%(charAsInt)08x).', 'illegal-codepoint-for-numeric-entity': 'Numeric entity represents an illegal codepoint: ' 'U+%(charAsInt)08x.', 'numeric-entity-without-semicolon': "Numeric entity didn't end with ';'.", 'expected-numeric-entity-but-got-eof': 'Numeric entity expected. Got end of file instead.', 'expected-numeric-entity': 'Numeric entity expected but none found.', 'named-entity-without-semicolon': "Named entity didn't end with ';'.", 'expected-named-entity': 'Named entity expected. Got none.', 'attributes-in-end-tag': 'End tag contains unexpected attributes.', 'self-closing-flag-on-end-tag': 'End tag contains unexpected self-closing flag.', 'expected-tag-name-but-got-right-bracket': "Expected tag name. Got '>' instead.", 'expected-tag-name-but-got-question-mark': "Expected tag name. Got '?' instead. (HTML doesn't " 'support processing instructions.)', 'expected-tag-name': 'Expected tag name. Got something else instead', 'expected-closing-tag-but-got-right-bracket': "Expected closing tag. Got '>' instead. Ignoring '</>'.", 'expected-closing-tag-but-got-eof': 'Expected closing tag. Unexpected end of file.', 'expected-closing-tag-but-got-char': "Expected closing tag. Unexpected character '%(data)s' found.", 'eof-in-tag-name': 'Unexpected end of file in the tag name.', 'expected-attribute-name-but-got-eof': 'Unexpected end of file. Expected attribute name instead.', 'eof-in-attribute-name': 'Unexpected end of file in attribute name.', 'invalid-character-in-attribute-name': 'Invalid character in attribute name', 'duplicate-attribute': 'Dropped duplicate attribute on tag.', 'expected-end-of-tag-name-but-got-eof': 'Unexpected end of file. Expected = or end of tag.', 'expected-attribute-value-but-got-eof': 'Unexpected end of file. Expected attribute value.', 'expected-attribute-value-but-got-right-bracket': "Expected attribute value. Got '>' instead.", 'equals-in-unquoted-attribute-value': 'Unexpected = in unquoted attribute', 'unexpected-character-in-unquoted-attribute-value': 'Unexpected character in unquoted attribute', 'invalid-character-after-attribute-name': 'Unexpected character after attribute name.', 'unexpected-character-after-attribute-value': 'Unexpected character after attribute value.', 'eof-in-attribute-value-double-quote': 'Unexpected end of file in attribute value (\".', 'eof-in-attribute-value-single-quote': "Unexpected end of file in attribute value (').", 'eof-in-attribute-value-no-quotes': 'Unexpected end of file in attribute value.', 'unexpected-EOF-after-solidus-in-tag': 'Unexpected end of file in tag. Expected >', 'unexpected-character-after-soldius-in-tag': 'Unexpected character after / in tag. Expected >', 'expected-dashes-or-doctype': "Expected '--' or 'DOCTYPE'. Not found.", 'unexpected-bang-after-double-dash-in-comment': 'Unexpected ! after -- in comment', 'unexpected-space-after-double-dash-in-comment': 'Unexpected space after -- in comment', 'incorrect-comment': 'Incorrect comment.', 'eof-in-comment': 'Unexpected end of file in comment.', 'eof-in-comment-end-dash': 'Unexpected end of file in comment (-)', 'unexpected-dash-after-double-dash-in-comment': "Unexpected '-' after '--' found in comment.", 'eof-in-comment-double-dash': 'Unexpected end of file in comment (--).', 'eof-in-comment-end-space-state': 'Unexpected end of file in comment.', 'eof-in-comment-end-bang-state': 'Unexpected end of file in comment.', 'unexpected-char-in-comment': 'Unexpected character in comment found.', 'need-space-after-doctype': "No space after literal string 'DOCTYPE'.", 'expected-doctype-name-but-got-right-bracket': 'Unexpected > character. Expected DOCTYPE name.', 'expected-doctype-name-but-got-eof': 'Unexpected end of file. Expected DOCTYPE name.', 'eof-in-doctype-name': 'Unexpected end of file in DOCTYPE name.', 'eof-in-doctype': 'Unexpected end of file in DOCTYPE.', 'expected-space-or-right-bracket-in-doctype': "Expected space or '>'. Got '%(data)s'", 'unexpected-end-of-doctype': 'Unexpected end of DOCTYPE.', 'unexpected-char-in-doctype': 'Unexpected character in DOCTYPE.', 'eof-in-innerhtml': 'XXX innerHTML EOF', 'unexpected-doctype': 'Unexpected DOCTYPE. Ignored.', 'non-html-root': 'html needs to be the first start tag.', 'expected-doctype-but-got-eof': 'Unexpected End of file. Expected DOCTYPE.', 'unknown-doctype': 'Erroneous DOCTYPE.', 'expected-doctype-but-got-chars': 'Unexpected non-space characters. Expected DOCTYPE.', 'expected-doctype-but-got-start-tag': 'Unexpected start tag (%(name)s). Expected DOCTYPE.', 'expected-doctype-but-got-end-tag': 'Unexpected end tag (%(name)s). Expected DOCTYPE.', 'end-tag-after-implied-root': 'Unexpected end tag (%(name)s) after the (implied) root element.', 'expected-named-closing-tag-but-got-eof': 'Unexpected end of file. Expected end tag (%(name)s).', 'two-heads-are-not-better-than-one': 'Unexpected start tag head in existing head. Ignored.', 'unexpected-end-tag': 'Unexpected end tag (%(name)s). Ignored.', 'unexpected-start-tag-out-of-my-head': 'Unexpected start tag (%(name)s) that can be in head. Moved.', 'unexpected-start-tag': 'Unexpected start tag (%(name)s).', 'missing-end-tag': 'Missing end tag (%(name)s).', 'missing-end-tags': 'Missing end tags (%(name)s).', 'unexpected-start-tag-implies-end-tag': 'Unexpected start tag (%(startName)s) ' 'implies end tag (%(endName)s).', 'unexpected-start-tag-treated-as': 'Unexpected start tag (%(originalName)s). Treated as %(newName)s.', 'deprecated-tag': "Unexpected start tag %(name)s. Don't use it!", 'unexpected-start-tag-ignored': 'Unexpected start tag %(name)s. Ignored.', 'expected-one-end-tag-but-got-another': 'Unexpected end tag (%(gotName)s). ' 'Missing end tag (%(expectedName)s).', 'end-tag-too-early': 'End tag (%(name)s) seen too early. Expected other end tag.', 'end-tag-too-early-named': 'Unexpected end tag (%(gotName)s). Expected end tag (%(expectedName)s).', 'end-tag-too-early-ignored': 'End tag (%(name)s) seen too early. Ignored.', 'adoption-agency-1.1': 'End tag (%(name)s) violates step 1, ' 'paragraph 1 of the adoption agency algorithm.', 'adoption-agency-1.2': 'End tag (%(name)s) violates step 1, ' 'paragraph 2 of the adoption agency algorithm.', 'adoption-agency-1.3': 'End tag (%(name)s) violates step 1, ' 'paragraph 3 of the adoption agency algorithm.', 'unexpected-end-tag-treated-as': 'Unexpected end tag (%(originalName)s). Treated as %(newName)s.', 'no-end-tag': 'This element (%(name)s) has no end tag.', 'unexpected-implied-end-tag-in-table': 'Unexpected implied end tag (%(name)s) in the table phase.', 'unexpected-implied-end-tag-in-table-body': 'Unexpected implied end tag (%(name)s) in the table body phase.', 'unexpected-char-implies-table-voodoo': 'Unexpected non-space characters in ' 'table context caused voodoo mode.', 'unexpected-hidden-input-in-table': 'Unexpected input with type hidden in table context.', 'unexpected-form-in-table': 'Unexpected form in table context.', 'unexpected-start-tag-implies-table-voodoo': 'Unexpected start tag (%(name)s) in ' 'table context caused voodoo mode.', 'unexpected-end-tag-implies-table-voodoo': 'Unexpected end tag (%(name)s) in ' 'table context caused voodoo mode.', 'unexpected-cell-in-table-body': 'Unexpected table cell start tag (%(name)s) ' 'in the table body phase.', 'unexpected-cell-end-tag': 'Got table cell end tag (%(name)s) ' 'while required end tags are missing.', 'unexpected-end-tag-in-table-body': 'Unexpected end tag (%(name)s) in the table body phase. Ignored.', 'unexpected-implied-end-tag-in-table-row': 'Unexpected implied end tag (%(name)s) in the table row phase.', 'unexpected-end-tag-in-table-row': 'Unexpected end tag (%(name)s) in the table row phase. Ignored.', 'unexpected-select-in-select': 'Unexpected select start tag in the select phase ' 'treated as select end tag.', 'unexpected-input-in-select': 'Unexpected input start tag in the select phase.', 'unexpected-start-tag-in-select': 'Unexpected start tag token (%(name)s in the select phase. ' 'Ignored.', 'unexpected-end-tag-in-select': 'Unexpected end tag (%(name)s) in the select phase. Ignored.', 'unexpected-table-element-start-tag-in-select-in-table': 'Unexpected table element start tag (%(name)s) in the select in table phase.', 'unexpected-table-element-end-tag-in-select-in-table': 'Unexpected table element end tag (%(name)s) in the select in table phase.', 'unexpected-char-after-body': 'Unexpected non-space characters in the after body phase.', 'unexpected-start-tag-after-body': 'Unexpected start tag token (%(name)s)' ' in the after body phase.', 'unexpected-end-tag-after-body': 'Unexpected end tag token (%(name)s)' ' in the after body phase.', 'unexpected-char-in-frameset': 'Unepxected characters in the frameset phase. Characters ignored.', 'unexpected-start-tag-in-frameset': 'Unexpected start tag token (%(name)s)' ' in the frameset phase. Ignored.', 'unexpected-frameset-in-frameset-innerhtml': 'Unexpected end tag token (frameset) ' 'in the frameset phase (innerHTML).', 'unexpected-end-tag-in-frameset': 'Unexpected end tag token (%(name)s)' ' in the frameset phase. Ignored.', 'unexpected-char-after-frameset': 'Unexpected non-space characters in the ' 'after frameset phase. Ignored.', 'unexpected-start-tag-after-frameset': 'Unexpected start tag (%(name)s)' ' in the after frameset phase. Ignored.', 'unexpected-end-tag-after-frameset': 'Unexpected end tag (%(name)s)' ' in the after frameset phase. Ignored.', 'unexpected-end-tag-after-body-innerhtml': 'Unexpected end tag after body(innerHtml)', 'expected-eof-but-got-char': 'Unexpected non-space characters. Expected end of file.', 'expected-eof-but-got-start-tag': 'Unexpected start tag (%(name)s)' '. Expected end of file.', 'expected-eof-but-got-end-tag': 'Unexpected end tag (%(name)s)' '. Expected end of file.', 'eof-in-table': 'Unexpected end of file. Expected table content.', 'eof-in-select': 'Unexpected end of file. Expected select content.', 'eof-in-frameset': 'Unexpected end of file. Expected frameset content.', 'eof-in-script-in-script': 'Unexpected end of file. Expected script content.', 'eof-in-foreign-lands': 'Unexpected end of file. Expected foreign content', 'non-void-element-with-trailing-solidus': 'Trailing solidus not allowed on element %(name)s', 'unexpected-html-element-in-foreign-content': 'Element %(name)s not allowed in a non-html context', 'unexpected-end-tag-before-html': 'Unexpected end tag (%(name)s) before html.', 'undefined-error': 'Undefined error (this sucks and should be fixed)', }; class Namespaces { static const html = 'http://www.w3.org/1999/xhtml'; static const mathml = 'http://www.w3.org/1998/Math/MathML'; static const svg = 'http://www.w3.org/2000/svg'; static const xlink = 'http://www.w3.org/1999/xlink'; static const xml = 'http://www.w3.org/XML/1998/namespace'; static const xmlns = 'http://www.w3.org/2000/xmlns/'; Namespaces._(); static String getPrefix(String url) { switch (url) { case html: return 'html'; case mathml: return 'math'; case svg: return 'svg'; case xlink: return 'xlink'; case xml: return 'xml'; case xmlns: return 'xmlns'; default: return null; } } } const List scopingElements = [ Pair(Namespaces.html, 'applet'), Pair(Namespaces.html, 'caption'), Pair(Namespaces.html, 'html'), Pair(Namespaces.html, 'marquee'), Pair(Namespaces.html, 'object'), Pair(Namespaces.html, 'table'), Pair(Namespaces.html, 'td'), Pair(Namespaces.html, 'th'), Pair(Namespaces.mathml, 'mi'), Pair(Namespaces.mathml, 'mo'), Pair(Namespaces.mathml, 'mn'), Pair(Namespaces.mathml, 'ms'), Pair(Namespaces.mathml, 'mtext'), Pair(Namespaces.mathml, 'annotation-xml'), Pair(Namespaces.svg, 'foreignObject'), Pair(Namespaces.svg, 'desc'), Pair(Namespaces.svg, 'title') ]; const formattingElements = [ Pair(Namespaces.html, 'a'), Pair(Namespaces.html, 'b'), Pair(Namespaces.html, 'big'), Pair(Namespaces.html, 'code'), Pair(Namespaces.html, 'em'), Pair(Namespaces.html, 'font'), Pair(Namespaces.html, 'i'), Pair(Namespaces.html, 'nobr'), Pair(Namespaces.html, 's'), Pair(Namespaces.html, 'small'), Pair(Namespaces.html, 'strike'), Pair(Namespaces.html, 'strong'), Pair(Namespaces.html, 'tt'), Pair(Namespaces.html, '') ]; const specialElements = [ Pair(Namespaces.html, 'address'), Pair(Namespaces.html, 'applet'), Pair(Namespaces.html, 'area'), Pair(Namespaces.html, 'article'), Pair(Namespaces.html, 'aside'), Pair(Namespaces.html, 'base'), Pair(Namespaces.html, 'basefont'), Pair(Namespaces.html, 'bgsound'), Pair(Namespaces.html, 'blockquote'), Pair(Namespaces.html, 'body'), Pair(Namespaces.html, 'br'), Pair(Namespaces.html, 'button'), Pair(Namespaces.html, 'caption'), Pair(Namespaces.html, 'center'), Pair(Namespaces.html, 'col'), Pair(Namespaces.html, 'colgroup'), Pair(Namespaces.html, 'command'), Pair(Namespaces.html, 'dd'), Pair(Namespaces.html, 'details'), Pair(Namespaces.html, 'dir'), Pair(Namespaces.html, 'div'), Pair(Namespaces.html, 'dl'), Pair(Namespaces.html, 'dt'), Pair(Namespaces.html, 'embed'), Pair(Namespaces.html, 'fieldset'), Pair(Namespaces.html, 'figure'), Pair(Namespaces.html, 'footer'), Pair(Namespaces.html, 'form'), Pair(Namespaces.html, 'frame'), Pair(Namespaces.html, 'frameset'), Pair(Namespaces.html, 'h1'), Pair(Namespaces.html, 'h2'), Pair(Namespaces.html, 'h3'), Pair(Namespaces.html, 'h4'), Pair(Namespaces.html, 'h5'), Pair(Namespaces.html, 'h6'), Pair(Namespaces.html, 'head'), Pair(Namespaces.html, 'header'), Pair(Namespaces.html, 'hr'), Pair(Namespaces.html, 'html'), Pair(Namespaces.html, 'iframe'), // Note that image is commented out in the spec as "this isn't an // element that can end up on the stack, so it doesn't matter," Pair(Namespaces.html, 'image'), Pair(Namespaces.html, 'img'), Pair(Namespaces.html, 'input'), Pair(Namespaces.html, 'isindex'), Pair(Namespaces.html, 'li'), Pair(Namespaces.html, 'link'), Pair(Namespaces.html, 'listing'), Pair(Namespaces.html, 'marquee'), Pair(Namespaces.html, 'men'), Pair(Namespaces.html, 'meta'), Pair(Namespaces.html, 'nav'), Pair(Namespaces.html, 'noembed'), Pair(Namespaces.html, 'noframes'), Pair(Namespaces.html, 'noscript'), Pair(Namespaces.html, 'object'), Pair(Namespaces.html, 'ol'), Pair(Namespaces.html, 'p'), Pair(Namespaces.html, 'param'), Pair(Namespaces.html, 'plaintext'), Pair(Namespaces.html, 'pre'), Pair(Namespaces.html, 'script'), Pair(Namespaces.html, 'section'), Pair(Namespaces.html, 'select'), Pair(Namespaces.html, 'style'), Pair(Namespaces.html, 'table'), Pair(Namespaces.html, 'tbody'), Pair(Namespaces.html, 'td'), Pair(Namespaces.html, 'textarea'), Pair(Namespaces.html, 'tfoot'), Pair(Namespaces.html, 'th'), Pair(Namespaces.html, 'thead'), Pair(Namespaces.html, 'title'), Pair(Namespaces.html, 'tr'), Pair(Namespaces.html, 'ul'), Pair(Namespaces.html, 'wbr'), Pair(Namespaces.html, 'xmp'), Pair(Namespaces.svg, 'foreignObject') ]; const htmlIntegrationPointElements = [ Pair(Namespaces.mathml, 'annotaion-xml'), Pair(Namespaces.svg, 'foreignObject'), Pair(Namespaces.svg, 'desc'), Pair(Namespaces.svg, 'title') ]; const mathmlTextIntegrationPointElements = [ Pair(Namespaces.mathml, 'mi'), Pair(Namespaces.mathml, 'mo'), Pair(Namespaces.mathml, 'mn'), Pair(Namespaces.mathml, 'ms'), Pair(Namespaces.mathml, 'mtext') ]; const spaceCharacters = ' \n\r\t\u000C'; const int NEWLINE = 10; const int RETURN = 13; bool isWhitespace(String char) { if (char == null) return false; return isWhitespaceCC(char.codeUnitAt(0)); } bool isWhitespaceCC(int charCode) { switch (charCode) { case 9: // '\t' case NEWLINE: // '\n' case 12: // '\f' case RETURN: // '\r' case 32: // ' ' return true; } return false; } const List<String> tableInsertModeElements = [ 'table', 'tbody', 'tfoot', 'thead', 'tr' ]; // TODO(jmesserly): remove these in favor of the test functions const asciiLetters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; const ZERO = 48; const LOWER_A = 97; const LOWER_Z = 122; const UPPER_A = 65; const UPPER_Z = 90; bool isLetterOrDigit(String char) => isLetter(char) || isDigit(char); // Note: this is intentially ASCII only bool isLetter(String char) { if (char == null) return false; var cc = char.codeUnitAt(0); return cc >= LOWER_A && cc <= LOWER_Z || cc >= UPPER_A && cc <= UPPER_Z; } bool isDigit(String char) { if (char == null) return false; var cc = char.codeUnitAt(0); return cc >= ZERO && cc < ZERO + 10; } bool isHexDigit(String char) { if (char == null) return false; switch (char.codeUnitAt(0)) { case 48: case 49: case 50: case 51: case 52: // '0' - '4' case 53: case 54: case 55: case 56: case 57: // '5' - '9' case 65: case 66: case 67: case 68: case 69: case 70: // 'A' - 'F' case 97: case 98: case 99: case 100: case 101: case 102: // 'a' - 'f' return true; } return false; } // Note: based on the original Python code, I assume we only want to convert // ASCII chars to.toLowerCase() case, unlike Dart's toLowerCase function. String asciiUpper2Lower(String text) { if (text == null) return null; var result = List<int>(text.length); for (var i = 0; i < text.length; i++) { var c = text.codeUnitAt(i); if (c >= UPPER_A && c <= UPPER_Z) { c += LOWER_A - UPPER_A; } result[i] = c; } return String.fromCharCodes(result); } // Heading elements need to be ordered const headingElements = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']; const cdataElements = ['title', 'textarea']; const rcdataElements = [ 'style', 'script', 'xmp', 'iframe', 'noembed', 'noframes', 'noscript' ]; // entitiesWindows1252 has to be _ordered_ and needs to have an index. It // therefore can't be a frozenset. const List<int> entitiesWindows1252 = [ 8364, // 0x80 0x20AC EURO SIGN 65533, // 0x81 UNDEFINED 8218, // 0x82 0x201A SINGLE LOW-9 QUOTATION MARK 402, // 0x83 0x0192 LATIN SMALL LETTER F WITH HOOK 8222, // 0x84 0x201E DOUBLE LOW-9 QUOTATION MARK 8230, // 0x85 0x2026 HORIZONTAL ELLIPSIS 8224, // 0x86 0x2020 DAGGER 8225, // 0x87 0x2021 DOUBLE DAGGER 710, // 0x88 0x02C6 MODIFIER LETTER CIRCUMFLEX ACCENT 8240, // 0x89 0x2030 PER MILLE SIGN 352, // 0x8A 0x0160 LATIN CAPITAL LETTER S WITH CARON 8249, // 0x8B 0x2039 SINGLE LEFT-POINTING ANGLE QUOTATION MARK 338, // 0x8C 0x0152 LATIN CAPITAL LIGATURE OE 65533, // 0x8D UNDEFINED 381, // 0x8E 0x017D LATIN CAPITAL LETTER Z WITH CARON 65533, // 0x8F UNDEFINED 65533, // 0x90 UNDEFINED 8216, // 0x91 0x2018 LEFT SINGLE QUOTATION MARK 8217, // 0x92 0x2019 RIGHT SINGLE QUOTATION MARK 8220, // 0x93 0x201C LEFT DOUBLE QUOTATION MARK 8221, // 0x94 0x201D RIGHT DOUBLE QUOTATION MARK 8226, // 0x95 0x2022 BULLET 8211, // 0x96 0x2013 EN DASH 8212, // 0x97 0x2014 EM DASH 732, // 0x98 0x02DC SMALL TILDE 8482, // 0x99 0x2122 TRADE MARK SIGN 353, // 0x9A 0x0161 LATIN SMALL LETTER S WITH CARON 8250, // 0x9B 0x203A SINGLE RIGHT-POINTING ANGLE QUOTATION MARK 339, // 0x9C 0x0153 LATIN SMALL LIGATURE OE 65533, // 0x9D UNDEFINED 382, // 0x9E 0x017E LATIN SMALL LETTER Z WITH CARON 376 // 0x9F 0x0178 LATIN CAPITAL LETTER Y WITH DIAERESIS ]; const xmlEntities = ['lt;', 'gt;', 'amp;', 'apos;', 'quot;']; const Map<String, String> entities = { 'AElig': '\xc6', 'AElig;': '\xc6', 'AMP': '&', 'AMP;': '&', 'Aacute': '\xc1', 'Aacute;': '\xc1', 'Abreve;': '\u0102', 'Acirc': '\xc2', 'Acirc;': '\xc2', 'Acy;': '\u0410', 'Afr;': '\u{01d504}', 'Agrave': '\xc0', 'Agrave;': '\xc0', 'Alpha;': '\u0391', 'Amacr;': '\u0100', 'And;': '\u2a53', 'Aogon;': '\u0104', 'Aopf;': '\u{01d538}', 'ApplyFunction;': '\u2061', 'Aring': '\xc5', 'Aring;': '\xc5', 'Ascr;': '\u{01d49c}', 'Assign;': '\u2254', 'Atilde': '\xc3', 'Atilde;': '\xc3', 'Auml': '\xc4', 'Auml;': '\xc4', 'Backslash;': '\u2216', 'Barv;': '\u2ae7', 'Barwed;': '\u2306', 'Bcy;': '\u0411', 'Because;': '\u2235', 'Bernoullis;': '\u212c', 'Beta;': '\u0392', 'Bfr;': '\u{01d505}', 'Bopf;': '\u{01d539}', 'Breve;': '\u02d8', 'Bscr;': '\u212c', 'Bumpeq;': '\u224e', 'CHcy;': '\u0427', 'COPY': '\xa9', 'COPY;': '\xa9', 'Cacute;': '\u0106', 'Cap;': '\u22d2', 'CapitalDifferentialD;': '\u2145', 'Cayleys;': '\u212d', 'Ccaron;': '\u010c', 'Ccedil': '\xc7', 'Ccedil;': '\xc7', 'Ccirc;': '\u0108', 'Cconint;': '\u2230', 'Cdot;': '\u010a', 'Cedilla;': '\xb8', 'CenterDot;': '\xb7', 'Cfr;': '\u212d', 'Chi;': '\u03a7', 'CircleDot;': '\u2299', 'CircleMinus;': '\u2296', 'CirclePlus;': '\u2295', 'CircleTimes;': '\u2297', 'ClockwiseContourIntegral;': '\u2232', 'CloseCurlyDoubleQuote;': '\u201d', 'CloseCurlyQuote;': '\u2019', 'Colon;': '\u2237', 'Colone;': '\u2a74', 'Congruent;': '\u2261', 'Conint;': '\u222f', 'ContourIntegral;': '\u222e', 'Copf;': '\u2102', 'Coproduct;': '\u2210', 'CounterClockwiseContourIntegral;': '\u2233', 'Cross;': '\u2a2f', 'Cscr;': '\u{01d49e}', 'Cup;': '\u22d3', 'CupCap;': '\u224d', 'DD;': '\u2145', 'DDotrahd;': '\u2911', 'DJcy;': '\u0402', 'DScy;': '\u0405', 'DZcy;': '\u040f', 'Dagger;': '\u2021', 'Darr;': '\u21a1', 'Dashv;': '\u2ae4', 'Dcaron;': '\u010e', 'Dcy;': '\u0414', 'Del;': '\u2207', 'Delta;': '\u0394', 'Dfr;': '\u{01d507}', 'DiacriticalAcute;': '\xb4', 'DiacriticalDot;': '\u02d9', 'DiacriticalDoubleAcute;': '\u02dd', 'DiacriticalGrave;': '`', 'DiacriticalTilde;': '\u02dc', 'Diamond;': '\u22c4', 'DifferentialD;': '\u2146', 'Dopf;': '\u{01d53b}', 'Dot;': '\xa8', 'DotDot;': '\u20dc', 'DotEqual;': '\u2250', 'DoubleContourIntegral;': '\u222f', 'DoubleDot;': '\xa8', 'DoubleDownArrow;': '\u21d3', 'DoubleLeftArrow;': '\u21d0', 'DoubleLeftRightArrow;': '\u21d4', 'DoubleLeftTee;': '\u2ae4', 'DoubleLongLeftArrow;': '\u27f8', 'DoubleLongLeftRightArrow;': '\u27fa', 'DoubleLongRightArrow;': '\u27f9', 'DoubleRightArrow;': '\u21d2', 'DoubleRightTee;': '\u22a8', 'DoubleUpArrow;': '\u21d1', 'DoubleUpDownArrow;': '\u21d5', 'DoubleVerticalBar;': '\u2225', 'DownArrow;': '\u2193', 'DownArrowBar;': '\u2913', 'DownArrowUpArrow;': '\u21f5', 'DownBreve;': '\u0311', 'DownLeftRightVector;': '\u2950', 'DownLeftTeeVector;': '\u295e', 'DownLeftVector;': '\u21bd', 'DownLeftVectorBar;': '\u2956', 'DownRightTeeVector;': '\u295f', 'DownRightVector;': '\u21c1', 'DownRightVectorBar;': '\u2957', 'DownTee;': '\u22a4', 'DownTeeArrow;': '\u21a7', 'Downarrow;': '\u21d3', 'Dscr;': '\u{01d49f}', 'Dstrok;': '\u0110', 'ENG;': '\u014a', 'ETH': '\xd0', 'ETH;': '\xd0', 'Eacute': '\xc9', 'Eacute;': '\xc9', 'Ecaron;': '\u011a', 'Ecirc': '\xca', 'Ecirc;': '\xca', 'Ecy;': '\u042d', 'Edot;': '\u0116', 'Efr;': '\u{01d508}', 'Egrave': '\xc8', 'Egrave;': '\xc8', 'Element;': '\u2208', 'Emacr;': '\u0112', 'EmptySmallSquare;': '\u25fb', 'EmptyVerySmallSquare;': '\u25ab', 'Eogon;': '\u0118', 'Eopf;': '\u{01d53c}', 'Epsilon;': '\u0395', 'Equal;': '\u2a75', 'EqualTilde;': '\u2242', 'Equilibrium;': '\u21cc', 'Escr;': '\u2130', 'Esim;': '\u2a73', 'Eta;': '\u0397', 'Euml': '\xcb', 'Euml;': '\xcb', 'Exists;': '\u2203', 'ExponentialE;': '\u2147', 'Fcy;': '\u0424', 'Ffr;': '\u{01d509}', 'FilledSmallSquare;': '\u25fc', 'FilledVerySmallSquare;': '\u25aa', 'Fopf;': '\u{01d53d}', 'ForAll;': '\u2200', 'Fouriertrf;': '\u2131', 'Fscr;': '\u2131', 'GJcy;': '\u0403', 'GT': '>', 'GT;': '>', 'Gamma;': '\u0393', 'Gammad;': '\u03dc', 'Gbreve;': '\u011e', 'Gcedil;': '\u0122', 'Gcirc;': '\u011c', 'Gcy;': '\u0413', 'Gdot;': '\u0120', 'Gfr;': '\u{01d50a}', 'Gg;': '\u22d9', 'Gopf;': '\u{01d53e}', 'GreaterEqual;': '\u2265', 'GreaterEqualLess;': '\u22db', 'GreaterFullEqual;': '\u2267', 'GreaterGreater;': '\u2aa2', 'GreaterLess;': '\u2277', 'GreaterSlantEqual;': '\u2a7e', 'GreaterTilde;': '\u2273', 'Gscr;': '\u{01d4a2}', 'Gt;': '\u226b', 'HARDcy;': '\u042a', 'Hacek;': '\u02c7', 'Hat;': '^', 'Hcirc;': '\u0124', 'Hfr;': '\u210c', 'HilbertSpace;': '\u210b', 'Hopf;': '\u210d', 'HorizontalLine;': '\u2500', 'Hscr;': '\u210b', 'Hstrok;': '\u0126', 'HumpDownHump;': '\u224e', 'HumpEqual;': '\u224f', 'IEcy;': '\u0415', 'IJlig;': '\u0132', 'IOcy;': '\u0401', 'Iacute': '\xcd', 'Iacute;': '\xcd', 'Icirc': '\xce', 'Icirc;': '\xce', 'Icy;': '\u0418', 'Idot;': '\u0130', 'Ifr;': '\u2111', 'Igrave': '\xcc', 'Igrave;': '\xcc', 'Im;': '\u2111', 'Imacr;': '\u012a', 'ImaginaryI;': '\u2148', 'Implies;': '\u21d2', 'Int;': '\u222c', 'Integral;': '\u222b', 'Intersection;': '\u22c2', 'InvisibleComma;': '\u2063', 'InvisibleTimes;': '\u2062', 'Iogon;': '\u012e', 'Iopf;': '\u{01d540}', 'Iota;': '\u0399', 'Iscr;': '\u2110', 'Itilde;': '\u0128', 'Iukcy;': '\u0406', 'Iuml': '\xcf', 'Iuml;': '\xcf', 'Jcirc;': '\u0134', 'Jcy;': '\u0419', 'Jfr;': '\u{01d50d}', 'Jopf;': '\u{01d541}', 'Jscr;': '\u{01d4a5}', 'Jsercy;': '\u0408', 'Jukcy;': '\u0404', 'KHcy;': '\u0425', 'KJcy;': '\u040c', 'Kappa;': '\u039a', 'Kcedil;': '\u0136', 'Kcy;': '\u041a', 'Kfr;': '\u{01d50e}', 'Kopf;': '\u{01d542}', 'Kscr;': '\u{01d4a6}', 'LJcy;': '\u0409', 'LT': '<', 'LT;': '<', 'Lacute;': '\u0139', 'Lambda;': '\u039b', 'Lang;': '\u27ea', 'Laplacetrf;': '\u2112', 'Larr;': '\u219e', 'Lcaron;': '\u013d', 'Lcedil;': '\u013b', 'Lcy;': '\u041b', 'LeftAngleBracket;': '\u27e8', 'LeftArrow;': '\u2190', 'LeftArrowBar;': '\u21e4', 'LeftArrowRightArrow;': '\u21c6', 'LeftCeiling;': '\u2308', 'LeftDoubleBracket;': '\u27e6', 'LeftDownTeeVector;': '\u2961', 'LeftDownVector;': '\u21c3', 'LeftDownVectorBar;': '\u2959', 'LeftFloor;': '\u230a', 'LeftRightArrow;': '\u2194', 'LeftRightVector;': '\u294e', 'LeftTee;': '\u22a3', 'LeftTeeArrow;': '\u21a4', 'LeftTeeVector;': '\u295a', 'LeftTriangle;': '\u22b2', 'LeftTriangleBar;': '\u29cf', 'LeftTriangleEqual;': '\u22b4', 'LeftUpDownVector;': '\u2951', 'LeftUpTeeVector;': '\u2960', 'LeftUpVector;': '\u21bf', 'LeftUpVectorBar;': '\u2958', 'LeftVector;': '\u21bc', 'LeftVectorBar;': '\u2952', 'Leftarrow;': '\u21d0', 'Leftrightarrow;': '\u21d4', 'LessEqualGreater;': '\u22da', 'LessFullEqual;': '\u2266', 'LessGreater;': '\u2276', 'LessLess;': '\u2aa1', 'LessSlantEqual;': '\u2a7d', 'LessTilde;': '\u2272', 'Lfr;': '\u{01d50f}', 'Ll;': '\u22d8', 'Lleftarrow;': '\u21da', 'Lmidot;': '\u013f', 'LongLeftArrow;': '\u27f5', 'LongLeftRightArrow;': '\u27f7', 'LongRightArrow;': '\u27f6', 'Longleftarrow;': '\u27f8', 'Longleftrightarrow;': '\u27fa', 'Longrightarrow;': '\u27f9', 'Lopf;': '\u{01d543}', 'LowerLeftArrow;': '\u2199', 'LowerRightArrow;': '\u2198', 'Lscr;': '\u2112', 'Lsh;': '\u21b0', 'Lstrok;': '\u0141', 'Lt;': '\u226a', 'Map;': '\u2905', 'Mcy;': '\u041c', 'MediumSpace;': '\u205f', 'Mellintrf;': '\u2133', 'Mfr;': '\u{01d510}', 'MinusPlus;': '\u2213', 'Mopf;': '\u{01d544}', 'Mscr;': '\u2133', 'Mu;': '\u039c', 'NJcy;': '\u040a', 'Nacute;': '\u0143', 'Ncaron;': '\u0147', 'Ncedil;': '\u0145', 'Ncy;': '\u041d', 'NegativeMediumSpace;': '\u200b', 'NegativeThickSpace;': '\u200b', 'NegativeThinSpace;': '\u200b', 'NegativeVeryThinSpace;': '\u200b', 'NestedGreaterGreater;': '\u226b', 'NestedLessLess;': '\u226a', 'NewLine;': '\n', 'Nfr;': '\u{01d511}', 'NoBreak;': '\u2060', 'NonBreakingSpace;': '\xa0', 'Nopf;': '\u2115', 'Not;': '\u2aec', 'NotCongruent;': '\u2262', 'NotCupCap;': '\u226d', 'NotDoubleVerticalBar;': '\u2226', 'NotElement;': '\u2209', 'NotEqual;': '\u2260', 'NotEqualTilde;': '\u2242\u0338', 'NotExists;': '\u2204', 'NotGreater;': '\u226f', 'NotGreaterEqual;': '\u2271', 'NotGreaterFullEqual;': '\u2267\u0338', 'NotGreaterGreater;': '\u226b\u0338', 'NotGreaterLess;': '\u2279', 'NotGreaterSlantEqual;': '\u2a7e\u0338', 'NotGreaterTilde;': '\u2275', 'NotHumpDownHump;': '\u224e\u0338', 'NotHumpEqual;': '\u224f\u0338', 'NotLeftTriangle;': '\u22ea', 'NotLeftTriangleBar;': '\u29cf\u0338', 'NotLeftTriangleEqual;': '\u22ec', 'NotLess;': '\u226e', 'NotLessEqual;': '\u2270', 'NotLessGreater;': '\u2278', 'NotLessLess;': '\u226a\u0338', 'NotLessSlantEqual;': '\u2a7d\u0338', 'NotLessTilde;': '\u2274', 'NotNestedGreaterGreater;': '\u2aa2\u0338', 'NotNestedLessLess;': '\u2aa1\u0338', 'NotPrecedes;': '\u2280', 'NotPrecedesEqual;': '\u2aaf\u0338', 'NotPrecedesSlantEqual;': '\u22e0', 'NotReverseElement;': '\u220c', 'NotRightTriangle;': '\u22eb', 'NotRightTriangleBar;': '\u29d0\u0338', 'NotRightTriangleEqual;': '\u22ed', 'NotSquareSubset;': '\u228f\u0338', 'NotSquareSubsetEqual;': '\u22e2', 'NotSquareSuperset;': '\u2290\u0338', 'NotSquareSupersetEqual;': '\u22e3', 'NotSubset;': '\u2282\u20d2', 'NotSubsetEqual;': '\u2288', 'NotSucceeds;': '\u2281', 'NotSucceedsEqual;': '\u2ab0\u0338', 'NotSucceedsSlantEqual;': '\u22e1', 'NotSucceedsTilde;': '\u227f\u0338', 'NotSuperset;': '\u2283\u20d2', 'NotSupersetEqual;': '\u2289', 'NotTilde;': '\u2241', 'NotTildeEqual;': '\u2244', 'NotTildeFullEqual;': '\u2247', 'NotTildeTilde;': '\u2249', 'NotVerticalBar;': '\u2224', 'Nscr;': '\u{01d4a9}', 'Ntilde': '\xd1', 'Ntilde;': '\xd1', 'Nu;': '\u039d', 'OElig;': '\u0152', 'Oacute': '\xd3', 'Oacute;': '\xd3', 'Ocirc': '\xd4', 'Ocirc;': '\xd4', 'Ocy;': '\u041e', 'Odblac;': '\u0150', 'Ofr;': '\u{01d512}', 'Ograve': '\xd2', 'Ograve;': '\xd2', 'Omacr;': '\u014c', 'Omega;': '\u03a9', 'Omicron;': '\u039f', 'Oopf;': '\u{01d546}', 'OpenCurlyDoubleQuote;': '\u201c', 'OpenCurlyQuote;': '\u2018', 'Or;': '\u2a54', 'Oscr;': '\u{01d4aa}', 'Oslash': '\xd8', 'Oslash;': '\xd8', 'Otilde': '\xd5', 'Otilde;': '\xd5', 'Otimes;': '\u2a37', 'Ouml': '\xd6', 'Ouml;': '\xd6', 'OverBar;': '\u203e', 'OverBrace;': '\u23de', 'OverBracket;': '\u23b4', 'OverParenthesis;': '\u23dc', 'PartialD;': '\u2202', 'Pcy;': '\u041f', 'Pfr;': '\u{01d513}', 'Phi;': '\u03a6', 'Pi;': '\u03a0', 'PlusMinus;': '\xb1', 'Poincareplane;': '\u210c', 'Popf;': '\u2119', 'Pr;': '\u2abb', 'Precedes;': '\u227a', 'PrecedesEqual;': '\u2aaf', 'PrecedesSlantEqual;': '\u227c', 'PrecedesTilde;': '\u227e', 'Prime;': '\u2033', 'Product;': '\u220f', 'Proportion;': '\u2237', 'Proportional;': '\u221d', 'Pscr;': '\u{01d4ab}', 'Psi;': '\u03a8', 'QUOT': '"', 'QUOT;': '"', 'Qfr;': '\u{01d514}', 'Qopf;': '\u211a', 'Qscr;': '\u{01d4ac}', 'RBarr;': '\u2910', 'REG': '\xae', 'REG;': '\xae', 'Racute;': '\u0154', 'Rang;': '\u27eb', 'Rarr;': '\u21a0', 'Rarrtl;': '\u2916', 'Rcaron;': '\u0158', 'Rcedil;': '\u0156', 'Rcy;': '\u0420', 'Re;': '\u211c', 'ReverseElement;': '\u220b', 'ReverseEquilibrium;': '\u21cb', 'ReverseUpEquilibrium;': '\u296f', 'Rfr;': '\u211c', 'Rho;': '\u03a1', 'RightAngleBracket;': '\u27e9', 'RightArrow;': '\u2192', 'RightArrowBar;': '\u21e5', 'RightArrowLeftArrow;': '\u21c4', 'RightCeiling;': '\u2309', 'RightDoubleBracket;': '\u27e7', 'RightDownTeeVector;': '\u295d', 'RightDownVector;': '\u21c2', 'RightDownVectorBar;': '\u2955', 'RightFloor;': '\u230b', 'RightTee;': '\u22a2', 'RightTeeArrow;': '\u21a6', 'RightTeeVector;': '\u295b', 'RightTriangle;': '\u22b3', 'RightTriangleBar;': '\u29d0', 'RightTriangleEqual;': '\u22b5', 'RightUpDownVector;': '\u294f', 'RightUpTeeVector;': '\u295c', 'RightUpVector;': '\u21be', 'RightUpVectorBar;': '\u2954', 'RightVector;': '\u21c0', 'RightVectorBar;': '\u2953', 'Rightarrow;': '\u21d2', 'Ropf;': '\u211d', 'RoundImplies;': '\u2970', 'Rrightarrow;': '\u21db', 'Rscr;': '\u211b', 'Rsh;': '\u21b1', 'RuleDelayed;': '\u29f4', 'SHCHcy;': '\u0429', 'SHcy;': '\u0428', 'SOFTcy;': '\u042c', 'Sacute;': '\u015a', 'Sc;': '\u2abc', 'Scaron;': '\u0160', 'Scedil;': '\u015e', 'Scirc;': '\u015c', 'Scy;': '\u0421', 'Sfr;': '\u{01d516}', 'ShortDownArrow;': '\u2193', 'ShortLeftArrow;': '\u2190', 'ShortRightArrow;': '\u2192', 'ShortUpArrow;': '\u2191', 'Sigma;': '\u03a3', 'SmallCircle;': '\u2218', 'Sopf;': '\u{01d54a}', 'Sqrt;': '\u221a', 'Square;': '\u25a1', 'SquareIntersection;': '\u2293', 'SquareSubset;': '\u228f', 'SquareSubsetEqual;': '\u2291', 'SquareSuperset;': '\u2290', 'SquareSupersetEqual;': '\u2292', 'SquareUnion;': '\u2294', 'Sscr;': '\u{01d4ae}', 'Star;': '\u22c6', 'Sub;': '\u22d0', 'Subset;': '\u22d0', 'SubsetEqual;': '\u2286', 'Succeeds;': '\u227b', 'SucceedsEqual;': '\u2ab0', 'SucceedsSlantEqual;': '\u227d', 'SucceedsTilde;': '\u227f', 'SuchThat;': '\u220b', 'Sum;': '\u2211', 'Sup;': '\u22d1', 'Superset;': '\u2283', 'SupersetEqual;': '\u2287', 'Supset;': '\u22d1', 'THORN': '\xde', 'THORN;': '\xde', 'TRADE;': '\u2122', 'TSHcy;': '\u040b', 'TScy;': '\u0426', 'Tab;': '\t', 'Tau;': '\u03a4', 'Tcaron;': '\u0164', 'Tcedil;': '\u0162', 'Tcy;': '\u0422', 'Tfr;': '\u{01d517}', 'Therefore;': '\u2234', 'Theta;': '\u0398', 'ThickSpace;': '\u205f\u200a', 'ThinSpace;': '\u2009', 'Tilde;': '\u223c', 'TildeEqual;': '\u2243', 'TildeFullEqual;': '\u2245', 'TildeTilde;': '\u2248', 'Topf;': '\u{01d54b}', 'TripleDot;': '\u20db', 'Tscr;': '\u{01d4af}', 'Tstrok;': '\u0166', 'Uacute': '\xda', 'Uacute;': '\xda', 'Uarr;': '\u219f', 'Uarrocir;': '\u2949', 'Ubrcy;': '\u040e', 'Ubreve;': '\u016c', 'Ucirc': '\xdb', 'Ucirc;': '\xdb', 'Ucy;': '\u0423', 'Udblac;': '\u0170', 'Ufr;': '\u{01d518}', 'Ugrave': '\xd9', 'Ugrave;': '\xd9', 'Umacr;': '\u016a', 'UnderBar;': '_', 'UnderBrace;': '\u23df', 'UnderBracket;': '\u23b5', 'UnderParenthesis;': '\u23dd', 'Union;': '\u22c3', 'UnionPlus;': '\u228e', 'Uogon;': '\u0172', 'Uopf;': '\u{01d54c}', 'UpArrow;': '\u2191', 'UpArrowBar;': '\u2912', 'UpArrowDownArrow;': '\u21c5', 'UpDownArrow;': '\u2195', 'UpEquilibrium;': '\u296e', 'UpTee;': '\u22a5', 'UpTeeArrow;': '\u21a5', 'Uparrow;': '\u21d1', 'Updownarrow;': '\u21d5', 'UpperLeftArrow;': '\u2196', 'UpperRightArrow;': '\u2197', 'Upsi;': '\u03d2', 'Upsilon;': '\u03a5', 'Uring;': '\u016e', 'Uscr;': '\u{01d4b0}', 'Utilde;': '\u0168', 'Uuml': '\xdc', 'Uuml;': '\xdc', 'VDash;': '\u22ab', 'Vbar;': '\u2aeb', 'Vcy;': '\u0412', 'Vdash;': '\u22a9', 'Vdashl;': '\u2ae6', 'Vee;': '\u22c1', 'Verbar;': '\u2016', 'Vert;': '\u2016', 'VerticalBar;': '\u2223', 'VerticalLine;': '|', 'VerticalSeparator;': '\u2758', 'VerticalTilde;': '\u2240', 'VeryThinSpace;': '\u200a', 'Vfr;': '\u{01d519}', 'Vopf;': '\u{01d54d}', 'Vscr;': '\u{01d4b1}', 'Vvdash;': '\u22aa', 'Wcirc;': '\u0174', 'Wedge;': '\u22c0', 'Wfr;': '\u{01d51a}', 'Wopf;': '\u{01d54e}', 'Wscr;': '\u{01d4b2}', 'Xfr;': '\u{01d51b}', 'Xi;': '\u039e', 'Xopf;': '\u{01d54f}', 'Xscr;': '\u{01d4b3}', 'YAcy;': '\u042f', 'YIcy;': '\u0407', 'YUcy;': '\u042e', 'Yacute': '\xdd', 'Yacute;': '\xdd', 'Ycirc;': '\u0176', 'Ycy;': '\u042b', 'Yfr;': '\u{01d51c}', 'Yopf;': '\u{01d550}', 'Yscr;': '\u{01d4b4}', 'Yuml;': '\u0178', 'ZHcy;': '\u0416', 'Zacute;': '\u0179', 'Zcaron;': '\u017d', 'Zcy;': '\u0417', 'Zdot;': '\u017b', 'ZeroWidthSpace;': '\u200b', 'Zeta;': '\u0396', 'Zfr;': '\u2128', 'Zopf;': '\u2124', 'Zscr;': '\u{01d4b5}', 'aacute': '\xe1', 'aacute;': '\xe1', 'abreve;': '\u0103', 'ac;': '\u223e', 'acE;': '\u223e\u0333', 'acd;': '\u223f', 'acirc': '\xe2', 'acirc;': '\xe2', 'acute': '\xb4', 'acute;': '\xb4', 'acy;': '\u0430', 'aelig': '\xe6', 'aelig;': '\xe6', 'af;': '\u2061', 'afr;': '\u{01d51e}', 'agrave': '\xe0', 'agrave;': '\xe0', 'alefsym;': '\u2135', 'aleph;': '\u2135', 'alpha;': '\u03b1', 'amacr;': '\u0101', 'amalg;': '\u2a3f', 'amp': '&', 'amp;': '&', 'and;': '\u2227', 'andand;': '\u2a55', 'andd;': '\u2a5c', 'andslope;': '\u2a58', 'andv;': '\u2a5a', 'ang;': '\u2220', 'ange;': '\u29a4', 'angle;': '\u2220', 'angmsd;': '\u2221', 'angmsdaa;': '\u29a8', 'angmsdab;': '\u29a9', 'angmsdac;': '\u29aa', 'angmsdad;': '\u29ab', 'angmsdae;': '\u29ac', 'angmsdaf;': '\u29ad', 'angmsdag;': '\u29ae', 'angmsdah;': '\u29af', 'angrt;': '\u221f', 'angrtvb;': '\u22be', 'angrtvbd;': '\u299d', 'angsph;': '\u2222', 'angst;': '\xc5', 'angzarr;': '\u237c', 'aogon;': '\u0105', 'aopf;': '\u{01d552}', 'ap;': '\u2248', 'apE;': '\u2a70', 'apacir;': '\u2a6f', 'ape;': '\u224a', 'apid;': '\u224b', 'apos;': "'", 'approx;': '\u2248', 'approxeq;': '\u224a', 'aring': '\xe5', 'aring;': '\xe5', 'ascr;': '\u{01d4b6}', 'ast;': '*', 'asymp;': '\u2248', 'asympeq;': '\u224d', 'atilde': '\xe3', 'atilde;': '\xe3', 'auml': '\xe4', 'auml;': '\xe4', 'awconint;': '\u2233', 'awint;': '\u2a11', 'bNot;': '\u2aed', 'backcong;': '\u224c', 'backepsilon;': '\u03f6', 'backprime;': '\u2035', 'backsim;': '\u223d', 'backsimeq;': '\u22cd', 'barvee;': '\u22bd', 'barwed;': '\u2305', 'barwedge;': '\u2305', 'bbrk;': '\u23b5', 'bbrktbrk;': '\u23b6', 'bcong;': '\u224c', 'bcy;': '\u0431', 'bdquo;': '\u201e', 'becaus;': '\u2235', 'because;': '\u2235', 'bemptyv;': '\u29b0', 'bepsi;': '\u03f6', 'bernou;': '\u212c', 'beta;': '\u03b2', 'beth;': '\u2136', 'between;': '\u226c', 'bfr;': '\u{01d51f}', 'bigcap;': '\u22c2', 'bigcirc;': '\u25ef', 'bigcup;': '\u22c3', 'bigodot;': '\u2a00', 'bigoplus;': '\u2a01', 'bigotimes;': '\u2a02', 'bigsqcup;': '\u2a06', 'bigstar;': '\u2605', 'bigtriangledown;': '\u25bd', 'bigtriangleup;': '\u25b3', 'biguplus;': '\u2a04', 'bigvee;': '\u22c1', 'bigwedge;': '\u22c0', 'bkarow;': '\u290d', 'blacklozenge;': '\u29eb', 'blacksquare;': '\u25aa', 'blacktriangle;': '\u25b4', 'blacktriangledown;': '\u25be', 'blacktriangleleft;': '\u25c2', 'blacktriangleright;': '\u25b8', 'blank;': '\u2423', 'blk12;': '\u2592', 'blk14;': '\u2591', 'blk34;': '\u2593', 'block;': '\u2588', 'bne;': '=\u20e5', 'bnequiv;': '\u2261\u20e5', 'bnot;': '\u2310', 'bopf;': '\u{01d553}', 'bot;': '\u22a5', 'bottom;': '\u22a5', 'bowtie;': '\u22c8', 'boxDL;': '\u2557', 'boxDR;': '\u2554', 'boxDl;': '\u2556', 'boxDr;': '\u2553', 'boxH;': '\u2550', 'boxHD;': '\u2566', 'boxHU;': '\u2569', 'boxHd;': '\u2564', 'boxHu;': '\u2567', 'boxUL;': '\u255d', 'boxUR;': '\u255a', 'boxUl;': '\u255c', 'boxUr;': '\u2559', 'boxV;': '\u2551', 'boxVH;': '\u256c', 'boxVL;': '\u2563', 'boxVR;': '\u2560', 'boxVh;': '\u256b', 'boxVl;': '\u2562', 'boxVr;': '\u255f', 'boxbox;': '\u29c9', 'boxdL;': '\u2555', 'boxdR;': '\u2552', 'boxdl;': '\u2510', 'boxdr;': '\u250c', 'boxh;': '\u2500', 'boxhD;': '\u2565', 'boxhU;': '\u2568', 'boxhd;': '\u252c', 'boxhu;': '\u2534', 'boxminus;': '\u229f', 'boxplus;': '\u229e', 'boxtimes;': '\u22a0', 'boxuL;': '\u255b', 'boxuR;': '\u2558', 'boxul;': '\u2518', 'boxur;': '\u2514', 'boxv;': '\u2502', 'boxvH;': '\u256a', 'boxvL;': '\u2561', 'boxvR;': '\u255e', 'boxvh;': '\u253c', 'boxvl;': '\u2524', 'boxvr;': '\u251c', 'bprime;': '\u2035', 'breve;': '\u02d8', 'brvbar': '\xa6', 'brvbar;': '\xa6', 'bscr;': '\u{01d4b7}', 'bsemi;': '\u204f', 'bsim;': '\u223d', 'bsime;': '\u22cd', 'bsol;': '\\', 'bsolb;': '\u29c5', 'bsolhsub;': '\u27c8', 'bull;': '\u2022', 'bullet;': '\u2022', 'bump;': '\u224e', 'bumpE;': '\u2aae', 'bumpe;': '\u224f', 'bumpeq;': '\u224f', 'cacute;': '\u0107', 'cap;': '\u2229', 'capand;': '\u2a44', 'capbrcup;': '\u2a49', 'capcap;': '\u2a4b', 'capcup;': '\u2a47', 'capdot;': '\u2a40', 'caps;': '\u2229\ufe00', 'caret;': '\u2041', 'caron;': '\u02c7', 'ccaps;': '\u2a4d', 'ccaron;': '\u010d', 'ccedil': '\xe7', 'ccedil;': '\xe7', 'ccirc;': '\u0109', 'ccups;': '\u2a4c', 'ccupssm;': '\u2a50', 'cdot;': '\u010b', 'cedil': '\xb8', 'cedil;': '\xb8', 'cemptyv;': '\u29b2', 'cent': '\xa2', 'cent;': '\xa2', 'centerdot;': '\xb7', 'cfr;': '\u{01d520}', 'chcy;': '\u0447', 'check;': '\u2713', 'checkmark;': '\u2713', 'chi;': '\u03c7', 'cir;': '\u25cb', 'cirE;': '\u29c3', 'circ;': '\u02c6', 'circeq;': '\u2257', 'circlearrowleft;': '\u21ba', 'circlearrowright;': '\u21bb', 'circledR;': '\xae', 'circledS;': '\u24c8', 'circledast;': '\u229b', 'circledcirc;': '\u229a', 'circleddash;': '\u229d', 'cire;': '\u2257', 'cirfnint;': '\u2a10', 'cirmid;': '\u2aef', 'cirscir;': '\u29c2', 'clubs;': '\u2663', 'clubsuit;': '\u2663', 'colon;': ':', 'colone;': '\u2254', 'coloneq;': '\u2254', 'comma;': ',', 'commat;': '@', 'comp;': '\u2201', 'compfn;': '\u2218', 'complement;': '\u2201', 'complexes;': '\u2102', 'cong;': '\u2245', 'congdot;': '\u2a6d', 'conint;': '\u222e', 'copf;': '\u{01d554}', 'coprod;': '\u2210', 'copy': '\xa9', 'copy;': '\xa9', 'copysr;': '\u2117', 'crarr;': '\u21b5', 'cross;': '\u2717', 'cscr;': '\u{01d4b8}', 'csub;': '\u2acf', 'csube;': '\u2ad1', 'csup;': '\u2ad0', 'csupe;': '\u2ad2', 'ctdot;': '\u22ef', 'cudarrl;': '\u2938', 'cudarrr;': '\u2935', 'cuepr;': '\u22de', 'cuesc;': '\u22df', 'cularr;': '\u21b6', 'cularrp;': '\u293d', 'cup;': '\u222a', 'cupbrcap;': '\u2a48', 'cupcap;': '\u2a46', 'cupcup;': '\u2a4a', 'cupdot;': '\u228d', 'cupor;': '\u2a45', 'cups;': '\u222a\ufe00', 'curarr;': '\u21b7', 'curarrm;': '\u293c', 'curlyeqprec;': '\u22de', 'curlyeqsucc;': '\u22df', 'curlyvee;': '\u22ce', 'curlywedge;': '\u22cf', 'curren': '\xa4', 'curren;': '\xa4', 'curvearrowleft;': '\u21b6', 'curvearrowright;': '\u21b7', 'cuvee;': '\u22ce', 'cuwed;': '\u22cf', 'cwconint;': '\u2232', 'cwint;': '\u2231', 'cylcty;': '\u232d', 'dArr;': '\u21d3', 'dHar;': '\u2965', 'dagger;': '\u2020', 'daleth;': '\u2138', 'darr;': '\u2193', 'dash;': '\u2010', 'dashv;': '\u22a3', 'dbkarow;': '\u290f', 'dblac;': '\u02dd', 'dcaron;': '\u010f', 'dcy;': '\u0434', 'dd;': '\u2146', 'ddagger;': '\u2021', 'ddarr;': '\u21ca', 'ddotseq;': '\u2a77', 'deg': '\xb0', 'deg;': '\xb0', 'delta;': '\u03b4', 'demptyv;': '\u29b1', 'dfisht;': '\u297f', 'dfr;': '\u{01d521}', 'dharl;': '\u21c3', 'dharr;': '\u21c2', 'diam;': '\u22c4', 'diamond;': '\u22c4', 'diamondsuit;': '\u2666', 'diams;': '\u2666', 'die;': '\xa8', 'digamma;': '\u03dd', 'disin;': '\u22f2', 'div;': '\xf7', 'divide': '\xf7', 'divide;': '\xf7', 'divideontimes;': '\u22c7', 'divonx;': '\u22c7', 'djcy;': '\u0452', 'dlcorn;': '\u231e', 'dlcrop;': '\u230d', 'dollar;': '\$', 'dopf;': '\u{01d555}', 'dot;': '\u02d9', 'doteq;': '\u2250', 'doteqdot;': '\u2251', 'dotminus;': '\u2238', 'dotplus;': '\u2214', 'dotsquare;': '\u22a1', 'doublebarwedge;': '\u2306', 'downarrow;': '\u2193', 'downdownarrows;': '\u21ca', 'downharpoonleft;': '\u21c3', 'downharpoonright;': '\u21c2', 'drbkarow;': '\u2910', 'drcorn;': '\u231f', 'drcrop;': '\u230c', 'dscr;': '\u{01d4b9}', 'dscy;': '\u0455', 'dsol;': '\u29f6', 'dstrok;': '\u0111', 'dtdot;': '\u22f1', 'dtri;': '\u25bf', 'dtrif;': '\u25be', 'duarr;': '\u21f5', 'duhar;': '\u296f', 'dwangle;': '\u29a6', 'dzcy;': '\u045f', 'dzigrarr;': '\u27ff', 'eDDot;': '\u2a77', 'eDot;': '\u2251', 'eacute': '\xe9', 'eacute;': '\xe9', 'easter;': '\u2a6e', 'ecaron;': '\u011b', 'ecir;': '\u2256', 'ecirc': '\xea', 'ecirc;': '\xea', 'ecolon;': '\u2255', 'ecy;': '\u044d', 'edot;': '\u0117', 'ee;': '\u2147', 'efDot;': '\u2252', 'efr;': '\u{01d522}', 'eg;': '\u2a9a', 'egrave': '\xe8', 'egrave;': '\xe8', 'egs;': '\u2a96', 'egsdot;': '\u2a98', 'el;': '\u2a99', 'elinters;': '\u23e7', 'ell;': '\u2113', 'els;': '\u2a95', 'elsdot;': '\u2a97', 'emacr;': '\u0113', 'empty;': '\u2205', 'emptyset;': '\u2205', 'emptyv;': '\u2205', 'emsp13;': '\u2004', 'emsp14;': '\u2005', 'emsp;': '\u2003', 'eng;': '\u014b', 'ensp;': '\u2002', 'eogon;': '\u0119', 'eopf;': '\u{01d556}', 'epar;': '\u22d5', 'eparsl;': '\u29e3', 'eplus;': '\u2a71', 'epsi;': '\u03b5', 'epsilon;': '\u03b5', 'epsiv;': '\u03f5', 'eqcirc;': '\u2256', 'eqcolon;': '\u2255', 'eqsim;': '\u2242', 'eqslantgtr;': '\u2a96', 'eqslantless;': '\u2a95', 'equals;': '=', 'equest;': '\u225f', 'equiv;': '\u2261', 'equivDD;': '\u2a78', 'eqvparsl;': '\u29e5', 'erDot;': '\u2253', 'erarr;': '\u2971', 'escr;': '\u212f', 'esdot;': '\u2250', 'esim;': '\u2242', 'eta;': '\u03b7', 'eth': '\xf0', 'eth;': '\xf0', 'euml': '\xeb', 'euml;': '\xeb', 'euro;': '\u20ac', 'excl;': '!', 'exist;': '\u2203', 'expectation;': '\u2130', 'exponentiale;': '\u2147', 'fallingdotseq;': '\u2252', 'fcy;': '\u0444', 'female;': '\u2640', 'ffilig;': '\ufb03', 'fflig;': '\ufb00', 'ffllig;': '\ufb04', 'ffr;': '\u{01d523}', 'filig;': '\ufb01', 'fjlig;': 'fj', 'flat;': '\u266d', 'fllig;': '\ufb02', 'fltns;': '\u25b1', 'fnof;': '\u0192', 'fopf;': '\u{01d557}', 'forall;': '\u2200', 'fork;': '\u22d4', 'forkv;': '\u2ad9', 'fpartint;': '\u2a0d', 'frac12': '\xbd', 'frac12;': '\xbd', 'frac13;': '\u2153', 'frac14': '\xbc', 'frac14;': '\xbc', 'frac15;': '\u2155', 'frac16;': '\u2159', 'frac18;': '\u215b', 'frac23;': '\u2154', 'frac25;': '\u2156', 'frac34': '\xbe', 'frac34;': '\xbe', 'frac35;': '\u2157', 'frac38;': '\u215c', 'frac45;': '\u2158', 'frac56;': '\u215a', 'frac58;': '\u215d', 'frac78;': '\u215e', 'frasl;': '\u2044', 'frown;': '\u2322', 'fscr;': '\u{01d4bb}', 'gE;': '\u2267', 'gEl;': '\u2a8c', 'gacute;': '\u01f5', 'gamma;': '\u03b3', 'gammad;': '\u03dd', 'gap;': '\u2a86', 'gbreve;': '\u011f', 'gcirc;': '\u011d', 'gcy;': '\u0433', 'gdot;': '\u0121', 'ge;': '\u2265', 'gel;': '\u22db', 'geq;': '\u2265', 'geqq;': '\u2267', 'geqslant;': '\u2a7e', 'ges;': '\u2a7e', 'gescc;': '\u2aa9', 'gesdot;': '\u2a80', 'gesdoto;': '\u2a82', 'gesdotol;': '\u2a84', 'gesl;': '\u22db\ufe00', 'gesles;': '\u2a94', 'gfr;': '\u{01d524}', 'gg;': '\u226b', 'ggg;': '\u22d9', 'gimel;': '\u2137', 'gjcy;': '\u0453', 'gl;': '\u2277', 'glE;': '\u2a92', 'gla;': '\u2aa5', 'glj;': '\u2aa4', 'gnE;': '\u2269', 'gnap;': '\u2a8a', 'gnapprox;': '\u2a8a', 'gne;': '\u2a88', 'gneq;': '\u2a88', 'gneqq;': '\u2269', 'gnsim;': '\u22e7', 'gopf;': '\u{01d558}', 'grave;': '`', 'gscr;': '\u210a', 'gsim;': '\u2273', 'gsime;': '\u2a8e', 'gsiml;': '\u2a90', 'gt': '>', 'gt;': '>', 'gtcc;': '\u2aa7', 'gtcir;': '\u2a7a', 'gtdot;': '\u22d7', 'gtlPar;': '\u2995', 'gtquest;': '\u2a7c', 'gtrapprox;': '\u2a86', 'gtrarr;': '\u2978', 'gtrdot;': '\u22d7', 'gtreqless;': '\u22db', 'gtreqqless;': '\u2a8c', 'gtrless;': '\u2277', 'gtrsim;': '\u2273', 'gvertneqq;': '\u2269\ufe00', 'gvnE;': '\u2269\ufe00', 'hArr;': '\u21d4', 'hairsp;': '\u200a', 'half;': '\xbd', 'hamilt;': '\u210b', 'hardcy;': '\u044a', 'harr;': '\u2194', 'harrcir;': '\u2948', 'harrw;': '\u21ad', 'hbar;': '\u210f', 'hcirc;': '\u0125', 'hearts;': '\u2665', 'heartsuit;': '\u2665', 'hellip;': '\u2026', 'hercon;': '\u22b9', 'hfr;': '\u{01d525}', 'hksearow;': '\u2925', 'hkswarow;': '\u2926', 'hoarr;': '\u21ff', 'homtht;': '\u223b', 'hookleftarrow;': '\u21a9', 'hookrightarrow;': '\u21aa', 'hopf;': '\u{01d559}', 'horbar;': '\u2015', 'hscr;': '\u{01d4bd}', 'hslash;': '\u210f', 'hstrok;': '\u0127', 'hybull;': '\u2043', 'hyphen;': '\u2010', 'iacute': '\xed', 'iacute;': '\xed', 'ic;': '\u2063', 'icirc': '\xee', 'icirc;': '\xee', 'icy;': '\u0438', 'iecy;': '\u0435', 'iexcl': '\xa1', 'iexcl;': '\xa1', 'iff;': '\u21d4', 'ifr;': '\u{01d526}', 'igrave': '\xec', 'igrave;': '\xec', 'ii;': '\u2148', 'iiiint;': '\u2a0c', 'iiint;': '\u222d', 'iinfin;': '\u29dc', 'iiota;': '\u2129', 'ijlig;': '\u0133', 'imacr;': '\u012b', 'image;': '\u2111', 'imagline;': '\u2110', 'imagpart;': '\u2111', 'imath;': '\u0131', 'imof;': '\u22b7', 'imped;': '\u01b5', 'in;': '\u2208', 'incare;': '\u2105', 'infin;': '\u221e', 'infintie;': '\u29dd', 'inodot;': '\u0131', 'int;': '\u222b', 'intcal;': '\u22ba', 'integers;': '\u2124', 'intercal;': '\u22ba', 'intlarhk;': '\u2a17', 'intprod;': '\u2a3c', 'iocy;': '\u0451', 'iogon;': '\u012f', 'iopf;': '\u{01d55a}', 'iota;': '\u03b9', 'iprod;': '\u2a3c', 'iquest': '\xbf', 'iquest;': '\xbf', 'iscr;': '\u{01d4be}', 'isin;': '\u2208', 'isinE;': '\u22f9', 'isindot;': '\u22f5', 'isins;': '\u22f4', 'isinsv;': '\u22f3', 'isinv;': '\u2208', 'it;': '\u2062', 'itilde;': '\u0129', 'iukcy;': '\u0456', 'iuml': '\xef', 'iuml;': '\xef', 'jcirc;': '\u0135', 'jcy;': '\u0439', 'jfr;': '\u{01d527}', 'jmath;': '\u0237', 'jopf;': '\u{01d55b}', 'jscr;': '\u{01d4bf}', 'jsercy;': '\u0458', 'jukcy;': '\u0454', 'kappa;': '\u03ba', 'kappav;': '\u03f0', 'kcedil;': '\u0137', 'kcy;': '\u043a', 'kfr;': '\u{01d528}', 'kgreen;': '\u0138', 'khcy;': '\u0445', 'kjcy;': '\u045c', 'kopf;': '\u{01d55c}', 'kscr;': '\u{01d4c0}', 'lAarr;': '\u21da', 'lArr;': '\u21d0', 'lAtail;': '\u291b', 'lBarr;': '\u290e', 'lE;': '\u2266', 'lEg;': '\u2a8b', 'lHar;': '\u2962', 'lacute;': '\u013a', 'laemptyv;': '\u29b4', 'lagran;': '\u2112', 'lambda;': '\u03bb', 'lang;': '\u27e8', 'langd;': '\u2991', 'langle;': '\u27e8', 'lap;': '\u2a85', 'laquo': '\xab', 'laquo;': '\xab', 'larr;': '\u2190', 'larrb;': '\u21e4', 'larrbfs;': '\u291f', 'larrfs;': '\u291d', 'larrhk;': '\u21a9', 'larrlp;': '\u21ab', 'larrpl;': '\u2939', 'larrsim;': '\u2973', 'larrtl;': '\u21a2', 'lat;': '\u2aab', 'latail;': '\u2919', 'late;': '\u2aad', 'lates;': '\u2aad\ufe00', 'lbarr;': '\u290c', 'lbbrk;': '\u2772', 'lbrace;': '{', 'lbrack;': '[', 'lbrke;': '\u298b', 'lbrksld;': '\u298f', 'lbrkslu;': '\u298d', 'lcaron;': '\u013e', 'lcedil;': '\u013c', 'lceil;': '\u2308', 'lcub;': '{', 'lcy;': '\u043b', 'ldca;': '\u2936', 'ldquo;': '\u201c', 'ldquor;': '\u201e', 'ldrdhar;': '\u2967', 'ldrushar;': '\u294b', 'ldsh;': '\u21b2', 'le;': '\u2264', 'leftarrow;': '\u2190', 'leftarrowtail;': '\u21a2', 'leftharpoondown;': '\u21bd', 'leftharpoonup;': '\u21bc', 'leftleftarrows;': '\u21c7', 'leftrightarrow;': '\u2194', 'leftrightarrows;': '\u21c6', 'leftrightharpoons;': '\u21cb', 'leftrightsquigarrow;': '\u21ad', 'leftthreetimes;': '\u22cb', 'leg;': '\u22da', 'leq;': '\u2264', 'leqq;': '\u2266', 'leqslant;': '\u2a7d', 'les;': '\u2a7d', 'lescc;': '\u2aa8', 'lesdot;': '\u2a7f', 'lesdoto;': '\u2a81', 'lesdotor;': '\u2a83', 'lesg;': '\u22da\ufe00', 'lesges;': '\u2a93', 'lessapprox;': '\u2a85', 'lessdot;': '\u22d6', 'lesseqgtr;': '\u22da', 'lesseqqgtr;': '\u2a8b', 'lessgtr;': '\u2276', 'lesssim;': '\u2272', 'lfisht;': '\u297c', 'lfloor;': '\u230a', 'lfr;': '\u{01d529}', 'lg;': '\u2276', 'lgE;': '\u2a91', 'lhard;': '\u21bd', 'lharu;': '\u21bc', 'lharul;': '\u296a', 'lhblk;': '\u2584', 'ljcy;': '\u0459', 'll;': '\u226a', 'llarr;': '\u21c7', 'llcorner;': '\u231e', 'llhard;': '\u296b', 'lltri;': '\u25fa', 'lmidot;': '\u0140', 'lmoust;': '\u23b0', 'lmoustache;': '\u23b0', 'lnE;': '\u2268', 'lnap;': '\u2a89', 'lnapprox;': '\u2a89', 'lne;': '\u2a87', 'lneq;': '\u2a87', 'lneqq;': '\u2268', 'lnsim;': '\u22e6', 'loang;': '\u27ec', 'loarr;': '\u21fd', 'lobrk;': '\u27e6', 'longleftarrow;': '\u27f5', 'longleftrightarrow;': '\u27f7', 'longmapsto;': '\u27fc', 'longrightarrow;': '\u27f6', 'looparrowleft;': '\u21ab', 'looparrowright;': '\u21ac', 'lopar;': '\u2985', 'lopf;': '\u{01d55d}', 'loplus;': '\u2a2d', 'lotimes;': '\u2a34', 'lowast;': '\u2217', 'lowbar;': '_', 'loz;': '\u25ca', 'lozenge;': '\u25ca', 'lozf;': '\u29eb', 'lpar;': '(', 'lparlt;': '\u2993', 'lrarr;': '\u21c6', 'lrcorner;': '\u231f', 'lrhar;': '\u21cb', 'lrhard;': '\u296d', 'lrm;': '\u200e', 'lrtri;': '\u22bf', 'lsaquo;': '\u2039', 'lscr;': '\u{01d4c1}', 'lsh;': '\u21b0', 'lsim;': '\u2272', 'lsime;': '\u2a8d', 'lsimg;': '\u2a8f', 'lsqb;': '[', 'lsquo;': '\u2018', 'lsquor;': '\u201a', 'lstrok;': '\u0142', 'lt': '<', 'lt;': '<', 'ltcc;': '\u2aa6', 'ltcir;': '\u2a79', 'ltdot;': '\u22d6', 'lthree;': '\u22cb', 'ltimes;': '\u22c9', 'ltlarr;': '\u2976', 'ltquest;': '\u2a7b', 'ltrPar;': '\u2996', 'ltri;': '\u25c3', 'ltrie;': '\u22b4', 'ltrif;': '\u25c2', 'lurdshar;': '\u294a', 'luruhar;': '\u2966', 'lvertneqq;': '\u2268\ufe00', 'lvnE;': '\u2268\ufe00', 'mDDot;': '\u223a', 'macr': '\xaf', 'macr;': '\xaf', 'male;': '\u2642', 'malt;': '\u2720', 'maltese;': '\u2720', 'map;': '\u21a6', 'mapsto;': '\u21a6', 'mapstodown;': '\u21a7', 'mapstoleft;': '\u21a4', 'mapstoup;': '\u21a5', 'marker;': '\u25ae', 'mcomma;': '\u2a29', 'mcy;': '\u043c', 'mdash;': '\u2014', 'measuredangle;': '\u2221', 'mfr;': '\u{01d52a}', 'mho;': '\u2127', 'micro': '\xb5', 'micro;': '\xb5', 'mid;': '\u2223', 'midast;': '*', 'midcir;': '\u2af0', 'middot': '\xb7', 'middot;': '\xb7', 'minus;': '\u2212', 'minusb;': '\u229f', 'minusd;': '\u2238', 'minusdu;': '\u2a2a', 'mlcp;': '\u2adb', 'mldr;': '\u2026', 'mnplus;': '\u2213', 'models;': '\u22a7', 'mopf;': '\u{01d55e}', 'mp;': '\u2213', 'mscr;': '\u{01d4c2}', 'mstpos;': '\u223e', 'mu;': '\u03bc', 'multimap;': '\u22b8', 'mumap;': '\u22b8', 'nGg;': '\u22d9\u0338', 'nGt;': '\u226b\u20d2', 'nGtv;': '\u226b\u0338', 'nLeftarrow;': '\u21cd', 'nLeftrightarrow;': '\u21ce', 'nLl;': '\u22d8\u0338', 'nLt;': '\u226a\u20d2', 'nLtv;': '\u226a\u0338', 'nRightarrow;': '\u21cf', 'nVDash;': '\u22af', 'nVdash;': '\u22ae', 'nabla;': '\u2207', 'nacute;': '\u0144', 'nang;': '\u2220\u20d2', 'nap;': '\u2249', 'napE;': '\u2a70\u0338', 'napid;': '\u224b\u0338', 'napos;': '\u0149', 'napprox;': '\u2249', 'natur;': '\u266e', 'natural;': '\u266e', 'naturals;': '\u2115', 'nbsp': '\xa0', 'nbsp;': '\xa0', 'nbump;': '\u224e\u0338', 'nbumpe;': '\u224f\u0338', 'ncap;': '\u2a43', 'ncaron;': '\u0148', 'ncedil;': '\u0146', 'ncong;': '\u2247', 'ncongdot;': '\u2a6d\u0338', 'ncup;': '\u2a42', 'ncy;': '\u043d', 'ndash;': '\u2013', 'ne;': '\u2260', 'neArr;': '\u21d7', 'nearhk;': '\u2924', 'nearr;': '\u2197', 'nearrow;': '\u2197', 'nedot;': '\u2250\u0338', 'nequiv;': '\u2262', 'nesear;': '\u2928', 'nesim;': '\u2242\u0338', 'nexist;': '\u2204', 'nexists;': '\u2204', 'nfr;': '\u{01d52b}', 'ngE;': '\u2267\u0338', 'nge;': '\u2271', 'ngeq;': '\u2271', 'ngeqq;': '\u2267\u0338', 'ngeqslant;': '\u2a7e\u0338', 'nges;': '\u2a7e\u0338', 'ngsim;': '\u2275', 'ngt;': '\u226f', 'ngtr;': '\u226f', 'nhArr;': '\u21ce', 'nharr;': '\u21ae', 'nhpar;': '\u2af2', 'ni;': '\u220b', 'nis;': '\u22fc', 'nisd;': '\u22fa', 'niv;': '\u220b', 'njcy;': '\u045a', 'nlArr;': '\u21cd', 'nlE;': '\u2266\u0338', 'nlarr;': '\u219a', 'nldr;': '\u2025', 'nle;': '\u2270', 'nleftarrow;': '\u219a', 'nleftrightarrow;': '\u21ae', 'nleq;': '\u2270', 'nleqq;': '\u2266\u0338', 'nleqslant;': '\u2a7d\u0338', 'nles;': '\u2a7d\u0338', 'nless;': '\u226e', 'nlsim;': '\u2274', 'nlt;': '\u226e', 'nltri;': '\u22ea', 'nltrie;': '\u22ec', 'nmid;': '\u2224', 'nopf;': '\u{01d55f}', 'not': '\xac', 'not;': '\xac', 'notin;': '\u2209', 'notinE;': '\u22f9\u0338', 'notindot;': '\u22f5\u0338', 'notinva;': '\u2209', 'notinvb;': '\u22f7', 'notinvc;': '\u22f6', 'notni;': '\u220c', 'notniva;': '\u220c', 'notnivb;': '\u22fe', 'notnivc;': '\u22fd', 'npar;': '\u2226', 'nparallel;': '\u2226', 'nparsl;': '\u2afd\u20e5', 'npart;': '\u2202\u0338', 'npolint;': '\u2a14', 'npr;': '\u2280', 'nprcue;': '\u22e0', 'npre;': '\u2aaf\u0338', 'nprec;': '\u2280', 'npreceq;': '\u2aaf\u0338', 'nrArr;': '\u21cf', 'nrarr;': '\u219b', 'nrarrc;': '\u2933\u0338', 'nrarrw;': '\u219d\u0338', 'nrightarrow;': '\u219b', 'nrtri;': '\u22eb', 'nrtrie;': '\u22ed', 'nsc;': '\u2281', 'nsccue;': '\u22e1', 'nsce;': '\u2ab0\u0338', 'nscr;': '\u{01d4c3}', 'nshortmid;': '\u2224', 'nshortparallel;': '\u2226', 'nsim;': '\u2241', 'nsime;': '\u2244', 'nsimeq;': '\u2244', 'nsmid;': '\u2224', 'nspar;': '\u2226', 'nsqsube;': '\u22e2', 'nsqsupe;': '\u22e3', 'nsub;': '\u2284', 'nsubE;': '\u2ac5\u0338', 'nsube;': '\u2288', 'nsubset;': '\u2282\u20d2', 'nsubseteq;': '\u2288', 'nsubseteqq;': '\u2ac5\u0338', 'nsucc;': '\u2281', 'nsucceq;': '\u2ab0\u0338', 'nsup;': '\u2285', 'nsupE;': '\u2ac6\u0338', 'nsupe;': '\u2289', 'nsupset;': '\u2283\u20d2', 'nsupseteq;': '\u2289', 'nsupseteqq;': '\u2ac6\u0338', 'ntgl;': '\u2279', 'ntilde': '\xf1', 'ntilde;': '\xf1', 'ntlg;': '\u2278', 'ntriangleleft;': '\u22ea', 'ntrianglelefteq;': '\u22ec', 'ntriangleright;': '\u22eb', 'ntrianglerighteq;': '\u22ed', 'nu;': '\u03bd', 'num;': '#', 'numero;': '\u2116', 'numsp;': '\u2007', 'nvDash;': '\u22ad', 'nvHarr;': '\u2904', 'nvap;': '\u224d\u20d2', 'nvdash;': '\u22ac', 'nvge;': '\u2265\u20d2', 'nvgt;': '>\u20d2', 'nvinfin;': '\u29de', 'nvlArr;': '\u2902', 'nvle;': '\u2264\u20d2', 'nvlt;': '<\u20d2', 'nvltrie;': '\u22b4\u20d2', 'nvrArr;': '\u2903', 'nvrtrie;': '\u22b5\u20d2', 'nvsim;': '\u223c\u20d2', 'nwArr;': '\u21d6', 'nwarhk;': '\u2923', 'nwarr;': '\u2196', 'nwarrow;': '\u2196', 'nwnear;': '\u2927', 'oS;': '\u24c8', 'oacute': '\xf3', 'oacute;': '\xf3', 'oast;': '\u229b', 'ocir;': '\u229a', 'ocirc': '\xf4', 'ocirc;': '\xf4', 'ocy;': '\u043e', 'odash;': '\u229d', 'odblac;': '\u0151', 'odiv;': '\u2a38', 'odot;': '\u2299', 'odsold;': '\u29bc', 'oelig;': '\u0153', 'ofcir;': '\u29bf', 'ofr;': '\u{01d52c}', 'ogon;': '\u02db', 'ograve': '\xf2', 'ograve;': '\xf2', 'ogt;': '\u29c1', 'ohbar;': '\u29b5', 'ohm;': '\u03a9', 'oint;': '\u222e', 'olarr;': '\u21ba', 'olcir;': '\u29be', 'olcross;': '\u29bb', 'oline;': '\u203e', 'olt;': '\u29c0', 'omacr;': '\u014d', 'omega;': '\u03c9', 'omicron;': '\u03bf', 'omid;': '\u29b6', 'ominus;': '\u2296', 'oopf;': '\u{01d560}', 'opar;': '\u29b7', 'operp;': '\u29b9', 'oplus;': '\u2295', 'or;': '\u2228', 'orarr;': '\u21bb', 'ord;': '\u2a5d', 'order;': '\u2134', 'orderof;': '\u2134', 'ordf': '\xaa', 'ordf;': '\xaa', 'ordm': '\xba', 'ordm;': '\xba', 'origof;': '\u22b6', 'oror;': '\u2a56', 'orslope;': '\u2a57', 'orv;': '\u2a5b', 'oscr;': '\u2134', 'oslash': '\xf8', 'oslash;': '\xf8', 'osol;': '\u2298', 'otilde': '\xf5', 'otilde;': '\xf5', 'otimes;': '\u2297', 'otimesas;': '\u2a36', 'ouml': '\xf6', 'ouml;': '\xf6', 'ovbar;': '\u233d', 'par;': '\u2225', 'para': '\xb6', 'para;': '\xb6', 'parallel;': '\u2225', 'parsim;': '\u2af3', 'parsl;': '\u2afd', 'part;': '\u2202', 'pcy;': '\u043f', 'percnt;': '%', 'period;': '.', 'permil;': '\u2030', 'perp;': '\u22a5', 'pertenk;': '\u2031', 'pfr;': '\u{01d52d}', 'phi;': '\u03c6', 'phiv;': '\u03d5', 'phmmat;': '\u2133', 'phone;': '\u260e', 'pi;': '\u03c0', 'pitchfork;': '\u22d4', 'piv;': '\u03d6', 'planck;': '\u210f', 'planckh;': '\u210e', 'plankv;': '\u210f', 'plus;': '+', 'plusacir;': '\u2a23', 'plusb;': '\u229e', 'pluscir;': '\u2a22', 'plusdo;': '\u2214', 'plusdu;': '\u2a25', 'pluse;': '\u2a72', 'plusmn': '\xb1', 'plusmn;': '\xb1', 'plussim;': '\u2a26', 'plustwo;': '\u2a27', 'pm;': '\xb1', 'pointint;': '\u2a15', 'popf;': '\u{01d561}', 'pound': '\xa3', 'pound;': '\xa3', 'pr;': '\u227a', 'prE;': '\u2ab3', 'prap;': '\u2ab7', 'prcue;': '\u227c', 'pre;': '\u2aaf', 'prec;': '\u227a', 'precapprox;': '\u2ab7', 'preccurlyeq;': '\u227c', 'preceq;': '\u2aaf', 'precnapprox;': '\u2ab9', 'precneqq;': '\u2ab5', 'precnsim;': '\u22e8', 'precsim;': '\u227e', 'prime;': '\u2032', 'primes;': '\u2119', 'prnE;': '\u2ab5', 'prnap;': '\u2ab9', 'prnsim;': '\u22e8', 'prod;': '\u220f', 'profalar;': '\u232e', 'profline;': '\u2312', 'profsurf;': '\u2313', 'prop;': '\u221d', 'propto;': '\u221d', 'prsim;': '\u227e', 'prurel;': '\u22b0', 'pscr;': '\u{01d4c5}', 'psi;': '\u03c8', 'puncsp;': '\u2008', 'qfr;': '\u{01d52e}', 'qint;': '\u2a0c', 'qopf;': '\u{01d562}', 'qprime;': '\u2057', 'qscr;': '\u{01d4c6}', 'quaternions;': '\u210d', 'quatint;': '\u2a16', 'quest;': '?', 'questeq;': '\u225f', 'quot': '"', 'quot;': '"', 'rAarr;': '\u21db', 'rArr;': '\u21d2', 'rAtail;': '\u291c', 'rBarr;': '\u290f', 'rHar;': '\u2964', 'race;': '\u223d\u0331', 'racute;': '\u0155', 'radic;': '\u221a', 'raemptyv;': '\u29b3', 'rang;': '\u27e9', 'rangd;': '\u2992', 'range;': '\u29a5', 'rangle;': '\u27e9', 'raquo': '\xbb', 'raquo;': '\xbb', 'rarr;': '\u2192', 'rarrap;': '\u2975', 'rarrb;': '\u21e5', 'rarrbfs;': '\u2920', 'rarrc;': '\u2933', 'rarrfs;': '\u291e', 'rarrhk;': '\u21aa', 'rarrlp;': '\u21ac', 'rarrpl;': '\u2945', 'rarrsim;': '\u2974', 'rarrtl;': '\u21a3', 'rarrw;': '\u219d', 'ratail;': '\u291a', 'ratio;': '\u2236', 'rationals;': '\u211a', 'rbarr;': '\u290d', 'rbbrk;': '\u2773', 'rbrace;': '}', 'rbrack;': ']', 'rbrke;': '\u298c', 'rbrksld;': '\u298e', 'rbrkslu;': '\u2990', 'rcaron;': '\u0159', 'rcedil;': '\u0157', 'rceil;': '\u2309', 'rcub;': '}', 'rcy;': '\u0440', 'rdca;': '\u2937', 'rdldhar;': '\u2969', 'rdquo;': '\u201d', 'rdquor;': '\u201d', 'rdsh;': '\u21b3', 'real;': '\u211c', 'realine;': '\u211b', 'realpart;': '\u211c', 'reals;': '\u211d', 'rect;': '\u25ad', 'reg': '\xae', 'reg;': '\xae', 'rfisht;': '\u297d', 'rfloor;': '\u230b', 'rfr;': '\u{01d52f}', 'rhard;': '\u21c1', 'rharu;': '\u21c0', 'rharul;': '\u296c', 'rho;': '\u03c1', 'rhov;': '\u03f1', 'rightarrow;': '\u2192', 'rightarrowtail;': '\u21a3', 'rightharpoondown;': '\u21c1', 'rightharpoonup;': '\u21c0', 'rightleftarrows;': '\u21c4', 'rightleftharpoons;': '\u21cc', 'rightrightarrows;': '\u21c9', 'rightsquigarrow;': '\u219d', 'rightthreetimes;': '\u22cc', 'ring;': '\u02da', 'risingdotseq;': '\u2253', 'rlarr;': '\u21c4', 'rlhar;': '\u21cc', 'rlm;': '\u200f', 'rmoust;': '\u23b1', 'rmoustache;': '\u23b1', 'rnmid;': '\u2aee', 'roang;': '\u27ed', 'roarr;': '\u21fe', 'robrk;': '\u27e7', 'ropar;': '\u2986', 'ropf;': '\u{01d563}', 'roplus;': '\u2a2e', 'rotimes;': '\u2a35', 'rpar;': ')', 'rpargt;': '\u2994', 'rppolint;': '\u2a12', 'rrarr;': '\u21c9', 'rsaquo;': '\u203a', 'rscr;': '\u{01d4c7}', 'rsh;': '\u21b1', 'rsqb;': ']', 'rsquo;': '\u2019', 'rsquor;': '\u2019', 'rthree;': '\u22cc', 'rtimes;': '\u22ca', 'rtri;': '\u25b9', 'rtrie;': '\u22b5', 'rtrif;': '\u25b8', 'rtriltri;': '\u29ce', 'ruluhar;': '\u2968', 'rx;': '\u211e', 'sacute;': '\u015b', 'sbquo;': '\u201a', 'sc;': '\u227b', 'scE;': '\u2ab4', 'scap;': '\u2ab8', 'scaron;': '\u0161', 'sccue;': '\u227d', 'sce;': '\u2ab0', 'scedil;': '\u015f', 'scirc;': '\u015d', 'scnE;': '\u2ab6', 'scnap;': '\u2aba', 'scnsim;': '\u22e9', 'scpolint;': '\u2a13', 'scsim;': '\u227f', 'scy;': '\u0441', 'sdot;': '\u22c5', 'sdotb;': '\u22a1', 'sdote;': '\u2a66', 'seArr;': '\u21d8', 'searhk;': '\u2925', 'searr;': '\u2198', 'searrow;': '\u2198', 'sect': '\xa7', 'sect;': '\xa7', 'semi;': ';', 'seswar;': '\u2929', 'setminus;': '\u2216', 'setmn;': '\u2216', 'sext;': '\u2736', 'sfr;': '\u{01d530}', 'sfrown;': '\u2322', 'sharp;': '\u266f', 'shchcy;': '\u0449', 'shcy;': '\u0448', 'shortmid;': '\u2223', 'shortparallel;': '\u2225', 'shy': '\xad', 'shy;': '\xad', 'sigma;': '\u03c3', 'sigmaf;': '\u03c2', 'sigmav;': '\u03c2', 'sim;': '\u223c', 'simdot;': '\u2a6a', 'sime;': '\u2243', 'simeq;': '\u2243', 'simg;': '\u2a9e', 'simgE;': '\u2aa0', 'siml;': '\u2a9d', 'simlE;': '\u2a9f', 'simne;': '\u2246', 'simplus;': '\u2a24', 'simrarr;': '\u2972', 'slarr;': '\u2190', 'smallsetminus;': '\u2216', 'smashp;': '\u2a33', 'smeparsl;': '\u29e4', 'smid;': '\u2223', 'smile;': '\u2323', 'smt;': '\u2aaa', 'smte;': '\u2aac', 'smtes;': '\u2aac\ufe00', 'softcy;': '\u044c', 'sol;': '/', 'solb;': '\u29c4', 'solbar;': '\u233f', 'sopf;': '\u{01d564}', 'spades;': '\u2660', 'spadesuit;': '\u2660', 'spar;': '\u2225', 'sqcap;': '\u2293', 'sqcaps;': '\u2293\ufe00', 'sqcup;': '\u2294', 'sqcups;': '\u2294\ufe00', 'sqsub;': '\u228f', 'sqsube;': '\u2291', 'sqsubset;': '\u228f', 'sqsubseteq;': '\u2291', 'sqsup;': '\u2290', 'sqsupe;': '\u2292', 'sqsupset;': '\u2290', 'sqsupseteq;': '\u2292', 'squ;': '\u25a1', 'square;': '\u25a1', 'squarf;': '\u25aa', 'squf;': '\u25aa', 'srarr;': '\u2192', 'sscr;': '\u{01d4c8}', 'ssetmn;': '\u2216', 'ssmile;': '\u2323', 'sstarf;': '\u22c6', 'star;': '\u2606', 'starf;': '\u2605', 'straightepsilon;': '\u03f5', 'straightphi;': '\u03d5', 'strns;': '\xaf', 'sub;': '\u2282', 'subE;': '\u2ac5', 'subdot;': '\u2abd', 'sube;': '\u2286', 'subedot;': '\u2ac3', 'submult;': '\u2ac1', 'subnE;': '\u2acb', 'subne;': '\u228a', 'subplus;': '\u2abf', 'subrarr;': '\u2979', 'subset;': '\u2282', 'subseteq;': '\u2286', 'subseteqq;': '\u2ac5', 'subsetneq;': '\u228a', 'subsetneqq;': '\u2acb', 'subsim;': '\u2ac7', 'subsub;': '\u2ad5', 'subsup;': '\u2ad3', 'succ;': '\u227b', 'succapprox;': '\u2ab8', 'succcurlyeq;': '\u227d', 'succeq;': '\u2ab0', 'succnapprox;': '\u2aba', 'succneqq;': '\u2ab6', 'succnsim;': '\u22e9', 'succsim;': '\u227f', 'sum;': '\u2211', 'sung;': '\u266a', 'sup1': '\xb9', 'sup1;': '\xb9', 'sup2': '\xb2', 'sup2;': '\xb2', 'sup3': '\xb3', 'sup3;': '\xb3', 'sup;': '\u2283', 'supE;': '\u2ac6', 'supdot;': '\u2abe', 'supdsub;': '\u2ad8', 'supe;': '\u2287', 'supedot;': '\u2ac4', 'suphsol;': '\u27c9', 'suphsub;': '\u2ad7', 'suplarr;': '\u297b', 'supmult;': '\u2ac2', 'supnE;': '\u2acc', 'supne;': '\u228b', 'supplus;': '\u2ac0', 'supset;': '\u2283', 'supseteq;': '\u2287', 'supseteqq;': '\u2ac6', 'supsetneq;': '\u228b', 'supsetneqq;': '\u2acc', 'supsim;': '\u2ac8', 'supsub;': '\u2ad4', 'supsup;': '\u2ad6', 'swArr;': '\u21d9', 'swarhk;': '\u2926', 'swarr;': '\u2199', 'swarrow;': '\u2199', 'swnwar;': '\u292a', 'szlig': '\xdf', 'szlig;': '\xdf', 'target;': '\u2316', 'tau;': '\u03c4', 'tbrk;': '\u23b4', 'tcaron;': '\u0165', 'tcedil;': '\u0163', 'tcy;': '\u0442', 'tdot;': '\u20db', 'telrec;': '\u2315', 'tfr;': '\u{01d531}', 'there4;': '\u2234', 'therefore;': '\u2234', 'theta;': '\u03b8', 'thetasym;': '\u03d1', 'thetav;': '\u03d1', 'thickapprox;': '\u2248', 'thicksim;': '\u223c', 'thinsp;': '\u2009', 'thkap;': '\u2248', 'thksim;': '\u223c', 'thorn': '\xfe', 'thorn;': '\xfe', 'tilde;': '\u02dc', 'times': '\xd7', 'times;': '\xd7', 'timesb;': '\u22a0', 'timesbar;': '\u2a31', 'timesd;': '\u2a30', 'tint;': '\u222d', 'toea;': '\u2928', 'top;': '\u22a4', 'topbot;': '\u2336', 'topcir;': '\u2af1', 'topf;': '\u{01d565}', 'topfork;': '\u2ada', 'tosa;': '\u2929', 'tprime;': '\u2034', 'trade;': '\u2122', 'triangle;': '\u25b5', 'triangledown;': '\u25bf', 'triangleleft;': '\u25c3', 'trianglelefteq;': '\u22b4', 'triangleq;': '\u225c', 'triangleright;': '\u25b9', 'trianglerighteq;': '\u22b5', 'tridot;': '\u25ec', 'trie;': '\u225c', 'triminus;': '\u2a3a', 'triplus;': '\u2a39', 'trisb;': '\u29cd', 'tritime;': '\u2a3b', 'trpezium;': '\u23e2', 'tscr;': '\u{01d4c9}', 'tscy;': '\u0446', 'tshcy;': '\u045b', 'tstrok;': '\u0167', 'twixt;': '\u226c', 'twoheadleftarrow;': '\u219e', 'twoheadrightarrow;': '\u21a0', 'uArr;': '\u21d1', 'uHar;': '\u2963', 'uacute': '\xfa', 'uacute;': '\xfa', 'uarr;': '\u2191', 'ubrcy;': '\u045e', 'ubreve;': '\u016d', 'ucirc': '\xfb', 'ucirc;': '\xfb', 'ucy;': '\u0443', 'udarr;': '\u21c5', 'udblac;': '\u0171', 'udhar;': '\u296e', 'ufisht;': '\u297e', 'ufr;': '\u{01d532}', 'ugrave': '\xf9', 'ugrave;': '\xf9', 'uharl;': '\u21bf', 'uharr;': '\u21be', 'uhblk;': '\u2580', 'ulcorn;': '\u231c', 'ulcorner;': '\u231c', 'ulcrop;': '\u230f', 'ultri;': '\u25f8', 'umacr;': '\u016b', 'uml': '\xa8', 'uml;': '\xa8', 'uogon;': '\u0173', 'uopf;': '\u{01d566}', 'uparrow;': '\u2191', 'updownarrow;': '\u2195', 'upharpoonleft;': '\u21bf', 'upharpoonright;': '\u21be', 'uplus;': '\u228e', 'upsi;': '\u03c5', 'upsih;': '\u03d2', 'upsilon;': '\u03c5', 'upuparrows;': '\u21c8', 'urcorn;': '\u231d', 'urcorner;': '\u231d', 'urcrop;': '\u230e', 'uring;': '\u016f', 'urtri;': '\u25f9', 'uscr;': '\u{01d4ca}', 'utdot;': '\u22f0', 'utilde;': '\u0169', 'utri;': '\u25b5', 'utrif;': '\u25b4', 'uuarr;': '\u21c8', 'uuml': '\xfc', 'uuml;': '\xfc', 'uwangle;': '\u29a7', 'vArr;': '\u21d5', 'vBar;': '\u2ae8', 'vBarv;': '\u2ae9', 'vDash;': '\u22a8', 'vangrt;': '\u299c', 'varepsilon;': '\u03f5', 'varkappa;': '\u03f0', 'varnothing;': '\u2205', 'varphi;': '\u03d5', 'varpi;': '\u03d6', 'varpropto;': '\u221d', 'varr;': '\u2195', 'varrho;': '\u03f1', 'varsigma;': '\u03c2', 'varsubsetneq;': '\u228a\ufe00', 'varsubsetneqq;': '\u2acb\ufe00', 'varsupsetneq;': '\u228b\ufe00', 'varsupsetneqq;': '\u2acc\ufe00', 'vartheta;': '\u03d1', 'vartriangleleft;': '\u22b2', 'vartriangleright;': '\u22b3', 'vcy;': '\u0432', 'vdash;': '\u22a2', 'vee;': '\u2228', 'veebar;': '\u22bb', 'veeeq;': '\u225a', 'vellip;': '\u22ee', 'verbar;': '|', 'vert;': '|', 'vfr;': '\u{01d533}', 'vltri;': '\u22b2', 'vnsub;': '\u2282\u20d2', 'vnsup;': '\u2283\u20d2', 'vopf;': '\u{01d567}', 'vprop;': '\u221d', 'vrtri;': '\u22b3', 'vscr;': '\u{01d4cb}', 'vsubnE;': '\u2acb\ufe00', 'vsubne;': '\u228a\ufe00', 'vsupnE;': '\u2acc\ufe00', 'vsupne;': '\u228b\ufe00', 'vzigzag;': '\u299a', 'wcirc;': '\u0175', 'wedbar;': '\u2a5f', 'wedge;': '\u2227', 'wedgeq;': '\u2259', 'weierp;': '\u2118', 'wfr;': '\u{01d534}', 'wopf;': '\u{01d568}', 'wp;': '\u2118', 'wr;': '\u2240', 'wreath;': '\u2240', 'wscr;': '\u{01d4cc}', 'xcap;': '\u22c2', 'xcirc;': '\u25ef', 'xcup;': '\u22c3', 'xdtri;': '\u25bd', 'xfr;': '\u{01d535}', 'xhArr;': '\u27fa', 'xharr;': '\u27f7', 'xi;': '\u03be', 'xlArr;': '\u27f8', 'xlarr;': '\u27f5', 'xmap;': '\u27fc', 'xnis;': '\u22fb', 'xodot;': '\u2a00', 'xopf;': '\u{01d569}', 'xoplus;': '\u2a01', 'xotime;': '\u2a02', 'xrArr;': '\u27f9', 'xrarr;': '\u27f6', 'xscr;': '\u{01d4cd}', 'xsqcup;': '\u2a06', 'xuplus;': '\u2a04', 'xutri;': '\u25b3', 'xvee;': '\u22c1', 'xwedge;': '\u22c0', 'yacute': '\xfd', 'yacute;': '\xfd', 'yacy;': '\u044f', 'ycirc;': '\u0177', 'ycy;': '\u044b', 'yen': '\xa5', 'yen;': '\xa5', 'yfr;': '\u{01d536}', 'yicy;': '\u0457', 'yopf;': '\u{01d56a}', 'yscr;': '\u{01d4ce}', 'yucy;': '\u044e', 'yuml': '\xff', 'yuml;': '\xff', 'zacute;': '\u017a', 'zcaron;': '\u017e', 'zcy;': '\u0437', 'zdot;': '\u017c', 'zeetrf;': '\u2128', 'zeta;': '\u03b6', 'zfr;': '\u{01d537}', 'zhcy;': '\u0436', 'zigrarr;': '\u21dd', 'zopf;': '\u{01d56b}', 'zscr;': '\u{01d4cf}', 'zwj;': '\u200d', 'zwnj;': '\u200c', }; const Map<int, String> replacementCharacters = { 0x00: '\uFFFD', 0x0d: '\u000D', 0x80: '\u20AC', 0x81: '\u0081', 0x82: '\u201A', 0x83: '\u0192', 0x84: '\u201E', 0x85: '\u2026', 0x86: '\u2020', 0x87: '\u2021', 0x88: '\u02C6', 0x89: '\u2030', 0x8A: '\u0160', 0x8B: '\u2039', 0x8C: '\u0152', 0x8D: '\u008D', 0x8E: '\u017D', 0x8F: '\u008F', 0x90: '\u0090', 0x91: '\u2018', 0x92: '\u2019', 0x93: '\u201C', 0x94: '\u201D', 0x95: '\u2022', 0x96: '\u2013', 0x97: '\u2014', 0x98: '\u02DC', 0x99: '\u2122', 0x9A: '\u0161', 0x9B: '\u203A', 0x9C: '\u0153', 0x9D: '\u009D', 0x9E: '\u017E', 0x9F: '\u0178' }; const Map<String, String> encodings = { '437': 'cp437', '850': 'cp850', '852': 'cp852', '855': 'cp855', '857': 'cp857', '860': 'cp860', '861': 'cp861', '862': 'cp862', '863': 'cp863', '865': 'cp865', '866': 'cp866', '869': 'cp869', 'ansix341968': 'ascii', 'ansix341986': 'ascii', 'arabic': 'iso8859-6', 'ascii': 'ascii', 'asmo708': 'iso8859-6', 'big5': 'big5', 'big5hkscs': 'big5hkscs', 'chinese': 'gbk', 'cp037': 'cp037', 'cp1026': 'cp1026', 'cp154': 'ptcp154', 'cp367': 'ascii', 'cp424': 'cp424', 'cp437': 'cp437', 'cp500': 'cp500', 'cp775': 'cp775', 'cp819': 'windows-1252', 'cp850': 'cp850', 'cp852': 'cp852', 'cp855': 'cp855', 'cp857': 'cp857', 'cp860': 'cp860', 'cp861': 'cp861', 'cp862': 'cp862', 'cp863': 'cp863', 'cp864': 'cp864', 'cp865': 'cp865', 'cp866': 'cp866', 'cp869': 'cp869', 'cp936': 'gbk', 'cpgr': 'cp869', 'cpis': 'cp861', 'csascii': 'ascii', 'csbig5': 'big5', 'cseuckr': 'cp949', 'cseucpkdfmtjapanese': 'euc_jp', 'csgb2312': 'gbk', 'cshproman8': 'hp-roman8', 'csibm037': 'cp037', 'csibm1026': 'cp1026', 'csibm424': 'cp424', 'csibm500': 'cp500', 'csibm855': 'cp855', 'csibm857': 'cp857', 'csibm860': 'cp860', 'csibm861': 'cp861', 'csibm863': 'cp863', 'csibm864': 'cp864', 'csibm865': 'cp865', 'csibm866': 'cp866', 'csibm869': 'cp869', 'csiso2022jp': 'iso2022_jp', 'csiso2022jp2': 'iso2022_jp_2', 'csiso2022kr': 'iso2022_kr', 'csiso58gb231280': 'gbk', 'csisolatin1': 'windows-1252', 'csisolatin2': 'iso8859-2', 'csisolatin3': 'iso8859-3', 'csisolatin4': 'iso8859-4', 'csisolatin5': 'windows-1254', 'csisolatin6': 'iso8859-10', 'csisolatinarabic': 'iso8859-6', 'csisolatincyrillic': 'iso8859-5', 'csisolatingreek': 'iso8859-7', 'csisolatinhebrew': 'iso8859-8', 'cskoi8r': 'koi8-r', 'csksc56011987': 'cp949', 'cspc775baltic': 'cp775', 'cspc850multilingual': 'cp850', 'cspc862latinhebrew': 'cp862', 'cspc8codepage437': 'cp437', 'cspcp852': 'cp852', 'csptcp154': 'ptcp154', 'csshiftjis': 'shift_jis', 'csunicode11utf7': 'utf-7', 'cyrillic': 'iso8859-5', 'cyrillicasian': 'ptcp154', 'ebcdiccpbe': 'cp500', 'ebcdiccpca': 'cp037', 'ebcdiccpch': 'cp500', 'ebcdiccphe': 'cp424', 'ebcdiccpnl': 'cp037', 'ebcdiccpus': 'cp037', 'ebcdiccpwt': 'cp037', 'ecma114': 'iso8859-6', 'ecma118': 'iso8859-7', 'elot928': 'iso8859-7', 'eucjp': 'euc_jp', 'euckr': 'cp949', 'extendedunixcodepackedformatforjapanese': 'euc_jp', 'gb18030': 'gb18030', 'gb2312': 'gbk', 'gb231280': 'gbk', 'gbk': 'gbk', 'greek': 'iso8859-7', 'greek8': 'iso8859-7', 'hebrew': 'iso8859-8', 'hproman8': 'hp-roman8', 'hzgb2312': 'hz', 'ibm037': 'cp037', 'ibm1026': 'cp1026', 'ibm367': 'ascii', 'ibm424': 'cp424', 'ibm437': 'cp437', 'ibm500': 'cp500', 'ibm775': 'cp775', 'ibm819': 'windows-1252', 'ibm850': 'cp850', 'ibm852': 'cp852', 'ibm855': 'cp855', 'ibm857': 'cp857', 'ibm860': 'cp860', 'ibm861': 'cp861', 'ibm862': 'cp862', 'ibm863': 'cp863', 'ibm864': 'cp864', 'ibm865': 'cp865', 'ibm866': 'cp866', 'ibm869': 'cp869', 'iso2022jp': 'iso2022_jp', 'iso2022jp2': 'iso2022_jp_2', 'iso2022kr': 'iso2022_kr', 'iso646irv1991': 'ascii', 'iso646us': 'ascii', 'iso88591': 'windows-1252', 'iso885910': 'iso8859-10', 'iso8859101992': 'iso8859-10', 'iso885911987': 'windows-1252', 'iso885913': 'iso8859-13', 'iso885914': 'iso8859-14', 'iso8859141998': 'iso8859-14', 'iso885915': 'iso8859-15', 'iso885916': 'iso8859-16', 'iso8859162001': 'iso8859-16', 'iso88592': 'iso8859-2', 'iso885921987': 'iso8859-2', 'iso88593': 'iso8859-3', 'iso885931988': 'iso8859-3', 'iso88594': 'iso8859-4', 'iso885941988': 'iso8859-4', 'iso88595': 'iso8859-5', 'iso885951988': 'iso8859-5', 'iso88596': 'iso8859-6', 'iso885961987': 'iso8859-6', 'iso88597': 'iso8859-7', 'iso885971987': 'iso8859-7', 'iso88598': 'iso8859-8', 'iso885981988': 'iso8859-8', 'iso88599': 'windows-1254', 'iso885991989': 'windows-1254', 'isoceltic': 'iso8859-14', 'isoir100': 'windows-1252', 'isoir101': 'iso8859-2', 'isoir109': 'iso8859-3', 'isoir110': 'iso8859-4', 'isoir126': 'iso8859-7', 'isoir127': 'iso8859-6', 'isoir138': 'iso8859-8', 'isoir144': 'iso8859-5', 'isoir148': 'windows-1254', 'isoir149': 'cp949', 'isoir157': 'iso8859-10', 'isoir199': 'iso8859-14', 'isoir226': 'iso8859-16', 'isoir58': 'gbk', 'isoir6': 'ascii', 'koi8r': 'koi8-r', 'koi8u': 'koi8-u', 'korean': 'cp949', 'ksc5601': 'cp949', 'ksc56011987': 'cp949', 'ksc56011989': 'cp949', 'l1': 'windows-1252', 'l10': 'iso8859-16', 'l2': 'iso8859-2', 'l3': 'iso8859-3', 'l4': 'iso8859-4', 'l5': 'windows-1254', 'l6': 'iso8859-10', 'l8': 'iso8859-14', 'latin1': 'windows-1252', 'latin10': 'iso8859-16', 'latin2': 'iso8859-2', 'latin3': 'iso8859-3', 'latin4': 'iso8859-4', 'latin5': 'windows-1254', 'latin6': 'iso8859-10', 'latin8': 'iso8859-14', 'latin9': 'iso8859-15', 'ms936': 'gbk', 'mskanji': 'shift_jis', 'pt154': 'ptcp154', 'ptcp154': 'ptcp154', 'r8': 'hp-roman8', 'roman8': 'hp-roman8', 'shiftjis': 'shift_jis', 'tis620': 'cp874', 'unicode11utf7': 'utf-7', 'us': 'ascii', 'usascii': 'ascii', 'utf16': 'utf-16', 'utf16be': 'utf-16-be', 'utf16le': 'utf-16-le', 'utf8': 'utf-8', 'windows1250': 'cp1250', 'windows1251': 'cp1251', 'windows1252': 'cp1252', 'windows1253': 'cp1253', 'windows1254': 'cp1254', 'windows1255': 'cp1255', 'windows1256': 'cp1256', 'windows1257': 'cp1257', 'windows1258': 'cp1258', 'windows936': 'gbk', 'x-x-big5': 'big5' };
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html/src/list_proxy.dart
/// A [List] proxy that you can subclass. library list_proxy; import 'dart:collection'; abstract class ListProxy<E> extends ListBase<E> { /// The inner [List<T>] with the actual storage. final List<E> _list = <E>[]; @override bool remove(Object item) => _list.remove(item); @override int get length => _list.length; // From Iterable @override Iterator<E> get iterator => _list.iterator; // From List @override E operator [](int index) => _list[index]; @override operator []=(int index, E value) { _list[index] = value; } @override set length(int value) { _list.length = value; } @override void add(E value) { _list.add(value); } @override void insert(int index, E item) => _list.insert(index, item); @override void addAll(Iterable<E> collection) { _list.addAll(collection); } @override void insertAll(int index, Iterable<E> iterable) { _list.insertAll(index, iterable); } @override E removeAt(int index) => _list.removeAt(index); @override void removeRange(int start, int length) { _list.removeRange(start, length); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html/src/query_selector.dart
/// Query selector implementation for our DOM. library html.src.query; import 'package:csslib/parser.dart' as css; import 'package:csslib/parser.dart' show TokenKind, Message; import 'package:csslib/visitor.dart'; // the CSSOM import 'package:html/dom.dart'; import 'package:html/src/constants.dart' show isWhitespaceCC; bool matches(Node node, String selector) => SelectorEvaluator().matches(node, _parseSelectorList(selector)); Element querySelector(Node node, String selector) => SelectorEvaluator().querySelector(node, _parseSelectorList(selector)); List<Element> querySelectorAll(Node node, String selector) { var results = <Element>[]; SelectorEvaluator() .querySelectorAll(node, _parseSelectorList(selector), results); return results; } // http://dev.w3.org/csswg/selectors-4/#grouping SelectorGroup _parseSelectorList(String selector) { var errors = <Message>[]; var group = css.parseSelectorGroup(selector, errors: errors); if (group == null || errors.isNotEmpty) { throw FormatException("'$selector' is not a valid selector: $errors"); } return group; } class SelectorEvaluator extends Visitor { /// The current HTML element to match against. Element _element; bool matches(Element element, SelectorGroup selector) { _element = element; return visitSelectorGroup(selector); } Element querySelector(Node root, SelectorGroup selector) { for (var node in root.nodes) { if (node is! Element) continue; if (matches(node, selector)) return node; var result = querySelector(node, selector); if (result != null) return result; } return null; } void querySelectorAll( Node root, SelectorGroup selector, List<Element> results) { for (var node in root.nodes) { if (node is! Element) continue; if (matches(node, selector)) results.add(node); querySelectorAll(node, selector, results); } } @override bool visitSelectorGroup(SelectorGroup group) => group.selectors.any(visitSelector); @override bool visitSelector(Selector selector) { var old = _element; var result = true; // Note: evaluate selectors right-to-left as it's more efficient. int combinator; for (var s in selector.simpleSelectorSequences.reversed) { if (combinator == null) { result = s.simpleSelector.visit(this); } else if (combinator == TokenKind.COMBINATOR_DESCENDANT) { // descendant combinator // http://dev.w3.org/csswg/selectors-4/#descendant-combinators do { _element = _element.parent; } while (_element != null && !s.simpleSelector.visit(this)); if (_element == null) result = false; } else if (combinator == TokenKind.COMBINATOR_TILDE) { // Following-sibling combinator // http://dev.w3.org/csswg/selectors-4/#general-sibling-combinators do { _element = _element.previousElementSibling; } while (_element != null && !s.simpleSelector.visit(this)); if (_element == null) result = false; } if (!result) break; switch (s.combinator) { case TokenKind.COMBINATOR_PLUS: // Next-sibling combinator // http://dev.w3.org/csswg/selectors-4/#adjacent-sibling-combinators _element = _element.previousElementSibling; break; case TokenKind.COMBINATOR_GREATER: // Child combinator // http://dev.w3.org/csswg/selectors-4/#child-combinators _element = _element.parent; break; case TokenKind.COMBINATOR_DESCENDANT: case TokenKind.COMBINATOR_TILDE: // We need to iterate through all siblings or parents. // For now, just remember what the combinator was. combinator = s.combinator; break; case TokenKind.COMBINATOR_NONE: break; default: throw _unsupported(selector); } if (_element == null) { result = false; break; } } _element = old; return result; } UnimplementedError _unimplemented(SimpleSelector selector) => UnimplementedError("'$selector' selector of type " '${selector.runtimeType} is not implemented'); FormatException _unsupported(selector) => FormatException("'$selector' is not a valid selector"); @override bool visitPseudoClassSelector(PseudoClassSelector selector) { switch (selector.name) { // http://dev.w3.org/csswg/selectors-4/#structural-pseudos // http://dev.w3.org/csswg/selectors-4/#the-root-pseudo case 'root': // TODO(jmesserly): fix when we have a .ownerDocument pointer // return _element == _element.ownerDocument.rootElement; return _element.localName == 'html' && _element.parentNode == null; // http://dev.w3.org/csswg/selectors-4/#the-empty-pseudo case 'empty': return _element.nodes .any((n) => !(n is Element || n is Text && n.text.isNotEmpty)); // http://dev.w3.org/csswg/selectors-4/#the-blank-pseudo case 'blank': return _element.nodes.any((n) => !(n is Element || n is Text && n.text.runes.any((r) => !isWhitespaceCC(r)))); // http://dev.w3.org/csswg/selectors-4/#the-first-child-pseudo case 'first-child': return _element.previousElementSibling == null; // http://dev.w3.org/csswg/selectors-4/#the-last-child-pseudo case 'last-child': return _element.nextElementSibling == null; // http://dev.w3.org/csswg/selectors-4/#the-only-child-pseudo case 'only-child': return _element.previousElementSibling == null && _element.nextElementSibling == null; // http://dev.w3.org/csswg/selectors-4/#link case 'link': return _element.attributes['href'] != null; case 'visited': // Always return false since we aren't a browser. This is allowed per: // http://dev.w3.org/csswg/selectors-4/#visited-pseudo return false; } // :before, :after, :first-letter/line can't match DOM elements. if (_isLegacyPsuedoClass(selector.name)) return false; throw _unimplemented(selector); } @override bool visitPseudoElementSelector(PseudoElementSelector selector) { // :before, :after, :first-letter/line can't match DOM elements. if (_isLegacyPsuedoClass(selector.name)) return false; throw _unimplemented(selector); } static bool _isLegacyPsuedoClass(String name) { switch (name) { case 'before': case 'after': case 'first-line': case 'first-letter': return true; default: return false; } } @override bool visitPseudoElementFunctionSelector(PseudoElementFunctionSelector s) => throw _unimplemented(s); @override bool visitPseudoClassFunctionSelector(PseudoClassFunctionSelector selector) { switch (selector.name) { // http://dev.w3.org/csswg/selectors-4/#child-index // http://dev.w3.org/csswg/selectors-4/#the-nth-child-pseudo case 'nth-child': // TODO(jmesserly): support An+B syntax too. var exprs = selector.expression.expressions; if (exprs.length == 1 && exprs[0] is LiteralTerm) { LiteralTerm literal = exprs[0]; var parent = _element.parentNode; return parent != null && literal.value > 0 && parent.nodes.indexOf(_element) == literal.value; } break; // http://dev.w3.org/csswg/selectors-4/#the-lang-pseudo case 'lang': // TODO(jmesserly): shouldn't need to get the raw text here, but csslib // gets confused by the "-" in the expression, such as in "es-AR". var toMatch = selector.expression.span.text; var lang = _getInheritedLanguage(_element); // TODO(jmesserly): implement wildcards in level 4 return lang != null && lang.startsWith(toMatch); } throw _unimplemented(selector); } static String _getInheritedLanguage(Node node) { while (node != null) { var lang = node.attributes['lang']; if (lang != null) return lang; node = node.parent; } return null; } @override bool visitNamespaceSelector(NamespaceSelector selector) { // Match element tag name if (!selector.nameAsSimpleSelector.visit(this)) return false; if (selector.isNamespaceWildcard) return true; if (selector.namespace == '') return _element.namespaceUri == null; throw _unimplemented(selector); } @override bool visitElementSelector(ElementSelector selector) => selector.isWildcard || _element.localName == selector.name.toLowerCase(); @override bool visitIdSelector(IdSelector selector) => _element.id == selector.name; @override bool visitClassSelector(ClassSelector selector) => _element.classes.contains(selector.name); // TODO(jmesserly): negation should support any selectors in level 4, // not just simple selectors. // http://dev.w3.org/csswg/selectors-4/#negation @override bool visitNegationSelector(NegationSelector selector) => !selector.negationArg.visit(this); @override bool visitAttributeSelector(AttributeSelector selector) { // Match name first var value = _element.attributes[selector.name.toLowerCase()]; if (value == null) return false; if (selector.operatorKind == TokenKind.NO_MATCH) return true; var select = '${selector.value}'; switch (selector.operatorKind) { case TokenKind.EQUALS: return value == select; case TokenKind.INCLUDES: return value.split(' ').any((v) => v.isNotEmpty && v == select); case TokenKind.DASH_MATCH: return value.startsWith(select) && (value.length == select.length || value[select.length] == '-'); case TokenKind.PREFIX_MATCH: return value.startsWith(select); case TokenKind.SUFFIX_MATCH: return value.endsWith(select); case TokenKind.SUBSTRING_MATCH: return value.contains(select); default: throw _unsupported(selector); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html/src/utils.dart
import 'constants.dart'; class Pair<F, S> { final F first; final S second; const Pair(this.first, this.second); @override int get hashCode => 37 * first.hashCode + second.hashCode; @override bool operator ==(other) => other.first == first && other.second == second; } bool startsWithAny(String str, List<String> prefixes) => prefixes.any(str.startsWith); // Like the python [:] operator. List<T> slice<T>(List<T> list, int start, [int end]) { end ??= list.length; if (end < 0) end += list.length; // Ensure the indexes are in bounds. if (end < start) end = start; if (end > list.length) end = list.length; return list.sublist(start, end); } bool allWhitespace(String str) { for (var i = 0; i < str.length; i++) { if (!isWhitespaceCC(str.codeUnitAt(i))) return false; } return true; } String padWithZeros(String str, int size) { if (str.length == size) return str; var result = StringBuffer(); size -= str.length; for (var i = 0; i < size; i++) { result.write('0'); } result.write(str); return result.toString(); } // TODO(jmesserly): this implementation is pretty wrong, but I need something // quick until dartbug.com/1694 is fixed. /// Format a string like Python's % string format operator. Right now this only /// supports a [data] dictionary used with %s or %08x. Those were the only /// things needed for [errorMessages]. String formatStr(String format, Map data) { if (data == null) return format; data.forEach((key, value) { var result = StringBuffer(); var search = '%($key)'; int last = 0, match; while ((match = format.indexOf(search, last)) >= 0) { result.write(format.substring(last, match)); match += search.length; var digits = match; while (isDigit(format[digits])) { digits++; } int numberSize; if (digits > match) { numberSize = int.parse(format.substring(match, digits)); match = digits; } switch (format[match]) { case 's': result.write(value); break; case 'd': var number = value.toString(); result.write(padWithZeros(number, numberSize)); break; case 'x': var number = value.toRadixString(16); result.write(padWithZeros(number, numberSize)); break; default: throw UnsupportedError('formatStr does not support format ' 'character ${format[match]}'); } last = match + 1; } result.write(format.substring(last, format.length)); format = result.toString(); }); return format; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/html/src/treebuilder.dart
/// Internals to the tree builders. library treebuilder; import 'dart:collection'; import 'package:html/dom.dart'; import 'package:html/parser.dart' show getElementNameTuple; import 'package:source_span/source_span.dart'; import 'constants.dart'; import 'list_proxy.dart'; import 'token.dart'; import 'utils.dart'; // The scope markers are inserted when entering object elements, // marquees, table cells, and table captions, and are used to prevent formatting // from "leaking" into tables, object elements, and marquees. const Node Marker = null; // TODO(jmesserly): this should extend ListBase<Element>, but my simple attempt // didn't work. class ActiveFormattingElements extends ListProxy<Element> { // Override the "add" method. // TODO(jmesserly): I'd rather not override this; can we do this in the // calling code instead? @override void add(Element node) { var equalCount = 0; if (node != Marker) { for (var element in reversed) { if (element == Marker) { break; } if (_nodesEqual(element, node)) { equalCount += 1; } if (equalCount == 3) { remove(element); break; } } } super.add(node); } } // TODO(jmesserly): this should exist in corelib... bool _mapEquals(Map a, Map b) { if (a.length != b.length) return false; if (a.isEmpty) return true; for (var keyA in a.keys) { var valB = b[keyA]; if (valB == null && !b.containsKey(keyA)) { return false; } if (a[keyA] != valB) { return false; } } return true; } bool _nodesEqual(Element node1, Element node2) { return getElementNameTuple(node1) == getElementNameTuple(node2) && _mapEquals(node1.attributes, node2.attributes); } /// Basic treebuilder implementation. class TreeBuilder { final String defaultNamespace; Document document; final List<Element> openElements = <Element>[]; final activeFormattingElements = ActiveFormattingElements(); Node headPointer; Element formPointer; /// Switch the function used to insert an element from the /// normal one to the misnested table one and back again bool insertFromTable; TreeBuilder(bool namespaceHTMLElements) : defaultNamespace = namespaceHTMLElements ? Namespaces.html : null { reset(); } void reset() { openElements.clear(); activeFormattingElements.clear(); //XXX - rename these to headElement, formElement headPointer = null; formPointer = null; insertFromTable = false; document = Document(); } bool elementInScope(target, {String variant}) { //If we pass a node in we match that. if we pass a string //match any node with that name var exactNode = target is Node; var listElements1 = scopingElements; var listElements2 = const []; var invert = false; if (variant != null) { switch (variant) { case 'button': listElements2 = const [Pair(Namespaces.html, 'button')]; break; case 'list': listElements2 = const [ Pair(Namespaces.html, 'ol'), Pair(Namespaces.html, 'ul') ]; break; case 'table': listElements1 = const [ Pair(Namespaces.html, 'html'), Pair(Namespaces.html, 'table') ]; break; case 'select': listElements1 = const [ Pair(Namespaces.html, 'optgroup'), Pair(Namespaces.html, 'option') ]; invert = true; break; default: throw StateError('We should never reach this point'); } } for (var node in openElements.reversed) { if (!exactNode && node.localName == target || exactNode && node == target) { return true; } else if (invert != (listElements1.contains(getElementNameTuple(node)) || listElements2.contains(getElementNameTuple(node)))) { return false; } } throw StateError('We should never reach this point'); } void reconstructActiveFormattingElements() { // Within this algorithm the order of steps described in the // specification is not quite the same as the order of steps in the // code. It should still do the same though. // Step 1: stop the algorithm when there's nothing to do. if (activeFormattingElements.isEmpty) { return; } // Step 2 and step 3: we start with the last element. So i is -1. var i = activeFormattingElements.length - 1; var entry = activeFormattingElements[i]; if (entry == Marker || openElements.contains(entry)) { return; } // Step 6 while (entry != Marker && !openElements.contains(entry)) { if (i == 0) { //This will be reset to 0 below i = -1; break; } i -= 1; // Step 5: let entry be one earlier in the list. entry = activeFormattingElements[i]; } while (true) { // Step 7 i += 1; // Step 8 entry = activeFormattingElements[i]; // TODO(jmesserly): optimize this. No need to create a token. var cloneToken = StartTagToken(entry.localName, namespace: entry.namespaceUri, data: LinkedHashMap.from(entry.attributes)) ..span = entry.sourceSpan; // Step 9 var element = insertElement(cloneToken); // Step 10 activeFormattingElements[i] = element; // Step 11 if (element == activeFormattingElements.last) { break; } } } void clearActiveFormattingElements() { var entry = activeFormattingElements.removeLast(); while (activeFormattingElements.isNotEmpty && entry != Marker) { entry = activeFormattingElements.removeLast(); } } /// Check if an element exists between the end of the active /// formatting elements and the last marker. If it does, return it, else /// return null. Element elementInActiveFormattingElements(String name) { for (var item in activeFormattingElements.reversed) { // Check for Marker first because if it's a Marker it doesn't have a // name attribute. if (item == Marker) { break; } else if (item.localName == name) { return item; } } return null; } void insertRoot(Token token) { var element = createElement(token); openElements.add(element); document.nodes.add(element); } void insertDoctype(DoctypeToken token) { var doctype = DocumentType(token.name, token.publicId, token.systemId) ..sourceSpan = token.span; document.nodes.add(doctype); } void insertComment(StringToken token, [Node parent]) { parent ??= openElements.last; parent.nodes.add(Comment(token.data)..sourceSpan = token.span); } /// Create an element but don't insert it anywhere Element createElement(StartTagToken token) { var name = token.name; var namespace = token.namespace ?? defaultNamespace; var element = document.createElementNS(namespace, name) ..attributes = token.data ..sourceSpan = token.span; return element; } Element insertElement(StartTagToken token) { if (insertFromTable) return insertElementTable(token); return insertElementNormal(token); } Element insertElementNormal(StartTagToken token) { var name = token.name; var namespace = token.namespace ?? defaultNamespace; var element = document.createElementNS(namespace, name) ..attributes = token.data ..sourceSpan = token.span; openElements.last.nodes.add(element); openElements.add(element); return element; } Element insertElementTable(token) { /// Create an element and insert it into the tree var element = createElement(token); if (!tableInsertModeElements.contains(openElements.last.localName)) { return insertElementNormal(token); } else { // We should be in the InTable mode. This means we want to do // special magic element rearranging var nodePos = getTableMisnestedNodePosition(); if (nodePos[1] == null) { // TODO(jmesserly): I don't think this is reachable. If insertFromTable // is true, there will be a <table> element open, and it always has a // parent pointer. nodePos[0].nodes.add(element); } else { nodePos[0].insertBefore(element, nodePos[1]); } openElements.add(element); } return element; } /// Insert text data. void insertText(String data, FileSpan span) { var parent = openElements.last; if (!insertFromTable || insertFromTable && !tableInsertModeElements.contains(openElements.last.localName)) { _insertText(parent, data, span); } else { // We should be in the InTable mode. This means we want to do // special magic element rearranging var nodePos = getTableMisnestedNodePosition(); _insertText(nodePos[0], data, span, nodePos[1]); } } /// Insert [data] as text in the current node, positioned before the /// start of node [refNode] or to the end of the node's text. static void _insertText(Node parent, String data, FileSpan span, [Element refNode]) { var nodes = parent.nodes; if (refNode == null) { if (nodes.isNotEmpty && nodes.last is Text) { Text last = nodes.last; last.appendData(data); if (span != null) { last.sourceSpan = span.file.span(last.sourceSpan.start.offset, span.end.offset); } } else { nodes.add(Text(data)..sourceSpan = span); } } else { var index = nodes.indexOf(refNode); if (index > 0 && nodes[index - 1] is Text) { Text last = nodes[index - 1]; last.appendData(data); } else { nodes.insert(index, Text(data)..sourceSpan = span); } } } /// Get the foster parent element, and sibling to insert before /// (or null) when inserting a misnested table node List<Node> getTableMisnestedNodePosition() { // The foster parent element is the one which comes before the most // recently opened table element // XXX - this is really inelegant Node lastTable; Node fosterParent; Node insertBefore; for (var elm in openElements.reversed) { if (elm.localName == 'table') { lastTable = elm; break; } } if (lastTable != null) { // XXX - we should really check that this parent is actually a // node here if (lastTable.parentNode != null) { fosterParent = lastTable.parentNode; insertBefore = lastTable; } else { fosterParent = openElements[openElements.indexOf(lastTable) - 1]; } } else { fosterParent = openElements[0]; } return [fosterParent, insertBefore]; } void generateImpliedEndTags([String exclude]) { var name = openElements.last.localName; // XXX td, th and tr are not actually needed if (name != exclude && const ['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'] .contains(name)) { openElements.removeLast(); // XXX This is not entirely what the specification says. We should // investigate it more closely. generateImpliedEndTags(exclude); } } /// Return the final tree. Document getDocument() => document; /// Return the final fragment. DocumentFragment getFragment() { //XXX assert innerHTML var fragment = DocumentFragment(); openElements[0].reparentChildren(fragment); return fragment; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/collection.dart
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. export 'src/algorithms.dart'; export 'src/canonicalized_map.dart'; export 'src/combined_wrappers/combined_iterable.dart'; export 'src/combined_wrappers/combined_list.dart'; export 'src/combined_wrappers/combined_map.dart'; export 'src/comparators.dart'; export 'src/equality.dart'; export 'src/equality_map.dart'; export 'src/equality_set.dart'; export 'src/functions.dart'; export 'src/iterable_zip.dart'; export 'src/priority_queue.dart'; export 'src/queue_list.dart'; export 'src/union_set.dart'; export 'src/union_set_controller.dart'; export 'src/unmodifiable_wrappers.dart'; export 'src/wrappers.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/algorithms.dart
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Import `collection.dart` instead. @Deprecated('Will be removed in collection 2.0.0.') library dart.pkg.collection.algorithms; export 'src/algorithms.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/priority_queue.dart
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Import `collection.dart` instead. @Deprecated('Will be removed in collection 2.0.0.') library dart.pkg.collection.priority_queue; export 'src/priority_queue.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/equality.dart
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Import `collection.dart` instead. @Deprecated('Will be removed in collection 2.0.0.') library dart.pkg.collection.equality; export 'src/equality.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/iterable_zip.dart
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Import `collection.dart` instead. @Deprecated('Will be removed in collection 2.0.0.') library dart.pkg.collection.iterable_zip; export 'src/iterable_zip.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/wrappers.dart
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// Import `collection.dart` instead. @Deprecated('Will be removed in collection 2.0.0.') library dart.pkg.collection.wrappers; export 'src/canonicalized_map.dart'; export 'src/unmodifiable_wrappers.dart'; export 'src/wrappers.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/src/equality_set.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:collection'; import 'equality.dart'; import 'wrappers.dart'; /// A [Set] whose key equality is determined by an [Equality] object. class EqualitySet<E> extends DelegatingSet<E> { /// Creates a set with equality based on [equality]. EqualitySet(Equality<E> equality) : super(LinkedHashSet( equals: equality.equals, hashCode: equality.hash, isValidKey: equality.isValidKey)); /// Creates a set with equality based on [equality] that contains all /// elements in [other]. /// /// If [other] has multiple values that are equivalent according to /// [equality], the first one reached during iteration takes precedence. EqualitySet.from(Equality<E> equality, Iterable<E> other) : super(LinkedHashSet( equals: equality.equals, hashCode: equality.hash, isValidKey: equality.isValidKey)) { addAll(other); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/src/empty_unmodifiable_set.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:collection'; import 'unmodifiable_wrappers.dart'; // Unfortunately, we can't use UnmodifiableSetMixin here, since const classes // can't use mixins. /// An unmodifiable, empty set that can have a const constructor. class EmptyUnmodifiableSet<E> extends IterableBase<E> implements UnmodifiableSetView<E> { static T _throw<T>() { throw UnsupportedError('Cannot modify an unmodifiable Set'); } @override Iterator<E> get iterator => Iterable<E>.empty().iterator; @override int get length => 0; const EmptyUnmodifiableSet(); @override EmptyUnmodifiableSet<T> cast<T>() => EmptyUnmodifiableSet<T>(); @override bool contains(Object element) => false; @override bool containsAll(Iterable<Object> other) => other.isEmpty; @override Iterable<E> followedBy(Iterable<E> other) => Set.from(other); @override E lookup(Object element) => null; @deprecated @override EmptyUnmodifiableSet<T> retype<T>() => EmptyUnmodifiableSet<T>(); @override E singleWhere(bool Function(E) test, {E Function() orElse}) => super.singleWhere(test); @override Iterable<T> whereType<T>() => EmptyUnmodifiableSet<T>(); @override Set<E> toSet() => {}; @override Set<E> union(Set<E> other) => Set.from(other); @override Set<E> intersection(Set<Object> other) => {}; @override Set<E> difference(Set<Object> other) => {}; @override bool add(E value) => _throw(); @override void addAll(Iterable<E> elements) => _throw(); @override void clear() => _throw(); @override bool remove(Object element) => _throw(); @override void removeAll(Iterable<Object> elements) => _throw(); @override void removeWhere(bool Function(E) test) => _throw(); @override void retainWhere(bool Function(E) test) => _throw(); @override void retainAll(Iterable<Object> elements) => _throw(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/src/union_set_controller.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'union_set.dart'; /// A controller that exposes a view of the union of a collection of sets. /// /// This is a convenience class for creating a [UnionSet] whose contents change /// over the lifetime of a class. For example: /// /// ```dart /// class Engine { /// Set<Test> get activeTests => _activeTestsGroup.set; /// final _activeTestsGroup = UnionSetController<Test>(); /// /// void addSuite(Suite suite) { /// _activeTestsGroup.add(suite.tests); /// _runSuite(suite); /// _activeTestsGroup.remove(suite.tests); /// } /// } /// ``` class UnionSetController<E> { /// The [UnionSet] that provides a view of the union of sets in [this]. UnionSet<E> get set => _set; UnionSet<E> _set; /// The sets whose union is exposed through [set]. final _sets = <Set<E>>{}; /// Creates a set of sets that provides a view of the union of those sets. /// /// If [disjoint] is `true`, this assumes that all component sets are /// disjoint—that is, that they contain no elements in common. This makes /// many operations including [length] more efficient. UnionSetController({bool disjoint = false}) { _set = UnionSet<E>(_sets, disjoint: disjoint); } /// Adds the contents of [component] to [set]. /// /// If the contents of [component] change over time, [set] will change /// accordingly. void add(Set<E> component) { _sets.add(component); } /// Removes the contents of [component] to [set]. /// /// If another set in [this] has overlapping elements with [component], those /// elements will remain in [set]. bool remove(Set<E> component) => _sets.remove(component); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/src/functions.dart
// Copyright (c) 2016, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:collection'; import 'dart:math' as math; import 'utils.dart'; /// Creates a new map from [map] with new keys and values. /// /// The return values of [key] are used as the keys and the return values of /// [value] are used as the values for the new map. @Deprecated('Use Map.map or a for loop in a Map literal.') Map<K2, V2> mapMap<K1, V1, K2, V2>(Map<K1, V1> map, {K2 Function(K1, V1) key, V2 Function(K1, V1) value}) { key ??= (mapKey, _) => mapKey as K2; value ??= (_, mapValue) => mapValue as V2; var result = <K2, V2>{}; map.forEach((mapKey, mapValue) { result[key(mapKey, mapValue)] = value(mapKey, mapValue); }); return result; } /// Returns a new map with all key/value pairs in both [map1] and [map2]. /// /// If there are keys that occur in both maps, the [value] function is used to /// select the value that goes into the resulting map based on the two original /// values. If [value] is omitted, the value from [map2] is used. Map<K, V> mergeMaps<K, V>(Map<K, V> map1, Map<K, V> map2, {V Function(V, V) value}) { var result = Map<K, V>.from(map1); if (value == null) return result..addAll(map2); map2.forEach((key, mapValue) { result[key] = result.containsKey(key) ? value(result[key], mapValue) : mapValue; }); return result; } /// Groups the elements in [values] by the value returned by [key]. /// /// Returns a map from keys computed by [key] to a list of all values for which /// [key] returns that key. The values appear in the list in the same relative /// order as in [values]. Map<T, List<S>> groupBy<S, T>(Iterable<S> values, T Function(S) key) { var map = <T, List<S>>{}; for (var element in values) { (map[key(element)] ??= []).add(element); } return map; } /// Returns the element of [values] for which [orderBy] returns the minimum /// value. /// /// The values returned by [orderBy] are compared using the [compare] function. /// If [compare] is omitted, values must implement [Comparable<T>] and they are /// compared using their [Comparable.compareTo]. S minBy<S, T>(Iterable<S> values, T Function(S) orderBy, {int Function(T, T) compare}) { compare ??= defaultCompare<T>(); S minValue; T minOrderBy; for (var element in values) { var elementOrderBy = orderBy(element); if (minOrderBy == null || compare(elementOrderBy, minOrderBy) < 0) { minValue = element; minOrderBy = elementOrderBy; } } return minValue; } /// Returns the element of [values] for which [orderBy] returns the maximum /// value. /// /// The values returned by [orderBy] are compared using the [compare] function. /// If [compare] is omitted, values must implement [Comparable<T>] and they are /// compared using their [Comparable.compareTo]. S maxBy<S, T>(Iterable<S> values, T Function(S) orderBy, {int Function(T, T) compare}) { compare ??= defaultCompare<T>(); S maxValue; T maxOrderBy; for (var element in values) { var elementOrderBy = orderBy(element); if (maxOrderBy == null || compare(elementOrderBy, maxOrderBy) > 0) { maxValue = element; maxOrderBy = elementOrderBy; } } return maxValue; } /// Returns the [transitive closure][] of [graph]. /// /// [transitive closure]: https://en.wikipedia.org/wiki/Transitive_closure /// /// Interprets [graph] as a directed graph with a vertex for each key and edges /// from each key to the values that the key maps to. /// /// Assumes that every vertex in the graph has a key to represent it, even if /// that vertex has no outgoing edges. This isn't checked, but if it's not /// satisfied, the function may crash or provide unexpected output. For example, /// `{"a": ["b"]}` is not valid, but `{"a": ["b"], "b": []}` is. Map<T, Set<T>> transitiveClosure<T>(Map<T, Iterable<T>> graph) { // This uses [Warshall's algorithm][], modified not to add a vertex from each // node to itself. // // [Warshall's algorithm]: https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm#Applications_and_generalizations. var result = <T, Set<T>>{}; graph.forEach((vertex, edges) { result[vertex] = Set<T>.from(edges); }); // Lists are faster to iterate than maps, so we create a list since we're // iterating repeatedly. var keys = graph.keys.toList(); for (var vertex1 in keys) { for (var vertex2 in keys) { for (var vertex3 in keys) { if (result[vertex2].contains(vertex1) && result[vertex1].contains(vertex3)) { result[vertex2].add(vertex3); } } } } return result; } /// Returns the [strongly connected components][] of [graph], in topological /// order. /// /// [strongly connected components]: https://en.wikipedia.org/wiki/Strongly_connected_component /// /// Interprets [graph] as a directed graph with a vertex for each key and edges /// from each key to the values that the key maps to. /// /// Assumes that every vertex in the graph has a key to represent it, even if /// that vertex has no outgoing edges. This isn't checked, but if it's not /// satisfied, the function may crash or provide unexpected output. For example, /// `{"a": ["b"]}` is not valid, but `{"a": ["b"], "b": []}` is. List<Set<T>> stronglyConnectedComponents<T>(Map<T, Iterable<T>> graph) { // This uses [Tarjan's algorithm][]. // // [Tarjan's algorithm]: https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm var index = 0; var stack = <T>[]; var result = <Set<T>>[]; // The order of these doesn't matter, so we use un-linked implementations to // avoid unnecessary overhead. var indices = HashMap<T, int>(); var lowLinks = HashMap<T, int>(); var onStack = HashSet<T>(); void strongConnect(T vertex) { indices[vertex] = index; lowLinks[vertex] = index; index++; stack.add(vertex); onStack.add(vertex); for (var successor in graph[vertex]) { if (!indices.containsKey(successor)) { strongConnect(successor); lowLinks[vertex] = math.min(lowLinks[vertex], lowLinks[successor]); } else if (onStack.contains(successor)) { lowLinks[vertex] = math.min(lowLinks[vertex], lowLinks[successor]); } } if (lowLinks[vertex] == indices[vertex]) { var component = <T>{}; T neighbor; do { neighbor = stack.removeLast(); onStack.remove(neighbor); component.add(neighbor); } while (neighbor != vertex); result.add(component); } } for (var vertex in graph.keys) { if (!indices.containsKey(vertex)) strongConnect(vertex); } // Tarjan's algorithm produces a reverse-topological sort, so we reverse it to // get a normal topological sort. return result.reversed.toList(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/src/comparators.dart
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. // Character constants. const int _zero = 0x30; const int _upperCaseA = 0x41; const int _upperCaseZ = 0x5a; const int _lowerCaseA = 0x61; const int _lowerCaseZ = 0x7a; const int _asciiCaseBit = 0x20; /// Checks if strings [a] and [b] differ only on the case of ASCII letters. /// /// Strings are equal if they have the same length, and the characters at /// each index are the same, or they are ASCII letters where one is upper-case /// and the other is the lower-case version of the same letter. /// /// The comparison does not ignore the case of non-ASCII letters, so /// an upper-case ae-ligature (Æ) is different from /// a lower case ae-ligature (æ). /// /// Ignoring non-ASCII letters is not generally a good idea, but it makes sense /// for situations where the strings are known to be ASCII. Examples could /// be Dart identifiers, base-64 or hex encoded strings, GUIDs or similar /// strings with a known structure. bool equalsIgnoreAsciiCase(String a, String b) { if (a.length != b.length) return false; for (var i = 0; i < a.length; i++) { var aChar = a.codeUnitAt(i); var bChar = b.codeUnitAt(i); if (aChar == bChar) continue; // Quick-check for whether this may be different cases of the same letter. if (aChar ^ bChar != _asciiCaseBit) return false; // If it's possible, then check if either character is actually an ASCII // letter. var aCharLowerCase = aChar | _asciiCaseBit; if (_lowerCaseA <= aCharLowerCase && aCharLowerCase <= _lowerCaseZ) { continue; } return false; } return true; } /// Hash code for a string which is compatible with [equalsIgnoreAsciiCase]. /// /// The hash code is unaffected by changing the case of ASCII letters, but /// the case of non-ASCII letters do affect the result. int hashIgnoreAsciiCase(String string) { // Jenkins hash code ( http://en.wikipedia.org/wiki/Jenkins_hash_function). // adapted to smi values. // Same hash used by dart2js for strings, modified to ignore ASCII letter // case. var hash = 0; for (var i = 0; i < string.length; i++) { var char = string.codeUnitAt(i); // Convert lower-case ASCII letters to upper case.upper // This ensures that strings that differ only in case will have the // same hash code. if (_lowerCaseA <= char && char <= _lowerCaseZ) char -= _asciiCaseBit; hash = 0x1fffffff & (hash + char); hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10)); hash >>= 6; } hash = 0x1fffffff & (hash + ((0x03ffffff & hash) << 3)); hash >>= 11; return 0x1fffffff & (hash + ((0x00003fff & hash) << 15)); } /// Compares [a] and [b] lexically, converting ASCII letters to upper case. /// /// Comparison treats all lower-case ASCII letters as upper-case letters, /// but does no case conversion for non-ASCII letters. /// /// If two strings differ only on the case of ASCII letters, the one with the /// capital letter at the first difference will compare as less than the other /// string. This tie-breaking ensures that the comparison is a total ordering /// on strings and is compatible with equality. /// /// Ignoring non-ASCII letters is not generally a good idea, but it makes sense /// for situations where the strings are known to be ASCII. Examples could /// be Dart identifiers, base-64 or hex encoded strings, GUIDs or similar /// strings with a known structure. int compareAsciiUpperCase(String a, String b) { var defaultResult = 0; // Returned if no difference found. for (var i = 0; i < a.length; i++) { if (i >= b.length) return 1; var aChar = a.codeUnitAt(i); var bChar = b.codeUnitAt(i); if (aChar == bChar) continue; // Upper-case if letters. var aUpperCase = aChar; var bUpperCase = bChar; if (_lowerCaseA <= aChar && aChar <= _lowerCaseZ) { aUpperCase -= _asciiCaseBit; } if (_lowerCaseA <= bChar && bChar <= _lowerCaseZ) { bUpperCase -= _asciiCaseBit; } if (aUpperCase != bUpperCase) return (aUpperCase - bUpperCase).sign; if (defaultResult == 0) defaultResult = (aChar - bChar); } if (b.length > a.length) return -1; return defaultResult.sign; } /// Compares [a] and [b] lexically, converting ASCII letters to lower case. /// /// Comparison treats all upper-case ASCII letters as lower-case letters, /// but does no case conversion for non-ASCII letters. /// /// If two strings differ only on the case of ASCII letters, the one with the /// capital letter at the first difference will compare as less than the other /// string. This tie-breaking ensures that the comparison is a total ordering /// on strings. /// /// Ignoring non-ASCII letters is not generally a good idea, but it makes sense /// for situations where the strings are known to be ASCII. Examples could /// be Dart identifiers, base-64 or hex encoded strings, GUIDs or similar /// strings with a known structure. int compareAsciiLowerCase(String a, String b) { var defaultResult = 0; for (var i = 0; i < a.length; i++) { if (i >= b.length) return 1; var aChar = a.codeUnitAt(i); var bChar = b.codeUnitAt(i); if (aChar == bChar) continue; var aLowerCase = aChar; var bLowerCase = bChar; // Upper case if ASCII letters. if (_upperCaseA <= bChar && bChar <= _upperCaseZ) { bLowerCase += _asciiCaseBit; } if (_upperCaseA <= aChar && aChar <= _upperCaseZ) { aLowerCase += _asciiCaseBit; } if (aLowerCase != bLowerCase) return (aLowerCase - bLowerCase).sign; if (defaultResult == 0) defaultResult = aChar - bChar; } if (b.length > a.length) return -1; return defaultResult.sign; } /// Compares strings [a] and [b] according to [natural sort ordering][]. /// /// A natural sort ordering is a lexical ordering where embedded /// numerals (digit sequences) are treated as a single unit and ordered by /// numerical value. /// This means that `"a10b"` will be ordered after `"a7b"` in natural /// ordering, where lexical ordering would put the `1` before the `7`, ignoring /// that the `1` is part of a larger number. /// /// Example: /// The following strings are in the order they would be sorted by using this /// comparison function: /// /// "a", "a0", "a0b", "a1", "a01", "a9", "a10", "a100", "a100b", "aa" /// /// [natural sort ordering]: https://en.wikipedia.org/wiki/Natural_sort_order int compareNatural(String a, String b) { for (var i = 0; i < a.length; i++) { if (i >= b.length) return 1; var aChar = a.codeUnitAt(i); var bChar = b.codeUnitAt(i); if (aChar != bChar) { return _compareNaturally(a, b, i, aChar, bChar); } } if (b.length > a.length) return -1; return 0; } /// Compares strings [a] and [b] according to lower-case /// [natural sort ordering][]. /// /// ASCII letters are converted to lower case before being compared, like /// for [compareAsciiLowerCase], then the result is compared like for /// [compareNatural]. /// /// If two strings differ only on the case of ASCII letters, the one with the /// capital letter at the first difference will compare as less than the other /// string. This tie-breaking ensures that the comparison is a total ordering /// on strings. /// /// [natural sort ordering]: https://en.wikipedia.org/wiki/Natural_sort_order int compareAsciiLowerCaseNatural(String a, String b) { var defaultResult = 0; // Returned if no difference found. for (var i = 0; i < a.length; i++) { if (i >= b.length) return 1; var aChar = a.codeUnitAt(i); var bChar = b.codeUnitAt(i); if (aChar == bChar) continue; var aLowerCase = aChar; var bLowerCase = bChar; if (_upperCaseA <= aChar && aChar <= _upperCaseZ) { aLowerCase += _asciiCaseBit; } if (_upperCaseA <= bChar && bChar <= _upperCaseZ) { bLowerCase += _asciiCaseBit; } if (aLowerCase != bLowerCase) { return _compareNaturally(a, b, i, aLowerCase, bLowerCase); } if (defaultResult == 0) defaultResult = aChar - bChar; } if (b.length > a.length) return -1; return defaultResult.sign; } /// Compares strings [a] and [b] according to upper-case /// [natural sort ordering][]. /// /// ASCII letters are converted to upper case before being compared, like /// for [compareAsciiUpperCase], then the result is compared like for /// [compareNatural]. /// /// If two strings differ only on the case of ASCII letters, the one with the /// capital letter at the first difference will compare as less than the other /// string. This tie-breaking ensures that the comparison is a total ordering /// on strings /// /// [natural sort ordering]: https://en.wikipedia.org/wiki/Natural_sort_order int compareAsciiUpperCaseNatural(String a, String b) { var defaultResult = 0; for (var i = 0; i < a.length; i++) { if (i >= b.length) return 1; var aChar = a.codeUnitAt(i); var bChar = b.codeUnitAt(i); if (aChar == bChar) continue; var aUpperCase = aChar; var bUpperCase = bChar; if (_lowerCaseA <= aChar && aChar <= _lowerCaseZ) { aUpperCase -= _asciiCaseBit; } if (_lowerCaseA <= bChar && bChar <= _lowerCaseZ) { bUpperCase -= _asciiCaseBit; } if (aUpperCase != bUpperCase) { return _compareNaturally(a, b, i, aUpperCase, bUpperCase); } if (defaultResult == 0) defaultResult = aChar - bChar; } if (b.length > a.length) return -1; return defaultResult.sign; } /// Check for numbers overlapping the current mismatched characters. /// /// If both [aChar] and [bChar] are digits, use numerical comparison. /// Check if the previous characters is a non-zero number, and if not, /// skip - but count - leading zeros before comparing numbers. /// /// If one is a digit and the other isn't, check if the previous character /// is a digit, and if so, the the one with the digit is the greater number. /// /// Otherwise just returns the difference between [aChar] and [bChar]. int _compareNaturally(String a, String b, int index, int aChar, int bChar) { assert(aChar != bChar); var aIsDigit = _isDigit(aChar); var bIsDigit = _isDigit(bChar); if (aIsDigit) { if (bIsDigit) { return _compareNumerically(a, b, aChar, bChar, index); } else if (index > 0 && _isDigit(a.codeUnitAt(index - 1))) { // aChar is the continuation of a longer number. return 1; } } else if (bIsDigit && index > 0 && _isDigit(b.codeUnitAt(index - 1))) { // bChar is the continuation of a longer number. return -1; } // Characters are both non-digits, or not continuation of earlier number. return (aChar - bChar).sign; } /// Compare numbers overlapping [aChar] and [bChar] numerically. /// /// If the numbers have the same numerical value, but one has more leading /// zeros, the longer number is considered greater than the shorter one. /// /// This ensures a total ordering on strings compatible with equality. int _compareNumerically(String a, String b, int aChar, int bChar, int index) { // Both are digits. Find the first significant different digit, then find // the length of the numbers. if (_isNonZeroNumberSuffix(a, index)) { // Part of a longer number, differs at this index, just count the length. var result = _compareDigitCount(a, b, index, index); if (result != 0) return result; // If same length, the current character is the most significant differing // digit. return (aChar - bChar).sign; } // Not part of larger (non-zero) number, so skip leading zeros before // comparing numbers. var aIndex = index; var bIndex = index; if (aChar == _zero) { do { aIndex++; if (aIndex == a.length) return -1; // number in a is zero, b is not. aChar = a.codeUnitAt(aIndex); } while (aChar == _zero); if (!_isDigit(aChar)) return -1; } else if (bChar == _zero) { do { bIndex++; if (bIndex == b.length) return 1; // number in b is zero, a is not. bChar = b.codeUnitAt(bIndex); } while (bChar == _zero); if (!_isDigit(bChar)) return 1; } if (aChar != bChar) { var result = _compareDigitCount(a, b, aIndex, bIndex); if (result != 0) return result; return (aChar - bChar).sign; } // Same leading digit, one had more leading zeros. // Compare digits until reaching a difference. while (true) { var aIsDigit = false; var bIsDigit = false; aChar = 0; bChar = 0; if (++aIndex < a.length) { aChar = a.codeUnitAt(aIndex); aIsDigit = _isDigit(aChar); } if (++bIndex < b.length) { bChar = b.codeUnitAt(bIndex); bIsDigit = _isDigit(bChar); } if (aIsDigit) { if (bIsDigit) { if (aChar == bChar) continue; // First different digit found. break; } // bChar is non-digit, so a has longer number. return 1; } else if (bIsDigit) { return -1; // b has longer number. } else { // Neither is digit, so numbers had same numerical value. // Fall back on number of leading zeros // (reflected by difference in indices). return (aIndex - bIndex).sign; } } // At first differing digits. var result = _compareDigitCount(a, b, aIndex, bIndex); if (result != 0) return result; return (aChar - bChar).sign; } /// Checks which of [a] and [b] has the longest sequence of digits. /// /// Starts counting from `i + 1` and `j + 1` (assumes that `a[i]` and `b[j]` are /// both already known to be digits). int _compareDigitCount(String a, String b, int i, int j) { while (++i < a.length) { var aIsDigit = _isDigit(a.codeUnitAt(i)); if (++j == b.length) return aIsDigit ? 1 : 0; var bIsDigit = _isDigit(b.codeUnitAt(j)); if (aIsDigit) { if (bIsDigit) continue; return 1; } else if (bIsDigit) { return -1; } else { return 0; } } if (++j < b.length && _isDigit(b.codeUnitAt(j))) { return -1; } return 0; } bool _isDigit(int charCode) => (charCode ^ _zero) <= 9; /// Check if the digit at [index] is continuing a non-zero number. /// /// If there is no non-zero digits before, then leading zeros at [index] /// are also ignored when comparing numerically. If there is a non-zero digit /// before, then zeros at [index] are significant. bool _isNonZeroNumberSuffix(String string, int index) { while (--index >= 0) { var char = string.codeUnitAt(index); if (char != _zero) return _isDigit(char); } return false; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/src/algorithms.dart
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:math' as math; import 'utils.dart'; /// Returns a position of the [value] in [sortedList], if it is there. /// /// If the list isn't sorted according to the [compare] function, the result /// is unpredictable. /// /// If [compare] is omitted, this defaults to calling [Comparable.compareTo] on /// the objects. If any object is not [Comparable], this throws a [TypeError] /// (`CastError` on some SDK versions). /// /// Returns -1 if [value] is not in the list by default. int binarySearch<T>(List<T> sortedList, T value, {int Function(T, T) compare}) { compare ??= defaultCompare<T>(); var min = 0; var max = sortedList.length; while (min < max) { var mid = min + ((max - min) >> 1); var element = sortedList[mid]; var comp = compare(element, value); if (comp == 0) return mid; if (comp < 0) { min = mid + 1; } else { max = mid; } } return -1; } /// Returns the first position in [sortedList] that does not compare less than /// [value]. /// /// If the list isn't sorted according to the [compare] function, the result /// is unpredictable. /// /// If [compare] is omitted, this defaults to calling [Comparable.compareTo] on /// the objects. If any object is not [Comparable], this throws a [TypeError] /// (`CastError` on some SDK versions). /// /// Returns [sortedList.length] if all the items in [sortedList] compare less /// than [value]. int lowerBound<T>(List<T> sortedList, T value, {int Function(T, T) compare}) { compare ??= defaultCompare<T>(); var min = 0; var max = sortedList.length; while (min < max) { var mid = min + ((max - min) >> 1); var element = sortedList[mid]; var comp = compare(element, value); if (comp < 0) { min = mid + 1; } else { max = mid; } } return min; } /// Shuffles a list randomly. /// /// A sub-range of a list can be shuffled by providing [start] and [end]. void shuffle(List list, [int start = 0, int end]) { var random = math.Random(); end ??= list.length; var length = end - start; while (length > 1) { var pos = random.nextInt(length); length--; var tmp1 = list[start + pos]; list[start + pos] = list[start + length]; list[start + length] = tmp1; } } /// Reverses a list, or a part of a list, in-place. void reverse(List list, [int start = 0, int end]) { end ??= list.length; _reverse(list, start, end); } /// Internal helper function that assumes valid arguments. void _reverse(List list, int start, int end) { for (var i = start, j = end - 1; i < j; i++, j--) { var tmp = list[i]; list[i] = list[j]; list[j] = tmp; } } /// Sort a list between [start] (inclusive) and [end] (exclusive) using /// insertion sort. /// /// If [compare] is omitted, this defaults to calling [Comparable.compareTo] on /// the objects. If any object is not [Comparable], this throws a [TypeError] /// (`CastError` on some SDK versions). /// /// Insertion sort is a simple sorting algorithm. For `n` elements it does on /// the order of `n * log(n)` comparisons but up to `n` squared moves. The /// sorting is performed in-place, without using extra memory. /// /// For short lists the many moves have less impact than the simple algorithm, /// and it is often the favored sorting algorithm for short lists. /// /// This insertion sort is stable: Equal elements end up in the same order /// as they started in. void insertionSort<T>(List<T> list, {int Function(T, T) compare, int start = 0, int end}) { // If the same method could have both positional and named optional // parameters, this should be (list, [start, end], {compare}). compare ??= defaultCompare<T>(); end ??= list.length; for (var pos = start + 1; pos < end; pos++) { var min = start; var max = pos; var element = list[pos]; while (min < max) { var mid = min + ((max - min) >> 1); var comparison = compare(element, list[mid]); if (comparison < 0) { max = mid; } else { min = mid + 1; } } list.setRange(min + 1, pos + 1, list, min); list[min] = element; } } /// Limit below which merge sort defaults to insertion sort. const int _MERGE_SORT_LIMIT = 32; /// Sorts a list between [start] (inclusive) and [end] (exclusive) using the /// merge sort algorithm. /// /// If [compare] is omitted, this defaults to calling [Comparable.compareTo] on /// the objects. If any object is not [Comparable], this throws a [TypeError] /// (`CastError` on some SDK versions). /// /// Merge-sorting works by splitting the job into two parts, sorting each /// recursively, and then merging the two sorted parts. /// /// This takes on the order of `n * log(n)` comparisons and moves to sort /// `n` elements, but requires extra space of about the same size as the list /// being sorted. /// /// This merge sort is stable: Equal elements end up in the same order /// as they started in. void mergeSort<T>(List<T> list, {int start = 0, int end, int Function(T, T) compare}) { end ??= list.length; compare ??= defaultCompare<T>(); var length = end - start; if (length < 2) return; if (length < _MERGE_SORT_LIMIT) { insertionSort(list, compare: compare, start: start, end: end); return; } // Special case the first split instead of directly calling // _mergeSort, because the _mergeSort requires its target to // be different from its source, and it requires extra space // of the same size as the list to sort. // This split allows us to have only half as much extra space, // and it ends up in the original place. var middle = start + ((end - start) >> 1); var firstLength = middle - start; var secondLength = end - middle; // secondLength is always the same as firstLength, or one greater. var scratchSpace = List<T>(secondLength); _mergeSort(list, compare, middle, end, scratchSpace, 0); var firstTarget = end - firstLength; _mergeSort(list, compare, start, middle, list, firstTarget); _merge(compare, list, firstTarget, end, scratchSpace, 0, secondLength, list, start); } /// Performs an insertion sort into a potentially different list than the /// one containing the original values. /// /// It will work in-place as well. void _movingInsertionSort<T>(List<T> list, int Function(T, T) compare, int start, int end, List<T> target, int targetOffset) { var length = end - start; if (length == 0) return; target[targetOffset] = list[start]; for (var i = 1; i < length; i++) { var element = list[start + i]; var min = targetOffset; var max = targetOffset + i; while (min < max) { var mid = min + ((max - min) >> 1); if (compare(element, target[mid]) < 0) { max = mid; } else { min = mid + 1; } } target.setRange(min + 1, targetOffset + i + 1, target, min); target[min] = element; } } /// Sorts [list] from [start] to [end] into [target] at [targetOffset]. /// /// The `target` list must be able to contain the range from `start` to `end` /// after `targetOffset`. /// /// Allows target to be the same list as [list], as long as it's not /// overlapping the `start..end` range. void _mergeSort<T>(List<T> list, int Function(T, T) compare, int start, int end, List<T> target, int targetOffset) { var length = end - start; if (length < _MERGE_SORT_LIMIT) { _movingInsertionSort(list, compare, start, end, target, targetOffset); return; } var middle = start + (length >> 1); var firstLength = middle - start; var secondLength = end - middle; // Here secondLength >= firstLength (differs by at most one). var targetMiddle = targetOffset + firstLength; // Sort the second half into the end of the target area. _mergeSort(list, compare, middle, end, target, targetMiddle); // Sort the first half into the end of the source area. _mergeSort(list, compare, start, middle, list, middle); // Merge the two parts into the target area. _merge(compare, list, middle, middle + firstLength, target, targetMiddle, targetMiddle + secondLength, target, targetOffset); } /// Merges two lists into a target list. /// /// One of the input lists may be positioned at the end of the target /// list. /// /// For equal object, elements from [firstList] are always preferred. /// This allows the merge to be stable if the first list contains elements /// that started out earlier than the ones in [secondList] void _merge<T>( int Function(T, T) compare, List<T> firstList, int firstStart, int firstEnd, List<T> secondList, int secondStart, int secondEnd, List<T> target, int targetOffset) { // No empty lists reaches here. assert(firstStart < firstEnd); assert(secondStart < secondEnd); var cursor1 = firstStart; var cursor2 = secondStart; var firstElement = firstList[cursor1++]; var secondElement = secondList[cursor2++]; while (true) { if (compare(firstElement, secondElement) <= 0) { target[targetOffset++] = firstElement; if (cursor1 == firstEnd) break; // Flushing second list after loop. firstElement = firstList[cursor1++]; } else { target[targetOffset++] = secondElement; if (cursor2 != secondEnd) { secondElement = secondList[cursor2++]; continue; } // Second list empties first. Flushing first list here. target[targetOffset++] = firstElement; target.setRange(targetOffset, targetOffset + (firstEnd - cursor1), firstList, cursor1); return; } } // First list empties first. Reached by break above. target[targetOffset++] = secondElement; target.setRange( targetOffset, targetOffset + (secondEnd - cursor2), secondList, cursor2); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/src/priority_queue.dart
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:collection'; import 'utils.dart'; /// A priority queue is a priority based work-list of elements. /// /// The queue allows adding elements, and removing them again in priority order. abstract class PriorityQueue<E> { /// Creates an empty [PriorityQueue]. /// /// The created [PriorityQueue] is a plain [HeapPriorityQueue]. /// /// The [comparison] is a [Comparator] used to compare the priority of /// elements. An element that compares as less than another element has /// a higher priority. /// /// If [comparison] is omitted, it defaults to [Comparable.compare]. If this /// is the case, `E` must implement [Comparable], and this is checked at /// runtime for every comparison. factory PriorityQueue([int Function(E, E) comparison]) = HeapPriorityQueue<E>; /// Number of elements in the queue. int get length; /// Whether the queue is empty. bool get isEmpty; /// Whether the queue has any elements. bool get isNotEmpty; /// Checks if [object] is in the queue. /// /// Returns true if the element is found. bool contains(E object); /// Adds element to the queue. /// /// The element will become the next to be removed by [removeFirst] /// when all elements with higher priority have been removed. void add(E element); /// Adds all [elements] to the queue. void addAll(Iterable<E> elements); /// Returns the next element that will be returned by [removeFirst]. /// /// The element is not removed from the queue. /// /// The queue must not be empty when this method is called. E get first; /// Removes and returns the element with the highest priority. /// /// Repeatedly calling this method, without adding element in between, /// is guaranteed to return elements in non-decreasing order as, specified by /// [comparison]. /// /// The queue must not be empty when this method is called. E removeFirst(); /// Removes an element that compares equal to [element] in the queue. /// /// Returns true if an element is found and removed, /// and false if no equal element is found. bool remove(E element); /// Removes all the elements from this queue and returns them. /// /// The returned iterable has no specified order. Iterable<E> removeAll(); /// Removes all the elements from this queue. void clear(); /// Returns a list of the elements of this queue in priority order. /// /// The queue is not modified. /// /// The order is the order that the elements would be in if they were /// removed from this queue using [removeFirst]. List<E> toList(); /// Return a comparator based set using the comparator of this queue. /// /// The queue is not modified. /// /// The returned [Set] is currently a [SplayTreeSet], /// but this may change as other ordered sets are implemented. /// /// The set contains all the elements of this queue. /// If an element occurs more than once in the queue, /// the set will contain it only once. Set<E> toSet(); } /// Heap based priority queue. /// /// The elements are kept in a heap structure, /// where the element with the highest priority is immediately accessible, /// and modifying a single element takes /// logarithmic time in the number of elements on average. /// /// * The [add] and [removeFirst] operations take amortized logarithmic time, /// O(log(n)), but may occasionally take linear time when growing the capacity /// of the heap. /// * The [addAll] operation works as doing repeated [add] operations. /// * The [first] getter takes constant time, O(1). /// * The [clear] and [removeAll] methods also take constant time, O(1). /// * The [contains] and [remove] operations may need to search the entire /// queue for the elements, taking O(n) time. /// * The [toList] operation effectively sorts the elements, taking O(n*log(n)) /// time. /// * The [toSet] operation effectively adds each element to the new set, taking /// an expected O(n*log(n)) time. class HeapPriorityQueue<E> implements PriorityQueue<E> { /// Initial capacity of a queue when created, or when added to after a /// [clear]. /// /// Number can be any positive value. Picking a size that gives a whole /// number of "tree levels" in the heap is only done for aesthetic reasons. static const int _INITIAL_CAPACITY = 7; /// The comparison being used to compare the priority of elements. final Comparator<E> comparison; /// List implementation of a heap. List<E> _queue = List<E>(_INITIAL_CAPACITY); /// Number of elements in queue. /// /// The heap is implemented in the first [_length] entries of [_queue]. int _length = 0; /// Create a new priority queue. /// /// The [comparison] is a [Comparator] used to compare the priority of /// elements. An element that compares as less than another element has /// a higher priority. /// /// If [comparison] is omitted, it defaults to [Comparable.compare]. If this /// is the case, `E` must implement [Comparable], and this is checked at /// runtime for every comparison. HeapPriorityQueue([int Function(E, E) comparison]) : comparison = comparison ?? defaultCompare<E>(); @override void add(E element) { _add(element); } @override void addAll(Iterable<E> elements) { for (var element in elements) { _add(element); } } @override void clear() { _queue = const []; _length = 0; } @override bool contains(E object) { return _locate(object) >= 0; } @override E get first { if (_length == 0) throw StateError('No such element'); return _queue[0]; } @override bool get isEmpty => _length == 0; @override bool get isNotEmpty => _length != 0; @override int get length => _length; @override bool remove(E element) { var index = _locate(element); if (index < 0) return false; var last = _removeLast(); if (index < _length) { var comp = comparison(last, element); if (comp <= 0) { _bubbleUp(last, index); } else { _bubbleDown(last, index); } } return true; } @override Iterable<E> removeAll() { var result = _queue; var length = _length; _queue = const []; _length = 0; return result.take(length); } @override E removeFirst() { if (_length == 0) throw StateError('No such element'); var result = _queue[0]; var last = _removeLast(); if (_length > 0) { _bubbleDown(last, 0); } return result; } @override List<E> toList() { var list = <E>[] ..length = _length ..setRange(0, _length, _queue) ..sort(comparison); return list; } @override Set<E> toSet() { Set<E> set = SplayTreeSet<E>(comparison); for (var i = 0; i < _length; i++) { set.add(_queue[i]); } return set; } /// Returns some representation of the queue. /// /// The format isn't significant, and may change in the future. @override String toString() { return _queue.take(_length).toString(); } /// Add element to the queue. /// /// Grows the capacity if the backing list is full. void _add(E element) { if (_length == _queue.length) _grow(); _bubbleUp(element, _length++); } /// Find the index of an object in the heap. /// /// Returns -1 if the object is not found. int _locate(E object) { if (_length == 0) return -1; // Count positions from one instead of zero. This gives the numbers // some nice properties. For example, all right children are odd, // their left sibling is even, and the parent is found by shifting // right by one. // Valid range for position is [1.._length], inclusive. var position = 1; // Pre-order depth first search, omit child nodes if the current // node has lower priority than [object], because all nodes lower // in the heap will also have lower priority. do { var index = position - 1; var element = _queue[index]; var comp = comparison(element, object); if (comp == 0) return index; if (comp < 0) { // Element may be in subtree. // Continue with the left child, if it is there. var leftChildPosition = position * 2; if (leftChildPosition <= _length) { position = leftChildPosition; continue; } } // Find the next right sibling or right ancestor sibling. do { while (position.isOdd) { // While position is a right child, go to the parent. position >>= 1; } // Then go to the right sibling of the left-child. position += 1; } while (position > _length); // Happens if last element is a left child. } while (position != 1); // At root again. Happens for right-most element. return -1; } E _removeLast() { var newLength = _length - 1; var last = _queue[newLength]; _queue[newLength] = null; _length = newLength; return last; } /// Place [element] in heap at [index] or above. /// /// Put element into the empty cell at `index`. /// While the `element` has higher priority than the /// parent, swap it with the parent. void _bubbleUp(E element, int index) { while (index > 0) { var parentIndex = (index - 1) ~/ 2; var parent = _queue[parentIndex]; if (comparison(element, parent) > 0) break; _queue[index] = parent; index = parentIndex; } _queue[index] = element; } /// Place [element] in heap at [index] or above. /// /// Put element into the empty cell at `index`. /// While the `element` has lower priority than either child, /// swap it with the highest priority child. void _bubbleDown(E element, int index) { var rightChildIndex = index * 2 + 2; while (rightChildIndex < _length) { var leftChildIndex = rightChildIndex - 1; var leftChild = _queue[leftChildIndex]; var rightChild = _queue[rightChildIndex]; var comp = comparison(leftChild, rightChild); var minChildIndex; E minChild; if (comp < 0) { minChild = leftChild; minChildIndex = leftChildIndex; } else { minChild = rightChild; minChildIndex = rightChildIndex; } comp = comparison(element, minChild); if (comp <= 0) { _queue[index] = element; return; } _queue[index] = minChild; index = minChildIndex; rightChildIndex = index * 2 + 2; } var leftChildIndex = rightChildIndex - 1; if (leftChildIndex < _length) { var child = _queue[leftChildIndex]; var comp = comparison(element, child); if (comp > 0) { _queue[index] = child; index = leftChildIndex; } } _queue[index] = element; } /// Grows the capacity of the list holding the heap. /// /// Called when the list is full. void _grow() { var newCapacity = _queue.length * 2 + 1; if (newCapacity < _INITIAL_CAPACITY) newCapacity = _INITIAL_CAPACITY; var newQueue = List<E>(newCapacity); newQueue.setRange(0, _length, _queue); _queue = newQueue; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/src/equality.dart
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:collection'; import 'comparators.dart'; const int _HASH_MASK = 0x7fffffff; /// A generic equality relation on objects. abstract class Equality<E> { const factory Equality() = DefaultEquality<E>; /// Compare two elements for being equal. /// /// This should be a proper equality relation. bool equals(E e1, E e2); /// Get a hashcode of an element. /// /// The hashcode should be compatible with [equals], so that if /// `equals(a, b)` then `hash(a) == hash(b)`. int hash(E e); /// Test whether an object is a valid argument to [equals] and [hash]. /// /// Some implementations may be restricted to only work on specific types /// of objects. bool isValidKey(Object o); } /// Equality of objects based on derived values. /// /// For example, given the class: /// ```dart /// abstract class Employee { /// int get employmentId; /// } /// ``` /// /// The following [Equality] considers employees with the same IDs to be equal: /// ```dart /// EqualityBy((Employee e) => e.employmentId); /// ``` /// /// It's also possible to pass an additional equality instance that should be /// used to compare the value itself. class EqualityBy<E, F> implements Equality<E> { final F Function(E) _comparisonKey; final Equality<F> _inner; EqualityBy(F Function(E) comparisonKey, [Equality<F> inner = const DefaultEquality()]) : _comparisonKey = comparisonKey, _inner = inner; @override bool equals(E e1, E e2) => _inner.equals(_comparisonKey(e1), _comparisonKey(e2)); @override int hash(E e) => _inner.hash(_comparisonKey(e)); @override bool isValidKey(Object o) { if (o is E) { final value = _comparisonKey(o); return value is F && _inner.isValidKey(value); } return false; } } /// Equality of objects that compares only the natural equality of the objects. /// /// This equality uses the objects' own [Object.==] and [Object.hashCode] for /// the equality. /// /// Note that [equals] and [hash] take `Object`s rather than `E`s. This allows /// `E` to be inferred as `Null` in const contexts where `E` wouldn't be a /// compile-time constant, while still allowing the class to be used at runtime. class DefaultEquality<E> implements Equality<E> { const DefaultEquality(); @override bool equals(Object e1, Object e2) => e1 == e2; @override int hash(Object e) => e.hashCode; @override bool isValidKey(Object o) => true; } /// Equality of objects that compares only the identity of the objects. class IdentityEquality<E> implements Equality<E> { const IdentityEquality(); @override bool equals(E e1, E e2) => identical(e1, e2); @override int hash(E e) => identityHashCode(e); @override bool isValidKey(Object o) => true; } /// Equality on iterables. /// /// Two iterables are equal if they have the same elements in the same order. /// /// The [equals] and [hash] methods accepts `null` values, /// even if the [isValidKey] returns `false` for `null`. /// The [hash] of `null` is `null.hashCode`. class IterableEquality<E> implements Equality<Iterable<E>> { final Equality<E> _elementEquality; const IterableEquality( [Equality<E> elementEquality = const DefaultEquality()]) : _elementEquality = elementEquality; @override bool equals(Iterable<E> elements1, Iterable<E> elements2) { if (identical(elements1, elements2)) return true; if (elements1 == null || elements2 == null) return false; var it1 = elements1.iterator; var it2 = elements2.iterator; while (true) { var hasNext = it1.moveNext(); if (hasNext != it2.moveNext()) return false; if (!hasNext) return true; if (!_elementEquality.equals(it1.current, it2.current)) return false; } } @override int hash(Iterable<E> elements) { if (elements == null) return null.hashCode; // Jenkins's one-at-a-time hash function. var hash = 0; for (var element in elements) { var c = _elementEquality.hash(element); hash = (hash + c) & _HASH_MASK; hash = (hash + (hash << 10)) & _HASH_MASK; hash ^= (hash >> 6); } hash = (hash + (hash << 3)) & _HASH_MASK; hash ^= (hash >> 11); hash = (hash + (hash << 15)) & _HASH_MASK; return hash; } @override bool isValidKey(Object o) => o is Iterable<E>; } /// Equality on lists. /// /// Two lists are equal if they have the same length and their elements /// at each index are equal. /// /// This is effectively the same as [IterableEquality] except that it /// accesses elements by index instead of through iteration. /// /// The [equals] and [hash] methods accepts `null` values, /// even if the [isValidKey] returns `false` for `null`. /// The [hash] of `null` is `null.hashCode`. class ListEquality<E> implements Equality<List<E>> { final Equality<E> _elementEquality; const ListEquality([Equality<E> elementEquality = const DefaultEquality()]) : _elementEquality = elementEquality; @override bool equals(List<E> list1, List<E> list2) { if (identical(list1, list2)) return true; if (list1 == null || list2 == null) return false; var length = list1.length; if (length != list2.length) return false; for (var i = 0; i < length; i++) { if (!_elementEquality.equals(list1[i], list2[i])) return false; } return true; } @override int hash(List<E> list) { if (list == null) return null.hashCode; // Jenkins's one-at-a-time hash function. // This code is almost identical to the one in IterableEquality, except // that it uses indexing instead of iterating to get the elements. var hash = 0; for (var i = 0; i < list.length; i++) { var c = _elementEquality.hash(list[i]); hash = (hash + c) & _HASH_MASK; hash = (hash + (hash << 10)) & _HASH_MASK; hash ^= (hash >> 6); } hash = (hash + (hash << 3)) & _HASH_MASK; hash ^= (hash >> 11); hash = (hash + (hash << 15)) & _HASH_MASK; return hash; } @override bool isValidKey(Object o) => o is List<E>; } abstract class _UnorderedEquality<E, T extends Iterable<E>> implements Equality<T> { final Equality<E> _elementEquality; const _UnorderedEquality(this._elementEquality); @override bool equals(T elements1, T elements2) { if (identical(elements1, elements2)) return true; if (elements1 == null || elements2 == null) return false; var counts = HashMap( equals: _elementEquality.equals, hashCode: _elementEquality.hash, isValidKey: _elementEquality.isValidKey); var length = 0; for (var e in elements1) { var count = counts[e] ?? 0; counts[e] = count + 1; length++; } for (var e in elements2) { var count = counts[e]; if (count == null || count == 0) return false; counts[e] = count - 1; length--; } return length == 0; } @override int hash(T elements) { if (elements == null) return null.hashCode; var hash = 0; for (E element in elements) { var c = _elementEquality.hash(element); hash = (hash + c) & _HASH_MASK; } hash = (hash + (hash << 3)) & _HASH_MASK; hash ^= (hash >> 11); hash = (hash + (hash << 15)) & _HASH_MASK; return hash; } } /// Equality of the elements of two iterables without considering order. /// /// Two iterables are considered equal if they have the same number of elements, /// and the elements of one set can be paired with the elements /// of the other iterable, so that each pair are equal. class UnorderedIterableEquality<E> extends _UnorderedEquality<E, Iterable<E>> { const UnorderedIterableEquality( [Equality<E> elementEquality = const DefaultEquality()]) : super(elementEquality); @override bool isValidKey(Object o) => o is Iterable<E>; } /// Equality of sets. /// /// Two sets are considered equal if they have the same number of elements, /// and the elements of one set can be paired with the elements /// of the other set, so that each pair are equal. /// /// This equality behaves the same as [UnorderedIterableEquality] except that /// it expects sets instead of iterables as arguments. /// /// The [equals] and [hash] methods accepts `null` values, /// even if the [isValidKey] returns `false` for `null`. /// The [hash] of `null` is `null.hashCode`. class SetEquality<E> extends _UnorderedEquality<E, Set<E>> { const SetEquality([Equality<E> elementEquality = const DefaultEquality()]) : super(elementEquality); @override bool isValidKey(Object o) => o is Set<E>; } /// Internal class used by [MapEquality]. /// /// The class represents a map entry as a single object, /// using a combined hashCode and equality of the key and value. class _MapEntry { final MapEquality equality; final key; final value; _MapEntry(this.equality, this.key, this.value); @override int get hashCode => (3 * equality._keyEquality.hash(key) + 7 * equality._valueEquality.hash(value)) & _HASH_MASK; @override bool operator ==(Object other) => other is _MapEntry && equality._keyEquality.equals(key, other.key) && equality._valueEquality.equals(value, other.value); } /// Equality on maps. /// /// Two maps are equal if they have the same number of entries, and if the /// entries of the two maps are pairwise equal on both key and value. /// /// The [equals] and [hash] methods accepts `null` values, /// even if the [isValidKey] returns `false` for `null`. /// The [hash] of `null` is `null.hashCode`. class MapEquality<K, V> implements Equality<Map<K, V>> { final Equality<K> _keyEquality; final Equality<V> _valueEquality; const MapEquality( {Equality<K> keys = const DefaultEquality(), Equality<V> values = const DefaultEquality()}) : _keyEquality = keys, _valueEquality = values; @override bool equals(Map<K, V> map1, Map<K, V> map2) { if (identical(map1, map2)) return true; if (map1 == null || map2 == null) return false; var length = map1.length; if (length != map2.length) return false; Map<_MapEntry, int> equalElementCounts = HashMap(); for (var key in map1.keys) { var entry = _MapEntry(this, key, map1[key]); var count = equalElementCounts[entry] ?? 0; equalElementCounts[entry] = count + 1; } for (var key in map2.keys) { var entry = _MapEntry(this, key, map2[key]); var count = equalElementCounts[entry]; if (count == null || count == 0) return false; equalElementCounts[entry] = count - 1; } return true; } @override int hash(Map<K, V> map) { if (map == null) return null.hashCode; var hash = 0; for (var key in map.keys) { var keyHash = _keyEquality.hash(key); var valueHash = _valueEquality.hash(map[key]); hash = (hash + 3 * keyHash + 7 * valueHash) & _HASH_MASK; } hash = (hash + (hash << 3)) & _HASH_MASK; hash ^= (hash >> 11); hash = (hash + (hash << 15)) & _HASH_MASK; return hash; } @override bool isValidKey(Object o) => o is Map<K, V>; } /// Combines several equalities into a single equality. /// /// Tries each equality in order, using [Equality.isValidKey], and returns /// the result of the first equality that applies to the argument or arguments. /// /// For `equals`, the first equality that matches the first argument is used, /// and if the second argument of `equals` is not valid for that equality, /// it returns false. /// /// Because the equalities are tried in order, they should generally work on /// disjoint types. Otherwise the multi-equality may give inconsistent results /// for `equals(e1, e2)` and `equals(e2, e1)`. This can happen if one equality /// considers only `e1` a valid key, and not `e2`, but an equality which is /// checked later, allows both. class MultiEquality<E> implements Equality<E> { final Iterable<Equality<E>> _equalities; const MultiEquality(Iterable<Equality<E>> equalities) : _equalities = equalities; @override bool equals(E e1, E e2) { for (var eq in _equalities) { if (eq.isValidKey(e1)) return eq.isValidKey(e2) && eq.equals(e1, e2); } return false; } @override int hash(E e) { for (var eq in _equalities) { if (eq.isValidKey(e)) return eq.hash(e); } return 0; } @override bool isValidKey(Object o) { for (var eq in _equalities) { if (eq.isValidKey(o)) return true; } return false; } } /// Deep equality on collections. /// /// Recognizes lists, sets, iterables and maps and compares their elements using /// deep equality as well. /// /// Non-iterable/map objects are compared using a configurable base equality. /// /// Works in one of two modes: ordered or unordered. /// /// In ordered mode, lists and iterables are required to have equal elements /// in the same order. In unordered mode, the order of elements in iterables /// and lists are not important. /// /// A list is only equal to another list, likewise for sets and maps. All other /// iterables are compared as iterables only. class DeepCollectionEquality implements Equality { final Equality _base; final bool _unordered; const DeepCollectionEquality([Equality base = const DefaultEquality()]) : _base = base, _unordered = false; /// Creates a deep equality on collections where the order of lists and /// iterables are not considered important. That is, lists and iterables are /// treated as unordered iterables. const DeepCollectionEquality.unordered( [Equality base = const DefaultEquality()]) : _base = base, _unordered = true; @override bool equals(e1, e2) { if (e1 is Set) { return e2 is Set && SetEquality(this).equals(e1, e2); } if (e1 is Map) { return e2 is Map && MapEquality(keys: this, values: this).equals(e1, e2); } if (!_unordered) { if (e1 is List) { return e2 is List && ListEquality(this).equals(e1, e2); } if (e1 is Iterable) { return e2 is Iterable && IterableEquality(this).equals(e1, e2); } } else if (e1 is Iterable) { if (e1 is List != e2 is List) return false; return e2 is Iterable && UnorderedIterableEquality(this).equals(e1, e2); } return _base.equals(e1, e2); } @override int hash(Object o) { if (o is Set) return SetEquality(this).hash(o); if (o is Map) return MapEquality(keys: this, values: this).hash(o); if (!_unordered) { if (o is List) return ListEquality(this).hash(o); if (o is Iterable) return IterableEquality(this).hash(o); } else if (o is Iterable) { return UnorderedIterableEquality(this).hash(o); } return _base.hash(o); } @override bool isValidKey(Object o) => o is Iterable || o is Map || _base.isValidKey(o); } /// String equality that's insensitive to differences in ASCII case. /// /// Non-ASCII characters are compared as-is, with no conversion. class CaseInsensitiveEquality implements Equality<String> { const CaseInsensitiveEquality(); @override bool equals(String string1, String string2) => equalsIgnoreAsciiCase(string1, string2); @override int hash(String string) => hashIgnoreAsciiCase(string); @override bool isValidKey(Object object) => object is String; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/src/iterable_zip.dart
// Copyright (c) 2013, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:collection'; /// Iterable that iterates over lists of values from other iterables. /// /// When [iterator] is read, an [Iterator] is created for each [Iterable] in /// the [Iterable] passed to the constructor. /// /// As long as all these iterators have a next value, those next values are /// combined into a single list, which becomes the next value of this /// [Iterable]'s [Iterator]. As soon as any of the iterators run out, /// the zipped iterator also stops. class IterableZip<T> extends IterableBase<List<T>> { final Iterable<Iterable<T>> _iterables; IterableZip(Iterable<Iterable<T>> iterables) : _iterables = iterables; /// Returns an iterator that combines values of the iterables' iterators /// as long as they all have values. @override Iterator<List<T>> get iterator { var iterators = _iterables.map((x) => x.iterator).toList(growable: false); // TODO(lrn): Return an empty iterator directly if iterators is empty? return _IteratorZip<T>(iterators); } } class _IteratorZip<T> implements Iterator<List<T>> { final List<Iterator<T>> _iterators; List<T> _current; _IteratorZip(List<Iterator<T>> iterators) : _iterators = iterators; @override bool moveNext() { if (_iterators.isEmpty) return false; for (var i = 0; i < _iterators.length; i++) { if (!_iterators[i].moveNext()) { _current = null; return false; } } _current = List(_iterators.length); for (var i = 0; i < _iterators.length; i++) { _current[i] = _iterators[i].current; } return true; } @override List<T> get current => _current; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/src/utils.dart
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. /// A pair of values. class Pair<E, F> { E first; F last; Pair(this.first, this.last); } /// Returns a [Comparator] that asserts that its first argument is comparable. Comparator<T> defaultCompare<T>() => (value1, value2) => (value1 as Comparable).compareTo(value2);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/src/canonicalized_map.dart
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:collection'; import 'utils.dart'; /// A map whose keys are converted to canonical values of type `C`. /// /// This is useful for using case-insensitive String keys, for example. It's /// more efficient than a [LinkedHashMap] with a custom equality operator /// because it only canonicalizes each key once, rather than doing so for each /// comparison. /// /// By default, `null` is allowed as a key. It can be forbidden via the /// `isValidKey` parameter. class CanonicalizedMap<C, K, V> implements Map<K, V> { final C Function(K) _canonicalize; final bool Function(Object) _isValidKeyFn; final _base = <C, Pair<K, V>>{}; /// Creates an empty canonicalized map. /// /// The [canonicalize] function should return the canonical value for the /// given key. Keys with the same canonical value are considered equivalent. /// /// The [isValidKey] function is called before calling [canonicalize] for /// methods that take arbitrary objects. It can be used to filter out keys /// that can't be canonicalized. CanonicalizedMap(C Function(K key) canonicalize, {bool Function(Object key) isValidKey}) : _canonicalize = canonicalize, _isValidKeyFn = isValidKey; /// Creates a canonicalized map that is initialized with the key/value pairs /// of [other]. /// /// The [canonicalize] function should return the canonical value for the /// given key. Keys with the same canonical value are considered equivalent. /// /// The [isValidKey] function is called before calling [canonicalize] for /// methods that take arbitrary objects. It can be used to filter out keys /// that can't be canonicalized. CanonicalizedMap.from(Map<K, V> other, C Function(K key) canonicalize, {bool Function(Object key) isValidKey}) : _canonicalize = canonicalize, _isValidKeyFn = isValidKey { addAll(other); } @override V operator [](Object key) { if (!_isValidKey(key)) return null; var pair = _base[_canonicalize(key as K)]; return pair == null ? null : pair.last; } @override void operator []=(K key, V value) { if (!_isValidKey(key)) return; _base[_canonicalize(key)] = Pair(key, value); } @override void addAll(Map<K, V> other) { other.forEach((key, value) => this[key] = value); } @override void addEntries(Iterable<MapEntry<K, V>> entries) => _base.addEntries( entries.map((e) => MapEntry(_canonicalize(e.key), Pair(e.key, e.value)))); @override Map<K2, V2> cast<K2, V2>() => _base.cast<K2, V2>(); @override void clear() { _base.clear(); } @override bool containsKey(Object key) { if (!_isValidKey(key)) return false; return _base.containsKey(_canonicalize(key as K)); } @override bool containsValue(Object value) => _base.values.any((pair) => pair.last == value); @override Iterable<MapEntry<K, V>> get entries => _base.entries.map((e) => MapEntry(e.value.first, e.value.last)); @override void forEach(void Function(K, V) f) { _base.forEach((key, pair) => f(pair.first, pair.last)); } @override bool get isEmpty => _base.isEmpty; @override bool get isNotEmpty => _base.isNotEmpty; @override Iterable<K> get keys => _base.values.map((pair) => pair.first); @override int get length => _base.length; @override Map<K2, V2> map<K2, V2>(MapEntry<K2, V2> Function(K, V) transform) => _base.map((_, pair) => transform(pair.first, pair.last)); @override V putIfAbsent(K key, V Function() ifAbsent) { return _base .putIfAbsent(_canonicalize(key), () => Pair(key, ifAbsent())) .last; } @override V remove(Object key) { if (!_isValidKey(key)) return null; var pair = _base.remove(_canonicalize(key as K)); return pair == null ? null : pair.last; } @override void removeWhere(bool Function(K key, V value) test) => _base.removeWhere((_, pair) => test(pair.first, pair.last)); @deprecated Map<K2, V2> retype<K2, V2>() => cast<K2, V2>(); @override V update(K key, V Function(V) update, {V Function() ifAbsent}) => _base .update(_canonicalize(key), (pair) => Pair(key, update(pair.last)), ifAbsent: ifAbsent == null ? null : () => Pair(key, ifAbsent())) .last; @override void updateAll(V Function(K key, V value) update) => _base .updateAll((_, pair) => Pair(pair.first, update(pair.first, pair.last))); @override Iterable<V> get values => _base.values.map((pair) => pair.last); @override String toString() { // Detect toString() cycles. if (_isToStringVisiting(this)) { return '{...}'; } var result = StringBuffer(); try { _toStringVisiting.add(this); result.write('{'); var first = true; forEach((k, v) { if (!first) { result.write(', '); } first = false; result.write('$k: $v'); }); result.write('}'); } finally { assert(identical(_toStringVisiting.last, this)); _toStringVisiting.removeLast(); } return result.toString(); } bool _isValidKey(Object key) => (key == null || key is K) && (_isValidKeyFn == null || _isValidKeyFn(key)); } /// A collection used to identify cyclic maps during toString() calls. final List _toStringVisiting = []; /// Check if we are currently visiting `o` in a toString() call. bool _isToStringVisiting(o) => _toStringVisiting.any((e) => identical(o, e));
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/collection/src/queue_list.dart
// Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file // for details. All rights reserved. Use of this source code is governed by a // BSD-style license that can be found in the LICENSE file. import 'dart:collection'; /// A class that efficiently implements both [Queue] and [List]. // TODO(nweiz): Currently this code is copied almost verbatim from // dart:collection. The only changes are to implement List and to remove methods // that are redundant with ListMixin. Remove or simplify it when issue 21330 is // fixed. class QueueList<E> extends Object with ListMixin<E> implements Queue<E> { /// Adapts [source] to be a `QueueList<T>`. /// /// Any time the class would produce an element that is not a [T], the element /// access will throw. /// /// Any time a [T] value is attempted stored into the adapted class, the store /// will throw unless the value is also an instance of [S]. /// /// If all accessed elements of [source] are actually instances of [T] and if /// all elements stored in the returned are actually instance of [S], /// then the returned instance can be used as a `QueueList<T>`. static QueueList<T> _castFrom<S, T>(QueueList<S> source) { return _CastQueueList<S, T>(source); } static const int _INITIAL_CAPACITY = 8; List<E> _table; int _head; int _tail; /// Create an empty queue. /// /// If [initialCapacity] is given, prepare the queue for at least that many /// elements. QueueList([int initialCapacity]) : _head = 0, _tail = 0 { if (initialCapacity == null || initialCapacity < _INITIAL_CAPACITY) { initialCapacity = _INITIAL_CAPACITY; } else if (!_isPowerOf2(initialCapacity)) { initialCapacity = _nextPowerOf2(initialCapacity); } assert(_isPowerOf2(initialCapacity)); _table = List<E>(initialCapacity); } // An internal constructor for use by _CastQueueList. QueueList._(); /// Create a queue initially containing the elements of [source]. factory QueueList.from(Iterable<E> source) { if (source is List) { var length = source.length; var queue = QueueList<E>(length + 1); assert(queue._table.length > length); var sourceList = source; queue._table.setRange(0, length, sourceList, 0); queue._tail = length; return queue; } else { return QueueList<E>()..addAll(source); } } // Collection interface. @override void add(E element) { _add(element); } @override void addAll(Iterable<E> iterable) { if (iterable is List) { var list = iterable; var addCount = list.length; var length = this.length; if (length + addCount >= _table.length) { _preGrow(length + addCount); // After preGrow, all elements are at the start of the list. _table.setRange(length, length + addCount, list, 0); _tail += addCount; } else { // Adding addCount elements won't reach _head. var endSpace = _table.length - _tail; if (addCount < endSpace) { _table.setRange(_tail, _tail + addCount, list, 0); _tail += addCount; } else { var preSpace = addCount - endSpace; _table.setRange(_tail, _tail + endSpace, list, 0); _table.setRange(0, preSpace, list, endSpace); _tail = preSpace; } } } else { for (var element in iterable) { _add(element); } } } QueueList<T> cast<T>() => QueueList._castFrom<E, T>(this); @deprecated QueueList<T> retype<T>() => cast<T>(); @override String toString() => IterableBase.iterableToFullString(this, '{', '}'); // Queue interface. @override void addLast(E element) { _add(element); } @override void addFirst(E element) { _head = (_head - 1) & (_table.length - 1); _table[_head] = element; if (_head == _tail) _grow(); } @override E removeFirst() { if (_head == _tail) throw StateError('No element'); var result = _table[_head]; _table[_head] = null; _head = (_head + 1) & (_table.length - 1); return result; } @override E removeLast() { if (_head == _tail) throw StateError('No element'); _tail = (_tail - 1) & (_table.length - 1); var result = _table[_tail]; _table[_tail] = null; return result; } // List interface. @override int get length => (_tail - _head) & (_table.length - 1); @override set length(int value) { if (value < 0) throw RangeError('Length $value may not be negative.'); var delta = value - length; if (delta >= 0) { if (_table.length <= value) { _preGrow(value); } _tail = (_tail + delta) & (_table.length - 1); return; } var newTail = _tail + delta; // [delta] is negative. if (newTail >= 0) { _table.fillRange(newTail, _tail, null); } else { newTail += _table.length; _table.fillRange(0, _tail, null); _table.fillRange(newTail, _table.length, null); } _tail = newTail; } @override E operator [](int index) { if (index < 0 || index >= length) { throw RangeError('Index $index must be in the range [0..$length).'); } return _table[(_head + index) & (_table.length - 1)]; } @override void operator []=(int index, E value) { if (index < 0 || index >= length) { throw RangeError('Index $index must be in the range [0..$length).'); } _table[(_head + index) & (_table.length - 1)] = value; } // Internal helper functions. /// Whether [number] is a power of two. /// /// Only works for positive numbers. static bool _isPowerOf2(int number) => (number & (number - 1)) == 0; /// Rounds [number] up to the nearest power of 2. /// /// If [number] is a power of 2 already, it is returned. /// /// Only works for positive numbers. static int _nextPowerOf2(int number) { assert(number > 0); number = (number << 1) - 1; for (;;) { var nextNumber = number & (number - 1); if (nextNumber == 0) return number; number = nextNumber; } } /// Adds element at end of queue. Used by both [add] and [addAll]. void _add(E element) { _table[_tail] = element; _tail = (_tail + 1) & (_table.length - 1); if (_head == _tail) _grow(); } /// Grow the table when full. void _grow() { var newTable = List<E>(_table.length * 2); var split = _table.length - _head; newTable.setRange(0, split, _table, _head); newTable.setRange(split, split + _head, _table, 0); _head = 0; _tail = _table.length; _table = newTable; } int _writeToList(List<E> target) { assert(target.length >= length); if (_head <= _tail) { var length = _tail - _head; target.setRange(0, length, _table, _head); return length; } else { var firstPartSize = _table.length - _head; target.setRange(0, firstPartSize, _table, _head); target.setRange(firstPartSize, firstPartSize + _tail, _table, 0); return _tail + firstPartSize; } } /// Grows the table even if it is not full. void _preGrow(int newElementCount) { assert(newElementCount >= length); // Add 1.5x extra room to ensure that there's room for more elements after // expansion. newElementCount += newElementCount >> 1; var newCapacity = _nextPowerOf2(newElementCount); var newTable = List<E>(newCapacity); _tail = _writeToList(newTable); _table = newTable; _head = 0; } } class _CastQueueList<S, T> extends QueueList<T> { final QueueList<S> _delegate; _CastQueueList(this._delegate) : super._() { _table = _delegate._table.cast<T>(); } @override int get _head => _delegate._head; @override set _head(int value) => _delegate._head = value; @override int get _tail => _delegate._tail; @override set _tail(int value) => _delegate._tail = value; }
0