language
stringclasses 1
value | owner
stringlengths 2
15
| repo
stringlengths 2
21
| sha
stringlengths 45
45
| message
stringlengths 7
36.3k
| path
stringlengths 1
199
| patch
stringlengths 15
102k
| is_multipart
bool 2
classes |
---|---|---|---|---|---|---|---|
Other | emberjs | ember.js | 05fc0bbd4112b1151b768a77c3024dc18d294edc.json | Remove some unnecessary uses of Ember.A | packages/@ember/debug/data-adapter.ts | @@ -552,14 +552,14 @@ export default class DataAdapter<T> extends EmberObject {
: this._getObjectsOnNamespaces();
// New adapters return strings instead of classes.
- let klassTypes = emberA(stringTypes).map((name) => {
+ let klassTypes = stringTypes.map((name) => {
return {
klass: this._nameToClass(name),
name,
};
});
- return emberA(klassTypes).filter((type) => this.detect(type.klass));
+ return klassTypes.filter((type) => this.detect(type.klass));
}
/**
@@ -571,8 +571,8 @@ export default class DataAdapter<T> extends EmberObject {
@return {Array} Array of model type strings.
*/
_getObjectsOnNamespaces() {
- let namespaces = emberA(Namespace.NAMESPACES);
- let types = emberA<string>();
+ let namespaces = Namespace.NAMESPACES;
+ let types: string[] = [];
namespaces.forEach((namespace) => {
for (let key in namespace) { | true |
Other | emberjs | ember.js | 720c3021213ff8e530c809d37ec3493899448681.json | Improve types for Ember Arrays | packages/@ember/-internals/glimmer/lib/utils/iterator.ts | @@ -5,6 +5,7 @@ import type { Option } from '@glimmer/interfaces';
import type { IteratorDelegate } from '@glimmer/reference';
import { consumeTag, isTracking, tagFor } from '@glimmer/validator';
import { EachInWrapper } from '../helpers/each-in';
+import type { NativeArray } from '@ember/array';
export default function toIterator(iterable: unknown): Option<IteratorDelegate> {
if (iterable instanceof EachInWrapper) {
@@ -100,11 +101,11 @@ class ArrayIterator extends BoundedIterator {
}
class EmberArrayIterator extends BoundedIterator {
- static from(iterable: EmberArray<unknown>) {
+ static from(iterable: EmberArray<unknown> | NativeArray<unknown>) {
return iterable.length > 0 ? new this(iterable) : null;
}
- constructor(private array: EmberArray<unknown>) {
+ constructor(private array: EmberArray<unknown> | NativeArray<unknown>) {
super(array.length);
}
| true |
Other | emberjs | ember.js | 720c3021213ff8e530c809d37ec3493899448681.json | Improve types for Ember Arrays | packages/@ember/-internals/utils/lib/ember-array.ts | @@ -1,4 +1,4 @@
-import type EmberArray from '@ember/array';
+import type { EmberArrayLike } from '@ember/array';
import { _WeakSet } from '@glimmer/util';
const EMBER_ARRAYS = new _WeakSet();
@@ -7,6 +7,6 @@ export function setEmberArray(obj: object) {
EMBER_ARRAYS.add(obj);
}
-export function isEmberArray(obj: unknown): obj is EmberArray<unknown> {
+export function isEmberArray(obj: unknown): obj is EmberArrayLike<unknown> {
return EMBER_ARRAYS.has(obj as object);
} | true |
Other | emberjs | ember.js | 720c3021213ff8e530c809d37ec3493899448681.json | Improve types for Ember Arrays | packages/@ember/-internals/utils/types.ts | @@ -4,4 +4,10 @@ export type MethodNamesOf<T> = {
[K in keyof T]: T[K] extends AnyFn ? K : never;
}[keyof T];
+export type MethodsOf<O> = Pick<O, MethodNamesOf<O>>;
+
+export type MethodParams<T, M extends MethodNamesOf<T>> = Parameters<MethodsOf<T>[M]>;
+
+export type MethodReturns<T, M extends MethodNamesOf<T>> = ReturnType<MethodsOf<T>[M]>;
+
export type OmitFirst<F> = F extends [any, ...infer R] ? R : []; | true |
Other | emberjs | ember.js | 720c3021213ff8e530c809d37ec3493899448681.json | Improve types for Ember Arrays | packages/@ember/array/index.ts | @@ -20,12 +20,12 @@ import MutableEnumerable from '@ember/enumerable/mutable';
import { compare, typeOf } from '@ember/utils';
import { ENV } from '@ember/-internals/environment';
import Observable from '@ember/object/observable';
-import type { AnyFn } from '@ember/-internals/utils/types';
+import type { MethodNamesOf, MethodParams, MethodReturns } from '@ember/-internals/utils/types';
import type { ComputedPropertyCallback } from '@ember/-internals/metal';
export { makeArray } from '@ember/-internals/utils';
-type Value<T, K extends string> = K extends keyof T ? T[K] : unknown;
+export type EmberArrayLike<T> = EmberArray<T> | NativeArray<T>;
const EMPTY_ARRAY = Object.freeze([] as const);
@@ -319,7 +319,8 @@ interface EmberArray<T> extends Enumerable {
@return this
@public
*/
- '[]': this;
+ get '[]'(): this;
+ set '[]'(newValue: T[] | EmberArray<T>);
/**
The first object in the array, or `undefined` if the array is empty.
@@ -515,7 +516,7 @@ interface EmberArray<T> extends Enumerable {
@return {Array} The mapped array.
@public
*/
- getEach<K extends string>(key: K): NativeArray<Value<T, K>>;
+ getEach<K extends keyof T>(key: K): NativeArray<T[K]>;
/**
Sets the value on the named property for each member. This is more
ergonomic than using other methods defined on this helper. If the object
@@ -535,7 +536,7 @@ interface EmberArray<T> extends Enumerable {
@return {Object} receiver
@public
*/
- setEach<K extends string>(key: K, value: Value<T, K>): this;
+ setEach<K extends keyof T>(key: K, value: T[K]): this;
/**
Maps all of the items in the enumeration to another value, returning
a new array. This method corresponds to `map()` defined in JavaScript 1.6.
@@ -593,7 +594,8 @@ interface EmberArray<T> extends Enumerable {
@return {Array} The mapped array.
@public
*/
- mapBy<K extends string>(key: K): NativeArray<Value<T, K>>;
+ mapBy<K extends keyof T>(key: K): NativeArray<T[K]>;
+ mapBy(key: string): NativeArray<unknown>;
/**
Returns a new array with all of the items in the enumeration that the provided
callback function returns true for. This method corresponds to [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter).
@@ -746,10 +748,6 @@ interface EmberArray<T> extends Enumerable {
@public
*/
rejectBy(key: string, value?: unknown): NativeArray<T>;
- find<S extends T, Target = void>(
- predicate: (this: void, value: T, index: number, obj: T[]) => value is S,
- thisArg?: Target
- ): S | undefined;
/**
Returns the first item in the array for which the callback returns true.
This method is similar to the `find()` method defined in ECMAScript 2015.
@@ -792,6 +790,10 @@ interface EmberArray<T> extends Enumerable {
@return {Object} Found item or `undefined`.
@public
*/
+ find<S extends T, Target = void>(
+ predicate: (this: void, value: T, index: number, obj: T[]) => value is S,
+ thisArg?: Target
+ ): S | undefined;
find<Target = void>(
callback: (this: Target, item: T, index: number, arr: this) => unknown,
target?: Target
@@ -824,7 +826,8 @@ interface EmberArray<T> extends Enumerable {
@return {Object} found item or `undefined`
@public
*/
- findBy<K extends string>(key: K, value?: Value<T, K>): T | undefined;
+ findBy<K extends keyof T>(key: K, value?: T[K]): T | undefined;
+ findBy(key: string, value?: unknown): T | undefined;
/**
Returns `true` if the passed function returns true for every item in the
enumeration. This corresponds with the `Array.prototype.every()` method defined in ES5.
@@ -904,7 +907,8 @@ interface EmberArray<T> extends Enumerable {
@since 1.3.0
@public
*/
- isEvery<K extends string>(key: K, value?: Value<T, K>): boolean;
+ isEvery<K extends keyof T>(key: K, value?: T[K]): boolean;
+ isEvery(key: string, value?: unknown): boolean;
/**
The any() method executes the callback function once for each element
present in the array until it finds the one where callback returns a truthy
@@ -972,7 +976,8 @@ interface EmberArray<T> extends Enumerable {
@since 1.3.0
@public
*/
- isAny<K extends string>(key: K, value?: Value<T, K>): boolean;
+ isAny<K extends keyof T>(key: K, value?: T[K]): boolean;
+ isAny(key: string, value?: unknown): boolean;
/**
This will combine the values of the array into a single value. It
is a useful way to collect a summary value from an array. This
@@ -1061,10 +1066,10 @@ interface EmberArray<T> extends Enumerable {
@return {Array} return values from calling invoke.
@public
*/
- invoke<K extends string>(
- methodName: K,
- ...args: Value<T, K> extends AnyFn ? Parameters<Value<T, K>> : unknown[]
- ): NativeArray<Value<T, K> extends AnyFn ? ReturnType<Value<T, K>> : unknown>;
+ invoke<M extends MethodNamesOf<T>>(
+ methodName: M,
+ ...args: MethodParams<T, M>
+ ): NativeArray<MethodReturns<T, M>>;
/**
Simply converts the object into a genuine array. The order is not
guaranteed. Corresponds to the method implemented by Prototype.
@@ -1086,7 +1091,7 @@ interface EmberArray<T> extends Enumerable {
@return {Array} the array without null and undefined elements.
@public
*/
- compact(): NativeArray<Exclude<T, null>>;
+ compact(): NativeArray<NonNullable<T>>;
/**
Used to determine if the array contains the passed object.
Returns `true` if found, `false` otherwise.
@@ -1176,6 +1181,7 @@ interface EmberArray<T> extends Enumerable {
@public
*/
uniqBy(key: string): NativeArray<T>;
+ uniqBy(callback: (value: T) => unknown): NativeArray<T>;
/**
Returns a new array that excludes the passed value. The default
implementation returns an array regardless of the receiver type.
@@ -1567,7 +1573,7 @@ interface MutableArray<T> extends EmberArray<T>, MutableEnumerable {
@return object same object passed as a param
@public
*/
- pushObject(obj: T): this;
+ pushObject(obj: T): T;
/**
Add the objects in the passed array to the end of the array. Defers
notifying observers of the change until all objects are added.
@@ -1599,7 +1605,7 @@ interface MutableArray<T> extends EmberArray<T>, MutableEnumerable {
@return object
@public
*/
- popObject(): T | undefined;
+ popObject(): T | null | undefined;
/**
Shift an object from start of array or nil if none are left. Works just
like `shift()` but it is KVO-compliant.
@@ -1632,7 +1638,7 @@ interface MutableArray<T> extends EmberArray<T>, MutableEnumerable {
@return object same object passed as a param
@public
*/
- unshiftObject(object: T): this;
+ unshiftObject(object: T): T;
/**
Adds the named objects to the beginning of the array. Defers notifying
observers until all objects have been added.
@@ -1892,6 +1898,167 @@ const MutableArray = Mixin.create(EmberArray, MutableEnumerable, {
/**
@module ember
*/
+
+type AnyArray<T> = EmberArray<T> | Array<T>;
+
+/**
+ * The final definition of NativeArray removes all native methods. This is the list of removed methods
+ * when run in Chrome 106.
+ */
+type IGNORED_MUTABLE_ARRAY_METHODS =
+ | 'length'
+ | 'slice'
+ | 'indexOf'
+ | 'lastIndexOf'
+ | 'forEach'
+ | 'map'
+ | 'filter'
+ | 'find'
+ | 'every'
+ | 'reduce'
+ | 'includes';
+
+/**
+ * These additional items must be redefined since `Omit` causes methods that return `this` to return the
+ * type at the time of the Omit.
+ */
+type RETURN_SELF_ARRAY_METHODS =
+ | '[]'
+ | 'clear'
+ | 'insertAt'
+ | 'removeAt'
+ | 'pushObjects'
+ | 'unshiftObjects'
+ | 'reverseObjects'
+ | 'setObjects'
+ | 'removeObject'
+ | 'removeObjects'
+ | 'addObject'
+ | 'addObjects'
+ | 'setEach';
+
+// This is the same as MutableArray, but removes the actual native methods that exist on Array.prototype.
+interface MutableArrayWithoutNative<T>
+ extends Omit<MutableArray<T>, IGNORED_MUTABLE_ARRAY_METHODS | RETURN_SELF_ARRAY_METHODS> {
+ /**
+ * Remove all elements from the array. This is useful if you
+ * want to reuse an existing array without having to recreate it.
+ */
+ clear(): this;
+ /**
+ * This will use the primitive `replace()` method to insert an object at the
+ * specified index.
+ */
+ insertAt(idx: number, object: T): this;
+ /**
+ * Remove an object at the specified index using the `replace()` primitive
+ * method. You can pass either a single index, or a start and a length.
+ */
+ removeAt(start: number, len?: number): this;
+ /**
+ * Add the objects in the passed numerable to the end of the array. Defers
+ * notifying observers of the change until all objects are added.
+ */
+ pushObjects(objects: AnyArray<T>): this;
+ /**
+ * Adds the named objects to the beginning of the array. Defers notifying
+ * observers until all objects have been added.
+ */
+ unshiftObjects(objects: AnyArray<T>): this;
+ /**
+ * Reverse objects in the array. Works just like `reverse()` but it is
+ * KVO-compliant.
+ */
+ reverseObjects(): this;
+ /**
+ * Replace all the receiver's content with content of the argument.
+ * If argument is an empty array receiver will be cleared.
+ */
+ setObjects(objects: AnyArray<T>): this;
+ /**
+ Remove all occurrences of an object in the array.
+
+ ```javascript
+ let cities = ['Chicago', 'Berlin', 'Lima', 'Chicago'];
+
+ cities.removeObject('Chicago'); // ['Berlin', 'Lima']
+ cities.removeObject('Lima'); // ['Berlin']
+ cities.removeObject('Tokyo') // ['Berlin']
+ ```
+
+ @method removeObject
+ @param {*} obj object to remove
+ @return {EmberArray} receiver
+ @public
+ */
+ removeObject(object: T): this;
+ /**
+ * Removes each object in the passed array from the receiver.
+ */
+ removeObjects(objects: AnyArray<T>): this;
+ /**
+ Push the object onto the end of the array if it is not already
+ present in the array.
+
+ ```javascript
+ let cities = ['Chicago', 'Berlin'];
+
+ cities.addObject('Lima'); // ['Chicago', 'Berlin', 'Lima']
+ cities.addObject('Berlin'); // ['Chicago', 'Berlin', 'Lima']
+ ```
+
+ @method addObject
+ @param {*} obj object to add, if not already present
+ @return {EmberArray} receiver
+ @public
+ */
+ addObject(obj: T): this;
+ /**
+ * Adds each object in the passed enumerable to the receiver.
+ */
+ addObjects(objects: AnyArray<T>): this;
+ /**
+ Sets the value on the named property for each member. This is more
+ ergonomic than using other methods defined on this helper. If the object
+ implements Observable, the value will be changed to `set(),` otherwise
+ it will be set directly. `null` objects are skipped.
+
+ ```javascript
+ let people = [{name: 'Joe'}, {name: 'Matt'}];
+
+ people.setEach('zipCode', '10011');
+ // [{name: 'Joe', zipCode: '10011'}, {name: 'Matt', zipCode: '10011'}];
+ ```
+
+ @method setEach
+ @param {String} key The key to set
+ @param {Object} value The object to set
+ @return {Object} receiver
+ @public
+ */
+ setEach<K extends keyof T>(key: K, value: T[K]): this;
+ /**
+ This is the handler for the special array content property. If you get
+ this property, it will return this. If you set this property to a new
+ array, it will replace the current content.
+
+ ```javascript
+ let peopleToMoon = ['Armstrong', 'Aldrin'];
+
+ peopleToMoon.get('[]'); // ['Armstrong', 'Aldrin']
+
+ peopleToMoon.set('[]', ['Collins']); // ['Collins']
+ peopleToMoon.get('[]'); // ['Collins']
+ ```
+
+ @property []
+ @return this
+ @public
+ */
+ get '[]'(): this;
+ set '[]'(newValue: T[] | this);
+}
+
/**
The NativeArray mixin contains the properties needed to make the native
Array support MutableArray and all of its dependent APIs. Unless you
@@ -1904,10 +2071,7 @@ const MutableArray = Mixin.create(EmberArray, MutableEnumerable, {
@uses Observable
@public
*/
-interface NativeArray<T>
- extends Omit<Array<T>, 'every' | 'filter' | 'find' | 'forEach' | 'map' | 'reduce' | 'slice'>,
- MutableArray<T>,
- Observable {}
+interface NativeArray<T> extends Array<T>, Observable, MutableArrayWithoutNative<T> {}
let NativeArray = Mixin.create(MutableArray, Observable, {
objectAt(idx: number) { | true |
Other | emberjs | ember.js | 720c3021213ff8e530c809d37ec3493899448681.json | Improve types for Ember Arrays | packages/@ember/array/type-tests/index.ts | @@ -25,8 +25,11 @@ class Target {
let target = new Target();
-expectTypeOf(arr).toMatchTypeOf<EmberArray<Foo>>();
-expectTypeOf(arr).toMatchTypeOf<MutableArray<Foo>>();
+// NativeArray does not exactly extend the interface of EmberArray and MutableArray,
+// since native methods are not overwritten.
+expectTypeOf(arr).not.toMatchTypeOf<EmberArray<Foo>>();
+expectTypeOf(arr).not.toMatchTypeOf<MutableArray<Foo>>();
+
expectTypeOf(arr).toEqualTypeOf<NativeArray<Foo>>();
expectTypeOf(arr.length).toEqualTypeOf<number>();
@@ -37,9 +40,9 @@ expectTypeOf(arr.firstObject).toEqualTypeOf<Foo | undefined>();
expectTypeOf(arr.lastObject).toEqualTypeOf<Foo | undefined>();
-expectTypeOf(arr.slice()).toEqualTypeOf<NativeArray<Foo>>();
-expectTypeOf(arr.slice(1)).toEqualTypeOf<NativeArray<Foo>>();
-expectTypeOf(arr.slice(1, 2)).toEqualTypeOf<NativeArray<Foo>>();
+expectTypeOf(arr.slice()).toEqualTypeOf<Foo[]>();
+expectTypeOf(arr.slice(1)).toEqualTypeOf<Foo[]>();
+expectTypeOf(arr.slice(1, 2)).toEqualTypeOf<Foo[]>();
expectTypeOf(arr.indexOf(new Foo())).toEqualTypeOf<number>();
// @ts-expect-error checks param type
@@ -49,7 +52,7 @@ expectTypeOf(arr.lastIndexOf(new Foo())).toEqualTypeOf<number>();
// @ts-expect-error checks param type
arr.lastIndexOf('invalid');
-expectTypeOf(arr.forEach((item: Foo) => String(item))).toEqualTypeOf(arr);
+expectTypeOf(arr.forEach((item: Foo) => String(item))).toEqualTypeOf<void>();
arr.forEach((item, index, arr) => {
expectTypeOf(this).toEqualTypeOf<undefined>();
@@ -58,29 +61,30 @@ arr.forEach((item, index, arr) => {
expectTypeOf(arr).toEqualTypeOf(arr);
});
arr.forEach(function (_item) {
- expectTypeOf(this).toEqualTypeOf(target);
+ // No-op
}, target);
expectTypeOf(arr.getEach('bar')).toEqualTypeOf<NativeArray<number>>();
-expectTypeOf(arr.getEach('missing')).toEqualTypeOf<NativeArray<unknown>>();
+// @ts-expect-error Unknown property
+arr.getEach('missing');
expectTypeOf(arr.setEach('bar', 2)).toEqualTypeOf(arr);
-// @ts-expect-error string is not assignable to bar
+// @ts-expect-error Invalid value
arr.setEach('bar', 'string');
-// Can set unknown property
-expectTypeOf(arr.setEach('missing', 'anything')).toEqualTypeOf(arr);
+// @ts-expect-error Unknown property
+arr.setEach('missing', 'anything');
let mapped = arr.map((item, index, arr) => {
expectTypeOf(item).toEqualTypeOf<Foo>();
expectTypeOf(index).toEqualTypeOf<number>();
expectTypeOf(arr).toEqualTypeOf(arr);
return 1;
});
-expectTypeOf(mapped).toEqualTypeOf<NativeArray<number>>();
+expectTypeOf(mapped).toEqualTypeOf<number[]>();
arr.map(function (_item) {
- expectTypeOf(this).toEqualTypeOf(target);
+ return true;
}, target);
expectTypeOf(arr.mapBy('bar')).toEqualTypeOf<NativeArray<number>>();
@@ -92,9 +96,8 @@ let filtered = arr.filter((item, index, arr) => {
expectTypeOf(arr).toEqualTypeOf(arr);
return true;
});
-expectTypeOf(filtered).toEqualTypeOf<NativeArray<Foo>>();
+expectTypeOf(filtered).toEqualTypeOf<Foo[]>();
arr.filter(function (_item) {
- expectTypeOf(this).toEqualTypeOf(target);
return true;
}, target);
@@ -118,9 +121,11 @@ expectTypeOf(arr.rejectBy('missing')).toEqualTypeOf<NativeArray<Foo>>();
expectTypeOf(arr.findBy('bar')).toEqualTypeOf<Foo | undefined>();
arr.findBy('bar', 1);
-// @ts-expect-error value has incorrect type
+// TODO: Ideally we'd mark the value as being invalid
arr.findBy('bar', 'invalid');
-arr.findBy('missing', 'whatever');
+// Allows any value to be passed to an unkown property
+expectTypeOf(arr.findBy('missing', 'whatever')).toEqualTypeOf<Foo | undefined>();
+expectTypeOf(arr.findBy('bar')).toEqualTypeOf<Foo | undefined>();
let isEvery = arr.every((item, index, arr) => {
expectTypeOf(item).toEqualTypeOf<Foo>();
@@ -130,15 +135,15 @@ let isEvery = arr.every((item, index, arr) => {
});
expectTypeOf(isEvery).toEqualTypeOf<boolean>();
arr.every(function (_item) {
- expectTypeOf(this).toEqualTypeOf(target);
return true;
}, target);
expectTypeOf(arr.isEvery('bar')).toEqualTypeOf<boolean>();
arr.isEvery('bar', 1);
-// @ts-expect-error value has incorrect type
+// TODO: Ideally we'd mark the value as being invalid
arr.isEvery('bar', 'invalid');
-arr.isEvery('missing', 'whatever');
+// Allows any value to be passed to an unknown property
+expectTypeOf(arr.isEvery('missing', 'whatever')).toEqualTypeOf<boolean>();
let isAny = arr.any((item, index, arr) => {
expectTypeOf(item).toEqualTypeOf<Foo>();
@@ -154,9 +159,10 @@ arr.any(function (_item) {
expectTypeOf(arr.isAny('bar')).toEqualTypeOf<boolean>();
arr.isAny('bar', 1);
-// @ts-expect-error value has incorrect type
+// TODO: Ideally we'd mark the value as being invalid
arr.isAny('bar', 'invalid');
-arr.isAny('missing', 'whatever');
+// Allows any value to be passed to an unknown property
+expectTypeOf(arr.isAny('missing', 'whatever')).toEqualTypeOf<boolean>();
let reduced = arr.reduce((summation, item, index, arr) => {
expectTypeOf(summation).toEqualTypeOf<number>();
@@ -166,16 +172,14 @@ let reduced = arr.reduce((summation, item, index, arr) => {
return 1;
}, 1);
expectTypeOf(reduced).toEqualTypeOf<number>();
-// NOTE: This doesn't match native behavior and is a bit weird
-expectTypeOf(arr.reduce((summation, _item) => summation)).toEqualTypeOf<unknown>();
+expectTypeOf(arr.reduce((summation, _item) => summation)).toEqualTypeOf<Foo>();
expectTypeOf(arr.invoke('hi')).toEqualTypeOf<NativeArray<string>>();
expectTypeOf(arr.invoke('withArgs', 1, 'two')).toEqualTypeOf<NativeArray<string>>();
// @ts-expect-error Doesn't allow calling with invalid args
arr.invoke('withArgs', 'invalid');
-expectTypeOf(arr.invoke('missing')).toEqualTypeOf<NativeArray<unknown>>();
-// Currently, args passed to unrecognized methods are ignored
-arr.invoke('missing', 'invalid');
+// @ts-expect-error Doesn't allow calling with invalid method
+arr.invoke('missing');
expectTypeOf(arr.toArray()).toEqualTypeOf<Foo[]>();
| true |
Other | emberjs | ember.js | 720c3021213ff8e530c809d37ec3493899448681.json | Improve types for Ember Arrays | packages/@ember/array/type-tests/mutable.ts | @@ -1,63 +1,67 @@
-import type MutableArray from '@ember/array/mutable';
-import { A } from '@ember/array';
+import MutableArray from '@ember/array/mutable';
import { expectTypeOf } from 'expect-type';
-class Foo {}
+class Foo {
+ constructor(public name: string) {}
+}
-let foo = new Foo();
+let foo = new Foo('test');
-let arr = A([foo]);
+let originalArr = [foo];
+// This is not really the ideal way to set things up.
+MutableArray.apply(originalArr);
+let arr = originalArr as unknown as MutableArray<Foo>;
expectTypeOf(arr).toMatchTypeOf<MutableArray<Foo>>();
expectTypeOf(arr.replace(1, 1, [foo])).toEqualTypeOf<void>();
-// TODO: Why doesn't this fail?
+// @ts-expect-error invalid item
arr.replace(1, 1, ['invalid']);
expectTypeOf(arr.clear()).toEqualTypeOf(arr);
expectTypeOf(arr.insertAt(1, foo)).toEqualTypeOf(arr);
-// TODO: Why doesn't this fail?
+// @ts-expect-error invalid item
arr.insertAt(1, 'invalid');
expectTypeOf(arr.removeAt(1, 1)).toEqualTypeOf(arr);
-expectTypeOf(arr.pushObject(foo)).toEqualTypeOf(arr);
-// TODO: Why doesn't this fail?
+expectTypeOf(arr.pushObject(foo)).toEqualTypeOf(foo);
+// @ts-expect-error invalid item
arr.pushObject('invalid');
expectTypeOf(arr.pushObjects([foo])).toEqualTypeOf(arr);
-// TODO: Why doesn't this fail?
+// @ts-expect-error invalid item
arr.pushObjects(['invalid']);
-expectTypeOf(arr.popObject()).toEqualTypeOf<Foo | undefined>();
+expectTypeOf(arr.popObject()).toEqualTypeOf<Foo | null | undefined>();
expectTypeOf(arr.shiftObject()).toEqualTypeOf<Foo | null | undefined>();
-expectTypeOf(arr.unshiftObject(foo)).toEqualTypeOf(arr);
-// TODO: Why doesn't this fail?
+expectTypeOf(arr.unshiftObject(foo)).toEqualTypeOf(foo);
+// @ts-expect-error invalid item
arr.unshiftObject('invalid');
expectTypeOf(arr.unshiftObjects([foo])).toEqualTypeOf(arr);
-// TODO: Why doesn't this fail?
+// @ts-expect-error invalid item
arr.unshiftObjects(['invalid']);
expectTypeOf(arr.reverseObjects()).toEqualTypeOf(arr);
expectTypeOf(arr.setObjects([foo])).toEqualTypeOf(arr);
-// TODO: Why doesn't this fail?
+// @ts-expect-error invalid item
arr.setObjects(['invalid']);
expectTypeOf(arr.removeObject(foo)).toEqualTypeOf(arr);
-// TODO: Why doesn't this fail?
+// @ts-expect-error invalid item
arr.removeObject('invalid');
expectTypeOf(arr.addObject(foo)).toEqualTypeOf(arr);
-// TODO: Why doesn't this fail?
+// @ts-expect-error invalid item
arr.addObject('invalid');
expectTypeOf(arr.addObjects([foo])).toEqualTypeOf(arr);
-// TODO: Why doesn't this fail?
+// @ts-expect-error invalid item
arr.addObjects(['invalid']); | true |
Other | emberjs | ember.js | 720c3021213ff8e530c809d37ec3493899448681.json | Improve types for Ember Arrays | packages/@ember/debug/data-adapter.ts | @@ -544,7 +544,7 @@ export default class DataAdapter<T> extends EmberObject {
@method getModelTypes
@return {Array} Array of model types.
*/
- getModelTypes(): NativeArray<{ klass: unknown; name: string }> {
+ getModelTypes(): Array<{ klass: unknown; name: string }> {
let containerDebugAdapter = this.containerDebugAdapter;
let stringTypes = containerDebugAdapter.canCatalogEntriesByType('model') | true |
Other | emberjs | ember.js | 720c3021213ff8e530c809d37ec3493899448681.json | Improve types for Ember Arrays | type-tests/preview/@ember/array-test/array.ts | @@ -3,6 +3,7 @@ import type Array from '@ember/array';
import { A } from '@ember/array';
import type MutableArray from '@ember/array/mutable';
import { expectTypeOf } from 'expect-type';
+import NativeArray from '@ember/array/-private/native-array';
class Person extends EmberObject {
name = '';
@@ -19,20 +20,18 @@ expectTypeOf(people.get('lastObject')).toEqualTypeOf<Person | undefined>();
expectTypeOf(people.get('firstObject')).toEqualTypeOf<Person | undefined>();
expectTypeOf(people.isAny('isHappy')).toBeBoolean();
expectTypeOf(people.isAny('isHappy', false)).toBeBoolean();
-// @ts-expect-error -- string != boolean
+// TODO: Ideally we'd mark the value as being invalid
people.isAny('isHappy', 'false');
expectTypeOf(people.objectAt(0)).toEqualTypeOf<Person | undefined>();
expectTypeOf(people.objectsAt([1, 2, 3])).toEqualTypeOf<Array<Person | undefined>>();
expectTypeOf(people.filterBy('isHappy')).toMatchTypeOf<Person[]>();
-expectTypeOf(people.filterBy('isHappy')).toMatchTypeOf<MutableArray<Person>>();
+expectTypeOf(people.filterBy('isHappy')).toMatchTypeOf<NativeArray<Person>>();
expectTypeOf(people.rejectBy('isHappy')).toMatchTypeOf<Person[]>();
-expectTypeOf(people.rejectBy('isHappy')).toMatchTypeOf<MutableArray<Person>>();
+expectTypeOf(people.rejectBy('isHappy')).toMatchTypeOf<NativeArray<Person>>();
+expectTypeOf(people.filter((person) => person.get('name') === 'Yehuda')).toMatchTypeOf<Person[]>();
expectTypeOf(people.filter((person) => person.get('name') === 'Yehuda')).toMatchTypeOf<Person[]>();
-expectTypeOf(people.filter((person) => person.get('name') === 'Yehuda')).toMatchTypeOf<
- MutableArray<Person>
->();
expectTypeOf(people.get('[]')).toEqualTypeOf<typeof people>();
expectTypeOf(people.get('[]').get('firstObject')).toEqualTypeOf<Person | undefined>(); | true |
Other | emberjs | ember.js | 720c3021213ff8e530c809d37ec3493899448681.json | Improve types for Ember Arrays | type-tests/preview/ember/array.ts | @@ -16,20 +16,18 @@ expectTypeOf(people.get('lastObject')).toEqualTypeOf<Person | undefined>();
expectTypeOf(people.get('firstObject')).toEqualTypeOf<Person | undefined>();
expectTypeOf(people.isAny('isHappy')).toBeBoolean();
expectTypeOf(people.isAny('isHappy', false)).toBeBoolean();
-// @ts-expect-error
+// TODO: Ideally we'd mark the value as being invalid
people.isAny('isHappy', 'false');
expectTypeOf(people.objectAt(0)).toEqualTypeOf<Person | undefined>();
expectTypeOf(people.objectsAt([1, 2, 3])).toEqualTypeOf<Ember.Array<Person | undefined>>();
expectTypeOf(people.filterBy('isHappy')).toMatchTypeOf<Person[]>();
-expectTypeOf(people.filterBy('isHappy')).toMatchTypeOf<Ember.MutableArray<Person>>();
+expectTypeOf(people.filterBy('isHappy')).toMatchTypeOf<Ember.NativeArray<Person>>();
expectTypeOf(people.rejectBy('isHappy')).toMatchTypeOf<Person[]>();
-expectTypeOf(people.rejectBy('isHappy')).toMatchTypeOf<Ember.MutableArray<Person>>();
+expectTypeOf(people.rejectBy('isHappy')).toMatchTypeOf<Ember.NativeArray<Person>>();
+expectTypeOf(people.filter((person) => person.get('name') === 'Yehuda')).toMatchTypeOf<Person[]>();
expectTypeOf(people.filter((person) => person.get('name') === 'Yehuda')).toMatchTypeOf<Person[]>();
-expectTypeOf(people.filter((person) => person.get('name') === 'Yehuda')).toMatchTypeOf<
- Ember.MutableArray<Person>
->();
expectTypeOf(people.get('[]')).toEqualTypeOf<typeof people>();
expectTypeOf(people.get('[]').get('firstObject')).toEqualTypeOf<Person | undefined>();
@@ -48,15 +46,14 @@ if (first) {
expectTypeOf(first.get('isHappy')).toBeBoolean();
}
-const letters: Ember.Array<string> = Ember.A(['a', 'b', 'c']);
+const letters: Ember.NativeArray<string> = Ember.A(['a', 'b', 'c']);
const codes = letters.map((item, index, array) => {
expectTypeOf(item).toBeString();
expectTypeOf(index).toBeNumber();
- expectTypeOf(array).toEqualTypeOf<Ember.Array<string>>();
+ expectTypeOf(array).toEqualTypeOf<string[]>();
return item.charCodeAt(0);
});
-expectTypeOf(codes).toMatchTypeOf<number[]>();
-expectTypeOf(codes).toEqualTypeOf<Ember.NativeArray<number>>();
+expectTypeOf(codes).toEqualTypeOf<number[]>();
const value = '1,2,3';
const filters = Ember.A(value.split(',')); | true |
Other | emberjs | ember.js | 720c3021213ff8e530c809d37ec3493899448681.json | Improve types for Ember Arrays | type-tests/preview/ember/ember-module-tests.ts | @@ -153,7 +153,7 @@ expectTypeOf(Ember.Application.create()).toEqualTypeOf<Ember.Application>();
expectTypeOf(new Ember.ApplicationInstance()).toEqualTypeOf<Ember.ApplicationInstance>();
expectTypeOf(Ember.ApplicationInstance.create()).toEqualTypeOf<Ember.ApplicationInstance>();
// Ember.Array
-const a1: Ember.Array<string> = Ember.A([]);
+const a1: Ember.NativeArray<string> = Ember.A([]);
// @ts-expect-error
const a2: Ember.Array<string> = {};
// Ember.ArrayProxy
@@ -232,13 +232,13 @@ class UsesMixin extends Ember.Object {
}
}
// Ember.MutableArray
-const ma1: Ember.MutableArray<string> = Ember.A(['money', 'in', 'the', 'bananna', 'stand']);
-expectTypeOf(ma1.addObject('!')).toBeString();
-// @ts-expect-error
+const ma1: Ember.NativeArray<string> = Ember.A(['money', 'in', 'the', 'bananna', 'stand']);
+expectTypeOf(ma1.addObject('!')).toMatchTypeOf(ma1);
+// TODO: Ideally we'd mark the value as being invalid
ma1.filterBy('');
expectTypeOf(ma1.firstObject).toEqualTypeOf<string | undefined>();
expectTypeOf(ma1.lastObject).toEqualTypeOf<string | undefined>();
-const ma2: Ember.MutableArray<{ name: string }> = Ember.A([
+const ma2: Ember.NativeArray<{ name: string }> = Ember.A([
{ name: 'chris' },
{ name: 'dan' },
{ name: 'james' }, | true |
Other | emberjs | ember.js | 720c3021213ff8e530c809d37ec3493899448681.json | Improve types for Ember Arrays | type-tests/preview/ember/ember-tests.ts | @@ -112,14 +112,13 @@ people.invoke('sayHello');
// @ts-expect-error
people.invoke('name');
-type Arr = Ember.NativeArray<
- Ember.Object & {
- name?: string;
- }
->;
-const arr: Arr = Ember.A([Ember.Object.create(), Ember.Object.create()]);
-expectTypeOf(arr.setEach('name', 'unknown')).toEqualTypeOf<void>();
-expectTypeOf(arr.setEach('name', undefined)).toEqualTypeOf<void>();
+class Obj extends Ember.Object {
+ name?: string;
+}
+
+const arr: Ember.NativeArray<Obj> = Ember.A([Ember.Object.create(), Ember.Object.create()]);
+expectTypeOf(arr.setEach('name', 'unknown')).toEqualTypeOf(arr);
+expectTypeOf(arr.setEach('name', undefined)).toEqualTypeOf(arr);
expectTypeOf(arr.getEach('name')).toEqualTypeOf<Ember.NativeArray<string | undefined>>();
// @ts-expect-error
arr.setEach('age', 123);
@@ -141,7 +140,7 @@ people2.every(isHappy);
people2.any(isHappy);
people2.isEvery('isHappy');
people2.isEvery('isHappy', true);
-// @ts-expect-error
+// TODO: Ideally we'd mark the value as being invalid
people2.isAny('isHappy', 'true');
people2.isAny('isHappy', true);
people2.isAny('isHappy'); | true |
Other | emberjs | ember.js | 720c3021213ff8e530c809d37ec3493899448681.json | Improve types for Ember Arrays | types/preview/@ember/array/-private/native-array.d.ts | @@ -1,22 +1,180 @@
declare module '@ember/array/-private/native-array' {
import Observable from '@ember/object/observable';
+ import EmberArray from '@ember/array';
import MutableArray from '@ember/array/mutable';
import Mixin from '@ember/object/mixin';
// Get an alias to the global Array type to use in inner scope below.
type Array<T> = T[];
+ type AnyArray<T> = EmberArray<T> | Array<T>;
+
+ /**
+ * The final definition of NativeArray removes all native methods. This is the list of removed methods
+ * when run in Chrome 106.
+ */
+ type IGNORED_MUTABLE_ARRAY_METHODS =
+ | 'length'
+ | 'slice'
+ | 'indexOf'
+ | 'lastIndexOf'
+ | 'forEach'
+ | 'map'
+ | 'filter'
+ | 'find'
+ | 'every'
+ | 'reduce'
+ | 'includes';
+
+ /**
+ * These additional items must be redefined since `Omit` causes methods that return `this` to return the
+ * type at the time of the Omit.
+ */
+ type RETURN_SELF_ARRAY_METHODS =
+ | '[]'
+ | 'clear'
+ | 'insertAt'
+ | 'removeAt'
+ | 'pushObjects'
+ | 'unshiftObjects'
+ | 'reverseObjects'
+ | 'setObjects'
+ | 'removeObject'
+ | 'removeObjects'
+ | 'addObject'
+ | 'addObjects'
+ | 'setEach';
+
+ // This is the same as MutableArray, but removes the actual native methods that exist on Array.prototype.
+ interface MutableArrayWithoutNative<T>
+ extends Omit<MutableArray<T>, IGNORED_MUTABLE_ARRAY_METHODS | RETURN_SELF_ARRAY_METHODS> {
+ /**
+ * Remove all elements from the array. This is useful if you
+ * want to reuse an existing array without having to recreate it.
+ */
+ clear(): this;
+ /**
+ * This will use the primitive `replace()` method to insert an object at the
+ * specified index.
+ */
+ insertAt(idx: number, object: T): this;
+ /**
+ * Remove an object at the specified index using the `replace()` primitive
+ * method. You can pass either a single index, or a start and a length.
+ */
+ removeAt(start: number, len?: number): this;
+ /**
+ * Add the objects in the passed numerable to the end of the array. Defers
+ * notifying observers of the change until all objects are added.
+ */
+ pushObjects(objects: AnyArray<T>): this;
+ /**
+ * Adds the named objects to the beginning of the array. Defers notifying
+ * observers until all objects have been added.
+ */
+ unshiftObjects(objects: AnyArray<T>): this;
+ /**
+ * Reverse objects in the array. Works just like `reverse()` but it is
+ * KVO-compliant.
+ */
+ reverseObjects(): this;
+ /**
+ * Replace all the receiver's content with content of the argument.
+ * If argument is an empty array receiver will be cleared.
+ */
+ setObjects(objects: AnyArray<T>): this;
+ /**
+ Remove all occurrences of an object in the array.
+
+ ```javascript
+ let cities = ['Chicago', 'Berlin', 'Lima', 'Chicago'];
+
+ cities.removeObject('Chicago'); // ['Berlin', 'Lima']
+ cities.removeObject('Lima'); // ['Berlin']
+ cities.removeObject('Tokyo') // ['Berlin']
+ ```
+
+ @method removeObject
+ @param {*} obj object to remove
+ @return {EmberArray} receiver
+ @public
+ */
+ removeObject(object: T): this;
+ /**
+ * Removes each object in the passed array from the receiver.
+ */
+ removeObjects(objects: AnyArray<T>): this;
+ /**
+ Push the object onto the end of the array if it is not already
+ present in the array.
+
+ ```javascript
+ let cities = ['Chicago', 'Berlin'];
+
+ cities.addObject('Lima'); // ['Chicago', 'Berlin', 'Lima']
+ cities.addObject('Berlin'); // ['Chicago', 'Berlin', 'Lima']
+ ```
+
+ @method addObject
+ @param {*} obj object to add, if not already present
+ @return {EmberArray} receiver
+ @public
+ */
+ addObject(obj: T): this;
+ /**
+ * Adds each object in the passed enumerable to the receiver.
+ */
+ addObjects(objects: AnyArray<T>): this;
+ /**
+ Sets the value on the named property for each member. This is more
+ ergonomic than using other methods defined on this helper. If the object
+ implements Observable, the value will be changed to `set(),` otherwise
+ it will be set directly. `null` objects are skipped.
+
+ ```javascript
+ let people = [{name: 'Joe'}, {name: 'Matt'}];
+
+ people.setEach('zipCode', '10011');
+ // [{name: 'Joe', zipCode: '10011'}, {name: 'Matt', zipCode: '10011'}];
+ ```
+
+ @method setEach
+ @param {String} key The key to set
+ @param {Object} value The object to set
+ @return {Object} receiver
+ @public
+ */
+ setEach<K extends keyof T>(key: K, value: T[K]): this;
+ /**
+ This is the handler for the special array content property. If you get
+ this property, it will return this. If you set this property to a new
+ array, it will replace the current content.
+
+ ```javascript
+ let peopleToMoon = ['Armstrong', 'Aldrin'];
+
+ peopleToMoon.get('[]'); // ['Armstrong', 'Aldrin']
+
+ peopleToMoon.set('[]', ['Collins']); // ['Collins']
+ peopleToMoon.get('[]'); // ['Collins']
+ ```
+
+ @property []
+ @return this
+ @public
+ */
+ get '[]'(): this;
+ set '[]'(newValue: T[] | this);
+ }
+
/**
* The NativeArray mixin contains the properties needed to make the native
* Array support Ember.MutableArray and all of its dependent APIs. Unless you
* have `EmberENV.EXTEND_PROTOTYPES` or `EmberENV.EXTEND_PROTOTYPES.Array` set to
* false, this will be applied automatically. Otherwise you can apply the mixin
* at anytime by calling `Ember.NativeArray.apply(Array.prototype)`.
*/
- interface NativeArray<T>
- extends Omit<Array<T>, 'every' | 'filter' | 'find' | 'forEach' | 'map' | 'reduce' | 'slice'>,
- Observable,
- MutableArray<T> {}
+ interface NativeArray<T> extends Array<T>, Observable, MutableArrayWithoutNative<T> {}
const NativeArray: Mixin;
export default NativeArray; | true |
Other | emberjs | ember.js | 720c3021213ff8e530c809d37ec3493899448681.json | Improve types for Ember Arrays | types/preview/@ember/array/index.d.ts | @@ -73,7 +73,7 @@ declare module '@ember/array' {
* implements Ember.Observable, the value will be changed to `set(),` otherwise
* it will be set directly. `null` objects are skipped.
*/
- setEach<K extends keyof T>(key: K, value: T[K]): void;
+ setEach<K extends keyof T>(key: K, value: T[K]): this;
/**
* Maps all of the items in the enumeration to another value, returning
* a new array. This method corresponds to `map()` defined in JavaScript 1.6.
@@ -111,12 +111,14 @@ declare module '@ember/array' {
* this will match any property that evaluates to `true`.
*/
filterBy<K extends keyof T>(key: K, value?: T[K]): NativeArray<T>;
+ filterBy(key: string, value?: unknown): NativeArray<T>;
/**
* Returns an array with the items that do not have truthy values for
* key. You can pass an optional second argument with the target value. Otherwise
* this will match any property that evaluates to false.
*/
rejectBy<K extends keyof T>(key: K, value?: T[K]): NativeArray<T>;
+ rejectBy(key: string, value?: unknown): NativeArray<T>;
/**
* Returns the first item in the array for which the callback returns true.
* This method works similar to the `filter()` method defined in JavaScript 1.6
@@ -136,6 +138,7 @@ declare module '@ember/array' {
* this will match any property that evaluates to `true`.
*/
findBy<K extends keyof T>(key: K, value?: T[K]): T | undefined;
+ findBy(key: string, value?: unknown): T | undefined;
/**
* Returns `true` if the passed function returns true for every item in the
* enumeration. This corresponds with the `every()` method in JavaScript 1.6.
@@ -150,6 +153,7 @@ declare module '@ember/array' {
* than using a callback.
*/
isEvery<K extends keyof T>(key: K, value?: T[K]): boolean;
+ isEvery(key: string, value?: unknown): boolean;
/**
* Returns `true` if the passed function returns true for any item in the
* enumeration.
@@ -164,12 +168,16 @@ declare module '@ember/array' {
* than using a callback.
*/
isAny<K extends keyof T>(key: K, value?: T[K]): boolean;
+ isAny(key: string, value?: unknown): boolean;
/**
* This will combine the values of the enumerator into a single value. It
* is a useful way to collect a summary value from an enumeration. This
* corresponds to the `reduce()` method defined in JavaScript 1.8.
*/
- reduce: T[]['reduce'];
+ reduce<V>(
+ callback: (summation: V, current: T, index: number, arr: this) => V,
+ initialValue?: V
+ ): V;
/**
* Invokes the named method on every object in the receiver that
* implements it. This method corresponds to the implementation in
@@ -178,7 +186,7 @@ declare module '@ember/array' {
invoke<M extends MethodNamesOf<T>>(
methodName: M,
...args: MethodParams<T, M>
- ): Array<MethodReturns<T, M>>;
+ ): NativeArray<MethodReturns<T, M>>;
/**
* Simply converts the enumerable into a genuine array. The order is not
* guaranteed. Corresponds to the method implemented by Prototype.
@@ -196,7 +204,7 @@ declare module '@ember/array' {
* Converts the enumerable into an array and sorts by the keys
* specified in the argument.
*/
- sortBy(...properties: string[]): NativeArray<T>;
+ sortBy(...properties: string[]): T[];
/**
* Returns a new enumerable that excludes the passed value. The default
* implementation returns an array regardless of the receiver type.
@@ -219,8 +227,8 @@ declare module '@ember/array' {
* this property, it will return this. If you set this property to a new
* array, it will replace the current content.
*/
- get '[]'(): NativeArray<T>;
- set '[]'(newValue: NativeArray<T>);
+ get '[]'(): this;
+ set '[]'(newValue: T[] | Array<T>);
}
// Ember.Array rather than Array because the `array-type` lint rule doesn't realize the global is shadowed
const Array: Mixin; | true |
Other | emberjs | ember.js | 720c3021213ff8e530c809d37ec3493899448681.json | Improve types for Ember Arrays | types/preview/@ember/array/mutable.d.ts | @@ -15,7 +15,7 @@ declare module '@ember/array/mutable' {
/**
* __Required.__ You must implement this method to apply this mixin.
*/
- replace(idx: number, amt: number, objects: T[]): this;
+ replace(idx: number, amt: number, objects: T[]): void;
/**
* Remove all elements from the array. This is useful if you
* want to reuse an existing array without having to recreate it.
@@ -45,12 +45,12 @@ declare module '@ember/array/mutable' {
* Pop object from array or nil if none are left. Works just like `pop()` but
* it is KVO-compliant.
*/
- popObject(): T;
+ popObject(): T | null | undefined;
/**
* Shift an object from start of array or nil if none are left. Works just
* like `shift()` but it is KVO-compliant.
*/
- shiftObject(): T;
+ shiftObject(): T | null | undefined;
/**
* Unshift an object to start of array. Works just like `unshift()` but it is
* KVO-compliant.
@@ -82,7 +82,7 @@ declare module '@ember/array/mutable' {
/**
* __Required.__ You must implement this method to apply this mixin.
*/
- addObject(object: T): T;
+ addObject(object: T): this;
/**
* Adds each object in the passed enumerable to the receiver.
*/ | true |
Other | emberjs | ember.js | 720c3021213ff8e530c809d37ec3493899448681.json | Improve types for Ember Arrays | types/preview/ember/-private/type-utils.d.ts | @@ -7,16 +7,12 @@ declare module 'ember/-private/type-utils' {
export type AnyMethod<Target> = (this: Target, ...args: any[]) => unknown;
- export type MethodsOf<O> = {
- [K in keyof O]: O[K] extends AnyFn ? O[K] : never;
- };
-
- // Not just `keyof MethodsOf<O>` because that doesn't correctly exclude all the
- // `never` fields.
export type MethodNamesOf<O> = {
[K in keyof O]: O[K] extends AnyFn ? K : never;
}[keyof O];
+ export type MethodsOf<O> = Pick<O, MethodNamesOf<O>>;
+
export type MethodParams<T, M extends MethodNamesOf<T>> = Parameters<MethodsOf<T>[M]>;
export type MethodReturns<T, M extends MethodNamesOf<T>> = ReturnType<MethodsOf<T>[M]>; | true |
Other | emberjs | ember.js | dff8831cdbb5583de443a1859e4f09054687119f.json | Explain the (un)safety of the type of `getOwner()`
The type for `getOwner()` is *technically* unsafe, but this unsafety is
one which end users will rarely hit in practice and, courtesy of Ember's
current types, is unavoidable if `getOwner(someService)` is to correctly
return `Owner` instead of `Owner | undefined`.
The Typed Ember folks have discussed this point at some length, but I
realized on looking at this to make the changes in the preceding two
commits that we didn't have it committed to the code base anywhere, so
here I am just introducing a long comment explaining it. When we switch
from preview to stable types, this comment should come along! | types/preview/@ember/application/index.d.ts | @@ -136,7 +136,14 @@ declare module '@ember/application' {
* objects is the responsibility of an "owner", which handled its
* instantiation and manages its lifetime.
*/
- export function getOwner(object: FrameworkObject): Owner;
+ // SAFETY: this first overload is, strictly speaking, *unsafe*. It is possible
+ // to do `let x = EmberObject.create(); getOwner(x);` and the result will *not*
+ // be `Owner` but instead `undefined`. However, that's quite unusual at this
+ // point, and more to the point we cannot actually distinguish a `Service`
+ // subclass from `EmberObject` at this point: `Service` subclasses `EmberObject`
+ // and adds nothing to it. Accordingly, if we want to catch `Service`s with this
+ // (and `getOwner(this)` for some service will definitely be defined!), it has
+ // to be this way. :sigh:
export function getOwner(object: KnownFrameworkObject): Owner;
export function getOwner(object: unknown): Owner | undefined;
/** | false |
Other | emberjs | ember.js | cdd04dab708955e862166ce1a00bb2a74b06f26b.json | Add failing type test for `getOwner(Component<S>)`
This catches the scenario where we have a component which actually has
a signature defined:
class Example extends Component<{ Args: { anyWillDo: true } }> {
method() {
getOwner(this); // should be `Owner`, not `| undefined`
}
}
Presently, we return `Owner | undefined` instead. | type-tests/preview/@ember/owner-tests.ts | @@ -6,7 +6,11 @@ import Owner, {
Resolver,
KnownForTypeResult,
} from '@ember/owner';
+import Component from '@glimmer/component';
import { expectTypeOf } from 'expect-type';
+// TODO: once we move the runtime export to `@ember/owner`, update this import
+// as well. (That's why it's tested in this module!)
+import { getOwner } from '@ember/application';
// Just a class we can construct in the Factory and FactoryManager tests
declare class ConstructThis {
@@ -143,6 +147,30 @@ typedStrings.map((aString) => owner.lookup(aString));
const aConstName = 'type:name';
expectTypeOf(owner.lookup(aConstName)).toBeUnknown();
+// Check handling with Glimmer components carrying a Signature: they should
+// properly resolve to `Owner`, *not* `Owner | undefined`.
+interface Sig<T> {
+ Args: {
+ name: string;
+ age: number;
+ extra: T;
+ };
+ Element: HTMLParagraphElement;
+ Blocks: {
+ default: [greeting: string];
+ extra: [T];
+ };
+}
+
+class ExampleComponent<T> extends Component<Sig<T>> {
+ checkThis() {
+ expectTypeOf(getOwner(this)).toEqualTypeOf<Owner>();
+ }
+}
+
+declare let example: ExampleComponent<string>;
+expectTypeOf(getOwner(example)).toEqualTypeOf<Owner>();
+
// ----- Minimal further coverage for POJOs ----- //
// `Factory` and `FactoryManager` don't have to deal in actual classes. :sigh:
const Creatable = { | false |
Other | emberjs | ember.js | 0580eed5c18cdfcd239ccd475e04a1b4c222963c.json | Add v4.8.2 to CHANGELOG
(cherry picked from commit de4ecf64304e04f1543bc1b59cb71ff448b8543c) | CHANGELOG.md | @@ -1,5 +1,9 @@
# Ember Changelog
+### v4.8.2 (November 3, 2022)
+
+- [#20244](https://github.com/emberjs/ember.js/pull/20244) Add missing type for `getComponentTemplate` to preview types
+
### v4.9.0-beta.3 (November 2, 2022)
- [CVE pending](https://emberjs.com/blog/ember-4-8-1-released) Fix a prototype pollution vulnerability in `set` and `setProperties` | false |
Other | emberjs | ember.js | cca036eb575e10676e089f0d8efa01edd474cdb1.json | Add v4.9.0-beta.3 to CHANGELOG
(cherry picked from commit 0de013590e92900e5aee664e804ac0fcddf611bd) | CHANGELOG.md | @@ -1,5 +1,13 @@
# Ember Changelog
+### v4.9.0-beta.3 (November 2, 2022)
+
+- [CVE pending](https://emberjs.com/blog/ember-4-8-1-released) Fix a prototype pollution vulnerability in `set` and `setProperties`
+- [#20233](https://github.com/emberjs/ember.js/pull/20233) [BUGFIX] Include package name in deprecation error message
+- [#20235](https://github.com/emberjs/ember.js/pull/20235) [BUGFIX] Update `@types/node` for TS 4.9 issue
+- [#20238](https://github.com/emberjs/ember.js/pull/20238) [BUGFIX] Update Node.js versions to match support policy
+- [#20244](https://github.com/emberjs/ember.js/pull/20244) [BUGFIX] Expose getComponentTemplate type
+
### v4.8.1 (November 2, 2022)
- [CVE pending](https://emberjs.com/blog/ember-4-8-1-released) Fix a prototype pollution vulnerability in `set` and `setProperties` | false |
Other | emberjs | ember.js | 53ca013f87509315200c5969a8f55417af913786.json | Add v4.8.1 to CHANGELOG
(cherry picked from commit 9c226d38d41b7845e27bbd34bf463cbcc1a06cec) | CHANGELOG.md | @@ -1,5 +1,9 @@
# Ember Changelog
+### v4.8.1 (November 2, 2022)
+
+- [CVE pending](https://emberjs.com/blog/ember-4-8-1-released) Fix a prototype pollution vulnerability in `set` and `setProperties`
+
### v4.4.4 (November 2, 2022)
- [CVE pending](https://emberjs.com/blog/ember-4-8-1-released) Fix a prototype pollution vulnerability in `set` and `setProperties | false |
Other | emberjs | ember.js | 6a17b8417e7e00e15b2b6f0441703f3c74f3fd0c.json | Add v4.4.4 to CHANGELOG
(cherry picked from commit 1dad13a08ae0e1165d83b7d5927e33cd8498c708) | CHANGELOG.md | @@ -1,5 +1,9 @@
# Ember Changelog
+### v4.4.4 (November 2, 2022)
+
+- [CVE pending](https://emberjs.com/blog/ember-4-8-1-released) Fix a prototype pollution vulnerability in `set` and `setProperties
+
## v3.28.10 (November 2, 2022)
- [CVE pending](https://emberjs.com/blog/ember-4-8-1-released) Fix a prototype pollution vulnerability in `set` and `setProperties` | false |
Other | emberjs | ember.js | 701ee45b79b4ee3f860d2c380aa3d87212e3fad5.json | Add v3.28.10 to CHANGELOG
(cherry picked from commit 198d7e168f3c857be4b7da539dd5b3785b2c1452) | CHANGELOG.md | @@ -1,5 +1,9 @@
# Ember Changelog
+## v3.28.10 (November 2, 2022)
+
+- [CVE pending](https://emberjs.com/blog/ember-4-8-1-released) Fix a prototype pollution vulnerability in `set` and `setProperties`
+
### v3.24.7 (November 2, 2022)
- [CVE pending](https://emberjs.com/blog/ember-4-8-1-released) Fix a prototype pollution vulnerability in `set` and `setProperties` | false |
Other | emberjs | ember.js | a20bff305ae45840deb07a4a36a09de55073e916.json | Add v3.24.7 to CHANGELOG
(cherry picked from commit 44e20f73ab7c49003d185bef361353412d7a6518) | CHANGELOG.md | @@ -1,6 +1,11 @@
# Ember Changelog
+### v3.24.7 (November 2, 2022)
+
+- [CVE pending](https://emberjs.com/blog/ember-4-8-1-released) Fix a prototype pollution vulnerability in `set` and `setProperties`
+
### v4.9.0-beta.2 (October 25, 2022)
+
- [#20227](https://github.com/emberjs/ember.js/pull/20227) [BUGFIX] Fix unsafe internal cast for NativeArray
- [#20228](https://github.com/emberjs/ember.js/pull/20228) [BUGFIX] Remove type export for ControllerMixin
| false |
Other | emberjs | ember.js | 8bddebebc2df55625b1d1fe92332de3d2885752c.json | Convert packages/ember to TS | packages/@ember/-internals/environment/lib/context.ts | @@ -23,7 +23,7 @@ export const context = (function (
};
})(global, global.Ember);
-export function getLookup(): object {
+export function getLookup(): Record<string, unknown> {
return context.lookup;
}
| true |
Other | emberjs | ember.js | 8bddebebc2df55625b1d1fe92332de3d2885752c.json | Convert packages/ember to TS | packages/@ember/-internals/error-handling/index.ts | @@ -10,7 +10,7 @@ export function getOnerror() {
return onerror;
}
// Ember.onerror setter
-export function setOnerror(handler: Function) {
+export function setOnerror(handler: Function | undefined) {
onerror = handler;
}
| true |
Other | emberjs | ember.js | 8bddebebc2df55625b1d1fe92332de3d2885752c.json | Convert packages/ember to TS | packages/@ember/-internals/glimmer/lib/helper.ts | @@ -44,6 +44,32 @@ export interface SimpleHelper<T, P extends unknown[], N extends Dict<unknown>> {
compute: HelperFunction<T, P, N>;
}
+/**
+ In many cases it is not necessary to use the full `Helper` class.
+ The `helper` method create pure-function helpers without instances.
+ For example:
+
+ ```app/helpers/format-currency.js
+ import { helper } from '@ember/component/helper';
+
+ export default helper(function([cents], {currency}) {
+ return `${currency}${cents * 0.01}`;
+ });
+ ```
+
+ @static
+ @param {Function} helper The helper function
+ @method helper
+ @for @ember/component/helper
+ @public
+ @since 1.13.0
+*/
+export function helper<T, P extends unknown[], N extends Dict<unknown>>(
+ helperFn: HelperFunction<T, P, N>
+): HelperFactory<SimpleHelper<T, P, N>> {
+ return new Wrapper(helperFn);
+}
+
/**
Ember Helpers are functions that can compute values, and are used in templates.
For example, this code calls a helper named `format-currency`:
@@ -105,6 +131,12 @@ class Helper extends FrameworkObject {
static isHelperFactory = true;
static [IS_CLASSIC_HELPER] = true;
+ // `packages/ember/index.js` was setting `Helper.helper`. This seems like
+ // a bad idea and probably not something we want. We've moved that definition
+ // here, but it should definitely be reviewed and probably removed.
+ /** @deprecated */
+ static helper = helper;
+
// SAFETY: this is initialized in `init`, rather than `constructor`. It is
// safe to `declare` like this *if and only if* nothing uses the constructor
// directly in this class, since nothing else can run before `init`.
@@ -269,30 +301,4 @@ export const SIMPLE_CLASSIC_HELPER_MANAGER = new SimpleClassicHelperManager();
setHelperManager(() => SIMPLE_CLASSIC_HELPER_MANAGER, Wrapper.prototype);
-/**
- In many cases it is not necessary to use the full `Helper` class.
- The `helper` method create pure-function helpers without instances.
- For example:
-
- ```app/helpers/format-currency.js
- import { helper } from '@ember/component/helper';
-
- export default helper(function([cents], {currency}) {
- return `${currency}${cents * 0.01}`;
- });
- ```
-
- @static
- @param {Function} helper The helper function
- @method helper
- @for @ember/component/helper
- @public
- @since 1.13.0
-*/
-export function helper<T, P extends unknown[], N extends Dict<unknown>>(
- helperFn: HelperFunction<T, P, N>
-): HelperFactory<SimpleHelper<T, P, N>> {
- return new Wrapper(helperFn);
-}
-
export default Helper; | true |
Other | emberjs | ember.js | 8bddebebc2df55625b1d1fe92332de3d2885752c.json | Convert packages/ember to TS | packages/@ember/helper/type-tests/invoke-helper.test.ts | @@ -1,4 +1,4 @@
-import Component from '@ember/-internals/glimmer/lib/component';
+import Component from '@ember/component';
import { getValue } from '@ember/-internals/metal';
import Helper from '@ember/component/helper';
import { invokeHelper } from '@ember/helper'; | true |
Other | emberjs | ember.js | 8bddebebc2df55625b1d1fe92332de3d2885752c.json | Convert packages/ember to TS | packages/ember/index.js | @@ -1,619 +0,0 @@
-import require, { has } from 'require';
-
-import { getENV, getLookup, setLookup } from '@ember/-internals/environment';
-import * as utils from '@ember/-internals/utils';
-import { Registry, Container } from '@ember/-internals/container';
-import * as instrumentation from '@ember/instrumentation';
-import { meta } from '@ember/-internals/meta';
-import * as metal from '@ember/-internals/metal';
-import { FEATURES, isEnabled } from '@ember/canary-features';
-import * as EmberDebug from '@ember/debug';
-import { assert, captureRenderTree, deprecate } from '@ember/debug';
-import Backburner from 'backburner';
-import Controller, { inject as injectController, ControllerMixin } from '@ember/controller';
-import {
- _getStrings,
- _setStrings,
- dasherize,
- camelize,
- capitalize,
- classify,
- decamelize,
- loc,
- underscore,
- w,
-} from '@ember/string';
-import Service, { service } from '@ember/service';
-
-import EmberObject, { action, computed, observer } from '@ember/object';
-import { dependentKeyCompat } from '@ember/object/compat';
-
-import {
- RegistryProxyMixin,
- ContainerProxyMixin,
- _ProxyMixin,
- RSVP,
- Comparable,
- ActionHandler,
-} from '@ember/-internals/runtime';
-import {
- Component,
- componentCapabilities,
- modifierCapabilities,
- setComponentManager,
- escapeExpression,
- getTemplates,
- Helper,
- helper,
- htmlSafe,
- isHTMLSafe,
- setTemplates,
- template,
- Input,
- isSerializationFirstNode,
-} from '@ember/-internals/glimmer';
-import VERSION from './version';
-import * as views from '@ember/-internals/views';
-import ContainerDebugAdapter from '@ember/debug/container-debug-adapter';
-import DataAdapter from '@ember/debug/data-adapter';
-import EmberError from '@ember/error';
-import { run } from '@ember/runloop';
-import { getOnerror, setOnerror } from '@ember/-internals/error-handling';
-import { getOwner, setOwner } from '@ember/-internals/owner';
-import EmberArray, { A, NativeArray, isArray } from '@ember/array';
-import MutableArray from '@ember/array/mutable';
-import ArrayProxy from '@ember/array/proxy';
-import Application, { onLoad, runLoadHooks } from '@ember/application';
-import ApplicationInstance from '@ember/application/instance';
-import Namespace from '@ember/application/namespace';
-import Engine from '@ember/engine';
-import EngineInstance from '@ember/engine/instance';
-import Enumerable from '@ember/enumerable';
-import MutableEnumerable from '@ember/enumerable/mutable';
-import CoreObject from '@ember/object/core';
-import Evented from '@ember/object/evented';
-import Mixin, { mixin } from '@ember/object/mixin';
-import Observable from '@ember/object/observable';
-import ObjectProxy from '@ember/object/proxy';
-import PromiseProxyMixin from '@ember/object/promise-proxy-mixin';
-import { assign } from '@ember/polyfills';
-import AutoLocation from '@ember/routing/auto-location';
-import HashLocation from '@ember/routing/hash-location';
-import HistoryLocation from '@ember/routing/history-location';
-import NoneLocation from '@ember/routing/none-location';
-import EmberLocation from '@ember/routing/location';
-import Route from '@ember/routing/route';
-import Router from '@ember/routing/router';
-import {
- controllerFor,
- generateController,
- generateControllerFactory,
- DSL as RouterDSL,
-} from '@ember/routing/-internals';
-import { isNone, isBlank, isEmpty, isPresent, isEqual, typeOf, compare } from '@ember/utils';
-
-import {
- templateOnlyComponent,
- invokeHelper,
- hash,
- array,
- concat,
- get,
- on,
- fn,
-} from '@glimmer/runtime';
-
-import {
- helperCapabilities,
- setModifierManager,
- setComponentTemplate,
- getComponentTemplate,
- setHelperManager,
-} from '@glimmer/manager';
-
-import {
- assertDestroyablesDestroyed,
- associateDestroyableChild,
- destroy,
- enableDestroyableTracking,
- isDestroying,
- isDestroyed,
- registerDestructor,
- unregisterDestructor,
-} from '@ember/destroyable';
-
-// ****@ember/-internals/environment****
-
-const Ember = {};
-
-Ember.isNamespace = true;
-Ember.toString = function () {
- return 'Ember';
-};
-
-Object.defineProperty(Ember, 'ENV', {
- get: getENV,
- enumerable: false,
-});
-
-Object.defineProperty(Ember, 'lookup', {
- get: getLookup,
- set: setLookup,
- enumerable: false,
-});
-
-// ****@ember/application****
-Ember.getOwner = getOwner;
-Ember.setOwner = setOwner;
-Ember.Application = Application;
-Ember.ApplicationInstance = ApplicationInstance;
-
-// ****@ember/engine****
-Ember.Engine = Engine;
-Ember.EngineInstance = EngineInstance;
-
-// ****@ember/polyfills****
-Ember.assign = assign;
-
-// ****@ember/-internals/utils****
-Ember.generateGuid = utils.generateGuid;
-Ember.GUID_KEY = utils.GUID_KEY;
-Ember.guidFor = utils.guidFor;
-Ember.inspect = utils.inspect;
-Ember.makeArray = utils.makeArray;
-Ember.canInvoke = utils.canInvoke;
-Ember.wrap = utils.wrap;
-Ember.uuid = utils.uuid;
-
-// ****@ember/-internals/container****
-Ember.Container = Container;
-Ember.Registry = Registry;
-
-// ****@ember/debug****
-Ember.assert = EmberDebug.assert;
-Ember.warn = EmberDebug.warn;
-Ember.debug = EmberDebug.debug;
-Ember.deprecate = EmberDebug.deprecate;
-Ember.deprecateFunc = EmberDebug.deprecateFunc;
-Ember.runInDebug = EmberDebug.runInDebug;
-
-// ****@ember/error****
-Ember.Error = EmberError;
-
-/**
- @public
- @class Ember.Debug
-*/
-Ember.Debug = {
- registerDeprecationHandler: EmberDebug.registerDeprecationHandler,
- registerWarnHandler: EmberDebug.registerWarnHandler,
- isComputed: metal.isComputed,
-};
-
-// ****@ember/instrumentation****
-Ember.instrument = instrumentation.instrument;
-Ember.subscribe = instrumentation.subscribe;
-Ember.Instrumentation = {
- instrument: instrumentation.instrument,
- subscribe: instrumentation.subscribe,
- unsubscribe: instrumentation.unsubscribe,
- reset: instrumentation.reset,
-};
-
-// ****@ember/runloop****
-
-Ember.run = run;
-
-// ****@ember/-internals/metal****
-
-// in globals builds
-Ember.computed = computed;
-Ember._descriptor = metal.nativeDescDecorator;
-Ember._tracked = metal.tracked;
-Ember.cacheFor = metal.getCachedValueFor;
-Ember.ComputedProperty = metal.ComputedProperty;
-Ember._setClassicDecorator = metal.setClassicDecorator;
-Ember.meta = meta;
-Ember.get = metal.get;
-Ember._getPath = metal._getPath;
-Ember.set = metal.set;
-Ember.trySet = metal.trySet;
-Ember.FEATURES = Object.assign({ isEnabled }, FEATURES);
-Ember._Cache = utils.Cache;
-Ember.on = metal.on;
-Ember.addListener = metal.addListener;
-Ember.removeListener = metal.removeListener;
-Ember.sendEvent = metal.sendEvent;
-Ember.hasListeners = metal.hasListeners;
-Ember.isNone = isNone;
-Ember.isEmpty = isEmpty;
-Ember.isBlank = isBlank;
-Ember.isPresent = isPresent;
-Ember.notifyPropertyChange = metal.notifyPropertyChange;
-Ember.beginPropertyChanges = metal.beginPropertyChanges;
-Ember.endPropertyChanges = metal.endPropertyChanges;
-Ember.changeProperties = metal.changeProperties;
-Ember.platform = {
- defineProperty: true,
- hasPropertyAccessors: true,
-};
-Ember.defineProperty = metal.defineProperty;
-Ember.destroy = destroy;
-Ember.libraries = metal.libraries;
-Ember.getProperties = metal.getProperties;
-Ember.setProperties = metal.setProperties;
-Ember.expandProperties = metal.expandProperties;
-Ember.addObserver = metal.addObserver;
-Ember.removeObserver = metal.removeObserver;
-Ember.observer = observer;
-Ember.mixin = mixin;
-Ember.Mixin = Mixin;
-
-Ember._createCache = metal.createCache;
-Ember._cacheGetValue = metal.getValue;
-Ember._cacheIsConst = metal.isConst;
-
-Ember._registerDestructor = registerDestructor;
-Ember._unregisterDestructor = unregisterDestructor;
-Ember._associateDestroyableChild = associateDestroyableChild;
-Ember._assertDestroyablesDestroyed = assertDestroyablesDestroyed;
-Ember._enableDestroyableTracking = enableDestroyableTracking;
-Ember._isDestroying = isDestroying;
-Ember._isDestroyed = isDestroyed;
-
-/**
- A function may be assigned to `Ember.onerror` to be called when Ember
- internals encounter an error. This is useful for specialized error handling
- and reporting code.
-
- ```javascript
-
- Ember.onerror = function(error) {
- const payload = {
- stack: error.stack,
- otherInformation: 'whatever app state you want to provide'
- };
-
- fetch('/report-error', {
- method: 'POST',
- body: JSON.stringify(payload)
- });
- };
- ```
-
- Internally, `Ember.onerror` is used as Backburner's error handler.
-
- @event onerror
- @for Ember
- @param {Exception} error the error object
- @public
-*/
-Object.defineProperty(Ember, 'onerror', {
- get: getOnerror,
- set: setOnerror,
- enumerable: false,
-});
-
-Object.defineProperty(Ember, 'testing', {
- get: EmberDebug.isTesting,
- set: EmberDebug.setTesting,
- enumerable: false,
-});
-
-Ember._Backburner = Backburner;
-
-// ****@ember/-internals/runtime****
-Ember.A = A;
-Ember.String = {
- loc,
- w,
- dasherize,
- decamelize,
- camelize,
- classify,
- underscore,
- capitalize,
-};
-Ember.Object = EmberObject;
-Ember._RegistryProxyMixin = RegistryProxyMixin;
-Ember._ContainerProxyMixin = ContainerProxyMixin;
-Ember.compare = compare;
-Ember.isEqual = isEqual;
-
-/**
-@module ember
-*/
-
-/**
- Namespace for injection helper methods.
-
- @class inject
- @namespace Ember
- @static
- @public
-*/
-Ember.inject = function inject() {
- assert(
- `Injected properties must be created through helpers, see '${Object.keys(inject)
- .map((k) => `'inject.${k}'`)
- .join(' or ')}'`
- );
-};
-Ember.inject.service = service;
-Ember.inject.controller = injectController;
-
-Ember.Array = EmberArray;
-Ember.Comparable = Comparable;
-Ember.Enumerable = Enumerable;
-Ember.ArrayProxy = ArrayProxy;
-Ember.ObjectProxy = ObjectProxy;
-Ember.ActionHandler = ActionHandler;
-Ember.CoreObject = CoreObject;
-Ember.NativeArray = NativeArray;
-Ember.MutableEnumerable = MutableEnumerable;
-Ember.MutableArray = MutableArray;
-Ember.Evented = Evented;
-Ember.PromiseProxyMixin = PromiseProxyMixin;
-Ember.Observable = Observable;
-Ember.typeOf = typeOf;
-Ember.isArray = isArray;
-Ember.Object = EmberObject;
-Ember.onLoad = onLoad;
-Ember.runLoadHooks = runLoadHooks;
-Ember.Controller = Controller;
-Ember.ControllerMixin = ControllerMixin;
-Ember.Service = Service;
-Ember._ProxyMixin = _ProxyMixin;
-Ember.RSVP = RSVP;
-Ember.Namespace = Namespace;
-
-Ember._action = action;
-Ember._dependentKeyCompat = dependentKeyCompat;
-
-/**
- Defines the hash of localized strings for the current language. Used by
- the `String.loc` helper. To localize, add string values to this
- hash.
-
- @property STRINGS
- @for Ember
- @type Object
- @private
-*/
-Object.defineProperty(Ember, 'STRINGS', {
- configurable: false,
- get: _getStrings,
- set: _setStrings,
-});
-
-/**
- Whether searching on the global for new Namespace instances is enabled.
-
- This is only exported here as to not break any addons. Given the new
- visit API, you will have issues if you treat this as a indicator of
- booted.
-
- Internally this is only exposing a flag in Namespace.
-
- @property BOOTED
- @for Ember
- @type Boolean
- @private
-*/
-Object.defineProperty(Ember, 'BOOTED', {
- configurable: false,
- enumerable: false,
- get: metal.isNamespaceSearchDisabled,
- set: metal.setNamespaceSearchDisabled,
-});
-
-// ****@ember/-internals/glimmer****
-Ember.Component = Component;
-Helper.helper = helper;
-Ember.Helper = Helper;
-Ember._setComponentManager = setComponentManager;
-Ember._componentManagerCapabilities = componentCapabilities;
-Ember._setModifierManager = setModifierManager;
-Ember._modifierManagerCapabilities = modifierCapabilities;
-
-Ember._getComponentTemplate = getComponentTemplate;
-Ember._setComponentTemplate = setComponentTemplate;
-Ember._templateOnlyComponent = templateOnlyComponent;
-
-Ember._Input = Input;
-Ember._hash = hash;
-Ember._array = array;
-Ember._concat = concat;
-Ember._get = get;
-Ember._on = on;
-Ember._fn = fn;
-
-Ember._helperManagerCapabilities = helperCapabilities;
-Ember._setHelperManager = setHelperManager;
-Ember._invokeHelper = invokeHelper;
-Ember._captureRenderTree = captureRenderTree;
-
-const deprecateImportFromString = function (
- name,
- message = `Importing ${name} from '@ember/string' is deprecated. Please import ${name} from '@ember/template' instead.`
-) {
- // Disabling this deprecation due to unintended errors in 3.25
- // See https://github.com/emberjs/ember.js/issues/19393 fo more information.
- deprecate(message, true, {
- id: 'ember-string.htmlsafe-ishtmlsafe',
- for: 'ember-source',
- since: {
- available: '3.25',
- enabled: '3.25',
- },
- until: '4.0.0',
- url: 'https://deprecations.emberjs.com/v3.x/#toc_ember-string-htmlsafe-ishtmlsafe',
- });
-};
-Object.defineProperty(Ember.String, 'htmlSafe', {
- enumerable: true,
- configurable: true,
- get() {
- deprecateImportFromString('htmlSafe');
- return htmlSafe;
- },
-});
-Object.defineProperty(Ember.String, 'isHTMLSafe', {
- enumerable: true,
- configurable: true,
- get() {
- deprecateImportFromString('isHTMLSafe');
- return isHTMLSafe;
- },
-});
-
-/**
- Global hash of shared templates. This will automatically be populated
- by the build tools so that you can store your Handlebars templates in
- separate files that get loaded into JavaScript at buildtime.
-
- @property TEMPLATES
- @for Ember
- @type Object
- @private
-*/
-Object.defineProperty(Ember, 'TEMPLATES', {
- get: getTemplates,
- set: setTemplates,
- configurable: false,
- enumerable: false,
-});
-
-/**
- The semantic version
-
- @property VERSION
- @type String
- @public
-*/
-Ember.VERSION = VERSION;
-
-Ember.ViewUtils = {
- isSimpleClick: views.isSimpleClick,
- getElementView: views.getElementView,
- getViewElement: views.getViewElement,
- getViewBounds: views.getViewBounds,
- getViewClientRects: views.getViewClientRects,
- getViewBoundingClientRect: views.getViewBoundingClientRect,
- getRootViews: views.getRootViews,
- getChildViews: views.getChildViews,
- isSerializationFirstNode: isSerializationFirstNode,
-};
-Ember.ComponentLookup = views.ComponentLookup;
-Ember.EventDispatcher = views.EventDispatcher;
-
-Ember.Location = EmberLocation;
-Ember.AutoLocation = AutoLocation;
-Ember.HashLocation = HashLocation;
-Ember.HistoryLocation = HistoryLocation;
-Ember.NoneLocation = NoneLocation;
-Ember.controllerFor = controllerFor;
-Ember.generateControllerFactory = generateControllerFactory;
-Ember.generateController = generateController;
-Ember.RouterDSL = RouterDSL;
-Ember.Router = Router;
-Ember.Route = Route;
-
-runLoadHooks('Ember.Application', Application);
-
-Ember.DataAdapter = DataAdapter;
-Ember.ContainerDebugAdapter = ContainerDebugAdapter;
-
-let EmberHandlebars = {
- template,
- Utils: {
- escapeExpression,
- },
-};
-
-let EmberHTMLBars = {
- template,
-};
-
-function defineEmberTemplateCompilerLazyLoad(key) {
- Object.defineProperty(Ember, key, {
- configurable: true,
- enumerable: true,
- get() {
- if (has('ember-template-compiler')) {
- let templateCompiler = require('ember-template-compiler');
-
- EmberHTMLBars.precompile = EmberHandlebars.precompile = templateCompiler.precompile;
- EmberHTMLBars.compile = EmberHandlebars.compile = templateCompiler.compile;
-
- Object.defineProperty(Ember, 'HTMLBars', {
- configurable: true,
- writable: true,
- enumerable: true,
- value: EmberHTMLBars,
- });
- Object.defineProperty(Ember, 'Handlebars', {
- configurable: true,
- writable: true,
- enumerable: true,
- value: EmberHandlebars,
- });
- }
-
- return key === 'Handlebars' ? EmberHandlebars : EmberHTMLBars;
- },
- });
-}
-
-defineEmberTemplateCompilerLazyLoad('HTMLBars');
-defineEmberTemplateCompilerLazyLoad('Handlebars');
-
-// do this to ensure that Ember.Test is defined properly on the global
-// if it is present.
-function defineEmberTestingLazyLoad(key) {
- Object.defineProperty(Ember, key, {
- configurable: true,
- enumerable: true,
- get() {
- if (has('ember-testing')) {
- let testing = require('ember-testing');
-
- let { Test, Adapter, QUnitAdapter, setupForTesting } = testing;
- Test.Adapter = Adapter;
- Test.QUnitAdapter = QUnitAdapter;
-
- Object.defineProperty(Ember, 'Test', {
- configurable: true,
- writable: true,
- enumerable: true,
- value: Test,
- });
- Object.defineProperty(Ember, 'setupForTesting', {
- configurable: true,
- writable: true,
- enumerable: true,
- value: setupForTesting,
- });
-
- return key === 'Test' ? Test : setupForTesting;
- }
-
- return undefined;
- },
- });
-}
-
-defineEmberTestingLazyLoad('Test');
-defineEmberTestingLazyLoad('setupForTesting');
-
-runLoadHooks('Ember');
-
-Ember.__loader = {
- require,
- // eslint-disable-next-line no-undef
- define,
- // eslint-disable-next-line no-undef
- registry: typeof requirejs !== 'undefined' ? requirejs.entries : require.entries,
-};
-
-export default Ember; | true |
Other | emberjs | ember.js | 8bddebebc2df55625b1d1fe92332de3d2885752c.json | Convert packages/ember to TS | packages/ember/index.ts | @@ -0,0 +1,710 @@
+/**
+@module ember
+*/
+
+import require, { has } from 'require';
+
+import { getENV, getLookup, setLookup } from '@ember/-internals/environment';
+import * as utils from '@ember/-internals/utils';
+import { Registry, Container } from '@ember/-internals/container';
+import * as instrumentation from '@ember/instrumentation';
+import { meta } from '@ember/-internals/meta';
+import * as metal from '@ember/-internals/metal';
+import { FEATURES, isEnabled } from '@ember/canary-features';
+import * as EmberDebug from '@ember/debug';
+import { assert, captureRenderTree } from '@ember/debug';
+import Backburner from 'backburner';
+import Controller, { inject as injectController, ControllerMixin } from '@ember/controller';
+import {
+ _getStrings,
+ _setStrings,
+ dasherize,
+ camelize,
+ capitalize,
+ classify,
+ decamelize,
+ underscore,
+ w,
+} from '@ember/string';
+import Service, { service } from '@ember/service';
+
+import EmberObject, {
+ action,
+ computed,
+ defineProperty,
+ notifyPropertyChange,
+ observer,
+ get,
+ getProperties,
+ set,
+ setProperties,
+ trySet,
+} from '@ember/object';
+import { cacheFor } from '@ember/object/-internals';
+import { dependentKeyCompat } from '@ember/object/compat';
+import ComputedProperty, { expandProperties } from '@ember/object/computed';
+import { addListener, removeListener, sendEvent } from '@ember/object/events';
+
+import {
+ RegistryProxyMixin,
+ ContainerProxyMixin,
+ _ProxyMixin,
+ RSVP,
+ Comparable,
+ ActionHandler,
+} from '@ember/-internals/runtime';
+import {
+ componentCapabilities,
+ modifierCapabilities,
+ setComponentManager,
+ escapeExpression,
+ getTemplates,
+ setTemplates,
+ template,
+ isSerializationFirstNode,
+} from '@ember/-internals/glimmer';
+import VERSION from './version';
+import * as views from '@ember/-internals/views';
+import ContainerDebugAdapter from '@ember/debug/container-debug-adapter';
+import DataAdapter from '@ember/debug/data-adapter';
+import EmberError from '@ember/error';
+import { run } from '@ember/runloop';
+import { getOnerror, setOnerror } from '@ember/-internals/error-handling';
+import EmberArray, { A, NativeArray, isArray } from '@ember/array';
+import MutableArray from '@ember/array/mutable';
+import ArrayProxy from '@ember/array/proxy';
+import Application, { getOwner, setOwner, onLoad, runLoadHooks } from '@ember/application';
+import ApplicationInstance from '@ember/application/instance';
+import Namespace from '@ember/application/namespace';
+import Component, { Input } from '@ember/component';
+import Helper from '@ember/component/helper';
+import Engine from '@ember/engine';
+import EngineInstance from '@ember/engine/instance';
+import Enumerable from '@ember/enumerable';
+import MutableEnumerable from '@ember/enumerable/mutable';
+import CoreObject from '@ember/object/core';
+import Evented, { on } from '@ember/object/evented';
+import Mixin, { mixin } from '@ember/object/mixin';
+import Observable from '@ember/object/observable';
+import { addObserver, removeObserver } from '@ember/object/observers';
+import ObjectProxy from '@ember/object/proxy';
+import PromiseProxyMixin from '@ember/object/promise-proxy-mixin';
+import { assign } from '@ember/polyfills';
+import AutoLocation from '@ember/routing/auto-location';
+import HashLocation from '@ember/routing/hash-location';
+import HistoryLocation from '@ember/routing/history-location';
+import NoneLocation from '@ember/routing/none-location';
+import EmberLocation from '@ember/routing/location';
+import Route from '@ember/routing/route';
+import Router from '@ember/routing/router';
+import {
+ controllerFor,
+ generateController,
+ generateControllerFactory,
+ DSL as RouterDSL,
+} from '@ember/routing/-internals';
+import { isNone, isBlank, isEmpty, isPresent, isEqual, typeOf, compare } from '@ember/utils';
+
+import * as glimmerRuntime from '@glimmer/runtime';
+
+import {
+ helperCapabilities,
+ setModifierManager,
+ setComponentTemplate,
+ getComponentTemplate,
+ setHelperManager,
+} from '@glimmer/manager';
+
+import {
+ assertDestroyablesDestroyed,
+ associateDestroyableChild,
+ destroy,
+ enableDestroyableTracking,
+ isDestroying,
+ isDestroyed,
+ registerDestructor,
+ unregisterDestructor,
+} from '@ember/destroyable';
+
+import type * as EmberTemplateCompiler from 'ember-template-compiler';
+import type { precompile, compile } from 'ember-template-compiler';
+import type * as EmberTesting from 'ember-testing';
+
+/**
+ Namespace for injection helper methods.
+
+ @class inject
+ @namespace Ember
+ @static
+ @public
+*/
+function inject() {
+ assert(
+ `Injected properties must be created through helpers, see '${Object.keys(inject)
+ .map((k) => `'inject.${k}'`)
+ .join(' or ')}'`
+ );
+}
+// ****@ember/controller****
+inject.controller = injectController;
+// ****@ember/service****
+inject.service = service;
+
+const PartialEmber = {
+ isNamespace: true,
+
+ toString() {
+ return 'Ember';
+ },
+
+ // ****@ember/-internals/container****
+ Container,
+ Registry,
+
+ // ****@ember/-internals/glimmer****
+ // Partially re-exported from @glimmer/manager
+ _setComponentManager: setComponentManager,
+ _componentManagerCapabilities: componentCapabilities,
+ _modifierManagerCapabilities: modifierCapabilities,
+
+ // ****@ember/-internals/meta****
+ meta,
+
+ // ****@ember/-internals/metal****
+ _createCache: metal.createCache, // Also @glimmer/validator
+ _cacheGetValue: metal.getValue, // Also @glimmer/validator
+ _cacheIsConst: metal.isConst, // Also @glimmer/validator
+ _descriptor: metal.nativeDescDecorator,
+ _getPath: metal._getPath,
+ _setClassicDecorator: metal.setClassicDecorator,
+ _tracked: metal.tracked, // Also exported from @glimmer/tracking
+ beginPropertyChanges: metal.beginPropertyChanges,
+ changeProperties: metal.changeProperties,
+ endPropertyChanges: metal.endPropertyChanges,
+ hasListeners: metal.hasListeners,
+ libraries: metal.libraries,
+
+ // ****@ember/-internals/runtime****
+ _ContainerProxyMixin: ContainerProxyMixin,
+ _ProxyMixin,
+ _RegistryProxyMixin: RegistryProxyMixin,
+ ActionHandler,
+ Comparable,
+ RSVP, // Also from 'rsvp' directly.
+
+ // ****@ember/-internals/view****
+ ComponentLookup: views.ComponentLookup,
+ EventDispatcher: views.EventDispatcher,
+
+ // ****@ember/-internals/utils****
+ _Cache: utils.Cache,
+ GUID_KEY: utils.GUID_KEY,
+ canInvoke: utils.canInvoke,
+ inspect: utils.inspect,
+ generateGuid: utils.generateGuid,
+ guidFor: utils.guidFor,
+ makeArray: utils.makeArray,
+ uuid: utils.uuid,
+ wrap: utils.wrap,
+
+ // ****@ember/application****
+ getOwner,
+ onLoad,
+ runLoadHooks,
+ setOwner,
+ Application,
+
+ // ****@ember/application/instance****
+ ApplicationInstance,
+
+ // ****@ember/application/namespace****
+ Namespace,
+
+ // ****@ember/array****
+ A,
+ Array: EmberArray,
+ NativeArray,
+ isArray,
+
+ // ****@ember/array/mutable****
+ MutableArray,
+
+ // ****@ember/array/proxy****
+ ArrayProxy,
+
+ // ****@ember/canary-features****
+ Features: { isEnabled, ...FEATURES },
+
+ // ****@ember/component****
+ _Input: Input,
+ Component,
+
+ // ****@ember/component/helper****
+ Helper,
+
+ // ****@ember/controller****
+ Controller,
+ ControllerMixin,
+
+ // ****@ember/debug****
+ _captureRenderTree: captureRenderTree,
+ assert: EmberDebug.assert,
+ warn: EmberDebug.warn,
+ debug: EmberDebug.debug,
+ deprecate: EmberDebug.deprecate,
+ deprecateFunc: EmberDebug.deprecateFunc,
+ runInDebug: EmberDebug.runInDebug,
+
+ Debug: {
+ registerDeprecationHandler: EmberDebug.registerDeprecationHandler,
+ registerWarnHandler: EmberDebug.registerWarnHandler,
+ // ****@ember/-internals/metal****
+ isComputed: metal.isComputed,
+ },
+
+ // ****@ember/debug/container-debug-adapter****
+ ContainerDebugAdapter,
+
+ // ****@ember/debug/data-adapter****
+ DataAdapter,
+
+ // ****@ember/destroyable****
+ _assertDestroyablesDestroyed: assertDestroyablesDestroyed,
+ _associateDestroyableChild: associateDestroyableChild,
+ _enableDestroyableTracking: enableDestroyableTracking,
+ _isDestroying: isDestroying,
+ _isDestroyed: isDestroyed,
+ _registerDestructor: registerDestructor,
+ _unregisterDestructor: unregisterDestructor,
+ destroy,
+
+ // ****@ember/engine****
+ Engine,
+
+ // ****@ember/engine/instance****
+ EngineInstance,
+
+ // ****@ember/enumerable****
+ Enumerable,
+
+ // ****@ember/enumerable/mutable****
+ MutableEnumerable,
+
+ // ****@ember/error****
+ Error: EmberError,
+
+ // ****@ember/instrumentation****
+ instrument: instrumentation.instrument,
+ subscribe: instrumentation.subscribe,
+
+ Instrumentation: {
+ instrument: instrumentation.instrument,
+ subscribe: instrumentation.subscribe,
+ unsubscribe: instrumentation.unsubscribe,
+ reset: instrumentation.reset,
+ },
+
+ // ****@ember/object****
+ Object: EmberObject,
+ _action: action,
+ computed,
+ defineProperty,
+ get,
+ getProperties,
+ notifyPropertyChange,
+ observer,
+ set,
+ trySet,
+ setProperties,
+
+ // ****@ember/object/-internals****
+ cacheFor,
+
+ // ****@ember/object/compat****
+ _dependentKeyCompat: dependentKeyCompat,
+
+ // ****@ember/object/computed****
+ ComputedProperty,
+ expandProperties,
+
+ // ****@ember/object/core****
+ CoreObject,
+
+ // ****@ember/object/evented****
+ Evented,
+ on,
+
+ // ****@ember/object/events****
+ addListener,
+ removeListener,
+ sendEvent,
+
+ // ****@ember/object/mixin****
+ Mixin,
+ mixin,
+
+ // ****@ember/object/observable****
+ Observable,
+
+ // ****@ember/object/observers****
+ addObserver,
+ removeObserver,
+
+ // ****@ember/object/promise-proxy-mixin****
+ PromiseProxyMixin,
+
+ // ****@ember/object/proxy****
+ ObjectProxy,
+
+ // ****@ember/polyfills****
+ assign,
+
+ // ****@ember/routing/-internals****
+ RouterDSL,
+ controllerFor,
+ generateController,
+ generateControllerFactory,
+
+ // ****@ember/routing/auto-location****
+ AutoLocation,
+
+ // ****@ember/routing/hash-location****
+ HashLocation,
+
+ // ****@ember/routing/history-location****
+ HistoryLocation,
+
+ // ****@ember/routing/location****
+ Location: EmberLocation,
+
+ // ****@ember/routing/none-location****
+ NoneLocation,
+
+ // ****@ember/routing/route****
+ Route,
+
+ // ****@ember/routing/router****
+ Router,
+
+ // ****@ember/runloop****
+ run,
+
+ // ****@ember/service****
+ Service,
+
+ // ****@ember/string****
+ String: {
+ camelize,
+ capitalize,
+ classify,
+ decamelize,
+ dasherize,
+ underscore,
+ w,
+ },
+
+ // ****@ember/utils****
+ compare,
+ isBlank,
+ isEmpty,
+ isEqual,
+ isNone,
+ isPresent,
+ typeOf,
+
+ // ****@ember/version****
+ /**
+ The semantic version
+
+ @property VERSION
+ @type String
+ @public
+ */
+ VERSION,
+
+ ViewUtils: {
+ // ****@ember/-internals/views****
+ getChildViews: views.getChildViews,
+ getElementView: views.getElementView,
+ getRootViews: views.getRootViews,
+ getViewBounds: views.getViewBounds,
+ getViewBoundingClientRect: views.getViewBoundingClientRect,
+ getViewClientRects: views.getViewClientRects,
+ getViewElement: views.getViewElement,
+ isSimpleClick: views.isSimpleClick,
+
+ // ****@ember/-internals/glimmer****
+ isSerializationFirstNode,
+ },
+
+ // ****@glimmer/manager****
+ _getComponentTemplate: getComponentTemplate,
+ _helperManagerCapabilities: helperCapabilities,
+ _setComponentTemplate: setComponentTemplate,
+ _setHelperManager: setHelperManager,
+ _setModifierManager: setModifierManager,
+
+ // ****@glimmer/runtime****
+ _templateOnlyComponent: glimmerRuntime.templateOnlyComponent,
+ _invokeHelper: glimmerRuntime.invokeHelper,
+ _hash: glimmerRuntime.hash,
+ _array: glimmerRuntime.array,
+ _concat: glimmerRuntime.concat,
+ _get: glimmerRuntime.get,
+ _on: glimmerRuntime.on,
+ _fn: glimmerRuntime.fn,
+
+ // Backburner
+ _Backburner: Backburner,
+
+ // ****@ember/controller, @ember/service****
+ inject,
+
+ // Non-imported
+ platform: {
+ defineProperty: true,
+ hasPropertyAccessors: true,
+ },
+
+ __loader: {
+ require,
+ define,
+ // @ts-expect-error These properties don't appear as being defined
+ registry: typeof requirejs !== 'undefined' ? requirejs.entries : require.entries,
+ },
+
+ get ENV() {
+ return getENV();
+ },
+
+ /**
+ A function may be assigned to `Ember.onerror` to be called when Ember
+ internals encounter an error. This is useful for specialized error handling
+ and reporting code.
+
+ ```javascript
+
+ Ember.onerror = function(error) {
+ const payload = {
+ stack: error.stack,
+ otherInformation: 'whatever app state you want to provide'
+ };
+
+ fetch('/report-error', {
+ method: 'POST',
+ body: JSON.stringify(payload)
+ });
+ };
+ ```
+
+ Internally, `Ember.onerror` is used as Backburner's error handler.
+
+ @event onerror
+ @for Ember
+ @param {Exception} error the error object
+ @public
+ */
+ // ****@ember/-internals/error-handling****
+ get onerror(): Function | undefined {
+ return getOnerror();
+ },
+
+ set onerror(handler: Function | undefined) {
+ setOnerror(handler);
+ },
+
+ // ****@ember/debug****
+ get testing(): boolean {
+ return EmberDebug.isTesting();
+ },
+
+ set testing(value: boolean) {
+ EmberDebug.setTesting(value);
+ },
+
+ // ****@ember/-internals/environment****
+ get lookup() {
+ return getLookup();
+ },
+
+ set lookup(value) {
+ setLookup(value);
+ },
+
+ /**
+ Defines the hash of localized strings for the current language. Used by
+ the `String.loc` helper. To localize, add string values to this
+ hash.
+
+ @property STRINGS
+ @for Ember
+ @type Object
+ @private
+ */
+ // ****@ember/string****
+ get STRINGS() {
+ return _getStrings();
+ },
+
+ set STRINGS(value) {
+ _setStrings(value);
+ },
+
+ /**
+ Whether searching on the global for new Namespace instances is enabled.
+
+ This is only exported here as to not break any addons. Given the new
+ visit API, you will have issues if you treat this as a indicator of
+ booted.
+
+ Internally this is only exposing a flag in Namespace.
+
+ @property BOOTED
+ @for Ember
+ @type Boolean
+ @private
+ */
+ get BOOTED() {
+ return metal.isNamespaceSearchDisabled();
+ },
+
+ set BOOTED(value) {
+ metal.setNamespaceSearchDisabled(value);
+ },
+
+ /**
+ Global hash of shared templates. This will automatically be populated
+ by the build tools so that you can store your Handlebars templates in
+ separate files that get loaded into JavaScript at buildtime.
+
+ @property TEMPLATES
+ @for Ember
+ @type Object
+ @private
+ */
+ get TEMPLATES() {
+ return getTemplates();
+ },
+
+ set TEMPLATES(value) {
+ setTemplates(value);
+ },
+} as const;
+
+interface EmberHandlebars {
+ template: typeof template;
+ Utils: {
+ escapeExpression: typeof escapeExpression;
+ };
+ compile?: typeof compile;
+ precompile?: typeof precompile;
+}
+
+interface EmberHTMLBars {
+ template: typeof template;
+ compile?: typeof compile;
+ precompile?: typeof precompile;
+}
+
+type PartialEmber = typeof PartialEmber;
+interface Ember extends PartialEmber {
+ HTMLBars: EmberHTMLBars;
+ Handlebars: EmberHandlebars;
+ Test?: typeof EmberTesting['Test'] & {
+ Adapter: typeof EmberTesting['Adapter'];
+ QUnitAdapter: typeof EmberTesting['QUnitAdapter'];
+ };
+ setupForTesting?: typeof EmberTesting['setupForTesting'];
+}
+const Ember = PartialEmber as Ember;
+
+runLoadHooks('Ember.Application', Application);
+
+let EmberHandlebars: EmberHandlebars = {
+ template,
+ Utils: {
+ escapeExpression,
+ },
+};
+
+let EmberHTMLBars: EmberHTMLBars = {
+ template,
+};
+
+function defineEmberTemplateCompilerLazyLoad(key: 'HTMLBars' | 'Handlebars') {
+ Object.defineProperty(Ember, key, {
+ configurable: true,
+ enumerable: true,
+ get() {
+ if (has('ember-template-compiler')) {
+ let templateCompiler = require('ember-template-compiler') as typeof EmberTemplateCompiler;
+
+ EmberHTMLBars.precompile = EmberHandlebars.precompile = templateCompiler.precompile;
+ EmberHTMLBars.compile = EmberHandlebars.compile = templateCompiler.compile;
+
+ Object.defineProperty(Ember, 'HTMLBars', {
+ configurable: true,
+ writable: true,
+ enumerable: true,
+ value: EmberHTMLBars,
+ });
+ Object.defineProperty(Ember, 'Handlebars', {
+ configurable: true,
+ writable: true,
+ enumerable: true,
+ value: EmberHandlebars,
+ });
+ }
+
+ return key === 'Handlebars' ? EmberHandlebars : EmberHTMLBars;
+ },
+ });
+}
+
+defineEmberTemplateCompilerLazyLoad('HTMLBars');
+defineEmberTemplateCompilerLazyLoad('Handlebars');
+
+// do this to ensure that Ember.Test is defined properly on the global
+// if it is present.
+function defineEmberTestingLazyLoad(key: 'Test' | 'setupForTesting') {
+ Object.defineProperty(Ember, key, {
+ configurable: true,
+ enumerable: true,
+ get() {
+ if (has('ember-testing')) {
+ let testing = require('ember-testing') as typeof EmberTesting;
+
+ let { Test, Adapter, QUnitAdapter, setupForTesting } = testing;
+ // @ts-expect-error We should not do this
+ Test.Adapter = Adapter;
+ // @ts-expect-error We should not do this
+ Test.QUnitAdapter = QUnitAdapter;
+
+ Object.defineProperty(Ember, 'Test', {
+ configurable: true,
+ writable: true,
+ enumerable: true,
+ value: Test,
+ });
+ Object.defineProperty(Ember, 'setupForTesting', {
+ configurable: true,
+ writable: true,
+ enumerable: true,
+ value: setupForTesting,
+ });
+
+ return key === 'Test' ? Test : setupForTesting;
+ }
+
+ return undefined;
+ },
+ });
+}
+
+defineEmberTestingLazyLoad('Test');
+defineEmberTestingLazyLoad('setupForTesting');
+
+// @ts-expect-error Per types, runLoadHooks requires a second parameter. Should we loosen types?
+runLoadHooks('Ember');
+
+export default Ember; | true |
Other | emberjs | ember.js | 8bddebebc2df55625b1d1fe92332de3d2885752c.json | Convert packages/ember to TS | packages/ember/type-tests/ember.test.ts | @@ -0,0 +1,7 @@
+import Ember from 'ember';
+
+import { expectTypeOf } from 'expect-type';
+
+expectTypeOf(Ember.onerror).toEqualTypeOf<Function | undefined>();
+
+expectTypeOf(Ember.HTMLBars).toMatchTypeOf<object>(); | true |
Other | emberjs | ember.js | 8bddebebc2df55625b1d1fe92332de3d2885752c.json | Convert packages/ember to TS | packages/internal-test-helpers/lib/test-cases/rendering.ts | @@ -2,7 +2,8 @@ import type { EmberPrecompileOptions } from 'ember-template-compiler';
import { compile } from 'ember-template-compiler';
import { EventDispatcher } from '@ember/-internals/views';
import type { Renderer } from '@ember/-internals/glimmer';
-import { helper, Helper, Component, _resetRenderers } from '@ember/-internals/glimmer';
+import Component from '@ember/component';
+import { helper, Helper, _resetRenderers } from '@ember/-internals/glimmer';
import type Resolver from '../test-resolver';
import { ModuleBasedResolver } from '../test-resolver';
| true |
Other | emberjs | ember.js | 8bddebebc2df55625b1d1fe92332de3d2885752c.json | Convert packages/ember to TS | packages/internal-test-helpers/lib/test-cases/router-non-application.ts | @@ -2,7 +2,8 @@ import type { EmberPrecompileOptions } from 'ember-template-compiler';
import { compile } from 'ember-template-compiler';
import { EventDispatcher } from '@ember/-internals/views';
import type { Renderer } from '@ember/-internals/glimmer';
-import { Component, _resetRenderers } from '@ember/-internals/glimmer';
+import Component from '@ember/component';
+import { _resetRenderers } from '@ember/-internals/glimmer';
import type Resolver from '../test-resolver';
import { ModuleBasedResolver } from '../test-resolver';
| true |
Other | emberjs | ember.js | 8bddebebc2df55625b1d1fe92332de3d2885752c.json | Convert packages/ember to TS | packages/internal-test-helpers/lib/test-cases/test-resolver-application.ts | @@ -1,7 +1,7 @@
import AbstractApplicationTestCase from './abstract-application';
import type Resolver from '../test-resolver';
import { ModuleBasedResolver } from '../test-resolver';
-import { Component } from '@ember/-internals/glimmer';
+import Component from '@ember/component';
import type { Factory } from '@ember/-internals/owner';
export default abstract class TestResolverApplicationTestCase extends AbstractApplicationTestCase { | true |
Other | emberjs | ember.js | 8bddebebc2df55625b1d1fe92332de3d2885752c.json | Convert packages/ember to TS | packages/loader/lib/index.d.ts | @@ -1,9 +1,3 @@
-declare module 'ember' {
- const Ember: any;
-
- export default Ember;
-}
-
declare module 'require' {
export function has(path: string): boolean;
export default function require(path: string): any; | true |
Other | emberjs | ember.js | d61d713c055be1cc2c9c916c46d83af75f9af1ab.json | Add v4.9.0-beta.2 to CHANGELOG
(cherry picked from commit 5c79b3f6d2352fa3ca2ae585e7c1b9662f754d29) | CHANGELOG.md | @@ -1,5 +1,9 @@
# Ember Changelog
+### v4.9.0-beta.2 (October 25, 2022)
+- [#20227](https://github.com/emberjs/ember.js/pull/20227) [BUGFIX] Fix unsafe internal cast for NativeArray
+- [#20228](https://github.com/emberjs/ember.js/pull/20228) [BUGFIX] Remove type export for ControllerMixin
+
### v4.9.0-beta.1 (October 17, 2022)
- [#20203](https://github.com/emberjs/ember.js/pull/20203) / [#20204](https://github.com/emberjs/ember.js/pull/20204) [FEATURE] Preview types: Update to Typescript 4.8 | false |
Other | emberjs | ember.js | fdbd78031fd98da373af0623fe9c448cf5709550.json | Remove fallback to ember | packages/@ember/debug/lib/deprecate.ts | @@ -91,8 +91,7 @@ if (DEBUG) {
}
if (options?.until) {
- let namespace = options?.for ? options.for : "Ember";
- message = message + ` This will be removed in ${namespace} ${options.until}.`;
+ message = message + ` This will be removed in ${options.for} ${options.until}.`;
}
if (options?.url) { | false |
Other | emberjs | ember.js | 53affff6b3c8af459442034bcddac09e135a33fb.json | Add v4.9.0-beta.1 to CHANGELOG
(cherry picked from commit 1211052b2aa89ac90009f9b626e542754c9a383a) | CHANGELOG.md | @@ -1,5 +1,9 @@
# Ember Changelog
+### v4.9.0-beta.1 (October 17, 2022)
+
+- [#20203](https://github.com/emberjs/ember.js/pull/20203) / [#20204](https://github.com/emberjs/ember.js/pull/20204) [FEATURE] Preview types: Update to Typescript 4.8
+
### v4.8.0 (October 17, 2022)
- [#20180](https://github.com/emberjs/ember.js/pull/20180) [FEATURE] Publish an opt-in preview of public types for Ember | false |
Other | emberjs | ember.js | 449c9a5cf0264d304805c00ac9937e88bd438111.json | Add v4.8.0 to CHANGELOG
(cherry picked from commit 9021de5a7c49d2556ccbe5f671c1b90a57da4cf1) | CHANGELOG.md | @@ -1,5 +1,10 @@
# Ember Changelog
+### v4.8.0 (October 17, 2022)
+
+- [#20180](https://github.com/emberjs/ember.js/pull/20180) [FEATURE] Publish an opt-in preview of public types for Ember
+- [#20166](https://github.com/emberjs/ember.js/pull/20166) [BUGFIX] Upgrade router_js to fix Linked list of RouteInfos contains undefined object
+
### v4.4.3 (October 12, 2022)
- [#20166](https://github.com/emberjs/ember.js/pull/20166) [BUGFIX] Fix missing `RouteInfo` entries
@@ -8,28 +13,6 @@
- [#20166](https://github.com/emberjs/ember.js/pull/20166) [BUGFIX] Fix missing `RouteInfo` entries
-### v4.8.0-beta.5 (October 3, 2022)
-
-- [#20212](https://github.com/emberjs/ember.js/pull/20212) [BUGFIX] Remove incorrect exports from preview routing types
-
-### v4.8.0-beta.4 (September 26, 2022)
-
-- [#20201](https://github.com/emberjs/ember.js/pull/20201) [BUGFIX] Fix type definition for `Route`
-
-### v4.8.0-beta.3 (September 19, 2022)
-
-- [#20194](https://github.com/emberjs/ember.js/pull/20194) [BUGFIX] Provide a `.d.ts` file at types/stable
-- [#20196](https://github.com/emberjs/ember.js/pull/20196) [BUGFIX] types imports are at 'ember-source/types'
-
-### v4.8.0-beta.2 (September 13, 2022)
-
-- [#20186](https://github.com/emberjs/ember.js/pull/20186) [BUGFIX] Fix `@ember/runloop` type tests folder name so that the tests are properly excluded from the build
-- [#20180](https://github.com/emberjs/ember.js/pull/20180) [FEATURE] Publish an opt-in preview of public types for Ember
-
-### v4.8.0-beta.1 (September 6, 2022)
-
-- [#20166](https://github.com/emberjs/ember.js/pull/20166) [BUGFIX] Upgrade router_js to fix Linked list of RouteInfos contains undefined object
-
### v4.7.0 (September 6, 2022)
- [#20126](https://github.com/emberjs/ember.js/pull/20126) [BUGFIX] Replace Firefox detection that used a deprecated browser API | false |
Other | emberjs | ember.js | 1ea72b1cd37d80b45f97f05ef228dfeb13405370.json | Add v4.4.3 to CHANGELOG
(cherry picked from commit fd0f7cbeea607084ae1b29201e1bec56db0c7d5c) | CHANGELOG.md | @@ -1,5 +1,9 @@
# Ember Changelog
+### v4.4.3 (October 12, 2022)
+
+- [#20166](https://github.com/emberjs/ember.js/pull/20166) [BUGFIX] Fix missing `RouteInfo` entries
+
### v4.7.1 (October 12, 2022)
- [#20166](https://github.com/emberjs/ember.js/pull/20166) [BUGFIX] Fix missing `RouteInfo` entries | false |
Other | emberjs | ember.js | 908329efd8d45829e960b38740cd95d6493bf732.json | Add v4.7.1 to CHANGELOG
(cherry picked from commit 9113e22b1c820b8ae149293782cd1d5d5ea63a67) | CHANGELOG.md | @@ -1,5 +1,9 @@
# Ember Changelog
+### v4.7.1 (October 12, 2022)
+
+- [#20166](https://github.com/emberjs/ember.js/pull/20166) [BUGFIX] Fix missing `RouteInfo` entries
+
### v4.8.0-beta.5 (October 3, 2022)
- [#20212](https://github.com/emberjs/ember.js/pull/20212) [BUGFIX] Remove incorrect exports from preview routing types | false |
Other | emberjs | ember.js | 81c10c76d5f074d9113a921e1117c290bda21fe9.json | Add v4.8.0-beta.5 to CHANGELOG
(cherry picked from commit 6cd18e4f675bab791ccc0b22e68b48be34e13c2e) | CHANGELOG.md | @@ -1,5 +1,9 @@
# Ember Changelog
+### v4.8.0-beta.5 (October 3, 2022)
+
+- [#20212](https://github.com/emberjs/ember.js/pull/20212) [BUGFIX] Remove incorrect exports from preview routing types
+
### v4.8.0-beta.4 (September 26, 2022)
- [#20201](https://github.com/emberjs/ember.js/pull/20201) [BUGFIX] Fix type definition for `Route` | false |
Other | emberjs | ember.js | 9921e72527239e0261094258dd69ae1d1a9ad269.json | Fix internal issues caught by TS 4.9
TS 4.9 understands the `in` operator and catches two issues for us which
earlier versions did not:
1. We were checking `name in model` in `Route#serialize` without
checking that `model` there is an object. Given that a route's model
is *not* guaranteed to be an object, this was a runtime error waiting
to happen. `'a' in 2` will produce `TypeError: 2 is not an Object.'
2. We were checking for `Symbol.iterator in Array` in an internal
`iterate()` utility in the `@ember/debug/data-adapter` package. This
check is *always* true when targeting ES6 or newer for arrays, which
would *appear* to makie the `else` branch a no-op on all supported
browsers. Unfortunately, at least some consumers of this API
implement a narrower contract for iterables (presumably due to
legacy needs to interop with IE11 in Ember < 4.x). In those cases,
we really have an iterable, *not* an array. | packages/@ember/debug/data-adapter.ts | @@ -10,6 +10,7 @@ import { A as emberA } from '@ember/array';
import type { Cache } from '@glimmer/validator';
import { consumeTag, createCache, getValue, tagFor, untrack } from '@glimmer/validator';
import type ContainerDebugAdapter from '@ember/debug/container-debug-adapter';
+import { assert } from '.';
/**
@module @ember/debug/data-adapter
@@ -34,13 +35,27 @@ type WrappedRecord<T> = {
type RecordCallback<T> = (records: Array<{ columnValues: object; object: T }>) => void;
+// Represents the base contract for iterables as understood in the GLimmer VM
+// historically. This is *not* the public API for it, because there *is* no
+// public API for it. Recent versions of Glimmer simply use `Symbol.iterator`,
+// but some older consumers still use this basic shape.
+interface GlimmerIterable<T> {
+ length: number;
+ forEach(fn: (value: T) => void): void;
+}
+
function iterate<T>(arr: Array<T>, fn: (value: T) => void): void {
if (Symbol.iterator in arr) {
for (let item of arr) {
fn(item);
}
} else {
- arr.forEach(fn);
+ // SAFETY: this cast required to work this way to interop between TS 4.8
+ // and 4.9. When we drop support for 4.8, it will narrow correctly via the
+ // use of the `in` operator above. (Preferably we will solve this by just
+ // switching to require `Symbol.iterator` instead.)
+ assert('', typeof (arr as unknown as GlimmerIterable<T>).forEach === 'function');
+ (arr as unknown as GlimmerIterable<T>).forEach(fn);
}
}
| true |
Other | emberjs | ember.js | 9921e72527239e0261094258dd69ae1d1a9ad269.json | Fix internal issues caught by TS 4.9
TS 4.9 understands the `in` operator and catches two issues for us which
earlier versions did not:
1. We were checking `name in model` in `Route#serialize` without
checking that `model` there is an object. Given that a route's model
is *not* guaranteed to be an object, this was a runtime error waiting
to happen. `'a' in 2` will produce `TypeError: 2 is not an Object.'
2. We were checking for `Symbol.iterator in Array` in an internal
`iterate()` utility in the `@ember/debug/data-adapter` package. This
check is *always* true when targeting ES6 or newer for arrays, which
would *appear* to makie the `else` branch a no-op on all supported
browsers. Unfortunately, at least some consumers of this API
implement a narrower contract for iterables (presumably due to
legacy needs to interop with IE11 in Ember < 4.x). In those cases,
we really have an iterable, *not* an array. | packages/@ember/routing/route.ts | @@ -353,7 +353,7 @@ class Route<T = unknown>
if (params.length === 1) {
let [name] = params;
assert('has name', name);
- if (name in model) {
+ if (typeof model === 'object' && name in model) {
object[name] = get(model, name);
} else if (/_id$/.test(name)) {
object[name] = get(model, 'id'); | true |
Other | emberjs | ember.js | 3ec17789315fec24f63de0e0ab3177feb8906d83.json | Add v4.8.0-beta.4 to CHANGELOG
(cherry picked from commit 4ca204d9618ad3f3603908cb6caba917f8369908) | CHANGELOG.md | @@ -1,5 +1,9 @@
# Ember Changelog
+### v4.8.0-beta.4 (September 26, 2022)
+
+- [#20201](https://github.com/emberjs/ember.js/pull/20201) [BUGFIX] Fix type definition for `Route`
+
### v4.8.0-beta.3 (September 19, 2022)
- [#20194](https://github.com/emberjs/ember.js/pull/20194) [BUGFIX] Provide a `.d.ts` file at types/stable | false |
Other | emberjs | ember.js | 73016e3798fa089512089e28b97b45d4d67a19e1.json | add annotations to comment | packages/@ember/object/observable.ts | @@ -125,6 +125,11 @@ interface Observable {
If this method returns any value other than `undefined`, it will be returned
instead. This allows you to implement "virtual" properties that are
not defined upfront.
+
+ @method get
+ @param {String} keyName The property to retrieve
+ @return {Object} The property value or undefined.
+ @public
*/
get(key: string): unknown;
@@ -143,6 +148,11 @@ interface Observable {
record.getProperties(['firstName', 'lastName', 'zipCode']);
// { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
```
+
+ @method getProperties
+ @param {String...|Array} list of keys to get
+ @return {Object}
+ @public
*/
getProperties<L extends string[]>(list: L): { [Key in L[number]]: unknown };
getProperties<L extends string[]>(...list: L): { [Key in L[number]]: unknown };
@@ -185,6 +195,12 @@ interface Observable {
immediately. Any "remote" observers (i.e. observer methods declared on
another object) will be placed in a queue and called at a later time in a
coalesced manner.
+
+ @method set
+ @param {String} keyName The property to set
+ @param {Object} value The value to set or `null`.
+ @return {Object} The passed value
+ @public
*/
set<T>(key: string, value: T): T;
@@ -197,6 +213,11 @@ interface Observable {
```javascript
record.setProperties({ firstName: 'Charles', lastName: 'Jolley' });
```
+
+ @method setProperties
+ @param {Object} hash the hash of keys and values to set
+ @return {Object} The passed in hash
+ @public
*/
setProperties<T extends Record<string, any>>(hash: T): T;
@@ -210,6 +231,11 @@ interface Observable {
actually calling `get()` or `set()` on it. In this case, you can use this
method instead. Calling this method will notify all observers that the
property has potentially changed value.
+
+ @method notifyPropertyChange
+ @param {String} keyName The property key to be notified about.
+ @return {Observable}
+ @public
*/
notifyPropertyChange(keyName: string): this;
@@ -287,14 +313,30 @@ interface Observable {
the end. In this case, it is common to write observer methods that take
only a sender and key value as parameters or, if you aren't interested in
any of these values, to write an observer that has no parameters at all.
+
+ @method addObserver
+ @param {String} key The key to observe
+ @param {Object} target The target object to invoke
+ @param {String|Function} method The method to invoke
+ @param {Boolean} sync Whether the observer is sync or not
+ @return {Observable}
+ @public
*/
addObserver<Target>(key: keyof this, target: Target, method: ObserverMethod<Target, this>): this;
addObserver(key: keyof this, method: ObserverMethod<this, this>): this;
/**
- * Remove an observer you have previously registered on this object. Pass
- * the same key, target, and method you passed to `addObserver()` and your
- * target will no longer receive notifications.
+ Remove an observer you have previously registered on this object. Pass
+ the same key, target, and method you passed to `addObserver()` and your
+ target will no longer receive notifications.
+
+ @method removeObserver
+ @param {String} key The key to observe
+ @param {Object} target The target object to invoke
+ @param {String|Function} method The method to invoke
+ @param {Boolean} sync Whether the observer is async or not
+ @return {Observable}
+ @public
*/
removeObserver<Target>(
key: keyof this,
@@ -311,6 +353,12 @@ interface Observable {
person.incrementProperty('age');
team.incrementProperty('score', 2);
```
+
+ @method incrementProperty
+ @param {String} keyName The name of the property to increment
+ @param {Number} increment The amount to increment by. Defaults to 1
+ @return {Number} The new property value
+ @public
*/
incrementProperty(keyName: keyof this, increment?: number): number;
@@ -322,6 +370,12 @@ interface Observable {
player.decrementProperty('lives');
orc.decrementProperty('health', 5);
```
+
+ @method decrementProperty
+ @param {String} keyName The name of the property to decrement
+ @param {Number} decrement The amount to decrement by. Defaults to 1
+ @return {Number} The new property value
+ @public
*/
decrementProperty(keyName: keyof this, decrement?: number): number;
@@ -333,15 +387,25 @@ interface Observable {
```javascript
starship.toggleProperty('warpDriveEngaged');
```
+
+ @method toggleProperty
+ @param {String} keyName The name of the property to toggle
+ @return {Boolean} The new property value
+ @public
*/
toggleProperty(keyName: keyof this): boolean;
/**
- * Returns the cached value of a computed property, if it exists.
- * This allows you to inspect the value of a computed property
- * without accidentally invoking it if it is intended to be
- * generated lazily.
- */
+ Returns the cached value of a computed property, if it exists.
+ This allows you to inspect the value of a computed property
+ without accidentally invoking it if it is intended to be
+ generated lazily.
+
+ @method cacheFor
+ @param {String} keyName
+ @return {Object} The cached value of the computed property, if any
+ @public
+ */
cacheFor<K extends keyof this>(key: K): unknown;
}
const Observable = Mixin.create({ | false |
Other | emberjs | ember.js | ef3926a60ffb14690e79902f26d984c49ffab709.json | Fix missing tags lint error | packages/@ember/controller/index.ts | @@ -44,12 +44,14 @@ interface ControllerMixin<T> extends ActionHandler {
as part of the application's initialization process. In most cases the
`target` property will automatically be set to the logical consumer of
actions for the controller.
+ @public
*/
target: unknown | null;
/**
The controller's current model. When retrieving or modifying a controller's
model, this property should be used instead of the `content` property.
+ @public
*/
model: T;
@@ -74,6 +76,7 @@ interface ControllerMixin<T> extends ActionHandler {
```
Available values for the `type` parameter are `'boolean'`, `'number'`, `'array'`, and `'string'`.
If query param type is not specified, it will default to `'string'`.
+ @public
*/
queryParams: Array<ControllerQueryParam>;
@@ -140,6 +143,7 @@ interface ControllerMixin<T> extends ActionHandler {
```
See also [replaceRoute](/ember/release/classes/Ember.ControllerMixin/methods/replaceRoute?anchor=replaceRoute).
+ @public
*/
transitionToRoute(...args: RouteArgs<Route>): Transition;
@@ -192,6 +196,7 @@ interface ControllerMixin<T> extends ActionHandler {
aController.replaceRoute('/');
aController.replaceRoute('/blog/post/1/comment/13');
```
+ @public
*/
replaceRoute(...args: RouteArgs<Route>): Transition;
} | false |
Other | emberjs | ember.js | a6d6831e242eb410a2d924735746119ccd25c95c.json | fix TypeWatcher invoking itself during onChange | packages/@ember/debug/data-adapter.ts | @@ -1,6 +1,6 @@
import type { Owner } from '@ember/-internals/owner';
import { getOwner } from '@ember/-internals/owner';
-import { _backburner } from '@ember/runloop';
+import { _backburner, next } from '@ember/runloop';
import { get } from '@ember/object';
import { dasherize } from '@ember/string';
import Namespace from '@ember/application/namespace';
@@ -141,7 +141,7 @@ class TypeWatcher {
consumeTag(tagFor(records, '[]'));
if (hasBeenAccessed === true) {
- onChange();
+ next(onChange);
} else {
hasBeenAccessed = true;
} | false |
Other | emberjs | ember.js | 46774eba9a2e8956dd7227cdbd08aad96fe74b26.json | Add v4.8.0-beta.3 to CHANGELOG
(cherry picked from commit 975b69e3de1bc8f8f6ad2c5096438c35c712f8ff) | CHANGELOG.md | @@ -1,5 +1,10 @@
# Ember Changelog
+### v4.8.0-beta.3 (September 19, 2022)
+
+- [#20194](https://github.com/emberjs/ember.js/pull/20194) [BUGFIX] Provide a `.d.ts` file at types/stable
+- [#20196](https://github.com/emberjs/ember.js/pull/20196) [BUGFIX] types imports are at 'ember-source/types'
+
### v4.8.0-beta.2 (September 13, 2022)
- [#20186](https://github.com/emberjs/ember.js/pull/20186) [BUGFIX] Fix `@ember/runloop` type tests folder name so that the tests are properly excluded from the build | false |
Other | emberjs | ember.js | 2290078615a70a22013bc4780b4239bb92e1b534.json | fix license year | LICENSE | @@ -1,4 +1,4 @@
-Copyright (c) 2020 Yehuda Katz, Tom Dale and Ember.js contributors
+Copyright (c) 2022 Yehuda Katz, Tom Dale and Ember.js contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in | false |
Other | emberjs | ember.js | 40c1c8df3a10896db1f2e66e768b6985a53f208b.json | Use quickfix to fix two typescript errors | packages/@ember/-internals/container/lib/container.ts | @@ -225,13 +225,15 @@ if (DEBUG) {
* Wrap a factory manager in a proxy which will not permit properties to be
* set on the manager.
*/
-function wrapManagerInDeprecationProxy<T extends object, C>(
+function wrapManagerInDeprecationProxy<T extends object, C extends object | FactoryClass>(
manager: FactoryManager<T, C>
): FactoryManager<T, C> {
let validator = {
set(_obj: T, prop: keyof T) {
throw new Error(
- `You attempted to set "${prop}" on a factory manager created by container#factoryFor. A factory manager is a read-only construct.`
+ `You attempted to set "${String(
+ prop
+ )}" on a factory manager created by container#factoryFor. A factory manager is a read-only construct.`
);
},
}; | false |
Other | emberjs | ember.js | 4588ee19a79d635e13ffa15aeaa485b74171e904.json | remove the duplicate doc | packages/@ember/object/observable.ts | @@ -338,138 +338,18 @@ interface Observable {
cacheFor<K extends keyof this>(key: K): unknown;
}
const Observable = Mixin.create({
- /**
- Retrieves the value of a property from the object.
-
- This method is usually similar to using `object[keyName]` or `object.keyName`,
- however it supports both computed properties and the unknownProperty
- handler.
-
- Because `get` unifies the syntax for accessing all these kinds
- of properties, it can make many refactorings easier, such as replacing a
- simple property with a computed property, or vice versa.
-
- ### Computed Properties
-
- Computed properties are methods defined with the `property` modifier
- declared at the end, such as:
-
- ```javascript
- import { computed } from '@ember/object';
-
- fullName: computed('firstName', 'lastName', function() {
- return this.get('firstName') + ' ' + this.get('lastName');
- })
- ```
-
- When you call `get` on a computed property, the function will be
- called and the return value will be returned instead of the function
- itself.
-
- ### Unknown Properties
-
- Likewise, if you try to call `get` on a property whose value is
- `undefined`, the `unknownProperty()` method will be called on the object.
- If this method returns any value other than `undefined`, it will be returned
- instead. This allows you to implement "virtual" properties that are
- not defined upfront.
-
- @method get
- @param {String} keyName The property to retrieve
- @return {Object} The property value or undefined.
- @public
- */
get(keyName: string) {
return get(this, keyName);
},
- /**
- To get the values of multiple properties at once, call `getProperties`
- with a list of strings or an array:
-
- ```javascript
- record.getProperties('firstName', 'lastName', 'zipCode');
- // { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
- ```
-
- is equivalent to:
-
- ```javascript
- record.getProperties(['firstName', 'lastName', 'zipCode']);
- // { firstName: 'John', lastName: 'Doe', zipCode: '10011' }
- ```
-
- @method getProperties
- @param {String...|Array} list of keys to get
- @return {Object}
- @public
- */
getProperties(...args: string[]) {
return getProperties(this, ...args);
},
- /**
- Sets the provided key or path to the value.
-
- ```javascript
- record.set("key", value);
- ```
-
- This method is generally very similar to calling `object["key"] = value` or
- `object.key = value`, except that it provides support for computed
- properties, the `setUnknownProperty()` method and property observers.
-
- ### Computed Properties
-
- If you try to set a value on a key that has a computed property handler
- defined (see the `get()` method for an example), then `set()` will call
- that method, passing both the value and key instead of simply changing
- the value itself. This is useful for those times when you need to
- implement a property that is composed of one or more member
- properties.
-
- ### Unknown Properties
-
- If you try to set a value on a key that is undefined in the target
- object, then the `setUnknownProperty()` handler will be called instead. This
- gives you an opportunity to implement complex "virtual" properties that
- are not predefined on the object. If `setUnknownProperty()` returns
- undefined, then `set()` will simply set the value on the object.
-
- ### Property Observers
-
- In addition to changing the property, `set()` will also register a property
- change with the object. Unless you have placed this call inside of a
- `beginPropertyChanges()` and `endPropertyChanges(),` any "local" observers
- (i.e. observer methods declared on the same object), will be called
- immediately. Any "remote" observers (i.e. observer methods declared on
- another object) will be placed in a queue and called at a later time in a
- coalesced manner.
-
- @method set
- @param {String} keyName The property to set
- @param {Object} value The value to set or `null`.
- @return {Object} The passed value
- @public
- */
set(keyName: string, value: unknown) {
return set(this, keyName, value);
},
- /**
- Sets a list of properties at once. These properties are set inside
- a single `beginPropertyChanges` and `endPropertyChanges` batch, so
- observers will be buffered.
-
- ```javascript
- record.setProperties({ firstName: 'Charles', lastName: 'Jolley' });
- ```
-
- @method setProperties
- @param {Object} hash the hash of keys and values to set
- @return {Object} The passed in hash
- @public
- */
setProperties(hash: object) {
return setProperties(this, hash);
},
@@ -531,89 +411,6 @@ const Observable = Mixin.create({
return this;
},
- /**
- Adds an observer on a property.
-
- This is the core method used to register an observer for a property.
-
- Once you call this method, any time the key's value is set, your observer
- will be notified. Note that the observers are triggered any time the
- value is set, regardless of whether it has actually changed. Your
- observer should be prepared to handle that.
-
- There are two common invocation patterns for `.addObserver()`:
-
- - Passing two arguments:
- - the name of the property to observe (as a string)
- - the function to invoke (an actual function)
- - Passing three arguments:
- - the name of the property to observe (as a string)
- - the target object (will be used to look up and invoke a
- function on)
- - the name of the function to invoke on the target object
- (as a string).
-
- ```app/components/my-component.js
- import Component from '@ember/component';
-
- export default Component.extend({
- init() {
- this._super(...arguments);
-
- // the following are equivalent:
-
- // using three arguments
- this.addObserver('foo', this, 'fooDidChange');
-
- // using two arguments
- this.addObserver('foo', (...args) => {
- this.fooDidChange(...args);
- });
- },
-
- fooDidChange() {
- // your custom logic code
- }
- });
- ```
-
- ### Observer Methods
-
- Observer methods have the following signature:
-
- ```app/components/my-component.js
- import Component from '@ember/component';
-
- export default Component.extend({
- init() {
- this._super(...arguments);
- this.addObserver('foo', this, 'fooDidChange');
- },
-
- fooDidChange(sender, key, value, rev) {
- // your code
- }
- });
- ```
-
- The `sender` is the object that changed. The `key` is the property that
- changes. The `value` property is currently reserved and unused. The `rev`
- is the last property revision of the object when it changed, which you can
- use to detect if the key value has really changed or not.
-
- Usually you will not need the value or revision parameters at
- the end. In this case, it is common to write observer methods that take
- only a sender and key value as parameters or, if you aren't interested in
- any of these values, to write an observer that has no parameters at all.
-
- @method addObserver
- @param {String} key The key to observe
- @param {Object} target The target object to invoke
- @param {String|Function} method The method to invoke
- @param {Boolean} sync Whether the observer is sync or not
- @return {Observable}
- @public
- */
addObserver(
key: string,
target: object | Function | null,
@@ -624,19 +421,6 @@ const Observable = Mixin.create({
return this;
},
- /**
- Remove an observer you have previously registered on this object. Pass
- the same key, target, and method you passed to `addObserver()` and your
- target will no longer receive notifications.
-
- @method removeObserver
- @param {String} key The key to observe
- @param {Object} target The target object to invoke
- @param {String|Function} method The method to invoke
- @param {Boolean} sync Whether the observer is async or not
- @return {Observable}
- @public
- */
removeObserver(
key: string,
target: object | Function | null,
@@ -662,20 +446,6 @@ const Observable = Mixin.create({
return hasListeners(this, `${key}:change`);
},
- /**
- Set the value of a property to the current value plus some amount.
-
- ```javascript
- person.incrementProperty('age');
- team.incrementProperty('score', 2);
- ```
-
- @method incrementProperty
- @param {String} keyName The name of the property to increment
- @param {Number} increment The amount to increment by. Defaults to 1
- @return {Number} The new property value
- @public
- */
incrementProperty(keyName: string, increment = 1) {
assert(
'Must pass a numeric value to incrementProperty',
@@ -684,20 +454,6 @@ const Observable = Mixin.create({
return set(this, keyName, (parseFloat(get(this, keyName)) || 0) + increment);
},
- /**
- Set the value of a property to the current value minus some amount.
-
- ```javascript
- player.decrementProperty('lives');
- orc.decrementProperty('health', 5);
- ```
-
- @method decrementProperty
- @param {String} keyName The name of the property to decrement
- @param {Number} decrement The amount to decrement by. Defaults to 1
- @return {Number} The new property value
- @public
- */
decrementProperty(keyName: string, decrement = 1) {
assert(
'Must pass a numeric value to decrementProperty',
@@ -706,34 +462,10 @@ const Observable = Mixin.create({
return set(this, keyName, (get(this, keyName) || 0) - decrement);
},
- /**
- Set the value of a boolean property to the opposite of its
- current value.
-
- ```javascript
- starship.toggleProperty('warpDriveEngaged');
- ```
-
- @method toggleProperty
- @param {String} keyName The name of the property to toggle
- @return {Boolean} The new property value
- @public
- */
toggleProperty(keyName: string) {
return set(this, keyName, !get(this, keyName));
},
- /**
- Returns the cached value of a computed property, if it exists.
- This allows you to inspect the value of a computed property
- without accidentally invoking it if it is intended to be
- generated lazily.
-
- @method cacheFor
- @param {String} keyName
- @return {Object} The cached value of the computed property, if any
- @public
- */
cacheFor(keyName: string) {
let meta = peekMeta(this);
| false |
Other | emberjs | ember.js | eac8bdfaf95a0e04e34f93465c948bfae275b577.json | Use service registry in owner.lookup | type-tests/preview/@ember/owner-tests.ts | @@ -64,6 +64,13 @@ expectTypeOf(owner.lookup('type:name')).toEqualTypeOf<unknown>();
owner.lookup('non-namespace-string');
expectTypeOf(owner.lookup('namespace@type:name')).toEqualTypeOf<unknown>();
+declare module '@ember/service' {
+ interface Registry {
+ 'my-type-test-service': ConstructThis;
+ }
+}
+expectTypeOf(owner.lookup('service:my-type-test-service')).toEqualTypeOf<ConstructThis>();
+
expectTypeOf(owner.register('type:name', aFactory)).toEqualTypeOf<void>();
expectTypeOf(owner.register('type:name', aFactory, {})).toEqualTypeOf<void>();
expectTypeOf(owner.register('type:name', aFactory, { instantiate: true })).toEqualTypeOf<void>(); | true |
Other | emberjs | ember.js | eac8bdfaf95a0e04e34f93465c948bfae275b577.json | Use service registry in owner.lookup | types/preview/@ember/owner/index.d.ts | @@ -1,13 +1,12 @@
declare module '@ember/owner' {
+ import type { Registry } from '@ember/service';
+
/**
* The name for a factory consists of a namespace and the name of a specific
* type within that namespace, like `'service:session'`.
*/
export type FullName = `${string}:${string}`;
- // TODO: when migrating into Ember proper, evaluate whether we should introduce
- // a registry which users can provide to resolve known types, so e.g.
- // `owner.lookup('service:session')` can return the right thing.
/**
* Framework objects in an Ember application (components, services, routes,
* etc.) are created via a factory and dependency injection system. Each of
@@ -18,6 +17,7 @@ declare module '@ember/owner' {
/**
* Given a {@linkcode FullName} return a corresponding instance.
*/
+ lookup<Name extends keyof Registry>(fullName: `service:${Name}`): Registry[Name];
lookup(fullName: FullName): unknown;
/** | true |
Other | emberjs | ember.js | f48affedde8e19f617c973b4c01df33dfc475fee.json | Add v4.8.0-beta.1 to CHANGELOG
(cherry picked from commit 72f117864bd5054fd3c0098221ca9770aa0e1137) | CHANGELOG.md | @@ -1,5 +1,9 @@
# Ember Changelog
+### v4.8.0-beta.1 (September 6, 2022)
+
+- [#20166](https://github.com/emberjs/ember.js/pull/20166) [BUGFIX] Upgrade router_js to fix Linked list of RouteInfos contains undefined object
+
### v4.7.0 (September 6, 2022)
- [#20126](https://github.com/emberjs/ember.js/pull/20126) [BUGFIX] Replace Firefox detection that used a deprecated browser API | false |
Other | emberjs | ember.js | bf16bd3c4b5c209cd68d7704e5c367b488210634.json | Add v4.7.0 to CHANGELOG
(cherry picked from commit 0c59b21bb380daa491d9d9fcb1dc27fd5e56cd5d) | CHANGELOG.md | @@ -1,8 +1,8 @@
# Ember Changelog
-### v4.7.0-beta.1 (July 25, 2022)
+### v4.7.0 (September 6, 2022)
-- [#20126](https://github.com/emberjs/ember.js/pull/20126) [BUGFIX] Replacing Firefox detection that used a deprecated browser API
+- [#20126](https://github.com/emberjs/ember.js/pull/20126) [BUGFIX] Replace Firefox detection that used a deprecated browser API
### v4.6.0 (July 25, 2022)
| false |
Other | emberjs | ember.js | 119b42cf214ff9c2bb5855787df68629b32afb16.json | Types preview: remove dead imports
The corresponding module declarations were removed earlier; this simply
drops the 'side-effect' imports from `types/preview/index.d.ts`. | types/preview/index.d.ts | @@ -89,10 +89,7 @@ import './@ember/polyfills';
import './@ember/polyfills/types';
import './@ember/routing';
-import './@ember/routing/-private/route-info'; // TODO: remove
-import './@ember/routing/-private/route-info-with-attributes'; // TODO: remove
import './@ember/routing/-private/router-dsl';
-import './@ember/routing/-private/transition'; // TODO: remove
import './@ember/routing/auto-location';
import './@ember/routing/hash-location';
import './@ember/routing/history-location'; | false |
Other | emberjs | ember.js | 3fcc6d61d00e50ef0ca9f33e28fb8fc6fa4931e9.json | Fix import circularity | packages/@ember/controller/index.ts | @@ -1,4 +1,4 @@
-import { getOwner } from '@ember/application';
+import { getOwner } from '@ember/-internals/owner'; // This is imported from -internals to avoid circularity
import { computed, get } from '@ember/object';
import { FrameworkObject } from '@ember/object/-internals';
import { inject as metalInject } from '@ember/-internals/metal'; | false |
Other | emberjs | ember.js | 17df5a1fed5cc42dfe511b2f6a2cd94f7ee03832.json | Remove types for array prototype extensions
See previous commit message for discussion of *why* these are being
removed. If we decide to re-introduce these types later, it will require
not only adding back in these tests but also taking some fairly distinct
approach to their inclusion, given the problems with the way they work. | package.json | @@ -43,7 +43,6 @@
"lint:eslint:fix": "npm-run-all \"lint:eslint --fix\"",
"lint:tsc:stable": "tsc --noEmit",
"lint:tsc:preview": "tsc --noEmit --project type-tests/preview",
- "lint:tsc:preview-array-ext": "tsc --noEmit --project type-tests/preview-prototype-extensions",
"lint:tsc": "npm-run-all lint:tsc:*",
"lint:fix": "npm-run-all lint:*:fix",
"test": "node bin/run-tests.js", | true |
Other | emberjs | ember.js | 17df5a1fed5cc42dfe511b2f6a2cd94f7ee03832.json | Remove types for array prototype extensions
See previous commit message for discussion of *why* these are being
removed. If we decide to re-introduce these types later, it will require
not only adding back in these tests but also taking some fairly distinct
approach to their inclusion, given the problems with the way they work. | type-tests/preview-prototype-extensions/README.md | @@ -1 +0,0 @@
-This exists so we can test the *rest* of the system *without* pulling in Array prototype extensions. | true |
Other | emberjs | ember.js | 17df5a1fed5cc42dfe511b2f6a2cd94f7ee03832.json | Remove types for array prototype extensions
See previous commit message for discussion of *why* these are being
removed. If we decide to re-introduce these types later, it will require
not only adding back in these tests but also taking some fairly distinct
approach to their inclusion, given the problems with the way they work. | type-tests/preview-prototype-extensions/array-module-ext.ts | @@ -1,21 +0,0 @@
-import EmberObject from '@ember/object';
-import { expectTypeOf } from 'expect-type';
-import type NativeArray from '@ember/array/-private/native-array';
-
-class Person extends EmberObject {
- declare name: string;
-}
-
-const person = Person.create({ name: 'Joe' });
-const array = [person];
-
-expectTypeOf(array.get('length')).toBeNumber();
-expectTypeOf(array.get('firstObject')).toEqualTypeOf<Person | undefined>();
-expectTypeOf(array.mapBy('name')).toEqualTypeOf<NativeArray<string>>();
-expectTypeOf(array.map((p) => p.get('name'))).toEqualTypeOf<string[]>();
-// These use `toMatchTypeOf` instead of `toEqualTypeOf` because they are not
-// actually returning `Array`; they return `Ember.NativeArray`
-expectTypeOf(array.sortBy('name')).toMatchTypeOf<Person[]>();
-expectTypeOf(array.uniq()).toMatchTypeOf<Person[]>();
-expectTypeOf(array.uniqBy('name')).toMatchTypeOf<Person[]>();
-expectTypeOf(array.uniqBy((p) => p.get('name'))).toMatchTypeOf<Person[]>(); | true |
Other | emberjs | ember.js | 17df5a1fed5cc42dfe511b2f6a2cd94f7ee03832.json | Remove types for array prototype extensions
See previous commit message for discussion of *why* these are being
removed. If we decide to re-introduce these types later, it will require
not only adding back in these tests but also taking some fairly distinct
approach to their inclusion, given the problems with the way they work. | type-tests/preview-prototype-extensions/ember-namespace-array-ext.ts | @@ -1,18 +0,0 @@
-import Ember from 'ember';
-import { expectTypeOf } from 'expect-type';
-
-class Person extends Ember.Object {
- declare name: string;
-}
-
-const person = Person.create({ name: 'Joe' });
-const array = [person];
-
-expectTypeOf(array.get('length')).toBeNumber();
-expectTypeOf(array.get('firstObject')).toEqualTypeOf<Person | undefined>();
-expectTypeOf(array.mapBy('name')).toMatchTypeOf<string[]>();
-expectTypeOf(array.map((p) => p.get('name'))).toEqualTypeOf<string[]>();
-// These return `Ember.NativeArray` so use `toMatchTypeOf`
-expectTypeOf(array.sortBy('name')).toMatchTypeOf<Person[]>();
-expectTypeOf(array.uniq()).toMatchTypeOf<Person[]>();
-expectTypeOf(array.uniqBy('name')).toMatchTypeOf<Person[]>(); | true |
Other | emberjs | ember.js | 17df5a1fed5cc42dfe511b2f6a2cd94f7ee03832.json | Remove types for array prototype extensions
See previous commit message for discussion of *why* these are being
removed. If we decide to re-introduce these types later, it will require
not only adding back in these tests but also taking some fairly distinct
approach to their inclusion, given the problems with the way they work. | type-tests/preview-prototype-extensions/index.d.ts | @@ -1,6 +0,0 @@
-import '../../types/preview';
-import type ArrayPrototypeExtensions from '@ember/array/types/prototype-extensions';
-
-declare global {
- interface Array<T> extends ArrayPrototypeExtensions<T> {}
-} | true |
Other | emberjs | ember.js | 17df5a1fed5cc42dfe511b2f6a2cd94f7ee03832.json | Remove types for array prototype extensions
See previous commit message for discussion of *why* these are being
removed. If we decide to re-introduce these types later, it will require
not only adding back in these tests but also taking some fairly distinct
approach to their inclusion, given the problems with the way they work. | type-tests/preview-prototype-extensions/tsconfig.json | @@ -1,3 +0,0 @@
-{
- "extends": "@tsconfig/ember/tsconfig.json",
-} | true |
Other | emberjs | ember.js | 17df5a1fed5cc42dfe511b2f6a2cd94f7ee03832.json | Remove types for array prototype extensions
See previous commit message for discussion of *why* these are being
removed. If we decide to re-introduce these types later, it will require
not only adding back in these tests but also taking some fairly distinct
approach to their inclusion, given the problems with the way they work. | types/preview/@ember/array/types/prototype-extensions.d.ts | @@ -1,6 +0,0 @@
-declare module '@ember/array/types/prototype-extensions' {
- import Observable from '@ember/object/observable';
- import MutableArray from '@ember/array/mutable';
-
- export default interface ArrayPrototypeExtensions<T> extends MutableArray<T>, Observable {}
-} | true |
Other | emberjs | ember.js | 17df5a1fed5cc42dfe511b2f6a2cd94f7ee03832.json | Remove types for array prototype extensions
See previous commit message for discussion of *why* these are being
removed. If we decide to re-introduce these types later, it will require
not only adding back in these tests but also taking some fairly distinct
approach to their inclusion, given the problems with the way they work. | types/preview/ember/index.d.ts | @@ -44,7 +44,6 @@ declare module 'ember' {
import EmberArrayProxy from '@ember/array/proxy';
import type EmberEnumerable from '@ember/array/-private/enumerable';
import type EmberMutableEnumerable from '@ember/array/-private/mutable-enumerable';
- import type EmberArrayProtoExtensions from '@ember/array/types/prototype-extensions';
// @ember/error
import type EmberError from '@ember/error';
@@ -94,7 +93,6 @@ declare module 'ember' {
export const setOwner: typeof EmberApplicationNs.setOwner;
export class EventDispatcher extends EmberEventDispatcher {}
export class Registry extends EmberRegistry {}
- export interface ArrayPrototypeExtensions<T> extends EmberArrayProtoExtensions<T> {}
/**
* Implements some standard methods for comparing objects. Add this mixin to | true |
Other | emberjs | ember.js | 17df5a1fed5cc42dfe511b2f6a2cd94f7ee03832.json | Remove types for array prototype extensions
See previous commit message for discussion of *why* these are being
removed. If we decide to re-introduce these types later, it will require
not only adding back in these tests but also taking some fairly distinct
approach to their inclusion, given the problems with the way they work. | types/preview/index.d.ts | @@ -35,7 +35,6 @@ import './@ember/array/-private/mutable-enumerable';
import './@ember/array/-private/native-array';
import './@ember/array/mutable';
import './@ember/array/proxy';
-import './@ember/array/types/prototype-extensions';
import './@ember/component';
import './@ember/component/-private/class-names-support'; | true |
Other | emberjs | ember.js | a0fd30ad4ea3927e23f0563002a4f2c8fc77f7ab.json | Ignore a case where Ember.get is distinct from get
While we would prefer this to work, it is not a hard necessity, for (at
least) two reasons:
1. Use of `Ember.get` vs. the import from `@ember/object` is rare and
should be discouraged.
2. Use of `get` is itself fairly unusual to *need* these days; most
uses either will not hit this case, as in the deep key lookup (which
is always just `unknown` anyways) or should be trivially replaced
with direct property access (since Ember 3.1!). | types/preview/ember/test/object.ts | @@ -65,8 +65,18 @@ export class Foo2 extends Ember.Object {
// (currently) possible for the type utility to match it.
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const x: string = Ember.set(this, 'name', name);
+
+ // TODO: it would be nice if we can get this to work correctly; it is
+ // unclear why the version on the namespace does *not* work correctly but
+ // the standalone version *does*. However, the Ember namespace should be
+ // little used (and hopefully we will deprecate it soon), and `get` itself
+ // is in much the same bucket: 99% of cases are *either* totally unsafe deep
+ // key access like `get(foo, 'bar.baz.quux')` which we do not support at all
+ // *or* they can be trivially codemodded to direct property access.
+ // @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const y: string = Ember.get(this, 'name');
+
this.setProperties({
name,
}); | false |
Other | emberjs | ember.js | 2dc87a1060efe1dbe8616a7c50d68fa78ed4149b.json | Add sundry improvements to preview types. | packages/@ember/-internals/runtime/lib/mixins/registry_proxy.ts | @@ -12,6 +12,14 @@ import { assert } from '@ember/debug';
// This is defined as a separate interface so that it can be used in the definition of
// `Owner` without also including the `__registry__` property.
export interface IRegistry {
+ /**
+ Given a fullName return the corresponding factory.
+
+ @public
+ @method resolveRegistration
+ @param {String} fullName
+ @return {Function} fullName's factory
+ */
resolveRegistration(fullName: string): Factory<object> | object | undefined;
register(fullName: string, factory: Factory<object> | object, options?: TypeOptions): void;
@@ -48,14 +56,6 @@ interface RegistryProxyMixin extends IRegistry {
const RegistryProxyMixin = Mixin.create({
__registry__: null,
- /**
- Given a fullName return the corresponding factory.
-
- @public
- @method resolveRegistration
- @param {String} fullName
- @return {Function} fullName's factory
- */
resolveRegistration(fullName: string) {
assert('fullName must be a proper full name', this.__registry__.isValidFullName(fullName));
return this.__registry__.resolve(fullName); | true |
Other | emberjs | ember.js | 2dc87a1060efe1dbe8616a7c50d68fa78ed4149b.json | Add sundry improvements to preview types. | types/preview/@ember/engine/test/engine.ts | @@ -23,20 +23,20 @@ BaseEngine.instanceInitializer({
},
});
-const Engine1 = BaseEngine.create({
- rootElement: '#engine-one',
- customEvents: {
+class Engine1 extends BaseEngine {
+ rootElement = '#engine-one';
+ customEvents = {
paste: 'paste',
- },
-});
+ };
+}
-const Engine2 = BaseEngine.create({
- rootElement: '#engine-two',
- customEvents: {
+class Engine2 extends BaseEngine {
+ rootElement = '#engine-two';
+ customEvents = {
mouseenter: null,
mouseleave: null,
- },
-});
+ };
+}
const Engine3 = BaseEngine.create();
| true |
Other | emberjs | ember.js | 2dc87a1060efe1dbe8616a7c50d68fa78ed4149b.json | Add sundry improvements to preview types. | types/preview/@ember/object/test/create-negative.ts | @@ -1,11 +1,8 @@
-import { assertType } from './lib/assert';
-import { PersonWithNumberName, Person } from './create';
+import { Person } from './create';
// @ts-expect-error
Person.create({ firstName: 99 });
// @ts-expect-error
Person.create({}, { firstName: 99 });
// @ts-expect-error
Person.create({}, {}, { firstName: 99 });
-
-const p4 = new PersonWithNumberName(); | true |
Other | emberjs | ember.js | 2dc87a1060efe1dbe8616a7c50d68fa78ed4149b.json | Add sundry improvements to preview types. | types/preview/@ember/object/test/object.ts | @@ -1,102 +1,88 @@
-import EmberObject, { computed, notifyPropertyChange } from '@ember/object';
+import Object, { computed, get, notifyPropertyChange, set, setProperties } from '@ember/object';
+import { expectTypeOf } from 'expect-type';
-const LifetimeHooks = EmberObject.extend({
- resource: undefined as {} | undefined,
+class LifetimeHooks extends Object {
+ resource: {} | undefined;
- init() {
- this._super();
- this.resource = {};
- },
+ init() {
+ this._super();
+ this.resource = {};
+ }
- willDestroy() {
- this.resource = undefined;
- this._super();
- },
-});
+ willDestroy() {
+ this.resource = undefined;
+ this._super();
+ }
+}
-class MyObject30 extends EmberObject {
- constructor() {
- super();
- }
+class MyObject30 extends Object {
+ constructor() {
+ super();
+ }
}
-class MyObject31 extends EmberObject {
- constructor(properties: object) {
- super(properties);
- }
+class MyObject31 extends Object {
+ constructor(properties: object) {
+ super(properties);
+ }
}
-class Foo extends EmberObject {
- a = computed({
- get() {
- return '';
- },
- set(key: string, newVal: string) {
- return '';
- },
- });
- b = 5;
- c = computed({
- get() {
- return '';
- },
- set(key: string, newVal: string | number) {
- return '';
- }
- });
- baz() {
- const x = this.a; // $ExpectType ComputedProperty<string, string>
- const y = this.b; // $ExpectType number
- const z = this.c; // $ExpectType ComputedProperty<string, string | number>
- this.b = 10;
- this.get('b').toFixed(4); // $ExpectType string
- this.set('a', 'abc').split(','); // $ExpectType string[]
- this.set('b', 10).toFixed(4); // $ExpectType string
- this.get('c').split(','); // $ExpectType string[]
- this.set('c', '10').split(','); // $ExpectType string[]
- this.set('c', 10);
- // @ts-expect-error
- this.set('c', 10).split(',');
+class Foo extends Object {
+ @computed()
+ get a() {
+ return '';
+ }
+
+ set a(newVal: string) {
+ /* no-op */
+ }
+
+ b = 5;
+
+ baz() {
+ const y = this.b; // $ExpectType number
+ const z = this.a; // $ExpectType ComputedProperty<string, string>
+ this.b = 10;
+ this.get('b').toFixed(4); // $ExpectType string
+ this.set('a', 'abc').split(','); // $ExpectType string[]
+ this.set('b', 10).toFixed(4); // $ExpectType string
- this.setProperties({ b: 11 });
- // this.setProperties({ b: '11' }); // @ts-expect-error
- this.setProperties({
- a: 'def',
- b: 11,
- });
- }
- bar() {
- notifyPropertyChange(this, 'name');
- // @ts-expect-error
- notifyPropertyChange(this);
- // @ts-expect-error
- notifyPropertyChange('name');
- // @ts-expect-error
- notifyPropertyChange(this, 'name', 'bar');
- }
+ this.setProperties({ b: 11 });
+ // this.setProperties({ b: '11' }); // @ts-expect-error
+ this.setProperties({
+ a: 'def',
+ b: 11,
+ });
+ }
}
-// TODO: enable after TS 3.0 https://github.com/typed-ember/ember-cli-typescript/issues/291
-// class Foo extends EmberObject.extend({
-// a: computed({
-// get() { return ''; },
-// set(key: string, newVal: string) { return ''; }
-// })
-// }) {
-// b = 5;
-// baz() {
-// const y = this.b; // $ExpectType number
-// const z = this.a; // $ExpectType ComputedProperty<string, string>
-// this.b = 10;
-// this.get('b').toFixed(4); // $ExpectType string
-// this.set('a', 'abc').split(','); // $ExpectType string[]
-// this.set('b', 10).toFixed(4); // $ExpectType string
+export class Foo2 extends Object {
+ name = '';
-// this.setProperties({ b: 11 });
-// // this.setProperties({ b: '11' }); // @ts-expect-error
-// this.setProperties({
-// a: 'def',
-// b: 11
-// });
-// }
-// }
+ changeName(name: string) {
+ expectTypeOf(this.set('name', name)).toEqualTypeOf<string>();
+ // This is checking for assignability; `expectTypeOf` doesn't work correctly
+ // here because TS isn't resolving `this['name']` eagerly, and so it is not
+ // (currently) possible for the type utility to match it.
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const x: string = set(this, 'name', name);
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
+ const y: string = get(this, 'name');
+ this.setProperties({
+ name,
+ });
+ setProperties(this, {
+ name,
+ });
+ }
+
+ bar() {
+ notifyPropertyChange(this, 'name');
+ // @ts-expect-error
+ notifyPropertyChange(this);
+ // @ts-expect-error
+ notifyPropertyChange('name');
+ // @ts-expect-error
+ notifyPropertyChange(this, 'name', 'bar');
+ }
+} | true |
Other | emberjs | ember.js | 2dc87a1060efe1dbe8616a7c50d68fa78ed4149b.json | Add sundry improvements to preview types. | types/preview/@ember/object/test/proxy.ts | @@ -1,44 +1,50 @@
import Ember from 'ember';
import ObjectProxy from '@ember/object/proxy';
+import { expectTypeOf } from 'expect-type';
interface Book {
- title: string;
- subtitle: string;
- chapters: Array<{ title: string }>;
+ title: string;
+ subtitle: string;
+ chapters: Array<{ title: string }>;
}
class DefaultProxy extends ObjectProxy {}
DefaultProxy.create().content; // $ExpectType object | undefined
class BookProxy extends ObjectProxy<Book> {
- private readonly baz = 'baz';
+ private readonly baz = 'baz';
- altTitle = 'Alt';
+ altTitle = 'Alt';
- getTitle() {
- return this.get('title');
- }
+ getTitle() {
+ return this.get('title');
+ }
- getPropertiesTitleSubtitle() {
- return this.getProperties('title', 'subtitle');
- }
+ getPropertiesTitleSubtitle() {
+ return this.getProperties('title', 'subtitle');
+ }
}
const book = BookProxy.create();
-book.content; // $ExpectType Book | undefined
+expectTypeOf(book.content).toEqualTypeOf<Book | undefined>(); // $ExpectType Book | undefined
// @ts-expect-error
book.get('unknownProperty');
-book.get('title'); // $ExpectType string | undefined
-book.get('altTitle'); // $ExpectType string
-book.getTitle(); // $ExpectType string | undefined
+expectTypeOf(book.get('title')).toEqualTypeOf<string | undefined>();
+expectTypeOf(book.get('altTitle')).toBeString();
+expectTypeOf(book.getTitle()).toEqualTypeOf<string | undefined>();
// @ts-expect-error
book.getProperties('title', 'unknownProperty');
-book.getProperties('title', 'subtitle'); // $ExpectType Pick<Partial<UnwrapComputedPropertyGetters<Book>>, "title" | "subtitle">
-book.getPropertiesTitleSubtitle(); // $ExpectType Pick<Partial<UnwrapComputedPropertyGetters<Book>>, "title" | "subtitle">
-// tslint:disable-next-line
-book.getProperties(['subtitle', 'chapters']); // $ExpectType Pick<Partial<UnwrapComputedPropertyGetters<Book>>, "subtitle" | "chapters"> || Pick<Partial<UnwrapComputedPropertyGetters<Book>>, "chapters" | "subtitle">
+expectTypeOf(book.getProperties('title', 'subtitle')).toEqualTypeOf<
+ Pick<Partial<Book>, 'title' | 'subtitle'>
+>();
+expectTypeOf(book.getPropertiesTitleSubtitle()).toEqualTypeOf<
+ Pick<Partial<Book>, 'title' | 'subtitle'>
+>();
+expectTypeOf(book.getProperties(['subtitle', 'chapters'])).toEqualTypeOf<
+ Pick<Partial<Book>, 'subtitle' | 'chapters'>
+>();
// @ts-expect-error
book.getProperties(['title', 'unknownProperty']);
@@ -52,9 +58,9 @@ book.set('altTitle', 'Alternate');
// @ts-expect-error
book.set('altTitle', 1);
book.setProperties({
- title: 'new',
- subtitle: 'and improved',
- altTitle: 'Alternate2',
+ title: 'new',
+ subtitle: 'and improved',
+ altTitle: 'Alternate2',
});
// @ts-expect-error
book.setProperties({ title: 1 });
@@ -64,39 +70,38 @@ book.setProperties({ altTitle: 1 });
book.setProperties({ invalid: true });
class Person extends Ember.Object {
- firstName = 'Peter';
+ firstName = 'Peter';
- lastName = 'Wagenet';
+ lastName = 'Wagenet';
- fullName = Ember.computed('firstName', 'lastName', {
- get() {
- return `${this.firstName} ${this.lastName}`;
- },
+ @Ember.computed('firstName', 'lastName')
+ get fullName() {
+ return `${this.firstName} ${this.lastName}`;
+ }
- set(key, value: string) {
- const [firstName, lastName] = value.split(' ');
+ set fullName(value: string) {
+ const [firstName, lastName] = value.split(' ');
- Ember.set(this, 'firstName', firstName);
- Ember.set(this, 'lastName', lastName);
-
- return value;
- }
- });
+ Ember.set(this, 'firstName', firstName ?? '');
+ Ember.set(this, 'lastName', lastName ?? '');
+ }
}
-class PersonProxy extends ObjectProxy<Person> { }
+class PersonProxy extends ObjectProxy<Person> {}
const person = PersonProxy.create();
-person.get('firstName'); // $ExpectType string | undefined
-person.get('fullName'); // $ExpectType string | undefined
-person.set('fullName', 'John Doe'); // $ExpectType string
+expectTypeOf(person.get('firstName')).toEqualTypeOf<string | undefined>();
+expectTypeOf(person.get('fullName')).toEqualTypeOf<string | undefined>();
+expectTypeOf(person.set('fullName', 'John Doe')).toBeString();
// @ts-expect-error
person.set('fullName', 1);
// @ts-expect-error
person.set('invalid', true);
-person.setProperties({ fullName: 'John Doe' }); // $ExpectType Pick<UnwrapComputedPropertySetters<PersonProxy & Person>, "fullName">
-person.setProperties({ fullName: 'John Doe' }).fullName; // $ExpectType string
+expectTypeOf(person.setProperties({ fullName: 'John Doe' })).toEqualTypeOf<
+ Pick<PersonProxy & Person, 'fullName'>
+>();
+expectTypeOf(person.setProperties({ fullName: 'John Doe' }).fullName).toBeString();
// @ts-expect-error
person.setProperties({ fullName: 1 });
// @ts-expect-error | true |
Other | emberjs | ember.js | 2dc87a1060efe1dbe8616a7c50d68fa78ed4149b.json | Add sundry improvements to preview types. | types/preview/@ember/routing/test/route.ts | @@ -1,3 +1,4 @@
+/* eslint-disable prefer-const */
import Route from '@ember/routing/route';
import Array from '@ember/array';
import EmberObject from '@ember/object';
@@ -9,201 +10,201 @@ class Post extends EmberObject {}
interface Posts extends Array<Post> {}
-Route.extend({
- beforeModel(transition: Transition) {
- this.transitionTo('someOtherRoute');
- },
-});
-
-Route.extend({
- afterModel(posts: Posts, transition: Transition) {
- if (posts.firstObject) {
- this.transitionTo('post.show', posts.firstObject);
- }
- },
-});
-
-Route.extend({
- model() {
- return this.modelFor('post');
- },
-});
-
-Route.extend({
- queryParams: {
- memberQp: { refreshModel: true },
- },
-});
-
-Route.extend({
- resetController(controller: Controller, isExiting: boolean, transition: Transition) {
- if (isExiting) {
- // controller.set('page', 1);
- transition.abort();
- }
- },
-});
-
-class ActivateRoute extends Route {
- activate(transition: Transition) {
- this.transitionTo('someOtherRoute');
- }
+class BeforeModelText extends Route {
+ beforeModel(transition: Transition) {
+ this.transitionTo('someOtherRoute');
+ }
}
-class DeactivateRoute extends Route {
- deactivate(transition: Transition) {
- this.transitionTo('someOtherRoute');
+class AfterModel extends Route {
+ afterModel(posts: Posts, transition: Transition) {
+ if (posts.firstObject) {
+ this.transitionTo('post.show', posts.firstObject);
}
+ }
}
-class RedirectRoute extends Route {
- redirect(model: {}, a: Transition) {
- if (!model) {
- this.transitionTo('there');
- }
- }
+class ModelTest extends Route {
+ model() {
+ return this.modelFor('post');
+ }
}
-class InvalidRedirect extends Route {
- // @ts-expect-error
- redirect(model: {}, a: Transition, anOddArg: unknown) {
- if (!model) {
- this.transitionTo('there');
- }
- }
+class QPsTest extends Route {
+ queryParams = {
+ memberQp: { refreshModel: true },
+ };
}
-class TransitionToExamples extends Route {
- // NOTE: this one won't check that `queryParams` has the right shape,
- // because the overload for the version where `models` are passed
- // necessarily includes all objects.
- transitionToModelAndQP() {
- // $ExpectType Transition<unknown>
- this.transitionTo('somewhere', { queryParams: { neat: true } });
- }
-
- transitionToJustQP() {
- // $ExpectType Transition<unknown>
- this.transitionTo({ queryParams: { neat: 'true' } });
- }
-
- transitionToNonsense() {
- // @ts-expect-error
- this.transitionTo({ cannotDoModelHere: true });
+class ResetControllerTest extends Route {
+ resetController(controller: Controller, isExiting: boolean, transition: Transition) {
+ if (isExiting) {
+ // controller.set('page', 1);
+ transition.abort();
}
+ }
+}
- transitionToBadQP() {
- // @ts-expect-error
- this.transitionTo({ queryParams: 12 });
- }
+class ActivateRoute extends Route {
+ activate(transition: Transition) {
+ this.transitionTo('someOtherRoute');
+ }
+}
- transitionToId() {
- // $ExpectType Transition<unknown>
- this.transitionTo('blog-post', 1);
- }
+class DeactivateRoute extends Route {
+ deactivate(transition: Transition) {
+ this.transitionTo('someOtherRoute');
+ }
+}
- transitionToIdWithQP() {
- // $ExpectType Transition<unknown>
- this.transitionTo('blog-post', 1, { queryParams: { includeComments: true } });
+class RedirectRoute extends Route {
+ redirect(model: {}, a: Transition) {
+ if (!model) {
+ this.transitionTo('there');
}
+ }
+}
- transitionToIds() {
- // $ExpectType Transition<unknown>
- this.transitionTo('blog-comment', 1, '13');
+class InvalidRedirect extends Route {
+ // @ts-expect-error
+ redirect(model: {}, a: Transition, anOddArg: unknown) {
+ if (!model) {
+ this.transitionTo('there');
}
+ }
+}
- transitionToIdsWithQP() {
- // $ExpectType Transition<unknown>
- this.transitionTo('blog-comment', 1, '13', { queryParams: { includePost: true } });
- }
+class TransitionToExamples extends Route {
+ // NOTE: this one won't check that `queryParams` has the right shape,
+ // because the overload for the version where `models` are passed
+ // necessarily includes all objects.
+ transitionToModelAndQP() {
+ expectTypeOf(
+ this.transitionTo('somewhere', { queryParams: { neat: true } })
+ ).toEqualTypeOf<Transition>();
+ }
+
+ transitionToJustQP() {
+ expectTypeOf(this.transitionTo({ queryParams: { neat: 'true' } })).toEqualTypeOf<Transition>();
+ }
+
+ transitionToNonsense() {
+ // @ts-expect-error
+ this.transitionTo({ cannotDoModelHere: true });
+ }
- buildRouteInfoMetadata() {
- return { foo: 'bar' };
- }
+ transitionToBadQP() {
+ // @ts-expect-error
+ this.transitionTo({ queryParams: 12 });
+ }
+
+ transitionToId() {
+ // $ExpectType Transition<unknown>
+ this.transitionTo('blog-post', 1);
+ }
+
+ transitionToIdWithQP() {
+ // $ExpectType Transition<unknown>
+ this.transitionTo('blog-post', 1, { queryParams: { includeComments: true } });
+ }
+
+ transitionToIds() {
+ // $ExpectType Transition<unknown>
+ this.transitionTo('blog-comment', 1, '13');
+ }
+
+ transitionToIdsWithQP() {
+ // $ExpectType Transition<unknown>
+ this.transitionTo('blog-comment', 1, '13', { queryParams: { includePost: true } });
+ }
+
+ buildRouteInfoMetadata() {
+ return { foo: 'bar' };
+ }
}
class ApplicationController extends Controller {}
declare module '@ember/controller' {
- interface Registry {
- application: ApplicationController;
- }
+ interface Registry {
+ application: ApplicationController;
+ }
}
-Route.extend({
- setupController(controller: Controller, model: {}, transition: Transition) {
- this._super(controller, model);
- this.controllerFor('application').set('model', model);
- transition.abort();
- },
-});
+class SetupControllerTest extends Route {
+ setupController(controller: Controller, model: {}, transition: Transition) {
+ this._super(controller, model);
+ this.controllerFor('application').set('model', model);
+ transition.abort();
+ }
+}
const route = Route.create();
-route.controllerFor('whatever'); // $ExpectType Controller
-route.paramsFor('whatever'); // $ExpectType object
+expectTypeOf(route.controllerFor('whatever')).toEqualTypeOf<Controller>();
+expectTypeOf(route.paramsFor('whatever')).toEqualTypeOf<object>();
class RouteUsingClass extends Route.extend({
- randomProperty: 'the .extend + extends bit type-checks properly',
+ randomProperty: 'the .extend + extends bit type-checks properly',
}) {
- beforeModel() {
- return Promise.resolve('beforeModel can return promises');
- }
- afterModel(resolvedModel: unknown, transition: Transition) {
- return Promise.resolve('afterModel can also return promises');
- }
- intermediateTransitionWithoutModel() {
- this.intermediateTransitionTo('some-route');
- }
- intermediateTransitionWithModel() {
- this.intermediateTransitionTo('some.other.route', {});
- }
- intermediateTransitionWithMultiModel() {
- this.intermediateTransitionTo('some.other.route', 1, 2, {});
- }
+ beforeModel() {
+ return Promise.resolve('beforeModel can return promises');
+ }
+ afterModel(resolvedModel: unknown, transition: Transition) {
+ return Promise.resolve('afterModel can also return promises');
+ }
+ intermediateTransitionWithoutModel() {
+ this.intermediateTransitionTo('some-route');
+ }
+ intermediateTransitionWithModel() {
+ this.intermediateTransitionTo('some.other.route', {});
+ }
+ intermediateTransitionWithMultiModel() {
+ this.intermediateTransitionTo('some.other.route', 1, 2, {});
+ }
}
class WithNonReturningBeforeAndModelHooks extends Route {
- beforeModel(transition: Transition): void | Promise<unknown> {
- return;
- }
+ beforeModel(transition: Transition): void | Promise<unknown> {
+ return;
+ }
- afterModel(resolvedModel: unknown, transition: Transition): void {
- return;
- }
+ afterModel(resolvedModel: unknown, transition: Transition): void {
+ return;
+ }
}
class WithBadReturningBeforeAndModelHooks extends Route {
- beforeModel(transition: Transition): void | Promise<unknown> {
- // @ts-expect-error
- return "returning anything else is nonsensical (if 'legal')";
- }
+ beforeModel(transition: Transition): void | Promise<unknown> {
+ // @ts-expect-error
+ return "returning anything else is nonsensical (if 'legal')";
+ }
- afterModel(resolvedModel: unknown, transition: Transition): void {
- // @ts-expect-error
- return "returning anything else is nonsensical (if 'legal')";
- }
+ afterModel(resolvedModel: unknown, transition: Transition): void {
+ // @ts-expect-error
+ return "returning anything else is nonsensical (if 'legal')";
+ }
}
interface RouteParams {
- cool: string;
+ cool: string;
}
class WithParamsInModel extends Route<boolean, RouteParams> {
- model(params: RouteParams, transition: Transition) {
- return true;
- }
+ model(params: RouteParams, transition: Transition) {
+ return true;
+ }
}
// @ts-expect-error
class WithNonsenseParams extends Route<boolean, number> {}
class WithImplicitParams extends Route {
- model(params: RouteParams) {
- return { whatUp: 'dog' };
- }
+ model(params: RouteParams) {
+ return { whatUp: 'dog' };
+ }
}
-// $ExpectType RouteParams
type ImplicitParams = WithImplicitParams extends Route<any, infer T> ? T : never;
+expectTypeOf<ImplicitParams>().toEqualTypeOf<RouteParams>();
// back-compat for existing users of these
// NOTE: we will *not* migrate the private import locations when moving to
@@ -221,6 +222,7 @@ publicRouteInfo = privateRouteInfo;
privateRouteInfo = publicRouteInfo;
import PrivateRouteInfoWithAttributes from '@ember/routing/-private/route-info-with-attributes';
+import { expectTypeOf } from 'expect-type';
declare let publicRouteInfoWithAttributes: RouteInfoWithAttributes;
declare let privateRouteInfoWithAttributes: PrivateRouteInfoWithAttributes;
publicRouteInfoWithAttributes = privateRouteInfoWithAttributes; | true |
Other | emberjs | ember.js | 2dc87a1060efe1dbe8616a7c50d68fa78ed4149b.json | Add sundry improvements to preview types. | types/preview/@ember/runloop/index.d.ts | @@ -3,6 +3,7 @@ import {
EmberMethodParams,
AnyFn,
EmberMethodReturn,
+ AnyMethod,
} from 'ember/-private/type-utils';
import { EmberRunQueues } from './-private/types';
import { EmberRunTimer } from '@ember/runloop/types';
@@ -100,6 +101,12 @@ export function once<T, M extends EmberMethod<T>>(
...args: EmberMethodParams<T, M>
): EmberRunTimer;
+export function once<T, M extends keyof T>(
+ target: T,
+ method: M,
+ ...args: EmberMethodParams<T, M>
+): EmberRunTimer;
+
/**
* Schedules a function to run one time in a given queue of the current RunLoop.
* Calling this method with the same queue/target/method combination will have | true |
Other | emberjs | ember.js | 2dc87a1060efe1dbe8616a7c50d68fa78ed4149b.json | Add sundry improvements to preview types. | types/preview/@ember/service/service-test.ts | @@ -0,0 +1,34 @@
+import Service, { inject, service } from '@ember/service';
+import EmberObject from '@ember/object';
+
+class FirstSvc extends Service {
+ foo = 'bar';
+ first() {
+ return '';
+ }
+}
+const SecondSvc = Service.extend({
+ foo: 'bar',
+ second() {
+ return '';
+ },
+});
+
+declare module '@ember/service' {
+ interface Registry {
+ first: FirstSvc;
+ second: InstanceType<typeof SecondSvc>;
+ }
+}
+
+class Foo extends EmberObject {
+ @inject declare foo: FirstSvc;
+ @inject('first') declare baz: FirstSvc;
+ @inject declare bar: FirstSvc;
+}
+
+class FooService extends EmberObject {
+ @service declare foo: FirstSvc;
+ @service('first') declare baz: FirstSvc;
+ @service declare bar: FirstSvc;
+} | true |
Other | emberjs | ember.js | 2dc87a1060efe1dbe8616a7c50d68fa78ed4149b.json | Add sundry improvements to preview types. | types/preview/ember/index.d.ts | @@ -236,7 +236,9 @@ export namespace Ember {
* Can only be used when defining another controller.
*/
function controller(): Controller;
- function controller<K extends keyof ControllerRegistry>(name: K): ControllerRegistry[K];
+ function controller<K extends keyof ControllerRegistry>(
+ name: K
+ ): ControllerRegistry[K] & EmberObjectComputedNs.BasicComputedProperty;
const service: typeof EmberServiceNs.inject;
}
namespace ENV { | true |
Other | emberjs | ember.js | 2dc87a1060efe1dbe8616a7c50d68fa78ed4149b.json | Add sundry improvements to preview types. | types/preview/ember/test/access-modifier.ts | @@ -1,42 +0,0 @@
-/**
- * Tests to ensure that access modifier keywords are appropriately
- * respected and supported
- */
-import Ember from 'ember';
-import { assertType } from './lib/assert';
-
-class Foo extends Ember.Object {
- hello() {
- return 'world';
- }
- protected bar() {
- return 'bar';
- }
- private baz() {
- return 'baz';
- }
-}
-const f = new Foo();
-assertType<string>(f.hello());
-// protected property should not be visible from outside of Foo
-// @ts-expect-error
-assertType<string>(f.bar());
-// private property should not be visible from outside of Foo
-// @ts-expect-error
-assertType<string>(f.baz());
-
-class Foo2 extends Ember.Object.extend({
- bar: '',
-}) {
- hello() {
- return 'world';
- }
- // Cannot override with a mis-matched property type
- // @ts-expect-error
- protected bar() {
- return 'bar';
- }
- private baz() {
- return 'baz';
- }
-} | true |
Other | emberjs | ember.js | 2dc87a1060efe1dbe8616a7c50d68fa78ed4149b.json | Add sundry improvements to preview types. | types/preview/ember/test/application-instance.ts | @@ -5,18 +5,18 @@ const appInstance = ApplicationInstance.create();
appInstance.register('some:injection', class Foo {});
appInstance.register('some:injection', class Foo {}, {
- singleton: true,
+ singleton: true,
});
appInstance.register('some:injection', class Foo {}, {
- instantiate: false,
+ instantiate: false,
});
appInstance.register('templates:foo/bar', hbs`<h1>Hello World</h1>`);
appInstance.register('some:injection', class Foo {}, {
- singleton: false,
- instantiate: true,
+ singleton: false,
+ instantiate: true,
});
appInstance.factoryFor('router:main');
@@ -25,5 +25,5 @@ appInstance.lookup('route:basic');
appInstance.boot();
(async () => {
- await appInstance.boot();
+ await appInstance.boot();
})(); | true |
Other | emberjs | ember.js | 2dc87a1060efe1dbe8616a7c50d68fa78ed4149b.json | Add sundry improvements to preview types. | types/preview/ember/test/array-proxy.ts | @@ -9,16 +9,16 @@ proxy.set('content', Ember.A(['amoeba', 'paramecium']));
proxy.get('firstObject'); // 'amoeba'
const overridden = Ember.ArrayProxy.create({
- content: Ember.A(pets),
- objectAtContent(idx: number): string {
- return this.get('content').objectAt(idx)!.toUpperCase();
- },
+ content: Ember.A(pets),
+ objectAtContent(this: Ember.ArrayProxy<string>, idx: number): string {
+ return this.get('content').objectAt(idx)!.toUpperCase();
+ },
});
overridden.get('firstObject'); // 'DOG'
class MyNewProxy<T> extends Ember.ArrayProxy<T> {
- isNew = true;
+ isNew = true;
}
const x = MyNewProxy.create({ content: Ember.A([1, 2, 3]) }) as MyNewProxy<number>; | true |
Other | emberjs | ember.js | 2dc87a1060efe1dbe8616a7c50d68fa78ed4149b.json | Add sundry improvements to preview types. | types/preview/ember/test/controller.ts | @@ -1,11 +1,11 @@
-import Controller from '@ember/controller';
+import Ember from 'ember';
-Controller.extend({
- queryParams: ['category'],
- category: null,
- isExpanded: false,
+class MyController extends Ember.Controller {
+ queryParams = ['category'];
+ category = null;
+ isExpanded = false;
- toggleBody() {
- this.toggleProperty('isExpanded');
- },
-});
+ toggleBody() {
+ this.toggleProperty('isExpanded');
+ }
+} | true |
Other | emberjs | ember.js | 2dc87a1060efe1dbe8616a7c50d68fa78ed4149b.json | Add sundry improvements to preview types. | types/preview/ember/test/create-negative.ts | @@ -1,14 +1,8 @@
-import { assertType } from './lib/assert';
-import Ember from 'ember';
-import { PersonWithNumberName, Person } from './create';
+import { Person } from './create';
// @ts-expect-error
Person.create({ firstName: 99 });
// @ts-expect-error
Person.create({}, { firstName: 99 });
// @ts-expect-error
Person.create({}, {}, { firstName: 99 });
-
-const p4 = new PersonWithNumberName();
-
-// assertType<Ember.ComputedProperty<string, string>>(p4.fullName); // @ts-expect-error | true |
Other | emberjs | ember.js | 2dc87a1060efe1dbe8616a7c50d68fa78ed4149b.json | Add sundry improvements to preview types. | types/preview/ember/test/ember-module-tests.ts | @@ -34,8 +34,8 @@ Ember.compare('31', '114'); // $ExpectType number
Ember.debug('some info for developers');
// deprecate
Ember.deprecate("you shouldn't use this anymore", 3 === 3, {
- id: 'no-longer-allowed',
- until: '99.0.0',
+ id: 'no-longer-allowed',
+ until: '99.0.0',
});
// get
Ember.get({ z: 23 }, 'z'); // $ExpectType number
@@ -76,16 +76,16 @@ Ember.isPresent(''); // $ExpectType boolean
Ember.isPresent([]); // $ExpectType boolean
// observer
const o2 = Ember.Object.extend({
- name: 'foo',
- age: 3,
- nameWatcher: Ember.observer('name', () => {}),
- nameWatcher2: Ember.observer('name', 'fullName', () => {}),
+ name: 'foo',
+ age: 3,
+ nameWatcher: Ember.observer('name', () => {}),
+ nameWatcher2: Ember.observer('name', 'fullName', () => {}),
});
// on
const o3 = Ember.Object.extend({
- name: 'foo',
- nameWatcher: Ember.on('init', () => {}),
- nameWatcher2: Ember.on('destroy', () => {}),
+ name: 'foo',
+ nameWatcher: Ember.on('init', () => {}),
+ nameWatcher2: Ember.on('destroy', () => {}),
});
// removeListener
Ember.removeListener(o2, 'create', null, () => {});
@@ -148,7 +148,7 @@ new Ember.ArrayProxy<number>([3, 3, 2]); // $ExpectType ArrayProxy<number>
// Ember.Component
const C1 = Ember.Component.extend({ classNames: ['foo'] });
class C2 extends Ember.Component {
- classNames = ['foo'];
+ classNames = ['foo'];
}
const c1 = new C1();
const c2 = new C2();
@@ -158,12 +158,12 @@ c1.didInsertElement();
c2.didInsertElement();
// Ember.ComputedProperty
const cp: Ember.ComputedProperty<string, string> = Ember.computed('foo', {
- get(): string {
- return '';
- },
- set(_key: string, newVal: string): string {
- return '';
- },
+ get(): string {
+ return '';
+ },
+ set(_key: string, newVal: string): string {
+ return '';
+ },
});
// Ember.ContainerDebugAdapter
const cda = new Ember.ContainerDebugAdapter(); // $ExpectType ContainerDebugAdapter
@@ -193,18 +193,18 @@ oe1.on('bar', { foo() {} }, () => {});
const hl = new Ember.HashLocation(); // $ExpectType HashLocation
// Ember.Helper
const h1 = Ember.Helper.extend({
- compute() {
- this.recompute();
- return '';
- },
+ compute() {
+ this.recompute();
+ return '';
+ },
});
// Ember.HistoryLocation
const hil = new Ember.HistoryLocation(); // $ExpectType HistoryLocation
// Ember.Mixin
Ember.Object.extend(Ember.Mixin.create({ foo: 'bar' }), {
- baz() {
- this.foo; // $ExpectType string
- },
+ baz() {
+ this.foo; // $ExpectType string
+ },
});
// Ember.MutableArray
const ma1: Ember.MutableArray<string> = ['money', 'in', 'the', 'bananna', 'stand'];
@@ -213,7 +213,11 @@ ma1.addObject('!'); // $ExpectType string
ma1.filterBy('');
ma1.firstObject; // $ExpectType string | undefined
ma1.lastObject; // $ExpectType string | undefined
-const ma2: Ember.MutableArray<{ name: string }> = [{ name: 'chris' }, { name: 'dan' }, { name: 'james' }];
+const ma2: Ember.MutableArray<{ name: string }> = [
+ { name: 'chris' },
+ { name: 'dan' },
+ { name: 'james' },
+];
ma2.filterBy('name', 'chris'); // $ExpectType NativeArray<{ name: string; }>
// Ember.MutableEnumerable
const me1: Ember.MutableEnumerable<string | null | undefined> = ['foo', undefined, null];
@@ -234,10 +238,10 @@ new Ember.ObjectProxy(); // $ExpectType ObjectProxy
Ember.Object.extend(Ember.Observable, {});
// Ember.PromiseProxyMixin
Ember.Object.extend(Ember.PromiseProxyMixin, {
- foo() {
- this.reason; // $ExpectType unknown
- this.isPending; // $ExpectType boolean
- },
+ foo() {
+ this.reason; // $ExpectType unknown
+ this.isPending; // $ExpectType boolean
+ },
});
// Ember.Route
new Ember.Route(); | true |
Other | emberjs | ember.js | 2dc87a1060efe1dbe8616a7c50d68fa78ed4149b.json | Add sundry improvements to preview types. | types/preview/ember/test/engine.ts | @@ -1,40 +1,41 @@
import Ember from 'ember';
-import { assertType } from './lib/assert';
-const BaseEngine = Ember.Engine.extend({
- modulePrefix: 'my-engine',
-});
+class BaseEngine extends Ember.Engine {
+ modulePrefix = 'my-engine';
+}
-class Obj extends Ember.Object.extend({ foo: 'bar' }) {}
+class Obj extends Ember.Object {
+ foo = 'bar';
+}
BaseEngine.initializer({
- name: 'my-initializer',
- initialize(engine) {
- engine.register('foo:bar', Obj);
- },
+ name: 'my-initializer',
+ initialize(engine) {
+ engine.register('foo:bar', Obj);
+ },
});
BaseEngine.instanceInitializer({
- name: 'my-instance-initializer',
- initialize(engine) {
- (engine.lookup('foo:bar') as Obj).get('foo');
- },
-});
-
-const Engine1 = BaseEngine.create({
- rootElement: '#engine-one',
- customEvents: {
- paste: 'paste',
- },
+ name: 'my-instance-initializer',
+ initialize(engine) {
+ (engine.lookup('foo:bar') as Obj).get('foo');
+ },
});
-const Engine2 = BaseEngine.create({
- rootElement: '#engine-two',
- customEvents: {
- mouseenter: null,
- mouseleave: null,
- },
-});
+class Engine1 extends BaseEngine {
+ rootElement = '#engine-one';
+ customEvents = {
+ paste: 'paste',
+ };
+}
+
+class Engine2 extends BaseEngine {
+ rootElement = '#engine-two';
+ customEvents = {
+ mouseenter: null,
+ mouseleave: null,
+ };
+}
const Engine3 = BaseEngine.create();
| true |
Other | emberjs | ember.js | 2dc87a1060efe1dbe8616a7c50d68fa78ed4149b.json | Add sundry improvements to preview types. | types/preview/ember/test/inject.ts | @@ -1,4 +1,5 @@
import Ember from 'ember';
+import { expectTypeOf } from 'expect-type';
class AuthService extends Ember.Service {
declare isAuthenticated: boolean;
@@ -18,13 +19,16 @@ declare module '@ember/service' {
declare module '@ember/controller' {
interface Registry {
- application: ApplicationController;
+ emberApplication: ApplicationController;
}
}
class LoginRoute extends Ember.Route {
- auth = Ember.inject.service('auth');
- application = Ember.inject.controller('application');
+ @Ember.inject.service('auth')
+ declare auth: AuthService;
+
+ @Ember.inject.controller('emberApplication')
+ declare application: ApplicationController;
didTransition() {
if (!this.get('auth').get('isAuthenticated')) {
@@ -34,24 +38,32 @@ class LoginRoute extends Ember.Route {
anyOldMethod() {
this.get('application').set('string', 'must be a string');
- this.controllerFor('application'); // $ExpectType Controller
+ expectTypeOf(this.controllerFor('emberApplication')).toEqualTypeOf<Controller>();
}
}
// New module injection style.
-import Controller, { inject as controller } from '@ember/controller';
-import Service, { inject as service } from '@ember/service';
import { assertType } from './lib/assert';
+import RouterService from '@ember/routing/router-service';
+import Controller from '@ember/controller';
class ComponentInjection extends Ember.Component {
- applicationController = controller('application');
- auth = service('auth');
- router = service('router');
- misc = service();
+ @Ember.inject.controller('emberApplication')
+ declare applicationController: ApplicationController;
+
+ @Ember.inject.service('auth')
+ declare auth: AuthService;
+
+ @Ember.inject.service('router')
+ declare router: RouterService;
+
+ @Ember.inject.service
+ declare misc: Ember.Service;
testem() {
- assertType<Ember.Service>(this.get('misc'));
- const url = this.get('router').urlFor('some-route', 1, 2, 3, {
+ expectTypeOf(this.misc).toEqualTypeOf<Ember.Service>();
+
+ const url = this.router.urlFor('some-route', 1, 2, 3, {
queryParams: { seriously: 'yes' },
});
assertType<string>(url); | true |
Other | emberjs | ember.js | 20c6148c42df5514e8e8a5712e3dbe522a952d8f.json | Fix preview types/tests for @ember/service | types/preview/@ember/service/index.d.ts | @@ -1,22 +1,22 @@
import EmberObject from '@ember/object';
-import ComputedProperty from '@ember/object/computed';
+import type { BasicComputedProperty } from '@ember/object/computed';
export default class Service extends EmberObject {}
/**
* Creates a property that lazily looks up a service in the container. There
* are no restrictions as to what objects a service can be injected into.
*/
-export function inject(): ComputedProperty<Service>; // @inject() foo, foo: inject()
+export function inject(): Service; // @inject() foo, foo: inject()
export function inject(target: object, propertyKey: string | symbol): void; // @inject foo
-export function inject<K extends keyof Registry>(name: K): ComputedProperty<Registry[K]>; // @inject('store') foo @inject() foo
+export function inject<K extends keyof Registry>(name: K): Registry[K] & BasicComputedProperty; // @inject('store') foo @inject() foo
/**
* Creates a property that lazily looks up a service in the container. There
* are no restrictions as to what objects a service can be injected into.
*/
-export function service(): ComputedProperty<Service>; // @service() foo, foo: service()
+export function service(): Service; // @service() foo, foo: service()
export function service(target: object, propertyKey: string | symbol): void; // @service foo
-export function service<K extends keyof Registry>(name: K): ComputedProperty<Registry[K]>; // @service('store') foo @service() foo
+export function service<K extends keyof Registry>(name: K): Registry[K] & BasicComputedProperty; // @service('store') foo @service() foo
// A type registry for Ember `Service`s. Meant to be declaration-merged so
// string lookups resolve to the correct type. | true |
Other | emberjs | ember.js | 20c6148c42df5514e8e8a5712e3dbe522a952d8f.json | Fix preview types/tests for @ember/service | types/preview/@ember/service/test/main.ts | @@ -1,58 +0,0 @@
-import Service, { inject, service } from '@ember/service';
-import EmberObject from '@ember/object';
-
-class FirstSvc extends Service {
- foo = 'bar';
- first() {
- return '';
- }
-}
-const SecondSvc = Service.extend({
- foo: 'bar',
- second() {
- return '';
- },
-});
-
-class ThirdSvc extends Service.extend({
- foo: 'bar',
- third() {
- return '';
- },
-}) {}
-
-declare module '@ember/service' {
- interface Registry {
- first: FirstSvc;
- second: InstanceType<typeof SecondSvc>;
- third: ThirdSvc;
- }
-}
-
-const ServiceTriplet = EmberObject.extend({
- sFirst: inject('first'),
- sSecond: inject('second'),
- sThird: inject('third'),
- unknownService: inject(),
-});
-
-const obj = ServiceTriplet.create();
-
-obj.get('sFirst'); // $ExpectType FirstSvc
-obj.get('sSecond').second(); // $ExpectType ""
-obj.get('sThird'); // $ExpectType ThirdSvc
-obj.get('unknownService'); // $ExpectType Service
-
-const ServiceTripletService = EmberObject.extend({
- sFirst: service('first'),
- sSecond: service('second'),
- sThird: service('third'),
- unknownService: service(),
-});
-
-const objService = ServiceTripletService.create();
-
-objService.get('sFirst'); // $ExpectType FirstSvc
-objService.get('sSecond').second(); // $ExpectType ""
-objService.get('sThird'); // $ExpectType ThirdSvc
-objService.get('unknownService'); // $ExpectType Service | true |
Other | emberjs | ember.js | 20c6148c42df5514e8e8a5712e3dbe522a952d8f.json | Fix preview types/tests for @ember/service | types/preview/@ember/service/test/octane.ts | @@ -1,34 +0,0 @@
-import Service, { inject, service } from '@ember/service';
-import EmberObject from '@ember/object';
-
-class FirstSvc extends Service {
- foo = 'bar';
- first() {
- return '';
- }
-}
-const SecondSvc = Service.extend({
- foo: 'bar',
- second() {
- return '';
- },
-});
-
-declare module '@ember/service' {
- interface Registry {
- first: FirstSvc;
- second: InstanceType<typeof SecondSvc>;
- }
-}
-
-class Foo extends EmberObject {
- @inject declare foo: FirstSvc;
- @inject('first') declare baz: FirstSvc;
- @inject() declare bar: FirstSvc;
-}
-
-class FooService extends EmberObject {
- @service declare foo: FirstSvc;
- @service('first') declare baz: FirstSvc;
- @service() declare bar: FirstSvc;
-} | true |
Other | emberjs | ember.js | 20c6148c42df5514e8e8a5712e3dbe522a952d8f.json | Fix preview types/tests for @ember/service | types/preview/ember/test/inject.ts | @@ -1,41 +1,41 @@
import Ember from 'ember';
class AuthService extends Ember.Service {
- declare isAuthenticated: boolean;
+ declare isAuthenticated: boolean;
}
class ApplicationController extends Ember.Controller {
- model = {};
- declare string: string;
- transitionToLogin() {}
+ model = {};
+ declare string: string;
+ transitionToLogin() {}
}
declare module '@ember/service' {
- interface Registry {
- auth: AuthService;
- }
+ interface Registry {
+ auth: AuthService;
+ }
}
declare module '@ember/controller' {
- interface Registry {
- application: ApplicationController;
- }
+ interface Registry {
+ application: ApplicationController;
+ }
}
class LoginRoute extends Ember.Route {
- auth = Ember.inject.service('auth');
- application = Ember.inject.controller('application');
+ auth = Ember.inject.service('auth');
+ application = Ember.inject.controller('application');
- didTransition() {
- if (!this.get('auth').get('isAuthenticated')) {
- this.get('application').transitionToLogin();
- }
+ didTransition() {
+ if (!this.get('auth').get('isAuthenticated')) {
+ this.get('application').transitionToLogin();
}
+ }
- anyOldMethod() {
- this.get('application').set('string', 'must be a string');
- this.controllerFor('application'); // $ExpectType Controller
- }
+ anyOldMethod() {
+ this.get('application').set('string', 'must be a string');
+ this.controllerFor('application'); // $ExpectType Controller
+ }
}
// New module injection style.
@@ -44,17 +44,19 @@ import Service, { inject as service } from '@ember/service';
import { assertType } from './lib/assert';
class ComponentInjection extends Ember.Component {
- applicationController = controller('application');
- auth = service('auth');
- router = service('router');
- misc = service();
-
- testem() {
- assertType<Ember.Service>(this.get('misc'));
- const url = this.get('router').urlFor('some-route', 1, 2, 3, { queryParams: { seriously: 'yes' } });
- assertType<string>(url);
- if (!this.get('auth').isAuthenticated) {
- this.get('applicationController').transitionToLogin();
- }
+ applicationController = controller('application');
+ auth = service('auth');
+ router = service('router');
+ misc = service();
+
+ testem() {
+ assertType<Ember.Service>(this.get('misc'));
+ const url = this.get('router').urlFor('some-route', 1, 2, 3, {
+ queryParams: { seriously: 'yes' },
+ });
+ assertType<string>(url);
+ if (!this.get('auth').isAuthenticated) {
+ this.get('applicationController').transitionToLogin();
}
+ }
} | true |
Other | emberjs | ember.js | d32122b36f28c0781ba3da5d84a4689d975c1b7a.json | Improve preview types and tests for controllers | types/preview/@ember/controller/index.d.ts | @@ -1,6 +1,7 @@
import ActionHandler from '@ember/object/-private/action-handler';
import Mixin from '@ember/object/mixin';
import EmberObject from '@ember/object';
+import type { BasicComputedProperty } from '@ember/object/computed';
type QueryParamTypes = 'boolean' | 'number' | 'array' | 'string';
type QueryParamScopeTypes = 'controller' | 'model';
@@ -37,7 +38,7 @@ export default class Controller extends EmberObject {}
export default interface Controller extends ControllerMixin {}
export function inject(): Controller;
-export function inject<K extends keyof Registry>(name: K): Registry[K];
+export function inject<K extends keyof Registry>(name: K): Registry[K] & BasicComputedProperty;
export function inject(target: object, propertyKey: string | symbol): void;
// A type registry for Ember `Controller`s. Meant to be declaration-merged | true |
Other | emberjs | ember.js | d32122b36f28c0781ba3da5d84a4689d975c1b7a.json | Improve preview types and tests for controllers | types/preview/@ember/controller/test/main.ts | @@ -1,14 +1,14 @@
import Controller, { inject } from '@ember/controller';
-Controller.extend({
- queryParams: ['category'],
- category: null,
- isExpanded: false,
+class MyController extends Controller {
+ queryParams = ['category'];
+ category = null;
+ isExpanded = false;
- first: inject(),
- second: inject('second'),
+ @inject declare first: Controller;
+ @inject('second') declare second: Controller;
- toggleBody() {
- this.toggleProperty('isExpanded');
- },
-});
+ toggleBody() {
+ this.toggleProperty('isExpanded');
+ }
+} | true |
Other | emberjs | ember.js | d32122b36f28c0781ba3da5d84a4689d975c1b7a.json | Improve preview types and tests for controllers | types/preview/@ember/controller/test/octane.ts | @@ -1,36 +1,36 @@
import Controller, { inject } from '@ember/controller';
class FirstController extends Controller {
- foo = 'bar';
- @inject declare second: InstanceType<typeof SecondController>;
- @inject() declare otherSecond: InstanceType<typeof SecondController>;
- @inject('second') declare moreSecond: InstanceType<typeof SecondController>;
+ foo = 'bar';
+ @inject declare second: InstanceType<typeof SecondController>;
+ @inject declare otherSecond: InstanceType<typeof SecondController>;
+ @inject('second') declare moreSecond: InstanceType<typeof SecondController>;
- queryParams = [
- 'category',
- {
- searchTerm: {
- as: 'search',
- },
- subCategory: 'sub-category',
- },
- ];
+ queryParams = [
+ 'category',
+ {
+ searchTerm: {
+ as: 'search',
+ },
+ subCategory: 'sub-category',
+ },
+ ];
- first() {
- return '';
- }
+ first() {
+ return '';
+ }
}
const SecondController = Controller.extend({
- foo: 'bar',
+ foo: 'bar',
- second() {
- return '';
- },
+ second() {
+ return '';
+ },
});
declare module '@ember/controller' {
- interface Registry {
- first: FirstController;
- second: InstanceType<typeof SecondController>;
- }
+ interface Registry {
+ first: FirstController;
+ second: InstanceType<typeof SecondController>;
+ }
} | true |
Other | emberjs | ember.js | 69eda9f3e0271cd2bd5d309a3f8ed22b175e34ef.json | Improve preview types and tests for helper | types/preview/@ember/component/helper.d.ts | @@ -21,7 +21,7 @@ declare const Empty: unique symbol;
* themselves, so ***DO NOT RELY ON IT***.
*/
export interface EmptyObject {
- [Empty]?: true;
+ [Empty]?: true;
}
type DefaultPositional = unknown[];
@@ -33,37 +33,37 @@ type DefaultNamed = EmptyObject;
* "normal" signature shape: `Args: { Named: { ... }, Positional: [...] }`.
*/
export interface HelperSignature {
- NamedArgs?: DefaultNamed;
- PositionalArgs?: DefaultPositional;
- Return?: unknown;
+ NamedArgs?: DefaultNamed;
+ PositionalArgs?: DefaultPositional;
+ Return?: unknown;
}
type GetOrElse<Obj, K, Fallback> = K extends keyof Obj ? Obj[K] : Fallback;
/** Given a signature `S`, get back the `Args` type. */
type ArgsFor<S> = 'Args' extends keyof S
- ? {
- Named: GetOrElse<S['Args'], 'Named', DefaultNamed>;
- Positional: GetOrElse<S['Args'], 'Positional', []>;
- }
- : { Named: DefaultNamed; Positional: [] };
+ ? {
+ Named: GetOrElse<S['Args'], 'Named', DefaultNamed>;
+ Positional: GetOrElse<S['Args'], 'Positional', []>;
+ }
+ : { Named: DefaultNamed; Positional: [] };
interface LegacyArgsFor<T> {
- Named: GetOrElse<T, 'NamedArgs', DefaultNamed>;
- Positional: GetOrElse<T, 'PositionalArgs', DefaultPositional>;
+ Named: GetOrElse<T, 'NamedArgs', DefaultNamed>;
+ Positional: GetOrElse<T, 'PositionalArgs', DefaultPositional>;
}
// This type allows us to present a slightly-less-obtuse error message
// when attempting to resolve the signature of a helper that doesn't have
// one declared from within a tool like Glint.
declare const BadType: unique symbol;
interface BadType<Message> {
- [BadType]: Message;
+ [BadType]: Message;
}
interface MissingSignatureArgs {
- Named: BadType<'This helper is missing a signature'>;
- Positional: unknown[];
+ Named: BadType<'This helper is missing a signature'>;
+ Positional: unknown[];
}
/**
@@ -84,19 +84,21 @@ interface MissingSignatureArgs {
// all `ExpandSignature` types fully general to work with *any* invokable. But
// "future" here probably means Ember v5. :sobbing:
export interface ExpandSignature<T> {
- Args: unknown extends T // Is this the default (i.e. unspecified) signature?
- ? MissingSignatureArgs // Then return our special "missing signature" type
- : keyof T extends 'Args' | 'Return' // Is this a `Signature`?
- ? ArgsFor<T> // Then use `Signature` args
- : LegacyArgsFor<T>; // Otherwise fall back to classic `Args`.
- Return: 'Return' extends keyof T ? T['Return'] : unknown;
+ Args: unknown extends T // Is this the default (i.e. unspecified) signature?
+ ? MissingSignatureArgs // Then return our special "missing signature" type
+ : keyof T extends 'Args' | 'Return' // Is this a `Signature`?
+ ? ArgsFor<T> // Then use `Signature` args
+ : LegacyArgsFor<T>; // Otherwise fall back to classic `Args`.
+ Return: 'Return' extends keyof T ? T['Return'] : unknown;
}
// The `unknown extends S` checks on both of these are here to preserve backward
// compatibility with the existing non-`Signature` definition. When migrating
// into Ember or otherwise making a breaking change, we can drop the "default"
// in favor of just using `ExpandSignature`.
-type NamedArgs<S> = unknown extends S ? Record<string, unknown> : ExpandSignature<S>['Args']['Named'];
+type NamedArgs<S> = unknown extends S
+ ? Record<string, unknown>
+ : ExpandSignature<S>['Args']['Named'];
type PositionalArgs<S> = unknown extends S ? unknown[] : ExpandSignature<S>['Args']['Positional'];
type Return<S> = GetOrElse<S, 'Return', unknown>;
@@ -106,23 +108,23 @@ type Return<S> = GetOrElse<S, 'Return', unknown>;
* For example, this code calls a helper named `format-currency`:
*/
export default class Helper<S = unknown> extends EmberObject {
- /**
- * In many cases, the ceremony of a full `Ember.Helper` class is not required.
- * The `helper` method create pure-function helpers without instances. For
- * example:
- */
- static helper<P extends DefaultPositional, N = EmptyObject, R = unknown>(
- helper: (positional: P, named: N) => R,
- ): Helper<{ Args: { Positional: P; Named: N }; Return: R }>;
- /**
- * Override this function when writing a class-based helper.
- */
- compute(positional: PositionalArgs<S>, named: NamedArgs<S>): Return<S>;
- /**
- * On a class-based helper, it may be useful to force a recomputation of that
- * helpers value. This is akin to `rerender` on a component.
- */
- recompute(): void;
+ /**
+ * In many cases, the ceremony of a full `Ember.Helper` class is not required.
+ * The `helper` method create pure-function helpers without instances. For
+ * example:
+ */
+ static helper<P extends DefaultPositional, N = EmptyObject, R = unknown>(
+ helper: (positional: P, named: N) => R
+ ): Helper<{ Args: { Positional: P; Named: N }; Return: R }>;
+ /**
+ * Override this function when writing a class-based helper.
+ */
+ compute(positional: PositionalArgs<S>, named: NamedArgs<S>): Return<S>;
+ /**
+ * On a class-based helper, it may be useful to force a recomputation of that
+ * helpers value. This is akin to `rerender` on a component.
+ */
+ recompute(): void;
}
// The generic here is for a *signature: a way to hang information for tools
@@ -140,7 +142,7 @@ export default interface Helper<S> extends Opaque<S> {}
// augmentations of the `Helper` type performed by tools like Glint will
// also apply to function-based helpers as well.
export abstract class FunctionBasedHelperInstance<S> extends Helper<S> {
- protected abstract __concrete__: never;
+ protected abstract __concrete__: never;
}
/**
@@ -172,27 +174,27 @@ export type FunctionBasedHelper<S> = abstract new () => FunctionBasedHelperInsta
// This overload allows users to write types directly on the callback passed to
// the `helper` function and infer the resulting type correctly.
export function helper<P extends DefaultPositional, N = EmptyObject, R = unknown>(
- helperFn: (positional: P, named: N) => R,
+ helperFn: (positional: P, named: N) => R
): FunctionBasedHelper<{
- Args: {
- Positional: P;
- Named: N;
- };
- Return: R;
+ Args: {
+ Positional: P;
+ Named: N;
+ };
+ Return: R;
}>;
// This overload allows users to provide a `Signature` type explicitly at the
// helper definition site, e.g. `helper<Sig>((pos, named) => {...})`. **Note:**
// this overload must appear second, since TS' inference engine will not
// correctly infer the type of `S` here from the types on the supplied callback.
export function helper<S>(
- helperFn: (positional: PositionalArgs<S>, named: NamedArgs<S>) => Return<S>,
+ helperFn: (positional: PositionalArgs<S>, named: NamedArgs<S>) => Return<S>
): FunctionBasedHelper<{
- Args: {
- Positional: PositionalArgs<S>;
- Named: NamedArgs<S>;
- };
- Return: Return<S>;
+ Args: {
+ Positional: PositionalArgs<S>;
+ Named: NamedArgs<S>;
+ };
+ Return: Return<S>;
}>;
export {}; | true |
Other | emberjs | ember.js | 69eda9f3e0271cd2bd5d309a3f8ed22b175e34ef.json | Improve preview types and tests for helper | types/preview/@ember/component/test/helper.ts | @@ -1,120 +1,142 @@
import Helper, { ExpandSignature, helper } from '@ember/component/helper';
class DeprecatedSignatureForm extends Helper<{
- PositionalArgs: [offset: Date];
- Return: Date;
+ PositionalArgs: [offset: Date];
+ Return: Date;
}> {
- timer?: ReturnType<typeof setInterval> | undefined;
- now = new Date();
- init() {
- super.init();
- this.timer = setInterval(() => {
- this.set('now', new Date());
- this.recompute();
- }, 100);
- }
- compute([offset]: [Date]): Date {
- return new Date(this.now.getTime() + offset.getTime());
- }
- willDestroy() {
- clearInterval(this.timer);
+ timer?: ReturnType<typeof setInterval> | undefined;
+ now = new Date();
+ init() {
+ super.init();
+ this.timer = setInterval(() => {
+ this.set('now', new Date());
+ this.recompute();
+ }, 100);
+ }
+ compute([offset]: [Date]): Date {
+ return new Date(this.now.getTime() + offset.getTime());
+ }
+ willDestroy() {
+ if (this.timer) {
+ clearInterval(this.timer);
}
+ }
}
interface DemoSig {
- Args: {
- Named: {
- name: string;
- age: number;
- };
- Positional: [i18nizer: (s: string) => string];
+ Args: {
+ Named: {
+ name: string;
+ age: number;
};
- Return: string;
+ Positional: [i18nizer: (s: string) => string];
+ };
+ Return: string;
}
function testMissingSignature({ Args, Return }: ExpandSignature<unknown>) {
- // $ExpectType BadType<"This helper is missing a signature">
- Args.Named;
+ // $ExpectType BadType<"This helper is missing a signature">
+ Args.Named;
- // $ExpectType unknown[]
- Args.Positional;
+ // $ExpectType unknown[]
+ Args.Positional;
- // $ExpectType unknown
- Return;
+ // $ExpectType unknown
+ Return;
}
class SignatureForm extends Helper<DemoSig> {
- compute([i18nizer]: [i18nizer: (s: string) => string], { name, age }: { name: string; age: number }): string {
- return i18nizer(`${name} is ${age} years old`);
- }
+ compute(
+ [i18nizer]: [i18nizer: (s: string) => string],
+ { name, age }: { name: string; age: number }
+ ): string {
+ return i18nizer(`${name} is ${age} years old`);
+ }
}
class NoSignatureForm extends Helper {
- compute([i18nizer]: [i18nizer: (s: string) => string], { name, age }: { name: string; age: number }): string {
- return i18nizer(`${name} is ${age} years old`);
- }
+ compute(
+ [i18nizer]: [i18nizer: (s: string) => string],
+ { name, age }: { name: string; age: number }
+ ): string {
+ return i18nizer(`${name} is ${age} years old`);
+ }
}
class BadPosSigForm extends Helper<DemoSig> {
- compute(
- // @ts-expect-error
- [i18nizer, extra]: [i18nizer: (s: string) => string],
- { name, age }: { name: string; age: number },
- ): string {
- return i18nizer(`${name} is ${age} years old`);
- }
+ compute(
+ // @ts-expect-error
+ [i18nizer, extra]: [i18nizer: (s: string) => string],
+ { name, age }: { name: string; age: number }
+ ): string {
+ return i18nizer(`${name} is ${age} years old`);
+ }
}
class BadNamedSigForm extends Helper<DemoSig> {
- compute(
- [i18nizer]: [i18nizer: (s: string) => string],
- // @ts-expect-error
- { name, age, potato }: { name: string; age: number },
- ): string {
- return i18nizer(`${name} is ${age} years old`);
- }
+ compute(
+ [i18nizer]: [i18nizer: (s: string) => string],
+ // @ts-expect-error
+ { name, age, potato }: { name: string; age: number }
+ ): string {
+ return i18nizer(`${name} is ${age} years old`);
+ }
}
class BadReturnForm extends Helper<DemoSig> {
- compute([i18nizer]: [i18nizer: (s: string) => string], { name, age }: { name: string; age: number }): string {
- // @ts-expect-error
- return Boolean(i18nizer(`${name} is ${age} years old`));
- }
+ compute(
+ [i18nizer]: [i18nizer: (s: string) => string],
+ { name, age }: { name: string; age: number }
+ ): string {
+ // @ts-expect-error
+ return Boolean(i18nizer(`${name} is ${age} years old`));
+ }
}
// $ExpectType FunctionBasedHelper<{ Args: { Positional: [number, number]; Named: EmptyObject; }; Return: number; }>
const inferenceOnPositional = helper(function add([a, b]: [number, number]) {
- return a + b;
+ return a + b;
});
-const coolHelper = helper(([], named) => {
- // $ExpectType EmptyObject
- named;
+const coolHelper = helper((_, named) => {
+ // $ExpectType EmptyObject
+ named;
});
// $ExpectType FunctionBasedHelper<{ Args: { Positional: DefaultPositional; Named: { cool: boolean; }; }; Return: 123 | "neat"; }>
-const typeInferenceOnNamed = helper(([], { cool }: { cool: boolean }) => {
- // $ExpectType boolean
- cool;
+const typeInferenceOnNamed = helper((_, { cool }: { cool: boolean }) => {
+ // $ExpectType boolean
+ cool;
- return cool ? 123 : 'neat';
+ return cool ? 123 : 'neat';
});
// $ExpectType FunctionBasedHelper<{ Args: { Positional: [string]; Named: { delim?: string; }; }; Return: string; }>
-const dasherizeHelper = helper(function dasherize([str]: [string], { delim = '-' }: { delim?: string }) {
- return str.split(/[\s\n\_\.]+/g).join(delim);
+const dasherizeHelper = helper(function dasherize(
+ [str]: [string],
+ { delim = '-' }: { delim?: string }
+) {
+ return str.split(/[\s\n_.]+/g).join(delim);
});
-const signatureForm = helper<DemoSig>(([i18nizer], { name, age }) => i18nizer(`${name} is ${age} years old`));
-
-// @ts-expect-error
-const badPosArgsSig = helper<DemoSig>(([i18nizer, extra], { name, age }) => i18nizer(`${name} is ${age} years old`));
+const signatureForm = helper<DemoSig>(([i18nizer], { name, age }) =>
+ i18nizer(`${name} is ${age} years old`)
+);
// @ts-expect-error
-const badNamedArgsSig = helper<DemoSig>(([i18nizer], { name, age, potato }) => i18nizer(`${name} is ${age} years old`));
+const badPosArgsSig = helper<DemoSig>(([i18nizer, extra], { name, age }) =>
+ i18nizer(`${name} is ${age} years old`)
+);
// @ts-expect-error
-const badReturnSig = helper<DemoSig>(([i18nizer], { name, age }) => Boolean(i18nizer(`${name} is ${age} years old`)));
+const badNamedArgsSig = helper<DemoSig>(([i18nizer], { name, age, potato }) =>
+ i18nizer(`${name} is ${age} years old`)
+);
+
+const badReturnSig = helper<DemoSig>(([i18nizer], { name, age }) =>
+ // @ts-expect-error
+ Boolean(i18nizer(`${name} is ${age} years old`))
+);
const greet = helper(([name]: [string]) => `Hello, ${name}`);
| true |
Other | emberjs | ember.js | d95a927fdcd851bbada245190f94d024734d6d30.json | Fix preview type tests for Ember Component | types/preview/@ember/component/test/component.ts | @@ -1,141 +1,138 @@
import Component from '@ember/component';
import Object, { computed, get } from '@ember/object';
-import hbs from 'htmlbars-inline-precompile';
import { assertType } from './lib/assert';
Component.extend({
- layout: hbs`
- <div>
- {{yield}}
- </div>
- `,
-});
-
-Component.extend({
- layout: 'my-layout',
+ layout: 'my-layout',
});
const MyComponent = Component.extend();
assertType<string | string[]>(get(MyComponent, 'positionalParams'));
const component1 = Component.extend({
- actions: {
- hello(name: string) {
- console.log('Hello', name);
- },
- },
-});
-
-Component.extend({
- name: '',
+ actions: {
hello(name: string) {
- this.set('name', name);
+ console.log('Hello', name);
},
+ },
});
-Component.extend({
- tagName: 'em',
-});
+class AnotherComponent extends Component {
+ name = '';
+
+ hello(name: string) {
+ this.set('name', name);
+ this.name = name;
+ }
+}
Component.extend({
- classNames: ['my-class', 'my-other-class'],
+ tagName: 'em',
});
Component.extend({
- classNameBindings: ['propertyA', 'propertyB'],
- propertyA: 'from-a',
- propertyB: computed(function () {
- if (!this.get('propertyA')) {
- return 'from-b';
- }
- }),
+ classNames: ['my-class', 'my-other-class'],
});
+class Bindings extends Component {
+ classNameBindings = ['propertyA', 'propertyB'];
+ propertyA = 'from-a';
+
+ @computed()
+ get propertyB() {
+ if (!this.get('propertyA')) {
+ return 'from-b';
+ }
+ }
+}
+
Component.extend({
- classNameBindings: ['hovered'],
- hovered: true,
+ classNameBindings: ['hovered'],
+ hovered: true,
});
+class Message extends Object {
+ empty = false;
+}
+
Component.extend({
- classNameBindings: ['messages.empty'],
- messages: Object.create({
- empty: true,
- }),
+ classNameBindings: ['messages.empty'],
+ messages: Message.create({
+ empty: true,
+ }),
});
Component.extend({
- classNameBindings: ['isEnabled:enabled:disabled'],
- isEnabled: true,
+ classNameBindings: ['isEnabled:enabled:disabled'],
+ isEnabled: true,
});
Component.extend({
- classNameBindings: ['isEnabled::disabled'],
- isEnabled: true,
+ classNameBindings: ['isEnabled::disabled'],
+ isEnabled: true,
});
Component.extend({
- tagName: 'a',
- attributeBindings: ['href'],
- href: 'http://google.com',
+ tagName: 'a',
+ attributeBindings: ['href'],
+ href: 'http://google.com',
});
Component.extend({
- tagName: 'a',
- attributeBindings: ['url:href'],
- url: 'http://google.com',
+ tagName: 'a',
+ attributeBindings: ['url:href'],
+ url: 'http://google.com',
});
Component.extend({
- tagName: 'use',
- attributeBindings: ['xlinkHref:xlink:href'],
- xlinkHref: '#triangle',
+ tagName: 'use',
+ attributeBindings: ['xlinkHref:xlink:href'],
+ xlinkHref: '#triangle',
});
Component.extend({
- tagName: 'input',
- attributeBindings: ['disabled'],
- disabled: false,
+ tagName: 'input',
+ attributeBindings: ['disabled'],
+ disabled: false,
});
Component.extend({
- tagName: 'input',
- attributeBindings: ['disabled'],
- disabled: computed(() => {
- if ('someLogic') {
- return true;
- } else {
- return false;
- }
- }),
+ tagName: 'input',
+ attributeBindings: ['disabled'],
+ disabled: computed(() => {
+ return someLogic();
+ }),
});
+declare function someLogic(): boolean;
+
Component.extend({
- tagName: 'form',
- attributeBindings: ['novalidate'],
- novalidate: null,
+ tagName: 'form',
+ attributeBindings: ['novalidate'],
+ novalidate: null,
});
Component.extend({
- click(event: object) {
- // will be called when an instance's
- // rendered element is clicked
- },
+ click(event: object) {
+ // will be called when an instance's
+ // rendered element is clicked
+ },
});
// @ts-expect-error
Component.reopen({
- attributeBindings: ['metadata:data-my-metadata'],
- metadata: '',
+ attributeBindings: ['metadata:data-my-metadata'],
+ metadata: '',
});
interface MySig {
- Args: {
- Named: {
- name: string;
- age: number;
- };
- Positional: [action: () => void];
+ Args: {
+ Named: {
+ name: string;
+ age: number;
};
+ Positional: [action: () => void];
+ };
}
// These type helpers are stolen (and tweaked) from Glimmer and Glint internals
@@ -146,12 +143,12 @@ type NamedArgsFor<T> = GetWithFallback<GetWithFallback<T, 'Args', {}>, 'Named',
interface SigExample extends NamedArgsFor<MySig> {}
class SigExample extends Component<MySig> {
- get accessArgs() {
- const {
- name, // $ExpectType string
- age, // $ExpectType number
- } = this;
-
- return `${name} is ${age} years old`;
- }
+ get accessArgs() {
+ const {
+ name, // $ExpectType string
+ age, // $ExpectType number
+ } = this;
+
+ return `${name} is ${age} years old`;
+ }
} | true |
Other | emberjs | ember.js | d95a927fdcd851bbada245190f94d024734d6d30.json | Fix preview type tests for Ember Component | types/preview/ember/test/component.ts | @@ -1,124 +1,119 @@
import Ember from 'ember';
-import Component from '@ember/component';
-import Object, { computed } from '@ember/object';
-import hbs from 'htmlbars-inline-precompile';
-import { assertType } from './lib/assert';
-
-Component.extend({
- layout: hbs`
- <div>
- {{yield}}
- </div>
- `,
-});
+import { expectTypeOf } from 'expect-type';
-Component.extend({
- layout: 'my-layout',
+Ember.Component.extend({
+ layout: 'my-layout',
});
-const MyComponent = Component.extend();
-assertType<string | string[]>(Ember.get(MyComponent, 'positionalParams'));
-
-const component1 = Component.extend({
- actions: {
- hello(name: string) {
- console.log('Hello', name);
- },
- },
-});
+const MyComponent = Ember.Component.extend();
+expectTypeOf(Ember.get(MyComponent, 'positionalParams')).toEqualTypeOf<string | string[]>();
-Component.extend({
- name: '',
+const component1 = Ember.Component.extend({
+ actions: {
hello(name: string) {
- this.set('name', name);
+ console.log('Hello', name);
},
+ },
});
-Component.extend({
- tagName: 'em',
-});
+class AnotherComponent extends Ember.Component {
+ name = '';
+
+ hello(name: string) {
+ this.set('name', name);
+ this.name = name;
+ }
+}
-Component.extend({
- classNames: ['my-class', 'my-other-class'],
+Ember.Component.extend({
+ tagName: 'em',
});
-Component.extend({
- classNameBindings: ['propertyA', 'propertyB'],
- propertyA: 'from-a',
- propertyB: computed(function () {
- if (!this.get('propertyA')) {
- return 'from-b';
- }
- }),
+Ember.Component.extend({
+ classNames: ['my-class', 'my-other-class'],
});
-Component.extend({
- classNameBindings: ['hovered'],
- hovered: true,
+class Bindings extends Ember.Component {
+ classNameBindings = ['propertyA', 'propertyB'];
+ propertyA = 'from-a';
+
+ @Ember.computed()
+ get propertyB() {
+ if (!this.get('propertyA')) {
+ return 'from-b';
+ }
+ }
+}
+
+Ember.Component.extend({
+ classNameBindings: ['hovered'],
+ hovered: true,
});
-Component.extend({
- classNameBindings: ['messages.empty'],
- messages: Object.create({
- empty: true,
- }),
+class Message extends Ember.Object {
+ empty = false;
+}
+
+Ember.Component.extend({
+ classNameBindings: ['messages.empty'],
+ messages: Message.create({
+ empty: true,
+ }),
});
-Component.extend({
- classNameBindings: ['isEnabled:enabled:disabled'],
- isEnabled: true,
+Ember.Component.extend({
+ classNameBindings: ['isEnabled:enabled:disabled'],
+ isEnabled: true,
});
-Component.extend({
- classNameBindings: ['isEnabled::disabled'],
- isEnabled: true,
+Ember.Component.extend({
+ classNameBindings: ['isEnabled::disabled'],
+ isEnabled: true,
});
-Component.extend({
- tagName: 'a',
- attributeBindings: ['href'],
- href: 'http://google.com',
+Ember.Component.extend({
+ tagName: 'a',
+ attributeBindings: ['href'],
+ href: 'http://google.com',
});
-Component.extend({
- tagName: 'a',
- attributeBindings: ['url:href'],
- url: 'http://google.com',
+Ember.Component.extend({
+ tagName: 'a',
+ attributeBindings: ['url:href'],
+ url: 'http://google.com',
});
-Component.extend({
- tagName: 'use',
- attributeBindings: ['xlinkHref:xlink:href'],
- xlinkHref: '#triangle',
+Ember.Component.extend({
+ tagName: 'use',
+ attributeBindings: ['xlinkHref:xlink:href'],
+ xlinkHref: '#triangle',
});
-Component.extend({
- tagName: 'input',
- attributeBindings: ['disabled'],
- disabled: false,
+Ember.Component.extend({
+ tagName: 'input',
+ attributeBindings: ['disabled'],
+ disabled: false,
});
-Component.extend({
- tagName: 'input',
- attributeBindings: ['disabled'],
- disabled: computed(() => {
- if ('someLogic') {
- return true;
- } else {
- return false;
- }
- }),
+Ember.Component.extend({
+ tagName: 'input',
+ attributeBindings: ['disabled'],
+ disabled: Ember.computed(() => {
+ return someLogic();
+ }),
});
-Component.extend({
- tagName: 'form',
- attributeBindings: ['novalidate'],
- novalidate: null,
+declare function someLogic(): boolean;
+
+Ember.Component.extend({
+ tagName: 'form',
+ attributeBindings: ['novalidate'],
+ novalidate: null,
});
-Component.extend({
- click(event: object) {
- // will be called when an instance's
- // rendered element is clicked
- },
+Ember.Component.extend({
+ click(event: object) {
+ // will be called when an instance's
+ // rendered element is clicked
+ },
}); | true |
Other | emberjs | ember.js | 4730ecd8b7a8e6b7b3f560fb7dabd3de605c3753.json | Fix preview types and tests for `Evented` | types/preview/@ember/object/test/event.ts | @@ -1,92 +1,96 @@
-import EmberObject, { observer } from '@ember/object';
+import EmberObject from '@ember/object';
import { sendEvent, addListener, removeListener } from '@ember/object/events';
import Evented, { on } from '@ember/object/evented';
function testOn() {
- const Job = EmberObject.extend({
- logStartOrUpdate: on('started', 'updated', () => {
- console.log('Job updated!');
- }),
- logCompleted: on('completed', () => {
- console.log('Job completed!');
- }),
- });
-
- const job = Job.create();
-
- sendEvent(job, 'started'); // Logs 'Job started!'
- sendEvent(job, 'updated'); // Logs 'Job updated!'
- sendEvent(job, 'completed'); // Logs 'Job completed!'
+ const Job = EmberObject.extend({
+ logStartOrUpdate: on('started', 'updated', () => {
+ console.log('Job updated!');
+ }),
+ logCompleted: on('completed', () => {
+ console.log('Job completed!');
+ }),
+ });
+
+ const job = Job.create();
+
+ sendEvent(job, 'started'); // Logs 'Job started!'
+ sendEvent(job, 'updated'); // Logs 'Job updated!'
+ sendEvent(job, 'completed'); // Logs 'Job completed!'
}
function testEvented() {
- const Person = EmberObject.extend(Evented, {
- greet() {
- this.trigger('greet');
- },
- });
-
- const person = Person.create();
-
- person.on('potato', 'greet');
-
- const target = {
- hi() {
- console.log('Hello!');
- },
- };
-
- person.on('greet', () => {
- console.log('Our person has greeted');
- });
-
- person
- .on('greet', () => {
- console.log('Our person has greeted');
- })
- .one('greet', () => {
- console.log('Offer one-time special');
- })
- .off('event', {}, () => {});
-
- person.on('greet', target, 'hi').one('greet', target, 'hi').off('event', target, 'hi');
-
- person.on('greet', target, target.hi).one('greet', target, target.hi).off('event', target, target.hi);
-
- person.greet();
+ interface Person extends Evented {}
+ class Person extends EmberObject {
+ greet() {
+ this.trigger('greet');
+ }
+ }
+
+ const person = Person.create();
+
+ person.on('potato', 'greet');
+
+ const target = {
+ hi() {
+ console.log('Hello!');
+ },
+ };
+
+ person.on('greet', () => {
+ console.log('Our person has greeted');
+ });
+
+ person
+ .on('greet', () => {
+ console.log('Our person has greeted');
+ })
+ .one('greet', () => {
+ console.log('Offer one-time special');
+ })
+ .off('event', {}, () => {});
+
+ person.on('greet', target, 'hi').one('greet', target, 'hi').off('event', target, 'hi');
+
+ person
+ .on('greet', target, target.hi)
+ .one('greet', target, target.hi)
+ .off('event', target, target.hi);
+
+ person.greet();
}
function testObserver() {
- EmberObject.extend({
- // TODO: enable after https://github.com/typed-ember/ember-cli-typescript/issues/290
- // valueObserver: observer('value', () => {
- // // Executes whenever the "value" property changes
- // })
- });
+ EmberObject.extend({
+ // TODO: enable after https://github.com/typed-ember/ember-cli-typescript/issues/290
+ // valueObserver: observer('value', () => {
+ // // Executes whenever the "value" property changes
+ // })
+ });
}
function testListener() {
- function willDestroyListener() {}
-
- EmberObject.extend({
- init() {
- addListener(this, 'willDestroy', this, 'willDestroyListener');
- addListener(this, 'willDestroy', this, 'willDestroyListener', true);
- addListener(this, 'willDestroy', this, willDestroyListener);
- addListener(this, 'willDestroy', this, willDestroyListener, true);
- removeListener(this, 'willDestroy', this, 'willDestroyListener');
- removeListener(this, 'willDestroy', this, willDestroyListener);
-
- addListener(this, 'willDestroy', 'willDestroyListener');
- addListener(this, 'willDestroy', 'willDestroyListener', true);
- addListener(this, 'willDestroy', willDestroyListener);
- addListener(this, 'willDestroy', willDestroyListener, true);
- removeListener(this, 'willDestroy', 'willDestroyListener');
- removeListener(this, 'willDestroy', willDestroyListener);
- },
-
- willDestroyListener() {
- willDestroyListener();
- },
- });
+ function willDestroyListener() {}
+
+ class Destroy extends EmberObject {
+ init() {
+ addListener(this, 'willDestroy', this, 'willDestroyListener');
+ addListener(this, 'willDestroy', this, 'willDestroyListener', true);
+ addListener(this, 'willDestroy', this, willDestroyListener);
+ addListener(this, 'willDestroy', this, willDestroyListener, true);
+ removeListener(this, 'willDestroy', this, 'willDestroyListener');
+ removeListener(this, 'willDestroy', this, willDestroyListener);
+
+ addListener(this, 'willDestroy', 'willDestroyListener');
+ addListener(this, 'willDestroy', 'willDestroyListener', true);
+ addListener(this, 'willDestroy', willDestroyListener);
+ addListener(this, 'willDestroy', willDestroyListener, true);
+ removeListener(this, 'willDestroy', 'willDestroyListener');
+ removeListener(this, 'willDestroy', willDestroyListener);
+ }
+
+ willDestroyListener() {
+ willDestroyListener();
+ }
+ }
} | true |
Other | emberjs | ember.js | 4730ecd8b7a8e6b7b3f560fb7dabd3de605c3753.json | Fix preview types and tests for `Evented` | types/preview/ember/index.d.ts | @@ -138,6 +138,7 @@ export namespace Ember {
const Error: typeof EmberError;
const Evented: typeof EmberObjectEventedNs.default;
+ interface Evented extends EmberObjectEventedNs.default {}
class Mixin extends EmberMixin {}
| true |
Other | emberjs | ember.js | 4730ecd8b7a8e6b7b3f560fb7dabd3de605c3753.json | Fix preview types and tests for `Evented` | types/preview/ember/test/event.ts | @@ -1,60 +1,61 @@
import Ember from 'ember';
function testOn() {
- const Job = Ember.Object.extend({
- logCompleted: Ember.on('completed', () => {
- console.log('Job completed!');
- }),
- });
+ const Job = Ember.Object.extend({
+ logCompleted: Ember.on('completed', () => {
+ console.log('Job completed!');
+ }),
+ });
- const job = Job.create();
+ const job = Job.create();
- Ember.sendEvent(job, 'completed'); // Logs 'Job completed!'
+ Ember.sendEvent(job, 'completed'); // Logs 'Job completed!'
}
function testEvented() {
- const Person = Ember.Object.extend(Ember.Evented, {
- greet() {
- this.trigger('greet');
- },
- });
-
- const person = Person.create();
-
- person.on('greet', () => {
- console.log('Our person has greeted');
- });
-
- person
- .on('greet', () => {
- console.log('Our person has greeted');
- })
- .one('greet', () => {
- console.log('Offer one-time special');
- })
- .off('event', {}, () => {});
-
- person.greet();
+ interface Person extends Ember.Evented {}
+ class Person extends Ember.Object {
+ greet() {
+ this.trigger('greet');
+ }
+ }
+
+ const person = Person.create();
+
+ person.on('greet', () => {
+ console.log('Our person has greeted');
+ });
+
+ person
+ .on('greet', () => {
+ console.log('Our person has greeted');
+ })
+ .one('greet', () => {
+ console.log('Offer one-time special');
+ })
+ .off('event', {}, () => {});
+
+ person.greet();
}
function testObserver() {
- Ember.Object.extend({
- valueObserver: Ember.observer('value', () => {
- // Executes whenever the "value" property changes
- }),
- });
+ Ember.Object.extend({
+ valueObserver: Ember.observer('value', () => {
+ // Executes whenever the "value" property changes
+ }),
+ });
}
function testListener() {
- Ember.Component.extend({
- init() {
- Ember.addListener(this, 'willDestroyElement', this, 'willDestroyListener');
- Ember.addListener(this, 'willDestroyElement', this, 'willDestroyListener', true);
- Ember.addListener(this, 'willDestroyElement', this, this.willDestroyListener);
- Ember.addListener(this, 'willDestroyElement', this, this.willDestroyListener, true);
- Ember.removeListener(this, 'willDestroyElement', this, 'willDestroyListener');
- Ember.removeListener(this, 'willDestroyElement', this, this.willDestroyListener);
- },
- willDestroyListener() {},
- });
+ class TestListener extends Ember.Component {
+ init() {
+ Ember.addListener(this, 'willDestroyElement', this, 'willDestroyListener');
+ Ember.addListener(this, 'willDestroyElement', this, 'willDestroyListener', true);
+ Ember.addListener(this, 'willDestroyElement', this, this.willDestroyListener);
+ Ember.addListener(this, 'willDestroyElement', this, this.willDestroyListener, true);
+ Ember.removeListener(this, 'willDestroyElement', this, 'willDestroyListener');
+ Ember.removeListener(this, 'willDestroyElement', this, this.willDestroyListener);
+ }
+ willDestroyListener() {}
+ }
} | true |
Other | emberjs | ember.js | 52abdf166e8a5c80063a6a6f59a6dfb7682d6287.json | Update preview types for @ember/controller | types/preview/@ember/controller/index.d.ts | @@ -1,7 +1,6 @@
import ActionHandler from '@ember/object/-private/action-handler';
import Mixin from '@ember/object/mixin';
import EmberObject from '@ember/object';
-import ComputedProperty from '@ember/object/computed';
type QueryParamTypes = 'boolean' | 'number' | 'array' | 'string';
type QueryParamScopeTypes = 'controller' | 'model';
@@ -32,13 +31,13 @@ export interface ControllerMixin extends ActionHandler {
queryParams: Array<string | Record<string, QueryParamConfig | string | undefined>>;
target: object;
}
-export const ControllerMixin: Mixin<ControllerMixin>;
+export const ControllerMixin: Mixin;
export default class Controller extends EmberObject {}
export default interface Controller extends ControllerMixin {}
-export function inject(): ComputedProperty<Controller>;
-export function inject<K extends keyof Registry>(name: K): ComputedProperty<Registry[K]>;
+export function inject(): Controller;
+export function inject<K extends keyof Registry>(name: K): Registry[K];
export function inject(target: object, propertyKey: string | symbol): void;
// A type registry for Ember `Controller`s. Meant to be declaration-merged | false |