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/async
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/single_subscription_transformer.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:async'; /// A transformer that converts a broadcast stream into a single-subscription /// stream. /// /// This buffers the broadcast stream's events, which means that it starts /// listening to a stream as soon as it's bound. /// /// This also casts the source stream's events to type `T`. If the cast fails, /// the result stream will emit a [CastError]. This behavior is deprecated, and /// should not be relied upon. class SingleSubscriptionTransformer<S, T> extends StreamTransformerBase<S, T> { const SingleSubscriptionTransformer(); @override Stream<T> bind(Stream<S> stream) { StreamSubscription<S> subscription; var controller = StreamController<T>(sync: true, onCancel: () => subscription.cancel()); subscription = stream.listen((value) { // TODO(nweiz): When we release a new major version, get rid of the second // type parameter and avoid this conversion. try { controller.add(value as T); } on CastError catch (error, stackTrace) { controller.addError(error, stackTrace); } }, onError: controller.addError, onDone: controller.close); return controller.stream; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/cancelable_operation.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:async'; import 'package:async/async.dart'; import 'utils.dart'; /// An asynchronous operation that can be cancelled. /// /// The value of this operation is exposed as [value]. When this operation is /// cancelled, [value] won't complete either successfully or with an error. If /// [value] has already completed, cancelling the operation does nothing. class CancelableOperation<T> { /// The completer that produced this operation. /// /// This is canceled when [cancel] is called. final CancelableCompleter<T> _completer; CancelableOperation._(this._completer); /// Creates a [CancelableOperation] wrapping [inner]. /// /// When this operation is canceled, [onCancel] will be called and any value /// or error produced by [inner] will be discarded. If [onCancel] returns a /// [Future], it will be forwarded to [cancel]. /// /// [onCancel] will be called synchronously when the operation is canceled. /// It's guaranteed to only be called once. /// /// Calling this constructor is equivalent to creating a [CancelableCompleter] /// and completing it with [inner]. As such, [isCompleted] is true from the /// moment this [CancelableOperation] is created, regardless of whether /// [inner] has completed yet or not. factory CancelableOperation.fromFuture(Future<T> inner, {FutureOr Function() onCancel}) { var completer = CancelableCompleter<T>(onCancel: onCancel); completer.complete(inner); return completer.operation; } /// The value returned by the operation. Future<T> get value => _completer._inner.future; /// Creates a [Stream] containing the result of this operation. /// /// This is like `value.asStream()`, but if a subscription to the stream is /// canceled, this is as well. Stream<T> asStream() { var controller = StreamController<T>(sync: true, onCancel: _completer._cancel); value.then((value) { controller.add(value); controller.close(); }, onError: (error, StackTrace stackTrace) { controller.addError(error, stackTrace); controller.close(); }); return controller.stream; } /// Creates a [Future] that completes when this operation completes *or* when /// it's cancelled. /// /// If this operation completes, this completes to the same result as [value]. /// If this operation is cancelled, the returned future waits for the future /// returned by [cancel], then completes to [cancellationValue]. Future<T> valueOrCancellation([T cancellationValue]) { var completer = Completer<T>.sync(); value.then((result) => completer.complete(result), onError: completer.completeError); _completer._cancelMemo.future.then((_) { completer.complete(cancellationValue); }, onError: completer.completeError); return completer.future; } /// Registers callbacks to be called when this operation completes. /// /// [onValue] and [onError] behave in the same way as [Future.then]. /// /// If [onCancel] is provided, and this operation is canceled, the [onCancel] /// callback is called and the returned operation completes with the result. /// /// If [onCancel] is not given, and this operation is canceled, then the /// returned operation is canceled. /// /// If [propagateCancel] is `true` and the returned operation is canceled then /// this operation is canceled. The default is `false`. CancelableOperation<R> then<R>(FutureOr<R> Function(T) onValue, {FutureOr<R> Function(Object, StackTrace) onError, FutureOr<R> Function() onCancel, bool propagateCancel = false}) { final completer = CancelableCompleter<R>(onCancel: propagateCancel ? cancel : null); valueOrCancellation().then((T result) { if (!completer.isCanceled) { if (isCompleted) { completer.complete(Future.sync(() => onValue(result))); } else if (onCancel != null) { completer.complete(Future.sync(onCancel)); } else { completer._cancel(); } } }, onError: (error, StackTrace stackTrace) { if (!completer.isCanceled) { if (onError != null) { completer.complete(Future.sync(() => onError(error, stackTrace))); } else { completer.completeError(error, stackTrace); } } }); return completer.operation; } /// Cancels this operation. /// /// This returns the [Future] returned by the [CancelableCompleter]'s /// `onCancel` callback. Unlike [Stream.cancel], it never returns `null`. Future cancel() => _completer._cancel(); /// Whether this operation has been canceled before it completed. bool get isCanceled => _completer.isCanceled; /// Whether the [CancelableCompleter] backing this operation has been /// completed. /// /// This value being true does not imply that the [value] future has /// completed, but merely that it is no longer possible to [cancel] the /// operation. bool get isCompleted => _completer.isCompleted; } /// A completer for a [CancelableOperation]. class CancelableCompleter<T> { /// The completer for the wrapped future. final Completer<T> _inner; /// The callback to call if the future is canceled. final FutureOrCallback _onCancel; /// Creates a new completer for a [CancelableOperation]. /// /// When the future operation canceled, as long as the completer hasn't yet /// completed, [onCancel] is called. If [onCancel] returns a [Future], it's /// forwarded to [CancelableOperation.cancel]. /// /// [onCancel] will be called synchronously when the operation is canceled. /// It's guaranteed to only be called once. CancelableCompleter({FutureOr Function() onCancel}) : _onCancel = onCancel, _inner = Completer<T>() { _operation = CancelableOperation<T>._(this); } /// The operation controlled by this completer. CancelableOperation<T> get operation => _operation; CancelableOperation<T> _operation; /// Whether the completer has completed. bool get isCompleted => _isCompleted; bool _isCompleted = false; /// Whether the completer was canceled before being completed. bool get isCanceled => _isCanceled; bool _isCanceled = false; /// The memoizer for [_cancel]. final _cancelMemo = AsyncMemoizer(); /// Completes [operation] to [value]. /// /// If [value] is a [Future], this will complete to the result of that /// [Future] once it completes. void complete([FutureOr<T> value]) { if (_isCompleted) throw StateError('Operation already completed'); _isCompleted = true; if (value is! Future) { if (_isCanceled) return; _inner.complete(value); return; } final future = value as Future<T>; if (_isCanceled) { // Make sure errors from [value] aren't top-leveled. future.catchError((_) {}); return; } future.then((result) { if (_isCanceled) return; _inner.complete(result); }, onError: (error, StackTrace stackTrace) { if (_isCanceled) return; _inner.completeError(error, stackTrace); }); } /// Completes [operation] to [error]. void completeError(Object error, [StackTrace stackTrace]) { if (_isCompleted) throw StateError('Operation already completed'); _isCompleted = true; if (_isCanceled) return; _inner.completeError(error, stackTrace); } /// Cancel the completer. Future _cancel() { if (_inner.isCompleted) return Future.value(); return _cancelMemo.runOnce(() { _isCanceled = true; if (_onCancel != null) return _onCancel(); }); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/restartable_timer.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:async'; /// A non-periodic timer that can be restarted any number of times. /// /// Once restarted (via [reset]), the timer counts down from its original /// duration again. class RestartableTimer implements Timer { /// The duration of the timer. final Duration _duration; /// The callback to call when the timer fires. final ZoneCallback _callback; /// The timer for the current or most recent countdown. /// /// This timer is canceled and overwritten every time this [RestartableTimer] /// is reset. Timer _timer; /// Creates a new timer. /// /// The [callback] function is invoked after the given [duration]. Unlike a /// normal non-periodic [Timer], [callback] may be called more than once. RestartableTimer(this._duration, this._callback) : _timer = Timer(_duration, _callback); @override bool get isActive => _timer.isActive; /// Restarts the timer so that it counts down from its original duration /// again. /// /// This restarts the timer even if it has already fired or has been canceled. void reset() { _timer.cancel(); _timer = Timer(_duration, _callback); } @override void cancel() { _timer.cancel(); } /// The number of durations preceding the most recent timer event on the most /// recent countdown. /// /// Calls to [reset] will also reset the tick so subsequent tick values may /// not be strictly larger than previous values. @override int get tick => _timer.tick; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/typed_stream_transformer.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:async'; /// Creates a wrapper that coerces the type of [transformer]. /// /// This soundly converts a [StreamTransformer] to a `StreamTransformer<S, T>`, /// regardless of its original generic type, by asserting that the events /// emitted by the transformed stream are instances of `T` whenever they're /// provided. If they're not, the stream throws a [CastError]. @Deprecated('Use Stream.cast after binding a transformer instead') StreamTransformer<S, T> typedStreamTransformer<S, T>( StreamTransformer transformer) => transformer is StreamTransformer<S, T> ? transformer : _TypeSafeStreamTransformer(transformer); /// A wrapper that coerces the type of the stream returned by an inner /// transformer. class _TypeSafeStreamTransformer<S, T> extends StreamTransformerBase<S, T> { final StreamTransformer _inner; _TypeSafeStreamTransformer(this._inner); @override Stream<T> bind(Stream<S> stream) => _inner.bind(stream).cast(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/byte_collector.dart
// Copyright (c) 2017, 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:typed_data'; import 'cancelable_operation.dart'; /// Collects an asynchronous sequence of byte lists into a single list of bytes. /// /// If the [source] stream emits an error event, /// the collection fails and the returned future completes with the same error. /// /// If any of the input data are not valid bytes, they will be truncated to /// an eight-bit unsigned value in the resulting list. Future<Uint8List> collectBytes(Stream<List<int>> source) { return _collectBytes(source, (_, result) => result); } /// Collects an asynchronous sequence of byte lists into a single list of bytes. /// /// Returns a [CancelableOperation] that provides the result future and a way /// to cancel the collection early. /// /// If the [source] stream emits an error event, /// the collection fails and the returned future completes with the same error. /// /// If any of the input data are not valid bytes, they will be truncated to /// an eight-bit unsigned value in the resulting list. CancelableOperation<Uint8List> collectBytesCancelable( Stream<List<int>> source) { return _collectBytes( source, (subscription, result) => CancelableOperation.fromFuture(result, onCancel: subscription.cancel)); } /// Generalization over [collectBytes] and [collectBytesCancelable]. /// /// Performs all the same operations, but the final result is created /// by the [result] function, which has access to the stream subscription /// so it can cancel the operation. T _collectBytes<T>(Stream<List<int>> source, T Function(StreamSubscription<List<int>>, Future<Uint8List>) result) { var byteLists = <List<int>>[]; var length = 0; var completer = Completer<Uint8List>.sync(); var subscription = source.listen( (bytes) { byteLists.add(bytes); length += bytes.length; }, onError: completer.completeError, onDone: () { completer.complete(_collect(length, byteLists)); }, cancelOnError: true); return result(subscription, completer.future); } // Join a lists of bytes with a known total length into a single [Uint8List]. Uint8List _collect(int length, List<List<int>> byteLists) { var result = Uint8List(length); var i = 0; for (var byteList in byteLists) { var end = i + byteList.length; result.setRange(i, end, byteList); i = end; } return result; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/stream_group.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:async'; /// A collection of streams whose events are unified and sent through a central /// stream. /// /// Both errors and data events are forwarded through [stream]. The streams in /// the group won't be listened to until [stream] has a listener. **Note that /// this means that events emitted by broadcast streams will be dropped until /// [stream] has a listener.** /// /// If the `StreamGroup` is constructed using [new StreamGroup], [stream] will /// be single-subscription. In this case, if [stream] is paused or canceled, all /// streams in the group will likewise be paused or canceled, respectively. /// /// If the `StreamGroup` is constructed using [StreamGroup.broadcast], /// [stream] will be a broadcast stream. In this case, the streams in the group /// will never be paused and single-subscription streams in the group will never /// be canceled. **Note that single-subscription streams in a broadcast group /// may drop events if a listener is added and later removed.** Broadcast /// streams in the group will be canceled once [stream] has no listeners, and /// will be listened to again once [stream] has listeners. /// /// [stream] won't close until [close] is called on the group *and* every stream /// in the group closes. class StreamGroup<T> implements Sink<Stream<T>> { /// The stream through which all events from streams in the group are emitted. Stream<T> get stream => _controller.stream; StreamController<T> _controller; /// Whether the group is closed, meaning that no more streams may be added. var _closed = false; /// The current state of the group. /// /// See [_StreamGroupState] for detailed descriptions of each state. var _state = _StreamGroupState.dormant; /// Streams that have been added to the group, and their subscriptions if they /// have been subscribed to. /// /// The subscriptions will be null until the group has a listener registered. /// If it's a broadcast group and it goes dormant again, broadcast stream /// subscriptions will be canceled and set to null again. Single-subscriber /// stream subscriptions will be left intact, since they can't be /// re-subscribed. final _subscriptions = <Stream<T>, StreamSubscription<T>>{}; /// Merges the events from [streams] into a single single-subscription stream. /// /// This is equivalent to adding [streams] to a group, closing that group, and /// returning its stream. static Stream<T> merge<T>(Iterable<Stream<T>> streams) { var group = StreamGroup<T>(); streams.forEach(group.add); group.close(); return group.stream; } /// Merges the events from [streams] into a single broadcast stream. /// /// This is equivalent to adding [streams] to a broadcast group, closing that /// group, and returning its stream. static Stream<T> mergeBroadcast<T>(Iterable<Stream<T>> streams) { var group = StreamGroup<T>.broadcast(); streams.forEach(group.add); group.close(); return group.stream; } /// Creates a new stream group where [stream] is single-subscriber. StreamGroup() { _controller = StreamController<T>( onListen: _onListen, onPause: _onPause, onResume: _onResume, onCancel: _onCancel, sync: true); } /// Creates a new stream group where [stream] is a broadcast stream. StreamGroup.broadcast() { _controller = StreamController<T>.broadcast( onListen: _onListen, onCancel: _onCancelBroadcast, sync: true); } /// Adds [stream] as a member of this group. /// /// Any events from [stream] will be emitted through [this.stream]. If this /// group has a listener, [stream] will be listened to immediately; otherwise /// it will only be listened to once this group gets a listener. /// /// If this is a single-subscription group and its subscription has been /// canceled, [stream] will be canceled as soon as its added. If this returns /// a [Future], it will be returned from [add]. Otherwise, [add] returns /// `null`. /// /// Throws a [StateError] if this group is closed. @override Future add(Stream<T> stream) { if (_closed) { throw StateError("Can't add a Stream to a closed StreamGroup."); } if (_state == _StreamGroupState.dormant) { _subscriptions.putIfAbsent(stream, () => null); } else if (_state == _StreamGroupState.canceled) { // Listen to the stream and cancel it immediately so that no one else can // listen, for consistency. If the stream has an onCancel listener this // will also fire that, which may help it clean up resources. return stream.listen(null).cancel(); } else { _subscriptions.putIfAbsent(stream, () => _listenToStream(stream)); } return null; } /// Removes [stream] as a member of this group. /// /// No further events from [stream] will be emitted through this group. If /// [stream] has been listened to, its subscription will be canceled. /// /// If [stream] has been listened to, this *synchronously* cancels its /// subscription. This means that any events from [stream] that haven't yet /// been emitted through this group will not be. /// /// If [stream]'s subscription is canceled, this returns /// [StreamSubscription.cancel]'s return value. Otherwise, it returns `null`. Future remove(Stream<T> stream) { var subscription = _subscriptions.remove(stream); var future = subscription == null ? null : subscription.cancel(); if (_closed && _subscriptions.isEmpty) _controller.close(); return future; } /// A callback called when [stream] is listened to. /// /// This is called for both single-subscription and broadcast groups. void _onListen() { _state = _StreamGroupState.listening; _subscriptions.forEach((stream, subscription) { // If this is a broadcast group and this isn't the first time it's been // listened to, there may still be some subscriptions to // single-subscription streams. if (subscription != null) return; _subscriptions[stream] = _listenToStream(stream); }); } /// A callback called when [stream] is paused. void _onPause() { _state = _StreamGroupState.paused; for (var subscription in _subscriptions.values) { subscription.pause(); } } /// A callback called when [stream] is resumed. void _onResume() { _state = _StreamGroupState.listening; for (var subscription in _subscriptions.values) { subscription.resume(); } } /// A callback called when [stream] is canceled. /// /// This is only called for single-subscription groups. Future _onCancel() { _state = _StreamGroupState.canceled; var futures = _subscriptions.values .map((subscription) => subscription.cancel()) .where((future) => future != null) .toList(); _subscriptions.clear(); return futures.isEmpty ? null : Future.wait(futures); } /// A callback called when [stream]'s last listener is canceled. /// /// This is only called for broadcast groups. void _onCancelBroadcast() { _state = _StreamGroupState.dormant; _subscriptions.forEach((stream, subscription) { // Cancel the broadcast streams, since we can re-listen to those later, // but allow the single-subscription streams to keep firing. Their events // will still be added to [_controller], but then they'll be dropped since // it has no listeners. if (!stream.isBroadcast) return; subscription.cancel(); _subscriptions[stream] = null; }); } /// Starts actively forwarding events from [stream] to [_controller]. /// /// This will pause the resulting subscription if [this] is paused. StreamSubscription<T> _listenToStream(Stream<T> stream) { var subscription = stream.listen(_controller.add, onError: _controller.addError, onDone: () => remove(stream)); if (_state == _StreamGroupState.paused) subscription.pause(); return subscription; } /// Closes the group, indicating that no more streams will be added. /// /// If there are no streams in the group, [stream] is closed immediately. /// Otherwise, [stream] will close once all streams in the group close. /// /// Returns a [Future] that completes once [stream] has actually been closed. @override Future close() { if (_closed) return _controller.done; _closed = true; if (_subscriptions.isEmpty) _controller.close(); return _controller.done; } } /// An enum of possible states of a [StreamGroup]. class _StreamGroupState { /// The group has no listeners. /// /// New streams added to the group will be listened once the group has a /// listener. static const dormant = _StreamGroupState('dormant'); /// The group has one or more listeners and is actively firing events. /// /// New streams added to the group will be immediately listeners. static const listening = _StreamGroupState('listening'); /// The group is paused and no more events will be fired until it resumes. /// /// New streams added to the group will be listened to, but then paused. They /// will be resumed once the group itself is resumed. /// /// This state is only used by single-subscriber groups. static const paused = _StreamGroupState('paused'); /// The group is canceled and no more events will be fired ever. /// /// New streams added to the group will be listened to, canceled, and /// discarded. /// /// This state is only used by single-subscriber groups. static const canceled = _StreamGroupState('canceled'); /// The name of the state. /// /// Used for debugging. final String name; const _StreamGroupState(this.name); @override String toString() => name; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/utils.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:async'; /// A generic typedef for a function that takes one type and returns another. typedef UnaryFunction<E, F> = F Function(E argument); /// A typedef for a function that takes no arguments and returns a Future or a /// value. typedef FutureOrCallback<T> = FutureOr<T> Function();
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/async_memoizer.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:async'; /// A class for running an asynchronous function exactly once and caching its /// result. /// /// An `AsyncMemoizer` is used when some function may be run multiple times in /// order to get its result, but it only actually needs to be run once for its /// effect. To memoize the result of an async function, you can create a /// memoizer outside the function (for example as an instance field if you want /// to memoize the result of a method), and then wrap the function's body in a /// call to [runOnce]. /// /// This is useful for methods like `close()` and getters that need to do /// asynchronous work. For example: /// /// ```dart /// class SomeResource { /// final _closeMemo = AsyncMemoizer(); /// /// Future close() => _closeMemo.runOnce(() { /// // ... /// }); /// } /// ``` class AsyncMemoizer<T> { /// The future containing the method's result. /// /// This can be accessed at any time, and will fire once [runOnce] is called. Future<T> get future => _completer.future; final _completer = Completer<T>(); /// Whether [runOnce] has been called yet. bool get hasRun => _completer.isCompleted; /// Runs the function, [computation], if it hasn't been run before. /// /// If [runOnce] has already been called, this returns the original result. Future<T> runOnce(FutureOr<T> Function() computation) { if (!hasRun) _completer.complete(Future.sync(computation)); return future; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/future_group.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:async'; /// A collection of futures waits until all added [Future]s complete. /// /// Futures are added to the group with [add]. Once you're finished adding /// futures, signal that by calling [close]. Then, once all added futures have /// completed, [future] will complete with a list of values from the futures in /// the group, in the order they were added. /// /// If any added future completes with an error, [future] will emit that error /// and the group will be closed, regardless of the state of other futures in /// the group. /// /// This is similar to [Future.wait] with `eagerError` set to `true`, except /// that a [FutureGroup] can have futures added gradually over time rather than /// needing them all at once. class FutureGroup<T> implements Sink<Future<T>> { /// The number of futures that have yet to complete. var _pending = 0; /// Whether [close] has been called. var _closed = false; /// The future that fires once [close] has been called and all futures in the /// group have completed. /// /// This will also complete with an error if any of the futures in the group /// fails, regardless of whether [close] was called. Future<List<T>> get future => _completer.future; final _completer = Completer<List<T>>(); /// Whether this group has no pending futures. bool get isIdle => _pending == 0; /// A broadcast stream that emits a `null` event whenever the last pending /// future in this group completes. /// /// Once this group isn't waiting on any futures *and* [close] has been /// called, this stream will close. Stream get onIdle => (_onIdleController ??= StreamController.broadcast(sync: true)).stream; StreamController _onIdleController; /// The values emitted by the futures that have been added to the group, in /// the order they were added. /// /// The slots for futures that haven't completed yet are `null`. final _values = <T>[]; /// Wait for [task] to complete. @override void add(Future<T> task) { if (_closed) throw StateError('The FutureGroup is closed.'); // Ensure that future values are put into [values] in the same order they're // added to the group by pre-allocating a slot for them and recording its // index. var index = _values.length; _values.add(null); _pending++; task.then((value) { if (_completer.isCompleted) return null; _pending--; _values[index] = value; if (_pending != 0) return null; if (_onIdleController != null) _onIdleController.add(null); if (!_closed) return null; if (_onIdleController != null) _onIdleController.close(); _completer.complete(_values); }).catchError((error, StackTrace stackTrace) { if (_completer.isCompleted) return null; _completer.completeError(error, stackTrace); }); } /// Signals to the group that the caller is done adding futures, and so /// [future] should fire once all added futures have completed. @override void close() { _closed = true; if (_pending != 0) return; if (_completer.isCompleted) return; _completer.complete(_values); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/stream_sink_transformer.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:async'; import 'stream_sink_transformer/handler_transformer.dart'; import 'stream_sink_transformer/stream_transformer_wrapper.dart'; import 'stream_sink_transformer/typed.dart'; /// A [StreamSinkTransformer] transforms the events being passed to a sink. /// /// This works on the same principle as a [StreamTransformer]. Each transformer /// defines a [bind] method that takes in the original [StreamSink] and returns /// the transformed version. However, where a [StreamTransformer] transforms /// events after they leave the stream, this transforms them before they enter /// the sink. /// /// Transformers must be able to have `bind` called used multiple times. abstract class StreamSinkTransformer<S, T> { /// Creates a [StreamSinkTransformer] that transforms events and errors /// using [transformer]. /// /// This is equivalent to piping all events from the outer sink through a /// stream transformed by [transformer] and from there into the inner sink. const factory StreamSinkTransformer.fromStreamTransformer( StreamTransformer<S, T> transformer) = StreamTransformerWrapper<S, T>; /// Creates a [StreamSinkTransformer] that delegates events to the given /// handlers. /// /// The handlers work exactly as they do for [StreamTransformer.fromHandlers]. /// They're called for each incoming event, and any actions on the sink /// they're passed are forwarded to the inner sink. If a handler is omitted, /// the event is passed through unaltered. factory StreamSinkTransformer.fromHandlers( {void Function(S, EventSink<T>) handleData, void Function(Object, StackTrace, EventSink<T>) handleError, void Function(EventSink<T>) handleDone}) { return HandlerTransformer<S, T>(handleData, handleError, handleDone); } /// Transforms the events passed to [sink]. /// /// Creates a new sink. When events are passed to the returned sink, it will /// transform them and pass the transformed versions to [sink]. StreamSink<S> bind(StreamSink<T> sink); /// Creates a wrapper that coerces the type of [transformer]. /// /// This soundly converts a [StreamSinkTransformer] to a /// `StreamSinkTransformer<S, T>`, regardless of its original generic type. /// This means that calls to [StreamSink.add] on the returned sink may throw a /// [CastError] if the argument type doesn't match the reified type of the /// sink. @deprecated // TODO remove TypeSafeStreamSinkTransformer static StreamSinkTransformer<S, T> typed<S, T>( StreamSinkTransformer transformer) => transformer is StreamSinkTransformer<S, T> ? transformer : TypeSafeStreamSinkTransformer(transformer); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/null_stream_sink.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:async'; /// A [StreamSink] that discards all events. /// /// The sink silently drops events until [close] is called, at which point it /// throws [StateError]s when events are added. This is the same behavior as a /// sink whose remote end has closed, such as when a [WebSocket] connection has /// been closed. /// /// This can be used when a sink is needed but no events are actually intended /// to be added. The [NullStreamSink.error] constructor can be used to /// represent errors when creating a sink, since [StreamSink.done] exposes sink /// errors. For example: /// /// ```dart /// StreamSink<List<int>> openForWrite(String filename) { /// try { /// return RandomAccessSink(File(filename).openSync()); /// } on IOException catch (error, stackTrace) { /// return NullStreamSink.error(error, stackTrace); /// } /// } /// ``` class NullStreamSink<T> implements StreamSink<T> { @override final Future done; /// Whether the sink has been closed. var _closed = false; /// Whether an [addStream] call is pending. /// /// We don't actually add any events from streams, but it does return the /// [StreamSubscription.cancel] future so to be [StreamSink]-complaint we /// reject events until that completes. var _addingStream = false; /// Creates a null sink. /// /// If [done] is passed, it's used as the [Sink.done] future. Otherwise, a /// completed future is used. NullStreamSink({Future done}) : done = done ?? Future.value(); /// Creates a null sink whose [done] future emits [error]. /// /// Note that this error will not be considered uncaught. NullStreamSink.error(error, [StackTrace stackTrace]) : done = Future.error(error, stackTrace) // Don't top-level the error. This gives the user a change to call // [close] or [done], and matches the behavior of a remote endpoint // experiencing an error. ..catchError((_) {}); @override void add(T data) { _checkEventAllowed(); } @override void addError(error, [StackTrace stackTrace]) { _checkEventAllowed(); } @override Future addStream(Stream<T> stream) { _checkEventAllowed(); _addingStream = true; var future = stream.listen(null).cancel() ?? Future.value(); return future.whenComplete(() { _addingStream = false; }); } /// Throws a [StateError] if [close] has been called or an [addStream] call is /// pending. void _checkEventAllowed() { if (_closed) throw StateError('Cannot add to a closed sink.'); if (_addingStream) { throw StateError('Cannot add to a sink while adding a stream.'); } } @override Future close() { _closed = true; return done; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/stream_zip.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:async'; /// A stream that combines the values of other streams. /// /// This emits lists of collected values from each input stream. The first list /// contains the first value emitted by each stream, the second contains the /// second value, and so on. The lists have the same ordering as the iterable /// passed to [new StreamZip]. /// /// Any errors from any of the streams are forwarded directly to this stream. class StreamZip<T> extends Stream<List<T>> { final Iterable<Stream<T>> _streams; StreamZip(Iterable<Stream<T>> streams) : _streams = streams; @override StreamSubscription<List<T>> listen(void Function(List<T>) onData, {Function onError, void Function() onDone, bool cancelOnError}) { cancelOnError = identical(true, cancelOnError); var subscriptions = <StreamSubscription<T>>[]; StreamController<List<T>> controller; List<T> current; var dataCount = 0; /// Called for each data from a subscription in [subscriptions]. void handleData(int index, T data) { current[index] = data; dataCount++; if (dataCount == subscriptions.length) { var data = current; current = List(subscriptions.length); dataCount = 0; for (var i = 0; i < subscriptions.length; i++) { if (i != index) subscriptions[i].resume(); } controller.add(data); } else { subscriptions[index].pause(); } } /// Called for each error from a subscription in [subscriptions]. /// Except if [cancelOnError] is true, in which case the function below /// is used instead. void handleError(Object error, StackTrace stackTrace) { controller.addError(error, stackTrace); } /// Called when a subscription has an error and [cancelOnError] is true. /// /// Prematurely cancels all subscriptions since we know that we won't /// be needing any more values. void handleErrorCancel(Object error, StackTrace stackTrace) { for (var i = 0; i < subscriptions.length; i++) { subscriptions[i].cancel(); } controller.addError(error, stackTrace); } void handleDone() { for (var i = 0; i < subscriptions.length; i++) { subscriptions[i].cancel(); } controller.close(); } try { for (var stream in _streams) { var index = subscriptions.length; subscriptions.add(stream.listen((data) { handleData(index, data); }, onError: cancelOnError ? handleError : handleErrorCancel, onDone: handleDone, cancelOnError: cancelOnError)); } } catch (e) { for (var i = subscriptions.length - 1; i >= 0; i--) { subscriptions[i].cancel(); } rethrow; } current = List(subscriptions.length); controller = StreamController<List<T>>(onPause: () { for (var i = 0; i < subscriptions.length; i++) { // This may pause some subscriptions more than once. // These will not be resumed by onResume below, but must wait for the // next round. subscriptions[i].pause(); } }, onResume: () { for (var i = 0; i < subscriptions.length; i++) { subscriptions[i].resume(); } }, onCancel: () { for (var i = 0; i < subscriptions.length; i++) { // Canceling more than once is safe. subscriptions[i].cancel(); } }); if (subscriptions.isEmpty) { controller.close(); } return controller.stream.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/stream_subscription_transformer.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:async'; import 'async_memoizer.dart'; typedef _AsyncHandler<T> = Future Function(StreamSubscription<T> inner); typedef _VoidHandler<T> = void Function(StreamSubscription<T> inner); /// Creates a [StreamTransformer] that modifies the behavior of subscriptions to /// a stream. /// /// When [StreamSubscription.cancel], [StreamSubscription.pause], or /// [StreamSubscription.resume] is called, the corresponding handler is invoked. /// By default, handlers just forward to the underlying subscription. /// /// Guarantees that none of the [StreamSubscription] callbacks and none of the /// callbacks passed to `subscriptionTransformer()` will be invoked once the /// transformed [StreamSubscription] has been canceled and `handleCancel()` has /// run. The [handlePause] and [handleResume] are invoked regardless of whether /// the subscription is paused already or not. /// /// In order to preserve [StreamSubscription] guarantees, **all callbacks must /// synchronously call the corresponding method** on the inner /// [StreamSubscription]: [handleCancel] must call `cancel()`, [handlePause] /// must call `pause()`, and [handleResume] must call `resume()`. StreamTransformer<T, T> subscriptionTransformer<T>( {Future Function(StreamSubscription<T>) handleCancel, void Function(StreamSubscription<T>) handlePause, void Function(StreamSubscription<T>) handleResume}) { return StreamTransformer((stream, cancelOnError) { return _TransformedSubscription( stream.listen(null, cancelOnError: cancelOnError), handleCancel ?? (inner) => inner.cancel(), handlePause ?? (inner) { inner.pause(); }, handleResume ?? (inner) { inner.resume(); }); }); } /// A [StreamSubscription] wrapper that calls callbacks for subscription /// methods. class _TransformedSubscription<T> implements StreamSubscription<T> { /// The wrapped subscription. StreamSubscription<T> _inner; /// The callback to run when [cancel] is called. final _AsyncHandler<T> _handleCancel; /// The callback to run when [pause] is called. final _VoidHandler<T> _handlePause; /// The callback to run when [resume] is called. final _VoidHandler<T> _handleResume; @override bool get isPaused => _inner?.isPaused ?? false; _TransformedSubscription( this._inner, this._handleCancel, this._handlePause, this._handleResume); @override void onData(void Function(T) handleData) { _inner?.onData(handleData); } @override void onError(Function handleError) { _inner?.onError(handleError); } @override void onDone(void Function() handleDone) { _inner?.onDone(handleDone); } @override Future cancel() => _cancelMemoizer.runOnce(() { var inner = _inner; _inner.onData(null); _inner.onDone(null); // Setting onError to null will cause errors to be top-leveled. _inner.onError((_, __) {}); _inner = null; return _handleCancel(inner); }); final _cancelMemoizer = AsyncMemoizer(); @override void pause([Future resumeFuture]) { if (_cancelMemoizer.hasRun) return; if (resumeFuture != null) resumeFuture.whenComplete(resume); _handlePause(_inner); } @override void resume() { if (_cancelMemoizer.hasRun) return; _handleResume(_inner); } @override Future<E> asFuture<E>([E futureValue]) => _inner?.asFuture(futureValue) ?? Completer<E>().future; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/async_cache.dart
// Copyright (c) 2017, 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 'package:async/async.dart'; /// Runs asynchronous functions and caches the result for a period of time. /// /// This class exists to cover the pattern of having potentially expensive code /// such as file I/O, network access, or isolate computation that's unlikely to /// change quickly run fewer times. For example: /// /// ```dart /// final _usersCache = new AsyncCache<List<String>>(const Duration(hours: 1)); /// /// /// Uses the cache if it exists, otherwise calls the closure: /// Future<List<String>> get onlineUsers => _usersCache.fetch(() { /// // Actually fetch online users here. /// }); /// ``` /// /// This class's timing can be mocked using [`fake_async`][fake_async]. /// /// [fake_async]: https://pub.dev/packages/fake_async class AsyncCache<T> { /// How long cached values stay fresh. final Duration _duration; /// Cached results of a previous [fetchStream] call. StreamSplitter<T> _cachedStreamSplitter; /// Cached results of a previous [fetch] call. Future<T> _cachedValueFuture; /// Fires when the cache should be considered stale. Timer _stale; /// Creates a cache that invalidates its contents after [duration] has passed. /// /// The [duration] starts counting after the Future returned by [fetch] /// completes, or after the Stream returned by [fetchStream] emits a done /// event. AsyncCache(this._duration); /// Creates a cache that invalidates after an in-flight request is complete. /// /// An ephemeral cache guarantees that a callback function will only be /// executed at most once concurrently. This is useful for requests for which /// data is updated frequently but stale data is acceptable. factory AsyncCache.ephemeral() => AsyncCache(Duration.zero); /// Returns a cached value from a previous call to [fetch], or runs [callback] /// to compute a new one. /// /// If [fetch] has been called recently enough, returns its previous return /// value. Otherwise, runs [callback] and returns its new return value. Future<T> fetch(Future<T> Function() callback) async { if (_cachedStreamSplitter != null) { throw StateError('Previously used to cache via `fetchStream`'); } if (_cachedValueFuture == null) { _cachedValueFuture = callback(); await _cachedValueFuture; _startStaleTimer(); } return _cachedValueFuture; } /// Returns a cached stream from a previous call to [fetchStream], or runs /// [callback] to compute a new stream. /// /// If [fetchStream] has been called recently enough, returns a copy of its /// previous return value. Otherwise, runs [callback] and returns its new /// return value. Stream<T> fetchStream(Stream<T> Function() callback) { if (_cachedValueFuture != null) { throw StateError('Previously used to cache via `fetch`'); } _cachedStreamSplitter ??= StreamSplitter( callback().transform(StreamTransformer.fromHandlers(handleDone: (sink) { _startStaleTimer(); sink.close(); }))); return _cachedStreamSplitter.split(); } /// Removes any cached value. void invalidate() { // TODO: This does not return a future, but probably should. _cachedValueFuture = null; // TODO: This does not await, but probably should. _cachedStreamSplitter?.close(); _cachedStreamSplitter = null; _stale?.cancel(); _stale = null; } void _startStaleTimer() { _stale = Timer(_duration, invalidate); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/stream_completer.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:async'; /// A single-subscription [stream] where the contents are provided later. /// /// It is generally recommended that you never create a `Future<Stream>` /// because you can just directly create a stream that doesn't do anything /// until it's ready to do so. /// This class can be used to create such a stream. /// /// The [stream] is a normal stream that you can listen to immediately, /// but until either [setSourceStream] or [setEmpty] is called, /// the stream won't produce any events. /// /// The same effect can be achieved by using a [StreamController] /// and adding the stream using `addStream` when both /// the controller's stream is listened to and the source stream is ready. /// This class attempts to shortcut some of the overhead when possible. /// For example, if the [stream] is only listened to /// after the source stream has been set, /// the listen is performed directly on the source stream. class StreamCompleter<T> { /// The stream doing the actual work, is returned by [stream]. final _stream = _CompleterStream<T>(); /// Convert a `Future<Stream>` to a `Stream`. /// /// This creates a stream using a stream completer, /// and sets the source stream to the result of the future when the /// future completes. /// /// If the future completes with an error, the returned stream will /// instead contain just that error. static Stream<T> fromFuture<T>(Future<Stream<T>> streamFuture) { var completer = StreamCompleter<T>(); streamFuture.then(completer.setSourceStream, onError: completer.setError); return completer.stream; } /// The stream of this completer. /// /// This stream is always a single-subscription stream. /// /// When a source stream is provided, its events will be forwarded to /// listeners on this stream. /// /// The stream can be listened either before or after a source stream /// is set. Stream<T> get stream => _stream; /// Set a stream as the source of events for the [StreamCompleter]'s /// [stream]. /// /// The completer's `stream` will act exactly as [sourceStream]. /// /// If the source stream is set before [stream] is listened to, /// the listen call on [stream] is forwarded directly to [sourceStream]. /// /// If [stream] is listened to before setting the source stream, /// an intermediate subscription is created. It looks like a completely /// normal subscription, and can be paused or canceled, but it won't /// produce any events until a source stream is provided. /// /// If the `stream` subscription is canceled before a source stream is set, /// the source stream will be listened to and immediately canceled again. /// /// Otherwise, when the source stream is then set, /// it is immediately listened to, and its events are forwarded to the /// existing subscription. /// /// Any one of [setSourceStream], [setEmpty], and [setError] may be called at /// most once. Trying to call any of them again will fail. void setSourceStream(Stream<T> sourceStream) { if (_stream._isSourceStreamSet) { throw StateError('Source stream already set'); } _stream._setSourceStream(sourceStream); } /// Equivalent to setting an empty stream using [setSourceStream]. /// /// Any one of [setSourceStream], [setEmpty], and [setError] may be called at /// most once. Trying to call any of them again will fail. void setEmpty() { if (_stream._isSourceStreamSet) { throw StateError('Source stream already set'); } _stream._setEmpty(); } /// Completes this to a stream that emits [error] and then closes. /// /// This is useful when the process of creating the data for the stream fails. /// /// Any one of [setSourceStream], [setEmpty], and [setError] may be called at /// most once. Trying to call any of them again will fail. void setError(error, [StackTrace stackTrace]) { setSourceStream(Stream.fromFuture(Future.error(error, stackTrace))); } } /// Stream completed by [StreamCompleter]. class _CompleterStream<T> extends Stream<T> { /// Controller for an intermediate stream. /// /// Created if the user listens on this stream before the source stream /// is set, or if using [_setEmpty] so there is no source stream. StreamController<T> _controller; /// Source stream for the events provided by this stream. /// /// Set when the completer sets the source stream using [_setSourceStream] /// or [_setEmpty]. Stream<T> _sourceStream; @override StreamSubscription<T> listen(void Function(T) onData, {Function onError, void Function() onDone, bool cancelOnError}) { if (_controller == null) { if (_sourceStream != null && !_sourceStream.isBroadcast) { // If the source stream is itself single subscription, // just listen to it directly instead of creating a controller. return _sourceStream.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); } _createController(); if (_sourceStream != null) { _linkStreamToController(); } } return _controller.stream.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError); } /// Whether a source stream has been set. /// /// Used to throw an error if trying to set a source stream twice. bool get _isSourceStreamSet => _sourceStream != null; /// Sets the source stream providing the events for this stream. /// /// If set before the user listens, listen calls will be directed directly /// to the source stream. If the user listenes earlier, and intermediate /// stream is created using a stream controller, and the source stream is /// linked into that stream later. void _setSourceStream(Stream<T> sourceStream) { assert(_sourceStream == null); _sourceStream = sourceStream; if (_controller != null) { // User has already listened, so provide the data through controller. _linkStreamToController(); } } /// Links source stream to controller when both are available. void _linkStreamToController() { assert(_controller != null); assert(_sourceStream != null); _controller .addStream(_sourceStream, cancelOnError: false) .whenComplete(_controller.close); } /// Sets an empty source stream. /// /// Uses [_controller] for the stream, then closes the controller /// immediately. void _setEmpty() { assert(_sourceStream == null); if (_controller == null) { _createController(); } _sourceStream = _controller.stream; // Mark stream as set. _controller.close(); } // Creates the [_controller]. void _createController() { assert(_controller == null); _controller = StreamController<T>(sync: true); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/delegate/future.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:async'; /// A wrapper that forwards calls to a [Future]. class DelegatingFuture<T> implements Future<T> { /// The wrapped [Future]. final Future<T> _future; DelegatingFuture(this._future); /// Creates a wrapper which throws if [future]'s value isn't an instance of /// `T`. /// /// This soundly converts a [Future] to a `Future<T>`, regardless of its /// original generic type, by asserting that its value is an instance of `T` /// whenever it's provided. If it's not, the future throws a [CastError]. @Deprecated('Use future.then((v) => v as T) instead.') static Future<T> typed<T>(Future future) => future is Future<T> ? future : future.then((v) => v as T); @override Stream<T> asStream() => _future.asStream(); @override Future<T> catchError(Function onError, {bool Function(Object error) test}) => _future.catchError(onError, test: test); @override Future<S> then<S>(FutureOr<S> Function(T) onValue, {Function onError}) => _future.then(onValue, onError: onError); @override Future<T> whenComplete(FutureOr Function() action) => _future.whenComplete(action); @override Future<T> timeout(Duration timeLimit, {FutureOr<T> Function() onTimeout}) => _future.timeout(timeLimit, onTimeout: onTimeout); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/delegate/stream.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:async'; /// Simple delegating wrapper around a [Stream]. /// /// Subclasses can override individual methods, or use this to expose only the /// [Stream] methods of a subclass. /// /// Note that this is identical to [StreamView] in `dart:async`. It's provided /// under this name for consistency with other `Delegating*` classes. class DelegatingStream<T> extends StreamView<T> { DelegatingStream(Stream<T> stream) : super(stream); /// Creates a wrapper which throws if [stream]'s events aren't instances of /// `T`. /// /// This soundly converts a [Stream] to a `Stream<T>`, regardless of its /// original generic type, by asserting that its events are instances of `T` /// whenever they're provided. If they're not, the stream throws a /// [CastError]. @Deprecated('Use stream.cast instead') static Stream<T> typed<T>(Stream stream) => stream.cast(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/delegate/stream_subscription.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:async'; import '../typed/stream_subscription.dart'; /// Simple delegating wrapper around a [StreamSubscription]. /// /// Subclasses can override individual methods. class DelegatingStreamSubscription<T> implements StreamSubscription<T> { final StreamSubscription<T> _source; /// Create delegating subscription forwarding calls to [sourceSubscription]. DelegatingStreamSubscription(StreamSubscription<T> sourceSubscription) : _source = sourceSubscription; /// Creates a wrapper which throws if [subscription]'s events aren't instances /// of `T`. /// /// This soundly converts a [StreamSubscription] to a `StreamSubscription<T>`, /// regardless of its original generic type, by asserting that its events are /// instances of `T` whenever they're provided. If they're not, the /// subscription throws a [CastError]. @Deprecated('Use Stream.cast instead') // TODO - Remove `TypeSafeStreamSubscription` and tests when removing this. static StreamSubscription<T> typed<T>(StreamSubscription subscription) => subscription is StreamSubscription<T> ? subscription : TypeSafeStreamSubscription<T>(subscription); @override void onData(void Function(T) handleData) { _source.onData(handleData); } @override void onError(Function handleError) { _source.onError(handleError); } @override void onDone(void Function() handleDone) { _source.onDone(handleDone); } @override void pause([Future resumeFuture]) { _source.pause(resumeFuture); } @override void resume() { _source.resume(); } @override Future cancel() => _source.cancel(); @override Future<E> asFuture<E>([E futureValue]) => _source.asFuture(futureValue); @override bool get isPaused => _source.isPaused; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/delegate/sink.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. /// Simple delegating wrapper around a [Sink]. /// /// Subclasses can override individual methods, or use this to expose only the /// [Sink] methods of a subclass. class DelegatingSink<T> implements Sink<T> { final Sink _sink; /// Create a delegating sink forwarding calls to [sink]. DelegatingSink(Sink<T> sink) : _sink = sink; DelegatingSink._(this._sink); /// Creates a wrapper that coerces the type of [sink]. /// /// Unlike [new DelegatingSink], this only requires its argument to be an /// instance of `Sink`, not `Sink<T>`. This means that calls to [add] may /// throw a [CastError] if the argument type doesn't match the reified type of /// [sink]. @Deprecated( 'Use StreamController<T>(sync: true)..stream.cast<S>().pipe(sink)') static Sink<T> typed<T>(Sink sink) => sink is Sink<T> ? sink : DelegatingSink._(sink); @override void add(T data) { _sink.add(data); } @override void close() { _sink.close(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/delegate/stream_sink.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:async'; /// Simple delegating wrapper around a [StreamSink]. /// /// Subclasses can override individual methods, or use this to expose only the /// [StreamSink] methods of a subclass. class DelegatingStreamSink<T> implements StreamSink<T> { final StreamSink _sink; @override Future get done => _sink.done; /// Create delegating sink forwarding calls to [sink]. DelegatingStreamSink(StreamSink<T> sink) : _sink = sink; DelegatingStreamSink._(this._sink); /// Creates a wrapper that coerces the type of [sink]. /// /// Unlike [new StreamSink], this only requires its argument to be an instance /// of `StreamSink`, not `StreamSink<T>`. This means that calls to [add] may /// throw a [CastError] if the argument type doesn't match the reified type of /// [sink]. @Deprecated( 'Use StreamController<T>(sync: true)..stream.cast<S>().pipe(sink)') static StreamSink<T> typed<T>(StreamSink sink) => sink is StreamSink<T> ? sink : DelegatingStreamSink._(sink); @override void add(T data) { _sink.add(data); } @override void addError(error, [StackTrace stackTrace]) { _sink.addError(error, stackTrace); } @override Future addStream(Stream<T> stream) => _sink.addStream(stream); @override Future close() => _sink.close(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/delegate/stream_consumer.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:async'; /// Simple delegating wrapper around a [StreamConsumer]. /// /// Subclasses can override individual methods, or use this to expose only the /// [StreamConsumer] methods of a subclass. class DelegatingStreamConsumer<T> implements StreamConsumer<T> { final StreamConsumer _consumer; /// Create a delegating consumer forwarding calls to [consumer]. DelegatingStreamConsumer(StreamConsumer<T> consumer) : _consumer = consumer; DelegatingStreamConsumer._(this._consumer); /// Creates a wrapper that coerces the type of [consumer]. /// /// Unlike [new StreamConsumer], this only requires its argument to be an /// instance of `StreamConsumer`, not `StreamConsumer<T>`. This means that /// calls to [addStream] may throw a [CastError] if the argument type doesn't /// match the reified type of [consumer]. @Deprecated( 'Use StreamController<T>(sync: true)..stream.cast<S>().pipe(sink)') static StreamConsumer<T> typed<T>(StreamConsumer consumer) => consumer is StreamConsumer<T> ? consumer : DelegatingStreamConsumer._(consumer); @override Future addStream(Stream<T> stream) => _consumer.addStream(stream); @override Future close() => _consumer.close(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/delegate/event_sink.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:async'; /// Simple delegating wrapper around an [EventSink]. /// /// Subclasses can override individual methods, or use this to expose only the /// [EventSink] methods of a subclass. class DelegatingEventSink<T> implements EventSink<T> { final EventSink _sink; /// Create a delegating sink forwarding calls to [sink]. DelegatingEventSink(EventSink<T> sink) : _sink = sink; DelegatingEventSink._(this._sink); /// Creates a wrapper that coerces the type of [sink]. /// /// Unlike [new DelegatingEventSink], this only requires its argument to be an /// instance of `EventSink`, not `EventSink<T>`. This means that calls to /// [add] may throw a [CastError] if the argument type doesn't match the /// reified type of [sink]. @Deprecated( 'Use StreamController<T>(sync: true)..stream.cast<S>().pipe(sink)') static EventSink<T> typed<T>(EventSink sink) => sink is EventSink<T> ? sink : DelegatingEventSink._(sink); @override void add(T data) { _sink.add(data); } @override void addError(error, [StackTrace stackTrace]) { _sink.addError(error, stackTrace); } @override void close() { _sink.close(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/typed/stream_subscription.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:async'; class TypeSafeStreamSubscription<T> implements StreamSubscription<T> { final StreamSubscription _subscription; @override bool get isPaused => _subscription.isPaused; TypeSafeStreamSubscription(this._subscription); @override void onData(void Function(T) handleData) { _subscription.onData((data) => handleData(data as T)); } @override void onError(Function handleError) { _subscription.onError(handleError); } @override void onDone(void Function() handleDone) { _subscription.onDone(handleDone); } @override void pause([Future resumeFuture]) { _subscription.pause(resumeFuture); } @override void resume() { _subscription.resume(); } @override Future cancel() => _subscription.cancel(); @override Future<E> asFuture<E>([E futureValue]) => _subscription.asFuture(futureValue); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/stream_sink_transformer/typed.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:async'; import '../stream_sink_transformer.dart'; /// A wrapper that coerces the generic type of the sink returned by an inner /// transformer to `S`. class TypeSafeStreamSinkTransformer<S, T> implements StreamSinkTransformer<S, T> { final StreamSinkTransformer _inner; TypeSafeStreamSinkTransformer(this._inner); @override StreamSink<S> bind(StreamSink<T> sink) => StreamController(sync: true) ..stream.cast<dynamic>().pipe(_inner.bind(sink)); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/stream_sink_transformer/handler_transformer.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:async'; import '../stream_sink_transformer.dart'; import '../delegate/stream_sink.dart'; /// The type of the callback for handling data events. typedef HandleData<S, T> = void Function(S data, EventSink<T> sink); /// The type of the callback for handling error events. typedef HandleError<T> = void Function( Object error, StackTrace stackTrace, EventSink<T> sink); /// The type of the callback for handling done events. typedef HandleDone<T> = void Function(EventSink<T> sink); /// A [StreamSinkTransformer] that delegates events to the given handlers. class HandlerTransformer<S, T> implements StreamSinkTransformer<S, T> { /// The handler for data events. final HandleData<S, T> _handleData; /// The handler for error events. final HandleError<T> _handleError; /// The handler for done events. final HandleDone<T> _handleDone; HandlerTransformer(this._handleData, this._handleError, this._handleDone); @override StreamSink<S> bind(StreamSink<T> sink) => _HandlerSink<S, T>(this, sink); } /// A sink created by [HandlerTransformer]. class _HandlerSink<S, T> implements StreamSink<S> { /// The transformer that created this sink. final HandlerTransformer<S, T> _transformer; /// The original sink that's being transformed. final StreamSink<T> _inner; /// The wrapper for [_inner] whose [StreamSink.close] method can't emit /// errors. final StreamSink<T> _safeCloseInner; @override Future get done => _inner.done; _HandlerSink(this._transformer, StreamSink<T> inner) : _inner = inner, _safeCloseInner = _SafeCloseSink<T>(inner); @override void add(S event) { if (_transformer._handleData == null) { _inner.add(event as T); } else { _transformer._handleData(event, _safeCloseInner); } } @override void addError(error, [StackTrace stackTrace]) { if (_transformer._handleError == null) { _inner.addError(error, stackTrace); } else { _transformer._handleError(error, stackTrace, _safeCloseInner); } } @override Future addStream(Stream<S> stream) { return _inner.addStream(stream.transform( StreamTransformer<S, T>.fromHandlers( handleData: _transformer._handleData, handleError: _transformer._handleError, handleDone: _closeSink))); } @override Future close() { if (_transformer._handleDone == null) return _inner.close(); _transformer._handleDone(_safeCloseInner); return _inner.done; } } /// A wrapper for [StreamSink]s that swallows any errors returned by [close]. /// /// [HandlerTransformer] passes this to its handlers to ensure that when they /// call [close], they don't leave any dangling [Future]s behind that might emit /// unhandleable errors. class _SafeCloseSink<T> extends DelegatingStreamSink<T> { _SafeCloseSink(StreamSink<T> inner) : super(inner); @override Future close() => super.close().catchError((_) {}); } /// A function to pass as a [StreamTransformer]'s `handleDone` callback. void _closeSink(EventSink sink) { sink.close(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/stream_sink_transformer/stream_transformer_wrapper.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:async'; import '../stream_sink_transformer.dart'; /// A [StreamSinkTransformer] that wraps a pre-existing [StreamTransformer]. class StreamTransformerWrapper<S, T> implements StreamSinkTransformer<S, T> { /// The wrapped transformer. final StreamTransformer<S, T> _transformer; const StreamTransformerWrapper(this._transformer); @override StreamSink<S> bind(StreamSink<T> sink) => _StreamTransformerWrapperSink<S, T>(_transformer, sink); } /// A sink created by [StreamTransformerWrapper]. class _StreamTransformerWrapperSink<S, T> implements StreamSink<S> { /// The controller through which events are passed. /// /// This is used to create a stream that can be transformed by the wrapped /// transformer. final _controller = StreamController<S>(sync: true); /// The original sink that's being transformed. final StreamSink<T> _inner; @override Future get done => _inner.done; _StreamTransformerWrapperSink( StreamTransformer<S, T> transformer, this._inner) { _controller.stream .transform(transformer) .listen(_inner.add, onError: _inner.addError, onDone: () { // Ignore any errors that come from this call to [_inner.close]. The // user can access them through [done] or the value returned from // [this.close], and we don't want them to get top-leveled. _inner.close().catchError((_) {}); }); } @override void add(S event) { _controller.add(event); } @override void addError(error, [StackTrace stackTrace]) { _controller.addError(error, stackTrace); } @override Future addStream(Stream<S> stream) => _controller.addStream(stream); @override Future close() { _controller.close(); return _inner.done; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/result/future.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:async'; import '../delegate/future.dart'; import 'result.dart'; /// A [Future] wrapper that provides synchronous access to the result of the /// wrapped [Future] once it's completed. class ResultFuture<T> extends DelegatingFuture<T> { /// Whether the future has fired and [result] is available. bool get isComplete => result != null; /// The result of the wrapped [Future], if it's completed. /// /// If it hasn't completed yet, this will be `null`. Result<T> get result => _result; Result<T> _result; ResultFuture(Future<T> future) : super(future) { Result.capture(future).then((result) { _result = result; }); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/result/result.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:async'; import 'capture_sink.dart'; import 'capture_transformer.dart'; import 'error.dart'; import 'release_sink.dart'; import 'release_transformer.dart'; import 'value.dart'; import '../stream_sink_transformer.dart'; /// The result of a computation. /// /// Capturing a result (either a returned value or a thrown error) means /// converting it into a [Result] - either a [ValueResult] or an [ErrorResult]. /// /// This value can release itself by writing itself either to a [EventSink] or a /// [Completer], or by becoming a [Future]. /// /// A [Future] represents a potential result, one that might not have been /// computed yet, and a [Result] is always a completed and available result. abstract class Result<T> { /// A stream transformer that captures a stream of events into [Result]s. /// /// The result of the transformation is a stream of [Result] values and no /// error events. This is the transformer used by [captureStream]. static const StreamTransformer<Object, Result<Object>> captureStreamTransformer = CaptureStreamTransformer<Object>(); /// A stream transformer that releases a stream of result events. /// /// The result of the transformation is a stream of values and error events. /// This is the transformer used by [releaseStream]. static const StreamTransformer<Result<Object>, Object> releaseStreamTransformer = ReleaseStreamTransformer<Object>(); /// A sink transformer that captures events into [Result]s. /// /// The result of the transformation is a sink that only forwards [Result] /// values and no error events. static const StreamSinkTransformer<Object, Result<Object>> captureSinkTransformer = StreamSinkTransformer<Object, Result<Object>>.fromStreamTransformer( CaptureStreamTransformer<Object>()); /// A sink transformer that releases result events. /// /// The result of the transformation is a sink that forwards of values and /// error events. static const StreamSinkTransformer<Result<Object>, Object> releaseSinkTransformer = StreamSinkTransformer<Result<Object>, Object>.fromStreamTransformer( ReleaseStreamTransformer<Object>()); /// Creates a `Result` with the result of calling [computation]. /// /// This generates either a [ValueResult] with the value returned by /// calling `computation`, or an [ErrorResult] with an error thrown by /// the call. factory Result(T Function() computation) { try { return ValueResult<T>(computation()); } catch (e, s) { return ErrorResult(e, s); } } /// Creates a `Result` holding a value. /// /// Alias for [ValueResult.ValueResult]. factory Result.value(T value) = ValueResult<T>; /// Creates a `Result` holding an error. /// /// Alias for [ErrorResult.ErrorResult]. factory Result.error(Object error, [StackTrace stackTrace]) => ErrorResult(error, stackTrace); /// Captures the result of a future into a `Result` future. /// /// The resulting future will never have an error. /// Errors have been converted to an [ErrorResult] value. static Future<Result<T>> capture<T>(Future<T> future) { return future.then((value) => ValueResult(value), onError: (error, StackTrace stackTrace) => ErrorResult(error, stackTrace)); } /// Captures each future in [elements], /// /// Returns a (future of) a list of results for each element in [elements], /// in iteration order. /// Each future in [elements] is [capture]d and each non-future is /// wrapped as a [Result.value]. /// The returned future will never have an error. static Future<List<Result<T>>> captureAll<T>(Iterable<FutureOr<T>> elements) { var results = <Result<T>>[]; var pending = 0; Completer<List<Result<T>>> completer; for (var element in elements) { if (element is Future<T>) { var i = results.length; results.add(null); pending++; Result.capture<T>(element).then((result) { results[i] = result; if (--pending == 0) { completer.complete(results); } }); } else { results.add(Result<T>.value(element as T)); } } if (pending == 0) { return Future<List<Result<T>>>.value(results); } completer = Completer<List<Result<T>>>(); return completer.future; } /// Releases the result of a captured future. /// /// Converts the [Result] value of the given [future] to a value or error /// completion of the returned future. /// /// If [future] completes with an error, the returned future completes with /// the same error. static Future<T> release<T>(Future<Result<T>> future) => future.then<T>((result) => result.asFuture); /// Captures the results of a stream into a stream of [Result] values. /// /// The returned stream will not have any error events. /// Errors from the source stream have been converted to [ErrorResult]s. static Stream<Result<T>> captureStream<T>(Stream<T> source) => source.transform(CaptureStreamTransformer<T>()); /// Releases a stream of [result] values into a stream of the results. /// /// `Result` values of the source stream become value or error events in /// the returned stream as appropriate. /// Errors from the source stream become errors in the returned stream. static Stream<T> releaseStream<T>(Stream<Result<T>> source) => source.transform(ReleaseStreamTransformer<T>()); /// Releases results added to the returned sink as data and errors on [sink]. /// /// A [Result] added to the returned sink is added as a data or error event /// on [sink]. Errors added to the returned sink are forwarded directly to /// [sink] and so is the [EventSink.close] calls. static EventSink<Result<T>> releaseSink<T>(EventSink<T> sink) => ReleaseSink<T>(sink); /// Captures the events of the returned sink into results on [sink]. /// /// Data and error events added to the returned sink are captured into /// [Result] values and added as data events on the provided [sink]. /// No error events are ever added to [sink]. /// /// When the returned sink is closed, so is [sink]. static EventSink<T> captureSink<T>(EventSink<Result<T>> sink) => CaptureSink<T>(sink); /// Converts a result of a result to a single result. /// /// If the result is an error, or it is a `Result` value /// which is then an error, then a result with that error is returned. /// Otherwise both levels of results are value results, and a single /// result with the value is returned. static Result<T> flatten<T>(Result<Result<T>> result) { if (result.isValue) return result.asValue.value; return result.asError; } /// Converts a sequence of results to a result of a list. /// /// Returns either a list of values if [results] doesn't contain any errors, /// or the first error result in [results]. static Result<List<T>> flattenAll<T>(Iterable<Result<T>> results) { var values = <T>[]; for (var result in results) { if (result.isValue) { values.add(result.asValue.value); } else { return result.asError; } } return Result<List<T>>.value(values); } /// Whether this result is a value result. /// /// Always the opposite of [isError]. bool get isValue; /// Whether this result is an error result. /// /// Always the opposite of [isValue]. bool get isError; /// If this is a value result, returns itself. /// /// Otherwise returns `null`. ValueResult<T> get asValue; /// If this is an error result, returns itself. /// /// Otherwise returns `null`. ErrorResult get asError; /// Completes a completer with this result. void complete(Completer<T> completer); /// Adds this result to an [EventSink]. /// /// Calls the sink's `add` or `addError` method as appropriate. void addTo(EventSink<T> sink); /// A future that has been completed with this result as a value or an error. Future<T> get asFuture; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/result/error.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:async'; import 'result.dart'; import 'value.dart'; /// A result representing a thrown error. class ErrorResult implements Result<Null> { /// The error object that was thrown. final Object error; /// The stack trace corresponding to where [error] was thrown. final StackTrace stackTrace; @override bool get isValue => false; @override bool get isError => true; @override ValueResult<Null> get asValue => null; @override ErrorResult get asError => this; ErrorResult(this.error, this.stackTrace); @override void complete(Completer completer) { completer.completeError(error, stackTrace); } @override void addTo(EventSink sink) { sink.addError(error, stackTrace); } @override Future<Null> get asFuture => Future<Null>.error(error, stackTrace); /// Calls an error handler with the error and stacktrace. /// /// An async error handler function is either a function expecting two /// arguments, which will be called with the error and the stack trace, or it /// has to be a function expecting only one argument, which will be called /// with only the error. void handle(Function errorHandler) { if (errorHandler is ZoneBinaryCallback) { errorHandler(error, stackTrace); } else { errorHandler(error); } } @override int get hashCode => error.hashCode ^ stackTrace.hashCode ^ 0x1d61823f; /// This is equal only to an error result with equal [error] and [stackTrace]. @override bool operator ==(Object other) => other is ErrorResult && error == other.error && stackTrace == other.stackTrace; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/result/capture_sink.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:async'; import 'result.dart'; /// Used by [Result.captureSink]. class CaptureSink<T> implements EventSink<T> { final EventSink<Result<T>> _sink; CaptureSink(EventSink<Result<T>> sink) : _sink = sink; @override void add(T value) { _sink.add(Result<T>.value(value)); } @override void addError(Object error, [StackTrace stackTrace]) { _sink.add(Result.error(error, stackTrace)); } @override void close() { _sink.close(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/result/value.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:async'; import 'result.dart'; import 'error.dart'; /// A result representing a returned value. class ValueResult<T> implements Result<T> { /// The result of a successful computation. final T value; @override bool get isValue => true; @override bool get isError => false; @override ValueResult<T> get asValue => this; @override ErrorResult get asError => null; ValueResult(this.value); @override void complete(Completer<T> completer) { completer.complete(value); } @override void addTo(EventSink<T> sink) { sink.add(value); } @override Future<T> get asFuture => Future.value(value); @override int get hashCode => value.hashCode ^ 0x323f1d61; @override bool operator ==(Object other) => other is ValueResult && value == other.value; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/result/release_transformer.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:async'; import 'result.dart'; import 'release_sink.dart'; /// A transformer that releases result events as data and error events. class ReleaseStreamTransformer<T> extends StreamTransformerBase<Result<T>, T> { const ReleaseStreamTransformer(); @override Stream<T> bind(Stream<Result<T>> source) { return Stream<T>.eventTransformed(source, _createSink); } // Since Stream.eventTransformed is not generic, this method can be static. static EventSink<Result> _createSink(EventSink sink) => ReleaseSink(sink); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/result/release_sink.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:async'; import 'result.dart'; /// Used by [Result.releaseSink]. class ReleaseSink<T> implements EventSink<Result<T>> { final EventSink<T> _sink; ReleaseSink(this._sink); @override void add(Result<T> result) { result.addTo(_sink); } @override void addError(Object error, [StackTrace stackTrace]) { // Errors may be added by intermediate processing, even if it is never // added by CaptureSink. _sink.addError(error, stackTrace); } @override void close() { _sink.close(); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/async/src/result/capture_transformer.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:async'; import 'result.dart'; import 'capture_sink.dart'; /// A stream transformer that captures a stream of events into [Result]s. /// /// The result of the transformation is a stream of [Result] values and no /// error events. Exposed by [Result.captureStream]. class CaptureStreamTransformer<T> extends StreamTransformerBase<T, Result<T>> { const CaptureStreamTransformer(); @override Stream<Result<T>> bind(Stream<T> source) => Stream<Result<T>>.eventTransformed( source, (sink) => CaptureSink<T>(sink)); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert/convert.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 convert; export 'src/accumulator_sink.dart'; export 'src/byte_accumulator_sink.dart'; export 'src/hex.dart'; export 'src/identity_codec.dart'; export 'src/percent.dart'; export 'src/string_accumulator_sink.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert/src/percent.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 convert.percent; import 'dart:convert'; import 'percent/encoder.dart'; import 'percent/decoder.dart'; export 'percent/encoder.dart' hide percentEncoder; export 'percent/decoder.dart' hide percentDecoder; /// The canonical instance of [PercentCodec]. const percent = const PercentCodec._(); // TODO(nweiz): Add flags to support generating and interpreting "+" as a space // character. Also add an option for custom sets of unreserved characters. /// A codec that converts byte arrays to and from percent-encoded (also known as /// URL-encoded) strings according to [RFC 3986][rfc]. /// /// [rfc]: https://tools.ietf.org/html/rfc3986#section-2.1 /// /// [encoder] encodes all bytes other than ASCII letters, decimal digits, or one /// of `-._~`. This matches the behavior of [Uri.encodeQueryComponent] except /// that it doesn't encode `0x20` bytes to the `+` character. /// /// To be maximally flexible, [decoder] will decode any percent-encoded byte and /// will allow any non-percent-encoded byte other than `%`. By default, it /// interprets `+` as `0x2B` rather than `0x20` as emitted by /// [Uri.encodeQueryComponent]. class PercentCodec extends Codec<List<int>, String> { PercentEncoder get encoder => percentEncoder; PercentDecoder get decoder => percentDecoder; const PercentCodec._(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert/src/hex.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 convert.hex; import 'dart:convert'; import 'hex/encoder.dart'; import 'hex/decoder.dart'; export 'hex/encoder.dart' hide hexEncoder; export 'hex/decoder.dart' hide hexDecoder; /// The canonical instance of [HexCodec]. const hex = const HexCodec._(); /// A codec that converts byte arrays to and from hexadecimal strings, following /// [the Base16 spec][rfc]. /// /// [rfc]: https://tools.ietf.org/html/rfc4648#section-8 /// /// This should be used via the [hex] field. class HexCodec extends Codec<List<int>, String> { HexEncoder get encoder => hexEncoder; HexDecoder get decoder => hexDecoder; const HexCodec._(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert/src/byte_accumulator_sink.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:typed_data/typed_data.dart'; /// A sink that provides access to the concatenated bytes passed to it. /// /// See also [ByteConversionSink.withCallback]. class ByteAccumulatorSink extends ByteConversionSinkBase { /// The bytes accumulated so far. /// /// The returned [Uint8List] is viewing a shared buffer, so it should not be /// changed and any bytes outside the view should not be accessed. Uint8List get bytes => new Uint8List.view(_buffer.buffer, 0, _buffer.length); final _buffer = new Uint8Buffer(); /// Whether [close] has been called. bool get isClosed => _isClosed; var _isClosed = false; /// Removes all bytes from [bytes]. /// /// This can be used to avoid double-processing data. void clear() { _buffer.clear(); } void add(List<int> bytes) { if (_isClosed) { throw new StateError("Can't add to a closed sink."); } _buffer.addAll(bytes); } void addSlice(List<int> chunk, int start, int end, bool isLast) { if (_isClosed) { throw new StateError("Can't add to a closed sink."); } _buffer.addAll(chunk, start, end); if (isLast) _isClosed = true; } void close() { _isClosed = true; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert/src/string_accumulator_sink.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'; /// A sink that provides access to the concatenated strings passed to it. /// /// See also [StringConversionSink.withCallback]. class StringAccumulatorSink extends StringConversionSinkBase { /// The string accumulated so far. String get string => _buffer.toString(); final _buffer = new StringBuffer(); /// Whether [close] has been called. bool get isClosed => _isClosed; var _isClosed = false; /// Empties [string]. /// /// This can be used to avoid double-processing data. void clear() { _buffer.clear(); } void add(String chunk) { if (_isClosed) { throw new StateError("Can't add to a closed sink."); } _buffer.write(chunk); } void addSlice(String chunk, int start, int end, bool isLast) { if (_isClosed) { throw new StateError("Can't add to a closed sink."); } _buffer.write(chunk.substring(start, end)); if (isLast) _isClosed = true; } void close() { _isClosed = true; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert/src/accumulator_sink.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'; /// A sink that provides access to all the [events] that have been passed to it. /// /// See also [ChunkedConversionSink.withCallback]. class AccumulatorSink<T> implements Sink<T> { /// An unmodifiable list of events passed to this sink so far. List<T> get events => new UnmodifiableListView(_events); final _events = <T>[]; /// Whether [close] has been called. bool get isClosed => _isClosed; var _isClosed = false; /// Removes all events from [events]. /// /// This can be used to avoid double-processing events. void clear() { _events.clear(); } void add(T event) { if (_isClosed) { throw new StateError("Can't add to a closed sink."); } _events.add(event); } void close() { _isClosed = true; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert/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. library convert.utils; import 'package:charcode/ascii.dart'; /// Returns the digit (0 through 15) corresponding to the hexadecimal code unit /// at index [i] in [codeUnits]. /// /// If the given code unit isn't valid hexadecimal, throws a [FormatException]. int digitForCodeUnit(List<int> codeUnits, int index) { // If the code unit 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. var codeUnit = codeUnits[index]; var digit = $0 ^ codeUnit; if (digit <= 9) { if (digit >= 0) return digit; } else { // If the code unit 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. var letter = 0x20 | codeUnit; if ($a <= letter && letter <= $f) return letter - $a + 10; } throw new FormatException( "Invalid hexadecimal code unit " "U+${codeUnit.toRadixString(16).padLeft(4, '0')}.", codeUnits, index); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert/src/identity_codec.dart
import 'dart:convert'; class _IdentityConverter<T> extends Converter<T, T> { _IdentityConverter(); T convert(T input) => input; } /// A [Codec] that performs the identity conversion (changing nothing) in both /// directions. /// /// The identity codec passes input directly to output in both directions. /// This class can be used as a base when combining multiple codecs, /// because fusing the identity codec with any other codec gives the other /// codec back. /// /// Note, that when fused with another [Codec] the identity codec disppears. class IdentityCodec<T> extends Codec<T, T> { const IdentityCodec(); Converter<T, T> get decoder => new _IdentityConverter<T>(); Converter<T, T> get encoder => new _IdentityConverter<T>(); /// Fuse with an other codec. /// /// Fusing with the identify converter is a no-op, so this always return /// [other]. Codec<T, R> fuse<R>(Codec<T, R> other) => other; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert/src/percent/decoder.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 convert.percent.decoder; import 'dart:convert'; import 'package:charcode/ascii.dart'; import 'package:typed_data/typed_data.dart'; import '../utils.dart'; /// The canonical instance of [PercentDecoder]. const percentDecoder = const PercentDecoder._(); const _lastPercent = -1; /// A converter that decodes percent-encoded strings into byte arrays. /// /// To be maximally flexible, this will decode any percent-encoded byte and /// will allow any non-percent-encoded byte other than `%`. By default, it /// interprets `+` as `0x2B` rather than `0x20` as emitted by /// [Uri.encodeQueryComponent]. /// /// This will throw a [FormatException] if the input string has an incomplete /// percent-encoding, or if it contains non-ASCII code units. class PercentDecoder extends Converter<String, List<int>> { const PercentDecoder._(); List<int> convert(String string) { var buffer = new Uint8Buffer(); var lastDigit = _decode(string.codeUnits, 0, string.length, buffer); if (lastDigit != null) { throw new FormatException( "Input ended with incomplete encoded byte.", string, string.length); } return buffer.buffer.asUint8List(0, buffer.length); } StringConversionSink startChunkedConversion(Sink<List<int>> sink) => new _PercentDecoderSink(sink); } /// A conversion sink for chunked percent-encoded decoding. class _PercentDecoderSink extends StringConversionSinkBase { /// The underlying sink to which decoded byte arrays will be passed. final Sink<List<int>> _sink; /// The trailing digit from the previous string. /// /// This is `null` if the previous string ended with a complete /// percent-encoded byte or a literal character. It's [_lastPercent] if the /// most recent string ended with `%`. Otherwise, the most recent string ended /// with a `%` followed by a hexadecimal digit, and this is that digit. Since /// it's the most significant digit, it's always a multiple of 16. int _lastDigit; _PercentDecoderSink(this._sink); void addSlice(String string, int start, int end, bool isLast) { RangeError.checkValidRange(start, end, string.length); if (start == end) { if (isLast) _close(string, end); return; } var buffer = new Uint8Buffer(); var codeUnits = string.codeUnits; if (_lastDigit == _lastPercent) { _lastDigit = 16 * digitForCodeUnit(codeUnits, start); start++; if (start == end) { if (isLast) _close(string, end); return; } } if (_lastDigit != null) { buffer.add(_lastDigit + digitForCodeUnit(codeUnits, start)); start++; } _lastDigit = _decode(codeUnits, start, end, buffer); _sink.add(buffer.buffer.asUint8List(0, buffer.length)); if (isLast) _close(string, end); } ByteConversionSink asUtf8Sink(bool allowMalformed) => new _PercentDecoderByteSink(_sink); void close() => _close(); /// Like [close], but includes [string] and [index] in the [FormatException] /// if one is thrown. void _close([String string, int index]) { if (_lastDigit != null) { throw new FormatException( "Input ended with incomplete encoded byte.", string, index); } _sink.close(); } } /// A conversion sink for chunked percent-encoded decoding from UTF-8 bytes. class _PercentDecoderByteSink extends ByteConversionSinkBase { /// The underlying sink to which decoded byte arrays will be passed. final Sink<List<int>> _sink; /// The trailing digit from the previous string. /// /// This is `null` if the previous string ended with a complete /// percent-encoded byte or a literal character. It's [_lastPercent] if the /// most recent string ended with `%`. Otherwise, the most recent string ended /// with a `%` followed by a hexadecimal digit, and this is that digit. Since /// it's the most significant digit, it's always a multiple of 16. int _lastDigit; _PercentDecoderByteSink(this._sink); void add(List<int> chunk) => addSlice(chunk, 0, chunk.length, false); void addSlice(List<int> chunk, int start, int end, bool isLast) { RangeError.checkValidRange(start, end, chunk.length); if (start == end) { if (isLast) _close(chunk, end); return; } var buffer = new Uint8Buffer(); if (_lastDigit == _lastPercent) { _lastDigit = 16 * digitForCodeUnit(chunk, start); start++; if (start == end) { if (isLast) _close(chunk, end); return; } } if (_lastDigit != null) { buffer.add(_lastDigit + digitForCodeUnit(chunk, start)); start++; } _lastDigit = _decode(chunk, start, end, buffer); _sink.add(buffer.buffer.asUint8List(0, buffer.length)); if (isLast) _close(chunk, end); } 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 (_lastDigit != null) { throw new FormatException( "Input ended with incomplete encoded byte.", chunk, index); } _sink.close(); } } /// Decodes [codeUnits] and writes the result into [destination]. /// /// This reads from [codeUnits] between [sourceStart] and [sourceEnd]. It writes /// the result into [destination] starting at [destinationStart]. /// /// If there's a leftover digit at the end of the decoding, this returns that /// digit. Otherwise it returns `null`. int _decode(List<int> codeUnits, int start, int end, Uint8Buffer buffer) { // A bitwise OR of all code units in [codeUnits]. This allows us to check for // out-of-range code units without adding more branches than necessary to the // core loop. var codeUnitOr = 0; // The beginning of the current slice of adjacent non-% characters. We can add // all of these to the buffer at once. var sliceStart = start; for (var i = start; i < end; i++) { // First, loop through non-% characters. var codeUnit = codeUnits[i]; if (codeUnits[i] != $percent) { codeUnitOr |= codeUnit; continue; } // We found a %. The slice from `sliceStart` to `i` represents characters // than can be copied to the buffer as-is. if (i > sliceStart) { _checkForInvalidCodeUnit(codeUnitOr, codeUnits, sliceStart, i); buffer.addAll(codeUnits, sliceStart, i); } // Now decode the percent-encoded byte and add it as well. i++; if (i >= end) return _lastPercent; var firstDigit = digitForCodeUnit(codeUnits, i); i++; if (i >= end) return 16 * firstDigit; var secondDigit = digitForCodeUnit(codeUnits, i); buffer.add(16 * firstDigit + secondDigit); // The next iteration will look for non-% characters again. sliceStart = i + 1; } if (end > sliceStart) { _checkForInvalidCodeUnit(codeUnitOr, codeUnits, sliceStart, end); if (start == sliceStart) { buffer.addAll(codeUnits); } else { buffer.addAll(codeUnits, sliceStart, end); } } return null; } void _checkForInvalidCodeUnit( int codeUnitOr, List<int> codeUnits, int start, int end) { if (codeUnitOr >= 0 && codeUnitOr <= 0x7f) return; for (var i = start; i < end; i++) { var codeUnit = codeUnits[i]; if (codeUnit >= 0 && codeUnit <= 0x7f) continue; throw new FormatException( "Non-ASCII code unit " "U+${codeUnit.toRadixString(16).padLeft(4, '0')}", codeUnits, i); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert/src/percent/encoder.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 convert.percent.encoder; import 'dart:convert'; import 'package:charcode/ascii.dart'; /// The canonical instance of [PercentEncoder]. const percentEncoder = const PercentEncoder._(); /// A converter that encodes byte arrays into percent-encoded strings. /// /// [encoder] encodes all bytes other than ASCII letters, decimal digits, or one /// of `-._~`. This matches the behavior of [Uri.encodeQueryComponent] except /// that it doesn't encode `0x20` bytes to the `+` character. /// /// This will throw a [RangeError] if the byte array has any digits that don't /// fit in the gamut of a byte. class PercentEncoder extends Converter<List<int>, String> { const PercentEncoder._(); String convert(List<int> bytes) => _convert(bytes, 0, bytes.length); ByteConversionSink startChunkedConversion(Sink<String> sink) => new _PercentEncoderSink(sink); } /// A conversion sink for chunked percentadecimal encoding. class _PercentEncoderSink extends ByteConversionSinkBase { /// The underlying sink to which decoded byte arrays will be passed. final Sink<String> _sink; _PercentEncoderSink(this._sink); void add(List<int> chunk) { _sink.add(_convert(chunk, 0, chunk.length)); } void addSlice(List<int> chunk, int start, int end, bool isLast) { RangeError.checkValidRange(start, end, chunk.length); _sink.add(_convert(chunk, start, end)); if (isLast) _sink.close(); } void close() { _sink.close(); } } String _convert(List<int> bytes, int start, int end) { var buffer = new StringBuffer(); // A bitwise OR of all bytes in [bytes]. This allows us to check for // out-of-range bytes without adding more branches than necessary to the // core loop. var byteOr = 0; for (var i = start; i < end; i++) { var byte = bytes[i]; byteOr |= byte; // If the byte is an uppercase letter, convert it to lowercase to check if // it's unreserved. 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. var letter = 0x20 | byte; if ((letter >= $a && letter <= $z) || (byte >= $0 && byte <= $9) || byte == $dash || byte == $dot || byte == $underscore || byte == $tilde) { // Unreserved characters are safe to write as-is. buffer.writeCharCode(byte); continue; } buffer.writeCharCode($percent); // The bitwise arithmetic here is equivalent to `byte ~/ 16` and `byte % 16` // for valid byte values, but is easier for dart2js to optimize given that // it can't prove that [byte] will always be positive. buffer.writeCharCode(_codeUnitForDigit((byte & 0xF0) >> 4)); buffer.writeCharCode(_codeUnitForDigit(byte & 0x0F)); } if (byteOr >= 0 && byteOr <= 255) return buffer.toString(); // If there was an invalid byte, find it and throw an exception. for (var i = start; i < end; i++) { var byte = bytes[i]; if (byte >= 0 && byte <= 0xff) continue; throw new FormatException( "Invalid byte ${byte < 0 ? "-" : ""}0x${byte.abs().toRadixString(16)}.", bytes, i); } throw 'unreachable'; } /// Returns the ASCII/Unicode code unit corresponding to the hexadecimal digit /// [digit]. int _codeUnitForDigit(int digit) => digit < 10 ? digit + $0 : digit + $A - 10;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert/src/hex/decoder.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 convert.hex.decoder; import 'dart:convert'; import 'dart:typed_data'; import '../utils.dart'; /// The canonical instance of [HexDecoder]. const hexDecoder = const HexDecoder._(); /// A converter that decodes hexadecimal strings into byte arrays. /// /// Because two hexadecimal digits correspond to a single byte, this will throw /// a [FormatException] if given an odd-length string. It will also throw a /// [FormatException] if given a string containing non-hexadecimal code units. class HexDecoder extends Converter<String, List<int>> { const HexDecoder._(); List<int> convert(String string) { if (!string.length.isEven) { throw new FormatException( "Invalid input length, must be even.", string, string.length); } var bytes = new Uint8List(string.length ~/ 2); _decode(string.codeUnits, 0, string.length, bytes, 0); return bytes; } StringConversionSink startChunkedConversion(Sink<List<int>> sink) => new _HexDecoderSink(sink); } /// A conversion sink for chunked hexadecimal decoding. class _HexDecoderSink extends StringConversionSinkBase { /// The underlying sink to which decoded byte arrays will be passed. final Sink<List<int>> _sink; /// The trailing digit from the previous string. /// /// This will be non-`null` if the most recent string had an odd number of /// hexadecimal digits. Since it's the most significant digit, it's always a /// multiple of 16. int _lastDigit; _HexDecoderSink(this._sink); void addSlice(String string, int start, int end, bool isLast) { RangeError.checkValidRange(start, end, string.length); if (start == end) { if (isLast) _close(string, end); return; } var codeUnits = string.codeUnits; Uint8List bytes; int bytesStart; if (_lastDigit == null) { bytes = new Uint8List((end - start) ~/ 2); bytesStart = 0; } else { var hexPairs = (end - start - 1) ~/ 2; bytes = new Uint8List(1 + hexPairs); bytes[0] = _lastDigit + digitForCodeUnit(codeUnits, start); start++; bytesStart = 1; } _lastDigit = _decode(codeUnits, start, end, bytes, bytesStart); _sink.add(bytes); if (isLast) _close(string, end); } ByteConversionSink asUtf8Sink(bool allowMalformed) => new _HexDecoderByteSink(_sink); void close() => _close(); /// Like [close], but includes [string] and [index] in the [FormatException] /// if one is thrown. void _close([String string, int index]) { if (_lastDigit != null) { throw new FormatException( "Input ended with incomplete encoded byte.", string, index); } _sink.close(); } } /// A conversion sink for chunked hexadecimal decoding from UTF-8 bytes. class _HexDecoderByteSink extends ByteConversionSinkBase { /// The underlying sink to which decoded byte arrays will be passed. final Sink<List<int>> _sink; /// The trailing digit from the previous string. /// /// This will be non-`null` if the most recent string had an odd number of /// hexadecimal digits. Since it's the most significant digit, it's always a /// multiple of 16. int _lastDigit; _HexDecoderByteSink(this._sink); void add(List<int> chunk) => addSlice(chunk, 0, chunk.length, false); void addSlice(List<int> chunk, int start, int end, bool isLast) { RangeError.checkValidRange(start, end, chunk.length); if (start == end) { if (isLast) _close(chunk, end); return; } Uint8List bytes; int bytesStart; if (_lastDigit == null) { bytes = new Uint8List((end - start) ~/ 2); bytesStart = 0; } else { var hexPairs = (end - start - 1) ~/ 2; bytes = new Uint8List(1 + hexPairs); bytes[0] = _lastDigit + digitForCodeUnit(chunk, start); start++; bytesStart = 1; } _lastDigit = _decode(chunk, start, end, bytes, bytesStart); _sink.add(bytes); if (isLast) _close(chunk, end); } 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 (_lastDigit != null) { throw new FormatException( "Input ended with incomplete encoded byte.", chunk, index); } _sink.close(); } } /// Decodes [codeUnits] and writes the result into [destination]. /// /// This reads from [codeUnits] between [sourceStart] and [sourceEnd]. It writes /// the result into [destination] starting at [destinationStart]. /// /// If there's a leftover digit at the end of the decoding, this returns that /// digit. Otherwise it returns `null`. int _decode(List<int> codeUnits, int sourceStart, int sourceEnd, List<int> destination, int destinationStart) { var destinationIndex = destinationStart; for (var i = sourceStart; i < sourceEnd - 1; i += 2) { var firstDigit = digitForCodeUnit(codeUnits, i); var secondDigit = digitForCodeUnit(codeUnits, i + 1); destination[destinationIndex++] = 16 * firstDigit + secondDigit; } if ((sourceEnd - sourceStart).isEven) return null; return 16 * digitForCodeUnit(codeUnits, sourceEnd - 1); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert/src
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/convert/src/hex/encoder.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 convert.hex.encoder; import 'dart:convert'; import 'dart:typed_data'; import 'package:charcode/ascii.dart'; /// The canonical instance of [HexEncoder]. const hexEncoder = const HexEncoder._(); /// A converter that encodes byte arrays into hexadecimal strings. /// /// This will throw a [RangeError] if the byte array has any digits that don't /// fit in the gamut of a byte. class HexEncoder extends Converter<List<int>, String> { const HexEncoder._(); String convert(List<int> bytes) => _convert(bytes, 0, bytes.length); ByteConversionSink startChunkedConversion(Sink<String> sink) => new _HexEncoderSink(sink); } /// A conversion sink for chunked hexadecimal encoding. class _HexEncoderSink extends ByteConversionSinkBase { /// The underlying sink to which decoded byte arrays will be passed. final Sink<String> _sink; _HexEncoderSink(this._sink); void add(List<int> chunk) { _sink.add(_convert(chunk, 0, chunk.length)); } void addSlice(List<int> chunk, int start, int end, bool isLast) { RangeError.checkValidRange(start, end, chunk.length); _sink.add(_convert(chunk, start, end)); if (isLast) _sink.close(); } void close() { _sink.close(); } } String _convert(List<int> bytes, int start, int end) { // A Uint8List is more efficient than a StringBuffer given that we know that // we're only emitting ASCII-compatible characters, and that we know the // length ahead of time. var buffer = new Uint8List((end - start) * 2); var bufferIndex = 0; // A bitwise OR of all bytes in [bytes]. This allows us to check for // out-of-range bytes without adding more branches than necessary to the // core loop. var byteOr = 0; for (var i = start; i < end; i++) { var byte = bytes[i]; byteOr |= byte; // The bitwise arithmetic here is equivalent to `byte ~/ 16` and `byte % 16` // for valid byte values, but is easier for dart2js to optimize given that // it can't prove that [byte] will always be positive. buffer[bufferIndex++] = _codeUnitForDigit((byte & 0xF0) >> 4); buffer[bufferIndex++] = _codeUnitForDigit(byte & 0x0F); } if (byteOr >= 0 && byteOr <= 255) return new String.fromCharCodes(buffer); // If there was an invalid byte, find it and throw an exception. for (var i = start; i < end; i++) { var byte = bytes[i]; if (byte >= 0 && byte <= 0xff) continue; throw new FormatException( "Invalid byte ${byte < 0 ? "-" : ""}0x${byte.abs().toRadixString(16)}.", bytes, i); } throw 'unreachable'; } /// Returns the ASCII/Unicode code unit corresponding to the hexadecimal digit /// [digit]. int _codeUnitForDigit(int digit) => digit < 10 ? digit + $0 : digit + $a - 10;
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_admin_interop/firebase_admin_interop.dart
// Copyright (c) 2017, Anatoly Pulyaevskiy. All rights reserved. Use of this source code // is governed by a BSD-style license that can be found in the LICENSE file. /// Firebase Admin Interop Library for Dart. /// /// This is a JS interop library so it can't be used standalone. It must be /// compiled to JavaScript as a valid Node module and import official Node.js /// Admin SDK for Firebase. /// /// Main entry point to this library is [FirebaseAdmin] class. It is a higher /// level interface on top of JS bindings which abstracts away some details /// of interacting with JavaScript and Node.js APIs. /// /// It is still possible to use JS bindings directly by importing "js.dart": /// /// import 'package:firebase_admin_interop/js.dart'; /// /// Below is a quick start example of working with the Realtime Database API: /// /// import 'dart:async'; /// import 'package:firebase_admin_interop/firebase_admin_interop.dart'; /// /// Future main() async { /// var admin = FirebaseAdmin.instance; /// var cert = admin.certFromPath(serviceAccountKeyFilename); /// var app = admin.initializeApp(new AppOptions( /// credential: cert, /// databaseUrl: "YOUR_DB_URL", /// )); /// var ref = app.database().ref('/test-path'); /// // Write value to the database at "/test-path" location. /// await ref.setValue("Hello world"); /// // Read value from the same database location. /// var snapshot = ref.once("value"); /// print(snapshot.val()); /// } /// /// See also: /// * [FirebaseAdmin] /// * [Auth] /// * [App] /// * [Database] /// * [Firestore] library firebase_admin_interop; export 'src/admin.dart'; export 'src/app.dart'; export 'src/auth.dart'; export 'src/bindings.dart' show AppOptions, SetOptions, FirestoreSettings; export 'src/database.dart'; export 'src/firestore.dart'; export 'src/messaging.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_admin_interop/js.dart
// Copyright (c) 2017, Anatoly Pulyaevskiy. All rights reserved. Use of this source code // is governed by a BSD-style license that can be found in the LICENSE file. /// Dart facade for Firebase Admin Node.js library. /// /// import 'package:firebase_admin_interop/js.dart'; /// import 'package:node_interop/node.dart'; /// /// void main() { /// FirebaseAdmin admin = require('firebase-admin'); /// App app = admin.initializeApp(jsify({ /// 'projectId': '<YOUR_PROJECT_ID>', // etc. /// })); /// console.log(app); /// } library firebase_admin_interop.js; export 'src/bindings.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_admin_interop
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_admin_interop/src/app.dart
// Copyright (c) 2017, Anatoly Pulyaevskiy. 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 'package:meta/meta.dart'; import 'package:node_interop/util.dart'; import 'admin.dart'; import 'auth.dart'; import 'bindings.dart' as js; import 'database.dart'; import 'firestore.dart'; import 'messaging.dart'; /// Represents initialized Firebase application and provides access to the /// app's services. class App { App(this.nativeInstance); @protected final js.App nativeInstance; /// The name of this application. String get name => nativeInstance.name; /// The (read-only) configuration options for this app. These are the original /// parameters given in [FirebaseAdmin.initializeApp]. js.AppOptions get options => nativeInstance.options; /// Gets the [Auth] service for this application. Auth auth() => _auth ??= new Auth(nativeInstance.auth()); Auth _auth; /// Gets Realtime [Database] client for this application. Database database() => _database ??= new Database(this.nativeInstance.database(), this); Database _database; /// Gets [Firestore] client for this application. Firestore firestore() => _firestore ??= new Firestore(nativeInstance.firestore()); Firestore _firestore; /// Gets [Messaging] client for this application. Messaging messaging() => _messaging ??= new Messaging(nativeInstance.messaging()); Messaging _messaging; /// Renders this app unusable and frees the resources of all associated /// services. Future<void> delete() => promiseToFuture<void>(nativeInstance.delete()); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_admin_interop
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_admin_interop/src/storage_bindings.dart
@JS() library firebase_storage; import "package:js/js.dart"; import 'package:node_interop/node.dart'; import 'bindings.dart'; /// The Cloud Storage service interface. @JS() @anonymous abstract class Storage { /// The app associated with this Storage instance. external App get app; /// Returns a reference to a Google Cloud Storage bucket. /// /// Returned reference can be used to upload and download content from /// Google Cloud Storage. /// /// [name] of the bucket to be retrieved is optional. If [name] is not /// specified, retrieves a reference to the default bucket. external Bucket bucket([String name]); } @JS() @anonymous abstract class Bucket { /// Combine multiple files into one new file. /// /// [sources] can be a list of strings or [StorageFile]s. /// [destination] can be a string or [StorageFile]. /// /// Returns promise containing list with following values: /// [0] [StorageFile] - The new file. /// [1] [Object] - The full API response. external Promise combine(List sources, dynamic destination, [options, callback]); /// Create a bucket. /// /// Returns promise containing CreateBucketResponse. external Promise create([CreateBucketRequest metadata, callback]); /// Checks if the bucket exists. /// /// Returns promise containing list with following values: /// [0] [boolean] - Whether this bucket exists. external Promise exists([BucketExistsOptions options, callback]); /// Creates a [StorageFile] object. /// /// See [StorageFile] to see for more details. external StorageFile file(String name, [StorageFileOptions options]); /// Upload a file to the bucket. This is a convenience method that wraps /// [StorageFile.createWriteStream]. /// /// [path] is the fully qualified path to the file you wish to upload to your /// bucket. /// /// You can specify whether or not an upload is resumable by setting /// `options.resumable`. Resumable uploads are enabled by default if your /// input file is larger than 5 MB. /// /// For faster crc32c computation, you must manually install `fast-crc32c`: /// /// npm install --save fast-crc32c external Promise upload(String pathString, [options, callback]); } @JS() @anonymous abstract class CombineOptions { /// Resource name of the Cloud KMS key that will be used to encrypt the /// object. /// /// Overwrites the object metadata's kms_key_name value, if any. external String get kmsKeyName; /// The ID of the project which will be billed for the request. external String get userProject; external factory CombineOptions({String kmsKeyName, String userProject}); } @JS() @anonymous abstract class CreateBucketRequest { // TODO: complete } @JS() @anonymous abstract class BucketExistsOptions { /// The ID of the project which will be billed for the request. external String get userProject; external factory BucketExistsOptions({String userProject}); } @JS() @anonymous abstract class StorageFileOptions { /// Only use a specific revision of this file. external String get generation; /// A custom encryption key. external String get encryptionKey; /// Resource name of the Cloud KMS key that will be used to encrypt the /// object. /// /// Overwrites the object metadata's kms_key_name value, if any. external String get kmsKeyName; external factory StorageFileOptions( {String generation, String encryptionKey, String kmsKeyName}); } @JS() @anonymous abstract class StorageFile {}
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_admin_interop
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_admin_interop/src/auth.dart
// Copyright (c) 2018, Anatoly Pulyaevskiy. 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 'package:meta/meta.dart'; import 'package:node_interop/util.dart'; import 'bindings.dart' as js show Auth; import 'bindings.dart' show UserRecord, CreateUserRequest, UpdateUserRequest, ListUsersResult, DecodedIdToken; export 'bindings.dart' show UserRecord, UserInfo, UserMetadata, CreateUserRequest, UpdateUserRequest, ListUsersResult, DecodedIdToken, FirebaseSignInInfo; class Auth { Auth(this.nativeInstance); @protected final js.Auth nativeInstance; /// Creates a new Firebase custom token (JWT) that can be sent back to a client /// device to use to sign in with the client SDKs' signInWithCustomToken() /// methods. /// /// Returns a [Future] containing a custom token string for the provided [uid] /// and payload. Future<String> createCustomToken(String uid, [Map<String, String> developerClaims]) => promiseToFuture( nativeInstance.createCustomToken(uid, jsify(developerClaims))); /// Creates a new user. Future<UserRecord> createUser(CreateUserRequest properties) => promiseToFuture(nativeInstance.createUser(properties)); /// Deletes an existing user. Future<void> deleteUser(String uid) => promiseToFuture(nativeInstance.deleteUser(uid)); /// Gets the user data for the user corresponding to a given [uid]. Future<UserRecord> getUser(String uid) => promiseToFuture(nativeInstance.getUser(uid)); /// Gets the user data for the user corresponding to a given [email]. Future<UserRecord> getUserByEmail(String email) => promiseToFuture(nativeInstance.getUserByEmail(email)); /// Gets the user data for the user corresponding to a given [phoneNumber]. Future<UserRecord> getUserByPhoneNumber(String phoneNumber) => promiseToFuture(nativeInstance.getUserByPhoneNumber(phoneNumber)); /// Retrieves a list of users (single batch only) with a size of [maxResults] /// and starting from the offset as specified by [pageToken]. /// /// This is used to retrieve all the users of a specified project in batches. Future<ListUsersResult> listUsers([num maxResults, String pageToken]) { if (pageToken != null && maxResults != null) { return promiseToFuture(nativeInstance.listUsers(maxResults, pageToken)); } else if (maxResults != null) { return promiseToFuture(nativeInstance.listUsers(maxResults)); } else { return promiseToFuture(nativeInstance.listUsers()); } } /// Revokes all refresh tokens for an existing user. /// /// This API will update the user's [UserRecord.tokensValidAfterTime] to the /// current UTC. It is important that the server on which this is called has /// its clock set correctly and synchronized. /// /// While this will revoke all sessions for a specified user and disable any /// new ID tokens for existing sessions from getting minted, existing ID tokens /// may remain active until their natural expiration (one hour). To verify that /// ID tokens are revoked, use [Auth.verifyIdToken] where `checkRevoked` is set to /// `true`. Future<void> revokeRefreshTokens(String uid) => promiseToFuture(nativeInstance.revokeRefreshTokens(uid)); /// Sets additional developer claims on an existing user identified by the /// provided [uid], typically used to define user roles and levels of access. /// /// These claims should propagate to all devices where the user is already /// signed in (after token expiration or when token refresh is forced) and the /// next time the user signs in. If a reserved OIDC claim name is used /// (sub, iat, iss, etc), an error is thrown. They will be set on the /// authenticated user's ID token JWT. /// /// [customUserClaims] can be `null` in which case existing custom /// claims are deleted. Passing a custom claims payload larger than 1000 bytes /// will throw an error. Custom claims are added to the user's ID token which /// is transmitted on every authenticated request. For profile non-access /// related user attributes, use database or other separate storage systems. Future<void> setCustomUserClaims( String uid, Map<String, dynamic> customUserClaims) => promiseToFuture( nativeInstance.setCustomUserClaims(uid, jsify(customUserClaims))); /// Updates an existing user. Future<UserRecord> updateUser(String uid, UpdateUserRequest properties) => promiseToFuture(nativeInstance.updateUser(uid, properties)); /// Verifies a Firebase ID token (JWT). /// /// If the token is valid, the returned [Future] is completed with an instance /// of [DecodedIdToken]; otherwise, the future is completed with an error. /// An optional flag can be passed to additionally check whether the ID token /// was revoked. Future<DecodedIdToken> verifyIdToken(String idToken, [bool checkRevoked]) { if (checkRevoked != null) { return promiseToFuture( nativeInstance.verifyIdToken(idToken, checkRevoked)); } else { return promiseToFuture(nativeInstance.verifyIdToken(idToken)); } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_admin_interop
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_admin_interop/src/firestore.dart
// Copyright (c) 2018, Anatoly Pulyaevskiy. 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:js'; import 'dart:typed_data'; import 'package:js/js.dart'; import 'package:meta/meta.dart'; import 'package:node_interop/js.dart'; import 'package:node_interop/node.dart'; import 'package:node_interop/util.dart'; import 'package:quiver_hashcode/hashcode.dart'; import 'bindings.dart' as js; @Deprecated('This function will be hidden from public API in future versions.') js.GeoPoint createGeoPoint(num latitude, num longitude) => _createJsGeoPoint(latitude, longitude); js.GeoPoint _createJsGeoPoint(num latitude, num longitude) { final proto = new js.GeoPointProto(latitude: latitude, longitude: longitude); return js.admin.firestore.GeoPoint.fromProto(proto); } js.Timestamp _createJsTimestamp(Timestamp ts) { return callConstructor( js.admin.firestore.Timestamp, jsify([ts.seconds, ts.nanoseconds])); } @Deprecated('This function will be hidden from public API in future versions.') js.FieldPath createFieldPath(List<String> fieldNames) { return callConstructor(js.admin.firestore.FieldPath, jsify(fieldNames)); } /// Returns a special sentinel [FieldPath] to refer to the ID of a document. /// It can be used in queries to sort or filter by the document ID. @Deprecated('Use "Firestore.documentId" instead.') js.FieldPath documentId() { final js.FieldPathPrototype proto = js.admin.firestore.FieldPath; return proto.documentId(); } /// Represents a Firestore Database and is the entry point for all /// Firestore operations. class Firestore { /// Sentinel field values that can be used when writing document fields with /// `set` or `update`. static final FieldValues fieldValues = FieldValues._(); /// Returns a special sentinel [FieldPath] to refer to the ID of a document. /// It can be used in queries to sort or filter by the document ID. static js.FieldPath documentId() { final js.FieldPathPrototype proto = js.admin.firestore.FieldPath; return proto.documentId(); } /// JavaScript Firestore object wrapped by this instance. @protected final js.Firestore nativeInstance; /// Creates new Firestore Database client which wraps [nativeInstance]. Firestore(this.nativeInstance); /// Specifies custom settings to be used to configure the `Firestore` /// instance. /// /// Can only be invoked once and before any other [Firestore] method. void settings(js.FirestoreSettings settings) { nativeInstance.settings(settings); } /// Gets a [CollectionReference] for the specified Firestore path. CollectionReference collection(String path) { assert(path != null); return new CollectionReference(nativeInstance.collection(path), this); } /// Creates and returns a new Query that includes all documents in the /// database that are contained in a collection or subcollection with the /// given [collectionId]. /// /// [collectionId] identifies the collections to query over. Every collection /// or subcollection with this ID as the last segment of its path will be /// included. Cannot contain a slash. DocumentQuery collectionGroup(String collectionId) { assert(collectionId != null); return new DocumentQuery( nativeInstance.collectionGroup(collectionId), this); } /// Gets a [DocumentReference] for the specified Firestore path. DocumentReference document(String path) { assert(path != null); return new DocumentReference(nativeInstance.doc(path), this); } /// Executes the given [updateFunction] and commits the changes applied within /// the transaction. /// /// You can use the transaction object passed to [updateFunction] to read and /// modify Firestore documents under lock. Transactions are committed once /// [updateFunction] resolves and attempted up to five times on failure. /// /// Returns the same `Future` returned by [updateFunction] if transaction /// completed successfully of was explicitly aborted by returning a Future /// with an error. If [updateFunction] throws then returned Future completes /// with the same error. Future<T> runTransaction<T>( Future<T> updateFunction(Transaction transaction)) { assert(updateFunction != null); Function jsUpdateFunction = (js.Transaction transaction) { return futureToPromise(updateFunction(new Transaction(transaction))); }; return promiseToFuture<T>( nativeInstance.runTransaction(allowInterop(jsUpdateFunction))); } /// Fetches the root collections that are associated with this Firestore /// database. Future<List<CollectionReference>> listCollections() async => (await promiseToFuture<List>(nativeInstance.listCollections())) .map((nativeCollectionReference) => CollectionReference(nativeCollectionReference, this)) .toList(growable: false); /// Creates a write batch, used for performing multiple writes as a single /// atomic operation. WriteBatch batch() => new WriteBatch(nativeInstance.batch()); /// Retrieves multiple documents from Firestore. Future<List<DocumentSnapshot>> getAll(List<DocumentReference> refs) async { final nativeRefs = refs .map((DocumentReference ref) => ref.nativeInstance) .toList(growable: false); final promise = callMethod(nativeInstance, 'getAll', nativeRefs); final result = await promiseToFuture<List>(promise); return result .map((nativeSnapshot) => DocumentSnapshot(nativeSnapshot, this)) .toList(growable: false); } } /// A CollectionReference object can be used for adding documents, getting /// document references, and querying for documents (using the methods /// inherited from [DocumentQuery]). class CollectionReference extends DocumentQuery { CollectionReference( js.CollectionReference nativeInstance, Firestore firestore) : super(nativeInstance, firestore); @override @protected js.CollectionReference get nativeInstance => super.nativeInstance; /// For subcollections, parent returns the containing DocumentReference. /// /// For root collections, null is returned. DocumentReference get parent { return (nativeInstance.parent != null) ? new DocumentReference(nativeInstance.parent, firestore) : null; } /// Returns a `DocumentReference` with the provided path. /// /// If no [path] is provided, an auto-generated ID is used. /// /// The unique key generated is prefixed with a client-generated timestamp /// so that the resulting list will be chronologically-sorted. DocumentReference document([String path]) { final docRef = (path == null) ? nativeInstance.doc() : nativeInstance.doc(path); return new DocumentReference(docRef, firestore); } /// Returns a `DocumentReference` with an auto-generated ID, after /// populating it with provided [data]. /// /// The unique key generated is prefixed with a client-generated timestamp /// so that the resulting list will be chronologically-sorted. Future<DocumentReference> add(DocumentData data) { return promiseToFuture(nativeInstance.add(data.nativeInstance)) .then((jsRef) => new DocumentReference(jsRef, firestore)); } /// The last path element of the referenced collection. String get id => nativeInstance.id; /// A string representing the path of the referenced collection (relative to /// the root of the database). String get path => nativeInstance.path; } /// A [DocumentReference] refers to a document location in a Firestore database /// and can be used to write, read, or listen to the location. /// /// The document at the referenced location may or may not exist. /// A [DocumentReference] can also be used to create a [CollectionReference] /// to a subcollection. class DocumentReference { DocumentReference(this.nativeInstance, this.firestore); @protected final js.DocumentReference nativeInstance; final Firestore firestore; /// Slash-delimited path representing the database location of this query. String get path => nativeInstance.path; /// This document's given or generated ID in the collection. String get documentID => nativeInstance.id; CollectionReference get parent { return new CollectionReference(nativeInstance.parent, firestore); } /// Writes to the document referred to by this [DocumentReference]. If the /// document does not yet exist, it will be created. If you pass [SetOptions], /// the provided data will be merged into an existing document. Future<void> setData(DocumentData data, [js.SetOptions options]) { final docData = data.nativeInstance; if (options != null) { return promiseToFuture(nativeInstance.set(docData, options)); } return promiseToFuture(nativeInstance.set(docData)); } /// Updates fields in the document referred to by this [DocumentReference]. /// /// If no document exists yet, the update will fail. Future<void> updateData(UpdateData data) { final docData = data.nativeInstance; return promiseToFuture(nativeInstance.update(docData)); } /// Reads the document referenced by this [DocumentReference]. /// /// If no document exists, the read will return null. Future<DocumentSnapshot> get() { return promiseToFuture(nativeInstance.get()) .then((jsSnapshot) => new DocumentSnapshot(jsSnapshot, firestore)); } /// Deletes the document referred to by this [DocumentReference]. Future<void> delete() => promiseToFuture(nativeInstance.delete()); /// Returns the reference of a collection contained inside of this /// document. CollectionReference collection(String path) => new CollectionReference(nativeInstance.collection(path), firestore); /// Notifies of documents at this location. Stream<DocumentSnapshot> get snapshots { Function cancelCallback; // It's fine to let the StreamController be garbage collected once all the // subscribers have cancelled; this analyzer warning is safe to ignore. StreamController<DocumentSnapshot> controller; // ignore: close_sinks void _onNextSnapshot(js.DocumentSnapshot jsSnapshot) { controller.add(new DocumentSnapshot(jsSnapshot, firestore)); } controller = new StreamController<DocumentSnapshot>.broadcast( onListen: () { cancelCallback = nativeInstance.onSnapshot(allowInterop(_onNextSnapshot)); }, onCancel: () { cancelCallback(); }, ); return controller.stream; } /// Fetches the subcollections that are direct children of this document. Future<List<CollectionReference>> listCollections() async => (await promiseToFuture<List>(nativeInstance.listCollections())) .map((nativeCollectionReference) => CollectionReference(nativeCollectionReference, firestore)) .toList(growable: false); } /// An enumeration of document change types. enum DocumentChangeType { /// Indicates a new document was added to the set of documents matching the /// query. added, /// Indicates a document within the query was modified. modified, /// Indicates a document within the query was removed (either deleted or no /// longer matches the query. removed, } /// A DocumentChange represents a change to the documents matching a query. /// /// It contains the document affected and the type of change that occurred /// (added, modified, or removed). class DocumentChange { DocumentChange(this.nativeInstance, this.firestore); @protected final js.DocumentChange nativeInstance; final Firestore firestore; /// The type of change that occurred (added, modified, or removed). /// /// Can be `null` if this document change was returned from [DocumentQuery.get]. DocumentChangeType get type { if (_type != null) return _type; if (nativeInstance.type == 'added') { _type = DocumentChangeType.added; } else if (nativeInstance.type == 'modified') { _type = DocumentChangeType.modified; } else if (nativeInstance.type == 'removed') { _type = DocumentChangeType.removed; } return _type; } DocumentChangeType _type; /// The index of the changed document in the result set immediately prior to /// this [DocumentChange] (i.e. supposing that all prior DocumentChange objects /// have been applied). /// /// -1 for [DocumentChangeType.added] events. int get oldIndex => nativeInstance.oldIndex.toInt(); /// The index of the changed document in the result set immediately after this /// DocumentChange (i.e. supposing that all prior [DocumentChange] objects /// and the current [DocumentChange] object have been applied). /// /// -1 for [DocumentChangeType.removed] events. int get newIndex => nativeInstance.newIndex.toInt(); /// The document affected by this change. DocumentSnapshot get document => _document ??= new DocumentSnapshot(nativeInstance.doc, firestore); DocumentSnapshot _document; } class DocumentSnapshot { DocumentSnapshot(this.nativeInstance, this.firestore); @protected final js.DocumentSnapshot nativeInstance; final Firestore firestore; /// The reference that produced this snapshot DocumentReference get reference => _reference ??= new DocumentReference(nativeInstance.ref, firestore); DocumentReference _reference; /// Contains all the data of this snapshot DocumentData get data => _data ??= new DocumentData(nativeInstance.data()); DocumentData _data; /// Returns `true` if the document exists. bool get exists => nativeInstance.exists; /// Returns the ID of the snapshot's document String get documentID => nativeInstance.id; /// The time the document was created. Not set for documents that don't /// exist. Timestamp get createTime { final ts = nativeInstance.createTime; if (ts == null) return null; return new Timestamp(ts.seconds, ts.nanoseconds); } /// The time the document was last updated (at the time the snapshot was /// generated). Not set for documents that don't exist. /// /// Note that this value includes nanoseconds and can not be represented /// by a [DateTime] object with expected accuracy when used in [Transaction]. Timestamp get updateTime { final ts = nativeInstance.updateTime; if (ts == null) return null; return new Timestamp(ts.seconds, ts.nanoseconds); } } class _FirestoreData { _FirestoreData([Object nativeInstance]) : nativeInstance = nativeInstance ?? newObject(); @protected final dynamic nativeInstance; /// Length of this document. int get length => objectKeys(nativeInstance).length; bool get isEmpty => length == 0; bool get isNotEmpty => !isEmpty; void _setField(String key, dynamic value) { if (value == null) { setProperty(nativeInstance, key, null); } else if (value is String) { setString(key, value); } else if (value is int) { setInt(key, value); } else if (value is double) { setDouble(key, value); } else if (value is bool) { setBool(key, value); } else if (value is DateTime) { // ignore: deprecated_member_use, deprecated_member_use_from_same_package setDateTime(key, value); } else if (value is GeoPoint) { setGeoPoint(key, value); } else if (value is Blob) { setBlob(key, value); } else if (value is DocumentReference) { setReference(key, value); } else if (value is List) { setList(key, value); } else if (value is Timestamp) { setTimestamp(key, value); } else if (value is FieldValue) { setFieldValue(key, value); } else if (value is Map) { setNestedData( key, new DocumentData.fromMap(value.cast<String, dynamic>())); } else { throw new ArgumentError.value( value, key, 'Unsupported value type for Firestore.'); } } String getString(String key) => (getProperty(nativeInstance, key) as String); void setString(String key, String value) { setProperty(nativeInstance, key, value); } int getInt(String key) => (getProperty(nativeInstance, key) as int); void setInt(String key, int value) { setProperty(nativeInstance, key, value); } double getDouble(String key) => (getProperty(nativeInstance, key) as double); void setDouble(String key, double value) { setProperty(nativeInstance, key, value); } bool getBool(String key) => (getProperty(nativeInstance, key) as bool); void setBool(String key, bool value) { setProperty(nativeInstance, key, value); } /// Returns true if this data contains an entry with the given [key]. bool has(String key) => hasProperty(nativeInstance, key); @Deprecated('Migrate to using Firestore Timestamps and "getTimestamp()".') DateTime getDateTime(String key) { final Date value = getProperty(nativeInstance, key); if (value == null) return null; assert(_isDate(value), 'Tried to get Date and got $value'); return new DateTime.fromMillisecondsSinceEpoch(value.getTime()); } Timestamp getTimestamp(String key) { js.Timestamp ts = getProperty(nativeInstance, key); if (ts == null) return null; assert(_isTimestamp(ts), 'Tried to get Timestamp and got $ts.'); return new Timestamp(ts.seconds, ts.nanoseconds); } @Deprecated('Migrate to using Firestore Timestamps and "setTimestamp()".') void setDateTime(String key, DateTime value) { assert(key != null); final data = (value != null) ? new Date(value.millisecondsSinceEpoch) : null; setProperty(nativeInstance, key, data); } void setTimestamp(String key, Timestamp value) { assert(key != null); final ts = (value != null) ? _createJsTimestamp(value) : null; setProperty(nativeInstance, key, ts); } GeoPoint getGeoPoint(String key) { js.GeoPoint value = getProperty(nativeInstance, key); if (value == null) return null; assert(_isGeoPoint(value), 'Invalid value provided to $runtimeType.getGeoPoint().'); return new GeoPoint(value.latitude.toDouble(), value.longitude.toDouble()); } Blob getBlob(String key) { var value = getProperty(nativeInstance, key); if (value == null) return null; assert(_isBlob(value), 'Invalid value provided to $runtimeType.getBlob().'); return new Blob(value); } void setGeoPoint(String key, GeoPoint value) { assert(key != null); final data = (value != null) ? _createJsGeoPoint(value.latitude, value.longitude) : null; setProperty(nativeInstance, key, data); } void setBlob(String key, Blob value) { assert(key != null); final data = (value != null) ? value.data : null; setProperty(nativeInstance, key, data); } void setFieldValue(String key, FieldValue value) { assert(key != null); setProperty(nativeInstance, key, value?._jsify()); } void setNestedData(String key, DocumentData value) { assert(key != null); setProperty(nativeInstance, key, value.nativeInstance); } static bool _isPrimitive(value) => value == null || value is int || value is double || value is String || value is bool; List getList(String key) { final data = getProperty(nativeInstance, key); if (data == null) return null; if (data is! List) { throw new StateError('Expected list but got ${data.runtimeType}.'); } final result = new List(); for (var item in data) { item = _dartify(item); result.add(item); } return result; } void setList(String key, List value) { assert(key != null); if (value == null) { setProperty(nativeInstance, key, value); return; } // The contents remains is js final data = _jsifyList(value); setProperty(nativeInstance, key, data); } DocumentReference getReference(String key) { js.DocumentReference ref = getProperty(nativeInstance, key); if (ref == null) return null; assert(_isReference(ref), 'Invalid value provided to $runtimeType.getReference().'); js.Firestore firestore = ref.firestore; return new DocumentReference(ref, new Firestore(firestore)); } void setReference(String key, DocumentReference value) { assert(key != null); final data = (value != null) ? value.nativeInstance : null; setProperty(nativeInstance, key, data); } bool _isTimestamp(value) => hasProperty(value, '_seconds') && hasProperty(value, '_nanoseconds'); // Workarounds for dart2js as `value is Type` doesn't work as expected. bool _isDate(value) => hasProperty(value, 'toDateString') && hasProperty(value, 'getTime') && getProperty(value, 'getTime') is Function; bool _isGeoPoint(value) => hasProperty(value, '_latitude') && hasProperty(value, '_longitude'); bool _isBlob(value) { if (value is Uint8List) { return true; } else { var proto = getProperty(value, '__proto__'); if (proto != null) { return getProperty(proto, "writeUInt8") is Function && getProperty(proto, "readUInt8") is Function; } return false; } } bool _isReference(value) => hasProperty(value, 'firestore') && hasProperty(value, 'id') && hasProperty(value, 'onSnapshot') && getProperty(value, 'onSnapshot') is Function; // TODO: figure out how to handle array* field values. For now ignored as they // don't need js to dart conversion bool _isFieldValue(value) { if (value == js.admin.firestore.FieldValue.delete() || value == js.admin.firestore.FieldValue.serverTimestamp()) { return true; } return false; } /// Supports nested List and maps. static dynamic _jsify(item) { if (_isPrimitive(item)) { return item; } else if (item is GeoPoint) { GeoPoint point = item; return _createJsGeoPoint(point.latitude, point.longitude); } else if (item is DocumentReference) { DocumentReference ref = item; return ref.nativeInstance; } else if (item is Blob) { Blob blob = item; return blob.data; } else if (item is DateTime) { DateTime date = item; return new Date(date.millisecondsSinceEpoch); } else if (item is Timestamp) { return _createJsTimestamp(item); } else if (item is FieldValue) { return item._jsify(); } else if (item is List) { return _jsifyList(item); } else if (item is Map) { return DocumentData.fromMap(item?.cast<String, dynamic>()).nativeInstance; } else { throw UnsupportedError( 'Value of type ${item.runtimeType} is not supported by Firestore.'); } } dynamic _dartify(item) { /// This is a best-effort implementation which attempts to convert /// built-in Firestore data types into Dart objects. /// /// We check types starting with higher level of confidence: /// 1. Primitive types (int, bool, String, double, null) /// 2. Data types with properties of type [Function]: DateTime, DocumentReference /// 3. GeoPoint /// 4. Blob /// 5. Timestamp /// 6. Date /// 7. Field value /// 8. Lists /// 7. Nested arbitrary maps. /// /// The assumption is that Firestore does not support storing [Function] /// values so if a native object contains a known function property /// (`Date.getTime` or `DocumentReference.onSnapshot`) it should be safe to /// treat it as such type. /// /// The only possible mismatch here would be treating an arbitrary nested /// map as a GeoPoint because we can only check presence of `latitude` and /// `longitude`. The [_isGeoPoint] method relies additionally on the output /// of `GeoPoint.toString()` method which must contain "GeoPoint". /// See: https://github.com/googleapis/nodejs-firestore/blob/35c1af0d0afc660b467d411f5de39792f8330be2/src/document.js#L129 if (_isPrimitive(item)) { return item; } else if (_isGeoPoint(item)) { js.GeoPoint point = item; return GeoPoint(point.latitude.toDouble(), point.longitude.toDouble()); } else if (_isReference(item)) { js.DocumentReference ref = item; js.Firestore firestore = ref.firestore; return DocumentReference(ref, new Firestore(firestore)); } else if (_isBlob(item)) { return Blob(item); } else if (_isTimestamp(item)) { js.Timestamp ts = item; return Timestamp(ts.seconds, ts.nanoseconds); } else if (_isDate(item)) { Date date = item; return DateTime.fromMillisecondsSinceEpoch(date.getTime()); } else if (_isFieldValue(item)) { return FieldValue._fromJs(item); } else if (item is List) { return _dartifyList(item); } else { // Handle like any object return _dartifyObject(item); } } static List _jsifyList(List list) { var data = []; for (dynamic item in list) { if (item is List) { // Otherwise this crashes in firestore // we cannot have list of lists such as [[1]] throw ArgumentError('A list item cannot be a List'); } data.add(_jsify(item)); } return data; } List _dartifyList(List list) { return list.map(_dartify).toList(); } Map<String, dynamic> _dartifyObject(object) { return DocumentData(object).toMap(); } @override String toString() => '$runtimeType'; } /// Data stored in a Firestore Document. /// /// This class represents full data snapshot of a document as a tree. /// This class provides typed methods to get and set field values in a document. /// /// Use [setNestedData] and [getNestedData] to access data in nested fields. /// /// See also: /// - [UpdateData] which is used to update a part of a document and follows /// different pattern for handling nested fields. class DocumentData extends _FirestoreData { DocumentData([js.DocumentData nativeInstance]) : super(nativeInstance); factory DocumentData.fromMap(Map<String, dynamic> data) { final doc = new DocumentData(); data.forEach(doc._setField); return doc; } DocumentData getNestedData(String key) { final data = getProperty(nativeInstance, key); if (data == null) return null; return new DocumentData(data); } /// List of keys in this document data. List<String> get keys => objectKeys(nativeInstance); /// Converts this document data into a [Map]. Map<String, dynamic> toMap() { final Map<String, dynamic> map = {}; for (var key in keys) { map[key] = _dartify(getProperty(nativeInstance, key)); } return map; } } /// Represents data to update in a Firestore document. /// /// Main difference of this class from [DocumentData] is in how nested fields /// are handled. /// /// [DocumentData] always represents full snapshot of a document as a tree. /// [UpdateData] represents only a part of the document which must be updated, /// and nested fields use dot-separated keys. For instance, /// /// // Using DocumentData with "profile" field which itself contains /// // "name" field: /// DocumentData profile = new DocumentData(); /// profile.setString("name", "John"); /// DocumentData doc = new DocumentData(); /// doc.setNestedData("profile", profile); /// /// // Using UpdateData to update profile name: /// UpdateData data = new UpdateData(); /// data.setString("profile.name", "John"); class UpdateData extends _FirestoreData { UpdateData([js.UpdateData nativeInstance]) : super(nativeInstance); factory UpdateData.fromMap(Map<String, dynamic> data) { final doc = new UpdateData(); data.forEach(doc._setField); return doc; } } /// Represents Firestore timestamp object. class Timestamp { final int seconds; final int nanoseconds; Timestamp(this.seconds, this.nanoseconds); factory Timestamp.fromDateTime(DateTime dateTime) { final int seconds = dateTime.millisecondsSinceEpoch ~/ 1000; final int nanoseconds = (dateTime.microsecondsSinceEpoch % 1000000) * 1000; return Timestamp(seconds, nanoseconds); } @override bool operator ==(Object other) { if (identical(this, other)) return true; if (other is! Timestamp) return false; Timestamp typedOther = other; return seconds == typedOther.seconds && nanoseconds == typedOther.nanoseconds; } @override int get hashCode => hash2(seconds, nanoseconds); int get millisecondsSinceEpoch => (microsecondsSinceEpoch / 1000).floor(); int get microsecondsSinceEpoch { return (seconds * 1000000 + nanoseconds / 1000).floor(); } DateTime toDateTime() { return new DateTime.fromMicrosecondsSinceEpoch(microsecondsSinceEpoch); } } /// Represents Firestore geo point object. class GeoPoint { final double latitude; final double longitude; GeoPoint(this.latitude, this.longitude); @override bool operator ==(other) { if (identical(this, other)) return true; if (other is! GeoPoint) return false; GeoPoint point = other; return latitude == point.latitude && longitude == point.longitude; } @override int get hashCode => hash2(latitude, longitude); @override String toString() { return 'GeoPoint($latitude, $longitude)'; } } /// An immutable object representing an array of bytes. class Blob { final Uint8List _data; /// Creates new blob from list of bytes in [data]. Blob(List<int> data) : _data = new Uint8List.fromList(data); /// Creates new blob from list of bytes in [Uint8List]. Blob.fromUint8List(this._data); /// List of bytes contained in this blob. List<int> get data => _data; /// Returns byte data in this blob as an instance of [Uint8List]. Uint8List asUint8List() => _data; } /// A QuerySnapshot contains zero or more DocumentSnapshot objects. class QuerySnapshot { QuerySnapshot(this.nativeInstance, this.firestore); @protected final js.QuerySnapshot nativeInstance; final Firestore firestore; bool get isEmpty => nativeInstance.empty; bool get isNotEmpty => !isEmpty; /// Gets a list of all the documents included in this snapshot List<DocumentSnapshot> get documents { if (isEmpty) return const <DocumentSnapshot>[]; _documents ??= new List<js.QueryDocumentSnapshot>.from(nativeInstance.docs) .map((jsDoc) => new DocumentSnapshot(jsDoc, firestore)) .toList(growable: false); return _documents; } List<DocumentSnapshot> _documents; /// An array of the documents that changed since the last snapshot. If this /// is the first snapshot, all documents will be in the list as Added changes. List<DocumentChange> get documentChanges { if (_changes == null) { if (nativeInstance.docChanges() == null) { _changes = const <DocumentChange>[]; } else { _changes = new List<js.DocumentChange>.from(nativeInstance.docChanges()) .map((jsChange) => new DocumentChange(jsChange, firestore)) .toList(growable: false); } } return _changes; } List<DocumentChange> _changes; } /// Represents a query over the data at a particular location. class DocumentQuery { DocumentQuery(this.nativeInstance, this.firestore); @protected final js.DocumentQuery nativeInstance; final Firestore firestore; Future<QuerySnapshot> get() { return promiseToFuture(nativeInstance.get()) .then((jsSnapshot) => new QuerySnapshot(jsSnapshot, firestore)); } /// Notifies of query results at this location. Stream<QuerySnapshot> get snapshots { // It's fine to let the StreamController be garbage collected once all the // subscribers have cancelled; this analyzer warning is safe to ignore. StreamController<QuerySnapshot> controller; // ignore: close_sinks void onSnapshot(js.QuerySnapshot snapshot) { controller.add(new QuerySnapshot(snapshot, firestore)); } void onError(error) { controller.addError(error); } Function unsubscribe; controller = new StreamController<QuerySnapshot>.broadcast( onListen: () { unsubscribe = nativeInstance.onSnapshot( allowInterop(onSnapshot), allowInterop(onError)); }, onCancel: () { unsubscribe(); }, ); return controller.stream; } /// Creates and returns a new [DocumentQuery] with additional filter on specified /// [field]. /// /// Only documents satisfying provided condition are included in the result /// set. DocumentQuery where( String field, { dynamic isEqualTo, dynamic isLessThan, dynamic isLessThanOrEqualTo, dynamic isGreaterThan, dynamic isGreaterThanOrEqualTo, dynamic arrayContains, bool isNull, }) { js.DocumentQuery query = nativeInstance; void addCondition(String field, String opStr, dynamic value) { query = query.where(field, opStr, _FirestoreData._jsify(value)); } if (isEqualTo != null) addCondition(field, '==', isEqualTo); if (isLessThan != null) addCondition(field, '<', isLessThan); if (isLessThanOrEqualTo != null) addCondition(field, '<=', isLessThanOrEqualTo); if (isGreaterThan != null) addCondition(field, '>', isGreaterThan); if (isGreaterThanOrEqualTo != null) addCondition(field, '>=', isGreaterThanOrEqualTo); if (arrayContains != null) addCondition(field, 'array-contains', arrayContains); if (isNull != null) { assert( isNull, 'isNull can only be set to true. ' 'Use isEqualTo to filter on non-null values.'); addCondition(field, '==', null); } return new DocumentQuery(query, firestore); } /// Creates and returns a new [DocumentQuery] that's additionally sorted by the specified /// [field]. DocumentQuery orderBy(String field, {bool descending: false}) { String direction = descending ? 'desc' : 'asc'; return new DocumentQuery( nativeInstance.orderBy(field, direction), firestore); } /// Takes a [snapshot] or a list of [values], creates and returns a new [DocumentQuery] /// that starts after the provided fields relative to the order of the query. /// /// Either [snapshot] or [values] can be provided at the same time, not both. /// The [values] must be in order of [orderBy] filters. /// /// Cannot be used in combination with [startAt]. DocumentQuery startAfter({DocumentSnapshot snapshot, List<dynamic> values}) { return new DocumentQuery( _wrapPaginatingFunctionCall("startAfter", snapshot, values), firestore); } /// Takes a [snapshot] or a list of [values], creates and returns a new [DocumentQuery] /// that starts at the provided fields relative to the order of the query. /// /// Either [snapshot] or [values] can be provided at the same time, not both. /// The [values] must be in order of [orderBy] filters. /// /// Cannot be used in combination with [startAfter]. DocumentQuery startAt({DocumentSnapshot snapshot, List<dynamic> values}) { return new DocumentQuery( _wrapPaginatingFunctionCall("startAt", snapshot, values), firestore); } /// Takes a [snapshot] or a list of [values], creates and returns a new [DocumentQuery] /// that ends at the provided fields relative to the order of the query. /// /// Either [snapshot] or [values] can be provided at the same time, not both. /// The [values] must be in order of [orderBy] filters. /// /// Cannot be used in combination with [endBefore]. DocumentQuery endAt({DocumentSnapshot snapshot, List<dynamic> values}) { return new DocumentQuery( _wrapPaginatingFunctionCall("endAt", snapshot, values), firestore); } /// Takes a [snapshot] or a list of [values], creates and returns a new [DocumentQuery] /// that ends before the provided fields relative to the order of the query. /// /// Either [snapshot] or [values] can be provided at the same time, not both. /// The [values] must be in order of [orderBy] filters. /// /// Cannot be used in combination with [endAt]. DocumentQuery endBefore({DocumentSnapshot snapshot, List<dynamic> values}) { return new DocumentQuery( _wrapPaginatingFunctionCall("endBefore", snapshot, values), firestore); } /// Creates and returns a new Query that's additionally limited to only return up /// to the specified number of documents. DocumentQuery limit(int length) { assert(length != null); return new DocumentQuery(nativeInstance.limit(length), firestore); } /// Specifies the offset of the returned results. DocumentQuery offset(int offset) { assert(offset != null); return new DocumentQuery(nativeInstance.offset(offset), firestore); } /// Calls js paginating [method] with [DocumentSnapshot] or List of [values]. /// We need to call this method in all paginating methods to fix that Dart /// doesn't support varargs - we need to use [List] to call js function. js.DocumentQuery _wrapPaginatingFunctionCall( String method, DocumentSnapshot snapshot, List<dynamic> values) { if (snapshot == null && values == null) { throw new ArgumentError( "Please provide either snapshot or values parameter."); } else if (snapshot != null && values != null) { throw new ArgumentError( 'Cannot provide both snapshot and values parameters.'); } List<dynamic> args = (snapshot != null) ? [snapshot.nativeInstance] : values.map(_FirestoreData._jsify).toList(); return callMethod(nativeInstance, method, args); } /// Creates and returns a new Query instance that applies a field mask /// to the result and returns only the specified subset of fields. /// You can specify a list of field paths to return, or use an empty /// list to only return the references of matching documents. DocumentQuery select(List<String> fieldPaths) { assert(fieldPaths != null); // Dart doesn't support varargs return new DocumentQuery( callMethod(nativeInstance, "select", fieldPaths), firestore); } } /// A reference to a transaction. /// The [Transaction] object passed to a transaction's updateFunction provides /// the methods to read and write data within the transaction context. See /// [Firestore.runTransaction]. class Transaction { final js.Transaction nativeInstance; Transaction(this.nativeInstance); /// Reads the document referenced by the provided [documentRef]. /// Holds a pessimistic lock on the returned document. Future<DocumentSnapshot> get(DocumentReference documentRef) { final nativeRef = documentRef.nativeInstance; return promiseToFuture(nativeInstance.get(nativeRef)).then((jsSnapshot) => new DocumentSnapshot(jsSnapshot, documentRef.firestore)); } /// Retrieves a query result. Holds a pessimistic lock on the returned /// documents. Future<QuerySnapshot> getQuery(DocumentQuery query) { final nativeQuery = query.nativeInstance; return promiseToFuture(nativeInstance.get(nativeQuery)) .then((jsSnapshot) => new QuerySnapshot(jsSnapshot, query.firestore)); } /// Create the document referred to by the provided [documentRef]. /// The operation will fail the transaction if a document exists at the /// specified location. void create(DocumentReference documentRef, DocumentData data) { var docData = data.nativeInstance; var nativeRef = documentRef.nativeInstance; nativeInstance.create(nativeRef, docData); } /// Writes to the document referred to by the provided [documentRef]. /// If the document does not exist yet, it will be created. If you pass /// [options], the provided data can be merged into the existing document. void set(DocumentReference documentRef, DocumentData data, {bool merge: false}) { final docData = data.nativeInstance; final nativeRef = documentRef.nativeInstance; nativeInstance.set(nativeRef, docData, _getNativeSetOptions(merge)); } /// Updates fields in the document referred to by the provided [documentRef]. /// /// The update will fail if applied to a document that does not exist. /// [lastUpdateTime] argument can be used to add a precondition for this /// update. This argument, if specified, must contain value of /// [DocumentSnapshot.updateTime]. The update will be accepted only if /// update time on the server is equal to this value. void update(DocumentReference documentRef, UpdateData data, {Timestamp lastUpdateTime}) { final docData = data.nativeInstance; final nativeRef = documentRef.nativeInstance; if (lastUpdateTime != null) { nativeInstance.update( nativeRef, docData, _getNativePrecondition(lastUpdateTime)); } else { nativeInstance.update(nativeRef, docData); } } /// Deletes the document referred to by the provided [documentRef]. /// /// [lastUpdateTime] argument can be used to add a precondition for this /// delete. This argument, if specified, must contain value of /// [DocumentSnapshot.updateTime]. The delete will be accepted only if /// update time on the server is equal to this value. void delete(DocumentReference documentRef, {Timestamp lastUpdateTime}) { final nativeRef = documentRef.nativeInstance; if (lastUpdateTime != null) { nativeInstance.delete(nativeRef, _getNativePrecondition(lastUpdateTime)); } else { nativeInstance.delete(nativeRef); } } } /// A write batch, used to perform multiple writes as a single atomic unit. /// /// A [WriteBatch] object can be acquired by calling [Firestore.batch]. It /// provides methods for adding writes to the write batch. None of the /// writes will be committed (or visible locally) until [WriteBatch.commit] /// is called. /// /// Unlike transactions, write batches are persisted offline and therefore are /// preferable when you don't need to condition your writes on read data. class WriteBatch { final js.WriteBatch nativeInstance; WriteBatch(this.nativeInstance); /// Write to the document referred to by the provided [documentRef]. /// If the document does not exist yet, it will be created. If you pass /// [options], the provided data can be merged into the existing document. void setData(DocumentReference documentRef, DocumentData data, [js.SetOptions options]) { final docData = data.nativeInstance; final nativeRef = documentRef.nativeInstance; if (options != null) { nativeInstance.set(nativeRef, docData, options); } else { nativeInstance.set(nativeRef, docData); } } /// Updates fields in the document referred to by this [documentRef]. /// The update will fail if applied to a document that does not exist. /// /// Nested fields can be updated by providing dot-separated field path strings. void updateData(DocumentReference documentRef, UpdateData data) => nativeInstance.update(documentRef.nativeInstance, data.nativeInstance); /// Deletes the document referred to by the provided [documentRef]. void delete(DocumentReference documentRef) => nativeInstance.delete(documentRef.nativeInstance); /// Commits all of the writes in this write batch as a single atomic unit. Future commit() => promiseToFuture(nativeInstance.commit()); } /// An options object that configures conditional behavior of [update] and /// [delete] calls in [DocumentReference], [WriteBatch], and [Transaction]. /// Using Preconditions, these calls can be restricted to only apply to /// documents that match the specified restrictions. js.Precondition _getNativePrecondition(Timestamp lastUpdateTime) { assert(lastUpdateTime != null, 'Precontition lastUpdateTime can`t be null'); final ts = _createJsTimestamp(lastUpdateTime); return new js.Precondition(lastUpdateTime: ts); } /// An options object that configures the behavior of [set] calls in /// [DocumentReference], [WriteBatch] and [Transaction]. These calls can be /// configured to perform granular merges instead of overwriting the target /// documents in their entirety by providing a [SetOptions] with [merge]: true. js.SetOptions _getNativeSetOptions(bool merge) { assert(merge != null, 'SetOption merge can`t be null'); return new js.SetOptions(merge: merge); } class _FieldValueDelete implements FieldValue { @override dynamic _jsify() { return js.admin.firestore.FieldValue.delete(); } @override String toString() => 'FieldValue.delete()'; } class _FieldValueServerTimestamp implements FieldValue { @override dynamic _jsify() { return js.admin.firestore.FieldValue.serverTimestamp(); } @override String toString() => 'FieldValue.serverTimestamp()'; } abstract class _FieldValueArray implements FieldValue { final List elements; _FieldValueArray(this.elements); } class _FieldValueArrayUnion extends _FieldValueArray { _FieldValueArrayUnion(List elements) : super(elements); @override _jsify() { return callMethod(js.admin.firestore.FieldValue, 'arrayUnion', _FirestoreData._jsifyList(elements)); } @override String toString() => 'FieldValue.arrayUnion($elements)'; } class _FieldValueArrayRemove extends _FieldValueArray { _FieldValueArrayRemove(List elements) : super(elements); @override _jsify() { return callMethod(js.admin.firestore.FieldValue, 'arrayRemove', _FirestoreData._jsifyList(elements)); } @override String toString() => 'FieldValue.arrayRemove($elements)'; } /// Sentinel values that can be used when writing document fields with set() /// or update(). abstract class FieldValue { factory FieldValue._fromJs(dynamic jsFieldValue) { if (jsFieldValue == js.admin.firestore.FieldValue.delete()) { return Firestore.fieldValues.delete(); } else if (jsFieldValue == js.admin.firestore.FieldValue.serverTimestamp()) { return Firestore.fieldValues.serverTimestamp(); } else { throw ArgumentError.value(jsFieldValue, 'jsFieldValue', "Invalid value provided. We don't support dartfying object like arrayUnion or arrayRemove since not needed"); } } dynamic _jsify(); } class FieldValues { /// Returns a sentinel used with set() or update() to include a /// server-generated timestamp in the written data. FieldValue serverTimestamp() => _serverTimestamp; /// Returns a sentinel for use with update() to mark a field for deletion. FieldValue delete() => _delete; /// Returns a special value that tells the server to union the given elements /// with any array value that already exists on the server. /// /// Can be used with set(), create() or update() operations. /// /// Each specified element that doesn't already exist in the array will be /// added to the end. If the field being modified is not already an array it /// will be overwritten with an array containing exactly the specified /// elements. FieldValue arrayUnion(List elements) => _FieldValueArrayUnion(elements); /// Returns a special value that tells the server to remove the given elements /// from any array value that already exists on the server. /// /// Can be used with set(), create() or update() operations. /// /// All instances of each element specified will be removed from the array. /// If the field being modified is not already an array it will be overwritten /// with an empty array. FieldValue arrayRemove(List elements) => _FieldValueArrayRemove(elements); FieldValues._(); final FieldValue _serverTimestamp = _FieldValueServerTimestamp(); final FieldValue _delete = _FieldValueDelete(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_admin_interop
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_admin_interop/src/firestore_bindings.dart
@JS() library firestore; import "package:js/js.dart"; import "package:node_interop/node.dart"; import "package:node_interop/stream.dart"; @JS() @anonymous abstract class FirestoreModule { /// Sets the log function for all active Firestore instances. external void setLogFunction(void logger(String msg)); external Function get Firestore; external GeoPointUtil get GeoPoint; external FieldValues get FieldValue; /// Reference to constructor function of [FieldPath]. /// /// See also: /// - [FieldPathPrototype] which exposes static members of this class. /// - [documentId] which is a convenience function to create sentinel /// [FieldPath] to refer to the ID of a document. external dynamic get FieldPath; external TimestampProto get Timestamp; } @JS() @anonymous abstract class TimestampProto { external Timestamp now(); external Timestamp fromDate(Date date); external Timestamp fromMillis(int milliseconds); } @JS() @anonymous abstract class Timestamp { external int get seconds; external int get nanoseconds; external Date toDate(); external int toMillis(); } @JS() @anonymous abstract class GeoPointUtil { external GeoPoint fromProto(proto); } @JS() @anonymous abstract class GeoPointProto { external factory GeoPointProto({num latitude, num longitude}); external num get latitude; external num get longitude; } /// Document data (for use with `DocumentReference.set()`) consists of fields /// mapped to values. @JS() @anonymous abstract class DocumentData {} /// Update data (for use with `DocumentReference.update()`) consists of field /// paths (e.g. 'foo' or 'foo.baz') mapped to values. Fields that contain dots /// reference nested fields within the document. @JS() @anonymous abstract class UpdateData {} /// `Firestore` represents a Firestore Database and is the entry point for all /// Firestore operations. @JS() @anonymous abstract class Firestore { /// Gets a `CollectionReference` instance that refers to the collection at /// the specified path. external CollectionReference collection(String collectionPath); /// Creates and returns a new Query that includes all documents in the /// database that are contained in a collection or subcollection with the /// given [collectionId]. /// /// [collectionId] identifies the collections to query over. Every collection /// or subcollection with this ID as the last segment of its path will be /// included. Cannot contain a slash. external DocumentQuery collectionGroup(String collectionId); /// Gets a `DocumentReference` instance that refers to the document at the /// specified path. external DocumentReference doc(String documentPath); /// Retrieves multiple documents from Firestore. /// snapshots. external Promise getAll( [DocumentReference documentRef1, DocumentReference documentRef2, DocumentReference documentRef3, DocumentReference documentRef4, DocumentReference documentRef5]); /// Fetches the root collections that are associated with this Firestore /// database. external Promise listCollections(); /// Executes the given updateFunction and commits the changes applied within /// the transaction. /// /// You can use the transaction object passed to [updateFunction] to read and /// modify Firestore documents under lock. Transactions are committed once /// [updateFunction] resolves and attempted up to five times on failure. /// /// /// If the transaction completed successfully or was explicitly aborted /// (by the [updateFunction] returning a failed Future), the Future /// returned by the updateFunction will be returned here. Else if the /// transaction failed, a rejected Future with the corresponding failure error /// will be returned. external Promise runTransaction( Promise updateFunction(Transaction transaction)); /// Creates a write batch, used for performing multiple writes as a single /// atomic operation. external WriteBatch batch(); /// Specifies custom settings to be used to configure the `Firestore` /// instance. /// /// Can only be invoked once and before any other [Firestore] method. external void settings(FirestoreSettings value); } @JS() @anonymous abstract class FirestoreSettings { /// The Firestore Project ID. /// /// Can be omitted in environments that support `Application Default Credentials`. external String get projectId; /// Local file containing the Service Account credentials. /// /// Can be omitted in environments that support `Application Default Credentials`. external String get keyFilename; /// Enables the use of `Timestamp`s for timestamp fields in /// `DocumentSnapshot`s. /// /// Currently, Firestore returns timestamp fields as `Date` but `Date` only /// supports millisecond precision, which leads to truncation and causes /// unexpected behavior when using a timestamp from a snapshot as a part /// of a subsequent query. /// /// Setting `timestampsInSnapshots` to true will cause Firestore to return /// `Timestamp` values instead of `Date` avoiding this kind of problem. To /// make this work you must also change any code that uses `Date` to use /// `Timestamp` instead. /// /// NOTE: in the future `timestampsInSnapshots: true` will become the /// default and this option will be removed so you should change your code to /// use `Timestamp` now and opt-in to this new behavior as soon as you can. external bool get timestampsInSnapshots; external factory FirestoreSettings({ String projectId, String keyFilename, bool timestampsInSnapshots, }); } /// An immutable object representing a geo point in Firestore. The geo point /// is represented as latitude/longitude pair. /// Latitude values are in the range of [-90, 90]. /// Longitude values are in the range of [-180, 180]. @JS() @anonymous abstract class GeoPoint { external num get latitude; external num get longitude; } /// A reference to a transaction. /// The `Transaction` object passed to a transaction's updateFunction provides /// the methods to read and write data within the transaction context. See /// `Firestore.runTransaction()`. @JS() @anonymous abstract class Transaction { /// Reads the document referenced by the provided `DocumentReference.` /// Holds a pessimistic lock on the returned document. /*external Promise<DocumentSnapshot> get(DocumentReference documentRef);*/ /// Retrieves a query result. Holds a pessimistic lock on the returned /// documents. /*external Promise<QuerySnapshot> get(Query query);*/ external Promise /*Promise<DocumentSnapshot>|Promise<QuerySnapshot>*/ get( dynamic /*DocumentReference|Query*/ documentRef_query); /// Create the document referred to by the provided `DocumentReference`. /// The operation will fail the transaction if a document exists at the /// specified location. external Transaction create(DocumentReference documentRef, DocumentData data); /// Writes to the document referred to by the provided `DocumentReference`. /// If the document does not exist yet, it will be created. If you pass /// `SetOptions`, the provided data can be merged into the existing document. external Transaction set(DocumentReference documentRef, DocumentData data, [SetOptions options]); /// Updates fields in the document referred to by the provided /// `DocumentReference`. The update will fail if applied to a document that /// does not exist. /// Nested fields can be updated by providing dot-separated field path /// strings. /// update the document. /*external Transaction update(DocumentReference documentRef, UpdateData data, [Precondition precondition]);*/ /// Updates fields in the document referred to by the provided /// `DocumentReference`. The update will fail if applied to a document that /// does not exist. /// Nested fields can be updated by providing dot-separated field path /// strings or by providing FieldPath objects. /// A `Precondition` restricting this update can be specified as the last /// argument. /// to update, optionally followed by a `Precondition` to enforce on this /// update. /*external Transaction update(DocumentReference documentRef, String|FieldPath field, dynamic value, [dynamic fieldsOrPrecondition1, dynamic fieldsOrPrecondition2, dynamic fieldsOrPrecondition3, dynamic fieldsOrPrecondition4, dynamic fieldsOrPrecondition5]);*/ external Transaction update( DocumentReference documentRef, dynamic /*String|FieldPath*/ data_field, [dynamic /*Precondition|dynamic*/ precondition_value, List<dynamic> fieldsOrPrecondition]); /// Deletes the document referred to by the provided `DocumentReference`. external Transaction delete(DocumentReference documentRef, [Precondition precondition]); } /// A write batch, used to perform multiple writes as a single atomic unit. /// /// A [WriteBatch] object can be acquired by calling [Firestore.batch]. It /// provides methods for adding writes to the write batch. None of the /// writes will be committed (or visible locally) until [WriteBatch.commit] /// is called. /// /// Unlike transactions, write batches are persisted offline and therefore are /// preferable when you don't need to condition your writes on read data. @JS() @anonymous abstract class WriteBatch { /// Create the document referred to by the provided [DocumentReference]. The /// operation will fail the batch if a document exists at the specified /// location. external WriteBatch create(DocumentReference documentRef, DocumentData data); /// Write to the document referred to by the provided [DocumentReference]. /// If the document does not exist yet, it will be created. If you pass /// [options], the provided data can be merged into the existing document. external WriteBatch set(DocumentReference documentRef, DocumentData data, [SetOptions options]); /// Updates fields in the document referred to by this DocumentReference. /// The update will fail if applied to a document that does not exist. /// /// Nested fields can be updated by providing dot-separated field path strings external WriteBatch update(DocumentReference documentRef, UpdateData data); /// Deletes the document referred to by the provided `DocumentReference`. external WriteBatch delete(DocumentReference documentRef); /// Commits all of the writes in this write batch as a single atomic unit. external Promise commit(); } /// An options object that configures conditional behavior of `update()` and /// `delete()` calls in `DocumentReference`, `WriteBatch`, and `Transaction`. /// Using Preconditions, these calls can be restricted to only apply to /// documents that match the specified restrictions. @JS() @anonymous abstract class Precondition { /// If set, the last update time to enforce (specified as an ISO 8601 /// string). external Timestamp get lastUpdateTime; external set lastUpdateTime(Timestamp v); external factory Precondition({Timestamp lastUpdateTime}); } /// An options object that configures the behavior of `set()` calls in /// `DocumentReference`, `WriteBatch` and `Transaction`. These calls can be /// configured to perform granular merges instead of overwriting the target /// documents in their entirety by providing a `SetOptions` with `merge: true`. @JS() @anonymous abstract class SetOptions { /// Changes the behavior of a set() call to only replace the values specified /// in its data argument. Fields omitted from the set() call remain /// untouched. external bool get merge; external set merge(bool v); external factory SetOptions({bool merge}); } /// A WriteResult wraps the write time set by the Firestore servers on `sets()`, /// `updates()`, and `creates()`. @JS() @anonymous abstract class WriteResult { /// The write time as set by the Firestore servers. Formatted as an ISO-8601 /// string. external Timestamp get writeTime; external set writeTime(Timestamp v); } /// A `DocumentReference` refers to a document location in a Firestore database /// and can be used to write, read, or listen to the location. The document at /// the referenced location may or may not exist. A `DocumentReference` can /// also be used to create a `CollectionReference` to a subcollection. @JS() @anonymous abstract class DocumentReference { /// The identifier of the document within its collection. external String get id; external set id(String v); /// The `Firestore` for the Firestore database (useful for performing /// transactions, etc.). external Firestore get firestore; external set firestore(Firestore v); /// A reference to the Collection to which this DocumentReference belongs. external CollectionReference get parent; external set parent(CollectionReference v); /// A string representing the path of the referenced document (relative /// to the root of the database). external String get path; external set path(String v); /// Gets a `CollectionReference` instance that refers to the collection at /// the specified path. external CollectionReference collection(String collectionPath); /// Fetches the subcollections that are direct children of this document. external Promise listCollections(); /// Creates a document referred to by this `DocumentReference` with the /// provided object values. The write fails if the document already exists external Promise create(DocumentData data); /// Writes to the document referred to by this `DocumentReference`. If the /// document does not yet exist, it will be created. If you pass /// `SetOptions`, the provided data can be merged into an existing document. external Promise set(DocumentData data, [SetOptions options]); /// Updates fields in the document referred to by this `DocumentReference`. /// The update will fail if applied to a document that does not exist. /// Nested fields can be updated by providing dot-separated field path /// strings. /// update the document. external Promise update(UpdateData data, [Precondition precondition]); /// Updates fields in the document referred to by this `DocumentReference`. /// The update will fail if applied to a document that does not exist. /// Nested fields can be updated by providing dot-separated field path /// strings or by providing FieldPath objects. /// A `Precondition` restricting this update can be specified as the last /// argument. /// values to update, optionally followed by a `Precondition` to enforce on /// this update. /*external Promise<WriteResult> update(String|FieldPath field, dynamic value, [dynamic moreFieldsOrPrecondition1, dynamic moreFieldsOrPrecondition2, dynamic moreFieldsOrPrecondition3, dynamic moreFieldsOrPrecondition4, dynamic moreFieldsOrPrecondition5]);*/ // external Promise update(dynamic /*String|FieldPath*/ data_field, // [dynamic /*Precondition|dynamic*/ precondition_value, // List<dynamic> moreFieldsOrPrecondition]); /// Deletes the document referred to by this `DocumentReference`. external Promise delete([Precondition precondition]); /// Reads the document referred to by this `DocumentReference`. /// current document contents. external Promise get(); /// Attaches a listener for DocumentSnapshot events. /// is available. /// cancelled. No further callbacks will occur. /// the snapshot listener. external Function onSnapshot(void onNext(DocumentSnapshot snapshot), [void onError(Error error)]); } /// A `DocumentSnapshot` contains data read from a document in your Firestore /// database. The data can be extracted with `.data()` or `.get(<field>)` to /// get a specific field. /// For a `DocumentSnapshot` that points to a non-existing document, any data /// access will return 'undefined'. You can use the `exists` property to /// explicitly verify a document's existence. @JS() @anonymous abstract class DocumentSnapshot { /// True if the document exists. external bool get exists; external set exists(bool v); /// A `DocumentReference` to the document location. external DocumentReference get ref; external set ref(DocumentReference v); /// The ID of the document for which this `DocumentSnapshot` contains data. external String get id; external set id(String v); /// The time the document was created. Not set for documents that don't /// exist. external Timestamp get createTime; external set createTime(Timestamp v); /// The time the document was last updated (at the time the snapshot was /// generated). Not set for documents that don't exist. external Timestamp get updateTime; external set updateTime(Timestamp v); /// The time this snapshot was read. external Timestamp get readTime; external set readTime(Timestamp v); /// Retrieves all fields in the document as an Object. Returns 'undefined' if /// the document doesn't exist. external dynamic /*DocumentData|dynamic*/ data(); /// Retrieves the field specified by `fieldPath`. /// field exists in the document. external dynamic get(dynamic /*String|FieldPath*/ fieldPath); } /// A `QueryDocumentSnapshot` contains data read from a document in your /// Firestore database as part of a query. The document is guaranteed to exist /// and its data can be extracted with `.data()` or `.get(<field>)` to get a /// specific field. /// A `QueryDocumentSnapshot` offers the same API surface as a /// `DocumentSnapshot`. Since query results contain only existing documents, the /// `exists` property will always be true and `data()` will never return /// 'undefined'. @JS() @anonymous abstract class QueryDocumentSnapshot extends DocumentSnapshot { /// The time the document was created. external Timestamp get createTime; external set createTime(Timestamp v); /// The time the document was last updated (at the time the snapshot was /// generated). external Timestamp get updateTime; external set updateTime(Timestamp v); /// Retrieves all fields in the document as an Object. /// @override external DocumentData data(); } /// The direction of a `Query.orderBy()` clause is specified as 'desc' or 'asc' /// (descending or ascending). /*export type OrderByDirection = 'desc' | 'asc';*/ /// Filter conditions in a `Query.where()` clause are specified using the /// strings '<', '<=', '==', '>=', and '>'. /*export type WhereFilterOp = '<' | '<=' | '==' | '>=' | '>';*/ /// A `Query` refers to a Query which you can read or listen to. You can also /// construct refined `Query` objects by adding filters and ordering. @JS() @anonymous abstract class DocumentQuery { /// The `Firestore` for the Firestore database (useful for performing /// transactions, etc.). external Firestore get firestore; external set firestore(Firestore v); /// Creates and returns a new Query with the additional filter that documents /// must contain the specified field and that its value should satisfy the /// relation constraint provided. /// This function returns a new (immutable) instance of the Query (rather /// than modify the existing instance) to impose the filter. external DocumentQuery where(dynamic /*String|FieldPath*/ fieldPath, String /*'<'|'<='|'=='|'>='|'>'*/ opStr, dynamic value); /// Creates and returns a new Query that's additionally sorted by the /// specified field, optionally in descending order instead of ascending. /// This function returns a new (immutable) instance of the Query (rather /// than modify the existing instance) to impose the order. /// not specified, order will be ascending. external DocumentQuery orderBy(dynamic /*String|FieldPath*/ fieldPath, [String /*'desc'|'asc'*/ directionStr]); /// Creates and returns a new Query that's additionally limited to only /// return up to the specified number of documents. /// This function returns a new (immutable) instance of the Query (rather /// than modify the existing instance) to impose the limit. external DocumentQuery limit(num limit); /// Specifies the offset of the returned results. /// This function returns a new (immutable) instance of the Query (rather /// than modify the existing instance) to impose the offset. external DocumentQuery offset(num offset); /// Creates and returns a new Query instance that applies a field mask to /// the result and returns only the specified subset of fields. You can /// specify a list of field paths to return, or use an empty list to only /// return the references of matching documents. /// This function returns a new (immutable) instance of the Query (rather /// than modify the existing instance) to impose the field mask. external DocumentQuery select( [dynamic /*String|FieldPath*/ field1, dynamic /*String|FieldPath*/ field2, dynamic /*String|FieldPath*/ field3, dynamic /*String|FieldPath*/ field4, dynamic /*String|FieldPath*/ field5]); /// Creates and returns a new Query that starts at the provided document /// (inclusive). The starting position is relative to the order of the query. /// The document must contain all of the fields provided in the orderBy of /// this query. /*external Query startAt(DocumentSnapshot snapshot);*/ /// Creates and returns a new Query that starts at the provided fields /// relative to the order of the query. The order of the field values /// must match the order of the order by clauses of the query. /// of the query's order by. /*external Query startAt( [dynamic fieldValues1, dynamic fieldValues2, dynamic fieldValues3, dynamic fieldValues4, dynamic fieldValues5]);*/ external DocumentQuery startAt( dynamic /*DocumentSnapshot|List<dynamic>*/ snapshot_fieldValues); /// Creates and returns a new Query that starts after the provided document /// (exclusive). The starting position is relative to the order of the query. /// The document must contain all of the fields provided in the orderBy of /// this query. /*external Query startAfter(DocumentSnapshot snapshot);*/ /// Creates and returns a new Query that starts after the provided fields /// relative to the order of the query. The order of the field values /// must match the order of the order by clauses of the query. /// of the query's order by. /*external Query startAfter( [dynamic fieldValues1, dynamic fieldValues2, dynamic fieldValues3, dynamic fieldValues4, dynamic fieldValues5]);*/ external DocumentQuery startAfter( dynamic /*DocumentSnapshot|List<dynamic>*/ snapshot_fieldValues); /// Creates and returns a new Query that ends before the provided document /// (exclusive). The end position is relative to the order of the query. The /// document must contain all of the fields provided in the orderBy of this /// query. /*external Query endBefore(DocumentSnapshot snapshot);*/ /// Creates and returns a new Query that ends before the provided fields /// relative to the order of the query. The order of the field values /// must match the order of the order by clauses of the query. /// of the query's order by. /*external Query endBefore( [dynamic fieldValues1, dynamic fieldValues2, dynamic fieldValues3, dynamic fieldValues4, dynamic fieldValues5]);*/ external DocumentQuery endBefore( dynamic /*DocumentSnapshot|List<dynamic>*/ snapshot_fieldValues); /// Creates and returns a new Query that ends at the provided document /// (inclusive). The end position is relative to the order of the query. The /// document must contain all of the fields provided in the orderBy of this /// query. /*external Query endAt(DocumentSnapshot snapshot);*/ /// Creates and returns a new Query that ends at the provided fields /// relative to the order of the query. The order of the field values /// must match the order of the order by clauses of the query. /// of the query's order by. /*external Query endAt( [dynamic fieldValues1, dynamic fieldValues2, dynamic fieldValues3, dynamic fieldValues4, dynamic fieldValues5]);*/ external DocumentQuery endAt( dynamic /*DocumentSnapshot|List<dynamic>*/ snapshot_fieldValues); /// Executes the query and returns the results as a `QuerySnapshot`. external Promise get(); /// Executes the query and returns the results as Node Stream. external Readable stream(); /// Attaches a listener for `QuerySnapshot `events. /// is available. /// cancelled. No further callbacks will occur. /// the snapshot listener. external Function onSnapshot(void onNext(QuerySnapshot snapshot), [void onError(Error error)]); } /// A `QuerySnapshot` contains zero or more `QueryDocumentSnapshot` objects /// representing the results of a query. The documents can be accessed as an /// array via the `docs` property or enumerated using the `forEach` method. The /// number of documents can be determined via the `empty` and `size` /// properties. @JS() @anonymous abstract class QuerySnapshot { /// The query on which you called `get` or `onSnapshot` in order to get this /// `QuerySnapshot`. external DocumentQuery get query; external set query(DocumentQuery v); /// An array of the documents that changed since the last snapshot. If this /// is the first snapshot, all documents will be in the list as added /// changes. external List<DocumentChange> docChanges(); /// An array of all the documents in the QuerySnapshot. external List<QueryDocumentSnapshot> get docs; external set docs(List<QueryDocumentSnapshot> v); /// The number of documents in the QuerySnapshot. external num get size; external set size(num v); /// True if there are no documents in the QuerySnapshot. external bool get empty; external set empty(bool v); /// The time this query snapshot was obtained. external Timestamp get readTime; external set readTime(Timestamp v); /// Enumerates all of the documents in the QuerySnapshot. /// each document in the snapshot. external void forEach(void callback(QueryDocumentSnapshot result), [dynamic thisArg]); } /// The type of of a `DocumentChange` may be 'added', 'removed', or 'modified'. /*export type DocumentChangeType = 'added' | 'removed' | 'modified';*/ /// A `DocumentChange` represents a change to the documents matching a query. /// It contains the document affected and the type of change that occurred. @JS() @anonymous abstract class DocumentChange { /// The type of change ('added', 'modified', or 'removed'). external String /*'added'|'removed'|'modified'*/ get type; external set type(String /*'added'|'removed'|'modified'*/ v); /// The document affected by this change. external QueryDocumentSnapshot get doc; external set doc(QueryDocumentSnapshot v); /// The index of the changed document in the result set immediately prior to /// this DocumentChange (i.e. supposing that all prior DocumentChange objects /// have been applied). Is -1 for 'added' events. external num get oldIndex; external set oldIndex(num v); /// The index of the changed document in the result set immediately after /// this DocumentChange (i.e. supposing that all prior DocumentChange /// objects and the current DocumentChange object have been applied). /// Is -1 for 'removed' events. external num get newIndex; external set newIndex(num v); external factory DocumentChange( {String /*'added'|'removed'|'modified'*/ type, QueryDocumentSnapshot doc, num oldIndex, num newIndex}); } /// A `CollectionReference` object can be used for adding documents, getting /// document references, and querying for documents (using the methods /// inherited from `Query`). @JS() @anonymous abstract class CollectionReference extends DocumentQuery { /// The identifier of the collection. external String get id; external set id(String v); /// A reference to the containing Document if this is a subcollection, else /// null. external DocumentReference /*DocumentReference|Null*/ get parent; external set parent(DocumentReference /*DocumentReference|Null*/ v); /// A string representing the path of the referenced collection (relative /// to the root of the database). external String get path; external set path(String v); /// Get a `DocumentReference` for the document within the collection at the /// specified path. If no path is specified, an automatically-generated /// unique ID will be used for the returned DocumentReference. external DocumentReference doc([String documentPath]); /// Add a new document to this collection with the specified data, assigning /// it a document ID automatically. /// newly created document after it has been written to the backend. external Promise add(DocumentData data); } /// Sentinel values that can be used when writing document fields with set() /// or update(). @JS() @anonymous abstract class FieldValues { /// Returns a sentinel used with set() or update() to include a /// server-generated timestamp in the written data. external FieldValue serverTimestamp(); /// Returns a sentinel for use with update() to mark a field for deletion. external FieldValue delete(); /// Returns a special value that tells the server to union the given elements /// with any array value that already exists on the server. /// /// Can be used with set(), create() or update() operations. /// /// Each specified element that doesn't already exist in the array will be /// added to the end. If the field being modified is not already an array it /// will be overwritten with an array containing exactly the specified /// elements. external FieldValue arrayUnion(List elements); /// Returns a special value that tells the server to remove the given elements /// from any array value that already exists on the server. /// /// Can be used with set(), create() or update() operations. /// /// All instances of each element specified will be removed from the array. /// If the field being modified is not already an array it will be overwritten /// with an empty array. external FieldValue arrayRemove(List elements); } @JS() @anonymous abstract class FieldValue {} @JS() @anonymous abstract class FieldPathPrototype { /// Returns a special sentinel FieldPath to refer to the ID of a document. /// It can be used in queries to sort or filter by the document ID. external FieldPath documentId(); } /// A FieldPath refers to a field in a document. The path may consist of a /// single field name (referring to a top-level field in the document), or a /// list of field names (referring to a nested field in the document). @JS() abstract class FieldPath { /// Creates a FieldPath from the provided field names. If more than one field /// name is provided, the path will point to a nested field in a document. external factory FieldPath( [String fieldNames1, String fieldNames2, String fieldNames3, String fieldNames4, String fieldNames5]); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_admin_interop
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_admin_interop/src/bindings.dart
// Copyright (c) 2017, Anatoly Pulyaevskiy. All rights reserved. Use of this source code // is governed by a BSD-style license that can be found in the LICENSE file. @JS() library firebase_admin; import 'package:js/js.dart'; import 'package:node_interop/node.dart'; import 'firestore_bindings.dart' show Firestore, GeoPointUtil, FieldValues; export 'firestore_bindings.dart'; // admin ========================================================================= const defaultAppName = '[DEFAULT]'; /// Singleton instance of [FirebaseAdmin] module. final FirebaseAdmin admin = require('firebase-admin'); @JS() @anonymous abstract class FirebaseAdmin { /// Creates and initializes a Firebase app instance. external App initializeApp([options, String name]); /// The current SDK version. external String get SDK_VERSION; /// A (read-only) array of all initialized apps. external List<App> get apps; /// Retrieves a Firebase [App] instance. /// /// When called with no arguments, the default app is returned. When an app /// [name] is provided, the app corresponding to that name is returned. /// /// An exception is thrown if the app being retrieved has not yet been /// initialized. external App app([String name]); /// Gets the [Auth] service for the default app or a given [app]. external Auth auth([App app]); /// Gets the [Database] service for the default app or a given [app]. external DatabaseService get database; /// Gets the [Firestore] client for the default app or a given [app]. external FirestoreService get firestore; external Credentials get credential; /// Gets the [Messaging] service for the default app or a given [app]. external Messaging messaging([App app]); } @JS() @anonymous abstract class FirebaseError implements JsError { /// Error codes are strings using the following format: /// "service/string-code". Some examples include "auth/invalid-uid" and /// "messaging/invalid-recipient". /// /// While the message for a given error can change, the code will remain the /// same between backward-compatible versions of the Firebase SDK. external String get code; } @JS() @anonymous abstract class FirebaseArrayIndexError { external FirebaseError get error; external num get index; } // admin.credential ============================================================ @JS() @anonymous abstract class Credentials { /// Returns a [Credential] created from the Google Application Default /// Credentials (ADC) that grants admin access to Firebase services. /// /// This credential can be used in the call to [initializeApp]. external Credential applicationDefault(); /// Returns [Credential] created from the provided service account that grants /// admin access to Firebase services. /// /// This credential can be used in the call to [initializeApp]. /// [credentials] must be a path to a service account key JSON file or an /// object representing a service account key. external Credential cert(credentials); /// Returns [Credential] created from the provided refresh token that grants /// admin access to Firebase services. /// /// This credential can be used in the call to [initializeApp]. external Credential refreshToken(refreshTokenPathOrObject); } @JS() @anonymous abstract class ServiceAccountConfig { external String get project_id; external String get client_email; external String get private_key; external factory ServiceAccountConfig( {String project_id, String client_email, String private_key}); } /// Interface which provides Google OAuth2 access tokens used to authenticate /// with Firebase services. @JS() @anonymous abstract class Credential { /// Returns a Google OAuth2 [AccessToken] object used to authenticate with /// Firebase services. external AccessToken getAccessToken(); } /// Google OAuth2 access token object used to authenticate with Firebase /// services. @JS() @anonymous abstract class AccessToken { /// The actual Google OAuth2 access token. external String get access_token; /// The number of seconds from when the token was issued that it expires. external num get expires_in; } // admin.app =================================================================== /// A Firebase app holds the initialization information for a collection of /// services. @JS() @anonymous abstract class App { /// The name for this app. /// /// The default app's name is `[DEFAULT]`. external String get name; /// The (read-only) configuration options for this app. These are the original /// parameters given in [initializeApp]. external AppOptions get options; /// Gets the [Auth] service for this app. external Auth auth(); /// Gets the [Database] service for this app. external Database database(); /// Renders this app unusable and frees the resources of all associated /// services. external Promise delete(); /// Gets the [Firestore] client for this app. external Firestore firestore(); /// Gets the [Messaging] service for this app. external Messaging messaging(); } /// Available options to pass to [initializeApp]. @JS() @anonymous abstract class AppOptions { /// A [Credential] object used to authenticate the Admin SDK. /// /// You can obtain a credential via one of the following methods: /// /// - [applicationDefaultCredential] /// - [cert] /// - [refreshToken] external Credential get credential; /// The URL of the Realtime Database from which to read and write data. external String get databaseURL; /// The ID of the Google Cloud project associated with the App. external String get projectId; /// The name of the default Cloud Storage bucket associated with the App. external String get storageBucket; /// Creates new instance of [AppOptions]. external factory AppOptions({ Credential credential, String databaseURL, String projectId, String storageBucket, }); } // admin.auth ================================================================== /// The Firebase Auth service interface. @JS() @anonymous abstract class Auth { /// The app associated with this Auth service instance. external App get app; /// Creates a new Firebase custom token (JWT) that can be sent back to a client /// device to use to sign in with the client SDKs' signInWithCustomToken() /// methods. /// /// Returns a promise fulfilled with a custom token string for the provided uid /// and payload. external Promise createCustomToken(String uid, developerClaims); /// Creates a new user. /// /// Returns a promise fulfilled with [UserRecord] corresponding to the newly /// created user. external Promise createUser(CreateUserRequest properties); /// Deletes an existing user. /// /// Returns a promise containing `void`. external Promise deleteUser(String uid); /// Gets the user data for the user corresponding to a given [uid]. /// /// Returns a promise fulfilled with [UserRecord] corresponding to the provided /// [uid]. external Promise getUser(String uid); /// Gets the user data for the user corresponding to a given [email]. /// /// Returns a promise fulfilled with [UserRecord] corresponding to the provided /// [email]. external Promise getUserByEmail(String email); /// Gets the user data for the user corresponding to a given [phoneNumber]. /// /// Returns a promise fulfilled with [UserRecord] corresponding to the provided /// [phoneNumber]. external Promise getUserByPhoneNumber(String phoneNumber); /// Retrieves a list of users (single batch only) with a size of [maxResults] /// and starting from the offset as specified by [pageToken]. /// /// This is used to retrieve all the users of a specified project in batches. /// /// Returns a promise that resolves with the current batch of downloaded users /// and the next page token as an instance of [ListUsersResult]. external Promise listUsers([num maxResults, String pageToken]); /// Revokes all refresh tokens for an existing user. /// /// This API will update the user's [UserRecord.tokensValidAfterTime] to the /// current UTC. It is important that the server on which this is called has /// its clock set correctly and synchronized. /// /// While this will revoke all sessions for a specified user and disable any /// new ID tokens for existing sessions from getting minted, existing ID tokens /// may remain active until their natural expiration (one hour). To verify that /// ID tokens are revoked, use [Auth.verifyIdToken] where `checkRevoked` is set /// to `true`. /// /// Returns a promise containing `void`. external Promise revokeRefreshTokens(String uid); /// Sets additional developer claims on an existing user identified by the /// provided uid, typically used to define user roles and levels of access. /// /// These claims should propagate to all devices where the user is already /// signed in (after token expiration or when token refresh is forced) and the /// next time the user signs in. If a reserved OIDC claim name is used /// (sub, iat, iss, etc), an error is thrown. They will be set on the /// authenticated user's ID token JWT. /// /// [customUserClaims] can be `null`. /// /// Returns a promise containing `void`. external Promise setCustomUserClaims(String uid, customUserClaims); /// Updates an existing user. /// /// Returns a promise containing updated [UserRecord]. external Promise updateUser(String uid, UpdateUserRequest properties); /// Verifies a Firebase ID token (JWT). /// /// If the token is valid, the returned promise is fulfilled with an instance of /// [DecodedIdToken]; otherwise, the promise is rejected. An optional flag can /// be passed to additionally check whether the ID token was revoked. external Promise verifyIdToken(String idToken, [bool checkRevoked]); } @JS() @anonymous abstract class CreateUserRequest { external bool get disabled; external String get displayName; external String get email; external bool get emailVerified; external String get password; external String get phoneNumber; external String get photoURL; external String get uid; external factory CreateUserRequest({ bool disabled, String displayName, String email, bool emailVerified, String password, String phoneNumber, String photoURL, String uid, }); } @JS() @anonymous abstract class UpdateUserRequest { external bool get disabled; external String get displayName; external String get email; external bool get emailVerified; external String get password; external String get phoneNumber; external String get photoURL; external factory UpdateUserRequest({ bool disabled, String displayName, String email, bool emailVerified, String password, String phoneNumber, String photoURL, }); } /// Interface representing a user. @JS() @anonymous abstract class UserRecord { /// The user's custom claims object if available, typically used to define user /// roles and propagated to an authenticated user's ID token. /// /// This is set via [Auth.setCustomUserClaims]. external get customClaims; /// Whether or not the user is disabled: true for disabled; false for enabled. external bool get disabled; /// The user's display name. external String get displayName; /// The user's primary email, if set. external String get email; /// Whether or not the user's primary email is verified. external bool get emailVerified; /// Additional metadata about the user. external UserMetadata get metadata; /// The user’s hashed password (base64-encoded), only if Firebase Auth hashing /// algorithm (SCRYPT) is used. /// /// If a different hashing algorithm had been used when uploading this user, /// typical when migrating from another Auth system, this will be an empty /// string. If no password is set, this will be`null`. /// /// This is only available when the user is obtained from [Auth.listUsers]. external String get passwordHash; /// The user’s password salt (base64-encoded), only if Firebase Auth hashing /// algorithm (SCRYPT) is used. /// /// If a different hashing algorithm had been used to upload this user, typical /// when migrating from another Auth system, this will be an empty string. /// If no password is set, this will be `null`. /// /// This is only available when the user is obtained from [Auth.listUsers]. external String get passwordSalt; /// The user's primary phone number or `null`. external String get phoneNumber; /// The user's photo URL or `null`. external String get photoURL; /// An array of providers (for example, Google, Facebook) linked to the user. external List<UserInfo> get providerData; /// The date the user's tokens are valid after, formatted as a UTC string. /// /// This is updated every time the user's refresh token are revoked either from /// the [Auth.revokeRefreshTokens] API or from the Firebase Auth backend on big /// account changes (password resets, password or email updates, etc). external String get tokensValidAfterTime; /// The user's uid. external String get uid; external dynamic toJSON(); } @JS() @anonymous abstract class UserMetadata { /// The date the user was created, formatted as a UTC string. external String get creationTime; /// The date the user last signed in, formatted as a UTC string. external String get lastSignInTime; } /// Interface representing a user's info from a third-party identity provider /// such as Google or Facebook. @JS() @anonymous abstract class UserInfo { /// The display name for the linked provider. external String get displayName; /// The email for the linked provider. external String get email; /// The phone number for the linked provider. external String get phoneNumber; /// The photo URL for the linked provider. external String get photoURL; /// The linked provider ID (for example, "google.com" for the Google provider). external String get providerId; /// The user identifier for the linked provider. external String get uid; external dynamic toJSON(); } /// Interface representing a resulting object returned from a [Auth.listUsers] /// operation containing the list of users for the current batch and the next /// page token if available. @JS() @anonymous abstract class ListUsersResult { external String get pageToken; external List<UserRecord> get users; } /// Interface representing a decoded Firebase ID token, returned from the /// [Auth.verifyIdToken] method. @JS() @anonymous abstract class DecodedIdToken { /// The audience for which this token is intended. /// /// This value is a string equal to your Firebase project ID, the unique /// identifier for your Firebase project, which can be found in your project's /// settings. external String get aud; /// Time, in seconds since the Unix epoch, when the end-user authentication /// occurred. /// /// This value is not when this particular ID token was created, but when the /// user initially logged in to this session. In a single session, the Firebase /// SDKs will refresh a user's ID tokens every hour. Each ID token will have a /// different [iat] value, but the same auth_time value. external num get auth_time; /// The ID token's expiration time, in seconds since the Unix epoch. /// /// That is, the time at which this ID token expires and should no longer be /// considered valid. /// /// The Firebase SDKs transparently refresh ID tokens every hour, issuing a new /// ID token with up to a one hour expiration. external num get exp; /// Information about the sign in event, including which sign in provider was /// used and provider-specific identity details. /// /// This data is provided by the Firebase Authentication service and is a /// reserved claim in the ID token. external FirebaseSignInInfo get firebase; /// The ID token's issued-at time, in seconds since the Unix epoch. /// /// That is, the time at which this ID token was issued and should start to /// be considered valid. /// /// The Firebase SDKs transparently refresh ID tokens every hour, issuing a new /// ID token with a new issued-at time. If you want to get the time at which /// the user session corresponding to the ID token initially occurred, see the /// [auth_time] property. external num get iat; /// The issuer identifier for the issuer of the response. /// /// This value is a URL with the format /// `https://securetoken.google.com/<PROJECT_ID>`, where <PROJECT_ID> is the /// same project ID specified in the [aud] property. external String get iss; /// The uid corresponding to the user who the ID token belonged to. /// /// As a convenience, this value is copied over to the [uid] property. external String get sub; /// The uid corresponding to the user who the ID token belonged to. /// /// This value is not actually in the JWT token claims itself. It is added as a /// convenience, and is set as the value of the [sub] property. external String get uid; } @JS() @anonymous abstract class FirebaseSignInInfo { /// Provider-specific identity details corresponding to the provider used to /// sign in the user. external get identities; /// The ID of the provider used to sign in the user. One of "anonymous", /// "password", "facebook.com", "github.com", "google.com", "twitter.com", /// or "custom". external String get sign_in_provider; } // admin.firestore =============================================================== @JS() @anonymous abstract class FirestoreService { external GeoPointUtil get GeoPoint; external FieldValues get FieldValue; external dynamic get Timestamp; external dynamic get FieldPath; } // admin.messaging ================================================================ /// The Firebase Messaging service interface. @JS() @anonymous abstract class Messaging { /// The app associated with this Messaging service instance. external App get app; /// Sends the given message via FCM. /// /// Returns Promise<string> fulfilled with a unique message ID string after the /// message has been successfully handed off to the FCM service for delivery external Promise send(FcmMessage message, [bool dryRun]); /// Sends all the messages in the given array via Firebase Cloud Messaging. /// /// Returns Promise<BatchResponse> fulfilled with an object representing the /// result of the send operation. external Promise sendAll(List<FcmMessage> messages, [bool dryRun]); /// Sends the given multicast message to all the FCM registration tokens /// specified in it. /// /// Returns Promise<BatchResponse> fulfilled with an object representing the /// result of the send operation. external Promise sendMulticast(MulticastMessage message, [bool dryRun]); /// Sends an FCM message to a condition. /// /// Returns Promise<MessagingConditionResponse> fulfilled with the server's /// response after the message has been sent. external Promise sendToCondition(String condition, MessagingPayload payload, [MessagingOptions options]); /// Sends an FCM message to a single device corresponding to the provided /// registration token. /// /// Returns Promise<MessagingDevicesResponse> fulfilled with the server's /// response after the message has been sent. external Promise sendToDevice( String registrationToken, MessagingPayload payload, [MessagingOptions options]); /// Sends an FCM message to a device group corresponding to the provided /// notification key. /// /// Returns Promise<MessagingDevicesResponse> fulfilled with the server's /// response after the message has been sent. external Promise sendToDeviceGroup( String notificationKey, MessagingPayload payload, [MessagingOptions options]); /// Sends an FCM message to a topic. /// /// Returns Promise<MessagingTopicResponse> fulfilled with the server's /// response after the message has been sent. external Promise sendToTopic(String topic, MessagingPayload payload, [MessagingOptions options]); /// Subscribes a device to an FCM topic. /// /// Returns Promise<MessagingTopicManagementResponse> fulfilled with the /// server's response after the device has been subscribed to the topic. external Promise subscribeToTopic(String registrationTokens, String topic); /// Unsubscribes a device from an FCM topic. /// /// Returns Promise<MessagingTopicManagementResponse> fulfilled with the /// server's response after the device has been subscribed to the topic. external Promise unsubscribeFromTopic( String registrationTokens, String topic); } @JS() @anonymous abstract class FcmMessage { external String get data; external Notification get notification; external String get token; external factory FcmMessage({ String data, Notification notification, String token, }); } @JS() @anonymous abstract class TopicMessage { external AndroidConfig get android; external ApnsConfig get apns; external dynamic get data; external String get key; external FcmOptions get fcmOptions; external Notification get notification; /// Required external String get topic; external WebpushConfig get webpush; external factory TopicMessage({ AndroidConfig android, ApnsConfig apns, dynamic data, String key, FcmOptions fcmOptions, Notification notification, String topic, WebpushConfig webpush, }); } @JS() @anonymous abstract class TokenMessage { external AndroidConfig get android; external ApnsConfig get apns; external dynamic get data; external String get key; external FcmOptions get fcmOptions; external Notification get notification; /// Required external String get token; external WebpushConfig get webpush; external factory TokenMessage({ AndroidConfig android, ApnsConfig apns, dynamic data, String key, FcmOptions fcmOptions, Notification notification, String token, WebpushConfig webpush, }); } @JS() @anonymous abstract class ConditionMessage { external AndroidConfig get android; external ApnsConfig get apns; /// Required external String get condition; external dynamic get data; external String get key; external FcmOptions get fcmOptions; external Notification get notification; external WebpushConfig get webpush; external factory ConditionMessage({ AndroidConfig android, ApnsConfig apns, String condition, dynamic data, String key, FcmOptions fcmOptions, Notification notification, WebpushConfig webpush, }); } @JS() @anonymous abstract class MulticastMessage { external AndroidConfig get android; external ApnsConfig get apns; external dynamic get data; external String get key; external FcmOptions get fcmOptions; external Notification get notification; /// Required external List<String> get tokens; external WebpushConfig get webpush; external factory MulticastMessage({ AndroidConfig android, ApnsConfig apns, dynamic data, String key, FcmOptions fcmOptions, Notification notification, List<String> tokens, WebpushConfig webpush, }); } /// A notification that can be included in admin.messaging.Message. @JS() @anonymous abstract class Notification { /// The notification body external String get body; /// URL of an image to be displayed in the notification. external String get imageUrl; /// The title of the notification. external String get title; external factory Notification({ String body, String imageUrl, String title, }); } /// Represents the WebPush-specific notification options that can be included /// in admin.messaging.WebpushConfig. @JS() @anonymous abstract class WebpushNotification { /// An array of notification actions representing the actions available to /// the user when the notification is presented. external List<dynamic> get actions; /// URL of the image used to represent the notification when there is not /// enough space to display the notification itself. external String get badge; /// Body text of the notification. external String get body; /// Arbitrary data that you want associated with the notification. This can /// be of any data type. external dynamic get data; /// The direction in which to display the notification. Must be one of auto, /// ltr or rtl. external String get dir; /// URL to the notification icon. external String get icon; /// URL of an image to be displayed in the notification. external String get image; /// The notification's language as a BCP 47 language tag. external String get lang; /// A boolean specifying whether the user should be notified after a new /// notification replaces an old one. Defaults to false. external bool get renotify; /// Indicates that a notification should remain active until the user clicks /// or dismisses it, rather than closing automatically. /// /// Defaults to false. external bool get requireInteraction; /// A boolean specifying whether the notification should be silent. /// /// Defaults to false. external bool get silent; /// An identifying tag for the notification. external String get tag; /// Timestamp of the notification external num get timestamp; /// Title text of the notification. external String get title; /// A vibration pattern for the device's vibration hardware to emit when the /// notification fires. external num get vibrate; external factory WebpushNotification({ List<dynamic> actions, String badge, String body, dynamic data, String dir, String icon, String image, String lang, bool renotify, bool requireInteraction, bool silent, String tag, num timestamp, String title, num vibrate, }); } /// Represents the WebPush protocol options that can be included in an /// admin.messaging.Message. @JS() @anonymous abstract class WebpushConfig { /// A collection of data fields. external dynamic get data; /// Options for features provided by the FCM SDK for Web. external FcmOptions get fcmOptions; /// A collection of WebPush headers. Header values must be strings. external dynamic get headers; /// A WebPush notification payload to be included in the message. external WebpushNotification get notification; external factory WebpushConfig({ dynamic data, FcmOptions fcmOptions, dynamic headers, WebpushNotification notification, }); } /// Represents options for features provided by the FCM SDK for Web (which are /// not part of the Webpush standard). @JS() @anonymous abstract class WebpushFcmOptions { /// The link to open when the user clicks on the notification. For all URL /// values, HTTPS is required. external String get link; external factory WebpushFcmOptions({ String link, }); } /// Options for features provided by the FCM SDK for Web. @JS() @anonymous abstract class FcmOptions { /// The label associated with the message's analytics data. external String get analyticsLabel; external factory FcmOptions({ String analyticsLabel, }); } /// Interface representing a Firebase Cloud Messaging message payload. One or /// both of the data and notification keys are required. @JS() @anonymous abstract class MessagingPayload { /// The data message payload. external DataMessagePayload get data; /// The notification message payload. external NotificationMessagePayload get notification; external factory MessagingPayload({ DataMessagePayload data, NotificationMessagePayload notification, }); } /// Interface representing an FCM legacy API data message payload. /// /// Data messages let developers send up to 4KB of custom key-value pairs. /// The keys and values must both be strings. @JS() @anonymous abstract class DataMessagePayload { /// Keys can be any custom string, except for the following reserved strings: /// "from" and anything starting with "google." external String get key; external dynamic get value; external factory DataMessagePayload({ String key, dynamic value, }); } /// Interface representing an FCM legacy API notification message payload. /// Notification messages let developers send up to 4KB of predefined key-value /// pairs. @JS() @anonymous abstract class NotificationMessagePayload { /// An array of notification actions representing the actions available to /// the user when the notification is presented. external List<dynamic> get actions; /// URL of the image used to represent the notification when there is not /// enough space to display the notification itself. external String get badge; /// Body text of the notification. external String get body; /// Variable string values to be used in place of the format specifiers in /// body_loc_key to use to localize the body text to the user's current /// localization. /// /// The value should be a stringified JSON array. external String get bodyLocArgs; /// The key to the body string in the app's string resources to use to /// localize the body text to the user's current localization. external String get bodyLocKey; /// Action associated with a user click on the notification. If specified, /// an activity with a matching Intent Filter is launched when a user clicks /// on the notification. external String get clickAction; /// The notification icon's color, expressed in #rrggbb format. external String get color; /// URL to the notification icon. external String get icon; /// Identifier used to replace existing notifications in the notification /// drawer. external String get sound; /// An identifying tag for the notification. external String get tag; /// The notification's title. external String get title; /// Variable string values to be used in place of the format specifiers in /// title_loc_key to use to localize the title text to the user's current /// localization. The value should be a stringified JSON array. external String get titleLocArgs; /// The key to the title string in the app's string resources to use to /// localize the title text to the user's current localization. external String get titleLocKey; external factory NotificationMessagePayload({ List<dynamic> actions, String badge, String body, String bodyLocArgs, String bodyLocKey, String clickAction, String color, String icon, String sound, String tag, String title, String titleLocArgs, String titleLocKey, }); } /// Interface representing the options that can be provided when sending a /// message via the FCM legacy APIs. @JS() @anonymous abstract class MessagingOptions { /// String identifying a group of messages (for example, "Updates Available") /// that can be collapsed, so that only the last message gets sent when /// delivery can be resumed. This is used to avoid sending too many of the /// same messages when the device comes back online or becomes active. external String get collapseKey; /// On iOS, use this field to represent content-available in the APNs payload. /// /// When a notification or data message is sent and this is set to true, /// an inactive client app is awoken. On Android, data messages wake the app /// by default. On Chrome, this flag is currently not supported. external bool get contentAvailable; /// Whether or not the message should actually be sent. /// /// When set to true, allows developers to test a request without actually /// sending a message. When set to false, the message will be sent. external bool get dryRun; /// On iOS, use this field to represent mutable-content in the APNs payload. /// /// When a notification is sent and this is set to true, the content of the /// notification can be modified before it is displayed, using a Notification /// Service app extension. On Android and Web, this parameter will be ignored. external bool get mutableContent; /// The priority of the message. Valid values are "normal" and "high". /// /// On iOS, these correspond to APNs priorities 5 and 10. external String get priority; /// The package name of the application which the registration tokens must /// match in order to receive the message. external String get restrictedPackageName; /// How long (in seconds) the message should be kept in FCM storage if the /// device is offline. /// /// The maximum time to live supported is four weeks, and the default value /// is also four weeks. external num get timeToLive; external factory MessagingOptions({ String collapseKey, bool contentAvailable, bool dryRun, bool mutableContent, String priority, String restrictedPackageName, num timeToLive, }); } /// Represents the Android-specific options that can be included in an /// admin.messaging.Message. @JS() @anonymous abstract class AndroidConfig { /// Collapse key for the message. /// /// Collapse key serves as an identifier for a group of messages that can be /// collapsed, so that only the last message gets sent when delivery can be /// resumed. A maximum of four different collapse keys may be active at any /// given time. external String get collapseKey; /// A collection of data fields to be included in the message. /// /// All values must be strings. When provided, overrides any data fields /// set on the top-level admin.messaging.Message. external dynamic get data; /// Options for features provided by the FCM SDK for Android. external AndroidFcmOptions get fcmOptions; /// Android notification to be included in the message. external AndroidNotification get notification; /// Priority of the message. Must be either normal or high. external String get priority; /// Package name of the application where the registration tokens must match /// in order to receive the message. external String get restrictedPackageName; /// Time-to-live duration of the message in milliseconds. external num get ttl; external factory AndroidConfig({ String collapseKey, dynamic data, AndroidFcmOptions fcmOptions, AndroidNotification notification, String priority, String restrictedPackageName, num ttl, }); } /// Represents options for features provided by the FCM SDK for Android. @JS() @anonymous abstract class AndroidFcmOptions { /// The label associated with the message's analytics data. external String get analyticsLabel; external factory AndroidFcmOptions({ String analyticsLabel, }); } /// Represents the Android-specific notification options that can be included /// in admin.messaging.AndroidConfig. @JS() @anonymous abstract class AndroidNotification { /// Body of the Android notification. When provided, overrides the body set /// via admin.messaging.Notification external String get body; /// An array of resource keys that will be used in place of the format /// specifiers in bodyLocKey. external List<String> get bodyLocArgs; /// The key to the body string in the app's string resources to use to /// localize the body text to the user's current localization. external String get bodyLocKey; /// The Android notification channel ID (new in Android O). external String get channelId; /// Action associated with a user click on the notification. /// /// If specified, an activity with a matching Intent Filter is launched when /// a user clicks on the notification. external String get clickAction; /// Notification icon color in #rrggbb format. external String get color; /// Icon resource for the Android notification. external String get icon; /// URL of an image to be displayed in the notification. external String get imageUrl; /// File name of the sound to be played when the device receives the /// notification. external String get sound; /// Notification tag. /// /// This is an identifier used to replace existing notifications in the /// notification drawer. If not specified, each request creates a new /// notification. external String get tag; /// Title of the Android notification. When provided, overrides the title set /// via admin.messaging.Notification. external String get title; /// An array of resource keys that will be used in place of the format /// specifiers in titleLocKey. external List<String> get titleLocArgs; /// Key of the title string in the app's string resource to use to localize /// the title text. external String get titleLocKey; external factory AndroidNotification({ String body, List<String> bodyLocArgs, String bodyLocKey, String channelId, String clickAction, String color, String icon, String imageUrl, String sound, String tag, String title, List<String> titleLocArgs, String titleLocKey, }); } /// Represents the APNs-specific options that can be included in an /// admin.messaging.Message. @JS() @anonymous abstract class ApnsConfig { /// Options for features provided by the FCM SDK for iOS. external ApnsFcmOptions get fcmOptions; /// A collection of APNs headers. Header values must be strings. external dynamic get headers; /// An APNs payload to be included in the message. external ApnsPayload get payload; external factory ApnsConfig({ ApnsFcmOptions fcmOptions, dynamic headers, ApnsPayload payload, }); } /// Represents options for features provided by the FCM SDK for iOS. @JS() @anonymous abstract class ApnsFcmOptions { /// The label associated with the message's analytics data. external String get analyticsLabel; /// URL of an image to be displayed in the notification. external String get imageUrl; external factory ApnsFcmOptions({String analyticsLabel, String imageUrl}); } /// Represents options for features provided by the FCM SDK for iOS. @JS() @anonymous abstract class ApnsPayload { /// The aps dictionary to be included in the message. external Aps get aps; external factory ApnsPayload({ Aps aps, }); } /// Represents the aps dictionary that is part of APNs messages. @JS() @anonymous abstract class Aps { /// Alert to be included in the message. This may be a string or an object of /// type admin.messaging.ApsAlert external String get alert; /// Badge to be displayed with the message. /// /// Set to 0 to remove the badge. When not specified, the badge will remain /// unchanged. external num get badge; /// Type of the notification. external String get category; /// Specifies whether to configure a background update notification. external bool get contentAvailable; /// Specifies whether to set the mutable-content property on the message so /// the clients can modify the notification via app extensions. external bool get mutableContent; /// Sound to be played with the message. external String get sound; /// An app-specific identifier for grouping notifications. external String get threadId; external factory Aps({ String alert, num badge, String category, bool contentAvailable, bool mutableContent, String sound, }); } @JS() @anonymous abstract class ApsAlert { external String get actionLocKey; external String get body; external String get launchImage; external List<String> get locArgs; external String get locKey; external String get subtitle; external List<String> get subtitleLocArgs; external String get subtitleLocKey; external String get title; external List<String> get titleLocArgs; external String get titleLocKey; external factory ApsAlert({ String actionLocKey, String body, String launchImage, List<String> locArgs, String locKey, String subtitle, List<String> subtitleLocArgs, String subtitleLocKey, String title, List<String> titleLocArgs, String titleLocKey, }); } /// Represents a critical sound configuration that can be included in the aps /// dictionary of an APNs payload. @JS() @anonymous abstract class CriticalSound { /// The critical alert flag. Set to true to enable the critical alert. external bool get critical; /// The name of a sound file in the app's main bundle or in the /// Library/Sounds folder of the app's container directory. /// /// Specify the string "default" to play the system sound. external String get name; /// The volume for the critical alert's sound. /// /// Must be a value between 0.0 (silent) and 1.0 (full volume). external num get volume; external factory CriticalSound({ bool critical, String name, num volume, }); } /// Interface representing the server response from the sendAll() and /// sendMulticast() methods. @JS() @anonymous abstract class BatchResponse { /// The number of messages that resulted in errors when sending. external num get failureCount; /// An array of responses, each corresponding to a message. external List<SendResponse> get responses; /// The number of messages that were successfully handed off for sending. external num get successCount; external factory BatchResponse({ num failureCount, List<SendResponse> responses, num successCount, }); } /// Interface representing the status of an individual message that was sent /// as part of a batch request. @JS() @anonymous abstract class SendResponse { /// An error, if the message was not handed off to FCM successfully. external FirebaseError get error; /// A unique message ID string, if the message was handed off to FCM for /// delivery. external String get messageId; /// A boolean indicating if the message was successfully handed off to FCM /// or not. /// /// When true, the messageId attribute is guaranteed to be set. When false, /// the error attribute is guaranteed to be set. external bool get success; external factory SendResponse({ FirebaseError error, String messageId, bool success, }); } /// Interface representing the server response from the legacy /// sendToCondition() method. @JS() @anonymous abstract class MessagingConditionResponse { /// The message ID for a successfully received request which FCM will attempt /// to deliver to all subscribed devices. external num get messageId; external factory MessagingConditionResponse({ num messageId, }); } /// Interface representing the server response from the sendToDeviceGroup() /// method. @JS() @anonymous abstract class MessagingDeviceGroupResponse { /// An array of registration tokens that failed to receive the message. external List<String> get failedRegistrationTokens; /// The number of messages that could not be processed and resulted in an error. external num get failureCount; /// The number of messages that could not be processed and resulted in an error. external num get successCount; external factory MessagingDeviceGroupResponse({ List<String> failedRegistrationTokens, num failureCount, num successCount, }); } /// Interface representing the status of a message sent to an individual device /// via the FCM legacy APIs. @JS() @anonymous abstract class MessagingDeviceResult { /// The canonical registration token for the client app that the message was /// processed and sent to. /// /// You should use this value as the registration token for future requests. /// Otherwise, future messages might be rejected. external String get canonicalRegistrationToken; /// The error that occurred when processing the message for the recipient. external FirebaseError get error; /// A unique ID for the successfully processed message. external String get messageId; external factory MessagingDeviceResult({ String canonicalRegistrationToken, FirebaseError error, String messageId, }); } /// Interface representing the server response from the legacy sendToDevice() /// method. @JS() @anonymous abstract class MessagingDevicesResponse { /// The number of results that contain a canonical registration token. /// /// A canonical registration token is the registration token corresponding /// to the last registration requested by the client app. This is the token /// that you should use when sending future messages to the device. You can /// access the canonical registration tokens within the results property. external num get canonicalRegistrationTokenCount; /// The number of messages that could not be processed and resulted in an /// error. external num get failureCount; /// The unique ID number identifying this multicast message. external num get multicastId; /// An array of [MessagingDeviceResult] objects representing the status of the /// processed messages. /// /// The objects are listed in the same order as in the request. That is, for /// each registration token in the request, its result has the same index in /// this array. If only a single registration token is provided, this array /// will contain a single object. external List<MessagingDeviceResult> get results; /// The number of messages that were successfully processed and sent. external num get successCount; external factory MessagingDevicesResponse({ num canonicalRegistrationTokenCount, num failureCount, num multicastId, List<MessagingDeviceResult> results, num successCount, }); } /// Interface representing the server response from the legacy sendToTopic() /// method. @JS() @anonymous abstract class MessagingTopicResponse { /// The message ID for a successfully received request which FCM will attempt /// to deliver to all subscribed devices. external num get messageId; external factory MessagingTopicResponse({ num messageId, }); } /// Interface representing the server response from the subscribeToTopic() and /// admin.messaging.Messaging#unsubscribeFromTopic unsubscribeFromTopic() /// methods. @JS() @anonymous abstract class MessagingTopicManagementResponse { /// An array of errors corresponding to the provided registration token(s). /// /// The length of this array will be equal to failureCount. external List<FirebaseArrayIndexError> get errors; /// The number of registration tokens that could not be subscribed to the /// topic and resulted in an error. external num get failureCount; /// The number of registration tokens that were successfully subscribed to /// the topic. external num get successCount; external factory MessagingTopicManagementResponse({ List<FirebaseArrayIndexError> errors, num failureCount, num successCount, }); } // admin.database ================================================================ @JS() @anonymous abstract class DatabaseService { // Implementing call method breaks dart2js. // external Database call([App app]); /// Logs debugging information to the console. external enableLogging([dynamic loggerOrBool, bool persistent]); external ServerValues get ServerValue; } /// A placeholder value for auto-populating the current timestamp (time since /// the Unix epoch, in milliseconds) as determined by the Firebase servers. @JS() @anonymous abstract class ServerValues { external num get TIMESTAMP; } /// The Firebase Database interface. /// /// Access via [FirebaseAdmin.database]. @JS() @anonymous abstract class Database { /// The app associated with this Database instance. external App get app; /// Disconnects from the server (all Database operations will be completed /// offline). external void goOffline(); /// Reconnects to the server and synchronizes the offline Database state with /// the server state. external void goOnline(); /// Returns a [Reference] representing the location in the Database /// corresponding to the provided [path]. If no path is provided, the /// Reference will point to the root of the Database. external Reference ref([String path]); /// Returns a Reference representing the location in the Database /// corresponding to the provided Firebase URL. external Reference refFromURL(String url); } /// A Reference represents a specific location in your [Database] and can be /// used for reading or writing data to that Database location. @JS() @anonymous abstract class Reference extends Query { /// The last part of this Reference's path. /// /// For example, "ada" is the key for `https://<DB>.firebaseio.com/users/ada`. /// The key of a root [Reference] is `null`. external String get key; /// The parent location of this Reference. /// /// The parent of a root Reference is `null`. external Reference get parent; /// The root `Reference` of the [Database]. external Reference get root; /// Gets a `Reference` for the location at the specified relative [path]. /// /// The relative [path] can either be a simple child name (for example, "ada") /// or a deeper slash-separated path (for example, "ada/name/first"). external Reference child(String path); /// Returns an [OnDisconnect] object. /// /// For more information on how to use it see /// [Enabling Offline Capabilities in JavaScript](https://firebase.google.com/docs/database/web/offline-capabilities). external OnDisconnect onDisconnect(); /// Generates a new child location using a unique key and returns its /// [Reference]. /// /// This is the most common pattern for adding data to a collection of items. /// /// If you provide a [value] to `push()`, the value will be written to the /// generated location. If you don't pass a value, nothing will be written to /// the Database and the child will remain empty (but you can use the /// [Reference] elsewhere). /// /// The unique key generated by this method are ordered by the current time, /// so the resulting list of items will be chronologically sorted. The keys /// are also designed to be unguessable (they contain 72 random bits of /// entropy). external ThenableReference push([value, onComplete(JsError error)]); /// Removes the data at this Database location. /// /// Any data at child locations will also be deleted. /// /// The effect of the remove will be visible immediately and the corresponding /// event 'value' will be triggered. Synchronization of the remove to the /// Firebase servers will also be started, and the returned [Promise] will /// resolve when complete. If provided, the [onComplete] callback will be /// called asynchronously after synchronization has finished. external Promise remove([onComplete(JsError error)]); /// Writes data to this Database location. /// /// This will overwrite any data at this location and all child locations. /// /// The effect of the write will be visible immediately, and the corresponding /// events ("value", "child_added", etc.) will be triggered. Synchronization /// of the data to the Firebase servers will also be started, and the returned /// [Promise] will resolve when complete. If provided, the [onComplete] /// callback will be called asynchronously after synchronization has finished. /// /// Passing `null` for the new value is equivalent to calling [remove]; /// namely, all data at this location and all child locations will be deleted. /// /// [set] will remove any priority stored at this location, so if priority is /// meant to be preserved, you need to use [setWithPriority] instead. /// /// Note that modifying data with [set] will cancel any pending transactions /// at that location, so extreme care should be taken if mixing [set] and /// [transaction] to modify the same data. /// /// A single [set] will generate a single "value" event at the location where /// the `set()` was performed. external Promise set(value, [onComplete(JsError error)]); /// Sets a priority for the data at this Database location. /// /// Applications need not use priority but can order collections by ordinary /// properties. /// /// See also: /// - [Sorting and filtering data](https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data) external Promise setPriority(priority, [onComplete(JsError error)]); /// Writes data the Database location. Like [set] but also specifies the /// [priority] for that data. /// /// Applications need not use priority but can order collections by ordinary /// properties. /// /// See also: /// - [Sorting and filtering data](https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data) external Promise setWithPriority(value, priority, [onComplete(JsError error)]); /// Atomically modifies the data at this location. /// /// Atomically modify the data at this location. Unlike a normal [set), which /// just overwrites the data regardless of its previous value, [transaction] /// is used to modify the existing value to a new value, ensuring there are no /// conflicts with other clients writing to the same location at the same time. /// /// To accomplish this, you pass transaction() an update function which is used /// to transform the current value into a new value. If another client writes to /// the location before your new value is successfully written, your update /// function will be called again with the new current value, and the write will /// be retried. This will happen repeatedly until your write succeeds without /// conflict or you abort the transaction by not returning a value from your /// update function. /// Note: Modifying data with [set] will cancel any pending transactions at that /// location, so extreme care should be taken if mixing set() and transaction() /// to update the same data. /// Note: When using transactions with Security and Firebase Rules in place, be /// aware that a client needs .read access in addition to .write access in order /// to perform a transaction. This is because the client-side nature of /// transactions requires the client to read the data in order to /// transactionally update it. external Promise transaction(transactionUpdate(snapshot), onComplete(error, bool committed, snapshot), bool applyLocally); /// Writes multiple values to the Database at once. /// /// The [values] argument contains multiple property-value pairs that will be /// written to the Database together. Each child property can either be a simple /// property (for example, "name") or a relative path (for example, /// "name/first") from the current location to the data to update. /// /// As opposed to the [set] method, [update] can be used to selectively update /// only the referenced properties at the current location (instead of replacing /// all the child properties at the current location). /// /// The effect of the write will be visible immediately, and the corresponding /// events ('value', 'child_added', etc.) will be triggered. Synchronization of /// the data to the Firebase servers will also be started, and the returned /// `Promise` will resolve when complete. /// /// If provided, the [onComplete] callback will be called asynchronously after /// synchronization has finished. /// /// A single [update] will generate a single "value" event at the location where /// the `update` was performed, regardless of how many children were modified. /// /// Note that modifying data with [update] will cancel any pending transactions /// at that location, so extreme care should be taken if mixing [update] and /// [transaction] to modify the same data. /// /// Passing `null` to [update] will remove the data at this location. external Promise update(values, [onComplete(JsError error)]); } @JS() @anonymous abstract class TransactionResult { bool get committed; DataSnapshot get snapshot; } @JS() @anonymous abstract class ThenableReference extends Reference implements Promise {} /// Allows you to write or clear data when your client disconnects from the /// [Database] server. These updates occur whether your client disconnects /// cleanly or not, so you can rely on them to clean up data even if a /// connection is dropped or a client crashes. /// /// This class is most commonly used to manage presence in applications where it /// is useful to detect how many clients are connected and when other clients /// disconnect. See [Enabling Offline Capabilities in JavaScript](https://firebase.google.com/docs/database/web/offline-capabilities) /// for more information. /// /// To avoid problems when a connection is dropped before the requests can be /// transferred to the Database server, these functions should be called before /// any data is written. /// /// Note that `onDisconnect` operations are only triggered once. If you want an /// operation to occur each time a disconnect occurs, you'll need to /// re-establish the onDisconnect operations each time you reconnect. @JS() @anonymous abstract class OnDisconnect { /// Cancels all previously queued `onDisconnect()` set or update events for /// this location and all children. /// /// If a write has been queued for this location via a [set] or [update] at a /// parent location, the write at this location will be canceled, though all /// other siblings will still be written. /// /// Optional [onComplete] function that will be called when synchronization to /// the server has completed. The callback will be passed a single parameter: /// `null` for success, or a [JsError] object indicating a failure. external Promise cancel([onComplete(JsError error)]); /// Ensures the data at this location is deleted when the client is /// disconnected (due to closing the browser, navigating to a new page, or /// network issues). /// /// Optional [onComplete] function that will be called when synchronization to /// the server has completed. The callback will be passed a single parameter: /// `null` for success, or a [JsError] object indicating a failure. external Promise remove([onComplete(JsError error)]); /// Ensures the data at this location is set to the specified [value] when the /// client is disconnected (due to closing the browser, navigating to a new /// page, or network issues). /// /// [set] is especially useful for implementing "presence" systems, where a /// value should be changed or cleared when a user disconnects so that they /// appear "offline" to other users. /// /// Optional [onComplete] function that will be called when synchronization to /// the server has completed. The callback will be passed a single parameter: /// `null` for success, or a [JsError] object indicating a failure. /// /// See also: /// - [Enabling Offline Capabilities in JavaScript](https://firebase.google.com/docs/database/web/offline-capabilities) external Promise set(value, [onComplete(JsError error)]); /// Ensures the data at this location is set to the specified [value] and /// [priority] when the client is disconnected (due to closing the browser, /// navigating to a new page, or network issues). external Promise setWithPriority(value, priority, [onComplete(JsError error)]); /// Writes multiple [values] at this location when the client is disconnected /// (due to closing the browser, navigating to a new page, or network issues). /// /// The [values] argument contains multiple property-value pairs that will be /// written to the Database together. Each child property can either be a /// simple property (for example, "name") or a relative path (for example, /// "name/first") from the current location to the data to update. /// /// As opposed to the [set] method, [update] can be use to selectively update /// only the referenced properties at the current location (instead of /// replacing all the child properties at the current location). /// /// See [Reference.update] for examples of using the connected version of /// update. external Promise update(values, [onComplete(JsError error)]); } /// Sorts and filters the data at a [Database] location so only a subset of the /// child data is included. /// /// This can be used to order a collection of data by some attribute (for /// example, height of dinosaurs) as well as to restrict a large list of items /// (for example, chat messages) down to a number suitable for synchronizing to /// the client. Queries are created by chaining together one or more of the /// filter methods defined here. /// /// Just as with a [Reference], you can receive data from a [Query] by using /// the [on] method. You will only receive events and [DataSnapshot]s for the /// subset of the data that matches your query. /// /// See also: /// - [Sorting and filtering data](https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data) @JS() @anonymous abstract class Query { /// Returns a `Reference` to the [Query]'s location. external Reference get ref; /// Creates a [Query] with the specified ending point. /// /// Using [startAt], [endAt], and [equalTo] allows you to choose arbitrary /// starting and ending points for your queries. /// The ending point is inclusive, so children with exactly the specified /// value will be included in the query. The optional key argument can be used /// to further limit the range of the query. If it is specified, then children /// that have exactly the specified value must also have a key name less than /// or equal to the specified key. /// /// The [value] type depends on which `orderBy*()` function was used in this /// query. Specify a value that matches the `orderBy*()` type. When used in /// combination with [orderByKey], the value must be a `String`. /// /// Optional [key] is only allowed if ordering by priority and defines the /// child key to end at, among the children with the previously specified /// priority. external Query endAt(dynamic value, [String key]); /// Creates a [Query] that includes children that match the specified value. /// /// Using [startAt], [endAt], and [equalTo] allows you to choose arbitrary /// starting and ending points for your queries. /// /// The [value] type depends on which `orderBy*()` function was used in this /// query. Specify a value that matches the `orderBy*()` type. When used in /// combination with [orderByKey], the value must be a `String`. /// /// The optional [key] argument can be used to further limit the range of the /// query. If it is specified, then children that have exactly the specified /// value must also have exactly the specified key as their key name. This can /// be used to filter result sets with many matches for the same value. external Query equalTo(dynamic value, [String key]); /// Returns `true` if this and [other] query are equal. /// /// Returns whether or not the current and provided queries represent the same /// location, have the same query parameters, and are from the same instance /// of [App]. Equivalent queries share the same sort order, limits, and /// starting and ending points. /// /// Two [Reference] objects are equivalent if they represent the same location /// and are from the same instance of [App]. external bool isEqual(Query other); /// Generates a new [Query] limited to the first specific number of children. /// /// This method is used to set a maximum number of children to be synced for a /// given callback. If we set a limit of 100, we will initially only receive /// up to 100 child_added events. If we have fewer than 100 messages stored in /// our [Database], a child_added event will fire for each message. However, /// if we have over 100 messages, we will only receive a child_added event for /// the first 100 ordered messages. As items change, we will receive /// child_removed events for each item that drops out of the active list so /// that the total number stays at 100. external Query limitToFirst(num limit); /// Generates a new [Query] limited to the last specific number of children. /// /// This method is used to set a maximum number of children to be synced for a /// given callback. If we set a limit of 100, we will initially only receive /// up to 100 child_added events. If we have fewer than 100 messages stored in /// our Database, a child_added event will fire for each message. However, if /// we have over 100 messages, we will only receive a child_added event for /// the last 100 ordered messages. As items change, we will receive /// child_removed events for each item that drops out of the active list so /// that the total number stays at 100. external Query limitToLast(num limit); /// Detaches a callback previously attached with [on]. /// /// Note that if [on] was called multiple times with the same [eventType] and /// [callback], the callback will be called multiple times for each event, and /// [off] must be called multiple times to remove the callback. Calling [off] /// on a parent listener will not automatically remove listeners registered on /// child nodes, [off] must also be called on any child listeners to remove /// the callback. /// /// If a [callback] is not specified, all callbacks for the specified /// [eventType] will be removed. Similarly, if no [eventType] or [callback] is /// specified, all callbacks for the [Reference] will be removed. external void off([String eventType, callback, context]); /// Listens for data changes at a particular location. /// /// This is the primary way to read data from a [Database]. Your callback will /// be triggered for the initial data and again whenever the data changes. /// Use [off] to stop receiving updates. external void on(String eventType, callback, [cancelCallbackOrContext, context]); /// Listens for exactly one event of the specified [eventType], and then stops /// listening. /// /// This is equivalent to calling [on], and then calling [off] inside the /// callback function. See [on] for details on the event types. external Promise once(String eventType, [successCallback, failureCallbackOrContext, context]); /// Generates a new [Query] object ordered by the specified child key. /// /// Queries can only order by one key at a time. Calling [orderByChild] /// multiple times on the same query is an error. external Query orderByChild(String path); /// Generates a new [Query] object ordered by key. /// /// Sorts the results of a query by their (ascending) key values. /// /// See also: /// - [Sort data](https://firebase.google.com/docs/database/web/lists-of-data#sort_data) external Query orderByKey(); /// Generates a new [Query] object ordered by priority. /// /// Applications need not use priority but can order collections by ordinary /// properties. /// /// See also: /// - [Sort data](https://firebase.google.com/docs/database/web/lists-of-data#sort_data) external Query orderByPriority(); /// Generates a new [Query] object ordered by value. /// /// If the children of a query are all scalar values (string, number, or /// boolean), you can order the results by their (ascending) values. /// /// See also: /// - [Sort data](https://firebase.google.com/docs/database/web/lists-of-data#sort_data) external Query orderByValue(); /// Creates a [Query] with the specified starting point. /// /// The starting point is inclusive, so children with exactly the specified /// [value] will be included in the query. /// /// The optional [key] argument can be used to further limit the range of the /// query. If it is specified, then children that have exactly the specified /// [value] must also have a `key` name greater than or equal to the specified /// [key]. /// /// See also: /// - [Filtering data](https://firebase.google.com/docs/database/web/lists-of-data#filtering_data) external Query startAt(dynamic value, [String key]); /// Returns a JSON-serializable representation of this object. external dynamic toJSON(); /// Gets the absolute URL for this location. /// /// Returned URL is ready to be put into a browser, curl command, or /// [Database.refFromURL] call. Since all of those expect the URL to be /// url-encoded, [toString] returns an encoded URL. /// /// Append '.json' to the returned URL when typed into a browser to download /// JSON-formatted data. If the location is secured (that is, not publicly /// readable), you will get a permission-denied error. external String toString(); } /// Contains data from a Database location. /// /// Any time you read data from the Database, you receive the data as a /// [DataSnapshot]. A DataSnapshot is passed to the event callbacks you attach /// with [Reference.on] or [Reference.once]. You can extract the contents of the /// snapshot as a JavaScript object by calling the [val] method. Alternatively, /// you can traverse into the snapshot by calling [child] to return child /// snapshots (which you could then call [val] on). /// /// A DataSnapshot is an efficiently generated, immutable copy of the data at a /// Database location. It cannot be modified and will never change (to modify /// data, you always call the [set] method on a [Reference] directly). @JS() @anonymous abstract class DataSnapshot { /// The key (last part of the path) of the location of this DataSnapshot. /// /// The last token in a Database location is considered its key. For example, /// "ada" is the key for the `/users/ada/` node. Accessing the key on any /// DataSnapshot will return the key for the location that generated it. /// However, accessing the key on the root URL of a Database will return /// `null`. external String get key; /// The [Reference] for the location that generated this DataSnapshot. external Reference get ref; /// Gets another DataSnapshot for the location at the specified relative /// [path]. /// /// Passing a relative path to the [child] method of a DataSnapshot returns /// another DataSnapshot for the location at the specified relative path. The /// relative [path] can either be a simple child name (for example, "ada") or /// a deeper, slash-separated path (for example, "ada/name/first"). If the /// child location has no data, an empty DataSnapshot (that is, a DataSnapshot /// whose value is `null`) is returned. external DataSnapshot child(String path); /// Returns `true` if this DataSnapshot contains any data. /// /// It is slightly more efficient than using `snapshot.val() != null`. external bool exists(); /// Exports the entire contents of the DataSnapshot as a JavaScript object. /// /// The [exportVal] method is similar to [val], except priority information is /// included (if available), making it suitable for backing up your data. external dynamic exportVal(); /// Enumerates the top-level children in this DataSnapshot. /// /// The [action] function is called for each child DataSnapshot. The callback /// can return `true` to cancel further enumeration. /// /// This method returns `true` if enumeration was canceled due to your /// callback returning true. /// /// Because of the way JavaScript objects work, the ordering of data in the /// JavaScript object returned by [val] is not guaranteed to match the /// ordering on the server nor the ordering of child_added events. That is /// where [forEach] comes in handy. It guarantees the children of a /// DataSnapshot will be iterated in their query order. /// /// If no explicit `orderBy*()` method is used, results are returned ordered /// by key (unless priorities are used, in which case, results are returned by /// priority). external bool forEach(bool action(DataSnapshot child)); /// Gets the priority value of the data in this DataSnapshot. /// /// Applications need not use priority but can order collections by ordinary /// properties. /// /// See also: /// - [Sorting and filtering data](https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data) external dynamic getPriority(); /// Returns `true` if the specified child [path] has (non-null) data. external bool hasChild(String path); /// Returns whether or not this DataSnapshot has any non-null child /// properties. /// /// You can use [hasChildren] to determine if a DataSnapshot has any children. /// If it does, you can enumerate them using [forEach]. If it doesn't, then /// either this snapshot contains a primitive value (which can be retrieved /// with [val]) or it is empty (in which case, [val] will return `null`). external bool hasChildren(); /// Returns the number of child properties of this DataSnapshot. external num numChildren(); /// Returns a JSON-serializable representation of this object. external dynamic toJSON(); /// Extracts a JavaScript value from this DataSnapshot. /// /// Depending on the data in a DataSnapshot, the [val] method may return a /// scalar type (string, number, or boolean), an array, or an object. It may /// also return `null`, indicating that the DataSnapshot is empty (contains /// no data). external dynamic val(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_admin_interop
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_admin_interop/src/admin.dart
// Copyright (c) 2017, Anatoly Pulyaevskiy. 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:meta/meta.dart'; import 'app.dart'; import 'bindings.dart' as js; /// Provides access to Firebase Admin APIs. /// /// To start using Firebase services initialize a Firebase application /// with [initializeApp] method. class FirebaseAdmin { final js.FirebaseAdmin _admin; final Map<String, App> _apps = new Map(); static FirebaseAdmin get instance => _instance ??= new FirebaseAdmin._(); static FirebaseAdmin _instance; FirebaseAdmin._() : _admin = js.admin; /// /// Creates and initializes a Firebase [App] instance with the given /// [options] and [name]. /// /// The options is initialized with provided `credential` and `databaseURL`. /// A valid credential can be obtained with [cert] or /// [certFromPath]. /// /// The [name] argument allows using multiple Firebase applications at the same /// time. If omitted then default app name is used. /// /// Example: /// /// var certificate = FirebaseAdmin.instance.cert( /// projectId: 'your-project-id', /// clientEmail: 'your-client-email', /// privateKey: 'your-private-key', /// ); /// var app = FirebaseAdmin.instance.initializeApp( /// new AppOptions( /// credential: certificate, /// databaseURL: 'https://your-database.firebase.io') /// ); /// /// See also: /// * [App] /// * [cert] /// * [certFromPath] App initializeApp([js.AppOptions options, String name]) { if (options == null && name == null) { // Special case for default app with Application Default Credentials. name = js.defaultAppName; if (!_apps.containsKey(name)) { _apps[name] = new App(_admin.initializeApp()); } return _apps[name]; } name ??= js.defaultAppName; if (!_apps.containsKey(name)) { _apps[name] = new App(_admin.initializeApp(options, name)); } return _apps[name]; } /// Creates [App] certificate. js.Credential cert({ @required String projectId, @required String clientEmail, @required String privateKey, }) { return _admin.credential.cert(new js.ServiceAccountConfig( project_id: projectId, client_email: clientEmail, private_key: privateKey, )); } /// Creates app certificate from service account file at specified [path]. js.Credential certFromPath(String path) { return _admin.credential.cert(path); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_admin_interop
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_admin_interop/src/database.dart
// Copyright (c) 2017, Anatoly Pulyaevskiy. 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:js'; import 'package:meta/meta.dart'; import 'package:node_interop/util.dart'; import 'package:node_interop/js.dart'; import 'app.dart'; import 'bindings.dart' as js; /// Firebase Realtime Database service. class Database { @protected final js.Database nativeInstance; /// The app associated with this Database instance. final App app; Database(this.nativeInstance, this.app); /// Disconnects from the server (all Database operations will be completed /// offline). void goOffline() => nativeInstance.goOffline(); /// Reconnects to the server and synchronizes the offline Database state with /// the server state. void goOnline() => nativeInstance.goOnline(); /// Returns a [Reference] representing the location in the Database /// corresponding to the provided [path]. If no path is provided, the /// Reference will point to the root of the Database. Reference ref([String path]) => new Reference(nativeInstance.ref(path)); /// Returns a [Reference] representing the location in the Database /// corresponding to the provided Firebase URL. Reference refFromUrl(String url) => new Reference(nativeInstance.refFromURL(url)); } /// List of event types supported in [Query.on] and [Query.off]. abstract class EventType { /// This event will trigger once with the initial data stored at specific /// location, and then trigger again each time the data changes. /// /// It won't trigger until the entire contents has been synchronized. /// If the location has no data, it will be triggered with an empty /// DataSnapshot. static const String value = 'value'; /// This event will be triggered once for each initial child at specific /// location, and it will be triggered again every time a new child is added. static const String childAdded = 'child_added'; /// This event will be triggered once every time a child is removed. /// /// A child will get removed when either: /// /// * a client explicitly calls [Reference.remove] on that child or one of /// its ancestors /// * a client calls [Reference.setValue] with `null` on that child or one /// of its ancestors /// * that child has all of its children removed /// * there is a query in effect which now filters out the child (because /// it's sort order changed or the max limit was hit) static const String childRemoved = 'child_removed'; /// This event will be triggered when the data stored in a child (or any of /// its descendants) changes. /// /// Note that a single child_changed event may represent multiple changes to /// the child. static const String childChanged = 'child_changed'; /// This event will be triggered when a child's sort order changes such that /// its position relative to its siblings changes. static const String childMoved = 'child_moved'; } /// QuerySubscription to keep function callback and allowing use to unsubscribe /// with [cancel] later. class QuerySubscription { /// Type of events handled by this subscription. /// /// One of [EventType] constants. final String eventType; final js.Query _nativeInstance; final Function _callback; QuerySubscription(this.eventType, this._nativeInstance, this._callback); /// Cancels this subscription. /// /// Detaches the callback previously registered with [Query.on]. /// /// See also [Query.off] for other ways of canceling subscriptions. void cancel() { _nativeInstance.off(this.eventType, this._callback); } } /// Sorts and filters the data at a [Database] location so only a subset of the /// child data is included. /// /// This can be used to order a collection of data by some attribute (for /// example, height of dinosaurs) as well as to restrict a large list of items /// (for example, chat messages) down to a number suitable for synchronizing to /// the client. Queries are created by chaining together one or more of the /// filter methods defined here. /// /// Just as with a [Reference], you can receive data from a [Query] by using /// the [on] method. You will only receive events and [DataSnapshot]s for the /// subset of the data that matches your query. /// /// See also: /// - [Sorting and filtering data](https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data) class Query { @protected final js.Query nativeInstance; Query(this.nativeInstance); /// Returns a [Reference] to the [Query]'s location. Reference get ref => _ref ??= new Reference(nativeInstance.ref); Reference _ref; /// Creates a [Query] with the specified ending point. /// /// Using [startAt], [endAt], and [equalTo] allows you to choose arbitrary /// starting and ending points for your queries. /// The ending point is inclusive, so children with exactly the specified /// value will be included in the query. The optional key argument can be used /// to further limit the range of the query. If it is specified, then children /// that have exactly the specified value must also have a key name less than /// or equal to the specified key. /// /// The [value] type depends on which `orderBy*()` function was used in this /// query. Specify a value that matches the `orderBy*()` type. When used in /// combination with [orderByKey], the value must be a `String`. /// /// Optional [key] is only allowed if ordering by priority and defines the /// child key to end at, among the children with the previously specified /// priority. Query endAt(value, [String key]) { if (key == null) { return new Query(nativeInstance.endAt(value)); } return new Query(nativeInstance.endAt(value, key)); } /// Creates a [Query] that includes children that match the specified value. /// /// Using [startAt], [endAt], and [equalTo] allows you to choose arbitrary /// starting and ending points for your queries. /// /// The [value] type depends on which `orderBy*()` function was used in this /// query. Specify a value that matches the `orderBy*()` type. When used in /// combination with [orderByKey], the value must be a `String`. /// /// The optional [key] argument can be used to further limit the range of the /// query. If it is specified, then children that have exactly the specified /// value must also have exactly the specified key as their key name. This can /// be used to filter result sets with many matches for the same value. Query equalTo(value, [String key]) { if (key == null) { return new Query(nativeInstance.equalTo(value)); } return new Query(nativeInstance.equalTo(value, key)); } /// Returns `true` if this and [other] query are equal. /// /// Returns whether or not the current and provided queries represent the same /// location, have the same query parameters, and are from the same instance /// of [App]. Equivalent queries share the same sort order, limits, and /// starting and ending points. /// /// Two [Reference] objects are equivalent if they represent the same location /// and are from the same instance of [App]. bool isEqual(Query other) => nativeInstance.isEqual(other.nativeInstance); /// Generates a new [Query] limited to the first specific number of children. /// /// This method is used to set a maximum number of children to be synced for a /// given callback. If we set a limit of 100, we will initially only receive /// up to 100 child_added events. If we have fewer than 100 messages stored in /// our [Database], a child_added event will fire for each message. However, /// if we have over 100 messages, we will only receive a child_added event for /// the first 100 ordered messages. As items change, we will receive /// child_removed events for each item that drops out of the active list so /// that the total number stays at 100. Query limitToFirst(int limit) => new Query(nativeInstance.limitToFirst(limit)); /// Generates a new [Query] limited to the last specific number of children. /// /// This method is used to set a maximum number of children to be synced for a /// given callback. If we set a limit of 100, we will initially only receive /// up to 100 child_added events. If we have fewer than 100 messages stored in /// our Database, a child_added event will fire for each message. However, if /// we have over 100 messages, we will only receive a child_added event for /// the last 100 ordered messages. As items change, we will receive /// child_removed events for each item that drops out of the active list so /// that the total number stays at 100. Query limitToLast(int limit) => new Query(nativeInstance.limitToLast(limit)); /// Listens for exactly one event of the specified [eventType], and then stops /// listening. Future<DataSnapshot<T>> once<T>(String eventType) { return promiseToFuture(nativeInstance.once(eventType)) .then((snapshot) => new DataSnapshot(snapshot)); } /// Cancels previously created subscription with [on]. /// /// Calling [off] on a parent listener will not automatically remove /// listeners registered on child nodes, [off] must also be called on /// any child listeners to remove the subscription. /// /// If [eventType] is specified, all subscriptions for that specified /// [eventType] will be removed. If no [eventType] is /// specified, all callbacks for the [Reference] will be removed. If /// specified, [eventType] must be one of [EventType] constants. /// /// To unsubscribe a specific callback, use [QuerySubscription.cancel]. void off([String eventType]) { if (eventType != null) { nativeInstance.off(eventType); } else { nativeInstance.off(); } } /// Listens for data changes at a particular location. /// /// [eventType] must be one of [EventType] constants. /// /// This is the primary way to read data from a [Database]. Your callback will /// be triggered for the initial data and again whenever the data changes. /// Use [off] or [QuerySubscription.cancel] to stop receiving updates. /// /// Returns [QuerySubscription] which can be used to cancel the subscription. QuerySubscription on<T>( String eventType, Function(DataSnapshot<T> snapshot) callback, [Function() cancelCallback]) { var fn = allowInterop((snapshot) => callback(new DataSnapshot(snapshot))); if (cancelCallback != null) { nativeInstance.on(eventType, fn, allowInterop(cancelCallback)); } else { nativeInstance.on(eventType, fn); } return QuerySubscription(eventType, nativeInstance, fn); } /// Generates a new [Query] object ordered by the specified child key. /// /// Queries can only order by one key at a time. Calling [orderByChild] /// multiple times on the same query is an error. Query orderByChild(String path) => new Query(nativeInstance.orderByChild(path)); /// Generates a new [Query] object ordered by key. /// /// Sorts the results of a query by their (ascending) key values. /// /// See also: /// - [Sort data](https://firebase.google.com/docs/database/web/lists-of-data#sort_data) Query orderByKey() => new Query(nativeInstance.orderByKey()); /// Generates a new [Query] object ordered by priority. /// /// Applications need not use priority but can order collections by ordinary /// properties. /// /// See also: /// - [Sort data](https://firebase.google.com/docs/database/web/lists-of-data#sort_data) Query orderByPriority() => new Query(nativeInstance.orderByPriority()); /// Generates a new [Query] object ordered by value. /// /// If the children of a query are all scalar values (string, number, or /// boolean), you can order the results by their (ascending) values. /// /// See also: /// - [Sort data](https://firebase.google.com/docs/database/web/lists-of-data#sort_data) Query orderByValue() => new Query(nativeInstance.orderByValue()); /// Creates a [Query] with the specified starting point. /// /// The starting point is inclusive, so children with exactly the specified /// [value] will be included in the query. /// /// The optional [key] argument can be used to further limit the range of the /// query. If it is specified, then children that have exactly the specified /// [value] must also have a `key` name greater than or equal to the specified /// [key]. /// /// See also: /// - [Filtering data](https://firebase.google.com/docs/database/web/lists-of-data#filtering_data) Query startAt(value, [String key]) { if (key == null) { return new Query(nativeInstance.startAt(value)); } return new Query(nativeInstance.startAt(value, key)); } // Note: intentionally not following JS convention and using Dart convention instead. /// Returns a JSON-serializable representation of this object. dynamic toJson() => nativeInstance.toJSON(); /// Gets the absolute URL for this location. /// /// Returned URL is ready to be put into a browser, curl command, or /// [Database.refFromURL] call. Since all of those expect the URL to be /// url-encoded, [toString] returns an encoded URL. /// /// Append '.json' to the returned URL when typed into a browser to download /// JSON-formatted data. If the location is secured (that is, not publicly /// readable), you will get a permission-denied error. @override String toString() => nativeInstance.toString(); } /// A Reference represents a specific location in your [Database] and can be /// used for reading or writing data to that Database location. class Reference extends Query { Reference(js.Reference nativeInstance) : super(nativeInstance); @override @protected js.Reference get nativeInstance => super.nativeInstance; /// The last part of this Reference's path. /// /// For example, "ada" is the key for `https://<DB>.firebaseio.com/users/ada`. /// The key of a root [Reference] is `null`. String get key => nativeInstance.key; /// The parent location of this Reference. /// /// The parent of a root Reference is `null`. Reference get parent => _parent ??= new Reference(nativeInstance.parent); Reference _parent; /// The root [Reference] of the [Database]. Reference get root => _root ??= new Reference(nativeInstance.root); Reference _root; /// Gets a [Reference] for the location at the specified relative [path]. /// /// The relative [path] can either be a simple child name (for example, "ada") /// or a deeper slash-separated path (for example, "ada/name/first"). Reference child(String path) => new Reference(nativeInstance.child(path)); /// Returns an [OnDisconnect] object. /// /// For more information on how to use it see /// [Enabling Offline Capabilities in JavaScript](https://firebase.google.com/docs/database/web/offline-capabilities). dynamic onDisconnect() { throw new UnimplementedError(); } /// Generates a new child location using a unique key and returns its /// [FutureReference]. /// /// This is the most common pattern for adding data to a collection of items. /// /// If you provide a [value] to [push], the value will be written to the /// generated location. If you don't pass a value, nothing will be written to /// the Database and the child will remain empty (but you can use the /// [FutureReference] elsewhere). /// /// The unique key generated by this method are ordered by the current time, /// so the resulting list of items will be chronologically sorted. The keys /// are also designed to be unguessable (they contain 72 random bits of /// entropy). FutureReference push<T>([T value]) { if (value != null) { var futureRef = nativeInstance.push(jsify(value)); return new FutureReference(futureRef, promiseToFuture(futureRef)); } else { // JS side returns regular Reference if value is not provided, but // we still convert it to FutureReference to be consistent with declared // return type. var newRef = nativeInstance.push(); return new FutureReference(newRef, new Future.value()); } } /// Removes the data at this Database location. /// /// Any data at child locations will also be deleted. /// /// The effect of the remove will be visible immediately and the corresponding /// event 'value' will be triggered. Synchronization of the remove to the /// Firebase servers will also be started, and the returned [Future] will /// resolve when complete. Future<void> remove() => promiseToFuture(nativeInstance.remove()); /// Writes data to this Database location. /// /// This will overwrite any data at this location and all child locations. /// /// The effect of the write will be visible immediately, and the corresponding /// events ("value", "child_added", etc.) will be triggered. Synchronization /// of the data to the Firebase servers will also be started, and the returned /// [Future] will resolve when complete. /// /// Passing `null` for the new value is equivalent to calling [remove]; /// namely, all data at this location and all child locations will be deleted. /// /// [setValue] will remove any priority stored at this location, so if priority is /// meant to be preserved, you need to use [setWithPriority] instead. /// /// Note that modifying data with [setValue] will cancel any pending transactions /// at that location, so extreme care should be taken if mixing [setValue] and /// [transaction] to modify the same data. /// /// A single [setValue] will generate a single "value" event at the location /// where the `setValue()` was performed. Future<void> setValue<T>(T value) { return promiseToFuture(nativeInstance.set(jsify(value))); } /// Sets a priority for the data at this Database location. /// /// Applications need not use priority but can order collections by ordinary /// properties. /// /// See also: /// - [Sorting and filtering data](https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data) Future<void> setPriority(priority) => promiseToFuture(nativeInstance.setPriority(priority)); /// Writes data the Database location. Like [setValue] but also specifies the /// [priority] for that data. /// /// Applications need not use priority but can order collections by ordinary /// properties. /// /// See also: /// - [Sorting and filtering data](https://firebase.google.com/docs/database/web/lists-of-data#sorting_and_filtering_data) Future<void> setWithPriority<T>(T value, priority) { return promiseToFuture( nativeInstance.setWithPriority(jsify(value), priority)); } /// Atomically modifies the data at this location. /// /// [handler] function must always return an instance of [TransactionResult] /// created with either [TransactionResult.abort] or [TransactionResult.success]. /// /// // Aborting a transaction /// var result = await ref.transaction((currentData) { /// // your logic /// return TransactionResult.abort; /// }); /// /// // Committing a transaction /// var result = await ref.transaction((currentData) { /// var data = yourUpdateDataLogic(currentData); /// return TransactionResult.success(data); /// }); /// /// Unlike a normal [set], which /// just overwrites the data regardless of its previous value, [transaction] /// is used to modify the existing value to a new value, ensuring there are no /// conflicts with other clients writing to the same location at the same time. /// /// To accomplish this, you pass transaction() an update function which is used /// to transform the current value into a new value. If another client writes to /// the location before your new value is successfully written, your update /// function will be called again with the new current value, and the write will /// be retried. This will happen repeatedly until your write succeeds without /// conflict or you abort the transaction by returning [TransactionResult.abort]. /// Note: Modifying data with [set] will cancel any pending transactions at that /// location, so extreme care should be taken if mixing set() and transaction() /// to update the same data. /// Note: When using transactions with Security and Firebase Rules in place, be /// aware that a client needs .read access in addition to .write access in order /// to perform a transaction. This is because the client-side nature of /// transactions requires the client to read the data in order to /// transactionally update it. Future<DatabaseTransaction> transaction<T>( DatabaseTransactionHandler<T> handler, [bool applyLocally = true]) { var promise = nativeInstance.transaction( allowInterop(_createTransactionHandler(handler)), allowInterop(_onComplete), applyLocally, ); return promiseToFuture(promise).then( (result) { final jsResult = result as js.TransactionResult; return new DatabaseTransaction( jsResult.committed, new DataSnapshot(jsResult.snapshot)); }, ); } _onComplete(error, bool committed, snapshot) { // no-op, we use returned Promise instead. } Function _createTransactionHandler<T>(DatabaseTransactionHandler<T> handler) { return (currentData) { final data = dartify(currentData); final result = handler(data); assert( result != null, 'Transaction handler returned null and this is not allowed. ' 'Make sure to always return an instance of TransactionResult.'); if (result.aborted) return undefined; return jsify(result.data); }; } /// Writes multiple values to the Database at once. /// /// The [values] argument contains multiple property-value pairs that will be /// written to the Database together. Each child property can either be a simple /// property (for example, "name") or a relative path (for example, /// "name/first") from the current location to the data to update. /// /// As opposed to the [setValue] method, [update] can be used to selectively update /// only the referenced properties at the current location (instead of replacing /// all the child properties at the current location). /// /// The effect of the write will be visible immediately, and the corresponding /// events ('value', 'child_added', etc.) will be triggered. Synchronization of /// the data to the Firebase servers will also be started, and the returned /// `Future` will resolve when complete. /// /// A single [update] will generate a single "value" event at the location where /// the `update` was performed, regardless of how many children were modified. /// /// Note that modifying data with [update] will cancel any pending transactions /// at that location, so extreme care should be taken if mixing [update] and /// [transaction] to modify the same data. /// /// Passing `null` to [update] will remove the data at this location. Future<void> update(Map<String, dynamic> values) { return promiseToFuture(nativeInstance.update(jsify(values))); } } /// Interface for a Realtime Database transaction handler function used /// in [Reference.transaction]. typedef DatabaseTransactionHandler<T> = TransactionResult<T> Function( T currentData); /// Realtime Database transaction result returned from [DatabaseTransactionHandler]. /// /// Use [TransactionResult.success] and [TransactionResult.abort] to create an /// instance of this class according to logic in your transactions. class TransactionResult<T> { TransactionResult._(this.aborted, this.data); final bool aborted; final T data; static TransactionResult abort = new TransactionResult._(true, null); static TransactionResult<T> success<T>(T data) => new TransactionResult._(false, data); } /// Firebase Realtime Database transaction result returned from /// [Reference.transaction]. class DatabaseTransaction { DatabaseTransaction(this.committed, this.snapshot); /// Returns `true` if this transaction was committed, `false` if aborted. final bool committed; /// Resulting data snapshot of this transaction. final DataSnapshot snapshot; } /// A special [Reference] which notifies when it's written to the database. /// /// This reference is returned from [Reference.push] and has only one extra /// property [done] - a [Future] which is resolved when data is written to /// the database. /// /// For more details see documentation for [Reference.push]. class FutureReference extends Reference { final Future<void> done; FutureReference(js.ThenableReference nativeInstance, this.done) : super(nativeInstance); } /// A `DataSnapshot` contains data from a [Database] location. /// /// Any time you read data from the Database, you receive the data as a /// [DataSnapshot]. class DataSnapshot<T> { @protected final js.DataSnapshot nativeInstance; DataSnapshot(this.nativeInstance); /// The key (last part of the path) of the location of this `DataSnapshot`. /// /// The last token in a [Database] location is considered its key. For example, /// `ada` is the key for the `/users/ada/` node. Accessing the key on any /// `DataSnapshot` will return the key for the location that generated it. /// However, accessing the key on the root URL of a `Database` will return /// `null`. String get key => nativeInstance.key; /// The [Reference] for the location that generated this [DataSnapshot]. Reference get ref => new Reference(nativeInstance.ref); /// Gets [DataSnapshot] for the location at the specified relative [path]. /// /// The relative path can either be a simple child name (for example, "ada") /// or a deeper, slash-separated path (for example, "ada/name/first"). If the /// child location has no data, an empty DataSnapshot (that is, a /// DataSnapshot whose value is `null`) is returned. DataSnapshot<S> child<S>(String path) => new DataSnapshot(nativeInstance.child(path)); /// Returns `true` if this DataSnapshot contains any data. /// /// It is slightly more efficient than using `snapshot.val() !== null`. bool exists() => nativeInstance.exists(); /// Enumerates the top-level children in this `DataSnapshot`. /// /// Guarantees the children of this `DataSnapshot` are iterated in their query /// order. /// /// If no explicit orderBy*() method is used, results are returned ordered by /// key (unless priorities are used, in which case, results are returned /// by priority). bool forEach<S>(bool action(DataSnapshot<S> child)) { bool wrapper(js.DataSnapshot child) { return action(new DataSnapshot<S>(child)); } return nativeInstance.forEach(allowInterop(wrapper)); } bool hasChild(String path) => nativeInstance.hasChild(path); bool hasChildren() => nativeInstance.hasChildren(); int numChildren() => nativeInstance.numChildren(); T _value; /// Returns value stored in this data snapshot. T val() { if (_value != null) return _value; if (!exists()) return null; // Don't attempt to dartify empty snapshot. _value = dartify(nativeInstance.val()); return _value; } // NOTE: intentionally not following JS library name – using Dart convention. /// Returns a JSON-serializable representation of this data snapshot. Object toJson() => dartify(nativeInstance.toJSON()); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_admin_interop
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/firebase_admin_interop/src/messaging.dart
// Copyright (c) 2018, Anatoly Pulyaevskiy. 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 'package:meta/meta.dart'; import 'package:node_interop/util.dart'; import 'bindings.dart' as js show Messaging; import 'bindings.dart' show FcmMessage, MulticastMessage, MessagingPayload, MessagingOptions, MessagingDevicesResponse, MessagingConditionResponse, MessagingDeviceGroupResponse, MessagingTopicResponse, MessagingTopicManagementResponse, BatchResponse; export 'bindings.dart' show FcmMessage, TopicMessage, TokenMessage, ConditionMessage, MulticastMessage, Notification, WebpushNotification, WebpushFcmOptions, WebpushConfig, FcmOptions, MessagingPayload, DataMessagePayload, NotificationMessagePayload, MessagingOptions, MessagingDevicesResponse, MessagingDeviceResult, MessagingConditionResponse, MessagingDeviceGroupResponse, MessagingTopicResponse, MessagingTopicManagementResponse, AndroidConfig, AndroidFcmOptions, AndroidNotification, ApnsConfig, ApnsFcmOptions, ApnsPayload, Aps, ApsAlert, CriticalSound, BatchResponse, SendResponse; class Messaging { Messaging(this.nativeInstance); @protected final js.Messaging nativeInstance; /// Sends the given [message] via FCM. /// /// Returns Future<String> fulfilled with a unique message ID string after the /// message has been successfully handed off to the FCM service for delivery Future<String> send(FcmMessage message, [bool dryRun]) { if (dryRun != null) return promiseToFuture(nativeInstance.send(message, dryRun)); else return promiseToFuture(nativeInstance.send(message)); } /// Sends all the [messages] in the given array via Firebase Cloud Messaging. /// /// Returns Future<BatchResponse> fulfilled with an object representing the /// result of the send operation. Future<BatchResponse> sendAll(List<FcmMessage> messages, [bool dryRun]) { if (dryRun != null) return promiseToFuture(nativeInstance.sendAll(messages, dryRun)); else return promiseToFuture(nativeInstance.sendAll(messages)); } /// Sends the given multicast [message] to all the FCM registration tokens /// specified in it. /// /// Returns Future<BatchResponse> fulfilled with an object representing the /// result of the send operation. Future<BatchResponse> sendMulticast(MulticastMessage message, [bool dryRun]) { if (dryRun != null) return promiseToFuture(nativeInstance.sendMulticast(message, dryRun)); else return promiseToFuture(nativeInstance.sendMulticast(message)); } /// Sends an FCM message to a [condition]. /// /// Returns Future<MessagingConditionResponse> fulfilled with the server's /// response after the message has been sent. Future<MessagingConditionResponse> sendToCondition( String condition, MessagingPayload payload, [MessagingOptions options]) { if (options != null) return promiseToFuture( nativeInstance.sendToCondition(condition, payload, options)); else return promiseToFuture( nativeInstance.sendToCondition(condition, payload)); } /// Sends an FCM message to a single device corresponding to the provided /// [registrationToken]. /// /// Returns Future<MessagingDevicesResponse> fulfilled with the server's /// response after the message has been sent. Future<MessagingDevicesResponse> sendToDevice( String registrationToken, MessagingPayload payload, [MessagingOptions options]) { if (options != null) return promiseToFuture( nativeInstance.sendToDevice(registrationToken, payload, options)); else return promiseToFuture( nativeInstance.sendToDevice(registrationToken, payload)); } /// Sends an FCM message to a device group corresponding to the provided /// [notificationKey]. /// /// Returns Future<MessagingDevicesResponse> fulfilled with the server's /// response after the message has been sent. Future<MessagingDeviceGroupResponse> sendToDeviceGroup( String notificationKey, MessagingPayload payload, [MessagingOptions options]) { if (options != null) return promiseToFuture( nativeInstance.sendToDeviceGroup(notificationKey, payload, options)); else return promiseToFuture( nativeInstance.sendToDeviceGroup(notificationKey, payload)); } /// Sends an FCM message to a [topic]. /// /// Returns Future<MessagingTopicResponse> fulfilled with the server's /// response after the message has been sent. Future<MessagingTopicResponse> sendToTopic( String topic, MessagingPayload payload, [MessagingOptions options]) { if (options != null) return promiseToFuture( nativeInstance.sendToTopic(topic, payload, options)); else return promiseToFuture(nativeInstance.sendToTopic(topic, payload)); } /// Subscribes a device to an FCM [topic]. /// /// Returns Future<MessagingTopicManagementResponse> fulfilled with the /// server's response after the device has been subscribed to the topic. Future<MessagingTopicManagementResponse> subscribeToTopic( String registrationTokens, String topic) => promiseToFuture( nativeInstance.subscribeToTopic(registrationTokens, topic)); /// Unsubscribes a device from an FCM [topic]. /// /// Returns Future<MessagingTopicManagementResponse> fulfilled with the /// server's response after the device has been subscribed to the topic. Future<MessagingTopicManagementResponse> unsubscribeFromTopic( String registrationTokens, String topic) => promiseToFuture( nativeInstance.unsubscribeFromTopic(registrationTokens, topic)); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/checked_yaml/checked_yaml.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 'package:json_annotation/json_annotation.dart'; import 'package:yaml/yaml.dart'; /// Decodes [yamlContent] as YAML and calls [constructor] with the resulting /// [Map]. /// /// If there are errors thrown while decoding [yamlContent], if it is not a /// [Map] or if [CheckedFromJsonException] is thrown when calling [constructor], /// a [ParsedYamlException] will be thrown. /// /// If [sourceUrl] is passed, it's used as the URL from which the YAML /// originated for error reporting. It can be a [String], a [Uri], or `null`. /// /// If [allowNull] is `true`, a `null` value from [yamlContent] will be allowed /// and passed to [constructor]. [constructor], therefore, will need to handle /// `null` values. T checkedYamlDecode<T>( String yamlContent, T Function(Map) constructor, { sourceUrl, bool allowNull = false, }) { allowNull ??= false; YamlNode yaml; Uri sourceUri; if (sourceUrl == null) { // noop } else if (sourceUrl is Uri) { sourceUri = sourceUrl; } else { sourceUri = Uri.parse(sourceUrl as String); } try { yaml = loadYamlNode(yamlContent, sourceUrl: sourceUri); } on YamlException catch (e) { throw ParsedYamlException.fromYamlException(e); } Map map; if (yaml is YamlMap) { map = yaml; } else if (allowNull && yaml is YamlScalar && yaml.value == null) { // TODO: test this case! map = null; } else { throw ParsedYamlException('Not a map', yaml); } try { return constructor(map); } on CheckedFromJsonException catch (e) { throw toParsedYamlException(e); } } /// Returns a [ParsedYamlException] for the provided [exception]. /// /// This function assumes `exception.map` is of type `YamlMap` from /// `package:yaml`. If not, you may provide an alternative via [exceptionMap]. ParsedYamlException toParsedYamlException( CheckedFromJsonException exception, { YamlMap exceptionMap, }) { final yamlMap = exceptionMap ?? exception.map as YamlMap; final innerError = exception.innerError; if (exception.badKey) { final key = (innerError is UnrecognizedKeysException) ? innerError.unrecognizedKeys.first : exception.key; final node = yamlMap.nodes.keys.singleWhere( (k) => (k as YamlScalar).value == key, orElse: () => yamlMap) as YamlNode; return ParsedYamlException( exception.message, node, innerError: exception, ); } else { final yamlValue = yamlMap.nodes[exception.key]; if (yamlValue == null) { // TODO: test this case! return ParsedYamlException( exception.message, yamlMap, innerError: exception, ); } else { var message = 'Unsupported value for "${exception.key}".'; if (exception.message != null) { message = '$message ${exception.message}'; } return ParsedYamlException( message, yamlValue, innerError: exception, ); } } } /// An exception thrown when parsing YAML that contains information about the /// location in the source where the exception occurred. class ParsedYamlException implements Exception { /// Describes the nature of the parse failure. final String message; /// The node associated with this exception. /// /// May be `null` if there was an error decoding. final YamlNode yamlNode; /// If this exception was thrown as a result of another error, /// contains the source error object. final Object innerError; ParsedYamlException( this.message, this.yamlNode, { this.innerError, }) : assert(message != null), assert(yamlNode != null); factory ParsedYamlException.fromYamlException(YamlException exception) => _WrappedYamlException(exception); /// Returns [message] formatted with source information provided by /// [yamlNode]. String get formattedMessage => yamlNode.span.message(message); @override String toString() => 'ParsedYamlException: $formattedMessage'; } class _WrappedYamlException implements ParsedYamlException { _WrappedYamlException(this.innerError); @override String get formattedMessage => innerError.span.message(innerError.message); @override final YamlException innerError; @override String get message => innerError.message; @override YamlNode get yamlNode => null; @override String toString() => 'ParsedYamlException: $formattedMessage'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml/yaml.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/loader.dart'; import 'src/style.dart'; import 'src/yaml_document.dart'; import 'src/yaml_exception.dart'; import 'src/yaml_node.dart'; export 'src/style.dart'; export 'src/utils.dart' show YamlWarningCallback, yamlWarningCallback; export 'src/yaml_document.dart'; export 'src/yaml_exception.dart'; export 'src/yaml_node.dart' hide setSpan; /// Loads a single document from a YAML string. /// /// If the string contains more than one document, this throws a /// [YamlException]. In future releases, this will become an [ArgumentError]. /// /// The return value is mostly normal Dart objects. However, since YAML mappings /// support some key types that the default Dart map implementation doesn't /// (NaN, lists, and maps), all maps in the returned document are [YamlMap]s. /// These have a few small behavioral differences from the default Map /// implementation; for details, see the [YamlMap] class. /// /// In future versions, maps will instead be [HashMap]s with a custom equality /// operation. /// /// If [sourceUrl] is passed, it's used as the URL from which the YAML /// originated for error reporting. It can be a [String], a [Uri], or `null`. dynamic loadYaml(String yaml, {sourceUrl}) => loadYamlNode(yaml, sourceUrl: sourceUrl).value; /// Loads a single document from a YAML string as a [YamlNode]. /// /// This is just like [loadYaml], except that where [loadYaml] would return a /// normal Dart value this returns a [YamlNode] instead. This allows the caller /// to be confident that the return value will always be a [YamlNode]. YamlNode loadYamlNode(String yaml, {sourceUrl}) => loadYamlDocument(yaml, sourceUrl: sourceUrl).contents; /// Loads a single document from a YAML string as a [YamlDocument]. /// /// This is just like [loadYaml], except that where [loadYaml] would return a /// normal Dart value this returns a [YamlDocument] instead. This allows the /// caller to access document metadata. YamlDocument loadYamlDocument(String yaml, {sourceUrl}) { var loader = Loader(yaml, sourceUrl: sourceUrl); var document = loader.load(); if (document == null) { return YamlDocument.internal(YamlScalar.internalWithSpan(null, loader.span), loader.span, null, const []); } var nextDocument = loader.load(); if (nextDocument != null) { throw YamlException('Only expected one document.', nextDocument.span); } return document; } /// Loads a stream of documents from a YAML string. /// /// The return value is mostly normal Dart objects. However, since YAML mappings /// support some key types that the default Dart map implementation doesn't /// (NaN, lists, and maps), all maps in the returned document are [YamlMap]s. /// These have a few small behavioral differences from the default Map /// implementation; for details, see the [YamlMap] class. /// /// In future versions, maps will instead be [HashMap]s with a custom equality /// operation. /// /// If [sourceUrl] is passed, it's used as the URL from which the YAML /// originated for error reporting. It can be a [String], a [Uri], or `null`. YamlList loadYamlStream(String yaml, {sourceUrl}) { var loader = Loader(yaml, sourceUrl: sourceUrl); var documents = <YamlDocument>[]; var document = loader.load(); while (document != null) { documents.add(document); document = loader.load(); } // TODO(jmesserly): the type on the `document` parameter is a workaround for: // https://github.com/dart-lang/dev_compiler/issues/203 return YamlList.internal( documents.map((YamlDocument document) => document.contents).toList(), loader.span, CollectionStyle.ANY); } /// Loads a stream of documents from a YAML string. /// /// This is like [loadYamlStream], except that it returns [YamlDocument]s with /// metadata wrapping the document contents. List<YamlDocument> loadYamlDocuments(String yaml, {sourceUrl}) { var loader = Loader(yaml, sourceUrl: sourceUrl); var documents = <YamlDocument>[]; var document = loader.load(); while (document != null) { documents.add(document); document = loader.load(); } return documents; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml/src/yaml_document.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 'package:source_span/source_span.dart'; import 'yaml_node.dart'; /// A YAML document, complete with metadata. class YamlDocument { /// The contents of the document. final YamlNode contents; /// The span covering the entire document. final SourceSpan span; /// The version directive for the document, if any. final VersionDirective versionDirective; /// The tag directives for the document. final List<TagDirective> tagDirectives; /// Whether the beginning of the document was implicit (versus explicit via /// `===`). final bool startImplicit; /// Whether the end of the document was implicit (versus explicit via `...`). final bool endImplicit; /// Users of the library should not use this constructor. YamlDocument.internal(this.contents, this.span, this.versionDirective, List<TagDirective> tagDirectives, {this.startImplicit = false, this.endImplicit = false}) : tagDirectives = UnmodifiableListView(tagDirectives); @override String toString() => contents.toString(); } /// A directive indicating which version of YAML a document was written to. class VersionDirective { /// The major version number. final int major; /// The minor version number. final int minor; VersionDirective(this.major, this.minor); @override String toString() => '%YAML $major.$minor'; } /// A directive describing a custom tag handle. class TagDirective { /// The handle for use in the document. final String handle; /// The prefix that the handle maps to. final String prefix; TagDirective(this.handle, this.prefix); @override String toString() => '%TAG $handle $prefix'; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml/src/event.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:source_span/source_span.dart'; import 'style.dart'; import 'yaml_document.dart'; /// An event emitted by a [Parser]. class Event { final EventType type; final FileSpan span; Event(this.type, this.span); @override String toString() => type.toString(); } /// An event indicating the beginning of a YAML document. class DocumentStartEvent implements Event { @override EventType get type => EventType.documentStart; @override final FileSpan span; /// The document's `%YAML` directive, or `null` if there was none. final VersionDirective versionDirective; /// The document's `%TAG` directives, if any. final List<TagDirective> tagDirectives; /// Whether the document started implicitly (that is, without an explicit /// `===` sequence). final bool isImplicit; DocumentStartEvent(this.span, {this.versionDirective, List<TagDirective> tagDirectives, this.isImplicit = true}) : tagDirectives = tagDirectives ?? []; @override String toString() => 'DOCUMENT_START'; } /// An event indicating the end of a YAML document. class DocumentEndEvent implements Event { @override EventType get type => EventType.documentEnd; @override final FileSpan span; /// Whether the document ended implicitly (that is, without an explicit /// `...` sequence). final bool isImplicit; DocumentEndEvent(this.span, {this.isImplicit = true}); @override String toString() => 'DOCUMENT_END'; } /// An event indicating that an alias was referenced. class AliasEvent implements Event { @override EventType get type => EventType.alias; @override final FileSpan span; /// The alias name. final String name; AliasEvent(this.span, this.name); @override String toString() => 'ALIAS $name'; } /// An event that can have associated anchor and tag properties. abstract class _ValueEvent implements Event { /// The name of the value's anchor, or `null` if it wasn't anchored. String get anchor; /// The text of the value's tag, or `null` if it wasn't tagged. String get tag; @override String toString() { var buffer = StringBuffer('$type'); if (anchor != null) buffer.write(' &$anchor'); if (tag != null) buffer.write(' $tag'); return buffer.toString(); } } /// An event indicating a single scalar value. class ScalarEvent extends _ValueEvent { @override EventType get type => EventType.scalar; @override final FileSpan span; @override final String anchor; @override final String tag; /// The contents of the scalar. final String value; /// The style of the scalar in the original source. final ScalarStyle style; ScalarEvent(this.span, this.value, this.style, {this.anchor, this.tag}); @override String toString() => '${super.toString()} "$value"'; } /// An event indicating the beginning of a sequence. class SequenceStartEvent extends _ValueEvent { @override EventType get type => EventType.sequenceStart; @override final FileSpan span; @override final String anchor; @override final String tag; /// The style of the collection in the original source. final CollectionStyle style; SequenceStartEvent(this.span, this.style, {this.anchor, this.tag}); } /// An event indicating the beginning of a mapping. class MappingStartEvent extends _ValueEvent { @override EventType get type => EventType.mappingStart; @override final FileSpan span; @override final String anchor; @override final String tag; /// The style of the collection in the original source. final CollectionStyle style; MappingStartEvent(this.span, this.style, {this.anchor, this.tag}); } /// The types of [Event] objects. enum EventType { streamStart, streamEnd, documentStart, documentEnd, alias, scalar, sequenceStart, sequenceEnd, mappingStart, mappingEnd }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml/src/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. import 'package:source_span/source_span.dart'; import 'package:string_scanner/string_scanner.dart'; import 'event.dart'; import 'scanner.dart'; import 'style.dart'; import 'token.dart'; import 'utils.dart'; import 'yaml_document.dart'; import 'yaml_exception.dart'; /// A parser that reads [Token]s emitted by a [Scanner] and emits [Event]s. /// /// This is based on the libyaml parser, available at /// https://github.com/yaml/libyaml/blob/master/src/parser.c. The license for /// that is available in ../../libyaml-license.txt. class Parser { /// The underlying [Scanner] that generates [Token]s. final Scanner _scanner; /// The stack of parse states for nested contexts. final _states = <_State>[]; /// The current parse state. var _state = _State.STREAM_START; /// The custom tag directives, by tag handle. final _tagDirectives = <String, TagDirective>{}; /// Whether the parser has finished parsing. bool get isDone => _state == _State.END; /// Creates a parser that parses [source]. /// /// [sourceUrl] can be a String or a [Uri]. Parser(String source, {sourceUrl}) : _scanner = Scanner(source, sourceUrl: sourceUrl); /// Consumes and returns the next event. Event parse() { try { if (isDone) throw StateError('No more events.'); var event = _stateMachine(); return event; } on StringScannerException catch (error) { throw YamlException(error.message, error.span); } } /// Dispatches parsing based on the current state. Event _stateMachine() { switch (_state) { case _State.STREAM_START: return _parseStreamStart(); case _State.DOCUMENT_START: return _parseDocumentStart(); case _State.DOCUMENT_CONTENT: return _parseDocumentContent(); case _State.DOCUMENT_END: return _parseDocumentEnd(); case _State.BLOCK_NODE: return _parseNode(block: true); case _State.BLOCK_NODE_OR_INDENTLESS_SEQUENCE: return _parseNode(block: true, indentlessSequence: true); case _State.FLOW_NODE: return _parseNode(); case _State.BLOCK_SEQUENCE_FIRST_ENTRY: // Scan past the `BLOCK-SEQUENCE-FIRST-ENTRY` token to the // `BLOCK-SEQUENCE-ENTRY` token. _scanner.scan(); return _parseBlockSequenceEntry(); case _State.BLOCK_SEQUENCE_ENTRY: return _parseBlockSequenceEntry(); case _State.INDENTLESS_SEQUENCE_ENTRY: return _parseIndentlessSequenceEntry(); case _State.BLOCK_MAPPING_FIRST_KEY: // Scan past the `BLOCK-MAPPING-FIRST-KEY` token to the // `BLOCK-MAPPING-KEY` token. _scanner.scan(); return _parseBlockMappingKey(); case _State.BLOCK_MAPPING_KEY: return _parseBlockMappingKey(); case _State.BLOCK_MAPPING_VALUE: return _parseBlockMappingValue(); case _State.FLOW_SEQUENCE_FIRST_ENTRY: return _parseFlowSequenceEntry(first: true); case _State.FLOW_SEQUENCE_ENTRY: return _parseFlowSequenceEntry(); case _State.FLOW_SEQUENCE_ENTRY_MAPPING_KEY: return _parseFlowSequenceEntryMappingKey(); case _State.FLOW_SEQUENCE_ENTRY_MAPPING_VALUE: return _parseFlowSequenceEntryMappingValue(); case _State.FLOW_SEQUENCE_ENTRY_MAPPING_END: return _parseFlowSequenceEntryMappingEnd(); case _State.FLOW_MAPPING_FIRST_KEY: return _parseFlowMappingKey(first: true); case _State.FLOW_MAPPING_KEY: return _parseFlowMappingKey(); case _State.FLOW_MAPPING_VALUE: return _parseFlowMappingValue(); case _State.FLOW_MAPPING_EMPTY_VALUE: return _parseFlowMappingValue(empty: true); default: throw 'Unreachable'; } } /// Parses the production: /// /// stream ::= /// STREAM-START implicit_document? explicit_document* STREAM-END /// ************ Event _parseStreamStart() { var token = _scanner.scan(); assert(token.type == TokenType.streamStart); _state = _State.DOCUMENT_START; return Event(EventType.streamStart, token.span); } /// Parses the productions: /// /// implicit_document ::= block_node DOCUMENT-END* /// * /// explicit_document ::= /// DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* /// ************************* Event _parseDocumentStart() { var token = _scanner.peek(); // libyaml requires any document beyond the first in the stream to have an // explicit document start indicator, but the spec allows it to be omitted // as long as there was an end indicator. // Parse extra document end indicators. while (token.type == TokenType.documentEnd) { token = _scanner.advance(); } if (token.type != TokenType.versionDirective && token.type != TokenType.tagDirective && token.type != TokenType.documentStart && token.type != TokenType.streamEnd) { // Parse an implicit document. _processDirectives(); _states.add(_State.DOCUMENT_END); _state = _State.BLOCK_NODE; return DocumentStartEvent(token.span.start.pointSpan()); } if (token.type == TokenType.streamEnd) { _state = _State.END; _scanner.scan(); return Event(EventType.streamEnd, token.span); } // Parse an explicit document. var start = token.span; var pair = _processDirectives(); var versionDirective = pair.first; var tagDirectives = pair.last; token = _scanner.peek(); if (token.type != TokenType.documentStart) { throw YamlException('Expected document start.', token.span); } _states.add(_State.DOCUMENT_END); _state = _State.DOCUMENT_CONTENT; _scanner.scan(); return DocumentStartEvent(start.expand(token.span), versionDirective: versionDirective, tagDirectives: tagDirectives, isImplicit: false); } /// Parses the productions: /// /// explicit_document ::= /// DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* /// *********** Event _parseDocumentContent() { var token = _scanner.peek(); switch (token.type) { case TokenType.versionDirective: case TokenType.tagDirective: case TokenType.documentStart: case TokenType.documentEnd: case TokenType.streamEnd: _state = _states.removeLast(); return _processEmptyScalar(token.span.start); default: return _parseNode(block: true); } } /// Parses the productions: /// /// implicit_document ::= block_node DOCUMENT-END* /// ************* /// explicit_document ::= /// DIRECTIVE* DOCUMENT-START block_node? DOCUMENT-END* /// ************* Event _parseDocumentEnd() { _tagDirectives.clear(); _state = _State.DOCUMENT_START; var token = _scanner.peek(); if (token.type == TokenType.documentEnd) { _scanner.scan(); return DocumentEndEvent(token.span, isImplicit: false); } else { return DocumentEndEvent(token.span.start.pointSpan(), isImplicit: true); } } /// Parses the productions: /// /// block_node_or_indentless_sequence ::= /// ALIAS /// ***** /// | properties (block_content | indentless_block_sequence)? /// ********** * /// | block_content | indentless_block_sequence /// * /// block_node ::= ALIAS /// ***** /// | properties block_content? /// ********** * /// | block_content /// * /// flow_node ::= ALIAS /// ***** /// | properties flow_content? /// ********** * /// | flow_content /// * /// properties ::= TAG ANCHOR? | ANCHOR TAG? /// ************************* /// block_content ::= block_collection | flow_collection | SCALAR /// ****** /// flow_content ::= flow_collection | SCALAR /// ****** Event _parseNode({bool block = false, bool indentlessSequence = false}) { var token = _scanner.peek(); if (token is AliasToken) { _scanner.scan(); _state = _states.removeLast(); return AliasEvent(token.span, token.name); } String anchor; TagToken tagToken; var span = token.span.start.pointSpan(); Token parseAnchor(AnchorToken token) { anchor = token.name; span = span.expand(token.span); return _scanner.advance(); } Token parseTag(TagToken token) { tagToken = token; span = span.expand(token.span); return _scanner.advance(); } if (token is AnchorToken) { token = parseAnchor(token as AnchorToken); if (token is TagToken) token = parseTag(token as TagToken); } else if (token is TagToken) { token = parseTag(token as TagToken); if (token is AnchorToken) token = parseAnchor(token as AnchorToken); } String tag; if (tagToken != null) { if (tagToken.handle == null) { tag = tagToken.suffix; } else { var tagDirective = _tagDirectives[tagToken.handle]; if (tagDirective == null) { throw YamlException('Undefined tag handle.', tagToken.span); } tag = tagDirective.prefix + tagToken.suffix; } } if (indentlessSequence && token.type == TokenType.blockEntry) { _state = _State.INDENTLESS_SEQUENCE_ENTRY; return SequenceStartEvent(span.expand(token.span), CollectionStyle.BLOCK, anchor: anchor, tag: tag); } if (token is ScalarToken) { // All non-plain scalars have the "!" tag by default. if (tag == null && token.style != ScalarStyle.PLAIN) tag = '!'; _state = _states.removeLast(); _scanner.scan(); return ScalarEvent(span.expand(token.span), token.value, token.style, anchor: anchor, tag: tag); } if (token.type == TokenType.flowSequenceStart) { _state = _State.FLOW_SEQUENCE_FIRST_ENTRY; return SequenceStartEvent(span.expand(token.span), CollectionStyle.FLOW, anchor: anchor, tag: tag); } if (token.type == TokenType.flowMappingStart) { _state = _State.FLOW_MAPPING_FIRST_KEY; return MappingStartEvent(span.expand(token.span), CollectionStyle.FLOW, anchor: anchor, tag: tag); } if (block && token.type == TokenType.blockSequenceStart) { _state = _State.BLOCK_SEQUENCE_FIRST_ENTRY; return SequenceStartEvent(span.expand(token.span), CollectionStyle.BLOCK, anchor: anchor, tag: tag); } if (block && token.type == TokenType.blockMappingStart) { _state = _State.BLOCK_MAPPING_FIRST_KEY; return MappingStartEvent(span.expand(token.span), CollectionStyle.BLOCK, anchor: anchor, tag: tag); } if (anchor != null || tag != null) { _state = _states.removeLast(); return ScalarEvent(span, '', ScalarStyle.PLAIN, anchor: anchor, tag: tag); } throw YamlException('Expected node content.', span); } /// Parses the productions: /// /// block_sequence ::= /// BLOCK-SEQUENCE-START (BLOCK-ENTRY block_node?)* BLOCK-END /// ******************** *********** * ********* Event _parseBlockSequenceEntry() { var token = _scanner.peek(); if (token.type == TokenType.blockEntry) { var start = token.span.start; token = _scanner.advance(); if (token.type == TokenType.blockEntry || token.type == TokenType.blockEnd) { _state = _State.BLOCK_SEQUENCE_ENTRY; return _processEmptyScalar(start); } else { _states.add(_State.BLOCK_SEQUENCE_ENTRY); return _parseNode(block: true); } } if (token.type == TokenType.blockEnd) { _scanner.scan(); _state = _states.removeLast(); return Event(EventType.sequenceEnd, token.span); } throw YamlException("While parsing a block collection, expected '-'.", token.span.start.pointSpan()); } /// Parses the productions: /// /// indentless_sequence ::= (BLOCK-ENTRY block_node?)+ /// *********** * Event _parseIndentlessSequenceEntry() { var token = _scanner.peek(); if (token.type != TokenType.blockEntry) { _state = _states.removeLast(); return Event(EventType.sequenceEnd, token.span.start.pointSpan()); } var start = token.span.start; token = _scanner.advance(); if (token.type == TokenType.blockEntry || token.type == TokenType.key || token.type == TokenType.value || token.type == TokenType.blockEnd) { _state = _State.INDENTLESS_SEQUENCE_ENTRY; return _processEmptyScalar(start); } else { _states.add(_State.INDENTLESS_SEQUENCE_ENTRY); return _parseNode(block: true); } } /// Parses the productions: /// /// block_mapping ::= BLOCK-MAPPING_START /// ******************* /// ((KEY block_node_or_indentless_sequence?)? /// *** * /// (VALUE block_node_or_indentless_sequence?)?)* /// /// BLOCK-END /// ********* Event _parseBlockMappingKey() { var token = _scanner.peek(); if (token.type == TokenType.key) { var start = token.span.start; token = _scanner.advance(); if (token.type == TokenType.key || token.type == TokenType.value || token.type == TokenType.blockEnd) { _state = _State.BLOCK_MAPPING_VALUE; return _processEmptyScalar(start); } else { _states.add(_State.BLOCK_MAPPING_VALUE); return _parseNode(block: true, indentlessSequence: true); } } // libyaml doesn't allow empty keys without an explicit key indicator, but // the spec does. See example 8.18: // http://yaml.org/spec/1.2/spec.html#id2798896. if (token.type == TokenType.value) { _state = _State.BLOCK_MAPPING_VALUE; return _processEmptyScalar(token.span.start); } if (token.type == TokenType.blockEnd) { _scanner.scan(); _state = _states.removeLast(); return Event(EventType.mappingEnd, token.span); } throw YamlException('Expected a key while parsing a block mapping.', token.span.start.pointSpan()); } /// Parses the productions: /// /// block_mapping ::= BLOCK-MAPPING_START /// /// ((KEY block_node_or_indentless_sequence?)? /// /// (VALUE block_node_or_indentless_sequence?)?)* /// ***** * /// BLOCK-END /// Event _parseBlockMappingValue() { var token = _scanner.peek(); if (token.type != TokenType.value) { _state = _State.BLOCK_MAPPING_KEY; return _processEmptyScalar(token.span.start); } var start = token.span.start; token = _scanner.advance(); if (token.type == TokenType.key || token.type == TokenType.value || token.type == TokenType.blockEnd) { _state = _State.BLOCK_MAPPING_KEY; return _processEmptyScalar(start); } else { _states.add(_State.BLOCK_MAPPING_KEY); return _parseNode(block: true, indentlessSequence: true); } } /// Parses the productions: /// /// flow_sequence ::= FLOW-SEQUENCE-START /// ******************* /// (flow_sequence_entry FLOW-ENTRY)* /// * ********** /// flow_sequence_entry? /// * /// FLOW-SEQUENCE-END /// ***************** /// flow_sequence_entry ::= /// flow_node | KEY flow_node? (VALUE flow_node?)? /// * Event _parseFlowSequenceEntry({bool first = false}) { if (first) _scanner.scan(); var token = _scanner.peek(); if (token.type != TokenType.flowSequenceEnd) { if (!first) { if (token.type != TokenType.flowEntry) { throw YamlException( "While parsing a flow sequence, expected ',' or ']'.", token.span.start.pointSpan()); } token = _scanner.advance(); } if (token.type == TokenType.key) { _state = _State.FLOW_SEQUENCE_ENTRY_MAPPING_KEY; _scanner.scan(); return MappingStartEvent(token.span, CollectionStyle.FLOW); } else if (token.type != TokenType.flowSequenceEnd) { _states.add(_State.FLOW_SEQUENCE_ENTRY); return _parseNode(); } } _scanner.scan(); _state = _states.removeLast(); return Event(EventType.sequenceEnd, token.span); } /// Parses the productions: /// /// flow_sequence_entry ::= /// flow_node | KEY flow_node? (VALUE flow_node?)? /// *** * Event _parseFlowSequenceEntryMappingKey() { var token = _scanner.peek(); if (token.type == TokenType.value || token.type == TokenType.flowEntry || token.type == TokenType.flowSequenceEnd) { // libyaml consumes the token here, but that seems like a bug, since it // always causes [_parseFlowSequenceEntryMappingValue] to emit an empty // scalar. var start = token.span.start; _state = _State.FLOW_SEQUENCE_ENTRY_MAPPING_VALUE; return _processEmptyScalar(start); } else { _states.add(_State.FLOW_SEQUENCE_ENTRY_MAPPING_VALUE); return _parseNode(); } } /// Parses the productions: /// /// flow_sequence_entry ::= /// flow_node | KEY flow_node? (VALUE flow_node?)? /// ***** * Event _parseFlowSequenceEntryMappingValue() { var token = _scanner.peek(); if (token.type == TokenType.value) { token = _scanner.advance(); if (token.type != TokenType.flowEntry && token.type != TokenType.flowSequenceEnd) { _states.add(_State.FLOW_SEQUENCE_ENTRY_MAPPING_END); return _parseNode(); } } _state = _State.FLOW_SEQUENCE_ENTRY_MAPPING_END; return _processEmptyScalar(token.span.start); } /// Parses the productions: /// /// flow_sequence_entry ::= /// flow_node | KEY flow_node? (VALUE flow_node?)? /// * Event _parseFlowSequenceEntryMappingEnd() { _state = _State.FLOW_SEQUENCE_ENTRY; return Event(EventType.mappingEnd, _scanner.peek().span.start.pointSpan()); } /// Parses the productions: /// /// flow_mapping ::= FLOW-MAPPING-START /// ****************** /// (flow_mapping_entry FLOW-ENTRY)* /// * ********** /// flow_mapping_entry? /// ****************** /// FLOW-MAPPING-END /// **************** /// flow_mapping_entry ::= /// flow_node | KEY flow_node? (VALUE flow_node?)? /// * *** * Event _parseFlowMappingKey({bool first = false}) { if (first) _scanner.scan(); var token = _scanner.peek(); if (token.type != TokenType.flowMappingEnd) { if (!first) { if (token.type != TokenType.flowEntry) { throw YamlException( "While parsing a flow mapping, expected ',' or '}'.", token.span.start.pointSpan()); } token = _scanner.advance(); } if (token.type == TokenType.key) { token = _scanner.advance(); if (token.type != TokenType.value && token.type != TokenType.flowEntry && token.type != TokenType.flowMappingEnd) { _states.add(_State.FLOW_MAPPING_VALUE); return _parseNode(); } else { _state = _State.FLOW_MAPPING_VALUE; return _processEmptyScalar(token.span.start); } } else if (token.type != TokenType.flowMappingEnd) { _states.add(_State.FLOW_MAPPING_EMPTY_VALUE); return _parseNode(); } } _scanner.scan(); _state = _states.removeLast(); return Event(EventType.mappingEnd, token.span); } /// Parses the productions: /// /// flow_mapping_entry ::= /// flow_node | KEY flow_node? (VALUE flow_node?)? /// * ***** * Event _parseFlowMappingValue({bool empty = false}) { var token = _scanner.peek(); if (empty) { _state = _State.FLOW_MAPPING_KEY; return _processEmptyScalar(token.span.start); } if (token.type == TokenType.value) { token = _scanner.advance(); if (token.type != TokenType.flowEntry && token.type != TokenType.flowMappingEnd) { _states.add(_State.FLOW_MAPPING_KEY); return _parseNode(); } } _state = _State.FLOW_MAPPING_KEY; return _processEmptyScalar(token.span.start); } /// Generate an empty scalar event. Event _processEmptyScalar(SourceLocation location) => ScalarEvent(location.pointSpan() as FileSpan, '', ScalarStyle.PLAIN); /// Parses directives. Pair<VersionDirective, List<TagDirective>> _processDirectives() { var token = _scanner.peek(); VersionDirective versionDirective; var tagDirectives = <TagDirective>[]; while (token.type == TokenType.versionDirective || token.type == TokenType.tagDirective) { if (token is VersionDirectiveToken) { if (versionDirective != null) { throw YamlException('Duplicate %YAML directive.', token.span); } if (token.major != 1 || token.minor == 0) { throw YamlException( 'Incompatible YAML document. This parser only supports YAML 1.1 ' 'and 1.2.', token.span); } else if (token.minor > 2) { // TODO(nweiz): Print to stderr when issue 6943 is fixed and dart:io // is available. warn('Warning: this parser only supports YAML 1.1 and 1.2.', token.span); } versionDirective = VersionDirective(token.major, token.minor); } else if (token is TagDirectiveToken) { var tagDirective = TagDirective(token.handle, token.prefix); _appendTagDirective(tagDirective, token.span); tagDirectives.add(tagDirective); } token = _scanner.advance(); } _appendTagDirective(TagDirective('!', '!'), token.span.start.pointSpan(), allowDuplicates: true); _appendTagDirective( TagDirective('!!', 'tag:yaml.org,2002:'), token.span.start.pointSpan(), allowDuplicates: true); return Pair(versionDirective, tagDirectives); } /// Adds a tag directive to the directives stack. void _appendTagDirective(TagDirective newDirective, FileSpan span, {bool allowDuplicates = false}) { if (_tagDirectives.containsKey(newDirective.handle)) { if (allowDuplicates) return; throw YamlException('Duplicate %TAG directive.', span); } _tagDirectives[newDirective.handle] = newDirective; } } /// The possible states for the parser. class _State { /// Expect [TokenType.streamStart]. static const STREAM_START = _State('STREAM_START'); /// Expect [TokenType.documentStart]. static const DOCUMENT_START = _State('DOCUMENT_START'); /// Expect the content of a document. static const DOCUMENT_CONTENT = _State('DOCUMENT_CONTENT'); /// Expect [TokenType.documentEnd]. static const DOCUMENT_END = _State('DOCUMENT_END'); /// Expect a block node. static const BLOCK_NODE = _State('BLOCK_NODE'); /// Expect a block node or indentless sequence. static const BLOCK_NODE_OR_INDENTLESS_SEQUENCE = _State('BLOCK_NODE_OR_INDENTLESS_SEQUENCE'); /// Expect a flow node. static const FLOW_NODE = _State('FLOW_NODE'); /// Expect the first entry of a block sequence. static const BLOCK_SEQUENCE_FIRST_ENTRY = _State('BLOCK_SEQUENCE_FIRST_ENTRY'); /// Expect an entry of a block sequence. static const BLOCK_SEQUENCE_ENTRY = _State('BLOCK_SEQUENCE_ENTRY'); /// Expect an entry of an indentless sequence. static const INDENTLESS_SEQUENCE_ENTRY = _State('INDENTLESS_SEQUENCE_ENTRY'); /// Expect the first key of a block mapping. static const BLOCK_MAPPING_FIRST_KEY = _State('BLOCK_MAPPING_FIRST_KEY'); /// Expect a block mapping key. static const BLOCK_MAPPING_KEY = _State('BLOCK_MAPPING_KEY'); /// Expect a block mapping value. static const BLOCK_MAPPING_VALUE = _State('BLOCK_MAPPING_VALUE'); /// Expect the first entry of a flow sequence. static const FLOW_SEQUENCE_FIRST_ENTRY = _State('FLOW_SEQUENCE_FIRST_ENTRY'); /// Expect an entry of a flow sequence. static const FLOW_SEQUENCE_ENTRY = _State('FLOW_SEQUENCE_ENTRY'); /// Expect a key of an ordered mapping. static const FLOW_SEQUENCE_ENTRY_MAPPING_KEY = _State('FLOW_SEQUENCE_ENTRY_MAPPING_KEY'); /// Expect a value of an ordered mapping. static const FLOW_SEQUENCE_ENTRY_MAPPING_VALUE = _State('FLOW_SEQUENCE_ENTRY_MAPPING_VALUE'); /// Expect the and of an ordered mapping entry. static const FLOW_SEQUENCE_ENTRY_MAPPING_END = _State('FLOW_SEQUENCE_ENTRY_MAPPING_END'); /// Expect the first key of a flow mapping. static const FLOW_MAPPING_FIRST_KEY = _State('FLOW_MAPPING_FIRST_KEY'); /// Expect a key of a flow mapping. static const FLOW_MAPPING_KEY = _State('FLOW_MAPPING_KEY'); /// Expect a value of a flow mapping. static const FLOW_MAPPING_VALUE = _State('FLOW_MAPPING_VALUE'); /// Expect an empty value of a flow mapping. static const FLOW_MAPPING_EMPTY_VALUE = _State('FLOW_MAPPING_EMPTY_VALUE'); /// Expect nothing. 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/yaml
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml/src/null_span.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:source_span/source_span.dart'; /// A [SourceSpan] with no location information. /// /// This is used with [YamlMap.wrap] and [YamlList.wrap] to provide means of /// accessing a non-YAML map that behaves transparently like a map parsed from /// YAML. class NullSpan extends SourceSpanMixin { @override final SourceLocation start; @override SourceLocation get end => start; @override final text = ''; NullSpan(sourceUrl) : start = SourceLocation(0, sourceUrl: sourceUrl); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml/src/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. /// An enum of source scalar styles. class ScalarStyle { /// No source style was specified. /// /// This usually indicates a scalar constructed with [YamlScalar.wrap]. static const ANY = ScalarStyle._('ANY'); /// The plain scalar style, unquoted and without a prefix. /// /// See http://yaml.org/spec/1.2/spec.html#style/flow/plain. static const PLAIN = ScalarStyle._('PLAIN'); /// The literal scalar style, with a `|` prefix. /// /// See http://yaml.org/spec/1.2/spec.html#id2795688. static const LITERAL = ScalarStyle._('LITERAL'); /// The folded scalar style, with a `>` prefix. /// /// See http://yaml.org/spec/1.2/spec.html#id2796251. static const FOLDED = ScalarStyle._('FOLDED'); /// The single-quoted scalar style. /// /// See http://yaml.org/spec/1.2/spec.html#style/flow/single-quoted. static const SINGLE_QUOTED = ScalarStyle._('SINGLE_QUOTED'); /// The double-quoted scalar style. /// /// See http://yaml.org/spec/1.2/spec.html#style/flow/double-quoted. static const DOUBLE_QUOTED = ScalarStyle._('DOUBLE_QUOTED'); final String name; /// Whether this is a quoted style ([SINGLE_QUOTED] or [DOUBLE_QUOTED]). bool get isQuoted => this == SINGLE_QUOTED || this == DOUBLE_QUOTED; const ScalarStyle._(this.name); @override String toString() => name; } /// An enum of collection styles. class CollectionStyle { /// No source style was specified. /// /// This usually indicates a collection constructed with [YamlList.wrap] or /// [YamlMap.wrap]. static const ANY = CollectionStyle._('ANY'); /// The indentation-based block style. /// /// See http://yaml.org/spec/1.2/spec.html#id2797293. static const BLOCK = CollectionStyle._('BLOCK'); /// The delimiter-based block style. /// /// See http://yaml.org/spec/1.2/spec.html#id2790088. static const FLOW = CollectionStyle._('FLOW'); final String name; const CollectionStyle._(this.name); @override String toString() => name; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml/src/scanner.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:source_span/source_span.dart'; import 'package:string_scanner/string_scanner.dart'; import 'style.dart'; import 'token.dart'; import 'utils.dart'; import 'yaml_exception.dart'; /// A scanner that reads a string of Unicode characters and emits [Token]s. /// /// This is based on the libyaml scanner, available at /// https://github.com/yaml/libyaml/blob/master/src/scanner.c. The license for /// that is available in ../../libyaml-license.txt. class Scanner { static const TAB = 0x9; static const LF = 0xA; static const CR = 0xD; static const SP = 0x20; static const DOLLAR = 0x24; static const LEFT_PAREN = 0x28; static const RIGHT_PAREN = 0x29; static const PLUS = 0x2B; static const COMMA = 0x2C; static const HYPHEN = 0x2D; static const PERIOD = 0x2E; static const QUESTION = 0x3F; static const COLON = 0x3A; static const SEMICOLON = 0x3B; static const EQUALS = 0x3D; static const LEFT_SQUARE = 0x5B; static const RIGHT_SQUARE = 0x5D; static const LEFT_CURLY = 0x7B; static const RIGHT_CURLY = 0x7D; static const HASH = 0x23; static const AMPERSAND = 0x26; static const ASTERISK = 0x2A; static const EXCLAMATION = 0x21; static const VERTICAL_BAR = 0x7C; static const LEFT_ANGLE = 0x3C; static const RIGHT_ANGLE = 0x3E; static const SINGLE_QUOTE = 0x27; static const DOUBLE_QUOTE = 0x22; static const PERCENT = 0x25; static const AT = 0x40; static const GRAVE_ACCENT = 0x60; static const TILDE = 0x7E; static const NULL = 0x0; static const BELL = 0x7; static const BACKSPACE = 0x8; static const VERTICAL_TAB = 0xB; static const FORM_FEED = 0xC; static const ESCAPE = 0x1B; static const SLASH = 0x2F; static const BACKSLASH = 0x5C; static const UNDERSCORE = 0x5F; static const NEL = 0x85; static const NBSP = 0xA0; static const LINE_SEPARATOR = 0x2028; static const PARAGRAPH_SEPARATOR = 0x2029; static const BOM = 0xFEFF; static const NUMBER_0 = 0x30; static const NUMBER_9 = 0x39; static const LETTER_A = 0x61; static const LETTER_B = 0x62; static const LETTER_E = 0x65; static const LETTER_F = 0x66; static const LETTER_N = 0x6E; static const LETTER_R = 0x72; static const LETTER_T = 0x74; static const LETTER_U = 0x75; static const LETTER_V = 0x76; static const LETTER_X = 0x78; static const LETTER_Z = 0x7A; static const LETTER_CAP_A = 0x41; static const LETTER_CAP_F = 0x46; static const LETTER_CAP_L = 0x4C; static const LETTER_CAP_N = 0x4E; static const LETTER_CAP_P = 0x50; static const LETTER_CAP_U = 0x55; static const LETTER_CAP_X = 0x58; static const LETTER_CAP_Z = 0x5A; /// The underlying [SpanScanner] used to read characters from the source text. /// /// This is also used to track line and column information and to generate /// [SourceSpan]s. final SpanScanner _scanner; /// Whether this scanner has produced a [TokenType.streamStart] token /// indicating the beginning of the YAML stream. var _streamStartProduced = false; /// Whether this scanner has produced a [TokenType.streamEnd] token /// indicating the end of the YAML stream. var _streamEndProduced = false; /// The queue of tokens yet to be emitted. /// /// These are queued up in advance so that [TokenType.key] tokens can be /// inserted once the scanner determines that a series of tokens represents a /// mapping key. final _tokens = QueueList<Token>(); /// The number of tokens that have been emitted. /// /// This doesn't count tokens in [tokens]. var _tokensParsed = 0; /// Whether the next token in [_tokens] is ready to be returned. /// /// It might not be ready if there may still be a [TokenType.key] inserted /// before it. var _tokenAvailable = false; /// The stack of indent levels for the current nested block contexts. /// /// The YAML spec specifies that the initial indentation level is -1 spaces. final _indents = <int>[-1]; /// Whether a simple key is allowed in this context. /// /// A simple key refers to any mapping key that doesn't have an explicit "?". var _simpleKeyAllowed = true; /// The stack of potential simple keys for each level of flow nesting. /// /// Entries in this list may be `null`, indicating that there is no valid /// simple key for the associated level of nesting. /// /// When a ":" is parsed and there's a simple key available, a [TokenType.key] /// token is inserted in [_tokens] before that key's token. This allows the /// parser to tell that the key is intended to be a mapping key. final _simpleKeys = <_SimpleKey>[null]; /// The current indentation level. int get _indent => _indents.last; /// Whether the scanner's currently positioned in a block-level structure (as /// opposed to flow-level). bool get _inBlockContext => _simpleKeys.length == 1; /// Whether the current character is a line break or the end of the source. bool get _isBreakOrEnd => _scanner.isDone || _isBreak; /// Whether the current character is a line break. bool get _isBreak => _isBreakAt(0); /// Whether the current character is whitespace or the end of the source. bool get _isBlankOrEnd => _isBlankOrEndAt(0); /// Whether the current character is whitespace. bool get _isBlank => _isBlankAt(0); /// Whether the current character is a valid tag name character. /// /// See http://yaml.org/spec/1.2/spec.html#ns-tag-name. bool get _isTagChar { var char = _scanner.peekChar(); if (char == null) return false; switch (char) { case HYPHEN: case SEMICOLON: case SLASH: case COLON: case AT: case AMPERSAND: case EQUALS: case PLUS: case DOLLAR: case PERIOD: case TILDE: case QUESTION: case ASTERISK: case SINGLE_QUOTE: case LEFT_PAREN: case RIGHT_PAREN: case PERCENT: return true; default: return (char >= NUMBER_0 && char <= NUMBER_9) || (char >= LETTER_A && char <= LETTER_Z) || (char >= LETTER_CAP_A && char <= LETTER_CAP_Z); } } /// Whether the current character is a valid anchor name character. /// /// See http://yaml.org/spec/1.2/spec.html#ns-anchor-name. bool get _isAnchorChar { if (!_isNonSpace) return false; switch (_scanner.peekChar()) { case COMMA: case LEFT_SQUARE: case RIGHT_SQUARE: case LEFT_CURLY: case RIGHT_CURLY: return false; default: return true; } } /// Whether the character at the current position is a decimal digit. bool get _isDigit { var char = _scanner.peekChar(); return char != null && (char >= NUMBER_0 && char <= NUMBER_9); } /// Whether the character at the current position is a hexidecimal /// digit. bool get _isHex { var char = _scanner.peekChar(); if (char == null) return false; return (char >= NUMBER_0 && char <= NUMBER_9) || (char >= LETTER_A && char <= LETTER_F) || (char >= LETTER_CAP_A && char <= LETTER_CAP_F); } /// Whether the character at the current position is a plain character. /// /// See http://yaml.org/spec/1.2/spec.html#ns-plain-char(c). bool get _isPlainChar => _isPlainCharAt(0); /// Whether the character at the current position is a printable character /// other than a line break or byte-order mark. /// /// See http://yaml.org/spec/1.2/spec.html#nb-char. bool get _isNonBreak { var char = _scanner.peekChar(); if (char == null) return false; switch (char) { case LF: case CR: case BOM: return false; case TAB: case NEL: return true; default: return (char >= 0x00020 && char <= 0x00007E) || (char >= 0x000A0 && char <= 0x00D7FF) || (char >= 0x0E000 && char <= 0x00FFFD) || (char >= 0x10000 && char <= 0x10FFFF); } } /// Whether the character at the current position is a printable character /// other than whitespace. /// /// See http://yaml.org/spec/1.2/spec.html#nb-char. bool get _isNonSpace { var char = _scanner.peekChar(); if (char == null) return false; switch (char) { case LF: case CR: case BOM: case SP: return false; case NEL: return true; default: return (char >= 0x00020 && char <= 0x00007E) || (char >= 0x000A0 && char <= 0x00D7FF) || (char >= 0x0E000 && char <= 0x00FFFD) || (char >= 0x10000 && char <= 0x10FFFF); } } /// Returns Whether or not the current character begins a documentation /// indicator. /// /// If so, this sets the scanner's last match to that indicator. bool get _isDocumentIndicator { return _scanner.column == 0 && _isBlankOrEndAt(3) && (_scanner.matches('---') || _scanner.matches('...')); } /// Creates a scanner that scans [source]. /// /// [sourceUrl] can be a String or a [Uri]. Scanner(String source, {sourceUrl}) : _scanner = SpanScanner.eager(source, sourceUrl: sourceUrl); /// Consumes and returns the next token. Token scan() { if (_streamEndProduced) throw StateError('Out of tokens.'); if (!_tokenAvailable) _fetchMoreTokens(); var token = _tokens.removeFirst(); _tokenAvailable = false; _tokensParsed++; _streamEndProduced = token is Token && token.type == TokenType.streamEnd; return token; } /// Consumes the next token and returns the one after that. Token advance() { scan(); return peek(); } /// Returns the next token without consuming it. Token peek() { if (_streamEndProduced) return null; if (!_tokenAvailable) _fetchMoreTokens(); return _tokens.first; } /// Ensures that [_tokens] contains at least one token which can be returned. void _fetchMoreTokens() { while (true) { if (_tokens.isNotEmpty) { _staleSimpleKeys(); // If there are no more tokens to fetch, break. if (_tokens.last.type == TokenType.streamEnd) break; // If the current token could be a simple key, we need to scan more // tokens until we determine whether it is or not. Otherwise we might // not emit the `KEY` token before we emit the value of the key. if (!_simpleKeys .any((key) => key != null && key.tokenNumber == _tokensParsed)) { break; } } _fetchNextToken(); } _tokenAvailable = true; } /// The dispatcher for token fetchers. void _fetchNextToken() { if (!_streamStartProduced) { _fetchStreamStart(); return; } _scanToNextToken(); _staleSimpleKeys(); _unrollIndent(_scanner.column); if (_scanner.isDone) { _fetchStreamEnd(); return; } if (_scanner.column == 0) { if (_scanner.peekChar() == PERCENT) { _fetchDirective(); return; } if (_isBlankOrEndAt(3)) { if (_scanner.matches('---')) { _fetchDocumentIndicator(TokenType.documentStart); return; } if (_scanner.matches('...')) { _fetchDocumentIndicator(TokenType.documentEnd); return; } } } switch (_scanner.peekChar()) { case LEFT_SQUARE: _fetchFlowCollectionStart(TokenType.flowSequenceStart); return; case LEFT_CURLY: _fetchFlowCollectionStart(TokenType.flowMappingStart); return; case RIGHT_SQUARE: _fetchFlowCollectionEnd(TokenType.flowSequenceEnd); return; case RIGHT_CURLY: _fetchFlowCollectionEnd(TokenType.flowMappingEnd); return; case COMMA: _fetchFlowEntry(); return; case ASTERISK: _fetchAnchor(anchor: false); return; case AMPERSAND: _fetchAnchor(anchor: true); return; case EXCLAMATION: _fetchTag(); return; case SINGLE_QUOTE: _fetchFlowScalar(singleQuote: true); return; case DOUBLE_QUOTE: _fetchFlowScalar(singleQuote: false); return; case VERTICAL_BAR: if (!_inBlockContext) _invalidScalarCharacter(); _fetchBlockScalar(literal: true); return; case RIGHT_ANGLE: if (!_inBlockContext) _invalidScalarCharacter(); _fetchBlockScalar(literal: false); return; case PERCENT: case AT: case GRAVE_ACCENT: _invalidScalarCharacter(); return; // These characters may sometimes begin plain scalars. case HYPHEN: if (_isPlainCharAt(1)) { _fetchPlainScalar(); } else { _fetchBlockEntry(); } return; case QUESTION: if (_isPlainCharAt(1)) { _fetchPlainScalar(); } else { _fetchKey(); } return; case COLON: if (!_inBlockContext && _tokens.isNotEmpty) { // If a colon follows a "JSON-like" value (an explicit map or list, or // a quoted string) it isn't required to have whitespace after it // since it unambiguously describes a map. var token = _tokens.last; if (token.type == TokenType.flowSequenceEnd || token.type == TokenType.flowMappingEnd || (token.type == TokenType.scalar && (token as ScalarToken).style.isQuoted)) { _fetchValue(); return; } } if (_isPlainCharAt(1)) { _fetchPlainScalar(); } else { _fetchValue(); } return; default: if (!_isNonBreak) _invalidScalarCharacter(); _fetchPlainScalar(); return; } } /// Throws an error about a disallowed character. void _invalidScalarCharacter() => _scanner.error('Unexpected character.', length: 1); /// Checks the list of potential simple keys and remove the positions that /// cannot contain simple keys anymore. void _staleSimpleKeys() { for (var i = 0; i < _simpleKeys.length; i++) { var key = _simpleKeys[i]; if (key == null) continue; // libyaml requires that all simple keys be a single line and no longer // than 1024 characters. However, in section 7.4.2 of the spec // (http://yaml.org/spec/1.2/spec.html#id2790832), these restrictions are // only applied when the curly braces are omitted. It's difficult to // retain enough context to know which keys need to have the restriction // placed on them, so for now we go the other direction and allow // everything but multiline simple keys in a block context. if (!_inBlockContext) continue; if (key.line == _scanner.line) continue; if (key.required) { throw YamlException("Expected ':'.", _scanner.emptySpan); } _simpleKeys[i] = null; } } /// Checks if a simple key may start at the current position and saves it if /// so. void _saveSimpleKey() { // A simple key is required at the current position if the scanner is in the // block context and the current column coincides with the indentation // level. var required = _inBlockContext && _indent == _scanner.column; // A simple key is required only when it is the first token in the current // line. Therefore it is always allowed. But we add a check anyway. assert(_simpleKeyAllowed || !required); if (!_simpleKeyAllowed) return; // If the current position may start a simple key, save it. _removeSimpleKey(); _simpleKeys[_simpleKeys.length - 1] = _SimpleKey( _tokensParsed + _tokens.length, _scanner.line, _scanner.column, _scanner.location, required: required); } /// Removes a potential simple key at the current flow level. void _removeSimpleKey() { var key = _simpleKeys.last; if (key != null && key.required) { throw YamlException("Could not find expected ':' for simple key.", key.location.pointSpan()); } _simpleKeys[_simpleKeys.length - 1] = null; } /// Increases the flow level and resizes the simple key list. void _increaseFlowLevel() { _simpleKeys.add(null); } /// Decreases the flow level. void _decreaseFlowLevel() { if (_inBlockContext) return; _simpleKeys.removeLast(); } /// Pushes the current indentation level to the stack and sets the new level /// if [column] is greater than [_indent]. /// /// If it is, appends or inserts the specified token into [_tokens]. If /// [tokenNumber] is provided, the corresponding token will be replaced; /// otherwise, the token will be added at the end. void _rollIndent(int column, TokenType type, SourceLocation location, {int tokenNumber}) { if (!_inBlockContext) return; if (_indent != -1 && _indent >= column) return; // Push the current indentation level to the stack and set the new // indentation level. _indents.add(column); // Create a token and insert it into the queue. var token = Token(type, location.pointSpan() as FileSpan); if (tokenNumber == null) { _tokens.add(token); } else { _tokens.insert(tokenNumber - _tokensParsed, token); } } /// Pops indentation levels from [_indents] until the current level becomes /// less than or equal to [column]. /// /// For each indentation level, appends a [TokenType.blockEnd] token. void _unrollIndent(int column) { if (!_inBlockContext) return; while (_indent > column) { _tokens.add(Token(TokenType.blockEnd, _scanner.emptySpan)); _indents.removeLast(); } } /// Pops indentation levels from [_indents] until the current level resets to /// -1. /// /// For each indentation level, appends a [TokenType.blockEnd] token. void _resetIndent() => _unrollIndent(-1); /// Produces a [TokenType.streamStart] token. void _fetchStreamStart() { // Much of libyaml's initialization logic here is done in variable // initializers instead. _streamStartProduced = true; _tokens.add(Token(TokenType.streamStart, _scanner.emptySpan)); } /// Produces a [TokenType.streamEnd] token. void _fetchStreamEnd() { _resetIndent(); _removeSimpleKey(); _simpleKeyAllowed = false; _tokens.add(Token(TokenType.streamEnd, _scanner.emptySpan)); } /// Produces a [TokenType.versionDirective] or [TokenType.tagDirective] /// token. void _fetchDirective() { _resetIndent(); _removeSimpleKey(); _simpleKeyAllowed = false; var directive = _scanDirective(); if (directive != null) _tokens.add(directive); } /// Produces a [TokenType.documentStart] or [TokenType.documentEnd] token. void _fetchDocumentIndicator(TokenType type) { _resetIndent(); _removeSimpleKey(); _simpleKeyAllowed = false; // Consume the indicator token. var start = _scanner.state; _scanner.readChar(); _scanner.readChar(); _scanner.readChar(); _tokens.add(Token(type, _scanner.spanFrom(start))); } /// Produces a [TokenType.flowSequenceStart] or /// [TokenType.flowMappingStart] token. void _fetchFlowCollectionStart(TokenType type) { _saveSimpleKey(); _increaseFlowLevel(); _simpleKeyAllowed = true; _addCharToken(type); } /// Produces a [TokenType.flowSequenceEnd] or [TokenType.flowMappingEnd] /// token. void _fetchFlowCollectionEnd(TokenType type) { _removeSimpleKey(); _decreaseFlowLevel(); _simpleKeyAllowed = false; _addCharToken(type); } /// Produces a [TokenType.flowEntry] token. void _fetchFlowEntry() { _removeSimpleKey(); _simpleKeyAllowed = true; _addCharToken(TokenType.flowEntry); } /// Produces a [TokenType.blockEntry] token. void _fetchBlockEntry() { if (_inBlockContext) { if (!_simpleKeyAllowed) { throw YamlException( 'Block sequence entries are not allowed here.', _scanner.emptySpan); } _rollIndent( _scanner.column, TokenType.blockSequenceStart, _scanner.location); } else { // It is an error for the '-' indicator to occur in the flow context, but // we let the Parser detect and report it because it's able to point to // the context. } _removeSimpleKey(); _simpleKeyAllowed = true; _addCharToken(TokenType.blockEntry); } /// Produces the [TokenType.key] token. void _fetchKey() { if (_inBlockContext) { if (!_simpleKeyAllowed) { throw YamlException( 'Mapping keys are not allowed here.', _scanner.emptySpan); } _rollIndent( _scanner.column, TokenType.blockMappingStart, _scanner.location); } // Simple keys are allowed after `?` in a block context. _simpleKeyAllowed = _inBlockContext; _addCharToken(TokenType.key); } /// Produces the [TokenType.value] token. void _fetchValue() { var simpleKey = _simpleKeys.last; if (simpleKey != null) { // Add a [TokenType.KEY] directive before the first token of the simple // key so the parser knows that it's part of a key/value pair. _tokens.insert(simpleKey.tokenNumber - _tokensParsed, Token(TokenType.key, simpleKey.location.pointSpan() as FileSpan)); // In the block context, we may need to add the // [TokenType.BLOCK_MAPPING_START] token. _rollIndent( simpleKey.column, TokenType.blockMappingStart, simpleKey.location, tokenNumber: simpleKey.tokenNumber); // Remove the simple key. _simpleKeys[_simpleKeys.length - 1] = null; // A simple key cannot follow another simple key. _simpleKeyAllowed = false; } else if (_inBlockContext) { if (!_simpleKeyAllowed) { throw YamlException( 'Mapping values are not allowed here. Did you miss a colon ' 'earlier?', _scanner.emptySpan); } // If we're here, we've found the ':' indicator following a complex key. _rollIndent( _scanner.column, TokenType.blockMappingStart, _scanner.location); _simpleKeyAllowed = true; } else if (_simpleKeyAllowed) { // If we're here, we've found the ':' indicator with an empty key. This // behavior differs from libyaml, which disallows empty implicit keys. _simpleKeyAllowed = false; _addCharToken(TokenType.key); } _addCharToken(TokenType.value); } /// Adds a token with [type] to [_tokens]. /// /// The span of the new token is the current character. void _addCharToken(TokenType type) { var start = _scanner.state; _scanner.readChar(); _tokens.add(Token(type, _scanner.spanFrom(start))); } /// Produces a [TokenType.alias] or [TokenType.anchor] token. void _fetchAnchor({bool anchor = true}) { _saveSimpleKey(); _simpleKeyAllowed = false; _tokens.add(_scanAnchor(anchor: anchor)); } /// Produces a [TokenType.tag] token. void _fetchTag() { _saveSimpleKey(); _simpleKeyAllowed = false; _tokens.add(_scanTag()); } /// Produces a [TokenType.scalar] token with style [ScalarStyle.LITERAL] or /// [ScalarStyle.FOLDED]. void _fetchBlockScalar({bool literal = false}) { _removeSimpleKey(); _simpleKeyAllowed = true; _tokens.add(_scanBlockScalar(literal: literal)); } /// Produces a [TokenType.scalar] token with style [ScalarStyle.SINGLE_QUOTED] /// or [ScalarStyle.DOUBLE_QUOTED]. void _fetchFlowScalar({bool singleQuote = false}) { _saveSimpleKey(); _simpleKeyAllowed = false; _tokens.add(_scanFlowScalar(singleQuote: singleQuote)); } /// Produces a [TokenType.scalar] token with style [ScalarStyle.PLAIN]. void _fetchPlainScalar() { _saveSimpleKey(); _simpleKeyAllowed = false; _tokens.add(_scanPlainScalar()); } /// Eats whitespace and comments until the next token is found. void _scanToNextToken() { var afterLineBreak = false; while (true) { // Allow the BOM to start a line. if (_scanner.column == 0) _scanner.scan('\uFEFF'); // Eat whitespace. // // libyaml disallows tabs after "-", "?", or ":", but the spec allows // them. See section 6.2: http://yaml.org/spec/1.2/spec.html#id2778241. while (_scanner.peekChar() == SP || ((!_inBlockContext || !afterLineBreak) && _scanner.peekChar() == TAB)) { _scanner.readChar(); } if (_scanner.peekChar() == TAB) { _scanner.error('Tab characters are not allowed as indentation.', length: 1); } // Eat a comment until a line break. _skipComment(); // If we're at a line break, eat it. if (_isBreak) { _skipLine(); // In the block context, a new line may start a simple key. if (_inBlockContext) _simpleKeyAllowed = true; afterLineBreak = true; } else { // Otherwise we've found a token. break; } } } /// Scans a [TokenType.YAML_DIRECTIVE] or [TokenType.tagDirective] token. /// /// %YAML 1.2 # a comment \n /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ /// %TAG !yaml! tag:yaml.org,2002: \n /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Token _scanDirective() { var start = _scanner.state; // Eat '%'. _scanner.readChar(); Token token; var name = _scanDirectiveName(); if (name == 'YAML') { token = _scanVersionDirectiveValue(start); } else if (name == 'TAG') { token = _scanTagDirectiveValue(start); } else { warn('Warning: unknown directive.', _scanner.spanFrom(start)); // libyaml doesn't support unknown directives, but the spec says to ignore // them and warn: http://yaml.org/spec/1.2/spec.html#id2781147. while (!_isBreakOrEnd) { _scanner.readChar(); } return null; } // Eat the rest of the line, including any comments. _skipBlanks(); _skipComment(); if (!_isBreakOrEnd) { throw YamlException('Expected comment or line break after directive.', _scanner.spanFrom(start)); } _skipLine(); return token; } /// Scans a directive name. /// /// %YAML 1.2 # a comment \n /// ^^^^ /// %TAG !yaml! tag:yaml.org,2002: \n /// ^^^ String _scanDirectiveName() { // libyaml only allows word characters in directive names, but the spec // disagrees: http://yaml.org/spec/1.2/spec.html#ns-directive-name. var start = _scanner.position; while (_isNonSpace) { _scanner.readChar(); } var name = _scanner.substring(start); if (name.isEmpty) { throw YamlException('Expected directive name.', _scanner.emptySpan); } else if (!_isBlankOrEnd) { throw YamlException( 'Unexpected character in directive name.', _scanner.emptySpan); } return name; } /// Scans the value of a version directive. /// /// %YAML 1.2 # a comment \n /// ^^^^^^ Token _scanVersionDirectiveValue(LineScannerState start) { _skipBlanks(); var major = _scanVersionDirectiveNumber(); _scanner.expect('.'); var minor = _scanVersionDirectiveNumber(); return VersionDirectiveToken(_scanner.spanFrom(start), major, minor); } /// Scans the version number of a version directive. /// /// %YAML 1.2 # a comment \n /// ^ /// %YAML 1.2 # a comment \n /// ^ int _scanVersionDirectiveNumber() { var start = _scanner.position; while (_isDigit) { _scanner.readChar(); } var number = _scanner.substring(start); if (number.isEmpty) { throw YamlException('Expected version number.', _scanner.emptySpan); } return int.parse(number); } /// Scans the value of a tag directive. /// /// %TAG !yaml! tag:yaml.org,2002: \n /// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Token _scanTagDirectiveValue(LineScannerState start) { _skipBlanks(); var handle = _scanTagHandle(directive: true); if (!_isBlank) { throw YamlException('Expected whitespace.', _scanner.emptySpan); } _skipBlanks(); var prefix = _scanTagUri(); if (!_isBlankOrEnd) { throw YamlException('Expected whitespace.', _scanner.emptySpan); } return TagDirectiveToken(_scanner.spanFrom(start), handle, prefix); } /// Scans a [TokenType.anchor] token. Token _scanAnchor({bool anchor = true}) { var start = _scanner.state; // Eat the indicator character. _scanner.readChar(); // libyaml only allows word characters in anchor names, but the spec // disagrees: http://yaml.org/spec/1.2/spec.html#ns-anchor-char. var startPosition = _scanner.position; while (_isAnchorChar) { _scanner.readChar(); } var name = _scanner.substring(startPosition); var next = _scanner.peekChar(); if (name.isEmpty || (!_isBlankOrEnd && next != QUESTION && next != COLON && next != COMMA && next != RIGHT_SQUARE && next != RIGHT_CURLY && next != PERCENT && next != AT && next != GRAVE_ACCENT)) { throw YamlException( 'Expected alphanumeric character.', _scanner.emptySpan); } if (anchor) { return AnchorToken(_scanner.spanFrom(start), name); } else { return AliasToken(_scanner.spanFrom(start), name); } } /// Scans a [TokenType.tag] token. Token _scanTag() { String handle; String suffix; var start = _scanner.state; // Check if the tag is in the canonical form. if (_scanner.peekChar(1) == LEFT_ANGLE) { // Eat '!<'. _scanner.readChar(); _scanner.readChar(); handle = ''; suffix = _scanTagUri(); _scanner.expect('>'); } else { // The tag has either the '!suffix' or the '!handle!suffix' form. // First, try to scan a handle. handle = _scanTagHandle(); if (handle.length > 1 && handle.startsWith('!') && handle.endsWith('!')) { suffix = _scanTagUri(flowSeparators: false); } else { suffix = _scanTagUri(head: handle, flowSeparators: false); // There was no explicit handle. if (suffix.isEmpty) { // This is the special '!' tag. handle = null; suffix = '!'; } else { handle = '!'; } } } // libyaml insists on whitespace after a tag, but example 7.2 indicates // that it's not required: http://yaml.org/spec/1.2/spec.html#id2786720. return TagToken(_scanner.spanFrom(start), handle, suffix); } /// Scans a tag handle. String _scanTagHandle({bool directive = false}) { _scanner.expect('!'); var buffer = StringBuffer('!'); // libyaml only allows word characters in tags, but the spec disagrees: // http://yaml.org/spec/1.2/spec.html#ns-tag-char. var start = _scanner.position; while (_isTagChar) { _scanner.readChar(); } buffer.write(_scanner.substring(start)); if (_scanner.peekChar() == EXCLAMATION) { buffer.writeCharCode(_scanner.readChar()); } else { // It's either the '!' tag or not really a tag handle. If it's a %TAG // directive, it's an error. If it's a tag token, it must be part of a // URI. if (directive && buffer.toString() != '!') _scanner.expect('!'); } return buffer.toString(); } /// Scans a tag URI. /// /// [head] is the initial portion of the tag that's already been scanned. /// [flowSeparators] indicates whether the tag URI can contain flow /// separators. String _scanTagUri({String head, bool flowSeparators = true}) { var length = head == null ? 0 : head.length; var buffer = StringBuffer(); // Copy the head if needed. // // Note that we don't copy the leading '!' character. if (length > 1) buffer.write(head.substring(1)); // The set of characters that may appear in URI is as follows: // // '0'-'9', 'A'-'Z', 'a'-'z', '_', '-', ';', '/', '?', ':', '@', '&', // '=', '+', '$', ',', '.', '!', '~', '*', '\'', '(', ')', '[', ']', // '%'. // // In a shorthand tag annotation, the flow separators ',', '[', and ']' are // disallowed. var start = _scanner.position; var char = _scanner.peekChar(); while (_isTagChar || (flowSeparators && (char == COMMA || char == LEFT_SQUARE || char == RIGHT_SQUARE))) { _scanner.readChar(); char = _scanner.peekChar(); } // libyaml manually decodes the URL, but we don't have to do that. return Uri.decodeFull(_scanner.substring(start)); } /// Scans a block scalar. Token _scanBlockScalar({bool literal = false}) { var start = _scanner.state; // Eat the indicator '|' or '>'. _scanner.readChar(); // Check for a chomping indicator. var chomping = _Chomping.clip; var increment = 0; var char = _scanner.peekChar(); if (char == PLUS || char == HYPHEN) { chomping = char == PLUS ? _Chomping.keep : _Chomping.strip; _scanner.readChar(); // Check for an indentation indicator. if (_isDigit) { // Check that the indentation is greater than 0. if (_scanner.peekChar() == NUMBER_0) { throw YamlException('0 may not be used as an indentation indicator.', _scanner.spanFrom(start)); } increment = _scanner.readChar() - NUMBER_0; } } else if (_isDigit) { // Do the same as above, but in the opposite order. if (_scanner.peekChar() == NUMBER_0) { throw YamlException('0 may not be used as an indentation indicator.', _scanner.spanFrom(start)); } increment = _scanner.readChar() - NUMBER_0; char = _scanner.peekChar(); if (char == PLUS || char == HYPHEN) { chomping = char == PLUS ? _Chomping.keep : _Chomping.strip; _scanner.readChar(); } } // Eat whitespace and comments to the end of the line. _skipBlanks(); _skipComment(); // Check if we're at the end of the line. if (!_isBreakOrEnd) { throw YamlException( 'Expected comment or line break.', _scanner.emptySpan); } _skipLine(); // If the block scalar has an explicit indentation indicator, add that to // the current indentation to get the indentation level for the scalar's // contents. var indent = 0; if (increment != 0) { indent = _indent >= 0 ? _indent + increment : increment; } // Scan the leading line breaks to determine the indentation level if // needed. var pair = _scanBlockScalarBreaks(indent); indent = pair.first; var trailingBreaks = pair.last; // Scan the block scalar contents. var buffer = StringBuffer(); var leadingBreak = ''; var leadingBlank = false; var trailingBlank = false; var end = _scanner.state; while (_scanner.column == indent && !_scanner.isDone) { // Check for a document indicator. libyaml doesn't do this, but the spec // mandates it. See example 9.5: // http://yaml.org/spec/1.2/spec.html#id2801606. if (_isDocumentIndicator) break; // We are at the beginning of a non-empty line. // Is there trailing whitespace? trailingBlank = _isBlank; // Check if we need to fold the leading line break. if (!literal && leadingBreak.isNotEmpty && !leadingBlank && !trailingBlank) { // Do we need to join the lines with a space? if (trailingBreaks.isEmpty) buffer.writeCharCode(SP); } else { buffer.write(leadingBreak); } leadingBreak = ''; // Append the remaining line breaks. buffer.write(trailingBreaks); // Is there leading whitespace? leadingBlank = _isBlank; var startPosition = _scanner.position; while (!_isBreakOrEnd) { _scanner.readChar(); } buffer.write(_scanner.substring(startPosition)); end = _scanner.state; // libyaml always reads a line here, but this breaks on block scalars at // the end of the document that end without newlines. See example 8.1: // http://yaml.org/spec/1.2/spec.html#id2793888. if (!_scanner.isDone) leadingBreak = _readLine(); // Eat the following indentation and spaces. var pair = _scanBlockScalarBreaks(indent); indent = pair.first; trailingBreaks = pair.last; } // Chomp the tail. if (chomping != _Chomping.strip) buffer.write(leadingBreak); if (chomping == _Chomping.keep) buffer.write(trailingBreaks); return ScalarToken(_scanner.spanFrom(start, end), buffer.toString(), literal ? ScalarStyle.LITERAL : ScalarStyle.FOLDED); } /// Scans indentation spaces and line breaks for a block scalar. /// /// Determines the intendation level if needed. Returns the new indentation /// level and the text of the line breaks. Pair<int, String> _scanBlockScalarBreaks(int indent) { var maxIndent = 0; var breaks = StringBuffer(); while (true) { while ((indent == 0 || _scanner.column < indent) && _scanner.peekChar() == SP) { _scanner.readChar(); } if (_scanner.column > maxIndent) maxIndent = _scanner.column; // libyaml throws an error here if a tab character is detected, but the // spec treats tabs like any other non-space character. See example 8.2: // http://yaml.org/spec/1.2/spec.html#id2794311. if (!_isBreak) break; breaks.write(_readLine()); } if (indent == 0) { indent = maxIndent; if (indent < _indent + 1) indent = _indent + 1; // libyaml forces indent to be at least 1 here, but that doesn't seem to // be supported by the spec. } return Pair(indent, breaks.toString()); } // Scans a quoted scalar. Token _scanFlowScalar({bool singleQuote = false}) { var start = _scanner.state; var buffer = StringBuffer(); // Eat the left quote. _scanner.readChar(); while (true) { // Check that there are no document indicators at the beginning of the // line. if (_isDocumentIndicator) { _scanner.error('Unexpected document indicator.'); } if (_scanner.isDone) { throw YamlException('Unexpected end of file.', _scanner.emptySpan); } var leadingBlanks = false; while (!_isBlankOrEnd) { var char = _scanner.peekChar(); if (singleQuote && char == SINGLE_QUOTE && _scanner.peekChar(1) == SINGLE_QUOTE) { // An escaped single quote. _scanner.readChar(); _scanner.readChar(); buffer.writeCharCode(SINGLE_QUOTE); } else if (char == (singleQuote ? SINGLE_QUOTE : DOUBLE_QUOTE)) { // The closing quote. break; } else if (!singleQuote && char == BACKSLASH && _isBreakAt(1)) { // An escaped newline. _scanner.readChar(); _skipLine(); leadingBlanks = true; break; } else if (!singleQuote && char == BACKSLASH) { var escapeStart = _scanner.state; // An escape sequence. int codeLength; switch (_scanner.peekChar(1)) { case NUMBER_0: buffer.writeCharCode(NULL); break; case LETTER_A: buffer.writeCharCode(BELL); break; case LETTER_B: buffer.writeCharCode(BACKSPACE); break; case LETTER_T: case TAB: buffer.writeCharCode(TAB); break; case LETTER_N: buffer.writeCharCode(LF); break; case LETTER_V: buffer.writeCharCode(VERTICAL_TAB); break; case LETTER_F: buffer.writeCharCode(FORM_FEED); break; case LETTER_R: buffer.writeCharCode(CR); break; case LETTER_E: buffer.writeCharCode(ESCAPE); break; case SP: case DOUBLE_QUOTE: case SLASH: case BACKSLASH: // libyaml doesn't support an escaped forward slash, but it was // added in YAML 1.2. See section 5.7: // http://yaml.org/spec/1.2/spec.html#id2776092 buffer.writeCharCode(_scanner.peekChar(1)); break; case LETTER_CAP_N: buffer.writeCharCode(NEL); break; case UNDERSCORE: buffer.writeCharCode(NBSP); break; case LETTER_CAP_L: buffer.writeCharCode(LINE_SEPARATOR); break; case LETTER_CAP_P: buffer.writeCharCode(PARAGRAPH_SEPARATOR); break; case LETTER_X: codeLength = 2; break; case LETTER_U: codeLength = 4; break; case LETTER_CAP_U: codeLength = 8; break; default: throw YamlException( 'Unknown escape character.', _scanner.spanFrom(escapeStart)); } _scanner.readChar(); _scanner.readChar(); if (codeLength != null) { var value = 0; for (var i = 0; i < codeLength; i++) { if (!_isHex) { _scanner.readChar(); throw YamlException( 'Expected $codeLength-digit hexidecimal number.', _scanner.spanFrom(escapeStart)); } value = (value << 4) + _asHex(_scanner.readChar()); } // Check the value and write the character. if ((value >= 0xD800 && value <= 0xDFFF) || value > 0x10FFFF) { throw YamlException('Invalid Unicode character escape code.', _scanner.spanFrom(escapeStart)); } buffer.writeCharCode(value); } } else { buffer.writeCharCode(_scanner.readChar()); } } // Check if we're at the end of a scalar. if (_scanner.peekChar() == (singleQuote ? SINGLE_QUOTE : DOUBLE_QUOTE)) { break; } var whitespace = StringBuffer(); var leadingBreak = ''; var trailingBreaks = StringBuffer(); while (_isBlank || _isBreak) { if (_isBlank) { // Consume a space or a tab. if (!leadingBlanks) { whitespace.writeCharCode(_scanner.readChar()); } else { _scanner.readChar(); } } else { // Check if it's a first line break. if (!leadingBlanks) { whitespace.clear(); leadingBreak = _readLine(); leadingBlanks = true; } else { trailingBreaks.write(_readLine()); } } } // Join the whitespace or fold line breaks. if (leadingBlanks) { if (leadingBreak.isNotEmpty && trailingBreaks.isEmpty) { buffer.writeCharCode(SP); } else { buffer.write(trailingBreaks); } } else { buffer.write(whitespace); whitespace.clear(); } } // Eat the right quote. _scanner.readChar(); return ScalarToken(_scanner.spanFrom(start), buffer.toString(), singleQuote ? ScalarStyle.SINGLE_QUOTED : ScalarStyle.DOUBLE_QUOTED); } /// Scans a plain scalar. Token _scanPlainScalar() { var start = _scanner.state; var end = _scanner.state; var buffer = StringBuffer(); var leadingBreak = ''; var trailingBreaks = ''; var whitespace = StringBuffer(); var indent = _indent + 1; while (true) { // Check for a document indicator. if (_isDocumentIndicator) break; // Check for a comment. if (_scanner.peekChar() == HASH) break; if (_isPlainChar) { // Join the whitespace or fold line breaks. if (leadingBreak.isNotEmpty) { if (trailingBreaks.isEmpty) { buffer.writeCharCode(SP); } else { buffer.write(trailingBreaks); } leadingBreak = ''; trailingBreaks = ''; } else { buffer.write(whitespace); whitespace.clear(); } } // libyaml's notion of valid identifiers differs substantially from YAML // 1.2's. We use [_isPlainChar] instead of libyaml's character here. var startPosition = _scanner.position; while (_isPlainChar) { _scanner.readChar(); } buffer.write(_scanner.substring(startPosition)); end = _scanner.state; // Is it the end? if (!_isBlank && !_isBreak) break; while (_isBlank || _isBreak) { if (_isBlank) { // Check for a tab character messing up the intendation. if (leadingBreak.isNotEmpty && _scanner.column < indent && _scanner.peekChar() == TAB) { _scanner.error('Expected a space but found a tab.', length: 1); } if (leadingBreak.isEmpty) { whitespace.writeCharCode(_scanner.readChar()); } else { _scanner.readChar(); } } else { // Check if it's a first line break. if (leadingBreak.isEmpty) { leadingBreak = _readLine(); whitespace.clear(); } else { trailingBreaks = _readLine(); } } } // Check the indentation level. if (_inBlockContext && _scanner.column < indent) break; } // Allow a simple key after a plain scalar with leading blanks. if (leadingBreak.isNotEmpty) _simpleKeyAllowed = true; return ScalarToken( _scanner.spanFrom(start, end), buffer.toString(), ScalarStyle.PLAIN); } /// Moves past the current line break, if there is one. void _skipLine() { var char = _scanner.peekChar(); if (char != CR && char != LF) return; _scanner.readChar(); if (char == CR && _scanner.peekChar() == LF) _scanner.readChar(); } // Moves past the current line break and returns a newline. String _readLine() { var char = _scanner.peekChar(); // libyaml supports NEL, PS, and LS characters as line separators, but this // is explicitly forbidden in section 5.4 of the YAML spec. if (char != CR && char != LF) { throw YamlException('Expected newline.', _scanner.emptySpan); } _scanner.readChar(); // CR LF | CR | LF -> LF if (char == CR && _scanner.peekChar() == LF) _scanner.readChar(); return '\n'; } // Returns whether the character at [offset] is whitespace. bool _isBlankAt(int offset) { var char = _scanner.peekChar(offset); return char == SP || char == TAB; } // Returns whether the character at [offset] is a line break. bool _isBreakAt(int offset) { // Libyaml considers NEL, LS, and PS to be line breaks as well, but that's // contrary to the spec. var char = _scanner.peekChar(offset); return char == CR || char == LF; } // Returns whether the character at [offset] is whitespace or past the end of // the source. bool _isBlankOrEndAt(int offset) { var char = _scanner.peekChar(offset); return char == null || char == SP || char == TAB || char == CR || char == LF; } /// Returns whether the character at [offset] is a plain character. /// /// See http://yaml.org/spec/1.2/spec.html#ns-plain-char(c). bool _isPlainCharAt(int offset) { switch (_scanner.peekChar(offset)) { case COLON: return _isPlainSafeAt(offset + 1); case HASH: var previous = _scanner.peekChar(offset - 1); return previous != SP && previous != TAB; default: return _isPlainSafeAt(offset); } } /// Returns whether the character at [offset] is a plain-safe character. /// /// See http://yaml.org/spec/1.2/spec.html#ns-plain-safe(c). bool _isPlainSafeAt(int offset) { var char = _scanner.peekChar(offset); switch (char) { case COMMA: case LEFT_SQUARE: case RIGHT_SQUARE: case LEFT_CURLY: case RIGHT_CURLY: // These characters are delimiters in a flow context and thus are only // safe in a block context. return _inBlockContext; case SP: case TAB: case LF: case CR: case BOM: return false; case NEL: return true; default: return char != null && ((char >= 0x00020 && char <= 0x00007E) || (char >= 0x000A0 && char <= 0x00D7FF) || (char >= 0x0E000 && char <= 0x00FFFD) || (char >= 0x10000 && char <= 0x10FFFF)); } } /// Returns the hexidecimal value of [char]. int _asHex(int char) { if (char <= NUMBER_9) return char - NUMBER_0; if (char <= LETTER_CAP_F) return 10 + char - LETTER_CAP_A; return 10 + char - LETTER_A; } /// Moves the scanner past any blank characters. void _skipBlanks() { while (_isBlank) { _scanner.readChar(); } } /// Moves the scanner past a comment, if one starts at the current position. void _skipComment() { if (_scanner.peekChar() != HASH) return; while (!_isBreakOrEnd) { _scanner.readChar(); } } } /// A record of the location of a potential simple key. class _SimpleKey { /// The index of the token that begins the simple key. /// /// This is the index relative to all tokens emitted, rather than relative to /// [_tokens]. final int tokenNumber; /// The source location of the beginning of the simple key. /// /// This is used for error reporting and for determining when a simple key is /// no longer on the current line. final SourceLocation location; /// The line on which the key appears. /// /// We could get this from [location], but that requires a binary search /// whereas this is O(1). final int line; /// The column on which the key appears. /// /// We could get this from [location], but that requires a binary search /// whereas this is O(1). final int column; /// Whether this key must exist for the document to be scanned. final bool required; _SimpleKey(this.tokenNumber, this.line, this.column, this.location, {bool required}) : required = required; } /// The ways to handle trailing whitespace for a block scalar. /// /// See http://yaml.org/spec/1.2/spec.html#id2794534. enum _Chomping { /// All trailing whitespace is discarded. strip, /// A single trailing newline is retained. clip, /// All trailing whitespace is preserved. keep }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml/src/yaml_node.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 'dart:collection' as collection; import 'package:collection/collection.dart'; import 'package:source_span/source_span.dart'; import 'event.dart'; import 'null_span.dart'; import 'style.dart'; import 'yaml_node_wrapper.dart'; /// An interface for parsed nodes from a YAML source tree. /// /// [YamlMap]s and [YamlList]s implement this interface in addition to the /// normal [Map] and [List] interfaces, so any maps and lists will be /// [YamlNode]s regardless of how they're accessed. /// /// Scalars values like strings and numbers, on the other hand, don't have this /// interface by default. Instead, they can be accessed as [YamlScalar]s via /// [YamlMap.nodes] or [YamlList.nodes]. abstract class YamlNode { /// The source span for this node. /// /// [SourceSpan.message] can be used to produce a human-friendly message about /// this node. SourceSpan get span => _span; SourceSpan _span; /// The inner value of this node. /// /// For [YamlScalar]s, this will return the wrapped value. For [YamlMap] and /// [YamlList], it will return [this], since they already implement [Map] and /// [List], respectively. dynamic get value; } /// A read-only [Map] parsed from YAML. class YamlMap extends YamlNode with collection.MapMixin, UnmodifiableMapMixin { /// A view of [this] where the keys and values are guaranteed to be /// [YamlNode]s. /// /// The key type is `dynamic` to allow values to be accessed using /// non-[YamlNode] keys, but [Map.keys] and [Map.forEach] will always expose /// them as [YamlNode]s. For example, for `{"foo": [1, 2, 3]}` [nodes] will be /// a map from a [YamlScalar] to a [YamlList], but since the key type is /// `dynamic` `map.nodes["foo"]` will still work. final Map<dynamic, YamlNode> nodes; /// The style used for the map in the original document. final CollectionStyle style; @override Map get value => this; @override Iterable get keys => nodes.keys.map((node) => node.value); /// Creates an empty YamlMap. /// /// This map's [span] won't have useful location information. However, it will /// have a reasonable implementation of [SourceSpan.message]. If [sourceUrl] /// is passed, it's used as the [SourceSpan.sourceUrl]. /// /// [sourceUrl] may be either a [String], a [Uri], or `null`. factory YamlMap({sourceUrl}) => YamlMapWrapper(const {}, sourceUrl); /// Wraps a Dart map so that it can be accessed (recursively) like a /// [YamlMap]. /// /// Any [SourceSpan]s returned by this map or its children will be dummies /// without useful location information. However, they will have a reasonable /// implementation of [SourceSpan.getLocationMessage]. If [sourceUrl] is /// passed, it's used as the [SourceSpan.sourceUrl]. /// /// [sourceUrl] may be either a [String], a [Uri], or `null`. factory YamlMap.wrap(Map dartMap, {sourceUrl}) => YamlMapWrapper(dartMap, sourceUrl); /// Users of the library should not use this constructor. YamlMap.internal(Map<dynamic, YamlNode> nodes, SourceSpan span, this.style) : nodes = UnmodifiableMapView<dynamic, YamlNode>(nodes) { _span = span; } @override dynamic operator [](key) => nodes[key]?.value; } // TODO(nweiz): Use UnmodifiableListMixin when issue 18970 is fixed. /// A read-only [List] parsed from YAML. class YamlList extends YamlNode with collection.ListMixin { final List<YamlNode> nodes; /// The style used for the list in the original document. final CollectionStyle style; @override List get value => this; @override int get length => nodes.length; @override set length(int index) { throw UnsupportedError('Cannot modify an unmodifiable List'); } /// Creates an empty YamlList. /// /// This list's [span] won't have useful location information. However, it /// will have a reasonable implementation of [SourceSpan.message]. If /// [sourceUrl] is passed, it's used as the [SourceSpan.sourceUrl]. /// /// [sourceUrl] may be either a [String], a [Uri], or `null`. factory YamlList({sourceUrl}) => YamlListWrapper(const [], sourceUrl); /// Wraps a Dart list so that it can be accessed (recursively) like a /// [YamlList]. /// /// Any [SourceSpan]s returned by this list or its children will be dummies /// without useful location information. However, they will have a reasonable /// implementation of [SourceSpan.getLocationMessage]. If [sourceUrl] is /// passed, it's used as the [SourceSpan.sourceUrl]. /// /// [sourceUrl] may be either a [String], a [Uri], or `null`. factory YamlList.wrap(List dartList, {sourceUrl}) => YamlListWrapper(dartList, sourceUrl); /// Users of the library should not use this constructor. YamlList.internal(List<YamlNode> nodes, SourceSpan span, this.style) : nodes = UnmodifiableListView<YamlNode>(nodes) { _span = span; } @override dynamic operator [](int index) => nodes[index].value; @override operator []=(int index, value) { throw UnsupportedError('Cannot modify an unmodifiable List'); } } /// A wrapped scalar value parsed from YAML. class YamlScalar extends YamlNode { @override final dynamic value; /// The style used for the scalar in the original document. final ScalarStyle style; /// Wraps a Dart value in a [YamlScalar]. /// /// This scalar's [span] won't have useful location information. However, it /// will have a reasonable implementation of [SourceSpan.message]. If /// [sourceUrl] is passed, it's used as the [SourceSpan.sourceUrl]. /// /// [sourceUrl] may be either a [String], a [Uri], or `null`. YamlScalar.wrap(this.value, {sourceUrl}) : style = ScalarStyle.ANY { _span = NullSpan(sourceUrl); } /// Users of the library should not use this constructor. YamlScalar.internal(this.value, ScalarEvent scalar) : style = scalar.style { _span = scalar.span; } /// Users of the library should not use this constructor. YamlScalar.internalWithSpan(this.value, SourceSpan span) : style = ScalarStyle.ANY { _span = span; } @override String toString() => value.toString(); } /// Sets the source span of a [YamlNode]. /// /// This method is not exposed publicly. void setSpan(YamlNode node, SourceSpan span) { node._span = span; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml/src/equality.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 'package:collection/collection.dart'; import 'yaml_node.dart'; /// Returns a [Map] that compares its keys based on [deepEquals]. Map<K, V> deepEqualsMap<K, V>() => LinkedHashMap(equals: deepEquals, hashCode: deepHashCode); /// Returns whether two objects are structurally equivalent. /// /// This considers `NaN` values to be equivalent, handles self-referential /// structures, and considers [YamlScalar]s to be equal to their values. bool deepEquals(obj1, obj2) => _DeepEquals().equals(obj1, obj2); /// A class that provides access to the list of parent objects used for loop /// detection. class _DeepEquals { final _parents1 = []; final _parents2 = []; /// Returns whether [obj1] and [obj2] are structurally equivalent. bool equals(obj1, obj2) { if (obj1 is YamlScalar) obj1 = obj1.value; if (obj2 is YamlScalar) obj2 = obj2.value; // _parents1 and _parents2 are guaranteed to be the same size. for (var i = 0; i < _parents1.length; i++) { var loop1 = identical(obj1, _parents1[i]); var loop2 = identical(obj2, _parents2[i]); // If both structures loop in the same place, they're equal at that point // in the structure. If one loops and the other doesn't, they're not // equal. if (loop1 && loop2) return true; if (loop1 || loop2) return false; } _parents1.add(obj1); _parents2.add(obj2); try { if (obj1 is List && obj2 is List) { return _listEquals(obj1, obj2); } else if (obj1 is Map && obj2 is Map) { return _mapEquals(obj1, obj2); } else if (obj1 is num && obj2 is num) { return _numEquals(obj1, obj2); } else { return obj1 == obj2; } } finally { _parents1.removeLast(); _parents2.removeLast(); } } /// Returns whether [list1] and [list2] are structurally equal. bool _listEquals(List list1, List list2) { if (list1.length != list2.length) return false; for (var i = 0; i < list1.length; i++) { if (!equals(list1[i], list2[i])) return false; } return true; } /// Returns whether [map1] and [map2] are structurally equal. bool _mapEquals(Map map1, Map map2) { if (map1.length != map2.length) return false; for (var key in map1.keys) { if (!map2.containsKey(key)) return false; if (!equals(map1[key], map2[key])) return false; } return true; } /// Returns whether two numbers are equivalent. /// /// This differs from `n1 == n2` in that it considers `NaN` to be equal to /// itself. bool _numEquals(num n1, num n2) { if (n1.isNaN && n2.isNaN) return true; return n1 == n2; } } /// Returns a hash code for [obj] such that structurally equivalent objects /// will have the same hash code. /// /// This supports deep equality for maps and lists, including those with /// self-referential structures, and returns the same hash code for /// [YamlScalar]s and their values. int deepHashCode(obj) { var parents = []; int _deepHashCode(value) { if (parents.any((parent) => identical(parent, value))) return -1; parents.add(value); try { if (value is Map) { var equality = const UnorderedIterableEquality(); return equality.hash(value.keys.map(_deepHashCode)) ^ equality.hash(value.values.map(_deepHashCode)); } else if (value is Iterable) { return const IterableEquality().hash(value.map(deepHashCode)); } else if (value is YamlScalar) { return value.value.hashCode; } else { return value.hashCode; } } finally { parents.removeLast(); } } return _deepHashCode(obj); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml/src/loader.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:charcode/ascii.dart'; import 'package:source_span/source_span.dart'; import 'equality.dart'; import 'event.dart'; import 'parser.dart'; import 'yaml_document.dart'; import 'yaml_exception.dart'; import 'yaml_node.dart'; /// A loader that reads [Event]s emitted by a [Parser] and emits /// [YamlDocument]s. /// /// This is based on the libyaml loader, available at /// https://github.com/yaml/libyaml/blob/master/src/loader.c. The license for /// that is available in ../../libyaml-license.txt. class Loader { /// The underlying [Parser] that generates [Event]s. final Parser _parser; /// Aliases by the alias name. final _aliases = <String, YamlNode>{}; /// The span of the entire stream emitted so far. FileSpan get span => _span; FileSpan _span; /// Creates a loader that loads [source]. /// /// [sourceUrl] can be a String or a [Uri]. Loader(String source, {sourceUrl}) : _parser = Parser(source, sourceUrl: sourceUrl) { var event = _parser.parse(); _span = event.span; assert(event.type == EventType.streamStart); } /// Loads the next document from the stream. /// /// If there are no more documents, returns `null`. YamlDocument load() { if (_parser.isDone) return null; var event = _parser.parse(); if (event.type == EventType.streamEnd) { _span = _span.expand(event.span); return null; } var document = _loadDocument(event as DocumentStartEvent); _span = _span.expand(document.span as FileSpan); _aliases.clear(); return document; } /// Composes a document object. YamlDocument _loadDocument(DocumentStartEvent firstEvent) { var contents = _loadNode(_parser.parse()); var lastEvent = _parser.parse() as DocumentEndEvent; assert(lastEvent.type == EventType.documentEnd); return YamlDocument.internal( contents, firstEvent.span.expand(lastEvent.span), firstEvent.versionDirective, firstEvent.tagDirectives, startImplicit: firstEvent.isImplicit, endImplicit: lastEvent.isImplicit); } /// Composes a node. YamlNode _loadNode(Event firstEvent) { switch (firstEvent.type) { case EventType.alias: return _loadAlias(firstEvent as AliasEvent); case EventType.scalar: return _loadScalar(firstEvent as ScalarEvent); case EventType.sequenceStart: return _loadSequence(firstEvent as SequenceStartEvent); case EventType.mappingStart: return _loadMapping(firstEvent as MappingStartEvent); default: throw 'Unreachable'; } } /// Registers an anchor. void _registerAnchor(String anchor, YamlNode node) { if (anchor == null) return; // libyaml throws an error for duplicate anchors, but example 7.1 makes it // clear that they should be overridden: // http://yaml.org/spec/1.2/spec.html#id2786448. _aliases[anchor] = node; } /// Composes a node corresponding to an alias. YamlNode _loadAlias(AliasEvent event) { var alias = _aliases[event.name]; if (alias != null) return alias; throw YamlException('Undefined alias.', event.span); } /// Composes a scalar node. YamlNode _loadScalar(ScalarEvent scalar) { YamlNode node; if (scalar.tag == '!') { node = YamlScalar.internal(scalar.value, scalar); } else if (scalar.tag != null) { node = _parseByTag(scalar); } else { node = _parseScalar(scalar); } _registerAnchor(scalar.anchor, node); return node; } /// Composes a sequence node. YamlNode _loadSequence(SequenceStartEvent firstEvent) { if (firstEvent.tag != '!' && firstEvent.tag != null && firstEvent.tag != 'tag:yaml.org,2002:seq') { throw YamlException('Invalid tag for sequence.', firstEvent.span); } var children = <YamlNode>[]; var node = YamlList.internal(children, firstEvent.span, firstEvent.style); _registerAnchor(firstEvent.anchor, node); var event = _parser.parse(); while (event.type != EventType.sequenceEnd) { children.add(_loadNode(event)); event = _parser.parse(); } setSpan(node, firstEvent.span.expand(event.span)); return node; } /// Composes a mapping node. YamlNode _loadMapping(MappingStartEvent firstEvent) { if (firstEvent.tag != '!' && firstEvent.tag != null && firstEvent.tag != 'tag:yaml.org,2002:map') { throw YamlException('Invalid tag for mapping.', firstEvent.span); } var children = deepEqualsMap<dynamic, YamlNode>(); var node = YamlMap.internal(children, firstEvent.span, firstEvent.style); _registerAnchor(firstEvent.anchor, node); var event = _parser.parse(); while (event.type != EventType.mappingEnd) { var key = _loadNode(event); var value = _loadNode(_parser.parse()); if (children.containsKey(key)) { throw YamlException('Duplicate mapping key.', key.span); } children[key] = value; event = _parser.parse(); } setSpan(node, firstEvent.span.expand(event.span)); return node; } /// Parses a scalar according to its tag name. YamlScalar _parseByTag(ScalarEvent scalar) { switch (scalar.tag) { case 'tag:yaml.org,2002:null': var result = _parseNull(scalar); if (result != null) return result; throw YamlException('Invalid null scalar.', scalar.span); case 'tag:yaml.org,2002:bool': var result = _parseBool(scalar); if (result != null) return result; throw YamlException('Invalid bool scalar.', scalar.span); case 'tag:yaml.org,2002:int': var result = _parseNumber(scalar, allowFloat: false); if (result != null) return result; throw YamlException('Invalid int scalar.', scalar.span); case 'tag:yaml.org,2002:float': var result = _parseNumber(scalar, allowInt: false); if (result != null) return result; throw YamlException('Invalid float scalar.', scalar.span); case 'tag:yaml.org,2002:str': return YamlScalar.internal(scalar.value, scalar); default: throw YamlException('Undefined tag: ${scalar.tag}.', scalar.span); } } /// Parses [scalar], which may be one of several types. YamlScalar _parseScalar(ScalarEvent scalar) => _tryParseScalar(scalar) ?? YamlScalar.internal(scalar.value, scalar); /// Tries to parse [scalar]. /// /// If parsing fails, this returns `null`, indicating that the scalar should /// be parsed as a string. YamlScalar _tryParseScalar(ScalarEvent scalar) { // Quickly check for the empty string, which means null. var length = scalar.value.length; if (length == 0) return YamlScalar.internal(null, scalar); // Dispatch on the first character. var firstChar = scalar.value.codeUnitAt(0); switch (firstChar) { case $dot: case $plus: case $minus: return _parseNumber(scalar); case $n: case $N: return length == 4 ? _parseNull(scalar) : null; case $t: case $T: return length == 4 ? _parseBool(scalar) : null; case $f: case $F: return length == 5 ? _parseBool(scalar) : null; case $tilde: return length == 1 ? YamlScalar.internal(null, scalar) : null; default: if (firstChar >= $0 && firstChar <= $9) return _parseNumber(scalar); return null; } } /// Parse a null scalar. /// /// Returns a Dart `null` if parsing fails. YamlScalar _parseNull(ScalarEvent scalar) { switch (scalar.value) { case '': case 'null': case 'Null': case 'NULL': case '~': return YamlScalar.internal(null, scalar); default: return null; } } /// Parse a boolean scalar. /// /// Returns `null` if parsing fails. YamlScalar _parseBool(ScalarEvent scalar) { switch (scalar.value) { case 'true': case 'True': case 'TRUE': return YamlScalar.internal(true, scalar); case 'false': case 'False': case 'FALSE': return YamlScalar.internal(false, scalar); default: return null; } } /// Parses a numeric scalar. /// /// Returns `null` if parsing fails. YamlScalar _parseNumber(ScalarEvent scalar, {bool allowInt = true, bool allowFloat = true}) { var value = _parseNumberValue(scalar.value, allowInt: allowInt, allowFloat: allowFloat); return value == null ? null : YamlScalar.internal(value, scalar); } /// Parses the value of a number. /// /// Returns the number if it's parsed successfully, or `null` if it's not. num _parseNumberValue(String contents, {bool allowInt = true, bool allowFloat = true}) { assert(allowInt || allowFloat); var firstChar = contents.codeUnitAt(0); var length = contents.length; // Quick check for single digit integers. if (allowInt && length == 1) { var value = firstChar - $0; return value >= 0 && value <= 9 ? value : null; } var secondChar = contents.codeUnitAt(1); // Hexadecimal or octal integers. if (allowInt && firstChar == $0) { // int.tryParse supports 0x natively. if (secondChar == $x) return int.tryParse(contents); if (secondChar == $o) { var afterRadix = contents.substring(2); return int.tryParse(afterRadix, radix: 8); } } // Int or float starting with a digit or a +/- sign. if ((firstChar >= $0 && firstChar <= $9) || ((firstChar == $plus || firstChar == $minus) && secondChar >= $0 && secondChar <= $9)) { // Try to parse an int or, failing that, a double. num result; if (allowInt) { // Pass "radix: 10" explicitly to ensure that "-0x10", which is valid // Dart but invalid YAML, doesn't get parsed. result = int.tryParse(contents, radix: 10); } if (allowFloat) result ??= double.tryParse(contents); return result; } if (!allowFloat) return null; // Now the only possibility is to parse a float starting with a dot or a // sign and a dot, or the signed/unsigned infinity values and not-a-numbers. if ((firstChar == $dot && secondChar >= $0 && secondChar <= $9) || (firstChar == $minus || firstChar == $plus) && secondChar == $dot) { // Starting with a . and a number or a sign followed by a dot. if (length == 5) { switch (contents) { case '+.inf': case '+.Inf': case '+.INF': return double.infinity; case '-.inf': case '-.Inf': case '-.INF': return -double.infinity; } } return double.tryParse(contents); } if (length == 4 && firstChar == $dot) { switch (contents) { case '.inf': case '.Inf': case '.INF': return double.infinity; case '.nan': case '.NaN': case '.NAN': return double.nan; } } return null; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml/src/token.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:source_span/source_span.dart'; import 'style.dart'; /// A token emitted by a [Scanner]. class Token { final TokenType type; final FileSpan span; Token(this.type, this.span); @override String toString() => type.toString(); } /// A token representing a `%YAML` directive. class VersionDirectiveToken implements Token { @override TokenType get type => TokenType.versionDirective; @override final FileSpan span; /// The declared major version of the document. final int major; /// The declared minor version of the document. final int minor; VersionDirectiveToken(this.span, this.major, this.minor); @override String toString() => 'VERSION_DIRECTIVE $major.$minor'; } /// A token representing a `%TAG` directive. class TagDirectiveToken implements Token { @override TokenType get type => TokenType.tagDirective; @override final FileSpan span; /// The tag handle used in the document. final String handle; /// The tag prefix that the handle maps to. final String prefix; TagDirectiveToken(this.span, this.handle, this.prefix); @override String toString() => 'TAG_DIRECTIVE $handle $prefix'; } /// A token representing an anchor (`&foo`). class AnchorToken implements Token { @override TokenType get type => TokenType.anchor; @override final FileSpan span; final String name; AnchorToken(this.span, this.name); @override String toString() => 'ANCHOR $name'; } /// A token representing an alias (`*foo`). class AliasToken implements Token { @override TokenType get type => TokenType.alias; @override final FileSpan span; final String name; AliasToken(this.span, this.name); @override String toString() => 'ALIAS $name'; } /// A token representing a tag (`!foo`). class TagToken implements Token { @override TokenType get type => TokenType.tag; @override final FileSpan span; /// The tag handle for named tags. final String handle; /// The tag suffix, or `null`. final String suffix; TagToken(this.span, this.handle, this.suffix); @override String toString() => 'TAG $handle $suffix'; } /// A scalar value. class ScalarToken implements Token { @override TokenType get type => TokenType.scalar; @override final FileSpan span; /// The unparsed contents of the value.. final String value; /// The style of the scalar in the original source. final ScalarStyle style; ScalarToken(this.span, this.value, this.style); @override String toString() => 'SCALAR $style "$value"'; } /// The types of [Token] objects. enum TokenType { streamStart, streamEnd, versionDirective, tagDirective, documentStart, documentEnd, blockSequenceStart, blockMappingStart, blockEnd, flowSequenceStart, flowSequenceEnd, flowMappingStart, flowMappingEnd, blockEntry, flowEntry, key, value, alias, anchor, tag, scalar }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml/src/yaml_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. import 'package:source_span/source_span.dart'; /// An error thrown by the YAML processor. class YamlException extends SourceSpanFormatException { YamlException(String message, SourceSpan span) : super(message, span); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml/src/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. import 'package:source_span/source_span.dart'; /// A pair of values. class Pair<E, F> { final E first; final F last; Pair(this.first, this.last); @override String toString() => '($first, $last)'; } /// Print a warning. /// /// If [span] is passed, associates the warning with that span. void warn(String message, [SourceSpan span]) => yamlWarningCallback(message, span); /// A callback for emitting a warning. /// /// [message] is the text of the warning. If [span] is passed, it's the portion /// of the document that the warning is associated with and should be included /// in the printed warning. typedef YamlWarningCallback = Function(String message, [SourceSpan span]); /// A callback for emitting a warning. /// /// In a very few cases, the YAML spec indicates that an implementation should /// emit a warning. To do so, it calls this callback. The default implementation /// prints a message using [print]. YamlWarningCallback yamlWarningCallback = (message, [span]) { // TODO(nweiz): Print to stderr with color when issue 6943 is fixed and // dart:io is available. if (span != null) message = span.message(message); print(message); };
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/yaml/src/yaml_node_wrapper.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 'package:collection/collection.dart' as pkg_collection; import 'package:source_span/source_span.dart'; import 'null_span.dart'; import 'style.dart'; import 'yaml_node.dart'; /// A wrapper that makes a normal Dart map behave like a [YamlMap]. class YamlMapWrapper extends MapBase with pkg_collection.UnmodifiableMapMixin implements YamlMap { @override final style = CollectionStyle.ANY; final Map _dartMap; @override final SourceSpan span; @override final Map<dynamic, YamlNode> nodes; @override Map get value => this; @override Iterable get keys => _dartMap.keys; YamlMapWrapper(Map dartMap, sourceUrl) : this._(dartMap, NullSpan(sourceUrl)); YamlMapWrapper._(Map dartMap, SourceSpan span) : _dartMap = dartMap, span = span, nodes = _YamlMapNodes(dartMap, span); @override dynamic operator [](Object key) { var value = _dartMap[key]; if (value is Map) return YamlMapWrapper._(value, span); if (value is List) return YamlListWrapper._(value, span); return value; } @override int get hashCode => _dartMap.hashCode; @override bool operator ==(Object other) => other is YamlMapWrapper && other._dartMap == _dartMap; } /// The implementation of [YamlMapWrapper.nodes] as a wrapper around the Dart /// map. class _YamlMapNodes extends MapBase<dynamic, YamlNode> with pkg_collection.UnmodifiableMapMixin<dynamic, YamlNode> { final Map _dartMap; final SourceSpan _span; @override Iterable get keys => _dartMap.keys.map((key) => YamlScalar.internalWithSpan(key, _span)); _YamlMapNodes(this._dartMap, this._span); @override YamlNode operator [](Object key) { // Use "as" here because key being assigned to invalidates type propagation. if (key is YamlScalar) key = (key as YamlScalar).value; if (!_dartMap.containsKey(key)) return null; return _nodeForValue(_dartMap[key], _span); } @override int get hashCode => _dartMap.hashCode; @override bool operator ==(Object other) => other is _YamlMapNodes && other._dartMap == _dartMap; } // TODO(nweiz): Use UnmodifiableListMixin when issue 18970 is fixed. /// A wrapper that makes a normal Dart list behave like a [YamlList]. class YamlListWrapper extends ListBase implements YamlList { @override final style = CollectionStyle.ANY; final List _dartList; @override final SourceSpan span; @override final List<YamlNode> nodes; @override List get value => this; @override int get length => _dartList.length; @override set length(int index) { throw UnsupportedError('Cannot modify an unmodifiable List.'); } YamlListWrapper(List dartList, sourceUrl) : this._(dartList, NullSpan(sourceUrl)); YamlListWrapper._(List dartList, SourceSpan span) : _dartList = dartList, span = span, nodes = _YamlListNodes(dartList, span); @override dynamic operator [](int index) { var value = _dartList[index]; if (value is Map) return YamlMapWrapper._(value, span); if (value is List) return YamlListWrapper._(value, span); return value; } @override operator []=(int index, value) { throw UnsupportedError('Cannot modify an unmodifiable List.'); } @override int get hashCode => _dartList.hashCode; @override bool operator ==(Object other) => other is YamlListWrapper && other._dartList == _dartList; } // TODO(nweiz): Use UnmodifiableListMixin when issue 18970 is fixed. /// The implementation of [YamlListWrapper.nodes] as a wrapper around the Dart /// list. class _YamlListNodes extends ListBase<YamlNode> { final List _dartList; final SourceSpan _span; @override int get length => _dartList.length; @override set length(int index) { throw UnsupportedError('Cannot modify an unmodifiable List.'); } _YamlListNodes(this._dartList, this._span); @override YamlNode operator [](int index) => _nodeForValue(_dartList[index], _span); @override operator []=(int index, value) { throw UnsupportedError('Cannot modify an unmodifiable List.'); } @override int get hashCode => _dartList.hashCode; @override bool operator ==(Object other) => other is _YamlListNodes && other._dartList == _dartList; } YamlNode _nodeForValue(value, SourceSpan span) { if (value is Map) return YamlMapWrapper._(value, span); if (value is List) return YamlListWrapper._(value, span); return YamlScalar.internalWithSpan(value, span); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_node_compilers/builders.dart
// Copyright (c) 2017, 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:build/build.dart'; import 'package:build_modules/build_modules.dart'; import 'package:collection/collection.dart'; import 'package:path/path.dart' as p; import 'build_node_compilers.dart'; import 'src/common.dart'; import 'src/platforms.dart'; //import 'src/sdk_js_copy_builder.dart'; // Shared entrypoint builder Builder nodeEntrypointBuilder(BuilderOptions options) => NodeEntrypointBuilder.fromOptions(options); // Ddc related builders Builder ddcMetaModuleBuilder(BuilderOptions options) => MetaModuleBuilder.forOptions(ddcPlatform, options); Builder ddcMetaModuleCleanBuilder(_) => MetaModuleCleanBuilder(ddcPlatform); Builder ddcModuleBuilder([_]) => ModuleBuilder(ddcPlatform); Builder ddcBuilder(BuilderOptions options) => DevCompilerBuilder( useIncrementalCompiler: _readUseIncrementalCompilerOption(options), platform: ddcPlatform, ); const ddcKernelExtension = '.ddc_node.dill'; Builder ddcKernelBuilder(BuilderOptions options) => KernelBuilder( summaryOnly: true, sdkKernelPath: p.url.join('lib', '_internal', 'ddc_sdk.dill'), outputExtension: ddcKernelExtension, platform: ddcPlatform, kernelTargetName: 'ddc', // otherwise kernel_worker fails on unknown target useIncrementalCompiler: _readUseIncrementalCompilerOption(options)); //Builder sdkJsCopyBuilder(_) => SdkJsCopyBuilder(); PostProcessBuilder sdkJsCleanupBuilder(BuilderOptions options) => FileDeletingBuilder( ['lib/src/dev_compiler/dart_sdk.js', 'lib/src/dev_compiler/require.js'], isEnabled: options.config['enabled'] as bool ?? false); // Dart2js related builders Builder dart2jsMetaModuleBuilder(BuilderOptions options) => MetaModuleBuilder.forOptions(dart2jsPlatform, options); Builder dart2jsMetaModuleCleanBuilder(_) => MetaModuleCleanBuilder(dart2jsPlatform); Builder dart2jsModuleBuilder([_]) => ModuleBuilder(dart2jsPlatform); //PostProcessBuilder dart2jsArchiveExtractor(BuilderOptions options) => // Dart2JsArchiveExtractor.fromOptions(options); // General purpose builders PostProcessBuilder dartSourceCleanup(BuilderOptions options) => (options.config['enabled'] as bool ?? false) ? const FileDeletingBuilder(['.dart', '.js.map']) : const FileDeletingBuilder(['.dart', '.js.map'], isEnabled: false); /// Reads the [_useIncrementalCompilerOption] from [options]. /// /// Note that [options] must be consistent across the entire build, and if it is /// not then an [ArgumentError] will be thrown. bool _readUseIncrementalCompilerOption(BuilderOptions options) { if (_previousDdcConfig != null) { if (!const MapEquality().equals(_previousDdcConfig, options.config)) { throw ArgumentError( 'The build_node_compilers:ddc builder must have the same ' 'configuration in all packages. Saw $_previousDdcConfig and ' '${options.config} which are not equal.\n\n ' 'Please use the `global_options` section in ' '`build.yaml` or the `--define` flag to set global options.'); } } else { _previousDdcConfig = options.config; } validateOptions(options.config, [_useIncrementalCompilerOption], 'build_node_compilers:ddc'); return options.config[_useIncrementalCompilerOption] as bool ?? true; } Map<String, dynamic> _previousDdcConfig; const _useIncrementalCompilerOption = 'use-incremental-compiler';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_node_compilers/build_node_compilers.dart
// Copyright (c) 2018, Anatoly Pulyaevskiy. 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/dev_compiler_builder.dart' show DevCompilerBuilder, jsModuleErrorsExtension, jsModuleExtension, jsSourceMapExtension; export 'src/node_entrypoint_builder.dart' show WebCompiler, NodeEntrypointBuilder, ddcBootstrapExtension; export 'src/platforms.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_node_compilers
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_node_compilers/src/dev_compiler_builder.dart
// Copyright (c) 2018, Anatoly Pulyaevskiy. 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:convert'; import 'dart:io'; import 'package:bazel_worker/bazel_worker.dart'; import 'package:build/build.dart'; import 'package:build_modules/build_modules.dart'; import 'package:meta/meta.dart'; import 'package:path/path.dart' as p; import 'package:scratch_space/scratch_space.dart'; import '../builders.dart'; import 'common.dart'; import 'errors.dart'; const jsModuleErrorsExtension = '.ddc_node.js.errors'; const jsModuleExtension = '.ddc_node.js'; const jsSourceMapExtension = '.ddc_node.js.map'; /// A builder which can output ddc modules! class DevCompilerBuilder implements Builder { final bool useIncrementalCompiler; final DartPlatform platform; /// The sdk kernel file for the current platform. final String sdkKernelPath; /// The root directory of the platform's dart SDK. /// /// If not provided, defaults to the directory of /// [Platform.resolvedExecutable]. /// /// On flutter this is the path to the root of the flutter_patched_sdk /// directory, which contains the platform kernel files. final String platformSdk; /// The absolute path to the libraries file for the current platform. /// /// If not provided, defaults to "lib/libraries.json" in the sdk directory. final String librariesPath; DevCompilerBuilder( {bool useIncrementalCompiler, @required this.platform, this.sdkKernelPath, String librariesPath, String platformSdk}) : useIncrementalCompiler = useIncrementalCompiler ?? true, platformSdk = platformSdk ?? sdkDir, librariesPath = librariesPath ?? p.join(platformSdk ?? sdkDir, 'lib', 'libraries.json'), buildExtensions = { moduleExtension(platform): [ jsModuleExtension, jsModuleErrorsExtension, jsSourceMapExtension ], }; @override final Map<String, List<String>> buildExtensions; @override Future build(BuildStep buildStep) async { var module = Module.fromJson( json.decode(await buildStep.readAsString(buildStep.inputId)) as Map<String, dynamic>); // Entrypoints always have a `.module` file for ease of looking them up, // but they might not be the primary source. if (module.primarySource.changeExtension(moduleExtension(platform)) != buildStep.inputId) { return; } Future<void> handleError(e) async { await buildStep.writeAsString( module.primarySource.changeExtension(jsModuleErrorsExtension), '$e'); log.severe('$e'); } try { await _createDevCompilerModule(module, buildStep, useIncrementalCompiler, platformSdk, sdkKernelPath, librariesPath); } on DartDevcCompilationException catch (e) { await handleError(e); } on MissingModulesException catch (e) { await handleError(e); } } } /// Compile [module] with the dev compiler. Future<void> _createDevCompilerModule( Module module, BuildStep buildStep, bool useIncrementalCompiler, String dartSdk, String sdkKernelPath, String librariesPath, {bool debugMode = true}) async { var transitiveDeps = await buildStep.trackStage('CollectTransitiveDeps', () => module.computeTransitiveDependencies(buildStep)); var transitiveKernelDeps = [ for (var dep in transitiveDeps) dep.primarySource.changeExtension(ddcKernelExtension) ]; var scratchSpace = await buildStep.fetchResource(scratchSpaceResource); var allAssetIds = <AssetId>{...module.sources, ...transitiveKernelDeps}; await buildStep.trackStage( 'EnsureAssets', () => scratchSpace.ensureAssets(allAssetIds, buildStep)); var jsId = module.primarySource.changeExtension(jsModuleExtension); var jsOutputFile = scratchSpace.fileFor(jsId); var sdkSummary = p.url.join(dartSdk, sdkKernelPath ?? 'lib/_internal/ddc_sdk.dill'); var packagesFile = await createPackagesFile(allAssetIds); var request = WorkRequest() ..arguments.addAll([ '--dart-sdk-summary=$sdkSummary', '--modules=common', '--no-summarize', '-o', jsOutputFile.path, debugMode ? '--source-map' : '--no-source-map', for (var dep in transitiveDeps) _summaryArg(dep), '--packages=${packagesFile.absolute.uri}', '--module-name=${ddcModuleName(jsId)}', '--multi-root-scheme=$multiRootScheme', '--multi-root=.', '--track-widget-creation', '--inline-source-map', '--libraries-file=${p.toUri(librariesPath)}', if (useIncrementalCompiler) ...[ '--reuse-compiler-result', '--use-incremental-compiler', ], for (var source in module.sources) _sourceArg(source), ]) ..inputs.add(Input() ..path = sdkSummary ..digest = [0]) ..inputs.addAll( await Future.wait(transitiveKernelDeps.map((dep) async => Input() ..path = scratchSpace.fileFor(dep).path ..digest = (await buildStep.digest(dep)).bytes))); WorkResponse response; try { var driverResource = dartdevkDriverResource; var driver = await buildStep.fetchResource(driverResource); response = await driver.doWork(request, trackWork: (response) => buildStep.trackStage('Compile', () => response, isExternal: true)); } finally { await packagesFile.parent.delete(recursive: true); } // TODO(jakemac53): Fix the ddc worker mode so it always sends back a bad // status code if something failed. Today we just make sure there is an output // JS file to verify it was successful. var message = response.output .replaceAll('${scratchSpace.tempDir.path}/', '') .replaceAll('$multiRootScheme:///', ''); if (response.exitCode != EXIT_CODE_OK || !jsOutputFile.existsSync() || message.contains('Error:')) { throw DartDevcCompilationException(jsId, message); } else { if (message.isNotEmpty) { log.info('\n$message'); } // Copy the output back using the buildStep. await scratchSpace.copyOutput(jsId, buildStep); if (debugMode) { // We need to modify the sources in the sourcemap to remove the custom // `multiRootScheme` that we use. var sourceMapId = module.primarySource.changeExtension(jsSourceMapExtension); var file = scratchSpace.fileFor(sourceMapId); var content = await file.readAsString(); var json = jsonDecode(content); json['sources'] = fixSourceMapSources((json['sources'] as List).cast()); await buildStep.writeAsString(sourceMapId, jsonEncode(json)); } } } /// Returns the `--summary=` argument for a dependency. String _summaryArg(Module module) { final kernelAsset = module.primarySource.changeExtension(ddcKernelExtension); final moduleName = ddcModuleName(module.primarySource.changeExtension(jsModuleExtension)); return '--summary=${scratchSpace.fileFor(kernelAsset).path}=$moduleName'; } /// The url to compile for a source. /// /// Use the package: path for files under lib and the full absolute path for /// other files. String _sourceArg(AssetId id) { var uri = canonicalUriFor(id); return uri.startsWith('package:') ? uri : '$multiRootScheme:///${id.path}'; } /// Copied to `web/stack_trace_mapper.dart`, these need to be kept in sync. /// /// Given a list of [uris] as [String]s from a sourcemap, fixes them up so that /// they make sense in a browser context. /// /// - Strips the scheme from the uri /// - Strips the top level directory if its not `packages` List<String> fixSourceMapSources(List<String> uris) { return uris.map((source) { var uri = Uri.parse(source); // We only want to rewrite multi-root scheme uris. if (uri.scheme.isEmpty) return source; var newSegments = uri.pathSegments.first == 'packages' ? uri.pathSegments : uri.pathSegments.skip(1); return Uri(path: p.url.joinAll(['/'].followedBy(newSegments))).toString(); }).toList(); } /// The module name according to ddc for [jsId] which represents the real js /// module file. String ddcModuleName(AssetId jsId) { var jsPath = jsId.path.startsWith('lib/') ? jsId.path.replaceFirst('lib/', 'packages/${jsId.package}/') : jsId.path; return jsPath.substring(0, jsPath.length - jsModuleExtension.length); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_node_compilers
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_node_compilers/src/dart2js_bootstrap.dart
// Copyright (c) 2018, Anatoly Pulyaevskiy. 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:convert'; import 'dart:io'; import 'package:build/build.dart'; import 'package:build_modules/build_modules.dart'; import 'package:crypto/crypto.dart'; import 'package:node_preamble/preamble.dart'; import 'package:path/path.dart' as p; import 'package:scratch_space/scratch_space.dart'; import 'node_entrypoint_builder.dart'; import 'platforms.dart'; Future<void> bootstrapDart2Js( BuildStep buildStep, List<String> dart2JsArgs) async { var dartEntrypointId = buildStep.inputId; var moduleId = dartEntrypointId.changeExtension(moduleExtension(dart2jsPlatform)); var args = <String>[]; { var module = Module.fromJson( json.decode(await buildStep.readAsString(moduleId)) as Map<String, dynamic>); List<Module> allDeps; try { allDeps = (await module.computeTransitiveDependencies(buildStep)) ..add(module); } on UnsupportedModules catch (e) { var librariesString = (await e.exactLibraries(buildStep).toList()) .map((lib) => AssetId(lib.id.package, lib.id.path.replaceFirst(moduleLibraryExtension, '.dart'))) .join('\n'); log.warning(''' Skipping compiling ${buildStep.inputId} with dart2js because some of its transitive libraries have sdk dependencies that not supported on this platform: $librariesString https://github.com/dart-lang/build/blob/master/docs/faq.md#how-can-i-resolve-skipped-compiling-warnings '''); return; } var scratchSpace = await buildStep.fetchResource(scratchSpaceResource); var allSrcs = allDeps.expand((module) => module.sources); await scratchSpace.ensureAssets(allSrcs, buildStep); var packageFile = await _createPackageFile(allSrcs, buildStep, scratchSpace); var dartPath = dartEntrypointId.path.startsWith('lib/') ? 'package:${dartEntrypointId.package}/' '${dartEntrypointId.path.substring('lib/'.length)}' : dartEntrypointId.path; var jsOutputPath = '${p.withoutExtension(dartPath.replaceFirst('package:', 'packages/'))}' '$jsEntrypointExtension'; args = dart2JsArgs.toList() ..addAll([ '--packages=$packageFile', '-o$jsOutputPath', dartPath, ]); } var dart2js = await buildStep.fetchResource(dart2JsWorkerResource); var result = await dart2js.compile(args); var jsOutputId = dartEntrypointId.changeExtension(jsEntrypointExtension); var jsOutputFile = scratchSpace.fileFor(jsOutputId); if (result.succeeded && await jsOutputFile.exists()) { log.info(result.output); addNodePreamble(jsOutputFile); await scratchSpace.copyOutput(jsOutputId, buildStep); var jsSourceMapId = dartEntrypointId.changeExtension(jsEntrypointSourceMapExtension); await _copyIfExists(jsSourceMapId, scratchSpace, buildStep); } else { log.severe(result.output); } } Future<void> _copyIfExists( AssetId id, ScratchSpace scratchSpace, AssetWriter writer) async { var file = scratchSpace.fileFor(id); if (await file.exists()) { await scratchSpace.copyOutput(id, writer); } } void addNodePreamble(File output) { var preamble = getPreamble(minified: true); var contents = output.readAsStringSync(); output ..writeAsStringSync(preamble) ..writeAsStringSync(contents, mode: FileMode.append); } /// Creates a `.packages` file unique to this entrypoint at the root of the /// scratch space and returns it's filename. /// /// Since multiple invocations of Dart2Js will share a scratch space and we only /// know the set of packages involved the current entrypoint we can't construct /// a `.packages` file that will work for all invocations of Dart2Js so a unique /// file is created for every entrypoint that is run. /// /// The filename is based off the MD5 hash of the asset path so that files are /// unique regardless of situations like `web/foo/bar.dart` vs /// `web/foo-bar.dart`. Future<String> _createPackageFile(Iterable<AssetId> inputSources, BuildStep buildStep, ScratchSpace scratchSpace) async { var inputUri = buildStep.inputId.uri; var packageFileName = '.package-${md5.convert(inputUri.toString().codeUnits)}'; var packagesFile = scratchSpace.fileFor(AssetId(buildStep.inputId.package, packageFileName)); var packageNames = inputSources.map((s) => s.package).toSet(); var packagesFileContent = packageNames.map((n) => '$n:packages/$n/').join('\n'); await packagesFile .writeAsString('# Generated for $inputUri\n$packagesFileContent'); return packageFileName; }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_node_compilers
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_node_compilers/src/platforms.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 'package:build_modules/build_modules.dart'; final ddcPlatform = DartPlatform.register('ddc_node', [ 'async', 'collection', 'convert', 'core', 'developer', 'html', 'html_common', 'indexed_db', 'js', 'js_util', 'math', 'svg', 'typed_data', 'web_audio', 'web_gl', 'web_sql', '_internal', ]); final dart2jsPlatform = DartPlatform.register('dart2js_node', [ 'async', 'collection', 'convert', 'core', 'developer', 'html', 'html_common', 'indexed_db', 'js', 'js_util', 'math', 'svg', 'typed_data', 'web_audio', 'web_gl', 'web_sql', '_internal', ]);
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_node_compilers
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_node_compilers/src/dev_compiler_bootstrap.dart
// Copyright (c) 2018, Anatoly Pulyaevskiy. 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:collection'; import 'dart:convert'; import 'package:build/build.dart'; import 'package:build_modules/build_modules.dart'; import 'package:path/path.dart' as _p; import 'package:pool/pool.dart'; import 'ddc_names.dart'; import 'dev_compiler_builder.dart'; import 'node_entrypoint_builder.dart'; import 'platforms.dart'; /// Alias `_p.url` to `p`. _p.Context get _context => _p.url; Future<void> bootstrapDdc(BuildStep buildStep, {DartPlatform platform, Set<String> skipPlatformCheckPackages = const {}}) async { var dartEntrypointId = buildStep.inputId; var moduleId = buildStep.inputId .changeExtension(moduleExtension(platform ?? ddcPlatform)); var module = Module.fromJson(json .decode(await buildStep.readAsString(moduleId)) as Map<String, dynamic>); // First, ensure all transitive modules are built. List<AssetId> transitiveJsModules; try { transitiveJsModules = await _ensureTransitiveJsModules(module, buildStep, skipPlatformCheckPackages: skipPlatformCheckPackages); } on UnsupportedModules catch (e) { var librariesString = (await e.exactLibraries(buildStep).toList()) .map((lib) => AssetId(lib.id.package, lib.id.path.replaceFirst(moduleLibraryExtension, '.dart'))) .join('\n'); log.warning(''' Skipping compiling ${buildStep.inputId} with ddc because some of its transitive libraries have sdk dependencies that not supported on this platform: $librariesString https://github.com/dart-lang/build/blob/master/docs/faq.md#how-can-i-resolve-skipped-compiling-warnings '''); return; } var jsId = module.primarySource.changeExtension(jsModuleExtension); var appModuleName = ddcModuleName(jsId); var appDigestsOutput = dartEntrypointId.changeExtension(digestsEntrypointExtension); // Package-relative entrypoint name within the entrypoint JS module. var appModuleScope = pathToJSIdentifier(_context.withoutExtension(buildStep.inputId.path)); // Map from module name to module path for custom modules. var modulePaths = SplayTreeMap.of( {'dart_sdk': r'packages/$sdk/dev_compiler/common/dart_sdk'}); for (var jsId in transitiveJsModules) { // Strip out the top level dir from the path for any module, and set it to // `packages/` for lib modules. We set baseUrl to `/` to simplify things, // and we only allow you to serve top level directories. var moduleName = ddcModuleName(jsId); modulePaths[moduleName] = _context.withoutExtension( jsId.path.startsWith('lib') ? '$moduleName$jsModuleExtension' : _context.joinAll(_context.split(jsId.path).skip(1))); } var bootstrapId = dartEntrypointId.changeExtension(ddcBootstrapExtension); var bootstrapModuleName = _context.withoutExtension(_context.relative( bootstrapId.path, from: _context.dirname(dartEntrypointId.path))); var bootstrapContent = StringBuffer(); bootstrapContent.write(_dartLoaderSetup(modulePaths)); bootstrapContent.write(_appBootstrap(appModuleName, appModuleScope)); await buildStep.writeAsString(bootstrapId, bootstrapContent.toString()); var entrypointJsContent = _entryPointJs(bootstrapModuleName); await buildStep.writeAsString( dartEntrypointId.changeExtension(jsEntrypointExtension), entrypointJsContent); // Output the digests for transitive modules. // These can be consumed for hot reloads. var moduleDigests = <String, String>{ for (var jsId in transitiveJsModules) _moduleDigestKey(jsId): '${await buildStep.digest(jsId)}', }; await buildStep.writeAsString(appDigestsOutput, jsonEncode(moduleDigests)); await buildStep.writeAsString( dartEntrypointId.changeExtension(jsEntrypointSourceMapExtension), '{"version":3,"sourceRoot":"","sources":[],"names":[],"mappings":"",' '"file":""}'); } String _moduleDigestKey(AssetId jsId) => '${ddcModuleName(jsId)}$jsModuleExtension'; final _lazyBuildPool = Pool(16); /// Ensures that all transitive js modules for [module] are available and built. /// /// Throws an [UnsupportedModules] exception if there are any /// unsupported modules. Future<List<AssetId>> _ensureTransitiveJsModules( Module module, BuildStep buildStep, {Set<String> skipPlatformCheckPackages}) async { // Collect all the modules this module depends on, plus this module. var transitiveDeps = await module.computeTransitiveDependencies(buildStep); var jsModules = [ module.primarySource.changeExtension(jsModuleExtension), for (var dep in transitiveDeps) dep.primarySource.changeExtension(jsModuleExtension), ]; // Check that each module is readable, and warn otherwise. await Future.wait(jsModules.map((jsId) async { if (await _lazyBuildPool.withResource(() => buildStep.canRead(jsId))) { return; } var errorsId = jsId.addExtension('.errors'); await buildStep.canRead(errorsId); log.warning('Unable to read $jsId, check your console or the ' '`.dart_tool/build/generated/${errorsId.package}/${errorsId.path}` ' 'log file.'); })); return jsModules; } /// Code that actually imports the [moduleName] module, and calls the /// `[moduleScope].main()` function on it. /// /// Also performs other necessary initialization. String _appBootstrap(String moduleName, String moduleScope) => ''' const app = require("$moduleName"); dart_sdk._isolate_helper.startRootIsolate(() => {}, []); // Register main app function in the bootstrap exports so that it can be // invoked by the entry point JS module. module.exports.main = app.$moduleScope.main; '''; /// The actual entrypoint JS file which injects all the necessary scripts to /// run the app. String _entryPointJs(String bootstrapModuleName) => ''' const bootstrap = require("./$bootstrapModuleName"); // Set this module's exports to the exports object of bootstrap module. module.exports = bootstrap; // Run the app which can (optionally) register more exports. bootstrap.main(); '''; /// Sets up a proxy for Node's `require` which can resolve Dart modules /// from [modulePaths]. String _dartLoaderSetup(Map<String, String> modulePaths) => ''' let modulePaths = ${const JsonEncoder.withIndent(" ").convert(modulePaths)}; const path = require('path'); const process = require('process'); /// Resolves module [id] for Dart package names to their absolute filenames. /// Regular NodeJS module IDs are returned as-is. function resolveId(id) { if (id in modulePaths) { var parts = process.argv[1].split(path.sep).slice(0,-1); parts.push(modulePaths[id]); var newId = parts.join(path.sep); return newId; } return id; }; // Override built-in `Module.require` function to resolve Dart package // names to their absolute filename paths. var Module = require('module'); var moduleRequire = Module.prototype.require; Module.prototype.require = function () { var id = arguments['0']; arguments['0'] = resolveId(id); return moduleRequire.apply(this, arguments); }; // From this point each call to `require` will be able to resolve Dart package // names. const dart_sdk = require("dart_sdk"); const dart = dart_sdk.dart; // There is a JS binding for `require` function in `node_interop` package. // DDC treats this binding as global and maps all calls to this function // in Dart code to `dart.global.require`. We define this function here as a // proxy to require function of bootstrap module. dart.global.require = function (id) { return require(id); }; // We also expose this module's exports here so that main Dart module // can register its functionality to be exported. // This exports object is forwarded by the entry point JS module. dart.global.exports = module.exports; // Some browser-specific globals which dart_sdk.js expects to be defined. dart.global.Blob = function () { }; dart.global.Event = function () { }; dart.global.window = function () { }; dart.global.Window = function () { }; dart.global.ImageData = function () { }; dart.global.Node = function () { }; // TODO: this is better to use __filename of the main.dart.js file dart.global.self = { location: { href: __filename } }; ''';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_node_compilers
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_node_compilers/src/node_entrypoint_builder.dart
// Copyright (c) 2018, Anatoly Pulyaevskiy. 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'; // ignore: deprecated_member_use import 'package:analyzer/analyzer.dart'; import 'package:build/build.dart'; import 'package:build_modules/build_modules.dart'; import 'common.dart'; import 'dart2js_bootstrap.dart'; import 'dev_compiler_bootstrap.dart'; const ddcBootstrapExtension = '.dart.bootstrap.js'; const jsEntrypointExtension = '.dart.js'; const jsEntrypointSourceMapExtension = '.dart.js.map'; const digestsEntrypointExtension = '.digests'; /// Which compiler to use when compiling web entrypoints. enum WebCompiler { Dart2Js, DartDevc, } /// The top level keys supported for the `options` config for the /// [NodeEntrypointBuilder]. const _supportedOptions = [ _compiler, _dart2jsArgs, _buildRootAppSummary, ]; const _buildRootAppSummary = 'build_root_app_summary'; const _compiler = 'compiler'; const _dart2jsArgs = 'dart2js_args'; /// The deprecated keys for the `options` config for the [NodeEntrypointBuilder]. const _deprecatedOptions = [ 'enable_sync_async', 'ignore_cast_failures', ]; /// A builder which compiles entrypoints for the web. /// /// Supports `dart2js` and `dartdevc`. class NodeEntrypointBuilder implements Builder { final WebCompiler webCompiler; final List<String> dart2JsArgs; const NodeEntrypointBuilder(this.webCompiler, {this.dart2JsArgs = const []}); factory NodeEntrypointBuilder.fromOptions(BuilderOptions options) { validateOptions( options.config, _supportedOptions, 'build_node_compilers|entrypoint', deprecatedOptions: _deprecatedOptions); var compilerOption = options.config[_compiler] as String ?? 'dartdevc'; WebCompiler compiler; switch (compilerOption) { case 'dartdevc': compiler = WebCompiler.DartDevc; break; case 'dart2js': compiler = WebCompiler.Dart2Js; break; default: throw ArgumentError.value(compilerOption, _compiler, 'Only `dartdevc` and `dart2js` are supported.'); } if (options.config[_dart2jsArgs] is! List) { throw ArgumentError.value(options.config[_dart2jsArgs], _dart2jsArgs, 'Expected a list for $_dart2jsArgs.'); } var dart2JsArgs = (options.config[_dart2jsArgs] as List) ?.map((arg) => '$arg') ?.toList() ?? const <String>[]; return NodeEntrypointBuilder(compiler, dart2JsArgs: dart2JsArgs); } @override final buildExtensions = const { '.dart': [ ddcBootstrapExtension, jsEntrypointExtension, jsEntrypointSourceMapExtension, digestsEntrypointExtension, ], }; @override Future<void> build(BuildStep buildStep) async { var dartEntrypointId = buildStep.inputId; var isAppEntrypoint = await _isAppEntryPoint(dartEntrypointId, buildStep); if (!isAppEntrypoint) return; if (webCompiler == WebCompiler.DartDevc) { try { await bootstrapDdc(buildStep); } on MissingModulesException catch (e) { log.severe('$e'); } } else if (webCompiler == WebCompiler.Dart2Js) { await bootstrapDart2Js(buildStep, dart2JsArgs); } } } /// Returns whether or not [dartId] is an app entrypoint (basically, whether /// or not it has a `main` function). Future<bool> _isAppEntryPoint(AssetId dartId, AssetReader reader) async { assert(dartId.extension == '.dart'); // Skip reporting errors here, dartdevc will report them later with nicer // formatting. // ignore: deprecated_member_use var parsed = parseCompilationUnit(await reader.readAsString(dartId), suppressErrors: true); // Allow two or fewer arguments so that entrypoints intended for use with // [spawnUri] get counted. // // TODO: This misses the case where a Dart file doesn't contain main(), // but has a part that does, or it exports a `main` from another library. return parsed.declarations.any((node) { return node is FunctionDeclaration && node.name.name == 'main' && node.functionExpression.parameters.parameters.length <= 2; }); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_node_compilers
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_node_compilers/src/common.dart
// Copyright (c) 2017, 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:build/build.dart'; import 'package:path/path.dart' as p; import 'package:scratch_space/scratch_space.dart'; import 'package:build_modules/build_modules.dart'; final defaultAnalysisOptionsId = AssetId('build_modules', 'lib/src/analysis_options.default.yaml'); final sdkDir = p.dirname(p.dirname(Platform.resolvedExecutable)); String defaultAnalysisOptionsArg(ScratchSpace scratchSpace) => '--options=${scratchSpace.fileFor(defaultAnalysisOptionsId).path}'; // TODO: better solution for a .packages file, today we just create a new one // for every kernel build action. Future<File> createPackagesFile(Iterable<AssetId> allAssets) async { var allPackages = allAssets.map((id) => id.package).toSet(); var packagesFileDir = await Directory.systemTemp.createTemp('kernel_builder_'); var packagesFile = File(p.join(packagesFileDir.path, '.packages')); await packagesFile.create(); await packagesFile.writeAsString(allPackages .map((pkg) => '$pkg:$multiRootScheme:///packages/$pkg') .join('\r\n')); return packagesFile; } /// Validates that [config] only has the top level keys [supportedOptions]. /// /// Throws an [ArgumentError] if not. void validateOptions(Map<String, dynamic> config, List<String> supportedOptions, String builderKey, {List<String> deprecatedOptions}) { deprecatedOptions ??= []; var unsupported = config.keys.where( (o) => !supportedOptions.contains(o) && !deprecatedOptions.contains(o)); if (unsupported.isNotEmpty) { throw ArgumentError.value(unsupported.join(', '), builderKey, 'only $supportedOptions are supported options, but got'); } var deprecated = config.keys.where(deprecatedOptions.contains); if (deprecated.isNotEmpty) { log.warning('Found deprecated options ${deprecated.join(', ')}. These no ' 'longer have any effect and should be removed.'); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_node_compilers
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_node_compilers/src/ddc_names.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 'package:path/path.dart' as p; /// Transforms a path to a valid JS identifier. /// /// This logic must be synchronized with [pathToJSIdentifier] in DDC at: /// pkg/dev_compiler/lib/src/compiler/module_builder.dart /// /// For backwards compatibility, if this pattern is changed, /// dev_compiler_bootstrap.dart must be updated to accept both old and new /// patterns. String pathToJSIdentifier(String path) { path = p.normalize(path); if (path.startsWith('/') || path.startsWith('\\')) { path = path.substring(1, path.length); } return toJSIdentifier(path .replaceAll('\\', '__') .replaceAll('/', '__') .replaceAll('..', '__') .replaceAll('-', '_')); } /// Escape [name] to make it into a valid identifier. String toJSIdentifier(String name) { if (name.isEmpty) return r'$'; // Escape any invalid characters StringBuffer buffer; for (var i = 0; i < name.length; i++) { var ch = name[i]; var needsEscape = ch == r'$' || _invalidCharInIdentifier.hasMatch(ch); if (needsEscape && buffer == null) { buffer = StringBuffer(name.substring(0, i)); } if (buffer != null) { buffer.write(needsEscape ? '\$${ch.codeUnits.join("")}' : ch); } } var result = buffer != null ? '$buffer' : name; // Ensure the identifier first character is not numeric and that the whole // identifier is not a keyword. if (result.startsWith(RegExp('[0-9]')) || invalidVariableName(result)) { return '\$$result'; } return result; } /// Returns true for invalid JS variable names, such as keywords. /// Also handles invalid variable names in strict mode, like "arguments". bool invalidVariableName(String keyword, {bool strictMode = true}) { switch (keyword) { // http://www.ecma-international.org/ecma-262/6.0/#sec-future-reserved-words case 'await': case 'break': case 'case': case 'catch': case 'class': case 'const': case 'continue': case 'debugger': case 'default': case 'delete': case 'do': case 'else': case 'enum': case 'export': case 'extends': case 'finally': case 'for': case 'function': case 'if': case 'import': case 'in': case 'instanceof': case 'let': case 'new': case 'return': case 'super': case 'switch': case 'this': case 'throw': case 'try': case 'typeof': case 'var': case 'void': case 'while': case 'with': return true; case 'arguments': case 'eval': // http://www.ecma-international.org/ecma-262/6.0/#sec-future-reserved-words // http://www.ecma-international.org/ecma-262/6.0/#sec-identifiers-static-semantics-early-errors case 'implements': case 'interface': case 'package': case 'private': case 'protected': case 'public': case 'static': case 'yield': return strictMode; } return false; } // Invalid characters for identifiers, which would need to be escaped. final _invalidCharInIdentifier = RegExp(r'[^A-Za-z_$0-9]');
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_node_compilers
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/build_node_compilers/src/errors.dart
// Copyright (c) 2018, Anatoly Pulyaevskiy. 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:build/build.dart'; /// An [Exception] that is thrown when a worker returns an error. abstract class _WorkerException implements Exception { final AssetId failedAsset; final String error; /// A message to prepend to [toString] output. String get message; _WorkerException(this.failedAsset, this.error); @override String toString() => '$message:$failedAsset\n\n$error'; } /// An [Exception] that is thrown when dartdevc compilation fails. class DartDevcCompilationException extends _WorkerException { @override final String message = 'Error compiling dartdevc module'; DartDevcCompilationException(AssetId jsId, String error) : super(jsId, error); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher/mirror_matchers.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. @deprecated library mirror_matchers; /// The mirror matchers library provides some additional matchers that /// make use of `dart:mirrors`. import 'dart:mirrors'; import 'matcher.dart'; /// Returns a matcher that checks if a class instance has a property /// with name [name], and optionally, if that property in turn satisfies /// a [matcher]. Matcher hasProperty(String name, [matcher]) => _HasProperty(name, matcher == null ? null : wrapMatcher(matcher)); class _HasProperty extends Matcher { final String _name; final Matcher _matcher; const _HasProperty(this._name, [this._matcher]); @override bool matches(item, Map matchState) { var mirror = reflect(item); var classMirror = mirror.type; var symbol = Symbol(_name); var candidate = classMirror.declarations[symbol]; if (candidate == null) { addStateInfo(matchState, {'reason': 'has no property named "$_name"'}); return false; } var isInstanceField = candidate is VariableMirror && !candidate.isStatic; var isInstanceGetter = candidate is MethodMirror && candidate.isGetter && !candidate.isStatic; if (!(isInstanceField || isInstanceGetter)) { addStateInfo(matchState, { 'reason': 'has a member named "$_name", but it is not an instance property' }); return false; } if (_matcher == null) return true; var result = mirror.getField(symbol); var resultMatches = _matcher.matches(result.reflectee, matchState); if (!resultMatches) { addStateInfo(matchState, {'value': result.reflectee}); } return resultMatches; } @override Description describe(Description description) { description.add('has property "$_name"'); if (_matcher != null) { description.add(' which matches ').addDescriptionOf(_matcher); } return description; } @override Description describeMismatch( item, Description mismatchDescription, Map matchState, bool verbose) { var reason = matchState == null ? null : matchState['reason']; if (reason != null) { mismatchDescription.add(reason as String); } else { mismatchDescription .add('has property "$_name" with value ') .addDescriptionOf(matchState['value']); var innerDescription = StringDescription(); _matcher.describeMismatch(matchState['value'], innerDescription, matchState['state'] as Map, verbose); if (innerDescription.length > 0) { mismatchDescription.add(' which ').add(innerDescription.toString()); } } return mismatchDescription; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher/matcher.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. /// Support for specifying test expectations, such as for unit tests. export 'src/core_matchers.dart'; export 'src/custom_matcher.dart'; export 'src/description.dart'; export 'src/equals_matcher.dart'; export 'src/error_matchers.dart'; export 'src/interfaces.dart'; export 'src/iterable_matchers.dart'; export 'src/map_matchers.dart'; export 'src/numeric_matchers.dart'; export 'src/operator_matchers.dart'; export 'src/order_matchers.dart'; export 'src/string_matchers.dart'; export 'src/type_matcher.dart'; export 'src/util.dart';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher/src/iterable_matchers.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 'description.dart'; import 'equals_matcher.dart'; import 'feature_matcher.dart'; import 'interfaces.dart'; import 'util.dart'; /// Returns a matcher which matches [Iterable]s in which all elements /// match the given [matcher]. Matcher everyElement(matcher) => _EveryElement(wrapMatcher(matcher)); class _EveryElement extends _IterableMatcher { final Matcher _matcher; _EveryElement(this._matcher); @override bool typedMatches(Iterable item, Map matchState) { var i = 0; for (var element in item) { if (!_matcher.matches(element, matchState)) { addStateInfo(matchState, {'index': i, 'element': element}); return false; } ++i; } return true; } @override Description describe(Description description) => description.add('every element(').addDescriptionOf(_matcher).add(')'); @override Description describeTypedMismatch( item, Description mismatchDescription, Map matchState, bool verbose) { if (matchState['index'] != null) { var index = matchState['index']; var element = matchState['element']; mismatchDescription .add('has value ') .addDescriptionOf(element) .add(' which '); var subDescription = StringDescription(); _matcher.describeMismatch( element, subDescription, matchState['state'] as Map, verbose); if (subDescription.length > 0) { mismatchDescription.add(subDescription.toString()); } else { mismatchDescription.add("doesn't match "); _matcher.describe(mismatchDescription); } mismatchDescription.add(' at index $index'); return mismatchDescription; } return super .describeMismatch(item, mismatchDescription, matchState, verbose); } } /// Returns a matcher which matches [Iterable]s in which at least one /// element matches the given [matcher]. Matcher anyElement(matcher) => _AnyElement(wrapMatcher(matcher)); class _AnyElement extends _IterableMatcher { final Matcher _matcher; _AnyElement(this._matcher); @override bool typedMatches(Iterable item, Map matchState) => item.any((e) => _matcher.matches(e, matchState)); @override Description describe(Description description) => description.add('some element ').addDescriptionOf(_matcher); } /// Returns a matcher which matches [Iterable]s that have the same /// length and the same elements as [expected], in the same order. /// /// This is equivalent to [equals] but does not recurse. Matcher orderedEquals(Iterable expected) => _OrderedEquals(expected); class _OrderedEquals extends _IterableMatcher { final Iterable _expected; final Matcher _matcher; _OrderedEquals(this._expected) : _matcher = equals(_expected, 1); @override bool typedMatches(Iterable item, Map matchState) => _matcher.matches(item, matchState); @override Description describe(Description description) => description.add('equals ').addDescriptionOf(_expected).add(' ordered'); @override Description describeTypedMismatch(Iterable item, Description mismatchDescription, Map matchState, bool verbose) { return _matcher.describeMismatch( item, mismatchDescription, matchState, verbose); } } /// Returns a matcher which matches [Iterable]s that have the same length and /// the same elements as [expected], but not necessarily in the same order. /// /// Note that this is worst case O(n^2) runtime and memory usage so it should /// only be used on small iterables. Matcher unorderedEquals(Iterable expected) => _UnorderedEquals(expected); class _UnorderedEquals extends _UnorderedMatches { final List _expectedValues; _UnorderedEquals(Iterable expected) : _expectedValues = expected.toList(), super(expected.map(equals)); @override Description describe(Description description) => description .add('equals ') .addDescriptionOf(_expectedValues) .add(' unordered'); } /// Iterable matchers match against [Iterable]s. We add this intermediate /// class to give better mismatch error messages than the base Matcher class. abstract class _IterableMatcher extends FeatureMatcher<Iterable> { const _IterableMatcher(); } /// Returns a matcher which matches [Iterable]s whose elements match the /// matchers in [expected], but not necessarily in the same order. /// /// Note that this is worst case O(n^2) runtime and memory usage so it should /// only be used on small iterables. Matcher unorderedMatches(Iterable expected) => _UnorderedMatches(expected); class _UnorderedMatches extends _IterableMatcher { final List<Matcher> _expected; final bool _allowUnmatchedValues; _UnorderedMatches(Iterable expected, {bool allowUnmatchedValues}) : _expected = expected.map(wrapMatcher).toList(), _allowUnmatchedValues = allowUnmatchedValues ?? false; String _test(List values) { // Check the lengths are the same. if (_expected.length > values.length) { return 'has too few elements (${values.length} < ${_expected.length})'; } else if (!_allowUnmatchedValues && _expected.length < values.length) { return 'has too many elements (${values.length} > ${_expected.length})'; } var edges = List.generate(values.length, (_) => <int>[], growable: false); for (var v = 0; v < values.length; v++) { for (var m = 0; m < _expected.length; m++) { if (_expected[m].matches(values[v], {})) { edges[v].add(m); } } } // The index into `values` matched with each matcher or `null` if no value // has been matched yet. var matched = List<int>(_expected.length); for (var valueIndex = 0; valueIndex < values.length; valueIndex++) { _findPairing(edges, valueIndex, matched); } for (var matcherIndex = 0; matcherIndex < _expected.length; matcherIndex++) { if (matched[matcherIndex] == null) { final description = StringDescription() .add('has no match for ') .addDescriptionOf(_expected[matcherIndex]) .add(' at index $matcherIndex'); final remainingUnmatched = matched.sublist(matcherIndex + 1).where((m) => m == null).length; return remainingUnmatched == 0 ? description.toString() : description .add(' along with $remainingUnmatched other unmatched') .toString(); } } return null; } @override bool typedMatches(Iterable item, Map mismatchState) => _test(item.toList()) == null; @override Description describe(Description description) => description .add('matches ') .addAll('[', ', ', ']', _expected) .add(' unordered'); @override Description describeTypedMismatch(item, Description mismatchDescription, Map matchState, bool verbose) => mismatchDescription.add(_test(item.toList())); /// Returns `true` if the value at [valueIndex] can be paired with some /// unmatched matcher and updates the state of [matched]. /// /// If there is a conflict where multiple values may match the same matcher /// recursively looks for a new place to match the old value. [reserved] /// tracks the matchers that have been used _during_ this search. bool _findPairing(List<List<int>> edges, int valueIndex, List<int> matched, [Set<int> reserved]) { reserved ??= <int>{}; final possiblePairings = edges[valueIndex].where((m) => !reserved.contains(m)); for (final matcherIndex in possiblePairings) { reserved.add(matcherIndex); final previouslyMatched = matched[matcherIndex]; if (previouslyMatched == null || // If the matcher isn't already free, check whether the existing value // occupying the matcher can be bumped to another one. _findPairing(edges, matched[matcherIndex], matched, reserved)) { matched[matcherIndex] = valueIndex; return true; } } return false; } } /// A pairwise matcher for [Iterable]s. /// /// The [comparator] function, taking an expected and an actual argument, and /// returning whether they match, will be applied to each pair in order. /// [description] should be a meaningful name for the comparator. Matcher pairwiseCompare<S, T>(Iterable<S> expected, bool Function(S, T) comparator, String description) => _PairwiseCompare(expected, comparator, description); typedef _Comparator<S, T> = bool Function(S a, T b); class _PairwiseCompare<S, T> extends _IterableMatcher { final Iterable<S> _expected; final _Comparator<S, T> _comparator; final String _description; _PairwiseCompare(this._expected, this._comparator, this._description); @override bool typedMatches(Iterable item, Map matchState) { if (item.length != _expected.length) return false; var iterator = item.iterator; var i = 0; for (var e in _expected) { iterator.moveNext(); if (!_comparator(e, iterator.current as T)) { addStateInfo(matchState, {'index': i, 'expected': e, 'actual': iterator.current}); return false; } i++; } return true; } @override Description describe(Description description) => description.add('pairwise $_description ').addDescriptionOf(_expected); @override Description describeTypedMismatch(Iterable item, Description mismatchDescription, Map matchState, bool verbose) { if (item.length != _expected.length) { return mismatchDescription .add('has length ${item.length} instead of ${_expected.length}'); } else { return mismatchDescription .add('has ') .addDescriptionOf(matchState['actual']) .add(' which is not $_description ') .addDescriptionOf(matchState['expected']) .add(' at index ${matchState["index"]}'); } } } /// Matches [Iterable]s which contain an element matching every value in /// [expected] in any order, and may contain additional values. /// /// For example: `[0, 1, 0, 2, 0]` matches `containsAll([1, 2])` and /// `containsAll([2, 1])` but not `containsAll([1, 2, 3])`. /// /// Will only match values which implement [Iterable]. /// /// Each element in the value will only be considered a match for a single /// matcher in [expected] even if it could satisfy more than one. For instance /// `containsAll([greaterThan(1), greaterThan(2)])` will not be satisfied by /// `[3]`. To check that all matchers are satisfied within an iterable and allow /// the same element to satisfy multiple matchers use /// `allOf(matchers.map(contains))`. /// /// Note that this is worst case O(n^2) runtime and memory usage so it should /// only be used on small iterables. Matcher containsAll(Iterable expected) => _ContainsAll(expected); class _ContainsAll extends _UnorderedMatches { final Iterable _unwrappedExpected; _ContainsAll(Iterable expected) : _unwrappedExpected = expected, super(expected.map(wrapMatcher), allowUnmatchedValues: true); @override Description describe(Description description) => description.add('contains all of ').addDescriptionOf(_unwrappedExpected); } /// Matches [Iterable]s which contain an element matching every value in /// [expected] in the same order, but may contain additional values interleaved /// throughout. /// /// For example: `[0, 1, 0, 2, 0]` matches `containsAllInOrder([1, 2])` but not /// `containsAllInOrder([2, 1])` or `containsAllInOrder([1, 2, 3])`. /// /// Will only match values which implement [Iterable]. Matcher containsAllInOrder(Iterable expected) => _ContainsAllInOrder(expected); class _ContainsAllInOrder extends _IterableMatcher { final Iterable _expected; _ContainsAllInOrder(this._expected); String _test(Iterable item, Map matchState) { var matchers = _expected.map(wrapMatcher).toList(); var matcherIndex = 0; for (var value in item) { if (matchers[matcherIndex].matches(value, matchState)) matcherIndex++; if (matcherIndex == matchers.length) return null; } return StringDescription() .add('did not find a value matching ') .addDescriptionOf(matchers[matcherIndex]) .add(' following expected prior values') .toString(); } @override bool typedMatches(Iterable item, Map matchState) => _test(item, matchState) == null; @override Description describe(Description description) => description .add('contains in order(') .addDescriptionOf(_expected) .add(')'); @override Description describeTypedMismatch(Iterable item, Description mismatchDescription, Map matchState, bool verbose) => mismatchDescription.add(_test(item, matchState)); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher/src/util.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 'core_matchers.dart'; import 'equals_matcher.dart'; import 'interfaces.dart'; typedef _Predicate<T> = bool Function(T value); /// A [Map] between whitespace characters and their escape sequences. const _escapeMap = { '\n': r'\n', '\r': r'\r', '\f': r'\f', '\b': r'\b', '\t': r'\t', '\v': r'\v', '\x7F': r'\x7F', // delete }; /// A [RegExp] that matches whitespace characters that should be escaped. final _escapeRegExp = RegExp( '[\\x00-\\x07\\x0E-\\x1F${_escapeMap.keys.map(_getHexLiteral).join()}]'); /// Useful utility for nesting match states. void addStateInfo(Map matchState, Map values) { var innerState = Map.from(matchState); matchState.clear(); matchState['state'] = innerState; matchState.addAll(values); } /// Takes an argument and returns an equivalent [Matcher]. /// /// If the argument is already a matcher this does nothing, /// else if the argument is a function, it generates a predicate /// function matcher, else it generates an equals matcher. Matcher wrapMatcher(x) { if (x is Matcher) { return x; } else if (x is _Predicate<Object>) { // x is already a predicate that can handle anything return predicate(x); } else if (x is _Predicate<Null>) { // x is a unary predicate, but expects a specific type // so wrap it. // ignore: unnecessary_lambdas return predicate((a) => (x as dynamic)(a)); } else { return equals(x); } } /// Returns [str] with all whitespace characters represented as their escape /// sequences. /// /// Backslash characters are escaped as `\\` String escape(String str) { str = str.replaceAll('\\', r'\\'); return str.replaceAllMapped(_escapeRegExp, (match) { var mapped = _escapeMap[match[0]]; if (mapped != null) return mapped; return _getHexLiteral(match[0]); }); } /// Given single-character string, return the hex-escaped equivalent. String _getHexLiteral(String input) { var rune = input.runes.single; return r'\x' + rune.toRadixString(16).toUpperCase().padLeft(2, '0'); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher/src/operator_matchers.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 'interfaces.dart'; import 'util.dart'; /// This returns a matcher that inverts [matcher] to its logical negation. Matcher isNot(matcher) => _IsNot(wrapMatcher(matcher)); class _IsNot extends Matcher { final Matcher _matcher; const _IsNot(this._matcher); @override bool matches(item, Map matchState) => !_matcher.matches(item, matchState); @override Description describe(Description description) => description.add('not ').addDescriptionOf(_matcher); } /// This returns a matcher that matches if all of the matchers passed as /// arguments (up to 7) match. /// /// Instead of passing the matchers separately they can be passed as a single /// List argument. Any argument that is not a matcher is implicitly wrapped in a /// Matcher to check for equality. Matcher allOf(arg0, [arg1, arg2, arg3, arg4, arg5, arg6]) { return _AllOf(_wrapArgs(arg0, arg1, arg2, arg3, arg4, arg5, arg6)); } class _AllOf extends Matcher { final List<Matcher> _matchers; const _AllOf(this._matchers); @override bool matches(item, Map matchState) { for (var matcher in _matchers) { if (!matcher.matches(item, matchState)) { addStateInfo(matchState, {'matcher': matcher}); return false; } } return true; } @override Description describeMismatch( item, Description mismatchDescription, Map matchState, bool verbose) { var matcher = matchState['matcher']; matcher.describeMismatch( item, mismatchDescription, matchState['state'], verbose); return mismatchDescription; } @override Description describe(Description description) => description.addAll('(', ' and ', ')', _matchers); } /// Matches if any of the given matchers evaluate to true. /// /// The arguments can be a set of matchers as separate parameters /// (up to 7), or a List of matchers. /// /// The matchers are evaluated from left to right using short-circuit /// evaluation, so evaluation stops as soon as a matcher returns true. /// /// Any argument that is not a matcher is implicitly wrapped in a /// Matcher to check for equality. Matcher anyOf(arg0, [arg1, arg2, arg3, arg4, arg5, arg6]) { return _AnyOf(_wrapArgs(arg0, arg1, arg2, arg3, arg4, arg5, arg6)); } class _AnyOf extends Matcher { final List<Matcher> _matchers; const _AnyOf(this._matchers); @override bool matches(item, Map matchState) { for (var matcher in _matchers) { if (matcher.matches(item, matchState)) { return true; } } return false; } @override Description describe(Description description) => description.addAll('(', ' or ', ')', _matchers); } List<Matcher> _wrapArgs(arg0, arg1, arg2, arg3, arg4, arg5, arg6) { Iterable args; if (arg0 is List) { if (arg1 != null || arg2 != null || arg3 != null || arg4 != null || arg5 != null || arg6 != null) { throw ArgumentError('If arg0 is a List, all other arguments must be' ' null.'); } args = arg0; } else { args = [arg0, arg1, arg2, arg3, arg4, arg5, arg6].where((e) => e != null); } return args.map(wrapMatcher).toList(); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher/src/string_matchers.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 'feature_matcher.dart'; import 'interfaces.dart'; /// Returns a matcher which matches if the match argument is a string and /// is equal to [value] when compared case-insensitively. Matcher equalsIgnoringCase(String value) => _IsEqualIgnoringCase(value); class _IsEqualIgnoringCase extends FeatureMatcher<String> { final String _value; final String _matchValue; _IsEqualIgnoringCase(String value) : _value = value, _matchValue = value.toLowerCase(); @override bool typedMatches(String item, Map matchState) => _matchValue == item.toLowerCase(); @override Description describe(Description description) => description.addDescriptionOf(_value).add(' ignoring case'); } /// Returns a matcher which matches if the match argument is a string and /// is equal to [value], ignoring whitespace. /// /// In this matcher, "ignoring whitespace" means comparing with all runs of /// whitespace collapsed to single space characters and leading and trailing /// whitespace removed. /// /// For example, the following will all match successfully: /// /// expect("hello world", equalsIgnoringWhitespace("hello world")); /// expect(" hello world", equalsIgnoringWhitespace("hello world")); /// expect("hello world ", equalsIgnoringWhitespace("hello world")); /// /// The following will not match: /// /// expect("helloworld", equalsIgnoringWhitespace("hello world")); /// expect("he llo world", equalsIgnoringWhitespace("hello world")); Matcher equalsIgnoringWhitespace(String value) => _IsEqualIgnoringWhitespace(value); class _IsEqualIgnoringWhitespace extends FeatureMatcher<String> { final String _matchValue; _IsEqualIgnoringWhitespace(String value) : _matchValue = collapseWhitespace(value); @override bool typedMatches(String item, Map matchState) => _matchValue == collapseWhitespace(item); @override Description describe(Description description) => description.addDescriptionOf(_matchValue).add(' ignoring whitespace'); @override Description describeTypedMismatch( item, Description mismatchDescription, Map matchState, bool verbose) { return mismatchDescription .add('is ') .addDescriptionOf(collapseWhitespace(item)) .add(' with whitespace compressed'); } } /// Returns a matcher that matches if the match argument is a string and /// starts with [prefixString]. Matcher startsWith(String prefixString) => _StringStartsWith(prefixString); class _StringStartsWith extends FeatureMatcher<String> { final String _prefix; const _StringStartsWith(this._prefix); @override bool typedMatches(item, Map matchState) => item.startsWith(_prefix); @override Description describe(Description description) => description.add('a string starting with ').addDescriptionOf(_prefix); } /// Returns a matcher that matches if the match argument is a string and /// ends with [suffixString]. Matcher endsWith(String suffixString) => _StringEndsWith(suffixString); class _StringEndsWith extends FeatureMatcher<String> { final String _suffix; const _StringEndsWith(this._suffix); @override bool typedMatches(item, Map matchState) => item.endsWith(_suffix); @override Description describe(Description description) => description.add('a string ending with ').addDescriptionOf(_suffix); } /// Returns a matcher that matches if the match argument is a string and /// contains a given list of [substrings] in relative order. /// /// For example, `stringContainsInOrder(["a", "e", "i", "o", "u"])` will match /// "abcdefghijklmnopqrstuvwxyz". Matcher stringContainsInOrder(List<String> substrings) => _StringContainsInOrder(substrings); class _StringContainsInOrder extends FeatureMatcher<String> { final List<String> _substrings; const _StringContainsInOrder(this._substrings); @override bool typedMatches(item, Map matchState) { var fromIndex = 0; for (var s in _substrings) { fromIndex = item.indexOf(s, fromIndex); if (fromIndex < 0) return false; } return true; } @override Description describe(Description description) => description.addAll( 'a string containing ', ', ', ' in order', _substrings); } /// Returns a matcher that matches if the match argument is a string and /// matches the regular expression given by [re]. /// /// [re] can be a [RegExp] instance or a [String]; in the latter case it will be /// used to create a RegExp instance. Matcher matches(re) => _MatchesRegExp(re); class _MatchesRegExp extends FeatureMatcher<String> { RegExp _regexp; _MatchesRegExp(re) { if (re is String) { _regexp = RegExp(re); } else if (re is RegExp) { _regexp = re; } else { throw ArgumentError('matches requires a regexp or string'); } } @override bool typedMatches(item, Map matchState) => _regexp.hasMatch(item); @override Description describe(Description description) => description.add("match '${_regexp.pattern}'"); } /// Utility function to collapse whitespace runs to single spaces /// and strip leading/trailing whitespace. String collapseWhitespace(String string) { var result = StringBuffer(); var skipSpace = true; for (var i = 0; i < string.length; i++) { var character = string[i]; if (_isWhitespace(character)) { if (!skipSpace) { result.write(' '); skipSpace = true; } } else { result.write(character); skipSpace = false; } } return result.toString().trim(); } bool _isWhitespace(String ch) => ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t';
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher/src/description.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 'interfaces.dart'; import 'pretty_print.dart'; /// The default implementation of [Description]. This should rarely need /// substitution, although conceivably it is a place where other languages /// could be supported. class StringDescription implements Description { final StringBuffer _out = StringBuffer(); /// Initialize the description with initial contents [init]. StringDescription([String init = '']) { _out.write(init); } @override int get length => _out.length; /// Get the description as a string. @override String toString() => _out.toString(); /// Append [text] to the description. @override Description add(String text) { _out.write(text); return this; } /// Change the value of the description. @override Description replace(String text) { _out.clear(); return add(text); } /// Appends a description of [value]. If it is an IMatcher use its /// describe method; if it is a string use its literal value after /// escaping any embedded control characters; otherwise use its /// toString() value and wrap it in angular "quotes". @override Description addDescriptionOf(value) { if (value is Matcher) { value.describe(this); } else { add(prettyPrint(value, maxLineLength: 80, maxItems: 25)); } return this; } /// Append an [Iterable] [list] of objects to the description, using the /// specified [separator] and framing the list with [start] /// and [end]. @override Description addAll( String start, String separator, String end, Iterable list) { var separate = false; add(start); for (var item in list) { if (separate) { add(separator); } addDescriptionOf(item); separate = true; } add(end); return this; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher/src/custom_matcher.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 'package:stack_trace/stack_trace.dart'; import 'description.dart'; import 'interfaces.dart'; import 'util.dart'; /// A useful utility class for implementing other matchers through inheritance. /// Derived classes should call the base constructor with a feature name and /// description, and an instance matcher, and should implement the /// [featureValueOf] abstract method. /// /// The feature description will typically describe the item and the feature, /// while the feature name will just name the feature. For example, we may /// have a Widget class where each Widget has a price; we could make a /// [CustomMatcher] that can make assertions about prices with: /// /// ```dart /// class HasPrice extends CustomMatcher { /// HasPrice(matcher) : super("Widget with price that is", "price", matcher); /// featureValueOf(actual) => (actual as Widget).price; /// } /// ``` /// /// and then use this for example like: /// /// ```dart /// expect(inventoryItem, HasPrice(greaterThan(0))); /// ``` class CustomMatcher extends Matcher { final String _featureDescription; final String _featureName; final Matcher _matcher; CustomMatcher(this._featureDescription, this._featureName, matcher) : _matcher = wrapMatcher(matcher); /// Override this to extract the interesting feature. Object featureValueOf(actual) => actual; @override bool matches(item, Map matchState) { try { var f = featureValueOf(item); if (_matcher.matches(f, matchState)) return true; addStateInfo(matchState, {'custom.feature': f}); } catch (exception, stack) { addStateInfo(matchState, { 'custom.exception': exception.toString(), 'custom.stack': Chain.forTrace(stack) .foldFrames( (frame) => frame.package == 'test' || frame.package == 'stream_channel' || frame.package == 'matcher', terse: true) .toString() }); } return false; } @override Description describe(Description description) => description.add(_featureDescription).add(' ').addDescriptionOf(_matcher); @override Description describeMismatch( item, Description mismatchDescription, Map matchState, bool verbose) { if (matchState['custom.exception'] != null) { mismatchDescription .add('threw ') .addDescriptionOf(matchState['custom.exception']) .add('\n') .add(matchState['custom.stack'].toString()); return mismatchDescription; } mismatchDescription .add('has ') .add(_featureName) .add(' with value ') .addDescriptionOf(matchState['custom.feature']); var innerDescription = StringDescription(); _matcher.describeMismatch(matchState['custom.feature'], innerDescription, matchState['state'] as Map, verbose); if (innerDescription.length > 0) { mismatchDescription.add(' which ').add(innerDescription.toString()); } return mismatchDescription; } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher/src/numeric_matchers.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 'feature_matcher.dart'; import 'interfaces.dart'; /// Returns a matcher which matches if the match argument is within [delta] /// of some [value]. /// /// In other words, this matches if the match argument is greater than /// than or equal [value]-[delta] and less than or equal to [value]+[delta]. Matcher closeTo(num value, num delta) => _IsCloseTo(value, delta); class _IsCloseTo extends FeatureMatcher<num> { final num _value, _delta; const _IsCloseTo(this._value, this._delta); @override bool typedMatches(item, Map matchState) { var diff = item - _value; if (diff < 0) diff = -diff; return diff <= _delta; } @override Description describe(Description description) => description .add('a numeric value within ') .addDescriptionOf(_delta) .add(' of ') .addDescriptionOf(_value); @override Description describeTypedMismatch( item, Description mismatchDescription, Map matchState, bool verbose) { var diff = item - _value; if (diff < 0) diff = -diff; return mismatchDescription.add(' differs by ').addDescriptionOf(diff); } } /// Returns a matcher which matches if the match argument is greater /// than or equal to [low] and less than or equal to [high]. Matcher inInclusiveRange(num low, num high) => _InRange(low, high, true, true); /// Returns a matcher which matches if the match argument is greater /// than [low] and less than [high]. Matcher inExclusiveRange(num low, num high) => _InRange(low, high, false, false); /// Returns a matcher which matches if the match argument is greater /// than [low] and less than or equal to [high]. Matcher inOpenClosedRange(num low, num high) => _InRange(low, high, false, true); /// Returns a matcher which matches if the match argument is greater /// than or equal to a [low] and less than [high]. Matcher inClosedOpenRange(num low, num high) => _InRange(low, high, true, false); class _InRange extends FeatureMatcher<num> { final num _low, _high; final bool _lowMatchValue, _highMatchValue; const _InRange( this._low, this._high, this._lowMatchValue, this._highMatchValue); @override bool typedMatches(value, Map matchState) { if (value < _low || value > _high) { return false; } if (value == _low) { return _lowMatchValue; } if (value == _high) { return _highMatchValue; } // Value may still be outside if range if it can't be compared. return value > _low && value < _high; } @override Description describe(Description description) => description.add('be in range from ' "$_low (${_lowMatchValue ? 'inclusive' : 'exclusive'}) to " "$_high (${_highMatchValue ? 'inclusive' : 'exclusive'})"); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher/src/pretty_print.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 'description.dart'; import 'interfaces.dart'; import 'util.dart'; /// Returns a pretty-printed representation of [object]. /// /// If [maxLineLength] is passed, this will attempt to ensure that each line is /// no longer than [maxLineLength] characters long. This isn't guaranteed, since /// individual objects may have string representations that are too long, but /// most lines will be less than [maxLineLength] long. /// /// If [maxItems] is passed, [Iterable]s and [Map]s will only print their first /// [maxItems] members or key/value pairs, respectively. String prettyPrint(object, {int maxLineLength, int maxItems}) { String _prettyPrint(object, int indent, Set seen, bool top) { // If the object is a matcher, use its description. if (object is Matcher) { var description = StringDescription(); object.describe(description); return '<$description>'; } // Avoid looping infinitely on recursively-nested data structures. if (seen.contains(object)) return '(recursive)'; seen = seen.union({object}); String pp(child) => _prettyPrint(child, indent + 2, seen, false); if (object is Iterable) { // Print the type name for non-List iterables. var type = object is List ? '' : _typeName(object) + ':'; // Truncate the list of strings if it's longer than [maxItems]. var strings = object.map(pp).toList(); if (maxItems != null && strings.length > maxItems) { strings.replaceRange(maxItems - 1, strings.length, ['...']); } // If the printed string is short and doesn't contain a newline, print it // as a single line. var singleLine = "$type[${strings.join(', ')}]"; if ((maxLineLength == null || singleLine.length + indent <= maxLineLength) && !singleLine.contains('\n')) { return singleLine; } // Otherwise, print each member on its own line. return '$type[\n' + strings.map((string) { return _indent(indent + 2) + string; }).join(',\n') + '\n' + _indent(indent) + ']'; } else if (object is Map) { // Convert the contents of the map to string representations. var strings = object.keys.map((key) { return '${pp(key)}: ${pp(object[key])}'; }).toList(); // Truncate the list of strings if it's longer than [maxItems]. if (maxItems != null && strings.length > maxItems) { strings.replaceRange(maxItems - 1, strings.length, ['...']); } // If the printed string is short and doesn't contain a newline, print it // as a single line. var singleLine = '{${strings.join(", ")}}'; if ((maxLineLength == null || singleLine.length + indent <= maxLineLength) && !singleLine.contains('\n')) { return singleLine; } // Otherwise, print each key/value pair on its own line. return '{\n' + strings.map((string) { return _indent(indent + 2) + string; }).join(',\n') + '\n' + _indent(indent) + '}'; } else if (object is String) { // Escape strings and print each line on its own line. var lines = object.split('\n'); return "'" + lines.map(_escapeString).join("\\n'\n${_indent(indent + 2)}'") + "'"; } else { var value = object.toString().replaceAll('\n', _indent(indent) + '\n'); var defaultToString = value.startsWith('Instance of '); // If this is the top-level call to [prettyPrint], wrap the value on angle // brackets to set it apart visually. if (top) value = '<$value>'; // Print the type of objects with custom [toString] methods. Primitive // objects and objects that don't implement a custom [toString] don't need // to have their types printed. if (object is num || object is bool || object is Function || object is RegExp || object is MapEntry || object is Expando || object == null || defaultToString) { return value; } else { return '${_typeName(object)}:$value'; } } } return _prettyPrint(object, 0, <Object>{}, true); } String _indent(int length) => List.filled(length, ' ').join(''); /// Returns the name of the type of [x] with fallbacks for core types with /// private implementations. String _typeName(x) { if (x is Type) return 'Type'; if (x is Uri) return 'Uri'; if (x is Set) return 'Set'; if (x is BigInt) return 'BigInt'; return '${x.runtimeType}'; } /// Returns [source] with any control characters replaced by their escape /// sequences. /// /// This doesn't add quotes to the string, but it does escape single quote /// characters so that single quotes can be applied externally. String _escapeString(String source) => escape(source).replaceAll("'", r"\'");
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher/src/order_matchers.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 'interfaces.dart'; /// Returns a matcher which matches if the match argument is greater /// than the given [value]. Matcher greaterThan(value) => _OrderingMatcher(value, false, false, true, 'a value greater than'); /// Returns a matcher which matches if the match argument is greater /// than or equal to the given [value]. Matcher greaterThanOrEqualTo(value) => _OrderingMatcher( value, true, false, true, 'a value greater than or equal to'); /// Returns a matcher which matches if the match argument is less /// than the given [value]. Matcher lessThan(value) => _OrderingMatcher(value, false, true, false, 'a value less than'); /// Returns a matcher which matches if the match argument is less /// than or equal to the given [value]. Matcher lessThanOrEqualTo(value) => _OrderingMatcher(value, true, true, false, 'a value less than or equal to'); /// A matcher which matches if the match argument is zero. const Matcher isZero = _OrderingMatcher(0, true, false, false, 'a value equal to'); /// A matcher which matches if the match argument is non-zero. const Matcher isNonZero = _OrderingMatcher(0, false, true, true, 'a value not equal to'); /// A matcher which matches if the match argument is positive. const Matcher isPositive = _OrderingMatcher(0, false, false, true, 'a positive value', false); /// A matcher which matches if the match argument is zero or negative. const Matcher isNonPositive = _OrderingMatcher(0, true, true, false, 'a non-positive value', false); /// A matcher which matches if the match argument is negative. const Matcher isNegative = _OrderingMatcher(0, false, true, false, 'a negative value', false); /// A matcher which matches if the match argument is zero or positive. const Matcher isNonNegative = _OrderingMatcher(0, true, false, true, 'a non-negative value', false); // TODO(kevmoo) Note that matchers that use _OrderingComparison only use // `==` and `<` operators to evaluate the match. Or change the matcher. class _OrderingMatcher extends Matcher { /// Expected value. final Object _value; /// What to return if actual == expected final bool _equalValue; /// What to return if actual < expected final bool _lessThanValue; /// What to return if actual > expected final bool _greaterThanValue; /// Textual name of the inequality final String _comparisonDescription; /// Whether to include the expected value in the description final bool _valueInDescription; const _OrderingMatcher(this._value, this._equalValue, this._lessThanValue, this._greaterThanValue, this._comparisonDescription, [bool valueInDescription = true]) : _valueInDescription = valueInDescription; @override bool matches(item, Map matchState) { if (item == _value) { return _equalValue; } else if (item < _value) { return _lessThanValue; } else if (item > _value) { return _greaterThanValue; } else { return false; } } @override Description describe(Description description) { if (_valueInDescription) { return description .add(_comparisonDescription) .add(' ') .addDescriptionOf(_value); } else { return description.add(_comparisonDescription); } } @override Description describeMismatch( item, Description mismatchDescription, Map matchState, bool verbose) { mismatchDescription.add('is not '); return describe(mismatchDescription); } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher/src/having_matcher.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 'custom_matcher.dart'; import 'interfaces.dart'; import 'type_matcher.dart'; import 'util.dart'; /// A package-private [TypeMatcher] implementation that handles is returned /// by calls to [TypeMatcher.having]. class HavingMatcher<T> implements TypeMatcher<T> { final TypeMatcher<T> _parent; final List<_FunctionMatcher<T>> _functionMatchers; HavingMatcher(TypeMatcher<T> parent, String description, Object Function(T) feature, Object matcher, [Iterable<_FunctionMatcher<T>> existing]) : _parent = parent, _functionMatchers = [ ...?existing, _FunctionMatcher<T>(description, feature, matcher) ]; @override TypeMatcher<T> having( Object Function(T) feature, String description, Object matcher) => HavingMatcher(_parent, description, feature, matcher, _functionMatchers); @override bool matches(item, Map matchState) { for (var matcher in <Matcher>[_parent].followedBy(_functionMatchers)) { if (!matcher.matches(item, matchState)) { addStateInfo(matchState, {'matcher': matcher}); return false; } } return true; } @override Description describeMismatch( item, Description mismatchDescription, Map matchState, bool verbose) { var matcher = matchState['matcher'] as Matcher; matcher.describeMismatch( item, mismatchDescription, matchState['state'] as Map, verbose); return mismatchDescription; } @override Description describe(Description description) => description .add('') .addDescriptionOf(_parent) .add(' with ') .addAll('', ' and ', '', _functionMatchers); } class _FunctionMatcher<T> extends CustomMatcher { final dynamic Function(T value) _feature; _FunctionMatcher(String name, this._feature, matcher) : super('`$name`:', '`$name`', matcher); @override Object featureValueOf(covariant T actual) => _feature(actual); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher/src/type_matcher.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 'having_matcher.dart'; import 'interfaces.dart'; /// Returns a matcher that matches objects with type [T]. /// /// ```dart /// expect(shouldBeDuration, isA<Duration>()); /// ``` /// /// Expectations can be chained on top of the type using the /// [TypeMatcher.having] method to add additional constraints. TypeMatcher<T> isA<T>() => TypeMatcher<T>(); /// A [Matcher] subclass that supports validating the [Type] of the target /// object. /// /// ```dart /// expect(shouldBeDuration, TypeMatcher<Duration>()); /// ``` /// /// If you want to further validate attributes of the specified [Type], use the /// [having] function. /// /// ```dart /// void shouldThrowRangeError(int value) { /// throw RangeError.range(value, 10, 20); /// } /// /// expect( /// () => shouldThrowRangeError(5), /// throwsA(const TypeMatcher<RangeError>() /// .having((e) => e.start, 'start', greaterThanOrEqualTo(10)) /// .having((e) => e.end, 'end', lessThanOrEqualTo(20)))); /// ``` /// /// Notice that you can chain multiple calls to [having] to verify multiple /// aspects of an object. /// /// Note: All of the top-level `isType` matchers exposed by this package are /// instances of [TypeMatcher], so you can use the [having] function without /// creating your own instance. /// /// ```dart /// expect( /// () => shouldThrowRangeError(5), /// throwsA(isRangeError /// .having((e) => e.start, 'start', greaterThanOrEqualTo(10)) /// .having((e) => e.end, 'end', lessThanOrEqualTo(20)))); /// ``` class TypeMatcher<T> extends Matcher { final String _name; /// Create a matcher matches instances of type [T]. /// /// For a fluent API to create TypeMatchers see [isA]. const TypeMatcher( [@Deprecated('Provide a type argument to TypeMatcher and omit the name. ' 'This argument will be removed in the next release.') String name]) : _name = // ignore: deprecated_member_use_from_same_package name; /// Returns a new [TypeMatcher] that validates the existing type as well as /// a specific [feature] of the object with the provided [matcher]. /// /// Provides a human-readable [description] of the [feature] to make debugging /// failures easier. /// /// ```dart /// /// Validates that the object is a [RangeError] with a message containing /// /// the string 'details' and `start` and `end` properties that are `null`. /// final _rangeMatcher = isRangeError /// .having((e) => e.message, 'message', contains('details')) /// .having((e) => e.start, 'start', isNull) /// .having((e) => e.end, 'end', isNull); /// ``` TypeMatcher<T> having( Object Function(T) feature, String description, Object matcher) => HavingMatcher(this, description, feature, matcher); @override Description describe(Description description) { var name = _name ?? _stripDynamic(T); return description.add("<Instance of '$name'>"); } @override Description describeMismatch( item, Description mismatchDescription, Map matchState, bool verbose) { var name = _name ?? _stripDynamic(T); return mismatchDescription.add("is not an instance of '$name'"); } @override bool matches(Object item, Map matchState) => item is T; } final _dart2DynamicArgs = RegExp('<dynamic(, dynamic)*>'); /// With this expression `{}.runtimeType.toString`, /// Dart 1: "<Instance of Map> /// Dart 2: "<Instance of Map<dynamic, dynamic>>" /// /// This functions returns the Dart 1 output, when Dart 2 runtime semantics /// are enabled. String _stripDynamic(Type type) => type.toString().replaceAll(_dart2DynamicArgs, '');
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher/src/core_matchers.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 'feature_matcher.dart'; import 'interfaces.dart'; import 'type_matcher.dart'; import 'util.dart'; /// Returns a matcher that matches the isEmpty property. const Matcher isEmpty = _Empty(); class _Empty extends Matcher { const _Empty(); @override bool matches(item, Map matchState) => item.isEmpty; @override Description describe(Description description) => description.add('empty'); } /// Returns a matcher that matches the isNotEmpty property. const Matcher isNotEmpty = _NotEmpty(); class _NotEmpty extends Matcher { const _NotEmpty(); @override bool matches(item, Map matchState) => item.isNotEmpty; @override Description describe(Description description) => description.add('non-empty'); } /// A matcher that matches any null value. const Matcher isNull = _IsNull(); /// A matcher that matches any non-null value. const Matcher isNotNull = _IsNotNull(); class _IsNull extends Matcher { const _IsNull(); @override bool matches(item, Map matchState) => item == null; @override Description describe(Description description) => description.add('null'); } class _IsNotNull extends Matcher { const _IsNotNull(); @override bool matches(item, Map matchState) => item != null; @override Description describe(Description description) => description.add('not null'); } /// A matcher that matches the Boolean value true. const Matcher isTrue = _IsTrue(); /// A matcher that matches anything except the Boolean value true. const Matcher isFalse = _IsFalse(); class _IsTrue extends Matcher { const _IsTrue(); @override bool matches(item, Map matchState) => item == true; @override Description describe(Description description) => description.add('true'); } class _IsFalse extends Matcher { const _IsFalse(); @override bool matches(item, Map matchState) => item == false; @override Description describe(Description description) => description.add('false'); } /// A matcher that matches the numeric value NaN. const Matcher isNaN = _IsNaN(); /// A matcher that matches any non-NaN value. const Matcher isNotNaN = _IsNotNaN(); class _IsNaN extends FeatureMatcher<num> { const _IsNaN(); @override bool typedMatches(num item, Map matchState) => double.nan.compareTo(item) == 0; @override Description describe(Description description) => description.add('NaN'); } class _IsNotNaN extends FeatureMatcher<num> { const _IsNotNaN(); @override bool typedMatches(num item, Map matchState) => double.nan.compareTo(item) != 0; @override Description describe(Description description) => description.add('not NaN'); } /// Returns a matches that matches if the value is the same instance /// as [expected], using [identical]. Matcher same(expected) => _IsSameAs(expected); class _IsSameAs extends Matcher { final Object _expected; const _IsSameAs(this._expected); @override bool matches(item, Map matchState) => identical(item, _expected); // If all types were hashable we could show a hash here. @override Description describe(Description description) => description.add('same instance as ').addDescriptionOf(_expected); } /// A matcher that matches any value. const Matcher anything = _IsAnything(); class _IsAnything extends Matcher { const _IsAnything(); @override bool matches(item, Map matchState) => true; @override Description describe(Description description) => description.add('anything'); } /// **DEPRECATED** Use [isA] instead. /// /// A matcher that matches if an object is an instance of [T] (or a subtype). @Deprecated('Use `isA<MyType>()` instead.') // ignore: camel_case_types class isInstanceOf<T> extends TypeMatcher<T> { const isInstanceOf(); } /// A matcher that matches a function call against no exception. /// /// The function will be called once. Any exceptions will be silently swallowed. /// The value passed to expect() should be a reference to the function. /// Note that the function cannot take arguments; to handle this /// a wrapper will have to be created. const Matcher returnsNormally = _ReturnsNormally(); class _ReturnsNormally extends FeatureMatcher<Function> { const _ReturnsNormally(); @override bool typedMatches(Function f, Map matchState) { try { f(); return true; } catch (e, s) { addStateInfo(matchState, {'exception': e, 'stack': s}); return false; } } @override Description describe(Description description) => description.add('return normally'); @override Description describeTypedMismatch(Function item, Description mismatchDescription, Map matchState, bool verbose) { mismatchDescription.add('threw ').addDescriptionOf(matchState['exception']); if (verbose) { mismatchDescription.add(' at ').add(matchState['stack'].toString()); } return mismatchDescription; } } /// A matcher for [Map]. const isMap = TypeMatcher<Map>(); /// A matcher for [List]. const isList = TypeMatcher<List>(); /// Returns a matcher that matches if an object has a length property /// that matches [matcher]. Matcher hasLength(matcher) => _HasLength(wrapMatcher(matcher)); class _HasLength extends Matcher { final Matcher _matcher; const _HasLength([Matcher matcher]) : _matcher = matcher; @override bool matches(item, Map matchState) { try { // This is harmless code that will throw if no length property // but subtle enough that an optimizer shouldn't strip it out. if (item.length * item.length >= 0) { return _matcher.matches(item.length, matchState); } } catch (e) { return false; } throw UnsupportedError('Should never get here'); } @override Description describe(Description description) => description.add('an object with length of ').addDescriptionOf(_matcher); @override Description describeMismatch( item, Description mismatchDescription, Map matchState, bool verbose) { try { // We want to generate a different description if there is no length // property; we use the same trick as in matches(). if (item.length * item.length >= 0) { return mismatchDescription .add('has length of ') .addDescriptionOf(item.length); } } catch (e) { return mismatchDescription.add('has no length property'); } throw UnsupportedError('Should never get here'); } } /// Returns a matcher that matches if the match argument contains the expected /// value. /// /// For [String]s this means substring matching; /// for [Map]s it means the map has the key, and for [Iterable]s /// it means the iterable has a matching element. In the case of iterables, /// [expected] can itself be a matcher. Matcher contains(expected) => _Contains(expected); class _Contains extends Matcher { final Object _expected; const _Contains(this._expected); @override bool matches(item, Map matchState) { var expected = _expected; if (item is String) { return expected is Pattern && item.contains(expected); } else if (item is Iterable) { if (expected is Matcher) { return item.any((e) => expected.matches(e, matchState)); } else { return item.contains(_expected); } } else if (item is Map) { return item.containsKey(_expected); } return false; } @override Description describe(Description description) => description.add('contains ').addDescriptionOf(_expected); @override Description describeMismatch( item, Description mismatchDescription, Map matchState, bool verbose) { if (item is String || item is Iterable || item is Map) { return super .describeMismatch(item, mismatchDescription, matchState, verbose); } else { return mismatchDescription.add('is not a string, map or iterable'); } } } /// Returns a matcher that matches if the match argument is in /// the expected value. This is the converse of [contains]. Matcher isIn(expected) { if (expected is Iterable) { return _In(expected, expected.contains); } else if (expected is String) { return _In<Pattern>(expected, expected.contains); } else if (expected is Map) { return _In(expected, expected.containsKey); } throw ArgumentError.value( expected, 'expected', 'Only Iterable, Map, and String are supported.'); } class _In<T> extends FeatureMatcher<T> { final Object _source; final bool Function(T) _containsFunction; const _In(this._source, this._containsFunction); @override bool typedMatches(T item, Map matchState) => _containsFunction(item); @override Description describe(Description description) => description.add('is in ').addDescriptionOf(_source); } /// Returns a matcher that uses an arbitrary function that returns /// true or false for the actual value. /// /// For example: /// /// expect(v, predicate((x) => ((x % 2) == 0), "is even")) Matcher predicate<T>(bool Function(T) f, [String description = 'satisfies function']) => _Predicate(f, description); typedef _PredicateFunction<T> = bool Function(T value); class _Predicate<T> extends FeatureMatcher<T> { final _PredicateFunction<T> _matcher; final String _description; _Predicate(this._matcher, this._description); @override bool typedMatches(T item, Map matchState) => _matcher(item); @override Description describe(Description description) => description.add(_description); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher/src/equals_matcher.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 'feature_matcher.dart'; import 'interfaces.dart'; import 'util.dart'; /// Returns a matcher that matches if the value is structurally equal to /// [expected]. /// /// If [expected] is a [Matcher], then it matches using that. Otherwise it tests /// for equality using `==` on the expected value. /// /// For [Iterable]s and [Map]s, this will recursively match the elements. To /// handle cyclic structures a recursion depth [limit] can be provided. The /// default limit is 100. [Set]s will be compared order-independently. Matcher equals(expected, [int limit = 100]) => expected is String ? _StringEqualsMatcher(expected) : _DeepMatcher(expected, limit); typedef _RecursiveMatcher = _Mismatch Function(dynamic, dynamic, String, int); /// A special equality matcher for strings. class _StringEqualsMatcher extends FeatureMatcher<String> { final String _value; _StringEqualsMatcher(this._value); @override bool typedMatches(String item, Map matchState) => _value == item; @override Description describe(Description description) => description.addDescriptionOf(_value); @override Description describeTypedMismatch(String item, Description mismatchDescription, Map matchState, bool verbose) { var buff = StringBuffer(); buff.write('is different.'); var escapedItem = escape(item); var escapedValue = escape(_value); var minLength = escapedItem.length < escapedValue.length ? escapedItem.length : escapedValue.length; var start = 0; for (; start < minLength; start++) { if (escapedValue.codeUnitAt(start) != escapedItem.codeUnitAt(start)) { break; } } if (start == minLength) { if (escapedValue.length < escapedItem.length) { buff.write(' Both strings start the same, but the actual value also' ' has the following trailing characters: '); _writeTrailing(buff, escapedItem, escapedValue.length); } else { buff.write(' Both strings start the same, but the actual value is' ' missing the following trailing characters: '); _writeTrailing(buff, escapedValue, escapedItem.length); } } else { buff.write('\nExpected: '); _writeLeading(buff, escapedValue, start); _writeTrailing(buff, escapedValue, start); buff.write('\n Actual: '); _writeLeading(buff, escapedItem, start); _writeTrailing(buff, escapedItem, start); buff.write('\n '); for (var i = start > 10 ? 14 : start; i > 0; i--) { buff.write(' '); } buff.write('^\n Differ at offset $start'); } return mismatchDescription.add(buff.toString()); } static void _writeLeading(StringBuffer buff, String s, int start) { if (start > 10) { buff.write('... '); buff.write(s.substring(start - 10, start)); } else { buff.write(s.substring(0, start)); } } static void _writeTrailing(StringBuffer buff, String s, int start) { if (start + 10 > s.length) { buff.write(s.substring(start)); } else { buff.write(s.substring(start, start + 10)); buff.write(' ...'); } } } class _DeepMatcher extends Matcher { final Object _expected; final int _limit; _DeepMatcher(this._expected, [int limit = 1000]) : _limit = limit; _Mismatch _compareIterables(Iterable expected, Object actual, _RecursiveMatcher matcher, int depth, String location) { if (actual is Iterable) { var expectedIterator = expected.iterator; var actualIterator = actual.iterator; for (var index = 0;; index++) { // Advance in lockstep. var expectedNext = expectedIterator.moveNext(); var actualNext = actualIterator.moveNext(); // If we reached the end of both, we succeeded. if (!expectedNext && !actualNext) return null; // Fail if their lengths are different. var newLocation = '$location[$index]'; if (!expectedNext) { return _Mismatch.simple(newLocation, actual, 'longer than expected'); } if (!actualNext) { return _Mismatch.simple(newLocation, actual, 'shorter than expected'); } // Match the elements. var rp = matcher(expectedIterator.current, actualIterator.current, newLocation, depth); if (rp != null) return rp; } } else { return _Mismatch.simple(location, actual, 'is not Iterable'); } } _Mismatch _compareSets(Set expected, Object actual, _RecursiveMatcher matcher, int depth, String location) { if (actual is Iterable) { var other = actual.toSet(); for (var expectedElement in expected) { if (other.every((actualElement) => matcher(expectedElement, actualElement, location, depth) != null)) { return _Mismatch( location, actual, (description, verbose) => description .add('does not contain ') .addDescriptionOf(expectedElement)); } } if (other.length > expected.length) { return _Mismatch.simple(location, actual, 'larger than expected'); } else if (other.length < expected.length) { return _Mismatch.simple(location, actual, 'smaller than expected'); } else { return null; } } else { return _Mismatch.simple(location, actual, 'is not Iterable'); } } _Mismatch _recursiveMatch( Object expected, Object actual, String location, int depth) { // If the expected value is a matcher, try to match it. if (expected is Matcher) { var matchState = {}; if (expected.matches(actual, matchState)) return null; return _Mismatch(location, actual, (description, verbose) { var oldLength = description.length; expected.describeMismatch(actual, description, matchState, verbose); if (depth > 0 && description.length == oldLength) { description.add('does not match '); expected.describe(description); } }); } else { // Otherwise, test for equality. try { if (expected == actual) return null; } catch (e) { // TODO(gram): Add a test for this case. return _Mismatch( location, actual, (description, verbose) => description.add('== threw ').addDescriptionOf(e)); } } if (depth > _limit) { return _Mismatch.simple( location, actual, 'recursion depth limit exceeded'); } // If _limit is 1 we can only recurse one level into object. if (depth == 0 || _limit > 1) { if (expected is Set) { return _compareSets( expected, actual, _recursiveMatch, depth + 1, location); } else if (expected is Iterable) { return _compareIterables( expected, actual, _recursiveMatch, depth + 1, location); } else if (expected is Map) { if (actual is! Map) { return _Mismatch.simple(location, actual, 'expected a map'); } var map = actual as Map; var err = (expected.length == map.length) ? '' : 'has different length and '; for (var key in expected.keys) { if (!map.containsKey(key)) { return _Mismatch( location, actual, (description, verbose) => description .add('${err}is missing map key ') .addDescriptionOf(key)); } } for (var key in map.keys) { if (!expected.containsKey(key)) { return _Mismatch( location, actual, (description, verbose) => description .add('${err}has extra map key ') .addDescriptionOf(key)); } } for (var key in expected.keys) { var rp = _recursiveMatch( expected[key], map[key], "$location['$key']", depth + 1); if (rp != null) return rp; } return null; } } // If we have recursed, show the expected value too; if not, expect() will // show it for us. if (depth > 0) { return _Mismatch(location, actual, (description, verbose) => description.addDescriptionOf(expected), instead: true); } else { return _Mismatch(location, actual, null); } } @override bool matches(Object actual, Map matchState) { var mismatch = _recursiveMatch(_expected, actual, '', 0); if (mismatch == null) return true; addStateInfo(matchState, {'mismatch': mismatch}); return false; } @override Description describe(Description description) => description.addDescriptionOf(_expected); @override Description describeMismatch( item, Description mismatchDescription, Map matchState, bool verbose) { var mismatch = matchState['mismatch'] as _Mismatch; if (mismatch.location.isNotEmpty) { mismatchDescription .add('at location ') .add(mismatch.location) .add(' is ') .addDescriptionOf(mismatch.actual); if (mismatch.describeProblem != null) { mismatchDescription .add(' ${mismatch.instead ? 'instead of' : 'which'} '); mismatch.describeProblem(mismatchDescription, verbose); } } else { // If we didn't get a good reason, that would normally be a // simple 'is <value>' message. We only add that if the mismatch // description is non empty (so we are supplementing the mismatch // description). if (mismatch.describeProblem == null) { if (mismatchDescription.length > 0) { mismatchDescription.add('is ').addDescriptionOf(item); } } else { mismatch.describeProblem(mismatchDescription, verbose); } } return mismatchDescription; } } class _Mismatch { /// A human-readable description of the location within the collection where /// the mismatch occurred. final String location; /// The actual value found at [location]. final Object actual; /// Callback that can create a detailed description of the problem. final void Function(Description, bool verbose) describeProblem; /// If `true`, [describeProblem] describes the expected value, so when the /// final mismatch description is pieced together, it will be preceded by /// `instead of` (e.g. `at location [2] is <3> instead of <4>`). If `false`, /// [describeProblem] is a problem description from a sub-matcher, so when the /// final mismatch description is pieced together, it will be preceded by /// `which` (e.g. `at location [2] is <foo> which has length of 3`). final bool instead; _Mismatch(this.location, this.actual, this.describeProblem, {this.instead = false}); _Mismatch.simple(this.location, this.actual, String problem, {this.instead = false}) : describeProblem = ((description, verbose) => description.add(problem)); }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher/src/error_matchers.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 'type_matcher.dart'; /// A matcher for [ArgumentError]. const isArgumentError = TypeMatcher<ArgumentError>(); /// A matcher for [CastError]. @Deprecated('CastError has been deprecated in favor of TypeError. ' 'Use `isA<TypeError>()` or, if you need compatibility with older SDKs, ' 'use `isA<CastError>()` and ignore the deprecation.') const isCastError = TypeMatcher<CastError>(); /// A matcher for [ConcurrentModificationError]. const isConcurrentModificationError = TypeMatcher<ConcurrentModificationError>(); /// A matcher for [CyclicInitializationError]. const isCyclicInitializationError = TypeMatcher<CyclicInitializationError>(); /// A matcher for [Exception]. const isException = TypeMatcher<Exception>(); /// A matcher for [FormatException]. const isFormatException = TypeMatcher<FormatException>(); /// A matcher for [NoSuchMethodError]. const isNoSuchMethodError = TypeMatcher<NoSuchMethodError>(); /// A matcher for [NullThrownError]. const isNullThrownError = TypeMatcher<NullThrownError>(); /// A matcher for [RangeError]. const isRangeError = TypeMatcher<RangeError>(); /// A matcher for [StateError]. const isStateError = TypeMatcher<StateError>(); /// A matcher for [UnimplementedError]. const isUnimplementedError = TypeMatcher<UnimplementedError>(); /// A matcher for [UnsupportedError]. const isUnsupportedError = TypeMatcher<UnsupportedError>();
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher/src/map_matchers.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 'interfaces.dart'; import 'util.dart'; /// Returns a matcher which matches maps containing the given [value]. Matcher containsValue(value) => _ContainsValue(value); class _ContainsValue extends Matcher { final Object _value; const _ContainsValue(this._value); @override bool matches(item, Map matchState) => item.containsValue(_value); @override Description describe(Description description) => description.add('contains value ').addDescriptionOf(_value); } /// Returns a matcher which matches maps containing the key-value pair /// with [key] => [value]. Matcher containsPair(key, value) => _ContainsMapping(key, wrapMatcher(value)); class _ContainsMapping extends Matcher { final Object _key; final Matcher _valueMatcher; const _ContainsMapping(this._key, this._valueMatcher); @override bool matches(item, Map matchState) => item.containsKey(_key) && _valueMatcher.matches(item[_key], matchState); @override Description describe(Description description) { return description .add('contains pair ') .addDescriptionOf(_key) .add(' => ') .addDescriptionOf(_valueMatcher); } @override Description describeMismatch( item, Description mismatchDescription, Map matchState, bool verbose) { if (!item.containsKey(_key)) { return mismatchDescription .add(" doesn't contain key ") .addDescriptionOf(_key); } else { mismatchDescription .add(' contains key ') .addDescriptionOf(_key) .add(' but with value '); _valueMatcher.describeMismatch( item[_key], mismatchDescription, matchState, verbose); return mismatchDescription; } } }
0
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher
mirrored_repositories/chat_ui_stream_iii_example/firebase/functions/build/packages/matcher/src/interfaces.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. /// Matchers build up their error messages by appending to Description objects. /// /// This interface is implemented by StringDescription. /// /// This interface is unlikely to need other implementations, but could be /// useful to replace in some cases - e.g. language conversion. abstract class Description { int get length; /// Change the value of the description. Description replace(String text); /// This is used to add arbitrary text to the description. Description add(String text); /// This is used to add a meaningful description of a value. Description addDescriptionOf(value); /// This is used to add a description of an [Iterable] [list], /// with appropriate [start] and [end] markers and inter-element [separator]. Description addAll(String start, String separator, String end, Iterable list); } /// The base class for all matchers. /// /// [matches] and [describe] must be implemented by subclasses. /// /// Subclasses can override [describeMismatch] if a more specific description is /// required when the matcher fails. abstract class Matcher { const Matcher(); /// Does the matching of the actual vs expected values. /// /// [item] is the actual value. [matchState] can be supplied /// and may be used to add details about the mismatch that are too /// costly to determine in [describeMismatch]. bool matches(item, Map matchState); /// Builds a textual description of the matcher. Description describe(Description description); /// Builds a textual description of a specific mismatch. /// /// [item] is the value that was tested by [matches]; [matchState] is /// the [Map] that was passed to and supplemented by [matches] /// with additional information about the mismatch, and [mismatchDescription] /// is the [Description] that is being built to describe the mismatch. /// /// A few matchers make use of the [verbose] flag to provide detailed /// information that is not typically included but can be of help in /// diagnosing failures, such as stack traces. Description describeMismatch(item, Description mismatchDescription, Map matchState, bool verbose) => mismatchDescription; }
0