text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { IgxTransactionService } from './igx-transaction'; import { Transaction, TransactionType, HierarchicalTransaction } from './transaction'; import { SampleTestData } from '../../test-utils/sample-test-data.spec'; import { IgxHierarchicalTransactionService } from './igx-hierarchical-transaction'; describe('IgxTransaction', () => { describe('IgxTransaction UNIT tests', () => { it('Should initialize transactions log properly', () => { const trans = new IgxTransactionService(); expect(trans).toBeDefined(); expect(trans['_transactions']).toBeDefined(); expect(trans['_transactions'].length).toEqual(0); expect(trans['_redoStack']).toBeDefined(); expect(trans['_redoStack'].length).toEqual(0); expect(trans['_states']).toBeDefined(); expect(trans['_states'].size).toEqual(0); }); it('Should add transactions to the transactions log', () => { const trans = new IgxTransactionService(); const transactions: Transaction[] = [ { id: '1', type: TransactionType.ADD, newValue: 1 }, { id: '2', type: TransactionType.ADD, newValue: 2 }, { id: '3', type: TransactionType.ADD, newValue: 3 }, { id: '1', type: TransactionType.UPDATE, newValue: 4 }, { id: '5', type: TransactionType.ADD, newValue: 5 }, { id: '6', type: TransactionType.ADD, newValue: 6 }, { id: '2', type: TransactionType.DELETE, newValue: 7 }, { id: '8', type: TransactionType.ADD, newValue: 8 }, { id: '9', type: TransactionType.ADD, newValue: 9 }, { id: '8', type: TransactionType.UPDATE, newValue: 10 } ]; expect(trans['_transactions'].length).toEqual(0); expect(trans['_redoStack'].length).toEqual(0); let transactionIndex = 1; transactions.forEach((transaction) => { trans.add(transaction); expect(trans.getTransactionLog(transaction.id).pop()).toEqual(transaction); expect(trans['_transactions'].length).toEqual(transactionIndex); expect(trans['_redoStack'].length).toEqual(0); transactionIndex++; }); }); it('Should throw an error when trying to add duplicate transaction', () => { const trans = new IgxTransactionService(); const transactions: Transaction[] = [ { id: '1', type: TransactionType.ADD, newValue: 1 }, { id: '2', type: TransactionType.ADD, newValue: 2 }, { id: '3', type: TransactionType.ADD, newValue: 3 }, { id: '1', type: TransactionType.UPDATE, newValue: 4 }, { id: '5', type: TransactionType.ADD, newValue: 5 }, { id: '6', type: TransactionType.ADD, newValue: 6 }, { id: '2', type: TransactionType.DELETE, newValue: 7 }, { id: '8', type: TransactionType.ADD, newValue: 8 }, { id: '9', type: TransactionType.ADD, newValue: 9 }, { id: '8', type: TransactionType.UPDATE, newValue: 10 } ]; transactions.forEach(t => trans.add(t)); const transaction = { id: '6', type: TransactionType.ADD, newValue: 6 }; expect(trans.getTransactionLog('6').pop()).toEqual(transaction); const msg = `Cannot add this transaction. Transaction with id: ${transaction.id} has been already added.`; expect(() => trans.add(transaction)).toThrowError(msg); }); it('Should throw an error when trying to update transaction with no recordRef', () => { const trans = new IgxTransactionService(); const transactions: Transaction[] = [ { id: '1', type: TransactionType.ADD, newValue: 1 }, { id: '2', type: TransactionType.ADD, newValue: 2 }, { id: '3', type: TransactionType.ADD, newValue: 3 }, { id: '1', type: TransactionType.UPDATE, newValue: 4 }, { id: '5', type: TransactionType.ADD, newValue: 5 }, { id: '6', type: TransactionType.ADD, newValue: 6 }, { id: '2', type: TransactionType.DELETE, newValue: 7 }, { id: '8', type: TransactionType.ADD, newValue: 8 }, { id: '9', type: TransactionType.ADD, newValue: 9 }, { id: '8', type: TransactionType.UPDATE, newValue: 10 } ]; transactions.forEach(transaction => trans.add(transaction)); const updateTransaction = { id: '2', type: TransactionType.DELETE, newValue: 7 }; expect(trans.getTransactionLog('2').pop()).toEqual(updateTransaction); const msg = `Cannot add this transaction. This is first transaction of type ${updateTransaction.type} ` + `for id ${updateTransaction.id}. For first transaction of this type recordRef is mandatory.`; expect(() => { updateTransaction.newValue = 107; trans.add(updateTransaction); }).toThrowError(msg); }); it('Should throw an error when trying to delete an already deleted item', () => { const trans = new IgxTransactionService(); const recordRef = { key: 'Key1', value: 1 }; const deleteTransaction: Transaction = { id: 'Key1', type: TransactionType.DELETE, newValue: null }; trans.add(deleteTransaction, recordRef); expect(trans.getTransactionLog('Key1').pop()).toEqual(deleteTransaction); const msg = `Cannot add this transaction. Transaction with id: ${deleteTransaction.id} has been already deleted.`; expect(() => trans.add(deleteTransaction)).toThrowError(msg); }); it('Should throw an error when trying to update an already deleted item', () => { const trans = new IgxTransactionService(); const recordRef = { key: 'Key1', value: 1 }; const deleteTransaction: Transaction = { id: 'Key1', type: TransactionType.DELETE, newValue: null }; trans.add(deleteTransaction, recordRef); expect(trans.getTransactionLog('Key1').pop()).toEqual(deleteTransaction); const msg = `Cannot add this transaction. Transaction with id: ${deleteTransaction.id} has been already deleted.`; expect(() => { deleteTransaction.type = TransactionType.UPDATE; deleteTransaction.newValue = 5; trans.add(deleteTransaction); }).toThrowError(msg); }); it('Should get a transaction by transaction id', () => { const trans = new IgxTransactionService(); let transaction: Transaction = { id: '0', type: TransactionType.ADD, newValue: 0 }; trans.add(transaction); expect(trans.getTransactionLog('0').pop()).toEqual(transaction); transaction = { id: '1', type: TransactionType.ADD, newValue: 1 }; trans.add(transaction); expect(trans.getTransactionLog('1').pop()).toEqual(transaction); transaction = { id: '2', type: TransactionType.ADD, newValue: 2 }; trans.add(transaction); expect(trans.getTransactionLog('2').pop()).toEqual(transaction); transaction = { id: '3', type: TransactionType.ADD, newValue: 3 }; trans.add(transaction); expect(trans.getTransactionLog('3').pop()).toEqual(transaction); transaction = { id: '1', type: TransactionType.UPDATE, newValue: 4 }; trans.add(transaction); expect(trans.getTransactionLog('1').pop()).toEqual(transaction); transaction = { id: '5', type: TransactionType.ADD, newValue: 5 }; trans.add(transaction); expect(trans.getTransactionLog('5').pop()).toEqual(transaction); transaction = { id: '6', type: TransactionType.ADD, newValue: 6 }; trans.add(transaction); expect(trans.getTransactionLog('6').pop()).toEqual(transaction); transaction = { id: '2', type: TransactionType.DELETE, newValue: 7 }; trans.add(transaction); expect(trans.getTransactionLog('2').pop()).toEqual(transaction); transaction = { id: '8', type: TransactionType.ADD, newValue: 8 }; trans.add(transaction); expect(trans.getTransactionLog('8').pop()).toEqual(transaction); transaction = { id: '9', type: TransactionType.ADD, newValue: 9 }; trans.add(transaction); expect(trans.getTransactionLog('9').pop()).toEqual(transaction); transaction = { id: '8', type: TransactionType.UPDATE, newValue: 10 }; trans.add(transaction); expect(trans.getTransactionLog('8').pop()).toEqual(transaction); // Get nonexisting transaction expect(trans.getTransactionLog('100').pop()).toEqual(undefined); }); it('Should add ADD type transaction - all feasible paths, and correctly fires onStateUpdate', () => { const trans = new IgxTransactionService(); spyOn(trans.onStateUpdate, 'emit').and.callThrough(); expect(trans).toBeDefined(); // ADD const addTransaction: Transaction = { id: 0, type: TransactionType.ADD, newValue: 1 }; trans.add(addTransaction); expect(trans.getAggregatedValue(0, true)).toEqual(1); expect(trans.getTransactionLog(0).pop()).toEqual(addTransaction); expect(trans.getTransactionLog()).toEqual([addTransaction]); expect(trans.getState(addTransaction.id)).toEqual({ value: addTransaction.newValue, recordRef: undefined, type: addTransaction.type }); expect(trans.onStateUpdate.emit).toHaveBeenCalledTimes(1); trans.clear(); expect(trans.getState(0)).toBeUndefined(); expect(trans.getAggregatedValue(0, true)).toBeNull(); expect(trans.getTransactionLog()).toEqual([]); expect(trans.getAggregatedChanges(true)).toEqual([]); expect(trans.onStateUpdate.emit).toHaveBeenCalledTimes(2); // ADD -> Undo trans.add(addTransaction); trans.undo(); expect(trans.getTransactionLog()).toEqual([]); expect(trans.getAggregatedChanges(true)).toEqual([]); expect(trans.onStateUpdate.emit).toHaveBeenCalledTimes(4); trans.clear(); expect(trans.onStateUpdate.emit).toHaveBeenCalledTimes(5); // ADD -> Undo -> Redo trans.add(addTransaction); trans.undo(); trans.redo(); expect(trans.getTransactionLog()).toEqual([addTransaction]); expect(trans.getState(addTransaction.id)).toEqual({ value: addTransaction.newValue, recordRef: undefined, type: addTransaction.type }); expect(trans.onStateUpdate.emit).toHaveBeenCalledTimes(8); trans.clear(); expect(trans.onStateUpdate.emit).toHaveBeenCalledTimes(9); // ADD -> DELETE trans.add(addTransaction); const deleteTransaction: Transaction = { id: 0, type: TransactionType.DELETE, newValue: 1 }; trans.add(deleteTransaction); expect(trans.getTransactionLog()).toEqual([addTransaction, deleteTransaction]); expect(trans.getAggregatedChanges(true)).toEqual([]); expect(trans.onStateUpdate.emit).toHaveBeenCalledTimes(11); trans.clear(); expect(trans.onStateUpdate.emit).toHaveBeenCalledTimes(12); // ADD -> DELETE -> Undo trans.add(addTransaction); trans.add(deleteTransaction); trans.undo(); expect(trans.getTransactionLog()).toEqual([addTransaction]); expect(trans.getState(addTransaction.id)).toEqual({ value: addTransaction.newValue, recordRef: undefined, type: addTransaction.type }); expect(trans.onStateUpdate.emit).toHaveBeenCalledTimes(15); trans.clear(); expect(trans.onStateUpdate.emit).toHaveBeenCalledTimes(16); // ADD -> DELETE -> Undo -> Redo trans.add(addTransaction); trans.add(deleteTransaction); trans.undo(); trans.redo(); expect(trans.getTransactionLog()).toEqual([addTransaction, deleteTransaction]); expect(trans.getAggregatedChanges(true)).toEqual([]); expect(trans.onStateUpdate.emit).toHaveBeenCalledTimes(20); trans.clear(); expect(trans.onStateUpdate.emit).toHaveBeenCalledTimes(21); // ADD -> DELETE -> Undo -> Undo trans.add(addTransaction); trans.add(deleteTransaction); trans.undo(); trans.undo(); expect(trans.getTransactionLog()).toEqual([]); expect(trans.getAggregatedChanges(true)).toEqual([]); expect(trans.onStateUpdate.emit).toHaveBeenCalledTimes(25); trans.clear(); expect(trans.onStateUpdate.emit).toHaveBeenCalledTimes(26); // ADD -> UPDATE trans.add(addTransaction); const updateTransaction: Transaction = { id: 0, type: TransactionType.UPDATE, newValue: 2 }; trans.add(updateTransaction); expect(trans.getTransactionLog()).toEqual([addTransaction, updateTransaction]); expect(trans.getState(addTransaction.id)).toEqual({ value: updateTransaction.newValue, recordRef: undefined, type: addTransaction.type }); expect(trans.onStateUpdate.emit).toHaveBeenCalledTimes(28); trans.clear(); expect(trans.onStateUpdate.emit).toHaveBeenCalledTimes(29); // ADD -> UPDATE -> Undo trans.add(addTransaction); trans.add(updateTransaction); trans.undo(); expect(trans.getTransactionLog()).toEqual([addTransaction]); expect(trans.getState(addTransaction.id)).toEqual({ value: addTransaction.newValue, recordRef: undefined, type: addTransaction.type }); expect(trans.onStateUpdate.emit).toHaveBeenCalledTimes(32); trans.clear(); expect(trans.onStateUpdate.emit).toHaveBeenCalledTimes(33); // ADD -> UPDATE -> Undo -> Redo trans.add(addTransaction); trans.add(updateTransaction); trans.undo(); trans.redo(); expect(trans.getTransactionLog()).toEqual([addTransaction, updateTransaction]); expect(trans.getState(addTransaction.id)).toEqual({ value: updateTransaction.newValue, recordRef: undefined, type: addTransaction.type }); expect(trans.onStateUpdate.emit).toHaveBeenCalledTimes(37); trans.clear(); expect(trans.onStateUpdate.emit).toHaveBeenCalledTimes(38); }); it('Should add DELETE type transaction - all feasible paths', () => { const trans = new IgxTransactionService(); expect(trans).toBeDefined(); // DELETE const recordRef = { key: 'Key1', value: 1 }; const deleteTransaction: Transaction = { id: 'Key1', type: TransactionType.DELETE, newValue: null }; trans.add(deleteTransaction, recordRef); expect(trans.getTransactionLog('Key1').pop()).toEqual(deleteTransaction); expect(trans.getTransactionLog()).toEqual([deleteTransaction]); expect(trans.getState(deleteTransaction.id)).toEqual({ value: null, recordRef, type: deleteTransaction.type }); trans.clear(); expect(trans.getTransactionLog()).toEqual([]); expect(trans.getAggregatedChanges(true)).toEqual([]); // DELETE -> Undo trans.add(deleteTransaction, recordRef); trans.undo(); expect(trans.getTransactionLog()).toEqual([]); expect(trans.getAggregatedChanges(true)).toEqual([]); trans.clear(); // DELETE -> Undo -> Redo trans.add(deleteTransaction, recordRef); trans.undo(); trans.redo(); expect(trans.getTransactionLog('Key1').pop()).toEqual(deleteTransaction); expect(trans.getTransactionLog()).toEqual([deleteTransaction]); expect(trans.getState(deleteTransaction.id)).toEqual({ value: null, recordRef, type: deleteTransaction.type }); trans.clear(); }); it('Should add UPDATE type transaction - all feasible paths', () => { const trans = new IgxTransactionService(); expect(trans).toBeDefined(); // UPDATE const recordRef = { key: 'Key1', value: 1 }; const newValue = { key: 'Key1', value: 2 }; const updateTransaction: Transaction = { id: 'Key1', type: TransactionType.UPDATE, newValue }; trans.add(updateTransaction, recordRef); expect(trans.getState('Key1')).toBeTruthy(); expect(trans.getAggregatedValue('Key1', true)).toEqual(newValue); expect(trans.getTransactionLog('Key1').pop()).toEqual(updateTransaction); expect(trans.getTransactionLog()).toEqual([updateTransaction]); expect(trans.getState(updateTransaction.id)).toEqual({ value: { value: 2 }, recordRef, type: updateTransaction.type }); trans.clear(); expect(trans.getState('Key1')).toBeFalsy(); expect(trans.getAggregatedValue('Key1', true)).toBeNull(); expect(trans.getTransactionLog()).toEqual([]); expect(trans.getAggregatedChanges(true)).toEqual([]); // UPDATE -> Undo trans.add(updateTransaction, recordRef); trans.undo(); expect(trans.getTransactionLog()).toEqual([]); expect(trans.getAggregatedChanges(true)).toEqual([]); trans.clear(); // UPDATE -> Undo -> Redo trans.add(updateTransaction, recordRef); trans.undo(); trans.redo(); expect(trans.getTransactionLog('Key1').pop()).toEqual(updateTransaction); expect(trans.getTransactionLog()).toEqual([updateTransaction]); expect(trans.getState(updateTransaction.id)).toEqual({ value: { value: 2 }, recordRef, type: updateTransaction.type }); trans.clear(); // UPDATE -> UPDATE trans.add(updateTransaction, recordRef); const newValue2 = { key: 'Key1', value: 3 }; const updateTransaction2: Transaction = { id: 'Key1', type: TransactionType.UPDATE, newValue: newValue2 }; trans.add(updateTransaction2, recordRef); expect(trans.getTransactionLog('Key1').pop()).toEqual(updateTransaction2); expect(trans.getTransactionLog()).toEqual([updateTransaction, updateTransaction2]); expect(trans.getState(updateTransaction.id)).toEqual({ value: { value: 3 }, recordRef, type: updateTransaction2.type }); trans.clear(); // UPDATE -> UPDATE (to initial recordRef) trans.add(updateTransaction, recordRef); const asRecordRefTransaction: Transaction = { id: 'Key1', type: TransactionType.UPDATE, newValue: recordRef }; trans.add(asRecordRefTransaction, recordRef); expect(trans.getTransactionLog('Key1').pop()).toEqual(asRecordRefTransaction); expect(trans.getTransactionLog()).toEqual([updateTransaction, asRecordRefTransaction]); expect(trans.getState(updateTransaction.id)).toBeUndefined(); expect(trans.getAggregatedChanges(false)).toEqual([]); trans.clear(); // UPDATE -> UPDATE -> Undo trans.add(updateTransaction, recordRef); trans.add(updateTransaction2, recordRef); trans.undo(); expect(trans.getTransactionLog('Key1').pop()).toEqual(updateTransaction); expect(trans.getTransactionLog()).toEqual([updateTransaction]); expect(trans.getState(updateTransaction.id)).toEqual({ value: { value: 2 }, recordRef, type: updateTransaction.type }); trans.clear(); // UPDATE -> UPDATE -> Undo -> Redo trans.add(updateTransaction, recordRef); trans.add(updateTransaction2, recordRef); trans.undo(); trans.redo(); expect(trans.getTransactionLog('Key1').pop()).toEqual(updateTransaction2); expect(trans.getTransactionLog()).toEqual([updateTransaction, updateTransaction2]); expect(trans.getState(updateTransaction.id)).toEqual({ value: { value: 3 }, recordRef, type: updateTransaction2.type }); trans.clear(); // UPDATE -> DELETE trans.add(updateTransaction, recordRef); const deleteTransaction: Transaction = { id: 'Key1', type: TransactionType.DELETE, newValue: null }; trans.add(deleteTransaction); expect(trans.getTransactionLog('Key1').pop()).toEqual(deleteTransaction); expect(trans.getTransactionLog()).toEqual([updateTransaction, deleteTransaction]); expect(trans.getState(deleteTransaction.id)).toEqual({ value: deleteTransaction.newValue, recordRef, type: deleteTransaction.type }); trans.clear(); // UPDATE -> DELETE -> Undo trans.add(updateTransaction, recordRef); trans.add(deleteTransaction); trans.undo(); expect(trans.getTransactionLog('Key1').pop()).toEqual(updateTransaction); expect(trans.getTransactionLog()).toEqual([updateTransaction]); expect(trans.getState(updateTransaction.id)).toEqual({ value: { value: 2 }, recordRef, type: updateTransaction.type }); trans.clear(); // UPDATE -> DELETE -> Undo -> Redo trans.add(updateTransaction, recordRef); trans.add(deleteTransaction); trans.undo(); trans.redo(); expect(trans.getTransactionLog('Key1').pop()).toEqual(deleteTransaction); expect(trans.getTransactionLog()).toEqual([updateTransaction, deleteTransaction]); expect(trans.getState(deleteTransaction.id)).toEqual({ value: deleteTransaction.newValue, recordRef, type: deleteTransaction.type }); trans.clear(); }); it('Should properly confirm the length of the undo/redo stacks', () => { const transaction = new IgxTransactionService(); expect(transaction).toBeDefined(); // Stacks are clear by default expect(transaction.canRedo).toBeFalsy(); expect(transaction.canUndo).toBeFalsy(); let addItem: Transaction = { id: 1, type: TransactionType.ADD, newValue: { Category: 'Something' } }; transaction.add(addItem); expect(transaction.canRedo).toBeFalsy(); expect(transaction.canUndo).toBeTruthy(); addItem = { id: 2, type: TransactionType.ADD, newValue: { Category: 'Something 2' } }; transaction.add(addItem); expect(transaction.canRedo).toBeFalsy(); expect(transaction.canUndo).toBeTruthy(); transaction.undo(); expect(transaction.canRedo).toBeTruthy(); expect(transaction.canUndo).toBeTruthy(); transaction.undo(); expect(transaction.canRedo).toBeTruthy(); expect(transaction.canUndo).toBeFalsy(); transaction.redo(); expect(transaction.canRedo).toBeTruthy(); expect(transaction.canUndo).toBeTruthy(); transaction.redo(); expect(transaction.canRedo).toBeFalsy(); expect(transaction.canUndo).toBeTruthy(); }); it('Should update data when data is list of objects', () => { const originalData = SampleTestData.generateProductData(50); const trans = new IgxTransactionService(); expect(trans).toBeDefined(); const item0Update1: Transaction = { id: 1, type: TransactionType.UPDATE, newValue: { Category: 'Some new value' } }; trans.add(item0Update1, originalData[1]); const item10Delete: Transaction = { id: 10, type: TransactionType.DELETE, newValue: null }; trans.add(item10Delete, originalData[10]); const newItem1: Transaction = { id: 'add1', type: TransactionType.ADD, newValue: { ID: undefined, Category: 'Category Added', Downloads: 100, Items: 'Items Added', ProductName: 'ProductName Added', ReleaseDate: new Date(), Released: true, Test: 'test Added' } }; trans.add(newItem1, undefined); trans.commit(originalData); expect(originalData.find(i => i.ID === 1).Category).toBe('Some new value'); expect(originalData.find(i => i.ID === 10)).toBeUndefined(); expect(originalData.length).toBe(50); expect(originalData[49]).toEqual(newItem1.newValue); }); it('Should update data for provided id when data is list of objects', () => { const originalData = SampleTestData.generateProductData(50); const trans = new IgxTransactionService(); expect(trans).toBeDefined(); const item0Update1: Transaction = { id: 0, type: TransactionType.UPDATE, newValue: { Category: 'Some new value' } }; trans.add(item0Update1, originalData[1]); const item10Delete: Transaction = { id: 10, type: TransactionType.DELETE, newValue: null }; trans.add(item10Delete, originalData[10]); const newItem1: Transaction = { id: 'add1', type: TransactionType.ADD, newValue: { ID: undefined, Category: 'Category Added', Downloads: 100, Items: 'Items Added', ProductName: 'ProductName Added', ReleaseDate: new Date(), Released: true, Test: 'test Added' } }; trans.add(newItem1, undefined); trans.commit(originalData, 10); expect(originalData.find(i => i.ID === 1).Category).toBe('Category1'); expect(originalData.find(i => i.ID === 10)).toBeUndefined(); expect(originalData.length).toBe(49); trans.commit(originalData, 'FAKE ID'); expect(originalData.find(i => i.ID === 1).Category).toBe('Category1'); expect(originalData.find(i => i.ID === 10)).toBeUndefined(); expect(originalData.length).toBe(49); trans.commit(originalData, 20); expect(originalData.find(i => i.ID === 1).Category).toBe('Category1'); expect(originalData.find(i => i.ID === 10)).toBeUndefined(); expect(originalData.length).toBe(49); trans.commit(originalData, 0); expect(originalData.find(i => i.ID === 1).Category).toBe('Some new value'); expect(originalData.find(i => i.ID === 10)).toBeUndefined(); expect(originalData.length).toBe(49); trans.commit(originalData, 'add1'); expect(originalData.find(i => i.ID === 1).Category).toBe('Some new value'); expect(originalData.find(i => i.ID === 10)).toBeUndefined(); expect(originalData.length).toBe(50); expect(originalData[49]).toEqual(newItem1.newValue); }); it('Should update data when data is list of primitives', () => { const originalData = SampleTestData.generateListOfPrimitiveValues(50, 'String'); const trans = new IgxTransactionService(); expect(trans).toBeDefined(); const item0Update1: Transaction = { id: 1, type: TransactionType.UPDATE, newValue: 'Updated Row' }; trans.add(item0Update1, originalData[1]); const item10Delete: Transaction = { id: 10, type: TransactionType.DELETE, newValue: null }; trans.add(item10Delete, originalData[10]); const newItem1: Transaction = { id: 'add1', type: TransactionType.ADD, newValue: 'Added Row' }; trans.add(newItem1, undefined); trans.commit(originalData); expect(originalData[1]).toBe('Updated Row'); expect(originalData.find(i => i === 'Row 10')).toBeUndefined(); expect(originalData.length).toBe(50); expect(originalData[49]).toEqual('Added Row'); }); it('Should update data for provided id when data is list of primitives', () => { const originalData = SampleTestData.generateListOfPrimitiveValues(50, 'String'); const trans = new IgxTransactionService(); expect(trans).toBeDefined(); const item0Update1: Transaction = { id: 1, type: TransactionType.UPDATE, newValue: 'Updated Row' }; trans.add(item0Update1, originalData[1]); const item10Delete: Transaction = { id: 10, type: TransactionType.DELETE, newValue: null }; trans.add(item10Delete, originalData[10]); const newItem1: Transaction = { id: 'add1', type: TransactionType.ADD, newValue: 'Added Row' }; trans.add(newItem1, undefined); trans.commit(originalData, 10); expect(originalData[1]).toBe('Row 1'); expect(originalData.find(i => i.id === 'Row 10')).toBeUndefined(); expect(originalData.length).toBe(49); trans.commit(originalData, 'FAKE ID'); expect(originalData[1]).toBe('Row 1'); expect(originalData.find(i => i.id === 'Row 10')).toBeUndefined(); expect(originalData.length).toBe(49); trans.commit(originalData, 20); expect(originalData[1]).toBe('Row 1'); expect(originalData.find(i => i.id === 'Row 10')).toBeUndefined(); expect(originalData.length).toBe(49); trans.commit(originalData, 1); expect(originalData[1]).toBe('Updated Row'); expect(originalData.find(i => i.id === 'Row 10')).toBeUndefined(); expect(originalData.length).toBe(49); trans.commit(originalData, 'add1'); expect(originalData[1]).toBe('Updated Row'); expect(originalData.find(i => i.id === 'Row 10')).toBeUndefined(); expect(originalData.length).toBe(50); expect(originalData[49]).toEqual(newItem1.newValue); }); it('Should add pending transaction and push it to transaction log, and correctly fires onStateUpdate', () => { const trans = new IgxTransactionService(); spyOn(trans.onStateUpdate, 'emit').and.callThrough(); expect(trans).toBeDefined(); const recordRef = { key: 'Key1', value1: 1, value2: 2, value3: 3 }; let newValue: any = { key: 'Key1', value1: 10 }; let updateTransaction: Transaction = { id: 'Key1', type: TransactionType.UPDATE, newValue }; trans.startPending(); trans.add(updateTransaction, recordRef); expect(trans.getState('Key1')).toBeUndefined(); expect(trans.getAggregatedValue('Key1', true)).toEqual({ key: 'Key1', value1: 10, value2: 2, value3: 3 }); expect(trans.getTransactionLog()).toEqual([]); expect(trans.getAggregatedChanges(true)).toEqual([]); newValue = { key: 'Key1', value3: 30 }; updateTransaction = { id: 'Key1', type: TransactionType.UPDATE, newValue }; trans.add(updateTransaction, recordRef); expect(trans.getState('Key1')).toBeUndefined(); expect(trans.getAggregatedValue('Key1', true)).toEqual({ key: 'Key1', value1: 10, value2: 2, value3: 30 }); expect(trans.getTransactionLog()).toEqual([]); expect(trans.getAggregatedChanges(true)).toEqual([]); trans.endPending(true); expect(trans.getState('Key1')).toBeTruthy(); expect(trans.getAggregatedValue('Key1', true)).toEqual({ key: 'Key1', value1: 10, value2: 2, value3: 30 }); expect(trans.getTransactionLog() as any).toEqual( [ { id: 'Key1', newValue: { key: 'Key1', value1: 10 }, type: 'update' }, { id: 'Key1', newValue: { key: 'Key1', value3: 30 }, type: 'update' } ]); expect(trans.getState(updateTransaction.id)).toEqual({ value: { value1: 10, value3: 30 }, recordRef, type: updateTransaction.type }); expect(trans.onStateUpdate.emit).toHaveBeenCalledTimes(1); }); it('Should not add pending transaction and push it to transaction log, and correctly fires onStateUpdate', () => { const trans = new IgxTransactionService(); spyOn(trans.onStateUpdate, 'emit').and.callThrough(); expect(trans).toBeDefined(); const recordRef = { key: 'Key1', value1: 1, value2: 2, value3: 3 }; let newValue: any = { key: 'Key1', value1: 10 }; let updateTransaction: Transaction = { id: 'Key1', type: TransactionType.UPDATE, newValue }; trans.startPending(); trans.add(updateTransaction, recordRef); expect(trans.getTransactionLog()).toEqual([]); expect(trans.getAggregatedChanges(true)).toEqual([]); newValue = { key: 'Key1', value3: 30 }; updateTransaction = { id: 'Key1', type: TransactionType.UPDATE, newValue }; trans.add(updateTransaction, recordRef); expect(trans.getTransactionLog()).toEqual([]); expect(trans.getAggregatedChanges(true)).toEqual([]); trans.endPending(false); expect(trans.getTransactionLog()).toEqual([]); expect(trans.getAggregatedChanges(true)).toEqual([]); expect(trans.onStateUpdate.emit).toHaveBeenCalledTimes(0); }); it('Should clear transactions for provided id', () => { const originalData = SampleTestData.generateProductData(50); const trans = new IgxTransactionService(); expect(trans).toBeDefined(); let transaction: Transaction = { id: 1, type: TransactionType.UPDATE, newValue: { Category: 'Some new value' } }; trans.add(transaction, originalData[1]); transaction = { id: 2, type: TransactionType.UPDATE, newValue: { Category: 'Some new value' } }; trans.add(transaction, originalData[2]); transaction = { id: 2, type: TransactionType.UPDATE, newValue: { Items: 'Some new value' } }; trans.add(transaction, originalData[2]); transaction = { id: 1, type: TransactionType.UPDATE, newValue: { Category: 'Some very new value' } }; trans.add(transaction, originalData[1]); transaction = { id: 10, type: TransactionType.UPDATE, newValue: { Category: 'Some new value' } }; trans.add(transaction, originalData[10]); expect(trans.getTransactionLog().length).toBe(5); expect(trans.getAggregatedChanges(true).length).toBe(3); expect(trans.canUndo).toBeTruthy(); expect(trans.canRedo).toBeFalsy(); trans.clear(1); expect(trans.getTransactionLog().length).toBe(3); expect(trans.getAggregatedChanges(true).length).toBe(2); expect(trans.canUndo).toBeTruthy(); expect(trans.canRedo).toBeFalsy(); trans.clear('FAKE ID'); expect(trans.getTransactionLog().length).toBe(3); expect(trans.getAggregatedChanges(true).length).toBe(2); expect(trans.canUndo).toBeTruthy(); expect(trans.canRedo).toBeFalsy(); trans.clear(20); expect(trans.getTransactionLog().length).toBe(3); expect(trans.getAggregatedChanges(true).length).toBe(2); expect(trans.canUndo).toBeTruthy(); expect(trans.canRedo).toBeFalsy(); trans.clear(10); expect(trans.getTransactionLog().length).toBe(2); expect(trans.getAggregatedChanges(true).length).toBe(1); expect(trans.canUndo).toBeTruthy(); expect(trans.canRedo).toBeFalsy(); }); }); describe('IgxHierarchicalTransaction UNIT Test', () => { it('Should set path for each state when transaction is added in Hierarchical data source', () => { const transaction = new IgxHierarchicalTransactionService(); expect(transaction).toBeDefined(); const path: any[] = ['P1', 'P2']; const addTransaction: HierarchicalTransaction = { id: 1, type: TransactionType.ADD, newValue: 'Add row', path }; transaction.add(addTransaction); expect(transaction.getState(1).path).toBeDefined(); expect(transaction.getState(1).path.length).toBe(2); expect(transaction.getState(1).path).toEqual(path); path.push('P3'); const updateTransaction: HierarchicalTransaction = { id: 1, type: TransactionType.UPDATE, newValue: 'Updated row', path }; transaction.add(updateTransaction, 'Update row'); expect(transaction.getState(1).path.length).toBe(3); expect(transaction.getState(1).path).toEqual(path); }); it('Should remove added transaction from states when deleted in Hierarchical data source', () => { const transaction = new IgxHierarchicalTransactionService(); expect(transaction).toBeDefined(); const path: any[] = []; let addTransaction: HierarchicalTransaction = { id: 1, type: TransactionType.ADD, newValue: 'Parent row', path }; transaction.add(addTransaction); expect(transaction.getState(1).path).toBeDefined(); expect(transaction.getState(1).path.length).toBe(0); expect(transaction.getState(1).path).toEqual(path); path.push(addTransaction.id); addTransaction = { id: 2, type: TransactionType.ADD, newValue: 'Child row', path }; transaction.add(addTransaction); expect(transaction.getState(2).path).toBeDefined(); expect(transaction.getState(2).path.length).toBe(1); expect(transaction.getState(2).path).toEqual(path); const deleteTransaction: HierarchicalTransaction = { id: 1, type: TransactionType.DELETE, newValue: null, path: [] }; transaction.add(deleteTransaction); expect(transaction.getState(1)).toBeUndefined(); expect(transaction.getState(2)).toBeUndefined(); }); it('Should mark update transactions state as deleted type when deleted in Hierarchical data source', () => { const transaction = new IgxHierarchicalTransactionService(); expect(transaction).toBeDefined(); const path: any[] = []; let updateTransaction: HierarchicalTransaction = { id: 1, type: TransactionType.UPDATE, newValue: 'Parent row', path }; transaction.add(updateTransaction, 'Original value'); expect(transaction.getState(1).path).toBeDefined(); expect(transaction.getState(1).path.length).toBe(0); expect(transaction.getState(1).path).toEqual(path); path.push(updateTransaction.id); updateTransaction = { id: 2, type: TransactionType.UPDATE, newValue: 'Child row', path }; transaction.add(updateTransaction, 'Original Value'); expect(transaction.getState(2).path).toBeDefined(); expect(transaction.getState(2).path.length).toBe(1); expect(transaction.getState(2).path).toEqual(path); const deleteTransaction: HierarchicalTransaction = { id: 1, type: TransactionType.DELETE, newValue: null, path: [] }; transaction.add(deleteTransaction); expect(transaction.getState(1)).toBeDefined(); expect(transaction.getState(1).type).toBe(TransactionType.DELETE); expect(transaction.getState(2)).toBeDefined(); expect(transaction.getState(2).type).toBe(TransactionType.DELETE); }); it('Should correctly call getAggregatedChanges without commit when recordRef is null', () => { const transaction = new IgxHierarchicalTransactionService(); expect(transaction).toBeDefined(); const deleteTransaction: HierarchicalTransaction = { id: 0, type: TransactionType.DELETE, newValue: null, path: [] }; transaction.add(deleteTransaction, 'Deleted row'); expect(transaction.getAggregatedChanges(false)).toEqual([deleteTransaction]); }); it('Should update data for provided id', () => { const data = SampleTestData.employeeTreeData(); const transaction = new IgxHierarchicalTransactionService(); expect(transaction).toBeDefined(); const addTransaction: HierarchicalTransaction = { id: 0, type: TransactionType.ADD, newValue: { ID: 999, Name: 'Root Add Transaction', HireDate: new Date(2018, 3, 20), Age: 45, OnPTO: false, Employees: [] }, path: null }; transaction.add(addTransaction); const updateTransaction: HierarchicalTransaction = { id: 475, type: TransactionType.UPDATE, newValue: { Age: 60 }, path: [data[0].ID] }; transaction.add(updateTransaction, data[0].Employees[0]); const deleteTransaction: HierarchicalTransaction = { id: 711, type: TransactionType.DELETE, newValue: {}, path: [data[0].ID, data[0].Employees[2].ID] }; transaction.add(deleteTransaction, data[0].Employees[2].Employees[0]); updateTransaction.newValue = { Name: 'New Name'}; transaction.add(updateTransaction, data[0].Employees[0]); expect(data.find(i => i.ID === 999)).toBeUndefined(); expect(data.length).toBe(4); transaction.commit(data, 'ID', 'Employees', 0); expect(data.find(i => i.ID === 999)).toBeDefined(); expect(data.find(i => i.ID === 999).Name).toBe('Root Add Transaction'); expect(data.length).toBe(5); expect(transaction.canUndo).toBeTruthy(); expect(transaction.getAggregatedChanges(false).length).toBe(2); expect(data[0].Employees[0].Age).toBe(43); expect(data[0].Employees[0].Name).toBe('Michael Langdon'); transaction.commit(data, 'ID', 'Employees', 475); expect(data[0].Employees[0].Age).toBe(60); expect(data[0].Employees[0].Name).toBe('New Name'); expect(transaction.canUndo).toBeTruthy(); expect(transaction.getAggregatedChanges(false).length).toBe(1); expect(data[0].Employees[2].Employees.length).toBe(2); transaction.commit(data, 'ID', 'Employees', 711); expect(data[0].Employees[2].Employees.length).toBe(1); expect(transaction.canUndo).toBeFalsy(); expect(transaction.getAggregatedChanges(false).length).toBe(0); }); it('Should emit onStateUpdate once when commiting a hierarchical transaction', () => { const data = SampleTestData.employeeTreeData(); const transaction = new IgxHierarchicalTransactionService(); spyOn(transaction.onStateUpdate, 'emit').and.callThrough(); expect(transaction).toBeDefined(); const updateTransaction: HierarchicalTransaction = { id: 475, type: TransactionType.UPDATE, newValue: { Age: 60 }, path: [data[0].ID] }; transaction.add(updateTransaction, data[0].Employees[0]); expect(transaction.onStateUpdate.emit).toHaveBeenCalledTimes(1); transaction.commit(data, 'ID'); expect(transaction.onStateUpdate.emit).toHaveBeenCalledTimes(2); }); }); });
the_stack
import * as React from 'react'; import styles from './InvitationManager.module.scss'; import { IInvitationManagerProps } from './IInvitationManagerProps'; import { IInvitationManagerState } from './IInvitationManagerState'; import { IInvitation } from './IInvitation'; import { IExternalUser } from './IExternalUser'; import { escape } from '@microsoft/sp-lodash-subset'; import { HttpClient, IHttpClientOptions, HttpClientResponse } from '@microsoft/sp-http'; import * as AuthenticationContext from 'adal-angular'; import adalConfig from '../AdalConfig'; import { IAdalConfig } from '../../IAdalConfig'; import '../../WebPartAuthenticationContext'; import { PrimaryButton, IButtonProps, DefaultButton } from 'office-ui-fabric-react/lib/Button'; import { TextField } from 'office-ui-fabric-react/lib/TextField'; import { Toggle } from 'office-ui-fabric-react/lib/Toggle'; import { autobind } from 'office-ui-fabric-react/lib/Utilities'; import { Icon } from 'office-ui-fabric-react/lib/Icon'; import { DetailsList, DetailsListLayoutMode, Selection } from 'office-ui-fabric-react/lib/DetailsList'; import { MarqueeSelection } from 'office-ui-fabric-react/lib/MarqueeSelection'; let _items = []; let _columns = [ { key: 'column1', name: 'Name', fieldName: 'name', minWidth: 100, maxWidth: 200, isResizable: true }, { key: 'column2', name: 'Value', fieldName: 'value', minWidth: 100, maxWidth: 200, isResizable: true }, ]; export default class InvitationManager extends React.Component<IInvitationManagerProps, IInvitationManagerState> { private _selection: Selection; private authCtx: adal.AuthenticationContext; constructor(props: IInvitationManagerProps, context?: any) { super(props); this._selection = new Selection({ onSelectionChanged: () => //this.setState({ selectionDetails: this._getSelectionDetails() }) this.setState((previousState: IInvitationManagerState, props: IInvitationManagerProps): IInvitationManagerState => { previousState.selectionDetails = this._getSelectionDetails(); return previousState; }) }); this.state = { loading: false, error: null, invitation: null, signedIn: false, sendInvitationMessage: true, redirectUrl: '', emailAddress: '', displayName: '', externalUser: null, selectionDetails: this._getSelectionDetails(), items: [], }; const config: IAdalConfig = adalConfig; config.popUp = true; config.webPartId = this.props.webPartId; config.callback = (error: any, token: string): void => { this.setState((previousState: IInvitationManagerState, currentProps: IInvitationManagerProps): IInvitationManagerState => { previousState.error = error; previousState.signedIn = !(!this.authCtx.getCachedUser()); return previousState; }); }; this.authCtx = new AuthenticationContext(config); AuthenticationContext.prototype._singletonInstance = undefined; } public componentDidMount(): void { this.authCtx.handleWindowCallback(); if (window !== window.top) { return; } this.setState((previousState: IInvitationManagerState, props: IInvitationManagerProps): IInvitationManagerState => { previousState.error = this.authCtx.getLoginError(); previousState.signedIn = !(!this.authCtx.getCachedUser()); return previousState; }); } public componentDidUpdate(prevProps: IInvitationManagerProps, prevState: IInvitationManagerState, prevContext: any): void { if (prevState.signedIn !== this.state.signedIn) { //this._sendInvitation(); this._getExternalUser(); } } public render(): React.ReactElement<IInvitationManagerProps> { const login: JSX.Element = this.state.signedIn ? <div /> : <button className={`${styles.button} ${styles.buttonCompound}`} onClick={() => { this.signIn(); } }><span className={styles.buttonLabel}>Sign in</span></button>; const loading: JSX.Element = this.state.loading ? <div style={{ margin: '0 auto', width: '7em' }}><div className={styles.spinner}><div className={`${styles.spinnerCircle} ${styles.spinnerNormal}`}></div><div className={styles.spinnerLabel}>Loading...</div></div></div> : <div/>; const error: JSX.Element = this.state.error ? <div><strong>Error: </strong> {this.state.error}</div> : <div/>; const invitedUserDisplayName: JSX.Element = this.state.invitation ? <div><strong>Display Name: </strong> {this.state.invitation.invitedUserDisplayName}</div> : <div/>; const invitedUserEmailAddress: JSX.Element = this.state.invitation ? <div><strong>Email Address: </strong> {this.state.invitation.invitedUserEmailAddress}</div> : <div/>; const status: JSX.Element = this.state.invitation ? <div><strong>Status: </strong> {this.state.invitation.status}</div> : <div/>; let { externalUser, selectionDetails } = this.state; return ( <div className={styles.invitationManager}> <div className={styles.container}> <div className={`ms-Grid-row ms-bgColor-white ${styles.row}`}> <div className="ms-Grid-col ms-u-lg9 ms-u-xl9"> <span className="ms-font-xl">{escape(this.props.title)}</span> <p className="ms-font-l">Invite external user</p> <TextField onChanged={ this._displayName_onChanged } label='Display' placeholder='Insert the display name of the external user' ariaLabel='Please enter text here' /> <TextField onChanged={ this._eMail_onChanged } label='Email' iconClass='ms-Icon--Mail ms-Icon' placeholder='Insert the email address of the external user' ariaLabel='Please enter text here' /> <TextField onChanged={ this._redirectURL_onChanged } label='Redirect URL' placeholder='Where do you want redirect the external user' ariaLabel='Please enter text here' /> <Toggle defaultChecked={ this.state.sendInvitationMessage } label='Send invitation message' onText='On' offText='Off' onChanged={ this._sendInvitationMessage_onChanged } /> <div> {loading} {error} {invitedUserDisplayName} {invitedUserEmailAddress} {status} </div> <DefaultButton data-automation-id='test' description='I am a description' onClick={() => { this._sendInvitation(); } } > <span className={styles.buttonDescription}>Invite the user</span> </DefaultButton> </div> <div className="ms-Grid-col ms-u-lg3 ms-u-xl3"> {login} </div> </div> {/*Grid of external users*/} <div className={`ms-Grid-row ms-bgColor-white ${styles.row}`}> <div className="ms-Grid-col ms-u-lg10 ms-u-xl12"> <p className="ms-font-l">External users in your organization</p> <div> <div>{ selectionDetails }</div> <TextField label='Filter by name' onChanged={ text => //this.setState({ externalUser: text ? _items.filter(i => i.name.toLowerCase().indexOf(text) > -1) : _items }) } this.setState((previousState: IInvitationManagerState, props: IInvitationManagerProps): IInvitationManagerState => { previousState.items = text ? _items.filter(i => i.name.toLowerCase().indexOf(text) > -1) : _items; return previousState; }) } /> <MarqueeSelection selection={ this._selection }> <DetailsList items={ this.state.items } columns={ _columns } setKey='set' layoutMode={ DetailsListLayoutMode.fixedColumns } selection={ this._selection } selectionPreservedOnEmptyClick={ true } onItemInvoked={ (item) => alert(`Item invoked: ${item.name}`) } /> </MarqueeSelection> </div> </div> </div> </div> </div> ); } private _getSelectionDetails(): string { let selectionCount = this._selection.getSelectedCount(); switch (selectionCount) { case 0: return 'No items selected'; case 1: return '1 item selected: ' + (this._selection.getSelection()[0] as any).name; default: return `${selectionCount} items selected`; } } @autobind private _sendInvitationMessage_onChanged(cheked: boolean): void { this.setState((previousState: IInvitationManagerState, currentProps: IInvitationManagerProps): IInvitationManagerState => { previousState.sendInvitationMessage = cheked; return previousState; }); } @autobind private _redirectURL_onChanged(newValue: any): void { this.setState((previousState: IInvitationManagerState, currentProps: IInvitationManagerProps): IInvitationManagerState => { previousState.redirectUrl = newValue; return previousState; }); } @autobind private _eMail_onChanged(newValue: any): void { this.setState((previousState: IInvitationManagerState, currentProps: IInvitationManagerProps): IInvitationManagerState => { previousState.emailAddress = newValue; return previousState; }); } @autobind private _displayName_onChanged(newValue: any): void { this.setState((previousState: IInvitationManagerState, currentProps: IInvitationManagerProps): IInvitationManagerState => { previousState.displayName = newValue; return previousState; }); } private _sendInvitation = (ev?:React.MouseEvent<HTMLButtonElement>) => { // Prevent postback ev ? ev.preventDefault() : null; if (this.state.signedIn !== false) { this.sendInvitation(); } } private _getExternalUser = () => { if (this.state.signedIn !== false) { this.getExternalUser(); } } public signIn(): void { this.authCtx.login(); } private getExternalUser(): void { this.setState((previousState: IInvitationManagerState, props: IInvitationManagerProps): IInvitationManagerState => { previousState.loading = true; return previousState; }); this.getGraphAccessToken() .then((accessToken: string): Promise<IExternalUser> => { console.log(accessToken); return InvitationManager.getExternalUser(accessToken, this.props.httpClient, this.state); }) .then((external: IExternalUser): void => { this.setState((prevState: IInvitationManagerState, props: IInvitationManagerProps): IInvitationManagerState => { prevState.loading = false; prevState.externalUser = external; // Populate with external users items. if (external !== null) { for (let i = 0; i < external.value.length; i++) { _items.push({ key: i, name: external.value[i].displayName, value: external.value[i].mail, }); } } prevState.items = _items; return prevState; }); }, (error: any): void => { this.setState((prevState: IInvitationManagerState, props: IInvitationManagerProps): IInvitationManagerState => { prevState.loading = false; prevState.error = error; return prevState; }); }); } private sendInvitation(): void { this.setState((previousState: IInvitationManagerState, props: IInvitationManagerProps): IInvitationManagerState => { previousState.loading = true; return previousState; }); this.getGraphAccessToken() .then((accessToken: string): Promise<IInvitation> => { console.log(accessToken); return InvitationManager.postInvitation(accessToken, this.props.httpClient, this.state); }) .then((invitation: IInvitation): void => { this.setState((prevState: IInvitationManagerState, props: IInvitationManagerProps): IInvitationManagerState => { prevState.loading = false; prevState.invitation = invitation; return prevState; }); }, (error: any): void => { this.setState((prevState: IInvitationManagerState, props: IInvitationManagerProps): IInvitationManagerState => { prevState.loading = false; prevState.error = error; return prevState; }); }); } private getGraphAccessToken(): Promise<string> { return new Promise<string>((resolve: (accessToken: string) => void, reject: (error: any) => void): void => { const graphResource: string = 'https://graph.microsoft.com'; const accessToken: string = this.authCtx.getCachedToken(graphResource); if (accessToken) { console.log('ACCESS TOKEN: ' + accessToken); resolve(accessToken); return; } if (this.authCtx.loginInProgress()) { reject('Login already in progress'); return; } this.authCtx.acquireToken(graphResource, (error: string, token: string) => { if (error) { reject(error); return; } if (token) { resolve(token); } else { reject('Couldn\'t retrieve access token'); } }); }); } private static getExternalUser(accessToken: string, httpClient: HttpClient, previousState: IInvitationManagerState): Promise<IExternalUser> { const URL = `https://graph.microsoft.com/v1.0/users?$filter=userType eq 'Guest'`; const requestHeaders: Headers = new Headers(); requestHeaders.append('Accept', 'application/json'); //For an OAuth token requestHeaders.append('Authorization', 'Bearer ' + accessToken); const httpClientOptions: IHttpClientOptions = { headers: requestHeaders }; return new Promise<IExternalUser>((resolve: (external: IExternalUser) => void, reject: (error: any) => void): void => { httpClient.get(URL, HttpClient.configurations.v1, httpClientOptions) .then((response: HttpClientResponse): Promise<IExternalUser> => { return response.json(); }) .then((externalResponse: IExternalUser): void => { resolve(externalResponse); }, (error: any): void => { reject(error); }); }); } private static postInvitation(accessToken: string, httpClient: HttpClient, previousState: IInvitationManagerState): Promise<IInvitation> { const postURL = `https://graph.microsoft.com/v1.0/invitations`; const body: string = JSON.stringify({ 'invitedUserDisplayName': previousState.displayName, 'invitedUserEmailAddress': previousState.emailAddress, 'inviteRedirectUrl': previousState.redirectUrl, "sendInvitationMessage": previousState.sendInvitationMessage, }); const requestHeaders: Headers = new Headers(); requestHeaders.append('Content-type', 'application/json'); requestHeaders.append('Cache-Control', 'no-cache'); //For an OAuth token requestHeaders.append('Authorization', 'Bearer ' + accessToken); //For Basic authentication requestHeaders.append('Authorization', 'Basic <CREDENTIALS>'); const httpClientOptions: IHttpClientOptions = { body: body, headers: requestHeaders }; return new Promise<IInvitation>((resolve: (invitation: IInvitation) => void, reject: (error: any) => void): void => { httpClient.post(postURL, HttpClient.configurations.v1, httpClientOptions) .then((response: HttpClientResponse): Promise<IInvitation> => { return response.json(); }) .then((invitationResponse: IInvitation ): void => { const invitation: IInvitation = { id: '', inviteRedeemUrl: '', invitedUserDisplayName: '', invitedUserEmailAddress: '', sendInvitationMessage: '', inviteRedirectUrl: '', status: '' }; invitation.id = invitationResponse.id; invitation.invitedUserDisplayName = invitationResponse.invitedUserDisplayName; invitation.invitedUserEmailAddress = invitationResponse.invitedUserEmailAddress; invitation.inviteRedeemUrl = invitationResponse.inviteRedeemUrl; invitation.inviteRedirectUrl = invitationResponse.inviteRedirectUrl; invitation.sendInvitationMessage = invitationResponse.sendInvitationMessage; invitation.status = invitationResponse.status; resolve(invitation); }, (error: any): void => { reject(error); }); }); } }
the_stack
import { UnaryOperator, BinaryOperator, NumberLiteral, NullLiteral, StringLiteral, BooleanLiteral, Literal, Identifier, MemberExpression, UnaryExpression, UpdateExpression, BinaryExpression, Property, ObjectExpression, ArrayExpression, SpreadElement, CallExpression, Expression, NumberParameter, NullParameter, StringParameter, BooleanParameter, ArrayParameter, ObjectParameter, Parameter, FromClause, JoinIntoClause, ConstClause, JoinClause, WhereClause, OrderByClauseArgument, OrderByClause, GroupIntoClause, GroupByClause, SelectClause, QueryExpression, Then, Clause } from './syntax' // --------------------------------------------------------------------------- // Operation Types // --------------------------------------------------------------------------- type Select = (item: any) => any type Comparer = (a: any, b: any) => number type Directive = [Comparer, Index, Select] type Key = any type Item = any type Index = number // --------------------------------------------------------------------------- // Group // --------------------------------------------------------------------------- /** * Utility function that is used by join, groupby and orderby to partition * a sequence of tuples. This function only operates on one of the tuples * contained within a sequence. An index is required that is used to select * the appropriate tuple, and a select function that picks the key for the * indexed tuple. This function returns a Map<TKey, TItem[]> where TItem * is the indexed tuple value. * * @example * * const iterator = [ * [{ a: 10, b: 20 }, {c: 60, d: 40 }], // 0 * [{ a: 10, b: 20 }, {c: 50, d: 40 }], // 1 * [{ a: 20, b: 20 }, {c: 40, d: 40 }], // 2 * [{ a: 20, b: 20 }, {c: 30, d: 40 }], // 3 * [{ a: 30, b: 20 }, {c: 20, d: 40 }], // 4 * [{ a: 30, b: 20 }, {c: 10, d: 40 }] // 5 * ] * const results = group(iterator, 0, item => item.a) * for(const [key, items] of [...results]) { * console.log('key:', key) * for(const item of items) { * const { a, b } = item[0] * const { c, d } = item[1] * console.log(' item:', a, b) * } * } * key: 10 * item: 10 20 * item: 10 20 * key: 20 * item: 20 20 * item: 20 20 * key: 30 * item: 30 20 * item: 30 20 */ export function group(iterator: any[][], index: number, select: Select): Map<Key, Item[]> { const groups = new Map<Key, Item[]>() for (const value of iterator) { const key = select(value[index]) if (!groups.has(key)) { groups.set(key, []) } groups.get(key)!.push(value) } return groups } // --------------------------------------------------------------------------- // GroupBy // --------------------------------------------------------------------------- export class Grouping<TKey, TValue> { constructor(public key: TKey, public values: TValue[]) { } public *[Symbol.iterator]() { for (const value of this.values) { yield value } } } /** Returns an iterator of Grouping. */ export function* groupby(iterator: any[][], index: number, select: Select) { const grouped = group(iterator, index, select) for (const [key, items] of grouped) { const values = [] as any[] for (const item of items) { values.push(item[index]); } yield new Grouping(key, values) } } /** Returns an iterator of single Grouping. Used for continuation. */ export function* groupinto(iterator: any[][], index: number, select: Select) { for (const grouped of groupby(iterator, index, select)) { yield [grouped] } } // --------------------------------------------------------------------------- // Ordering // --------------------------------------------------------------------------- export function ascending(a: any, b: any) { return (a < b) ? -1 : (a > b) ? 1 : 0 } export function descending(a: any, b: any) { return (a < b) ? 1 : (a > b) ? -1 : 0 } /** * Recursively sorts the given iterable with the suppled ordering directives. This * function will recursive group sort based on the keys read from the directive * select and continue to do so until the directive stack has been fully shifted. * * @example * * const iterator = [ * [{ a: 10, b: 20 }, {c: 60, d: 40 }], // 0 * [{ a: 10, b: 20 }, {c: 50, d: 40 }], // 1 * [{ a: 20, b: 20 }, {c: 40, d: 40 }], // 2 * [{ a: 20, b: 20 }, {c: 30, d: 40 }], // 3 * [{ a: 30, b: 20 }, {c: 20, d: 40 }], // 4 * [{ a: 30, b: 20 }, {c: 10, d: 40 }] // 5 * ] * * const results = ordering(iterator, [ * [ascending, 0, item => item.a], * [descending, 1, item => item.c], * ]) * * console.log([...results]) * * // results * [ * [ { a: 10, b: 20 }, { c: 60, d: 40 } ], * [ { a: 10, b: 20 }, { c: 50, d: 40 } ], * [ { a: 20, b: 20 }, { c: 40, d: 40 } ], * [ { a: 20, b: 20 }, { c: 30, d: 40 } ], * [ { a: 30, b: 20 }, { c: 20, d: 40 } ], * [ { a: 30, b: 20 }, { c: 10, d: 40 } ] * ] */ export function* orderby(iterable: any[][], directives: Directive[]): IterableIterator<any[][]> { if (directives.length === 0) { return yield* iterable } const [direction, index, select] = directives.shift()! const groups = group(iterable, index, select) const keys = [...groups.keys()].sort(direction) for (const key of keys) { const iterable = groups.get(key)! yield* orderby(iterable, [...directives]) } } // --------------------------------------------------------------------------- // GeneratorState // --------------------------------------------------------------------------- export class GeneratorState { constructor( public prev: string, public identifiers: string[] ) { } } export class JavaScriptGenerator { private parameter(node: Parameter): string { return `$parameters[${node.index}]` } // #region Expressions private identifier(node: Identifier): string { return node.name } private literal(node: Literal) { switch (node.kind) { case 'string': return node.raw case 'boolean': return node.raw case 'null': return node.raw case 'number': return node.raw } } private property(node: Property): string { return `${node.key}: ${this.visit(node.value)}` } private object_expression(node: ObjectExpression): string { const properties = node.properties.map(property => this.visit(property)).join(', ') return ['{', properties, '}'].join('') } private array_expression(node: ArrayExpression): string { const elements = node.elements.map(element => this.visit(element)).join(', ') return ['[', elements, ']'].join('') } private unary_expression(node: UnaryExpression): string { if (node.prefix) { return [node.operator, this.visit(node.argument)].join('') } else { return [this.visit(node.argument), node.operator].join('') } } private update_expression(node: UpdateExpression): string { if (node.prefix) { return [node.operator, this.visit(node.argument)].join('') } else { return [this.visit(node.argument), node.operator].join('') } } private binary_expression(node: BinaryExpression): string { return ['(', this.visit(node.left), node.operator, this.visit(node.right), ')'].join(' ') } private spread_element(node: SpreadElement): string { return ['...', this.visit(node.argument)].join('') } private call_expression(node: CallExpression): string { const args = node.arguments.map(argument => this.visit(argument)).join(', ') return [this.visit(node.callee), '(', args, ')'].join('') } private member_expression(node: MemberExpression): string { if (node.computed) { return [this.visit(node.object), '[', this.visit(node.property), ']'].join('') } else { return [this.visit(node.object), '.', this.visit(node.property)].join('') } } private visit(node: Expression | SpreadElement | Property): string { switch (node.type) { case 'ArrayExpression': return this.array_expression(node) case 'BinaryExpression': return this.binary_expression(node) case 'CallExpression': return this.call_expression(node) case 'Parameter': return this.parameter(node) case 'Identifier': return this.identifier(node) case 'Literal': return this.literal(node) case 'MemberExpression': return this.member_expression(node) case 'ObjectExpression': return this.object_expression(node) case 'Property': return this.property(node) case 'QueryExpression': return this.query_expression(node) case 'SpreadElement': return this.spread_element(node) case 'UnaryExpression': return this.unary_expression(node) case 'UpdateExpression': return this.update_expression(node) default: throw Error('unreachable') } } // #endregion // #region Clauses private clause_from(state: GeneratorState, clause: FromClause): string { const identifier = clause.identifier.name const iterable = this.visit(clause.iterable) const value = clause.identifier.name const buffer = [] buffer.push('const iterator = function* () {') buffer.push(state.prev) buffer.push('for(const prev of iterator()) {') buffer.push(`for(const ${identifier} of ${iterable}) {`) buffer.push(`yield [...prev, ${value}];`) buffer.push('}') buffer.push('}') buffer.push('}') const next = new GeneratorState(buffer.join('\n'), [...state.identifiers, clause.identifier.name]) return this.visit_clause(next, clause.then) } private clause_join_into(state: GeneratorState, clause: JoinIntoClause): string { const buffer = [] const left = this.visit(clause.left) const right = this.visit(clause.right) const base = this.basename(clause.left) const index = state.identifiers.indexOf(base) const identifier = clause.identifier.name const iterable = this.visit(clause.iterable) const value = clause.identifier.name buffer.push('const iterator = function* () {') buffer.push(state.prev) buffer.push('for(const prev of iterator()) {') buffer.push('const buffer = [];') buffer.push(`for(const ${identifier} of ${iterable}) {`) buffer.push(`const ${base} = prev[${index}]`) buffer.push(`if(${left} === ${right}) {`) buffer.push(`buffer.push(${value});`) buffer.push('}') buffer.push('}') buffer.push('yield [...prev, buffer]') buffer.push('}') buffer.push('}') const next = new GeneratorState(buffer.join('\n'), [...state.identifiers, clause.into.name]) return this.visit_clause(next, clause.then) } private clause_join(state: GeneratorState, clause: JoinClause): string { const buffer = [] const left = this.visit(clause.left) const right = this.visit(clause.right) const base = this.basename(clause.left) const index = state.identifiers.indexOf(base) const identifier = clause.identifier.name const iterable = this.visit(clause.iterable) const value = clause.identifier.name buffer.push('const iterator = function* () {') buffer.push(state.prev) buffer.push('for(const prev of iterator()) {') buffer.push(`for(const ${identifier} of ${iterable}) {`) buffer.push(`const ${base} = prev[${index}]`) buffer.push(`if(${left} === ${right}) {`) buffer.push(`yield [...prev, ${value}];`) buffer.push('}') buffer.push('}') buffer.push('}') buffer.push('}') const next = new GeneratorState(buffer.join('\n'), [...state.identifiers, clause.identifier.name]) return this.visit_clause(next, clause.then) } private clause_const(state: GeneratorState, clause: ConstClause): string { const identifiers = ['[', state.identifiers.join(', '), ']'].join('') const identifier = clause.identifier.name const expression = this.visit(clause.expression) const buffer = [] buffer.push('const iterator = function* () {') buffer.push(state.prev) buffer.push(`for(const ${identifiers} of iterator()) {`) buffer.push(`yield [...${identifiers}, ${expression}];`) buffer.push('}') buffer.push('}') const next = new GeneratorState(buffer.join('\n'), [...state.identifiers, identifier]) return this.visit_clause(next, clause.then) } private clause_where(state: GeneratorState, clause: WhereClause): string { const identifiers = ['[', state.identifiers.join(', '), ']'].join('') const expression = this.visit(clause.expression) const buffer = [] buffer.push('const iterator = function* () {') buffer.push(state.prev) buffer.push(`for(const ${identifiers} of iterator()) {`) buffer.push(`if(${expression}) {`) buffer.push(`yield ${identifiers};`) buffer.push('}') buffer.push('}') buffer.push('}') const next = new GeneratorState(buffer.join('\n'), [...state.identifiers]) return this.visit_clause(next, clause.then) } private clause_orderby(state: GeneratorState, clause: OrderByClause): string { const directions = clause.arguments.map(argument => argument.direction) const basenames = clause.arguments.map(argument => this.basename(argument.identifier)) const indices = clause.arguments.map((_, index) => state.identifiers.indexOf(basenames[index])) const selectors = clause.arguments.map(argument => this.visit(argument.identifier)) const directives = clause.arguments.map((_, index) => `[$func.${directions[index]}, ${indices[index]}, ${basenames[index]} => ${selectors[index]}]`).join(',\n') const buffer = [] buffer.push('const iterator = function* () {') buffer.push(state.prev) buffer.push('yield * $func.orderby([...iterator()], [') buffer.push(directives) buffer.push('])') buffer.push('}') const next = new GeneratorState(buffer.join('\n'), [...state.identifiers]) return this.visit_clause(next, clause.then) } private clause_group_into(state: GeneratorState, clause: GroupIntoClause): string { const selector = this.visit(clause.by) const basename = this.basename(clause.identifier) const index = state.identifiers.indexOf(basename) const buffer = [] buffer.push('const iterator = function* () {') buffer.push(state.prev) buffer.push(`yield * $func.groupinto(iterator(), ${index}, ${basename} => ${selector});`) buffer.push('}') const next = new GeneratorState(buffer.join('\n'), [clause.into.name]) return this.visit_clause(next, clause.then) } private clause_group_by(state: GeneratorState, clause: GroupByClause): string { const selector = this.visit(clause.by) const basename = this.basename(clause.identifier) const index = state.identifiers.indexOf(basename) const buffer = [] buffer.push('const iterator = function* () {') buffer.push(state.prev) buffer.push(`yield * $func.groupby(iterator(), ${index}, ${basename} => ${selector});`) buffer.push('}') return buffer.join('\n') } private clause_select(state: GeneratorState, clause: SelectClause): string { const identifiers = ['[', state.identifiers.join(', '), ']'].join('') const expression = this.visit(clause.expression) const buffer = [] buffer.push('const iterator = function* () {') buffer.push(state.prev) buffer.push(`for(const ${identifiers} of iterator()) {`) buffer.push(`yield ${expression};`) buffer.push('}') buffer.push('}') return buffer.join('\n') } // #endregion /** Builds an IIFE closure for the given expression */ private query_expression(node: QueryExpression): string { const initial_iterator = [] initial_iterator.push('const iterator = function* () {') initial_iterator.push(' yield [];') initial_iterator.push('}') const state = new GeneratorState(initial_iterator.join('\n'), []) const result = this.visit_clause(state, node.from) const buffer = [] buffer.push('(function() {') buffer.push(result) buffer.push('return iterator();') buffer.push('})()') return buffer.join('\n') } private visit_clause(state: GeneratorState, clause: Clause): string { switch (clause.type) { case 'FromClause': return this.clause_from(state, clause) case 'JoinIntoClause': return this.clause_join_into(state, clause) case 'JoinClause': return this.clause_join(state, clause) case 'ConstClause': return this.clause_const(state, clause) case 'WhereClause': return this.clause_where(state, clause) case 'OrderByClause': return this.clause_orderby(state, clause) case 'GroupIntoClause': return this.clause_group_into(state, clause) case 'GroupByClause': return this.clause_group_by(state, clause) case 'SelectClause': return this.clause_select(state, clause) } } /** For the given node, resolve the top most basename for the node. */ private basename(node: Identifier | MemberExpression | CallExpression): string { switch (node.type) { case 'MemberExpression': return this.basename(node.object) case 'CallExpression': return this.basename(node.callee) case 'Identifier': return node.name } } public generate(node: QueryExpression): [Function, string] { const content = `return ${this.visit(node)}` const func = new Function( '$func', '$parameters', content) return [func, content] } } const generator = new JavaScriptGenerator() export function generate(node: QueryExpression) { const [func, code] = generator.generate(node) return (parameters: any[]) => func({ groupby, groupinto, orderby, ascending, descending, }, parameters) }
the_stack
import { Injectable, Logger } from '@nestjs/common'; import { Employee, EmployeeJobPostsDocument, EmployeeJobPostsQuery, EmployeeQuery, UpdateEmployeeJobPost, UpworkJobsSearchCriterion } from './sdk/gauzy-ai-sdk'; import { TypedDocumentNode as DocumentNode } from '@graphql-typed-document-node/core'; import fetch from 'cross-fetch'; import { ApolloClient, ApolloQueryResult, NormalizedCacheObject, HttpLink, InMemoryCache, DefaultOptions, NetworkStatus, gql } from '@apollo/client/core'; import { IEmployeeUpworkJobsSearchCriterion, IEmployee, IVisibilityJobPostInput, IApplyJobPostInput, IUpdateEmployeeJobPostAppliedResult, IGetEmployeeJobPostInput, IPagination, IEmployeeJobPost, IJobPost, IGetEmployeeJobPostFilters, JobPostStatusEnum, JobPostTypeEnum, IEmployeeJobsStatistics } from '@gauzy/contracts'; @Injectable() export class GauzyAIService { private readonly _logger = new Logger(GauzyAIService.name); private _client: ApolloClient<NormalizedCacheObject>; // For now, we disable Apollo client caching for all GraphQL queries and mutations private readonly defaultOptions: DefaultOptions = { watchQuery: { fetchPolicy: 'no-cache', errorPolicy: 'ignore' }, query: { fetchPolicy: 'no-cache', errorPolicy: 'all' }, mutate: { fetchPolicy: 'no-cache', errorPolicy: 'all' } }; private gauzyAIGraphQLEndpoint: string; private initClient() { this._client = new ApolloClient({ typeDefs: EmployeeJobPostsDocument, link: new HttpLink({ // TODO: use endpoint from .env. We probably should inject settings into constructor for this. uri: this.gauzyAIGraphQLEndpoint, fetch }), cache: new InMemoryCache(), defaultOptions: this.defaultOptions }); } constructor() { try { // TODO: read from constructor injected parameter (e.g. config service) this.gauzyAIGraphQLEndpoint = process.env.GAUZY_AI_GRAPHQL_ENDPOINT; if (this.gauzyAIGraphQLEndpoint) { this._logger.log( 'Gauzy AI Endpoint configured in the environment' ); this.initClient(); const testConnectionQuery = async () => { try { const employeesQuery: DocumentNode<EmployeeQuery> = gql` query employee { employees { edges { node { id } } totalCount } } `; const employeesQueryResult: ApolloQueryResult<EmployeeQuery> = await this._client.query<EmployeeQuery>( { query: employeesQuery } ); if ( employeesQueryResult.networkStatus === NetworkStatus.error ) { this._client = null; } } catch (err) { this._logger.error(err); this._client = null; } }; testConnectionQuery(); } else { this._logger.warn( 'Gauzy AI Endpoint not configured in the environment' ); this._client = null; } } catch (err) { this._logger.error(err); this._client = null; } } /** * Get statistic from Gauzy AI about how many jobs are available for given employee * and to how many of jobs employee already applied and more statistic in the future. */ public async getEmployeesStatistics(): Promise<IEmployeeJobsStatistics[]> { return []; } /** * Updates in Gauzy AI if given Employee looking for a jobs or not. * If not looking, Gauzy AI will NOT return jobs for such employee and will NOT crawl sources for jobs for such employee * @param employeeId * @param isJobSearchActive */ public async updateEmployeeStatus( employeeId: string, isJobSearchActive: boolean ): Promise<boolean> { if (this._client == null) { return false; } // First we need to get employee id because we have only externalId const gauzyAIEmployeeId = await this.getEmployeeGauzyAIId(employeeId); console.log( `updateVisibility called. EmployeeId: ${employeeId}. Gauzy AI EmployeeId: ${gauzyAIEmployeeId}` ); return true; } /** * Updates job visibility * @param hide Should job be hidden or visible. This will set isActive field to false in Gauzy AI * @param employeeId If employeeId set, job will be set not active only for that specific employee (using EmployeeJobPost record update in Gauzy AI) * If employeeId is not set, job will be set not active for all employees (using JobPost record update in Gauzy AI) * @param providerCode e.g. 'upwork' * @param providerJobId Unique job id in the provider, e.g. in Upwork. If this value is not set, it will update ALL jobs for given provider */ public async updateVisibility( input: IVisibilityJobPostInput ): Promise<boolean> { if (this._client == null) { return false; } // If it's for specific employee and specific job if (input.employeeId && input.providerCode && input.providerJobId) { // First we need to get employee id because we have only externalId const employeeId = await this.getEmployeeGauzyAIId( input.employeeId ); console.log(`updateVisibility called. EmployeeId: ${employeeId}`); // Next we need to get a job using providerCode and providerJobId const jobPostId = await this.getJobPostId( input.providerCode, input.providerJobId ); console.log(`updateVisibility called. jobPostId: ${jobPostId}`); // Next, we need to find `public employee job post` table record in Gauzy AI to get id of record. // We can find by employeeId and jobPostId const employeeJobPostId = await this.getEmployeeJobPostId( employeeId, jobPostId ); console.log( `updateVisibility called. employeeJobPostId: ${employeeJobPostId}` ); if (employeeId && jobPostId && employeeJobPostId) { const update: UpdateEmployeeJobPost = { employeeId: employeeId, jobPostId: jobPostId, isActive: !input.hide, isArchived: input.hide }; const updateEmployeeJobPostMutation: DocumentNode<any> = gql` mutation updateOneEmployeeJobPost( $input: UpdateOneEmployeeJobPostInput! ) { updateOneEmployeeJobPost(input: $input) { employeeId jobPostId isActive isArchived isApplied appliedDate } } `; await this._client.mutate({ mutation: updateEmployeeJobPostMutation, variables: { input: { id: employeeJobPostId, update: update } } }); return true; } } else { // OK, so it's for all jobs for all employees or for all jobs on specific employee // TODO: implement } return false; } /** * Updates if Employee Applied to a job * @param applied This will set isApplied and appliedDate fields in Gauzy AI * @param employeeId Employee who applied for a job * @param providerCode e.g. 'upwork' * @p aram providerJobId Unique job id in the provider, e.g. in Upwork */ public async updateApplied( input: IApplyJobPostInput ): Promise<IUpdateEmployeeJobPostAppliedResult> { if (this._client == null) { return { isRedirectRequired: true }; } // First we need to get employee id because we have only externalId const employeeId = await this.getEmployeeGauzyAIId(input.employeeId); console.log(`updateApplied called. EmployeeId: ${employeeId}`); // Next we need to get a job using providerCode and providerJobId const jobPostId = await this.getJobPostId( input.providerCode, input.providerJobId ); console.log(`updateApplied called. jobPostId: ${jobPostId}`); // Next, we need to find `public employee job post` table record in Gauzy AI to get id of record. // We can find by employeeId and jobPostId const employeeJobPostId = await this.getEmployeeJobPostId( employeeId, jobPostId ); console.log( `updateApplied called. employeeJobPostId: ${employeeJobPostId}` ); if (employeeId && jobPostId && employeeJobPostId) { const update: UpdateEmployeeJobPost = { employeeId: employeeId, jobPostId: jobPostId, isApplied: input.applied }; const updateEmployeeJobPostMutation: DocumentNode<any> = gql` mutation updateOneEmployeeJobPost( $input: UpdateOneEmployeeJobPostInput! ) { updateOneEmployeeJobPost(input: $input) { employeeId jobPostId isActive isArchived isApplied appliedDate } } `; await this._client.mutate({ mutation: updateEmployeeJobPostMutation, variables: { input: { id: employeeJobPostId, update: update } } }); } // TODO: here we need to check what returned from Gauzy AI // Because for some providers (e.g. Upwork), redirect to apply manually required // But for other providers, apply can work inside Gauzy AI automatically return { isRedirectRequired: true }; } // We call this on each "Save" operation for matching for employee. // Both when Preset saved for given employee and when any criteria saved for given employee (new criteria or changes in criteria) // You should pass `employee` entity for which anything on Matching page was changes // IMPORTANT: You should ALWAYS pass ALL criteria defined for given employee on Matching page, not only new or changed! // Best way to call this method, is to reload from Gauzy DB all criteria for given employee before call this method. // We DO NOT USE DATA YOU PASS FROM UI! // INSTEAD, We CALL THIS METHOD FROM YOUR CQRS COMMAND HANDLERS when you detect that anything related to matching changes // But as explained above, we must reload criteria from DB, not use anything you have in the local variables // (because it might not be full data, but this method requires all data to be synced to Gauzy AI, even if such data was previously already synced) // How this method will work internally: // - it will call sync for employee first and if no such employee exists in Gauzy AI, it will create new. If exists, it will update employee properties, e.g. lastName // - next, it will remove all criteria for employee in Gauzy AI and create new records again for criterions. // I.e. no update will be done, it will be full replacement // The reason it's acceptable is because such data changes rarely for given employee, so it's totally fine to recreate it // NOTE: will need to call this method from multiple different CQRS command handlers! public async syncGauzyEmployeeJobSearchCriteria( employee: IEmployee, criteria: IEmployeeUpworkJobsSearchCriterion[] ): Promise<boolean> { if (this._client == null) { return false; } console.log( `syncGauzyEmployeeJobSearchCriteria called. Criteria: ${JSON.stringify( criteria )}. Employee: ${JSON.stringify(employee)}` ); try { const gauzyAIEmployee: Employee = await this.syncEmployee({ externalEmployeeId: employee.id, isActive: employee.isActive, isArchived: false, upworkJobSearchCriteria: undefined, upworkJobSearchCriteriaAggregate: undefined, firstName: employee.user.firstName, lastName: employee.user.lastName }); console.log(`Synced Employee ${JSON.stringify(gauzyAIEmployee)}`); // let's delete all criteria for Employee const deleteAllCriteriaMutation: DocumentNode<any> = gql` mutation deleteManyUpworkJobsSearchCriteria( $input: DeleteManyUpworkJobsSearchCriteriaInput! ) { deleteManyUpworkJobsSearchCriteria(input: $input) { deletedCount } } `; const deleteMutationResult = await this._client.mutate({ mutation: deleteAllCriteriaMutation, variables: { input: { filter: { isActive: { is: true }, employeeId: { eq: gauzyAIEmployee.id } } } } }); console.log( `Delete Existed Criterions count: ${JSON.stringify( deleteMutationResult.data.deleteManyUpworkJobsSearchCriteria .deletedCount )}` ); // now let's create new criteria in Gauzy AI based on Gauzy criterions data if (criteria && criteria.length > 0) { const gauzyAICriteria: UpworkJobsSearchCriterion[] = []; criteria.forEach( (criterion: IEmployeeUpworkJobsSearchCriterion) => { gauzyAICriteria.push({ employee: undefined, employeeId: gauzyAIEmployee.id, isActive: true, isArchived: false, jobType: 'hourly', // TODO: criterion.jobType keyword: criterion.keyword, category: criterion.category?.name, categoryId: criterion.categoryId, occupation: criterion.occupation?.name, occupationId: criterion.occupationId }); } ); const createCriteriaMutation: DocumentNode<any> = gql` mutation createManyUpworkJobsSearchCriteria( $input: CreateManyUpworkJobsSearchCriteriaInput! ) { createManyUpworkJobsSearchCriteria(input: $input) { id } } `; const createNewCriteriaResult = await this._client.mutate({ mutation: createCriteriaMutation, variables: { input: { upworkJobsSearchCriteria: gauzyAICriteria } } }); console.log( `Create New Criteria result: ${JSON.stringify( createNewCriteriaResult.data .createManyUpworkJobsSearchCriteria )}` ); } return true; } catch (err) { this._logger.error(err); return false; } } /** * * Creates employees in Gauzy AI if not exists yet. If exists, updates fields, including externalEmployeeId * How it works: * - search done externalEmployeeId field first in Gauzy AI to be equal to Gauzy employee Id. * - if no record found in Gauzy AI, it search Gauzy AI employees records by employee name * - if no record found in Gauzy AI, it creates new employee in Gauzy AI * * @param employees */ public async syncEmployees(employees: IEmployee[]): Promise<boolean> { if (this._client == null) { return false; } await Promise.all( employees.map(async (employee) => { try { const gauzyAIEmployee: Employee = await this.syncEmployee({ externalEmployeeId: employee.id, isActive: employee.isActive, isArchived: false, upworkJobSearchCriteria: undefined, upworkJobSearchCriteriaAggregate: undefined, firstName: employee.user.firstName, lastName: employee.user.lastName }); console.log( `Synced Employee ${JSON.stringify(gauzyAIEmployee)}` ); } catch (err) { this._logger.error(err); } }) ); return true; } private async getEmployeeJobPostId( employeeId: string, jobPostId: string ): Promise<string> { const employeeJobPostsQuery = gql` query employeeJobPostsByEmployeeIdJobPostId( $employeeIdFilter: String! $jobPostIdFilter: String! ) { employeeJobPosts( filter: { employeeId: { eq: $employeeIdFilter } jobPostId: { eq: $jobPostIdFilter } } ) { edges { node { id isActive isArchived } } } } `; const employeeJobPostsQueryResult = await this._client.query<any>({ query: employeeJobPostsQuery, variables: { employeeIdFilter: employeeId, jobPostIdFilter: jobPostId } }); const employeeJobPostsResponse = employeeJobPostsQueryResult.data.employeeJobPosts.edges; if (employeeJobPostsResponse && employeeJobPostsResponse.length > 0) { return employeeJobPostsResponse[0].node.id; } return null; } private async getJobPostId( providerCode: string, providerJobId: string ): Promise<string> { const jobPostsQuery = gql` query jobPosts( $providerCodeFilter: String! $providerJobIdFilter: String! ) { jobPosts( filter: { providerCode: { eq: $providerCodeFilter } providerJobId: { eq: $providerJobIdFilter } } ) { edges { node { id isActive isArchived } } } } `; const jobPostsQueryResult = await this._client.query<any>({ query: jobPostsQuery, variables: { providerCodeFilter: providerCode, providerJobIdFilter: providerJobId } }); const jobPostsResponse = jobPostsQueryResult.data.jobPosts.edges; if (jobPostsResponse && jobPostsResponse.length > 0) { return jobPostsResponse[0].node.id; } return null; } private async getEmployeeGauzyAIId( externalEmployeeId: string ): Promise<string> { const employeesQuery: DocumentNode<EmployeeQuery> = gql` query employeeByExternalEmployeeId( $externalEmployeeIdFilter: String! ) { employees( filter: { externalEmployeeId: { eq: $externalEmployeeIdFilter } } ) { edges { node { id externalEmployeeId } } totalCount } } `; const employeesQueryResult: ApolloQueryResult<EmployeeQuery> = await this._client.query<EmployeeQuery>( { query: employeesQuery, variables: { externalEmployeeIdFilter: externalEmployeeId } } ); const employeesResponse = employeesQueryResult.data.employees.edges; if (employeesResponse.length > 0) { return employeesResponse[0].node.id; } return null; } /** Sync Employee between Gauzy and Gauzy AI * Creates new Employee in Gauzy AI if it's not yet exists there yet (it try to find by externalEmployeeId field value or by name) * Update existed Gauzy AI Employee record with new data from Gauzy DB */ private async syncEmployee(employee: Employee): Promise<Employee> { // First, let's search by employee.externalEmployeeId (which is Gauzy employeeId) let employeesQuery: DocumentNode<EmployeeQuery> = gql` query employeeByExternalEmployeeId( $externalEmployeeIdFilter: String! ) { employees( filter: { externalEmployeeId: { eq: $externalEmployeeIdFilter } } ) { edges { node { id externalEmployeeId } } totalCount } } `; let employeesQueryResult: ApolloQueryResult<EmployeeQuery> = await this._client.query<EmployeeQuery>( { query: employeesQuery, variables: { externalEmployeeIdFilter: employee.externalEmployeeId } } ); let employeesResponse = employeesQueryResult.data.employees.edges; let isAlreadyCreated = employeesResponse.length > 0; console.log( `Is Employee ${employee.externalEmployeeId} already exists in Gauzy AI: ${isAlreadyCreated} by externalEmployeeId field` ); if (!isAlreadyCreated) { // OK, so we can't find by employee.externalEmployeeId value, let's try to search by name employeesQuery = gql` query employeeByName( $firstNameFilter: String! $lastNameFilter: String! ) { employees( filter: { firstName: { eq: $firstNameFilter } lastName: { eq: $lastNameFilter } } ) { edges { node { id firstName lastName externalEmployeeId } } totalCount } } `; employeesQueryResult = await this._client.query<EmployeeQuery>({ query: employeesQuery, variables: { firstNameFilter: employee.firstName, lastNameFilter: employee.lastName } }); employeesResponse = employeesQueryResult.data.employees.edges; isAlreadyCreated = employeesResponse.length > 0; console.log( `Is Employee ${employee.externalEmployeeId} already exists in Gauzy AI: ${isAlreadyCreated} by name fields` ); if (!isAlreadyCreated) { const createEmployeeMutation: DocumentNode<any> = gql` mutation createOneEmployee( $input: CreateOneEmployeeInput! ) { createOneEmployee(input: $input) { id externalEmployeeId firstName lastName } } `; const newEmployee = await this._client.mutate({ mutation: createEmployeeMutation, variables: { input: { employee } } }); return newEmployee.data.createOneEmployee; } } // update record of employee const id = employeesResponse[0].node.id; const updateEmployeeMutation: DocumentNode<any> = gql` mutation updateOneEmployee($input: UpdateOneEmployeeInput!) { updateOneEmployee(input: $input) { externalEmployeeId isActive isArchived firstName lastName } } `; await this._client.mutate({ mutation: updateEmployeeMutation, variables: { input: { id: id, update: employee } } }); return <Employee>employeesResponse[0].node; } /** * Get Jobs available for registered employees */ public async getEmployeesJobPosts( data: IGetEmployeeJobPostInput ): Promise<IPagination<IEmployeeJobPost>> { if (this._client == null) { return null; } console.log(`getEmployeesJobPosts. Data ${JSON.stringify(data)}`); const filters: IGetEmployeeJobPostFilters = data.filters ? JSON.parse(<any>data.filters) : undefined; console.log(`getEmployeesJobPosts. Filters ${JSON.stringify(filters)}`); const employeeIdFilter = filters && filters.employeeIds && filters.employeeIds.length > 0 ? filters.employeeIds[0] : undefined; try { // TODO: use Query saved in SDK, not hard-code it here. Note: we may add much more fields to that query as we need more info! const employeesQuery: DocumentNode<EmployeeJobPostsQuery> = gql` query employeeJobPosts( $after: ConnectionCursor! $first: Int! $filter: EmployeeJobPostFilter! $sorting: [EmployeeJobPostSort!] ) { employeeJobPosts( paging: { after: $after, first: $first } filter: $filter sorting: $sorting ) { totalCount pageInfo { hasNextPage hasPreviousPage startCursor endCursor } edges { node { id isApplied appliedDate createdAt updatedAt isActive isArchived employee { id externalEmployeeId } providerCode providerJobId jobDateCreated jobStatus jobType jobPost { id providerCode providerJobId title description jobDateCreated jobStatus jobType url budget duration workload skills category subcategory country clientFeedback clientReviewsCount clientJobsPosted clientPastHires clientPaymentVerificationStatus } } } } } `; const jobResponses: IEmployeeJobPost[] = []; let isContinue: boolean; let after = ''; const filter = { isActive: { is: true }, isArchived: { is: false }, employeeId: undefined }; if (employeeIdFilter) { const employeeId = await this.getEmployeeGauzyAIId( employeeIdFilter ); filter.employeeId = { eq: employeeId }; } console.log(`Applying filter: ${JSON.stringify(filter)}`); const graphQLPageSize = 50; // e.g. if it's page 7 and limit is 10, it mean we need to load first 70 records, i.e. do 2 trips to server because each trip get 50 records const loadCounts = Math.ceil( (data.page * data.limit) / graphQLPageSize ); console.log(`Round trips to Gauzy API: ${loadCounts}`); let currentCount = 1; let totalCount; do { const result: ApolloQueryResult<EmployeeJobPostsQuery> = await this._client.query<EmployeeJobPostsQuery>( { query: employeesQuery, variables: { after: after, first: graphQLPageSize, sorting: [ { field: 'jobDateCreated', direction: 'DESC' } ], filter: filter } } ); const jobsResponse = result.data.employeeJobPosts.edges.map( (it) => { const rec = it.node; const res: IEmployeeJobPost = { employeeId: rec.employee.externalEmployeeId, employee: undefined, jobPostId: rec.jobPost.id, jobPost: <IJobPost>rec.jobPost, jobDateCreated: rec.jobDateCreated, providerCode: rec.providerCode, providerJobId: rec.providerJobId, jobStatus: rec.jobStatus ? JobPostStatusEnum[rec.jobStatus] : undefined, jobType: rec.jobType ? JobPostTypeEnum[rec.jobType] : undefined, isApplied: rec.isApplied, appliedDate: rec.appliedDate, isActive: rec.isActive, isArchived: rec.isArchived, createdAt: rec.createdAt, updatedAt: rec.updatedAt }; return res; } ); isContinue = result.data.employeeJobPosts.pageInfo.hasNextPage && currentCount < loadCounts; after = result.data.employeeJobPosts.pageInfo.endCursor; totalCount = result.data.employeeJobPosts.totalCount; jobResponses.push(...jobsResponse); console.log( `Found ${jobsResponse.length} job records. IsContinue: ${isContinue}. After: ${after}` ); currentCount++; } while (isContinue); // Note: possible to do additional client side filtering like below: // jobResponses = _.filter(jobResponses, (it) => it.isActive === true && it.isArchived === false); console.log( `getEmployeesJobPosts. Total Count: ${totalCount}. Page ${data.page}` ); const response: IPagination<IEmployeeJobPost> = { items: this.paginate(jobResponses, data.limit, data.page), total: totalCount }; // console.log(`Found Records: ${JSON.stringify(response)}`); return response; } catch (err) { this._logger.error(err); return null; } } private paginate(array, page_size, page_number) { // human-readable page numbers usually start with 1, so we reduce 1 in the first argument return array.slice( (page_number - 1) * page_size, page_number * page_size ); } }
the_stack
import { play, pause, previous, next, PlayerName, Track, PlaylistItem, saveToSpotifyLiked, addTracksToPlaylist, removeFromSpotifyLiked, repeatOn, repeatOff, PlayerDevice, playSpotifyMacDesktopTrack, playSpotifyTrack, playSpotifyPlaylist, TrackStatus, setShuffle, setRepeatPlaylist, setRepeatTrack, mute, unmute, getTrack, getRunningTrack, } from "cody-music"; import { window, ViewColumn, Uri, commands } from "vscode"; import { MusicCommandManager } from "./MusicCommandManager"; import { showQuickPick } from "../MenuManager"; import { playInitialization, playNextLikedSong, playPreviousLikedSongs } from "../managers/PlaylistControlManager"; import { createSpotifyIdFromUri, createUriFromTrackId, isMac, getCodyErrorMessage, isWindows, checkRegistration } from "../Util"; import { SPOTIFY_LIKED_SONGS_PLAYLIST_NAME, OK_LABEL, SPOTIFY_LIKED_SONGS_PLAYLIST_ID, RECOMMENDATION_PLAYLIST_ID, } from "../app/utils/view_constants"; import { MusicStateManager } from "./MusicStateManager"; import { SocialShareManager } from "../social/SocialShareManager"; import { tmpdir } from "os"; import { MusicPlaylistManager } from "./MusicPlaylistManager"; import { MusicCommandUtil } from "./MusicCommandUtil"; import { fetchMusicTimeMetricsMarkdownDashboard, getMusicTimeMarkdownFile, getSoftwareDir } from "../managers/FileManager"; import { connectSpotify, isPremiumUser } from "../managers/SpotifyManager"; import { getBestActiveDevice, getDeviceSet, getSelectedTrackItem, getSpotifyPlaylists, isLikedSongPlaylistSelected, isTrackRepeating, removeTracksFromRecommendations, sortPlaylists, requiresSpotifyAccess, removeTrackFromLikedPlaylist, getCachedRunningTrack, addTrackToLikedPlaylist, createPlaylistItemFromTrack, getSelectedPlaylistId, updateLikedStatusInPlaylist, } from "../managers/PlaylistDataManager"; import { connectSlackWorkspace, hasSlackWorkspaces } from "../managers/SlackManager"; const fileIt = require("file-it"); const clipboardy = require("clipboardy"); export class MusicControlManager { private currentTrackToAdd: PlaylistItem = null; private static instance: MusicControlManager; private constructor() { // } static getInstance(): MusicControlManager { if (!MusicControlManager.instance) { MusicControlManager.instance = new MusicControlManager(); } return MusicControlManager.instance; } async nextSong() { if (isLikedSongPlaylistSelected()) { await playNextLikedSong(); } else if (this.useSpotifyDesktop()) { await next(PlayerName.SpotifyDesktop); } else { await MusicCommandUtil.getInstance().runSpotifyCommand(next, [PlayerName.SpotifyWeb]); } setTimeout(() => { MusicStateManager.getInstance().fetchTrack(); }, 1000); } async previousSong() { if (isLikedSongPlaylistSelected()) { await playPreviousLikedSongs(); } else if (this.useSpotifyDesktop()) { await previous(PlayerName.SpotifyDesktop); } else { await MusicCommandUtil.getInstance().runSpotifyCommand(previous, [PlayerName.SpotifyWeb]); } setTimeout(() => { MusicStateManager.getInstance().fetchTrack(); }, 1000); } /** * {status, state, statusText, message, data.status, error} */ async playSong(tries = 0) { let result: any = null; const deviceId = getBestActiveDevice(); const controlMgr: MusicControlManager = MusicControlManager.getInstance(); if (!deviceId && tries === 1) { // initiate the device selection prompt await playInitialization(controlMgr.playSong); } else { let runningTrack = await getRunningTrack(); if (!runningTrack || !runningTrack.id) { runningTrack = await getTrack(PlayerName.SpotifyWeb); if (!runningTrack || !runningTrack.id) { runningTrack = await MusicStateManager.getInstance().updateRunningTrackToMostRecentlyPlayed(); const device = getBestActiveDevice(); const result: any = await MusicCommandUtil.getInstance().runSpotifyCommand(play, [ PlayerName.SpotifyWeb, { track_ids: [runningTrack.id], device_id: device?.id, offset: 0, }, ]); } } else { if (controlMgr.useSpotifyDesktop()) { result = await play(PlayerName.SpotifyDesktop); } else { result = await MusicCommandUtil.getInstance().runSpotifyCommand(play, [PlayerName.SpotifyWeb]); } if (result && (result.status < 300 || result === "ok")) { MusicCommandManager.syncControls(runningTrack, true, TrackStatus.Playing); } } setTimeout(() => { MusicStateManager.getInstance().fetchTrack(); }, 1000); } } async pauseSong() { let result: any = null; if (this.useSpotifyDesktop()) { result = await pause(PlayerName.SpotifyDesktop); } else { result = await MusicCommandUtil.getInstance().runSpotifyCommand(pause, [PlayerName.SpotifyWeb]); } if (result && (result.status < 300 || result === "ok")) { MusicCommandManager.syncControls(await getRunningTrack(), true, TrackStatus.Paused); } setTimeout(() => { MusicStateManager.getInstance().fetchTrack(); }, 1000); } async setShuffleOn() { const device = getBestActiveDevice(); await setShuffle(PlayerName.SpotifyWeb, true, device?.id); setTimeout(() => { MusicStateManager.getInstance().fetchTrack(); }, 1000); } async setShuffleOff() { const device = getBestActiveDevice(); await setShuffle(PlayerName.SpotifyWeb, false, device?.id); setTimeout(() => { MusicStateManager.getInstance().fetchTrack(); }, 1000); } async setRepeatTrackOn() { const device = getBestActiveDevice(); await setRepeatTrack(PlayerName.SpotifyWeb, device?.id); setTimeout(() => { MusicStateManager.getInstance().fetchTrack(); }, 1000); } async setRepeatPlaylistOn() { const device = getBestActiveDevice(); await setRepeatPlaylist(PlayerName.SpotifyWeb, device?.id); setTimeout(() => { MusicStateManager.getInstance().fetchTrack(); }, 1000); } async setRepeatOnOff(setToOn: boolean) { let result = null; if (setToOn) { result = await repeatOn(PlayerName.SpotifyWeb); } else { result = await repeatOff(PlayerName.SpotifyWeb); } setTimeout(() => { MusicStateManager.getInstance().fetchTrack(); }, 1000); } async setMuteOn() { const playerDevice: PlayerDevice = getBestActiveDevice(); await MusicCommandUtil.getInstance().runSpotifyCommand(mute, [PlayerName.SpotifyWeb, playerDevice?.id]); setTimeout(() => { MusicStateManager.getInstance().fetchTrack(); }, 1000); } async setMuteOff() { const playerDevice: PlayerDevice = getBestActiveDevice(); // setVolume(PlayerName.SpotifyWeb, 50); const result = await MusicCommandUtil.getInstance().runSpotifyCommand(unmute, [PlayerName.SpotifyWeb, playerDevice?.id]); setTimeout(() => { MusicStateManager.getInstance().fetchTrack(); }, 1000); } useSpotifyDesktop() { const { webPlayer, desktop, activeDevice, activeComputerDevice, activeWebPlayerDevice, activeDesktopPlayerDevice } = getDeviceSet(); if (isMac() && (desktop || activeDesktopPlayerDevice)) { return true; } return false; } /** * Launch and play a spotify track via the web player. * @param isTrack boolean */ async playSpotifyWebPlaylistTrack(isTrack: boolean, devices: PlayerDevice[]) { const trackRepeating = await isTrackRepeating(); // get the selected track const selectedTrack = getSelectedTrackItem(); const isLikedSongsPlaylist = selectedTrack["playlist_id"] === SPOTIFY_LIKED_SONGS_PLAYLIST_NAME; const playlistId = isLikedSongsPlaylist ? "" : selectedTrack["playlist_id"]; if (isLikedSongsPlaylist) { await this.playSpotifyByTrack(selectedTrack, devices); } else if (isTrack) { await this.playSpotifyByTrackAndPlaylist(playlistId, selectedTrack.id); } else { // play the playlist await this.playSpotifyByTrackAndPlaylist(playlistId, ""); } setTimeout(async () => { if (trackRepeating) { // make sure it set to repeat commands.executeCommand("musictime.repeatOn"); } else { // set it to not repeat commands.executeCommand("musictime.repeatOff"); } setTimeout(() => { MusicStateManager.getInstance().fetchTrack(); }, 1000); }, 2000); } /** * Helper function to play a track or playlist if we've determined to play * against the mac spotify desktop app. */ async playSpotifyDesktopPlaylistTrack(devices: PlayerDevice[]) { const trackRepeating = await isTrackRepeating(); const selectedTrack: PlaylistItem = getSelectedTrackItem(); // get the selected playlist const isPrem = isPremiumUser(); const isWin = isWindows(); // get the selected track const isLikedSongsPlaylist = selectedTrack["playlist_id"] === SPOTIFY_LIKED_SONGS_PLAYLIST_NAME; if (isLikedSongsPlaylist) { if ((!isWin || isPrem) && devices && devices.length > 0) { // just play the 1st track this.playSpotifyByTrack(selectedTrack, devices); } else if (!isWin) { // try with the desktop app playSpotifyMacDesktopTrack(selectedTrack.id); } else { // just try to play it since it's windows and we don't have a device playSpotifyTrack(selectedTrack.id, ""); } } else { if (!isWin) { // ex: ["spotify:track:0R8P9KfGJCDULmlEoBagcO", "spotify:playlist:6ZG5lRT77aJ3btmArcykra"] // make sure the track has spotify:track and the playlist has spotify:playlist playSpotifyMacDesktopTrack(selectedTrack.id, selectedTrack["playlist_id"]); } else { this.playSpotifyByTrackAndPlaylist(selectedTrack["playlist_id"], selectedTrack.id); } } setTimeout(async () => { if (trackRepeating) { // make sure it set to repeat commands.executeCommand("musictime.repeatOn"); } else { // set it to not repeat commands.executeCommand("musictime.repeatOff"); } setTimeout(() => { MusicStateManager.getInstance().fetchTrack(); }, 1000); }, 2000); } async playSpotifyByTrackAndPlaylist(playlistId: string, trackId: string) { const device = getBestActiveDevice(); // just play the 1st track await playSpotifyPlaylist(playlistId, trackId, device?.id); } async playSpotifyByTrack(track: PlaylistItem, devices: PlayerDevice[] = []) { const device = getBestActiveDevice(); if (device) { playSpotifyTrack(track.id, device.id); } else if (!isWindows()) { // try with the desktop app playSpotifyMacDesktopTrack(track.id); } else { // just try to play it without the device playSpotifyTrack(track.id, ""); } } async setLiked(track: any, liked: boolean) { let trackId = track?.id; if (!trackId) { // check to see if we have a running track const runningTrack: Track = await getCachedRunningTrack(); track = createPlaylistItemFromTrack(runningTrack, 0); trackId = runningTrack?.id; } if (!trackId) { window.showInformationMessage(`No track currently playing. Please play a track to use this feature.`); return; } let isRecommendationTrack = false; let selectedPlaylistId = getSelectedPlaylistId(); if (!selectedPlaylistId) { selectedPlaylistId = track["playlist_id"]; } if (selectedPlaylistId === RECOMMENDATION_PLAYLIST_ID) { isRecommendationTrack = true; } // save the spotify track to the users liked songs playlist if (liked) { await saveToSpotifyLiked([trackId]); // add it to the liked songs playlist addTrackToLikedPlaylist(track); } else { await removeFromSpotifyLiked([trackId]); // remove from the cached liked list removeTrackFromLikedPlaylist(trackId); } if (isRecommendationTrack) { updateLikedStatusInPlaylist(selectedPlaylistId, trackId, liked); commands.executeCommand("musictime.refreshMusicTimeView", "recommendations", selectedPlaylistId); } else { // update liked state in the playlist the track is in if (selectedPlaylistId !== SPOTIFY_LIKED_SONGS_PLAYLIST_ID) { updateLikedStatusInPlaylist(selectedPlaylistId, trackId, liked); } if (selectedPlaylistId) { commands.executeCommand("musictime.refreshMusicTimeView", "playlists", selectedPlaylistId); } } setTimeout(() => { MusicStateManager.getInstance().fetchTrack(); }, 1000); } async copySpotifyLink(id: string, isPlaylist: boolean) { let link = buildSpotifyLink(id, isPlaylist); if (id === SPOTIFY_LIKED_SONGS_PLAYLIST_NAME) { link = "https://open.spotify.com/collection/tracks"; } let messageContext = ""; if (isPlaylist) { messageContext = "playlist"; } else { messageContext = "track"; } try { clipboardy.writeSync(link); window.showInformationMessage(`Spotify ${messageContext} link copied to clipboard.`); } catch (err) { console.log(`Unable to copy to clipboard, error: ${err.message}`); } } copyCurrentTrackLink() { // example: https://open.spotify.com/track/7fa9MBXhVfQ8P8Df9OEbD8 // get the current track const selectedItem: PlaylistItem = getSelectedTrackItem(); this.copySpotifyLink(selectedItem.id, false); } copyCurrentPlaylistLink() { // example: https://open.spotify.com/playlist/0mwG8hCL4scWi8Nkt7jyoV const selectedItem: PlaylistItem = getSelectedTrackItem(); this.copySpotifyLink(selectedItem["playlist_id"], true); } shareCurrentPlaylist() { const socialShare: SocialShareManager = SocialShareManager.getInstance(); const selectedItem: PlaylistItem = getSelectedTrackItem(); const url = buildSpotifyLink(selectedItem["playlist_id"], true); socialShare.shareIt("facebook", { u: url, hashtag: "OneOfMyFavs" }); } async showMenu() { let menuOptions = { items: [], }; // check if they need to connect to spotify const needsSpotifyAccess = requiresSpotifyAccess(); // check to see if they have the slack access token const hasSlackAccess = hasSlackWorkspaces(); menuOptions.items.push({ label: "Dashboard", detail: "View your latest music metrics right here in your editor", cb: displayMusicTimeMetricsMarkdownDashboard, }); menuOptions.items.push({ label: "Submit an issue on GitHub", detail: "Encounter a bug? Submit an issue on our GitHub page", url: "https://github.com/swdotcom/swdc-vscode-musictime/issues", }); menuOptions.items.push({ label: "Submit feedback", detail: "Send us an email at cody@software.com", url: "mailto:cody@software.com", }); menuOptions.items.push({ label: "More data at Software.com", detail: "See music analytics in the web app", command: "musictime.launchAnalytics", }); // show divider menuOptions.items.push({ label: "___________________________________________________________________", cb: null, url: null, command: null, }); if (needsSpotifyAccess) { menuOptions.items.push({ label: "Connect Spotify", detail: "To see your Spotify playlists in Music Time, please connect your account", url: null, cb: connectSpotify, }); } else { menuOptions.items.push({ label: "Disconnect Spotify", detail: "Disconnect your Spotify oauth integration", url: null, command: "musictime.disconnectSpotify", }); if (!hasSlackAccess) { menuOptions.items.push({ label: "Connect Slack", detail: "To share a playlist or track on Slack, please connect your account", url: null, cb: connectSlackWorkspace, }); } else { menuOptions.items.push({ label: "Disconnect Slack", detail: "Disconnect your Slack oauth integration", url: null, command: "musictime.disconnectSlack", }); } } showQuickPick(menuOptions); } async showCreatePlaylistInputPrompt(placeHolder: string) { return await window.showInputBox({ value: placeHolder, placeHolder: "New Playlist", validateInput: (text) => { return !text || text.trim().length === 0 ? "Please enter a playlist name to continue." : null; }, }); } async createNewPlaylist() { const musicControlMgr: MusicControlManager = MusicControlManager.getInstance(); // !!! important, need to use the get instance as this // method may be called within a callback and "this" will be undefined !!! const hasPlaylistItemToAdd = musicControlMgr.currentTrackToAdd ? true : false; const placeholder: string = hasPlaylistItemToAdd ? `${musicControlMgr.currentTrackToAdd.artist} - ${musicControlMgr.currentTrackToAdd.name}` : "New Playlist"; let playlistName = await musicControlMgr.showCreatePlaylistInputPrompt(placeholder); if (playlistName && playlistName.trim().length === 0) { window.showInformationMessage("Please enter a playlist name to continue."); return; } if (!playlistName) { return; } const playlistItems = hasPlaylistItemToAdd ? [musicControlMgr.currentTrackToAdd] : []; MusicPlaylistManager.getInstance().createPlaylist(playlistName, playlistItems); } async addToPlaylistMenu(playlistItem: PlaylistItem) { this.currentTrackToAdd = playlistItem; let menuOptions = { items: [ { label: "New Playlist", cb: this.createNewPlaylist, }, ], placeholder: "Select or Create a playlist", }; let playlists: PlaylistItem[] = await getSpotifyPlaylists(); sortPlaylists(playlists); playlists.forEach((item: PlaylistItem) => { menuOptions.items.push({ label: item.name, cb: null, }); }); const pick = await showQuickPick(menuOptions); if (pick && pick.label) { // add it to this playlist const matchingPlaylists = playlists.filter((n: PlaylistItem) => n.name === pick.label).map((n: PlaylistItem) => n); if (matchingPlaylists.length) { const matchingPlaylist = matchingPlaylists[0]; if (matchingPlaylist) { const playlistName = matchingPlaylist.name; let errMsg = null; const trackUri = playlistItem.uri || createUriFromTrackId(playlistItem.id); const trackId = playlistItem.id; if (matchingPlaylist.name !== "Liked Songs") { // it's a non-liked songs playlist update // uri:"spotify:track:2JHCaLTVvYjyUrCck0Uvrp" or id const codyResponse = await addTracksToPlaylist(matchingPlaylist.id, [trackUri]); errMsg = getCodyErrorMessage(codyResponse); // populate the spotify playlists await getSpotifyPlaylists(true); } else { // it's a liked songs playlist update let track: Track = await getRunningTrack(); if (track.id !== trackId) { track = new Track(); track.id = playlistItem.id; track.playerType = playlistItem.playerType; track.state = playlistItem.state; } await this.setLiked(playlistItem, true); } if (!errMsg) { window.showInformationMessage(`Added ${playlistItem.name} to ${playlistName}`); // refresh the playlist and clear the current recommendation metadata removeTracksFromRecommendations(trackId); commands.executeCommand("musictime.refreshMusicTimeView"); } else { if (errMsg) { window.showErrorMessage(`Failed to add '${playlistItem.name}' to '${playlistName}'. ${errMsg}`, ...[OK_LABEL]); } } } } } } } export function buildSpotifyLink(id: string, isPlaylist: boolean) { let link = ""; id = createSpotifyIdFromUri(id); if (isPlaylist) { link = `https://open.spotify.com/playlist/${id}`; } else { link = `https://open.spotify.com/track/${id}`; } return link; } export async function displayMusicTimeMetricsMarkdownDashboard() { const isRegistered = checkRegistration(); if (!isRegistered) { return; } const musicTimeFile = getMusicTimeMarkdownFile(); await fetchMusicTimeMetricsMarkdownDashboard(); const viewOptions = { viewColumn: ViewColumn.One, preserveFocus: false, }; const localResourceRoots = [Uri.file(getSoftwareDir()), Uri.file(tmpdir())]; const panel = window.createWebviewPanel("music-time-preview", `Music Time Dashboard`, viewOptions, { enableFindWidget: true, localResourceRoots, enableScripts: true, // enables javascript that may be in the content }); const content = fileIt.readContentFileSync(musicTimeFile); panel.webview.html = content; }
the_stack
import * as vscode from 'vscode'; import { Module, TlaDocumentInfo, TlaDocumentInfos } from '../model/documentInfo'; const COMMA_LEN = 1; export const ROOT_SYMBOL_NAME = '*'; export const ROOT_CONTAINER_NAME = ''; export const PLUS_CAL_DEFAULT_NAME = 'PlusCal algorithm'; enum SpecialSymbol { PlusCalEnd } /** * Holds information about currently parsing module (an actual TLA+ module or PlusCal algorithm) */ class ModuleContext { readonly symbols: vscode.SymbolInformation[] = []; lastTopDefBlock: vscode.SymbolInformation | undefined; simpleListSymbolKind: vscode.SymbolKind | undefined; constructor( readonly rootSymbol: vscode.SymbolInformation, readonly containerName = rootSymbol.name ) { this.symbols.push(rootSymbol); } addSymbol(symbol: vscode.SymbolInformation) { this.symbols.push(symbol); } close(end: vscode.Position) { this.rootSymbol.location.range = new vscode.Range(this.rootSymbol.location.range.start, end); } convert(): Module { return new Module( this.rootSymbol.name, this.symbols, this.rootSymbol.location.range ); } } class ParsingContext { readonly modules: ModuleContext[] = []; readonly rootModule: ModuleContext; // Collects symbols that are placed outside a TLA+ module and PlusCal algorithm plusCal: ModuleContext | undefined; currentModule: ModuleContext; constructor(document: vscode.TextDocument) { const zeroPos = new vscode.Position(0, 0); const rootSymbol = new vscode.SymbolInformation( // Represents the whole document ROOT_SYMBOL_NAME, vscode.SymbolKind.Namespace, ROOT_CONTAINER_NAME, new vscode.Location(document.uri, new vscode.Range(zeroPos, zeroPos)) ); this.rootModule = new ModuleContext(rootSymbol, ''); this.currentModule = this.rootModule; } isInRoot(): boolean { return this.currentModule === this.rootModule; } isInPlusCal(): boolean { return this.plusCal && this.currentModule === this.plusCal ? true : false; } startPlusCal(rootSymbol: vscode.SymbolInformation) { this.startModule(rootSymbol, true); } startModule(rootSymbol: vscode.SymbolInformation, plusCal = false): ModuleContext { const module = new ModuleContext(rootSymbol); this.modules.push(module); this.currentModule = module; if (plusCal) { this.plusCal = module; } return module; } closeModule(end: vscode.Position) { if (this.currentModule) { this.currentModule.close(end); this.currentModule = this.rootModule; } } } /** * Provides TLA+ symbols from the given document. */ export class TlaDocumentSymbolsProvider implements vscode.DocumentSymbolProvider { constructor( private readonly docInfos: TlaDocumentInfos ) {} provideDocumentSymbols( document: vscode.TextDocument, token: vscode.CancellationToken ): vscode.ProviderResult<vscode.SymbolInformation[] | vscode.DocumentSymbol[]> { const context = new ParsingContext(document); let lastLine = undefined; for (let i = 0; i < document.lineCount; i++) { const line = document.lineAt(i); lastLine = line; if (line.isEmptyOrWhitespace) { continue; } const sym = this.tryExtractSymbol(context, document, line); if (!sym) { this.tryExtractSpecialSymbol(context, line); } } if (context.currentModule && lastLine) { context.closeModule(lastLine.range.end); } let symbols = context.rootModule.symbols.filter(s => s.name !== ROOT_SYMBOL_NAME); for (const modCtx of context.modules) { symbols = symbols.concat(modCtx.symbols); } this.docInfos.set(document.uri, new TlaDocumentInfo( context.rootModule.convert(), context.plusCal?.convert(), context.modules.map(m => m.convert()), symbols.slice() )); if (context.plusCal) { symbols = symbols.concat(context.plusCal.symbols); } return symbols; } tryExtractSymbol( context: ParsingContext, document: vscode.TextDocument, line: vscode.TextLine ): boolean { const moduleStart = this.tryStartTlaModule(context, document, line); if (moduleStart) { return true; } if (context.isInRoot() && this.tryStartPlusCal(context, document.uri, line)) { return true; } if (this.tryEndModule(context, line)) { return true; } const module = context.currentModule; if (typeof module.simpleListSymbolKind !== 'undefined') { if (this.tryCollectListItems(module, document.uri, line.lineNumber, 0, line.text)) { return true; } } if (this.tryExtractDefinition(module, document, line)) { return true; } if (this.tryExtractListStart(module, document.uri, line)) { return true; } if (this.tryExtractTheoremAxiomLemma(module, document.uri, line)) { return true; } return false; } tryExtractSpecialSymbol(context: ParsingContext, line: vscode.TextLine): boolean { const symbol = this.tryExtractPlusCalEnd(line); if (typeof symbol === 'undefined') { return false; } if (symbol === SpecialSymbol.PlusCalEnd && context.isInPlusCal()) { context.closeModule(line.range.end); context.plusCal = undefined; } return true; } tryStartTlaModule( context: ParsingContext, document: vscode.TextDocument, line: vscode.TextLine ): boolean { const matches = /^\s*-{4,}\s*MODULE\s*(\w+)\s*-{4,}.*$/g.exec(line.text); if (!matches) { return false; } const lastLine = document.lineAt(document.lineCount - 1); const symbol = new vscode.SymbolInformation( matches[1], vscode.SymbolKind.Module, ROOT_CONTAINER_NAME, new vscode.Location( document.uri, new vscode.Range(line.range.start, lastLine.range.end) ) ); context.startModule(symbol); return true; } tryEndModule(context: ParsingContext, line: vscode.TextLine): boolean { const matches = /^={4,}\s*$/g.exec(line.text); if (!matches) { return false; } context.closeModule(line.range.end); return true; } tryExtractDefinition( module: ModuleContext, document: vscode.TextDocument, line: vscode.TextLine ): boolean { const matches = /^((?:\s|LET|\/\\)*)(\w+)\s*([(|[)].*)?\s*==\s*(.*)?/g.exec(line.text); if (!matches) { return false; } const prefix = matches[1]; const name = matches[2]; const blockStart = new vscode.Position(line.range.start.line, prefix.length); const ltp = module.lastTopDefBlock; if (ltp && line.range.start.line >= ltp.location.range.start.line && line.range.end.line <= ltp.location.range.end.line && prefix.length > module.rootSymbol.location.range.start.character ) { // This looks like a private variable within a top level definition module.addSymbol(new vscode.SymbolInformation( name, vscode.SymbolKind.Variable, ltp.name, new vscode.Location(document.uri, blockStart) )); return true; } // This is a top level definition let kind = vscode.SymbolKind.Field; const next = matches[3]; const value = matches[4]; if (next && (next[0] === '(' || next[0] === '[')) { kind = vscode.SymbolKind.Function; } else if (value && value.startsWith('INSTANCE')) { kind = vscode.SymbolKind.Namespace; } const blockEnd = findBlockDefinitionEnd(document, line, blockStart.character).range.end; const symbol = new vscode.SymbolInformation( name, kind, module.containerName, new vscode.Location(document.uri, new vscode.Range(blockStart, blockEnd)) ); module.addSymbol(symbol); module.lastTopDefBlock = symbol; return true; } tryExtractListStart( module: ModuleContext, docUri: vscode.Uri, line: vscode.TextLine ): boolean { const matches = /^(\s*)(VARIABLE(?:S)?|CONSTANT(?:S)?)(\s*.*)/g.exec(line.text); if (!matches) { return false; } module.simpleListSymbolKind = matches[2].startsWith('V') ? vscode.SymbolKind.Variable : vscode.SymbolKind.Constant; const startIdx = matches[1].length + matches[2].length; return this.tryCollectListItems(module, docUri, line.lineNumber, startIdx, matches[3]); } tryCollectListItems( module: ModuleContext, docUri: vscode.Uri, lineNum: number, startChar: number, text: string ): boolean { if (!module.simpleListSymbolKind) { return false; } let charIdx = startChar; const chunks = text.split(','); let name: string | undefined; for (const chunk of chunks) { const rChunk = chunk.trimLeft(); if (isCommentStart(rChunk)) { return true; } charIdx += chunk.length - rChunk.length; // + number of trimmed spaces const matches = /^(\w*)(\s*)(.*)$/g.exec(rChunk); if (!matches) { module.simpleListSymbolKind = undefined; return false; } name = matches[1]; const spaces = matches[2]; const rest = matches[3]; if (name === '') { charIdx += COMMA_LEN; continue; } if (rest !== '' && !isCommentStart(rest)) { module.simpleListSymbolKind = undefined; return false; } module.addSymbol(new vscode.SymbolInformation( name, module.simpleListSymbolKind, module.containerName, new vscode.Location(docUri, new vscode.Position(lineNum, charIdx)) )); charIdx += name.length + spaces.length + COMMA_LEN; if (rest !== '') { module.simpleListSymbolKind = undefined; break; // There were no comma after the name } } if (name !== '') { module.simpleListSymbolKind = undefined; // There were no comma after the last name } return true; } tryExtractTheoremAxiomLemma( module: ModuleContext, docUri: vscode.Uri, line: vscode.TextLine ): boolean { const matches = /^\s*(?:THEOREM|AXIOM|LEMMA)\s*(\w+)\s*==/g.exec(line.text); if (!matches) { return false; } module.addSymbol(new vscode.SymbolInformation( matches[1], vscode.SymbolKind.Boolean, module.containerName, new vscode.Location(docUri, line.range.start) )); return true; } tryStartPlusCal( context: ParsingContext, docUri: vscode.Uri, line: vscode.TextLine ): boolean { const matches = /(\(\*.*)--((?:fair\s+)?algorithm)\b\s*/g.exec(line.text); if (!matches) { return false; } const algName = line.text.substring(matches[0].length) || PLUS_CAL_DEFAULT_NAME; const symbol = new vscode.SymbolInformation( algName, vscode.SymbolKind.Namespace, ROOT_CONTAINER_NAME, new vscode.Location(docUri, line.range.start) ); context.startPlusCal(symbol); return true; } tryExtractPlusCalEnd(line: vscode.TextLine): SpecialSymbol | undefined { const matches = /(end\s+algorithm)(;)?\s*(\*\))/g.test(line.text); if (matches) { return SpecialSymbol.PlusCalEnd; } return line.text === '\\* BEGIN TRANSLATION' ? SpecialSymbol.PlusCalEnd : undefined; } } function isCommentStart(str: string): boolean { return str.startsWith('\\*') || str.startsWith('(*'); } /** * Finds and returns the last line of the definition block, started at the given line. * Definition block expands till the next non-empty line with no leading spaces. */ function findBlockDefinitionEnd( document: vscode.TextDocument, startLine: vscode.TextLine, indent: number ): vscode.TextLine { let lastLine = startLine; for (let i = startLine.lineNumber + 1; i < document.lineCount; i++) { const line = document.lineAt(i); if (line.isEmptyOrWhitespace) { continue; } if (line.firstNonWhitespaceCharacterIndex <= indent) { // New block started break; } lastLine = line; } return lastLine; }
the_stack
import { Hint, IconSymbol, Size, Switcher, TEXT, ThemeTypes as Theme, Tooltip, ButtonIcon, Style } from '@getstation/theme'; import * as classNames from 'classnames'; import { Iterable, List } from 'immutable'; import * as React from 'react'; import { compose } from 'react-apollo'; // @ts-ignore no declaration file import injectSheet from 'react-jss'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { oc } from 'ts-optchain'; import { uninstallAllInstances } from '../../abstract-application/duck'; import { withCheckForUpdatesApplicationMutation, withGetAbstractApplication } from '../../abstract-application/queries@local.gql.generated'; import { setAlwaysLoaded, setInstanceLogoInDock } from '../../application-settings/duck'; import { changeSelectedApp, installApplication, uninstallApplication } from '../../applications/duck'; import { checkForUpdate } from '../../chrome-extensions/duck'; import { getExtensionState } from '../../chrome-extensions/selectors'; import { ExtensionState } from '../../chrome-extensions/types'; import AppIcon from '../../dock/components/AppIcon'; import { removeLink } from '../../password-managers/duck'; import { StationState } from '../../types'; import AddNewInstance from '../applications/components/AddNewInstance'; import ApplicationExtensions from '../applications/components/ApplicationExtensions'; import ListInstances from '../applications/components/ListInstances'; import { getApplicationsForDock } from '../../../app/dock/selectors'; import RemoveModalConfirmation from '../applications/components/RemoveModalConfirmation'; import { Extension, Instance, Instances } from './types'; import ExtensionInfos from './components/ExtensionInfos'; import { pure } from 'recompose'; interface Classes { item: string, highlightedItem: string, header: string, appIcon: string, appTitle: string, appVersion: string, subtitle: string, extensionInfosWrapper: string, descriptionWrapper: string, description: string, instancesContainer: string, addInstance: string, buttonRemoveAllContainer: string, buttonRemoveAll: string, listInstances: string, } type DefaultProps = { highlighted: boolean, alwaysLoaded: boolean, alwaysLoadedByDefault: boolean, applicationName: string, applicationIcon: string, applicationThemeColor: string, applicationCxExtensionId?: string, instanceWording: string, instances: Instances, extensions: Extension[], useInstanceLogoInDock: boolean, applications: Instances, }; type OwnProps = DefaultProps & { classes?: Classes, manifestURL: string, attachAppRef: (node: HTMLDivElement) => any, closeSettings: ( manifestURL: string, applicationName: string, via: 'add-account' | 'configure-account' ) => any, }; interface StateProps { extensionState?: ExtensionState, } interface DispatchProps { onRemoveAllInstances: () => any, onAddNewInstance: () => any, onRemoveInstance: (instanceId: string) => any, onConfigureInstance: (instanceId: string) => any, onUnlinkPasswordManager: () => any, onExtensionToggle: (extensionManifestURL: string, added: boolean) => any, onToggleInstanceLogoInDock: () => any, onToogleAutoSleep: (event: React.FormEvent<HTMLInputElement>) => any, onExtensionCheckForUpdate: typeof checkForUpdate, } type Props = OwnProps & StateProps & DispatchProps; interface State { removeApplication: boolean, instancesToRemove: Instances, lastInstance: boolean, removeAction: () => any } @injectSheet((theme: Theme) => ({ item: { marginBottom: 20, padding: 20, backgroundColor: 'rgba(255, 255, 255, 0.10)', borderRadius: 6, transition: [ ['background-color', '300ms', 'ease-in'], ], }, highlightedItem: { backgroundColor: 'rgba(255, 255, 255, 0.50)', transition: [ ['background-color', '300ms', 'ease-out'], ], }, header: { display: 'flex', width: '100%', alignItems: 'center', paddingBottom: 20, }, appIcon: { width: 35, height: 35, borderRadius: 100, marginRight: 5, }, appTitle: { ...theme.titles.h2, marginLeft: 10, marginRight: 20, }, appVersion: { marginBottom: '-2.5px', }, subtitle: { ...theme.fontMixin(12, 600), margin: [20, 0, 10], }, extensionInfosWrapper: {}, descriptionWrapper: { display: 'flex', justifyContent: 'space-between', }, description: {}, instancesContainer: { margin: [20, 0], }, addInstance: { maxWidth: 300, }, buttonRemoveAllContainer: { marginLeft: 'auto', }, buttonRemoveAll: { backgroundColor: 'rgba(0, 0, 0, 0.25)', }, listInstances: { marginBottom: '20px', }, })) class AppImpl extends React.PureComponent<Props, State> { static defaultProps: DefaultProps = { highlighted: false, alwaysLoaded: false, alwaysLoadedByDefault: false, applicationName: '', applicationIcon: '', applicationThemeColor: '', applicationCxExtensionId: undefined, instanceWording: 'instance', instances: Iterable([]), extensions: [], useInstanceLogoInDock: false, applications: List([]), }; static defaultState: State = { removeApplication: false, instancesToRemove: List([]), lastInstance: false, removeAction: () => { }, }; constructor(props: Props) { super(props); this.state = AppImpl.defaultState; } onToggleAutoSleep = ( event: React.FormEvent<HTMLInputElement>, ) => { this.props.onToogleAutoSleep(event); } onConfirmRemoveApplication = () => this.setState({ ...AppImpl.defaultState, removeApplication: true, instancesToRemove: this.props.instances, removeAction: () => { this.props.onRemoveAllInstances(); this.setState(AppImpl.defaultState); }, }) onConfirmRemoveInstance = (id: string) => this.setState({ ...AppImpl.defaultState, instancesToRemove: this.props.instances.filter((i: Instance) => i.id === id), lastInstance: this.props.instances.count() === 1, removeAction: () => { this.props.onRemoveInstance(id); this.setState(AppImpl.defaultState); }, }) onCancelConfirmation = () => this.setState(AppImpl.defaultState); render() { const { classes, highlighted, alwaysLoaded, alwaysLoadedByDefault, manifestURL, applicationName, applicationIcon, applicationThemeColor, instanceWording, instances, extensions, useInstanceLogoInDock, attachAppRef, onAddNewInstance, onConfigureInstance, onUnlinkPasswordManager, onExtensionToggle, onToggleInstanceLogoInDock, onExtensionCheckForUpdate, applications, extensionState, } = this.props; const { removeApplication, instancesToRemove, lastInstance, removeAction, } = this.state; return ( <div ref={attachAppRef} key={manifestURL} className={classNames(classes!.item, { [classes!.highlightedItem]: highlighted })} > {(removeApplication || instancesToRemove.count() > 0) && <RemoveModalConfirmation applicationName={applicationName} instanceTypeWording={instanceWording} allInstancesRemoved={removeApplication || lastInstance} instancesToRemove={instancesToRemove} onContinue={removeAction} onCancel={this.onCancelConfirmation} /> } <div className={classes!.header}> <AppIcon imgUrl={applicationIcon} themeColor={applicationThemeColor} /> <div className={classes!.appTitle}> {applicationName} </div> <Tooltip className={classes!.buttonRemoveAllContainer} tooltip={'Remove app'} offset="-2, 12" placement={'left'} > <ButtonIcon className={classes!.buttonRemoveAll} iconColor="white" btnStyle={Style.SECONDARY} symbolId={IconSymbol.TRASH} btnSize={Size.SMALL} onClick={this.onConfirmRemoveApplication} /> </Tooltip> </div> {extensionState && <div className={classes!.extensionInfosWrapper}> <ExtensionInfos extensionState={extensionState} onCheckForUpdate={onExtensionCheckForUpdate} /> </div> } <div className={classes!.instancesContainer}> <div className={classes!.listInstances} > <ListInstances applications={applications} manifestURL={manifestURL} instanceTypeWording={instanceWording} onRemoveInstance={this.onConfirmRemoveInstance} onUnlinkPasswordManager={onUnlinkPasswordManager} onConfigureInstance={onConfigureInstance} instances={instances} /> </div> <AddNewInstance name={applicationName} instanceTypeWording={instanceWording} onClick={onAddNewInstance} /> </div> <ApplicationExtensions extensions={extensions} onExtensionToggle={onExtensionToggle} /> <div className={classes!.subtitle}> DOCK ICON </div> <div className={classes!.descriptionWrapper} > <div className={classes!.description}> When available, use {instanceWording} logo in the dock </div> <Switcher checked={useInstanceLogoInDock} onChange={onToggleInstanceLogoInDock} text={TEXT.YES_NO} /> </div> <div className={classes!.subtitle}> <Hint tooltip="By default, Station puts to sleep unused applications in order to preserve memory and prevent slow-downs."> BACKGROUND ACTIVITY </Hint> </div> <div className={classes!.descriptionWrapper}> <div className={classes!.description}> Keep {applicationName} active in background to receive calls and notifications. </div> <div> <Switcher checked={alwaysLoadedByDefault ? true : alwaysLoaded} disabled={alwaysLoadedByDefault} disabledHint={`${applicationName} is always kept active in background`} onChange={this.onToggleAutoSleep} text={TEXT.YES_NO} /> </div> </div> </div> ); } } const App = compose( // React Apollo HOC are not pure // let's wrap this in a pure component so that we get a performance boost pure, withGetAbstractApplication({ options: ({ manifestURL }: Props) => ({ variables: { manifestURL }, }), props: ({ data }) => { if (data) { const abstractApplication = oc(data).abstractApplication; const manifest = abstractApplication.manifest; const settings = abstractApplication.settings; const instances = abstractApplication.instances; const extensions = abstractApplication.extensions; if (manifest() && settings() && extensions()) { return { alwaysLoadedByDefault: manifest.bx_keep_always_loaded(), alwaysLoaded: settings.alwaysLoaded(), applicationName: manifest.name(), applicationIcon: manifest.interpretedIconURL(), applicationThemeColor: manifest.theme_color(), applicationCxExtensionId: manifest.cxExtensionId(), instanceWording: manifest.bx_multi_instance_config!.instance_wording(), instances: Iterable(instances()), extensions: extensions(), useInstanceLogoInDock: settings.instanceLogoInDock(), }; } } return {}; }, }), withCheckForUpdatesApplicationMutation({ props: ({ mutate, ownProps }) => ({ checkForUpdatesApplication: () => // @ts-ignore manifestURL exists on ownPropsw mutate && mutate({ variables: { manifestURL: ownProps.manifestURL } }), }), }), connect<StateProps, DispatchProps, OwnProps>( (state: StationState, props: DefaultProps) => ({ extensionState: props.applicationCxExtensionId ? getExtensionState(state, props.applicationCxExtensionId) : undefined, applications: getApplicationsForDock(state), }), // @ts-ignore (dispatch: Dispatch<any>, ownProps: OwnProps) => { const { manifestURL, applicationName, closeSettings, } = ownProps; return bindActionCreators( { onRemoveAllInstances: () => { return uninstallAllInstances(manifestURL); }, onRemoveInstance: (id) => { return uninstallApplication(id); }, onAddNewInstance: () => { closeSettings(manifestURL, applicationName, 'add-account'); return installApplication(manifestURL, { navigate: true }); }, onConfigureInstance: (id: string) => { closeSettings(id, applicationName, 'configure-account'); return changeSelectedApp(id); }, onUnlinkPasswordManager: (applicationId: string) => removeLink({ applicationId }), onExtensionToggle: (extensionManifestURL: string, added: boolean) => { if (added) { return installApplication(extensionManifestURL); } return uninstallAllInstances(extensionManifestURL); }, onToggleInstanceLogoInDock: (event: React.FormEvent<HTMLInputElement>) => { // @ts-ignore checked exists const checked = event.target.checked; return setInstanceLogoInDock(manifestURL, checked); }, onToogleAutoSleep: (event: React.FormEvent<HTMLInputElement>) => { // @ts-ignore checked exists const checked = event.target.checked; return setAlwaysLoaded(manifestURL, checked); }, onExtensionCheckForUpdate: checkForUpdate, }, dispatch ); }, null, { withRef: true }, ), )(AppImpl); export default App;
the_stack
'use strict'; import * as coqProto from './coq-proto'; import {spawn} from 'child_process'; import * as semver from 'semver'; import {AnnotatedText, normalizeText, textToDisplayString} from '../util/AnnotatedText'; /** Coqtop was interrupted; call cancelled */ export class Interrupted { constructor( public stateId: number) {} public toString() { return 'Coqtop Interrupted'; } } /** A fatal error of coqtop */ export class CoqtopSpawnError { constructor(private path: string, private message: string) {} public get binPath() : string { return this.path; } public toString() { return "Could not start coqtop: " + this.path + (this.message? "\n" + this.message : ""); } } /** A call did not succeed; a nonfatal error */ export class CallFailure { constructor( public message: AnnotatedText, public stateId?: number, public range?: coqProto.Location) { this.message = normalizeText(this.message); } public toString() { return textToDisplayString(this.message) + (this.range || this.stateId ? " (" + (this.range ? `offsets ${this.range.start}-${this.range.stop}` : (this.stateId ? " " : "")) + (this.stateId ? ` of stateId ${this.stateId}` : "") + ")" : "") } } export interface InitResult { stateId: number; } export interface AddResult { stateId: number; unfocusedStateId?: number; message: AnnotatedText; } export interface EditAtFocusResult { stateId: number; qedStateId: number; oldStateIdTip: number; } export interface EditAtResult { enterFocus?: EditAtFocusResult; } export interface ProofView { goals: coqProto.Subgoal[]; backgroundGoals: coqProto.UnfocusedGoalStack shelvedGoals: coqProto.Subgoal[]; abandonedGoals: coqProto.Subgoal[]; } export type NoProofTag = {mode: 'no-proof'} export type ProofModeTag = {mode: 'proof'} export type NoProofResult = NoProofTag & {} export type ProofModeResult = ProofModeTag & ProofView export type GoalResult = NoProofResult | ProofModeResult export interface EventCallbacks { onFeedback? : (feedback: coqProto.StateFeedback) => void; onMessage? : (msg: coqProto.Message, routeId: coqProto.RouteId, stateId?: coqProto.StateId) => void; onClosed?: (isError: boolean, message?: string) => void; } export function detectVersion(coqtopModule: string, cwd: string, console?: {log: (string)=>void, warn: (string)=>void}) : Promise<string|null> { if(console) console.log('exec: ' + coqtopModule + ' -v'); return new Promise<string>((resolve,reject) => { try { const coqtop = spawn(coqtopModule, ['-v'], {detached: false, cwd: cwd}); let result = ""; coqtop.stdout.on('data', (data:string) => { result += data }); coqtop.on('close', () => { const ver = /^\s*The Coq Proof Assistant, version (.+?)\s/.exec(result); // if(!ver) // console.warn('Could not detect coqtop version'); resolve(!ver ? undefined : ver[1]); }); coqtop.on('error', (code:number) => { // console.warn(`Could not start coqtop; error code: ${code}`) reject(new CoqtopSpawnError(coqtopModule, `error code: ${code}`)); }); } catch(err) { reject(new CoqtopSpawnError(coqtopModule, err)); } }) } export abstract class IdeSlave { protected callbacks : EventCallbacks = {}; public onFeedback(handler: (feedback: coqProto.StateFeedback) => void) : {dispose: ()=>void} { this.callbacks.onFeedback = handler; return { dispose: () => { this.callbacks.onFeedback = undefined; } } } public onMessage(handler: (msg: coqProto.Message, routeId: coqProto.RouteId, stateId: coqProto.StateId) => void) { this.callbacks.onMessage = handler; return { dispose: () => { this.callbacks.onMessage = undefined; } } } public onClosed(handler: (isError: boolean, message?: string) => void) { this.callbacks.onClosed = handler; return { dispose: () => { this.callbacks.onClosed = undefined; } } } // connect(version: string, mainR: stream.Readable, mainW: stream.Writable, controlR: stream.Readable, controlW: stream.Writable); public abstract dispose() : void; public abstract isConnected() : boolean; public abstract coqInterrupt() : Promise<boolean>; public abstract coqInit() : Promise<InitResult>; public abstract coqQuit() : Promise<void>; public abstract coqGoal() : Promise<GoalResult>; public abstract getStatus(force: boolean) : Promise<coqProto.CoqStatus>; public abstract coqAddCommand(command: string, editId: number, stateId: number, verbose?: boolean) : Promise<AddResult>; public abstract coqEditAt(stateId: number) : Promise<EditAtResult>; public abstract coqLtacProfilingResults(stateId?: number, routeId?: number) : Promise<void>; public abstract coqResizeWindow(columns: number) : Promise<void>; public abstract coqQuery(query: string, stateId?: number, routeId?: number) : Promise<void>; public abstract coqGetOptions(options: CoqOptions) : Promise<void>; public abstract coqSetOptions(options: CoqOptions) : Promise<void>; } export class CommunicationError extends Error { } export abstract class CoqTop extends IdeSlave { public abstract dispose(): void; public abstract isRunning() : boolean; public abstract getVersion() : semver.SemVer; public abstract startCoq() : Promise<InitResult>; /** Start coqtop. * Use two ports: one for reading & one for writing; i.e. HOST:READPORT:WRITEPORT */ // setupCoqTopReadAndWritePorts() : Promise<void>; public abstract isConnected() : boolean; public abstract coqInterrupt() : Promise<boolean>; public abstract coqInit() : Promise<InitResult>; public abstract coqQuit() : Promise<void>; public abstract coqGoal() : Promise<GoalResult>; public abstract getStatus(force: boolean) : Promise<coqProto.CoqStatus>; public abstract coqAddCommand(command: string, editId: number, stateId: number, verbose?: boolean) : Promise<AddResult>; public abstract coqEditAt(stateId: number) : Promise<EditAtResult>; public abstract coqLtacProfilingResults(stateId?: number, routeId?: number) : Promise<void>; public abstract coqResizeWindow(columns: number) : Promise<void>; public abstract coqQuery(query: string, stateId?: number, routeId?: number) : Promise<void>; public abstract coqGetOptions(options: CoqOptions) : Promise<void>; public abstract coqSetOptions(options: CoqOptions) : Promise<void>; } export interface CoqOptions { asymmetricPatterns?: boolean, atomicLoad?: boolean, automaticCoercionsImport?: boolean, automaticIntroduction?: boolean, booleanEqualitySchemes?: boolean, bracketingLastIntroductionPattern?: boolean, bulletBehavior?: string; // enum {Strict, subproofsCaseAnalysisSchemes?: boolean, compatNotations?: boolean, congruenceDepth?: number, congruenceVerbose?: boolean, contextualImplicit?: boolean, debugAuto?: boolean, debugEauto?: boolean, debugRAKAM?: boolean, debugTacticUnification?: boolean, debugTrivial?: boolean, debugUnification?: boolean, decidableEqualitySchemes?: boolean, defaultClearingUsedHypotheses?: boolean, defaultGoalSelector?: number, defaultProofMode?: string; // enum {Classic, defaultProofUsing?: any, defaultTimeout?: number, dependentPropositionsElimination?: boolean, discriminateIntroduction?: boolean, dumpBytecode?: boolean, eliminationSchemes?: boolean, equalityScheme?: boolean, extractionAutoInline?: boolean, extractionConservativeTypes?: boolean, extractionFileComment?: string, extractionFlag?: number, extractionKeepSingleton?: boolean, extractionOptimize?: boolean, extractionSafeImplicits?: boolean, extractionTypeExpand?: boolean, firstorderDepth?: number, hideObligations?: boolean, implicitArguments?: boolean, infoAuto?: boolean, infoEauto?: boolean, infoLevel?: any, infoTrivial?: boolean, injectionL2RPatternOrder?: boolean, injectionOnProofs?: boolean, inlineLevel?: number, intuitionIffUnfolding?: boolean, intuitionNegationUnfolding?: boolean, kernelTermSharing?: boolean, keyedUnification?: boolean, looseHintBehavior?: string; // enum {Lax, maximalImplicitInsertion?: boolean, nonrecursiveEliminationSchemes?: boolean, parsingExplicit?: boolean, primitiveProjections?: boolean, printingAll?: boolean, printingCoercions?: boolean, printingDepth?: number, printingExistentialInstances?: boolean, printingImplicit?: boolean, printingImplicitDefensive?: boolean, printingMatching?: boolean, printingNotations?: boolean, printingPrimitiveProjectionCompatibility?: boolean, printingPrimitiveProjectionParameters?: boolean, printingProjections?: boolean, printingRecords?: boolean, printingSynth?: boolean, printingUniverses?: boolean, printingWidth?: number, printingWildcard?: boolean, programMode?: boolean, proofUsingClearUnused?: boolean, recordEliminationSchemes?: boolean, regularSubstTactic?: boolean, reversiblePatternImplicit?: boolean, rewritingSchemes?: boolean, shortModulePrinting?: boolean, shrinkObligations?: boolean, simplIsCbn?: boolean, standardPropositionEliminationNames?: boolean, strictImplicit?: boolean, strictProofs?: boolean, strictUniverseDeclaration?: boolean, stronglyStrictImplicit?: boolean, suggestProofUsing?: boolean, tacticCompatContext?: boolean, tacticEvarsPatternUnification?: boolean, transparentObligations?: boolean, typeclassResolutionAfterApply?: boolean, typeclassResolutionForConversion?: boolean, typeclassesDebug?: boolean, typeclassesDependencyOrder?: boolean, typeclassesDepth?: any, typeclassesModuloEta?: boolean, typeclassesStrictResolution?: boolean, typeclassesUniqueInstances?: boolean, typeclassesUniqueSolutions?: boolean, universalLemmaUnderConjunction?: boolean, universeMinimizationToSet?: boolean, universePolymorphism?: boolean, verboseCompatNotations?: boolean, // Asynchronous options: function_debug?: boolean, function_raw_tcc?: boolean, functionalInductionRewriteDependent?: boolean, hypsLimit?: any, ltacDebug?: boolean, silent?: boolean, undo?: any, // [DEPRECATED] Tables: Search Blacklist Printing Coercion Printing If Printing Let Printing Record Printing Constructor // [DEPRECATED] Extraction AccessOpaque: boolean; // [DEPRECATED] Refine Instance Mode: boolean; // [DEPRECATED] Tactic Pattern Unification: boolean; }
the_stack
import { IAsyncEnumerable, IAsyncEqualityComparer, IComparer, IEqualityComparer, IGrouping, InferType, IOrderedAsyncEnumerable, IOrderedEnumerable, IParallelEnumerable, OfType, SelectorKeyType } from "./" /** * Iterable type with methods from LINQ. */ export interface IEnumerable<TSource> extends Iterable<TSource> { /** * Applies an accumulator function over a sequence. * @param func An accumulator function to be invoked on each element. * @returns The final accumulator value. */ aggregate(func: (x: TSource, y: TSource) => TSource): TSource /** * Applies an accumulator function over a sequence. * The specified seed value is used as the initial accumulator value. * @param seed The initial accumulator value. * @param func An accumulator function to be invoked on each element. * @returns The final accumulator value. */ aggregate<TAccumulate>(seed: TAccumulate, func: (x: TAccumulate, y: TSource) => TAccumulate): TAccumulate /** * Applies an accumulator function over a sequence. * The specified seed value is used as the initial accumulator value, * and the specified function is used to select the result value. * @param seed The initial accumulator value. * @param func An accumulator function to be invoked on each element. * @param resultSelector A function to transform the final accumulator value into the result value. * @returns The transformed final accumulator value. */ aggregate<TAccumulate, TResult>( seed: TAccumulate, func: (x: TAccumulate, y: TSource) => TAccumulate, resultSelector: (x: TAccumulate) => TResult): TResult /** * Determines whether all elements of a sequence satisfy a condition. * @param predicate A function to test each element for a condition. * @returns ``true`` if every element of the source sequence passes the test in the specified predicate, * or if the sequence is empty; otherwise, ``false``. */ all(predicate: (x: TSource) => boolean): boolean /** * Determines whether all elements of a sequence satisfy a condition. * @param predicate An async function to test each element for a condition. * @returns ``true`` if every element of the source sequence passes the test in the specified predicate, * or if the sequence is empty; otherwise, ``false``. */ allAsync(predicate: (x: TSource) => Promise<boolean>): Promise<boolean> /** * Determines whether a sequence contains any elements. * If predicate is specified, determines whether any element of a sequence satisfies a condition. * @param predicate A function to test each element for a condition. * @returns true if the source sequence contains any elements or passes the test specified; otherwise, false. */ any(predicate?: (x: TSource) => boolean): boolean /** * Determines whether any element of a sequence satisfies a condition. * @param predicate An async function to test each element for a condition. * @returns true if the source sequence contains any elements or passes the test specified; otherwise, false. */ anyAsync(predicate: (x: TSource) => Promise<boolean>): Promise<boolean> /** * Converts the iterable to an @see {IAsyncEnumerable} * @returns An IAsyncEnumerable<T> */ asAsync(): IAsyncEnumerable<TSource> /** * Converts an iterable to @see {IParallelEnumerable} * @returns An IParallelEnumerable<T> */ asParallel(): IParallelEnumerable<TSource> /** * Computes the average of a sequence of number values. * @throws {import('../types/InvalidOperationException')} source contains no elements. * @returns The average of the sequence of values. */ average(this: IEnumerable<number>): number /** * Computes the average of a sequence of values * that are obtained by invoking a transform function on each element of the input sequence. * @param selector A transform function to apply to each element. * @throws {import('../types/InvalidOperationException')} source contains no elements. * @returns The average of the sequence of values. */ average(selector: (x: TSource) => number): number /** * Computes the average of a sequence of values * that are obtained by invoking a transform function on each element of the input sequence. * @param selector An async transform function to apply to each element. * @throws {import('../types/InvalidOperationException')} source contains no elements. * @returns The average of the sequence of values. */ averageAsync(selector: (x: TSource) => Promise<number>): Promise<number> /** * Concatenates two sequences. * @param second The sequence to concatenate to the first sequence. * @returns An IEnumerable<T> that contains the concatenated elements of the two sequences. */ concatenate(second: IEnumerable<TSource>): IEnumerable<TSource> /** * Determines whether a sequence contains a specified element by * using the specified or default IEqualityComparer<T>. * @param value The value to locate in the sequence. * @param comparer An equality comparer to compare values. Optional. * @returns true if the source sequence contains an element that has the specified value; otherwise, false. */ contains(value: TSource, comparer?: IEqualityComparer<TSource>): boolean /** * Determines whether a sequence contains a specified element * by using the specified or default IEqualityComparer<T>. * @param value The value to locate in the sequence. * @param comparer An async equality comparer to compare values. * @returns true if the source sequence contains an element that has the specified value; otherwise, false. */ containsAsync(value: TSource, comparer: IAsyncEqualityComparer<TSource>): Promise<boolean> /** * Returns the number of elements in a sequence * or represents how many elements in the specified sequence satisfy a condition * if the predicate is specified. * @param predicate A function to test each element for a condition. Optional. * @returns The number of elements in the input sequence. */ count(predicate?: (x: TSource) => boolean): number /** * Returns the number of elements in a sequence * or represents how many elements in the specified sequence satisfy a condition * if the predicate is specified. * @param predicate A function to test each element for a condition. * @returns The number of elements in the input sequence. */ countAsync(predicate: (x: TSource) => Promise<boolean>): Promise<number> /** * Returns distinct elements from a sequence by using the default or specified equality comparer to compare values. * @param comparer An IEqualityComparer<T> to compare values. Optional. Defaults to Strict Equality Comparison. * @returns An IEnumerable<T> that contains distinct elements from the source sequence. */ distinct(comparer?: IEqualityComparer<TSource>): IEnumerable<TSource> /** * Returns distinct elements from a sequence by using the specified equality comparer to compare values. * @param comparer An IAsyncEqualityComparer<T> to compare values. * @returns An IAsyncEnumerable<T> that contains distinct elements from the source sequence. */ distinctAsync(comparer: IAsyncEqualityComparer<TSource>): IAsyncEnumerable<TSource> /** * Returns the element at a specified index in a sequence. * @param index The zero-based index of the element to retrieve. * @throws {import('../types/ArgumentOutOfRangeException')} * index is less than 0 or greater than or equal to the number of elements in source. * @returns The element at the specified position in the source sequence. */ elementAt(index: number): TSource /** * Returns the element at a specified index in a sequence or a default value if the index is out of range. * @param index The zero-based index of the element to retrieve. * @returns * null if the index is outside the bounds of the source sequence; * otherwise, the element at the specified position in the source sequence. */ elementAtOrDefault(index: number): TSource | null /** * Produces the set difference of two sequences by using the comparer provided * or EqualityComparer to compare values. * @param second An IEnumerable<T> whose elements that also occur in the first sequence * will cause those elements to be removed from the returned sequence. * @param comparer An IEqualityComparer<T> to compare values. Optional. * @returns A sequence that contains the set difference of the elements of two sequences. */ except(second: Iterable<TSource>, comparer?: IEqualityComparer<TSource>): IEnumerable<TSource> /** * Produces the set difference of two sequences by using the comparer provided to compare values. * @param second An IEnumerable<T> whose elements that also occur in the first sequence * will cause those elements to be removed from the returned sequence. * @param comparer An IAsyncEqualityComparer<T> to compare values. * @returns A sequence that contains the set difference of the elements of two sequences. */ exceptAsync(second: Iterable<TSource>, comparer: IAsyncEqualityComparer<TSource>): IAsyncEnumerable<TSource> /** * Returns first element in sequence that satisfies predicate otherwise * returns the first element in the sequence. * @param predicate A function to test each element for a condition. Optional. * @throws {import('../types/InvalidOperationException')} No elements in Iteration matching predicate * @returns The first element in the sequence * or the first element that passes the test in the specified predicate function. */ first(predicate?: (x: TSource) => boolean): TSource /** * Returns the first element in a sequence that satisfies a specified condition. * @param predicate A function to test each element for a condition. * @throws {import('../types/InvalidOperationException')} No elements in Iteration matching predicate * @returns The first element in the sequence that passes the test in the specified predicate function. */ firstAsync(predicate: (x: TSource) => Promise<boolean>): Promise<TSource> /** * Returns first element in sequence that satisfies predicate otherwise * returns the first element in the sequence. Returns null if no value found. * @param predicate A function to test each element for a condition. Optional. * @returns The first element in the sequence * or the first element that passes the test in the specified predicate function. * Returns null if no value found. */ firstOrDefault(predicate?: (x: TSource) => boolean): TSource | null /** * Returns the first element of the sequence that satisfies a condition or a default value * if no such element is found. * @param predicate An async function to test each element for a condition. * @returns null if source is empty or if no element passes the test specified by predicate; * otherwise, the first element in source that passes the test specified by predicate. */ firstOrDefaultAsync(predicate: (x: TSource) => Promise<boolean>): Promise<TSource | null> /** * Performs a specified action on each element of the Iterable<TSource> * @param action The action to take an each element * @returns A new IEnumerable<T> that executes the action lazily as you iterate. */ each(action: (x: TSource) => void): IEnumerable<TSource> /** * Performs a specified action on each element of the Iterable<TSource> * @param action The async action to take an each element * @returns A new IAsyncEnumerable<T> that executes the action lazily as you iterate. */ eachAsync(action: (x: TSource) => Promise<void>): IAsyncEnumerable<TSource> /** * Groups the elements of a sequence according to a specified key selector function. * @param keySelector A function to extract the key for each element. * @returns An IEnumerable<IGrouping<TKey, TSource>> * where each IGrouping<TKey,TElement> object contains a sequence of objects and a key. */ groupBy<TKey extends SelectorKeyType>( keySelector: (x: TSource) => TKey): IEnumerable<IGrouping<TKey, TSource>> /** * Groups the elements of a sequence according to a key selector function. * The keys are compared by using a comparer and each group's elements are projected by using a specified function. * @param keySelector A function to extract the key for each element. * @param comparer An IEqualityComparer<T> to compare keys. * @returns An IEnumerable<IGrouping<TKey, TSource>> * where each IGrouping<TKey,TElement> object contains a sequence of objects and a key. */ groupBy<TKey>( keySelector: (x: TSource) => TKey, comparer: IEqualityComparer<TKey>): IEnumerable<IGrouping<TKey, TSource>> /** * Groups the elements of a sequence according to a specified key selector function. * @param keySelector An async function to extract the key for each element. * @returns An IAsyncEnumerable<IGrouping<TKey, TSource>> * where each IGrouping<TKey,TElement> object contains a sequence of objects and a key. */ groupByAsync<TKey extends SelectorKeyType>( keySelector: (x: TSource) => Promise<TKey>): IAsyncEnumerable<IGrouping<TKey, TSource>> /** * Groups the elements of a sequence according to a specified key selector function. * @param keySelector A function to extract the key for each element. * @param comparer An IEqualityComparer<T> or IAsyncEqualityComparer<T> to compare keys. * @returns An IAsyncEnumerable<IGrouping<TKey, TSource>> * where each IGrouping<TKey,TElement> object contains a sequence of objects and a key. */ groupByAsync<TKey>( keySelector: (x: TSource) => Promise<TKey> | TKey, comparer: IEqualityComparer<TKey> | IAsyncEqualityComparer<TKey>) : IAsyncEnumerable<IGrouping<TKey, TSource>> /** * Groups the elements of a sequence according to a specified key selector function and * projects the elements for each group by using a specified function. * @param keySelector A function to extract the key for each element. * @param elementSelector A function to map each source element to an element in an IGrouping<TKey,TElement>. * @returns An IEnumerable<IGrouping<TKey, TElement>> * where each IGrouping<TKey,TElement> object contains a collection of objects of type TElement and a key. */ groupByWithSel<TElement, TKey extends SelectorKeyType>( keySelector: ((x: TSource) => TKey), elementSelector: (x: TSource) => TElement): IEnumerable<IGrouping<TKey, TElement>> /** * Groups the elements of a sequence according to a key selector function. * The keys are compared by using a comparer and each group's elements are projected by using a specified function. * @param keySelector A function to extract the key for each element. * @param elementSelector A function to map each source element to an element in an IGrouping<TKey,TElement>. * @param comparer An IEqualityComparer<T> to compare keys. * @returns An IEnumerable<IGrouping<TKey,TElement>> * where each IGrouping<TKey,TElement> object contains a collection of objects of type TElement and a key. */ groupByWithSel<TKey, TElement>( keySelector: ((x: TSource) => TKey), elementSelector: (x: TSource) => TElement, comparer: IEqualityComparer<TKey>): IEnumerable<IGrouping<TKey, TElement>> /** * Produces the set intersection of two sequences by using the specified IEqualityComparer<T> to compare values. * If no comparer is selected, uses the StrictEqualityComparer. * @param second An Iterable<T> whose distinct elements that also appear in the first sequence will be returned. * @param comparer An IEqualityComparer<T> to compare values. Optional. * @returns A sequence that contains the elements that form the set intersection of two sequences. */ intersect(second: IEnumerable<TSource>, comparer?: IEqualityComparer<TSource>): IEnumerable<TSource> /** * Produces the set intersection of two sequences by using the specified * IAsyncEqualityComparer<T> to compare values. * @param second An Iterable<T> whose distinct elements that also appear in the first sequence will be returned. * @param comparer An IAsyncEqualityComparer<T> to compare values. * @returns A sequence that contains the elements that form the set intersection of two sequences. */ intersectAsync( second: IEnumerable<TSource>, comparer: IAsyncEqualityComparer<TSource>): IAsyncEnumerable<TSource> /** * Correlates the elements of two sequences based on matching keys. * A specified IEqualityComparer<T> is used to compare keys or the strict equality comparer. * @param inner The sequence to join to the first sequence. * @param outerKeySelector A function to extract the join key from each element of the first sequence. * @param innerKeySelector A function to extract the join key from each element of the second sequence. * @param resultSelector A function to create a result element from two matching elements. * @param comparer An IEqualityComparer<T> to hash and compare keys. Optional. * @returns An IEnumerable<T> that has elements of type TResult that * are obtained by performing an inner join on two sequences. */ joinByKey<TInner, TKey, TResult>( inner: IEnumerable<TInner>, outerKeySelector: (x: TSource) => TKey, innerKeySelector: (x: TInner) => TKey, resultSelector: (x: TSource, y: TInner) => TResult, comparer?: IEqualityComparer<TKey>): IEnumerable<TResult> /** * Returns the last element of a sequence. * If predicate is specified, the last element of a sequence that satisfies a specified condition. * @param predicate A function to test each element for a condition. Optional. * @throws {import('../types/InvalidOperationException')} The source sequence is empty. * @returns The value at the last position in the source sequence * or the last element in the sequence that passes the test in the specified predicate function. */ last(predicate?: (x: TSource) => boolean): TSource /** * Returns the last element of a sequence that satisfies a specified condition. * @param predicate A function to test each element for a condition. * @throws {import('../types/InvalidOperationException')} The source sequence is empty. * @returns The last element in the sequence that passes the test in the specified predicate function. */ lastAsync(predicate: (x: TSource) => Promise<boolean>): Promise<TSource> /** * Returns the last element of a sequence. * If predicate is specified, the last element of a sequence that satisfies a specified condition. * @param predicate A function to test each element for a condition. Optional. * @returns The value at the last position in the source sequence * or the last element in the sequence that passes the test in the specified predicate function. */ lastOrDefault(predicate?: (x: TSource) => boolean): TSource | null /** * Returns the last element of a sequence that satisfies a specified condition. * @param predicate A function to test each element for a condition. * @returns The last element in the sequence that passes the test in the specified predicate function. * Null if no elements. */ lastOrDefaultAsync(predicate: (x: TSource) => Promise<boolean>): Promise<TSource | null> /** * Returns the maximum value in a sequence of values. * @throws {import('../types/InvalidOperationException')} source contains no elements. * @returns The maximum value in the sequence. */ max(this: IEnumerable<number>): number /** * Invokes a transform function on each element of a sequence and returns the maximum value. * @param selector A transform function to apply to each element. * @throws {import('../types/InvalidOperationException')} source contains no elements. * @returns The maximum value in the sequence. */ max(selector: (x: TSource) => number): number /** * Invokes an async transform function on each element of a sequence and returns the maximum value. * @param selector A transform function to apply to each element. * @throws {import('../types/InvalidOperationException')} source contains no elements. * @returns The maximum value in the sequence. */ maxAsync(selector: (x: TSource) => Promise<number>): Promise<number> /** * Returns the minimum value in a sequence of values. * @throws {import('../types/InvalidOperationException')} source contains no elements. * @returns The minimum value in the sequence. */ min(this: IEnumerable<number>): number /** * Invokes a transform function on each element of a sequence and returns the minimum value. * @param selector A transform function to apply to each element. * @throws {import('../types/InvalidOperationException')} source contains no elements. * @returns The minimum value in the sequence. */ min(selector: (x: TSource) => number): number /** * Invokes a transform function on each element of a sequence and returns the minimum value. * @param selector A transform function to apply to each element. * @throws {import('../types/InvalidOperationException')} source contains no elements. * @returns The minimum value in the sequence. */ minAsync(selector: (x: TSource) => Promise<number>): Promise<number> /** * Applies a type filter to a source iteration * @param type Either value for typeof or a consturctor function * @returns Values that match the type string or are instance of type */ ofType<T extends OfType>(type: T): IEnumerable<InferType<T>> /** * Sorts the elements of a sequence in ascending order by using a specified or default comparer. * @param keySelector A function to extract a key from an element. * @param comparer An IComparer<T> to compare keys. Optional. * @returns An IOrderedEnumerable<TElement> whose elements are sorted according to a key. */ orderBy<TKey>( predicate: (x: TSource) => TKey, comparer?: IComparer<TKey>): IOrderedEnumerable<TSource> /** * Sorts the elements of a sequence in ascending order by using a specified comparer. * @param keySelector An async function to extract a key from an element. * @param comparer An IComparer<T> to compare keys. * @returns An IOrderedAsyncEnumerable<TElement> whose elements are sorted according to a key. */ orderByAsync<TKey>( predicate: (x: TSource) => Promise<TKey>, comparer?: IComparer<TKey>): IOrderedAsyncEnumerable<TSource> /** * Sorts the elements of a sequence in descending order by using a specified or default comparer. * @param keySelector A function to extract a key from an element. * @param comparer An IComparer<T> to compare keys. Optional. * @returns An IOrderedEnumerable<TElement> whose elements are sorted in descending order according to a key. */ orderByDescending<TKey>( predicate: (x: TSource) => TKey, comparer?: IComparer<TKey>): IOrderedEnumerable<TSource> /** * Sorts the elements of a sequence in descending order by using a specified comparer. * @param keySelector An async function to extract a key from an element. * @param comparer An IComparer<T> to compare keys. * @returns An IOrderedAsyncEnumerable<TElement> whose elements are sorted in descending order according to a key. */ orderByDescendingAsync<TKey>( predicate: (x: TSource) => Promise<TKey>, comparer?: IComparer<TKey>): IOrderedAsyncEnumerable<TSource> /** * Partitions the values into a tuple of failing and passing arrays * @param predicate Predicate to determine whether a value passes or fails * @returns [values that pass, values that fail] */ partition(predicate: (x: TSource) => boolean): [pass: TSource[], fail: TSource[]] /** * Partitions the values into a tuple of failing and passing arrays * @param predicate Predicate to determine whether a value passes or fails * @returns [values that pass, values that fail] */ partitionAsync(predicate: (x: TSource) => Promise<boolean>): Promise<[pass: TSource[], fail: TSource[]]> /** * Inverts the order of the elements in a sequence. * @returns A sequence whose elements correspond to those of the input sequence in reverse order. */ reverse(): IEnumerable<TSource> /** * Projects each element of a sequence into a new form. * @param selector A transform function to apply to each element. * @returns * An IEnumerable<T> whose elements are the result of invoking the transform function on each element of source. */ select<TResult>(selector: (x: TSource, index: number) => TResult): IEnumerable<TResult> /** * Projects each element of a sequence into a new form. * @param selector A key of TSource. * @returns * An IEnumerable<T> whose elements are the result of getting the value from the key on each element of source. */ select<TKey extends keyof TSource>(key: TKey): IEnumerable<TSource[TKey]> /** * Projects each element of a sequence into a new form. * @param selector An async transform function to apply to each element. * @returns An IAsyncEnumerable<T> whose elements are the result of invoking * the transform function on each element of source. */ selectAsync<TResult>(selector: (x: TSource, index: number) => Promise<TResult>): IAsyncEnumerable<TResult> /** * Projects each element of a sequence into a new form. * @param key A key of the elements in the sequence * @returns An IAsyncEnumerable<T> whoe elements are the result of getting the value for key * on each element of source. */ selectAsync<TKey extends keyof TSource, TResult>( this: IEnumerable<{ [key: string]: Promise<TResult> }>, key: TKey): IAsyncEnumerable<TResult> /** * Projects each element of a sequence to an IEnumerable<T> and flattens the resulting sequences into one sequence. * @param selector A transform function to apply to each element. * @returns An IEnumerable<T> whose elements are the result of invoking the * one-to-many transform function on each element of the input sequence. */ selectMany<TResult>(selector: (x: TSource, index: number) => Iterable<TResult>): IEnumerable<TResult> /** * Projects each element of a sequence to an IEnumerable<T> and flattens the resulting sequences into one sequence. * @param selector A string key of TSource. * @returns An IEnumerable<T> whose elements are the result of invoking the * parameter the key is tried to on each element of the input sequence. */ selectMany<TBindedSource extends { [key: string]: Iterable<TOut>}, TOut>( this: IEnumerable<TBindedSource>, selector: keyof TBindedSource): IEnumerable<TOut> /** * Projects each element of a sequence to an IAsyncEnumerable<T> * and flattens the resulting sequences into one sequence. * @param selector A transform function to apply to each element. * @returns An IAsyncEnumerable<T> whose elements are the result of invoking the * one-to-many transform function on each element of the input sequence. */ selectManyAsync<TResult>( selector: (x: TSource, index: number) => Promise<Iterable<TResult>>): IAsyncEnumerable<TResult> /** * Determines whether or not two sequences are equal * @param second second iterable * @param comparer Compare function to use, by default is @see {StrictEqualityComparer} * @returns Whether or not the two iterations are equal */ sequenceEquals(second: IEnumerable<TSource>, comparer?: IEqualityComparer<TSource>): boolean /** * Compares two sequences to see if they are equal using an async comparer function. * @param second Second Sequence * @param comparer Async Comparer * @returns Whether or not the two iterations are equal */ sequenceEqualsAsync(second: IEnumerable<TSource>, comparer: IAsyncEqualityComparer<TSource>): Promise<boolean> /** * Returns the only element of a sequence that satisfies a specified condition (if specified), * and throws an exception if more than one such element exists. * @param predicate A function to test an element for a condition. (Optional) * @throws {import('../types/InvalidOperationException')} No element satisfies the condition in predicate. OR * More than one element satisfies the condition in predicate. OR * The source sequence is empty. * @returns The single element of the input sequence that satisfies a condition. */ single(predicate?: (x: TSource) => boolean): TSource /** * Returns the only element of a sequence that satisfies a specified condition, * and throws an exception if more than one such element exists. * @param predicate A function to test an element for a condition. * @throws {import('../types/InvalidOperationException')} * No element satisfies the condition in predicate. OR * More than one element satisfies the condition in predicate. OR * The source sequence is empty. * @returns The single element of the input sequence that satisfies a condition. */ singleAsync(predicate: (x: TSource) => Promise<boolean>): Promise<TSource> /** * If predicate is specified returns the only element of a sequence that satisfies a specified condition, * ootherwise returns the only element of a sequence. Returns a default value if no such element exists. * @param predicate A function to test an element for a condition. Optional. * @throws {import('../types/InvalidOperationException')} * If predicate is specified more than one element satisfies the condition in predicate, * otherwise the input sequence contains more than one element. * @returns The single element of the input sequence that satisfies the condition, * or null if no such element is found. */ singleOrDefault(predicate?: (x: TSource) => boolean): TSource | null /** * Returns the only element of a sequence that satisfies a specified condition. * Returns a default value if no such element exists. * @param predicate A function to test an element for a condition. Optional. * @throws {import('../types/InvalidOperationException')} * If predicate is specified more than one element satisfies the condition in predicate, * otherwise the input sequence contains more than one element. * @returns The single element of the input sequence that satisfies the condition, * or null if no such element is found. */ singleOrDefaultAsync(predicate: (x: TSource) => Promise<boolean>): Promise<TSource | null> /** * Bypasses a specified number of elements in a sequence and then returns the remaining elements. * @param count The number of elements to skip before returning the remaining elements. * @returns An IEnumerable<T> that contains the elements that occur after the specified index in the input sequence. */ skip(count: number): IEnumerable<TSource> /** * Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * @param predicate A function to test each source element for a condition; * the second parameter of the function represents the index of the source element. * @returns An IEnumerable<T> that contains the elements from the input sequence starting at the first element * in the linear series that does not pass the test specified by predicate. */ skipWhile(predicate: (x: TSource, index: number) => boolean): IEnumerable<TSource> /** * Bypasses elements in a sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * @param predicate A function to test each source element for a condition; * the second parameter of the function represents the index of the source element. * @returns An IAsyncEnumerable<T> that contains the elements from the input sequence starting * at the first element in the linear series that does not pass the test specified by predicate. */ skipWhileAsync(predicate: (x: TSource, index: number) => Promise<boolean>): IAsyncEnumerable<TSource> /** * Computes the sum of the sequence of numeric values. * @returns The sum of the values in the sequence. */ sum(this: IEnumerable<number>): number /** * Computes the sum of the sequence of numeric values that are obtained by invoking a transform function * on each element of the input sequence. * @param selector A transform function to apply to each element. * @returns The sum of the projected values. */ sum(selector: (x: TSource) => number): number /** * Computes the sum of the sequence of numeric values that are obtained by invoking a transform function * on each element of the input sequence. * @param selector An async transform function to apply to each element. * @returns The sum of the projected values. */ sumAsync(selector: (x: TSource) => Promise<number>): Promise<number> /** * Returns a specified number of contiguous elements from the start of a sequence. * @param amount The number of elements to return. * @returns An IEnumerable<T> that contains the specified number of elements from the start of the input sequence. */ take(amount: number): IEnumerable<TSource> /** * Returns elements from a sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param predicate A function to test each source element for a condition; * the second parameter of the function represents the index of the source element. * @returns An IEnumerable<T> that contains elements from the input sequence * that occur before the element at which the test no longer passes. */ takeWhile(predicate: (x: TSource, index: number) => boolean): IEnumerable<TSource> /** * Returns elements from a sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param predicate A async function to test each source element for a condition; * the second parameter of the function represents the index of the source element. * @returns An IAsyncEnumerable<T> that contains elements from the input sequence * that occur before the element at which the test no longer passes. */ takeWhileAsync(predicate: (x: TSource, index: number) => Promise<boolean>): IAsyncEnumerable<TSource> /** * Creates an array from a IEnumerable<T>. * @returns An array of elements */ toArray(): TSource[] /** * Converts an Iterable<V> to a Map<K, V[]>. * @param selector A function to serve as a key selector. * @returns Map<K, V[]> */ toMap<TKey>(selector: (x: TSource) => TKey): Map<TKey, TSource[]> /** * Converts an Iterable<V> to a Map<K, V[]>. * @param selector An async function to serve as a key selector. * @returns A promise for Map<K, V[]> */ toMapAsync<TKey>(selector: (x: TSource) => Promise<TKey>): Promise<Map<TKey, TSource[]>> /** * Converts the Iteration to an Object. Duplicate values will be overriden. * @param selector A function to determine the Key based on the value. * @returns KVP Object */ toObject<TKey extends keyof any>(selector: (x: TSource) => TKey): Record<TKey, TSource> /** * Converts the Iteration to an Object. Duplicate values will be overriden. * @param selector An async function to determine the Key based on the value. * @returns KVP Object */ toObjectAsync<TKey extends keyof any>(selector: (x: TSource) => Promise<TKey>): Promise<Record<TKey, TSource>> /** * Converts the iteration to a Set * @returns Set containing the iteration values */ toSet(): Set<TSource> /** * Produces the set union of two sequences by using scrict equality comparison or a specified IEqualityComparer<T>. * @param second An Iterable<T> whose distinct elements form the second set for the union. * @param comparer The IEqualityComparer<T> to compare values. Optional. * @returns An IEnumerable<T> that contains the elements from both input sequences, excluding duplicates. */ union(second: Iterable<TSource>, comparer?: IEqualityComparer<TSource>): IEnumerable<TSource> /** * Produces the set union of two sequences by using a specified IAsyncEqualityComparer<T>. * @param second An Iterable<T> whose distinct elements form the second set for the union. * @param comparer The IAsyncEqualityComparer<T> to compare values. * @returns An IAsyncEnumerable<T> that contains the elements from both input sequences, excluding duplicates. */ unionAsync(second: Iterable<TSource>, comparer: IAsyncEqualityComparer<TSource>): IAsyncEnumerable<TSource> /** * Filters a sequence of values based on a predicate. * Each element's index is used in the logic of the predicate function. * @param predicate A function to test each source element for a condition; * the second parameter of the function represents the index of the source element. * @returns An IEnumerable<T> that contains elements from the input sequence that satisfy the condition. */ where(predicate: (x: TSource, index: number) => boolean): IEnumerable<TSource> /** * Filters a sequence of values based on a predicate. * Each element's index is used in the logic of the predicate function. * @param predicate A async function to test each source element for a condition; * the second parameter of the function represents the index of the source element. * @returns An IAsyncEnumerable<T> that contains elements from the input sequence that satisfy the condition. */ whereAsync(predicate: (x: TSource, index: number) => Promise<boolean>): IAsyncEnumerable<TSource> /** * Creates a tuple of corresponding elements of two sequences, producing a sequence of the results. * @param second The second sequence to merge. * @returns An IEnumerable<[T, Y]> that contains merged elements of two input sequences. */ zip<TSecond>(second: Iterable<TSecond>): IEnumerable<[TSource, TSecond]> /** * Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results. * @param second The second sequence to merge. * @param resultSelector A function that specifies how to merge the elements from the two sequences. * @returns An IEnumerable<TResult> that contains merged elements of two input sequences. */ zip<TSecond, TResult>( second: Iterable<TSecond>, resultSelector: (x: TSource, y: TSecond) => TResult): IEnumerable<TResult> /** * Applies a specified async function to the corresponding elements of two sequences, * producing a sequence of the results. * @param second The second sequence to merge. * @param resultSelector An async function that specifies how to merge the elements from the two sequences. * @returns An IAsyncEnumerable<T> that contains merged elements of two input sequences. */ zipAsync<TSecond, TResult>( second: Iterable<TSecond>, resultSelector: (x: TSource, y: TSecond) => Promise<TResult>): IAsyncEnumerable<TResult> [Symbol.iterator](): IterableIterator<TSource> }
the_stack
import {initializeLayerFromSpecShowErrorStatus, LayerListSpecification, ManagedUserLayer} from 'neuroglancer/layer'; import {popDragStatus, pushDragStatus} from 'neuroglancer/ui/drag_and_drop'; import {Borrowed, Owned} from 'neuroglancer/util/disposable'; import {decodeParametersFromDragTypeList, DragInfo, encodeParametersAsDragType, getDropEffect, setDropEffect} from 'neuroglancer/util/drag_and_drop'; import {parseArray, verifyBoolean, verifyObjectProperty, verifyString} from 'neuroglancer/util/json'; const layerDragTypePrefix = 'neuroglancer-layer\0'; export interface LayerDragSourceInfo { manager: Owned<LayerListSpecification>; layers: Owned<ManagedUserLayer>[]; layoutSpec: any; isLayerListPanel?: boolean; } interface LayerDragSourceData extends LayerDragSourceInfo { isLayerListPanel: boolean; disposer: () => void; } let dragSource: LayerDragSourceData|undefined; export function startLayerDrag(event: DragEvent, sourceInfo: LayerDragSourceInfo) { event.dataTransfer!.setData( encodeParametersAsDragType( layerDragTypePrefix, sourceInfo.layers.map(layer => ({name: layer.name, visible: layer.visible}))), JSON.stringify( {layers: sourceInfo.layers.map(layer => layer.toJSON()), layout: sourceInfo.layoutSpec})); if (dragSource !== undefined) { dragSource.disposer(); } let newDragSource: LayerDragSourceData; let disposer = () => { sourceInfo.manager.unregisterDisposer(disposer); for (const layer of sourceInfo.layers) { layer.dispose(); } sourceInfo.manager.dispose(); if (dragSource === newDragSource) { dragSource = undefined; } }; dragSource = newDragSource = { manager: sourceInfo.manager.addRef(), layers: sourceInfo.layers.map(x => x.addRef()), layoutSpec: sourceInfo.layoutSpec, isLayerListPanel: sourceInfo.isLayerListPanel ?? false, disposer, }; } export function endLayerDrag(dropEffect: string = 'none') { if (dragSource !== undefined) { if (dropEffect === 'move') { // Remove source layers since they have been moved. const removedLayers = new Set(dragSource.layers); dragSource.manager.layerManager.filter((x: ManagedUserLayer) => !removedLayers.has(x)); } dragSource.disposer(); } } export function getLayerDragInfo(event: DragEvent): DragInfo|undefined { return decodeParametersFromDragTypeList(event.dataTransfer!.types, layerDragTypePrefix); } function getCompatibleDragSource(manager: Borrowed<LayerListSpecification>): LayerDragSourceData| undefined { if (dragSource !== undefined && dragSource.manager.rootLayers === manager.rootLayers) { return dragSource; } return undefined; } export class DropLayers { // If the layers are from another window, this set to the drag type (starting with // `layerDragTypePrefix`) that encodes the layer names and visible state. If the layers // are from this same Neuroglancer instance, set to undefined. dragType: string|undefined; targetIsLayerListPanel: boolean; sourceManager: Borrowed<LayerListSpecification>|undefined; sourceIsLayerListPanel: boolean; moveSupported: boolean; forceCopy: boolean; manager: Borrowed<LayerListSpecification>; // Maps each layer to its index in the specification. layers: Map<Owned<ManagedUserLayer>, number>; numSourceLayers: number; // LayerGroupViewer layout specification associated with these layers. Only used if the drop // operation creates a new layer group viewer. layoutSpec: any; /** * Called in the 'drop' event handler to actually initialize the layers if they are external. * Returns false if any layers failed to initialized. */ initializeExternalLayers(event: DragEvent): boolean { const {dragType} = this; if (dragType !== undefined) { try { const {layers: spec, layout} = JSON.parse(event.dataTransfer!.getData(dragType)); if (!Array.isArray(spec) || this.numSourceLayers !== spec.length) { throw new Error('Invalid layer drop data'); } this.layoutSpec = layout; for (const [layer, index] of this.layers) { initializeLayerFromSpecShowErrorStatus(layer, spec[index]); } } catch { return false; } } return true; } updateArchiveStates(event: DragEvent) { // If archived === false (i.e. drop target is a layer bar or new layer group location), set // all layers as non-archived, since those drop targets can only contain non-archived layers. // // If archived === true, drop target is the layer list panel. If the layer would not be // logically present in any layer groups, set it to archived. const {targetIsLayerListPanel} = this; const dropEffect = event.dataTransfer!.dropEffect; for (const layer of this.layers.keys()) { let shouldBeArchived = targetIsLayerListPanel; if (targetIsLayerListPanel && !layer.archived && dropEffect !== 'copy') { if (this.sourceIsLayerListPanel) { shouldBeArchived = false; } } if (layer.archived !== shouldBeArchived || (shouldBeArchived && layer.visible)) { layer.archived = shouldBeArchived; if (shouldBeArchived) layer.visible = false; layer.layerChanged.dispatch(); } } } get method() { if (this.sourceManager !== undefined) { if (this.manager === this.sourceManager && (this.sourceIsLayerListPanel === this.targetIsLayerListPanel)) { return 'move'; } else { return 'link'; } } else { return 'copy'; } } compatibleWithMethod(otherMethod: string) { if (this.method === otherMethod) { return true; } if (this.forceCopy && otherMethod !== 'copy') { return false; } if (!this.moveSupported && otherMethod === 'move') { return true; } return false; } } type LayerDropEffect = 'none'| 'move'|'copy'|'link'; export function getDropEffectFromModifiers<DropEffect extends string>( event: DragEvent, defaultDropEffect: DropEffect, moveAllowed: boolean): {dropEffect: DropEffect|'move'|'copy', dropEffectMessage: string} { let dropEffect: DropEffect | 'move'|'copy'; if (event.shiftKey) { dropEffect = 'copy'; } else if (event.ctrlKey && moveAllowed) { dropEffect = 'move'; } else { dropEffect = defaultDropEffect; } let message = ''; const addMessage = (msg: string) => { if (message !== '') { message += ', '; } message += msg; }; if (defaultDropEffect !== 'none' && dropEffect !== defaultDropEffect) { if (event.shiftKey) { addMessage(`release SHIFT to ${defaultDropEffect}`); } else { addMessage(`release CONTROL to ${defaultDropEffect}`); } } if (dropEffect !== 'copy') { addMessage('hold SHIFT to copy'); } if (dropEffect !== 'move' && moveAllowed && defaultDropEffect !== 'move') { addMessage('hold CONTROL to move'); } return {dropEffect, dropEffectMessage: message}; } export function getLayerDropEffect( event: DragEvent, manager: Borrowed<LayerListSpecification>, targetIsLayerListPanel: boolean, newTarget: boolean): {dropEffect: LayerDropEffect, dropEffectMessage: string} { const source = getCompatibleDragSource(manager); let moveAllowed = false; let defaultDropEffect:LayerDropEffect; if (source === undefined) { defaultDropEffect = 'copy'; } else { if (newTarget) { // We cannot "move" layers out of the layer list panel. if (!source.isLayerListPanel) { moveAllowed = true; } defaultDropEffect = 'link'; } else { if (source.manager === manager && source.isLayerListPanel === targetIsLayerListPanel) { defaultDropEffect = 'move'; moveAllowed = true; } else if (targetIsLayerListPanel) { defaultDropEffect = 'none'; } else if (source.isLayerListPanel) { defaultDropEffect = 'link'; } else { moveAllowed = true; defaultDropEffect = 'link'; } } } return getDropEffectFromModifiers(event, defaultDropEffect, moveAllowed); } export function updateLayerDropEffect( event: DragEvent, manager: Borrowed<LayerListSpecification>, targetIsLayerListPanel: boolean, newTarget: boolean): {dropEffect: LayerDropEffect, dropEffectMessage: string} { const result = getLayerDropEffect(event, manager, targetIsLayerListPanel, newTarget); setDropEffect(event, result.dropEffect); return result; } export interface GetDropLayersOptions { // Indicates that the user specifically requested copying. This ensures that a copy-compatible // DropLayers object will be returned. forceCopy: boolean; // Indicates that the `manager` is not the actual target, but instead a new layer group will be // created to hold the dropped layers. newTarget: boolean; // Indicates that the target is the layer list panel. New layers that are dropped will be // archived. isLayerListPanel?: boolean; } export function getDropLayers( event: DragEvent, manager: Borrowed<LayerListSpecification>, options: GetDropLayersOptions): DropLayers|undefined { const {forceCopy, newTarget, isLayerListPanel = false} = options; const source = getCompatibleDragSource(manager); if (!forceCopy && source !== undefined) { const moveSupported = !newTarget && source.manager === manager && (source.isLayerListPanel === isLayerListPanel || source.isLayerListPanel); const result = new DropLayers(); result.manager = manager; result.numSourceLayers = source.layers.length; result.sourceManager = source.manager; result.targetIsLayerListPanel = isLayerListPanel; result.sourceIsLayerListPanel = source.isLayerListPanel; result.moveSupported = moveSupported; result.layers = new Map(); result.forceCopy = false; result.layoutSpec = source.layoutSpec; if (moveSupported) { source.layers.forEach((layer, index) => { result.layers.set(layer, index); }); } else { source.layers.forEach((layer, index) => { if (newTarget || !manager.layerManager.has(layer)) { result.layers.set(layer.addRef(), index); } }); } return result; } const info = getLayerDragInfo(event); if (info !== undefined) { try { const layers = parseArray(info.parameters, (layerInfo, index) => { const name = verifyObjectProperty(layerInfo, 'name', verifyString); let visible = verifyObjectProperty(layerInfo, 'visible', verifyBoolean); const newLayer = new ManagedUserLayer(name, manager); if (isLayerListPanel) visible = false; newLayer.visible = visible; newLayer.archived = isLayerListPanel; return [newLayer, index] as [ManagedUserLayer, number]; }); const result = new DropLayers(); result.numSourceLayers = layers.length; result.targetIsLayerListPanel = isLayerListPanel; result.sourceIsLayerListPanel = false; result.sourceManager = undefined; result.moveSupported = false; result.forceCopy = source !== undefined; result.manager = manager; result.dragType = info.dragType; result.layers = new Map(layers); return result; } catch { } } return undefined; } function destroyDropLayers(dropLayers: DropLayers, targetLayer?: ManagedUserLayer) { if (dropLayers.moveSupported) { // Nothing to do. return false; } dropLayers.manager.layerManager.filter(layer => !dropLayers.layers.has(layer)); return targetLayer !== undefined && dropLayers.layers.has(targetLayer); } export interface LayerBarDropInterface { element: HTMLElement; manager: LayerListSpecification; dropLayers: DropLayers|undefined; dragEnterCount: number; } export function registerLayerBarDropHandlers( panel: LayerBarDropInterface, target: EventTarget, targetLayer: ManagedUserLayer|undefined, isLayerListPanel = false) { function update(event: DragEvent, updateDropEffect: boolean): {dropLayers: DropLayers, dropEffect: LayerDropEffect, dropEffectMessage: string}|undefined { let dropLayers = panel.dropLayers; const {dropEffect, dropEffectMessage} = updateDropEffect ? getLayerDropEffect(event, panel.manager, isLayerListPanel, /*newTarget=*/ false) : {dropEffect: getDropEffect() as LayerDropEffect, dropEffectMessage: ''}; if (dropEffect === undefined) return undefined; setDropEffect(event, dropEffect); let existingDropLayers = true; if (dropLayers !== undefined) { if (!dropLayers.compatibleWithMethod(dropEffect)) { panel.dropLayers = undefined; if (destroyDropLayers(dropLayers, targetLayer)) { // We destroyed the layer for which we received the dragenter event. Wait until we get // another dragenter or drop event to do something. return undefined; } } } if (dropLayers === undefined) { dropLayers = panel.dropLayers = getDropLayers( event, panel.manager, {forceCopy: dropEffect === 'copy', newTarget: false, isLayerListPanel}); if (dropLayers === undefined) { return undefined; } existingDropLayers = dropLayers.method === 'move'; } if (targetLayer !== undefined && dropLayers.layers.has(targetLayer)) { // Dragged onto itself, nothing to do. return {dropLayers, dropEffect, dropEffectMessage}; } if (!existingDropLayers) { let newIndex: number|undefined; if (targetLayer !== undefined) { newIndex = panel.manager.layerManager.managedLayers.indexOf(targetLayer); } for (const newLayer of dropLayers.layers.keys()) { panel.manager.add(newLayer, newIndex); } } else { // Rearrange layers. const {layerManager} = panel.manager; const existingLayers = new Set<ManagedUserLayer>(); let firstRemovalIndex = Number.POSITIVE_INFINITY; const managedLayers = layerManager.managedLayers = layerManager.managedLayers.filter((x: ManagedUserLayer, index) => { if (dropLayers!.layers.has(x)) { if (firstRemovalIndex === Number.POSITIVE_INFINITY) { firstRemovalIndex = index; } existingLayers.add(x); return false; } else { return true; } }); let newIndex: number; if (targetLayer !== undefined) { newIndex = managedLayers.indexOf(targetLayer); if (firstRemovalIndex <= newIndex) { ++newIndex; } } else { newIndex = managedLayers.length; } // Filter out layers that have been concurrently removed. for (const layer of dropLayers.layers.keys()) { if (!existingLayers.has(layer)) { dropLayers.layers.delete(layer); } } managedLayers.splice(newIndex, 0, ...dropLayers.layers.keys()); layerManager.layersChanged.dispatch(); } return {dropLayers,dropEffect,dropEffectMessage}; } target.addEventListener('dragenter', (event: DragEvent) => { if (update(event, /*updateDropEffect=*/ true) !== undefined) { event.preventDefault(); } else { popDragStatus(panel.element, 'drop'); } }); target.addEventListener('drop', (event: DragEvent) => { event.preventDefault(); panel.dragEnterCount = 0; popDragStatus(panel.element, 'drop'); const dropLayers = update(event, /*updateDropEffect=*/ false)?.dropLayers; panel.dropLayers = undefined; if (dropLayers === undefined) return; if (!dropLayers.initializeExternalLayers(event)) { destroyDropLayers(dropLayers); return; } dropLayers.updateArchiveStates(event); endLayerDrag(dropLayers.method === 'move' ? undefined : event.dataTransfer!.dropEffect); }); target.addEventListener('dragover', (event: DragEvent) => { const updateResult = update(event, /*updateDropEffect=*/ true); if (updateResult === undefined) { popDragStatus(panel.element, 'drop'); return; } const {dropLayers, dropEffect, dropEffectMessage} = updateResult; const numLayers = dropLayers.layers.size; let message = ''; const maybePlural = dropLayers.numSourceLayers === 1 ? '' : 's'; const numSourceLayers = dropLayers.numSourceLayers; if (dropEffect === 'none') { message = `Cannot link dragged layer${maybePlural} here`; } else { const layerCountMessage = numSourceLayers === numLayers ? `${numSourceLayers}` : `${numLayers}/${numSourceLayers}`; message = `Drop to ${dropEffect} ${layerCountMessage} layer${maybePlural}` } if (dropEffectMessage) { message += ` (${dropEffectMessage})`; } pushDragStatus(panel.element, 'drop', message); event.preventDefault(); event.stopPropagation(); }); } export function registerLayerDragHandlers( panel: LayerBarDropInterface, element: HTMLElement, layer: ManagedUserLayer, options: {getLayoutSpec: () => any, isLayerListPanel?: boolean}) { element.draggable = true; element.addEventListener('dragstart', (event: DragEvent) => { pushDragStatus( element, 'drag', 'Drag layer to another layer bar/panel (including in another Neuroglancer window), ' + 'or to the left/top/right/bottom edge of a layer group'); startLayerDrag(event, { manager: panel.manager, layers: [layer], layoutSpec: options.getLayoutSpec(), isLayerListPanel: options.isLayerListPanel }); event.stopPropagation(); }); element.addEventListener('dragend', () => { popDragStatus(element, 'drag'); // This call to endLayerDrag is a no-op if a drag was completed successfully within the same // browser window, because it will already have been called by the `drop` handler. This call // has an effect only for a cancelled drag or a successful cross-browser window drag. // Cross-browser window drags are always `copy` operations because Chrome does not properly // communicate the drag effect, so there is no way to signal a `move`. // // https://bugs.chromium.org/p/chromium/issues/detail?id=39399 endLayerDrag(); }); } export function registerLayerBarDragLeaveHandler(panel: LayerBarDropInterface) { panel.element.addEventListener('dragenter', () => { ++panel.dragEnterCount; }); panel.element.addEventListener('dragleave', () => { if (--panel.dragEnterCount !== 0) return; popDragStatus(panel.element, 'drop'); const {dropLayers} = panel; if (dropLayers !== undefined) { destroyDropLayers(dropLayers); panel.manager.layerManager.layersChanged.dispatch(); panel.dropLayers = undefined; } }); }
the_stack
import omit from 'lodash/omit' import mapValues from 'lodash/mapValues' import each from 'lodash/each' import oldProtocol from '../../../../fixtures/protocol/1/doItAll.json' import { renameOrderedSteps, addInitialDeckSetupStep, INITIAL_DECK_SETUP_STEP_ID, updateStepFormKeys, TCD_DEPRECATED_FIELD_NAMES, MIX_DEPRECATED_FIELD_NAMES, replaceTCDStepsWithMoveLiquidStep, } from '../1_1_0' describe('renameOrderedSteps', () => { // @ts-expect-error incorrect paramater type, should be PDProtocolFile type const migratedFile = renameOrderedSteps(oldProtocol) it('removes orderedSteps key', () => { expect(oldProtocol['designer-application'].data.orderedSteps).not.toEqual( undefined ) // @ts-expect-error orderedSteps doesn't exist on type PDMetaData expect(migratedFile['designer-application'].data.orderedSteps).toEqual( undefined ) }) it('adds orderedStepIds key and value', () => { const oldOrderedStepsIds = oldProtocol['designer-application'].data.orderedSteps // @ts-expect-error orderedSteps doesn't exist on type expect(oldProtocol['designer-application'].data.orderedStepIds).toEqual( undefined ) expect(migratedFile['designer-application'].data.orderedStepIds).toEqual( oldOrderedStepsIds ) }) it('the rest of file should be unaltered', () => { const oldWithout = { ...oldProtocol, 'designer-application': { ...oldProtocol['designer-application'], data: omit(oldProtocol['designer-application'].data, [ 'orderedSteps', 'orderedStepIds', ]), }, } const migratedWithout = { ...migratedFile, 'designer-application': { ...migratedFile['designer-application'], data: omit(migratedFile['designer-application'].data, [ 'orderedStepIds', 'orderedSteps', ]), }, } expect(oldWithout).toEqual(migratedWithout) }) }) describe('addInitialDeckSetupStep', () => { // @ts-expect-error oldProtocol not of type PDProtocolFile const migratedFile = addInitialDeckSetupStep(oldProtocol) it('adds savedStepForm key', () => { expect( // @ts-expect-error INITIAL_DECK_SETUP_STEP_ID does not exist on type oldProtocol['designer-application'].data.savedStepForms[ INITIAL_DECK_SETUP_STEP_ID ] ).toEqual(undefined) expect( migratedFile['designer-application'].data.savedStepForms[ INITIAL_DECK_SETUP_STEP_ID ] ).not.toEqual(undefined) }) describe('adds well formed savedStepForm value', () => { const wellFormedSetupStep = { stepType: 'manualIntervention', id: INITIAL_DECK_SETUP_STEP_ID, labwareLocationUpdate: { trashId: '12', }, pipetteLocationUpdate: {}, } const deckSetupStepForm = migratedFile['designer-application'].data.savedStepForms[ INITIAL_DECK_SETUP_STEP_ID ] it('is correct stepType', () => { expect(deckSetupStepForm.stepType).toEqual(wellFormedSetupStep.stepType) }) it('has correct id value', () => { expect(deckSetupStepForm.id).toEqual(wellFormedSetupStep.id) }) it('constructs labware location update object', () => { expect(deckSetupStepForm.labwareLocationUpdate).toEqual({ ...wellFormedSetupStep.labwareLocationUpdate, ...mapValues(oldProtocol.labware, l => l.slot), }) }) it('constructs pipette location update object', () => { expect(deckSetupStepForm.pipetteLocationUpdate).toEqual({ ...wellFormedSetupStep.pipetteLocationUpdate, ...mapValues(oldProtocol.pipettes, p => p.mount), }) }) }) }) describe('updateStepFormKeys', () => { describe('for TCD stepTypes', () => { const stubbedTCDStepsFile = { 'designer-application': { data: { savedStepForms: { 1: { id: 1, stepType: 'distribute', 'step-name': 'FakeStepName', 'step-details': 'fake details', aspirate_disposalVol_checkbox: true, aspirate_disposalVol_volume: 60, aspirate_changeTip: 'always', aspirate_preWetTip: true, aspirate_touchTip: true, aspirate_touchTipMmFromBottom: 20, dispense_touchTip: true, dispense_touchTipMmFromBottom: 22, dispense_blowout_checkbox: true, dispense_blowout_labware: 'trashId', dispense_blowout_location: 'trashId', aspirate_labware: 'db17bed0-2b08-11e9-9054-4913062421c2:trough-12row', aspirate_wells: ['A12'], pipette: 'pipette:p300_multi_v1.3:b45b5d11-2b08-11e9-9054-4913062421c2', dispense_labware: 'ccad1a20-2b08-11e9-9054-4913062421c2:96-flat', dispense_wells: ['A1', 'A2'], volume: 30, offsetFromBottomMm: 2, }, 2: { id: 2, stepType: 'transfer', 'step-name': 'FakeStepName', 'step-details': 'fake details', aspirate_disposalVol_checkbox: true, aspirate_disposalVol_volume: 60, aspirate_changeTip: 'always', aspirate_preWetTip: true, aspirate_touchTip: true, aspirate_touchTipMmFromBottom: 20, dispense_touchTip: true, dispense_touchTipMmFromBottom: 22, dispense_blowout_checkbox: true, dispense_blowout_labware: 'trashId', dispense_blowout_location: 'trashId', aspirate_labware: 'db17bed0-2b08-11e9-9054-4913062421c2:trough-12row', aspirate_wells: ['A12'], pipette: 'pipette:p300_multi_v1.3:b45b5d11-2b08-11e9-9054-4913062421c2', dispense_labware: 'ccad1a20-2b08-11e9-9054-4913062421c2:96-flat', dispense_wells: ['A1', 'A2'], volume: 30, offsetFromBottomMm: 2, }, 3: { id: 3, stepType: 'consolidate', 'step-name': 'FakeStepName', 'step-details': 'fake details', aspirate_disposalVol_checkbox: true, aspirate_disposalVol_volume: 60, aspirate_changeTip: 'always', aspirate_preWetTip: true, aspirate_touchTip: true, aspirate_touchTipMmFromBottom: 20, dispense_touchTip: true, dispense_touchTipMmFromBottom: 22, dispense_blowout_checkbox: true, dispense_blowout_labware: 'trashId', dispense_blowout_location: 'trashId', aspirate_labware: 'db17bed0-2b08-11e9-9054-4913062421c2:trough-12row', aspirate_wells: ['A12'], pipette: 'pipette:p300_multi_v1.3:b45b5d11-2b08-11e9-9054-4913062421c2', dispense_labware: 'ccad1a20-2b08-11e9-9054-4913062421c2:96-flat', dispense_wells: ['A1', 'A2'], volume: 30, offsetFromBottomMm: 2, }, }, }, }, } // @ts-expect-error incorrect parameter type const migratedFile = updateStepFormKeys(stubbedTCDStepsFile) it('deprecates all indicated field names', () => { each(TCD_DEPRECATED_FIELD_NAMES, fieldName => { each( stubbedTCDStepsFile['designer-application'].data.savedStepForms, stepForm => { // @ts-expect-error fieldname (any string) cannot be used to index type expect(stepForm[fieldName]).not.toEqual(undefined) } ) each( migratedFile['designer-application'].data.savedStepForms, stepForm => { expect(stepForm[fieldName]).toEqual(undefined) } ) }) }) it('creates non-existent new fields', () => { const oldFields = stubbedTCDStepsFile['designer-application'].data.savedStepForms['1'] const addedFields = { aspirate_touchTip_checkbox: oldFields.aspirate_touchTip, aspirate_touchTip_mmFromBottom: oldFields.aspirate_touchTipMmFromBottom, blowout_checkbox: oldFields.dispense_blowout_checkbox, blowout_location: oldFields.dispense_blowout_location, changeTip: oldFields.aspirate_changeTip, dispense_touchTip_checkbox: oldFields.dispense_touchTip, dispense_touchTip_mmFromBottom: oldFields.dispense_touchTipMmFromBottom, disposalVolume_checkbox: oldFields.aspirate_disposalVol_checkbox, disposalVolume_volume: oldFields.aspirate_disposalVol_volume, preWetTip: oldFields.aspirate_preWetTip, stepName: oldFields['step-name'], stepDetails: oldFields['step-details'], } each(Object.keys(addedFields), fieldName => { each( stubbedTCDStepsFile['designer-application'].data.savedStepForms, stepForm => { // @ts-expect-error fieldname (any string) cannot be used to index type expect(stepForm[fieldName]).toEqual(undefined) } ) each( migratedFile['designer-application'].data.savedStepForms, stepForm => // @ts-expect-error fieldname (any string) cannot be used to index type expect(stepForm[fieldName]).toEqual(addedFields[fieldName]) ) }) }) }) describe('for mix stepType', () => { const stubbedMixStepFile = { 'designer-application': { data: { savedStepForms: { 1: { id: 1, stepType: 'mix', 'step-name': 'Mix', 'step-details': 'here is how the mix will happen more specifically\n', aspirate_changeTip: 'never', labware: 'ccad1a20-2b08-11e9-9054-4913062421c2:96-flat', wells: ['A4'], pipette: 'pipette:p10_single_v1.3:b45b5d10-2b08-11e9-9054-4913062421c2', volume: 9, times: 2, dispense_blowout_checkbox: true, dispense_blowout_labware: 'trashId', dispense_blowout_location: 'trashId', dispense_mmFromBottom: 2, aspirate_wellOrder_first: 'l2r', aspirate_wellOrder_second: 't2b', touchTip: true, mix_touchTipMmFromBottom: 24, }, }, }, }, } // @ts-expect-error incorrect parameter type const migratedFile = updateStepFormKeys(stubbedMixStepFile) it('deprecates all indicated field names', () => { each(MIX_DEPRECATED_FIELD_NAMES, fieldName => { each( stubbedMixStepFile['designer-application'].data.savedStepForms, // @ts-expect-error fieldname (any string) cannot be used to index type stepForm => expect(stepForm[fieldName]).not.toEqual(undefined) ) each( migratedFile['designer-application'].data.savedStepForms, stepForm => expect(stepForm[fieldName]).toEqual(undefined) ) }) }) it('creates non-existent new fields', () => { const oldFields = stubbedMixStepFile['designer-application'].data.savedStepForms['1'] const addedFields = { stepName: oldFields['step-name'], stepDetails: oldFields['step-details'], changeTip: oldFields.aspirate_changeTip, mix_mmFromBottom: oldFields.dispense_mmFromBottom, mix_wellOrder_first: oldFields.aspirate_wellOrder_first, mix_wellOrder_second: oldFields.aspirate_wellOrder_second, mix_touchTip_checkbox: oldFields.touchTip, mix_touchTip_mmFromBottom: oldFields.mix_touchTipMmFromBottom, blowout_checkbox: oldFields.dispense_blowout_checkbox, blowout_location: oldFields.dispense_blowout_location, } each(Object.keys(addedFields), fieldName => { each( stubbedMixStepFile['designer-application'].data.savedStepForms, stepForm => { // @ts-expect-error fieldname (any string) cannot be used to index type expect(stepForm[fieldName]).toEqual(undefined) } ) each( migratedFile['designer-application'].data.savedStepForms, stepForm => { // @ts-expect-error fieldname (any string) cannot be used to index type expect(stepForm[fieldName]).toEqual(addedFields[fieldName]) } ) }) }) }) }) describe('replaceTCDStepsWithMoveLiquidStep', () => { const oldStepForms = oldProtocol['designer-application'].data.savedStepForms // @ts-expect-error incorrect parameter type const migratedFile = replaceTCDStepsWithMoveLiquidStep(oldProtocol) each(oldStepForms, (stepForm, stepId) => { if (stepForm.stepType === 'transfer') { it('transfer stepType changes into moveLiquid', () => { expect( migratedFile['designer-application'].data.savedStepForms[stepId] .stepType ).toEqual('moveLiquid') }) it('transfer stepType always receives single path', () => { expect( migratedFile['designer-application'].data.savedStepForms[stepId].path ).toEqual('single') }) } else if (stepForm.stepType === 'consolidate') { it('consolidate stepType changes into moveLiquid', () => { expect( migratedFile['designer-application'].data.savedStepForms[stepId] .stepType ).toEqual('moveLiquid') }) it('consolidate stepType always receives multiAspirate path', () => { expect( migratedFile['designer-application'].data.savedStepForms[stepId].path ).toEqual('multiAspirate') }) } else if (stepForm.stepType === 'distribute') { it('distribute stepType changes into moveLiquid', () => { expect( migratedFile['designer-application'].data.savedStepForms[stepId] .stepType ).toEqual('moveLiquid') }) it('distribute stepType always receives multiAspirate or single path', () => { expect( migratedFile['designer-application'].data.savedStepForms[stepId].path ).toMatch(/multiDispense|single/) }) } }) })
the_stack
import { jisToUnicodeMap } from "./jis_to_unicode_map"; import CRC32 from "crc-32"; import { Buffer } from "buffer"; function readBits(posBits: number, bits: number, buffer: Buffer): number { let value = 0; for (let i = 0; i < bits; i++) { value <<= 1; value |= (buffer[posBits >> 3] & (1 << (7 - (posBits & 7)))) ? 1 : 0; posBits++; } return value; } type DRCSGlyph = { width: number, height: number, depth: number, bitmap: number[], }; type DRCSGlyphs = { ku: number, ten: number, glyphs: DRCSGlyph[], }; export class BinaryWriter { private buffer: Buffer; private offset: number; private size: number; public constructor() { this.buffer = Buffer.alloc(4096); this.offset = 0; this.size = 0; } public get position(): number { return this.offset; } public seek(offset: number): number { const prev = this.offset; this.offset = offset; return prev; } private extend(needBytes: number) { const prevBuf = this.buffer; this.buffer = Buffer.alloc(Math.max(needBytes + this.offset, this.buffer.length * 2)); prevBuf.copy(this.buffer); } public writeUInt8(value: number): number { if (this.offset >= this.buffer.byteLength) { this.extend(1); } this.buffer.writeUInt8(value, this.offset); this.offset += 1; this.size = Math.max(this.offset, this.size); return this.offset - 1; } public writeUInt16BE(value: number): number { if (this.offset + 2 >= this.buffer.byteLength) { this.extend(2); } this.buffer.writeUInt16BE(value, this.offset); this.offset += 2; this.size = Math.max(this.offset, this.size); return this.offset - 2; } public writeUInt24BE(value: number): number { if (this.offset + 3 >= this.buffer.byteLength) { this.extend(3); } this.buffer.writeUInt8((value >> 8) & 0xff, this.offset); this.buffer.writeUInt16BE(value & 0xffff, this.offset); this.offset += 3; this.size = Math.max(this.offset, this.size); return this.offset - 3; } public writeUInt32BE(value: number): number { if (this.offset + 4 >= this.buffer.byteLength) { this.extend(4); } this.buffer.writeUInt32BE(value, this.offset); this.offset += 4; this.size = Math.max(this.offset, this.size); return this.offset - 4; } public writeInt8(value: number): number { if (this.offset + 1 >= this.buffer.byteLength) { this.extend(1); } this.buffer.writeInt8(value, this.offset); this.offset += 1; this.size = Math.max(this.offset, this.size); return this.offset - 1; } public writeInt16BE(value: number): number { if (this.offset + 2 >= this.buffer.byteLength) { this.extend(2); } this.buffer.writeInt16BE(value, this.offset); this.offset += 2; this.size = Math.max(this.offset, this.size); return this.offset - 2; } public writeInt32BE(value: number): number { if (this.offset + 4 >= this.buffer.byteLength) { this.extend(4); } this.buffer.writeInt32BE(value, this.offset); this.offset += 4; this.size = Math.max(this.offset, this.size); return this.offset - 4; } public writeInt64BE(value: number): number { if (this.offset + 8 >= this.buffer.byteLength) { this.extend(8); } this.buffer.writeBigInt64BE(BigInt(value), this.offset); this.offset += 8; this.size = Math.max(this.offset, this.size); return this.offset - 8; } public writeASCII(value: string): number { if (this.offset + value.length >= this.buffer.byteLength) { this.extend(value.length); } this.buffer.write(value, this.offset, "ascii"); this.offset += value.length; this.size = Math.max(this.offset, this.size); return this.offset - value.length; } public writeBuffer(value: Buffer): number { if (this.offset + value.length >= this.buffer.byteLength) { this.extend(value.length); } value.copy(this.buffer, this.offset); this.offset += value.length; this.size = Math.max(this.offset, this.size); return this.offset - value.length; } public getBuffer(): Buffer { return this.buffer.subarray(0, this.size); } public subarray(start?: number | undefined, end?: number | undefined): Buffer { if (end == null) { end = this.size; } return this.buffer.subarray(start, end); } } function checksum(buffer: Buffer): number { let chksum = 0; let i = 0; for (; i + 3 < buffer.length; i += 4) { chksum = (chksum + buffer.readInt32BE(i)) & 0xffffffff; } let remain = buffer.length - i; if (remain === 1) { chksum = (chksum + (buffer.readUInt8(i + 0) << 24)) & 0xffffffff; throw new Error("unreachable"); } else if (remain === 2) { chksum = (chksum + (buffer.readUInt16BE(i + 0) << 16)) & 0xffffffff; throw new Error("unreachable"); } else if (remain === 3) { chksum = (chksum + ((buffer.readUInt16BE(i + 0) << 16) | (buffer.readUInt8(i + 2) << 8))) & 0xffffffff; throw new Error("unreachable"); } else if (remain !== 0) { throw new Error("unreachable"); } return chksum; } export function toTTF(glyphs: DRCSGlyphs[]): { ttf: Buffer, unicodeCharacters: number[] } { const tables = [ { name: "cmap", writer: writeCMAP, headerOffset: -1 }, { name: "head", writer: writeHEAD, headerOffset: -1 }, { name: "hhea", writer: writeHHEA, headerOffset: -1 }, { name: "hmtx", writer: writeHMTX, headerOffset: -1 }, { name: "maxp", writer: writeMAXP, headerOffset: -1 }, { name: "name", writer: writeNAME, headerOffset: -1 }, { name: "OS/2", writer: writeOS2, headerOffset: -1 }, { name: "post", writer: writePOST, headerOffset: -1 }, // EBDTとEBLCは消されてしまうらしい // https://github.com/khaledhosny/ots/blob/main/docs/DesignDoc.md // > We don't support embedded bitmap strikes. // { name: "EBDT", writer: writeEBDT, headerOffset: -1 }, // { name: "EBLC", writer: writeEBLC, headerOffset: -1 }, { name: "CBDT", writer: writeCBDT, headerOffset: -1 }, { name: "CBLC", writer: writeCBLC, headerOffset: -1 }, { name: "glyf", writer: writeGLYF, headerOffset: -1 }, { name: "loca", writer: writeLOCA, headerOffset: -1 }, { name: "SVG ", writer: writeSVG, headerOffset: -1 } ]; tables.sort((a, b) => { if (a.name < b.name) { return -1; } if (a.name > b.name) { return 1; } return 0; }); const writer = new BinaryWriter(); writer.writeUInt32BE(0x00010000); const numTables = tables.length; writer.writeUInt16BE(numTables); const searchRange = 16 * Math.pow(2, Math.floor(Math.log2(numTables))); writer.writeUInt16BE(searchRange); const entrySelector = Math.floor(Math.log2(numTables)); writer.writeUInt16BE(entrySelector); // rangeShift writer.writeUInt16BE(numTables * 16 - searchRange); for (const i of tables) { i.headerOffset = writer.writeASCII(i.name); writer.writeUInt32BE(1234); // checksum writer.writeUInt32BE(0); // offset writer.writeUInt32BE(0); // length } let headOffset = -1; for (const i of tables) { const off = writer.position; if (i.name === "head") { headOffset = off; } i.writer(glyphs, writer); const len = writer.position - off; while (writer.position & 3) { writer.writeUInt8(0); } const chksum = checksum(writer.subarray(off, writer.position)); let prev = writer.seek(i.headerOffset + 4 /* name */); writer.writeInt32BE(chksum); writer.writeUInt32BE(off); writer.writeUInt32BE(len); writer.seek(prev); } const wholeChecksum = (0xB1B0AFBA - checksum(writer.getBuffer())) | 0; writer.seek(headOffset + 8); writer.writeInt32BE(wholeChecksum); const unicodeCharacters = glyphs.map(x => map(x.ku, x.ten)); return { ttf: writer.getBuffer(), unicodeCharacters }; } function map(ku: number, ten: number): number { const s = jisToUnicodeMap[(ku - 1) * 94 + ten - 1]; if (typeof s === "number") { return s; } else { return 0; } } function writeCMAP(glyphs: DRCSGlyphs[], writer: BinaryWriter) { let cmapOffset = writer.writeUInt16BE(0); // version writer.writeUInt16BE(1); // numTables // encoding record writer.writeUInt16BE(0); // platform id (unicode) writer.writeUInt16BE(3); // encoding ID writer.writeInt32BE(writer.position + 4 - cmapOffset); // subtable offset // table const offSubTable = writer.writeUInt16BE(4); // format const offLen = writer.writeUInt16BE(0); // length writer.writeUInt16BE(0); // language const segCount = glyphs.length + 1; writer.writeUInt16BE(segCount * 2); // segCountX2 const searchRange = 2 * Math.pow(2, Math.floor(Math.log2(segCount))); writer.writeUInt16BE(searchRange); const entrySelector = Math.log2(searchRange / 2); writer.writeUInt16BE(entrySelector); // rangeShift writer.writeUInt16BE(segCount * 2 - searchRange); // endCode for (let i = 0; i < glyphs.length; i++) { writer.writeUInt16BE(map(glyphs[i].ku, glyphs[i].ten)); } // endCode writer.writeUInt16BE(0xffff); writer.writeUInt16BE(0); // reserved // startCode for (let i = 0; i < glyphs.length; i++) { writer.writeUInt16BE(map(glyphs[i].ku, glyphs[i].ten)); } // startCode writer.writeUInt16BE(0xffff); // idDelta for (let i = 0; i < segCount - 1; i++) { writer.writeUInt16BE((-map(glyphs[i].ku, glyphs[i].ten) + i + 1) & 0xffff); } writer.writeInt16BE(1); // idRangeOffsets for (let i = 0; i < segCount; i++) { writer.writeUInt16BE(0); } const prev = writer.seek(offLen); writer.writeUInt16BE(prev - offSubTable); writer.seek(prev); } function writeHEAD(_glyphs: DRCSGlyphs[], writer: BinaryWriter) { writer.writeUInt16BE(1); // majorVersion writer.writeUInt16BE(0); // minorVersion writer.writeUInt16BE(1); // fontRevision writer.writeUInt16BE(1); // fontRevision writer.writeUInt32BE(0); // checkSumAdjustment writer.writeUInt32BE(0x5F0F3CF5); // magicNumber writer.writeUInt16BE(0); // flags writer.writeUInt16BE(1024); // unitsPerEm writer.writeInt64BE(0); // created writer.writeInt64BE(0); // modified writer.writeInt16BE(0); // xMin writer.writeInt16BE(-123); // yMin writer.writeInt16BE(1024); // xMax writer.writeInt16BE(901); // yMax writer.writeUInt16BE(0); // macStyle writer.writeUInt16BE(8); // lowestRecPPEM writer.writeUInt16BE(2); // fontDirectionHint writer.writeUInt16BE(1); // indexToLocFormat writer.writeUInt16BE(0); // glyphDataFormat } function writeHHEA(glyphs: DRCSGlyphs[], writer: BinaryWriter) { writer.writeUInt16BE(1); // majorVersion writer.writeUInt16BE(0); // minorVersion writer.writeInt16BE(901); // yAscender writer.writeInt16BE(-123); // yDescender writer.writeInt16BE(0); // lineGap writer.writeUInt16BE(1024); // advanceWidthMax writer.writeInt16BE(0); // minLeftSideBearing writer.writeInt16BE(0); // minRightSideBearing writer.writeInt16BE(1024); // xMaxExtent writer.writeInt16BE(1); // caretSlopeRise writer.writeInt16BE(0); // caretSlopeRun writer.writeInt16BE(0); // caretOffset writer.writeInt16BE(0); // reserved writer.writeInt16BE(0); // reserved writer.writeInt16BE(0); // reserved writer.writeInt16BE(0); // reserved writer.writeInt16BE(0); // metricDataFormat writer.writeUInt16BE(glyphs.length + 1); // numberOfHMetrics } function writeHMTX(glyphs: DRCSGlyphs[], writer: BinaryWriter) { for (let i = 0; i <= glyphs.length; i++) { // SVGグリフで文字間に間が空くので適当に縮める // どのみち拡大すると破綻する writer.writeUInt16BE(1024);//2550); writer.writeInt16BE(0); } } function writeMAXP(glyphs: DRCSGlyphs[], writer: BinaryWriter) { writer.writeUInt32BE(0x00010000); // version writer.writeUInt16BE(glyphs.length + 1); // numGlyphs writer.writeUInt16BE(0); // maxPoints writer.writeUInt16BE(0); // maxContours writer.writeUInt16BE(0); // maxCompositePoints writer.writeUInt16BE(0); // maxCompositeContours writer.writeUInt16BE(1); // maxZones writer.writeUInt16BE(0); // maxTwilightPoints writer.writeUInt16BE(0); // maxStorage writer.writeUInt16BE(0); // maxFunctionDefs writer.writeUInt16BE(0); // maxInstructionDefs writer.writeUInt16BE(0); // maxStackElements writer.writeUInt16BE(0); // maxSizeOfInstructions writer.writeUInt16BE(0); // maxComponentElements writer.writeUInt16BE(0); // maxComponentDepth } function writeNAME(_glyphs: DRCSGlyphs[], writer: BinaryWriter) { const begin = writer.position; writer.writeUInt16BE(0); // version writer.writeUInt16BE(1); // count const sizeofNameRecord = 2 * 6; writer.writeUInt16BE(sizeofNameRecord + 2 + 2 + 2); // storageOffset // NameRecord writer.writeUInt16BE(0); // Unicode writer.writeUInt16BE(3); // UnicodeBMP writer.writeUInt16BE(0); // languageID writer.writeUInt16BE(0); // nameID const str = "DRCS"; writer.writeUInt16BE(str.length * 2); writer.writeUInt16BE(0); writer.writeUInt16BE("DRCS".charCodeAt(0)); writer.writeUInt16BE("DRCS".charCodeAt(1)); writer.writeUInt16BE("DRCS".charCodeAt(2)); writer.writeUInt16BE("DRCS".charCodeAt(3)); } function writeOS2(_glyphs: DRCSGlyphs[], writer: BinaryWriter) { writer.writeUInt16BE(1); // version writer.writeInt16BE(1013); // xAvgCharWidth writer.writeUInt16BE(400); // usWeightClass writer.writeUInt16BE(5); // usWidthClass writer.writeUInt16BE(0); // fsType writer.writeInt16BE(666); // ySubscriptXSize writer.writeInt16BE(614); // ySubscriptYSize writer.writeInt16BE(0); // ySubscriptXOffset writer.writeInt16BE(77); // ySubscriptYOffset writer.writeInt16BE(666); // ySuperscriptXSize writer.writeInt16BE(614); // ySuperscriptYSize writer.writeInt16BE(0); // ySuperscriptXOffset writer.writeInt16BE(358); // ySuperscriptYOffset writer.writeInt16BE(38); // yStrikeoutSize writer.writeInt16BE(408); // yStrikeoutPosition writer.writeInt16BE(0); // sFamilyClass for (let i = 0; i < 10; i++) { writer.writeInt8(0); // panose } writer.writeUInt32BE(0); // ulUnicodeRange1 writer.writeUInt32BE(0); // ulUnicodeRange2 writer.writeUInt32BE(0); // ulUnicodeRange3 writer.writeUInt32BE(0); // ulUnicodeRange4 writer.writeASCII(" "); // archVendID writer.writeUInt16BE(0x40); // fsSelection writer.writeUInt16BE(0x0000); // usFirstCharIndex writer.writeUInt16BE(0xffff); // usLastCharIndex writer.writeInt16BE(901); // sTypoAscender writer.writeInt16BE(-123); // sTypoDescender writer.writeInt16BE(0); // sTypoLineGap writer.writeUInt16BE(901); // usWinAscent writer.writeUInt16BE(123); // usWinDescent writer.writeUInt32BE(0); // ulCodePageRange1 writer.writeUInt32BE(0); // ulCodePageRange2 } function writePOST(_glyphs: DRCSGlyphs[], writer: BinaryWriter) { writer.writeUInt32BE(0x00030000); // version writer.writeUInt16BE(0); // italicAngle writer.writeUInt16BE(0); // italicAngle writer.writeInt16BE(-1244); // underlinePosition writer.writeInt16BE(131); // underlineThickness writer.writeUInt32BE(0); // isFixedPitch writer.writeUInt32BE(0); // minMemType42 writer.writeUInt32BE(0); // maxMemType42 writer.writeUInt32BE(0); // minMemType1 writer.writeUInt32BE(0); // maxMemType1 } type Strike = { width: number, height: number, glyphs: { glyphIndex: number, glyph: DRCSGlyph }[] }; function getStrikes(glyphses: DRCSGlyphs[]): Strike[] { const result: Strike[] = []; const map = new Map<string, Strike>(); let glyphIndex = 0; for (const glyphs of glyphses) { glyphIndex++; for (const glyph of glyphs.glyphs) { const key = `${glyph.width}x${glyph.height}`; let strike = map.get(key); if (!strike) { strike = { width: glyph.width, height: glyph.height, glyphs: [] }; result.push(strike); map.set(key, strike); } strike.glyphs.push({ glyphIndex, glyph }); } } return result; } function writeCBLC(glyphs: DRCSGlyphs[], writer: BinaryWriter) { writer.writeUInt16BE(3); writer.writeUInt16BE(0); const strikes = getStrikes(glyphs); writer.writeUInt32BE(strikes.length); const headerSize = 2 * 2 + 4; const sizeOfSbitLineMetrics = 12; const sizeofBitmapSize = 4 * 4 + sizeOfSbitLineMetrics * 2 + 2 * 2 + 4; let indexSubTableArrayOffset = ((headerSize + sizeofBitmapSize * strikes.length) + 3) & ~3; const sizeOfIndexSubTableArray = 2 + 2 + 4; // BitmapSize for (const strike of strikes) { writer.writeUInt32BE(indexSubTableArrayOffset); // indexSubTableArrayOffset const indexTablesSize = sizeOfIndexSubTableArray * 1 + 2 + 2 + 4 + 4 + glyphs.length * 4; indexSubTableArrayOffset += indexTablesSize; writer.writeUInt32BE(indexTablesSize); // indexTablesSize writer.writeUInt32BE(1); // numberOfIndexSubTables writer.writeUInt32BE(0); // colorRef // hori { writer.writeInt8(Math.round(strike.width * 901 / 1024)); // ascender writer.writeInt8(Math.round(-strike.width * 123 / 1024)); // descender writer.writeUInt8(strike.width); // widthMax writer.writeInt8(0); // caretSlopeNumerator writer.writeInt8(0); // caretSlopeDenominator writer.writeInt8(0); // caretOffset writer.writeInt8(0); // minOriginSB writer.writeInt8(0); // minAdvanceSB writer.writeInt8(0); // maxBeforeBL writer.writeInt8(0); // minAfterBL writer.writeInt8(0); // pad1 writer.writeInt8(0); // pad2 } // vert { writer.writeInt8(Math.round(strike.width * 901 / 1024)); // ascender writer.writeInt8(Math.round(-strike.width * 123 / 1024)); // descender writer.writeUInt8(strike.height); // widthMax writer.writeInt8(0); // caretSlopeNumerator writer.writeInt8(0); // caretSlopeDenominator writer.writeInt8(0); // caretOffset writer.writeInt8(0); // minOriginSB writer.writeInt8(0); // minAdvanceSB writer.writeInt8(0); // maxBeforeBL writer.writeInt8(0); // minAfterBL writer.writeInt8(0); // pad1 writer.writeInt8(0); // pad2 } writer.writeUInt16BE(1); // startGlyphIndex writer.writeUInt16BE(glyphs.length); // endGlyphIndex writer.writeInt8(strike.width); // ppemX writer.writeInt8(strike.height); // ppemY writer.writeInt8(8); // bitDepth writer.writeInt8(1); // flags HORIZONTAL_METRICS } // IndexSubTableArray const sizeofIndexSubHeader = 2 + 2 + 4; const sizeofSmallGlyphMetrics = 5; let ebdtOffset = 2 + 2; // majorVersion, minorVersion for (const strike of strikes) { writer.writeUInt16BE(1); // firstGlyphIndex writer.writeUInt16BE(glyphs.length); // lastGlyphIndex writer.writeUInt32BE(2 + 2 + 4); // additionalOffsetToIndexSubtable // IndexSubHeader writer.writeUInt16BE(1); // indexFormat = IndexSubTable1 writer.writeUInt16BE(1); // imageFormat = Format 1: small metrics, byte-aligned data writer.writeUInt32BE(ebdtOffset); // imageDataOffset writer.writeUInt32BE(0); // sbitOffsets let sbitOffset = 0; for (let i = 1; i <= glyphs.length; i++) { const glyph = findBestBitmap(glyphs, strike, i); sbitOffset += sizeofSmallGlyphMetrics + 1 * strike.width * strike.height; writer.writeUInt32BE(sbitOffset); // sbitOffsets } ebdtOffset += sbitOffset; } } function findBestBitmap(glyphs: DRCSGlyphs[], strike: Strike, glyphIndex: number): DRCSGlyph { const found = strike.glyphs.find(x => x.glyphIndex === glyphIndex)?.glyph; if (found) { return found; } const bitmaps = glyphs[glyphIndex - 1].glyphs; if (bitmaps.length === 1) { return bitmaps[0]; } // 可能な限りstrikeのwidth, heightに近くなおかつそれ以上の大きさの外字を選ぶ const a = bitmaps.map(x => ({ score: (x.width * x.height) - (strike.width * strike.height), bitmap: x })); a.sort((a, b) => a.score - b.score); const bestSmall = a.find(x => x.score >= 0); if (bestSmall) { return bestSmall.bitmap; } // 見つからなければ妥協して一番大きいのを返す return a[a.length - 1]?.bitmap as DRCSGlyph; } function writeCBDT(glyphs: DRCSGlyphs[], writer: BinaryWriter) { writer.writeUInt16BE(3); writer.writeUInt16BE(0); // SmallGlyphMetrics const strikes = getStrikes(glyphs); for (const strike of strikes) { for (let i = 1; i <= glyphs.length; i++) { const g = findBestBitmap(glyphs, strike, i); writer.writeUInt8(strike.height); writer.writeUInt8(strike.width); writer.writeUInt8(0); // bearingX writer.writeUInt8(strike.height + Math.round(-strike.width * 123 / 1024)); // bearingY writer.writeUInt8(strike.width); // advance for (let y = 0; y < strike.height; y++) { for (let x = 0; x < strike.width; x++) { // ひとまず線形補間でストライクの大きさに合わせた拡大縮小を行う const y1 = y / strike.height * g.height; const x1 = x / strike.width * g.width; const fx = x1 - Math.floor(x1); const fy = y1 - Math.floor(y1); let b = 0; b += g.bitmap[Math.floor(x1) + Math.floor(y1) * g.width] * (1 - fx) * (1 - fy); b += g.bitmap[Math.min(g.width - 1, Math.floor(x1 + 1)) + Math.floor(y1) * g.width] * (fx) * (1 - fy); b += g.bitmap[Math.floor(x1) + Math.min(g.height - 1, Math.floor(y1 + 1)) * g.width] * (1 - fx) * (fy); b += g.bitmap[Math.min(g.width - 1, Math.floor(x1 + 1)) + Math.min(g.height - 1, Math.floor(y1 + 1)) * g.width] * (fx) * (fy); writer.writeUInt8(Math.round(b / (g.depth - 1) * 255)); } } } } } function writeGLYF(glyphs: DRCSGlyphs[], writer: BinaryWriter) { for (let i = 0; i <= glyphs.length; i++) { writer.writeUInt16BE(0); // numberOfContours writer.writeInt16BE(0); // xMin writer.writeInt16BE(-123); // yMin writer.writeInt16BE(1024); // xMax writer.writeInt16BE(901); // yMax writer.writeUInt16BE(0); // InstructionLength } } function writeLOCA(glyphs: DRCSGlyphs[], writer: BinaryWriter) { writer.writeUInt32BE(2 * 6 * 1); for (let i = 1; i <= glyphs.length + 1; i++) { writer.writeUInt32BE(2 * 6 * i); } } function encodePNG({ width, height, bitmap, depth }: DRCSGlyph): Buffer { const buffer = Buffer.alloc(33 /* IHDR */ + 12 /* IDAT */ + 2 + height * (5 + width * 2 + 1 /* filter */) + 4 + 12 /* IEND */); let off = 0; // 臼NG off = buffer.writeUInt8(0x89, off); off = buffer.writeUInt8(0x50, off); off = buffer.writeUInt8(0x4e, off); off = buffer.writeUInt8(0x47, off); off = buffer.writeUInt8(0x0d, off); off = buffer.writeUInt8(0x0a, off); off = buffer.writeUInt8(0x1a, off); off = buffer.writeUInt8(0x0a, off); off = buffer.writeUInt32BE(13, off); const ihdrOff = off; off += buffer.write("IHDR", off, "ascii"); off = buffer.writeUInt32BE(width, off); off = buffer.writeUInt32BE(height, off); // 8-bit grayscale, alpha off = buffer.writeUInt8(8, off); off = buffer.writeUInt8(4, off); // deflate, no filter, interlace off = buffer.writeUInt8(0, off); off = buffer.writeUInt8(0, off); off = buffer.writeUInt8(0, off); off = buffer.writeInt32BE(CRC32.buf(buffer.subarray(ihdrOff, off)), off); off = buffer.writeUInt32BE(2 + height * (5 + width * 2 + 1 /* filter */) + 4, off); const idatOff = off; off += buffer.write("IDAT", off, "ascii"); off = buffer.writeUInt8(0x78, off); off = buffer.writeUInt8(0x01, off); let a = 1, b = 0; for (let y = 0; y < height; y++) { off = buffer.writeUInt8(y === height - 1 ? 1 : 0, off); off = buffer.writeUInt16LE(width * 2 + 1, off); off = buffer.writeUInt16LE(~(width * 2 + 1) & 0xffff, off); off = buffer.writeUInt8(0x00, off); b = (b + a) % 65521; for (let x = 0; x < width; x++) { off = buffer.writeUInt8(255, off) a = (a + 255) % 65521; b = (b + a) % 65521; const v = Math.floor(bitmap[x + y * width] / (depth - 1) * 255); off = buffer.writeUInt8(v, off) a = (a + v) % 65521; b = (b + a) % 65521; } } off = buffer.writeInt32BE((b << 16) + a, off); off = buffer.writeInt32BE(CRC32.buf(buffer.subarray(idatOff, off)), off); off = buffer.writeUInt32BE(0, off); off += buffer.write("IEND", off, "ascii"); off = buffer.writeInt32BE(CRC32.buf(buffer.subarray(off - 4, off)), off); return buffer; } function writeSVG(glyphs: DRCSGlyphs[], writer: BinaryWriter) { // SVGTableHeader writer.writeUInt16BE(0); // version writer.writeUInt32BE(2 + 4 + 4); // svgDocumentListOffset writer.writeUInt32BE(0); // reserved // SVGDocumentList const offsetSVGDocumentList = writer.position; writer.writeUInt16BE(glyphs.length); for (let glyphId = 1; glyphId <= glyphs.length; glyphId++) { writer.writeUInt16BE(glyphId); // startGlyphID writer.writeUInt16BE(glyphId); // endGlyphID writer.writeUInt32BE(0); // svgDocOffset writer.writeUInt32BE(0); // svgDocLength } let offsets: { glyphId: number, offset: number, size: number }[] = []; for (let glyphId = 1; glyphId <= glyphs.length; glyphId++) { const glyph = glyphs[glyphId - 1].glyphs.slice().sort((a, b) => (b.width * b.height) - (a.width * a.height))[0]; const png = encodePNG(glyph); let svg = `<svg id="glyph${glyphId}" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 ${glyph.height} ${glyph.width} ${glyph.height}"> <defs> <mask id="mask"> <image x="0" y="${-Math.round(-glyph.width * 123 / 1024)}" width="${glyph.width + 1}" height="${glyph.height + 1}" xlink:href="data:image/png;base64,${png.toString("base64")}"/> </mask> </defs> <rect x="0" y="${-Math.round(-glyph.width * 123 / 1024)}" width="${glyph.width + 1}" height="${glyph.height + 1}" mask="url(#mask)" /> </svg>`; offsets.push({ glyphId, offset: writer.writeASCII(svg), size: svg.length }); } const prev = writer.seek(offsetSVGDocumentList + 2); for (const g of offsets) { writer.writeUInt16BE(g.glyphId); // startGlyphID writer.writeUInt16BE(g.glyphId); // endGlyphID writer.writeUInt32BE(g.offset - offsetSVGDocumentList); // svgDocOffset writer.writeUInt32BE(g.size); // svgDocLength } writer.seek(prev); } // 以下のフォントサイズのみが運用される (STD-B24 第二分冊 第二編 付属3 4.1.2参照) enum FontId { RoundGothic = 1, // 丸ゴシック SquareGothic = 2, // 角ゴシック BoldRoundGothic = 3, // 太丸ゴシック } export function loadDRCS(drcs: Buffer, filterId?: number): DRCSGlyphs[] { let off = 0; const nCode = drcs.readUInt8(off); off += 1; const ret: DRCSGlyphs[] = []; for (let i = 0; i < nCode; i++) { const charCode1 = drcs.readUInt8(off); off += 1; const charCode2 = drcs.readUInt8(off); off += 1; const nFont = drcs.readUInt8(off); off += 1; const glyphs: DRCSGlyphs = { ku: charCode1 - 0x20, ten: charCode2 - 0x20, glyphs: [] }; for (let j = 0; j < nFont; j++) { const b = drcs.readUInt8(off); off += 1; const fontId = (b >> 4) as FontId; const mode = b & 15; //console.log(`${charCode1} ${charCode2} ${fontId}`); // charCode1 - 0x20, charCode2 - 0x20でJISの区点 // これに0xA0を足すとEUC-JP // modeは1のみが運用される if (mode === 0 || mode === 1) { // depthは2のみが運用される(4階調) const depth = drcs.readUInt8(off); off += 1; // 以下のフォントサイズのみが運用される (STD-B24 第二分冊 第二編 付属3 4.6.10 表4-10参照) // 丸ゴシック(1) 16px, 20px, 24px, 30px, 36px // 太丸ゴシック(3) 30px // 角ゴシック(2) 20px, 24px // DRCSは全角のみが運用される const width = drcs.readUInt8(off); off += 1; const height = drcs.readUInt8(off); off += 1; const depthBits = Math.ceil(Math.log2(depth + 2)); let posBits = off * 8; const bitmap = new Array(width * height); if (filterId == null || (fontId as number) === filterId) { glyphs.glyphs.push({ width, height, depth: depth + 2, bitmap }); } for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { const bits = readBits(posBits, depthBits, drcs); bitmap[x + y * width] = bits; posBits += depthBits; } } off = (posBits + 7) >> 3; } else { // ジオメトリックは運用されない throw new Error("geometric is not operated"); } } if (glyphs.glyphs.length !== 0) { ret.push(glyphs); } } return ret; }
the_stack
window.URL.createObjectURL = jest.fn(); import * as fs from 'fs'; import React from 'react'; import {cleanup, fireEvent, render} from '@testing-library/react'; import {Polygon, Point} from 'ol/geom'; import {Pixel} from 'ol/pixel'; import {VectorTile} from 'ol/layer'; import {Feature} from 'ol'; import {RFeature, RLayerVector, RMap, RContext, ROverlay} from 'rlayers'; import * as common from './common'; describe('<RFeature>', () => { it('should create features', async () => { const mapEvents = ['Click', 'PointerDrag', 'PointerMove']; const featureEvents = ['Change']; const handler = jest.fn(); const handlers = mapEvents .concat(featureEvents) .reduce((ac, a) => ({...ac, ['on' + a]: handler}), {}); const map = React.createRef() as React.RefObject<RMap>; const ref = [ React.createRef() as React.RefObject<RFeature>, React.createRef() as React.RefObject<RFeature> ]; const {container, unmount} = render( <RMap ref={map} {...common.mapProps}> <RLayerVector zIndex={10}> <RFeature ref={ref[0]} {...handlers} style={common.styles.blueDot} geometry={new Point(common.coords.ArcDeTriomphe)} > <RContext.Consumer> {(c) => <div>marker {JSON.stringify(c, common.safeStringify)}</div>} </RContext.Consumer> </RFeature> <RFeature ref={ref[1]} {...handlers} style={common.styles.yellow} geometry={ new Polygon([ [ common.coords.PlaceDItalie, common.coords.Bastille, common.coords.TourEiffel, common.coords.PlaceDItalie ] ]) } > <RContext.Consumer> {(c) => <div>marker {JSON.stringify(c, common.safeStringify)}</div>} </RContext.Consumer> </RFeature> </RLayerVector> </RMap> ); if (map.current === null) throw new Error('map.current is null'); for (const evname of mapEvents) for (const r of ref) r.current?.ol.dispatchEvent( common.createEvent(evname.toLowerCase(), map.current.ol) ); for (const evname of featureEvents) for (const r of ref) r.current?.ol.dispatchEvent( common.createEvent(evname.toLowerCase(), map.current.ol) ); expect(container.innerHTML).toMatchSnapshot(); // +1 because there is one implicit change at creation expect(handler).toHaveBeenCalledTimes((mapEvents.length + featureEvents.length + 1) * 2); unmount(); }); it('should support updating feature props', async () => { const {container, rerender} = render( <RMap {...common.mapProps}> <RLayerVector> <RFeature properties={{name: 'Arc de Triomphe'}} geometry={new Point(common.coords.ArcDeTriomphe)} > <RContext.Consumer> {(c) => <div>marker {JSON.stringify(c, common.safeStringify)}</div>} </RContext.Consumer> </RFeature> </RLayerVector> </RMap> ); expect(container.innerHTML).toMatchSnapshot(); rerender( <RMap {...common.mapProps}> <RLayerVector> <RFeature properties={{name: "Place d'Italie"}} geometry={new Point(common.coords.PlaceDItalie)} > <RContext.Consumer> {(c) => <div>marker {JSON.stringify(c, common.safeStringify)}</div>} </RContext.Consumer> </RFeature> </RLayerVector> </RMap> ); expect(container.innerHTML).toMatchSnapshot(); }); it('should support replacing the bound feature object', async () => { const ref = React.createRef() as React.RefObject<RFeature>; const layer = React.createRef() as React.RefObject<RLayerVector>; const f1 = new Feature(new Point(common.coords.ArcDeTriomphe)); const f2 = new Feature(new Point(common.coords.PlaceDItalie)); const {rerender} = render( <RMap {...common.mapProps}> <RLayerVector ref={layer}> <RFeature ref={ref} feature={f1}></RFeature> </RLayerVector> </RMap> ); expect(ref.current?.ol).toStrictEqual(f1); expect((ref.current?.ol?.getGeometry() as Point).getCoordinates()).toEqual( common.coords.ArcDeTriomphe ); expect(layer.current?.source.getFeatures().length).toBe(1); rerender( <RMap {...common.mapProps}> <RLayerVector ref={layer}> <RFeature ref={ref} feature={f2}></RFeature> </RLayerVector> </RMap> ); expect(ref.current?.ol).toStrictEqual(f2); expect((ref.current?.ol?.getGeometry() as Point).getCoordinates()).toEqual( common.coords.PlaceDItalie ); expect(layer.current?.source.getFeatures().length).toBe(1); rerender( <RMap {...common.mapProps}> <RLayerVector ref={layer} /> </RMap> ); expect(layer.current?.source.getFeatures().length).toBe(0); }); it('should support deleting features with nested elements', async () => { const {container, rerender} = render( <RMap {...common.mapProps}> <RLayerVector> <RFeature properties={{name: 'Arc de Triomphe'}} geometry={new Point(common.coords.ArcDeTriomphe)} > <ROverlay> <div>Test</div> </ROverlay> </RFeature> </RLayerVector> </RMap> ); expect(container.innerHTML).toMatchSnapshot(); rerender( <RMap {...common.mapProps}> <RLayerVector></RLayerVector> </RMap> ); expect(container.innerHTML).toMatchSnapshot(); }); it('should relay map events to features', () => { const map = React.createRef() as React.RefObject<RMap>; const ref = [ React.createRef() as React.RefObject<RFeature>, React.createRef() as React.RefObject<RFeature> ]; const mapEvents = ['Click', 'SingleClick', 'DblClick', 'PointerDrag', 'PointerMove']; const handlers = [ jest.fn(common.handlerCheckContext(RFeature, ['map'], [map])), jest.fn(common.handlerCheckContext(RFeature, ['map'], [map])), jest.fn(common.handlerCheckContext(RFeature, ['map'], [map])) ]; const handlerProps = [ mapEvents.reduce((ac, a) => ({...ac, ['on' + a]: handlers[0]}), {}), mapEvents.reduce((ac, a) => ({...ac, ['on' + a]: handlers[1]}), {}), mapEvents.reduce((ac, a) => ({...ac, ['on' + a]: handlers[2]}), {}) ]; // First pass, test installing new handlers const {rerender} = render( <RMap ref={map} {...common.mapProps}> <RLayerVector> <RFeature ref={ref[0]} properties={{name: 'Arc de Triomphe'}} {...handlerProps[0]} geometry={new Point(common.coords.ArcDeTriomphe)} /> <RFeature ref={ref[1]} properties={{name: "Place d'Italie"}} {...handlerProps[1]} geometry={new Point(common.coords.PlaceDItalie)} /> </RLayerVector> </RMap> ); if (map.current === null) throw new Error('map.current is null'); const dummyLayer = new VectorTile(); const dummyGeom = new Point([0, 0]); map.current.ol.forEachFeatureAtPixel = jest.fn((pixel: Pixel, cb) => { if (ref[0].current === null || ref[1].current === null) throw new Error('Referenced feature not found'); if (pixel[0] === 10) return cb.call(this, ref[0].current.ol, dummyLayer, dummyGeom); if (pixel[0] === 20) return cb.call(this, ref[1].current.ol, dummyLayer, dummyGeom); throw new Error('unexpected'); }); for (const ev of mapEvents) { map.current?.ol.dispatchEvent(common.createEvent(ev, map.current.ol, 10)); map.current?.ol.dispatchEvent(common.createEvent(ev, map.current.ol, 20)); } expect(handlers[0]).toHaveBeenCalledTimes(mapEvents.length); expect(handlers[1]).toHaveBeenCalledTimes(mapEvents.length); expect(handlers[2]).toHaveBeenCalledTimes(0); // Second pass, test replacing handlers rerender( <RMap ref={map} {...common.mapProps}> <RLayerVector> <RFeature ref={ref[0]} properties={{name: 'Arc de Triomphe'}} {...handlerProps[2]} geometry={new Point(common.coords.ArcDeTriomphe)} /> <RFeature ref={ref[1]} properties={{name: "Place d'Italie"}} {...handlerProps[2]} geometry={new Point(common.coords.PlaceDItalie)} /> </RLayerVector> </RMap> ); for (const ev of mapEvents) { map.current?.ol.dispatchEvent(common.createEvent(ev, map.current.ol, 10)); map.current?.ol.dispatchEvent(common.createEvent(ev, map.current.ol, 20)); } expect(handlers[0]).toHaveBeenCalledTimes(mapEvents.length); expect(handlers[1]).toHaveBeenCalledTimes(mapEvents.length); expect(handlers[2]).toHaveBeenCalledTimes(mapEvents.length * 2); // Third pass, test removing handlers rerender( <RMap ref={map} {...common.mapProps}> <RLayerVector> <RFeature ref={ref[0]} properties={{name: 'Arc de Triomphe'}} geometry={new Point(common.coords.ArcDeTriomphe)} /> <RFeature ref={ref[1]} properties={{name: "Place d'Italie"}} geometry={new Point(common.coords.PlaceDItalie)} /> </RLayerVector> </RMap> ); for (const ev of mapEvents) { map.current?.ol.dispatchEvent(common.createEvent(ev, map.current.ol, 10)); map.current?.ol.dispatchEvent(common.createEvent(ev, map.current.ol, 20)); } expect(handlers[0]).toHaveBeenCalledTimes(mapEvents.length); expect(handlers[1]).toHaveBeenCalledTimes(mapEvents.length); expect(handlers[2]).toHaveBeenCalledTimes(mapEvents.length * 2); }); it('should generate pointerenter, pointerleave and pointerdragend', () => { const map = React.createRef() as React.RefObject<RMap>; const ref = [0, 1, 2].map(() => React.createRef() as React.RefObject<RFeature>); const mapEvents = ['PointerEnter', 'PointerLeave', 'PointerDragEnd']; const handlerProps = mapEvents.reduce( (ac, a) => ({ ...ac, ['on' + a]: jest.fn(common.handlerCheckContext(RFeature, ['map'], [map])) }), {} ); const {container} = render( <RMap ref={map} {...common.mapProps}> <RLayerVector> <RFeature ref={ref[0]} properties={{name: 'Arc de Triomphe'}} {...handlerProps} geometry={new Point(common.coords.ArcDeTriomphe)} /> <RFeature ref={ref[1]} properties={{name: "Place d'Italie"}} geometry={new Point(common.coords.PlaceDItalie)} /> <RFeature ref={ref[2]} properties={{name: "Arc de Triomphe' shadow"}} {...handlerProps} geometry={new Point(common.coords.ArcDeTriomphe)} /> </RLayerVector> </RMap> ); if (map.current === null) throw new Error('map.current is null'); const dummyLayer = new VectorTile(); const dummyGeom = new Point([0, 0]); map.current.ol.forEachFeatureAtPixel = jest.fn((pixel: Pixel, cb) => { if (ref[0].current === null || ref[1].current === null || ref[2].current === null) throw new Error('Referenced feature not found'); if (pixel[0] === 10) { if (cb.call(this, ref[0].current.ol, dummyLayer, dummyGeom)) return; return cb.call(this, ref[2].current.ol, dummyLayer, dummyGeom); } if (pixel[0] === 20) return cb.call(this, ref[1].current.ol, dummyLayer, dummyGeom); return undefined; }); map.current.ol.dispatchEvent(common.createEvent('pointermove', map.current.ol, 0)); expect(handlerProps['onPointerEnter']).toHaveBeenCalledTimes(0); map.current.ol.dispatchEvent(common.createEvent('pointermove', map.current.ol, 10)); expect(handlerProps['onPointerEnter']).toHaveBeenCalledTimes(2); expect(handlerProps['onPointerLeave']).toHaveBeenCalledTimes(0); map.current.ol.dispatchEvent(common.createEvent('pointermove', map.current.ol, 20)); expect(handlerProps['onPointerEnter']).toHaveBeenCalledTimes(2); expect(handlerProps['onPointerLeave']).toHaveBeenCalledTimes(2); map.current.ol.dispatchEvent(common.createEvent('pointermove', map.current.ol, 0)); map.current.ol.dispatchEvent(common.createEvent('pointermove', map.current.ol, 10)); map.current.ol.dispatchEvent(common.createEvent('pointermove', map.current.ol, 0)); expect(handlerProps['onPointerEnter']).toHaveBeenCalledTimes(4); expect(handlerProps['onPointerLeave']).toHaveBeenCalledTimes(4); map.current.ol.dispatchEvent(common.createEvent('pointerdrag', map.current.ol, 10, true)); map.current.ol.dispatchEvent(common.createEvent('pointermove', map.current.ol, 0)); expect(handlerProps['onPointerEnter']).toHaveBeenCalledTimes(4); expect(handlerProps['onPointerLeave']).toHaveBeenCalledTimes(4); expect(handlerProps['onPointerDragEnd']).toHaveBeenCalledTimes(2); expect(RFeature.lastFeaturesDragged.length).toBe(0); expect(RFeature.lastFeaturesEntered.length).toBe(0); }); it('should throw an error without a Layer', () => { const err = console.error; console.error = () => undefined; expect(() => render(<RFeature />)).toThrow('must be part of'); console.error = err; }); });
the_stack
import debounce from 'lodash.debounce'; import genSelectors from '../builders/selector'; import { localStorageGet } from '../Common/utils'; import { ActionType, BaseAction, ResizeAction, TagName } from '../types'; function isEventFromOverlay(event: Event) { return ( event .composedPath() .find((element) => (element as HTMLElement).id === 'overlay-controls') != null ); } /** * This is directly derived from: * https://github.com/microsoft/playwright/blob/4ff69529d410144b30bcdbde9497ad600141a6b8/packages/playwright-core/src/server/supplements/injected/recorder.ts#L449 */ function _shouldGenerateKeyPressFor(event: KeyboardEvent): boolean { // Backspace, Delete, AltGraph are changing input, will handle it there. if (['AltGraph', 'Backspace', 'Delete'].includes(event.key)) return false; // Ignore the QWERTZ shortcut for creating a at sign on MacOS if (event.key === '@' && event.code === 'KeyL') return false; // Allow and ignore common used shortcut for pasting. if (navigator.platform.includes('Mac')) { if (event.key === 'v' && event.metaKey) return false; } else { if (event.key === 'v' && event.ctrlKey) return false; if (event.key === 'Insert' && event.shiftKey) return false; } if (['Shift', 'Control', 'Meta', 'Alt'].includes(event.key)) return false; const hasModifier = event.ctrlKey || event.altKey || event.metaKey; if (event.key.length === 1 && !hasModifier) return false; return true; } function buildBaseAction( event: Event, overrideTarget?: HTMLElement ): BaseAction { const target = overrideTarget ?? (event.target as HTMLElement); return { isPassword: target instanceof HTMLInputElement && target.type.toLowerCase() === 'password', type: event.type as ActionType, tagName: target.tagName as TagName, inputType: target instanceof HTMLInputElement ? target.type : undefined, selectors: genSelectors(target) ?? {}, timestamp: event.timeStamp, hasOnlyText: target.children.length === 0 && target.innerText.length > 0, value: undefined, }; } class Recorder { private _recording: any[]; private currentEventHandleType: string | null = null; private onAction: any; private lastContextMenuEvent: MouseEvent | null = null; private appendToRecording = (action: any) => { this._recording.push(action); chrome.storage.local.set({ recording: this._recording }); if (this.onAction != null) { this.onAction(action, this._recording); } }; private updateLastRecordedAction = (actionUpdate: any) => { const lastAction = this._recording[this._recording.length - 1]; const newAction = { ...lastAction, ...actionUpdate, }; this._recording[this._recording.length - 1] = newAction; chrome.storage.local.set({ recording: this._recording }); if (this.onAction != null) { this.onAction(newAction, this._recording); } }; /** * * @param event * @returns true if it's already being handled somewhere else */ private checkAndSetDuplicateEventHandle = (event: Event) => { if (this.currentEventHandleType != null) { return true; // This is a duplicate handle } this.currentEventHandleType = event.type; setTimeout(() => { this.currentEventHandleType = null; }, 0); return false; // This was not a duplicate handle }; constructor({ onInitialized, onAction, }: { onInitialized?: any; onAction?: any; }) { this.onAction = onAction; this._recording = []; localStorageGet(['recording']).then(({ recording }) => { this._recording = recording; // Watch for changes to the recording from the background worker (when a SPA navigation happens) chrome.storage.onChanged.addListener((changes) => { if ( changes.recording != null && changes.recording.newValue != changes.recording.oldValue ) { this._recording = changes.recording.newValue; } }); window.addEventListener('click', this.onClick, true); window.addEventListener('contextmenu', this.onContextMenu, true); window.addEventListener('dragstart', this.onDrag, true); window.addEventListener('drop', this.onDrag, true); window.addEventListener('input', this.onInput, true); window.addEventListener('keydown', this.onKeyDown, true); window.addEventListener('resize', this.debouncedOnResize, true); window.addEventListener('wheel', this.onMouseWheel, true); // We listen to a context menu action chrome.runtime.onMessage.addListener(this.onBackgroundMessage); // Try capturing on start // Note: some browsers will fire 'resize' event on load this.onResize(); if (onInitialized != null) { onInitialized( this._recording?.[this._recording.length - 1], this._recording ); } }); } deregister() { window.removeEventListener('click', this.onClick, true); window.removeEventListener('contextmenu', this.onContextMenu, true); window.removeEventListener('dragstart', this.onDrag, true); window.removeEventListener('drop', this.onDrag, true); window.removeEventListener('input', this.onInput, true); window.removeEventListener('keydown', this.onKeyDown, true); window.removeEventListener('resize', this.debouncedOnResize, true); window.removeEventListener('wheel', this.onMouseWheel, true); } private onMouseWheel = (event: WheelEvent) => { if (isEventFromOverlay(event)) { return; } const lastAction = this._recording[this._recording.length - 1]; const { pageXOffset, pageYOffset } = window; if ( lastAction.type === 'wheel' && // We should record a new event if we've changed scroll directions Math.sign(lastAction.deltaX) === Math.sign(event.deltaX) && Math.sign(lastAction.deltaY) === Math.sign(event.deltaY) ) { this.updateLastRecordedAction({ deltaX: Math.floor(lastAction.deltaX + event.deltaX), deltaY: Math.floor(lastAction.deltaY + event.deltaY), pageXOffset, pageYOffset, }); } else { const action = { type: 'wheel', deltaX: Math.floor(event.deltaX), deltaY: Math.floor(event.deltaY), pageXOffset, pageYOffset, }; this.appendToRecording(action); } }; private onClick = (event: Event) => { if (event.isTrusted === false) { // Ignore synthetic events return; } if (isEventFromOverlay(event)) { return; } if (this.checkAndSetDuplicateEventHandle(event)) { return; } const target = event.target as HTMLElement; // Choose the parent element if it's a link, since we probably want the link const { parentElement } = target; const predictedTarget = parentElement?.tagName === 'A' ? parentElement : target; const action = { ...buildBaseAction(event, predictedTarget), }; // @ts-ignore this.appendToRecording(action); }; private onDrag = (event: DragEvent) => { if (isEventFromOverlay(event)) { return; } const lastAction = this._recording[this._recording.length - 1]; if (event.type === 'dragstart') { this.appendToRecording({ ...buildBaseAction(event), type: ActionType.DragAndDrop, sourceX: event.x, sourceY: event.y, }); } else if ( event.type === 'drop' && lastAction.type === ActionType.DragAndDrop ) { this.updateLastRecordedAction({ targetX: event.x, targetY: event.y, }); } }; private onKeyDown = (event: KeyboardEvent) => { if (isEventFromOverlay(event)) { return; } if (!_shouldGenerateKeyPressFor(event)) { return; } // We're committed to handling, check and set handling flag if (this.checkAndSetDuplicateEventHandle(event)) { return; } const action = { ...buildBaseAction(event), key: event.key, }; this.appendToRecording(action); }; private onContextMenu = (event: MouseEvent) => { if (isEventFromOverlay(event)) { return; } this.lastContextMenuEvent = event; }; private onBackgroundMessage = (request: any) => { // Context menu was clicked, pull last context menu element if ( request != null && request.type === 'onHoverCtxMenu' && this.lastContextMenuEvent != null ) { const action = { ...buildBaseAction(this.lastContextMenuEvent), type: 'hover', selectors: genSelectors( this.lastContextMenuEvent.target as HTMLElement ), }; this.appendToRecording(action); } if ( request != null && request.type === 'onAwaitTextCtxMenu' && this.lastContextMenuEvent != null ) { const action = { ...buildBaseAction(this.lastContextMenuEvent), type: 'awaitText', text: request.selectionText, selectors: genSelectors( this.lastContextMenuEvent.target as HTMLElement ), }; this.appendToRecording(action); } }; private onInput = (event: Event) => { if (isEventFromOverlay(event)) { return; } if (this.checkAndSetDuplicateEventHandle(event)) { return; } const target = event.target as HTMLInputElement; const selectors = genSelectors(target); const lastAction = this._recording[this._recording.length - 1]; // If the last event was also an input and for the same element, update the last event with the latest input if ( lastAction.type === 'input' && lastAction.selectors.generalSelector === selectors?.generalSelector ) { this.updateLastRecordedAction({ value: target?.value, timestamp: event.timeStamp, }); } else { const action = { ...buildBaseAction(event), // @ts-ignore value: target?.value, }; this.appendToRecording(action); } }; private onResize = () => { const lastResizeAction = this.getLastResizeAction(); const { innerWidth: width, innerHeight: height } = window; if ( lastResizeAction == null || lastResizeAction.width !== width || lastResizeAction.height !== height ) { const action = { type: ActionType.Resize, width, height, }; this.appendToRecording(action); } }; private getLastResizeAction = (): ResizeAction => { return this._recording.reduceRight((p, v) => { if (p != null) { return p; } if (v.type === 'resize') { return v; } }, null); }; private debouncedOnResize = debounce(this.onResize, 300); public onFullScreenshot = (): void => { const action = { type: ActionType.FullScreenshot, }; this.appendToRecording(action); }; } export default Recorder;
the_stack
import { SourceType } from 'coffee-lex'; import SourceTokenListIndex from 'coffee-lex/dist/SourceTokenListIndex'; import { Conditional } from 'decaffeinate-parser/dist/nodes'; import { PatcherContext, PatchOptions } from '../../../patchers/types'; import getEnclosingScopeBlock from '../../../utils/getEnclosingScopeBlock'; import notNull from '../../../utils/notNull'; import NodePatcher from './../../../patchers/NodePatcher'; import BlockPatcher from './BlockPatcher'; export default class ConditionalPatcher extends NodePatcher { node!: Conditional; condition: NodePatcher; consequent: BlockPatcher | null; alternate: BlockPatcher | null; negated = false; constructor( patcherContext: PatcherContext, condition: NodePatcher, consequent: BlockPatcher | null, alternate: BlockPatcher | null ) { super(patcherContext); this.condition = condition; this.consequent = consequent; this.alternate = alternate; } initialize(): void { this.condition.setRequiresExpression(); getEnclosingScopeBlock(this).markIIFEPatcherDescendant(this); } /** * Anything like `break`, `continue`, or `return` inside a conditional means * we can't even safely make it an IIFE. */ canPatchAsExpression(): boolean { if (this.consequent && !this.consequent.canPatchAsExpression()) { return false; } if (this.alternate && !this.alternate.canPatchAsExpression()) { return false; } return true; } prefersToPatchAsExpression(): boolean { const { consequent, alternate } = this; if (!consequent || !alternate) { return false; } return consequent.prefersToPatchAsExpression() && alternate.prefersToPatchAsExpression(); } setExpression(force = false): boolean { const willPatchAsExpression = super.setExpression(force); if (willPatchAsExpression && this.willPatchAsTernary()) { if (this.consequent) { this.consequent.setRequiresExpression(); } if (this.alternate) { this.alternate.setRequiresExpression(); } return true; } return false; } negate(): void { this.negated = !this.negated; } willPatchAsTernary(): boolean { return ( this.prefersToPatchAsExpression() || (this.forcedToPatchAsExpression() && (!this.consequent || this.consequent.prefersToPatchAsExpression()) && (!this.alternate || this.alternate.prefersToPatchAsExpression())) ); } /** * @private */ willPatchAsIIFE(): boolean { return !this.willPatchAsTernary() && this.forcedToPatchAsExpression(); } patchAsExpression({ needsParens }: PatchOptions = {}): void { const addParens = this.negated || (needsParens && !this.isSurroundedByParentheses()); // `if a then b` → `a then b` // ^^^ this.overwrite(this.contentStart, this.condition.outerStart, `${this.negated ? '!' : ''}${addParens ? '(' : ''}`); if (this.node.isUnless) { this.condition.negate(); } this.condition.patch(); const thenTokenIndex = this.getThenTokenIndex(); if (thenTokenIndex) { const thenToken = notNull(this.sourceTokenAtIndex(thenTokenIndex)); // `a then b` → `a ? b` // ^^^^ ^ this.overwrite(thenToken.start, thenToken.end, '?'); } else { // `a b` → `a ? b` // ^^ this.insert(this.condition.outerEnd, ' ?'); } const elseTokenIndex = this.getElseSourceTokenIndex(); const elseToken = elseTokenIndex && this.sourceTokenAtIndex(elseTokenIndex); const { consequent, alternate } = this; if (consequent && alternate) { if (!elseToken) { throw this.error('Expected else token in conditional.'); } consequent.patch(); // `a ? b else c` → `a ? b : c` this.overwrite(elseToken.start, elseToken.end, ':'); alternate.patch(); } else if (consequent && !alternate) { consequent.patch(); // `a ? b` → `a ? b : undefined` if (elseToken !== null) { this.overwrite(elseToken.start, elseToken.end, ' : undefined'); } else { this.insert(consequent.outerEnd, ' : undefined'); } } else if (alternate) { if (!elseToken) { throw this.error('Expected else token in conditional.'); } // We might have just a semicolon as the consequent. In that case, it will be null in the AST // but we will need to remove it. const semicolonTokenIndex = this.indexOfSourceTokenBetweenSourceIndicesMatching( this.condition.outerEnd, elseToken.start, (token) => token.type === SourceType.SEMICOLON ); if (semicolonTokenIndex) { const semicolonToken = this.sourceTokenAtIndex(semicolonTokenIndex); if (semicolonToken) { this.remove(semicolonToken.start, semicolonToken.end); } } this.overwrite(elseToken.start, elseToken.end, 'undefined :'); alternate.patch(); } else { if (elseToken !== null) { this.overwrite(elseToken.start, elseToken.end, 'undefined : undefined'); } else { this.insert(this.condition.outerEnd, ' undefined : undefined'); } } if (addParens) { this.insert(this.contentEnd, ')'); } } patchAsForcedExpression(): void { if (this.willPatchAsTernary()) { // We didn't want to be an expression because we don't have an alternate, // which means that the alternate of a generated ternary would be // `undefined`, which is ugly (i.e. `if a then b` → `a ? b : undefined`). // TODO: Generate a `do` expression instead? (i.e. `do { if (a) { b; } }`) this.patchAsExpression(); } else if (this.willPatchAsIIFE()) { this.patchAsIIFE(); } } patchAsIIFE(): void { if (this.negated) { this.insert(this.innerStart, '!'); } // We're only patched as an expression due to a parent instructing us to, // and the indent level is more logically the indent level of our parent. const baseIndent = notNull(this.parent).getIndent(0); const conditionIndent = notNull(this.parent).getIndent(1); if (this.consequent) { this.consequent.setShouldPatchInline(false); this.consequent.setImplicitlyReturns(); } if (this.alternate) { this.alternate.setShouldPatchInline(false); this.alternate.setImplicitlyReturns(); } this.patchInIIFE(() => { this.insert(this.innerStart, `\n${conditionIndent}`); this.patchAsStatement(); this.insert(this.innerEnd, `\n${baseIndent}`); }); } canHandleImplicitReturn(): boolean { return this.willPatchAsIIFE(); } patchAsStatement(): void { this.patchConditionForStatement(); this.patchConsequentForStatement(); this.patchAlternateForStatement(); } /** * @private */ patchConditionForStatement(): void { // `unless a` → `if a` // ^^^^^^ ^^ const ifToken = notNull(this.sourceTokenAtIndex(this.getIfSourceTokenIndex())); this.overwrite(ifToken.start, ifToken.end, 'if'); const conditionHasParentheses = this.condition.isSurroundedByParentheses(); if (!conditionHasParentheses) { // `if a` → `if (a` // ^ this.insert(this.condition.outerStart, '('); } if (this.node.isUnless) { this.condition.negate(); } this.condition.patch({ needsParens: false }); if (!conditionHasParentheses) { // `if (a` → `if (a)` // ^ this.insert(this.condition.outerEnd, ')'); } const thenTokenIndex = this.getThenTokenIndex(); if (thenTokenIndex) { const thenToken = notNull(this.sourceTokenAtIndex(thenTokenIndex)); // `if (a) then b` → `if (a) b` // ^^^^^ if (this.consequent) { this.remove(thenToken.start, this.consequent.outerStart); } else { this.remove(thenToken.start, thenToken.end); } } } /** * @private */ patchConsequentForStatement(): void { this.insert(this.condition.outerEnd, ' {'); if (this.alternate) { const elseTokenIndex = notNull(this.getElseSourceTokenIndex()); const elseToken = notNull(this.sourceTokenAtIndex(elseTokenIndex)); const rightBracePosition = elseToken.start; if (this.consequent !== null) { this.consequent.patch({ leftBrace: false, rightBrace: false }); } this.insert(rightBracePosition, '} '); } else { if (this.consequent !== null) { this.consequent.patch({ leftBrace: false }); } else { this.insert(this.condition.outerEnd, '} '); } } } /** * @private */ patchAlternateForStatement(): void { const elseTokenIndex = this.getElseSourceTokenIndex(); if (this.alternate && elseTokenIndex) { const ifToken = this.sourceTokenAtIndex(notNull(elseTokenIndex.next())); const isElseIf = ifToken ? ifToken.type === SourceType.IF : false; if (isElseIf) { // Let the nested ConditionalPatcher handle braces. this.alternate.patch({ leftBrace: false, rightBrace: false }); } else { const elseToken = notNull(this.sourceTokenAtIndex(elseTokenIndex)); const leftBracePosition = elseToken.end; this.insert(leftBracePosition, ' {'); this.alternate.patch({ leftBrace: false }); } } else if (elseTokenIndex !== null) { const elseToken = notNull(this.sourceTokenAtIndex(elseTokenIndex)); this.insert(elseToken.end, ' {}'); } else if (super.implicitlyReturns()) { const emptyImplicitReturnCode = this.implicitReturnPatcher().getEmptyImplicitReturnCode(); if (emptyImplicitReturnCode) { this.insert(this.innerEnd, ' else {\n'); this.insert(this.innerEnd, `${this.getIndent(1)}${emptyImplicitReturnCode}\n`); this.insert(this.innerEnd, `${this.getIndent()}}`); } } } /** * If we ended up as a statement, then we know our children are set as * implicit return nodes, so no need to turn the conditional into an * expression for implicit return purposes. */ implicitlyReturns(): boolean { return super.implicitlyReturns() && this.willPatchAsExpression(); } setImplicitlyReturns(): void { super.setImplicitlyReturns(); if (this.consequent) { this.consequent.setImplicitlyReturns(); } if (this.alternate) { this.alternate.setImplicitlyReturns(); } } /** * Conditionals do not need semicolons when used as statements. */ statementNeedsSemicolon(): boolean { return false; } /** * Gets the index of the token representing the `if` at the start. * * @private */ getIfSourceTokenIndex(): SourceTokenListIndex { const ifTokenIndex = this.indexOfSourceTokenStartingAtSourceIndex(this.contentStart); if (!ifTokenIndex) { throw this.error('expected IF token at start of conditional'); } const ifToken = notNull(this.sourceTokenAtIndex(ifTokenIndex)); if (ifToken.type !== SourceType.IF) { throw this.error(`expected IF token at start of conditional, but got ${SourceType[ifToken.type]}`); } return ifTokenIndex; } /** * Gets the index of the token representing the `else` between consequent and * alternate. * * @private */ getElseSourceTokenIndex(): SourceTokenListIndex | null { const elseTokenIndex = this.indexOfSourceTokenBetweenSourceIndicesMatching( this.consequent !== null ? this.consequent.outerEnd : this.condition.outerEnd, this.alternate !== null ? this.alternate.outerStart : this.outerEnd, (token) => token.type === SourceType.ELSE ); if (this.alternate !== null && !elseTokenIndex) { throw this.error( 'expected ELSE token between consequent and alternate', this.consequent !== null ? this.consequent.outerEnd : this.condition.outerEnd, this.alternate.outerStart ); } return elseTokenIndex; } /** * Gets the index of the token representing the `then` between condition and * consequent. * * @private */ getThenTokenIndex(): SourceTokenListIndex | null { let searchEnd; if (this.consequent) { searchEnd = this.consequent.outerStart; } else if (this.alternate) { searchEnd = this.alternate.outerStart; } else { const nextToken = this.nextSemanticToken(); if (nextToken) { searchEnd = nextToken.end; } else { searchEnd = this.contentEnd; } } return this.indexOfSourceTokenBetweenSourceIndicesMatching( this.condition.outerEnd, searchEnd, (token) => token.type === SourceType.THEN ); } /** * Conditionals have all code paths if there is an `else` and both the * consequent and alternate have all their code paths. */ allCodePathsPresent(): boolean { if (!this.consequent || !this.alternate) { return false; } return this.consequent.allCodePathsPresent() && this.alternate.allCodePathsPresent(); } }
the_stack
import { DownloadMethod, DownloadQuality, IEpisode, Intent, IRuntimeMessage, Server, } from "../common"; import * as utils from "../utils"; import * as api from "./api"; import {IFile} from "./api"; // We need this value while sending API requests. let ts = ""; // Name of the current anime. let animeName = ""; // We will use this to send message to tabs. let sender: chrome.runtime.MessageSender; // Keeps track of the download cycles. Each cycle starts // at downloader and end before requeue is called. // let inProgress = false; // This variable holds all links when method external is selected. // The links are then resolved via promise which then shows up in // the users tab. let aggregateLinks = ""; // The episodes that the users selected in the epModal are stored // here. These are the episodes that will be downloaded. let selectedEpisodes: IEpisode[] = []; // This is the episode that we are currently trying to download. let dlEpisode: IEpisode; // 9anime Companion can only download from 1 server at a time. This // variable holds the type of server from which we are currently // downloading/will download. let server: Server = Server.Default; let serverId = 22; // default F2 server // The preferred quality of the files to download. let quality: DownloadQuality = DownloadQuality["360p"]; // The preferred download method. let method: DownloadMethod = DownloadMethod.Browser; interface ISetupOptions { animeName: string; method: DownloadMethod; quality: DownloadQuality; selectedEpisodes: IEpisode[]; sender: chrome.runtime.MessageSender; /* we need this to send messages to tab */ server: Server; serverId: number; ts: string; } // Setup export function setup(options: ISetupOptions): void { // first we clear off the previous aggregate links aggregateLinks = ""; // Then we setup animeName = options.animeName; method = options.method; quality = options.quality; selectedEpisodes = options.selectedEpisodes; sender = options.sender; server = options.server; serverId = options.serverId; ts = options.ts; } /* --- 26-11-2017 --- */ // 9anime's new encryption // A special thanks to @hoppler (https://github.com/hoppler) for // helping out with decryptTs and rot8. const decryptTs = (str: string) => { let result = ""; const firstCharMap = []; const secondCharMap = []; for (let n = 65; n < 91; n++) { firstCharMap.push(String.fromCharCode(n)); if (n % 2 !== 0) { secondCharMap.push(String.fromCharCode(n)); } } for (let n = 65; n < 91; n++) { if (n % 2 === 0) { secondCharMap.push(String.fromCharCode(n)); } } for (let i = 0; i < str.length; i++) { let charReplaced = false; for (let y = 0; y < secondCharMap.length; y++) { if (str[i] === secondCharMap[y]) { result += firstCharMap[y]; charReplaced = true; break; } } if (!charReplaced) { result += str[i]; } } return atob(result); }; function decryptTokenAndOptions(str: string) { /* line: 14138, all.js */ const cleanStr = str.replace(/^-/, ""); const firstCharMap = []; const secondCharMap = []; for (let j = 97; j <= 122; j++) { firstCharMap.push(String.fromCharCode(j)); if (j % 2) { secondCharMap.push(String.fromCharCode(j)); } } for (let k = 97; k <= 122; k++) { if (k % 2 === 0) { secondCharMap.push(String.fromCharCode(k)); } } /* --- */ let result = ""; for (let e = 0; e < cleanStr.length; e++) { let replaced = false; for (let f = 0; f < secondCharMap.length; f++) { if (cleanStr[e] === secondCharMap[f]) { result += firstCharMap[f]; replaced = true; break; } } if (!replaced) { result += cleanStr[e]; } } /* --- */ return atob(result); } /*const rot8 = (str: string) => { const i = -18; const e = []; for (let q = 1; q < str.length; q++) { const intChar = str[q].charCodeAt(0); let newChar = 0; if (intChar >= 97 && intChar <= 122) { newChar = (intChar - 71 + i) % 26 + 97; } else if (intChar >= 65 && intChar <= 90) { newChar = (intChar - 39 + i) % 26 + 65; } else { newChar = intChar; } e.push(newChar); } return e .map(c => String.fromCharCode(c)) .join(""); };*/ /* --- ~~~ --- */ /** * Send messages to the tab/content script. */ function sendMessage(message: IRuntimeMessage): void { if (sender.tab && sender.tab.id) { chrome.tabs.sendMessage(sender.tab.id, message); } } /** * A simple wrapper around sendMessage * @see sendMessage */ function status(message: string): void { sendMessage({ intent: Intent.Download_Status, status: message, }); } /** * A simple helper function that generates a filename. * @param file * The current episode file * @param episode * episode data, i.e: id and num * @param ext * boolean value; should extension (ex: mp4) be part * of the title. Defaults to true. * @returns filename */ export function fileName(file: api.IFile, episode: IEpisode, ext = true): string { if (ext) { return utils.fileSafeString(`${animeName}_E${episode.num }_${file.label}`) + `.${file.type}`; } else { return utils.fileSafeString(`${animeName}_E${episode.num }_${file.label}`); } } /** * Returns: * - a file of users preferred quality from a list of files, * - or, if preferred quality is missing, returns the next lower quality, * - or, ff there are no lower qualities then same quality is returned * @param pref * The preferred quality. * @param files * The list of files from which we choose. * @returns * A file with preferred quality or the next lower quality. * @see {@link https://git.io/vQdkt} for the unit tests. */ export function autoFallback(pref: DownloadQuality, files: api.IFile[]): api.IFile | null { // Start at the preferred quality, then count down. for (let i = pref; i >= DownloadQuality["360p"]; i--) { // for each "quality" we loop through episodes // and see if we find a suitable match. for (let file of files) { if (file.label === DownloadQuality[i]) { return file; } } } // Meaning fallback failed. This can happen // if the preferred quality is invalid, ex: // Quality["555p"] etc return null; } /** * This function requeue's the downloader to run every * 2 seconds to avoid overloading the 9anime API and/or * getting our IP flagged as bot. */ function requeue(): void { if (selectedEpisodes.length > 0) { setTimeout(downloader, 2000); } else { // Send the last status message! status("All done!"); // Send the final intent! if (method === DownloadMethod.Browser) { sendMessage({ intent: Intent.Download_Complete, }); } else { sendMessage({ intent: Intent.Download_Complete, links: aggregateLinks, }); } } } function startDownload(file: IFile): void { switch (method) { case DownloadMethod.External: // the "?" is important after file.file aggregateLinks += `${file.file}?title=${fileName(file, dlEpisode, false)}&type=${file.type}\n`; status(`✔ Completed ${dlEpisode.num}`); break; default: chrome.downloads.download({ conflictAction: "uniquify", // this means, downloads will go to the 9anime Companion // subdirectory, inside the default download directory. filename: "9anime Companion/" + fileName(file, dlEpisode), url: file.file, }); status(`✔ Completed ${dlEpisode.num}`); break; } } function getLinks9a(data: api.IGrabber): void { api .links9a(data.grabber, { id: data.params.id, mobile: 0, options: decryptTokenAndOptions(data.params.options), token: decryptTokenAndOptions(data.params.token), ts: decryptTs(ts), }) .then(resp => { // console.log(resp); let file = autoFallback(quality, resp.data); if (!file) { status(`❌ Failed ${dlEpisode.num}. No fallback quality found. Use a higher preferred quality.`); return; } startDownload(file); }) .catch(err => { console.debug(err); status(`❌ Failed ${dlEpisode.num}`); }) // The last then acts like a finally. .then(() => { // inProgress = false; requeue(); }); } /** * Parse a source string of the form below and return a object. * <source src="https://xxx/xxx.mp4" type="video/mp4" title="720p" data-res="720" /> * @param {string} source * The source string */ function rvParseEpisodeDetails(source: string): IFile | null { let episodeDetails: IFile = { file: "", label: "", type: "", }; source.split(" ").forEach((el: string) => { let rvEpData = el.split("="); if (rvEpData.length === 2) { let value = rvEpData[1].replace(/["']/g, ""); // console.log(rvEpData[1], value); switch (rvEpData[0]) { case "src": episodeDetails.file = value; break; case "type": episodeDetails.type = value.replace("video/", ""); break; case "title": episodeDetails.label = value; break; default: break; } } }); if (episodeDetails.file === "" || episodeDetails.label === "" || episodeDetails.type === "") { return null; } else { return episodeDetails; } } // To get the links we basically scrap the RapidVideo link using regex. // TODO: try implementing fallback for rapidvideo downloads later export function getLinksRV(data: api.IGrabber): void { const rvSourcesRegex = /<source(.*)\/>/i; // decryptTokenAndOptions works for token, options and target. // const endpoint = decryptTokenAndOptions(data.target) + `?q=${DownloadQuality[quality]}`; // 18-12-2017 // looks like 9anime removed the encryption from RapidVideo target const endpoint = data.target + `?q=${DownloadQuality[quality]}`; fetch(endpoint) .then(response => { if (response.ok) { return response.text(); } throw new Error(response.status.toString()); }) .then(resp => { // We are looking for this specific line in the RapidVideo html file. // <source src="https://xxx/xxx.mp4" type="video/mp4" title="720p" data-res="720" /> let matched = resp.match(rvSourcesRegex); if (matched) { let rvEpisodeDetails = rvParseEpisodeDetails(matched[0]); // console.log(rvEpisodeDetails); if (rvEpisodeDetails && rvEpisodeDetails.label === DownloadQuality[quality]) { startDownload(rvEpisodeDetails); } else { status(`❌ Failed ${dlEpisode.num}. Preferred quality not found. Try changing the quality.`); return; } } else { status(`❌ Failed ${dlEpisode.num}. Preferred quality not found. Try changing the quality.`); return; } }) .catch(err => { console.debug(err); status(`❌ Failed ${dlEpisode.num}`); }) // The last then acts like a finally. .then(() => { // inProgress = false; requeue(); }); } /** * The boss function. It handles the entire downloading * process. */ export function downloader(): void { let ep = selectedEpisodes.shift(); if (ep) { // inProgress = true; dlEpisode = ep; status(`Downloading ${ep.num}`); api .grabber({ id: ep.id, server: serverId, ts: decryptTs(ts), update: 0, }) .then(resp => { // console.log(resp); // Server can either be RapidVideo or Default. // For Default, we make use of default case. switch (server) { case Server.RapidVideo: getLinksRV(resp); break; default: getLinks9a(resp); break; } }) .catch(err => { status(`❌ Failed ${(ep as IEpisode).num}`); console.debug(err); // getLinks9a automatically requeue downloads, but // that happens only after the download link is fetched. // But what if the download fails after trying to get // the grabber? We must requeue it again from here. // inProgress = false; requeue(); }); } } /** * Triggers the download process. * @param baseUrl * The baseUrl of the 9anime site. * Ex: https://9anime.to, https://9anime.is etc * @param setupOptions * Setup options for download all */ export function start(baseUrl: string, setupOptions: ISetupOptions): void { // TODO: support queues for download // NOTE: // 9ac **DOES NOT** support queues for download. So if you // are trying to download from multiple tabs, chances are // yor downloads might not go as expected. Please wait till // one set of download is over before starting again. api.setup({ /* setup the API */ baseUrl, }); setup(setupOptions); /* setup download all */ downloader(); /* trigger download */ sendMessage({ intent: Intent.Show_Notification, message: "Sit tight!", title: "Starting downloads", }); }
the_stack
import React, { useEffect, useState, useRef, RefObject, FunctionComponent, RefCallback, } from "react"; import useResizeObserver from "../"; import { createComponentHandler, Observed, render, HandlerReceiver, ObservedSize, MultiHandlerResolverComponentProps, ComponentHandler, HandlerResolverComponentProps, } from "./utils"; import awaitNextFrame from "./utils/awaitNextFrame"; describe("Vanilla tests", () => { it("should render with undefined sizes at first", async () => { const handler = await render(Observed); handler.assertDefaultSize(); }); it("should render with custom defaults", async () => { const { assertSize } = await render( Observed, {}, { defaultWidth: 24, defaultHeight: 42, } ); // By running this assertion immediately, it should check the default values // instead ot the first on-mount measurement. assertSize({ width: 24, height: 42 }); }); it("should follow size changes correctly with appropriate render count and without sub-pixels as they're used in CSS", async () => { const { setAndAssertSize, setSize, assertSize, assertRenderCount } = await render(Observed, { waitForFirstMeasurement: true }); // Default render + first measurement assertRenderCount(2); await setAndAssertSize({ width: 100, height: 200 }); assertRenderCount(3); setSize({ width: 321, height: 456 }); await awaitNextFrame(); assertSize({ width: 321, height: 456 }); assertRenderCount(4); }); it("should handle multiple instances", async () => { const Test: FunctionComponent<MultiHandlerResolverComponentProps> = ({ resolveHandler, }) => { let resolveHandler1: HandlerReceiver = () => {}; let resolveHandler2: HandlerReceiver = () => {}; const handlersPromise = Promise.all([ new Promise<ComponentHandler>( (resolve) => (resolveHandler1 = resolve as HandlerReceiver) ), new Promise<ComponentHandler>( (resolve) => (resolveHandler2 = resolve as HandlerReceiver) ), ]); useEffect(() => { handlersPromise.then( ([handler1, handler2]: [ComponentHandler, ComponentHandler]) => { resolveHandler([handler1, handler2]); } ); }, []); return ( <> <Observed resolveHandler={resolveHandler1} /> <Observed resolveHandler={resolveHandler2} /> </> ); }; const [handler1, handler2] = await render(Test, { waitForFirstMeasurement: true, }); await handler1.setAndAssertSize({ width: 100, height: 200 }); await handler2.setAndAssertSize({ width: 300, height: 400 }); // By the first measurement the component would've rendered three times: // - First natural render with "undefined" values // - Second with whatever size the window is // - Third render with the values set above handler1.assertRenderCount(3); handler2.assertRenderCount(3); await handler2.setAndAssertSize({ width: 321, height: 456 }); handler1.assertRenderCount(3); handler2.assertRenderCount(4); // Instance No. 1 should still be at the previous state. handler1.assertSize({ width: 100, height: 200 }); }); it("should handle custom refs", async () => { const Test: FunctionComponent<HandlerResolverComponentProps> = ({ resolveHandler, }) => { const ref = useRef(null); const { width, height } = useResizeObserver({ ref }); const currentSizeRef = useRef<ObservedSize>({} as ObservedSize); currentSizeRef.current.height = height; currentSizeRef.current.width = width; useEffect(() => { resolveHandler(createComponentHandler({ currentSizeRef })); }, []); return ( <div ref={ref} style={{ width: 100, height: 200 }}> {width}x{height} </div> ); }; const handler = await render(Test); // Default handler.assertDefaultSize(); // Actual measurement await awaitNextFrame(); handler.assertSize({ width: 100, height: 200 }); }); it("should be able to reuse the same ref to measure different elements", async () => { let switchRefs = (): void => { throw new Error(`"switchRefs" should've been implemented by now.`); }; const Test = ({ resolveHandler }: { resolveHandler: HandlerReceiver }) => { const ref1 = useRef<HTMLDivElement>(null); const ref2 = useRef<HTMLDivElement>(null); const [stateRef, setStateRef] = useState<RefObject<HTMLDivElement>>(ref1); // Measures ref1 first const sizeRef = useRef(null); const { width, height } = useResizeObserver({ ref: stateRef }); const currentSizeRef = useRef<ObservedSize>({ width: undefined, height: undefined, }); currentSizeRef.current.width = width; currentSizeRef.current.height = height; useEffect(() => { // Measures the second div on demand switchRefs = () => setStateRef(ref2); resolveHandler(createComponentHandler({ currentSizeRef })); }, []); return ( <> <div ref={sizeRef}> {width}x{height} </div> <div ref={ref1} style={{ width: 100, height: 200 }} /> <div ref={ref2} style={{ width: 150, height: 250 }} /> </> ); }; const handler = await render(Test); // Default handler.assertDefaultSize(); // Div 1 measurement await awaitNextFrame(); handler.assertSize({ width: 100, height: 200 }); // Div 2 measurement switchRefs(); await awaitNextFrame(); handler.assertSize({ width: 150, height: 250 }); }); it("should be able to render without mock defaults", async () => { const handler = await render(Observed); // Default values should be undefined handler.assertDefaultSize(); handler.setSize({ width: 100, height: 100 }); await awaitNextFrame(); handler.assertSize({ width: 100, height: 100 }); }); it("should not trigger unnecessary renders with the same width or height", async () => { const handler = await render(Observed); handler.assertDefaultSize(); // Default render + first measurement await awaitNextFrame(); handler.assertRenderCount(2); handler.setSize({ width: 100, height: 102 }); await awaitNextFrame(); handler.assertSize({ width: 100, height: 102 }); handler.assertRenderCount(3); // Shouldn't trigger on subpixel values that are rounded to be the same as the // previous size handler.setSize({ width: 100.4, height: 102.4 }); await awaitNextFrame(); handler.assertSize({ width: 100, height: 102 }); handler.assertRenderCount(3); }); it("should keep the same response instance between renders if nothing changed", async () => { let assertSameInstance = (): void => { throw new Error( `"assertSameInstance" should've been implemented by now.` ); }; const Test: FunctionComponent<HandlerResolverComponentProps> = ({ resolveHandler, }) => { const previousResponseRef = useRef< | ({ ref: RefCallback<HTMLElement>; } & ObservedSize) | null >(null); const response = useResizeObserver<HTMLDivElement>(); const [state, setState] = useState(false); const sameInstance = previousResponseRef.current === response; previousResponseRef.current = response; useEffect(() => { if (response.width && response.height) { // Triggering an extra render once the hook properly measured the element size once. // This'll allow us to see if the hook keeps the same response object or not. setState(true); } }, [response]); useEffect(() => { if (!state) { return; } assertSameInstance = () => { expect(sameInstance).toBe(true); }; // Everything is set up, ready for assertions resolveHandler({}); }, [state]); return <div ref={response.ref}>{String(sameInstance)}</div>; }; await render(Test); assertSameInstance(); }); it("should ignore invalid custom refs", async () => { const Test: FunctionComponent<HandlerResolverComponentProps> = ({ resolveHandler, }) => { // Passing in an invalid custom ref. // Same should be work if "null" or something similar gets passed in. const { width, height } = useResizeObserver({ ref: {} as RefObject<HTMLDivElement>, }); const currentSizeRef = useRef<ObservedSize>({} as ObservedSize); currentSizeRef.current.width = width; currentSizeRef.current.height = height; useEffect(() => { resolveHandler(createComponentHandler({ currentSizeRef })); }, []); return ( <div> {width}x{height} </div> ); }; const handler = await render(Test); // Since no refs were passed in with an element to be measured, the hook should // stay on the defaults await awaitNextFrame(); handler.assertDefaultSize(); }); it("should be able to work with onResize instead of rendering the values", async () => { const observations: ObservedSize[] = []; const handler = await render( Observed, {}, { onResize: (size: ObservedSize) => observations.push(size) } ); handler.setSize({ width: 100, height: 200 }); await awaitNextFrame(); handler.setSize({ width: 101, height: 201 }); await awaitNextFrame(); // Should stay at default as width/height is not passed to the hook response // when an onResize callback is given handler.assertDefaultSize(); expect(observations.length).toBe(2); expect(observations[0]).toEqual({ width: 100, height: 200 }); expect(observations[1]).toEqual({ width: 101, height: 201 }); // Should render once on mount only handler.assertRenderCount(1); }); it("should handle if the onResize handler changes properly with the correct render counts", async () => { let changeOnResizeHandler: (fn: Function) => void = () => {}; const Test: FunctionComponent<HandlerResolverComponentProps> = ({ resolveHandler, ...props }) => { const [onResizeHandler, setOnResizeHandler] = useState(() => () => {}); changeOnResizeHandler = (handler) => setOnResizeHandler(() => handler); return ( <Observed {...props} onResize={onResizeHandler} resolveHandler={resolveHandler} /> ); }; const { assertRenderCount, setSize } = await render(Test, { waitForFirstMeasurement: true, }); // Since `onResize` is used, no extra renders should've been triggered at this // point. (As opposed to the defaults where the hook would trigger a render // with the first measurement.) assertRenderCount(1); const observations1: ObservedSize[] = []; const observations2: ObservedSize[] = []; // Establishing a default, which'll be measured when the resize handler is set. setSize({ width: 1, height: 1 }); await awaitNextFrame(); assertRenderCount(1); changeOnResizeHandler((size: ObservedSize) => observations1.push(size)); await awaitNextFrame(); setSize({ width: 1, height: 2 }); await awaitNextFrame(); setSize({ width: 3, height: 4 }); assertRenderCount(2); await awaitNextFrame(); changeOnResizeHandler((size: ObservedSize) => observations2.push(size)); await awaitNextFrame(); setSize({ width: 5, height: 6 }); await awaitNextFrame(); setSize({ width: 7, height: 8 }); await awaitNextFrame(); assertRenderCount(3); expect(observations1.length).toBe(2); expect(observations1[0]).toEqual({ width: 1, height: 2 }); expect(observations1[1]).toEqual({ width: 3, height: 4 }); expect(observations2.length).toBe(2); expect(observations2[0]).toEqual({ width: 5, height: 6 }); expect(observations2[1]).toEqual({ width: 7, height: 8 }); }); });
the_stack
import { scan } from "../parser/parser"; import * as parseXml from '../parser/types'; import * as Syntax from '../parser/syntax'; import { WidgetModel, ExtraDataModel } from "../models/models"; import { makeVariableName, makePipeUniqueName } from "../utils"; export class PipeValueResolver { resolve(element: parseXml.Element, name: string, value: string, widget: WidgetModel, addReturn = true): { wrapperWidget: WidgetModel | null, extraData: ExtraDataModel | null, value: string } { let wrapperWidget: WidgetModel | null = null; let extraData: ExtraDataModel | null = null; value = this.prepareValue(value); const pipesResult = this.resolvePipes(value); const groupedPipesValues: any = {}; if (pipesResult.groupedPipes) { // apply grouped pipes (all pipes that are between braces) pipesResult.groupedPipes.forEach(groupedPipe => { ({ value, wrapperWidget } = this.applyPipes(value, groupedPipe, wrapperWidget, widget, name, addReturn)); const pipesNames = makePipeUniqueName(groupedPipe); // store pipe actual values groupedPipesValues[pipesNames] = value; }); } // apply not-grouped pipes ({ value, wrapperWidget } = this.applyPipes(value, pipesResult, wrapperWidget, widget, name, addReturn)); // replace pipe values' placeholders with their actual values if (pipesResult.groupedPipes) { pipesResult.groupedPipes.forEach(groupedPipe => { const pipesNames = makePipeUniqueName(groupedPipe); const placeholder = '_placeholder_for_' + pipesNames + '_pipes'; value = value.replace(placeholder, groupedPipesValues[pipesNames]); if (wrapperWidget) { wrapperWidget.properties.filter(p => typeof p.value === 'string').forEach(prop => { prop.value = (prop.value as String).replace(placeholder, groupedPipesValues[pipesNames]); }); } }); } return { wrapperWidget, extraData, value }; } private isBoundValue(value: any): boolean { return !!value && typeof value === 'string' && value.startsWith('{{') && value.endsWith('}}'); } private prepareValue(value: string): string { if (this.isBoundValue(value)) { return value.substring(2, value.length - 2); } return value; } // // stream & future builders // createStreamBuilder(value: string, initialValue: any, resultVarName: string, widget: WidgetModel, propertyName: string, addReturn: boolean, addNullChecking = true, addLocalVar = true) { return this.createCustomBuilder('StreamBuilder', 'stream', value, initialValue, resultVarName, widget, propertyName, addReturn, addNullChecking, addLocalVar); } createStreamBuilderWithInitialValue(value: string, resultVarName: string, widget: WidgetModel, propertyName: string, addReturn: boolean, addNullChecking = true, addLocalVar = true) { return this.createCustomBuilder('StreamBuilder', 'stream', value, `${value}.value`, resultVarName, widget, propertyName, addReturn, addNullChecking, addLocalVar); } createFutureBuilder(value: string, initialValue: any, resultVarName: string, widget: WidgetModel, propertyName: string, addReturn: boolean, addNullChecking = true, addLocalVar = true) { return this.createCustomBuilder('FutureBuilder', 'future', value, initialValue, resultVarName, widget, propertyName, addReturn, addNullChecking, addLocalVar); } createCustomBuilder(builderWidgetName: string, builderPropertyName: string, value: string, initialValue: any, resultVarName: string, widget: WidgetModel, propertyName: string, addReturn: boolean, addNullChecking = true, addLocalVar = true) { const parameterNamePrefix = makeVariableName(propertyName, value); const snapshotVarName = parameterNamePrefix + 'Snapshot'; resultVarName = resultVarName || `${parameterNamePrefix}Value`; let streamBuilderWidget: WidgetModel = { controllers: [], vars: [], formControls: [], properties: [ { dataType: 'object', value: `${value}`, name: builderPropertyName }, { dataType: 'object', value: `${initialValue ? initialValue : 'null'}`, name: 'initialData' }, { dataType: 'function', name: 'builder', value: '', extraData: { parameters: [ { name: 'context', type: 'BuildContext' }, { name: `${snapshotVarName}`, type: '' } ], logic: [ ...(addLocalVar ? [`final ${resultVarName} = ${snapshotVarName}.data;`] : []), ...(addNullChecking ? [ `if (${resultVarName} == null) {`, ' return Container(width: 0, height: 0);', '}' ] : []) ], addReturn: addReturn } } ], type: builderWidgetName, wrappedWidgets: [widget], id: Math.random() * 1000, onResolved: [], isCustom: true }; // set property value from local variable value = `${resultVarName}`; return { wrapperWidget: streamBuilderWidget, value }; } // // pipes // private applyPipes(value: string, pipesResult: { value: string; pipes: { name: string; args: any[]; }[]; groupedPipes: any[]; }, wrapperWidget: WidgetModel | null, widget: WidgetModel, name: string, addReturn: boolean): { value: string, wrapperWidget: WidgetModel | null } { value = pipesResult.value; let remainingPipes = pipesResult.pipes; // todo add ability to resolve multi-chained stream/future e.g. (streamVar | stream | somePipe | stream). const streamPipIndex = pipesResult.pipes.findIndex(a => a.name === 'stream'); const futurePipIndex = pipesResult.pipes.findIndex(a => a.name === 'future'); const streamWithInitialValuePipIndex = pipesResult.pipes.findIndex(a => a.name === 'behavior'); // this shortcut for (stream:varName.value) const hasStream = streamPipIndex > -1; const hasFuture = futurePipIndex > -1; const hasStreamWithInitialValue = streamWithInitialValuePipIndex > -1; if (hasStream) { const streamPipe = pipesResult.pipes[streamPipIndex]; const pipeValue = this.resolvePipeValue(pipesResult.value, pipesResult.pipes.slice(0, streamPipIndex).reverse()); ({ wrapperWidget, value } = this.createStreamBuilder(pipeValue, streamPipe.args[0], streamPipe.args[1], wrapperWidget || widget, name, addReturn, true, true)); // remove 'stream' from pipes remainingPipes = pipesResult.pipes.slice(streamPipIndex + 1); } else if (hasStreamWithInitialValue) { const streamWithInitialValuePipe = pipesResult.pipes[streamWithInitialValuePipIndex]; const pipeValue = this.resolvePipeValue(pipesResult.value, pipesResult.pipes.slice(0, streamWithInitialValuePipIndex).reverse()); ({ wrapperWidget, value } = this.createStreamBuilderWithInitialValue(pipeValue, streamWithInitialValuePipe.args[0], wrapperWidget || widget, name, addReturn, true, true)); // remove 'stream' from pipes remainingPipes = pipesResult.pipes.slice(streamWithInitialValuePipIndex + 1); } else if (hasFuture) { const futurePipe = pipesResult.pipes[futurePipIndex]; const pipeValue = this.resolvePipeValue(pipesResult.value, pipesResult.pipes.slice(0, futurePipIndex).reverse()); ({ wrapperWidget, value } = this.createFutureBuilder(pipeValue, futurePipe.args[0], futurePipe.args[1], wrapperWidget || widget, name, addReturn, true, true)); // remove 'future' from pipes remainingPipes = pipesResult.pipes.slice(futurePipIndex + 1); } // apply remaining pipes to the 'value' value = this.resolvePipeValue(value, remainingPipes.reverse()); return { value, wrapperWidget }; } private resolvePipeValue(value: string, pipes: { name: string, args: any[] }[], index = 0): string { if (index >= pipes.length) { return value.trim(); } const pipe = pipes[index]; value = (pipes.length > index + 1 ? this.resolvePipeValue(value, pipes, index + 1) : value).trim(); return `_pipeProvider.transform(context, "${pipe.name}", ${value}, [${pipe.args.join(', ')}])`; } private resolvePipes(value: string): { value: string, pipes: { name: string, args: any[] }[], groupedPipes: any[] } { // prepare grouped pipes (pipes that are between braces). const groupedPipes: { value: string, pipes:{ name: string, args: any[] }[] }[] = []; const { groups, output } = this.resolveGroupedPipes(value); const result = this.extractPipes(output); return { ...result, groupedPipes: groups }; } private resolveGroupedPipes(input: string): { groups: any[], output: string } { const stack: { index: number, exp: string }[] = []; const groupedPipes: any[] = []; let quotedWith = ''; let hasInterpolation = false; const resolvePipes = (start: { index: number, exp: string }, index: number, groupStart: string, groupEnd: string): number => { const group = input.substring(start.index + 1, index).trim(); if (group) { const result = this.extractPipes(group); if (result.pipes.length) { groupedPipes.push(result); const pipesNames = makePipeUniqueName(result); const placeholder = groupStart + '_placeholder_for_' + pipesNames + '_pipes' + groupEnd; const originalLength = input.length; input = this.replaceAt(input, placeholder, start.index, index); index -= originalLength - input.length; } } return index; }; for (let index = 0; index < input.length; index++) { const c = input[index]; // start of ${} if (c === '$' && input.length > index && input[index + 1] === '{') { stack.push({ exp: c, index }); hasInterpolation = true; } // end of ${} else if (c === '}') { hasInterpolation = false; const start = stack.pop(); if (start) { index = resolvePipes(start, index, '${', '}'); } } // if quoted else if (quotedWith && !hasInterpolation) { // end of quote if (quotedWith === c) { quotedWith = ''; } } // start of quote else if (c === '"' || c === "'") { quotedWith = c; } // start of brace else if (c === '(') { stack.push({ exp: c, index }); } // end of brace else if (c === ')') { const start = stack.pop(); if (start) { index = resolvePipes(start, index, '(', ')'); } } } return { groups: groupedPipes, output: input }; } private replaceAt(input: string, replace: string, startsAt: number, endsAt: number = -1) { const first = input.substring(0, startsAt); const second = input.substring((endsAt === -1 ? startsAt : endsAt) + 1); return first + replace + second; } private extractPipes(value: string) { const pipesReduced = value .split(/([^"'\|]+)|("[^"]*")|('[^']*')/g) // .split(/([^"\|]+)|("[^"]*")/g) .filter(a => a && a.trim()) .reduce((arr: any[], item) => { if (item === '|') { arr.push([true]); // true: there is pipe } else { arr.length > 1 ? arr[arr.length - 1].push(item) : arr.push([false, item]); // false: no pipes } return arr; }, []); const hasPipes = pipesReduced.filter(a => a[0]).length > 0; if (hasPipes) { // concat all items that aren't pipes value = pipesReduced.filter(a => !a[0]).map(a => a.slice(1).join('')).join(''); } const pipes = pipesReduced .filter(a => a[0]) // get pipes only .map(a => { const pipeText = a.slice(1).join(''); const args = this.resolvePipeArgs(pipeText).map(a => a.trim()); return { name: args[0], args: args.slice(1) }; }); // if (hasPipes) { // // get the 'value' and remove it from pipes // const firstItem = pipes.splice(0, 1)[0]; // if (firstItem) { // value = firstItem.name; // } // } return { value, pipes: hasPipes ? pipes : [] }; } private resolvePipeArgs(args: string): any[] { const matches = scan({ xml: args, pos: 0 }, Syntax.Global.PipeArgs); return matches; } }
the_stack
import { Orbit } from '@orbit/core'; import { buildTransform, DefaultRequestOptions, FullRequestOptions, FullResponse, pullable, pushable, queryable, RequestOptions, Resettable, ResponseHints, syncable, updatable } from '@orbit/data'; import { RecordCacheUpdateDetails } from '@orbit/record-cache'; import { RecordOperation, RecordOperationResult, RecordPullable, RecordPushable, RecordQuery, RecordQueryable, RecordQueryBuilder, RecordQueryExpressionResult, RecordQueryResult, RecordSource, RecordSourceQueryOptions, RecordSourceSettings, RecordSyncable, RecordTransform, RecordTransformBuilder, RecordTransformResult, RecordUpdatable, UpdateRecordOperation } from '@orbit/records'; import { IndexedDBCache, IndexedDBCacheClass, IndexedDBCacheSettings } from './indexeddb-cache'; import { supportsIndexedDB } from './lib/indexeddb'; const { assert } = Orbit; export interface IndexedDBSourceSettings< QO extends RequestOptions = RecordSourceQueryOptions, TO extends RequestOptions = RequestOptions, QB = RecordQueryBuilder, TB = RecordTransformBuilder, QRD = unknown, TRD extends RecordCacheUpdateDetails = RecordCacheUpdateDetails > extends RecordSourceSettings<QO, TO, QB, TB> { namespace?: string; cacheClass?: IndexedDBCacheClass<QO, TO, QB, TB, QRD, TRD>; cacheSettings?: Partial<IndexedDBCacheSettings<QO, TO, QB, TB>>; } export interface IndexedDBSource< QO extends RequestOptions = RecordSourceQueryOptions, TO extends RequestOptions = RequestOptions, QB = RecordQueryBuilder, TB = RecordTransformBuilder, QRD = unknown, TRD extends RecordCacheUpdateDetails = RecordCacheUpdateDetails > extends RecordSource<QO, TO, QB, TB>, RecordSyncable, RecordPullable<QRD>, RecordPushable<TRD>, RecordQueryable<QRD, QB, QO>, RecordUpdatable<TRD, TB, TO>, Resettable {} /** * Source for storing data in IndexedDB. */ @pullable @pushable @queryable @updatable @syncable export class IndexedDBSource< QO extends RequestOptions = RecordSourceQueryOptions, TO extends RequestOptions = RequestOptions, QB = RecordQueryBuilder, TB = RecordTransformBuilder, QRD = unknown, TRD extends RecordCacheUpdateDetails = RecordCacheUpdateDetails > extends RecordSource<QO, TO, QB, TB> implements RecordSyncable, RecordQueryable<QRD, QB, QO>, RecordUpdatable<TRD, TB, TO> { protected _cache: IndexedDBCache<QO, TO, QB, TB, QRD, TRD>; constructor(settings: IndexedDBSourceSettings<QO, TO, QB, TB, QRD, TRD>) { assert( "IndexedDBSource's `schema` must be specified in `settings.schema` constructor argument", !!settings.schema ); assert('Your browser does not support IndexedDB!', supportsIndexedDB()); settings.name = settings.name ?? 'indexedDB'; const autoActivate = settings.autoActivate !== false; settings.autoActivate = false; super(settings); const cacheSettings: Partial<IndexedDBCacheSettings<QO, TO, QB, TB>> = settings.cacheSettings ?? {}; cacheSettings.schema = settings.schema; cacheSettings.keyMap = settings.keyMap; cacheSettings.queryBuilder = cacheSettings.queryBuilder ?? this.queryBuilder; cacheSettings.transformBuilder = cacheSettings.transformBuilder ?? this.transformBuilder; cacheSettings.namespace = cacheSettings.namespace ?? settings.namespace; cacheSettings.defaultQueryOptions = cacheSettings.defaultQueryOptions ?? settings.defaultQueryOptions; cacheSettings.defaultTransformOptions = cacheSettings.defaultTransformOptions ?? settings.defaultTransformOptions; if ( cacheSettings.validatorFor === undefined && cacheSettings.validators === undefined ) { cacheSettings.validatorFor = this._validatorFor; } const cacheClass = settings.cacheClass ?? IndexedDBCache; this._cache = new cacheClass( cacheSettings as IndexedDBCacheSettings<QO, TO, QB, TB> ); if (autoActivate) { this.activate(); } } get cache(): IndexedDBCache<QO, TO, QB, TB, QRD, TRD> { return this._cache; } get defaultQueryOptions(): DefaultRequestOptions<QO> | undefined { return super.defaultQueryOptions; } set defaultQueryOptions(options: DefaultRequestOptions<QO> | undefined) { super.defaultQueryOptions = this.cache.defaultQueryOptions = options; } get defaultTransformOptions(): DefaultRequestOptions<TO> | undefined { return super.defaultTransformOptions; } set defaultTransformOptions(options: DefaultRequestOptions<TO> | undefined) { this._defaultTransformOptions = this.cache.defaultTransformOptions = options; } async upgrade(): Promise<void> { await this._cache.upgrade(); } protected async _activate(): Promise<void> { await super._activate(); await this.cache.openDB(); } async deactivate(): Promise<void> { await super.deactivate(); await this.cache.closeDB(); } ///////////////////////////////////////////////////////////////////////////// // Resettable interface implementation ///////////////////////////////////////////////////////////////////////////// async reset(): Promise<void> { await this._cache.reset(); } ///////////////////////////////////////////////////////////////////////////// // Syncable interface implementation ///////////////////////////////////////////////////////////////////////////// async _sync(transform: RecordTransform): Promise<void> { if (!this.transformLog.contains(transform.id)) { await this._applyTransform(transform); await this.transformed([transform]); } } ///////////////////////////////////////////////////////////////////////////// // Updatable interface implementation ///////////////////////////////////////////////////////////////////////////// async _update( transform: RecordTransform, hints?: ResponseHints<RecordTransformResult, TRD> ): Promise<FullResponse<RecordTransformResult, TRD, RecordOperation>> { let results: RecordTransformResult; const response: FullResponse< RecordTransformResult, TRD, RecordOperation > = {}; if (!this.transformLog.contains(transform.id)) { results = await this._applyTransform(transform); response.transforms = [transform]; } if (hints?.data) { if (Array.isArray(transform.operations)) { assert( 'IndexedDBSource#update: `hints.data` must be an array if `transform.operations` is an array', Array.isArray(hints.data) ); const responseData = []; const hintsData = hints.data as RecordOperationResult[]; for (let h of hintsData) { responseData.push(await this._retrieveOperationResult(h)); } response.data = responseData; } else { response.data = await this._retrieveOperationResult( hints.data as RecordOperationResult ); } } else if (results) { response.data = results; } if (hints?.details) { response.details = hints.details; } return response; } ///////////////////////////////////////////////////////////////////////////// // Queryable interface implementation ///////////////////////////////////////////////////////////////////////////// async _query( query: RecordQuery, hints?: ResponseHints<RecordQueryResult, QRD> ): Promise<FullResponse<RecordQueryResult, QRD, RecordOperation>> { let response: FullResponse<RecordQueryResult, QRD, RecordOperation>; if (hints?.data) { response = {}; if (Array.isArray(query.expressions)) { assert( 'IndexedDBSource#query: `hints.data` must be an array if `query.expressions` is an array', Array.isArray(hints.data) ); const responseData = []; const hintsData = hints.data as RecordQueryExpressionResult[]; for (let h of hintsData) { responseData.push(await this._retrieveQueryExpressionResult(h)); } response.data = responseData; } else { response.data = await this._retrieveQueryExpressionResult( hints.data as RecordQueryExpressionResult ); } } else { response = await this._cache.query(query, { fullResponse: true } as FullRequestOptions<QO>); } if (hints?.details) { response.details = hints.details; } return response; } ///////////////////////////////////////////////////////////////////////////// // Pushable interface implementation ///////////////////////////////////////////////////////////////////////////// async _push( transform: RecordTransform ): Promise<FullResponse<undefined, TRD, RecordOperation>> { const fullResponse: FullResponse<undefined, TRD, RecordOperation> = {}; if (!this.transformLog.contains(transform.id)) { await this._cache.update(transform); fullResponse.transforms = [transform]; } return fullResponse; } ///////////////////////////////////////////////////////////////////////////// // Pullable implementation ///////////////////////////////////////////////////////////////////////////// async _pull( query: RecordQuery ): Promise<FullResponse<undefined, QRD, RecordOperation>> { const fullResponse: FullResponse<undefined, QRD, RecordOperation> = {}; let operations: RecordOperation[]; const results = await this._cache.query(query); if (Array.isArray(query.expressions)) { operations = []; for (let result of results as RecordQueryExpressionResult[]) { operations.push(...this._operationsFromQueryResult(result)); } } else { operations = this._operationsFromQueryResult( results as RecordQueryExpressionResult ); } fullResponse.transforms = [buildTransform(operations)]; return fullResponse; } ///////////////////////////////////////////////////////////////////////////// // Protected methods ///////////////////////////////////////////////////////////////////////////// protected async _retrieveQueryExpressionResult( result: RecordQueryExpressionResult ): Promise<RecordQueryExpressionResult> { if (Array.isArray(result)) { return this._cache.getRecordsAsync(result); } else if (result) { return this._cache.getRecordAsync(result); } else { return result; } } protected async _retrieveOperationResult( result: RecordOperationResult ): Promise<RecordOperationResult> { if (result) { return this._cache.getRecordAsync(result); } else { return result; } } protected async _applyTransform( transform: RecordTransform ): Promise<RecordTransformResult> { return await this.cache.update(transform); } protected _operationsFromQueryResult( result: RecordQueryExpressionResult ): RecordOperation[] { if (Array.isArray(result)) { return result.map((r) => { return { op: 'updateRecord', record: r }; }); } else if (result) { return [ { op: 'updateRecord', record: result } as UpdateRecordOperation ]; } else { return []; } } }
the_stack
import { EventChannel, LocalEvent } from '@syllepsis/adapter'; import cs from 'classnames'; import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { ResizeBox } from '../comp/resizeable'; import { ToolWrapper } from '../comp/toolWrapper'; import { deepCopy } from '../helper'; import { TRetry } from '../helper/register'; import { IDynamicSylApi } from './schema'; import { getData, setData } from './store'; import { IPlaceholderCompProps, IPlaceholderData, loadOrRenderType, unmountType } from './types'; const DEFAULT_HEIGHT = 200; const Placeholder = (props: IPlaceholderCompProps, ref: any) => { const { selected, text, isError, onClick } = props; const { width, height } = props; return ( <div className={cs('placeholder', { selected, 'is-error': isError })} style={{ width, height }} onClick={onClick}> <div className="placeholder-text">{text}</div> </div> ) }; function trans2Number(number: string | number | undefined) { if (typeof number === 'string') { return parseInt(number); } else if (!number) { return 0 } return number; } const useUpdate = () => { const [, setState] = useState(0); return useCallback(() => { setState((num: number): number => num + 1); }, []); }; function Loading() { return <span className="loading"/> } function getInnerWidth() { const container = document.querySelector('.ProseMirror') as HTMLElement; const style = window.getComputedStyle(container); const paddingLeft = parseInt(style.paddingLeft); const paddingRight = parseInt(style.paddingRight); const borderWidth = 1; const width = container.getBoundingClientRect().width - paddingLeft - paddingRight - borderWidth * 2; return width; } function PlaceholderMask(props: { editor: IDynamicSylApi; attrs: IPlaceholderData; getPos: () => number; }) { const { editor, attrs, getPos } = props; const { id, name, typo, able, cycle = {} } = attrs.meta; const width = trans2Number(typo?.width); const height = trans2Number(typo?.height); const ratio = trans2Number(typo?.ratio); const cardData = deepCopy(attrs); const { data } = cardData; const [selected, setSelected] = useState(false); const [fullscreen, setFullscreen] = useState(false); const [realWidth, setRealWidth] = useState(0); const [realHeight, setRealHeight] = useState(0); const [maxWidth, setMaxWidth] = useState(10000); const [render, setRender] = useState(false); const [wrapRef, setWrapRef] = useState<Element>(); const tlRef = useRef<any>(); const contentRef = useRef(); const container = document.querySelector('.ProseMirror'); const forceUpdate = useUpdate(); const realCycle = { load: cycle.load || loadOrRenderType.INIT, render: cycle.render || loadOrRenderType.INIT, unmount: cycle.unmount || unmountType.NEVER } if (realCycle.load > realCycle.render) { realCycle.render = realCycle.load; console.warn(`plugin ${name} load error,load should exec early than render`); } useEffect(() => { if (tlRef.current) { setWrapRef(tlRef.current); } }, [tlRef, container]); function nextCycle(time: loadOrRenderType) { if (realCycle.load === time) { editor.dynamicPlugins.register.register(name, editor).then(() => { if (realCycle.render === time) { setRender(true); } }).catch(() => { console.error('do not support', name); }); } } // view port function isCompVisible() { if (wrapRef && container) { const rect = wrapRef.getBoundingClientRect(); if (rect) { const { top, bottom } = rect; const { top: wrapperTop, bottom: wrapperBottom } = container.getBoundingClientRect(); const offsetTop = wrapperTop; const offsetBottom = wrapperBottom; // just depend on scroll-y return (top > offsetTop && top < offsetBottom) || (bottom > offsetTop && bottom < offsetBottom); } } } const throttleIsCompVisible = isCompVisible; // scroll when visible function toggleVisible() { const visible = throttleIsCompVisible(); if (visible === true) { nextCycle(loadOrRenderType.VISIBLE); } else if (visible === false) { if (render && realCycle?.unmount === unmountType.INVISIBLE) { setRender(false); } } } useEffect(() => { nextCycle(loadOrRenderType.INIT); toggleVisible(); // only listen event after render if (realCycle?.load === loadOrRenderType.VISIBLE || realCycle?.render === loadOrRenderType.VISIBLE || realCycle?.unmount === unmountType.INVISIBLE) { container?.addEventListener('scroll', toggleVisible); return () => { container?.removeEventListener('scroll', toggleVisible); } } }, []); // init data useEffect(() => { if (able?.matcher) { const matcher = getData('matcher') as any || {}; matcher[able.matcher] = attrs; setData('matcher', matcher) } }, [able?.matcher, attrs]); const update = useCallback((_data: any) => { if (_data) { const isHistory = able?.history; const nextCardData = isHistory ? deepCopy(cardData) : cardData; if (typeof _data === 'string') { nextCardData.data = _data; } else if (Array.isArray(_data)) { nextCardData.data = [..._data]; } else if (typeof _data === 'object') { nextCardData.data = deepCopy(_data); } else { console.error('params error: data should be string or object', _data); return false; } // update card attrs const index = getPos(); editor?.updateCardAttrs(index, nextCardData, { merge: !isHistory }); editor?.setSelection({ index, length: 1 }); if (!isHistory) { editor.emit(LocalEvent.TEXT_CHANGED); } } }, [cardData, editor]); const handleSelectionChanged = useCallback((event) => { const selection = editor.getSelection(); // render selected border const pos = getPos(); const isSelectCard = selection.anchor === pos; setSelected(isSelectCard); }, [editor, getPos]); useEffect(() => { editor.on(EventChannel.LocalEvent.ON_CHANGE, handleSelectionChanged); editor.on( EventChannel.LocalEvent.SELECTION_CHANGED, handleSelectionChanged ); return () => { editor.off(EventChannel.LocalEvent.ON_CHANGE, handleSelectionChanged); editor.off( EventChannel.LocalEvent.SELECTION_CHANGED, handleSelectionChanged ); }; }, [editor, handleSelectionChanged]); // update placeholder width size useEffect(() => { const updateMaxWidth = () => { setMaxWidth(getInnerWidth()); } updateMaxWidth(); window.addEventListener('resize', updateMaxWidth); return () => { window.removeEventListener('resize', updateMaxWidth); } }, []); // calc init width useEffect(() => { let initWidth = width; let initHeight = height; if (!width) { // use container width when params width not assign initWidth = getInnerWidth(); } if (!initHeight) { if (ratio) { // use ratio when params height not assign initHeight = initWidth * ratio; } else { initHeight = DEFAULT_HEIGHT; } } setRealWidth(initWidth); setRealHeight(initHeight); }, []); const onResize = useCallback((options: { width?: number, height: number }, updateData?: boolean) => { let { width: toWidth, height: toHeight } = options; const maxWidth = getInnerWidth(); toHeight = Math.max(1, toHeight); toWidth = toWidth || maxWidth; if (width !== toWidth || height !== toHeight) { setRealWidth(toWidth); setRealHeight(toHeight); if (updateData === true) { const nextCardData = deepCopy(cardData); nextCardData.meta.typo = Object.assign(nextCardData.meta.typo, options); const index = getPos(); editor?.updateCardAttrs(index, nextCardData); editor?.setSelection({ index, length: 1 }); } } }, [cardData, editor]); const onClose = () => { const pos = getPos(); editor.deleteCard(pos); editor.setSelection({ index: pos }); } const handlerRef = (handler: any) => { if (handler) { if (!contentRef.current) { contentRef.current = handler; forceUpdate(); } else { contentRef.current = handler; } } }; const lazyCompLoader = editor.dynamicPlugins.register.getLazyComponentLoader(name); // render component const RenderComponent = useMemo(() => lazyCompLoader ? lazyCompLoader(() => // loading (<Placeholder selected={selected} text={<Loading/>}/>) , (props: { retry: TRetry }) => // load error (<Placeholder isError selected={selected} text="load error" onClick={() => { props.retry(); }}/>) , render) : null , [editor, render]); const content = RenderComponent && render ? <RenderComponent ref={handlerRef} selected={selected} fullscreen={fullscreen} style={{ width: realWidth, height: realHeight }} data={data} editor={editor} update={update} resize={onResize}/> : <Placeholder selected={selected} text={render ? `unSupport plugin「${name}」` : <Loading/>} onClick={() => nextCycle(loadOrRenderType.CLICK)}/> const resizeBox = <ResizeBox width={realWidth} height={realHeight} maxWidth={maxWidth} onResize={onResize} enabled={able?.resize && selected && !fullscreen}/> const isAdapt = (!width && !height && !ratio) || !!typo?.adapt; const isDependOnRatio = !width && !height && ratio && !typo?.adapt; return ( <ToolWrapper ref={tlRef} id={id} editor={editor} getPos={getPos} className={cs(typo?.align || 'left', name)} selected={selected} width={realWidth} height={realHeight} ratio={isDependOnRatio ? ratio : undefined} adapt={isAdapt} style={{ width: realWidth, height: realHeight }} fullscreen={fullscreen} onResize={onResize} resizeBox={resizeBox} contentRef={contentRef} onFullscreen={setFullscreen} onClose={able && able.close === false ? undefined : onClose}> {content} </ToolWrapper> ); } export { getInnerWidth, PlaceholderMask }
the_stack
'use strict'; import * as vscode from 'vscode'; import * as fs from 'fs-extra'; import * as path from 'path'; import { UserInputUtil } from './UserInputUtil'; import { Reporter } from '../util/Reporter'; import { PackageRegistryEntry } from '../registries/PackageRegistryEntry'; import { VSCodeBlockchainOutputAdapter } from '../logging/VSCodeBlockchainOutputAdapter'; import { LogType, FileSystemUtil } from 'ibm-blockchain-platform-common'; import { ExtensionCommands } from '../../ExtensionCommands'; import { SettingConfigurations } from '../configurations'; import { DeployView } from '../webview/DeployView'; import { CommandUtil } from '../util/CommandUtil'; interface IProperties { workspacePackageName: string; workspacePackageVersion: string; } /** * Main function which calls the methods and refreshes the blockchain explorer box each time that it runs successfully. * This will be used in other files to call the command to package a smart contract project. */ export async function packageSmartContract(workspace?: vscode.WorkspaceFolder, overrideName?: string, overrideVersion?: string, overrideFabricVersion?: number): Promise<PackageRegistryEntry> { const outputAdapter: VSCodeBlockchainOutputAdapter = VSCodeBlockchainOutputAdapter.instance(); outputAdapter.log(LogType.INFO, undefined, 'packageSmartContract'); let resolvedPkgDir: string; let properties: IProperties; let language: string; let packageError: string; let fabricVersion: number = overrideFabricVersion; try { // Determine the directory that will contain the packages and ensure it exists. const extDir: string = SettingConfigurations.getExtensionDir(); const pkgDir: string = path.join(extDir, 'packages'); resolvedPkgDir = FileSystemUtil.getDirPath(pkgDir); await fs.ensureDir(resolvedPkgDir); // Choose the workspace directory. if (!workspace || !workspace.uri) { // The second check above is to ensure we dont hit the `cannot read property "fsPath" of undefined` on VSCode v1.44.2 workspace = await UserInputUtil.chooseWorkspace(true); if (!workspace) { // User cancelled. return; } } // Build the workspace. await buildWorkspace(workspace); checkForProjectErrors(workspace); const fabricVersions: { version: number, label: string }[] = [ { version: 2, label: UserInputUtil.SELECT_PACKAGING_FABRIC_VERSION_2 }, { version: 1, label: UserInputUtil.SELECT_PACKAGING_FABRIC_VERSION_1 }, ]; if (!overrideFabricVersion || fabricVersions.findIndex(({ version }) => version === overrideFabricVersion) === -1) { const fabricVersionString: string = await UserInputUtil.showQuickPick('Select the packaging output format', fabricVersions.map(({ label }) => label)) as string; if (!fabricVersionString) { // User cancelled. return; } const selectedOption: { version: number, label: string } = fabricVersions.find(({ label }) => label === fabricVersionString); fabricVersion = selectedOption.version; } // Determine the language. language = await UserInputUtil.getLanguage(workspace); // Determine the package name and version. if (language === 'golang') { properties = await golangPackageAndVersion(overrideName, overrideVersion); packageError = 'Go package name'; } else if (language === 'java') { properties = await javaPackageAndVersion(overrideName, overrideVersion); packageError = 'Java package name'; } else { properties = await packageJsonNameAndVersion(workspace, overrideName, overrideVersion); packageError = 'package.json name'; } if (!properties) { // User cancelled. return; } const regex: RegExp = /^[a-zA-Z0-9-_]+$/; const replaceRegex: RegExp = /@.*?\//; properties.workspacePackageName = properties.workspacePackageName.replace(replaceRegex, ''); const validPackageName: boolean = regex.test(properties.workspacePackageName); // Check contract meets Fabric naming requirement if (!validPackageName) { outputAdapter.log(LogType.ERROR, `Invalid ${packageError}. Name can only include alphanumeric, "_" and "-" characters.`); return; } } catch (err) { outputAdapter.log(LogType.ERROR, err.message, err.toString()); return; } return vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: 'IBM Blockchain Platform Extension', cancellable: false }, async (progress: vscode.Progress<{ message: string }>) => { progress.report({ message: `Packaging Smart Contract` }); let originalGOPATH: string = ''; try { // Determine the filename of the new package. const pkgFileExtension: string = (fabricVersion === 1) ? 'cds' : 'tar.gz'; const pkgFile: string = path.join(resolvedPkgDir, `${properties.workspacePackageName}@${properties.workspacePackageVersion}.${pkgFileExtension}`); let pkgFileExists: boolean = await fs.pathExists(pkgFile); if (!pkgFileExists && fabricVersion === 2) { const altPkgFile: string = path.join(resolvedPkgDir, `${properties.workspacePackageName}@${properties.workspacePackageVersion}.tgz`); pkgFileExists = await fs.pathExists(altPkgFile); } if (pkgFileExists) { if (language === 'golang') { throw new Error('Package with name and version already exists. Please input a different name or version for your Go project.'); } else if (language === 'java') { throw new Error('Package with name and version already exists. Please input a different name or version for your Java project.'); } else { throw new Error('Package with name and version already exists. Please change the name and/or the version of the project in your package.json file.'); } } // Determine the path argument. let contractPath: string = workspace.uri.fsPath; // Workspace path const contractPathToVendor: string = contractPath; if (language === 'golang') { const isModule: boolean = await fs.pathExists(path.join(contractPath, 'go.mod')); if (fabricVersion === 1 || !isModule) { if (!process.env.GOPATH) { // The path is relative to $GOPATH/src for Go smart contracts. const indexSrc: number = contractPath.indexOf(path.sep + 'src' + path.sep); if (indexSrc === -1) { // Project path is not under GOPATH. throw new Error('The environment variable GOPATH has not been set, and the extension was not able to automatically detect the correct value. You cannot package this Go smart contract without setting the environment variable GOPATH.'); } else { const srcPath: string = contractPath.substring(0, indexSrc + 4); contractPath = path.relative(srcPath, contractPath); process.env.GOPATH = path.join(srcPath, '..'); } } else { // The path is relative to $GOPATH/src for Go smart contracts. const indexSrc: number = contractPath.indexOf(path.sep + 'src' + path.sep); let pathsMatch: boolean = false; if (indexSrc !== -1) { const srcPath: string = contractPath.substring(0, indexSrc + 4); const goPaths: string[] = process.env.GOPATH.split(path.delimiter); if (goPaths.length > 1) { originalGOPATH = process.env.GOPATH; } goPaths.forEach((value: string) => { if (value.charAt(value.length - 1) === path.sep) { value = value.substr(0, value.length - 1); } if (value === srcPath.substr(0, srcPath.length - 4)) { process.env.GOPATH = value; pathsMatch = true; } }); contractPath = path.relative(srcPath, contractPath); } if (!pathsMatch || !contractPath || contractPath.startsWith('..') || path.isAbsolute(contractPath)) { throw new Error('The Go smart contract is not a subdirectory of the path specified by the environment variable GOPATH. Please correct the environment variable GOPATH.'); } } } if (isModule) { await CommandUtil.sendCommandWithOutput('go', ['mod', 'vendor'], contractPathToVendor); } } // Determine if there is a metadata path. let metadataPath: string = path.join(workspace.uri.fsPath, 'META-INF'); const metadataPathExists: boolean = await fs.pathExists(metadataPath); if (!metadataPathExists) { metadataPath = null; } // Create the package. Need to dynamically load the package class // from the Fabric SDK to avoid early native module loading. const { PackageSmartContract } = await import('ibm-blockchain-platform-environment-v1'); const fileNames: string[] = await PackageSmartContract.packageContract(fabricVersion, properties.workspacePackageName, properties.workspacePackageVersion, contractPath, pkgFile, language, metadataPath); Reporter.instance().sendTelemetryEvent('packageCommand'); await vscode.commands.executeCommand(ExtensionCommands.REFRESH_PACKAGES); outputAdapter.log(LogType.SUCCESS, `Smart Contract packaged: ${pkgFile}`); outputAdapter.log(LogType.INFO, undefined, `${fileNames.length} file(s) packaged:`); for (const file of fileNames) { outputAdapter.log(LogType.INFO, undefined, `- ${file}`); } const packageEntry: PackageRegistryEntry = new PackageRegistryEntry(); packageEntry.name = properties.workspacePackageName; packageEntry.version = properties.workspacePackageVersion; packageEntry.path = pkgFile; const stat: fs.Stats = await fs.lstat(pkgFile); // get size const sizeKB: number = Math.round(stat.size / 1000); packageEntry.sizeKB = sizeKB; const panel: vscode.WebviewPanel = DeployView.panel; if (panel) { await DeployView.updatePackages(); } if (originalGOPATH) { process.env.GOPATH = originalGOPATH; } return packageEntry; } catch (err) { outputAdapter.log(LogType.ERROR, err.message, err.toString()); if (originalGOPATH) { process.env.GOPATH = originalGOPATH; } return; } }); } /** * Method to retrieve the package name and version from the projects package.json file, and returns them to be used in the getFinalDirectory() method. * @param workspaceDir {String} workspaceDir A string containing the path to the current active workspace (the workspace of the project the user is packaging). * @returns {string, string}An object with the workspacePackageName and workspacePackageVersion which will be used in the createPackageDir() method. */ async function packageJsonNameAndVersion(workspaceDir: vscode.WorkspaceFolder, overrideName?: string, overrideVersion?: string): Promise<IProperties> { const workspacePackage: string = path.join(workspaceDir.uri.fsPath, '/package.json'); const workspacePackageContents: Buffer = await fs.readFile(workspacePackage); const workspacePackageObj: any = JSON.parse(workspacePackageContents.toString('utf8')); let workspacePackageName: string = workspacePackageObj.name; let workspacePackageVersion: string = workspacePackageObj.version; if (overrideName) { workspacePackageName = overrideName; } if (overrideVersion) { workspacePackageVersion = overrideVersion; } if (!workspacePackageName || !workspacePackageVersion) { const message: string = 'Please enter a package name and/or package version into your package.json'; throw new Error(message); } return { workspacePackageName, workspacePackageVersion }; } /** * Method which calls an input box should the project be coded in java, which asks the user for a package name and version * (as java projects do not contain a package.json file), and returns an object containing both these values. * @param workspaceDir {String} workspaceDir A string containing the path to the current active workspace (the workspace of the project the user is packaging). * @returns {string, string} Returns an object with the workspacePackageName and workspacePackageVersion which will be used in the createPackageDir() method */ async function javaPackageAndVersion(overrideName?: string, overrideVersion?: string): Promise<IProperties> { let workspacePackageName: string = overrideName; if (!workspacePackageName) { workspacePackageName = await UserInputUtil.showInputBox('Enter a name for your Java package'); // Getting the specified name and package from the user if (!workspacePackageName) { // User has cancelled the input box return; } } let workspacePackageVersion: string = overrideVersion; if (!workspacePackageVersion) { workspacePackageVersion = await UserInputUtil.showInputBox('Enter a version for your Java package'); // Getting the specified name and package from the user if (!workspacePackageVersion) { // User has cancelled the input box return; } } return { workspacePackageName, workspacePackageVersion }; } /** * Method which calls an input box should the project be coded in golang, which asks the user for a package name and version * (as golang projects do not contain a package.json file), and returns an object containing both these values. * @param workspaceDir {String} workspaceDir A string containing the path to the current active workspace (the workspace of the project the user is packaging). * @returns {string, string} Returns an object with the workspacePackageName and workspacePackageVersion which will be used in the createPackageDir() method */ async function golangPackageAndVersion(overrideName?: string, overrideVersion?: string): Promise<IProperties> { let workspacePackageName: string = overrideName; if (!workspacePackageName) { workspacePackageName = await UserInputUtil.showInputBox('Enter a name for your Go package'); // Getting the specified name and package from the user if (!workspacePackageName) { // User has cancelled the input box return; } } let workspacePackageVersion: string = overrideVersion; if (!workspacePackageVersion) { workspacePackageVersion = await UserInputUtil.showInputBox('Enter a version for your Go package'); // Getting the specified name and package from the user if (!workspacePackageVersion) { // User has cancelled the input box return; } } return { workspacePackageName, workspacePackageVersion }; } function checkForProjectErrors(workspaceDir: vscode.WorkspaceFolder): void { const collections: [vscode.Uri, vscode.Diagnostic[]][] = vscode.languages.getDiagnostics(); for (const collection of collections) { for (const thing of collection) { if (thing instanceof vscode.Uri) { const uri: vscode.Uri = thing; const relativePath: string = path.relative(workspaceDir.uri.fsPath, uri.fsPath); if (!relativePath || relativePath.startsWith('..') || path.isAbsolute(relativePath)) { // not in this project must have another project open in the workspace break; } } else { const diagnostics: vscode.Diagnostic[] = thing; for (const diagnostic of diagnostics) { // only check for errors if (diagnostic.severity === 0) { throw new Error('Smart contract project has errors please fix them before packaging'); } } } } } } async function buildWorkspace(workspaceDir: vscode.WorkspaceFolder): Promise<void> { // Find all of the tasks. const tasks: vscode.Task[] = await vscode.tasks.fetchTasks(); // Then limit the tasks to build tasks that we can actually use. const buildTasks: vscode.Task[] = tasks.filter((task: vscode.Task) => { if (!task.scope || task.scope === vscode.TaskScope.Global || task.scope === vscode.TaskScope.Workspace) { // We don't want unscoped tasks, global tasks, or workspace tasks. return false; } else if (task.scope.uri.fsPath !== workspaceDir.uri.fsPath) { // We only want tasks for our smart contract project. return false; } else if (task.group !== vscode.TaskGroup.Build) { // We only want build tasks. return false; } else if (task.isBackground) { // We only want foreground tasks (not "npm watch"). return false; } else if (task.name.match(/watch/i)) { // We don't want anything with "watch" in the name! return false; } else { return true; } }); // If we have a set of build tasks, then execute the first one. if (buildTasks.length > 0) { const buildTask: vscode.Task = buildTasks[0]; await vscode.tasks.executeTask(buildTask); await new Promise((resolve: any): any => { const buildTaskListener: vscode.Disposable = vscode.tasks.onDidEndTask((_e: vscode.TaskEndEvent) => { buildTaskListener.dispose(); resolve(); }); }); } }
the_stack
import { Injectable } from '@angular/core'; import { CoreError } from '@classes/errors/error'; import { CoreWSError } from '@classes/errors/wserror'; import { CoreSite, CoreSiteWSPreSets } from '@classes/site'; import { CoreCourseCommonModWSOptions } from '@features/course/services/course'; import { CoreCourseLogHelper } from '@features/course/services/log-helper'; import { CoreSites, CoreSitesCommonWSOptions } from '@services/sites'; import { CoreWSExternalFile, CoreWSExternalWarning } from '@services/ws'; import { makeSingleton, Translate } from '@singletons'; const ROOT_CACHE_KEY = 'AddonModBBB:'; /** * Service that provides some features for Big Blue Button activity. */ @Injectable({ providedIn: 'root' }) export class AddonModBBBService { static readonly COMPONENT = 'mmaModBigBlueButtonBN'; /** * End a meeting. * * @param id BBB ID. * @param groupId Group ID, 0 means that the function will determine the user group. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when done. */ async endMeeting( id: number, groupId: number = 0, siteId?: string, ): Promise<void> { const site = await CoreSites.getSite(siteId); const params: AddonModBBBEndMeetingWSParams = { bigbluebuttonbnid: id, groupid: groupId, }; await site.write('mod_bigbluebuttonbn_end_meeting', params); } /** * Get a BBB activity. * * @param courseId Course ID. * @param cmId Course module ID. * @param options Other options. * @return Promise resolved when the activity is retrieved. */ async getBBB(courseId: number, cmId: number, options: CoreSitesCommonWSOptions = {}): Promise<AddonModBBBData> { const site = await CoreSites.getSite(options.siteId); const params: AddonModBBBGetBigBlueButtonBNsByCoursesWSParams = { courseids: [courseId], }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getBBBsCacheKey(courseId), updateFrequency: CoreSite.FREQUENCY_RARELY, component: AddonModBBBService.COMPONENT, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; const response = await site.read<AddonModBBBGetBigBlueButtonBNsByCoursesWSResponse>( 'mod_bigbluebuttonbn_get_bigbluebuttonbns_by_courses', params, preSets, ); const bbb = response.bigbluebuttonbns.find((bbb) => bbb.coursemodule == cmId); if (bbb) { return bbb; } throw new CoreError(Translate.instant('core.course.modulenotfound')); } /** * Get cache key for get BBB WS call. * * @param courseId Course ID. * @return Cache key. */ protected getBBBsCacheKey(courseId: number): string { return ROOT_CACHE_KEY + 'bbb:' + courseId; } /** * Get join URL for a BBB activity. * * @param cmId Course module ID. * @param groupId Group ID, 0 means that the function will determine the user group. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the list of messages. */ async getJoinUrl( cmId: number, groupId: number = 0, siteId?: string, ): Promise<string> { const site = await CoreSites.getSite(siteId); const params: AddonModBBBGetJoinUrlWSParams = { cmid: cmId, groupid: groupId, }; // Don't use cache. const response = await site.write<AddonModBBBGetJoinUrlWSResponse>( 'mod_bigbluebuttonbn_get_join_url', params, ); if (response.warnings?.length) { throw new CoreWSError(response.warnings[0]); } if (!response.join_url) { // Shouldn't happen, if there are no warning the app should always receive the URL. throw new CoreError( Translate.instant('addon.mod_bigbluebuttonbn.view_error_unable_join_studentview_error_unable_join_student'), ); } return response.join_url; } /** * Get meeting info for a BBB activity. * * @param id BBB ID. * @param groupId Group ID, 0 means that the function will determine the user group. * @param options Other options. * @return Promise resolved with the list of messages. */ async getMeetingInfo( id: number, groupId: number = 0, options: CoreCourseCommonModWSOptions = {}, ): Promise<AddonModBBBMeetingInfoWSResponse> { const site = await CoreSites.getSite(options.siteId); const params: AddonModBBBMeetingInfoWSParams = { bigbluebuttonbnid: id, groupid: groupId, }; const preSets: CoreSiteWSPreSets = { cacheKey: this.getMeetingInfoCacheKey(id, groupId), component: AddonModBBBService.COMPONENT, componentId: options.cmId, ...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets. }; return await site.read<AddonModBBBMeetingInfoWSResponse>( 'mod_bigbluebuttonbn_meeting_info', params, preSets, ); } /** * Get cache key for meeting info WS call. * * @param id BBB ID. * @param groupId Group ID, 0 means that the function will determine the user group. * @return Cache key. */ protected getMeetingInfoCacheKey(id: number, groupId: number = 0): string { return this.getMeetingInfoCacheKeyPrefix(id) + groupId; } /** * Get cache key prefix for meeting info WS call. * * @param id BBB ID. * @return Cache key prefix. */ protected getMeetingInfoCacheKeyPrefix(id: number): string { return ROOT_CACHE_KEY + 'meetingInfo:' + id + ':'; } /** * Report a BBB as being viewed. * * @param id BBB instance ID. * @param name Name of the BBB. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the WS call is successful. */ async logView(id: number, name?: string, siteId?: string): Promise<void> { const params: AddonModBBBViewBigBlueButtonBNWSParams = { bigbluebuttonbnid: id, }; await CoreCourseLogHelper.logSingle( 'mod_bigbluebuttonbn_view_bigbluebuttonbn', params, AddonModBBBService.COMPONENT, id, name, 'bigbluebuttonbn', {}, siteId, ); } /** * Invalidate BBBs. * * @param courseId Course ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateBBBs(courseId: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getBBBsCacheKey(courseId)); } /** * Invalidate meeting info for a certain group. * * @param id BBB ID. * @param groupId Group ID, 0 means that the function will determine the user group. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateMeetingInfo(id: number, groupId: number = 0, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKey(this.getMeetingInfoCacheKey(id, groupId)); } /** * Invalidate meeting info for all groups. * * @param id BBB ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the data is invalidated. */ async invalidateAllGroupsMeetingInfo(id: number, siteId?: string): Promise<void> { const site = await CoreSites.getSite(siteId); await site.invalidateWsCacheForKeyStartingWith(this.getMeetingInfoCacheKeyPrefix(id)); } /** * Returns whether or not the BBB plugin is enabled for a certain site. * * @param siteId Site ID. If not defined, current site. * @return Promise resolved with true if enabled, resolved with false or rejected otherwise. * @since 4.0, but the WebServices were backported to the plugin so it can be supported in older versions. */ async isPluginEnabled(siteId?: string): Promise<boolean> { const site = await CoreSites.getSite(siteId); return site.wsAvailable('mod_bigbluebuttonbn_meeting_info'); } } export const AddonModBBB = makeSingleton(AddonModBBBService); /** * Params of mod_bigbluebuttonbn_get_bigbluebuttonbns_by_courses WS. */ export type AddonModBBBGetBigBlueButtonBNsByCoursesWSParams = { courseids?: number[]; // Array of course ids. }; /** * Data returned by mod_bigbluebuttonbn_get_bigbluebuttonbns_by_courses WS. */ export type AddonModBBBGetBigBlueButtonBNsByCoursesWSResponse = { bigbluebuttonbns: AddonModBBBData[]; warnings?: CoreWSExternalWarning[]; }; /** * BBB data returned by mod_bigbluebuttonbn_get_bigbluebuttonbns_by_courses. */ export type AddonModBBBData = { id: number; // Module id. coursemodule: number; // Course module id. course: number; // Course id. name: string; // Name. intro: string; // Description. meetingid: string; // Meeting id. introformat?: number; // Intro format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN). introfiles: CoreWSExternalFile[]; timemodified: number; // Last time the instance was modified. section: number; // Course section id. visible: number; // Module visibility. groupmode: number; // Group mode. groupingid: number; // Grouping id. }; /** * Params of mod_bigbluebuttonbn_meeting_info WS. */ export type AddonModBBBMeetingInfoWSParams = { bigbluebuttonbnid: number; // Bigbluebuttonbn instance id. groupid?: number; // Bigbluebuttonbn group id. updatecache?: boolean; // Update cache ?. }; /** * Data returned by mod_bigbluebuttonbn_meeting_info WS. */ export type AddonModBBBMeetingInfoWSResponse = { cmid: number; // CM id. userlimit: number; // User limit. bigbluebuttonbnid: string; // Bigbluebuttonbn instance id. meetingid: string; // Meeting id. openingtime?: number; // Opening time. closingtime?: number; // Closing time. statusrunning?: boolean; // Status running. statusclosed?: boolean; // Status closed. statusopen?: boolean; // Status open. statusmessage?: string; // Status message. startedat?: number; // Started at. moderatorcount?: number; // Moderator count. participantcount?: number; // Participant count. moderatorplural?: boolean; // Several moderators ?. participantplural?: boolean; // Several participants ?. canjoin: boolean; // Can join. ismoderator: boolean; // Is moderator. presentations: { url: string; // Presentation URL. iconname: string; // Icon name. icondesc: string; // Icon text. name: string; // Presentation name. }[]; joinurl: string; // Join URL. }; /** * Params of mod_bigbluebuttonbn_get_join_url WS. */ export type AddonModBBBGetJoinUrlWSParams = { cmid: number; // Course module id. groupid?: number; // Bigbluebuttonbn group id. }; /** * Data returned by mod_bigbluebuttonbn_get_join_url WS. */ export type AddonModBBBGetJoinUrlWSResponse = { // eslint-disable-next-line @typescript-eslint/naming-convention join_url?: string; // Can join session. warnings?: CoreWSExternalWarning[]; }; /** * Params of mod_bigbluebuttonbn_view_bigbluebuttonbn WS. */ export type AddonModBBBViewBigBlueButtonBNWSParams = { bigbluebuttonbnid: number; // Bigbluebuttonbn instance id. }; /** * Params of mod_bigbluebuttonbn_end_meeting WS. */ export type AddonModBBBEndMeetingWSParams = { bigbluebuttonbnid: number; // Bigbluebuttonbn instance id. groupid?: number; // Bigbluebuttonbn group id. };
the_stack
import { postHandler, BodyParsingIncomingMessage } from '../../../api/serviceMessages/postHandler' import { Criticality, ExternalServiceMessage } from '../../../../lib/collections/CoreSystem' import { IncomingMessage, ServerResponse } from 'http' import { Socket } from 'net' import * as serviceMessagesApi from '../../../api/serviceMessages/serviceMessagesApi' jest.mock('../../../api/serviceMessages/serviceMessagesApi', () => { return { __esModule: true, writeMessage: jest.fn(() => ({ systemError: false })), } }) const validInput: ExternalServiceMessage = { id: '294a7079efdce49fb553e52d9e352e24', criticality: Criticality.CRITICAL, message: 'Something is wrong that should have been right', sender: 'ola', timestamp: new Date(), } declare global { namespace jest { interface Matchers<R> { toBeHttpOkStatusCode(): R } } } expect.extend({ toBeHttpOkStatusCode(value): jest.CustomMatcherResult { const allowed = [200, 201, 204] if (allowed.indexOf(value) > -1) { return { message: () => `expected ${value} to not be one of ${allowed.join(',')}`, pass: true, } } return { message: () => `expected ${value} to be one of ${allowed.join(',')}`, pass: false, } }, }) describe('ServiceMessages API POST endpoint', () => { let mockRequest: BodyParsingIncomingMessage let mockResponse: ServerResponse let mockResponseEnd: jest.Mock<Function> const mockedWriteMessage: jest.Mock<typeof serviceMessagesApi.writeMessage> = serviceMessagesApi.writeMessage as any beforeEach(() => { mockRequest = new IncomingMessage(new Socket()) mockResponse = new ServerResponse(mockRequest) mockResponseEnd = jest.fn() Object.defineProperty(mockResponse, 'end', { value: mockResponseEnd }) }) describe('input validation', () => { it('should accept valid input', () => { mockRequest.body = JSON.parse(JSON.stringify(validInput)) postHandler({}, mockRequest, mockResponse) expect(mockResponse.statusCode).toBeHttpOkStatusCode() expect(mockResponseEnd).toHaveBeenCalledTimes(1) }) describe('id field', () => { // id: string it('should reject when value is missing', () => { const invalidInput = { ...validInput } // @ts-expect-error delete invalidInput.id mockRequest.body = JSON.parse(JSON.stringify(invalidInput)) postHandler({}, mockRequest, mockResponse) expect(mockResponse.statusCode).toEqual(400) expect(mockResponseEnd).toHaveBeenCalledTimes(1) }) it('should reject empty string', () => { const invalidInput = { ...validInput } invalidInput.id = '' mockRequest.body = JSON.parse(JSON.stringify(invalidInput)) postHandler({}, mockRequest, mockResponse) expect(mockResponse.statusCode).toEqual(400) expect(mockResponseEnd).toHaveBeenCalledTimes(1) }) it('should reject blank string', () => { const invalidInput = { ...validInput } invalidInput.id = ' \t' mockRequest.body = JSON.parse(JSON.stringify(invalidInput)) postHandler({}, mockRequest, mockResponse) expect(mockResponse.statusCode).toEqual(400) expect(mockResponseEnd).toHaveBeenCalledTimes(1) }) }) describe('criticality field', () => { // criticality: Criticality it('should reject when value is missing', () => { const invalidInput = { ...validInput } // @ts-expect-error delete invalidInput.criticality mockRequest.body = JSON.parse(JSON.stringify(invalidInput)) postHandler({}, mockRequest, mockResponse) expect(mockResponse.statusCode).toEqual(400) expect(mockResponseEnd).toHaveBeenCalledTimes(1) }) it('should reject non numeric value', () => { const invalidInput: any = { ...validInput } invalidInput.criticality = 'lol' mockRequest.body = JSON.parse(JSON.stringify(invalidInput)) postHandler({}, mockRequest, mockResponse) expect(mockResponse.statusCode).toEqual(400) expect(mockResponseEnd).toHaveBeenCalledTimes(1) }) it('should reject negative number', () => { const invalidInput: any = { ...validInput } invalidInput.criticality = -1 mockRequest.body = JSON.parse(JSON.stringify(invalidInput)) postHandler({}, mockRequest, mockResponse) expect(mockResponse.statusCode).toEqual(400) expect(mockResponseEnd).toHaveBeenCalledTimes(1) }) it('should reject non-criticality positive number', () => { Object.values(Criticality) const tooHigh = (Object.values(Criticality).filter((value) => typeof value === 'number') as number[]).sort( (a, b) => b - a )[0] + 1 const invalidInput: any = { ...validInput } invalidInput.criticality = tooHigh mockRequest.body = JSON.parse(JSON.stringify(invalidInput)) postHandler({}, mockRequest, mockResponse) expect(mockResponse.statusCode).toEqual(400) expect(mockResponseEnd).toHaveBeenCalledTimes(1) }) it('should accept a valid value as a string', () => { const alsoValid: any = { ...validInput } alsoValid.criticality = `${validInput.criticality}` mockRequest.body = JSON.parse(JSON.stringify(alsoValid)) postHandler({}, mockRequest, mockResponse) expect(mockResponse.statusCode).toBeHttpOkStatusCode() expect(mockResponseEnd).toHaveBeenCalledTimes(1) }) it('should reject empty string value', () => { const invalidInput: any = { ...validInput } invalidInput.criticality = '' mockRequest.body = JSON.parse(JSON.stringify(invalidInput)) postHandler({}, mockRequest, mockResponse) expect(mockResponse.statusCode).toEqual(400) expect(mockResponseEnd).toHaveBeenCalledTimes(1) }) }) describe('message field', () => { // message: string it('should reject when value is missing', () => { const invalidInput = { ...validInput } // @ts-expect-error delete invalidInput.message mockRequest.body = JSON.parse(JSON.stringify(invalidInput)) postHandler({}, mockRequest, mockResponse) expect(mockResponse.statusCode).toEqual(400) expect(mockResponseEnd).toHaveBeenCalledTimes(1) }) it('should reject empty string', () => { const invalidInput = { ...validInput } invalidInput.message = '' mockRequest.body = JSON.parse(JSON.stringify(invalidInput)) postHandler({}, mockRequest, mockResponse) expect(mockResponse.statusCode).toEqual(400) expect(mockResponseEnd).toHaveBeenCalledTimes(1) }) it('should reject blank string', () => { const invalidInput = { ...validInput } invalidInput.message = ' \t' mockRequest.body = JSON.parse(JSON.stringify(invalidInput)) postHandler({}, mockRequest, mockResponse) expect(mockResponse.statusCode).toEqual(400) expect(mockResponseEnd).toHaveBeenCalledTimes(1) }) }) describe('sender field', () => { // sender?: string it('should accept missing value', () => { const alsoValid = { ...validInput } delete alsoValid.sender mockRequest.body = JSON.parse(JSON.stringify(alsoValid)) postHandler({}, mockRequest, mockResponse) expect(mockResponse.statusCode).toBeHttpOkStatusCode() expect(mockResponseEnd).toHaveBeenCalledTimes(1) }) it('should accept empty value', () => { const alsoValid = { ...validInput } alsoValid.sender = '' mockRequest.body = JSON.parse(JSON.stringify(alsoValid)) postHandler({}, mockRequest, mockResponse) expect(mockResponse.statusCode).toBeHttpOkStatusCode() expect(mockResponseEnd).toHaveBeenCalledTimes(1) }) }) describe('timestamp field', () => { // timestamp: Date it('should reject when value is missing', () => { const invalidInput = { ...validInput } // @ts-expect-error delete invalidInput.timestamp mockRequest.body = JSON.parse(JSON.stringify(invalidInput)) postHandler({}, mockRequest, mockResponse) expect(mockResponse.statusCode).toEqual(400) expect(mockResponseEnd).toHaveBeenCalledTimes(1) }) it('should reject non date value', () => { const invalidInput = { ...validInput } as any invalidInput.timestamp = 'this is not a date' mockRequest.body = JSON.parse(JSON.stringify(invalidInput)) postHandler({}, mockRequest, mockResponse) expect(mockResponse.statusCode).toEqual(400) expect(mockResponseEnd).toHaveBeenCalledTimes(1) }) }) }) describe('data storage', () => { it('should call API writeMessage with the given id', () => { const expected = validInput.id mockRequest.body = JSON.parse(JSON.stringify(validInput)) postHandler({}, mockRequest, mockResponse) expect(mockedWriteMessage.mock.calls[0][0]).toHaveProperty('id', expected) }) it('should call API writeMessage with the given criticality', () => { const expected = Number(validInput.criticality) mockRequest.body = JSON.parse(JSON.stringify(validInput)) postHandler({}, mockRequest, mockResponse) expect(mockedWriteMessage.mock.calls[0][0]).toHaveProperty('criticality', expected) }) it('should call API writeMessage with the given criticality when criticality is a string', () => { const expected = Number(validInput.criticality) const alsoValid: any = { ...validInput } alsoValid.criticality = `${validInput.criticality}` mockRequest.body = JSON.parse(JSON.stringify(alsoValid)) postHandler({}, mockRequest, mockResponse) expect(mockedWriteMessage.mock.calls[0][0]).toHaveProperty('criticality', expected) }) it('should call API writeMessage with the given message', () => { const expected = validInput.message mockRequest.body = JSON.parse(JSON.stringify(validInput)) postHandler({}, mockRequest, mockResponse) expect(mockedWriteMessage.mock.calls[0][0]).toHaveProperty('message', expected) }) it('should call API writeMessage with the given sender', () => { const expected = validInput.sender mockRequest.body = JSON.parse(JSON.stringify(validInput)) postHandler({}, mockRequest, mockResponse) expect(mockedWriteMessage.mock.calls[0][0]).toHaveProperty('sender', expected) }) it('should call API writeMessage with the given timestamp', () => { const expected = new Date(validInput.timestamp).getTime() mockRequest.body = JSON.parse(JSON.stringify(validInput)) postHandler({}, mockRequest, mockResponse) expect(mockedWriteMessage.mock.calls[0][0]).toHaveProperty('timestamp', expected) }) }) describe('http response', () => { it('should reply 201 Created for new messages', () => { const spy = jest.spyOn(serviceMessagesApi, 'writeMessage').mockImplementation(() => ({ isUpdate: false, })) mockRequest.body = JSON.parse(JSON.stringify(validInput)) postHandler({}, mockRequest, mockResponse) expect(mockResponse.statusCode).toBe(201) spy.mockRestore() }) it('should put the new message in the response body', () => { const spy = jest.spyOn(serviceMessagesApi, 'writeMessage').mockImplementation(() => ({ isUpdate: false, })) mockRequest.body = JSON.parse(JSON.stringify(validInput)) postHandler({}, mockRequest, mockResponse) const writtenMessage = mockedWriteMessage.mock.calls[0][0] const expected = JSON.stringify(writtenMessage) /* this isn't really perfect, as it would be perfectly fine for the * implementing unit to write the body with response#write. * But, I'm not implementing a full mock of ServerResponse at this stage :S */ expect(mockResponseEnd).toHaveBeenCalledWith(expected) spy.mockRestore() }) it('should reply 200 OK for updated messages', () => { const spy = jest.spyOn(serviceMessagesApi, 'writeMessage').mockImplementation(() => ({ isUpdate: true, })) mockRequest.body = JSON.parse(JSON.stringify(validInput)) postHandler({}, mockRequest, mockResponse) expect(mockResponse.statusCode).toBe(200) spy.mockRestore() }) it('should put the updated message in the response body', () => { const spy = jest.spyOn(serviceMessagesApi, 'writeMessage').mockImplementation(() => ({ isUpdate: true, })) mockRequest.body = JSON.parse(JSON.stringify(validInput)) postHandler({}, mockRequest, mockResponse) const writtenMessage = mockedWriteMessage.mock.calls[0][0] const expected = JSON.stringify(writtenMessage) /* this isn't really perfect, as it would be perfectly fine for the * implementing unit to write the body with response#write. * But, I'm not implementing a full mock of ServerResponse at this stage :S */ // expect(mockResponseEnd.mock.calls[0][0]).toEqual(expected) expect(mockResponseEnd).toHaveBeenCalledWith(expected) spy.mockRestore() }) it('should reply 500 when message cant be stored', () => { const spy = jest.spyOn(serviceMessagesApi, 'writeMessage').mockImplementation(() => { throw new Error('lol') }) mockRequest.body = JSON.parse(JSON.stringify(validInput)) postHandler({}, mockRequest, mockResponse) expect(mockResponse.statusCode).toBe(500) spy.mockRestore() }) }) })
the_stack
import requestAnimationFrame from 'raf'; import { RenderingContext2D } from './types'; import { compressSpaces, toNumbers } from './util'; import Property from './Property'; import ViewPort from './ViewPort'; import Mouse from './Mouse'; import Document, { Element, AnimateElement } from './Document'; export interface IScreenOptions { /** * Window object. */ window?: Window; /** * WHATWG-compatible `fetch` function. */ fetch?: typeof fetch; } export interface IScreenStartOptions { /** * Whether enable the redraw. */ enableRedraw?: boolean; /** * Ignore mouse events. */ ignoreMouse?: boolean; /** * Ignore animations. */ ignoreAnimation?: boolean; /** * Does not try to resize canvas. */ ignoreDimensions?: boolean; /** * Does not clear canvas. */ ignoreClear?: boolean; /** * Scales horizontally to width. */ scaleWidth?: number; /** * Scales vertically to height. */ scaleHeight?: number; /** * Draws at a x offset. */ offsetX?: number; /** * Draws at a y offset. */ offsetY?: number; /** * Will call the function on every frame, if it returns true, will redraw. */ forceRedraw?(): boolean; } export interface IScreenViewBoxConfig { document: Document; ctx: RenderingContext2D; aspectRatio: string; width: number; desiredWidth: number; height: number; desiredHeight: number; minX?: number; minY?: number; refX?: number; refY?: number; clip?: boolean; clipX?: number; clipY?: number; } const defaultWindow = typeof window !== 'undefined' ? window : null; const defaultFetch = typeof fetch !== 'undefined' ? fetch.bind(undefined) as typeof fetch // `fetch` depends on context: `someObject.fetch(...)` will throw error. : null; export default class Screen { static readonly defaultWindow = defaultWindow; static readonly defaultFetch = defaultFetch; FRAMERATE = 30; MAX_VIRTUAL_PIXELS = 30000; CLIENT_WIDTH = 800; CLIENT_HEIGHT = 600; readonly window?: Window; readonly fetch: typeof defaultFetch; readonly viewPort = new ViewPort(); readonly mouse = new Mouse(this); readonly animations: AnimateElement[] = []; private readyPromise: Promise<void>; private resolveReady: () => void; private waits: (() => boolean)[] = []; private frameDuration = 0; private isReadyLock = false; private isFirstRender = true; private intervalId: number = null; constructor( readonly ctx: RenderingContext2D, { fetch = defaultFetch, window = defaultWindow }: IScreenOptions = {} ) { this.window = window; this.fetch = fetch; } wait(checker: () => boolean) { this.waits.push(checker); } ready() { // eslint-disable-next-line @typescript-eslint/no-misused-promises if (!this.readyPromise) { return Promise.resolve(); } return this.readyPromise; } isReady() { if (this.isReadyLock) { return true; } const isReadyLock = this.waits.every(_ => _()); if (isReadyLock) { this.waits = []; if (this.resolveReady) { this.resolveReady(); } } this.isReadyLock = isReadyLock; return isReadyLock; } setDefaults(ctx: RenderingContext2D) { // initial values and defaults ctx.strokeStyle = 'rgba(0,0,0,0)'; ctx.lineCap = 'butt'; ctx.lineJoin = 'miter'; ctx.miterLimit = 4; } setViewBox({ document, ctx, aspectRatio, width, desiredWidth, height, desiredHeight, minX = 0, minY = 0, refX, refY, clip = false, clipX = 0, clipY = 0 }: IScreenViewBoxConfig) { // aspect ratio - http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute const cleanAspectRatio = compressSpaces(aspectRatio).replace(/^defer\s/, ''); // ignore defer const [ aspectRatioAlign, aspectRatioMeetOrSlice ] = cleanAspectRatio.split(' '); const align = aspectRatioAlign || 'xMidYMid'; const meetOrSlice = aspectRatioMeetOrSlice || 'meet'; // calculate scale const scaleX = width / desiredWidth; const scaleY = height / desiredHeight; const scaleMin = Math.min(scaleX, scaleY); const scaleMax = Math.max(scaleX, scaleY); let finalDesiredWidth = desiredWidth; let finalDesiredHeight = desiredHeight; if (meetOrSlice === 'meet') { finalDesiredWidth *= scaleMin; finalDesiredHeight *= scaleMin; } if (meetOrSlice === 'slice') { finalDesiredWidth *= scaleMax; finalDesiredHeight *= scaleMax; } const refXProp = new Property(document, 'refX', refX); const refYProp = new Property(document, 'refY', refY); const hasRefs = refXProp.hasValue() && refYProp.hasValue(); if (hasRefs) { ctx.translate( -scaleMin * refXProp.getPixels('x'), -scaleMin * refYProp.getPixels('y') ); } if (clip) { const scaledClipX = scaleMin * clipX; const scaledClipY = scaleMin * clipY; ctx.beginPath(); ctx.moveTo(scaledClipX, scaledClipY); ctx.lineTo(width, scaledClipY); ctx.lineTo(width, height); ctx.lineTo(scaledClipX, height); ctx.closePath(); ctx.clip(); } if (!hasRefs) { const isMeetMinY = meetOrSlice === 'meet' && scaleMin === scaleY; const isSliceMaxY = meetOrSlice === 'slice' && scaleMax === scaleY; const isMeetMinX = meetOrSlice === 'meet' && scaleMin === scaleX; const isSliceMaxX = meetOrSlice === 'slice' && scaleMax === scaleX; if (align.startsWith('xMid') && ( isMeetMinY || isSliceMaxY )) { ctx.translate(width / 2.0 - finalDesiredWidth / 2.0, 0); } if (align.endsWith('YMid') && ( isMeetMinX || isSliceMaxX )) { ctx.translate(0, height / 2.0 - finalDesiredHeight / 2.0); } if (align.startsWith('xMax') && ( isMeetMinY || isSliceMaxY )) { ctx.translate(width - finalDesiredWidth, 0); } if (align.endsWith('YMax') && ( isMeetMinX || isSliceMaxX )) { ctx.translate(0, height - finalDesiredHeight); } } // scale switch (true) { case align === 'none': ctx.scale(scaleX, scaleY); break; case meetOrSlice === 'meet': ctx.scale(scaleMin, scaleMin); break; case meetOrSlice === 'slice': ctx.scale(scaleMax, scaleMax); break; default: } // translate ctx.translate(-minX, -minY); } start( element: Element, { enableRedraw = false, ignoreMouse = false, ignoreAnimation = false, ignoreDimensions = false, ignoreClear = false, forceRedraw, scaleWidth, scaleHeight, offsetX, offsetY }: IScreenStartOptions = {} ) { const { FRAMERATE, mouse } = this; const frameDuration = 1000 / FRAMERATE; this.frameDuration = frameDuration; this.readyPromise = new Promise((resolve) => { this.resolveReady = resolve; }); if (this.isReady()) { this.render( element, ignoreDimensions, ignoreClear, scaleWidth, scaleHeight, offsetX, offsetY ); } if (!enableRedraw) { return; } let now = Date.now(); let then = now; let delta = 0; const tick = () => { now = Date.now(); delta = now - then; if (delta >= frameDuration) { then = now - (delta % frameDuration); if (this.shouldUpdate( ignoreAnimation, forceRedraw )) { this.render( element, ignoreDimensions, ignoreClear, scaleWidth, scaleHeight, offsetX, offsetY ); mouse.runEvents(); } } this.intervalId = requestAnimationFrame(tick); }; if (!ignoreMouse) { mouse.start(); } this.intervalId = requestAnimationFrame(tick); } stop() { if (this.intervalId) { requestAnimationFrame.cancel(this.intervalId); this.intervalId = null; } this.mouse.stop(); } private shouldUpdate( ignoreAnimation: boolean, forceRedraw: () => boolean ) { // need update from animations? if (!ignoreAnimation) { const { frameDuration } = this; const shouldUpdate = this.animations.reduce( (shouldUpdate, animation) => animation.update(frameDuration) || shouldUpdate, false ); if (shouldUpdate) { return true; } } // need update from redraw? if (typeof forceRedraw === 'function' && forceRedraw()) { return true; } if (!this.isReadyLock && this.isReady()) { return true; } // need update from mouse events? if (this.mouse.hasEvents()) { return true; } return false; } private render( element: Element, ignoreDimensions: boolean, ignoreClear: boolean, scaleWidth: number, scaleHeight: number, offsetX: number, offsetY: number ) { const { CLIENT_WIDTH, CLIENT_HEIGHT, viewPort, ctx, isFirstRender } = this; const canvas = ctx.canvas as HTMLCanvasElement; viewPort.clear(); if (canvas.width && canvas.height) { viewPort.setCurrent(canvas.width, canvas.height); } else { viewPort.setCurrent(CLIENT_WIDTH, CLIENT_HEIGHT); } const widthStyle = element.getStyle('width'); const heightStyle = element.getStyle('height'); if (!ignoreDimensions && ( isFirstRender || typeof scaleWidth !== 'number' && typeof scaleHeight !== 'number' )) { // set canvas size if (widthStyle.hasValue()) { canvas.width = widthStyle.getPixels('x'); if (canvas.style) { canvas.style.width = `${canvas.width}px`; } } if (heightStyle.hasValue()) { canvas.height = heightStyle.getPixels('y'); if (canvas.style) { canvas.style.height = `${canvas.height}px`; } } } let cWidth = canvas.clientWidth || canvas.width; let cHeight = canvas.clientHeight || canvas.height; if (ignoreDimensions && widthStyle.hasValue() && heightStyle.hasValue()) { cWidth = widthStyle.getPixels('x'); cHeight = heightStyle.getPixels('y'); } viewPort.setCurrent(cWidth, cHeight); if (typeof offsetX === 'number') { element.getAttribute('x', true).setValue(offsetX); } if (typeof offsetY === 'number') { element.getAttribute('y', true).setValue(offsetY); } if (typeof scaleWidth === 'number' || typeof scaleHeight === 'number' ) { const viewBox = toNumbers(element.getAttribute('viewBox').getString()); let xRatio = 0; let yRatio = 0; if (typeof scaleWidth === 'number') { const widthStyle = element.getStyle('width'); if (widthStyle.hasValue()) { xRatio = widthStyle.getPixels('x') / scaleWidth; } else if (!isNaN(viewBox[2])) { xRatio = viewBox[2] / scaleWidth; } } if (typeof scaleHeight === 'number') { const heightStyle = element.getStyle('height'); if (heightStyle.hasValue()) { yRatio = heightStyle.getPixels('y') / scaleHeight; } else if (!isNaN(viewBox[3])) { yRatio = viewBox[3] / scaleHeight; } } if (!xRatio) { xRatio = yRatio; } if (!yRatio) { yRatio = xRatio; } element.getAttribute('width', true).setValue(scaleWidth); element.getAttribute('height', true).setValue(scaleHeight); const transformStyle = element.getStyle('transform', true, true); transformStyle.setValue(`${transformStyle.getString()} scale(${1.0 / xRatio}, ${1.0 / yRatio})`); } // clear and render if (!ignoreClear) { ctx.clearRect(0, 0, cWidth, cHeight); } element.render(ctx); if (isFirstRender) { this.isFirstRender = false; } } }
the_stack
import { expect } from "chai"; import { GeometryQuery } from "../../curve/GeometryQuery"; import { LineString3d } from "../../curve/LineString3d"; import { Point3d, Vector3d } from "../../geometry3d/Point3dVector3d"; import { Point3dArray } from "../../geometry3d/PointHelpers"; import { PolygonOps } from "../../geometry3d/PolygonOps"; import { PolylineOps } from "../../geometry3d/PolylineOps"; import { Range3d } from "../../geometry3d/Range"; import { Sample } from "../../serialization/GeometrySamples"; import { Checker } from "../Checker"; import { GeometryCoreTestIO } from "../GeometryCoreTestIO"; class PolylineCompressionChecker { public ck = new Checker(); public x0 = 0; public y0 = 0; public allGeometry: GeometryQuery[] = []; public shift(dx: number, dy: number) { this.x0 += dx; this.y0 += dy; } public verifyGlobalChordErrorCompression(numExpected: number, points: Point3d[], globalEdgeTolerance: number, areaTolerance = 0.0, perpendicularDistanceTolerance: number = 0.0) { const result = PolylineOps.compressByChordError(points, globalEdgeTolerance); const y0 = this.y0; this.x0 += 2.0 * globalEdgeTolerance; if (numExpected > 0) this.ck.testExactNumber(numExpected, result.length); const range = Range3d.createArray(points); const yStep = 1.5 * range.diagonal().magnitude(); GeometryCoreTestIO.captureCloneGeometry(this.allGeometry, LineString3d.create(points), this.x0, this.y0); GeometryCoreTestIO.createAndCaptureXYCircle(this.allGeometry, points[0], globalEdgeTolerance, this.x0, this.y0); this.y0 += yStep; GeometryCoreTestIO.captureCloneGeometry(this.allGeometry, LineString3d.create(result), this.x0, this.y0); GeometryCoreTestIO.createAndCaptureXYCircle(this.allGeometry, result[0], globalEdgeTolerance, this.x0, this.y0); this.y0 += yStep; const edgeCompress = PolylineOps.compressShortEdges(points, globalEdgeTolerance); GeometryCoreTestIO.captureCloneGeometry(this.allGeometry, LineString3d.create(edgeCompress), this.x0, this.y0); GeometryCoreTestIO.createAndCaptureXYCircle(this.allGeometry, points[0], globalEdgeTolerance, this.x0, this.y0); this.y0 += yStep; if (areaTolerance > 0) { const areaCompress = PolylineOps.compressSmallTriangles(points, areaTolerance); GeometryCoreTestIO.captureCloneGeometry(this.allGeometry, LineString3d.create(areaCompress), this.x0, this.y0); GeometryCoreTestIO.createAndCaptureXYCircle(this.allGeometry, points[0], Math.sqrt(areaTolerance), this.x0, this.y0); this.y0 += yStep; } if (perpendicularDistanceTolerance > 0) { this.y0 += 2.0 * yStep; let num0 = points.length; const edgeLengthRange0 = PolylineOps.edgeLengthRange(points); for (const numPass of [1, 2, 3, 4, 5, 6, 7, 8]) { for (let i = 0; i < 25 && i < points.length; i++) GeometryCoreTestIO.createAndCaptureXYCircle(this.allGeometry, points[i], perpendicularDistanceTolerance, this.x0, this.y0); const perpCompress = PolylineOps.compressByPerpendicularDistance(points, perpendicularDistanceTolerance, numPass); const edgeLengthRange1 = PolylineOps.edgeLengthRange(perpCompress); if (perpCompress.length > 3) this.ck.testLE(edgeLengthRange0.high, edgeLengthRange1.high, "Compression does not reduce max edge length"); const num1 = perpCompress.length; GeometryCoreTestIO.captureCloneGeometry(this.allGeometry, LineString3d.create(perpCompress), this.x0, this.y0); if (num1 === num0) break; this.y0 += yStep; num0 = num1; } } this.y0 = y0; this.x0 += 10.0 * range.xLength(); } /** Save the collected geometry to given fileName. */ public close(fileName: string) { GeometryCoreTestIO.saveGeometry(this.allGeometry, "PolylineCompression", fileName); expect(this.ck.getNumErrors()).equals(0); } } describe("GlobalCompression", () => { it("HelloWorld", () => { const context = new PolylineCompressionChecker(); context.verifyGlobalChordErrorCompression(2, [Point3d.create(0, 0, 0), Point3d.create(10, 0, 0)], 1.0); const point3 = [Point3d.create(0, 0, 0), Point3d.create(5, 1, 0), Point3d.create(10, 0, 0)]; context.verifyGlobalChordErrorCompression(3, point3, 0.5); context.verifyGlobalChordErrorCompression(2, point3, 2.0); for (const depth of [1, 2, 3]) { for (const fractal of [ Sample.createFractalHatReversingPattern(depth, 0.25), Sample.createFractalLReversingPattern(depth, 1.0), Sample.createFractalHatReversingPattern(depth, 0.05)]) { const dataRange = Range3d.createFromVariantData(fractal); const qBase = 0.001 * dataRange.diagonal().magnitude(); for (const factor of [1.0, 5.0, 10.0, 50.0, 100.0, 200.0]) { const q = factor * qBase; const qArea = q * q; context.verifyGlobalChordErrorCompression(0, fractal, q, qArea, q); } } } context.close("HelloWorld"); }); it("IsolateSmallPattern", () => { const context = new PolylineCompressionChecker(); for (const depth of [3, 1, 2, 3]) { for (const fractal of [ Sample.createFractalHatReversingPattern(depth, 0.05)]) { const dataRange = Range3d.createFromVariantData(fractal); const qBase = 0.001 * dataRange.diagonal().magnitude(); for (const factor of [1.0, 5.0, 10.0, 50.0, 100.0, 200.0]) { const q = factor * qBase; const qArea = q * q; context.verifyGlobalChordErrorCompression(0, fractal, q, qArea, q); } context.x0 += dataRange.xLength() * 10.0; } } context.close("IsolateSmallPattern"); }); it("SmallArrays", () => { const ck = new Checker(); const points = []; let yy = 0.0; for (let i = 0; i < 3; i++) { points.push(Point3d.create(i, yy, 0)); yy = 2.0 - yy; // toggle to sharp corner const pointsA = PolylineOps.compressShortEdges(points, 1.0); ck.testExactNumber(points.length, pointsA.length, "No Change chord error case"); const pointsB = PolylineOps.compressSmallTriangles(points, 0.5); ck.testExactNumber(points.length, pointsB.length, "No Change triangle case"); const pointsC = PolylineOps.compressByPerpendicularDistance(points, 0.1, 1); ck.testExactNumber(points.length, pointsC.length, "No Change perp case"); const pointsD = PolylineOps.compressByPerpendicularDistance(points, 0.1, 2); ck.testExactNumber(points.length, pointsD.length, "No Change perp case"); const pointsE = PolylineOps.compressByChordError(points, 0.1); ck.testExactNumber(points.length, pointsE.length, "No Change global chord error case"); } expect(ck.getNumErrors()).equals(0); }); it("ColinearThroughStart", () => { const context = new PolylineCompressionChecker(); const pointsWithColinearThroughStart = [ Point3d.createFrom({ x: 0, y: 0, z: -3538.3128322623243 })!, Point3d.createFrom({ x: 0, y: 0, z: -3538.3128322623243 })!, Point3d.createFrom({ x: 1746.2903617595616, y: 0, z: -3538.3128322623243 })!, Point3d.createFrom({ x: 1746.2903617595616, y: -1151.9060537233227, z: -3538.3128322623243 })!, Point3d.createFrom({ x: 4102.778912210693, y: -1151.9060537233227, z: -3538.3128322623243 })!, Point3d.createFrom({ x: 4196.968933325803, y: -1151.9060537233227, z: -3538.3128322623243 })!, Point3d.createFrom({ x: 4196.968933325803, y: -2189.4980628055105, z: -3538.3128322623243 })!, Point3d.createFrom({ x: -611.3604034049928, y: -2189.4980628055105, z: -3538.3128322623243 })!, Point3d.createFrom({ x: -611.3604034049928, y: 0, z: -3538.3128322623243 })!, Point3d.createFrom({ x: 0, y: 0, z: -3538.3128322623243 })!, ]; context.verifyGlobalChordErrorCompression(0, pointsWithColinearThroughStart, 0.001); context.close("ColinearThroughStart"); }); // append points at multiple fractional positions along a vector. function appendPointsOnVector(points: Point3d[], vector: Vector3d, fractions: number[]) { if (points.length > 0) { const basePoint = points[points.length - 1]; for (const f of fractions) { points.push(basePoint.plusScaled(vector, f)); } } } // append points at multiple fractional positions along a vector. function insertPointsOnVector(points: Point3d[], baseIndex: number, vector: Vector3d, fractions: number[]): Point3d[] { const result: Point3d[] = []; for (let i = 0; i < points.length; i++){ result.push(points[i].clone()); if (i === baseIndex) { appendPointsOnVector(result, vector, fractions); } } return result; } it("Danglers", () => { const ck = new Checker(); const allGeometry: GeometryQuery[] = []; const originalPoints: Point3d[] = []; originalPoints.push(Point3d.create(0, 0, 0)); originalPoints.push(Point3d.create(10, 6, 0)); originalPoints.push(Point3d.create(0, 12, 0)); originalPoints.push(Point3d.create(-10, 6, 0)); const n = originalPoints.length; const vectorX4 = Vector3d.create(4, 0, 0); const vectorY2 = Vector3d.create(0, 2, 0); const vectorQ = Vector3d.create(2, 1, 0); const area0 = PolygonOps.areaXY(originalPoints); const originalLength = Point3dArray.sumEdgeLengths(originalPoints); let x0 = 0; let y0 = 0; const dx = 30; const dy = 20; const compressAndTest = (pointsWithDanglers: Point3d[]) => { const e0 = ck.getNumErrors(); const y00 = y0; GeometryCoreTestIO.captureCloneGeometry(allGeometry, pointsWithDanglers, x0, y0 += dy); GeometryCoreTestIO.createAndCaptureXYMarker(allGeometry, 0, pointsWithDanglers[0], 0.25, x0, y0); const areaA = PolygonOps.areaXY(pointsWithDanglers); // danglers do not affect area! const compressedPoints = PolylineOps.compressDanglers(pointsWithDanglers, true); GeometryCoreTestIO.captureCloneGeometry(allGeometry, compressedPoints, x0, y0 += dy); ck.testCoordinate(area0, Math.abs (areaA), "area after removing danglers"); ck.testExactNumber(originalPoints.length, compressedPoints.length, "point count after compression"); const compressedLength = Point3dArray.sumEdgeLengths(compressedPoints); ck.testCoordinate(originalLength, compressedLength); y0 += dy; if (e0 < ck.getNumErrors()) { const range = Range3d.createArray(pointsWithDanglers); GeometryCoreTestIO.captureRangeEdges(allGeometry, range, x0, y00); } }; const originalCount = originalPoints.length; for (const baseIndex of [0, 1, n - 2, n - 1]) { x0 += dx; y0 = 0; GeometryCoreTestIO.captureCloneGeometry(allGeometry, originalPoints, x0, y0); const pointsA = insertPointsOnVector(originalPoints, baseIndex, vectorX4, [1, 0]); compressAndTest(pointsA); // we know the dangler tip is at baseIndex + 1 !!! const pointsB = insertPointsOnVector(pointsA, baseIndex + 1, vectorY2, [1, 1.5, 1, 0]); compressAndTest(pointsB); const pointsC = insertPointsOnVector(pointsB, baseIndex + 1, vectorY2, [-1, -1.5, -1, 0]); compressAndTest(pointsC); // Another dangler -- this time with an "on edge" return --- for (const shift of [2,3, 5]){ const pointsD = insertPointsOnVector(pointsC, (baseIndex + originalCount - shift) % originalCount, vectorQ, [0,1,0.5,-0.25, -1.0, 0]); compressAndTest(pointsD); } const nC = pointsC.length; for (const setback of [1, 2, 3, 4, 5, 6, 8, 12, nC - 1, nC - 2, nC - 3]) { const i0 = n - setback; if (i0 > 0) { const rotatedPoints = [...pointsC.slice(i0, nC), ...pointsC.slice(0, i0)]; compressAndTest(rotatedPoints); compressAndTest(rotatedPoints.slice().reverse()); } } } GeometryCoreTestIO.saveGeometry(allGeometry, "PolylineCompression", "Danglers"); expect(ck.getNumErrors()).equals(0); }); });
the_stack
import first from 'lodash/first'; import last from 'lodash/last'; import findIndex from 'lodash/findIndex'; import findLastIndex from 'lodash/findLastIndex'; import { ActualsTimeseries } from 'api'; import { ActualsTimeseriesRow, RegionSummaryWithTimeseries, MetricsTimeseriesRow, Metricstimeseries, Metrics, Actuals, Annotations, } from 'api/schema/RegionSummaryWithTimeseries'; import { indexOfLastValue, lastValue } from './utils'; import { assert, formatPercent, getPercentChange } from 'common/utils'; import { Metric } from 'common/metricEnum'; import { Region } from 'common/regions'; import { getRegionMetricOverride } from 'cms-content/region-overrides'; /** * Override any disabled metrics and make them reenabled. Used by internal tools. */ let overrideDisabledMetrics = false; export function reenableDisabledMetrics(enable: boolean): void { overrideDisabledMetrics = enable; } /** * We truncate (or in the case of charts, switch to a dashed line) the last * seven days of r(t) data because it is susceptible to continued change as we * get future data points. */ export const RT_TRUNCATION_DAYS = 7; // We require at least 15 ICU beds in order to show ICU Capacity usage. // This still covers enough counties to cover 80% of the US population. const MIN_ICU_BEDS = 15; /** Parameters that can be provided when constructing a Projection. */ export interface ProjectionParameters { isCounty: boolean; } export interface Column { x: number; // ms since epoch y: any; } // TODO(michael): Rework the way we expose datasets (use an enum or separate // functions instead of magic strings). // These names must match exactly the field in `Projection` that stores the // data. See `getColumn()`. export type DatasetId = | 'rtRange' | 'icuUtilization' | 'testPositiveRate' | 'vaccinations' | 'vaccinationsCompleted' | 'caseDensityByCases' | 'caseDensityRange' | 'smoothedDailyCases' | 'smoothedDailyDeaths' | 'rawDailyCases' | 'rawDailyDeaths' | 'rawHospitalizations' | 'smoothedHospitalizations' | 'rawICUHospitalizations' | 'smoothedICUHospitalizations'; export interface RtRange { /** The actual Rt value. */ rt: number; /** The lower-bound of the confidence interval. */ low: number; /** The upper-bound of the confidence interval. */ high: number; } export interface CaseDensityRange { caseDensity: number; newCases: number | null; low: number; high: number; } export interface ICUCapacityInfo { metricSeries: Array<number | null>; metricValue: number | null; totalBeds: number; covidPatients: number | null; nonCovidPatients: number | null; totalPatients: number; } export interface VaccinationsInfo { ratioCompletedSeries: Array<number | null>; ratioInitiatedSeries: Array<number | null>; peopleInitiated: number; ratioInitiated: number; peopleVaccinated: number; ratioVaccinated: number; dosesDistributed: number | null; ratioDosesAdministered: number | null; } /** * We use use an estimated case fatality ratio of 1 % with lower and upper bounds * of 0.5% and 1.5% respectively, used to calculate case density by deaths (main * series and range). */ // TODO: We were intending to calculate a low/high range for // caseDensityByDeath, based on a range of CFRs, but this doesn't work when // we merge with caseDensityByCases which has no range. So for now, // we are punting. // const CASE_FATALITY_RATIO_LOWER = 0.005; // const CASE_FATALITY_RATIO_UPPER = 0.015; export const CASE_FATALITY_RATIO = 0.01; /** * Represents a single projection for a given state or county. Contains a * time-series of things like hospitalizations, hospital capacity, infections, etc. */ export class Projection { readonly totalPopulation: number; readonly fips: string; readonly region: Region; readonly icuCapacityInfo: ICUCapacityInfo | null; readonly vaccinationsInfo: VaccinationsInfo | null; readonly currentCumulativeDeaths: number | null; readonly currentCumulativeCases: number | null; private readonly currentCaseDensity: number | null; readonly currentDailyDeaths: number | null; private readonly cumulativeActualDeaths: Array<number | null>; private readonly dates: Date[]; private readonly isCounty: boolean; // NOTE: These are used dynamically by getColumn() private readonly smoothedDailyCases: Array<number | null>; private readonly rtRange: Array<RtRange | null>; // ICU Utilization series as values between 0-1 (or > 1 if over capacity). private readonly icuUtilization: Array<number | null>; // Test Positive series as values between 0-1. private readonly testPositiveRate: Array<number | null>; private readonly vaccinations: Array<number | null>; private readonly vaccinationsCompleted: Array<number | null>; private readonly caseDensityByCases: Array<number | null>; private readonly caseDensityRange: Array<CaseDensityRange | null>; private readonly smoothedDailyDeaths: Array<number | null>; private readonly rawDailyCases: Array<number | null>; private readonly rawDailyDeaths: Array<number | null>; private readonly rawHospitalizations: Array<number | null>; private readonly smoothedHospitalizations: Array<number | null>; private readonly rawICUHospitalizations: Array<number | null>; private readonly smoothedICUHospitalizations: Array<number | null>; private readonly metrics: Metrics | null; readonly annotations: Annotations; constructor( summaryWithTimeseries: RegionSummaryWithTimeseries, parameters: ProjectionParameters, region: Region, ) { const { actualTimeseries, metricsTimeseries, dates, } = this.getAlignedTimeseriesAndDates(summaryWithTimeseries); const metrics = summaryWithTimeseries.metrics; this.metrics = metrics || null; this.dates = dates; this.isCounty = parameters.isCounty; this.totalPopulation = summaryWithTimeseries.population; this.fips = summaryWithTimeseries.fips; this.region = region; // Set up our series data exposed via getDataset(). this.rawDailyCases = actualTimeseries.map(row => row && row.newCases); this.smoothedDailyCases = this.smoothWithRollingAverage(this.rawDailyCases); this.rawDailyDeaths = actualTimeseries.map(row => row && row.newDeaths); this.smoothedDailyDeaths = this.smoothWithRollingAverage( this.rawDailyDeaths, ); this.rawHospitalizations = actualTimeseries.map( row => row && row.hospitalBeds.currentUsageCovid, ); this.smoothedHospitalizations = this.smoothWithRollingAverage( this.rawHospitalizations, ); this.rawICUHospitalizations = actualTimeseries.map(row => row?.icuBeds ? row.icuBeds.currentUsageCovid : null, ); this.smoothedICUHospitalizations = this.smoothWithRollingAverage( this.rawICUHospitalizations, ); this.cumulativeActualDeaths = this.smoothCumulatives( actualTimeseries.map(row => row && row.deaths), ); this.rtRange = this.calcRtRange(metricsTimeseries); this.testPositiveRate = metricsTimeseries.map( row => row && row.testPositivityRatio, ); this.icuCapacityInfo = this.getIcuCapacityInfo( metrics, metricsTimeseries, actualTimeseries, ); this.icuUtilization = this.icuCapacityInfo?.metricSeries || this.dates.map(date => null); this.vaccinationsInfo = this.getVaccinationsInfo( summaryWithTimeseries.actuals, metrics, metricsTimeseries, ); this.vaccinations = this.vaccinationsInfo?.ratioInitiatedSeries || this.dates.map(date => null); this.vaccinationsCompleted = this.vaccinationsInfo?.ratioCompletedSeries || this.dates.map(date => null); this.caseDensityByCases = metricsTimeseries.map( row => row && row.caseDensity, ); this.caseDensityRange = this.calcCaseDensityRange(); this.currentCaseDensity = metrics?.caseDensity ?? null; this.currentDailyDeaths = lastValue(this.smoothedDailyDeaths); this.currentCumulativeDeaths = summaryWithTimeseries.actuals.deaths; this.currentCumulativeCases = summaryWithTimeseries.actuals.cases; this.annotations = summaryWithTimeseries.annotations; } // TODO(michael): We should really pre-compute currentDailyAverageCases and // make sure we're pulling all of the data from the same day, to make sure it // matches the graph. get currentDailyAverageCases() { return lastValue(this.smoothedDailyCases); } /** Returns the last date we have (case) data for. */ get finalDate(): Date { const lastIndex = indexOfLastValue(this.smoothedDailyCases) ?? this.dates.length - 1; return this.dates[lastIndex]; } get testPositiveRateSource(): string | null { return this.metrics?.testPositivityRatioDetails?.source || null; } getMetricValue(metric: Metric): number | null { if (this.isMetricDisabled(metric)) { return null; } switch (metric) { case Metric.CASE_GROWTH_RATE: return this.metrics?.infectionRate ?? null; case Metric.HOSPITAL_USAGE: return this.icuCapacityInfo ? this.icuCapacityInfo.metricValue : null; case Metric.POSITIVE_TESTS: return this.metrics?.testPositivityRatio ?? null; case Metric.VACCINATIONS: return this.vaccinationsInfo ? this.vaccinationsInfo.ratioInitiated : null; case Metric.CASE_DENSITY: return this.currentCaseDensity; default: fail('Unknown metric: ' + metric); } } isMetricDisabled(metric: Metric): boolean { return ( !overrideDisabledMetrics && this.isMetricDisabledIgnoreOverride(metric) ); } isMetricDisabledIgnoreOverride(metric: Metric): boolean { const override = getRegionMetricOverride(this.region, metric); if (override) { if (override.blocked && !override.start_date && !override.end_date) { return true; } } return false; } get twoWeekPercentChangeInCases() { return this.getTwoWeekPercentChange(this.smoothedDailyCases); } get twoWeekPercentChangeInDeaths() { return this.getTwoWeekPercentChange(this.smoothedDailyDeaths); } private getTwoWeekPercentChange(series: any[]): number | null { const lastIndex = indexOfLastValue(series); assert(lastIndex != null, 'series is empty'); const lastTwoWeeks = series.slice(lastIndex - 14, lastIndex + 1); const firstVal = lastTwoWeeks[0]; const lastVal = last(lastTwoWeeks); if (!firstVal || !lastVal) { return null; } return getPercentChange(firstVal, lastVal); } private getIcuCapacityInfo( metrics: Metrics, metricsTimeseries: Array<MetricsTimeseriesRow | null>, actualsTimeseries: Array<ActualsTimeseriesRow | null>, ): ICUCapacityInfo | null { if (this.isMetricDisabled(Metric.HOSPITAL_USAGE)) { return null; } // TODO(https://trello.com/c/bnwRazOo/): Something is broken where the API // top-level actuals don't match the current metric value. So we extract // them from the timeseries for now. const icuIndex = indexOfLastValue( metricsTimeseries.map(row => row?.icuCapacityRatio), ); if (icuIndex != null && metrics.icuCapacityRatio !== null) { // Make sure we don't somehow grab the wrong data, given we're pulling it from the metrics / actuals timeseries. assert( metrics.icuCapacityRatio === null || metrics.icuCapacityRatio === metricsTimeseries[icuIndex]?.icuCapacityRatio, "Timeseries icuCapacityRatio doesn't match current metric value.", ); assert( metricsTimeseries[icuIndex]?.date === actualsTimeseries[icuIndex]?.date, "Dates in actualTimeseries and metricTimeseries aren't aligned.", ); const icuActuals = actualsTimeseries[icuIndex]!.icuBeds; const metricSeries = metricsTimeseries.map( row => row && row.icuCapacityRatio, ); const totalBeds = icuActuals.capacity; const covidPatients = icuActuals.currentUsageCovid; const totalPatients = icuActuals.currentUsageTotal; const enoughBeds = totalBeds !== null && totalBeds >= MIN_ICU_BEDS; const metricValue = enoughBeds ? metrics.icuCapacityRatio : null; assert( totalBeds !== null && totalPatients !== null, 'These must be non-null for the metric to be non-null', ); const nonCovidPatients = covidPatients === null ? null : totalPatients - covidPatients; return { metricSeries, metricValue, totalBeds, covidPatients, nonCovidPatients, totalPatients, }; } return null; } private getVaccinationsInfo( actuals: Actuals, metrics: Metrics, metricsTimeseries: Array<MetricsTimeseriesRow | null>, ): VaccinationsInfo | null { const ratioInitiated = metrics.vaccinationsInitiatedRatio; const ratioVaccinated = metrics.vaccinationsCompletedRatio; if ( ratioInitiated === null || ratioInitiated === undefined || ratioVaccinated === null || ratioVaccinated === undefined || this.isMetricDisabled(Metric.VACCINATIONS) ) { return null; } const peopleVaccinated = actuals.vaccinationsCompleted ?? ratioVaccinated * this.totalPopulation; const peopleInitiated = actuals.vaccinationsInitiated ?? ratioInitiated * this.totalPopulation; if (ratioVaccinated > ratioInitiated) { console.error( `Suspicious vaccine data for ${this.fips}: % Vaccinated ${formatPercent( ratioVaccinated, 2, )} > % Initiated ${formatPercent(ratioInitiated, 2)}.`, ); } const vaccinationsCompletedSeries = metricsTimeseries.map( row => row?.vaccinationsCompletedRatio || null, ); const vaccinationsInitiatedSeries = metricsTimeseries.map( row => row?.vaccinationsInitiatedRatio || null, ); let dosesDistributed = actuals.vaccinesDistributed ?? null; let ratioDosesAdministered = dosesDistributed ? (peopleInitiated + peopleVaccinated) / dosesDistributed : null; if ( ratioDosesAdministered && (ratioDosesAdministered < 0 || ratioDosesAdministered > 1) ) { console.error( `Suppressing suspicious vaccine doses administered % for ${ this.fips }: ${formatPercent(ratioDosesAdministered, 2)}`, ); dosesDistributed = null; ratioDosesAdministered = null; } return { peopleVaccinated, peopleInitiated, ratioInitiated, ratioVaccinated, ratioCompletedSeries: vaccinationsCompletedSeries, ratioInitiatedSeries: vaccinationsInitiatedSeries, dosesDistributed, ratioDosesAdministered, }; } private getColumn(columnName: string): Column[] { return this.dates.map((date, idx) => ({ x: date.getTime(), y: (this as any)[columnName][idx], })); } getDataset(dataset: DatasetId): Column[] { return this.getColumn(dataset); } /** Makes a dictionary from a timerseries to a row so that we can look up the values * based off the date. Eventually would be nice to use this around instead of the * two list scenario we have going right now. */ private makeDateDictionary(ts: ActualsTimeseries | Metricstimeseries) { const dict: { [date: string]: ActualsTimeseriesRow | MetricsTimeseriesRow; } = {}; ts.forEach((row: ActualsTimeseriesRow | MetricsTimeseriesRow) => { dict[row.date] = row; }); return dict; } /** getAlignedTimeseriesAndDates aligns all timeseries (both the actuals and predicted * timeseries) as well as the dates to be consistent (since we keep track of * three lists). * * In order to do this, we grab the earliest and latest dates from the * timeseries and for every single day in between them fill each array * (the dates, the actuals and the timeseries(predicted)) with the value at * that date or null. */ private getAlignedTimeseriesAndDates( summaryWithTimeseries: RegionSummaryWithTimeseries, ) { const actualsTimeseriesRaw = summaryWithTimeseries.actualsTimeseries; const metricsTimeseriesRaw = summaryWithTimeseries.metricsTimeseries || []; if (actualsTimeseriesRaw.length === 0) { return { actualTimeseries: [], metricsTimeseries: [], dates: [], }; } let earliestDate, latestDate; // If we have projections, we use that time range; else we use the actuals. // TODO(chris): Is there a reason that this was bound to the projections timeseries first? // It cuts off some of the earlier dates if (metricsTimeseriesRaw.length > 0) { earliestDate = new Date(first(metricsTimeseriesRaw)!.date); latestDate = new Date(last(metricsTimeseriesRaw)!.date); } else { earliestDate = new Date(first(actualsTimeseriesRaw)!.date); latestDate = new Date(last(actualsTimeseriesRaw)!.date); } earliestDate = new Date('2020-03-01'); const actualsTimeseries: Array<ActualsTimeseriesRow | null> = []; const metricsTimeseries: Array<MetricsTimeseriesRow | null> = []; const dates: Date[] = []; const actualsTimeseriesDictionary = this.makeDateDictionary( actualsTimeseriesRaw, ); const metricsTimeseriesDictionary = this.makeDateDictionary( metricsTimeseriesRaw, ); let currDate = new Date(earliestDate.getTime()); while (currDate <= latestDate) { const ts = currDate.toISOString().substring(0, 10); const actualsTimeseriesrowForDate = actualsTimeseriesDictionary[ ts ] as ActualsTimeseriesRow; const metricsTimeseriesRowForDate = metricsTimeseriesDictionary[ ts ] as MetricsTimeseriesRow; actualsTimeseries.push(actualsTimeseriesrowForDate || null); metricsTimeseries.push(metricsTimeseriesRowForDate || null); // Clone the date since we're about to mutate it below. dates.push(new Date(currDate.getTime())); // Increment the date by one. // We specifically use setUTCDate and getUTCDate instead of setDate and getDate, // as the latter two do not take daylight savings into account. // This results in each day being incremented by 24 hours (although two days of the year should be 23 and 25), // leading to days being shifted and displayed incorrectly. currDate.setUTCDate(currDate.getUTCDate() + 1); } return { actualTimeseries: actualsTimeseries, metricsTimeseries: metricsTimeseries, dates: dates, }; } private calcCaseDensityRange(): Array<CaseDensityRange | null> { return this.caseDensityByCases.map((caseDensity, indx, arr) => caseDensity === null ? null : { caseDensity: caseDensity, newCases: this.smoothedDailyCases[indx], low: caseDensity, high: caseDensity, }, ); } private calcRtRange( timeseries: Array<MetricsTimeseriesRow | null>, ): Array<RtRange | null> { const rtSeries = timeseries.map(row => row && row.infectionRate); const rtCiSeries = timeseries.map(row => row && row.infectionRateCI90); return rtSeries.map((rt, idx) => { const ci = rtCiSeries[idx]; if (rt !== null && ci !== null) { return { rt: rt, low: rt - ci, high: rt + ci, }; } else { return null; } }); } /** * Given a series of cumulative values, convert it to a series of deltas. * * Always returns null for the first delta to avoid an arbitrarily large * delta (that may represent a bunch of historical data). * * Nulls are skipped, emitting null as the delta and keeping track of the * last non-null as the prior to use for calculating the next delta. */ private deltasFromCumulatives( cumulatives: Array<number | null>, ): Array<number | null> { let lastValue: number | null = null; const result: Array<number | null> = []; for (let i = 0; i < cumulatives.length; i++) { const current = cumulatives[i]; if (current === null) { result.push(null); } else { if (lastValue === null || current - lastValue < 0) { // Sometimes series have a "correction" that resets the count // backwards. We treat that as a 'null' delta. Note: They could also // have a correction in the opposite direction, forcing an unusually // high delta, but we don't have a way to detect / handle that. :-( result.push(null); } else { result.push(current - lastValue); } } lastValue = current; } return result; } // TODO: Due to // https://github.com/covid-projections/covid-data-model/issues/315 there may // be an erroneous "zero" data point ~today. We detect these and just average // the adjacent numbers. private fixZeros(data: (number | null)[]) { for (let i = 1; i < data.length - 1; i++) { if ( (data[i] === null || data[i] === 0) && data[i - 1] !== 0 && data[i - 1] !== null && data[i + 1] !== 0 && data[i + 1] !== null ) { data[i] = (data[i - 1]! + data[i + 1]!) / 2; } } } private interpolateNullGaps(data: Array<number | null>, maxGap: number) { const gaps = this.findNullGaps(data).filter(({ start, end }) => { const length = end - start - 1; return length <= maxGap; }); return this.interpolateRanges(data, gaps); } /** * Finds any "gaps" where data is missing or stalls at a steady number for * multiple days and replaces them with interpolated data. */ private smoothCumulatives(data: Array<number | null>): Array<number | null> { const gaps = this.findGapsInCumulatives(data); return this.interpolateRanges(data, gaps); } /** * Given data and a list of ranges, interpolates the values inside each * range, using the start/end of each range as the fixed values to * interpolate between. */ private interpolateRanges( data: Array<number | null>, ranges: Array<{ start: number; end: number }>, ): Array<number | null> { let result = [...data]; for (const { start, end } of ranges) { const startValue = data[start]!; const endValue = data[end]!; const round = Number.isInteger(startValue) && Number.isInteger(endValue); const divisions = end - start; const divisionDelta = (endValue - startValue) / divisions; for (let i = start + 1; i < end; i++) { const value = startValue + divisionDelta * (i - start); result[i] = round ? Math.round(value) : value; } } return result; } /** * Given a series of data points representing cumulative values (should be * monotonically increasing), finds any "gaps" where data is `0`, `null`, or * stalls at a steady number for multiple days. * * The returned {start, end} tuples are the indices of the entries surrounding each gap. * * Any `0` / `null` data points at the beginning or end of the data are not * considered a gap. * * TODO(michael): We might want to impose a maximum gap size (e.g. 10 days) * to avoid papering over too much missing data. */ private findGapsInCumulatives( data: Array<number | null>, ): Array<{ start: number; end: number }> { let lastValidValueIndex: number | null = null; let lastValidValue = -1; const gaps = []; for (let i = 0; i < data.length; i++) { const value = data[i]; const isValid = value !== 0 && value !== null && (lastValidValueIndex === null || value !== data[lastValidValueIndex]); if (isValid) { if ( lastValidValueIndex !== null && lastValidValueIndex !== i - 1 && value !== lastValidValue + 1 ) { // we found a gap! gaps.push({ start: lastValidValueIndex, end: i }); } lastValidValueIndex = i; lastValidValue = value!; } } return gaps; } /** * Given a series of data points, finds any "gaps" where data is `null`. * * The returned {start, end} tuples are the indices of the entries surrounding each gap. * * Any `null` data points at the beginning or end of the data are not considered a gap. */ private findNullGaps( data: Array<number | null>, ): Array<{ start: number; end: number }> { let lastValidValueIndex: number | null = null; const gaps = []; for (let i = 0; i < data.length; i++) { const value = data[i]; if (value !== null) { if (lastValidValueIndex !== null && lastValidValueIndex !== i - 1) { // we found a gap! gaps.push({ start: lastValidValueIndex, end: i }); } lastValidValueIndex = i; } } return gaps; } private fillLeadingNullsWithZeros(data: Array<number | null>) { let nonZeroIndex = findIndex(data, v => v !== null); const result = []; for (let i = 0; i < data.length; i++) { if (i < nonZeroIndex) { result[i] = 0; } else { result[i] = data[i]; } } return result; } private smoothWithRollingAverage( data: Array<number | null>, days = 7, includeTrailingZeros = true, ): Array<number | null> { const result = []; let sum = 0; let count = 0; let lastValidIndex = data.length - 1; if (!includeTrailingZeros) { lastValidIndex = findLastIndex( data, value => value !== null && value !== 0, ); } for (let i = 0; i < data.length; i++) { const oldValue = i < days ? null : data[i - days]; if (oldValue !== null) { sum -= oldValue; count--; } const newValue = data[i]; if (newValue !== null && i <= lastValidIndex) { sum += newValue; count++; result.push(sum / count); } else { result.push(null); } } return result; } }
the_stack
import { Injector } from "@angular/core"; import { I18nService, ServerError, TelemetryService } from "@batch-flask/core"; import { ListSelection } from "@batch-flask/core/list"; import { Activity, ActivityService, ActivityStatus } from "@batch-flask/ui/activity"; import { DialogService } from "@batch-flask/ui/dialogs"; import { NotificationService } from "@batch-flask/ui/notifications"; import { Permission } from "@batch-flask/ui/permission"; import { WorkspaceService } from "@batch-flask/ui/workspace"; import { exists, log, nil } from "@batch-flask/utils"; import * as inflection from "inflection"; import { Observable, forkJoin, of } from "rxjs"; import { map, share } from "rxjs/operators"; import { ActionableEntity, EntityCommands, ExecuteOptions } from "./entity-commands"; export enum EntityCommandNotify { Always, Never, OnFailure, } export interface EntityCommandAttributes<TEntity extends ActionableEntity, TOptions = void> { /** * Name is to be used by feature to show buttons. Or to define keyboard shortcuts */ name: string; label: ((entity: TEntity) => string) | string; icon?: ((entity: TEntity) => string) | string; action: (entity: TEntity, option?: TOptions) => Observable<any> | void; enabled?: (entity: TEntity) => boolean; visible?: (entity: TEntity) => boolean; multiple?: boolean | ((entities: TEntity[], options?: any) => Observable<any>); confirm?: ((entities: TEntity[]) => Observable<TOptions>) | boolean; notify?: EntityCommandNotify | boolean; permission?: Permission; } /** * Entity command is a commnad available to an entity */ export class EntityCommand<TEntity extends ActionableEntity, TOptions = void> { public name: string; public notify: EntityCommandNotify; public multiple: boolean | ((entities: TEntity[], options?: any) => Observable<any>); public enabled: (entity: TEntity) => boolean; public confirm: ((entities: TEntity[]) => Observable<TOptions>) | boolean; public definition: EntityCommands<TEntity>; public permission: Permission; public feature: string; private _action: (entity: TEntity, option?: TOptions) => Observable<any> | void; private _label: ((entity: TEntity) => string) | string; private _icon: ((entity: TEntity) => string) | string; private _visible: (entity: TEntity) => boolean; // Services private dialogService: DialogService; private notificationService: NotificationService; private activityService: ActivityService; private workspaceService: WorkspaceService; private i18n: I18nService; private telemetryService: TelemetryService; constructor(injector: Injector, attributes: EntityCommandAttributes<TEntity, TOptions>) { this.notificationService = injector.get(NotificationService); this.dialogService = injector.get(DialogService); this.activityService = injector.get(ActivityService); this.workspaceService = injector.get(WorkspaceService); this.i18n = injector.get(I18nService); this.telemetryService = injector.get(TelemetryService); this.name = attributes.name; this._label = attributes.label; this._icon = attributes.icon || "fa fa-question"; this._action = attributes.action; this.multiple = exists(attributes.multiple) ? attributes.multiple : true; this.enabled = attributes.enabled || (() => true); this._visible = attributes.visible || (() => true); this.confirm = exists(attributes.confirm) ? attributes.confirm : true; this.permission = attributes.permission || Permission.Read; if (attributes.notify === true || nil(attributes.notify)) { this.notify = EntityCommandNotify.Always; } else if (attributes.notify === false) { this.notify = EntityCommandNotify.Never; } else { this.notify = attributes.notify; } } public label(entity: TEntity) { return this._label instanceof Function ? this._label(entity) : this._label; } public icon(entity: TEntity) { return this._icon instanceof Function ? this._icon(entity) : this._icon; } public disabled(entity: TEntity) { return !this.enabled(entity); } public visible(entity: TEntity) { return this._visible(entity) && this._isFeatureEnabled(); } public performAction(entity: TEntity, option: TOptions): Observable<any> { const obs = this._action(entity, option); if (!obs) { return of(null); } return obs; } public performActionAndRefresh(entity: TEntity, option: TOptions): Observable<any> { const obs = this.performAction(entity, option); obs.subscribe({ complete: () => { this.definition.get(entity.id).subscribe({ error: () => null, }); }, error: () => { this.definition.get(entity.id).subscribe({ error: () => null, }); }, }); return obs; } /** * Try to execute the command for the given entity. * This will ask for confirmation unless command explicity configured not to */ public execute(entity: TEntity, options: ExecuteOptions = {}) { this._trackAction(1); if (this.confirm && !options.skipConfirm) { if (this.confirm instanceof Function) { this.confirm([entity]).subscribe((options) => { this._executeCommand(entity, options); }); } else { const label = this.label(entity); const type = this.definition.typeName.toLowerCase(); const message = this.i18n.t("entity-command.confirm.single.title", { action: label.toLowerCase(), type, }); const description = this.i18n.t("entity-command.confirm.single.description", { action: label.toLowerCase(), entityId: entity.id, }); this.dialogService.confirm(message, { description, yes: () => { this._executeCommand(entity); }, }); } } else { this._executeCommand(entity); } } /** * Try to execute the command for the given entities. * This will ask for confirmation unless command explicity configured not to */ public executeMultiple(entities: TEntity[], options: ExecuteOptions = {}) { this._trackAction(entities.length); if (this.confirm && !options.skipConfirm) { if (this.confirm instanceof Function) { this.confirm(entities).subscribe((options) => { this._executeMultiple(entities, options); }); } else { const type = inflection.pluralize(this.definition.typeName.toLowerCase()); const label = this.label(entities.first()); const message = this.i18n.t("entity-command.confirm.multiple.title", { action: label.toLowerCase(), count: entities.length, type, }); this.dialogService.confirm( message, { description: entities.map(x => x.id).join("\n"), yes: () => { this._executeMultiple(entities); }, }); } } else { this._executeMultiple(entities); } } public executeMultipleByIds(ids: string[]) { const obs = ids.map(id => this.definition.getFromCache(id)); return forkJoin(obs).pipe( map(entities => this.executeMultiple(entities)), share(), ); } public executeFromSelection(selection: ListSelection) { return this.executeMultipleByIds([...selection.keys]); } private _executeCommand(entity: TEntity, options?: any) { this._trackConfirm(1); const label = this.label(entity); this.performActionAndRefresh(entity, options).subscribe({ next: () => { this._notifySuccess(`${label} was successful.`, `${entity.name}`); }, error: (e: ServerError) => { this._notifyError(`${label} failed.`, `${entity.name} ${e.message}`); log.error(`Failed to execute command ${label} for entity ${entity.name}`, e); }, }); } private _executeMultiple(entities: TEntity[], options?: any) { this._trackConfirm(entities.length); const label = this.label(entities[0]); if (typeof this.multiple === "function") { return this.multiple(entities, options).subscribe({ next: () => { this._notifySuccess(`${label} was successful.`, ""); }, error: (e: ServerError) => { this._notifyError(`${label} failed.`, e.message); }, }); } const enabledEntities = entities.filter(x => this.enabled(x)); const type = inflection.pluralize(this.definition.typeName.toLowerCase()); // create an activity that creates a list of subactivities const activity = new Activity(`${label} ${type}`, () => { // create a subactivity for each enabled entity const subActivities = enabledEntities.map((entity) => { return new Activity(`${label} ${entity.name}`, () => { // each subactivity should perform an action and refresh return this.performActionAndRefresh(entity, options); }); }); return of(subActivities); }); // notify success after the parent activity completes activity.done.subscribe((status) => { if (status === ActivityStatus.Completed) { this._notifySuccess(`${label} was successful.`, ""); } }); // run the parent activity this.activityService.exec(activity); } private _notifySuccess(message: string, description: string) { if (this.notify === EntityCommandNotify.Always) { this.notificationService.success(message, description); } } private _notifyError(message: string, description: string) { if (this.notify !== EntityCommandNotify.Never) { this.notificationService.error(message, description); } } private _isFeatureEnabled(): boolean { const feature = this.definition.config.feature; if (!feature) { return true; } return this.workspaceService.isFeatureEnabled(`${feature}.${this.name}`); } private _trackAction(count: number) { this.telemetryService.trackEvent({ name: "Execute action", properties: { type: this.definition.typeName, name: this.name, count, }, }); } private _trackConfirm(count: number) { this.telemetryService.trackEvent({ name: "Execute action confirmed", properties: { type: this.definition.typeName, name: this.name, count, }, }); } }
the_stack
import 'fake-indexeddb/auto'; import { DataStore as DataStoreType, initSchema as initSchemaType, } from '../src/datastore/datastore'; import { PersistentModelConstructor } from '../src/types'; import { Model, Post, Comment, PostComposite, PostCustomPK, PostCustomPKSort, PostCustomPKComposite, testSchema, } from './helpers'; let initSchema: typeof initSchemaType; let DataStore: typeof DataStoreType; describe('Storage tests', () => { describe('Update', () => { describe('Only include changed fields', () => { let zenNext; beforeEach(() => { jest.resetModules(); jest.resetAllMocks(); zenNext = jest.fn(); jest.doMock('zen-push', () => { class zenPush { constructor() {} next = zenNext; } return zenPush; }); ({ initSchema, DataStore } = require('../src/datastore/datastore')); }); test('scalar', async () => { const classes = initSchema(testSchema()); const { Model } = classes as { Model: PersistentModelConstructor<Model>; }; const dateCreated = new Date().toISOString(); const model = await DataStore.save( new Model({ field1: 'Some value', dateCreated, }) ); await DataStore.save( Model.copyOf(model, draft => { draft.field1 = 'edited'; }) ); const [_settingsSave, [modelSave], [modelUpdate]] = zenNext.mock.calls; // Save should include expect(modelSave.element.dateCreated).toEqual(dateCreated); // Update mutation should only include updated fields // => dateCreated should be undefined expect(modelUpdate.element.dateCreated).toBeUndefined(); expect(modelUpdate.element.field1).toEqual('edited'); }); test('scalar - unchanged', async () => { const classes = initSchema(testSchema()); const { Model } = classes as { Model: PersistentModelConstructor<Model>; }; const dateCreated = new Date().toISOString(); const model = await DataStore.save( new Model({ field1: 'Some value', dateCreated, }) ); await DataStore.save( Model.copyOf(model, draft => { draft.field1 = 'Some value'; }) ); const [[_modelSave], modelUpdate] = zenNext.mock.calls; expect(modelUpdate).toBeUndefined(); expect(modelUpdate).toBeUndefined(); expect(true).toBeTruthy(); }); test('update by nulling previous value', async () => { const classes = initSchema(testSchema()); const { Model } = classes as { Model: PersistentModelConstructor<Model>; }; const model = await DataStore.save( new Model({ field1: 'Some value', optionalField1: 'Some optional value', dateCreated: new Date().toISOString(), }) ); await DataStore.save( Model.copyOf(model, draft => { draft.optionalField1 = null; }) ); const [[_modelSave], [modelUpdate]] = zenNext.mock.calls; expect(modelUpdate.element.optionalField1).toBeNull(); }); test('updating value with undefined gets saved as null', async () => { const classes = initSchema(testSchema()); const { Model } = classes as { Model: PersistentModelConstructor<Model>; }; const model = await DataStore.save( new Model({ field1: 'Some value', optionalField1: 'Some optional value', dateCreated: new Date().toISOString(), }) ); await DataStore.save( Model.copyOf(model, draft => { draft.optionalField1 = undefined; }) ); const [[_modelSave], [modelUpdate]] = zenNext.mock.calls; expect(modelUpdate.element.optionalField1).toBeNull(); }); test('list (destructured)', async () => { const classes = initSchema(testSchema()); const { Model } = classes as { Model: PersistentModelConstructor<Model>; }; const model = await DataStore.save( new Model({ field1: 'Some value', dateCreated: new Date().toISOString(), emails: ['john@doe.com', 'jane@doe.com'], }) ); await DataStore.save( Model.copyOf(model, draft => { draft.emails = [...draft.emails, 'joe@doe.com']; }) ); const [[_modelSave], [modelUpdate]] = zenNext.mock.calls; const expectedValueEmails = [ 'john@doe.com', 'jane@doe.com', 'joe@doe.com', ]; expect(modelUpdate.element.dateCreated).toBeUndefined(); expect(modelUpdate.element.field1).toBeUndefined(); expect(modelUpdate.element.emails).toMatchObject(expectedValueEmails); }); test('list (push)', async () => { const classes = initSchema(testSchema()); const { Model } = classes as { Model: PersistentModelConstructor<Model>; }; const model = await DataStore.save( new Model({ field1: 'Some value', dateCreated: new Date().toISOString(), emails: ['john@doe.com', 'jane@doe.com'], }) ); await DataStore.save( Model.copyOf(model, draft => { draft.emails.push('joe@doe.com'); }) ); const [[_modelSave], [modelUpdate]] = zenNext.mock.calls; const expectedValueEmails = [ 'john@doe.com', 'jane@doe.com', 'joe@doe.com', ]; expect(modelUpdate.element.dateCreated).toBeUndefined(); expect(modelUpdate.element.field1).toBeUndefined(); expect(modelUpdate.element.emails).toMatchObject(expectedValueEmails); }); test('update with changed field and list unchanged', async () => { const classes = initSchema(testSchema()); const { Model } = classes as { Model: PersistentModelConstructor<Model>; }; const model = await DataStore.save( new Model({ field1: 'Some value', dateCreated: new Date().toISOString(), emails: ['john@doe.com', 'jane@doe.com'], }) ); await DataStore.save( Model.copyOf(model, draft => { draft.field1 = 'Updated value'; // same as above. should not be included in mutation input draft.emails = ['john@doe.com', 'jane@doe.com']; }) ); const [[_modelSave], [modelUpdate]] = zenNext.mock.calls; expect(modelUpdate.element.dateCreated).toBeUndefined(); expect(modelUpdate.element.field1).toEqual('Updated value'); expect(modelUpdate.element.emails).toBeUndefined(); }); test('update with list unchanged', async () => { const classes = initSchema(testSchema()); const { Model } = classes as { Model: PersistentModelConstructor<Model>; }; const model = await DataStore.save( new Model({ field1: 'Some value', dateCreated: new Date().toISOString(), emails: ['john@doe.com', 'jane@doe.com'], }) ); await DataStore.save( Model.copyOf(model, draft => { // same as above. should not result in mutation event draft.emails = ['john@doe.com', 'jane@doe.com']; }) ); const [[_modelSave], modelUpdate] = zenNext.mock.calls; expect(modelUpdate).toBeUndefined(); }); test('update by nulling list', async () => { const classes = initSchema(testSchema()); const { Model } = classes as { Model: PersistentModelConstructor<Model>; }; const model = await DataStore.save( new Model({ field1: 'Some value', dateCreated: new Date().toISOString(), emails: ['john@doe.com', 'jane@doe.com'], }) ); await DataStore.save( Model.copyOf(model, draft => { draft.emails = null; }) ); const [[_modelSave], [modelUpdate]] = zenNext.mock.calls; expect(modelUpdate.element.emails).toBeNull(); }); test('custom type (destructured)', async () => { const classes = initSchema(testSchema()); const { Model } = classes as { Model: PersistentModelConstructor<Model>; }; const model = await DataStore.save( new Model({ field1: 'Some value', dateCreated: new Date().toISOString(), metadata: { author: 'some author', rewards: [], penNames: [], }, }) ); await DataStore.save( Model.copyOf(model, draft => { draft.metadata = { ...draft.metadata, penNames: ['bob'], }; }) ); const [[_modelSave], [modelUpdate]] = zenNext.mock.calls; const expectedValueMetadata = { author: 'some author', rewards: [], penNames: ['bob'], }; expect(modelUpdate.element.dateCreated).toBeUndefined(); expect(modelUpdate.element.field1).toBeUndefined(); expect(modelUpdate.element.metadata).toMatchObject( expectedValueMetadata ); }); test('custom type (accessor)', async () => { const classes = initSchema(testSchema()); const { Model } = classes as { Model: PersistentModelConstructor<Model>; }; const model = await DataStore.save( new Model({ field1: 'Some value', dateCreated: new Date().toISOString(), metadata: { author: 'some author', rewards: [], penNames: [], }, }) ); await DataStore.save( Model.copyOf(model, draft => { draft.metadata.penNames = ['bob']; }) ); const [[_modelSave], [modelUpdate]] = zenNext.mock.calls; const expectedValueMetadata = { author: 'some author', rewards: [], penNames: ['bob'], }; expect(modelUpdate.element.dateCreated).toBeUndefined(); expect(modelUpdate.element.field1).toBeUndefined(); expect(modelUpdate.element.metadata).toMatchObject( expectedValueMetadata ); }); test('custom type unchanged', async () => { const classes = initSchema(testSchema()); const { Model } = classes as { Model: PersistentModelConstructor<Model>; }; const model = await DataStore.save( new Model({ field1: 'Some value', dateCreated: new Date().toISOString(), metadata: { author: 'some author', rewards: [], penNames: [], }, }) ); await DataStore.save( Model.copyOf(model, draft => { draft.field1 = 'Updated value'; draft.metadata = { author: 'some author', rewards: [], penNames: [], }; }) ); const [[_modelSave], [modelUpdate]] = zenNext.mock.calls; expect(modelUpdate.element.dateCreated).toBeUndefined(); expect(modelUpdate.element.field1).toEqual('Updated value'); expect(modelUpdate.element.metadata).toBeUndefined(); }); test('relation', async () => { const classes = initSchema(testSchema()); const { Post, Comment } = classes as { Post: PersistentModelConstructor<Post>; Comment: PersistentModelConstructor<Comment>; }; const post = await DataStore.save( new Post({ title: 'New Post', }) ); const comment = await DataStore.save( new Comment({ content: 'Hello world', post, }) ); const anotherPost = await DataStore.save( new Post({ title: 'Another Post', }) ); await DataStore.save( Comment.copyOf(comment, updated => { updated.post = anotherPost; }) ); const [, [commentSave], , [commentUpdate]] = zenNext.mock.calls; expect(commentSave.element.postId).toEqual(post.id); expect(commentUpdate.element.postId).toEqual(anotherPost.id); }); test('composite key', async () => { const classes = initSchema(testSchema()); // model has a GSI with a composite key defined: // @key(name: "titleSort", fields: ["title", "created", "sort"]) // updating any of the fields that comprise the sort portion of the composite key [1..n] // should include all of the other fields in that key // updating the hash key [0] should NOT include the other fields in that key const { PostComposite } = classes as { PostComposite: PersistentModelConstructor<PostComposite>; }; const createdTimestamp = String(Date.now()); const post = await DataStore.save( new PostComposite({ title: 'New Post', description: 'Desc', created: createdTimestamp, sort: 100, }) ); // `sort` is part of the key's composite sort key. // `created` should also be included in the mutation input const updated1 = await DataStore.save( PostComposite.copyOf(post, updated => { updated.sort = 101; }) ); // `title` is the HK, so `sort` and `created` should NOT be included in the input const updated2 = await DataStore.save( PostComposite.copyOf(updated1, updated => { updated.title = 'Updated Title'; }) ); // `description` does not belong to a key. No other fields should be included await DataStore.save( PostComposite.copyOf(updated2, updated => { updated.description = 'Updated Desc'; }) ); const [, [postUpdate1], [postUpdate2], [postUpdate3]] = zenNext.mock.calls; expect(postUpdate1.element.title).toBeUndefined(); expect(postUpdate1.element.created).toEqual(createdTimestamp); expect(postUpdate1.element.sort).toEqual(101); expect(postUpdate1.element.description).toBeUndefined(); expect(postUpdate2.element.title).toEqual('Updated Title'); expect(postUpdate2.element.created).toBeUndefined(); expect(postUpdate2.element.sort).toBeUndefined(); expect(postUpdate2.element.description).toBeUndefined(); expect(postUpdate3.element.title).toBeUndefined(); expect(postUpdate3.element.created).toBeUndefined(); expect(postUpdate3.element.sort).toBeUndefined(); expect(postUpdate3.element.description).toEqual('Updated Desc'); }); test('custom pk', async () => { const classes = initSchema(testSchema()); // model has a custom pk defined via @key(fields: ["postId"]) // the PK should always be included in the mutation input const { PostCustomPK } = classes as { PostCustomPK: PersistentModelConstructor<PostCustomPK>; }; const post = await DataStore.save( new PostCustomPK({ postId: 100, title: 'New Post', description: 'Desc', }) ); await DataStore.save( PostCustomPK.copyOf(post, updated => { updated.title = 'Updated'; }) ); const [, [postUpdate]] = zenNext.mock.calls; expect(postUpdate.element.postId).toEqual(100); expect(postUpdate.element.title).toEqual('Updated'); expect(postUpdate.element.description).toBeUndefined(); }); test('custom pk - with sort', async () => { const classes = initSchema(testSchema()); // model has a custom pk (hk + sort key) defined via @key(fields: ["id", "postId"]) // all of the fields in the PK should always be included in the mutation input const { PostCustomPKSort } = classes as { PostCustomPKSort: PersistentModelConstructor<PostCustomPKSort>; }; const post = await DataStore.save( new PostCustomPKSort({ postId: 100, title: 'New Post', description: 'Desc', }) ); await DataStore.save( PostCustomPKSort.copyOf(post, updated => { updated.title = 'Updated'; }) ); const [, [postUpdate]] = zenNext.mock.calls; expect(postUpdate.element.postId).toEqual(100); expect(postUpdate.element.title).toEqual('Updated'); expect(postUpdate.element.description).toBeUndefined(); }); test('custom pk - with composite', async () => { const classes = initSchema(testSchema()); // model has a custom pk (hk + composite key) defined via @key(fields: ["id", "postId", "sort"]) // all of the fields in the PK should always be included in the mutation input const { PostCustomPKComposite } = classes as { PostCustomPKComposite: PersistentModelConstructor<PostCustomPKComposite>; }; const post = await DataStore.save( new PostCustomPKComposite({ postId: 100, title: 'New Post', description: 'Desc', sort: 1, }) ); await DataStore.save( PostCustomPKComposite.copyOf(post, updated => { updated.title = 'Updated'; }) ); const [, [postUpdate]] = zenNext.mock.calls; expect(postUpdate.element.postId).toEqual(100); expect(postUpdate.element.sort).toEqual(1); expect(postUpdate.element.title).toEqual('Updated'); expect(postUpdate.element.description).toBeUndefined(); }); }); }); });
the_stack
import http from "http"; import https from "https"; import express from "express"; const ntlm = require("express-ntlm"); import net from "net"; import bodyParser from "body-parser"; import { pki } from "node-forge"; import { AddressInfo } from "net"; interface ExpressError extends Error { status?: number; } export interface AuthResponeHeader { header: string; status: number; } export class ExpressServer { private appNoAuth = express(); private appNtlmAuth = express(); private certPem = ""; private privateKeyPem = ""; private publicKeyPem = ""; private httpServer: http.Server; private httpsServer: https.Server; private httpServerSockets = new Set<net.Socket>(); private httpsServerSockets = new Set<net.Socket>(); private lastRequestHeaders: http.IncomingHttpHeaders; private sendNtlmType2Header: string = null; private sendWwwAuthHeader: AuthResponeHeader[] = []; private closeConnectionOnNextRequestState = false; private customStatusPhrase: string = null; constructor() { this.initExpress(this.appNoAuth, false); this.initExpress(this.appNtlmAuth, true); this.generateSelfSignedCert(); this.httpServer = http.createServer(this.appNtlmAuth); this.httpsServer = https.createServer( { key: this.privateKeyPem, cert: this.certPem, }, this.appNtlmAuth ); } private createResponse(res: express.Response, body: any) { if (this.closeConnectionOnNextRequestState) { this.closeConnectionOnNextRequestState = false; res.connection.destroy(); return; } res.setHeader("Content-Type", "application/json"); if (this.sendNtlmType2Header !== null) { res.setHeader("www-authenticate", "NTLM " + this.sendNtlmType2Header); res.sendStatus(401); return; } if (this.sendWwwAuthHeader.length > 0) { const auth = this.sendWwwAuthHeader.shift(); res.setHeader("www-authenticate", auth.header); res.sendStatus(auth.status); return; } if (this.customStatusPhrase) { res.statusMessage = this.customStatusPhrase; this.customStatusPhrase = null; } res.status(200).send(JSON.stringify(body)); } private initExpress(app: express.Application, useNtlm: boolean) { app.use(bodyParser.json()); app.use(function (err: ExpressError, req: express.Request, res: express.Response, next: express.NextFunction) { if (res.headersSent) { return next(err); } res.status(err.status || 500); res.render("error", { message: err.message, error: err, }); }); if (useNtlm) { app.use(ntlm({})); // Enables NTLM without check of user/pass } app.get("/get", (req, res) => { this.lastRequestHeaders = req.headers; let body = { message: "Expecting larger payload on GET", reply: "OK ÅÄÖéß", }; this.createResponse(res, body); }); app.post("/post", (req, res) => { this.lastRequestHeaders = req.headers; if (!req.body || !("ntlmHost" in req.body)) { res.status(400).send("Invalid body"); } req.body.reply = "OK ÅÄÖéß"; this.createResponse(res, req.body); }); app.put("/put", (req, res) => { this.lastRequestHeaders = req.headers; if (!req.body || !("ntlmHost" in req.body)) { res.status(400).send("Invalid body"); } req.body.reply = "OK ÅÄÖéß"; this.createResponse(res, req.body); }); app.delete("/delete", (req, res) => { this.lastRequestHeaders = req.headers; if (!req.body || !("ntlmHost" in req.body)) { res.status(400).send("Invalid body"); } req.body.reply = "OK ÅÄÖéß"; this.createResponse(res, req.body); }); } private yesterday(): Date { let d = new Date(); d.setDate(d.getDate() - 1); return d; } private tomorrow(): Date { let d = new Date(); d.setDate(d.getDate() + 1); return d; } private randomSerialNumber(): string { // generate random 16 bytes hex string let sn = ""; for (let i = 0; i < 4; i++) { sn += ("00000000" + Math.floor(Math.random() * Math.pow(256, 4)).toString(16)).slice(-8); } return sn; } private configureCert(certServer: pki.Certificate, publicKey: pki.rsa.PublicKey) { certServer.publicKey = publicKey; certServer.serialNumber = this.randomSerialNumber(); certServer.validity.notBefore = this.yesterday(); certServer.validity.notAfter = this.tomorrow(); let subject = [ { name: "commonName", value: "localhost", }, { name: "countryName", value: "SE", }, { shortName: "ST", value: "Legoland", }, { name: "localityName", value: "Bricksburg", }, { name: "organizationName", value: "TestOrg", }, { shortName: "OU", value: "TestOrg", }, ]; certServer.setSubject(subject); certServer.setIssuer(subject); let extensions = [ { name: "basicConstraints", cA: true, }, { name: "keyUsage", keyCertSign: true, digitalSignature: true, nonRepudiation: true, keyEncipherment: true, dataEncipherment: true, }, { name: "extKeyUsage", serverAuth: true, clientAuth: true, codeSigning: true, emailProtection: true, timeStamping: true, }, { name: "nsCertType", client: true, server: true, email: true, objsign: true, sslCA: true, emailCA: true, objCA: true, }, { name: "subjectAltName", altNames: [ { type: 2, // hostname value: "localhost", }, { type: 7, // IP ip: "127.0.0.1", }, ], }, { name: "subjectKeyIdentifier", }, ]; certServer.setExtensions(extensions); } private generateSelfSignedCert() { let keysServer = pki.rsa.generateKeyPair(1024); let certServer = pki.createCertificate(); this.configureCert(certServer, keysServer.publicKey); certServer.sign(keysServer.privateKey); this.certPem = pki.certificateToPem(certServer); this.privateKeyPem = pki.privateKeyToPem(keysServer.privateKey); this.publicKeyPem = pki.publicKeyToPem(keysServer.publicKey); } async startHttpServer(useNtlm: boolean, port?: number): Promise<string> { if (!port) { port = 0; } if (useNtlm) { this.httpServer = http.createServer(this.appNtlmAuth); } else { this.httpServer = http.createServer(this.appNoAuth); } // Increase TCP keep-alive timeout to 61 secs to detect issues with hanging connections this.httpsServer.keepAliveTimeout = 61 * 1000; this.httpsServer.headersTimeout = 65 * 1000; this.httpServer.on("connection", (socket) => { this.httpServerSockets.add(socket); socket.on("close", () => { this.httpServerSockets.delete(socket); }); }); return await new Promise<string>((resolve, reject) => { this.httpServer.on("listening", () => { let addressInfo = this.httpServer.address() as AddressInfo; const url = "http://localhost:" + addressInfo.port; this.httpServer.removeListener("error", reject); resolve(url); }); this.httpServer.on("error", reject); this.httpServer.listen(port); }); } async stopHttpServer() { await new Promise<void>((resolve, reject) => { this.httpServer.on("close", () => resolve()); // Called when all connections have been closed this.httpServer.close((err) => { if (err) { reject(err); } }); }); } destroyHttpSockets() { for (const socket of this.httpServerSockets.values()) { socket.destroy(); } this.httpServerSockets = new Set(); } async startHttpsServer(useNtlm: boolean, port?: number): Promise<string> { if (!port) { port = 0; } if (useNtlm) { this.httpsServer = https.createServer( { key: this.privateKeyPem, cert: this.certPem, }, this.appNtlmAuth ); } else { this.httpsServer = https.createServer( { key: this.privateKeyPem, cert: this.certPem, }, this.appNoAuth ); } // Increase TCP keep-alive timeout to 61 secs to detect issues with hanging connections this.httpsServer.keepAliveTimeout = 61 * 1000; this.httpsServer.headersTimeout = 65 * 1000; this.httpsServer.on("connection", (socket) => { this.httpsServerSockets.add(socket); socket.on("close", () => { this.httpsServerSockets.delete(socket); }); }); return await new Promise<string>((resolve, reject) => { this.httpsServer.on("listening", () => { let addressInfo = this.httpsServer.address() as AddressInfo; const url = "https://localhost:" + addressInfo.port; this.httpsServer.removeListener("error", reject); resolve(url); }); this.httpsServer.on("error", reject); this.httpsServer.listen(port); }); } async stopHttpsServer() { await new Promise<void>((resolve, reject) => { this.httpsServer.on("close", () => resolve()); // Called when all connections have been closed this.httpsServer.close((err) => { if (err) { reject(err); } }); }); } destroyHttpsSockets() { for (const socket of this.httpsServerSockets.values()) { socket.destroy(); } this.httpsServerSockets = new Set(); } get caCert(): Buffer { return Buffer.from(this.certPem, "utf8"); } lastRequestContainedAuthHeader(): boolean { return this.lastRequestHeaders.authorization !== undefined && this.lastRequestHeaders.authorization.length > 0; } sendNtlmType2(fakeHeader: string) { this.sendNtlmType2Header = fakeHeader; } sendWwwAuthOnce(fakeHeader: string) { this.sendWwwAuthHeader = [{ header: fakeHeader, status: 401 }]; } sendWwwAuth(fakeHeaders: AuthResponeHeader[]) { this.sendWwwAuthHeader = fakeHeaders; } closeConnectionOnNextRequest(close: boolean) { this.closeConnectionOnNextRequestState = close; } restartNtlm() { this.appNtlmAuth.use(ntlm({})); } setCustomStatusPhrase(phrase: string) { this.customStatusPhrase = phrase; } }
the_stack
import { AckMessage, AckFunc, AckPayload, NackPayload } from './ack'; import { ApiTransportBase, MessagePackage, MessageConfiguration } from './api_transport_base'; import { default as RequestHandler } from './base_handler'; import { Endpoint, ActionMap } from '../shapes'; import { Identity, AppObj } from '../../../shapes'; declare var require: any; import * as coreState from '../../core_state'; import {ipc, channels} from '../../transports/electron_ipc'; import { getWebContentsInitialOptionSet, RoutingInfo } from '../../core_state'; const system = require('../../api/system').System; class RendererBatchConfiguration { public readonly action: string; public readonly enabled: boolean; public readonly length: number; public readonly maxSize: number; public readonly payload: any; public readonly ttl: number; constructor(windowOptions: any, payload: any) { // This destructuring is safe because the shape of // window options are enforced and well defined // To Do: Convert five0BaseOptions to TypeScript const { experimental: { api: { batching: { renderer: { enabled, ttl, maxSize } } } } } = windowOptions; this.enabled = enabled; this.ttl = ttl; this.maxSize = maxSize; this.action = payload && payload.action; this.payload = payload; this.length = (payload && payload.payload && payload.payload.messages && payload.payload.messages.length) || 1; } } class BreadcrumbConfiguration { public readonly enabled: boolean; constructor(windowOptions: any) { // This destructuring is safe because the shape of // window options are enforced and well defined // To Do: Convert five0BaseOptions to TypeScript const { experimental: { api: { breadcrumbs } } } = windowOptions; this.enabled = breadcrumbs; } } // Optional properties so the base-type can remain declared in api_transport_base.ts class ElIPCConfiguration implements MessageConfiguration { public readonly breadcrumbConfiguration: BreadcrumbConfiguration; public readonly rendererBatchConfiguration: RendererBatchConfiguration; constructor(breadcrumbConfiguration: BreadcrumbConfiguration, rendererBatchConfiguration: RendererBatchConfiguration) { this.breadcrumbConfiguration = breadcrumbConfiguration; this.rendererBatchConfiguration = rendererBatchConfiguration; } } export class ElipcStrategy extends ApiTransportBase<MessagePackage> { constructor(actionMap: ActionMap, requestHandler: RequestHandler<MessagePackage>) { super(actionMap, requestHandler); this.requestHandler.addHandler((mp: MessagePackage, next: () => void) => { const { identity, data, ack, nack, strategyName } = mp; if (strategyName !== this.constructor.name) { next(); } else { const endpoint: Endpoint = this.actionMap[data.action]; if (endpoint) { let endpointReturnValue: any; try { endpointReturnValue = endpoint.apiFunc(identity, data, ack, nack); } catch (error) { return nack(error); } if (endpointReturnValue instanceof Promise) { // Promise-based endpoint endpointReturnValue.then(result => { ack(new AckPayload(result)); }).catch(err => { nack(err); }); } else if (endpointReturnValue !== undefined) { // Synchronous endpoint with returned data ack(new AckPayload(endpointReturnValue)); } else { // Callback-based endpoint (takes care of calling ack/nack by itself) } } else { const runtimeVersion = system.getVersion(); const message = `API call ${data.action} not implemented in runtime version: ${runtimeVersion}.`; ack(new NackPayload(message)); } } }); } private canTrySend(routingInfo: any): boolean { const { webContents, frameRoutingId } = routingInfo; const webContentsLocated = webContents; const webContentsExists = !webContents.isDestroyed(); const validRoutingId = typeof frameRoutingId === 'number'; return webContentsLocated && webContentsExists && validRoutingId; } // Dispatch a message private innerSend(payload: string, routingInfo: RoutingInfo): void { const { webContents, frameRoutingId, mainFrameRoutingId, _options} = routingInfo; if (frameRoutingId === mainFrameRoutingId) { // this is the main window frame if (!_options.api.iframe.enableDeprecatedSharedName) { webContents.sendToFrame(frameRoutingId, channels.CORE_MESSAGE, payload); } else { webContents.send(channels.CORE_MESSAGE, payload); } } else { // frameRoutingId != webContents.mainFrameRoutingId implies a frame webContents.sendToFrame(frameRoutingId, channels.CORE_MESSAGE, payload); } } public registerMessageHandlers(): void { ipc.on(channels.WINDOW_MESSAGE, this.onMessage.bind(this)); } public send(identity: Identity, payloadObj: any): void { const { uuid, name } = identity; const routingInfo = coreState.getRoutingInfoByUuidFrame(uuid, name); if (!routingInfo) { system.debugLog(1, `Routing info for uuid:${uuid} name:${name} not found`); return; } const { frameRoutingId } = routingInfo; const payload = JSON.stringify(payloadObj); if (!this.canTrySend(routingInfo)) { system.debugLog(1, `uuid:${uuid} name:${name} frameRoutingId:${frameRoutingId} not reachable, payload:${payload}`); } else { this.innerSend(payload, routingInfo); } } //TODO: this needs to be refactor at some point. public onClientAuthenticated(cb: Function): void { throw new Error('Not implemented'); } //TODO: this needs to be refactor at some point. public onClientDisconnect(cb: Function): void { throw new Error('Not implemented'); } protected onMessage(e: any, rawData: any, ackFactoryDelegate: any): void { try { const webContentsId = e.sender.id; const opts: any = getWebContentsInitialOptionSet(webContentsId).options; if (!opts) { throw new Error(`Unable to locate window information for endpoint with window id ${webContentsId}`); } const data = JSON.parse(JSON.stringify(rawData)); const configuration: ElIPCConfiguration = new ElIPCConfiguration(new BreadcrumbConfiguration(opts), new RendererBatchConfiguration(opts, data)); const ackFactory = ackFactoryDelegate || this.ackDecorator.bind(this); const ack = !data.isSync ? ackFactory(e, data.messageId, data, configuration) : this.ackDecoratorSync(e, data.messageId); const nack = this.nackDecorator(ack); const entityType = e.sender.getEntityType(e.frameRoutingId); const isIframe = e.sender.isIframe(e.frameRoutingId); const { api: { iframe: { enableDeprecatedSharedName } } } = opts; let subFrameName; if (!isIframe || enableDeprecatedSharedName) { subFrameName = opts.name; } else { subFrameName = e.sender.getFrameName(e.frameRoutingId); } const identity = { batch: data.action === 'api-batch', entityType, name: subFrameName, parentFrame: opts.name, uuid: opts.uuid }; /* tslint:disable: max-line-length */ //message payload might contain sensitive data, mask it. const disableIabSecureLogging = (<AppObj>coreState.getAppObjByUuid(opts.uuid))._options.disableIabSecureLogging; let replacer = (!disableIabSecureLogging && (data.action === 'publish-message' || data.action === 'send-message')) ? this.payloadReplacer : null; if (data.action === 'window-authenticate') { // not log password replacer = this.passwordReplacer; } system.debugLog(1, `received in-runtime${data.isSync ? '-sync ' : ''}: ${e.frameRoutingId} [${identity.uuid}]-[${identity.name}] ${JSON.stringify(data, replacer)}`); /* tslint:enable: max-line-length */ if (!identity.batch) { this.requestHandler.handle({ identity, data, ack, nack, e, strategyName: this.constructor.name }); } else { const deferredAckFactory = this.ackDeferredDecorator(e, data.messageId, data, configuration); data.payload.messages.forEach((m: any) => { this.onMessage(e, m, deferredAckFactory); }); } } catch (err) { system.debugLog(1, err); } } protected ackDecoratorSync(e: any, messageId: number): AckFunc { const ackObj = new AckMessage(); ackObj.correlationId = messageId; return (payload: any): void => { ackObj.payload = payload; try { // Log all messages when -v=1 system.debugLog(1, `sent sync in-runtime <= ${JSON.stringify(ackObj)}`); } catch (err) { /* tslint:disable: no-empty */ } if (!e.sender.isDestroyed()) { e.returnValue = JSON.stringify(ackObj); } }; } protected createAckObject(configuration: ElIPCConfiguration, originalPayload: any, messageId: number): AckMessage { const usingBreadcrumbs = configuration.breadcrumbConfiguration.enabled; const ackObj = (!usingBreadcrumbs ? new AckMessage() : new AckMessage(originalPayload.breadcrumb, originalPayload.action)); ackObj.correlationId = messageId; return ackObj; } protected ackDecorator(e: any, messageId: number, originalPayload: any, baseConfiguration: MessageConfiguration): AckFunc { const configuration: ElIPCConfiguration = <ElIPCConfiguration>baseConfiguration; const usingBreadcrumbs = configuration.breadcrumbConfiguration.enabled; const ackObj = this.createAckObject(configuration, originalPayload, messageId); if (usingBreadcrumbs) { ackObj.addBreadcrumb('core/ackDecorator'); } return (payload: any): void => { ackObj.payload = payload; try { // Log all messages when -v=1 /* tslint:disable: max-line-length */ system.debugLog(1, `sent in-runtime <= ${e.frameRoutingId} ${JSON.stringify(ackObj)}`); } catch (err) { /* tslint:disable: no-empty */ } if (!e.sender.isDestroyed()) { if (usingBreadcrumbs) { ackObj.addBreadcrumb('core/ACK'); } e.sender.sendToFrame(e.frameRoutingId, channels.CORE_MESSAGE, JSON.stringify(ackObj)); } }; } // Handles API batches. Generates a mock of ackDecorator, stores API ACKs, and dispatches as one combined message only after // all API messages in the batch have been resolved (ACK'd) protected ackDeferredDecorator(e: any, messageId: number, originalPayload: any, baseConfiguration: MessageConfiguration): any { const configuration: ElIPCConfiguration = <ElIPCConfiguration>baseConfiguration; const usingBreadcrumbs = configuration.breadcrumbConfiguration.enabled; const deferredAcks: any = []; // ACK of the entire API batch const mainAck = this.ackDecorator(e, messageId, originalPayload, baseConfiguration); // Stubs the responsibility of a normal ackDecorator // Track state for all ACKs in the batch return (e: any, messageId: number, originalPayload: any): AckFunc => { const ackObj = this.createAckObject(configuration, originalPayload, messageId); if (usingBreadcrumbs) { ackObj.addBreadcrumb('core/ackDelegate'); } // AckFunc to emulate Promise.all() return (payload: any): void => { ackObj.payload = payload; if (usingBreadcrumbs) { ackObj.addBreadcrumb('core/deferredACK'); } deferredAcks.push(ackObj); if (deferredAcks.length === configuration.rendererBatchConfiguration.length) { mainAck({ success: true, data: deferredAcks }); } }; }; } }
the_stack
import { StyleSetEvaluator } from "@here/harp-datasource-protocol/index-decoder"; import { mercatorProjection, TileKey } from "@here/harp-geoutils"; import { expect } from "chai"; import * as sinon from "sinon"; import { OmvDataAdapter } from "../lib/adapters/omv/OmvDataAdapter"; import { com } from "../lib/adapters/omv/proto/vector_tile"; import { DecodeInfo } from "../lib/DecodeInfo"; import { OmvFeatureFilterDescriptionBuilder } from "../lib/OmvDataFilter"; import { OmvFeatureFilterDescription, OmvFilterDescription, OmvFilterString, OmvGeometryType } from "../lib/OmvDecoderDefs"; import { MockGeometryProcessor } from "./MockGeometryProcessor"; enum VTJsonGeometryType { Unknown, Point, LineString, Polygon } // Encoded geometries - https://docs.mapbox.com/vector-tiles/specification/#encoding-geometry // See https://github.com/mapbox/vector-tile-spec/blob/master/2.1/README.md#4356-example-multi-polygon // Polygon 1: // Exterior Ring: CW // (0,0) // (10,0) // (10,10) // (0,10) // (0,0) // Polygon 2: // Exterior Ring: CW // (11,11) // (20,11) // (20,20) // (11,20) // Interior Ring: CCW // (13,13) // (13,17) // (17,17) // (17,13) const MultiPolygon = [ 9, 0, 0, 26, 20, 0, 0, 20, 19, 0, 15, // end Polygon1 9, 22, 2, 26, 18, 0, 0, 18, 17, 0, 15, // end Polygon2#exterior 9, 4, 13, 26, 0, 8, 8, 0, 0, 7, 15 // end Polygon2#interior ]; // MultiPolygon with rings having opposite winding // Polygon#1 - [ext:CCW] // Polygon#2 - [ext:CCW, int:CW] const WrongWindingMultiPolygon = [ 9, 0, 0, 26, 0, 20, 20, 0, 0, 19, 15, // end Polygon1 9, 2, 22, 26, 0, 18, 18, 0, 0, 17, 15, // end Polygon2#exterior 9, 13, 4, 26, 0, 0, 8, 7, 0, 15 // end Polygon2#interior ]; const line = [9, 0, 0, 26, 20, 0, 0, 20, 19, 0, 15]; const point = [9, 0, 0, 15]; const MVTLayer = { name: "layer", features: [ { type: VTJsonGeometryType.Polygon, id: 1, tags: {}, geometry: MultiPolygon } ] }; const MVTTile = { layers: [MVTLayer] }; describe("OmvDataAdapter", function () { let decodeInfo: DecodeInfo; let geometryProcessor: MockGeometryProcessor; let adapter: OmvDataAdapter; let styleSetEvaluator: StyleSetEvaluator; let TileDecodeStub: any; beforeEach(function () { decodeInfo = new DecodeInfo(mercatorProjection, new TileKey(0, 0, 1)); geometryProcessor = new MockGeometryProcessor(); adapter = new OmvDataAdapter(); styleSetEvaluator = new StyleSetEvaluator({ styleSet: [] }); sinon.stub(styleSetEvaluator, "wantsLayer").returns(true); sinon.stub(styleSetEvaluator, "wantsFeature").returns(true); TileDecodeStub = sinon.stub(com.mapbox.pb.Tile, "decode"); }); afterEach(function () { sinon.restore(); }); it("process polygon geometries with correct winding", function () { const polygonSpy = sinon.spy(geometryProcessor, "processPolygonFeature"); TileDecodeStub.returns(MVTTile); adapter.process(1 as any, decodeInfo, geometryProcessor); const polygons = polygonSpy.getCalls()[0].args[2]; expect(polygons.length).equals(2); }); it("process polygon geometries with opposite winding", function () { const polygonSpy = sinon.spy(geometryProcessor, "processPolygonFeature"); const tile = { ...MVTTile }; const layer = { ...MVTLayer }; const fakeData = 1; layer.features[0].geometry = WrongWindingMultiPolygon; tile.layers = [layer]; TileDecodeStub.returns(tile); adapter.process(fakeData as any, decodeInfo, geometryProcessor); const polygons = polygonSpy.getCalls()[0].args[2]; expect(polygons.length).equals(2); }); const layerName = "boundaries"; const attrKey = "fakeAttribute"; const attrValue = 42; const defFeatureFilter = new OmvFeatureFilterDescriptionBuilder().createDescription(); const defFilter: OmvFilterDescription = { layerName: { value: layerName, match: OmvFilterString.StringMatch.Match }, minLevel: 0, maxLevel: 20, geometryTypes: [OmvGeometryType.POINT, OmvGeometryType.LINESTRING, OmvGeometryType.POLYGON] }; interface TestInstance { visitMethod: "visitPointFeature" | "visitLineFeature" | "visitPolygonFeature"; processorMethod: "processPointFeature" | "processLineFeature" | "processPolygonFeature"; geometryType: com.mapbox.pb.Tile.GeomType; geometry: number[]; filterDescription: OmvFeatureFilterDescription; modifierDescription: OmvFeatureFilterDescription; } const testInstances: TestInstance[] = [ { visitMethod: "visitPointFeature", processorMethod: "processPointFeature", geometryType: com.mapbox.pb.Tile.GeomType.POINT, geometry: point, filterDescription: { ...defFeatureFilter, processPointsDefault: false }, modifierDescription: { ...defFeatureFilter, processPointsDefault: false, pointsToProcess: [ { ...defFilter, featureAttribute: { key: attrKey, value: attrValue } } ] } }, { visitMethod: "visitLineFeature", processorMethod: "processLineFeature", geometryType: com.mapbox.pb.Tile.GeomType.LINESTRING, geometry: line, filterDescription: { ...defFeatureFilter, processLinesDefault: false }, modifierDescription: { ...defFeatureFilter, processLinesDefault: false, linesToProcess: [ { ...defFilter, featureAttribute: { key: attrKey, value: attrValue } } ] } }, { visitMethod: "visitPolygonFeature", processorMethod: "processPolygonFeature", geometryType: com.mapbox.pb.Tile.GeomType.POLYGON, geometry: MultiPolygon, filterDescription: { ...defFeatureFilter, processPolygonsDefault: false }, modifierDescription: { ...defFeatureFilter, processPolygonsDefault: false, polygonsToProcess: [ { ...defFilter, featureAttribute: { key: attrKey, value: attrValue } } ] } } ]; for (const testInstance of testInstances) { const visitMethod = testInstance.visitMethod; const processorMethod = testInstance.processorMethod; const type = testInstance.geometryType; const geometry = testInstance.geometry; const filterDescription = testInstance.filterDescription; const modifierDescription = testInstance.modifierDescription; const extent = 4096; const layer: com.mapbox.pb.Tile.ILayer = { version: 0, name: layerName, extent, keys: ["kind:aq", "id"], values: [{ stringValue: "disputed boundary" }, { intValue: 42 }] }; const kindTags = [0, 0]; // Indices to attributes names in layer.keys and values in layer.values. const idTags = [1, 1]; // Indices to id attribute name and value. describe(`${visitMethod}`, function () { let processSpy: sinon.SinonSpy<any>; beforeEach(function () { processSpy = sinon.spy(geometryProcessor, processorMethod); TileDecodeStub.returns({ layers: [] }); adapter.process(new ArrayBuffer(0), decodeInfo, geometryProcessor); adapter.visitLayer(layer); }); it("gets feature id from properties if present, otherwise from feature.id", function () { adapter.configure({}, styleSetEvaluator); const featureId = 13; adapter[visitMethod]({ geometry, type, id: featureId, tags: idTags }); expect(processSpy.calledOnce).is.true; const id = processSpy.firstCall.args[4]; expect(id).equals(layer.values![1].intValue); processSpy.resetHistory(); // Remove the id property, id should be taken now from feature.id. adapter.configure({}, styleSetEvaluator); adapter[visitMethod]({ geometry, type, id: featureId }); expect(processSpy.calledOnce).is.true; const newId = processSpy.firstCall.args[4]; expect(newId).equals(featureId); }); it("applies feature modifiers before finding matching techniques", function () { // Filter out feature using attribute value, checked by modifier. adapter.configure({ filterDescription: modifierDescription }, styleSetEvaluator); adapter[visitMethod]({ geometry, type }); expect(processSpy.calledOnce).is.false; // Remove the modifier and check the feature reaches the geometry processor. adapter.configure({ filterDescription: null }, styleSetEvaluator); adapter[visitMethod]({ geometry, type }); expect(processSpy.calledOnce).is.true; }); if (type === com.mapbox.pb.Tile.GeomType.LINESTRING) { it("applies political view modifiers", function () { // Configure political view. adapter.configure({ politicalView: "aq" }, styleSetEvaluator); adapter[visitMethod]({ geometry, type, tags: kindTags }); expect(processSpy.calledOnce).is.true; const kind = processSpy.firstCall.args[3]["kind"]; expect(kind).equals(layer.values![0].stringValue); processSpy.resetHistory(); // Set to default political view. adapter.configure({ politicalView: "" }, styleSetEvaluator); adapter[visitMethod]({ geometry, type, tags: kindTags }); expect(processSpy.calledOnce).is.true; const newKind = processSpy.firstCall.args[3]["kind"]; expect(newKind).to.be.undefined; }); } it("filters features", function () { // Filter out feature geometry type entirely. adapter.configure({ filterDescription }, styleSetEvaluator); adapter[visitMethod]({ geometry, type }); expect(processSpy.calledOnce).is.false; // Remove the filter and check the feature reaches the geometry processor. adapter.configure({ filterDescription: null }, styleSetEvaluator); adapter[visitMethod]({ geometry, type }); expect(processSpy.calledOnce).is.true; }); if (type !== com.mapbox.pb.Tile.GeomType.POINT) { // (0,0) -> (extent-1,extent-1) const lineAtBorder = [9, 0, 0, 10, (extent - 1) << 1, (extent - 1) << 1, 15]; function getEndCoords() { expect(processSpy.calledOnce); const geometries = processSpy.firstCall.args[2]; expect(geometries).has.lengthOf(1); const geometry = geometries[0]; processSpy.resetHistory(); return geometry.positions ? geometry.positions[1] : geometry.rings[0][1]; } it("does not round up x coordinates by default", function () { adapter.configure({}, styleSetEvaluator); adapter[visitMethod]({ geometry: lineAtBorder, type }); const endCoord = getEndCoords(); expect(endCoord.x).equals(extent - 1); expect(endCoord.y).equals(extent - 1); }); it("does not round up x coordinates if tile is not at antimer. on level <5", function () { adapter.configure({ roundUpCoordinatesIfNeeded: true }, styleSetEvaluator); // Level too high. adapter.process( new ArrayBuffer(0), { tileKey: new TileKey(0, TileKey.columnsAtLevel(5) - 1, 5) } as DecodeInfo, geometryProcessor ); adapter[visitMethod]({ geometry: lineAtBorder, type }); { const endCoord = getEndCoords(); expect(endCoord.x).equals(extent - 1); expect(endCoord.y).equals(extent - 1); } // Tile not at antimeridian. adapter.process( new ArrayBuffer(0), { tileKey: new TileKey(0, TileKey.columnsAtLevel(4) - 2, 4) } as DecodeInfo, geometryProcessor ); adapter[visitMethod]({ geometry: lineAtBorder, type }); const endCoord = getEndCoords(); expect(endCoord.x).equals(extent - 1); expect(endCoord.y).equals(extent - 1); }); it("rounds up x coordinates if flag set and tile at antimeridian on level <5", function () { adapter.configure({ roundUpCoordinatesIfNeeded: true }, styleSetEvaluator); adapter.process( new ArrayBuffer(0), { tileKey: new TileKey(0, TileKey.columnsAtLevel(4) - 1, 4) } as DecodeInfo, geometryProcessor ); adapter[visitMethod]({ geometry: lineAtBorder, type }); const endCoord = getEndCoords(); expect(endCoord.x).equals(extent); expect(endCoord.y).equals(extent - 1); processSpy.resetHistory(); }); } }); } });
the_stack
import * as util from '../util'; import * as concat3d_util from './concat3d_util'; import * as conv_util from './conv_util'; import {MatrixOrientation, NDArrayMath} from './math'; import * as ndarray from './ndarray'; import {Array1D, Array2D, Array3D, Array4D, NDArray, Scalar} from './ndarray'; import * as addscaledmat_gpu from './webgl/addscaledmat_gpu'; import {ArgMaxEqualsProgram} from './webgl/argmaxequals_gpu'; import {ArgMinMaxProgram} from './webgl/argminmax_gpu'; import * as avg_pool_gpu from './webgl/avg_pool_gpu'; import * as batchnorm_gpu from './webgl/batchnorm_gpu'; import * as concat3d_gpu from './webgl/concat3d_gpu'; import * as conv_backprop_gpu from './webgl/conv_backprop_gpu'; import * as conv_gpu from './webgl/conv_gpu'; import * as copy_gpu from './webgl/copy_gpu'; import {GPGPUContext} from './webgl/gpgpu_context'; import {BinaryOpProgram} from './webgl/binaryop_gpu'; import {GPGPUProgram, GPGPUBinary} from './webgl/gpgpu_math'; import * as gpgpu_math from './webgl/gpgpu_math'; import * as gpgpu_util from './webgl/gpgpu_util'; import {LogSumExpProgram} from './webgl/logsumexp_gpu'; import * as max_pool_backprop_gpu from './webgl/max_pool_backprop_gpu'; import * as max_pool_gpu from './webgl/max_pool_gpu'; import * as min_pool_gpu from './webgl/min_pool_gpu'; import {MinMaxProgram} from './webgl/minmax_gpu'; import {MatMulProgram} from './webgl/mulmat_gpu'; import * as pool_gpu from './webgl/pool_gpu'; import {ReduceSumProgram} from './webgl/reducesum_gpu'; import * as reshape_gpu from './webgl/reshape_gpu'; import * as resize_bilinear_gpu from './webgl/resize_bilinear_gpu'; import {TextureManager} from './webgl/texture_manager'; import * as webgl_util from './webgl/webgl_util'; import {UnaryOpProgram, UnaryOp} from './webgl/unaryop_gpu'; const BATCHNORM_PROG = 'batchnorm'; const COPY_PROG = 'copy'; const CONCAT_PROG = 'concat'; // Matrix algebra. const ADD_SCALED_MAT_PROG = 'addscaledmat'; // Element-wise ops. const RESHAPE_PROG = 'reshape'; // Convolution. const CONV2D_PROG = 'conv'; const CONV2D_TRANSPOSE_PROG = 'conv_transpose'; const CONV2D_DERW_PROG = 'conv_derw'; const CONV2D_DERB_PROG = 'conv_derb'; const MAX_POOL_PROG = 'maxpool'; const MAX_POOL_POSITIONS_PROG = 'maxpool_posn'; const MAX_POOL_BACKPROP_PROG = 'maxpool_backprop'; const MIN_POOL_PROG = 'minpool'; const AVG_POOL_PROG = 'avgpool'; const RESIZE_BILINEAR_PROG = 'resizebilin'; function makeCopyProgramName( sourceShapeRowCol: [number, number], sourceSizeRowCol: [number, number], destSizeRowCol: [number, number]): string { const shapeName = `${sourceShapeRowCol[0]}_${sourceShapeRowCol[1]}`; const srcSizeName = `${sourceSizeRowCol[0]}_${sourceSizeRowCol[1]}`; const dstSizeName = `${destSizeRowCol[0]}_${destSizeRowCol[1]}`; return `${COPY_PROG}_${shapeName}_${srcSizeName}_${dstSizeName}`; } export class NDArrayMathGPU extends NDArrayMath { private gpgpu: GPGPUContext; private textureManager: TextureManager; private programCache: {[key: string]: WebGLProgram} = {}; private binaryCache: {[key: string]: GPGPUBinary} = {}; private gpgpuCreatedLocally: boolean; constructor(gpgpu?: GPGPUContext, safeMode = true) { super(safeMode); if (gpgpu == null) { const gl = gpgpu_util.createWebGLContext(); this.gpgpu = new GPGPUContext(gl); this.gpgpuCreatedLocally = true; } else { this.gpgpu = gpgpu; this.gpgpuCreatedLocally = false; } this.textureManager = new TextureManager(this.gpgpu); ndarray.initializeGPU(this.gpgpu, this.textureManager); } getGPGPUContext(): GPGPUContext { return this.gpgpu; } protected cloneInternal<T extends NDArray>(ndarray: T): T { const textureShapeRC = ndarray.getTextureShapeRC(); const program = this.getAndSaveProgram( makeCopyProgramName(textureShapeRC, textureShapeRC, textureShapeRC), () => copy_gpu.getFragmentShaderSource( textureShapeRC, textureShapeRC, textureShapeRC)); const resultTexture = this.textureManager.acquireTexture(textureShapeRC); copy_gpu.copy( this.gpgpu, program, ndarray.getTexture(), textureShapeRC, [0, 0], textureShapeRC, resultTexture, textureShapeRC, [0, 0], textureShapeRC); return NDArray.make<T>( ndarray.shape, {texture: resultTexture, textureShapeRC}); } protected reshapeInternal<T1 extends NDArray, T2 extends NDArray>( ndarray: T1, newShape: number[]): T2 { let newTexShape: [number, number]; switch (newShape.length) { case 0: newTexShape = [1, 1]; break; case 1: newTexShape = [newShape[0], 1]; break; case 2: newTexShape = [newShape[0], newShape[1]]; break; case 3: newTexShape = [newShape[0], newShape[1] * newShape[2]]; break; default: throw Error( `Reshapes into ${newShape.length}-dim ndarray is not yet ` + `supported on GPU`); } const actualTexShape = ndarray.getTextureShapeRC(newTexShape); let clonedArray: T1; if (!util.arraysEqual(actualTexShape, newTexShape)) { clonedArray = this.reshapeTexture(ndarray, newTexShape); } else { clonedArray = this.cloneInternal(ndarray); } return clonedArray.reshape<T2>(newShape); } protected slice2DInternal( input: Array2D, beginRowCol: [number, number], sizeRowCol: [number, number]): Array2D { const result = NDArray.make<Array2D>(sizeRowCol, { texture: this.textureManager.acquireTexture(sizeRowCol), textureShapeRC: sizeRowCol }); this.copy2DInternal( input, beginRowCol, sizeRowCol, result, [0, 0], sizeRowCol); return result; } protected copy2DInternal( source: Array2D, sourceBeginRowCol: [number, number], sourceSizeRowCol: [number, number], dest: Array2D, destBeginRowCol: [number, number], destSizeRowCol: [number, number]): void { const sourceShapeRC = source.getTextureShapeRC(); const destShapeRC = dest.getTextureShapeRC(); const program = this.getAndSaveProgram( makeCopyProgramName(sourceShapeRC, sourceSizeRowCol, destSizeRowCol), () => copy_gpu.getFragmentShaderSource( sourceShapeRC, sourceSizeRowCol, destSizeRowCol)); copy_gpu.copy( this.gpgpu, program, source.getTexture(), sourceShapeRC, sourceBeginRowCol, sourceSizeRowCol, dest.getTexture(), destShapeRC, destBeginRowCol, destSizeRowCol); } protected concat3DInternal(x1: Array3D, x2: Array3D, axis: number): Array3D { const x1TexShapeRC: [number, number] = conv_util.computeTexShapeFrom3D(x1.shape); const x2TexShapeRC: [number, number] = conv_util.computeTexShapeFrom3D(x2.shape); // If the texture shapes doesn't match the shapes that shaders expect, // do physical texture reshapes on the GPU. const actualX1TexShape = x1.getTextureShapeRC(x1TexShapeRC); let cleanupX1 = false; if (!util.arraysEqual(actualX1TexShape, x1TexShapeRC)) { x1 = this.reshapeTexture(x1, x1TexShapeRC); cleanupX1 = true; } const actualX2TexShape = x2.getTextureShapeRC(x2TexShapeRC); let cleanupX2 = false; if (!util.arraysEqual(actualX2TexShape, x2TexShapeRC)) { x2 = this.reshapeTexture(x2, x2TexShapeRC); cleanupX2 = true; } const resultShapeRCD = concat3d_util.computeConcat3DOutputShape(x1.shape, x2.shape, axis); const program = this.getAndSaveProgram( `${CONCAT_PROG}_${x1.shape}_${x2.shape}_${axis}`, () => concat3d_gpu.getFragmentShaderSource( x1.shape, x2.shape, resultShapeRCD, axis)); const resultTexShape = conv_util.computeTexShapeFrom3D(resultShapeRCD); const resultTex = this.textureManager.acquireTexture(resultTexShape); concat3d_gpu.concat3D( this.gpgpu, program, x1.getTexture(), x2.getTexture(), resultTex, resultTexShape); if (cleanupX1) { x1.dispose(); } if (cleanupX2) { x2.dispose(); } return NDArray.make<Array3D>( resultShapeRCD, {texture: resultTex, textureShapeRC: resultTexShape}); } protected scaledArrayAddInternal<T extends NDArray>( c1: Scalar, a: T, c2: Scalar, b: T) { let cleanupB = false; if (!this.doGPUShapesMatch(a, b)) { b = this.reshapeTexture(b, a.getTextureShapeRC()); cleanupB = true; } const program = this.getAndSaveProgram( ADD_SCALED_MAT_PROG, () => addscaledmat_gpu.getFragmentShaderSource()); const textureShapeRC = a.getTextureShapeRC(); const resultTexture = this.textureManager.acquireTexture(textureShapeRC); addscaledmat_gpu.addScaledMatrices( this.gpgpu, program, a.getTexture(), b.getTexture(), textureShapeRC[0], textureShapeRC[1], c1.getTexture(), c2.getTexture(), resultTexture); if (cleanupB) { b.dispose(); } // Bring the result back to the original shape. return NDArray.make<T>(a.shape, {texture: resultTexture, textureShapeRC}); } protected negInternal<T extends NDArray>(a: T): T { const program = new UnaryOpProgram(a.shape, UnaryOp.NEG); return this.compileAndRun<T, T>(program, [a]); } private makeOutputArray<T extends NDArray>(shape: number[]): T { const textureShapeRC = webgl_util.getTextureShapeFromLogicalShape(this.gpgpu.gl, shape); const texture = this.textureManager.acquireTexture(textureShapeRC); return NDArray.make<T>(shape, {texture, textureShapeRC}); } private compileAndRun<T extends NDArray, K extends NDArray>( program: GPGPUProgram, inputs: T[]): K { const output = this.makeOutputArray<K>(program.outputShape); const key = gpgpu_math.makeShaderKey(program, inputs, output); const binary = this.getAndSaveBinary(key, () => { return gpgpu_math.compileProgram(this.gpgpu, program, inputs, output); }); gpgpu_math.runProgram(binary, inputs, output); return output; } private reshapeTexture<T extends NDArray>(a: T, newTextureShape: [ number, number ]): T { const aTexShape = a.getTextureShapeRC(); const program = this.getAndSaveProgram( RESHAPE_PROG, () => reshape_gpu.getFragmentShaderSource()); const resultTexture = this.textureManager.acquireTexture(newTextureShape); reshape_gpu.reshape( this.gpgpu, program, a.getTexture(), aTexShape[0], aTexShape[1], resultTexture, newTextureShape[0], newTextureShape[1]); return NDArray.make<T>( a.shape, {texture: resultTexture, textureShapeRC: newTextureShape}); } protected matMulInternal( a: Array2D, b: Array2D, aOrientation: MatrixOrientation, bOrientation: MatrixOrientation): Array2D { const program = new MatMulProgram(a.shape, b.shape, aOrientation, bOrientation); return this.compileAndRun<Array2D, Array2D>(program, [a, b]); } protected multiplyInternal<T extends NDArray>(a: T, b: T): T { const program = new BinaryOpProgram('*', a.shape, b.shape); return this.compileAndRun<T, T>(program, [a, b]); } protected batchNormalization3DInternal( x: Array3D, mean: Array3D|Array1D, variance: Array3D|Array1D, varianceEpsilon: number, scale?: Array3D|Array1D, offset?: Array3D|Array1D): Array3D { const xTexShape = x.getTextureShapeRC(); let cleanupMean = false; const preferredMeanTexShape: [number, number] = mean.rank === 1 ? [1, mean.size] : xTexShape; let meanTexShape = mean.getTextureShapeRC(preferredMeanTexShape); if (!util.arraysEqual(meanTexShape, preferredMeanTexShape)) { mean = this.reshapeTexture(mean, preferredMeanTexShape); meanTexShape = preferredMeanTexShape; cleanupMean = true; } let cleanupVariance = false; const preferredVarianceTexShape: [number, number] = variance.rank === 1 ? [1, variance.size] : xTexShape; let varianceTexShape = variance.getTextureShapeRC(preferredMeanTexShape); if (!util.arraysEqual(varianceTexShape, preferredVarianceTexShape)) { variance = this.reshapeTexture(variance, preferredVarianceTexShape); varianceTexShape = preferredVarianceTexShape; cleanupVariance = true; } let scaleTexShape: [number, number]|null = null; let cleanupScale = false; if (scale != null) { const preferredScaleTexShape: [number, number] = scale.rank === 1 ? [1, scale.size] : xTexShape; scaleTexShape = scale.getTextureShapeRC(preferredScaleTexShape); if (!util.arraysEqual(scaleTexShape, preferredScaleTexShape)) { scale = this.reshapeTexture(scale, preferredScaleTexShape); scaleTexShape = preferredScaleTexShape; cleanupScale = true; } } let offsetTexShape: [number, number]|null = null; let cleanupOffset = false; if (offset != null) { const preferredOffsetTexShape: [number, number] = offset.rank === 1 ? [1, offset.size] : xTexShape; offsetTexShape = offset.getTextureShapeRC(preferredOffsetTexShape); if (!util.arraysEqual(offsetTexShape, preferredOffsetTexShape)) { offset = this.reshapeTexture(offset, preferredOffsetTexShape); offsetTexShape = preferredOffsetTexShape; cleanupOffset = true; } } const resultTexShape: [number, number] = x.getTextureShapeRC(); const program = this.getAndSaveProgram( `${BATCHNORM_PROG}_${xTexShape}_${meanTexShape}_${varianceTexShape}_` + `${scaleTexShape!}_${offsetTexShape!}_${varianceEpsilon}`, () => batchnorm_gpu.getFragmentShaderSource( xTexShape, meanTexShape, varianceTexShape, offsetTexShape, scaleTexShape, varianceEpsilon)); const resultTexture = this.textureManager.acquireTexture(resultTexShape); batchnorm_gpu.batchNormalization( this.gpgpu, program, x.getTexture(), xTexShape, mean.getTexture(), meanTexShape, variance.getTexture(), varianceTexShape, offset != null ? offset.getTexture() : null, offset != null ? offsetTexShape : null, scale != null ? scale.getTexture() : null, scale != null ? scaleTexShape : null, resultTexture, resultTexShape); if (cleanupMean) { mean.dispose(); } if (cleanupVariance) { variance.dispose(); } if (cleanupScale) { scale!.dispose(); } if (cleanupOffset) { offset!.dispose(); } return NDArray.make<Array3D>( x.shape, {texture: resultTexture, textureShapeRC: resultTexShape}); } protected switchDimInternal<T extends NDArray>(a: T, newDim: number[]): T { throw new Error('Not yet implemented!'); } protected sumInternal(a: NDArray): Scalar { const program = new ReduceSumProgram(a.size); return this.compileAndRun(program, [a]); } protected argMinInternal(a: NDArray): Scalar { const program = new ArgMinMaxProgram(a.size, 'min'); return this.compileAndRun(program, [a]); } protected argMaxInternal(a: NDArray): Scalar { const program = new ArgMinMaxProgram(a.size, 'max'); return this.compileAndRun(program, [a]); } protected argMaxEqualsInternal(x1: NDArray, x2: NDArray): Scalar { const program = new ArgMaxEqualsProgram(x1.size, x2.size); return this.compileAndRun(program, [x1, x2]); } protected topKInternal(ndarray: NDArray, k: number): {values: Array1D, indices: Array1D} { throw new Error('topK GPU not yet implemented!'); } protected minInternal(a: NDArray): Scalar { const program = new MinMaxProgram(a.size, 'min'); return this.compileAndRun(program, [a]); } protected maxInternal(a: NDArray): Scalar { const program = new MinMaxProgram(a.size, 'max'); return this.compileAndRun(program, [a]); } protected divideInternal<T extends NDArray>(a: T, b: T): T { const program = new BinaryOpProgram('/', a.shape, b.shape); return this.compileAndRun<NDArray, T>(program, [a, b]); } protected addInternal<T extends NDArray>(a: T, b: T): T { const program = new BinaryOpProgram('+', a.shape, b.shape); return this.compileAndRun<NDArray, T>(program, [a, b]); } protected subInternal<T extends NDArray>(a: T, b: T): T { const program = new BinaryOpProgram('-', a.shape, b.shape); return this.compileAndRun<NDArray, T>(program, [a, b]); } protected logSumExpInternal(a: NDArray): Scalar { const program = new LogSumExpProgram(a.size); return this.compileAndRun(program, [a]); } protected expInternal<T extends NDArray>(a: T): T { const program = new UnaryOpProgram(a.shape, UnaryOp.EXP); return this.compileAndRun<T, T>(program, [a]); } protected logInternal<T extends NDArray>(a: T): T { const program = new UnaryOpProgram(a.shape, UnaryOp.LOG); return this.compileAndRun<T, T>(program, [a]); } protected reluInternal<T extends NDArray>(a: T): T { const program = new UnaryOpProgram(a.shape, UnaryOp.RELU); return this.compileAndRun<T, T>(program, [a]); } protected sigmoidInternal<T extends NDArray>(a: T): T { const program = new UnaryOpProgram(a.shape, UnaryOp.SIGMOID); return this.compileAndRun<T, T>(program, [a]); } protected tanhInternal<T extends NDArray>(a: T): T { const program = new UnaryOpProgram(a.shape, UnaryOp.TANH); return this.compileAndRun<T, T>(program, [a]); } protected sinInternal<T extends NDArray>(a: T): T { const program = new UnaryOpProgram(a.shape, UnaryOp.SIN); return this.compileAndRun<T, T>(program, [a]); } protected stepInternal<T extends NDArray>(a: T): T { const program = new UnaryOpProgram(a.shape, UnaryOp.STEP); return this.compileAndRun<T, T>(program, [a]); } protected conv2dInternal( x: Array3D, weights: Array4D, biases: Array1D|null, stride: number, zeroPad: number): Array3D { const fieldSize = weights.shape[0]; const inputDepth = weights.shape[2]; const outputDepth = weights.shape[3]; const progKey = [ CONV2D_PROG, x.shape, outputDepth, fieldSize, stride, biases != null ].join('_'); const program = this.getAndSaveProgram(progKey, () => { return conv_gpu.getFragmentShaderSource( x.shape, outputDepth, fieldSize, stride, zeroPad, biases != null); }); const xTexShape = conv_util.computeTexShapeFrom3D(x.shape); const wTexShape = conv_util.computeWeightsTexShape(inputDepth, outputDepth, fieldSize); const biasTexShape = conv_util.computeBiasesTexShape(outputDepth); // If the texture shapes doesn't match the shapes that shaders expect, // do physical texture reshapes on the GPU. const actualXTexShape = x.getTextureShapeRC(xTexShape); let cleanupX = false; if (!util.arraysEqual(actualXTexShape, xTexShape)) { x = this.reshapeTexture(x, xTexShape); cleanupX = true; } let cleanupW = false; const actualWTexShape = weights.getTextureShapeRC(wTexShape); if (!util.arraysEqual(actualWTexShape, wTexShape)) { weights = this.reshapeTexture(weights, wTexShape); cleanupW = true; } let cleanupB = false; if (biases != null) { const actualBTexShape = biases.getTextureShapeRC(biasTexShape); if (!util.arraysEqual(actualBTexShape, biasTexShape)) { biases = this.reshapeTexture(biases, biasTexShape); cleanupB = true; } } const resultShape = conv_util.computeOutputShape3D( x.shape, fieldSize, outputDepth, stride, zeroPad); const resultTexShape = conv_util.computeTexShapeFrom3D(resultShape); const resultTex = this.textureManager.acquireTexture(resultTexShape); conv_gpu.convolve( this.gpgpu, program, x.getTexture(), weights.getTexture(), biases != null ? biases.getTexture() : null, resultTex, resultTexShape); if (cleanupX) { x.dispose(); } if (cleanupW) { weights.dispose(); } if (cleanupB && biases != null) { biases.dispose(); } return NDArray.make<Array3D>( resultShape, {texture: resultTex, textureShapeRC: resultTexShape}); } protected conv2dBackPropInternal( x: Array3D, dy: Array3D, weights: Array4D, stride: number, pad: number): {dx: Array3D, dw: Array4D, db: Array1D} { const fSize = weights.shape[0]; const inputDepth = weights.shape[2]; const outputDepth = weights.shape[3]; const xTexShape = conv_util.computeTexShapeFrom3D(x.shape); const wTexShape = conv_util.computeWeightsTexShape(inputDepth, outputDepth, fSize); const yTexShape = conv_util.computeTexShapeFrom3D(dy.shape); // If the texture shapes doesn't match the shapes that shaders expect, // do physical texture reshapes on the GPU. let cleanupX = false; const actualXTexShape = x.getTextureShapeRC(xTexShape); if (!util.arraysEqual(actualXTexShape, xTexShape)) { x = this.reshapeTexture(x, xTexShape); cleanupX = true; } let cleanupW = false; const actualWTexShape = weights.getTextureShapeRC(wTexShape); if (!util.arraysEqual(actualWTexShape, wTexShape)) { weights = this.reshapeTexture(weights, wTexShape); cleanupW = true; } let cleanupY = false; const actualYTexShape = dy.getTextureShapeRC(yTexShape); if (!util.arraysEqual(actualYTexShape, yTexShape)) { dy = this.reshapeTexture(dy, yTexShape); cleanupY = true; } const dw = this.conv2dDerWeights(x, dy, fSize, stride, pad); const db = this.conv2dDerBias(dy); const dx = this.conv2dTransposeInternal( dy, weights, null /** biases */, stride, pad); if (cleanupX) { x.dispose(); } if (cleanupW) { weights.dispose(); } if (cleanupY) { dy.dispose(); } return {dx, db, dw}; } protected conv2dTransposeInternal( x: Array3D, weights: Array4D, biases: Array1D|null, origStride: number, origPad: number): Array3D { const origInputDepth = weights.shape[2]; const origOutputDepth = weights.shape[3]; const fieldSize = weights.shape[0]; const progKey = [ CONV2D_TRANSPOSE_PROG, x.shape, fieldSize, origInputDepth, origStride, origPad, biases != null ].join('_'); const program = this.getAndSaveProgram(progKey, () => { return conv_backprop_gpu.getFragmentShaderConvTransposeSource( x.shape, fieldSize, origInputDepth, origStride, origPad, biases != null); }); const xTexShape = conv_util.computeTexShapeFrom3D(x.shape); const wTexShape = conv_util.computeWeightsTexShape( origInputDepth, origOutputDepth, fieldSize); const biasTexShape = conv_util.computeBiasesTexShape(origInputDepth); // If the texture shapes doesn't match the shapes that shaders expect, // do physical texture reshapes on the GPU. const actualXTexShape = x.getTextureShapeRC(xTexShape); let cleanupX = false; if (!util.arraysEqual(actualXTexShape, xTexShape)) { x = this.reshapeTexture(x, xTexShape); cleanupX = true; } let cleanupW = false; const actualWTexShape = weights.getTextureShapeRC(wTexShape); if (!util.arraysEqual(actualWTexShape, wTexShape)) { weights = this.reshapeTexture(weights, wTexShape); cleanupW = true; } let cleanupB = false; if (biases != null) { const actualBiasTexShape = biases.getTextureShapeRC(biasTexShape); if (!util.arraysEqual(actualBiasTexShape, biasTexShape)) { biases = this.reshapeTexture(biases, biasTexShape); cleanupB = true; } } // Figure out the output shape by dilating the input. const dilatedRC = conv_util.computeDilatedRC([x.shape[0], x.shape[1]], origStride); const pad = fieldSize - 1 - origPad; const resultShape = conv_util.computeOutputShape3D( [dilatedRC[0], dilatedRC[1], origOutputDepth], fieldSize, origInputDepth, 1, pad); const resultTexShape = conv_util.computeTexShapeFrom3D(resultShape); const resultTex = this.textureManager.acquireTexture(resultTexShape); conv_backprop_gpu.convTranspose( this.gpgpu, program, x.getTexture(), weights.getTexture(), biases != null ? biases.getTexture() : null, resultTex, resultTexShape); if (cleanupX) { x.dispose(); } if (cleanupW) { weights.dispose(); } if (cleanupB) { biases!.dispose(); } return NDArray.make<Array3D>( resultShape, {texture: resultTex, textureShapeRC: resultTexShape}); } conv2dDerWeights( x: Array3D, dY: Array3D, fSize: number, stride: number, zeroPad: number): Array4D { const inputDepth = x.shape[2]; const outputDepth = dY.shape[2]; const progKey = [ CONV2D_DERW_PROG, x.shape, fSize, outputDepth, stride, zeroPad ].join('_'); const program = this.getAndSaveProgram(progKey, () => { return conv_backprop_gpu.getFragmentShaderDerWeightsSource( x.shape, fSize, outputDepth, stride, zeroPad); }); const xTexShape = conv_util.computeTexShapeFrom3D(x.shape); const yShape = conv_util.computeOutputShape3D( x.shape, fSize, outputDepth, stride, zeroPad); const yTexShape = conv_util.computeTexShapeFrom3D(yShape); // If the texture shapes doesn't match the shapes that shaders expect, // do physical texture reshapes on the GPU. const actualXTexShape = x.getTextureShapeRC(xTexShape); let cleanupX = false; if (!util.arraysEqual(actualXTexShape, xTexShape)) { x = this.reshapeTexture(x, xTexShape); cleanupX = true; } let cleanupY = false; const actualYTexShape = dY.getTextureShapeRC(yTexShape); if (!util.arraysEqual(actualYTexShape, yTexShape)) { dY = this.reshapeTexture(dY, yTexShape); cleanupY = true; } const resultTexShape = conv_util.computeWeightsTexShape(inputDepth, outputDepth, fSize); const resultTex = this.textureManager.acquireTexture(resultTexShape); conv_backprop_gpu.derWeights( this.gpgpu, program, x.getTexture(), dY.getTexture(), resultTex, resultTexShape); if (cleanupX) { x.dispose(); } if (cleanupY) { dY.dispose(); } const weightsShape = conv_util.computeWeightsShape4D(inputDepth, outputDepth, fSize); return NDArray.make<Array4D>( weightsShape, {texture: resultTex, textureShapeRC: resultTexShape}); } conv2dDerBias(dY: Array3D): Array1D { const outputDepth = dY.shape[2]; const progKey = [CONV2D_DERB_PROG, dY.shape].join('_'); const program = this.getAndSaveProgram(progKey, () => { return conv_backprop_gpu.getFragmentShaderDerBiasSource(dY.shape); }); const yTexShape = conv_util.computeTexShapeFrom3D(dY.shape); // If the texture shapes doesn't match the shapes that shaders expect, // do physical texture reshapes on the GPU. let cleanupY = false; const actualYTexShape = dY.getTextureShapeRC(yTexShape); if (!util.arraysEqual(actualYTexShape, yTexShape)) { dY = this.reshapeTexture(dY, yTexShape); cleanupY = true; } const resultTexShape = conv_util.computeBiasesTexShape(outputDepth); const resultTex = this.textureManager.acquireTexture(resultTexShape); conv_backprop_gpu.derBias( this.gpgpu, program, dY.getTexture(), resultTex, resultTexShape); if (cleanupY) { dY.dispose(); } return NDArray.make<Array1D>( [outputDepth], {texture: resultTex, textureShapeRC: resultTexShape}); } private pool( program: WebGLProgram, x: Array3D, fSize: number, stride: number, pad: number): Array3D { const xTexShape = conv_util.computeTexShapeFrom3D(x.shape); // If the texture shapes doesn't match the shapes that shaders expect, // do physical texture reshapes on the GPU. const actualXTexShape = x.getTextureShapeRC(xTexShape); let cleanupX = false; if (!util.arraysEqual(actualXTexShape, xTexShape)) { x = this.reshapeTexture(x, xTexShape); cleanupX = true; } const resultShape = conv_util.computeOutputShape3D(x.shape, fSize, x.shape[2], stride, pad); const resultTexShape = conv_util.computeTexShapeFrom3D(resultShape); const poolResultTex = this.textureManager.acquireTexture(resultTexShape); pool_gpu.poolCommon( this.gpgpu, program, x.getTexture(), poolResultTex, resultTexShape); if (cleanupX) { x.dispose(); } return NDArray.make<Array3D>( resultShape, {texture: poolResultTex, textureShapeRC: resultTexShape}); } protected maxPoolInternal( x: Array3D, fSize: number, stride: number, pad: number): Array3D { const maxPoolProgKey = [MAX_POOL_PROG, x.shape, fSize, stride, pad].join('_'); const maxPoolProgram = this.getAndSaveProgram(maxPoolProgKey, () => { return max_pool_gpu.getFragmentShaderMaxPoolSource( x.shape, fSize, stride, pad); }); return this.pool(maxPoolProgram, x, fSize, stride, pad); } protected minPoolInternal( x: Array3D, fSize: number, stride: number, pad: number): Array3D { const minPoolProgKey = [MIN_POOL_PROG, x.shape, fSize, stride, pad].join('_'); const minPoolProgram = this.getAndSaveProgram(minPoolProgKey, () => { return min_pool_gpu.getFragmentShaderMinPoolSource( x.shape, fSize, stride, pad); }); return this.pool(minPoolProgram, x, fSize, stride, pad); } protected avgPoolInternal( x: Array3D, fSize: number, stride: number, pad: number): Array3D { const avgPoolProgKey = [AVG_POOL_PROG, x.shape, fSize, stride, pad].join('_'); const avgPoolProgram = this.getAndSaveProgram(avgPoolProgKey, () => { return avg_pool_gpu.getFragmentShaderAvgPoolSource( x.shape, fSize, stride, pad); }); return this.pool(avgPoolProgram, x, fSize, stride, pad); } protected maxPoolBackpropInternal( dy: Array3D, x: Array3D, fSize: number, origStride: number, origPad: number): Array3D { const maxPoolPositionsProgKey = [ MAX_POOL_POSITIONS_PROG, x.shape, fSize, origStride, origPad ].join('_'); const maxPoolPositionsProgram = this.getAndSaveProgram(maxPoolPositionsProgKey, () => { return max_pool_gpu.getFragmentShaderMaxPoolPositionsSource( x.shape, fSize, origStride, origPad); }); const maxPoolResultShape = conv_util.computeOutputShape3D( x.shape, fSize, x.shape[2], origStride, origPad); const maxPoolResultTexShape = conv_util.computeTexShapeFrom3D(maxPoolResultShape); const maxPoolPositionsResultTex = this.textureManager.acquireTexture(maxPoolResultTexShape); // If the texture shapes doesn't match the shapes that shaders expect, // do physical texture reshapes on the GPU. const xTexShape = conv_util.computeTexShapeFrom3D(x.shape); const actualXTexShape = x.getTextureShapeRC(xTexShape); let cleanupX = false; if (!util.arraysEqual(actualXTexShape, xTexShape)) { x = this.reshapeTexture(x, xTexShape); cleanupX = true; } max_pool_gpu.maxPoolCommon( this.gpgpu, maxPoolPositionsProgram, x.getTexture(), maxPoolPositionsResultTex, maxPoolResultTexShape); const maxPoolBackpropProgKey = [ MAX_POOL_BACKPROP_PROG, dy.shape, fSize, origStride, origPad ].join('_'); const program = this.getAndSaveProgram(maxPoolBackpropProgKey, () => { return max_pool_backprop_gpu.getFragmentShaderMaxPoolBackprop( dy.shape, fSize, origStride, origPad); }); const dyTexShape = conv_util.computeTexShapeFrom3D(dy.shape); // If the texture shapes doesn't match the shapes that shaders expect, // do physical texture reshapes on the GPU. const actualDyTexShape = dy.getTextureShapeRC(dyTexShape); let cleanupDy = false; if (!util.arraysEqual(actualDyTexShape, dyTexShape)) { dy = this.reshapeTexture(dy, dyTexShape); cleanupDy = true; } const dilatedDyRC = conv_util.computeDilatedRC([dy.shape[0], dy.shape[1]], origStride); const pad = fSize - 1 - origPad; const resultShapeRCD = conv_util.computeOutputShape3D( [dilatedDyRC[0], dilatedDyRC[1], dy.shape[2]], fSize, dy.shape[2], 1, pad); const resultTexShape = conv_util.computeTexShapeFrom3D(resultShapeRCD); const resultTex = this.textureManager.acquireTexture(resultTexShape); max_pool_backprop_gpu.maxPoolBackprop( this.gpgpu, program, dy.getTexture(), maxPoolPositionsResultTex, resultTex, resultTexShape); if (cleanupDy) { dy.dispose(); } if (cleanupX) { x.dispose(); } this.textureManager.releaseTexture( maxPoolPositionsResultTex, maxPoolResultTexShape); return NDArray.make<Array3D>( resultShapeRCD, {texture: resultTex, textureShapeRC: resultTexShape}); } protected resizeBilinear3DInternal( x: Array3D, newShape2D: [number, number], alignCorners: boolean): Array3D { const programKey = [RESIZE_BILINEAR_PROG, x.shape, newShape2D, alignCorners].join('_'); const newShapeRCD: [number, number, number] = [newShape2D[0], newShape2D[1], x.shape[2]]; const resultTexShape = conv_util.computeTexShapeFrom3D(newShapeRCD); const program = this.getAndSaveProgram( programKey, () => resize_bilinear_gpu.getFragmentShaderSource( x.shape, newShape2D, alignCorners)); const resultTexture = this.textureManager.acquireTexture(resultTexShape); resize_bilinear_gpu.resizeBilinear( this.gpgpu, program, x.getTexture(), resultTexture, resultTexShape); return NDArray.make<Array3D>( newShapeRCD, {texture: resultTexture, textureShapeRC: resultTexShape}); } private getAndSaveBinary(key: string, getBinary: () => GPGPUBinary): GPGPUBinary { if (!(key in this.binaryCache)) { this.binaryCache[key] = getBinary(); } return this.binaryCache[key]; } private getAndSaveProgram(programKey: string, getShaderSource: () => string): WebGLProgram { if (!(programKey in this.programCache)) { this.programCache[programKey] = this.gpgpu.createProgram(getShaderSource()); } return this.programCache[programKey]; } private doGPUShapesMatch(a: NDArray, b: NDArray): boolean { util.assertShapesMatch(a.shape, b.shape); if (a.inGPU()) { // Prefer B to have the shape of A. b.getTextureShapeRC(a.getTextureShapeRC()); } else if (b.inGPU()) { // Prefer A to have the shape of B. a.getTextureShapeRC(b.getTextureShapeRC()); } return util.arraysEqual(a.getTextureShapeRC(), b.getTextureShapeRC()); } getTextureManager(): TextureManager { return this.textureManager; } dispose() { for (const programKey in this.programCache) { if (this.programCache.hasOwnProperty(programKey)) { this.gpgpu.deleteProgram(this.programCache[programKey]); } } for (const key in this.binaryCache) { this.gpgpu.deleteProgram(this.binaryCache[key].webGLProgram); } this.textureManager.dispose(); if (this.gpgpuCreatedLocally) { this.gpgpu.dispose(); } } }
the_stack
export const DART_LIBRARIES_FOR_BROWSER_TYPES = new Map(Object.entries({ 'HTMLDivElement': 'dart:html', 'NavigatorID': 'dart:html', 'HTMLImageElement': 'dart:html', 'TreeWalker': 'dart:html', 'HTMLTableSectionElement': 'dart:html', 'TextTrackCue': 'dart:html', 'FileEntry': 'dart:html', 'HTMLDetailsElement': 'dart:html', 'XPathResult': 'dart:html', 'XMLHttpRequest': 'dart:html', 'SpeechSynthesisUtterance': 'dart:html', 'DOMFileSystemSync': 'dart:html', 'CredentialsContainer': 'dart:html', 'Animation': 'dart:html', 'MessageChannel': 'dart:html', 'Navigator': 'dart:html', 'MediaQueryList': 'dart:html', 'CloseEvent': 'dart:html', 'ProgressEvent': 'dart:html', 'CSSImportRule': 'dart:html', 'MediaController': 'dart:html', 'StorageQuota': 'dart:html', 'MediaQueryListEvent': 'dart:html', 'HTMLCollection': 'dart:html', 'Element': 'dart:html', 'SpeechSynthesis': 'dart:html', 'FileList': 'dart:html', 'Plugin': 'dart:html', 'CSSFontFaceRule': 'dart:html', 'ReadableStream': 'dart:html', 'File': 'dart:html', 'Node': 'dart:html', 'MouseEvent': 'dart:html', 'DedicatedWorkerGlobalScope': 'dart:html', 'HTMLMenuElement': 'dart:html', 'AudioTrackList': 'dart:html', 'FetchEvent': 'dart:html', 'MediaStreamTrack': 'dart:html', 'StyleMedia': 'dart:html', 'WindowEventHandlers': 'dart:html', 'ShadowRoot': 'dart:html', 'SourceInfo': 'dart:html', 'DirectoryEntrySync': 'dart:html', 'WebKitAnimationEvent': 'dart:html', 'SpeechSynthesisEvent': 'dart:html', 'PluginPlaceholderElement': 'dart:html', 'MutationEvent': 'dart:html', 'Counter': 'dart:html', 'HTMLLinkElement': 'dart:html', 'TextTrackCueList': 'dart:html', 'VideoPlaybackQuality': 'dart:html', 'Window': 'dart:html', 'HTMLIFrameElement': 'dart:html', 'SpeechRecognition': 'dart:html', 'Console': 'dart:html', 'AutocompleteErrorEvent': 'dart:html', 'FontFace': 'dart:html', 'CanvasGradient': 'dart:html', 'HTMLAnchorElement': 'dart:html', 'Document': 'dart:html', 'MediaStream': 'dart:html', 'MessageEvent': 'dart:html', 'ClientRectList': 'dart:html', 'Rect': 'dart:html', 'RTCDTMFSender': 'dart:html', 'HTMLParamElement': 'dart:html', 'TextTrack': 'dart:html', 'HTMLModElement': 'dart:html', 'XSLTProcessor': 'dart:html', 'HTMLScriptElement': 'dart:html', 'NavigatorLanguage': 'dart:html', 'HTMLParagraphElement': 'dart:html', 'Touch': 'dart:html', 'URL': 'dart:html', 'BarProp': 'dart:html', 'DeviceLightEvent': 'dart:html', 'SourceBuffer': 'dart:html', 'CSSCharsetRule': 'dart:html', 'HTMLEmbedElement': 'dart:html', 'InstallEvent': 'dart:html', 'Metadata': 'dart:html', 'DeprecatedStorageQuota': 'dart:html', 'WebKitCSSTransformValue': 'dart:html', 'HTMLBaseElement': 'dart:html', 'HTMLBRElement': 'dart:html', 'DataTransfer': 'dart:html', 'Presentation': 'dart:html', 'MutationObserver': 'dart:html', 'FileEntrySync': 'dart:html', 'CircularGeofencingRegion': 'dart:html', 'XMLSerializer': 'dart:html', 'HTMLPictureElement': 'dart:html', 'PushManager': 'dart:html', 'CSSValueList': 'dart:html', 'HTMLObjectElement': 'dart:html', 'TouchEvent': 'dart:html', 'DOMMatrix': 'dart:html', 'AbstractWorker': 'dart:html', 'HTMLMeterElement': 'dart:html', 'ResourceProgressEvent': 'dart:html', 'HTMLUListElement': 'dart:html', 'ValidityState': 'dart:html', 'HTMLHRElement': 'dart:html', 'Storage': 'dart:html', 'DocumentType': 'dart:html', 'HTMLOptGroupElement': 'dart:html', 'Crypto': 'dart:html', 'ErrorEvent': 'dart:html', 'PerformanceTiming': 'dart:html', 'HTMLBodyElement': 'dart:html', 'RTCDataChannel': 'dart:html', 'NavigatorOnLine': 'dart:html', 'DeprecatedStorageInfo': 'dart:html', 'Geoposition': 'dart:html', 'HTMLAppletElement': 'dart:html', 'ApplicationCacheErrorEvent': 'dart:html', 'SpeechSynthesisVoice': 'dart:html', 'FontFaceSetLoadEvent': 'dart:html', 'MutationRecord': 'dart:html', 'HTMLFieldSetElement': 'dart:html', 'HTMLSourceElement': 'dart:html', 'InjectedScriptHost': 'dart:html', 'DirectoryReaderSync': 'dart:html', 'UIEvent': 'dart:html', 'HTMLHtmlElement': 'dart:html', 'RTCSessionDescription': 'dart:html', 'HTMLOptionElement': 'dart:html', 'Text': 'dart:html', 'MediaSource': 'dart:html', 'PositionError': 'dart:html', 'MediaKeyMessageEvent': 'dart:html', 'VideoTrackList': 'dart:html', 'GamepadButton': 'dart:html', 'CustomEvent': 'dart:html', 'WorkerConsole': 'dart:html', 'VTTRegion': 'dart:html', 'Stream': 'dart:html', 'HTMLHeadingElement': 'dart:html', 'History': 'dart:html', 'HTMLTemplateElement': 'dart:html', 'ClientRect': 'dart:math', 'RTCStatsReport': 'dart:html', 'TimeRanges': 'dart:html', 'ServiceWorkerRegistration': 'dart:html', 'Request': 'dart:html', 'WindowTimers': 'dart:html', 'WorkerNavigator': 'dart:html', 'DirectoryReader': 'dart:html', 'AnimationTimeline': 'dart:html', 'Event': 'dart:html', 'Iterator': 'dart:html', 'Headers': 'dart:html', 'ImageData': 'dart:html', 'MediaStreamTrackEvent': 'dart:html', 'RTCStatsResponse': 'dart:html', 'VTTRegionList': 'dart:html', 'HTMLDataListElement': 'dart:html', 'HTMLElement': 'dart:html', 'HTMLDocument': 'dart:html', 'MediaList': 'dart:html', 'ServiceWorkerClients': 'dart:html', 'MIDIPort': 'dart:html', 'CSSMediaRule': 'dart:html', 'ParentNode': 'dart:html', 'FileReaderSync': 'dart:html', 'CSSViewportRule': 'dart:html', 'DataTransferItemList': 'dart:html', 'DocumentFragment': 'dart:html', 'GlobalEventHandlers': 'dart:html', 'FederatedCredential': 'dart:html', 'RTCIceCandidateEvent': 'dart:html', 'PerformanceMark': 'dart:html', 'SharedWorkerGlobalScope': 'dart:html', 'DOMImplementation': 'dart:html', 'MimeTypeArray': 'dart:html', 'HTMLDialogElement': 'dart:html', 'StyleSheet': 'dart:html', 'HTMLTableRowElement': 'dart:html', 'MessagePort': 'dart:html', 'FileReader': 'dart:html', 'HTMLOptionsCollection': 'dart:html', 'Geofencing': 'dart:html', 'NodeList': 'dart:html', 'HTMLFrameSetElement': 'dart:html', 'PerformanceMeasure': 'dart:html', 'ServiceWorkerContainer': 'dart:html', 'RelatedEvent': 'dart:html', 'MIDIAccess': 'dart:html', 'HTMLTableCaptionElement': 'dart:html', 'CSSStyleRule': 'dart:html', 'DOMError': 'dart:html', 'HTMLMenuItemElement': 'dart:html', 'HashChangeEvent': 'dart:html', 'RTCDataChannelEvent': 'dart:html', 'HTMLMediaElement': 'dart:html', 'HTMLInputElement': 'dart:html', 'MediaDeviceInfo': 'dart:html', 'CDATASection': 'dart:html', 'StorageEvent': 'dart:html', 'CSSStyleSheet': 'dart:html', 'DOMRectReadOnly': 'dart:html', 'FormData': 'dart:html', 'PushEvent': 'dart:html', 'CSSSupportsRule': 'dart:html', 'DOMParser': 'dart:html', 'HTMLLIElement': 'dart:html', 'CSSPageRule': 'dart:html', 'PageTransitionEvent': 'dart:html', 'LocalCredential': 'dart:html', 'MemoryInfo': 'dart:html', 'ServiceWorkerGlobalScope': 'dart:html', 'HTMLPreElement': 'dart:html', 'NamedNodeMap': 'dart:html', 'HTMLStyleElement': 'dart:html', 'TrackEvent': 'dart:html', 'XPathEvaluator': 'dart:html', 'Performance': 'dart:html', 'AnimationNode': 'dart:html', 'HTMLContentElement': 'dart:html', 'CompositionEvent': 'dart:html', 'FileWriter': 'dart:html', 'HTMLSpanElement': 'dart:html', 'WebKitCSSMatrix': 'dart:html', 'CSSKeyframeRule': 'dart:html', 'WorkerPerformance': 'dart:html', 'MIDIInputMap': 'dart:html', 'TransitionEvent': 'dart:html', 'XMLDocument': 'dart:html', 'CSSValue': 'dart:html', 'GamepadEvent': 'dart:html', 'HTMLFontElement': 'dart:html', 'Response': 'dart:html', 'PagePopupController': 'dart:html', 'AnimationPlayerEvent': 'dart:html', 'DOMTokenList': 'dart:html', 'Credential': 'dart:html', 'DOMException': 'dart:html', 'PluginArray': 'dart:html', 'GamepadList': 'dart:html', 'DOMPoint': 'dart:html', 'HTMLLegendElement': 'dart:html', 'DOMFileSystem': 'dart:html', 'NavigatorCPU': 'dart:html', 'VideoTrack': 'dart:html', 'HTMLQuoteElement': 'dart:html', 'XMLHttpRequestEventTarget': 'dart:html', 'HTMLLabelElement': 'dart:html', 'NavigatorUserMediaError': 'dart:html', 'HTMLTextAreaElement': 'dart:html', 'TextMetrics': 'dart:html', 'HTMLUnknownElement': 'dart:html', 'RadioNodeList': 'dart:html', 'Selection': 'dart:html', 'AnimationEffect': 'dart:html', 'NodeIterator': 'dart:html', 'HTMLAreaElement': 'dart:html', 'ImageBitmap': 'dart:html', 'Notification': 'dart:html', 'CSSUnknownRule': 'dart:html', 'HTMLDirectoryElement': 'dart:html', 'Canvas2DContextAttributes': 'dart:html', 'HTMLTableCellElement': 'dart:html', 'DOMStringMap': 'dart:html', 'Entry': 'dart:html', 'AudioTrack': 'dart:html', 'RGBColor': 'dart:html', 'RTCIceCandidate': 'dart:html', 'SpeechRecognitionResult': 'dart:html', 'Body': 'dart:html', 'TextTrackList': 'dart:html', 'HTMLFrameElement': 'dart:html', 'ServiceWorker': 'dart:html', 'SharedWorker': 'dart:html', 'EventTarget': 'dart:html', 'HTMLFormControlsCollection': 'dart:html', 'KeyboardEvent': 'dart:html', 'Attr': 'dart:html', 'MIDIMessageEvent': 'dart:html', 'CacheStorage': 'dart:html', 'CanvasRenderingContext2D': 'dart:html', 'HTMLOListElement': 'dart:html', 'BatteryManager': 'dart:html', 'HTMLCanvasElement': 'dart:html', 'StyleSheetList': 'dart:html', 'Path2D': 'dart:html', 'PushRegistration': 'dart:html', 'ApplicationCache': 'dart:html', 'RTCPeerConnection': 'dart:html', 'HTMLVideoElement': 'dart:html', 'DeviceRotationRate': 'dart:html', 'HTMLOutputElement': 'dart:html', 'Screen': 'dart:html', 'Coordinates': 'dart:html', 'NetworkInformation': 'dart:html', 'StorageInfo': 'dart:html', 'HTMLTableColElement': 'dart:html', 'FocusEvent': 'dart:html', 'SpeechGrammarList': 'dart:html', 'Range': 'dart:html', 'SpeechGrammar': 'dart:html', 'WorkerGlobalScope': 'dart:html', 'CSSStyleDeclaration': 'dart:html', 'DOMStringList': 'dart:html', 'CSSPrimitiveValue': 'dart:html', 'ScreenOrientation': 'dart:html', 'XMLHttpRequestUpload': 'dart:html', 'HTMLTitleElement': 'dart:html', 'MediaKeySession': 'dart:html', 'AnimationPlayer': 'dart:html', 'Gamepad': 'dart:html', 'Worker': 'dart:html', 'MIDIConnectionEvent': 'dart:html', 'FileError': 'dart:html', 'HTMLDListElement': 'dart:html', 'CanvasPathMethods': 'dart:html', 'HTMLSelectElement': 'dart:html', 'HTMLHeadElement': 'dart:html', 'URLUtils': 'dart:html', 'ConsoleBase': 'dart:html', 'HTMLAudioElement': 'dart:html', 'DOMSettableTokenList': 'dart:html', 'SpeechRecognitionEvent': 'dart:html', 'WebSocket': 'dart:html', 'WorkerLocation': 'dart:html', 'Location': 'dart:html', 'TouchList': 'dart:html', 'XMLHttpRequestProgressEvent': 'dart:html', 'PerformanceEntry': 'dart:html', 'HTMLMetaElement': 'dart:html', 'Timing': 'dart:html', 'HTMLTrackElement': 'dart:html', 'WheelEvent': 'dart:html', 'WebKitCSSFilterValue': 'dart:html', 'Cache': 'dart:html', 'MimeType': 'dart:html', 'MIDIOutputMap': 'dart:html', 'DOMMatrixReadOnly': 'dart:html', 'ChildNode': 'dart:html', 'HTMLFormElement': 'dart:html', 'Geolocation': 'dart:html', 'MediaKeyEvent': 'dart:html', 'CSSRuleList': 'dart:html', 'SpeechRecognitionResultList': 'dart:html', 'HTMLProgressElement': 'dart:html', 'InputMethodContext': 'dart:html', 'FontFaceSet': 'dart:html', 'BeforeUnloadEvent': 'dart:html', 'DataTransferItem': 'dart:html', 'MediaKeyNeededEvent': 'dart:html', 'HTMLKeygenElement': 'dart:html', 'CryptoKey': 'dart:html', 'HTMLButtonElement': 'dart:html', 'HTMLAllCollection': 'dart:html', 'SubtleCrypto': 'dart:html', 'CSSKeyframesRule': 'dart:html', 'ProcessingInstruction': 'dart:html', 'HTMLMarqueeElement': 'dart:html', 'TextEvent': 'dart:html', 'EntrySync': 'dart:html', 'DeviceAcceleration': 'dart:html', 'HTMLMapElement': 'dart:html', 'MediaKeys': 'dart:html', 'DOMPointReadOnly': 'dart:html', 'WindowBase64': 'dart:html', 'SpeechRecognitionError': 'dart:html', 'MIDIOutput': 'dart:html', 'EventSource': 'dart:html', 'RTCDTMFToneChangeEvent': 'dart:html', 'DeviceOrientationEvent': 'dart:html', 'DirectoryEntry': 'dart:html', 'HTMLShadowElement': 'dart:html', 'Blob': 'dart:html', 'VTTCue': 'dart:html', 'PopStateEvent': 'dart:html', 'NodeFilter': 'dart:html', 'DOMRect': 'dart:html', 'URLUtilsReadOnly': 'dart:html', 'OverflowEvent': 'dart:html', 'MediaError': 'dart:html', 'SourceBufferList': 'dart:html', 'DeviceMotionEvent': 'dart:html', 'Comment': 'dart:html', 'PerformanceResourceTiming': 'dart:html', 'CanvasPattern': 'dart:html', 'GeofencingRegion': 'dart:html', 'CharacterData': 'dart:html', 'CSS': 'dart:html', 'MediaKeyError': 'dart:html', 'MIDIInput': 'dart:html', 'CSSRule': 'dart:html', 'SpeechRecognitionAlternative': 'dart:html', 'WebKitCSSFilterRule': 'dart:html', 'XPathExpression': 'dart:html', 'ServiceWorkerClient': 'dart:html', 'PerformanceNavigation': 'dart:html', 'ExtendableEvent': 'dart:html', 'MediaStreamEvent': 'dart:html', 'XPathNSResolver': 'dart:html', 'SecurityPolicyViolationEvent': 'dart:html', 'FileWriterSync': 'dart:html', 'HTMLTableElement': 'dart:html', 'IDBFactory': 'dart:indexed_db', 'IDBKeyRange': 'dart:indexed_db', 'IDBCursor': 'dart:indexed_db', 'IDBRequest': 'dart:indexed_db', 'IDBOpenDBRequest': 'dart:indexed_db', 'IDBDatabase': 'dart:indexed_db', 'IDBIndex': 'dart:indexed_db', 'IDBObjectStore': 'dart:indexed_db', 'IDBTransaction': 'dart:indexed_db', 'IDBCursorWithValue': 'dart:indexed_db', 'IDBVersionChangeEvent': 'dart:indexed_db', 'WebGLRenderingContextBase': 'dart:web_gl', 'WebGLBuffer': 'dart:web_gl', 'EXTShaderTextureLOD': 'dart:web_gl', 'WebGLUniformLocation': 'dart:web_gl', 'EXTBlendMinMax': 'dart:web_gl', 'WebGLFramebuffer': 'dart:web_gl', 'WebGLTexture': 'dart:web_gl', 'WebGLContextAttributes': 'dart:web_gl', 'OESStandardDerivatives': 'dart:web_gl', 'WebGLDepthTexture': 'dart:web_gl', 'WebGLDrawBuffers': 'dart:web_gl', 'OESTextureFloatLinear': 'dart:web_gl', 'OESTextureHalfFloatLinear': 'dart:web_gl', 'WebGLDebugShaders': 'dart:web_gl', 'OESVertexArrayObject': 'dart:web_gl', 'WebGLCompressedTextureS3TC': 'dart:web_gl', 'WebGLProgram': 'dart:web_gl', 'EXTFragDepth': 'dart:web_gl', 'WebGLContextEvent': 'dart:web_gl', 'ANGLEInstancedArrays': 'dart:web_gl', 'WebGLDebugRendererInfo': 'dart:web_gl', 'WebGLShader': 'dart:web_gl', 'WebGLCompressedTextureATC': 'dart:web_gl', 'WebGLRenderingContext': 'dart:web_gl', 'WebGLShaderPrecisionFormat': 'dart:web_gl', 'OESTextureHalfFloat': 'dart:web_gl', 'EXTTextureFilterAnisotropic': 'dart:web_gl', 'OESTextureFloat': 'dart:web_gl', 'OESElementIndexUint': 'dart:web_gl', 'WebGLCompressedTextureETC1': 'dart:web_gl', 'WebGLLoseContext': 'dart:web_gl', 'WebGLVertexArrayObjectOES': 'dart:web_gl', 'WebGLCompressedTexturePVRTC': 'dart:web_gl', 'WebGLRenderbuffer': 'dart:web_gl', 'WebGLActiveInfo': 'dart:web_gl', 'SQLError': 'dart:web_sql', 'SQLResultSet': 'dart:web_sql', 'SQLResultSetRowList': 'dart:web_sql', 'Database': 'dart:web_sql', 'SQLTransaction': 'dart:web_sql', 'SVGAnimatedString': 'dart:svg', 'SVGFilterElement': 'dart:svg', 'SVGFEFuncAElement': 'dart:svg', 'SVGPathSegLinetoRel': 'dart:svg', 'SVGPathSegLinetoVerticalRel': 'dart:svg', 'SVGURIReference': 'dart:svg', 'SVGAnimatedLengthList': 'dart:svg', 'SVGImageElement': 'dart:svg', 'SVGStyleElement': 'dart:svg', 'SVGAnimatedPreserveAspectRatio': 'dart:svg', 'SVGTextElement': 'dart:svg', 'SVGDefsElement': 'dart:svg', 'SVGFontFaceFormatElement': 'dart:svg', 'SVGFEDiffuseLightingElement': 'dart:svg', 'SVGFEMorphologyElement': 'dart:svg', 'SVGAltGlyphElement': 'dart:svg', 'SVGFETileElement': 'dart:svg', 'SVGPathSegLinetoHorizontalAbs': 'dart:svg', 'SVGPathSegMovetoRel': 'dart:svg', 'SVGPolygonElement': 'dart:svg', 'SVGUseElement': 'dart:svg', 'SVGPoint': 'dart:svg', 'SVGRect': 'dart:svg', 'SVGAnimatedBoolean': 'dart:svg', 'SVGPathSegArcRel': 'dart:svg', 'SVGTransform': 'dart:svg', 'SVGFEDropShadowElement': 'dart:svg', 'SVGFETurbulenceElement': 'dart:svg', 'SVGNumberList': 'dart:svg', 'SVGAnimateElement': 'dart:svg', 'SVGAnimationElement': 'dart:svg', 'SVGAnimatedRect': 'dart:svg', 'SVGGraphicsElement': 'dart:svg', 'SVGMarkerElement': 'dart:svg', 'SVGFECompositeElement': 'dart:svg', 'SVGPolylineElement': 'dart:svg', 'SVGTransformList': 'dart:svg', 'SVGPathSegList': 'dart:svg', 'SVGPathSegCurvetoQuadraticSmoothRel': 'dart:svg', 'SVGEllipseElement': 'dart:svg', 'SVGFEFuncGElement': 'dart:svg', 'SVGPointList': 'dart:svg', 'SVGFEMergeElement': 'dart:svg', 'SVGGlyphElement': 'dart:svg', 'SVGCircleElement': 'dart:svg', 'SVGFEFuncRElement': 'dart:svg', 'SVGMissingGlyphElement': 'dart:svg', 'SVGAnimatedNumberList': 'dart:svg', 'SVGFEFuncBElement': 'dart:svg', 'SVGSwitchElement': 'dart:svg', 'SVGFEBlendElement': 'dart:svg', 'SVGGlyphRefElement': 'dart:svg', 'SVGAnimatedAngle': 'dart:svg', 'SVGTSpanElement': 'dart:svg', 'SVGRadialGradientElement': 'dart:svg', 'SVGPathSegCurvetoCubicRel': 'dart:svg', 'SVGFEDistantLightElement': 'dart:svg', 'SVGLinearGradientElement': 'dart:svg', 'SVGFontFaceSrcElement': 'dart:svg', 'SVGTextPositioningElement': 'dart:svg', 'SVGAnimateMotionElement': 'dart:svg', 'SVGGeometryElement': 'dart:svg', 'SVGAltGlyphItemElement': 'dart:svg', 'SVGAnimateTransformElement': 'dart:svg', 'SVGFontFaceUriElement': 'dart:svg', 'SVGPathSegCurvetoQuadraticRel': 'dart:svg', 'SVGAltGlyphDefElement': 'dart:svg', 'SVGPreserveAspectRatio': 'dart:svg', 'SVGPathElement': 'dart:svg', 'SVGFEColorMatrixElement': 'dart:svg', 'SVGPathSegLinetoHorizontalRel': 'dart:svg', 'SVGLength': 'dart:svg', 'SVGPatternElement': 'dart:svg', 'SVGFEConvolveMatrixElement': 'dart:svg', 'SVGStringList': 'dart:svg', 'SVGTextContentElement': 'dart:svg', 'SVGPathSegLinetoAbs': 'dart:svg', 'SVGFESpecularLightingElement': 'dart:svg', 'SVGAnimatedTransformList': 'dart:svg', 'SVGFEGaussianBlurElement': 'dart:svg', 'SVGRenderingIntent': 'dart:svg', 'SVGNumber': 'dart:svg', 'SVGFontElement': 'dart:svg', 'SVGFESpotLightElement': 'dart:svg', 'SVGLineElement': 'dart:svg', 'SVGZoomEvent': 'dart:svg', 'SVGMatrix': 'dart:svg', 'SVGPathSegCurvetoCubicSmoothAbs': 'dart:svg', 'SVGSVGElement': 'dart:svg', 'SVGFitToViewBox': 'dart:svg', 'SVGAnimatedNumber': 'dart:svg', 'SVGMPathElement': 'dart:svg', 'SVGFontFaceNameElement': 'dart:svg', 'SVGFEDisplacementMapElement': 'dart:svg', 'SVGAngle': 'dart:svg', 'SVGMaskElement': 'dart:svg', 'SVGPathSegCurvetoQuadraticSmoothAbs': 'dart:svg', 'SVGPathSegClosePath': 'dart:svg', 'SVGAnimatedLength': 'dart:svg', 'SVGSymbolElement': 'dart:svg', 'SVGPathSegArcAbs': 'dart:svg', 'SVGVKernElement': 'dart:svg', 'SVGRectElement': 'dart:svg', 'SVGClipPathElement': 'dart:svg', 'SVGStopElement': 'dart:svg', 'SVGFEFloodElement': 'dart:svg', 'SVGPathSegCurvetoQuadraticAbs': 'dart:svg', 'SVGScriptElement': 'dart:svg', 'SVGViewSpec': 'dart:svg', 'SVGFontFaceElement': 'dart:svg', 'SVGLengthList': 'dart:svg', 'SVGAnimatedInteger': 'dart:svg', 'SVGTests': 'dart:svg', 'SVGCursorElement': 'dart:svg', 'SVGForeignObjectElement': 'dart:svg', 'SVGSetElement': 'dart:svg', 'SVGElement': 'dart:svg', 'SVGUnitTypes': 'dart:svg', 'SVGFEComponentTransferElement': 'dart:svg', 'SVGDescElement': 'dart:svg', 'SVGDiscardElement': 'dart:svg', 'SVGPathSegCurvetoCubicSmoothRel': 'dart:svg', 'SVGPathSegLinetoVerticalAbs': 'dart:svg', 'SVGFEMergeNodeElement': 'dart:svg', 'SVGHKernElement': 'dart:svg', 'SVGPathSeg': 'dart:svg', 'SVGGElement': 'dart:svg', 'SVGPathSegMovetoAbs': 'dart:svg', 'SVGTextPathElement': 'dart:svg', 'SVGFEOffsetElement': 'dart:svg', 'SVGPathSegCurvetoCubicAbs': 'dart:svg', 'SVGAnimatedEnumeration': 'dart:svg', 'SVGZoomAndPan': 'dart:svg', 'SVGTitleElement': 'dart:svg', 'SVGViewElement': 'dart:svg', 'SVGMetadataElement': 'dart:svg', 'SVGAElement': 'dart:svg', 'SVGGradientElement': 'dart:svg', 'SVGFEImageElement': 'dart:svg', 'SVGComponentTransferFunctionElement': 'dart:svg', 'SVGFEPointLightElement': 'dart:svg', 'SVGFilterPrimitiveStandardAttributes': 'dart:svg', 'AudioListener': 'dart:web_audio', 'AudioNode': 'dart:web_audio', 'AudioDestinationNode': 'dart:web_audio', 'WaveShaperNode': 'dart:web_audio', 'GainNode': 'dart:web_audio', 'MediaStreamAudioDestinationNode': 'dart:web_audio', 'AudioProcessingEvent': 'dart:web_audio', 'ScriptProcessorNode': 'dart:web_audio', 'MediaElementAudioSourceNode': 'dart:web_audio', 'AudioBufferSourceNode': 'dart:web_audio', 'AudioContext': 'dart:web_audio', 'ChannelSplitterNode': 'dart:web_audio', 'DynamicsCompressorNode': 'dart:web_audio', 'DelayNode': 'dart:web_audio', 'OfflineAudioCompletionEvent': 'dart:web_audio', 'OscillatorNode': 'dart:web_audio', 'PeriodicWave': 'dart:web_audio', 'BiquadFilterNode': 'dart:web_audio', 'MediaStreamAudioSourceNode': 'dart:web_audio', 'PannerNode': 'dart:web_audio', 'OfflineAudioContext': 'dart:web_audio', 'AudioBuffer': 'dart:web_audio', 'AudioParam': 'dart:web_audio', 'AnalyserNode': 'dart:web_audio', 'ConvolverNode': 'dart:web_audio', 'ChannelMergerNode': 'dart:web_audio', 'AudioSourceNode': 'dart:web_audio', // TODO(jacobr): add these classes to the autogenerated list. 'DataView': 'dart:typed_data', 'Float32Array': 'dart:typed_data', 'Float64Array': 'dart:typed_data', 'Int8Array': 'dart:typed_data', 'Int16Array': 'dart:typed_data', 'Int32Array': 'dart:typed_data', 'Uint8Array': 'dart:typed_data', 'Uint8ClampedArray': 'dart:typed_data', 'Uint16Array': 'dart:typed_data', 'Uint32Array': 'dart:typed_data', 'ArrayBuffer': 'dart:typed_data', 'ArrayBufferView': 'dart:typed_data', })); const STDLIB_TYPE_REPLACEMENTS = new Map(Object.entries({ 'HTMLDivElement': 'DivElement', 'HTMLImageElement': 'ImageElement', 'HTMLTableSectionElement': 'TableSectionElement', 'HTMLDetailsElement': 'DetailsElement', 'XMLHttpRequest': 'HttpRequest', 'CSSImportRule': 'CssImportRule', 'HTMLCollection': 'HtmlCollection', 'CSSFontFaceRule': 'CssFontFaceRule', 'HTMLMenuElement': 'MenuElement', 'WebKitAnimationEvent': 'AnimationEvent', 'HTMLLinkElement': 'LinkElement', 'HTMLIFrameElement': 'IFrameElement', 'HTMLAnchorElement': 'AnchorElement', 'RTCDTMFSender': 'RtcDtmfSender', 'HTMLParamElement': 'ParamElement', 'HTMLModElement': 'ModElement', 'XSLTProcessor': 'XsltProcessor', 'HTMLScriptElement': 'ScriptElement', 'HTMLParagraphElement': 'ParagraphElement', 'URL': 'Url', 'CSSCharsetRule': 'CssCharsetRule', 'HTMLEmbedElement': 'EmbedElement', 'HTMLBaseElement': 'BaseElement', 'HTMLBRElement': 'BRElement', 'XMLSerializer': 'XmlSerializer', 'HTMLPictureElement': 'PictureElement', 'HTMLObjectElement': 'ObjectElement', 'DOMMatrix': 'DomMatrix', 'HTMLMeterElement': 'MeterElement', 'HTMLUListElement': 'UListElement', 'HTMLHRElement': 'HRElement', 'HTMLOptGroupElement': 'OptGroupElement', 'HTMLBodyElement': 'BodyElement', 'RTCDataChannel': 'RtcDataChannel', 'HTMLFieldSetElement': 'FieldSetElement', 'HTMLSourceElement': 'SourceElement', 'HTMLHtmlElement': 'HtmlHtmlElement', 'RTCSessionDescription': 'RtcSessionDescription', 'HTMLOptionElement': 'OptionElement', 'VTTRegion': 'VttRegion', 'Stream': 'FileStream', 'HTMLHeadingElement': 'HeadingElement', 'HTMLTemplateElement': 'TemplateElement', 'RTCStatsReport': 'RtcStatsReport', 'Iterator': 'DomIterator', 'RTCStatsResponse': 'RtcStatsResponse', 'VTTRegionList': 'VttRegionList', 'HTMLDataListElement': 'DataListElement', 'HTMLElement': 'HtmlElement', 'HTMLDocument': 'HtmlDocument', 'MIDIPort': 'MidiPort', 'CSSMediaRule': 'CssMediaRule', 'CSSViewportRule': 'CssViewportRule', 'RTCIceCandidateEvent': 'RtcIceCandidateEvent', 'DOMImplementation': 'DomImplementation', 'HTMLDialogElement': 'DialogElement', 'HTMLTableRowElement': 'TableRowElement', 'HTMLOptionsCollection': 'HtmlOptionsCollection', 'MIDIAccess': 'MidiAccess', 'HTMLTableCaptionElement': 'TableCaptionElement', 'CSSStyleRule': 'CssStyleRule', 'DOMError': 'DomError', 'HTMLMenuItemElement': 'MenuItemElement', 'RTCDataChannelEvent': 'RtcDataChannelEvent', 'HTMLMediaElement': 'MediaElement', 'HTMLInputElement': 'InputElement', 'CDATASection': 'CDataSection', 'CSSStyleSheet': 'CssStyleSheet', 'DOMRectReadOnly': 'DomRectReadOnly', 'CSSSupportsRule': 'CssSupportsRule', 'DOMParser': 'DomParser', 'HTMLLIElement': 'LIElement', 'CSSPageRule': 'CssPageRule', 'HTMLPreElement': 'PreElement', 'HTMLStyleElement': 'StyleElement', 'HTMLContentElement': 'ContentElement', 'HTMLSpanElement': 'SpanElement', 'CSSKeyframeRule': 'CssKeyframeRule', 'MIDIInputMap': 'MidiInputMap', 'XMLDocument': 'XmlDocument', 'DOMTokenList': 'DomTokenList', 'DOMException': 'DomException', 'DOMPoint': 'DomPoint', 'HTMLLegendElement': 'LegendElement', 'DOMFileSystem': 'FileSystem', 'NavigatorCPU': 'NavigatorCpu', 'HTMLQuoteElement': 'QuoteElement', 'XMLHttpRequestEventTarget': 'HttpRequestEventTarget', 'HTMLLabelElement': 'LabelElement', 'HTMLTextAreaElement': 'TextAreaElement', 'HTMLUnknownElement': 'UnknownElement', 'HTMLAreaElement': 'AreaElement', 'HTMLTableCellElement': 'TableCellElement', 'DOMStringMap': 'DomStringMap', 'RTCIceCandidate': 'RtcIceCandidate', 'HTMLFormControlsCollection': 'HtmlFormControlsCollection', 'MIDIMessageEvent': 'MidiMessageEvent', 'HTMLOListElement': 'OListElement', 'HTMLCanvasElement': 'CanvasElement', 'RTCPeerConnection': 'RtcPeerConnection', 'HTMLVideoElement': 'VideoElement', 'HTMLOutputElement': 'OutputElement', 'HTMLTableColElement': 'TableColElement', 'CSSStyleDeclaration': 'CssStyleDeclaration', 'DOMStringList': 'DomStringList', 'XMLHttpRequestUpload': 'HttpRequestUpload', 'HTMLTitleElement': 'TitleElement', 'MIDIConnectionEvent': 'MidiConnectionEvent', 'HTMLDListElement': 'DListElement', 'HTMLSelectElement': 'SelectElement', 'HTMLHeadElement': 'HeadElement', 'URLUtils': 'UrlUtils', 'HTMLAudioElement': 'AudioElement', 'DOMSettableTokenList': 'DomSettableTokenList', 'HTMLMetaElement': 'MetaElement', 'HTMLTrackElement': 'TrackElement', 'MIDIOutputMap': 'MidiOutputMap', 'DOMMatrixReadOnly': 'DomMatrixReadOnly', 'HTMLFormElement': 'FormElement', 'HTMLProgressElement': 'ProgressElement', 'HTMLKeygenElement': 'KeygenElement', 'HTMLButtonElement': 'ButtonElement', 'CSSKeyframesRule': 'CssKeyframesRule', 'HTMLMapElement': 'MapElement', 'DOMPointReadOnly': 'DomPointReadOnly', 'MIDIOutput': 'MidiOutput', 'RTCDTMFToneChangeEvent': 'RtcDtmfToneChangeEvent', 'HTMLShadowElement': 'ShadowElement', 'VTTCue': 'VttCue', 'URLUtilsReadOnly': 'UrlUtilsReadOnly', 'CSS': 'Css', 'MIDIInput': 'MidiInput', 'CSSRule': 'CssRule', 'WebKitCSSFilterRule': 'CssFilterRule', 'HTMLTableElement': 'TableElement', 'IDBFactory': 'IdbFactory', 'IDBKeyRange': 'KeyRange', 'IDBCursor': 'Cursor', 'IDBRequest': 'Request', 'IDBOpenDBRequest': 'OpenDBRequest', 'IDBDatabase': 'Database', 'IDBIndex': 'Index', 'IDBObjectStore': 'ObjectStore', 'IDBTransaction': 'Transaction', 'IDBCursorWithValue': 'CursorWithValue', 'IDBVersionChangeEvent': 'VersionChangeEvent', 'WebGLBuffer': 'Buffer', 'EXTShaderTextureLOD': 'ExtShaderTextureLod', 'WebGLUniformLocation': 'UniformLocation', 'EXTBlendMinMax': 'ExtBlendMinMax', 'WebGLFramebuffer': 'Framebuffer', 'WebGLTexture': 'Texture', 'WebGLContextAttributes': 'ContextAttributes', 'OESStandardDerivatives': 'OesStandardDerivatives', 'WebGLDepthTexture': 'DepthTexture', 'WebGLDrawBuffers': 'DrawBuffers', 'OESTextureFloatLinear': 'OesTextureFloatLinear', 'OESTextureHalfFloatLinear': 'OesTextureHalfFloatLinear', 'WebGLDebugShaders': 'DebugShaders', 'OESVertexArrayObject': 'OesVertexArrayObject', 'WebGLCompressedTextureS3TC': 'CompressedTextureS3TC', 'WebGLProgram': 'Program', 'EXTFragDepth': 'ExtFragDepth', 'WebGLContextEvent': 'ContextEvent', 'ANGLEInstancedArrays': 'AngleInstancedArrays', 'WebGLDebugRendererInfo': 'DebugRendererInfo', 'WebGLShader': 'Shader', 'WebGLCompressedTextureATC': 'CompressedTextureAtc', 'WebGLRenderingContext': 'RenderingContext', 'WebGLShaderPrecisionFormat': 'ShaderPrecisionFormat', 'OESTextureHalfFloat': 'OesTextureHalfFloat', 'EXTTextureFilterAnisotropic': 'ExtTextureFilterAnisotropic', 'OESTextureFloat': 'OesTextureFloat', 'OESElementIndexUint': 'OesElementIndexUint', 'WebGLCompressedTextureETC1': 'CompressedTextureETC1', 'WebGLLoseContext': 'LoseContext', 'WebGLVertexArrayObjectOES': 'VertexArrayObject', 'WebGLCompressedTexturePVRTC': 'CompressedTexturePvrtc', 'WebGLRenderbuffer': 'Renderbuffer', 'WebGLActiveInfo': 'ActiveInfo', 'SQLError': 'SqlError', 'SQLResultSet': 'SqlResultSet', 'SQLResultSetRowList': 'SqlResultSetRowList', 'Database': 'SqlDatabase', 'SQLTransaction': 'SqlTransaction', 'SVGAnimatedString': 'AnimatedString', 'SVGFilterElement': 'FilterElement', 'SVGFEFuncAElement': 'FEFuncAElement', 'SVGPathSegLinetoRel': 'PathSegLinetoRel', 'SVGPathSegLinetoVerticalRel': 'PathSegLinetoVerticalRel', 'SVGURIReference': 'UriReference', 'SVGAnimatedLengthList': 'AnimatedLengthList', 'SVGImageElement': 'ImageElement', 'SVGStyleElement': 'StyleElement', 'SVGAnimatedPreserveAspectRatio': 'AnimatedPreserveAspectRatio', 'SVGTextElement': 'TextElement', 'SVGDefsElement': 'DefsElement', 'SVGFEDiffuseLightingElement': 'FEDiffuseLightingElement', 'SVGFEMorphologyElement': 'FEMorphologyElement', 'SVGAltGlyphElement': 'AltGlyphElement', 'SVGFETileElement': 'FETileElement', 'SVGPathSegLinetoHorizontalAbs': 'PathSegLinetoHorizontalAbs', 'SVGPathSegMovetoRel': 'PathSegMovetoRel', 'SVGPolygonElement': 'PolygonElement', 'SVGUseElement': 'UseElement', 'SVGPoint': 'Point', 'SVGRect': 'Rect', 'SVGAnimatedBoolean': 'AnimatedBoolean', 'SVGPathSegArcRel': 'PathSegArcRel', 'SVGTransform': 'Transform', 'SVGFETurbulenceElement': 'FETurbulenceElement', 'SVGNumberList': 'NumberList', 'SVGAnimateElement': 'AnimateElement', 'SVGAnimationElement': 'AnimationElement', 'SVGAnimatedRect': 'AnimatedRect', 'SVGGraphicsElement': 'GraphicsElement', 'SVGMarkerElement': 'MarkerElement', 'SVGFECompositeElement': 'FECompositeElement', 'SVGPolylineElement': 'PolylineElement', 'SVGTransformList': 'TransformList', 'SVGPathSegList': 'PathSegList', 'SVGPathSegCurvetoQuadraticSmoothRel': 'PathSegCurvetoQuadraticSmoothRel', 'SVGEllipseElement': 'EllipseElement', 'SVGFEFuncGElement': 'FEFuncGElement', 'SVGPointList': 'PointList', 'SVGFEMergeElement': 'FEMergeElement', 'SVGCircleElement': 'CircleElement', 'SVGFEFuncRElement': 'FEFuncRElement', 'SVGAnimatedNumberList': 'AnimatedNumberList', 'SVGFEFuncBElement': 'FEFuncBElement', 'SVGSwitchElement': 'SwitchElement', 'SVGFEBlendElement': 'FEBlendElement', 'SVGAnimatedAngle': 'AnimatedAngle', 'SVGTSpanElement': 'TSpanElement', 'SVGRadialGradientElement': 'RadialGradientElement', 'SVGPathSegCurvetoCubicRel': 'PathSegCurvetoCubicRel', 'SVGFEDistantLightElement': 'FEDistantLightElement', 'SVGLinearGradientElement': 'LinearGradientElement', 'SVGTextPositioningElement': 'TextPositioningElement', 'SVGAnimateMotionElement': 'AnimateMotionElement', 'SVGGeometryElement': 'GeometryElement', 'SVGAnimateTransformElement': 'AnimateTransformElement', 'SVGPathSegCurvetoQuadraticRel': 'PathSegCurvetoQuadraticRel', 'SVGPreserveAspectRatio': 'PreserveAspectRatio', 'SVGPathElement': 'PathElement', 'SVGFEColorMatrixElement': 'FEColorMatrixElement', 'SVGPathSegLinetoHorizontalRel': 'PathSegLinetoHorizontalRel', 'SVGLength': 'Length', 'SVGPatternElement': 'PatternElement', 'SVGFEConvolveMatrixElement': 'FEConvolveMatrixElement', 'SVGStringList': 'StringList', 'SVGTextContentElement': 'TextContentElement', 'SVGPathSegLinetoAbs': 'PathSegLinetoAbs', 'SVGFESpecularLightingElement': 'FESpecularLightingElement', 'SVGAnimatedTransformList': 'AnimatedTransformList', 'SVGFEGaussianBlurElement': 'FEGaussianBlurElement', 'SVGRenderingIntent': 'RenderingIntent', 'SVGNumber': 'Number', 'SVGFESpotLightElement': 'FESpotLightElement', 'SVGLineElement': 'LineElement', 'SVGZoomEvent': 'ZoomEvent', 'SVGMatrix': 'Matrix', 'SVGPathSegCurvetoCubicSmoothAbs': 'PathSegCurvetoCubicSmoothAbs', 'SVGSVGElement': 'SvgSvgElement', 'SVGFitToViewBox': 'FitToViewBox', 'SVGAnimatedNumber': 'AnimatedNumber', 'SVGFEDisplacementMapElement': 'FEDisplacementMapElement', 'SVGAngle': 'Angle', 'SVGMaskElement': 'MaskElement', 'SVGPathSegCurvetoQuadraticSmoothAbs': 'PathSegCurvetoQuadraticSmoothAbs', 'SVGPathSegClosePath': 'PathSegClosePath', 'SVGAnimatedLength': 'AnimatedLength', 'SVGSymbolElement': 'SymbolElement', 'SVGPathSegArcAbs': 'PathSegArcAbs', 'SVGRectElement': 'RectElement', 'SVGClipPathElement': 'ClipPathElement', 'SVGStopElement': 'StopElement', 'SVGFEFloodElement': 'FEFloodElement', 'SVGPathSegCurvetoQuadraticAbs': 'PathSegCurvetoQuadraticAbs', 'SVGScriptElement': 'ScriptElement', 'SVGViewSpec': 'ViewSpec', 'SVGLengthList': 'LengthList', 'SVGAnimatedInteger': 'AnimatedInteger', 'SVGTests': 'Tests', 'SVGForeignObjectElement': 'ForeignObjectElement', 'SVGSetElement': 'SetElement', 'SVGElement': 'SvgElement', 'SVGUnitTypes': 'UnitTypes', 'SVGFEComponentTransferElement': 'FEComponentTransferElement', 'SVGDescElement': 'DescElement', 'SVGDiscardElement': 'DiscardElement', 'SVGPathSegCurvetoCubicSmoothRel': 'PathSegCurvetoCubicSmoothRel', 'SVGPathSegLinetoVerticalAbs': 'PathSegLinetoVerticalAbs', 'SVGFEMergeNodeElement': 'FEMergeNodeElement', 'SVGPathSeg': 'PathSeg', 'SVGGElement': 'GElement', 'SVGPathSegMovetoAbs': 'PathSegMovetoAbs', 'SVGTextPathElement': 'TextPathElement', 'SVGFEOffsetElement': 'FEOffsetElement', 'SVGPathSegCurvetoCubicAbs': 'PathSegCurvetoCubicAbs', 'SVGAnimatedEnumeration': 'AnimatedEnumeration', 'SVGZoomAndPan': 'ZoomAndPan', 'SVGTitleElement': 'TitleElement', 'SVGViewElement': 'ViewElement', 'SVGMetadataElement': 'MetadataElement', 'SVGAElement': 'AElement', 'SVGFEImageElement': 'FEImageElement', 'SVGFEPointLightElement': 'FEPointLightElement', 'SVGFilterPrimitiveStandardAttributes': 'FilterPrimitiveStandardAttributes', // Warning this rename is dangerous. It is correct for client rectangles // passed to Dart through dart:html but dangerous for ones passed from Dart to // JS. We should probably have dart:html just expose an explicit ClientRect // interface to avoid conflating the cases. 'ClientRect': 'Rectangle', 'Date': 'DateTime', 'Array': 'List', 'ReadonlyArray': 'List', 'ArrayBuffer': 'ByteBuffer', // 'Promise': 'Future', // TODO(jacobr): add back once we unify Promise and // Future. 'ArrayBufferView': 'TypedData', 'DataView': 'ByteData', 'Float32Array': 'Float32List', 'Float64Array': 'Float64List', 'Int8Array': 'Int8List', 'Int16Array': 'Int16List', 'Int32Array': 'Int32List', 'Uint8Array': 'Uint8List', 'Uint8ClampedArray': 'Uint8ClampedList', 'Uint16Array': 'Uint16List', 'Uint32Array': 'Uint32List', 'Boolean': 'bool', 'Number': 'num', })); export const TS_TO_DART_TYPENAMES = new Map(Object.entries({ 'lib.es5': STDLIB_TYPE_REPLACEMENTS, 'lib.es6': STDLIB_TYPE_REPLACEMENTS, 'lib.dom': STDLIB_TYPE_REPLACEMENTS }));
the_stack
import AceEditor from "react-ace"; import PropTypes from "prop-types"; import * as React from "react"; import isEqual from "lodash.isequal"; import "brace/ext/searchbox"; import "brace/mode/json"; import "brace/theme/monokai"; import "brace/ext/language_tools"; import { omit } from "../utils/Util"; import JSONUtil from "../utils/JSONUtil"; import JSONEditorUtil from "../utils/JSONEditorUtil"; /** * How long to wait before clearing the `isTyping` flag, used internally to * prohibit external updates to the editor while the user is typing. * * @const {number} */ const IS_TYPING_TIMEOUT = 2000; /** * This is a high-order component on top of `AceEditor` that abstracts the JSON * string manipulation and allows object-level access to the underlying data. * * It's features are: * * - Solve some bugs and peculiarities of AceEditor component * - Maintain visual coherence between object updates * - Callback on per-property updates as the user types * - Receive errors through properties and show them in the gutter * * @example <caption>How to use the JSONEditor</caption> * * handleChange(newObject) { * console.log('New object:', newObject); * } * * handlePropertyChange(path, value) { * console.log('Property /'+path.join('/'), 'changed to', value); * } * * render() { * let value = { * some: {value: 'object'} * }; * let errors = [ * {path: ['some'], message: 'An error on object `some`'} * ]; * * return ( * <JSONEditor * value={value} * errors={errors} * onChange={this.handleChange} * onPropertyChange={this.handlePropertyChange} * /> * ); * }; * */ class JSONEditor extends React.Component { static defaultProps = { errors: [], editorProps: { $blockScrolling: Infinity }, height: "100%", onBlur() {}, onChange() {}, onErrorStateChange() {}, onFocus() {}, onPropertyChange() {}, value: {}, width: "100%", }; static propTypes = { errors: PropTypes.array, editorProps: PropTypes.object, height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), onBlur: PropTypes.func, onChange: PropTypes.func, onErrorStateChange: PropTypes.func, onFocus: PropTypes.func, onPropertyChange: PropTypes.func, value: PropTypes.object, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), }; constructor(...args) { super(...args); // Clone the given initial value const jsonText = JSON.stringify(this.props.value || {}, null, 2); // We are using the react-way of updating the component **only** when we // need to define a new text to work upon (ex. when the owner component has // updated the value). // // Updating the AceEditor on every render cycle seems to cause some trouble // to it's internals, that I couldn't pinpoint yet. this.state = { aceEditorState: { jsonText, }, }; // // The following properties are part of the `internal`, non-react state // and is synchronized with the react through `UNSAFE_componentWillReceiveProps` // this.externalErrors = (this.props.errors || []).slice(); this.jsonError = null; this.jsonMeta = []; this.jsonText = null; this.jsonValue = {}; // // The following properties are flags and references used for other purposes // this.aceEditor = null; this.isFocused = false; this.isTyping = false; this.timerIsTyping = null; // Initial state synchronization this.updateLocalJsonState(this.getNewJsonState(jsonText)); } /** * @override */ UNSAFE_componentWillReceiveProps(nextProps) { // Synchronize error updates if (!isEqual(this.externalErrors, nextProps.errors)) { this.externalErrors = (nextProps.errors || []).slice(); this.updateEditorState(); } // Ignore invalid values if (typeof nextProps.value !== "object") { return; } // Ignore property changes if the user is currently using the editor field if (this.isTyping && this.isFocused) { return; } // If this update originates from an onChange -> prop={value} loop, the // object defined in the `internalValue` property should be equal to the // `value` property we just received. In this case, don't update anything. if (isEqual(this.jsonValue, nextProps.value)) { return; } // If we reached this point, the owning component has actually sent us a new // json object that we must display. For visual coherence we must try our // best to properly display the new values without breaking the JSON text // arrangement. // Align the order the properties appear & calculate new JSON text const value = JSONEditorUtil.sortObjectKeys( this.jsonValue, nextProps.value ); const jsonText = JSON.stringify(value, null, 2); // Update local state with the new, computed text this.updateLocalJsonState(this.getNewJsonState(jsonText)); this.setState({ aceEditorState: { jsonText } }); } /** * Since ACEEditor component does not behave nicely when we update the text * as a response to an `onChange` event, we must be very careful never to * render the ACEEditor when the user types. * * This way, the component is updated *only* when: * * - Editor-related properties change (ex. editorProps, width, height) * - The text in the editor has to be replaced due to an external value change * * @override */ shouldComponentUpdate(nextProps, nextState) { // Update if ACE editor properties are changed if ( !isEqual(nextProps.editorProps, this.props.editorProps) || nextProps.height !== this.props.height || nextProps.width !== this.props.width ) { return true; } // Otherwise update ONLY when initial value changes in state return nextState.aceEditorState !== this.state.aceEditorState; } /** * @override */ componentDidUpdate() { this.updateEditorState(); } handleEditorLoad = (editor) => { this.aceEditor = editor; // Disable tab index for JSON editor this.aceEditor.renderer.textarea.setAttribute("tabIndex", -1); // Disable syntax highlighting worker, since we are responsible for feeding // the correct syntax error + provided error markers const editorSession = editor.getSession(); editorSession.setUseWorker(false); // Enable soft tabs and set tab space to 2 editorSession.setTabSize(2); // Synchronize editor state this.updateEditorState(); }; /** * `onBlur` handler for the AceEditor * * @param {DOMEvent} event - The event object */ handleBlur = (event) => { this.props.onBlur(event, this.jsonValue); this.isFocused = false; }; /** * `onChange` handler for the AceEditor * * @param {string} jsonText - The new JSON string */ handleChange = (jsonText) => { const lastValue = this.jsonValue; const lastError = this.jsonError; // Calculate what the next state is going to be const getNewJsonState = this.getNewJsonState(jsonText); if (getNewJsonState === null) { return; // No change. } const { jsonValue, jsonMeta, jsonError } = getNewJsonState; // Update the `isTyping` flag this.isTyping = true; this.scheduleIsTypingReset(IS_TYPING_TIMEOUT); // Handle errors if (lastError !== jsonError) { this.props.onErrorStateChange(jsonError); } // If we have errors don't continue with updating the local structures if (!jsonError) { // Calculate differences in the JSON and trigger `onPropertyChange` // event for every property that changed in the JSON const diff = JSONEditorUtil.deepObjectDiff(lastValue, jsonValue); diff.forEach(({ path, value }) => { this.props.onPropertyChange(path, value, jsonValue); }); // Trigger change with the latest json object this.props.onChange(jsonValue); } // Update local json state this.updateLocalJsonState({ jsonValue, jsonMeta, jsonError, jsonText }); }; /** * `onFocus` handler for the AceEditor * * @param {DOMEvent} event - The event object */ handleFocus = (event) => { this.props.onFocus(event, this.jsonValue); this.isFocused = true; }; /** * Apply pending state updates to the ACE editor instance. * * This function operates purely on the `aceEditor` instance, created by the * `AceEditor` composed and exposed through the `onLoad` event. Since the * `AceEditor` component does a pretty bad job updating only what's needed, * we had to use this approach and avoid re-rendering the component as much * as possible. */ updateEditorState() { if (!this.aceEditor) { return; } // Defer the annotation update, since for some reason ACE editor // does not get updated if the update comes from the same stack call // that set it's state. setTimeout(() => { this.aceEditor.getSession().setAnnotations(this.getErrorMarkers()); }, 1); } /** * Get new JSON state (parsed value and meta data) from json text. * * @param {String} jsonText - The JSON buffer to extract metadata from * @return {null | { * jsonValue:object, * jsonText:string, * jsonMeta:object, * jsonError:string * }} jsonState - JSON state including parsed value and meta data */ getNewJsonState(jsonText) { // Do not perform heavyweight calculations, such as `getObjectInformation` // if the json text hasn't really changed. if (this.jsonText === jsonText) { return null; } // Reset some properties let { jsonValue, jsonMeta, jsonError } = this; // Try to parse and extract metadata try { jsonError = null; jsonValue = JSON.parse(jsonText); jsonMeta = JSONUtil.getObjectInformation(jsonText); } catch (e) { // Prettify the error message by resolving the line/column instead of // just keeping the offset in the string const errorStr = e.toString(); jsonError = errorStr.replace(/at position (\d+)/g, (match, offset) => { const cursor = JSONEditorUtil.cursorFromOffset( parseInt(offset, 10), jsonText ); return `at line ${cursor.row}:${cursor.column}`; }); } return { jsonValue, jsonText, jsonMeta, jsonError }; } /** * This function assigns the local JSON state (parsed value and meta data), * outside the React state, since this does not necessarily trigger an update. * * This is useful in order to have the latest available metainformation when * the user changes the text (on the `handleChange` handler), but we don't * want to re-do the processing when this will eventually trigger an update * to the `value` property with the same data. * * @param {object|null} jsonState * @param {object} jsonState.jsonValue * @param {string} jsonState.jsonText * @param {object} jsonState.jsonMeta * @param {string} jsonState.jsonError */ updateLocalJsonState(jsonState) { if (jsonState == null) { return; } this.jsonText = jsonState.jsonText; this.jsonError = jsonState.jsonError; this.jsonValue = jsonState.jsonValue; this.jsonMeta = jsonState.jsonMeta; // Sync editor without a render cycle this.updateEditorState(); } /** * Schedule the `isTyping` state property to set back to `false` if this * function is not called within the given timeout. * * @param {number} timeout - The timeout (in millisecond) on which to clear * the flag */ scheduleIsTypingReset(timeout) { if (this.timerIsTyping) { clearTimeout(this.timerIsTyping); } this.timerIsTyping = setTimeout(() => { this.isTyping = false; }, timeout); } /** * Collects error markers to set on the Ace Editor * @return {Array<({ * row:Number, * text:String, * type:String * })>} An array of errors to show in the Ace Editor */ getErrorMarkers() { // Extract syntax errors, or other errors that refer to line if (this.jsonError) { // Strip out the 'at line xxx' message, and keep track of that line let errorLine = 0; const errorMsg = this.jsonError.replace( /at line ([\d:]+)/g, (m, line) => { errorLine = parseInt(line.split(":")[0], 10); return ""; } ); // Return error marker return [ { row: errorLine, text: errorMsg, type: "error", }, ]; } const errors = [].concat(...this.externalErrors); return errors.map((error) => { const { path, message } = error; // All errors with empty paths go to line 0 if (path.length === 0) { return { row: 0, text: message, type: "error", }; } // Check if there is a token that matches the path completely const errorPath = error.path.join("."); const token = this.jsonMeta.find( (token) => token.path.join(".") === errorPath ); if (token) { return { row: token.line - 1, text: message, type: "error", }; } // When we are not able to find an exact match we are going to gradually // increase the error scope until we find a token that exists. // // If nothing is found, default to root ([]) // const candidates = this.jsonMeta.reduce( (memo, token) => { const isMatch = token.path.every( (component, i) => path[i] === component ); if (isMatch) { memo.push({ path: token.path, row: token.line - 1, }); } return memo; }, [{ path: [], row: 0 }] ); // Find the most specific token line const candidate = candidates.sort( (a, b) => b.path.length - a.path.length )[0]; // Keep the difference between the original and the new path and display // it as prefix in the error message: const prefixPath = path.slice(candidate.path.length).join("."); return { row: candidate.row, text: `${prefixPath}: ${message}`, type: "error", }; }); } /** * @override */ render() { const { width, height, editorProps } = this.props; const { aceEditorState } = this.state; const omitKeys = [].concat(Object.keys(JSONEditor.propTypes), "mode"); return ( <AceEditor {...omit(this.props, omitKeys)} width={width} height={height} editorProps={editorProps} mode="json" onBlur={this.handleBlur} onChange={this.handleChange} onFocus={this.handleFocus} onLoad={this.handleEditorLoad} value={aceEditorState.jsonText} /> ); } } export default JSONEditor;
the_stack
import { FretLabelPosition, Shape, SVGuitarChord } from '../src/svguitar' import { saveSvg, setUpSvgDom } from './testutils' const document = setUpSvgDom() describe('SVGuitarChord', () => { let container: HTMLElement let svguitar: SVGuitarChord beforeEach(() => { container = document.documentElement svguitar = new SVGuitarChord(container) }) it('Should create an instance of the SVGuitarChord class', () => { expect(svguitar).toBeTruthy() }) it('Should completely remove the diagram from the DOM when removing', () => { // given svguitar.draw() // when svguitar.remove() // then expect(container.querySelector('svg')).toBeNull() }) it('Should render an svg of an arbitrary chord', () => { svguitar .chord({ fingers: [ [1, 2], [2, 1], [3, 2], [4, 0], // fret 0 = open string [5, 'x'], // fret x = muted string ], barres: [], }) .configure({ strings: 5, frets: 6, title: 'Amaj7', }) .draw() saveSvg('arbitrary chord', container.outerHTML) }) it('Should render fingers over barre chords', () => { svguitar .chord({ fingers: [[2, 1, { color: 'green', text: '1' }]], barres: [ { fromString: 3, toString: 1, fret: 1, color: 'blue', }, ], }) .configure({ strings: 5, frets: 6, title: 'Finger over Barre Chord', }) .draw() saveSvg('finger over barre', container.outerHTML) }) it('Should render text on the nuts', () => { svguitar .chord({ fingers: [ [1, 2, 'A'], [2, 1, 'B'], [3, 2, 'C'], [4, 0], // fret 0 = open string [5, 'x'], // fret x = muted string ], barres: [], }) .configure({ strings: 5, frets: 6, title: 'Text on Nuts', nutTextColor: 'tomato', }) .draw() saveSvg('text on nuts', container.outerHTML) }) it('Should set the stroke width on silent and open string indicators', () => { svguitar .chord({ fingers: [ [2, 0], [3, 'x'], [4, 0, { strokeWidth: 5 }], [5, 'x', { strokeWidth: 5 }], ], barres: [], }) .configure({ title: 'Open & Silent String Indicator Strokes', }) .draw() saveSvg('silent and open strokes', container.outerHTML) }) it('Should set the stroke colors on silent and open string indicators', () => { svguitar .chord({ fingers: [ [4, 0, { strokeColor: 'blue' }], [5, 'x', { strokeColor: 'green' }], ], barres: [], }) .configure({ title: 'Open & Silent String Indicator Colors', }) .draw() saveSvg('silent and open colored', container.outerHTML) }) it('Should render text on silent and open string indicators', () => { svguitar .chord({ fingers: [ [2, 0, 'A'], [3, 'x', 'B'], [4, 0, { text: 'C', textColor: 'green' }], [5, 'x', { text: 'D', textColor: 'blue' }], ], barres: [], }) .configure({ title: 'Text on Open & Silent Strings', }) .draw() saveSvg('silent and open colored', container.outerHTML) }) it('Should render nuts with a different color', () => { svguitar .chord({ fingers: [ [1, 2, { color: 'green' }], [2, 1, { text: 'B', color: 'blue' }], ], barres: [], }) .configure({ strings: 5, frets: 6, title: 'Colored Nuts', }) .draw() saveSvg('colored nuts', container.outerHTML) }) it('Should render square nuts', () => { svguitar .chord({ fingers: [ [1, 2, { shape: Shape.SQUARE }], [2, 3, { shape: Shape.SQUARE, color: 'blue', text: 'X' }], ], barres: [], }) .configure({ strings: 5, frets: 6, title: 'Square Nuts', }) .draw() saveSvg('square nuts', container.outerHTML) }) it('Should render triangle nuts', () => { svguitar .chord({ fingers: [ [1, 2, { shape: Shape.TRIANGLE }], [2, 3, { shape: Shape.TRIANGLE, color: 'blue', text: 'X' }], ], barres: [], }) .configure({ strings: 5, frets: 6, title: 'Triangle Nuts', }) .draw() saveSvg('triangle nuts', container.outerHTML) }) it('Should render pentagon shaped nuts', () => { svguitar .chord({ fingers: [ [1, 2, { shape: Shape.PENTAGON }], [2, 3, { shape: Shape.PENTAGON, color: 'blue', text: 'X' }], ], barres: [], }) .configure({ strings: 5, frets: 6, title: 'Pentagon Nuts', }) .draw() saveSvg('pentagon nuts', container.outerHTML) }) it('Should render outline square nuts ', () => { svguitar .chord({ fingers: [ [ 2, 3, { shape: Shape.SQUARE, color: 'blue', text: 'X', strokeColor: 'red', strokeWidth: 3, }, ], ], barres: [], }) .configure({ title: 'Outline Square Nuts', }) .draw() saveSvg('outline square nuts', container.outerHTML) }) it('Should render outline triangle nuts', () => { svguitar .chord({ fingers: [ [ 2, 3, { shape: Shape.TRIANGLE, color: 'blue', text: 'X', strokeColor: 'red', strokeWidth: 3, }, ], ], barres: [], }) .configure({ title: 'Outline Triangle Nuts', }) .draw() saveSvg('outline triangle nuts', container.outerHTML) }) it('Should render pentagon shaped nuts', () => { svguitar .chord({ fingers: [ [ 2, 3, { shape: Shape.PENTAGON, color: 'blue', text: 'X', strokeColor: 'red', strokeWidth: 3, }, ], ], barres: [], }) .configure({ title: 'Outline Pentagon Nuts', }) .draw() saveSvg('outline pentagon nuts', container.outerHTML) }) it('Should render an outlined barre chord', () => { svguitar .chord({ fingers: [], barres: [ { fromString: 4, toString: 2, fret: 1, strokeWidth: 3, strokeColor: 'green', }, ], }) .configure({ title: 'Outlined Barre Chord', }) .draw() saveSvg('outline barre', container.outerHTML) }) it('Should render all fingers and barre chords with an outline', () => { svguitar .chord({ fingers: [ [2, 3, { shape: Shape.SQUARE }], [3, 4], ], barres: [ { fromString: 3, toString: 1, fret: 1, }, ], }) .configure({ nutStrokeWidth: 3, barreChordStrokeWidth: 3, barreChordStrokeColor: 'green', nutStrokeColor: 'red', title: 'Outlined', }) .draw() saveSvg('outline nuts', container.outerHTML) }) it('Should throw an error if an invliad shape is provided', () => { expect(() => { svguitar .chord({ fingers: [[1, 2, { shape: 'XXX' as Shape }]], barres: [], }) .draw() }).toThrowError(/XXX/) }) it('Should render text on nuts with a different color', () => { svguitar .chord({ fingers: [ [1, 2, { text: 'G', textColor: 'green' }], [2, 1, { text: 'B', textColor: 'blue' }], [3, 1, { textColor: 'green' }], // no effect ], barres: [], }) .configure({ strings: 5, frets: 6, title: 'Colored Text on Nuts', }) .draw() saveSvg('colored text on nuts', container.outerHTML) }) it('Should render barre chords with a different color', () => { svguitar .chord({ fingers: [], barres: [ { fret: 1, fromString: 4, toString: 1, color: 'blue', }, { fret: 3, fromString: 5, toString: 2, color: 'red', }, ], }) .configure({ strings: 5, frets: 6, title: 'Colored Barre Chords', }) .draw() saveSvg('colored barre chords', container.outerHTML) }) it('Should render text on barre chords with a different color', () => { svguitar .chord({ fingers: [], barres: [ { fret: 1, fromString: 4, toString: 1, text: 'Blue Text', textColor: 'blue', }, { fret: 3, fromString: 5, toString: 2, text: 'Red Text', textColor: 'red', }, { fret: 2, fromString: 3, toString: 2, textColor: 'red', }, ], }) .configure({ strings: 5, frets: 6, title: 'Colored Text on Barre Chords', }) .draw() saveSvg('colored text on barre chords', container.outerHTML) }) it('Should render text on the barre chords', () => { svguitar .chord({ fingers: [], barres: [ { fret: 1, fromString: 4, toString: 1, text: 'B', }, { fret: 3, fromString: 5, toString: 2, text: 'A', }, ], }) .configure({ strings: 5, frets: 5, title: 'Text on Barres', nutTextColor: 'lightgreen', }) .draw() saveSvg('text on barre chords', container.outerHTML) }) it('Should render a title nicely', () => { svguitar .configure({ title: 'Test Title', }) .draw() saveSvg('with title', container.outerHTML) }) it('Should render a title provided as part of the chord', () => { svguitar .configure({ title: 'DO NOT RENDER THIS', }) .chord({ fingers: [], barres: [], title: 'title from chord', }) .draw() saveSvg('title from chord', container.outerHTML) }) it('Should render the position provided as part of the chord', () => { svguitar .configure({ position: 999, }) .chord({ fingers: [], barres: [], position: 3, }) .draw() saveSvg('position from chord', container.outerHTML) }) it('Should render a very long title nicely', () => { svguitar .configure({ title: 'This is a very long title that does not fit easily', }) .draw() saveSvg('with long title', container.outerHTML) }) it('Should render 8 strings', () => { svguitar .configure({ title: '8 Strings', }) .configure({ strings: 8, }) .draw() saveSvg('8 strings', container.outerHTML) }) it('Should render 8 frets', () => { svguitar .configure({ title: '8 Frets', }) .configure({ frets: 8, }) .draw() saveSvg('8 frets', container.outerHTML) }) it('Should render from fret 2 with the fret label left', () => { svguitar .configure({ position: 2, fretLabelPosition: FretLabelPosition.LEFT, }) .draw() saveSvg('starting fret 2 left', container.outerHTML) }) it('Should render from fret 2 with the fret label right', () => { svguitar .configure({ position: 2, fretLabelPosition: FretLabelPosition.RIGHT, }) .draw() saveSvg('starting fret 2 right', container.outerHTML) }) it('Should render all tunings', () => { svguitar .configure({ strings: 5, tuning: ['1', '2', '3', '4', '5'], }) .draw() saveSvg('tunings', container.outerHTML) }) it('Should render not render all tunings if there are extranous tunings', () => { svguitar .configure({ strings: 5, tuning: ['1', '2', '3', '4', '5', '6'], }) .draw() saveSvg('too many tunings', container.outerHTML) }) it('Should render barre chords', () => { svguitar .configure({ strings: 5, frets: 5, }) .chord({ fingers: [], barres: [ { fret: 1, fromString: 4, toString: 1, }, { fret: 3, fromString: 5, toString: 2, }, ], }) .draw() saveSvg('barre chords', container.outerHTML) }) it('Should render everything in red', () => { svguitar .configure({ color: '#f00', tuning: ['1', '2', '3', '4', '5', '6'], title: 'Test', position: 3, }) .chord({ fingers: [ [1, 2], [2, 1], [3, 2], [4, 0], // fret 0 = open string [5, 'x'], // fret x = muted string ], barres: [], }) .draw() saveSvg('red', container.outerHTML) }) it('Should render correctly with all default settings overridden', () => { svguitar .configure({ strings: 6, frets: 5, position: 1, tuning: [], tuningsFontSize: 28, fretLabelFontSize: 38, fretLabelPosition: FretLabelPosition.RIGHT, nutSize: 0.65, sidePadding: 0.2, titleFontSize: 48, titleBottomMargin: 0, color: '#000', emptyStringIndicatorSize: 0.6, strokeWidth: 2, topFretWidth: 10, fretSize: 1.5, barreChordRadius: 0.25, fontFamily: 'Arial, "Helvetica Neue", Helvetica, sans-serif', }) .chord({ fingers: [ [1, 2], [2, 1], [3, 2], [4, 0], // fret 0 = open string [5, 'x'], // fret x = muted string ], barres: [], }) .draw() saveSvg('settings overridden', container.outerHTML) }) it('Should render correctly without any configuration', () => { svguitar .chord({ fingers: [ [1, 2], [2, 1], [3, 2], [4, 0], // fret 0 = open string [5, 'x'], // fret x = muted string ], barres: [], }) .draw() saveSvg('settings overridden', container.outerHTML) }) it('Should render very fat strokes', () => { svguitar .configure({ title: 'Fat Strokes', strokeWidth: 10, topFretWidth: 30, }) .chord({ fingers: [ [1, 2], [2, 1], [3, 2], [4, 0], // fret 0 = open string [5, 'x'], // fret x = muted string ], barres: [], }) .draw() saveSvg('fat strokes', container.outerHTML) }) it('Should render a green background', () => { svguitar .configure({ title: 'With Background', backgroundColor: '#00FF00', }) .draw() saveSvg('with background', container.outerHTML) }) it('Should vertically center the barre correctly', () => { svguitar .chord({ fingers: [], barres: [ { fret: 1, fromString: 4, toString: 1, }, ], }) .configure({ title: 'Centered Barre', fretSize: 1, nutSize: 1, strokeWidth: 5, nutColor: 'tomato', barreChordRadius: 0, }) .draw() saveSvg('centered barre', container.outerHTML) }) it('Should render two diagrams in the same position, with and without title', () => { svguitar .configure({ title: 'With Title', fixedDiagramPosition: true, }) .draw() saveSvg('fixed diagram position 1', container.outerHTML) svguitar .configure({ title: undefined, fixedDiagramPosition: true, }) .draw() saveSvg('fixed diagram position 2', container.outerHTML) svguitar .configure({ fixedDiagramPosition: true, }) .chord({ fingers: [[5, 'x']], barres: [], }) .draw() saveSvg('fixed diagram position 3', container.outerHTML) }) it('Should add custom classes to the barrre chord', () => { svguitar .chord({ fingers: [], barres: [ { fret: 1, fromString: 4, toString: 1, className: 'custom-class-123', }, ], }) .configure({ title: 'Barre with Custom Class', }) .draw() saveSvg('barre with class', container.outerHTML) }) it('Should add custom classes to fingers', () => { svguitar .chord({ fingers: [ [1, 2, { text: 'a', className: 'custom-class-a' }], [2, 1, { text: 'b', className: 'custom-class-b' }], [3, 1, { text: 'c', className: 'custom-class-c' }], ], barres: [], }) .configure({ title: 'Fingers with Custom Class', }) .draw() saveSvg('fingers with class', container.outerHTML) }) test.each` setting | value | valid ${'strings'} | ${1} | ${false} ${'strings'} | ${2} | ${true} ${'frets'} | ${0} | ${true} ${'frets'} | ${-1} | ${false} ${'position'} | ${1} | ${true} ${'position'} | ${0} | ${false} ${'fretSize'} | ${-1} | ${false} ${'nutSize'} | ${-1} | ${false} ${'strokeWidth'} | ${-1} | ${false} `('Should correctly sanity check the settings', ({ setting, value, valid }) => { // console.log(`Should ${valid ? 'not' : ''} thrown if ${setting} is ${value}`) if (valid) { expect(() => svguitar.configure({ [setting]: value })).not.toThrow() } else { expect(() => svguitar.configure({ [setting]: value })).toThrow() } }) })
the_stack
import React from "react"; import { render, fireEvent } from "@testing-library/react"; import { renderHook } from "@testing-library/react-hooks"; import useLottieInteractivity, { getContainerVisibility, getContainerCursorPosition, useInitInteractivity, InitInteractivity, } from "../hooks/useLottieInteractivity"; import { InteractivityProps } from "../types"; import { act } from "react-dom/test-utils"; function renderUseLottieInteractivity(props: InteractivityProps) { return renderHook(() => useLottieInteractivity(props)); } function renderUseInitInteractivity(props: InitInteractivity) { return renderHook(() => useInitInteractivity(props)); } describe("useLottieInteractivity", () => { describe("General", () => { test("mounts with a div wrapper around lottie element", async () => { const hook = renderUseLottieInteractivity({ lottieObj: { View: <span />, } as any, mode: "scroll", actions: [], }); const result = render(hook.result.current); expect(result.container.innerHTML).toEqual("<div><span></span></div>"); }); }); }); describe("useInitInteractivity", () => { const result = render(<div role="test" />); const wrapperRef = { current: result.getByRole("test"), }; wrapperRef.current.getBoundingClientRect = jest.fn(); const animationItem = { stop: jest.fn(), play: jest.fn(), goToAndStop: jest.fn(), playSegments: jest.fn(), resetSegments: jest.fn(), firstFrame: 0, isPaused: false, }; beforeEach(() => { (wrapperRef.current.getBoundingClientRect as jest.Mock< any, any >).mockClear(); // Object.values(wrapperRef.current).forEach((f) => { // f.mockClear(); // }); let { firstFrame, isPaused, ...itemMocks } = animationItem; Object.values(itemMocks).forEach((f) => { f.mockClear(); }); firstFrame = 0; isPaused = false; }); describe("General", () => { test("does nothing if animationItem is not provided", () => { const stopSpy = jest.spyOn(animationItem, "stop"); renderUseInitInteractivity({ wrapperRef: wrapperRef as any, animationItem: undefined as any, mode: "scroll", actions: [], }); expect(stopSpy).toHaveBeenCalledTimes(0); }); test("calls animationItem.stop() when mounts", () => { const stopSpy = jest.spyOn(animationItem, "stop"); renderUseInitInteractivity({ wrapperRef: wrapperRef as any, animationItem: animationItem as any, mode: "scroll", actions: [], }); expect(stopSpy).toHaveBeenCalledTimes(1); }); }); describe("scroll mode", () => { beforeAll(() => { window = Object.assign(window, { innerHeight: 1 }); (wrapperRef.current.getBoundingClientRect as jest.Mock< any, any >).mockReturnValue({ top: 0, left: 0, width: 0, height: 1, }); // currentPercent/containerVisibility => 0.5 }); beforeEach(() => { animationItem.isPaused = false; }); test("attaches and detaches eventListeners", () => { const AddLSpy = jest.spyOn(document, "addEventListener"); const RmLSpy = jest.spyOn(document, "removeEventListener"); const hook = renderUseInitInteractivity({ wrapperRef: wrapperRef as any, animationItem: animationItem as any, mode: "scroll", actions: [], }); expect(AddLSpy).toHaveBeenCalledTimes(1); hook.unmount(); expect(RmLSpy).toHaveBeenCalledTimes(1); }); test("do not process if action does not match", () => { const goToAndStopSpy = jest.spyOn(animationItem, "goToAndStop"); const playSegmentsSpy = jest.spyOn(animationItem, "playSegments"); const resetSegmentsSpy = jest.spyOn(animationItem, "resetSegments"); renderUseInitInteractivity({ wrapperRef: wrapperRef as any, animationItem: animationItem as any, mode: "scroll", actions: [{ visibility: [0, 0.4], frames: [5, 10], type: "seek" }], }); act(() => { fireEvent.scroll(document); }); expect(goToAndStopSpy).toHaveBeenCalledTimes(0); expect(playSegmentsSpy).toHaveBeenCalledTimes(0); expect(resetSegmentsSpy).toHaveBeenCalledTimes(0); }); test("handles `seek` type correctly", () => { // frameToGo = 10 const goToAndStopSpy = jest.spyOn(animationItem, "goToAndStop"); const goToAndStopArgMock = 10 - animationItem.firstFrame - 1; renderUseInitInteractivity({ wrapperRef: wrapperRef as any, animationItem: animationItem as any, mode: "scroll", actions: [{ visibility: [0, 1], frames: [5, 10], type: "seek" }], }); act(() => { fireEvent.scroll(document); fireEvent.scroll(document); }); expect(goToAndStopSpy).toHaveBeenCalledTimes(2); expect(goToAndStopSpy).toHaveBeenCalledWith(goToAndStopArgMock, true); }); test("handles `loop` type correctly", () => { const playSegmentsSpy = jest.spyOn(animationItem, "playSegments"); renderUseInitInteractivity({ wrapperRef: wrapperRef as any, animationItem: animationItem as any, mode: "scroll", actions: [ { visibility: [0, 0.4], frames: [10, 15], type: "loop" }, { visibility: [0.4, 1], frames: [5, 10], type: "loop" }, ], }); act(() => { fireEvent.scroll(document); }); expect(playSegmentsSpy).toHaveBeenCalledTimes(1); expect(playSegmentsSpy).toHaveBeenCalledWith([5, 10], true); act(() => { fireEvent.scroll(document); }); expect(playSegmentsSpy).toHaveBeenCalledTimes(1); // assignedSegment === action.frames animationItem.isPaused = true; act(() => { fireEvent.scroll(document); }); expect(playSegmentsSpy).toHaveBeenCalledTimes(2); // container visibility => 0.2 (wrapperRef.current.getBoundingClientRect as jest.Mock< any, any >).mockReturnValue({ top: 0.6, left: 0, width: 0, height: 1, }); act(() => { fireEvent.scroll(document); }); expect(playSegmentsSpy).toHaveBeenCalledTimes(3); }); test("handles `play` type correctly", () => { const playSpy = jest.spyOn(animationItem, "play"); const resetSegmentsSpy = jest.spyOn(animationItem, "resetSegments"); renderUseInitInteractivity({ wrapperRef: wrapperRef as any, animationItem: animationItem as any, mode: "scroll", actions: [{ visibility: [0, 1], frames: [5, 10], type: "play" }], }); expect(resetSegmentsSpy).toHaveBeenCalledTimes(0); expect(playSpy).toHaveBeenCalledTimes(0); act(() => { fireEvent.scroll(document); }); animationItem.isPaused = true; act(() => { fireEvent.scroll(document); }); expect(resetSegmentsSpy).toHaveBeenCalledTimes(1); expect(resetSegmentsSpy).toBeCalledWith(true); expect(playSpy).toHaveBeenCalledTimes(1); }); test("handles `stop` type correctly", () => { const goToAndStopSpy = jest.spyOn(animationItem, "goToAndStop"); const goToAndStopArgMock = 5 - animationItem.firstFrame - 1; renderUseInitInteractivity({ wrapperRef: wrapperRef as any, animationItem: animationItem as any, mode: "scroll", actions: [{ visibility: [0, 1], frames: [5, 10], type: "stop" }], }); act(() => { fireEvent.scroll(document); }); expect(goToAndStopSpy).toHaveBeenCalledTimes(1); expect(goToAndStopSpy).toHaveBeenCalledWith(goToAndStopArgMock, true); }); }); describe("cursor mode", () => { beforeAll(() => { (wrapperRef.current.getBoundingClientRect as jest.Mock< any, any >).mockReturnValue({ left: -1, top: -1, width: 2, height: 2, }); // x = 0.5; y = 0.5 }); test("attaches and detaches eventListeners", () => { const wrapperAddLSpy = jest.spyOn(wrapperRef.current, "addEventListener"); const wrapperRmLSpy = jest.spyOn( wrapperRef.current, "removeEventListener", ); const hook = renderUseInitInteractivity({ wrapperRef: wrapperRef as any, animationItem: animationItem as any, mode: "cursor", actions: [], }); expect(wrapperAddLSpy).toHaveBeenCalledTimes(2); hook.unmount(); expect(wrapperRmLSpy).toHaveBeenCalledTimes(2); }); test("handles mouseout event correctly", () => { const goToAndStopSpy = jest.spyOn(animationItem, "goToAndStop"); const playSegmentsSpy = jest.spyOn(animationItem, "playSegments"); const resetSegmentsSpy = jest.spyOn(animationItem, "resetSegments"); renderUseInitInteractivity({ wrapperRef: wrapperRef as any, animationItem: animationItem as any, mode: "cursor", actions: [ { position: { x: [0, 1], y: [0, 1] }, frames: [5, 10], type: "loop" }, ], }); act(() => { fireEvent.mouseOut(wrapperRef.current); }); expect(goToAndStopSpy).toHaveBeenCalledTimes(0); expect(playSegmentsSpy).toHaveBeenCalledTimes(0); expect(resetSegmentsSpy).toHaveBeenCalledTimes(0); }); test("do not process lottie if action does not match", () => { const goToAndStopSpy = jest.spyOn(animationItem, "goToAndStop"); const playSegmentsSpy = jest.spyOn(animationItem, "playSegments"); const resetSegmentsSpy = jest.spyOn(animationItem, "resetSegments"); const commonProps = { wrapperRef: wrapperRef as any, animationItem: animationItem as any, mode: "cursor" as "cursor", }; renderUseInitInteractivity({ ...commonProps, actions: [ { position: { x: [0, 1], y: [1, 0] }, frames: [5, 10], type: "seek" }, ], }); act(() => { fireEvent.mouseMove(wrapperRef.current); }); expect(goToAndStopSpy).toHaveBeenCalledTimes(0); expect(playSegmentsSpy).toHaveBeenCalledTimes(0); expect(resetSegmentsSpy).toHaveBeenCalledTimes(0); renderUseInitInteractivity({ ...commonProps, actions: [ { position: { x: 0.5, y: 0.8 }, frames: [5, 10], type: "seek" }, ], }); act(() => { fireEvent.mouseMove(wrapperRef.current); }); expect(goToAndStopSpy).toHaveBeenCalledTimes(0); expect(playSegmentsSpy).toHaveBeenCalledTimes(0); expect(resetSegmentsSpy).toHaveBeenCalledTimes(0); renderUseInitInteractivity({ ...commonProps, actions: [ { position: { x: 0.5, y: NaN }, frames: [5, 10], type: "seek" }, ], }); act(() => { fireEvent.mouseMove(wrapperRef.current); }); expect(goToAndStopSpy).toHaveBeenCalledTimes(0); expect(playSegmentsSpy).toHaveBeenCalledTimes(0); expect(resetSegmentsSpy).toHaveBeenCalledTimes(0); }); test("handles `seek` type correctly", () => { const playSegmentsSpy = jest.spyOn(animationItem, "playSegments"); const goToAndStopSpy = jest.spyOn(animationItem, "goToAndStop"); renderUseInitInteractivity({ wrapperRef: wrapperRef as any, animationItem: animationItem as any, mode: "cursor", actions: [ { position: { x: [0, 1], y: [0, 1] }, frames: [5, 10], type: "seek" }, ], }); act(() => { fireEvent.mouseMove(wrapperRef.current); }); expect(goToAndStopSpy).toHaveBeenCalledTimes(1); expect(goToAndStopSpy).toHaveBeenCalledWith(3, true); expect(playSegmentsSpy).toHaveBeenCalledTimes(1); expect(playSegmentsSpy).toHaveBeenCalledWith([5, 10], true); }); test("handles `loop` type correctly", () => { const playSegmentsSpy = jest.spyOn(animationItem, "playSegments"); renderUseInitInteractivity({ wrapperRef: wrapperRef as any, animationItem: animationItem as any, mode: "cursor", actions: [ { position: { x: [0, 1], y: [0, 1] }, frames: [5, 10], type: "loop" }, ], }); act(() => { fireEvent.mouseMove(wrapperRef.current); }); expect(playSegmentsSpy).toHaveBeenCalledTimes(1); expect(playSegmentsSpy).toHaveBeenCalledWith([5, 10], true); }); test("handles `play` type correctly", () => { const resetSegmentsSpy = jest.spyOn(animationItem, "resetSegments"); const playSegmentsSpy = jest.spyOn(animationItem, "playSegments"); renderUseInitInteractivity({ wrapperRef: wrapperRef as any, animationItem: animationItem as any, mode: "cursor", actions: [ { position: { x: [0, 1], y: [0, 1] }, frames: [5, 10], type: "play" }, ], }); act(() => { fireEvent.mouseMove(wrapperRef.current); }); expect(resetSegmentsSpy).toHaveBeenCalledTimes(0); expect(playSegmentsSpy).toHaveBeenCalledTimes(1); animationItem.isPaused = true; act(() => { fireEvent.mouseMove(wrapperRef.current); }); expect(resetSegmentsSpy).toHaveBeenCalledTimes(1); expect(resetSegmentsSpy).toHaveBeenCalledWith(false); expect(playSegmentsSpy).toHaveBeenCalledTimes(2); expect(playSegmentsSpy).toHaveBeenCalledWith([5, 10]); }); test("handles `stop` type correctly", () => { const goToAndStopSpy = jest.spyOn(animationItem, "goToAndStop"); renderUseInitInteractivity({ wrapperRef: wrapperRef as any, animationItem: animationItem as any, mode: "cursor", actions: [ { position: { x: [0, 1], y: [0, 1] }, frames: [5, 10], type: "stop" }, ], }); act(() => { fireEvent.mouseMove(wrapperRef.current); }); expect(goToAndStopSpy).toHaveBeenCalledTimes(1); expect(goToAndStopSpy).toHaveBeenCalledWith(5, true); }); }); describe("helpers", () => { test("getContainerVisbility does correct calculations", () => { const values = { top: 5, height: -10, innerHeight: 15, result: 2, }; const wrapper = wrapperRef.current; (wrapper.getBoundingClientRect as jest.Mock<any, any>).mockReturnValue({ top: values.top, height: values.height, }); window = Object.assign(window, { innerHeight: values.innerHeight }); const result = getContainerVisibility(wrapper as any); expect(wrapper.getBoundingClientRect).toHaveBeenCalledTimes(1); expect(result).toEqual(values.result); }); test("getContainerCursorPosition does correct calculations", () => { const values = { left: 5, top: 5, width: 2, height: 2, cursorX: 15, cursorY: 15, result: { x: 5, y: 5 }, }; const wrapper = wrapperRef.current; (wrapper.getBoundingClientRect as jest.Mock<any, any>).mockReturnValue({ top: values.top, left: values.left, width: values.width, height: values.height, }); const result = getContainerCursorPosition( wrapper as any, values.cursorX, values.cursorY, ); expect(wrapper.getBoundingClientRect).toHaveBeenCalledTimes(1); expect(result).toEqual(values.result); }); }); });
the_stack
import { Quaternion } from './quaternion' import { Matrix } from './matrix' const f32 = { min: Number.MIN_VALUE, max: Number.MAX_VALUE } export class Vector3 { /** Returns a vector with values set to their maximum values. */ public static MAX_VALUE: Vector3 = new Vector3(f32.max, f32.max, f32.max) /** Returns a vector with values set to their minimum values. */ public static MIN_VALUE: Vector3 = new Vector3(f32.min, f32.min, f32.min) /** the internal elements for this type. */ public v: Float32Array /** Creates a new Vector3. */ constructor(x: number, y: number, z: number) { this.v = new Float32Array(3) this.v[0] = x this.v[1] = y this.v[2] = z } /** Returns the string representation of this object. */ public toString(): string { return `[${this.v[0]}, ${this.v[1]}, ${this.v[2]}]` } /** Returns the type kind of this object. */ public kind(): string { return 'Vector3' } /** Returns a clone of this vector. */ public clone(): Vector3 { return Vector3.clone(this) } public get x(): number { return this.v[0]; } public get y(): number { return this.v[1] } public get z(): number { return this.v[2] } public set x(value: number) { this.v[0] = value; } public set y(value: number) { this.v[1] = value } public set z(value: number) { this.v[2] = value } /** Returns the length of this vector. */ public length(): number { return Vector3.getLength(this) } /** Returns the length of this vector. */ public lengthSq(): number { return Vector3.getLengthSq(this) } /** Returns this vector normalized. */ public normalize(): Vector3 { return Vector3.normalize(this) } /** Returns the dot product between this and the given vector. */ public dot(v0: Vector3): number { return Vector3.dot(this, v0) } /** Returns the cross product between this and the given vector. */ public cross(v0: Vector3): Vector3 { return Vector3.cross(this, v0) } /** Returns the addition between this and the given vector. */ public add(v0: Vector3): Vector3 { return Vector3.add(this, v0) } /** Returns the subtraction between this and the given vector. */ public sub(v0: Vector3): Vector3 { return Vector3.sub(this, v0) } /** Returns the multiplication between this and the given vector. */ public mul(v0: Vector3): Vector3 { return Vector3.mul(this, v0) } /** Returns the division between this and the given vector. */ public div(v0: Vector3): Vector3 { return Vector3.div(this, v0) } /** Returns a new scaled vector from the given scalar value. */ public scale(s0: number): Vector3 { return Vector3.scale(this, s0) } /** Returns a new negated vector from this vector. */ public negate(): Vector3 { return Vector3.negate(this) } /** Returns a new vector whose values are initialized to zero. */ public static zero(): Vector3 { return new Vector3(0.0, 0.0, 0.0) } /** Returns a new vector whose values are initialized to one. */ public static one(): Vector3 { return new Vector3(1.0, 1.0, 1.0) } /** Returns a new unit x vector. */ public static unitX(): Vector3 { return new Vector3(1.0, 0.0, 0.0) } /** Returns a new unit y vector. */ public static unitY(): Vector3 { return new Vector3(0.0, 1.0, 0.0) } /** Returns a new unit z vector. */ public static unitZ(): Vector3 { return new Vector3(0.0, 0.0, 1.0) } /** Returns a new left vector. */ public static left(): Vector3 { return new Vector3(-1.0, 0.0, 0.0) } /** Returns a new right vector. */ public static right(): Vector3 { return new Vector3(1.0, 0.0, 0.0) } /** Returns a new up vector. */ public static up(): Vector3 { return new Vector3(0.0, 1.0, 0.0) } /** Returns a new up vector. */ public static down(): Vector3 { return new Vector3(0.0, -1.0, 0.0) } /** Returns a new forward vector. */ public static forward(): Vector3 { return new Vector3(0.0, 0.0, 1.0) } /** Returns a new backward vector. */ public static backward(): Vector3 { return new Vector3(0.0, 0.0, -1.0) } /** Compares the left and right vectors for equality. */ public static equals(v0: Vector3, v1: Vector3): boolean { return ( v0.v[0] === v1.v[0] && v0.v[1] === v1.v[1] && v0.v[2] === v1.v[2] ) } /** Returns the length of the given vector. */ public static getLength(v0: Vector3): number { return Math.sqrt( (v0.v[0] * v0.v[0]) + (v0.v[1] * v0.v[1]) + (v0.v[2] * v0.v[2]) ) } /** Returns the square length of the given vector. */ public static getLengthSq(v0: Vector3): number { return ( (v0.v[0] * v0.v[0]) + (v0.v[1] * v0.v[1]) + (v0.v[2] * v0.v[2]) ) } /** Returns the distance between the left and right vectors. */ public static distance(v0: Vector3, v1: Vector3): number { const x = v0.v[0] - v1.v[0] const y = v0.v[1] - v1.v[1] const z = v0.v[2] - v1.v[2] return Math.sqrt((x * x) + (y * y) + (z * z)) } /** Returns the squared distance between the left and right vectors. */ public static distanceSq(v0: Vector3, v1: Vector3): number { const x = v0.v[0] - v1.v[0] const y = v0.v[1] - v1.v[1] const z = v0.v[2] - v1.v[2] return ((x * x) + (y * y) + (z * z)) } /** Returns the dot product between the given two vectors. */ public static dot(v0: Vector3, v1: Vector3): number { return ( (v0.v[0] * v1.v[0]) + (v0.v[1] * v1.v[1]) + (v0.v[2] * v1.v[2]) ) } /** Returns a normalized vector from the given vector. */ public static normalize(v0: Vector3): Vector3 { const len = 1.0 / Math.sqrt( (v0.v[0] * v0.v[0]) + (v0.v[1] * v0.v[1]) + (v0.v[2] * v0.v[2]) ) return new Vector3( v0.v[0] * len, v0.v[1] * len, v0.v[2] * len ) } /** Returns the cross product for the given two vectors. */ public static cross(v0: Vector3, v1: Vector3): Vector3 { return new Vector3( (v0.v[1] * v1.v[2]) - (v0.v[2] * v1.v[1]), (v0.v[2] * v1.v[0]) - (v0.v[0] * v1.v[2]), (v0.v[0] * v1.v[1]) - (v0.v[1] * v1.v[0]) ) } /** Returns the reflected vector about the given vector and normal. */ public static reflect(v0: Vector3, n0: Vector3): Vector3 { const dot = ( (v0.v[0] * n0.v[0]) + (v0.v[1] * n0.v[1]) + (v0.v[2] * n0.v[2]) ) return new Vector3( v0.v[0] - ((2.0 * dot) * n0.v[0]), v0.v[1] - ((2.0 * dot) * n0.v[1]), v0.v[2] - ((2.0 * dot) * n0.v[2]) ) } /** Returns a vectors whose values are absoluted from the given vector. */ public static abs(v0: Vector3): Vector3 { return new Vector3( Math.abs(v0.v[0]), Math.abs(v0.v[1]), Math.abs(v0.v[2]) ) } /** Returns the minimum components from the given to vectors. */ public static min(v0: Vector3, v1: Vector3): Vector3 { return new Vector3( (v0.v[0] < v1.v[0]) ? v0.v[0] : v1.v[0], (v0.v[1] < v1.v[1]) ? v0.v[1] : v1.v[1], (v0.v[2] < v1.v[2]) ? v0.v[2] : v1.v[2] ) } /** Returns the maximum components from the given to vectors. */ public static max(v0: Vector3, v1: Vector3): Vector3 { return new Vector3( (v0.v[0] > v1.v[0]) ? v0.v[0] : v1.v[0], (v0.v[1] > v1.v[1]) ? v0.v[1] : v1.v[1], (v0.v[2] > v1.v[2]) ? v0.v[2] : v1.v[2] ) } /** Returns a clamped vector within the given min and max range. */ public static clamp(v0: Vector3, min: Vector3, max: Vector3): Vector3 { let x = v0.v[0] let y = v0.v[1] let z = v0.v[2] x = (x > max.v[0]) ? max.v[0] : x x = (x < min.v[0]) ? min.v[0] : x y = (y > max.v[1]) ? max.v[1] : y y = (y < min.v[1]) ? min.v[1] : y z = (z > max.v[2]) ? max.v[2] : z z = (z < min.v[2]) ? min.v[2] : z return new Vector3(x, y, z) } /** Returns the linear interpolation vector between the given two vectors and amount. */ public static lerp(v0: Vector3, v1: Vector3, amount: number): Vector3 { return new Vector3( v0.v[0] + ((v1.v[0] - v0.v[0]) * amount), v0.v[1] + ((v1.v[1] - v0.v[1]) * amount), v0.v[2] + ((v1.v[2] - v0.v[2]) * amount) ) } /** Returns the barycentric coordinate between the given 3 vectors and amounts. */ public static barycentric(v0: Vector3, v1: Vector3, v2: Vector3, amount0: number, amount1: number): Vector3 { return new Vector3( (v0.v[0] + (amount0 * (v1.v[0] - v0.v[0]))) + (amount1 * (v2.v[0] - v0.v[0])), (v0.v[1] + (amount0 * (v1.v[1] - v0.v[1]))) + (amount1 * (v2.v[1] - v0.v[1])), (v0.v[2] + (amount0 * (v1.v[2] - v0.v[2]))) + (amount1 * (v2.v[2] - v0.v[2])) ) } /** Returns the smooth step interpolation between the given two vectors and amount. */ public static smoothstep(v0: Vector3, v1: Vector3, amount: number): Vector3 { amount = (amount > 1.0) ? 1.0 : ((amount < 0.0) ? 0.0 : amount) amount = (amount * amount) * (3.0 - (2.0 * amount)) return new Vector3( v0.v[0] + ((v1.v[0] - v0.v[0]) * amount), v0.v[1] + ((v1.v[1] - v0.v[1]) * amount), v0.v[2] + ((v1.v[2] - v0.v[2]) * amount) ) } /** Returns the catmull rom interpolation between the given vectors and amount. */ public static catmullrom(v0: Vector3, v1: Vector3, v2: Vector3, v3: Vector3, amount: number): Vector3 { const n0 = amount * amount const n1 = amount * n0 return new Vector3( 0.5 * ((((2.0 * v1.v[0]) + ((-v0.v[0] + v2.v[0]) * amount)) + (((((2.0 * v0.v[0]) - (5.0 * v1.v[0])) + (4.0 * v2.v[0])) - v3.v[0]) * n0)) + ((((-v0.v[0] + (3.0 * v1.v[0])) - (3.0 * v2.v[0])) + v3.v[0]) * n1)), 0.5 * ((((2.0 * v1.v[1]) + ((-v0.v[1] + v2.v[1]) * amount)) + (((((2.0 * v0.v[1]) - (5.0 * v1.v[1])) + (4.0 * v2.v[1])) - v3.v[1]) * n0)) + ((((-v0.v[1] + (3.0 * v1.v[1])) - (3.0 * v2.v[1])) + v3.v[1]) * n1)), 0.5 * ((((2.0 * v1.v[2]) + ((-v0.v[2] + v2.v[2]) * amount)) + (((((2.0 * v0.v[2]) - (5.0 * v1.v[2])) + (4.0 * v2.v[2])) - v3.v[2]) * n0)) + ((((-v0.v[2] + (3.0 * v1.v[2])) - (3.0 * v2.v[2])) + v3.v[2]) * n1)) ) } /** Returns the hermite interpolation between the given vectors and amount. */ public static hermite(v0: Vector3, t0: Vector3, v1: Vector3, t1: Vector3, amount: number): Vector3 { const n0 = amount * amount const n1 = amount * n0 const n2 = ((2.0 * n1) - (3.0 * n0)) + 1.0 const n3 = (-2.0 * n1) + (3.0 * n0) const n4 = (n1 - (2.0 * n0)) + amount const n5 = n1 - n0 return new Vector3( (((v0.v[0] * n2) + (v1.v[0] * n3)) + (t0.v[0] * n4)) + (t1.v[0] * n5), (((v0.v[1] * n2) + (v1.v[1] * n3)) + (t0.v[1] * n4)) + (t1.v[1] * n5), (((v0.v[2] * n2) + (v1.v[2] * n3)) + (t0.v[2] * n4)) + (t1.v[2] * n5) ) } /** Returns the transformed vector from the given vector and Matrix. */ public static transform(v0: Vector3, m0: Matrix): Vector3 { return new Vector3( (((v0.v[0] * m0.v[0]) + (v0.v[1] * m0.v[4])) + (v0.v[2] * m0.v[8])) + m0.v[12], (((v0.v[0] * m0.v[1]) + (v0.v[1] * m0.v[5])) + (v0.v[2] * m0.v[9])) + m0.v[13], (((v0.v[0] * m0.v[2]) + (v0.v[1] * m0.v[6])) + (v0.v[2] * m0.v[10])) + m0.v[14] ) } /** Returns the transformed normal (3 component) vector from the given normal and Matrix. */ public static transformNormal(n0: Vector3, m0: Matrix): Vector3 { return new Vector3( ((n0.v[0] * m0.v[0]) + (n0.v[1] * m0.v[4])) + (n0.v[2] * m0.v[8]), ((n0.v[0] * m0.v[1]) + (n0.v[1] * m0.v[5])) + (n0.v[2] * m0.v[9]), ((n0.v[0] * m0.v[2]) + (n0.v[1] * m0.v[6])) + (n0.v[2] * m0.v[10]) ) } /** Returns the transformed vector from the given normal and quaternion. */ public static transformQuaternion(v0: Vector3, q0: Quaternion): Vector3 { const n0 = q0.v[0] + q0.v[0] const n1 = q0.v[1] + q0.v[1] const n2 = q0.v[2] + q0.v[2] const n3 = q0.v[3] * n0 const n4 = q0.v[3] * n1 const n5 = q0.v[3] * n2 const n6 = q0.v[0] * n0 const n7 = q0.v[0] * n1 const n8 = q0.v[0] * n2 const n9 = q0.v[1] * n1 const n10 = q0.v[1] * n2 const n11 = q0.v[2] * n2 return new Vector3( ((v0.v[0] * ((1.0 - n9) - n11)) + (v0.v[1] * (n7 - n5))) + (v0.v[2] * (n8 + n4)), ((v0.v[0] * (n7 + n5)) + (v0.v[1] * ((1.0 - n6) - n11))) + (v0.v[2] * (n10 - n3)), ((v0.v[0] * (n8 - n4)) + (v0.v[1] * (n10 + n3))) + (v0.v[2] * ((1.0 - n6) - n9)) ) } /** Returns the addition of the given vectors. */ public static add(v0: Vector3, v1: Vector3): Vector3 { return new Vector3( v0.v[0] + v1.v[0], v0.v[1] + v1.v[1], v0.v[2] + v1.v[2] ) } /** Returns the subtraction of the given vectors. */ public static sub(v0: Vector3, v1: Vector3): Vector3 { return new Vector3( v0.v[0] - v1.v[0], v0.v[1] - v1.v[1], v0.v[2] - v1.v[2] ) } /** Multiplies the given two vectors. */ public static mul(v0: Vector3, v1: Vector3): Vector3 { return new Vector3( v0.v[0] * v1.v[0], v0.v[1] * v1.v[1], v0.v[2] * v1.v[2] ) } /** Divides the given two vectors. */ public static div(v0: Vector3, v1: Vector3): Vector3 { return new Vector3( v0.v[0] / v1.v[0], v0.v[1] / v1.v[1], v0.v[2] / v1.v[2] ) } /** Multiplies the given vector with the scalar. */ public static scale(v0: Vector3, scalar: number): Vector3 { return new Vector3( v0.v[0] * scalar, v0.v[1] * scalar, v0.v[2] * scalar ) } /** Negates the given vector. */ public static negate(v0: Vector3): Vector3 { return new Vector3( -v0.v[0], -v0.v[1], -v0.v[2] ) } /** Returns a clone of the given vector. */ public static clone(v0: Vector3): Vector3 { return new Vector3( v0.v[0], v0.v[1], v0.v[2] ) } /** Creates a new Vector3. */ public static create(x: number, y: number, z: number): Vector3 { return new Vector3(x, y, z) } }
the_stack
import path from 'path'; import fs from 'fs-extra'; import { cloneDeep } from 'lodash'; import { loadFromPath } from '../../src/fhirdefs/load'; import { FHIRDefinitions } from '../../src/fhirdefs/FHIRDefinitions'; import { StructureDefinition } from '../../src/fhirtypes/StructureDefinition'; import { TestFisher } from '../testhelpers'; import { ElementDefinition } from '../../src/fhirtypes'; describe('ElementDefinition', () => { let defs: FHIRDefinitions; let observation: StructureDefinition; let riskEvidenceSynthesis: StructureDefinition; let capabilityStatement: StructureDefinition; let appointment: StructureDefinition; let fisher: TestFisher; beforeAll(() => { defs = new FHIRDefinitions(); loadFromPath(path.join(__dirname, '..', 'testhelpers', 'testdefs'), 'r4-definitions', defs); fisher = new TestFisher().withFHIR(defs); }); beforeEach(() => { observation = fisher.fishForStructureDefinition('Observation'); riskEvidenceSynthesis = fisher.fishForStructureDefinition('RiskEvidenceSynthesis'); capabilityStatement = fisher.fishForStructureDefinition('CapabilityStatement'); appointment = fisher.fishForStructureDefinition('Appointment'); }); describe('#assignNumber', () => { // assigning a decimal it('should assign a decimal to a decimal', () => { const riskEstimateValue = riskEvidenceSynthesis.elements.find( e => e.id === 'RiskEvidenceSynthesis.riskEstimate.value' ); riskEstimateValue.assignValue(1.23); expect(riskEstimateValue.patternDecimal).toBe(1.23); }); it('should assign a decimal to a decimal (exactly)', () => { const riskEstimateValue = riskEvidenceSynthesis.elements.find( e => e.id === 'RiskEvidenceSynthesis.riskEstimate.value' ); riskEstimateValue.assignValue(1.23, true); expect(riskEstimateValue.fixedDecimal).toBe(1.23); }); it('should assign an integer to a decimal', () => { const riskEstimateValue = riskEvidenceSynthesis.elements.find( e => e.id === 'RiskEvidenceSynthesis.riskEstimate.value' ); riskEstimateValue.assignValue(BigInt(123)); expect(riskEstimateValue.patternDecimal).toBe(123); expect(riskEstimateValue.fixedDecimal).toBeUndefined(); }); it('should assign an integer to a decimal (exactly)', () => { const riskEstimateValue = riskEvidenceSynthesis.elements.find( e => e.id === 'RiskEvidenceSynthesis.riskEstimate.value' ); riskEstimateValue.assignValue(BigInt(123), true); expect(riskEstimateValue.fixedDecimal).toBe(123); expect(riskEstimateValue.patternDecimal).toBeUndefined(); }); it('should throw ValueAlreadyAssignedError when assigning an already assigned decimal by pattern[x]', () => { const riskEstimateValue = riskEvidenceSynthesis.elements.find( e => e.id === 'RiskEvidenceSynthesis.riskEstimate.value' ); riskEstimateValue.assignValue(1.23); expect(riskEstimateValue.patternDecimal).toBe(1.23); expect(() => { riskEstimateValue.assignValue(1.24); }).toThrow( 'Cannot assign 1.24 to this element; a different decimal is already assigned: 1.23.' ); expect(() => { riskEstimateValue.assignValue(1.24, true); }).toThrow( 'Cannot assign 1.24 to this element; a different decimal is already assigned: 1.23.' ); }); it('should throw ValueAlreadyAssignedError when assigning an already assigned decimal by fixed[x]', () => { const riskEstimateValue = riskEvidenceSynthesis.elements.find( e => e.id === 'RiskEvidenceSynthesis.riskEstimate.value' ); riskEstimateValue.assignValue(1.23, true); expect(riskEstimateValue.fixedDecimal).toBe(1.23); expect(() => { riskEstimateValue.assignValue(1.24, true); }).toThrow( 'Cannot assign 1.24 to this element; a different decimal is already assigned: 1.23.' ); }); it('should throw ValueAlreadyAssignedError when assigning a decimal to a different value set in a parent by pattern[x]', () => { const valueQuantity = observation.findElementByPath('valueQuantity', fisher); valueQuantity.patternQuantity = { value: 1.5 }; valueQuantity.unfold(fisher); const valueQuantityValue = observation.elements.find( e => e.id === 'Observation.value[x]:valueQuantity.value' ); const clone = cloneDeep(valueQuantityValue); expect(() => { valueQuantityValue.assignValue(2.5); }).toThrow( 'Cannot assign 2.5 to this element; a different decimal is already assigned: 1.5.' ); expect(() => { valueQuantityValue.assignValue(2.5, true); }).toThrow( 'Cannot assign 2.5 to this element; a different decimal is already assigned: 1.5.' ); expect(clone).toEqual(valueQuantityValue); }); it('should throw ValueAlreadyAssignedError when assigning a decimal to a different value set in a parent by fixed[x]', () => { const valueQuantity = observation.findElementByPath('valueQuantity', fisher); valueQuantity.fixedQuantity = { value: 1.5 }; valueQuantity.unfold(fisher); const valueQuantityValue = observation.elements.find( e => e.id === 'Observation.value[x]:valueQuantity.value' ); const clone = cloneDeep(valueQuantityValue); expect(() => { valueQuantityValue.assignValue(2.5); }).toThrow( 'Cannot assign 2.5 to this element; a different decimal is already assigned: 1.5.' ); expect(() => { valueQuantityValue.assignValue(2.5, true); }).toThrow( 'Cannot assign 2.5 to this element; a different decimal is already assigned: 1.5.' ); expect(clone).toEqual(valueQuantityValue); }); it('should throw FixedToPatternError when trying to change fixed[x] to pattern[x]', () => { const riskEstimateValue = riskEvidenceSynthesis.elements.find( e => e.id === 'RiskEvidenceSynthesis.riskEstimate.value' ); riskEstimateValue.assignValue(1.23, true); expect(riskEstimateValue.fixedDecimal).toBe(1.23); expect(() => { riskEstimateValue.assignValue(1.23); }).toThrow( 'Cannot assign this element using a pattern; as it is already assigned in the StructureDefinition using fixedDecimal.' ); }); // assigning an integer it('should assign an integer to an integer', () => { const riskEstimateValueNumeratorCount = riskEvidenceSynthesis.elements.find( e => e.id === 'RiskEvidenceSynthesis.riskEstimate.numeratorCount' ); riskEstimateValueNumeratorCount.assignValue(BigInt(123)); expect(riskEstimateValueNumeratorCount.patternInteger).toBe(123); expect(riskEstimateValueNumeratorCount.fixedInteger).toBeUndefined(); }); it('should assign an integer to an integer (exactly)', () => { const riskEstimateValueNumeratorCount = riskEvidenceSynthesis.elements.find( e => e.id === 'RiskEvidenceSynthesis.riskEstimate.numeratorCount' ); riskEstimateValueNumeratorCount.assignValue(BigInt(123), true); expect(riskEstimateValueNumeratorCount.fixedInteger).toBe(123); expect(riskEstimateValueNumeratorCount.patternInteger).toBeUndefined(); }); it('should throw ValueAlreadyAssignedError when assigning an already assigned integer by pattern[x]', () => { const riskEstimateValueNumeratorCount = riskEvidenceSynthesis.elements.find( e => e.id === 'RiskEvidenceSynthesis.riskEstimate.numeratorCount' ); riskEstimateValueNumeratorCount.assignValue(BigInt(123)); expect(riskEstimateValueNumeratorCount.patternInteger).toBe(123); expect(() => { riskEstimateValueNumeratorCount.assignValue(BigInt(124)); }).toThrow( 'Cannot assign 124 to this element; a different integer is already assigned: 123.' ); expect(() => { riskEstimateValueNumeratorCount.assignValue(BigInt(124), true); }).toThrow( 'Cannot assign 124 to this element; a different integer is already assigned: 123.' ); }); it('should throw ValueAlreadyAssignedError when assigning an already assigned integer by fixed[x]', () => { const riskEstimateValueNumeratorCount = riskEvidenceSynthesis.elements.find( e => e.id === 'RiskEvidenceSynthesis.riskEstimate.numeratorCount' ); riskEstimateValueNumeratorCount.assignValue(BigInt(123), true); expect(riskEstimateValueNumeratorCount.fixedInteger).toBe(123); expect(() => { riskEstimateValueNumeratorCount.assignValue(BigInt(124), true); }).toThrow( 'Cannot assign 124 to this element; a different integer is already assigned: 123.' ); }); it('should throw FixedToPatternError when trying to change fixed[x] to pattern[x]', () => { const riskEstimateValueNumeratorCount = riskEvidenceSynthesis.elements.find( e => e.id === 'RiskEvidenceSynthesis.riskEstimate.numeratorCount' ); riskEstimateValueNumeratorCount.assignValue(BigInt(123), true); expect(riskEstimateValueNumeratorCount.fixedInteger).toBe(123); expect(() => { riskEstimateValueNumeratorCount.assignValue(BigInt(123)); }).toThrow( 'Cannot assign this element using a pattern; as it is already assigned in the StructureDefinition using fixedInteger.' ); }); it('should throw MismatchedTypeError when assigning a decimal to an integer value', () => { const riskEstimateValueNumeratorCount = riskEvidenceSynthesis.elements.find( e => e.id === 'RiskEvidenceSynthesis.riskEstimate.numeratorCount' ); expect(() => { riskEstimateValueNumeratorCount.assignValue(12.3); }).toThrow('Cannot assign number value: 12.3. Value does not match element type: integer'); expect(() => { riskEstimateValueNumeratorCount.assignValue(12.3, true); }).toThrow('Cannot assign number value: 12.3. Value does not match element type: integer'); }); // assigning an unsignedInt it('should assign zero to an unsigned integer', () => { const reliableCache = capabilityStatement.elements.find( e => e.id === 'CapabilityStatement.messaging.reliableCache' ); reliableCache.assignValue(BigInt(0)); expect(reliableCache.patternUnsignedInt).toBe(0); expect(reliableCache.fixedUnsignedInt).toBeUndefined(); }); it('should assign zero to an unsigned integer (exactly)', () => { const reliableCache = capabilityStatement.elements.find( e => e.id === 'CapabilityStatement.messaging.reliableCache' ); reliableCache.assignValue(BigInt(0), true); expect(reliableCache.fixedUnsignedInt).toBe(0); expect(reliableCache.patternUnsignedInt).toBeUndefined(); }); it('should throw MismatchedTypeError when assigning a decimal to an unsignedInt', () => { const reliableCache = capabilityStatement.elements.find( e => e.id === 'CapabilityStatement.messaging.reliableCache' ); expect(() => { reliableCache.assignValue(2.4); }).toThrow('Cannot assign number value: 2.4. Value does not match element type: unsignedInt'); expect(() => { reliableCache.assignValue(2.4, true); }).toThrow('Cannot assign number value: 2.4. Value does not match element type: unsignedInt'); }); it('should throw MismatchedTypeError when assigning a negative integer to an unsignedInt', () => { const reliableCache = capabilityStatement.elements.find( e => e.id === 'CapabilityStatement.messaging.reliableCache' ); expect(() => { reliableCache.assignValue(BigInt(-24)); }).toThrow('Cannot assign number value: -24. Value does not match element type: unsignedInt'); expect(() => { reliableCache.assignValue(BigInt(-24), true); }).toThrow('Cannot assign number value: -24. Value does not match element type: unsignedInt'); }); it('should throw ValueAlreadyAssignedError when assigning an already assigned unsignedInt by pattern[x]', () => { const reliableCache = capabilityStatement.elements.find( e => e.id === 'CapabilityStatement.messaging.reliableCache' ); reliableCache.assignValue(BigInt(12)); expect(reliableCache.patternUnsignedInt).toBe(12); expect(() => { reliableCache.assignValue(BigInt(34)); }).toThrow( 'Cannot assign 34 to this element; a different unsignedInt is already assigned: 12.' ); expect(() => { reliableCache.assignValue(BigInt(34), true); }).toThrow( 'Cannot assign 34 to this element; a different unsignedInt is already assigned: 12.' ); }); it('should throw ValueAlreadyAssignedError when assigning an already assigned unsignedInt by fixed[x]', () => { const reliableCache = capabilityStatement.elements.find( e => e.id === 'CapabilityStatement.messaging.reliableCache' ); reliableCache.assignValue(BigInt(12), true); expect(reliableCache.fixedUnsignedInt).toBe(12); expect(() => { reliableCache.assignValue(BigInt(34), true); }).toThrow( 'Cannot assign 34 to this element; a different unsignedInt is already assigned: 12.' ); }); it('should throw ValueAlreadyAssignedError when assigning an already assigned unsignedInt by fixed[x]', () => { const reliableCache = capabilityStatement.elements.find( e => e.id === 'CapabilityStatement.messaging.reliableCache' ); reliableCache.assignValue(BigInt(12), true); expect(reliableCache.fixedUnsignedInt).toBe(12); expect(() => { reliableCache.assignValue(BigInt(34), true); }).toThrow( 'Cannot assign 34 to this element; a different unsignedInt is already assigned: 12.' ); }); it('should throw FixedToPatternError when trying to change fixed[x] to pattern[x]', () => { const reliableCache = capabilityStatement.elements.find( e => e.id === 'CapabilityStatement.messaging.reliableCache' ); reliableCache.assignValue(BigInt(12), true); expect(reliableCache.fixedUnsignedInt).toBe(12); expect(() => { reliableCache.assignValue(BigInt(12)); }).toThrow( 'Cannot assign this element using a pattern; as it is already assigned in the StructureDefinition using fixedUnsignedInt.' ); }); // assigning a positiveInt it('should assign a positive integer to positiveInt', () => { const minutesDuration = appointment.elements.find( e => e.id === 'Appointment.minutesDuration' ); minutesDuration.assignValue(BigInt(12)); expect(minutesDuration.patternPositiveInt).toBe(12); expect(minutesDuration.fixedPositiveInt).toBeUndefined(); }); it('should assign a positive integer to positiveInt (exactly)', () => { const minutesDuration = appointment.elements.find( e => e.id === 'Appointment.minutesDuration' ); minutesDuration.assignValue(BigInt(12), true); expect(minutesDuration.fixedPositiveInt).toBe(12); expect(minutesDuration.patternPositiveInt).toBeUndefined(); }); it('should throw MismatchedTypeError when assigning a decimal to a positiveInt', () => { const minutesDuration = appointment.elements.find( e => e.id === 'Appointment.minutesDuration' ); expect(() => { minutesDuration.assignValue(1.2); }).toThrow('Cannot assign number value: 1.2. Value does not match element type: positiveInt'); expect(() => { minutesDuration.assignValue(1.2, true); }).toThrow('Cannot assign number value: 1.2. Value does not match element type: positiveInt'); }); it('should throw MismatchedTypeError when assigning zero to a positiveInt', () => { const minutesDuration = appointment.elements.find( e => e.id === 'Appointment.minutesDuration' ); expect(() => { minutesDuration.assignValue(BigInt(0)); }).toThrow('Cannot assign number value: 0. Value does not match element type: positiveInt'); expect(() => { minutesDuration.assignValue(BigInt(0), true); }).toThrow('Cannot assign number value: 0. Value does not match element type: positiveInt'); }); it('should throw MismatchedTypeError when assigning a negative to a positiveInt', () => { const minutesDuration = appointment.elements.find( e => e.id === 'Appointment.minutesDuration' ); expect(() => { minutesDuration.assignValue(BigInt(-12)); }).toThrow('Cannot assign number value: -12. Value does not match element type: positiveInt'); expect(() => { minutesDuration.assignValue(BigInt(-12), true); }).toThrow('Cannot assign number value: -12. Value does not match element type: positiveInt'); }); it('should throw ValueAlreadyAssignedError when assigning an already assigned positiveInt by pattern[x]', () => { const minutesDuration = appointment.elements.find( e => e.id === 'Appointment.minutesDuration' ); minutesDuration.assignValue(BigInt(12)); expect(minutesDuration.patternPositiveInt).toEqual(12); expect(() => { minutesDuration.assignValue(BigInt(34)); }).toThrow( 'Cannot assign 34 to this element; a different positiveInt is already assigned: 12.' ); expect(() => { minutesDuration.assignValue(BigInt(34), true); }).toThrow( 'Cannot assign 34 to this element; a different positiveInt is already assigned: 12.' ); }); it('should throw ValueAlreadyAssignedError when assigning an already assigned positiveInt by fixed[x]', () => { const minutesDuration = appointment.elements.find( e => e.id === 'Appointment.minutesDuration' ); minutesDuration.assignValue(BigInt(12), true); expect(minutesDuration.fixedPositiveInt).toEqual(12); expect(() => { minutesDuration.assignValue(BigInt(34), true); }).toThrow( 'Cannot assign 34 to this element; a different positiveInt is already assigned: 12.' ); }); it('should throw FixedToPatternError when trying to change fixed[x] to pattern[x]', () => { const minutesDuration = appointment.elements.find( e => e.id === 'Appointment.minutesDuration' ); minutesDuration.assignValue(BigInt(12), true); expect(minutesDuration.fixedPositiveInt).toEqual(12); expect(() => { minutesDuration.assignValue(BigInt(12)); }).toThrow( 'Cannot assign this element using a pattern; as it is already assigned in the StructureDefinition using fixedPositiveInt.' ); }); // assigning a non-numerical value it('should throw MismatchedTypeError when assigning an integer to a non-numerical value', () => { const status = observation.elements.find(e => e.id === 'Observation.status'); expect(() => { status.assignValue(BigInt(123)); }).toThrow('Cannot assign number value: 123. Value does not match element type: code'); expect(() => { status.assignValue(BigInt(123), true); }).toThrow('Cannot assign number value: 123. Value does not match element type: code'); }); it('should throw NoSingleTypeError when element has multiple types', () => { const valueX = observation.elements.find(e => e.id === 'Observation.value[x]'); expect(() => { valueX.assignValue(BigInt(123)); }).toThrow( 'Cannot assign number value on this element since this element does not have a single type' ); expect(() => { valueX.assignValue(BigInt(123), true); }).toThrow( 'Cannot assign number value on this element since this element does not have a single type' ); expect(valueX.patternInteger).toBeUndefined(); expect(valueX.fixedInteger).toBeUndefined(); }); }); describe('#integer64', () => { let valueX: ElementDefinition; let valueInteger64: ElementDefinition; beforeAll(() => { const r5Extension = StructureDefinition.fromJSON( JSON.parse( fs.readFileSync( path.join( __dirname, '..', 'testhelpers', 'testdefs', 'r5-definitions', 'package', 'StructureDefinition-Extension.json' ), 'utf-8' ) ) ); valueX = r5Extension.elements.find(e => e.id === 'Extension.value[x]'); }); beforeEach(() => { valueInteger64 = cloneDeep(valueX); valueInteger64.type = valueInteger64.type.filter(t => t.code === 'integer64'); }); // assigning an integer64 // NOTE: Tests of assigning an integer64 as a string are in ElementDefinition.assignString.test.ts it('should assign an integer to an integer64', () => { valueInteger64.assignValue(BigInt(123)); expect(valueInteger64.patternInteger64).toBe('123'); expect(valueInteger64.fixedInteger64).toBeUndefined(); }); it('should assign an integer to an integer64 (exactly)', () => { valueInteger64.assignValue(BigInt(123), true); expect(valueInteger64.patternInteger64).toBeUndefined(); expect(valueInteger64.fixedInteger64).toBe('123'); }); it('should assign a large integer to an integer64 without losing precision', () => { valueInteger64.assignValue(BigInt('12345678901234567890')); expect(valueInteger64.patternInteger64).toBe('12345678901234567890'); expect(valueInteger64.fixedInteger64).toBeUndefined(); }); it('should throw ValueAlreadyAssignedError when assigning an already assigned integer by pattern[x]', () => { valueInteger64.assignValue(BigInt(123)); expect(valueInteger64.patternInteger64).toBe('123'); expect(() => { valueInteger64.assignValue(BigInt(124)); }).toThrow( 'Cannot assign 124 to this element; a different integer64 is already assigned: "123".' ); expect(() => { valueInteger64.assignValue(BigInt(124), true); }).toThrow( 'Cannot assign 124 to this element; a different integer64 is already assigned: "123".' ); }); it('should throw ValueAlreadyAssignedError when assigning an already assigned integer by fixed[x]', () => { valueInteger64.assignValue(BigInt(123), true); expect(valueInteger64.fixedInteger64).toBe('123'); expect(() => { valueInteger64.assignValue(BigInt(124), true); }).toThrow( 'Cannot assign 124 to this element; a different integer64 is already assigned: "123".' ); }); it('should throw FixedToPatternError when trying to change fixed[x] to pattern[x]', () => { valueInteger64.assignValue(BigInt(123), true); expect(valueInteger64.fixedInteger64).toBe('123'); expect(() => { valueInteger64.assignValue(BigInt(123)); }).toThrow( 'Cannot assign this element using a pattern; as it is already assigned in the StructureDefinition using fixedInteger64.' ); }); it('should throw MismatchedTypeError when assigning a decimal to an integer64 value', () => { expect(() => { valueInteger64.assignValue(12.3); }).toThrow('Cannot assign number value: 12.3. Value does not match element type: integer64'); expect(() => { valueInteger64.assignValue(12.3, true); }).toThrow('Cannot assign number value: 12.3. Value does not match element type: integer64'); }); }); });
the_stack
import * as fs from "fs"; import { parseString } from "xml2js"; import { OptionalInputArgument, OutputArgument, RequiredInputArgument, TaFuncApiXml } from "./ta_func_api.generated"; import G = require("glob"); import { Arguments } from "yargs"; import { createMap } from "monofile-utilities/lib/map"; import { piclick } from "monofile-utilities/lib/piclick"; interface Json2ts { convertObjectToTsInterfaces<T>(content: T, name?: string): string; toUpperFirstLetter(text: string): string; toLowerFirstLetter(text: string): string; removeMajority(text: string): string; } const json2ts: Json2ts = require("json2ts"); json2ts.toLowerFirstLetter = json2ts.toUpperFirstLetter = json2ts.removeMajority = text => text; export function parseXml() { const config = fs.readFileSync( __dirname + "/../ta-lib/ta_func_api.xml", "utf8" ); parseString(config, (err, result) => { if (err) { console.error(err); } else { fs.writeFileSync( __dirname + "/ta_func_api.generated.json", JSON.stringify(result, void 0, 2) ); const content = json2ts.convertObjectToTsInterfaces( result, "TaFuncApiXml" ); fs.writeFileSync(__dirname + "/ta_func_api.generated.ts", content); } }); } export function displayTypes() { const config: TaFuncApiXml = require("./ta_func_api.generated.json"); const requiredNames = createMap<true>(); const requiredTypes = createMap<true>(); const optionalNames = createMap<true>(); const optionalTypes = createMap<true>(); const outputNames = createMap<true>(); const outputTypes = createMap<true>(); const outputFlags = createMap<true>(); config.FinancialFunctions.FinancialFunction.forEach(func => { func.RequiredInputArguments && func.RequiredInputArguments.forEach(requires => { requires.RequiredInputArgument.forEach(argv => { argv.Name.forEach(name => (requiredNames[name] = true)); argv.Type.forEach(type => (requiredTypes[type] = true)); }); }); func.OptionalInputArguments && func.OptionalInputArguments.forEach(options => { options.OptionalInputArgument.forEach(argv => { argv.Name.forEach(name => (optionalNames[name] = true)); argv.Type.forEach(type => (optionalTypes[type] = true)); }); }); func.OutputArguments && func.OutputArguments.forEach(outputs => { outputs.OutputArgument.forEach(argv => { argv.Name.forEach(name => (outputNames[name] = true)); argv.Type.forEach(type => (outputTypes[type] = true)); argv.Flags.forEach(flags => { flags.Flag.forEach(flag => (outputFlags[flag] = true)); }); }); }); }); const result = { requiredNames, requiredTypes, optionalNames, optionalTypes, outputNames, outputTypes, outputFlags }; process.stdout.write( Object.keys(result) .map(name => { return ( name + ": " + Object.keys(result[name as keyof typeof result]).join(", ") ); }) .join("\n") ); } class Indenter { constructor(public prefix = " ", public indented = 0) {} indent(content: string) { return this.prefix.repeat(++this.indented) + content; } undent(content: string) { return this.prefix.repeat(--this.indented) + content; } normal(content: string) { return this.prefix.repeat(this.indented) + content; } } class ContentBuilder { constructor( public content: string[] = [], public indenter = new Indenter() ) {} indent(...contents: string[]): this { this.indenter.indented++; for (let i = 0; i < contents.length; i++) { this.content.push(this.indenter.normal(contents[i])); } return this; } undent(...contents: string[]): this { this.indenter.indented--; for (let i = 0; i < contents.length; i++) { this.content.push(this.indenter.normal(contents[i])); } return this; } normal(...contents: string[]) { for (let i = 0; i < contents.length; i++) { this.content.push(this.indenter.normal(contents[i])); } return this; } build() { return this.content.join("\n"); } } export function ucFirst(str: string) { return str.charAt(0).toUpperCase() + str.substr(1); } export function normalName(name: string) { return name.replace(/-/g, "").replace(/\s+/g, "_"); } export function optName(argv: OptionalInputArgument) { if (argv.Name.length !== 1) { throw new Error("out name is not a single array " + JSON.stringify(argv)); } const name = argv.Name[0]; return normalName(name.startsWith("opt") ? name : `opt${ucFirst(name)}`); } export function inName(argv: RequiredInputArgument) { if (argv.Name.length !== 1) { throw new Error("out name is not a single array " + JSON.stringify(argv)); } const name = argv.Name[0]; return normalName(name.startsWith("in") ? name : `in${ucFirst(name)}`); } export function outName(argv: OutputArgument) { if (argv.Name.length !== 1) { throw new Error("out name is not a single array " + JSON.stringify(argv)); } const name = argv.Name[0]; return normalName(name.startsWith("out") ? name : `out${ucFirst(name)}`); } export function jsInName(argv: RequiredInputArgument) { return inName(argv) + "_JS"; } export function jsOutName(argv: OutputArgument) { return outName(argv) + "_JS"; } export function optDft(argv: OptionalInputArgument, ts = false) { const type = optType(argv); return type === "TA_MAType" ? ts ? TA_MATypes[argv.DefaultValue[0]].split("_")[2] : TA_MATypes[argv.DefaultValue[0]] : argv.DefaultValue[0]; } export function optType(argv: OptionalInputArgument, ts = false) { if (argv.Type.length !== 1) { throw new TypeError( "opt type must be a single string " + JSON.stringify(argv) ); } if (ts) { switch (argv.Type[0]) { case "Integer": case "Double": return "number"; case "MA Type": return "MATypes"; default: throw new TypeError( "Unrecognized opt param type " + JSON.stringify(argv) ); } } switch (argv.Type[0]) { case "Integer": return "int"; case "MA Type": return "TA_MAType"; case "Double": return "double"; default: throw new TypeError( "Unrecognized opt param type " + JSON.stringify(argv) ); } } export function outType(argv: OutputArgument) { if (argv.Type.length > 1) { throw new TypeError( "output type must be a single string " + JSON.stringify(argv) ); } switch (argv.Type[0]) { case "Double Array": return "double"; case "Integer Array": return "int"; default: throw new TypeError( "unrecognized out param type " + JSON.stringify(argv) ); } } export const RecordFields = ["Open", "High", "Low", "Close", "Volume"]; export const TA_MATypes: Record<string | number, string> = createMap({ 0: "TA_MAType_SMA", 1: "TA_MAType_EMA", 2: "TA_MAType_WMA", 3: "TA_MAType_DEMA", 4: "TA_MAType_TEMA", 5: "TA_MAType_TRIMA", 6: "TA_MAType_KAMA", 7: "TA_MAType_MAMA", 8: "TA_MAType_T3" }); export function generateBindings({ _ }: Arguments) { const body = new ContentBuilder(); body.normal( "/*!", " * This file is generated by generate.ts, do not edit it.", " */", "", "#include <nan.h>", '#include "../ta-lib/c/include/ta_libc.h"', "" ); const footer = new ContentBuilder(); footer .normal("") .normal( "void Init(v8::Local<v8::Object> exports, v8::Local<v8::Object> module) {" ) .indent("TA_RetCode retCode = TA_Initialize();") .normal("if (retCode != TA_SUCCESS) {") .indent('Nan::ThrowError("TA initialize failed!");') .normal("return;") .undent("}"); const config: TaFuncApiXml = require("./ta_func_api.generated.json"); config.FinancialFunctions.FinancialFunction.filter( func => _.length === 0 || _.indexOf(func.Abbreviation[0]) > -1 ).forEach((func, index) => { if (index > 0) { // return; } const name = func.Abbreviation[0]; const required: RequiredInputArgument[] = func.RequiredInputArguments ? func.RequiredInputArguments.reduce( (prev, curr) => { return curr.RequiredInputArgument ? prev.concat(curr.RequiredInputArgument) : prev; }, [] as RequiredInputArgument[] ) : []; const optional: OptionalInputArgument[] = func.OptionalInputArguments ? func.OptionalInputArguments.reduce( (prev, curr) => { return curr.OptionalInputArgument ? prev.concat(curr.OptionalInputArgument) : prev; }, [] as OptionalInputArgument[] ) : []; const output: OutputArgument[] = func.OutputArguments ? func.OutputArguments.reduce( (prev, curr) => { return curr.OutputArgument ? prev.concat(curr.OutputArgument) : prev; }, [] as OutputArgument[] ) : []; const doubleRequired = required.filter( argv => RecordFields.indexOf(argv.Type[0]) === -1 ); const outInitJS: string[] = ["v8::Local<v8::Array> outAll_JS;"]; output.forEach(argv => { outInitJS.push( `v8::Local<v8::Array> ${jsOutName( argv )} = Nan::New<v8::Array>(outLength);` ); }); if (output.length === 1) { outInitJS.push(`outAll_JS = ${jsOutName(output[0])};`); } else { outInitJS.push(`outAll_JS = Nan::New<v8::Array>(${output.length});`); output.forEach((argv, index) => { outInitJS.push(`Nan::Set(outAll_JS, ${index}, ${jsOutName(argv)});`); }); } const returnStatement = `info.GetReturnValue().Set(outAll_JS);`; body // function declare .normal( `void TA_FUNC_${name}(const Nan::FunctionCallbackInfo<v8::Value> &info) {` ) // first argument .indent( "v8::Local<v8::Context> context = info.GetIsolate()->GetCurrentContext();" ) .normal( "v8::Local<v8::Array> inFirst = v8::Local<v8::Array>::Cast(info[0]);" ) // input length .normal("int inLength = inFirst->Length();") // output length .normal("int outLength = 0;") // check input length, if is 0, return empty result, avoid check parameters .normal("if (inLength == 0) {") .indent(...outInitJS) .normal(returnStatement) .normal("return;") .undent("}") // first input is Record[] or double[] .normal("int firstIsRecord = 0;") .normal("if (Nan::Get(inFirst, 0).ToLocalChecked()->IsObject()) {") .indent("firstIsRecord = 1;") .undent("}") // declare required input .normal( ...required.map( argv => `double *${inName(argv)} = new double[inLength];` ) ) // declare optional input .normal( ...optional.map(argv => { const type = optType(argv); const defaults = type === "TA_MAType" ? TA_MATypes[argv.DefaultValue[0]] : argv.DefaultValue[0]; return `${type} ${optName(argv)} = ${defaults};`; }) ) // declare internal input .normal("int startIdx = 0;") .normal("int endIdx = inLength - 1;") .normal("int outBegIdx = 0;") .normal("int outNBElement = 0;") .normal("uint32_t i = 0;") .normal("int argc = info.Length();") // init inputs .normal("if (firstIsRecord == 0) {") .indent( ...required.map((argv, index) => { return `v8::Local<v8::Array> ${jsInName( argv )} = v8::Local<v8::Array>::Cast(info[${index}]);`; }) ) // init required .normal("for (i = 0; i < (uint32_t) inLength; i++) {") .indent( ...required.map( argv => `${inName(argv)}[i] = Nan::Get(${jsInName( argv )}, i).ToLocalChecked()->NumberValue(context).FromJust();` ) ) .undent("}") // init optional .normal( ...optional.map((argv, index) => { index += required.length; const type = optType(argv); const check = type === "double" ? "Number" : "Int32"; const cast = type === "TA_MAType" ? "(TA_MAType) " : ""; return ( `${optName( argv )} = argc > ${index} && info[${index}]->Is${check}()` + ` ? ${cast} info[${index}]->${check}Value(context).FromJust() : ${optName( argv )};` ); }) ) .normal( ...["startIdx", "endIdx"].map((name, index) => { index += required.length + optional.length; return `${name} = argc > ${index} && info[${index}]->IsInt32() ? info[${index}]->Int32Value(context).FromJust() : ${name};`; }) ) .undent("} else {") .indent( ...required.map((argv, index) => { const ctor = doubleRequired.indexOf(argv) === -1 ? `Nan::New("${argv.Type[0]}").ToLocalChecked()` : `info[${index + 1}]->ToString(context).ToLocalChecked();`; return `v8::Local<v8::String> ${inName(argv)}Name = ${ctor};`; }) ) .normal(`v8::Local<v8::Object> inObject;`) .normal("for (i = 0; i < (uint32_t) inLength; i++) {") .indent( "inObject = Nan::Get(inFirst, i).ToLocalChecked()->ToObject(context).ToLocalChecked();" ) .normal( ...required.map(argv => { return `${inName(argv)}[i] = Nan::Get(inObject, ${inName( argv )}Name).ToLocalChecked()->NumberValue(context).FromJust();`; }) ) .undent("}") .normal( ...optional.map((argv, index) => { index += 1 + doubleRequired.length; const type = optType(argv); const check = type === "double" ? "Number" : "Int32"; const cast = type === "TA_MAType" ? "(TA_MAType) " : ""; return ( `${optName( argv )} = argc > ${index} && info[${index}]->Is${check}()` + ` ? ${cast} info[${index}]->${check}Value(context).FromJust() : ${optName( argv )};` ); }) ) .normal( ...["startIdx", "endIdx"].map((name, index) => { index += 1 + doubleRequired.length + optional.length; return `${name} = argc > ${index} && info[${index}]->IsInt32() ? info[${index}]->Int32Value(context).FromJust() : ${name};`; }) ) .undent("}") .normal("if (startIdx < 0 || endIdx >= inLength || startIdx > endIdx) {") .indent('Nan::ThrowRangeError("`startIdx` or `endIdx` out of range");') .normal("return;") .undent("}") .normal( `int lookback = TA_${name}_Lookback(${optional .map(argv => optName(argv)) .join(", ")});` ) .normal("int temp = lookback > startIdx ? lookback : startIdx;") .normal("outLength = temp > endIdx ? 0 : endIdx - temp + 1;") .normal("if (outLength == 0) {") .indent(...outInitJS) .normal(returnStatement) .normal("return;") .undent("}") .normal( ...output.map( argv => `${outType(argv)} *${outName(argv)} = new ${outType( argv )}[outLength];` ) ) .normal( `TA_RetCode result = TA_${name}(startIdx, endIdx, ` + required.map(argv => inName(argv)).join(", ") + (required.length > 0 ? ", " : "") + optional.map(argv => optName(argv)).join(", ") + (optional.length > 0 ? ", " : "") + "&outBegIdx, &outNBElement, " + output.map(argv => outName(argv)).join(", ") + ");" ) .normal("if (result != TA_SUCCESS) {") .indent(...required.map(argv => `delete[] ${inName(argv)};`)) .normal(...output.map(argv => `delete[] ${outName(argv)};`)) .normal("TA_RetCodeInfo retCodeInfo;") .normal("TA_SetRetCodeInfo(result, &retCodeInfo);") .normal("char error[100];") .normal(`strcpy(error, "TA_${name} ERROR: ");`) .normal("strcat(error, retCodeInfo.enumStr);") .normal('strcat(error, " - ");') .normal("strcat(error, retCodeInfo.infoStr);") .normal("Nan::ThrowError(error);") .normal("return;") .undent("}") .normal(...outInitJS) .normal("for (i = 0; i < (uint32_t) outLength; i++) {") .indent( ...output.map(argv => { return `Nan::Set(${jsOutName( argv )}, i, Nan::New<v8::Number>(${outName(argv)}[i]));`; }) ) .undent("}") .normal(returnStatement) .normal(...required.map(argv => `delete[] ${inName(argv)};`)) .normal(...output.map(argv => `delete[] ${outName(argv)};`)) .undent("}", "", ""); footer.normal( `Nan::Set(exports, Nan::New("${name}").ToLocalChecked(), Nan::New<v8::FunctionTemplate>(TA_FUNC_${name})->GetFunction(Nan::GetCurrentContext()).ToLocalChecked());` ); }); footer .normal("v8::Local<v8::Object> MATypes = Nan::New<v8::Object>();") .normal( ...Object.keys(TA_MATypes).map(value => { const [, , name] = TA_MATypes[value].split("_"); return `Nan::Set(MATypes, Nan::New("${name}").ToLocalChecked(), Nan::New<v8::Number>(${value}));`; }) ) .normal('Nan::Set(exports, Nan::New("MATypes").ToLocalChecked(), MATypes);') .undent("}") .normal("") .normal("NODE_MODULE(talib_binding, Init)", ""); fs.writeFileSync( __dirname + "/talib-binding.generated.cc", body.build() + footer.build() ); } export function generateTypes() { const config: TaFuncApiXml = require("./ta_func_api.generated.json"); const body = new ContentBuilder(); body .normal( "/*!", " * This file is generated by generate.ts, do not edit it.", " */", "" ) .normal("export declare enum MATypes {") .indent( ...Object.keys(TA_MATypes).map(value => { const [, , name] = TA_MATypes[value].split("_"); return `${name} = ${value},`; }) ) .undent("}") .normal("") .normal("export declare interface Record {") .indent("Time: number;") .normal("Open: number;") .normal("High: number;") .normal("Low: number;") .normal("Close: number;") .normal("Volume: number;") .undent("}", ""); config.FinancialFunctions.FinancialFunction.forEach(func => { const name = func.Abbreviation[0]; const required: RequiredInputArgument[] = func.RequiredInputArguments ? func.RequiredInputArguments.reduce( (prev, curr) => { return curr.RequiredInputArgument ? prev.concat(curr.RequiredInputArgument) : prev; }, [] as RequiredInputArgument[] ) : []; const optional: OptionalInputArgument[] = func.OptionalInputArguments ? func.OptionalInputArguments.reduce( (prev, curr) => { return curr.OptionalInputArgument ? prev.concat(curr.OptionalInputArgument) : prev; }, [] as OptionalInputArgument[] ) : []; const output: OutputArgument[] = func.OutputArguments ? func.OutputArguments.reduce( (prev, curr) => { return curr.OutputArgument ? prev.concat(curr.OutputArgument) : prev; }, [] as OutputArgument[] ) : []; const doubleRequired = required.filter( argv => RecordFields.indexOf(argv.Type[0]) === -1 ); body .normal("/**", ` * ${name} - ${func.ShortDescription[0]}`, " *") .normal( ...required.map(argv => { return ` * @param {number[]} ${inName(argv)} - ${argv.Type[0]}`; }) ) .normal( ...optional.map(argv => { return ` * @param {${optType(argv, true)}} [${optName(argv)}=${optDft( argv, true )}] - ${argv.ShortDescription[0]}`; }) ) .normal( " * @param {number} [startIdx=0] - The start index to process", " * @param {number} [endIdx=inLength-1] - The end index to process, please not that the value is included, default is the input records length - 1" ) .normal( output.length === 1 ? ` * @returns {number[]} - ${output[0].Name[0]} (${ output[0].Type[0] })` : ` * @returns {[${output .map(() => "number[]") .join(", ")}]} - [${output.map(argv => argv.Name[0]).join(", ")}]` ) .normal(" */") .normal( `export declare function ${name}(` + required.map(argv => inName(argv) + ": number[]").join(", ") + (required.length > 0 ? ", " : "") + optional .map(argv => optName(argv) + "?: " + optType(argv, true)) .join(", ") + (optional.length > 0 ? ", " : "") + "startIdx?: number, endIdx?: number): " + (output.length === 1 ? "number[]" : `[${output.map(() => "number[]").join(", ")}]`) + ";" ) .normal( "/**", ` * ${name} - ${func.ShortDescription[0]}`, " *", " * @param {Record[]} inRecords - The records to extract data" ) .normal( ...doubleRequired.map(argv => { return ` * @param {string} ${inName( argv )}Name - The field name to extract from \`inRecords\``; }) ) .normal( ...optional.map(argv => { return ` * @param {${optType(argv, true)}} [${optName(argv)}=${optDft( argv, true )}] - ${argv.ShortDescription[0]}`; }) ) .normal( " * @param {number} [startIdx=0] - The start index to process", " * @param {number} [endIdx=inLength - 1] - The end index to process, please not that the value is included, default is the input records length - 1" ) .normal( output.length === 1 ? ` * @returns {number[]} - ${output[0].Name[0]} (${ output[0].Type[0] })` : ` * @returns {[${output .map(() => "number[]") .join(", ")}]} - [${output.map(argv => argv.Name[0]).join(", ")}]` ) .normal(" */") .normal( `export declare function ${name}(` + "inRecords: Record[], " + doubleRequired.map(argv => inName(argv) + "Name: string, ").join("") + optional .map(argv => optName(argv) + "?: " + optType(argv, true) + ", ") .join("") + "startIdx?: number, endIdx?: number): " + (output.length === 1 ? "number[]" : `[${output.map(() => "number[]").join(", ")}]`) + ";" ) .normal(""); }); fs.writeFileSync(__dirname + "/talib-binding.generated.d.ts", body.build()); } export function generateGyp() { const sources = G.sync( "ta-lib/c/src/{ta_abstract,ta_common,ta_func}/**/!(ta_java_defs|excel_glue).c", { cwd: __dirname + "/..", nodir: true } ); const includes = G.sync( "ta-lib/c/{include,src/{ta_abstract,ta_common,ta_func}/**}/", { cwd: __dirname + "/..", nodir: false } ); sources.push("src/talib-binding.generated.cc"); includes.push("<!(node -e \"require('nan')\")"); const config: any = { targets: [ { target_name: "talib_binding", sources: sources, include_dirs: includes } ] }; fs.writeFileSync( __dirname + "/../binding.gyp", JSON.stringify(config, void 0, 2) ); } piclick(module);
the_stack
import { ServiceClient, ServiceClientOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from "./models"; export default class PredictionAPIClient extends ServiceClient { /** * @class * Initializes a new instance of the PredictionAPIClient class. * @constructor * * @param {string} apiKey - API key. * * @param {string} endpoint - Supported Cognitive Services endpoints. * * @param {object} [options] - The parameter options * * @param {Array} [options.filters] - Filters to be added to the request pipeline * * @param {object} [options.requestOptions] - Options for the underlying request object * {@link https://github.com/request/request#requestoptions-callback Options doc} * * @param {boolean} [options.noRetryPolicy] - If set to true, turn off default retry policy * */ constructor(apiKey: string, endpoint: string, options?: ServiceClientOptions); apiKey: string; endpoint: string; /** * @summary Classify an image url and saves the result. * * @param {uuid} projectId The project id. * * @param {string} publishedName Specifies the name of the model to evaluate * against. * * @param {object} imageUrl An ImageUrl that contains the url of the image to * be evaluated. * * @param {string} imageUrl.url Url of the image. * * @param {object} [options] Optional Parameters. * * @param {string} [options.application] Optional. Specifies the name of * application using the endpoint. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ImagePrediction>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ classifyImageUrlWithHttpOperationResponse(projectId: string, publishedName: string, imageUrl: models.ImageUrl, options?: { application? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ImagePrediction>>; /** * @summary Classify an image url and saves the result. * * @param {uuid} projectId The project id. * * @param {string} publishedName Specifies the name of the model to evaluate * against. * * @param {object} imageUrl An ImageUrl that contains the url of the image to * be evaluated. * * @param {string} imageUrl.url Url of the image. * * @param {object} [options] Optional Parameters. * * @param {string} [options.application] Optional. Specifies the name of * application using the endpoint. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ImagePrediction} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ImagePrediction} [result] - The deserialized result object if an error did not occur. * See {@link ImagePrediction} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ classifyImageUrl(projectId: string, publishedName: string, imageUrl: models.ImageUrl, options?: { application? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ImagePrediction>; classifyImageUrl(projectId: string, publishedName: string, imageUrl: models.ImageUrl, callback: ServiceCallback<models.ImagePrediction>): void; classifyImageUrl(projectId: string, publishedName: string, imageUrl: models.ImageUrl, options: { application? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ImagePrediction>): void; /** * @summary Classify an image and saves the result. * * @param {uuid} projectId The project id. * * @param {string} publishedName Specifies the name of the model to evaluate * against. * * @param {object} imageData Binary image data. Supported formats are JPEG, * GIF, PNG, and BMP. Supports images up to 4MB. * * @param {object} [options] Optional Parameters. * * @param {string} [options.application] Optional. Specifies the name of * application using the endpoint. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ImagePrediction>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ classifyImageWithHttpOperationResponse(projectId: string, publishedName: string, imageData: stream.Readable, options?: { application? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ImagePrediction>>; /** * @summary Classify an image and saves the result. * * @param {uuid} projectId The project id. * * @param {string} publishedName Specifies the name of the model to evaluate * against. * * @param {object} imageData Binary image data. Supported formats are JPEG, * GIF, PNG, and BMP. Supports images up to 4MB. * * @param {object} [options] Optional Parameters. * * @param {string} [options.application] Optional. Specifies the name of * application using the endpoint. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ImagePrediction} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ImagePrediction} [result] - The deserialized result object if an error did not occur. * See {@link ImagePrediction} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ classifyImage(projectId: string, publishedName: string, imageData: stream.Readable, options?: { application? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ImagePrediction>; classifyImage(projectId: string, publishedName: string, imageData: stream.Readable, callback: ServiceCallback<models.ImagePrediction>): void; classifyImage(projectId: string, publishedName: string, imageData: stream.Readable, options: { application? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ImagePrediction>): void; /** * @summary Classify an image url without saving the result. * * @param {uuid} projectId The project id. * * @param {string} publishedName Specifies the name of the model to evaluate * against. * * @param {object} imageUrl An {Iris.Web.Api.Models.ImageUrl} that contains the * url of the image to be evaluated. * * @param {string} imageUrl.url Url of the image. * * @param {object} [options] Optional Parameters. * * @param {string} [options.application] Optional. Specifies the name of * application using the endpoint. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ImagePrediction>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ classifyImageUrlWithNoStoreWithHttpOperationResponse(projectId: string, publishedName: string, imageUrl: models.ImageUrl, options?: { application? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ImagePrediction>>; /** * @summary Classify an image url without saving the result. * * @param {uuid} projectId The project id. * * @param {string} publishedName Specifies the name of the model to evaluate * against. * * @param {object} imageUrl An {Iris.Web.Api.Models.ImageUrl} that contains the * url of the image to be evaluated. * * @param {string} imageUrl.url Url of the image. * * @param {object} [options] Optional Parameters. * * @param {string} [options.application] Optional. Specifies the name of * application using the endpoint. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ImagePrediction} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ImagePrediction} [result] - The deserialized result object if an error did not occur. * See {@link ImagePrediction} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ classifyImageUrlWithNoStore(projectId: string, publishedName: string, imageUrl: models.ImageUrl, options?: { application? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ImagePrediction>; classifyImageUrlWithNoStore(projectId: string, publishedName: string, imageUrl: models.ImageUrl, callback: ServiceCallback<models.ImagePrediction>): void; classifyImageUrlWithNoStore(projectId: string, publishedName: string, imageUrl: models.ImageUrl, options: { application? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ImagePrediction>): void; /** * @summary Classify an image without saving the result. * * @param {uuid} projectId The project id. * * @param {string} publishedName Specifies the name of the model to evaluate * against. * * @param {object} imageData Binary image data. Supported formats are JPEG, * GIF, PNG, and BMP. Supports images up to 0MB. * * @param {object} [options] Optional Parameters. * * @param {string} [options.application] Optional. Specifies the name of * application using the endpoint. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ImagePrediction>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ classifyImageWithNoStoreWithHttpOperationResponse(projectId: string, publishedName: string, imageData: stream.Readable, options?: { application? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ImagePrediction>>; /** * @summary Classify an image without saving the result. * * @param {uuid} projectId The project id. * * @param {string} publishedName Specifies the name of the model to evaluate * against. * * @param {object} imageData Binary image data. Supported formats are JPEG, * GIF, PNG, and BMP. Supports images up to 0MB. * * @param {object} [options] Optional Parameters. * * @param {string} [options.application] Optional. Specifies the name of * application using the endpoint. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ImagePrediction} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ImagePrediction} [result] - The deserialized result object if an error did not occur. * See {@link ImagePrediction} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ classifyImageWithNoStore(projectId: string, publishedName: string, imageData: stream.Readable, options?: { application? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ImagePrediction>; classifyImageWithNoStore(projectId: string, publishedName: string, imageData: stream.Readable, callback: ServiceCallback<models.ImagePrediction>): void; classifyImageWithNoStore(projectId: string, publishedName: string, imageData: stream.Readable, options: { application? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ImagePrediction>): void; /** * @summary Detect objects in an image url and saves the result. * * @param {uuid} projectId The project id. * * @param {string} publishedName Specifies the name of the model to evaluate * against. * * @param {object} imageUrl An ImageUrl that contains the url of the image to * be evaluated. * * @param {string} imageUrl.url Url of the image. * * @param {object} [options] Optional Parameters. * * @param {string} [options.application] Optional. Specifies the name of * application using the endpoint. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ImagePrediction>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ detectImageUrlWithHttpOperationResponse(projectId: string, publishedName: string, imageUrl: models.ImageUrl, options?: { application? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ImagePrediction>>; /** * @summary Detect objects in an image url and saves the result. * * @param {uuid} projectId The project id. * * @param {string} publishedName Specifies the name of the model to evaluate * against. * * @param {object} imageUrl An ImageUrl that contains the url of the image to * be evaluated. * * @param {string} imageUrl.url Url of the image. * * @param {object} [options] Optional Parameters. * * @param {string} [options.application] Optional. Specifies the name of * application using the endpoint. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ImagePrediction} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ImagePrediction} [result] - The deserialized result object if an error did not occur. * See {@link ImagePrediction} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ detectImageUrl(projectId: string, publishedName: string, imageUrl: models.ImageUrl, options?: { application? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ImagePrediction>; detectImageUrl(projectId: string, publishedName: string, imageUrl: models.ImageUrl, callback: ServiceCallback<models.ImagePrediction>): void; detectImageUrl(projectId: string, publishedName: string, imageUrl: models.ImageUrl, options: { application? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ImagePrediction>): void; /** * @summary Detect objects in an image and saves the result. * * @param {uuid} projectId The project id. * * @param {string} publishedName Specifies the name of the model to evaluate * against. * * @param {object} imageData Binary image data. Supported formats are JPEG, * GIF, PNG, and BMP. Supports images up to 4MB. * * @param {object} [options] Optional Parameters. * * @param {string} [options.application] Optional. Specifies the name of * application using the endpoint. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ImagePrediction>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ detectImageWithHttpOperationResponse(projectId: string, publishedName: string, imageData: stream.Readable, options?: { application? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ImagePrediction>>; /** * @summary Detect objects in an image and saves the result. * * @param {uuid} projectId The project id. * * @param {string} publishedName Specifies the name of the model to evaluate * against. * * @param {object} imageData Binary image data. Supported formats are JPEG, * GIF, PNG, and BMP. Supports images up to 4MB. * * @param {object} [options] Optional Parameters. * * @param {string} [options.application] Optional. Specifies the name of * application using the endpoint. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ImagePrediction} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ImagePrediction} [result] - The deserialized result object if an error did not occur. * See {@link ImagePrediction} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ detectImage(projectId: string, publishedName: string, imageData: stream.Readable, options?: { application? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ImagePrediction>; detectImage(projectId: string, publishedName: string, imageData: stream.Readable, callback: ServiceCallback<models.ImagePrediction>): void; detectImage(projectId: string, publishedName: string, imageData: stream.Readable, options: { application? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ImagePrediction>): void; /** * @summary Detect objects in an image url without saving the result. * * @param {uuid} projectId The project id. * * @param {string} publishedName Specifies the name of the model to evaluate * against. * * @param {object} imageUrl An {Iris.Web.Api.Models.ImageUrl} that contains the * url of the image to be evaluated. * * @param {string} imageUrl.url Url of the image. * * @param {object} [options] Optional Parameters. * * @param {string} [options.application] Optional. Specifies the name of * application using the endpoint. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ImagePrediction>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ detectImageUrlWithNoStoreWithHttpOperationResponse(projectId: string, publishedName: string, imageUrl: models.ImageUrl, options?: { application? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ImagePrediction>>; /** * @summary Detect objects in an image url without saving the result. * * @param {uuid} projectId The project id. * * @param {string} publishedName Specifies the name of the model to evaluate * against. * * @param {object} imageUrl An {Iris.Web.Api.Models.ImageUrl} that contains the * url of the image to be evaluated. * * @param {string} imageUrl.url Url of the image. * * @param {object} [options] Optional Parameters. * * @param {string} [options.application] Optional. Specifies the name of * application using the endpoint. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ImagePrediction} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ImagePrediction} [result] - The deserialized result object if an error did not occur. * See {@link ImagePrediction} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ detectImageUrlWithNoStore(projectId: string, publishedName: string, imageUrl: models.ImageUrl, options?: { application? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ImagePrediction>; detectImageUrlWithNoStore(projectId: string, publishedName: string, imageUrl: models.ImageUrl, callback: ServiceCallback<models.ImagePrediction>): void; detectImageUrlWithNoStore(projectId: string, publishedName: string, imageUrl: models.ImageUrl, options: { application? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ImagePrediction>): void; /** * @summary Detect objects in an image without saving the result. * * @param {uuid} projectId The project id. * * @param {string} publishedName Specifies the name of the model to evaluate * against. * * @param {object} imageData Binary image data. Supported formats are JPEG, * GIF, PNG, and BMP. Supports images up to 0MB. * * @param {object} [options] Optional Parameters. * * @param {string} [options.application] Optional. Specifies the name of * application using the endpoint. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ImagePrediction>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ detectImageWithNoStoreWithHttpOperationResponse(projectId: string, publishedName: string, imageData: stream.Readable, options?: { application? : string, customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ImagePrediction>>; /** * @summary Detect objects in an image without saving the result. * * @param {uuid} projectId The project id. * * @param {string} publishedName Specifies the name of the model to evaluate * against. * * @param {object} imageData Binary image data. Supported formats are JPEG, * GIF, PNG, and BMP. Supports images up to 0MB. * * @param {object} [options] Optional Parameters. * * @param {string} [options.application] Optional. Specifies the name of * application using the endpoint. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ImagePrediction} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ImagePrediction} [result] - The deserialized result object if an error did not occur. * See {@link ImagePrediction} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ detectImageWithNoStore(projectId: string, publishedName: string, imageData: stream.Readable, options?: { application? : string, customHeaders? : { [headerName: string]: string; } }): Promise<models.ImagePrediction>; detectImageWithNoStore(projectId: string, publishedName: string, imageData: stream.Readable, callback: ServiceCallback<models.ImagePrediction>): void; detectImageWithNoStore(projectId: string, publishedName: string, imageData: stream.Readable, options: { application? : string, customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ImagePrediction>): void; } export { PredictionAPIClient, models as PredictionAPIModels };
the_stack
import { localize } from 'vs/nls'; import { deepClone } from 'vs/base/common/objects'; import { isObject, isArray, assertIsDefined, withUndefinedAsNull, withNullAsUndefined } from 'vs/base/common/types'; import { ICodeEditor, IDiffEditor } from 'vs/editor/browser/editorBrowser'; import { IDiffEditorOptions, IEditorOptions as ICodeEditorOptions } from 'vs/editor/common/config/editorOptions'; import { AbstractTextEditor, IEditorConfiguration } from 'vs/workbench/browser/parts/editor/textEditor'; import { TEXT_DIFF_EDITOR_ID, IEditorFactoryRegistry, EditorExtensions, ITextDiffEditorPane, IEditorOpenContext, EditorInputCapabilities, isEditorInput, isTextEditorViewState } from 'vs/workbench/common/editor'; import { EditorInput } from 'vs/workbench/common/editor/editorInput'; import { applyTextEditorOptions } from 'vs/workbench/common/editor/editorOptions'; import { DiffEditorInput } from 'vs/workbench/common/editor/diffEditorInput'; import { DiffNavigator } from 'vs/editor/browser/widget/diffNavigator'; import { DiffEditorWidget } from 'vs/editor/browser/widget/diffEditorWidget'; import { TextDiffEditorModel } from 'vs/workbench/common/editor/textDiffEditorModel'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IStorageService } from 'vs/platform/storage/common/storage'; import { ITextResourceConfigurationService } from 'vs/editor/common/services/textResourceConfiguration'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { IThemeService } from 'vs/platform/theme/common/themeService'; import { TextFileOperationError, TextFileOperationResult } from 'vs/workbench/services/textfile/common/textfiles'; import { ScrollType, IDiffEditorViewState, IDiffEditorModel } from 'vs/editor/common/editorCommon'; import { DisposableStore } from 'vs/base/common/lifecycle'; import { Registry } from 'vs/platform/registry/common/platform'; import { URI } from 'vs/base/common/uri'; import { IEditorGroup, IEditorGroupsService } from 'vs/workbench/services/editor/common/editorGroupsService'; import { IEditorService } from 'vs/workbench/services/editor/common/editorService'; import { CancellationToken } from 'vs/base/common/cancellation'; import { EditorActivation, ITextEditorOptions } from 'vs/platform/editor/common/editor'; import { IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { isEqual } from 'vs/base/common/resources'; import { Dimension, multibyteAwareBtoa } from 'vs/base/browser/dom'; import { IFileService } from 'vs/platform/files/common/files'; /** * The text editor that leverages the diff text editor for the editing experience. */ export class TextDiffEditor extends AbstractTextEditor<IDiffEditorViewState> implements ITextDiffEditorPane { static readonly ID = TEXT_DIFF_EDITOR_ID; private diffEditorControl: IDiffEditor | undefined = undefined; private diffNavigator: DiffNavigator | undefined; private readonly diffNavigatorDisposables = this._register(new DisposableStore()); override get scopedContextKeyService(): IContextKeyService | undefined { if (!this.diffEditorControl) { return undefined; } const originalEditor = this.diffEditorControl.getOriginalEditor(); const modifiedEditor = this.diffEditorControl.getModifiedEditor(); return (originalEditor.hasTextFocus() ? originalEditor : modifiedEditor).invokeWithinContext(accessor => accessor.get(IContextKeyService)); } constructor( @ITelemetryService telemetryService: ITelemetryService, @IInstantiationService instantiationService: IInstantiationService, @IStorageService storageService: IStorageService, @ITextResourceConfigurationService configurationService: ITextResourceConfigurationService, @IEditorService editorService: IEditorService, @IThemeService themeService: IThemeService, @IEditorGroupsService editorGroupService: IEditorGroupsService, @IFileService fileService: IFileService ) { super(TextDiffEditor.ID, telemetryService, instantiationService, storageService, configurationService, themeService, editorService, editorGroupService, fileService); } override getTitle(): string { if (this.input) { return this.input.getName(); } return localize('textDiffEditor', "Text Diff Editor"); } override createEditorControl(parent: HTMLElement, configuration: ICodeEditorOptions): void { this.diffEditorControl = this._register(this.instantiationService.createInstance(DiffEditorWidget, parent, configuration, {})); } protected updateEditorControlOptions(options: ICodeEditorOptions): void { this.diffEditorControl?.updateOptions(options); } protected getMainControl(): ICodeEditor | undefined { return this.diffEditorControl?.getModifiedEditor(); } override async setInput(input: DiffEditorInput, options: ITextEditorOptions | undefined, context: IEditorOpenContext, token: CancellationToken): Promise<void> { // Dispose previous diff navigator this.diffNavigatorDisposables.clear(); // Set input and resolve await super.setInput(input, options, context, token); try { const resolvedModel = await input.resolve(); // Check for cancellation if (token.isCancellationRequested) { return undefined; } // Fallback to open as binary if not text if (!(resolvedModel instanceof TextDiffEditorModel)) { this.openAsBinary(input, options); return undefined; } // Set Editor Model const control = assertIsDefined(this.diffEditorControl); const resolvedDiffEditorModel = resolvedModel as TextDiffEditorModel; control.setModel(withUndefinedAsNull(resolvedDiffEditorModel.textDiffEditorModel)); // Restore view state (unless provided by options) let hasPreviousViewState = false; if (!isTextEditorViewState(options?.viewState)) { hasPreviousViewState = this.restoreTextDiffEditorViewState(input, options, context, control); } // Apply options to editor if any let optionsGotApplied = false; if (options) { optionsGotApplied = applyTextEditorOptions(options, control, ScrollType.Immediate); } // Diff navigator this.diffNavigator = new DiffNavigator(control, { alwaysRevealFirst: !optionsGotApplied && !hasPreviousViewState // only reveal first change if we had no options or viewstate }); this.diffNavigatorDisposables.add(this.diffNavigator); // Since the resolved model provides information about being readonly // or not, we apply it here to the editor even though the editor input // was already asked for being readonly or not. The rationale is that // a resolved model might have more specific information about being // readonly or not that the input did not have. control.updateOptions({ readOnly: resolvedDiffEditorModel.modifiedModel?.isReadonly(), originalEditable: !resolvedDiffEditorModel.originalModel?.isReadonly() }); } catch (error) { // In case we tried to open a file and the response indicates that this is not a text file, fallback to binary diff. if (this.isFileBinaryError(error)) { this.openAsBinary(input, options); return; } throw error; } } private restoreTextDiffEditorViewState(editor: DiffEditorInput, options: ITextEditorOptions | undefined, context: IEditorOpenContext, control: IDiffEditor): boolean { const editorViewState = this.loadEditorViewState(editor, context); if (editorViewState) { if (options?.selection && editorViewState.modified) { editorViewState.modified.cursorState = []; // prevent duplicate selections via options } control.restoreViewState(editorViewState); return true; } return false; } private openAsBinary(input: DiffEditorInput, options: ITextEditorOptions | undefined): void { const original = input.original; const modified = input.modified; const binaryDiffInput = this.instantiationService.createInstance(DiffEditorInput, input.getName(), input.getDescription(), original, modified, true); // Forward binary flag to input if supported const fileEditorFactory = Registry.as<IEditorFactoryRegistry>(EditorExtensions.EditorFactory).getFileEditorFactory(); if (fileEditorFactory.isFileEditor(original)) { original.setForceOpenAsBinary(); } if (fileEditorFactory.isFileEditor(modified)) { modified.setForceOpenAsBinary(); } // Replace this editor with the binary one (this.group ?? this.editorGroupService.activeGroup).replaceEditors([{ editor: input, replacement: binaryDiffInput, options: { ...options, // Make sure to not steal away the currently active group // because we are triggering another openEditor() call // and do not control the initial intent that resulted // in us now opening as binary. activation: EditorActivation.PRESERVE, pinned: this.group?.isPinned(input), sticky: this.group?.isSticky(input) } }]); } override setOptions(options: ITextEditorOptions | undefined): void { super.setOptions(options); if (options) { applyTextEditorOptions(options, assertIsDefined(this.diffEditorControl), ScrollType.Smooth); } } protected override computeConfiguration(configuration: IEditorConfiguration): ICodeEditorOptions { const editorConfiguration = super.computeConfiguration(configuration); // Handle diff editor specially by merging in diffEditor configuration if (isObject(configuration.diffEditor)) { const diffEditorConfiguration: IDiffEditorOptions = deepClone(configuration.diffEditor); // User settings defines `diffEditor.codeLens`, but here we rename that to `diffEditor.diffCodeLens` to avoid collisions with `editor.codeLens`. diffEditorConfiguration.diffCodeLens = diffEditorConfiguration.codeLens; delete diffEditorConfiguration.codeLens; // User settings defines `diffEditor.wordWrap`, but here we rename that to `diffEditor.diffWordWrap` to avoid collisions with `editor.wordWrap`. diffEditorConfiguration.diffWordWrap = <'off' | 'on' | 'inherit' | undefined>diffEditorConfiguration.wordWrap; delete diffEditorConfiguration.wordWrap; Object.assign(editorConfiguration, diffEditorConfiguration); } return editorConfiguration; } protected override getConfigurationOverrides(): IDiffEditorOptions { const readOnly = this.input instanceof DiffEditorInput && this.input.modified.hasCapability(EditorInputCapabilities.Readonly); return { ...super.getConfigurationOverrides(), readOnly, enableDropIntoEditor: !readOnly, originalEditable: this.input instanceof DiffEditorInput && !this.input.original.hasCapability(EditorInputCapabilities.Readonly), lineDecorationsWidth: '2ch' }; } protected override updateReadonly(input: EditorInput): void { if (input instanceof DiffEditorInput) { this.diffEditorControl?.updateOptions({ readOnly: input.hasCapability(EditorInputCapabilities.Readonly), originalEditable: !input.original.hasCapability(EditorInputCapabilities.Readonly), enableDropIntoEditor: !input.hasCapability(EditorInputCapabilities.Readonly) }); } else { super.updateReadonly(input); } } private isFileBinaryError(error: Error[]): boolean; private isFileBinaryError(error: Error): boolean; private isFileBinaryError(error: Error | Error[]): boolean { if (isArray(error)) { const errors = <Error[]>error; return errors.some(error => this.isFileBinaryError(error)); } return (<TextFileOperationError>error).textFileOperationResult === TextFileOperationResult.FILE_IS_BINARY; } override clearInput(): void { super.clearInput(); // Dispose previous diff navigator this.diffNavigatorDisposables.clear(); // Clear Model this.diffEditorControl?.setModel(null); } getDiffNavigator(): DiffNavigator | undefined { return this.diffNavigator; } override getControl(): IDiffEditor | undefined { return this.diffEditorControl; } override focus(): void { this.diffEditorControl?.focus(); } override hasFocus(): boolean { return this.diffEditorControl?.hasTextFocus() || super.hasFocus(); } protected override setEditorVisible(visible: boolean, group: IEditorGroup | undefined): void { super.setEditorVisible(visible, group); if (visible) { this.diffEditorControl?.onVisible(); } else { this.diffEditorControl?.onHide(); } } override layout(dimension: Dimension): void { this.diffEditorControl?.layout(dimension); } protected override tracksEditorViewState(input: EditorInput): boolean { return input instanceof DiffEditorInput; } protected override computeEditorViewState(resource: URI): IDiffEditorViewState | undefined { if (!this.diffEditorControl) { return undefined; } const model = this.diffEditorControl.getModel(); if (!model || !model.modified || !model.original) { return undefined; // view state always needs a model } const modelUri = this.toEditorViewStateResource(model); if (!modelUri) { return undefined; // model URI is needed to make sure we save the view state correctly } if (!isEqual(modelUri, resource)) { return undefined; // prevent saving view state for a model that is not the expected one } return withNullAsUndefined(this.diffEditorControl.saveViewState()); } protected override toEditorViewStateResource(modelOrInput: IDiffEditorModel | EditorInput): URI | undefined { let original: URI | undefined; let modified: URI | undefined; if (modelOrInput instanceof DiffEditorInput) { original = modelOrInput.original.resource; modified = modelOrInput.modified.resource; } else if (!isEditorInput(modelOrInput)) { original = modelOrInput.original.uri; modified = modelOrInput.modified.uri; } if (!original || !modified) { return undefined; } // create a URI that is the Base64 concatenation of original + modified resource return URI.from({ scheme: 'diff', path: `${multibyteAwareBtoa(original.toString())}${multibyteAwareBtoa(modified.toString())}` }); } }
the_stack
import { Grid } from '../../../src/grid/base/grid'; import { Page } from '../../../src/grid/actions/page'; import { Freeze } from '../../../src/grid/actions/freeze'; import { data } from '../base/datasource.spec'; import '../../../node_modules/es6-promise/dist/es6-promise'; import { createGrid, destroy } from '../base/specutil.spec'; import {profile , inMB, getMemoryProfile} from '../base/common.spec'; Grid.Inject(Page, Freeze); describe('auto wrap testing', () => { describe('auto wrap properties', () => { let gridObj: Grid; let actionComplete: (e?: Object) => void; beforeAll((done: Function) => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) } gridObj = createGrid( { dataSource: data, allowPaging: false, columns: [ { headerText: 'OrderID', field: 'OrderID' }, { headerText: 'CustomerID', field: 'CustomerID' }, { headerText: 'EmployeeID', field: 'EmployeeID' }, { headerText: 'ShipCountry', field: 'ShipCountry' }, { headerText: 'ShipCity', field: 'ShipCity' }, ], allowTextWrap: true, textWrapSettings: { wrapMode: 'Header' }, actionComplete: actionComplete, }, done); }); it('class testing for header', () => { expect(gridObj.element.classList.contains('e-wrap')).toBeFalsy(); expect(gridObj.element.querySelector('.e-columnheader').classList.contains('e-wrap')).toBeTruthy(); expect(gridObj.getContent().classList.contains('e-wrap')).toBeFalsy(); }); it('class testing for content', () => { gridObj.textWrapSettings.wrapMode = 'Content'; gridObj.dataBind(); expect(gridObj.element.classList.contains('e-wrap')).toBeFalsy(); expect(gridObj.element.querySelector('.e-columnheader').classList.contains('e-wrap')).toBeFalsy(); expect(gridObj.getContent().classList.contains('e-wrap')).toBeTruthy(); }); it('class testing for both', () => { gridObj.textWrapSettings.wrapMode = 'Both'; gridObj.dataBind(); expect(gridObj.element.classList.contains('e-wrap')).toBeTruthy(); expect(gridObj.element.querySelector('.e-columnheader').classList.contains('e-wrap')).toBeFalsy(); expect(gridObj.getContent().classList.contains('e-wrap')).toBeFalsy(); }); it('class testing for auto wrap property as false', () => { gridObj.allowTextWrap = false; gridObj.textWrapSettings.wrapMode = 'Both'; gridObj.dataBind(); expect(gridObj.element.classList.contains('e-wrap')).toBeFalsy(); expect(gridObj.element.querySelector('.e-columnheader').classList.contains('e-wrap')).toBeFalsy(); expect(gridObj.getContent().classList.contains('e-wrap')).toBeFalsy(); }); afterAll(() => { destroy(gridObj); gridObj = actionComplete = null; }); }); describe('auto wrap properties for stacked headercolumns', () => { let gridObj: Grid; let actionComplete: (e?: Object) => void; beforeAll((done: Function) => { gridObj = createGrid( { dataSource: data, allowPaging: false, columns: [{ headerText: 'Detail of the order', columns: [{ headerText: 'OrderID', field: 'OrderID' }, { headerText: 'CustomerID', field: 'CustomerID' }, { headerText: 'EmployeeID', field: 'EmployeeID' } ] }, { headerText: 'Details of shipping', columns: [{ headerText: 'ShipCountry', field: 'ShipCountry' }, { headerText: 'ShipCity', field: 'ShipCity' }] } ], allowTextWrap: true, textWrapSettings: { wrapMode: 'Header' }, actionComplete: actionComplete, }, done); }); it('class testing for header in stackedheadercolumns', () => { expect(gridObj.element.classList.contains('e-wrap')).toBeFalsy(); let headerRows: Element[] = [].slice.call(gridObj.element.querySelectorAll('.e-columnheader')); for (let i: number = 0; i < headerRows.length; i++) { expect(headerRows[i].classList.contains('e-wrap')).toBeTruthy(); } expect(gridObj.getContent().classList.contains('e-wrap')).toBeFalsy(); }); afterAll(() => { destroy(gridObj); gridObj = actionComplete = null; }); }); describe('auto wrap properties for GroupedColumns', () => { let gridObj: Grid; let actionComplete: (e?: Object) => void; beforeAll((done: Function) => { gridObj = createGrid( { dataSource: data, allowPaging: false, columns: [{ headerText: 'Detail of the order', columns: [{ headerText: 'OrderID', field: 'OrderID' }, { headerText: 'CustomerID', field: 'CustomerID' }, { headerText: 'EmployeeID', field: 'EmployeeID' } ] }, { headerText: 'Details of shipping', columns: [{ headerText: 'ShipCountry', field: 'ShipCountry' }, { headerText: 'ShipCity', field: 'ShipCity' }] } ], allowTextWrap: true, textWrapSettings: { wrapMode: 'Header' }, actionComplete: actionComplete, }, done); }); it('class testing for header with GroupedColumns', () => { gridObj.allowGrouping = true; gridObj.groupSettings.columns = ['CustomerID']; expect(gridObj.element.classList.contains('e-wrap')).toBeFalsy(); let headerRows: Element[] = [].slice.call(gridObj.element.querySelectorAll('.e-columnheader')); for (let i: number = 0; i < headerRows.length; i++) { expect(headerRows[i].classList.contains('e-wrap')).toBeTruthy(); } expect(gridObj.getContent().classList.contains('e-wrap')).toBeFalsy(); }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }); afterAll(() => { destroy(gridObj); gridObj = actionComplete = null; }); }); // describe('Auto wrap with Freeze', () => { // let gridObj: Grid; // beforeAll((done: Function) => { // gridObj = createGrid( // { // dataSource: data, // frozenColumns: 2, // frozenRows: 2, // columns: [{ field: 'OrderID', width: 100, headerText: 'Order IDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD' }, // { field: 'CustomerID', width: 100, headerText: 'Customer ID' }, // { field: 'EmployeeID', width: 100, headerText: 'Employee ID' }, // { field: 'ShipName', width: 100, headerText: 'Ship Name' }, // { field: 'ShipAddress', width: 100, headerText: 'Ship Address' }, // { field: 'OrderDate', headerText: 'Order Date', width: 130, format: 'yMd', textAlign: 'Right' }, // { field: 'Freight', width: 110, format: 'C2', headerText: 'Freight' }, // { field: 'ShipCountry', width: 130, headerText: 'Ship Country' }, // { field: 'Verified', headerText: 'Verified', width: 190 } // ], // allowTextWrap: true, // textWrapSettings: { wrapMode: 'Header' }, // }, done); // }); // it('comparing height', () => { // let fHdrTr: HTMLElement = gridObj.getHeaderContent().querySelector('.e-frozenheader').querySelector('tr'); // let mHdrTr: HTMLElement = gridObj.getHeaderContent().querySelector('.e-movableheader').querySelector('tr'); // let fHdrContTr: HTMLElement = gridObj.getHeaderContent() // .querySelector('.e-frozenheader').querySelector('tbody').querySelector('tr'); // let mHdrContTr: HTMLElement = gridObj.getHeaderContent() // .querySelector('.e-movableheader').querySelector('tbody').querySelector('tr'); // let fContTr: HTMLElement = gridObj.getContent().querySelector('.e-frozencontent').querySelector('tr'); // let mContTr: HTMLElement = gridObj.getContent().querySelector('.e-movablecontent').querySelector('tr'); // gridObj.textWrapSettings.wrapMode = 'Both'; // gridObj.dataBind(); // expect(fHdrTr.offsetHeight).toBe(mHdrTr.offsetHeight); // expect(fHdrContTr.offsetHeight).toBe(mHdrContTr.offsetHeight); // expect(fContTr.offsetHeight).toBe(mContTr.offsetHeight); // gridObj.textWrapSettings.wrapMode = 'Header'; // gridObj.dataBind(); // expect(fHdrTr.offsetHeight).toBe(mHdrTr.offsetHeight); // expect(fHdrContTr.offsetHeight).toBe(mHdrContTr.offsetHeight); // expect(fContTr.offsetHeight).toBe(mContTr.offsetHeight); // gridObj.textWrapSettings.wrapMode = 'Content'; // gridObj.dataBind(); // expect(fHdrTr.offsetHeight).toBe(mHdrTr.offsetHeight); // expect(fHdrContTr.offsetHeight).toBe(mHdrContTr.offsetHeight); // expect(fContTr.offsetHeight).toBe(mContTr.offsetHeight); // expect((gridObj.getHeaderContent().firstChild as Element).classList.contains('e-wrap')).toBeTruthy(); // gridObj.allowTextWrap = false; // gridObj.dataBind(); // expect(fHdrTr.offsetHeight).toBe(mHdrTr.offsetHeight); // expect(fHdrContTr.offsetHeight).toBe(mHdrContTr.offsetHeight); // expect(fContTr.offsetHeight).toBe(mContTr.offsetHeight); // }); // afterAll(() => { // destroy(gridObj); // }); // }); describe('EJ2-42308: Resize handler height with auto wrap', () => { let gridObj: Grid; let actionComplete: (e?: Object) => void; beforeAll((done: Function) => { gridObj = createGrid( { dataSource: data, allowPaging: false, width:500, allowResizing: true, allowTextWrap: true, textWrapSettings: { wrapMode: 'Header' }, columns: [{ field: 'OrderID', headerText: 'OrderID', width: 140 }, { field: 'About', headerText: 'About', width: 140, maxWidth: 300, minWidth: 200 }, { field: 'EmployeeID', headerText: 'Employee details example for checking the resize handlers', width: 130 }, { field: 'Freight', headerText: 'Freight', width: 150, allowResizing: false }, { field: 'ShipCity', headerText: 'ShipCity', width: 150 } ] }, done); }); it('checking the resize handlers height', () => { expect((gridObj.element.querySelector('.e-rhandler') as HTMLElement).style.height).toBe( gridObj.getHeaderTable().querySelector('tr').offsetHeight + 'px'); }); it('checking the resize handlers height after dynamically disabling the textWrap property', () => { gridObj.allowTextWrap = false; expect((gridObj.element.querySelector('.e-rhandler') as HTMLElement).style.height).toBe( gridObj.getHeaderTable().querySelector('tr').offsetHeight + 'px'); }); afterAll(() => { destroy(gridObj); gridObj = actionComplete = null; }); }); });
the_stack
import CircleRoundedIcon from '@mui/icons-material/CircleRounded'; import { Box, Button, Container, Stack, Tab, Tabs, Typography, } from '@mui/material'; import React, { useEffect } from 'react'; import { KubeconfigBox, FeedbackLink, LogTailerBox } from 'components'; import { GlobalAppState } from 'providers'; import { Actions, ClusterStates, IAppState, IClusterStatus, } from 'providers/globalAppState/reducer'; interface TabPanelProps { children?: React.ReactNode; index: number; value: number; } function TabPanel(props: TabPanelProps) { const { children, value, index, ...other } = props; return ( <Box sx={{ height: '100%' }} role="tabpanel" hidden={value !== index} id={`simple-tabpanel-${index}`} {...other} > {value === index && <Box sx={{ p: 3, height: '100%' }}>{children}</Box>} </Box> ); } function a11yProps(index: number) { return { id: `simple-tab-${index}`, 'aria-controls': `simple-tabpanel-${index}`, }; } export interface AppProps { createCluster?: boolean; } export default function App(props: AppProps) { const TABS = { LOGS: 0, KUBECONFIG: 1, }; // TODO: Call to create a cluster if App is invoked from Intro page const { state: appState, dispatch } = React.useContext(GlobalAppState); // First load of the page. We refresh the cluster status from backend to verify it matches localStorage // TODO: See if we can move this to the intro screen or somewhere that can execute faster // TODO: Also, have a periodic sync of state useEffect(() => { if (props.createCluster) createCluster(); window.ddClient.extension.vm.cli .exec(`/backend/clustermgr`, [`status`]) .then((cmdResult: any) => { let status: IClusterStatus = cmdResult.parseJsonObject(); if ( status.status !== appState.clusterStatus.status || status.description !== appState.clusterStatus.description ) { // Depends on what's the new state, do some other actions if (status.status === ClusterStates.DELETED) { dispatch({ type: 'CLUSTER_LOGS', payload: [] } as Actions); dispatch({ type: 'FETCH_KUBECONFIG', payload: '' } as Actions); dispatch({ type: 'CLUSTER_STARTED', payload: false } as Actions); } dispatch({ type: 'CLUSTER_STATUS', payload: status } as Actions); } }); }, []); // Update other states based on cluster status useEffect(() => { let interval: any = null; if (appState.clusterStatus.status === ClusterStates.RUNNING) { dispatch({ type: 'CLUSTER_STARTED', payload: true } as Actions); if (interval != undefined) clearInterval(interval); if (interval == undefined) { interval = setInterval(() => { executeWhileRunning(); }, 5000); return () => clearInterval(interval); } } else { if ( appState.clusterStatus.status === ClusterStates.CREATING || appState.clusterStatus.status === ClusterStates.INITIALIZING || appState.clusterStatus.status === ClusterStates.DELETING ) { dispatch({ type: 'CLUSTER_STARTED', payload: true } as Actions); interval = setInterval(() => { executeWhileCreating(); }, 2000); return () => clearInterval(interval); } else { if ( appState.clusterStatus.status === ClusterStates.DELETED || appState.clusterStatus.status === ClusterStates.NOT_EXISTS ) { dispatch({ type: 'CLUSTER_STARTED', payload: false } as Actions); } if (interval != undefined) clearInterval(interval); } } }, [appState.clusterStatus.status]); useEffect(() => { const textarea = document.getElementById('log'); if (textarea != null) textarea.scrollTop = textarea.scrollHeight; }, [appState.logs]); function executeWhileRunning() { getClusterStatus(); } function executeWhileCreating() { getClusterStatus(); getLogs(); } async function getClusterStatus() { await window.ddClient.extension.vm.cli .exec(`/backend/clustermgr`, [`status`]) .then((cmdResult: any) => { let status: IClusterStatus = cmdResult.parseJsonObject(); dispatch({ type: 'CLUSTER_STATUS', payload: status } as Actions); // TODO: Update other CLUSTER_STARTED based on states }); } function createCluster() { dispatch({ type: 'CLUSTER_LOGS', payload: [] } as Actions); dispatch({ type: 'FETCH_KUBECONFIG', payload: '' } as Actions); dispatch({ type: 'CLUSTER_STARTED', payload: true } as Actions); dispatch({ type: 'CLUSTER_STATUS', payload: { status: ClusterStates.CREATING, description: 'Cluster creating', }, } as Actions); window.ddClient.extension.vm.cli .exec(`/backend/clustermgr`, [`create`]) .then((cmdResult: any) => { let status: IClusterStatus = cmdResult.parseJsonObject(); }); setSelectedTab(TABS.LOGS); } function deleteCluster() { dispatch({ type: 'CLUSTER_LOGS', payload: [] } as Actions); dispatch({ type: 'FETCH_KUBECONFIG', payload: '' } as Actions); dispatch({ type: 'CLUSTER_STARTED', payload: false } as Actions); dispatch({ type: 'CLUSTER_STATUS', payload: { status: ClusterStates.DELETING, description: 'Cluster is being deleted', }, } as Actions); window.ddClient.extension.vm.cli .exec(`/backend/clustermgr`, [`delete`]) .then((cmdResult: any) => { let status: IClusterStatus = cmdResult.parseJsonObject(); }); setSelectedTab(TABS.LOGS); } function getClusterKubeconfig() { if (appState.clusterStatus.status === ClusterStates.RUNNING) { window.ddClient.extension.vm.cli .exec(`/backend/clustermgr`, [`kubeconfig`]) .then((cmdResult: any) => { let status: IClusterStatus = cmdResult.parseJsonObject(); dispatch({ type: 'FETCH_KUBECONFIG', payload: status.output, } as Actions); }); // setSelectedTab(TABS.KUBECONFIG); } } async function getLogs() { if (appState.clusterStatus.status != ClusterStates.DELETED) { window.ddClient.extension.vm.cli .exec(`/backend/clustermgr`, [`logs`]) // cluster-create-logs .then((cmdResult: any) => { let status: IClusterStatus = cmdResult.parseJsonObject(); let logs: string[] = []; logs[0] = status.output || ''; // TODO: Convert string to string[] dispatch({ type: 'CLUSTER_LOGS', payload: logs } as Actions); }); } } const [selectedTab, setSelectedTab] = React.useState(0); const selectTab = (event: React.SyntheticEvent, newValue: number) => { if (newValue === TABS.LOGS) { getLogs(); } // Start a trigger to refresh stats every 2 seconds while the Stats tab is selected setSelectedTab(newValue); }; function clusterStateIcon(state: IAppState) { let showIcon: boolean = true; let iconColor: string = ''; switch (state.clusterStatus.status) { case ClusterStates.UNKNOWN: case ClusterStates.NOT_EXISTS: showIcon = false; break; case ClusterStates.DELETED: case ClusterStates.DELETING: case ClusterStates.ERROR: iconColor = 'red'; break; case ClusterStates.CREATING: case ClusterStates.INITIALIZING: iconColor = 'orange'; break; case ClusterStates.RUNNING: iconColor = 'green'; break; } return ( <CircleRoundedIcon sx={{ fontSize: 12 }} style={{ color: iconColor }} /> ); } return ( <Container> <FeedbackLink /> <Stack spacing={2}> <Box py={5} textAlign="left" alignItems="left" sx={{ height: '25vh' }}> <Stack direction="row" sx={{ display: 'flex', justifyContent: 'space-between' }} > <Stack sx={{ display: 'flex', justifyContent: 'space-between' }}> <Box sx={{ mt: 2 }}> <img src="TCE-logo.svg" width="300" className="Header-logo" alt="logo" /> </Box> <Box sx={{ ml: 11 }}> <Typography style={{ fontWeight: 600 }}> {' '} {clusterStateIcon(appState)} {' '} {appState.clusterStatus?.description} {appState.clusterStatus?.errorMessage && appState.clusterStatus?.errorMessage !== '' ? '. ' : ''} {appState.clusterStatus?.errorMessage} </Typography> </Box> </Stack> <Stack sx={{ mt: 4, display: 'flex', alignItems: 'center', width: '50%', justifyContent: 'right', }} direction="row" spacing={2} justifyContent="center" > {(appState.clusterStatus.status === ClusterStates.DELETED || appState.clusterStatus.status === ClusterStates.NOT_EXISTS) && ( <Button variant="contained" onClick={createCluster}> Create </Button> )} {(appState.clusterStatus.status === ClusterStates.RUNNING || appState.clusterStatus.status === ClusterStates.ERROR) && ( <Button variant="contained" onClick={deleteCluster}> Delete </Button> )} </Stack> </Stack> </Box> <Box sx={{ width: '100%', height: '65vh' }}> <Box sx={{ borderBottom: 1, borderColor: 'divider' }}> <Tabs value={selectedTab} onChange={selectTab}> <Tab label="Logs" {...a11yProps(TABS.LOGS)} /> {appState.clusterStatus.status === ClusterStates.RUNNING && ( <Tab label="KubeConfig" {...a11yProps(TABS.KUBECONFIG)} onClick={getClusterKubeconfig} /> )} </Tabs> </Box> <TabPanel value={selectedTab} index={TABS.LOGS}> <LogTailerBox log={appState.logs} /> </TabPanel> <TabPanel value={selectedTab} index={TABS.KUBECONFIG}> <KubeconfigBox kubeconfig={appState.kubeconfig} /> </TabPanel> </Box> </Stack> </Container> ); }
the_stack
* Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. */ import {Command, flags, CLIError} from '@microsoft/bf-cli-command' import {Helper, TranslateLine, PARSERCONSTS, Block, TranslateOption, TranslateParts} from '../../utils' import * as txtfile from 'read-text-file' import * as path from 'path' import * as fs from 'fs-extra' import * as os from 'os' export default class TranslateCommand extends Command { static description = 'Machine translate .lg files using Microsoft Translator Text API.' private readonly MAX_TRANSLATE_BATCH_SIZE = 25 private readonly MAX_CHAR_IN_REQUEST = 4990 private readonly NEWLINE = os.EOL private readonly DEFAULT_SOURCE_LANG = 'en' private readonly ImportRegex = /^\[.+\]\(.+\)$/g private readonly ConditionRegex = /^(if|(else\s*if)|else|switch|case|default)\s*:.*/gi private readonly ExpressionRegex = /(?<!\\)\$\{(('[^'\r\n]*')|("[^"\r\n]*")|(`(\\`|[^`])*`)|([^\r\n{}'"`]))+\}?/g static flags: flags.Input<any> = { in: flags.string({char: 'i', description: 'Folder that contains .lg file.', required: true}), tgtlang: flags.string({description: 'Comma separated list of target languages.', required: true}), translatekey: flags.string({description: 'Machine translation endpoint key.', required: true}), recurse: flags.boolean({char: 'r', description: 'Consider sub-folders to find .lg file(s)'}), out: flags.string({char: 'o', description: 'Output file or folder name. If not specified stdout will be used as output'}), force: flags.boolean({char: 'f', description: 'If --out flag is provided with the path to an existing file, overwrites that file'}), srclang: flags.string({description: 'Source lang code. Auto detect if missing.'}), translate_comments: flags.boolean({description: 'Machine translate all comments found in .lg file'}), translate_link_text: flags.boolean({description: 'Machine translate link description in .lg file'}), region: flags.string({description: 'The sub region.', required: true}), help: flags.help({char: 'h', description: 'lg:translate help'}), } async run() { const {flags} = this.parse(TranslateCommand) const lgFilePaths = Helper.findLGFiles(flags.in, flags.recurse) Helper.checkInputAndOutput(lgFilePaths, flags.out) for (const filePath of lgFilePaths) { await this.translateLGFile(filePath, flags) } } private async translateLGFile(filePath: string, flags: any) { let src_lang = this.DEFAULT_SOURCE_LANG if (flags.srclang) { src_lang = flags.srclang } const translateParts = new TranslateParts(Boolean(flags.translate_comments), Boolean(flags.translate_link_text)) // Support multi-language specification for targets. // Accepted formats are space or comma separated list of target language codes. // Tokenize to_lang const toLangs = flags.tgtlang.split(/[, ]/g) for (const toLang of toLangs) { const tgt_lang = toLang.trim() if (tgt_lang !== '') { const translateOption = new TranslateOption(flags.translatekey, toLang, src_lang, flags.region) const result = await this.translateLGFileToSpecificLang(filePath, translateOption, translateParts) const outputFilePath = this.getOutputFile(filePath, tgt_lang, flags.out) if (!outputFilePath) { this.log(`Translate result of file ${filePath} to ${tgt_lang}:`) this.log(result) } else { Helper.writeContentIntoFile(outputFilePath, result, flags.force) this.log(`Translate result of file ${filePath} to ${tgt_lang} has been written to ${outputFilePath}`) } } } } private getOutputFile(filePath: string, language: string, out: string|undefined): string | undefined { if (filePath === undefined || filePath === '' || out === undefined) { return undefined } const base = Helper.normalizePath(path.resolve(out)) const root = path.dirname(base) if (!fs.existsSync(root)) { throw new Error(`folder ${root} not exist`) } const extension = path.extname(base) if (extension) { // file return base } // folder // // a.lg -> a.en-us.lg const newFileName = path.basename(filePath).replace('.lg', '') + '.' + language + '.lg' return path.join(base, newFileName) } private async translateLGFileToSpecificLang( filePath: string, translateOption: TranslateOption, translateParts: TranslateParts ): Promise<string> { const fileContent = await txtfile.read(filePath) if (!fileContent) { throw new CLIError('unable to read file: ' + filePath) } const parsedLocContent = await this.parseAndTranslate(fileContent, translateOption, translateParts) if (!parsedLocContent) { throw (new CLIError('Sorry, file : ' + filePath + ' had invalid content')) } return parsedLocContent } // eslint-disable-next-line complexity private async parseAndTranslate( fileContent: string, translateOption: TranslateOption, translateParts: TranslateParts): Promise<string> { fileContent = Helper.sanitizeNewLines(fileContent) const linesInFile = fileContent.split(this.NEWLINE) let linesToTranslate: TranslateLine[] = [] let localizedContent = '' let lineCtr = 0 let inMultiLine = false let inStructure = false for (const currentLine of linesInFile) { lineCtr++ if (inStructure) { if (currentLine.trim() === PARSERCONSTS.RIGHT_SQUARE_BRACKET) { this.addSegment(linesToTranslate, currentLine, false) inStructure = false } else { // structure mode const equalIndex = currentLine.indexOf('=') if (equalIndex >= 0) { this.addSegment(linesToTranslate, currentLine.substr(0, equalIndex + 1), false) const valueString = currentLine.substr(equalIndex + 1) // handle list value const valueList = valueString.split('|') // eslint-disable-next-line max-depth for (let i = 0; i < valueList.length; i++) { this.addSegmentWithExpression(linesToTranslate, valueList[i]) // eslint-disable-next-line max-depth if (i < valueList.length - 1) { this.addSegment(linesToTranslate, '|', false) } } } else { this.addSegment(linesToTranslate, currentLine, false) } } } else if (inMultiLine) { if (currentLine.trim().endsWith(PARSERCONSTS.MULTILINE)) { inMultiLine = false } // multiline this.addSegment(linesToTranslate, currentLine, false) } else if (this.ImportRegex.test(currentLine.trim())) { // [abc](def) -> transfer abc if (translateParts.link) { const linkValueRegEx = new RegExp(/\(.*?\)/g) let linkValue = '' const linkValueList = currentLine.trim().match(linkValueRegEx) if (linkValueList && linkValueList.length > 0 && linkValueList[0]) { linkValue = linkValueList[0].replace('(', '').replace(')', '') } const linkTextRegEx = new RegExp(/\[.*\]/g) let linkTextValue = '' const linkTextList = currentLine.trim().match(linkTextRegEx) if (linkTextList && linkTextList.length > 0 && linkTextList[0]) { linkTextValue = linkTextList[0].replace('[', '').replace(']', '') } this.addSegment(linesToTranslate, '[', false) this.addSegment(linesToTranslate, linkTextValue, true) this.addSegment(linesToTranslate, ']', false) this.addSegment(linesToTranslate, '(' + linkValue + ')', false) } else { this.addSegment(linesToTranslate, currentLine, false) } // > abc -> translate abc } else if (currentLine.trim().startsWith(PARSERCONSTS.DASH) && currentLine.trim().substr(PARSERCONSTS.DASH.length).trim().startsWith(PARSERCONSTS.MULTILINE)) { // meet - ``` abc, start multi line this.addSegment(linesToTranslate, currentLine, false) inMultiLine = true } else if (currentLine.trim().startsWith(PARSERCONSTS.LEFT_SQUARE_BRACKET)) { // enter structure this.addSegment(linesToTranslate, currentLine, false) inStructure = true } else if (currentLine.trim().startsWith(PARSERCONSTS.COMMENT)) { // comments. > abc if (translateParts.comments) { const commentIndex = currentLine.trim().indexOf(PARSERCONSTS.COMMENT) this.addSegment(linesToTranslate, currentLine.substr(0, commentIndex + 1) + ' ', false) this.addSegment(linesToTranslate, currentLine.trim().substr(commentIndex + 1), true) } else { this.addSegment(linesToTranslate, currentLine, false) } } else if (currentLine.trim().startsWith(PARSERCONSTS.DASH)) { // - abc dash // 1. normal template string // 2. condition/switch expression template string // 3. condition/swich template string // 4. structure value const dashIndex = currentLine.indexOf(PARSERCONSTS.DASH) this.addSegment(linesToTranslate, currentLine.substr(0, dashIndex + 1) + ' ', false) const content = currentLine.substr(dashIndex + 1).trim() if (this.ConditionRegex.test(content)) { // condition/switch expression template string this.addSegment(linesToTranslate, content, false) } else { // other template string this.addSegmentWithExpression(linesToTranslate, content) } } else if (currentLine.trim() === '') { // do nothing } else { // add default value this.addSegment(linesToTranslate, currentLine, false) } // add new line for each line this.addSegment(linesToTranslate, this.NEWLINE, false) if ((linesToTranslate.length !== 0) && (lineCtr % this.MAX_TRANSLATE_BATCH_SIZE === 0)) { localizedContent += await this.batchTranslateText(linesToTranslate, translateOption) linesToTranslate = [] } } if ((linesToTranslate.length !== 0)) { localizedContent += await this.batchTranslateText(linesToTranslate, translateOption) linesToTranslate = [] } return localizedContent } private addSegmentWithExpression(linesToTranslate: TranslateLine[], content: string) { const blockList: Block[] = [] const expressionsFound = content.match(this.ExpressionRegex) if (expressionsFound) { for (const expression of expressionsFound) { const eStartIndex = content.indexOf(expression) const eEndIndex = eStartIndex + expression.length - 1 blockList.push(new Block(expression, eStartIndex, eEndIndex)) } } let offset = 0 let candidateText = '' // Tokenize the input utterance. for (const block of blockList) { if (block.start !== offset) { candidateText = content.substring(offset, block.start) if (candidateText.trim() !== '') { this.addSegment(linesToTranslate, candidateText, true) } else { this.addSegment(linesToTranslate, candidateText, false) } } this.addSegment(linesToTranslate, block.block, false) offset = block.end + 1 } if (offset !== content.length) { candidateText = content.substring(offset) if (candidateText.trim() !== '') { this.addSegment(linesToTranslate, candidateText, true) } else { this.addSegment(linesToTranslate, candidateText, false) } } } private addSegment(linesToTranslate: TranslateLine[], text: string, localize: boolean) { if (text.length >= this.MAX_CHAR_IN_REQUEST) { // break it up into smaller segments and add it to the batchRequest payload const splitRegExp = new RegExp(`(.{${this.MAX_CHAR_IN_REQUEST}})`) const splitLine = text.split(splitRegExp).filter(O => O) splitLine.forEach(item => { linesToTranslate.push(new TranslateLine(item, localize)) }) } else { linesToTranslate.push(new TranslateLine(text, localize)) } } private async batchTranslateText(linesToTranslate: TranslateLine[], translateOption: TranslateOption) { // responsible for breaking localizable text into chunks that are // - not more than 5000 characters in combined length // - not more than 25 segments in one chunk let retValue = '' if (!Array.isArray(linesToTranslate) || linesToTranslate.length === 0) return retValue let charCountInChunk = 0 let batchTranslate: any[] = [] for (const idx in linesToTranslate) { const item = linesToTranslate[idx] if (item.text.length + charCountInChunk >= this.MAX_CHAR_IN_REQUEST) { await this.translateAndMap(batchTranslate, translateOption, linesToTranslate) batchTranslate = [] charCountInChunk = 0 } const currentBatchSize = batchTranslate.length > 0 ? batchTranslate.length : 1 if (currentBatchSize % this.MAX_TRANSLATE_BATCH_SIZE === 0) { await this.translateAndMap(batchTranslate, translateOption, linesToTranslate) batchTranslate = [] charCountInChunk = 0 } if (item.localize) { item.idx = batchTranslate.length const textItem = { Text: item.text, } batchTranslate.push(textItem) charCountInChunk += item.text.length } } if (batchTranslate.length !== 0) { await this.translateAndMap(batchTranslate, translateOption, linesToTranslate) batchTranslate = [] charCountInChunk = 0 } for (const item of linesToTranslate) { retValue += item.text } return retValue } private async translateAndMap(batchRequest: any, translateOption: TranslateOption, linesToTranslateCopy: TranslateLine[]) { if (batchRequest.length === 0) return const data = await Helper.translateText(batchRequest, translateOption) data.forEach((item: any, idx: number) => { // find the correponding item in linesToTranslate const itemInLine = linesToTranslateCopy.find(item => item.idx === idx) if (itemInLine) { itemInLine.text = item.translations[0].text itemInLine.idx = -1 } }) } }
the_stack
import { TypedEvent, TypedEventBase } from "../events/EventBase"; import { arrayProgress } from "../tasks/arrayProgress"; import type { progressCallback } from "../tasks/progressCallback"; import { assertNever, isArray, isDefined, isFunction, isNullOrUndefined, isNumber, isString } from "../typeChecks"; import type { WorkerClientMessages, WorkerClientMethodCallMessage, WorkerClientPropertySetMessage, WorkerServerErrorMessage, WorkerServerEventMessage, WorkerServerMessages, WorkerServerProgressMessage, WorkerServerPropertyChangedMessage, WorkerServerPropertyInitializedMessage, WorkerServerReturnMessage } from "./WorkerMessages"; import { GET_PROPERTY_VALUES_METHOD, WorkerClientMessageType, WorkerServerMessageType } from "./WorkerMessages"; interface WorkerInvocation { onProgress: progressCallback; resolve: (value: any) => void; reject: (reason?: any) => void; methodName: string; } export class WorkerClient<EventsT> extends TypedEventBase<EventsT> { static isSupported = "Worker" in globalThis; private scriptPath: string; private taskCounter: number; private workers: Worker[]; private invocations = new Map<number, WorkerInvocation>(); private dispatchMessageResponse: (evt: MessageEvent<WorkerServerMessages>) => void; private propertyValues = new Map<string, any>(); readonly ready: Promise<unknown>; /** * Creates a new pooled worker method executor. * @param scriptPath - the path to the unminified script to use for the worker */ constructor(scriptPath: string); /** * Creates a new pooled worker method executor. * @param scriptPath - the path to the unminified script to use for the worker * @param workers - a set of workers that are already running. * @param startTaskCounter - the next task ID that the worker should use. */ constructor(scriptPath: string, workers: Worker[], startTaskCounter: number); /** * Creates a new pooled worker method executor. * @param scriptPath - the path to the unminified script to use for the worker * @param minScriptPath - the path to the minified script to use for the worker */ constructor(scriptPath: string, minScriptPath: string); /** * Creates a new pooled worker method executor. * @param scriptPath - the path to the unminified script to use for the worker * @param workerPoolSize - the number of worker threads to create for the pool (defaults to 1) */ constructor(scriptPath: string, workerPoolSize: number); /** * Creates a new pooled worker method executor. * @param scriptPath - the path to the unminified script to use for the worker * @param minScriptPath - the path to the minified script to use for the worker (optional) * @param workerPoolSize - the number of worker threads to create for the pool (defaults to 1) */ constructor(scriptPath: string, minScriptPath: string, workerPoolSize: number); constructor(scriptPath: string, minScriptPathOrWorkers?: number | string | Worker[], workerPoolSizeOrCurTaskCounter?: number) { super(); if (!WorkerClient.isSupported) { console.warn("Workers are not supported on this system."); } // Normalize constructor parameters. if (isNumber(minScriptPathOrWorkers)) { workerPoolSizeOrCurTaskCounter = minScriptPathOrWorkers; minScriptPathOrWorkers = undefined; } if (isNullOrUndefined(workerPoolSizeOrCurTaskCounter)) { workerPoolSizeOrCurTaskCounter = navigator.hardwareConcurrency || 4; } // Validate parameters if (workerPoolSizeOrCurTaskCounter < 1) { throw new Error("Worker pool size must be a postive integer greater than 0"); } // Choose which version of the script we're going to load. if (process.env.NODE_ENV === "development" || !isString(minScriptPathOrWorkers)) { this.scriptPath = scriptPath; } else { this.scriptPath = minScriptPathOrWorkers; } this.dispatchMessageResponse = (evt: MessageEvent<WorkerServerMessages>) => { const data = evt.data; switch (data.type) { case WorkerServerMessageType.Event: this.propogateEvent(data); break; case WorkerServerMessageType.PropertyInit: this.propertyInit(data); break; case WorkerServerMessageType.Property: this.propertyChanged(data); break; case WorkerServerMessageType.Progress: this.progressReport(data); break; case WorkerServerMessageType.Return: this.methodReturned(data); break; case WorkerServerMessageType.Error: this.invocationError(data); break; default: assertNever(data); } }; if (isArray(minScriptPathOrWorkers)) { this.taskCounter = workerPoolSizeOrCurTaskCounter; this.workers = minScriptPathOrWorkers; } else { this.taskCounter = 0; this.workers = new Array(workerPoolSizeOrCurTaskCounter); for (let i = 0; i < workerPoolSizeOrCurTaskCounter; ++i) { this.workers[i] = new Worker(this.scriptPath); } } for (const worker of this.workers) { worker.addEventListener("message", this.dispatchMessageResponse); } this.ready = this.callMethodOnAll(GET_PROPERTY_VALUES_METHOD); } private propogateEvent(data: WorkerServerEventMessage) { const evt = new TypedEvent(data.eventName); this.dispatchEvent(Object.assign(evt, data.data)); } private propertyInit(data: WorkerServerPropertyInitializedMessage) { if (this.propertyValues.has(data.propertyName)) { this.setProperty( data.propertyName, this.propertyValues.get(data.propertyName)); } else { this.propertyValues.set(data.propertyName, data.value); } } private propertyChanged(data: WorkerServerPropertyChangedMessage) { this.propertyValues.set(data.propertyName, data.value); } private progressReport(data: WorkerServerProgressMessage) { const invocation = this.invocations.get(data.taskID); const { onProgress } = invocation; if (isFunction(onProgress)) { onProgress(data.soFar, data.total, data.msg); } } private methodReturned(data: WorkerServerReturnMessage) { const messageHandler = this.removeInvocation(data.taskID); const { resolve } = messageHandler; resolve(data.returnValue); } private invocationError(data: WorkerServerErrorMessage) { const messageHandler = this.removeInvocation(data.taskID); const { reject, methodName } = messageHandler; reject(new Error(`${methodName} failed. Reason: ${data.errorMessage}`)); } /** * When the invocation has errored, we want to stop listening to the worker * message channel so we don't eat up processing messages that have no chance * ever pertaining to the invocation. **/ private removeInvocation(taskID: number) { const invocation = this.invocations.get(taskID); this.invocations.delete(taskID); return invocation; } /** * Invokes the given method on one particular worker thread. * @param worker * @param taskID * @param methodName * @param params * @param transferables * @param onProgress */ private callMethodOnWorker<T>(worker: Worker, taskID: number, methodName: string, params?: any[], transferables?: Transferable[], onProgress?: progressCallback): Promise<T> { return new Promise((resolve, reject) => { const invocation: WorkerInvocation = { onProgress, resolve, reject, methodName }; this.invocations.set(taskID, invocation); let message: WorkerClientMethodCallMessage = null; if (isDefined(params)) { message = { type: WorkerClientMessageType.MethodCall, taskID, methodName, params }; } else { message = { type: WorkerClientMessageType.MethodCall, taskID, methodName }; } this.postMessage(worker, message, transferables); }); } private postMessage(worker: Worker, message: WorkerClientMessages, transferables?: Transferable[]) { if (isDefined(transferables)) { worker.postMessage(message, transferables); } else { worker.postMessage(message); } } /** * Set a property value on all of the worker threads. * @param propertyName - the name of the property to set. * @param value - the value to which to set the property. */ protected setProperty<T>(propertyName: string, value: T): void { if (!WorkerClient.isSupported) { throw new Error("Workers are not supported on this system."); } this.propertyValues.set(propertyName, value); const message: WorkerClientPropertySetMessage = { type: WorkerClientMessageType.PropertySet, taskID: this.taskCounter++, propertyName, value }; for (const worker of this.workers) { this.postMessage(worker, message); } } /** * Retrieve the most recently cached value for a given property. * @param propertyName - the name of the property to get. */ protected getProperty<T>(propertyName: string): T { return this.propertyValues.get(propertyName) as T; } /** * Execute a method on a round-robin selected worker thread. * @param methodName - the name of the method to execute. * @param onProgress - a callback for receiving progress reports on long-running invocations. */ protected callMethod<T>(methodName: string, onProgress?: progressCallback): Promise<T>; /** * Execute a method on a round-robin selected worker thread. * @param methodName - the name of the method to execute. * @param params - the parameters to pass to the method. * @param onProgress - a callback for receiving progress reports on long-running invocations. */ protected callMethod<T>(methodName: string, params: any[], onProgress?: progressCallback): Promise<T>; /** * Execute a method on a round-robin selected worker thread. * @param methodName - the name of the method to execute. * @param params - the parameters to pass to the method. * @param transferables - any values in any of the parameters that should be transfered instead of copied to the worker thread. * @param onProgress - a callback for receiving progress reports on long-running invocations. */ protected callMethod<T>(methodName: string, params: any[], transferables: Transferable[], onProgress?: progressCallback): Promise<T>; /** * Execute a method on a round-robin selected worker thread. * @param methodName - the name of the method to execute. * @param params - the parameters to pass to the method. * @param transferables - any values in any of the parameters that should be transfered instead of copied to the worker thread. * @param onProgress - a callback for receiving progress reports on long-running invocations. */ protected callMethod<T>(methodName: string, params?: any[] | progressCallback, transferables?: Transferable[] | progressCallback, onProgress?: progressCallback): Promise<T | undefined> { if (!WorkerClient.isSupported) { return Promise.reject(new Error("Workers are not supported on this system.")); } // Normalize method parameters. let parameters: any[] = null; let tfers: Transferable[] = null; if (isFunction(params)) { onProgress = params; params = null; transferables = null; } if (isFunction(transferables) && !onProgress) { onProgress = transferables; transferables = null; } if (isArray(params)) { parameters = params; } if (isArray(transferables)) { tfers = transferables; } // taskIDs help us keep track of return values. const taskID = this.taskCounter++; // Workers are pooled, so the modulus selects them in a round-robin fashion. const workerID = taskID % this.workers.length; const worker = this.workers[workerID]; return this.callMethodOnWorker<T>( worker, taskID, methodName, parameters, tfers, onProgress); } /** * Execute a method on all of the worker threads. * @param methodName - the name of the method to execute. * @param onProgress - a callback for receiving progress reports on long-running invocations. */ protected callMethodOnAll<T>(methodName: string, onProgress?: progressCallback): Promise<T[]>; /** * Execute a method on all of the worker threads. * @param methodName - the name of the method to execute. * @param params - the parameters to pass to the method. * @param onProgress - a callback for receiving progress reports on long-running invocations. */ protected callMethodOnAll<T>(methodName: string, params: any[], onProgress?: progressCallback): Promise<T[]>; /** * Execute a method on all of the worker threads. * @param methodName - the name of the method to execute. * @param params - the parameters to pass to the method. * @param onProgress - a callback for receiving progress reports on long-running invocations. */ protected async callMethodOnAll<T>(methodName: string, params?: any[] | progressCallback, onProgress?: progressCallback): Promise<T[]> { if (!WorkerClient.isSupported) { return Promise.reject(new Error("Workers are not supported on this system.")); } if (isFunction(params)) { onProgress = params; params = null; } let parameters: any[] = null; if (isArray(params)) { parameters = params; } const rootTaskID = this.taskCounter; this.taskCounter += this.workers.length; return await arrayProgress( onProgress, this.workers, (worker, subProgress, i) => this.callMethodOnWorker<T>( worker, rootTaskID + i, methodName, parameters, null, subProgress)); } /** * Remove one of the workers from the worker pool and create a new instance * of the workerized object for just that worker. This is useful for creating * workers that cache network requests in memory. **/ getDedicatedClient() { if (this.workers.length === 1) { throw new Error("Can't create a dedicated fetcher from a dedicated fetcher."); } const Class = Object.getPrototypeOf(this).constructor; const worker = this.workers.pop(); worker.removeEventListener("message", this.dispatchMessageResponse); return new Class(this.scriptPath, [worker], this.taskCounter + 1); } }
the_stack
import { OverlayController } from '@inkline/inkline/controllers'; import { fireEvent } from '@testing-library/vue'; import { keymap } from '@inkline/inkline/constants'; describe('Factories', () => { describe('OverlayController', () => { let modalElement: any; beforeEach(() => { modalElement = { style: { zIndex: 0 } }; OverlayController.instances = {}; OverlayController.stack = []; }); describe('props', () => { describe('instances', () => { it('should be defined', () => { expect(OverlayController.instances).toBeDefined(); expect(OverlayController.instances).toEqual({}); }); }); describe('stack', () => { it('should be defined', () => { expect(OverlayController.stack).toBeDefined(); expect(OverlayController.stack).toEqual([]); }); }); describe('zIndex', () => { it('should be defined', () => { expect(OverlayController.zIndex).toBeDefined(); expect(OverlayController.zIndex).toEqual(1000); }); }); }); describe('constructor()', () => { it('should add keydown event listener', async () => { const spy = jest.spyOn(OverlayController, 'onPressEscape'); await fireEvent.keyDown(window, { key: keymap.esc[0] }); expect(spy).toHaveBeenCalled(); }); it('should close topmost modal on pressing Escape', async () => { const instance = { name: 'abc', closeOnPressEscape: true, hide: () => OverlayController.close('abc'), $el: modalElement }; const spy = jest.spyOn(instance, 'hide'); OverlayController.register(instance); OverlayController.open('abc'); expect(OverlayController.stack).toEqual(['abc']); await fireEvent.keyDown(window, { key: keymap.esc[0] }); expect(spy).toHaveBeenCalled(); expect(OverlayController.stack).toEqual([]); expect(instance.$el.style.zIndex).toEqual(1000); }); it('should not react to other key other than Escape', async () => { const instance = { name: 'abc', hide: () => {}, closeOnPressEscape: true, $el: modalElement }; const spy = jest.spyOn(instance, 'hide'); OverlayController.register(instance); OverlayController.open('abc'); await fireEvent.keyDown(window, { key: keymap.enter[0] }); expect(spy).not.toHaveBeenCalled(); }); it('should not close topmost modal on pressing Escape if closeOnPressEscape is false', async () => { const instance = { name: 'abc', close: () => {}, closeOnPressEscape: false, $el: modalElement }; const spy = jest.spyOn(instance, 'close'); OverlayController.register(instance); OverlayController.open('abc'); await fireEvent.keyDown(window, { key: keymap.enter[0] }); expect(spy).not.toHaveBeenCalled(); }); }); describe('register()', () => { it('should register modal instance', () => { const instance = { name: 'abc', $el: modalElement }; OverlayController.register(instance); expect(OverlayController.instances).toHaveProperty(instance.name); expect(OverlayController.instances[instance.name]).toEqual(instance); }); it('should not register modal instance if instance not defined', () => { OverlayController.register(null); expect(Object.keys(OverlayController.instances).length).toEqual(0); }); it('should not register modal instance if id not present', () => { const instance = {}; OverlayController.register(instance); expect(Object.keys(OverlayController.instances).length).toEqual(0); }); }); // describe('unregister()', () => { // it('should unregister modal instance', () => { // const instance = { name: 'abc' }; // // OverlayController.register(instance); // OverlayController.unregister(instance); // // expect(OverlayController.instances).not.toHaveProperty(instance.name); // expect(OverlayController.instances[instance.name]).not.toBeDefined(); // }); // // it('should not unregister modal instance if id not present', () => { // const instance = { name: 'abc' }; // // OverlayController.register(instance); // OverlayController.unregister({}); // // expect(Object.keys(OverlayController.instances).length).toEqual(1); // }); // // it('should not unregister modal instance if id not present', () => { // const instance = { name: 'abc' }; // // OverlayController.register(instance); // OverlayController.unregister(null); // // expect(Object.keys(OverlayController.instances).length).toEqual(1); // }); // }); // // describe('nextZIndex()', () => { // it('should return incremented zIndex', () => { // const zIndex = OverlayController.zIndex; // // expect(OverlayController.nextZIndex()).toEqual(zIndex); // expect(OverlayController.nextZIndex()).toEqual(zIndex + 1); // expect(OverlayController.nextZIndex()).toEqual(zIndex + 2); // }); // }); // // describe('open()', () => { // it('should return if Vue.$isServer', () => { // isServer(true); // // OverlayController.open('abc'); // // expect(OverlayController.modalStack.length).toEqual(0); // // isServer(false); // }); // // it('should add modal to modal stack if not already open', () => { // OverlayController.open('abc'); // // expect(OverlayController.modalStack.length).toEqual(1); // expect(OverlayController.modalStack[0]).toEqual({ name: 'abc' }); // }); // // it('should set modal zIndex if already open', () => { // OverlayController.modalStack.push({ // name: 'abc', // $el: { // style: {} // } // }); // // OverlayController.open('abc'); // // expect(OverlayController.modalStack.length).toEqual(1); // expect(OverlayController.modalStack[0].$el.style.zIndex).toEqual(1000); // }); // // it('should add ".-modal" modifier class to document body', () => { // OverlayController.open('abc'); // // expect(window.document.body.classList.contains('-modal')).toEqual(true); // }); // }); // // describe('close()', () => { // it('should return if Vue.$isServer', () => { // isServer(true); // // OverlayController.open('abc'); // OverlayController.close('abc'); // // expect(OverlayController.modalStack.length).toEqual(0); // // isServer(false); // }); // // it('should remove modal from modal stack', () => { // OverlayController.open('abc'); // OverlayController.close('abc'); // // expect(OverlayController.modalStack.length).toEqual(0); // }); // // it('should remove ".-modal" modifier class from document body', () => { // OverlayController.open('abc'); // OverlayController.close('abc'); // // expect(window.document.body.classList.contains('-modal')).toEqual(false); // }); // }); // // describe('getTopPopup()', () => { // it('should return instance of topmost open modal', () => { // OverlayController.register({ name: 'abc' }); // OverlayController.register({ name: 'def' }); // OverlayController.open('abc'); // OverlayController.open('def'); // // expect(OverlayController.getTopPopup()).toEqual({ name: 'def' }); // }); // // it('should return undefined if instance is undefined', () => { // OverlayController.register({ name: 'abc' }); // OverlayController.open('abc'); // // OverlayController.modalStack.push(undefined); // // expect(OverlayController.getTopPopup()).not.toBeDefined(); // }); // // it('should return undefined if no open modals', () => { // OverlayController.register({ name: 'abc' }); // // expect(OverlayController.getTopPopup()).not.toBeDefined(); // }); // }); }); });
the_stack
import * as BN from 'bn.js'; import { HexDataBuffer as HEX } from '../serialization/hex'; import { Base64DataBuffer as B64 } from '../serialization/base64'; /** * Class used for reading BCS data chunk by chunk. Meant to be used * by some wrapper, which will make sure that data is valid and is * matching the desired format. * * @example * // data for this example is: * // { a: u8, b: u32, c: bool, d: u64 } * * let reader = new BcsReader("647f1a060001ffffe7890423c78a050102030405"); * let field1 = reader.read8(); * let field2 = reader.read32(); * let field3 = reader.read8() == '1'; // bool * let field4 = reader.read64(); * // .... * * Reading vectors is another deal in BCS. To read a vector, you first need to read * its length using {@link readULEB}. Here's an example: * @example * // data encoded: { field: [1, 2, 3, 4, 5] } * let reader = new BcsReader("050102030405"); * let vec_length = reader.readULEB(); * let elements = []; * for (let i = 0; i < vec_length; i++) { * elements.push(reader.read8()); * } * console.log(elements); // [1,2,3,4,5] * * @param {String} data HEX-encoded data (serialized BCS) */ export class BcsReader { private dataView: DataView; private bytePosition: number = 0; /** * @param {Uint8Array} data Data to use as a buffer. */ constructor(data: Uint8Array) { this.dataView = new DataView(data.buffer); } /** * Shift current cursor position by `bytes`. * * @param {Number} bytes Number of bytes to * @returns {this} Self for possible chaining. */ shift(bytes: number) { this.bytePosition += bytes; return this; } /** * Read U8 value from the buffer and shift cursor by 1. * @returns */ read8(): BN { let value = this.dataView.getUint8(this.bytePosition); this.shift(1); return new BN.BN(value, 10); } /** * Read U16 value from the buffer and shift cursor by 2. * @returns */ read16(): BN { let value = this.dataView.getUint16(this.bytePosition, true); this.shift(2); return new BN.BN(value, 10); } /** * Read U32 value from the buffer and shift cursor by 4. * @returns */ read32(): BN { let value = this.dataView.getUint32(this.bytePosition, true); this.shift(4); return new BN.BN(value, 10); } /** * Read U64 value from the buffer and shift cursor by 8. * @returns */ read64(): BN { let value1 = this.read32(); let value2 = this.read32(); let result = value2.toString(16) + value1.toString(16).padStart(8, '0'); return new BN.BN(result, 16); } /** * Read U128 value from the buffer and shift cursor by 16. * @returns */ read128(): BN { let value1 = this.read64(); let value2 = this.read64(); let result = value2.toString(16) + value1.toString(16).padStart(8, '0'); return new BN.BN(result, 16); } /** * Read `num` number of bytes from the buffer and shift cursor by `num`. * @param num Number of bytes to read. * @returns Selected Buffer. */ readBytes(num: number): Uint8Array { let start = this.bytePosition + this.dataView.byteOffset; let value = new Uint8Array(this.dataView.buffer, start, num); this.shift(num); return value; } /** * Read ULEB value - an integer of varying size. Used for enum indexes and * vector lengths. * @returns {Number} The ULEB value. */ readULEB(): number { let start = this.bytePosition + this.dataView.byteOffset; let buffer = new Uint8Array(this.dataView.buffer, start); let { value, length } = ulebDecode(buffer); this.shift(length); return value; } /** * Read a BCS vector: read a length and then apply function `cb` X times * where X is the length of the vector, defined as ULEB in BCS bytes. * @param cb Callback to process elements of vector. * @returns {Array<Any>} Array of the resulting values, returned by callback. */ readVec(cb: (reader: BcsReader, i: number, length: number) => any): any[] { let length = this.readULEB(); let result = []; for (let i = 0; i < length; i++) { result.push(cb(this, i, length)); } return result; } } /** * Class used to write BCS data into a buffer. Initializer requires * some size of a buffer to init; default value for this buffer is 1KB. * * Most methods are chainable, so it is possible to write them in one go. * * @example * let serialized = new BcsWriter() * .write8(10) * .write32(1000000) * .write64(10000001000000) * .hex(); */ export class BcsWriter { private dataView: DataView; private bytePosition: number = 0; /** * @param {Number} [size=1024] Size of the buffer to reserve for serialization. */ constructor(size = 1024) { this.dataView = new DataView(new ArrayBuffer(size)); } /** * Unify argument types by converting them to BN. */ static toBN(number: number | BN | bigint | string): BN { switch (typeof number) { case 'bigint': return new BN.BN(number.toString()); default: return new BN.BN(number); } } /** * Shift current cursor position by `bytes`. * * @param {Number} bytes Number of bytes to * @returns {this} Self for possible chaining. */ shift(bytes: number): this { this.bytePosition += bytes; return this; } /** * Write a U8 value into a buffer and shift cursor position by 1. * @param {Number} value Value to write. * @returns {this} */ write8(value: number | bigint | BN): this { this.dataView.setUint8(this.bytePosition, +BcsWriter.toBN(value)); return this.shift(1); } /** * Write a U16 value into a buffer and shift cursor position by 2. * @param {Number} value Value to write. * @returns {this} */ write16(value: number | bigint | BN): this { this.dataView.setUint16(this.bytePosition, +BcsWriter.toBN(value), true); return this.shift(2); } /** * Write a U32 value into a buffer and shift cursor position by 4. * @param {Number} value Value to write. * @returns {this} */ write32(value: number | bigint | BN): this { this.dataView.setUint32(this.bytePosition, +BcsWriter.toBN(value), true); return this.shift(4); } /** * Write a U64 value into a buffer and shift cursor position by 8. * @param {bigint} value Value to write. * @returns {this} */ write64(value: bigint | BN): this { BcsWriter.toBN(value) .toArray('le', 8) .forEach(el => this.write8(el)); return this; } /** * Write a U128 value into a buffer and shift cursor position by 16. * * @unimplemented * @param {bigint} value Value to write. * @returns {this} */ write128(value: bigint | BN): this { BcsWriter.toBN(value) .toArray('le', 16) .forEach(el => this.write8(el)); return this; } /** * Write a ULEB value into a buffer and shift cursor position by number of bytes * written. * @param {Number} value Value to write. * @returns {this} */ writeULEB(value: number): this { ulebEncode(value).forEach(el => this.write8(el)); return this; } /** * Write a vector into a buffer by first writing the vector length and then calling * a callback on each passed value. * * @param {Array<Any>} vector Array of elements to write. * @param {WriteVecCb} cb Callback to call on each element of the vector. * @returns {this} */ writeVec( vector: Array<any>, cb: (writer: BcsWriter, el: any, i: number, len: number) => {} ): this { this.writeULEB(vector.length); Array.from(vector).forEach((el, i) => cb(this, el, i, vector.length)); return this; } /** * Get underlying buffer taking only value bytes (in case initial buffer size was bigger). * @returns {Uint8Array} Resulting BCS. */ toBytes() { return new Uint8Array(this.dataView.buffer.slice(0, this.bytePosition)); } /** * Represent data as 'hex' or 'base64' * @param encoding Encoding to use: 'base64' or 'hex' */ toString(encoding: string): string { switch (encoding) { case 'base64': return new B64(this.toBytes()).toString(); case 'hex': return new HEX(this.toBytes()).toString(); default: throw new Error( 'Unsupported encoding, supported values are: base64, hex' ); } } } // Helper utility: write number as an ULEB array. // Original code is taken from: https://www.npmjs.com/package/uleb128 (no longer exists) function ulebEncode(num: number): Array<number> { let arr = []; let len = 0; if (num === 0) { return [0]; } while (num > 0) { arr[len] = num & 0x7f; if ((num >>= 7)) { arr[len] |= 0x80; } len += 1; } return arr; } // Helper utility: decode ULEB as an array of numbers. // Original code is taken from: https://www.npmjs.com/package/uleb128 (no longer exists) function ulebDecode( arr: Array<number> | Uint8Array ): { value: number; length: number } { let total = 0; let shift = 0; let len = 0; while (true) { let byte = arr[len]; len += 1; total |= (byte & 0x7f) << shift; if ((byte & 0x80) === 0) { break; } shift += 7; } return { value: total, length: len, }; } /** * Set of methods that allows data encoding/decoding as standalone * BCS value or a part of a composed structure/vector. */ interface TypeInterface { encode: (data: any, size: number) => BcsWriter; decode: (data: Uint8Array) => any; _encodeRaw: (writer: BcsWriter, data: any) => BcsWriter; _decodeRaw: (reader: BcsReader) => any; } /** * BCS implementation for Move types and few additional built-ins. */ export class BCS { // Prefefined types constants static readonly U8: string = 'u8'; static readonly U32: string = 'u32'; static readonly U64: string = 'u64'; static readonly U128: string = 'u128'; static readonly BOOL: string = 'bool'; static readonly VECTOR: string = 'vector'; static readonly ADDRESS: string = 'address'; static readonly STRING: string = 'string'; private static types: Map<string, TypeInterface> = new Map(); /** * Serialize data into BCS. * * @example * BCS.registerVectorType('vector<u8>', 'u8'); * * let serialized = BCS * .set('vector<u8>', [1,2,3,4,5,6]) * .toBytes(); * * console.assert(BCS.util.toHex(serialized) === '06010203040506'); * * @param type Name of the type to serialize (must be registered). * @param data Data to serialize. * @param size Serialization buffer size. Default 1024 = 1KB. * @return A BCS reader instance. Usually you'd want to call `.toBytes()` */ public static set(type: string, data: any, size: number = 1024): BcsWriter { return this.getTypeInterface(type).encode(data, size); } /** * Deserialize BCS into a JS type. * * @example * // use util to form an Uint8Array buffer * let data = BCS.de(BCS.U32, new Uint8Array([255, 255, 255, 255])); * console.assert(data.toString() == '4294967295'); * * @param type Name of the type to deserialize (must be registered). * @param data Data to deserialize. * @return Deserialized data. */ public static de(type: string, data: Uint8Array): any { return this.getTypeInterface(type).decode(data); } /** * Check whether a TypeInterface has been loaded for the `Type` * @param type Name of the type to check. * @returns */ public static hasType(type: string): boolean { return this.types.has(type); } /** * Method to register new types for BCS internal representation. * For each registered type 2 callbacks must be specified and one is optional: * * - encodeCb(writer, data) - write a way to serialize data with BcsWriter; * - decodeCb(reader) - write a way to deserialize data with BcsReader; * - validateCb(data) - validate data - either return bool or throw an error * * @example * // our type would be a string that consists only of numbers * BCS.registerType('number_string', * (writer, data) => writer.writeVec(data, (w, el) => w.write8(el)), * (reader) => reader.readVec((r) => r.read8()).join(''), // read each value as u8 * (value) => /[0-9]+/.test(value) // test that it has at least one digit * ); * console.log(Array.from(BCS.set('number_string', '12345').toBytes()) == [5,1,2,3,4,5]); * * @param name * @param encodeCb Callback to encode a value. * @param decodeCb Callback to decode a value. * @param validateCb Optional validator Callback to check type before serialization. */ public static registerType( name: string, encodeCb: (writer: BcsWriter, data: any) => BcsWriter, decodeCb: (reader: BcsReader) => any, validateCb: (data: any) => boolean = () => true ): typeof BCS { this.types.set(name, { encode(data, size = 1024) { return this._encodeRaw(new BcsWriter(size), data); }, decode(data) { return this._decodeRaw(new BcsReader(data)); }, // these methods should always be used with caution as they require pre-defined // reader and writer and mainly exist to allow multi-field (de)serialization; _encodeRaw(writer, data) { if (validateCb(data)) { return encodeCb(writer, data); } else { throw new Error(`Validation failed for type ${name}, data: ${data}`); } }, _decodeRaw(reader) { return decodeCb(reader); }, }); return this; } /** * Register an address type which is a sequence of U8s of specified length. * @example * BCS.registerAddressType('address', 20); * let addr = BCS.de('address', 'ca27601ec5d915dd40d42e36c395d4a156b24026'); * * @param name Name of the address type. * @param length Byte length of the address. * @returns */ public static registerAddressType(name: string, length: number): typeof BCS { return this.registerType( name, (writer, data) => new HEX(data) .getData() .reduce((writer, el) => writer.write8(el), writer), reader => new HEX(reader.readBytes(length)).toString() ); } /** * Register custom vector type inside the BCS. * * @example * BCS.registerVectorType('vector<u8>', 'u8'); * let array = BCS.de('vector<u8>', new Uint8Array([6,1,2,3,4,5,6])); // [1,2,3,4,5,6]; * let again = BCS.set('vector<u8>', [1,2,3,4,5,6]).toBytes(); * * @param name Name of the type to register. * @param elementType Name of the inner type of the vector. * @return Returns self for chaining. */ public static registerVectorType( name: string, elementType: string ): typeof BCS { // OMITTING SAFETY CHECK TO ALLOW RECURSIVE DEFINITIONS // if (!BCS.hasType(elementType)) { // throw new Error(`Type ${elementType} is not registered`); // } return this.registerType( name, (writer, data) => writer.writeVec(data, (writer, el) => { return BCS.getTypeInterface(elementType)._encodeRaw(writer, el); }), reader => reader.readVec(reader => { return BCS.getTypeInterface(elementType)._decodeRaw(reader); }) ); } /** * Safe method to register a custom Move struct. The first argument is a name of the * struct which is only used on the FrontEnd and has no affect on serialization results, * and the second is a struct description passed as an Object. * * The description object MUST have the same order on all of the platforms (ie in Move * or in Rust). * * @example * // Move / Rust struct * // struct Coin { * // value: u64, * // owner: vector<u8>, // name // Vec<u8> in Rust * // is_locked: bool, * // } * * BCS.registerStructType('Coin', { * value: BCS.U64, * owner: BCS.STRING, * is_locked: BCS.BOOL * }); * * // Created in Rust with diem/bcs * // let rust_bcs_str = '80d1b105600000000e4269672057616c6c65742047757900'; * let rust_bcs_str = [ // using an Array here as BCS works with Uint8Buffer * 128, 209, 177, 5, 96, 0, 0, * 0, 14, 66, 105, 103, 32, 87, * 97, 108, 108, 101, 116, 32, 71, * 117, 121, 0 * ]; * * // Let's encode the value as well * let test_set = BCS.set('Coin', { * owner: 'Big Wallet Guy', * value: '412412400000', * is_locked: false, * }); * * console.assert(Array.from(test_set.toBytes()) === rust_bcs_str, 'Whoopsie, result mismatch'); * * @param name Name of the type to register. * @param fields Fields of the struct. Must be in the correct order. * @return Returns BCS for chaining. */ public static registerStructType( name: string, fields: { [key: string]: string } ): typeof BCS { let struct = Object.freeze(fields); // Make sure the order doesn't get changed // IMPORTANT: we need to store canonical order of fields for each registered // struct so we maintain it and allow developers to use any field ordering in // their code (and not cause mismatches based on field order). let canonicalOrder = Object.keys(struct); // Make sure all the types in the fields description are already known // and that all the field types are strings. // OMITTING this check to allow recursive definitions and dynamic typing. // for (let type of Object.values(struct)) { // throw new Error(`Type ${type} is not registered`); // } // } return this.registerType( name, (writer, data) => { for (let key of canonicalOrder) { BCS.getTypeInterface(struct[key])._encodeRaw(writer, data[key]); } return writer; }, reader => { let result: { [key: string]: any } = {}; for (let key of canonicalOrder) { result[key] = BCS.getTypeInterface(struct[key])._decodeRaw(reader); } return result; } ); } /** * Safe method to register custom enum type where each invariant holds the value of another type. * @example * BCS.registerStructType('Coin', { value: 'u64' }); * BCS.registerVectorType('vector<Coin>', 'Coin'); * BCS.registerEnumType('MyEnum', { * single: 'Coin', * multi: 'vector<Coin>' * }); * * let example1 = Buffer.from('AICWmAAAAAAA', 'base64'); * let example2 = Buffer.from('AQIBAAAAAAAAAAIAAAAAAAAA', 'base64'); * * console.log( * BCS.de('MyEnum', new Uint8Array(example1)), // { single: { value: 10000000 } } * BCS.de('MyEnum', new Uint8Array(example2)) // { multi: [ { value: 1 }, { value: 2 } ] } * } * * // and serialization * BCS.set('MyEnum', { single: { value: 10000000 } }).toBytes(); * BCS.set('MyEnum', { multi: [ { value: 1 }, { value: 2 } ] }); * * @param name * @param variants */ public static registerEnumType( name: string, variants: { [key: string]: string | null } ) { let struct = Object.freeze(variants); // Make sure the order doesn't get changed // IMPORTANT: enum is an ordered type and we have to preserve ordering in BCS let canonicalOrder = Object.keys(struct); return this.registerType( name, (writer, data) => { let key = Object.keys(data)[0]; if (key === undefined) { throw new Error(`Unknown invariant of the enum ${name}`); } let orderByte = canonicalOrder.indexOf(key); if (orderByte === -1) { throw new Error( `Unknown invariant of the enum ${name}, allowed values: ${canonicalOrder}` ); } let invariant = canonicalOrder[orderByte]; let invariantType = struct[invariant]; writer.write8(orderByte); // write order byte // Allow empty Enum values! return invariantType !== null ? BCS.getTypeInterface(invariantType)._encodeRaw(writer, data[key]) : writer; }, reader => { let orderByte = reader.readULEB(); let invariant = canonicalOrder[orderByte]; let invariantType = struct[invariant]; if (orderByte === -1) { throw new Error( `Decoding type mismatch, expected enum ${name} invariant index, received ${orderByte}` ); } return { [invariant]: invariantType !== null ? BCS.getTypeInterface(invariantType)._decodeRaw(reader) : true, }; } ); } static getTypeInterface(type: string): TypeInterface { let typeInterface = BCS.types.get(type); if (typeInterface === undefined) { throw new Error(`Type ${type} is not registered`); } return typeInterface; } } (function registerPrimitives(): void { BCS.registerType( BCS.U8, (writer, data) => writer.write8(data), reader => reader.read8(), u8 => u8 < 256 ); BCS.registerType( BCS.U32, (writer, data) => writer.write32(data), reader => reader.read32(), u32 => u32 < 4294967296 ); BCS.registerType( BCS.U64, (writer, data) => writer.write64(data), reader => reader.read64(), _u64 => true ); BCS.registerType( BCS.U128, (writer, data) => writer.write128(data), reader => reader.read128(), _u128 => true ); BCS.registerType( BCS.BOOL, (writer, data) => writer.write8(data), reader => reader.read8().toString(10) == '1', (_bool: boolean) => true ); BCS.registerType( BCS.STRING, (writer, data) => writer.writeVec(Array.from(data), (writer, el) => writer.write8(el.charCodeAt(0)) ), reader => { return reader .readVec(reader => reader.read8()) .map(el => String.fromCharCode(el)) .join(''); }, (str: string) => /^[\x00-\x7F]*$/.test(str) ); })();
the_stack
import { TestBed } from '@angular/core/testing'; import { CollectionNode, CollectionNodeBackendDict } from 'domain/collection/collection-node.model'; import { Collection } from 'domain/collection/collection.model'; import { CollectionLinearizerService } from './collection-linearizer.service'; describe('Collection linearizer service', () => { let collectionLinearizerService: CollectionLinearizerService; let firstCollectionNode; let secondCollectionNode; let thirdCollectionNode; beforeEach(() => { collectionLinearizerService = TestBed.inject(CollectionLinearizerService); let firstCollectionNodeBackendObject = { exploration_id: 'exp_id0', exploration_summary: { title: 'exp title0', category: 'exp category', objective: 'exp objective' } }; firstCollectionNode = CollectionNode.create( firstCollectionNodeBackendObject as CollectionNodeBackendDict); let secondCollectionNodeBackendObject = { exploration_id: 'exp_id1', exploration_summary: { title: 'exp title1', category: 'exp category', objective: 'exp objective' } }; secondCollectionNode = CollectionNode.create( secondCollectionNodeBackendObject as CollectionNodeBackendDict); let thirdCollectionNodeBackendObject = { exploration_id: 'exp_id2', exploration_summary: { title: 'exp title2', category: 'exp category', objective: 'exp objective' } }; thirdCollectionNode = CollectionNode.create( thirdCollectionNodeBackendObject as CollectionNodeBackendDict); }); // The linear order of explorations is: exp_id0 -> exp_id1 -> exp_id2. let createLinearCollection = () => { let collection = Collection.createEmptyCollection(); // Add collections in a different order from which they will be displayed // by the linearizer for robustness. collection.addCollectionNode(firstCollectionNode); collection.addCollectionNode(secondCollectionNode); collection.addCollectionNode(thirdCollectionNode); return collection; }; describe('removeCollectionNode()', () => { it('should not remove a non-existent node from a single node collection', () => { let collection = Collection.createEmptyCollection(); collection.addCollectionNode(firstCollectionNode); expect(collection.containsCollectionNode('exp_id0')).toBe(true); expect( collectionLinearizerService.removeCollectionNode( collection, 'non_existent')).toBe(false); expect(collection.containsCollectionNode('exp_id0')).toBe(true); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual([firstCollectionNode]); } ); it('should not remove a non-existent node from a multiple nodes collection', () => { let collection = createLinearCollection(); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [firstCollectionNode, secondCollectionNode, thirdCollectionNode]); expect( collectionLinearizerService.removeCollectionNode( collection, 'non_existent')).toBe(false); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [firstCollectionNode, secondCollectionNode, thirdCollectionNode]); } ); it('should correctly remove a node from a single node collection', () => { let collection = Collection.createEmptyCollection(); collection.addCollectionNode(firstCollectionNode); expect(collection.containsCollectionNode('exp_id0')).toBe(true); expect( collectionLinearizerService.removeCollectionNode( collection, 'exp_id0')).toBe(true); expect(collection.containsCollectionNode('exp_id0')).toBe(false); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual([]); } ); it('should correctly remove the first node from a collection', () => { let collection = createLinearCollection(); expect(collection.containsCollectionNode('exp_id0')).toBe(true); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [firstCollectionNode, secondCollectionNode, thirdCollectionNode]); expect( collectionLinearizerService.removeCollectionNode( collection, 'exp_id0')).toBe(true); expect(collection.containsCollectionNode('exp_id0')).toBe(false); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual([secondCollectionNode, thirdCollectionNode]); }); it('should correctly remove the last node from a collection', () => { let collection = createLinearCollection(); expect(collection.containsCollectionNode('exp_id2')).toBe(true); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [firstCollectionNode, secondCollectionNode, thirdCollectionNode]); expect( collectionLinearizerService.removeCollectionNode( collection, 'exp_id2')).toBe(true); expect(collection.containsCollectionNode('exp_id2')).toBe(false); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual([firstCollectionNode, secondCollectionNode]); }); it('should correctly remove a middle node from a collection', () => { let collection = createLinearCollection(); expect(collection.containsCollectionNode('exp_id1')).toBe(true); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [firstCollectionNode, secondCollectionNode, thirdCollectionNode]); expect( collectionLinearizerService.removeCollectionNode( collection, 'exp_id1')).toBe(true); expect(collection.containsCollectionNode('exp_id1')).toBe(false); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual([firstCollectionNode, thirdCollectionNode]); }); }); describe('appendCollectionNode()', () => { it('should correctly append a node to an empty collection', () => { let collection = Collection.createEmptyCollection(); expect(collection.containsCollectionNode('exp_id0')).toBe(false); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual([]); collectionLinearizerService.appendCollectionNode( collection, 'exp_id0', firstCollectionNode.getExplorationSummaryObject()); firstCollectionNode = collection.getCollectionNodeByExplorationId( 'exp_id0'); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual([firstCollectionNode]); }); it('should correctly append a node to a non-empty collection', () => { let collection = createLinearCollection(); let newCollectionNodeBackendObject = { exploration_id: 'exp_id3', exploration_summary: { title: 'exp title3', category: 'exp category', objective: 'exp objective' } }; let newCollectionNode = CollectionNode.create( newCollectionNodeBackendObject as CollectionNodeBackendDict); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [firstCollectionNode, secondCollectionNode, thirdCollectionNode]); collectionLinearizerService.appendCollectionNode( collection, 'exp_id3', newCollectionNode.getExplorationSummaryObject()); newCollectionNode = collection.getCollectionNodeByExplorationId( 'exp_id3'); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual([ collection.getCollectionNodeByExplorationId('exp_id0'), collection.getCollectionNodeByExplorationId('exp_id1'), collection.getCollectionNodeByExplorationId('exp_id2'), collection.getCollectionNodeByExplorationId('exp_id3')]); }); }); describe('shiftNodeLeft()', () => { it('should correctly shift a node in a single node collection', () => { let collection = Collection.createEmptyCollection(); collection.addCollectionNode(firstCollectionNode); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual([firstCollectionNode]); expect( collectionLinearizerService.shiftNodeLeft( collection, 'exp_id0')).toBe(true); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual([firstCollectionNode]); } ); it('should not shift a non-existent node', () => { let collection = createLinearCollection(); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [firstCollectionNode, secondCollectionNode, thirdCollectionNode]); expect(collectionLinearizerService.shiftNodeLeft( collection, 'non_existent')).toBe(false); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [firstCollectionNode, secondCollectionNode, thirdCollectionNode]); }); it('should correctly shift the first node', () => { let collection = createLinearCollection(); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [firstCollectionNode, secondCollectionNode, thirdCollectionNode]); expect( collectionLinearizerService.shiftNodeLeft( collection, 'exp_id0')).toBe(true); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [firstCollectionNode, secondCollectionNode, thirdCollectionNode]); }); it('should correctly shift the last node', () => { let collection = createLinearCollection(); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [firstCollectionNode, secondCollectionNode, thirdCollectionNode]); expect( collectionLinearizerService.shiftNodeLeft( collection, 'exp_id2')).toBe(true); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [firstCollectionNode, thirdCollectionNode, secondCollectionNode]); }); it('should correctly shift a middle node', () => { let collection = createLinearCollection(); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [firstCollectionNode, secondCollectionNode, thirdCollectionNode]); expect( collectionLinearizerService.shiftNodeLeft( collection, 'exp_id1')).toBe(true); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [secondCollectionNode, firstCollectionNode, thirdCollectionNode]); }); }); describe('shiftNodeRight()', () => { it('should correctly shift a node in a single node collection', () => { let collection = Collection.createEmptyCollection(); collection.addCollectionNode(firstCollectionNode); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual([firstCollectionNode]); expect( collectionLinearizerService.shiftNodeRight( collection, 'exp_id0')).toBe(true); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual([firstCollectionNode]); } ); it('should not shift a non-existent node', () => { let collection = createLinearCollection(); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [firstCollectionNode, secondCollectionNode, thirdCollectionNode]); expect( collectionLinearizerService.shiftNodeRight( collection, 'non_existent')).toBe(false); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [firstCollectionNode, secondCollectionNode, thirdCollectionNode]); }); it('should correctly shift the first node', () => { let collection = createLinearCollection(); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [firstCollectionNode, secondCollectionNode, thirdCollectionNode]); expect( collectionLinearizerService.shiftNodeRight( collection, 'exp_id0')).toBe(true); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [secondCollectionNode, firstCollectionNode, thirdCollectionNode]); }); it('should correctly shift the last node', () => { let collection = createLinearCollection(); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [firstCollectionNode, secondCollectionNode, thirdCollectionNode]); expect( collectionLinearizerService.shiftNodeRight( collection, 'exp_id2')).toBe(true); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [firstCollectionNode, secondCollectionNode, thirdCollectionNode]); }); it('should correctly shift middle node', () => { let collection = createLinearCollection(); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [firstCollectionNode, secondCollectionNode, thirdCollectionNode]); expect( collectionLinearizerService.shiftNodeRight( collection, 'exp_id1')).toBe(true); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [firstCollectionNode, thirdCollectionNode, secondCollectionNode]); }); }); describe('getNextExplorationId()', () => { it('should return no exploration ids for a completed linear collection', () => { let collection = createLinearCollection(); expect( collectionLinearizerService.getNextExplorationId( collection, ['exp_id0', 'exp_id1', 'exp_id2'])).toEqual(null); } ); it('should return next exploration id for a partially completed collection', () => { let collection = createLinearCollection(); expect( collectionLinearizerService.getNextExplorationId( collection, ['exp_id0', 'exp_id1'])).toEqual('exp_id2'); } ); }); describe('getCollectionNodesInPlayableOrder()', () => { it('should correctly return an empty list for an empty collection', () => { let collection = Collection.createEmptyCollection(); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual([]); } ); it('should correctly return a list for a collection with a single node', () => { let collection = Collection.createEmptyCollection(); collection.addCollectionNode(firstCollectionNode); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual([firstCollectionNode]); } ); it('should correctly return a list for a collection with multiple nodes', () => { let collection = createLinearCollection(); expect( collectionLinearizerService.getCollectionNodesInPlayableOrder( collection)).toEqual( [firstCollectionNode, secondCollectionNode, thirdCollectionNode]); } ); }); });
the_stack
'use strict'; import * as cheerio from 'cheerio'; import { ISong } from "chord/music/api/song"; import { ILyric } from 'chord/music/api/lyric'; import { IAlbum } from "chord/music/api/album"; import { IArtist } from "chord/music/api/artist"; import { ITag } from "chord/music/api/tag"; import { ICollection } from "chord/music/api/collection"; import { IAudio } from "chord/music/api/audio"; import { parseToMillisecond } from 'chord/base/common/time'; import { isObject } from 'chord/base/common/checker'; import { getSongUrl, getAlbumUrl, getArtistUrl, getCollectionUrl, getUserUrl, getSongId, getAlbumId, getArtistId, getCollectionId, getUserId, } from "chord/music/common/origin"; import { makeLyric as _makeLyric } from 'chord/music/utils/lyric'; function absoluteUrl(uri: string): string { if (uri.startsWith('//')) { return 'http:' + uri; } return uri; } const _origin = 'migu'; const _getSongUrl: (id: string) => string = getSongUrl.bind(null, _origin); const _getSongId: (id: string) => string = getSongId.bind(null, _origin); const _getAlbumUrl: (id: string) => string = getAlbumUrl.bind(null, _origin); const _getAlbumId: (id: string) => string = getAlbumId.bind(null, _origin); const _getArtistUrl: (id: string) => string = getArtistUrl.bind(null, _origin); const _getArtistId: (id: string) => string = getArtistId.bind(null, _origin); const _getCollectionUrl: (id: string) => string = getCollectionUrl.bind(null, _origin); const _getCollectionId: (id: string) => string = getCollectionId.bind(null, _origin); // const _getUserUrl: (id: string) => string = getUserUrl.bind(null, _origin); const _getUserId: (id: string) => string = getUserId.bind(null, _origin); export function makeAudios(infos: any): Array<IAudio> { if (!infos) return null; let audios = []; let url = absoluteUrl(infos['playUrl']); let format: string; let kbps: number; if (url.includes('/flac/')) { kbps = 720; format = 'flac'; } else { format = 'mp3'; if (url.match(/MP3_\d+/)) { let m = /MP3_(\d+)/.exec(url)[1]; kbps = Number.parseInt(m); } else { kbps = 90; } } let audio = { format, size: null, kbps, url, path: null, }; audios.push(audio); return audios; } export function makeSong(info: any): ISong { let songOriginalId = info['copyrightId']; let songMid = (info['songId'] || info['id']).toString(); let albumInfo = info['albums'] ? info['albums'][0] : info; let albumOriginalId = albumInfo['albumId'] && albumInfo['albumId'].toString(); let artistInfo = info['singers'] ? info['singers'][0] : info; let artistOriginalId = artistInfo['artistId'] || artistInfo['singerId'] && (isObject(artistInfo['singerId']) ? ( artistInfo['singerId'].length > 0 ? artistInfo['singerId'][0].toString() : null ) : artistInfo['singerId']); let artistName = artistInfo['artistName'] || artistInfo['singerName'] && (isObject(artistInfo['singerName']) ? ( artistInfo['singerName'].length > 0 ? artistInfo['singerName'][0].split(',')[0] : null ) : artistInfo['singerName']); let audios = []; if (isObject(info['auditions'])) { for (let tp of ['HQ', 'SQ', 'Bq']) { let url = info['auditions']['lis' + tp]; let size = info['auditions']['lis' + tp + 'Size']; if (!url) continue; let kbps; if (url.includes('MP3_128')) { kbps = 128; } else if (url.includes('MP3_320')) { kbps = 320; } else if (url.includes('flac')) { kbps = 720; } else { continue; } let audio = { format: url.split('.').slice(-1)[0], size, kbps, url, path: null, }; audios.push(audio); } } let song: ISong = { songId: _getSongId(songOriginalId), type: 'song', origin: _origin, songOriginalId, url: _getSongUrl(songOriginalId), songName: info['songName'] || (info['contentName'] || '').split(',')[0], songMid, albumId: _getAlbumId(albumOriginalId), albumOriginalId, albumName: albumInfo['albumName'] || info['cover'], albumCoverUrl: albumInfo['picS'], // migu cover image can't change size, // so we use the smallest one artistId: _getArtistId(artistOriginalId), artistOriginalId, artistName, lyricUrl: info['lyrics'], track: null, cdSerial: null, // millisecond duration: info['length'] && parseToMillisecond(info['length']), // millisecond releaseDate: null, playCountWeb: 0, playCount: 0, audios, disable: false, }; return song; } export function makeSongs(info: any): Array<ISong> { return (info || []).map(songInfo => makeSong(songInfo)); } export function makeLyric(songId: string, lyricInfo: string, transInfo: string): ILyric { if (!lyricInfo) return null; let lyric = _makeLyric(lyricInfo); let chunksMap = {}; lyric.chunks.forEach(chunk => chunksMap[chunk.point] = chunk); if (transInfo) { let trans = _makeLyric(transInfo); trans.chunks.forEach((chunk, index) => { let lyricChunk = chunksMap[chunk.point]; if (lyricChunk) lyricChunk.translation = chunk.text; }); } lyric.songId = _getSongId(songId); return lyric; } export function makeAlbum(info: any): IAlbum { let albumOriginalId = (info['albumId'] || info['id']).toString(); let albumCoverUrl = (info['localAlbumPicS'] || info['albumPicS'] || '').split('?')[0]; let artistOriginalId = null; let artistName = null; if (info['singerId']) { artistOriginalId = info['singerId'].toString(); } else { if (isObject(info['singer'])) { artistOriginalId = info['singer'][0]['id']; artistName = info['singer'][0]['name']; } } let album: IAlbum = { albumId: _getAlbumId(albumOriginalId), type: 'album', origin: _origin, albumOriginalId: albumOriginalId, url: _getAlbumUrl(albumOriginalId), albumName: info['albumName'] || info['title'], albumCoverUrl: albumCoverUrl, artistId: _getArtistId(artistOriginalId), artistOriginalId, artistName, tags: [], description: info['albumIntro'], releaseDate: parseToMillisecond(info['publishDate']), company: info['publishCompany'], songs: [], songCount: Number.parseInt(info['trackCount'] || info['songNum']), }; return album; } export function makeAlbums(info: any): Array<IAlbum> { return (info || []).map(albumInfo => makeAlbum(albumInfo)); } export function makeCollection(info: any): ICollection { let collectionOriginalId = (info['playListId'] || info['id']).toString(); let collectionCoverUrl = info['image'] || info['img']; let tags: Array<ITag> = (info['tagLists'] || []).map(tag => ({ name: tag['tagName'] })); let userOriginalId = info['createUserId'] || info['userId']; let userName = info['createName'] || info['userName']; let collection: ICollection = { collectionId: _getCollectionId(collectionOriginalId), type: 'collection', origin: _origin, collectionOriginalId, url: _getCollectionUrl(collectionOriginalId), collectionName: info['playListName'] || info['name'], collectionCoverUrl, userId: _getUserId(userOriginalId), userName, releaseDate: Date.parse(info['createTime']), description: info['summary'], tags, songs: [], songCount: Number.parseInt(info['contentCount'] || info['musicNum']), playCount: info['playCount'] || info['playNum'], likeCount: info['keepNum'], }; return collection; } export function extractCollectionSongIds(html: any): Array<string> { let m = /data-cids="([\da-zA-Z]+,[\da-zA-Z,]+)"/.exec(html); let songIds = m ? m[1].split(',').filter(id => !!id) : []; return songIds; } export function makeCollections(info: any): Array<ICollection> { return (info || []).map(collectionInfo => makeCollection(collectionInfo)); } export function makeArtist(info: any): IArtist { let artistOriginalId = (info['artistId'] || info['id']).toString(); let artistAvatarUrl = (info['localArtistPicS'] || info['artistPicS'] || '').split('?')[0]; let artist: IArtist = { artistId: _getArtistId(artistOriginalId), type: 'artist', origin: _origin, artistOriginalId: artistOriginalId, url: _getArtistUrl(artistOriginalId), artistName: info['artistName'] || info['title'], artistAlias: info['anotherName'], artistAvatarUrl: artistAvatarUrl, description: info['intro'], songs: [], albums: [], playCount: info['playCount'], }; return artist; } export function makeArtists(info: any): Array<IArtist> { return (info || []).map(artistInfo => makeArtist(artistInfo)); } export function extractArtistSongIds(html: any): Array<string> { let $ = cheerio.load(html); let songIds = Array.from(($('a.action') || [])).map(item => item.attribs['data-cids']).filter(id => !!id); return songIds; } export function makeArtistAlbums(html: any): Array<IAlbum> { let $ = cheerio.load(html); // Artist infos let elem = $('a.singer')[0]; if (!elem) return []; let artistOriginalId = elem.attribs.href.split('/').slice(-1)[0]; let artistName = elem.children[0].data; let description = $('div.full-content')[0].children[0].data; let albums = Array.from($('a.thumb-link')).map((item: any) => { let albumOriginalId = item.attribs.href.split('/').slice(-1)[0]; let img = item.children.filter(c => c.name == 'img')[0]; let albumCoverUrl = absoluteUrl(img.attribs['data-original']); let albumName = img.attribs.alt; let album = { albumId: _getAlbumId(albumOriginalId), type: 'album', origin: _origin, albumOriginalId: albumOriginalId, url: _getAlbumUrl(albumOriginalId), albumName, albumCoverUrl: albumCoverUrl, artistId: _getArtistId(artistOriginalId), artistOriginalId, artistName, tags: [], description, songs: [], } return album; }); return albums; }
the_stack
import * as assert from 'assert'; import { DODOContext, getDODOContext } from './utils/Context'; import { decimalStr } from './utils/Converter'; import { logGas } from './utils/Log'; let lp: string; let trader: string; async function init(ctx: DODOContext): Promise<void> { await ctx.setOraclePrice(decimalStr("100")); lp = ctx.spareAccounts[0]; trader = ctx.spareAccounts[1]; await ctx.approveDODO(lp); await ctx.approveDODO(trader); await ctx.mintTestToken(lp, decimalStr("10"), decimalStr("1000")); await ctx.mintTestToken(trader, decimalStr("10"), decimalStr("1000")); await ctx.DODO.methods .depositBaseTo(lp, decimalStr("10")) .send(ctx.sendParam(lp)); await ctx.DODO.methods .depositQuoteTo(lp, decimalStr("1000")) .send(ctx.sendParam(lp)); } describe("Trader", () => { let snapshotId: string; let ctx: DODOContext; before(async () => { ctx = await getDODOContext(); await init(ctx); }); beforeEach(async () => { snapshotId = await ctx.EVM.snapshot(); }); afterEach(async () => { await ctx.EVM.reset(snapshotId); }); describe("R goes above ONE", () => { it("buy when R equals ONE", async () => { await logGas(ctx.DODO.methods.buyBaseToken(decimalStr("1"), decimalStr("110"), "0x"), ctx.sendParam(trader), "buy base token when balanced") // trader balances assert.equal( await ctx.BASE.methods.balanceOf(trader).call(), decimalStr("11") ); assert.equal( await ctx.QUOTE.methods.balanceOf(trader).call(), "898581839502056240973" ); // maintainer balances assert.equal( await ctx.BASE.methods.balanceOf(ctx.Maintainer).call(), decimalStr("0.001") ); assert.equal( await ctx.QUOTE.methods.balanceOf(ctx.Maintainer).call(), decimalStr("0") ); // dodo balances assert.equal( await ctx.DODO.methods._BASE_BALANCE_().call(), decimalStr("8.999") ); assert.equal( await ctx.DODO.methods._QUOTE_BALANCE_().call(), "1101418160497943759027" ); // price update assert.equal( await ctx.DODO.methods.getMidPrice().call(), "102353368821735563400" ); }); it("buy when R is ABOVE ONE", async () => { await ctx.DODO.methods.buyBaseToken(decimalStr("1"), decimalStr("110"), "0x").send(ctx.sendParam(trader)) await logGas(ctx.DODO.methods.buyBaseToken(decimalStr("1"), decimalStr("130"), "0x"), ctx.sendParam(trader), "buy when R is ABOVE ONE") // trader balances assert.equal( await ctx.BASE.methods.balanceOf(trader).call(), decimalStr("12") ); assert.equal( await ctx.QUOTE.methods.balanceOf(trader).call(), "794367183433412077653" ); // maintainer balances assert.equal( await ctx.BASE.methods.balanceOf(ctx.Maintainer).call(), decimalStr("0.002") ); assert.equal( await ctx.QUOTE.methods.balanceOf(ctx.Maintainer).call(), decimalStr("0") ); // dodo balances assert.equal( await ctx.DODO.methods._BASE_BALANCE_().call(), decimalStr("7.998") ); assert.equal( await ctx.DODO.methods._QUOTE_BALANCE_().call(), "1205632816566587922347" ); }); it("sell when R is ABOVE ONE", async () => { await ctx.DODO.methods.buyBaseToken(decimalStr("1"), decimalStr("110"), "0x").send(ctx.sendParam(trader)) await logGas(ctx.DODO.methods.sellBaseToken(decimalStr("0.5"), decimalStr("40"), "0x"), ctx.sendParam(trader), "sell when R is ABOVE ONE") // trader balances assert.equal( await ctx.BASE.methods.balanceOf(trader).call(), decimalStr("10.5") ); assert.equal( await ctx.QUOTE.methods.balanceOf(trader).call(), "949280846351657143136" ); // maintainer balances assert.equal( await ctx.BASE.methods.balanceOf(ctx.Maintainer).call(), decimalStr("0.001") ); assert.equal( await ctx.QUOTE.methods.balanceOf(ctx.Maintainer).call(), "50851561534203512" ); // dodo balances assert.equal( await ctx.DODO.methods._BASE_BALANCE_().call(), decimalStr("9.499") ); assert.equal( await ctx.DODO.methods._QUOTE_BALANCE_().call(), "1050668302086808653352" ); }); it("sell when R is ABOVE ONE and RStatus back to ONE", async () => { await ctx.DODO.methods.buyBaseToken(decimalStr("1"), decimalStr("110"), "0x").send(ctx.sendParam(trader)) await logGas(ctx.DODO.methods.sellBaseToken("1003002430889317763", decimalStr("90"), "0x"), ctx.sendParam(trader), "sell when R is ABOVE ONE and RStatus back to ONE") // R status assert.equal(await ctx.DODO.methods._R_STATUS_().call(), "0"); // trader balances assert.equal( await ctx.BASE.methods.balanceOf(trader).call(), "9996997569110682237" ); assert.equal( await ctx.QUOTE.methods.balanceOf(trader).call(), "999695745518506168723" ); // maintainer balances assert.equal( await ctx.BASE.methods.balanceOf(ctx.Maintainer).call(), decimalStr("0.001") ); assert.equal( await ctx.QUOTE.methods.balanceOf(ctx.Maintainer).call(), "101418160497943759" ); // dodo balances assert.equal( await ctx.DODO.methods._BASE_BALANCE_().call(), "10002002430889317763" ); assert.equal( await ctx.DODO.methods._QUOTE_BALANCE_().call(), "1000202836320995887518" ); // target status assert.equal( await ctx.DODO.methods._TARGET_BASE_TOKEN_AMOUNT_().call(), "10002002430889317763" ); assert.equal( await ctx.DODO.methods._TARGET_QUOTE_TOKEN_AMOUNT_().call(), "1000202836320995887518" ); }); it("sell when R is ABOVE ONE and RStatus becomes BELOW ONE", async () => { await ctx.DODO.methods.buyBaseToken(decimalStr("1"), decimalStr("110"), "0x").send(ctx.sendParam(trader)) await logGas(ctx.DODO.methods.sellBaseToken(decimalStr("2"), decimalStr("90"), "0x"), ctx.sendParam(trader), "sell when R is ABOVE ONE and RStatus becomes BELOW ONE [gas cost worst case]") // R status assert.equal(await ctx.DODO.methods._R_STATUS_().call(), "2"); // trader balances assert.equal( await ctx.BASE.methods.balanceOf(trader).call(), decimalStr("9") ); assert.equal( await ctx.QUOTE.methods.balanceOf(trader).call(), "1098020621600061709144" ); // maintainer balances assert.equal( await ctx.BASE.methods.balanceOf(ctx.Maintainer).call(), decimalStr("0.001") ); assert.equal( await ctx.QUOTE.methods.balanceOf(ctx.Maintainer).call(), "200038898794388634" ); // dodo balances assert.equal( await ctx.DODO.methods._BASE_BALANCE_().call(), decimalStr("10.999") ); assert.equal( await ctx.DODO.methods._QUOTE_BALANCE_().call(), "901779339501143902222" ); // target status assert.equal( await ctx.DODO.methods._TARGET_BASE_TOKEN_AMOUNT_().call(), "10002002430889317763" ); assert.equal( await ctx.DODO.methods._TARGET_QUOTE_TOKEN_AMOUNT_().call(), "1000400077797588777268" ); }); }); describe("R goes below ONE", () => { it("sell when R equals ONE", async () => { await logGas(ctx.DODO.methods.sellBaseToken(decimalStr("1"), decimalStr("90"), "0x"), ctx.sendParam(trader), "sell base token when balanced") // trader balances assert.equal( await ctx.BASE.methods.balanceOf(trader).call(), decimalStr("9") ); assert.equal( await ctx.QUOTE.methods.balanceOf(trader).call(), "1098617454226610630663" ); // maintainer balances assert.equal( await ctx.BASE.methods.balanceOf(ctx.Maintainer).call(), "0" ); assert.equal( await ctx.QUOTE.methods.balanceOf(ctx.Maintainer).call(), "98914196817061816" ); // dodo balances assert.equal( await ctx.DODO.methods._BASE_BALANCE_().call(), decimalStr("11") ); assert.equal( await ctx.DODO.methods._QUOTE_BALANCE_().call(), "901283631576572307521" ); // price update assert.equal( await ctx.DODO.methods.getMidPrice().call(), "97736983274307939149" ); }); it("sell when R is BELOW ONE", async () => { await ctx.DODO.methods.sellBaseToken(decimalStr("3"), decimalStr("90"), "0x").send(ctx.sendParam(trader)) await logGas(ctx.DODO.methods.sellBaseToken(decimalStr("3"), decimalStr("90"), "0x"), ctx.sendParam(trader), "sell when R is BELOW ONE") // trader balances assert.equal( await ctx.BASE.methods.balanceOf(trader).call(), decimalStr("4") ); assert.equal( await ctx.QUOTE.methods.balanceOf(trader).call(), "1535961012052716726151" ); // maintainer balances assert.equal( await ctx.BASE.methods.balanceOf(ctx.Maintainer).call(), "0" ); assert.equal( await ctx.QUOTE.methods.balanceOf(ctx.Maintainer).call(), "537573733252474148" ); // dodo balances assert.equal( await ctx.DODO.methods._BASE_BALANCE_().call(), decimalStr("16") ); assert.equal( await ctx.DODO.methods._QUOTE_BALANCE_().call(), "463501414214030799701" ); }); it("buy when R is BELOW ONE", async () => { await ctx.DODO.methods.sellBaseToken(decimalStr("1"), decimalStr("90"), "0x").send(ctx.sendParam(trader)) await logGas(ctx.DODO.methods.buyBaseToken(decimalStr("0.5"), decimalStr("60"), "0x"), ctx.sendParam(trader), "buy when R is BELOW ONE") // trader balances assert.equal( await ctx.BASE.methods.balanceOf(trader).call(), decimalStr("9.5") ); assert.equal( await ctx.QUOTE.methods.balanceOf(trader).call(), "1049294316148665165453" ); // maintainer balances assert.equal( await ctx.BASE.methods.balanceOf(ctx.Maintainer).call(), decimalStr("0.0005") ); assert.equal( await ctx.QUOTE.methods.balanceOf(ctx.Maintainer).call(), "98914196817061816" ); // dodo balances assert.equal( await ctx.DODO.methods._BASE_BALANCE_().call(), decimalStr("10.4995") ); assert.equal( await ctx.DODO.methods._QUOTE_BALANCE_().call(), "950606769654517772731" ); }); it("buy when R is BELOW ONE and RStatus back to ONE", async () => { await ctx.DODO.methods.sellBaseToken(decimalStr("1"), decimalStr("90"), "0x").send(ctx.sendParam(trader)) await logGas(ctx.DODO.methods.buyBaseToken("997008973080757728", decimalStr("110"), "0x"), ctx.sendParam(trader), "buy when R is BELOW ONE and RStatus back to ONE") // R status assert.equal(await ctx.DODO.methods._R_STATUS_().call(), "0"); // trader balances assert.equal( await ctx.BASE.methods.balanceOf(trader).call(), "9997008973080757728" ); assert.equal( await ctx.QUOTE.methods.balanceOf(trader).call(), "999703024198699411500" ); // maintainer balances assert.equal( await ctx.BASE.methods.balanceOf(ctx.Maintainer).call(), "997008973080757" ); assert.equal( await ctx.QUOTE.methods.balanceOf(ctx.Maintainer).call(), "98914196817061816" ); // dodo balances assert.equal( await ctx.DODO.methods._BASE_BALANCE_().call(), "10001994017946161515" ); assert.equal( await ctx.DODO.methods._QUOTE_BALANCE_().call(), "1000198061604483526684" ); // target status assert.equal( await ctx.DODO.methods._TARGET_BASE_TOKEN_AMOUNT_().call(), "10001994017946161515" ); assert.equal( await ctx.DODO.methods._TARGET_QUOTE_TOKEN_AMOUNT_().call(), "1000198061604483526684" ); }); it("buy when R is BELOW ONE and RStatus becomes ABOVE ONE", async () => { await ctx.DODO.methods.sellBaseToken(decimalStr("1"), decimalStr("90"), "0x").send(ctx.sendParam(trader)) await logGas(ctx.DODO.methods.buyBaseToken(decimalStr("2"), decimalStr("220"), "0x"), ctx.sendParam(trader), "buy when R is BELOW ONE and RStatus becomes ABOVE ONE [gas cost worst case]") // R status assert.equal(await ctx.DODO.methods._R_STATUS_().call(), "1"); // trader balances assert.equal( await ctx.BASE.methods.balanceOf(trader).call(), decimalStr("11") ); assert.equal( await ctx.QUOTE.methods.balanceOf(trader).call(), "897977789597854403796" ); // maintainer balances assert.equal( await ctx.BASE.methods.balanceOf(ctx.Maintainer).call(), decimalStr("0.002") ); assert.equal( await ctx.QUOTE.methods.balanceOf(ctx.Maintainer).call(), "98914196817061816" ); // dodo balances assert.equal( await ctx.DODO.methods._BASE_BALANCE_().call(), decimalStr("8.998") ); assert.equal( await ctx.DODO.methods._QUOTE_BALANCE_().call(), "1101923296205328534388" ); // target status assert.equal( await ctx.DODO.methods._TARGET_BASE_TOKEN_AMOUNT_().call(), "10004000000000000000" ); assert.equal( await ctx.DODO.methods._TARGET_QUOTE_TOKEN_AMOUNT_().call(), "1000198061604483526684" ); }); }); describe("Corner cases", () => { it("buy or sell 0", async () => { await ctx.DODO.methods .sellBaseToken(decimalStr("0"), decimalStr("0"), "0x") .send(ctx.sendParam(trader)); assert.equal( await ctx.BASE.methods.balanceOf(trader).call(), decimalStr("10") ); assert.equal( await ctx.QUOTE.methods.balanceOf(trader).call(), decimalStr("1000") ); await ctx.DODO.methods .buyBaseToken(decimalStr("0"), decimalStr("0"), "0x") .send(ctx.sendParam(trader)); assert.equal( await ctx.BASE.methods.balanceOf(trader).call(), decimalStr("10") ); assert.equal( await ctx.QUOTE.methods.balanceOf(trader).call(), decimalStr("1000") ); }); it("buy or sell a tiny amount", async () => { // no precision problem await ctx.DODO.methods .sellBaseToken("1", decimalStr("0"), "0x") .send(ctx.sendParam(trader)); assert.equal( await ctx.BASE.methods.balanceOf(trader).call(), "9999999999999999999" ); assert.equal( await ctx.QUOTE.methods.balanceOf(trader).call(), "1000000000000000000100" ); // have precision problem, charge 0 await ctx.DODO.methods .buyBaseToken("1", decimalStr("1"), "0x") .send(ctx.sendParam(trader)); assert.equal( await ctx.BASE.methods.balanceOf(trader).call(), "10000000000000000000" ); assert.equal( await ctx.QUOTE.methods.balanceOf(trader).call(), "1000000000000000000100" ); assert.equal(await ctx.DODO.methods._R_STATUS_().call(), "0"); // no precision problem if trading amount is extremely small await ctx.DODO.methods .buyBaseToken("10", decimalStr("1"), "0x") .send(ctx.sendParam(trader)); assert.equal( await ctx.BASE.methods.balanceOf(trader).call(), "10000000000000000010" ); assert.equal( await ctx.QUOTE.methods.balanceOf(trader).call(), "999999999999999999100" ); }); it("sell a huge amount of base token", async () => { await ctx.mintTestToken(trader, decimalStr("10000"), "0"); await ctx.DODO.methods .sellBaseToken(decimalStr("10000"), "0", "0x") .send(ctx.sendParam(trader)); // nearly drain out quote pool // because the fee donated is greater than remaining quote pool // quote lp earn a considerable profit assert.equal( await ctx.QUOTE.methods.balanceOf(trader).call(), "1996900220185135480813" ); assert.equal( await ctx.DODO.methods.getLpQuoteBalance(lp).call(), "4574057156329524019750" ); }); }); describe("Revert cases", () => { it("price limit", async () => { await assert.rejects( ctx.DODO.methods .buyBaseToken(decimalStr("1"), decimalStr("100"), "0x") .send(ctx.sendParam(trader)), /BUY_BASE_COST_TOO_MUCH/ ); await assert.rejects( ctx.DODO.methods .sellBaseToken(decimalStr("1"), decimalStr("100"), "0x") .send(ctx.sendParam(trader)), /SELL_BASE_RECEIVE_NOT_ENOUGH/ ); }); it("base balance limit", async () => { await assert.rejects( ctx.DODO.methods .buyBaseToken(decimalStr("11"), decimalStr("10000"), "0x") .send(ctx.sendParam(trader)), /DODO_BASE_BALANCE_NOT_ENOUGH/ ); await ctx.DODO.methods .buyBaseToken(decimalStr("1"), decimalStr("200"), "0x") .send(ctx.sendParam(trader)); await assert.rejects( ctx.DODO.methods .buyBaseToken(decimalStr("11"), decimalStr("10000"), "0x") .send(ctx.sendParam(trader)), /DODO_BASE_BALANCE_NOT_ENOUGH/ ); }); }); });
the_stack
import fs from 'fs-extra'; import mimeTypes from 'mime-types'; import { basename, dirname, extname, join, relative, resolve } from 'path'; import { Builder, BuildResultV2, BuildResultV3, File, FileFsRef, BuilderV2, BuilderV3, Lambda, PackageJson, Prerender, download, EdgeFunction, BuildResultBuildOutput, } from '@vercel/build-utils'; import pipe from 'promisepipe'; import { unzip } from './unzip'; import { VERCEL_DIR } from '../projects/link'; export const OUTPUT_DIR = join(VERCEL_DIR, 'output'); export async function writeBuildResult( outputDir: string, buildResult: BuildResultV2 | BuildResultV3, build: Builder, builder: BuilderV2 | BuilderV3, builderPkg: PackageJson, cleanUrls?: boolean ) { const { version } = builder; if (version === 2) { return writeBuildResultV2( outputDir, buildResult as BuildResultV2, cleanUrls ); } else if (version === 3) { return writeBuildResultV3(outputDir, buildResult as BuildResultV3, build); } throw new Error( `Unsupported Builder version \`${version}\` from "${builderPkg.name}"` ); } function isEdgeFunction(v: any): v is EdgeFunction { return v?.type === 'EdgeFunction'; } function isLambda(v: any): v is Lambda { return v?.type === 'Lambda'; } function isPrerender(v: any): v is Prerender { return v?.type === 'Prerender'; } function isFile(v: any): v is File { const type = v?.type; return type === 'FileRef' || type === 'FileFsRef' || type === 'FileBlob'; } export interface PathOverride { contentType?: string; path?: string; } /** * Writes the output from the `build()` return value of a v2 Builder to * the filesystem. */ async function writeBuildResultV2( outputDir: string, buildResult: BuildResultV2, cleanUrls?: boolean ) { if ('buildOutputPath' in buildResult) { await mergeBuilderOutput(outputDir, buildResult); return; } const lambdas = new Map<Lambda, string>(); const overrides: Record<string, PathOverride> = {}; for (const [path, output] of Object.entries(buildResult.output)) { if (isLambda(output)) { await writeLambda(outputDir, output, path, lambdas); } else if (isPrerender(output)) { await writeLambda(outputDir, output.lambda, path, lambdas); // Write the fallback file alongside the Lambda directory let fallback = output.fallback; if (fallback) { const ext = getFileExtension(fallback); const fallbackName = `${path}.prerender-fallback${ext}`; const fallbackPath = join(outputDir, 'functions', fallbackName); const stream = fallback.toStream(); await pipe( stream, fs.createWriteStream(fallbackPath, { mode: fallback.mode }) ); fallback = new FileFsRef({ ...output.fallback, fsPath: basename(fallbackName), }); } const prerenderConfigPath = join( outputDir, 'functions', `${path}.prerender-config.json` ); const prerenderConfig = { ...output, lambda: undefined, fallback, }; await fs.writeJSON(prerenderConfigPath, prerenderConfig, { spaces: 2 }); } else if (isFile(output)) { await writeStaticFile(outputDir, output, path, overrides, cleanUrls); } else if (isEdgeFunction(output)) { await writeEdgeFunction(outputDir, output, path); } else { throw new Error( `Unsupported output type: "${(output as any).type}" for ${path}` ); } } return Object.keys(overrides).length > 0 ? overrides : undefined; } /** * Writes the output from the `build()` return value of a v3 Builder to * the filesystem. */ async function writeBuildResultV3( outputDir: string, buildResult: BuildResultV3, build: Builder ) { const { output } = buildResult; const src = build.src; if (typeof src !== 'string') { throw new Error(`Expected "build.src" to be a string`); } const ext = extname(src); const path = build.config?.zeroConfig ? src.substring(0, src.length - ext.length) : src; if (isLambda(output)) { await writeLambda(outputDir, output, path); } else if (isEdgeFunction(output)) { await writeEdgeFunction(outputDir, output, path); } else { throw new Error( `Unsupported output type: "${(output as any).type}" for ${build.src}` ); } } /** * Writes a static `File` instance to the file system in the "static" directory. * If the filename does not have a file extension then one attempts to be inferred * from the extension of the `fsPath`. * * @param file The `File` instance to write * @param path The URL path where the `File` can be accessed from * @param overrides Record of override configuration when a File is renamed or has other metadata */ async function writeStaticFile( outputDir: string, file: File, path: string, overrides: Record<string, PathOverride>, cleanUrls = false ) { let fsPath = path; let override: PathOverride | null = null; // If the output path doesn't match the determined file extension of // the File then add the extension. This is to help avoid conflicts // where an output path matches a directory name of another output path // (i.e. `blog` -> `blog.html` and `blog/hello` -> `blog/hello.html`) const ext = getFileExtension(file); if (ext && extname(path) !== ext) { fsPath += ext; if (!override) override = {}; override.path = path; } // If `cleanUrls` is true then remove the `.html` file extension // for HTML files. if (cleanUrls && path.endsWith('.html')) { if (!override) override = {}; override.path = path.slice(0, -5); } // Ensure an explicit "content-type" on the `File` is returned in // the final output asset. if (file.contentType) { if (!override) override = {}; override.contentType = file.contentType; } if (override) { overrides[fsPath] = override; } const dest = join(outputDir, 'static', fsPath); await fs.mkdirp(dirname(dest)); // TODO: handle (or skip) symlinks? const stream = file.toStream(); await pipe(stream, fs.createWriteStream(dest, { mode: file.mode })); } /** * Serializes the `EdgeFunction` instance to the file system. * * @param edgeFunction The `EdgeFunction` instance * @param path The URL path where the `EdgeFunction` can be accessed from */ async function writeEdgeFunction( outputDir: string, edgeFunction: EdgeFunction, path: string ) { const dest = join(outputDir, 'functions', `${path}.func`); await fs.mkdirp(dest); const ops: Promise<any>[] = []; ops.push(download(edgeFunction.files, dest)); const config = { runtime: 'edge', ...edgeFunction, files: undefined, type: undefined, }; const configPath = join(dest, '.vc-config.json'); ops.push( fs.writeJSON(configPath, config, { spaces: 2, }) ); await Promise.all(ops); } /** * Writes the file references from the `Lambda` instance to the file system. * * @param lambda The `Lambda` instance * @param path The URL path where the `Lambda` can be accessed from * @param lambdas (optional) Map of `Lambda` instances that have previously been written */ async function writeLambda( outputDir: string, lambda: Lambda, path: string, lambdas?: Map<Lambda, string> ) { const dest = join(outputDir, 'functions', `${path}.func`); // If the `lambda` has already been written to the filesystem at a different // location then create a symlink to the previous location instead of copying // the files again. const existingLambdaPath = lambdas?.get(lambda); if (existingLambdaPath) { const destDir = dirname(dest); const targetDest = join( outputDir, 'functions', `${existingLambdaPath}.func` ); const target = relative(destDir, targetDest); await fs.mkdirp(destDir); await fs.symlink(target, dest); return; } lambdas?.set(lambda, path); await fs.mkdirp(dest); const ops: Promise<any>[] = []; if (lambda.files) { // `files` is defined ops.push(download(lambda.files, dest)); } else if (lambda.zipBuffer) { // Builders that use the deprecated `createLambda()` might only have `zipBuffer` ops.push(unzip(lambda.zipBuffer, dest)); } else { throw new Error('Malformed `Lambda` - no "files" present'); } const config = { ...lambda, type: undefined, files: undefined, zipBuffer: undefined, }; const configPath = join(dest, '.vc-config.json'); ops.push( fs.writeJSON(configPath, config, { spaces: 2, }) ); await Promise.all(ops); // XXX: remove any `.vercel/builders` directories that were // extracted into the `dest` dir. This is a temporary band-aid // to make `vercel-php` work since it is inadvertently including // `.vercel/builders` into the Lambda files due to glob syntax. // See: https://github.com/juicyfx/vercel-php/pull/232 for await (const dir of findDirs('.vercel', dest)) { const absDir = join(dest, dir); const entries = await fs.readdir(absDir); if (entries.includes('cache')) { // Delete everything except for "cache" await Promise.all( entries .filter(e => e !== 'cache') .map(entry => fs.remove(join(absDir, entry))) ); } else { // Delete the entire `.vercel` directory await fs.remove(absDir); } } } /** * When the Root Directory setting is utilized, merge the contents of the * `.vercel/output` directory that was specified by the Builder into the * `vc build` output directory. */ async function mergeBuilderOutput( outputDir: string, buildResult: BuildResultBuildOutput ) { const absOutputDir = resolve(outputDir); if (absOutputDir === buildResult.buildOutputPath) { // `.vercel/output` dir is already in the correct location, // so no need to do anything return; } await fs.copy(buildResult.buildOutputPath, outputDir); } /** * Attempts to return the file extension (i.e. `.html`) from the given * `File` instance, based on its actual filesystem path and/or the * "content-type" of the File. */ function getFileExtension(file: File): string { let ext = ''; if (file.type === 'FileFsRef') { ext = extname(file.fsPath); } if (!ext && file.contentType) { const e = mimeTypes.extension(file.contentType); if (e) { ext = `.${e}`; } } return ext; } /** * Creates an async iterator that scans a directory * for sub-directories with the matching `name`. */ export async function* findDirs( name: string, dir: string, root = dir ): AsyncIterable<string> { let paths: string[]; try { paths = await fs.readdir(dir); } catch (err: any) { if (err.code !== 'ENOENT') { throw err; } paths = []; } for (const path of paths) { const abs = join(dir, path); const s = await fs.stat(abs); if (s.isDirectory()) { if (path === name) { yield relative(root, abs); } else { yield* findDirs(name, abs, root); } } } }
the_stack
export type StringHint = string & { zz_ignore_me?: never }; export type NumberHint = number & { zz_ignore_me?: never }; export type CSSValueGeneral = NumberHint | StringHint; export type CSSGlobalValues = | "initial" | "inherit" | /** combination of `initial` and `inherit` */ "unset" | "revert" | StringHint; export type CSSBlendMode = | "normal" | "multiply" | "screen" | "overlay" | "darken" | "lighten" | "color-dodge" | "color-burn" | "hard-light" | "soft-light" | "difference" | "exclusion" | "hue" | "saturation" | "color" | "luminosity"; export type CSSBox = "border-box" | "padding-box" | "content-box" | CSSGlobalValues | StringHint; export type CSSColor = "transparent" | "currentColor" | CSSGlobalValues | StringHint; export type CSSFlexAlign = "flex-start" | "flex-end" | "center" | "baseline" | "stretch"; export type CSSFontSize = | CSSGlobalValues | CSSValueGeneral | "xx-small" | "x-small" | "small" | "medium" | "large" | "x-large" | "xx-large" | "larger" | "smaller"; export type CSSLineStyle = | StringHint | "none" | "hidden" | "dotted" | "dashed" | "solid" | "double" | "groove" | "ridge" | "inset" | "outset"; export type CSSOverflow = "visible" | "hidden" | "scroll" | "clip" | "auto"; export type CSSRepeatStyle = StringHint | "repeat-x" | "repeat-y" | "repeat" | "space" | "round" | "no-repeat"; export type CSSFontWeight = | "normal" | "bold" | "bolder" | "lighter" | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900 | CSSValueGeneral | CSSGlobalValues; export type CSSLazy<T> = T | StringHint | ((styles: CSSInlineStyles, key: string) => T | StringHint); export type CSSLazyString = CSSLazy<string>; export type CSSLazyValueGeneral = CSSLazy<CSSValueGeneral>; /** * This interface documents key CSS properties for autocomplete */ export interface CSSInlineStyles { /** * Smooth scrolling on an iPhone. Specifies whether to use native-style scrolling in an element. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/-webkit-overflow-scrolling */ overflowScrolling?: CSSLazy<"auto" | "touch">; /** * Aligns a flex container's lines within the flex container when there is extra space in the cross-axis, similar to how justify-content aligns individual items within the main-axis. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/align-content */ alignContent?: CSSLazy< "stretch" | "center" | "flex-start" | "flex-end" | "space-between" | "space-around" | "initial" | "inherit" >; /** * Sets the default alignment in the cross axis for all of the flex container's items, including anonymous flex items, similarly to how justify-content aligns items along the main axis. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/align-items */ alignItems?: CSSLazy<CSSFlexAlign>; /** * Allows the default alignment to be overridden for individual flex items. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/align-self */ alignSelf?: CSSLazy<"auto" | CSSFlexAlign>; /** * This property allows precise alignment of elements, such as graphics, that do not have a baseline-table or lack the desired baseline in their baseline-table. With the alignment-adjust property, the position of the baseline identified by the alignment-baseline can be explicitly determined. It also determines precisely the alignment point for each glyph within a textual element. */ alignmentAdjust?: CSSLazyValueGeneral; /** * The alignment-baseline attribute specifies how an object is aligned with respect to its parent. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/alignment-baseline */ alignmentBaseline?: CSSLazy< | "auto" | "baseline" | "before-edge" | "text-before-edge" | "middle" | "central" | "after-edge" | "text-after-edge" | "ideographic" | "alphabetic" | "hanging" | "mathematical" | "inherit" >; /** * Shorthand property for animation-name, animation-duration, animation-timing-function, animation-delay, * animation-iteration-count, animation-direction, animation-fill-mode, and animation-play-state. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/animation */ animation?: CSSLazyString; /** * Defines a length of time to elapse before an animation starts, allowing an animation to begin execution some time after it is applied. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/animation-delay */ animationDelay?: CSSLazyValueGeneral; /** * Defines whether an animation should run in reverse on some or all cycles. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/animation-direction */ animationDirection?: CSSLazy<CSSGlobalValues | "normal" | "alternate" | "reverse" | "alternate-reverse">; /** * The animation-duration CSS property specifies the length of time that an animation should take to complete one cycle. * A value of '0s', which is the default value, indicates that no animation should occur. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/animation-duration */ animationDuration?: CSSLazyString; /** * Specifies how a CSS animation should apply styles to its target before and after it is executing. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/animation-fill-mode */ animationFillMode?: CSSLazy<"none" | "forwards" | "backwards" | "both">; /** * Specifies how many times an animation cycle should play. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/animation-iteration-count */ animationIterationCount?: CSSLazy<CSSValueGeneral | "infinite">; /** * Defines the list of animations that apply to the element. * Note: You probably want animationDuration as well * @see https://developer.mozilla.org/en-US/docs/Web/CSS/animation-name */ animationName?: CSSLazyString; /** * Defines whether an animation is running or paused. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/animation-play-state */ animationPlayState?: CSSLazyString; /** * Sets the pace of an animation * @see https://developer.mozilla.org/en-US/docs/Web/CSS/animation-timing-function */ animationTimingFunction?: CSSLazyString; /** * Allows changing the style of any element to platform-based interface elements or vice versa. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/appearance */ appearance?: CSSLazy<"auto" | "none">; /** * Determines whether or not the “back” side of a transformed element is visible when facing the viewer. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/backface-visibility */ backfaceVisibility?: CSSLazy<CSSGlobalValues | "visible" | "hidden">; /** * Shorthand property to set the values for one or more of: * background-clip, background-color, background-image, * background-origin, background-position, background-repeat, * background-size, and background-attachment. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/background */ background?: CSSLazyString; /** * If a background-image is specified, this property determines * whether that image's position is fixed within the viewport, * or scrolls along with its containing block. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/background-attachment */ backgroundAttachment?: CSSLazy<"scroll" | "fixed" | "local">; /** * This property describes how the element's background images should blend with each other and the element's background color. * The value is a list of blend modes that corresponds to each background image. Each element in the list will apply to the corresponding element of background-image. If a property doesn’t have enough comma-separated values to match the number of layers, the UA must calculate its used value by repeating the list of values until there are enough. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/background-blend-mode */ backgroundBlendMode?: CSSLazy<CSSBlendMode>; /** * Specifies whether an element's background, either the color or image, extends underneath its border. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/background-clip */ backgroundClip?: CSSLazy<CSSBox | "text">; /** * Sets the background color of an element. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/background-color */ backgroundColor?: CSSLazy<CSSColor>; /** * Sets a compositing style for background images and colors. */ backgroundComposite?: CSSLazyString; /** * Applies one or more background images to an element. These can be any valid CSS image, including url() paths to image files or CSS gradients. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/background-image */ backgroundImage?: CSSLazyString; /** * Specifies what the background-position property is relative to. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/background-origin */ backgroundOrigin?: CSSLazy<CSSBox>; /** * Sets the position of a background image. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/background-position */ backgroundPosition?: CSSLazy<CSSValueGeneral | "top" | "bottom" | "left" | "right" | "center" | CSSGlobalValues>; /** * Background-repeat defines if and how background images will be repeated after they have been sized and positioned * @see https://developer.mozilla.org/en-US/docs/Web/CSS/background-repeat */ backgroundRepeat?: CSSLazy<CSSRepeatStyle>; /** * Background-size specifies the size of a background image * @see https://developer.mozilla.org/en-US/docs/Web/CSS/background-size */ backgroundSize?: CSSLazy<"auto" | "cover" | "contain" | CSSValueGeneral | CSSGlobalValues>; /** * Shorthand property that defines the different properties of all four sides of an element's border in a single declaration. It can be used to set border-width, border-style and border-color, or a subset of these. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border */ border?: CSSLazyValueGeneral; /** * Shorthand that sets the values of border-bottom-color, * border-bottom-style, and border-bottom-width. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom */ borderBottom?: CSSLazyValueGeneral; /** * Sets the color of the bottom border of an element. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-color */ borderBottomColor?: CSSLazy<CSSColor>; /** * Defines the shape of the border of the bottom-left corner. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-left-radius */ borderBottomLeftRadius?: CSSLazyValueGeneral; /** * Defines the shape of the border of the bottom-right corner. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-right-radius */ borderBottomRightRadius?: CSSLazyValueGeneral; /** * Sets the line style of the bottom border of a box. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-style */ borderBottomStyle?: CSSLazy<CSSLineStyle>; /** * Sets the width of an element's bottom border. To set all four borders, use the border-width shorthand property which sets the values simultaneously for border-top-width, border-right-width, border-bottom-width, and border-left-width. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-bottom-width */ borderBottomWidth?: CSSLazyValueGeneral; /** * Border-collapse can be used for collapsing the borders between table cells * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-collapse */ borderCollapse?: CSSLazy<"collapse" | "separate" | "inherit">; /** * The CSS border-color property sets the color of an element's four borders. This property can have from one to four values, made up of the elementary properties: * • border-top-color * • border-right-color * • border-bottom-color * • border-left-color The default color is the currentColor of each of these values. * If you provide one value, it sets the color for the element. Two values set the horizontal and vertical values, respectively. Providing three values sets the top, vertical, and bottom values, in that order. Four values set all for sides: top, right, bottom, and left, in that order. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-color */ borderColor?: CSSLazy<CSSColor>; /** * Specifies different corner clipping effects, such as scoop (inner curves), bevel (straight cuts) or notch (cut-off rectangles). Works along with border-radius to specify the size of each corner effect. */ borderCornerShape?: CSSLazyValueGeneral; /** * The property border-image-source is used to set the image to be used instead of the border style. If this is set to none the border-style is used instead. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-image-source */ borderImageSource?: CSSLazyString; /** * The border-image-width CSS property defines the offset to use for dividing the border image in nine parts, the top-left corner, central top edge, top-right-corner, central right edge, bottom-right corner, central bottom edge, bottom-left corner, and central right edge. They represent inward distance from the top, right, bottom, and left edges. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-image-width */ borderImageWidth?: CSSLazyValueGeneral; /** * Shorthand property that defines the border-width, border-style and border-color of an element's left border in a single declaration. Note that you can use the corresponding longhand properties to set specific individual properties of the left border — border-left-width, border-left-style and border-left-color. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-left */ borderLeft?: CSSLazyValueGeneral; /** * The CSS border-left-color property sets the color of an element's left border. This page explains the border-left-color value, but often you will find it more convenient to fix the border's left color as part of a shorthand set, either border-left or border-color. * Colors can be defined several ways. For more information, see Usage. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-left-color */ borderLeftColor?: CSSLazy<CSSColor>; /** * Sets the style of an element's left border. To set all four borders, use the shorthand property, border-style. Otherwise, you can set the borders individually with border-top-style, border-right-style, border-bottom-style, border-left-style. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-left-style */ borderLeftStyle?: CSSLazy<CSSLineStyle>; /** * Sets the width of an element's left border. To set all four borders, use the border-width shorthand property which sets the values simultaneously for border-top-width, border-right-width, border-bottom-width, and border-left-width. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-left-width */ borderLeftWidth?: CSSLazyValueGeneral; /** * Allows Web authors to define how rounded border corners are * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-radius */ borderRadius?: CSSLazyValueGeneral; /** * Shorthand property that defines the border-width, border-style and border-color of an element's right border in a single declaration. Note that you can use the corresponding longhand properties to set specific individual properties of the right border — border-right-width, border-right-style and border-right-color. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-right */ borderRight?: CSSLazyValueGeneral; /** * Sets the color of an element's right border. This page explains the border-right-color value, but often you will find it more convenient to fix the border's right color as part of a shorthand set, either border-right or border-color. * Colors can be defined several ways. For more information, see Usage. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-right-color */ borderRightColor?: CSSLazy<CSSColor>; /** * Sets the style of an element's right border. To set all four borders, use the shorthand property, border-style. Otherwise, you can set the borders individually with border-top-style, border-right-style, border-bottom-style, border-left-style. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-right-style */ borderRightStyle?: CSSLazy<CSSLineStyle>; /** * Sets the width of an element's right border. To set all four borders, use the border-width shorthand property which sets the values simultaneously for border-top-width, border-right-width, border-bottom-width, and border-left-width. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-right-width */ borderRightWidth?: CSSLazyValueGeneral; /** * Specifies the distance between the borders of adjacent cells. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-spacing */ borderSpacing?: CSSLazyValueGeneral; /** * Sets the style of an element's four borders. This property can have from one to four values. With only one value, the value will be applied to all four borders; otherwise, this works as a shorthand property for each of border-top-style, border-right-style, border-bottom-style, border-left-style, where each border style may be assigned a separate value. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-style */ borderStyle?: CSSLazy<CSSLineStyle>; /** * Shorthand property that defines the border-width, border-style and border-color of an element's top border in a single declaration. Note that you can use the corresponding longhand properties to set specific individual properties of the top border — border-top-width, border-top-style and border-top-color. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-top */ borderTop?: CSSLazyValueGeneral; /** * Sets the color of an element's top border. This page explains the border-top-color value, but often you will find it more convenient to fix the border's top color as part of a shorthand set, either border-top or border-color. * Colors can be defined several ways. For more information, see Usage. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-color */ borderTopColor?: CSSLazy<CSSColor>; /** * Sets the rounding of the top-left corner of the element. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-left-radius */ borderTopLeftRadius?: CSSLazyValueGeneral; /** * Sets the rounding of the top-right corner of the element. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-right-radius */ borderTopRightRadius?: CSSLazyValueGeneral; /** * Sets the style of an element's top border. To set all four borders, use the shorthand property, border-style. Otherwise, you can set the borders individually with border-top-style, border-right-style, border-bottom-style, border-left-style. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-style */ borderTopStyle?: CSSLazy<CSSLineStyle>; /** * Sets the width of an element's top border. To set all four borders, use the border-width shorthand property which sets the values simultaneously for border-top-width, border-right-width, border-bottom-width, and border-left-width. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-top-width */ borderTopWidth?: CSSLazyValueGeneral; /** * Sets the width of an element's four borders. This property can have from one to four values. This is a shorthand property for setting values simultaneously for border-top-width, border-right-width, border-bottom-width, and border-left-width. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/border-width */ borderWidth?: CSSLazyValueGeneral; /** * This property specifies how far an absolutely positioned box's bottom margin edge is offset above the bottom edge of the box's containing block. For relatively positioned boxes, the offset is with respect to the bottom edges of the box itself (i.e., the box is given a position in the normal flow, then offset from that position according to these properties). * @see https://developer.mozilla.org/en-US/docs/Web/CSS/bottom */ bottom?: CSSLazyValueGeneral; /** * Breaks a box into fragments creating new borders, padding and repeating backgrounds or lets it stay as a continuous box on a page break, column break, or, for inline elements, at a line break. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/box-decoration-break */ boxDecorationBreak?: CSSLazy<"slice" | "clone">; /** * box sizing * @see https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing */ boxSizing?: CSSLazy<CSSGlobalValues | "content-box" | "border-box">; /** * Box shadow * @see https://developer.mozilla.org/en-US/docs/Web/CSS/box-shadow */ boxShadow?: CSSLazyValueGeneral; /** * The CSS break-after property allows you to force a break on multi-column layouts. More specifically, it allows you to force a break after an element. It allows you to determine if a break should occur, and what type of break it should be. The break-after CSS property describes how the page, column or region break behaves after the generated box. If there is no generated box, the property is ignored. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/break-after */ breakAfter?: CSSLazy< | "auto" | "avoid" | "avoid-page" | "page" | "left" | "right" | "recto" | "verso" | "avoid-column" | "column" | "avoid-region" | "region" >; /** * Control page/column/region breaks that fall above a block of content * @see https://developer.mozilla.org/en-US/docs/Web/CSS/break-before */ breakBefore?: CSSLazy< | "auto" | "avoid" | "avoid-page" | "page" | "left" | "right" | "recto" | "verso" | "avoid-column" | "column" | "avoid-region" | "region" >; /** * Control page/column/region breaks that fall within a block of content * @see https://developer.mozilla.org/en-US/docs/Web/CSS/break-inside */ breakInside?: CSSLazy<"auto" | "avoid" | "avoid-page" | "avoid-column" | "avoid-region">; /** * The caption-side CSS property positions the content of a table's <caption> on the specified side. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/caption-side */ captionSide?: CSSLazy< CSSGlobalValues | "top" | "bottom" | "block-start" | "block-end" | "inline-start" | "inline-end" >; /** * The clear CSS property specifies if an element can be positioned next to or must be positioned below the floating elements that precede it in the markup. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/clear */ clear?: CSSLazy<CSSGlobalValues | "none" | "left" | "right" | "both">; /** * Clipping crops an graphic, so that only a portion of the graphic is rendered, or filled. This clip-rule property, when used with the clip-path property, defines which clip rule, or algorithm, to use when filling the different parts of a graphics. * @see https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/clip-rule */ clipRule?: CSSLazyString; /** * The color property sets the color of an element's foreground content (usually text), accepting any standard CSS color from keywords and hex values to RGB(a) and HSL(a). * @see https://developer.mozilla.org/en-US/docs/Web/CSS/color */ color?: CSSLazy<CSSColor>; /** * Describes the number of columns of the element. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/column-count */ columnCount?: CSSLazyValueGeneral; /** * Specifies how to fill columns (balanced or sequential). * @see https://developer.mozilla.org/en-US/docs/Web/CSS/column-fill */ columnFill?: CSSLazyString; /** * The column-gap property controls the width of the gap between columns in multi-column elements. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/column-gap */ columnGap?: CSSLazyValueGeneral; /** * Sets the width, style, and color of the rule between columns. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/column-rule */ columnRule?: CSSLazyString; /** * Specifies the color of the rule between columns. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/column-rule-color */ columnRuleColor?: CSSLazy<CSSColor>; /** * Specifies the width of the rule between columns. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/column-rule-width */ columnRuleWidth?: CSSLazyValueGeneral; /** * The column-span CSS property makes it possible for an element to span across all columns when its value is set to all. An element that spans more than one column is called a spanning element. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/column-span */ columnSpan?: CSSLazyValueGeneral; /** * Specifies the width of columns in multi-column elements. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/column-width */ columnWidth?: CSSLazyValueGeneral; /** * This property is a shorthand property for setting column-width and/or column-count. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/columns */ columns?: CSSLazyValueGeneral; /** * The content property is used with the :before and :after pseudo-elements, to insert generated content. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/content */ content?: CSSLazyString; /** * The counter-increment property accepts one or more names of counters (identifiers), each one optionally followed by an integer which specifies the value by which the counter should be incremented (e.g. if the value is 2, the counter increases by 2 each time it is invoked). * @see https://developer.mozilla.org/en-US/docs/Web/CSS/counter-increment */ counterIncrement?: CSSLazyValueGeneral; /** * The counter-reset property contains a list of one or more names of counters, each one optionally followed by an integer (otherwise, the integer defaults to 0.) Each time the given element is invoked, the counters specified by the property are set to the given integer. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/counter-reset */ counterReset?: CSSLazyValueGeneral; /** * Specifies the mouse cursor displayed when the mouse pointer is over an element. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/cursor */ cursor?: CSSLazy< | CSSGlobalValues | StringHint | "auto" | "default" | "none" | "context-menu" | "help" | "pointer" | "progress" | "wait" | "cell" | "crosshair" | "text" | "vertical-text" | "alias" | "copy" | "move" | "no-drop" | "not-allowed" | "e-resize" | "n-resize" | "ne-resize" | "nw-resize" | "s-resize" | "se-resize" | "sw-resize" | "w-resize" | "ew-resize" | "ns-resize" | "nesw-resize" | "nwse-resize" | "col-resize" | "row-resize" | "all-scroll" | "zoom-in" | "zoom-out" | "grab" | "grabbing" >; /** * The direction CSS property specifies the text direction/writing direction. The rtl is used for Hebrew or Arabic text, the ltr is for other languages. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/direction */ direction?: CSSLazy<CSSGlobalValues | "ltr" | "rtl">; /** * This property specifies the type of rendering box used for an element. It is a shorthand property for many other display properties. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/display */ display?: CSSLazy< | CSSGlobalValues | StringHint | "none" | "inline" | "block" | "inline-block" | "contents" | "list-item" | "inline-list-item" | "table" | "inline-table" | "table-cell" | "table-column" | "table-column-group" | "table-footer-group" | "table-header-group" | "table-row" | "table-row-group" | "table-caption" | "flex" | "inline-flex" | "grid" | "inline-grid" | "ruby" | "ruby-base" | "ruby-text" | "ruby-base-container" | "ruby-text-container" | "run-in" >; /** * The ‘fill’ property paints the interior of the given graphical element. The area to be painted consists of any areas inside the outline of the shape. To determine the inside of the shape, all subpaths are considered, and the interior is determined according to the rules associated with the current value of the ‘fill-rule’ property. The zero-width geometric outline of a shape is included in the area to be painted. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/fill */ fill?: CSSLazyString; /** * SVG: Specifies the opacity of the color or the content the current object is filled with. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/fill-opacity */ fillOpacity?: CSSLazyValueGeneral; /** * The ‘fill-rule’ property indicates the algorithm which is to be used to determine what parts of the canvas are included inside the shape. For a simple, non-intersecting path, it is intuitively clear what region lies "inside"; however, for a more complex path, such as a path that intersects itself or where one subpath encloses another, the interpretation of "inside" is not so obvious. * The ‘fill-rule’ property provides two options for how the inside of a shape is determined: * @see https://developer.mozilla.org/en-US/docs/Web/CSS/fill-rule */ fillRule?: CSSLazyString; /** * Applies various image processing effects. This property is largely unsupported. See Compatibility section for more information. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/filter */ filter?: CSSLazyString; /** * Shorthand for `flex-grow`, `flex-shrink`, and `flex-basis`. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/flex */ flex?: CSSLazyValueGeneral; /** * The flex-basis CSS property describes the initial main size of the flex item before any free space is distributed according to the flex factors described in the flex property (flex-grow and flex-shrink). * @see https://developer.mozilla.org/en-US/docs/Web/CSS/flex-basis */ flexBasis?: CSSLazyValueGeneral; /** * The flex-direction CSS property describes how flex items are placed in the flex container, by setting the direction of the flex container's main axis. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/flex-direction */ flexDirection?: CSSLazy<CSSGlobalValues | "row" | "row-reverse" | "column" | "column-reverse">; /** * The flex-flow CSS property defines the flex container's main and cross axis. It is a shorthand property for the flex-direction and flex-wrap properties. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/flex-flow */ flexFlow?: CSSLazyString; /** * Specifies the flex grow factor of a flex item. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/flex-grow */ flexGrow?: CSSLazyValueGeneral; /** * Gets or sets a value that specifies the ordinal group that a flexbox element belongs to. This ordinal value identifies the display order for the group. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/flex-order */ flexOrder?: CSSLazyValueGeneral; /** * Specifies the flex shrink factor of a flex item. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/flex-shrink */ flexShrink?: CSSLazyValueGeneral; /** * Specifies whether flex items are forced into a single line or can be wrapped onto multiple lines. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/flex-wrap */ flexWrap?: CSSLazy<CSSGlobalValues | "nowrap" | "wrap" | "wrap-reverse">; /** * Elements which have the style float are floated horizontally. These elements can move as far to the left or right of the containing element. All elements after the floating element will flow around it, but elements before the floating element are not impacted. If several floating elements are placed after each other, they will float next to each other as long as there is room. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/float */ float?: CSSLazy<CSSGlobalValues | "left" | "right" | "none" | "inline-start" | "inline-end">; /** * Flows content from a named flow (specified by a corresponding flow-into) through selected elements to form a dynamic chain of layout regions. */ flowFrom?: CSSLazyValueGeneral; /** * The font property is shorthand that allows you to do one of two things: you can either set up six of the most mature font properties in one line, or you can set one of a choice of keywords to adopt a system font setting. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/font */ font?: CSSLazyString; /** * The font-family property allows one or more font family names and/or generic family names to be specified for usage on the selected element(s)' text. The browser then goes through the list; for each character in the selection it applies the first font family that has an available glyph for that character. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/font-family */ fontFamily?: CSSLazyString; /** * The font-kerning property allows contextual adjustment of inter-glyph spacing, i.e. the spaces between the characters in text. This property controls <bold>metric kerning</bold> - that utilizes adjustment data contained in the font. Optical Kerning is not supported as yet. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/font-kerning */ fontKerning?: CSSLazy<CSSGlobalValues | "auto" | "normal" | "none">; /** * Specifies the size of the font. Used to compute em and ex units. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/font-size */ fontSize?: CSSLazy<CSSFontSize>; /** * The font-size-adjust property adjusts the font-size of the fallback fonts defined with font-family, so that the x-height is the same no matter what font is used. This preserves the readability of the text when fallback happens. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/font-size-adjust */ fontSizeAdjust?: CSSLazyValueGeneral; /** * Allows you to expand or condense the widths for a normal, condensed, or expanded font face. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/font-stretch */ fontStretch?: CSSLazy< | CSSGlobalValues | "normal" | "ultra-condensed" | "extra-condensed" | "condensed" | "semi-condensed" | "semi-expanded" | "expanded" | "extra-expanded" | "ultra-expanded" >; /** * The font-style property allows normal, italic, or oblique faces to be selected. Italic forms are generally cursive in nature while oblique faces are typically sloped versions of the regular face. Oblique faces can be simulated by artificially sloping the glyphs of the regular face. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/font-style */ fontStyle?: CSSLazy<CSSGlobalValues | "normal" | "italic" | "oblique">; /** * This value specifies whether the user agent is allowed to synthesize bold or oblique font faces when a font family lacks bold or italic faces. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/font-synthesis */ fontSynthesis?: CSSLazyString; /** * The font-variant property enables you to select the small-caps font within a font family. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant */ fontVariant?: CSSLazyString; /** * Fonts can provide alternate glyphs in addition to default glyph for a character. This property provides control over the selection of these alternate glyphs. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/font-variant-alternates */ fontVariantAlternates?: CSSLazyString; /** * Specifies the weight or boldness of the font. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight */ fontWeight?: CSSLazy<CSSFontWeight>; /** * Lays out one or more grid items bound by 4 grid lines. Shorthand for setting grid-column-start, grid-column-end, grid-row-start, and grid-row-end in a single declaration. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/grid-area */ gridArea?: CSSLazyString; /** * Controls a grid item's placement in a grid area, particularly grid position and a grid span. Shorthand for setting grid-column-start and grid-column-end in a single declaration. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/grid-column */ gridColumn?: CSSLazyString; /** * Controls a grid item's placement in a grid area as well as grid position and a grid span. The grid-column-end property (with grid-row-start, grid-row-end, and grid-column-start) determines a grid item's placement by specifying the grid lines of a grid item's grid area. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/grid-column-end */ gridColumnEnd?: CSSLazyValueGeneral; /** * Determines a grid item's placement by specifying the starting grid lines of a grid item's grid area . A grid item's placement in a grid area consists of a grid position and a grid span. See also ( grid-row-start, grid-row-end, and grid-column-end) * @see https://developer.mozilla.org/en-US/docs/Web/CSS/grid-column-start */ gridColumnStart?: CSSLazyValueGeneral; /** * Gets or sets a value that indicates which row an element within a Grid should appear in. Shorthand for setting grid-row-start and grid-row-end in a single declaration. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/grid-row */ gridRow?: CSSLazyString; /** * Determines a grid item’s placement by specifying the block-end. A grid item's placement in a grid area consists of a grid position and a grid span. The grid-row-end property (with grid-row-start, grid-column-start, and grid-column-end) determines a grid item's placement by specifying the grid lines of a grid item's grid area. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/grid-row-end */ gridRowEnd?: CSSLazyValueGeneral; /** * Determines a grid item’s start position within the grid row by contributing a line, a span, or nothing (automatic) to its grid placement, thereby specifying the inline-start edge of its grid area. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/grid-row-start */ gridRowStart?: CSSLazyValueGeneral; /** * Specifies a row position based upon an integer location, string value, or desired row size. * css/properties/grid-row is used as short-hand for grid-row-position and grid-row-position */ gridRowPosition?: CSSLazyString; gridRowSpan?: CSSLazyValueGeneral; /** * Specifies named grid areas which are not associated with any particular grid item, but can be referenced from the grid-placement properties. The syntax of the grid-template-areas property also provides a visualization of the structure of the grid, making the overall layout of the grid container easier to understand. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-areas */ gridTemplateAreas?: CSSLazyValueGeneral; /** * Specifies (with grid-template-rows) the line names and track sizing functions of the grid. Each sizing function can be specified as a length, a percentage of the grid container’s size, a measurement of the contents occupying the column or row, or a fraction of the free space in the grid. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-columns */ gridTemplateColumns?: CSSLazyValueGeneral; /** * Specifies (with grid-template-columns) the line names and track sizing functions of the grid. Each sizing function can be specified as a length, a percentage of the grid container’s size, a measurement of the contents occupying the column or row, or a fraction of the free space in the grid. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/grid-template-rows */ gridTemplateRows?: CSSLazyValueGeneral; /** * Sets the height of an element. The content area of the element height does not include the padding, border, and margin of the element. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/height */ height?: CSSLazy<"auto" | CSSValueGeneral | CSSGlobalValues>; /** * Specifies the minimum number of characters in a hyphenated word * @see https://msdn.microsoft.com/en-us/library/hh771865(v=vs.85).aspx */ hyphenateLimitChars?: CSSLazyValueGeneral; /** * Indicates the maximum number of successive hyphenated lines in an element. The ‘no-limit’ value means that there is no limit. * @see https://msdn.microsoft.com/en-us/library/hh771867(v=vs.85).aspx */ hyphenateLimitLines?: CSSLazyValueGeneral; /** * Specifies the maximum amount of trailing whitespace (before justification) that may be left in a line before hyphenation is triggered to pull part of a word from the next line back up into the current one. * @see https://msdn.microsoft.com/en-us/library/hh771869(v=vs.85).aspx */ hyphenateLimitZone?: CSSLazyValueGeneral; /** * Specifies whether or not words in a sentence can be split by the use of a manual or automatic hyphenation mechanism. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/hyphens */ hyphens?: CSSLazy<CSSGlobalValues | StringHint | "none" | "manual" | "auto">; /** * Controls the state of the input method editor for text fields. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/ime-mode */ imeMode?: CSSLazy<CSSGlobalValues | "auto" | "normal" | "active" | "inactive" | "disabled">; /** * Defines how the browser distributes space between and around flex items * along the main-axis of their container. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/justify-content */ justifyContent?: CSSLazy<"flex-start" | "flex-end" | "center" | "space-between" | "space-around">; layoutGrid?: CSSLazyValueGeneral; layoutGridChar?: CSSLazyValueGeneral; layoutGridLine?: CSSLazyValueGeneral; layoutGridMode?: CSSLazyValueGeneral; layoutGridType?: CSSLazyValueGeneral; /** * Sets the left edge of an element * @see https://developer.mozilla.org/en-US/docs/Web/CSS/left */ left?: CSSLazy<"auto" | CSSValueGeneral>; /** * The letter-spacing CSS property specifies the spacing behavior between text characters. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/letter-spacing */ letterSpacing?: CSSLazyValueGeneral; lineClamp?: CSSLazyValueGeneral; /** * Specifies the height of an inline block level element. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/line-height */ lineHeight?: CSSLazyValueGeneral; /** * Shorthand property that sets the list-style-type, list-style-position and list-style-image properties in one declaration. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/list-style */ listStyle?: CSSLazyString; /** * This property sets the image that will be used as the list item marker. When the image is available, it will replace the marker set with the 'list-style-type' marker. That also means that if the image is not available, it will show the style specified by list-style-property * @see https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-image */ listStyleImage?: CSSLazyString; /** * Specifies if the list-item markers should appear inside or outside the content flow. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-position */ listStylePosition?: CSSLazy<CSSGlobalValues | "inside" | "outside">; /** * Specifies the type of list-item marker in a list. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/list-style-type */ listStyleType?: CSSLazyString; /** * The margin property is shorthand to allow you to set all four margins of an element at once. Its equivalent longhand properties are margin-top, margin-right, margin-bottom and margin-left. Negative values are also allowed. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/margin */ margin?: CSSLazyValueGeneral; /** * margin-bottom sets the bottom margin of an element. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/margin-bottom */ marginBottom?: CSSLazyValueGeneral; /** * margin-left sets the left margin of an element. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/margin-left */ marginLeft?: CSSLazyValueGeneral; /** * margin-right sets the right margin of an element. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/margin-right */ marginRight?: CSSLazyValueGeneral; /** * margin-top sets the top margin of an element. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/margin-top */ marginTop?: CSSLazyValueGeneral; /** * This property is shorthand for setting mask-image, mask-mode, mask-repeat, mask-position, mask-clip, mask-origin, mask-composite and mask-size. Omitted values are set to their original properties' initial values. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/mask */ mask?: CSSLazyString; /** * This property is shorthand for setting mask-border-source, mask-border-slice, mask-border-width, mask-border-outset, and mask-border-repeat. Omitted values are set to their original properties' initial values. */ maskBorder?: CSSLazyString; /** * This property specifies how the images for the sides and the middle part of the mask image are scaled and tiled. The first keyword applies to the horizontal sides, the second one applies to the vertical ones. If the second keyword is absent, it is assumed to be the same as the first, similar to the CSS border-image-repeat property. */ maskBorderRepeat?: CSSLazyValueGeneral; /** * This property specifies inward offsets from the top, right, bottom, and left edges of the mask image, dividing it into nine regions: four corners, four edges, and a middle. The middle image part is discarded and treated as fully transparent black unless the fill keyword is present. The four values set the top, right, bottom and left offsets in that order, similar to the CSS border-image-slice property. */ maskBorderSlice?: CSSLazyValueGeneral; /** * Specifies an image to be used as a mask. An image that is empty, fails to download, is non-existent, or cannot be displayed is ignored and does not mask the element. */ maskBorderSource?: CSSLazyString; /** * This property sets the width of the mask box image, similar to the CSS border-image-width property. */ maskBorderWidth?: CSSLazyValueGeneral; /** * Determines the mask painting area, which defines the area that is affected by the mask. The painted content of an element may be restricted to this area. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/mask-clip */ maskClip?: CSSLazyString; /** * For elements rendered as a single box, specifies the mask positioning area. For elements rendered as multiple boxes (e.g., inline boxes on several lines, boxes on several pages) specifies which boxes box-decoration-break operates on to determine the mask positioning area(s). * @see https://developer.mozilla.org/en-US/docs/Web/CSS/mask-origin */ maskOrigin?: CSSLazyString; /** * Sets the maximum height for an element. It prevents the height of the element to exceed the specified value. If min-height is specified and is greater than max-height, max-height is overridden. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/max-height */ maxHeight?: CSSLazyValueGeneral; /** * Sets the maximum width for an element. It limits the width property to be larger than the value specified in max-width. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/max-width */ maxWidth?: CSSLazyValueGeneral; /** * Sets the minimum height for an element. It prevents the height of the element to be smaller than the specified value. The value of min-height overrides both max-height and height. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/min-height */ minHeight?: CSSLazyValueGeneral; /** * Sets the minimum width of an element. It limits the width property to be not smaller than the value specified in min-width. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/min-width */ minWidth?: CSSLazyValueGeneral; /** * The blend mode defines the formula that must be used to mix the colors with the backdrop * @see https://drafts.fxtf.org/compositing-1/#mix-blend-mode * @see https://developer.mozilla.org/en-US/docs/Web/CSS/mix-blend-mode */ mixBlendMode?: CSSLazy<CSSBlendMode>; /** * Specifies the transparency of an element. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/opacity */ opacity?: CSSLazyValueGeneral; /** * Specifies the order used to lay out flex items in their flex container. * Elements are laid out in the ascending order of the order value. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/order */ order?: CSSLazyValueGeneral; /** * In paged media, this property defines the minimum number of lines in * a block container that must be left at the bottom of the page. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/orphans */ orphans?: CSSLazyValueGeneral; /** * The CSS outline property is a shorthand property for setting one or more of the individual outline properties outline-style, outline-width and outline-color in a single rule. In most cases the use of this shortcut is preferable and more convenient. * Outlines differ from borders in the following ways: * • Outlines do not take up space, they are drawn above the content. * • Outlines may be non-rectangular. They are rectangular in Gecko/Firefox. Internet Explorer attempts to place the smallest contiguous outline around all elements or shapes that are indicated to have an outline. Opera draws a non-rectangular shape around a construct. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/outline */ outline?: CSSLazyValueGeneral; /** * The outline-color property sets the color of the outline of an element. An outline is a line that is drawn around elements, outside the border edge, to make the element stand out. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/outline-color */ outlineColor?: CSSLazy<CSSColor>; /** * The outline-style property sets the style of the outline of an element. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/outline-style */ outlineStyle?: CSSLazy< | CSSGlobalValues | "auto" | "none" | "dotted" | "dashed" | "solid" | "double" | "groove" | "ridge" | "inset" | "outset" >; /** * The outline-offset property offsets the outline and draw it beyond the border edge. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/outline-offset */ outlineOffset?: CSSLazyValueGeneral; /** * The overflow property controls how extra content exceeding the bounding box of an element is rendered. It can be used in conjunction with an element that has a fixed width and height, to eliminate text-induced page distortion. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/overflow */ overflow?: CSSLazy<CSSOverflow>; /** * Specifies the preferred scrolling methods for elements that overflow. */ overflowStyle?: CSSLazyValueGeneral; /** * Controls how extra content exceeding the x-axis of the bounding box of an element is rendered. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-x */ overflowX?: CSSLazy<CSSOverflow>; /** * Controls how extra content exceeding the y-axis of the bounding box of an element is rendered. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/overflow-y */ overflowY?: CSSLazy<CSSOverflow>; /** * The padding optional CSS property sets the required padding space on one to four sides of an element. The padding area is the space between an element and its border. Negative values are not allowed but decimal values are permitted. The element size is treated as fixed, and the content of the element shifts toward the center as padding is increased. * The padding property is a shorthand to avoid setting each side separately (padding-top, padding-right, padding-bottom, padding-left). * @see https://developer.mozilla.org/en-US/docs/Web/CSS/padding */ padding?: CSSLazyValueGeneral; /** * The padding-bottom CSS property of an element sets the padding space required on the bottom of an element. The padding area is the space between the content of the element and its border. Contrary to margin-bottom values, negative values of padding-bottom are invalid. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/padding-bottom */ paddingBottom?: CSSLazyValueGeneral; /** * The padding-left CSS property of an element sets the padding space required on the left side of an element. The padding area is the space between the content of the element and its border. Contrary to margin-left values, negative values of padding-left are invalid. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/padding-left */ paddingLeft?: CSSLazyValueGeneral; /** * The padding-right CSS property of an element sets the padding space required on the right side of an element. The padding area is the space between the content of the element and its border. Contrary to margin-right values, negative values of padding-right are invalid. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/padding-right */ paddingRight?: CSSLazyValueGeneral; /** * The padding-top CSS property of an element sets the padding space required on the top of an element. The padding area is the space between the content of the element and its border. Contrary to margin-top values, negative values of padding-top are invalid. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/padding-top */ paddingTop?: CSSLazyValueGeneral; /** * The page-break-after property is supported in all major browsers. With CSS3, page-break-* properties are only aliases of the break-* properties. The CSS3 Fragmentation spec defines breaks for all CSS box fragmentation. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/page-break-after */ pageBreakAfter?: CSSLazy<CSSGlobalValues | "auto" | "always" | "avoid" | "left" | "right" | "recto" | "verso">; /** * The page-break-before property sets the page-breaking behavior before an element. With CSS3, page-break-* properties are only aliases of the break-* properties. The CSS3 Fragmentation spec defines breaks for all CSS box fragmentation. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/page-break-before */ pageBreakBefore?: CSSLazy<CSSGlobalValues | "auto" | "always" | "avoid" | "left" | "right" | "recto" | "verso">; /** * Sets the page-breaking behavior inside an element. With CSS3, page-break-* properties are only aliases of the break-* properties. The CSS3 Fragmentation spec defines breaks for all CSS box fragmentation. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/page-break-inside */ pageBreakInside?: CSSLazy<CSSGlobalValues | "auto" | "avoid">; /** * The perspective property defines how far an element is placed from the view on the z-axis, from the screen to the viewer. * Perspective defines how an object is viewed. In graphic arts, perspective is the representation on a flat surface of what the viewer's eye would see in a 3D space. (See Wikipedia for more information about graphical perspective and for related illustrations.) * The illusion of perspective on a flat surface, such as a computer screen, is created by projecting points on the flat surface as they would appear if the flat surface were a window through which the viewer was looking at the object. In discussion of virtual environments, this flat surface is called a projection plane. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/perspective */ perspective?: CSSLazyValueGeneral; /** * The perspective-origin property establishes the origin for the perspective property. It effectively sets the X and Y position at which the viewer appears to be looking at the children of the element. * When used with perspective, perspective-origin changes the appearance of an object, as if a viewer were looking at it from a different origin. An object appears differently if a viewer is looking directly at it versus looking at it from below, above, or from the side. Thus, the perspective-origin is like a vanishing point. * The default value of perspective-origin is 50% 50%. This displays an object as if the viewer's eye were positioned directly at the center of the screen, both top-to-bottom and left-to-right. A value of 0% 0% changes the object as if the viewer was looking toward the top left angle. A value of 100% 100% changes the appearance as if viewed toward the bottom right angle. * @see https://developer.mozilla.org/en-US/docs/Web/CSS/perspective-origin */ perspectiveOrigin?: CSSLazyValueGeneral; /** * The pointer-events property allows you to control whether an element can be the target for the pointing device (e.g, mouse, pen) events. * @see https://developer.mozilla.org/en/docs/Web/CSS/pointer-events */ pointerEvents?: CSSLazy< | CSSGlobalValues | "auto" | "none" | "visiblePainted" | "visibleFill" | "visibleStroke" | "visible" | "painted" | "fill" | "stroke" | "all" >; /** * The position property controls the type of positioning used by an element within its parent elements. The effect of the position property depends on a lot of factors, for example the position property of parent elements. * @see https://developer.mozilla.org/en/docs/Web/CSS/position */ position?: CSSLazy<CSSGlobalValues | "static" | "relative" | "absolute" | "sticky" | "fixed">; /** * Sets the type of quotation marks for embedded quotations. * @see https://developer.mozilla.org/en/docs/Web/CSS/quotes */ quotes?: CSSLazyValueGeneral; /** * Controls whether the last region in a chain displays additional 'overset' content according its default overflow property, or if it displays a fragment of content as if it were flowing into a subsequent region. */ regionFragment?: CSSLazyValueGeneral; /** * The resize CSS property lets you control the resizability of an element. * @see https://developer.mozilla.org/en/docs/Web/CSS/resize */ resize?: CSSLazy<CSSGlobalValues | "none" | "both " | "horizontal" | "vertical">; /** * The rest-after property determines how long a speech media agent should pause after presenting an element's main content, before presenting that element's exit cue sound. It may be replaced by the shorthand property rest, which sets rest time before and after. */ restAfter?: CSSLazyValueGeneral; /** * The rest-before property determines how long a speech media agent should pause after presenting an intro cue sound for an element, before presenting that element's main content. It may be replaced by the shorthand property rest, which sets rest time before and after. */ restBefore?: CSSLazyValueGeneral; /** * Specifies the position an element in relation to the right side of the containing element. * @see https://developer.mozilla.org/en/docs/Web/CSS/right */ right?: CSSLazy<"auto" | CSSValueGeneral | CSSGlobalValues>; /** * Specifies the distribution of the different ruby elements over the base. * @see https://developer.mozilla.org/en/docs/Web/CSS/ruby-align */ rubyAlign?: CSSLazy<CSSGlobalValues | "start" | "center" | "space-between" | "space-around">; /** * Specifies the position of a ruby element relatives to its base element. It can be position over the element (over), under it (under), or between the characters, on their right side (inter-character). * @see https://developer.mozilla.org/en/docs/Web/CSS/ruby-position */ rubyPosition?: CSSLazy<CSSGlobalValues | "over" | "under" | "inter-character">; /** * Defines the alpha channel threshold used to extract a shape from an image. Can be thought of as a "minimum opacity" threshold; that is, a value of 0.5 means that the shape will enclose all the pixels that are more than 50% opaque. * @see https://developer.mozilla.org/en/docs/Web/CSS/shape-image-threshold */ shapeImageThreshold?: CSSLazyValueGeneral; /** * A future level of CSS Shapes will define a shape-inside property, which will define a shape to wrap content within the element. See Editor's Draft <http://dev.w3.org/csswg/css-shapes/> and CSSWG wiki page on next-level plans <http://wiki.csswg.org/spec/css-shapes> */ shapeInside?: CSSLazyValueGeneral; /** * Adds a margin to a shape-outside. In effect, defines a new shape that is the smallest contour around all the points that are the shape-margin distance outward perpendicular to each point on the underlying shape. For points where a perpendicular direction is not defined (e.g., a triangle corner), takes all points on a circle centered at the point and with a radius of the shape-margin distance. This property accepts only non-negative values. * @see https://developer.mozilla.org/en/docs/Web/CSS/shape-margin */ shapeMargin?: CSSLazyValueGeneral; /** * Declares a shape around which text should be wrapped, with possible modifications from the shape-margin property. The shape defined by shape-outside and shape-margin changes the geometry of a float element's float area. * @see https://developer.mozilla.org/en/docs/Web/CSS/shape-outside */ shapeOutside?: CSSLazyValueGeneral; /** * The speak property determines whether or not a speech synthesizer will read aloud the contents of an element. */ speak?: CSSLazyValueGeneral; /** * The speak-as property determines how the speech synthesizer interprets the content: words as whole words or as a sequence of letters, numbers as a numerical value or a sequence of digits, punctuation as pauses in speech or named punctuation characters. */ speakAs?: CSSLazyValueGeneral; /** * SVG: Specifies the opacity of the outline on the current object. * @see https://developer.mozilla.org/en/docs/Web/CSS/stroke-opacity */ strokeOpacity?: CSSLazyValueGeneral; /** * SVG: Specifies the width of the outline on the current object. * @see https://developer.mozilla.org/en/docs/Web/CSS/stroke-width */ strokeWidth?: CSSLazyValueGeneral; /** * The tab-size CSS property is used to customise the width of a tab (U+0009) character. * @see https://developer.mozilla.org/en/docs/Web/CSS/tab-size */ tabSize?: CSSLazyValueGeneral; /** * The 'table-layout' property controls the algorithm used to lay out the table cells, rows, and columns. * @see https://developer.mozilla.org/en/docs/Web/CSS/table-layout */ tableLayout?: CSSLazyValueGeneral; /** * The text-align CSS property describes how inline content like text is aligned in its parent block element. text-align does not control the alignment of block elements itself, only their inline content. * @see https://developer.mozilla.org/en/docs/Web/CSS/text-align */ textAlign?: CSSLazy< CSSGlobalValues | "start" | "end" | "left" | "right" | "center" | "justify" | "justify-all" | "match-parent" >; /** * The text-align-last CSS property describes how the last line of a block element or a line before line break is aligned in its parent block element. * @see https://developer.mozilla.org/en/docs/Web/CSS/text-align-last */ textAlignLast?: CSSLazy<CSSGlobalValues | "auto" | "start" | "end" | "left" | "right" | "center" | "justify">; /** * The text-decoration CSS property is used to set the text formatting to underline, overline, line-through or blink. * underline and overline decorations are positioned under the text, line-through over it. * @see https://developer.mozilla.org/en/docs/Web/CSS/text-decoration */ textDecoration?: CSSLazyValueGeneral; /** * Sets the color of any text decoration, such as underlines, overlines, and strike throughs. * @see https://developer.mozilla.org/en/docs/Web/CSS/text-decoration-color */ textDecorationColor?: CSSLazy<CSSColor>; /** * Sets what kind of line decorations are added to an element, such as underlines, overlines, etc. * @see https://developer.mozilla.org/en/docs/Web/CSS/text-decoration-line */ textDecorationLine?: CSSLazyValueGeneral; textDecorationLineThrough?: CSSLazyValueGeneral; textDecorationNone?: CSSLazyValueGeneral; textDecorationOverline?: CSSLazyValueGeneral; /** * Specifies what parts of an element’s content are skipped over when applying any text decoration. * @see https://developer.mozilla.org/en/docs/Web/CSS/text-decoration-skip */ textDecorationSkip?: CSSLazyValueGeneral; /** * This property specifies the style of the text decoration line drawn on the specified element. The intended meaning for the values are the same as those of the border-style-properties. * @see https://developer.mozilla.org/en/docs/Web/CSS/text-decoration-style */ textDecorationStyle?: CSSLazy<CSSGlobalValues | "solid" | "double" | "dotted" | "dashed" | "wavy">; textDecorationUnderline?: CSSLazyValueGeneral; /** * The text-emphasis property will apply special emphasis marks to the elements text. Slightly similar to the text-decoration property only that this property can have affect on the line-height. It also is noted that this is shorthand for text-emphasis-style and for text-emphasis-color. * @see https://developer.mozilla.org/en/docs/Web/CSS/text-emphasis */ textEmphasis?: CSSLazyValueGeneral; /** * The text-emphasis-color property specifies the foreground color of the emphasis marks. * @see https://developer.mozilla.org/en/docs/Web/CSS/text-emphasis-color */ textEmphasisColor?: CSSLazy<CSSColor>; /** * The text-emphasis-style property applies special emphasis marks to an element's text. * @see https://developer.mozilla.org/en/docs/Web/CSS/text-emphasis-style */ textEmphasisStyle?: CSSLazyValueGeneral; /** * This property helps determine an inline box's block-progression dimension, derived from the text-height and font-size properties for non-replaced elements, the height or the width for replaced elements, and the stacked block-progression dimension for inline-block elements. The block-progression dimension determines the position of the padding, border and margin for the element. */ textHeight?: CSSLazyValueGeneral; /** * Specifies the amount of space horizontally that should be left on the first line of the text of an element. This horizontal spacing is at the beginning of the first line and is in respect to the left edge of the containing block box. * @see https://developer.mozilla.org/en/docs/Web/CSS/text-indent */ textIndent?: CSSLazyValueGeneral; /** * The text-overflow shorthand CSS property determines how overflowed content that is not displayed is signaled to the users. It can be clipped, display an ellipsis ('…', U+2026 HORIZONTAL ELLIPSIS) or a Web author-defined string. It covers the two long-hand properties text-overflow-mode and text-overflow-ellipsis * @see https://developer.mozilla.org/en/docs/Web/CSS/text-overflow */ textOverflow?: CSSLazy<CSSGlobalValues | "clip" | "ellipsis" | StringHint>; /** * The text-overline property is the shorthand for the text-overline-style, text-overline-width, text-overline-color, and text-overline-mode properties. */ textOverline?: CSSLazyValueGeneral; /** * Specifies the line color for the overline text decoration. */ textOverlineColor?: CSSLazy<CSSColor>; /** * Sets the mode for the overline text decoration, determining whether the text decoration affects the space characters or not. */ textOverlineMode?: CSSLazyValueGeneral; /** * Specifies the line style for overline text decoration. */ textOverlineStyle?: CSSLazyValueGeneral; /** * Specifies the line width for the overline text decoration. */ textOverlineWidth?: CSSLazyValueGeneral; /** * The text-rendering CSS property provides information to the browser about how to optimize when rendering text. Options are: legibility, speed or geometric precision. * @see https://developer.mozilla.org/en/docs/Web/CSS/text-rendering */ textRendering?: CSSLazy<CSSGlobalValues | "auto" | "optimizeSpeed" | "optimizeLegibility" | "geometricPrecision">; /** * The CSS text-shadow property applies one or more drop shadows to the text and <text-decorations> of an element. Each shadow is specified as an offset from the text, along with optional color and blur radius values. * @see https://developer.mozilla.org/en/docs/Web/CSS/text-shadow */ textShadow?: CSSLazyValueGeneral; /** * This property transforms text for styling purposes. (It has no effect on the underlying content.) * @see https://developer.mozilla.org/en/docs/Web/CSS/text-transform */ textTransform?: CSSLazy<CSSGlobalValues | "none" | "capitalize" | "uppercase" | "lowercase" | "full-width">; /** * Unsupported. * This property will add a underline position value to the element that has an underline defined. */ textUnderlinePosition?: CSSLazyValueGeneral; /** * After review this should be replaced by text-decoration should it not? * This property will set the underline style for text with a line value for underline, overline, and line-through. */ textUnderlineStyle?: CSSLazyValueGeneral; /** * This property specifies how far an absolutely positioned box's top margin edge is offset below the top edge of the box's containing block. For relatively positioned boxes, the offset is with respect to the top edges of the box itself (i.e., the box is given a position in the normal flow, then offset from that position according to these properties). * @see https://developer.mozilla.org/en/docs/Web/CSS/top */ top?: CSSLazy<"auto" | CSSValueGeneral | CSSGlobalValues>; /** * Determines whether touch input may trigger default behavior supplied by the user agent, such as panning or zooming. * @see https://developer.mozilla.org/en/docs/Web/CSS/touch-action */ touchAction?: CSSLazy< | CSSGlobalValues | "auto" | "none" | "pan-x" | "pan-left" | "pan-right" | "pan-y" | "pan-up" | "pan-down" | "manipulation" >; /** * CSS transforms allow elements styled with CSS to be transformed in two-dimensional or three-dimensional space. Using this property, elements can be translated, rotated, scaled, and skewed. The value list may consist of 2D and/or 3D transform values. * @see https://developer.mozilla.org/en/docs/Web/CSS/transform */ transform?: CSSLazyString; /** * This property defines the origin of the transformation axes relative to the element to which the transformation is applied. * @see https://developer.mozilla.org/en/docs/Web/CSS/transform-origin */ transformOrigin?: CSSLazyValueGeneral; /** * This property allows you to define the relative position of the origin of the transformation grid along the z-axis. */ transformOriginZ?: CSSLazyValueGeneral; /** * This property specifies how nested elements are rendered in 3D space relative to their parent. * @see https://developer.mozilla.org/en/docs/Web/CSS/transform-style */ transformStyle?: CSSLazy<CSSGlobalValues | "flat" | "preserve-3d">; /** * The transition CSS property is a shorthand property for transition-property, transition-duration, transition-timing-function, and transition-delay. It allows to define the transition between two states of an element. * @see https://developer.mozilla.org/en/docs/Web/CSS/transition */ transition?: CSSLazyValueGeneral; /** * The unicode-bidi CSS property specifies the level of embedding with respect to the bidirectional algorithm. * @see https://developer.mozilla.org/en/docs/Web/CSS/unicode-bidi */ unicodeBidi?: CSSLazyValueGeneral; /** * User select * @see https://developer.mozilla.org/en/docs/Web/CSS/user-select */ userSelect?: CSSLazy<StringHint | "auto" | "text" | "none" | "contain" | "all">; /** * The vertical-align property controls how inline elements or text are vertically aligned compared to the baseline. If this property is used on table-cells it controls the vertical alignment of content of the table cell. * @see https://developer.mozilla.org/en/docs/Web/CSS/vertical-align */ verticalAlign?: CSSLazy< | CSSGlobalValues | "baseline" | "sub" | "super" | "text-top" | "text-bottom" | "middle" | "top" | "bottom" | CSSValueGeneral >; /** * The visibility property specifies whether the boxes generated by an element are rendered. * @see https://developer.mozilla.org/en/docs/Web/CSS/visibility */ visibility?: CSSLazy<CSSGlobalValues | "visible" | "hidden" | "collapse">; /** * The white-space property controls whether and how white space inside the element is collapsed, and whether lines may wrap at unforced "soft wrap" opportunities. * @see https://developer.mozilla.org/en/docs/Web/CSS/white-space */ whiteSpace?: CSSLazy<CSSGlobalValues | "normal" | "nowrap" | "pre" | "pre-line" | "pre-wrap">; /** * In paged media, this property defines the mimimum number of lines * that must be left at the top of the second page. * @see https://developer.mozilla.org/en/docs/Web/CSS/widows */ widows?: CSSLazyValueGeneral; /** * Specifies the width of the content area of an element. The content area of the element width does not include the padding, border, and margin of the element. * @see https://developer.mozilla.org/en/docs/Web/CSS/width */ width?: CSSLazy<"auto" | CSSValueGeneral | CSSGlobalValues>; /** * The word-break property is often used when there is long generated content that is strung together without and spaces or hyphens to beak apart. A common case of this is when there is a long URL that does not have any hyphens. This case could potentially cause the breaking of the layout as it could extend past the parent element. * @see https://developer.mozilla.org/en/docs/Web/CSS/word-break */ wordBreak?: CSSLazy<CSSGlobalValues | "normal" | "break-all" | "keep-all">; /** * The word-spacing CSS property specifies the spacing behavior between "words". * @see https://developer.mozilla.org/en/docs/Web/CSS/word-spacing */ wordSpacing?: CSSLazy<CSSGlobalValues | "normal" | CSSValueGeneral>; /** * An alias of css/properties/overflow-wrap, word-wrap defines whether to break words when the content exceeds the boundaries of its container. * @see https://developer.mozilla.org/en/docs/Web/CSS/word-wrap */ wordWrap?: CSSLazy<CSSGlobalValues | "normal" | "break-word">; /** * writing-mode specifies if lines of text are laid out horizontally or vertically, and the direction which lines of text and blocks progress. * @see https://developer.mozilla.org/en/docs/Web/CSS/writing-mode */ writingMode?: CSSLazy< CSSGlobalValues | "horizontal-tb" | "vertical-rl" | "vertical-lr" | "sideways-rl" | "sideways-lr" >; /** * The z-index property specifies the z-order of an element and its descendants. * When elements overlap, z-order determines which one covers the other. * @see https://developer.mozilla.org/en/docs/Web/CSS/z-index */ zIndex?: CSSLazy<"auto" | CSSValueGeneral>; /** * Sets the initial zoom factor of a document defined by @viewport. * @see https://developer.mozilla.org/en/docs/Web/CSS/zoom */ zoom?: CSSLazy<"auto" | CSSValueGeneral>; [prop: string]: CSSLazyValueGeneral | undefined; } export type CSSStylesItem = | string // IBobrilStyleDef | ((styles: CSSInlineStyles, pseudo: CSSPseudoStyles) => void) | Readonly<CSSInlineStyles> | boolean | null | undefined; export type CSSStyles = CSSStylesItemArray | CSSStylesItem; export interface CSSStylesItemArray extends Array<CSSStyles> { fill: any; pop: any; push: any; concat: any; reverse: any; shift: any; slice: any; sort: any; splice: any; unshift: any; indexOf: any; lastIndexOf: any; every: any; some: any; forEach: any; map: any; filter: any; reduce: any; reduceRight: any; find: any; findIndex: any; [Symbol.iterator]: any; entries: any; values: any; readonly [index: number]: CSSStyles; } export type CSSPseudoStyles = { active?: CSSStyles; checked?: CSSStyles; disabled?: CSSStyles; enabled?: CSSStyles; "first-child"?: CSSStyles; focus?: CSSStyles; hover?: CSSStyles; invalid?: CSSStyles; "last-child"?: CSSStyles; valid?: CSSStyles; visited?: CSSStyles; [selector: string]: CSSStyles; };
the_stack
import Section from './Section' const Privacy = () => { return ( <Section id="privacy-policy" style="bg-gray-600" title="Privacy Policy"> <div className="grid lg:grid-cols-1"> <div className="my-auto gap-10 text-lg"> Effective date: 08/07/2020<br/> <br/><strong>1. Introduction<br/></strong> <br/>Welcome to OpenQuery Ltd..<br/> <br/>OpenQuery Ltd. (“us”, “we”, or “our”) operates http://getsynth.com (hereinafter referred to as “Service”).<br/> <br/>Our Privacy Policy governs your visit to http://getsynth.com, and explains how we collect, safeguard and disclose information that results from your use of our Service. <br/> <br/>We use your data to provide and improve Service. By using Service, you agree to the collection and use of information in accordance with this policy. Unless otherwise defined in this Privacy Policy, the terms used in this Privacy Policy have the same meanings as in our Terms and Conditions.<br/> <br/>Our Terms and Conditions (“Terms”) govern all use of our Service and together with the Privacy Policy constitutes your agreement with us (“agreement”).<br/> <br/><strong>2. Definitions<br/></strong> <br/><strong>SERVICE</strong> means the http://getsynth.com website operated by OpenQuery Ltd..<br/> <br/><strong>PERSONAL DATA</strong> means data about a living individual who can be identified from those data (or from those and other information either in our possession or likely to come into our possession).<br/> <br/><strong>USAGE DATA</strong> is data collected automatically either generated by the use of Service or from Service infrastructure itself (for example, the duration of a page visit).<br/> <br/><strong>COOKIES</strong> are small files stored on your device (computer or mobile device).<br/> <br/><strong>DATA CONTROLLER</strong> means a natural or legal person who (either alone or jointly or in common with other persons) determines the purposes for which and the manner in which any personal data are, or are to be, processed. For the purpose of this Privacy Policy, we are a Data Controller of your data.<br/> <br/><strong>DATA PROCESSORS (OR SERVICE PROVIDERS)</strong> means any natural or legal person who processes the data on behalf of the Data Controller. We may use the services of various Service Providers in order to process your data more effectively.<br/> <br/><strong>DATA SUBJECT</strong> is any living individual who is the subject of Personal Data.<br/> <br/><strong>THE USER</strong> is the individual using our Service. The User corresponds to the Data Subject, who is the subject of Personal Data.<br/> <br/><strong>3. Information Collection and Use<br/></strong> <br/>We collect several different types of information for various purposes to provide and improve our Service to you.<br/> <br/><strong>4. Types of Data Collected<br/></strong> <br/><strong>Personal Data<br/></strong>While using our Service, we may ask you to provide us with certain personally identifiable information that can be used to contact or identify you (“Personal Data”). Personally identifiable information may include, but is not limited to:<br/> <br/>(a) Email address<br/> <br/>(b) First name and last name<br/> <br/>We may use your Personal Data to contact you with newsletters, marketing or promotional materials and other information that may be of interest to you. You may opt out of receiving any, or all, of these communications from us by following the unsubscribe link or by emailing at info@getsynth.com.<br/> <br/><strong>Usage Data<br/></strong>We may also collect information that your browser sends whenever you visit our Service or when you access Service by or through a mobile device (“Usage Data”).<br/> <br/>This Usage Data may include information such as your computer&#x27;s Internet Protocol address (e.g. IP address), browser type, browser version, the pages of our Service that you visit, the time and date of your visit, the time spent on those pages, unique device identifiers and other diagnostic data.<br/> <br/>When you access Service with a mobile device, this Usage Data may include information such as the type of mobile device you use, your mobile device unique ID, the IP address of your mobile device, your mobile operating system, the type of mobile Internet browser you use, unique device identifiers and other diagnostic data.<br/> <br/><strong>Tracking Cookies Data<br/></strong>We use cookies and similar tracking technologies to track the activity on our Service and we hold certain information.<br/> <br/>Cookies are files with a small amount of data which may include an anonymous unique identifier. Cookies are sent to your browser from a website and stored on your device. Other tracking technologies are also used such as beacons, tags and scripts to collect and track information and to improve and analyze our Service.<br/> <br/>You can instruct your browser to refuse all cookies or to indicate when a cookie is being sent. However, if you do not accept cookies, you may not be able to use some portions of our Service.<br/> <br/><strong>Examples of Cookies we use:<br/></strong> <br/>(a) Session Cookies: We use Session Cookies to operate our Service.<br/> <br/>(b) Preference Cookies: We use Preference Cookies to remember your preferences and various settings.<br/> <br/>(c) Security Cookies: We use Security Cookies for security purposes.<br/> <br/><strong>5. Use of Data<br/></strong> <br/>OpenQuery Ltd. uses the collected data for various purposes:<br/> <br/>(a) to provide and maintain our Service;<br/> <br/>(b) to notify you about changes to our Service; <br/> <br/>(c) to allow you to participate in interactive features of our Service when you choose to do so; <br/> <br/>(d) to provide customer support; <br/> <br/>(e) to gather analysis or valuable information so that we can improve our Service; <br/> <br/>(f) to monitor the usage of our Service;<br/> <br/>(g) to detect, prevent and address technical issues;<br/> <br/>(h) to fulfill any other purpose for which you provide it;<br/> <br/>(i) to carry out our obligations and enforce our rights arising from any contracts entered into between you and us, including for billing and collection;<br/> <br/>(j) to provide you with notices about your account and/or subscription, including expiration and renewal notices, email-instructions, etc.;<br/> <br/>(k) to provide you with news, special offers and general information about other goods, services and events which we offer that are similar to those that you have already purchased or enquired about unless you have opted not to receive such information;<br/> <br/>(l) in any other way we may describe when you provide the information;<br/> <br/>(m) for any other purpose with your consent. <br/> <br/><strong>6. Retention of Data<br/></strong> <br/>We will retain your Personal Data only for as long as is necessary for the purposes set out in this Privacy Policy. We will retain and use your Personal Data to the extent necessary to comply with our legal obligations (for example, if we are required to retain your data to comply with applicable laws), resolve disputes, and enforce our legal agreements and policies.<br/> <br/>We will also retain Usage Data for internal analysis purposes. Usage Data is generally retained for a shorter period, except when this data is used to strengthen the security or to improve the functionality of our Service, or we are legally obligated to retain this data for longer time periods.<br/> <br/><strong>7. Transfer of Data<br/></strong> <br/>Your information, including Personal Data, may be transferred to – and maintained on – computers located outside of your state, province, country or other governmental jurisdiction where the data protection laws may differ from those of your jurisdiction.<br/> <br/>Your consent to this Privacy Policy followed by your submission of such information represents your agreement to that transfer.<br/> <br/>OpenQuery Ltd. will take all the steps reasonably necessary to ensure that your data is treated securely and in accordance with this Privacy Policy and no transfer of your Personal Data will take place to an organisation or a country unless there are adequate controls in place including the security of your data and other personal information.<br/> <br/><strong>8. Disclosure of Data<br/></strong> <br/>We may disclose personal information that we collect, or you provide:<br/> <br/>(a) Disclosure for Law Enforcement.<br/>Under certain circumstances, we may be required to disclose your Personal Data if required to do so by law or in response to valid requests by public authorities.<br/> <br/>(b) Business Transaction.<br/>If we or our subsidiaries are involved in a merger, acquisition or asset sale, your Personal Data may be transferred.<br/> <br/>(c) Other cases. We may disclose your information also:<br/> <br/> (i) to our subsidiaries and affiliates;<br/> <br/> (ii) to contractors, service providers, and other third parties we use to support our business;<br/> <br/> (iii) to fulfill the purpose for which you provide it;<br/> <br/> (iv) for the purpose of including your company’s logo on our website;<br/> <br/> (v) for any other purpose disclosed by us when you provide the information;<br/> <br/> (vi) with your consent in any other cases;<br/> <br/> (vii) if we believe disclosure is necessary or appropriate to protect the rights, property, or safety of the Company, our customers, or others.<br/> <br/><strong>9. Security of Data<br/></strong> <br/>The security of your data is important to us but remember that no method of transmission over the Internet or method of electronic storage is 100% secure. While we strive to use commercially acceptable means to protect your Personal Data, we cannot guarantee its absolute security.<br/> <br/>10. Your Data Protection Rights Under General Data Protection Regulation (GDPR)<br/> <br/>If you are a resident of the European Union (EU) and European Economic Area (EEA), you have certain data protection rights, covered by GDPR. – See more at https://eur-lex.europa.eu/eli/reg/2016/679/oj <br/> <br/>We aim to take reasonable steps to allow you to correct, amend, delete, or limit the use of your Personal Data.<br/> <br/>If you wish to be informed what Personal Data we hold about you and if you want it to be removed from our systems, please email us at info@getsynth.com. <br/> <br/>In certain circumstances, you have the following data protection rights:<br/> <br/>(a) the right to access, update or to delete the information we have on you;<br/> <br/>(b) the right of rectification. You have the right to have your information rectified if that information is inaccurate or incomplete;<br/> <br/>(c) the right to object. You have the right to object to our processing of your Personal Data;<br/> <br/>(d) the right of restriction. You have the right to request that we restrict the processing of your personal information;<br/> <br/>(e) the right to data portability. You have the right to be provided with a copy of your Personal Data in a structured, machine-readable and commonly used format;<br/> <br/>(f) the right to withdraw consent. You also have the right to withdraw your consent at any time where we rely on your consent to process your personal information;<br/> <br/>Please note that we may ask you to verify your identity before responding to such requests. Please note, we may not able to provide Service without some necessary data.<br/> <br/>You have the right to complain to a Data Protection Authority about our collection and use of your Personal Data. For more information, please contact your local data protection authority in the European Economic Area (EEA).<br/> <br/><strong>11. Your Data Protection Rights under the California Privacy Protection Act (CalOPPA)<br/></strong> <br/>CalOPPA is the first state law in the nation to require commercial websites and online services to post a privacy policy. The law’s reach stretches well beyond California to require a person or company in the United States (and conceivable the world) that operates websites collecting personally identifiable information from California consumers to post a conspicuous privacy policy on its website stating exactly the information being collected and those individuals with whom it is being shared, and to comply with this policy. – See more at: https://consumercal.org/about-cfc/cfc-education-foundation/california-online-privacy-protection-act-caloppa-3/ <br/> <br/>According to CalOPPA we agree to the following:<br/> <br/>(a) users can visit our site anonymously;<br/> <br/>(b) our Privacy Policy link includes the word “Privacy”, and can easily be found on the page specified above on the home page of our website;<br/> <br/>(c) users will be notified of any privacy policy changes on our Privacy Policy Page;<br/> <br/>(d) users are able to change their personal information by emailing us at info@getsynth.com. <br/> <br/>Our Policy on “Do Not Track” Signals:<br/> <br/>We honor Do Not Track signals and do not track, plant cookies, or use advertising when a Do Not Track browser mechanism is in place. Do Not Track is a preference you can set in your web browser to inform websites that you do not want to be tracked. <br/> <br/>You can enable or disable Do Not Track by visiting the Preferences or Settings page of your web browser.<br/> <br/><strong>12. Your Data Protection Rights under the California Consumer Privacy Act (CCPA)<br/></strong> <br/>If you are a California resident, you are entitled to learn what data we collect about you, ask to delete your data and not to sell (share) it. To exercise your data protection rights, you can make certain requests and ask us:<br/> <br/>(a) What personal information we have about you. If you make this request, we will return to you:<br/> <br/> (i) The categories of personal information we have collected about you.<br/> <br/> (ii) The categories of sources from which we collect your personal information.<br/> <br/> (iii) The business or commercial purpose for collecting or selling your personal information.<br/> <br/> (iv) The categories of third parties with whom we share personal information.<br/> <br/> (v) The specific pieces of personal information we have collected about you.<br/> <br/> (vi) A list of categories of personal information that we have sold, along with the category of any other company we sold it to. If we have not sold your personal information, we will inform you of that fact.<br/> <br/> (vii) A list of categories of personal information that we have disclosed for a business purpose, along with the category of any other company we shared it with.<br/> <br/>Please note, you are entitled to ask us to provide you with this information up to two times in a rolling twelve-month period. When you make this request, the information provided may be limited to the personal information we collected about you in the previous 12 months.<br/> <br/>(b) To delete your personal information. If you make this request, we will delete the personal information we hold about you as of the date of your request from our records and direct any service providers to do the same. In some cases, deletion may be accomplished through de-identification of the information. If you choose to delete your personal information, you may not be able to use certain functions that require your personal information to operate. <br/> <br/>(c) To stop selling your personal information. We do not sell your personal information for monetary consideration. However, under some circumstances, a transfer of personal information to a third party, or within our family of companies, without monetary consideration may be considered a “sale” under California law.<br/> <br/>If you submit a request to stop selling your personal information, we will stop making such transfers. If you are a California resident, to opt-out of the sale of your personal information, click “Do Not Sell My Personal Information” at the bottom of our home page to submit your request.<br/> <br/>Please note, if you ask us to delete or stop selling your data, it may impact your experience with us, and you may not be able to participate in certain programs or membership services which require the usage of your personal information to function. But in no circumstances, we will discriminate against you for exercising your rights.<br/> <br/>To exercise your California data protection rights described above, please send your request(s) by one of the following means:<br/> <br/>By email: info@getsynth.com<br/> <br/>By visiting this page on our website: http://getsynth.com/contact<br/> <br/>Your data protection rights, described above, are covered by the CCPA, short for the California Consumer Privacy Act. To find out more, visit the official California Legislative Information website. The CCPA took effect on 01/01/2020. <br/> <br/><strong>13. Service Providers<br/></strong> <br/>We may employ third party companies and individuals to facilitate our Service (“Service Providers”), provide Service on our behalf, perform Service-related services or assist us in analysing how our Service is used.<br/> <br/>These third parties have access to your Personal Data only to perform these tasks on our behalf and are obligated not to disclose or use it for any other purpose.<br/> <br/><strong>14. Analytics<br/></strong> <br/>We may use third-party Service Providers to monitor and analyze the use of our Service.<br/> <br/>Fathom Analytics<br/>Fathom Analytics is analytics service provided by Conva Ventures Inc. You can find their Privacy Policy here: https://usefathom.com/privacy/<br/> <br/><strong>15. CI/CD tools<br/></strong> <br/>We may use third-party Service Providers to automate the development process of our Service. <br/> <br/>GitHub<br/> <br/>GitHub is provided by GitHub, Inc.<br/> <br/>GitHub is a development platform to host and review code, manage projects, and build software.<br/> <br/>For more information on what data GitHub collects for what purpose and how the protection of the data is ensured, please visit GitHub Privacy Policy page: https://help.github.com/en/articles/github-privacy-statement.<br/> <br/><strong>16. Payments<br/></strong> <br/>We may provide paid products and/or services within Service. In that case, we use third-party services for payment processing (e.g. payment processors).<br/> <br/>We will not store or collect your payment card details. That information is provided directly to our third-party payment processors whose use of your personal information is governed by their Privacy Policy. These payment processors adhere to the standards set by PCI-DSS as managed by the PCI Security Standards Council, which is a joint effort of brands like Visa, Mastercard, American Express and Discover. PCI-DSS requirements help ensure the secure handling of payment information.<br/> <br/>The payment processors we work with are:<br/> <br/><strong>Stripe:</strong><span><strong><br/></strong>T</span>heir Privacy Policy can be viewed at: https://stripe.com/us/privacy<br/> <br/><strong>17. Links to Other Sites<br/></strong> <br/>Our Service may contain links to other sites that are not operated by us. If you click a third party link, you will be directed to that third party&#x27;s site. We strongly advise you to review the Privacy Policy of every site you visit.<br/> <br/>We have no control over and assume no responsibility for the content, privacy policies or practices of any third party sites or services.<br/> <br/><strong>18. Children&#x27;s Privacy<br/></strong> <br/>Our Services are not intended for use by children under the age of 18 (“Child” or “Children”). <br/> <br/>We do not knowingly collect personally identifiable information from Children under 18. If you become aware that a Child has provided us with Personal Data, please contact us. If we become aware that we have collected Personal Data from Children without verification of parental consent, we take steps to remove that information from our servers.<br/> <br/><strong>19. Changes to This Privacy Policy<br/></strong> <br/>We may update our Privacy Policy from time to time. We will notify you of any changes by posting the new Privacy Policy on this page.<br/> <br/>We will let you know via email and/or a prominent notice on our Service, prior to the change becoming effective and update “effective date” at the top of this Privacy Policy.<br/> <br/>You are advised to review this Privacy Policy periodically for any changes. Changes to this Privacy Policy are effective when they are posted on this page.<br/> <br/><strong>20. Contact Us<br/></strong> <br/>If you have any questions about this Privacy Policy, please contact us:<br/> <br/>By email: info@getsynth.com.<br/> <br/>By visiting this page on our website: http://getsynth.com/contact. </div> </div> </Section> ); } export default Privacy;
the_stack
/* tslint:disable */ //---------------------- // <auto-generated> // Generated using the NSwag toolchain v8.8.6231.38725 (NJsonSchema v7.7.6231.35489) (http://NSwag.org) // </auto-generated> //---------------------- import * as moment from 'moment'; import 'rxjs/Rx'; import {Observable} from 'rxjs/Observable'; import {Injectable, Inject, Optional, OpaqueToken} from '@angular/core'; import {Http, Headers, Response, RequestOptionsArgs} from '@angular/http'; export const API_BASE_URL = new OpaqueToken('API_BASE_URL'); @Injectable() export class AccountServiceProxy { private http: Http = null; private baseUrl: string = undefined; protected jsonParseReviver: (key: string, value: any) => any = undefined; constructor(@Inject(Http) http: Http, @Optional() @Inject(API_BASE_URL) baseUrl?: string) { this.http = http; this.baseUrl = baseUrl ? baseUrl : ""; } /** * @return Success */ isTenantAvailable(input: IsTenantAvailableInput): Observable<IsTenantAvailableOutput> { let url_ = this.baseUrl + "/api/services/app/Account/IsTenantAvailable"; const content_ = JSON.stringify(input ? input.toJS() : null); return this.http.request(url_, { body: content_, method: "post", headers: new Headers({ "Content-Type": "application/json; charset=UTF-8", "Accept": "application/json; charset=UTF-8" }) }).map((response) => { return this.processIsTenantAvailable(response); }).catch((response: any, caught: any) => { if (response instanceof Response) { try { return Observable.of(this.processIsTenantAvailable(response)); } catch (e) { return <Observable<IsTenantAvailableOutput>><any>Observable.throw(e); } } else return <Observable<IsTenantAvailableOutput>><any>Observable.throw(response); }); } protected processIsTenantAvailable(response: Response): IsTenantAvailableOutput { const responseText = response.text(); const status = response.status; if (status === 200) { let result200: IsTenantAvailableOutput = null; let resultData200 = responseText === "" ? null : JSON.parse(responseText, this.jsonParseReviver); result200 = resultData200 ? IsTenantAvailableOutput.fromJS(resultData200) : new IsTenantAvailableOutput(); return result200; } else if (status !== 200 && status !== 204) { this.throwException("An unexpected server error occurred.", status, responseText); } return null; } /** * @return Success */ register(input: RegisterInput): Observable<RegisterOutput> { let url_ = this.baseUrl + "/api/services/app/Account/Register"; const content_ = JSON.stringify(input ? input.toJS() : null); return this.http.request(url_, { body: content_, method: "post", headers: new Headers({ "Content-Type": "application/json; charset=UTF-8", "Accept": "application/json; charset=UTF-8" }) }).map((response) => { return this.processRegister(response); }).catch((response: any, caught: any) => { if (response instanceof Response) { try { return Observable.of(this.processRegister(response)); } catch (e) { return <Observable<RegisterOutput>><any>Observable.throw(e); } } else return <Observable<RegisterOutput>><any>Observable.throw(response); }); } protected processRegister(response: Response): RegisterOutput { const responseText = response.text(); const status = response.status; if (status === 200) { let result200: RegisterOutput = null; let resultData200 = responseText === "" ? null : JSON.parse(responseText, this.jsonParseReviver); result200 = resultData200 ? RegisterOutput.fromJS(resultData200) : new RegisterOutput(); return result200; } else if (status !== 200 && status !== 204) { this.throwException("An unexpected server error occurred.", status, responseText); } return null; } protected throwException(message: string, status: number, response: string, result?: any): any { if(result !== null && result !== undefined) throw result; else throw new SwaggerException(message, status, response); } } @Injectable() export class ConfigurationServiceProxy { private http: Http = null; private baseUrl: string = undefined; protected jsonParseReviver: (key: string, value: any) => any = undefined; constructor(@Inject(Http) http: Http, @Optional() @Inject(API_BASE_URL) baseUrl?: string) { this.http = http; this.baseUrl = baseUrl ? baseUrl : ""; } /** * @return Success */ changeUiTheme(input: ChangeUiThemeInput): Observable<void> { let url_ = this.baseUrl + "/api/services/app/Configuration/ChangeUiTheme"; const content_ = JSON.stringify(input ? input.toJS() : null); return this.http.request(url_, { body: content_, method: "post", headers: new Headers({ "Content-Type": "application/json; charset=UTF-8", "Accept": "application/json; charset=UTF-8" }) }).map((response) => { return this.processChangeUiTheme(response); }).catch((response: any, caught: any) => { if (response instanceof Response) { try { return Observable.of(this.processChangeUiTheme(response)); } catch (e) { return <Observable<void>><any>Observable.throw(e); } } else return <Observable<void>><any>Observable.throw(response); }); } protected processChangeUiTheme(response: Response): void { const responseText = response.text(); const status = response.status; if (status === 200) { return null; } else if (status !== 200 && status !== 204) { this.throwException("An unexpected server error occurred.", status, responseText); } return null; } protected throwException(message: string, status: number, response: string, result?: any): any { if(result !== null && result !== undefined) throw result; else throw new SwaggerException(message, status, response); } } @Injectable() export class RoleServiceProxy { private http: Http = null; private baseUrl: string = undefined; protected jsonParseReviver: (key: string, value: any) => any = undefined; constructor(@Inject(Http) http: Http, @Optional() @Inject(API_BASE_URL) baseUrl?: string) { this.http = http; this.baseUrl = baseUrl ? baseUrl : ""; } /** * @return Success */ updateRolePermissions(input: UpdateRolePermissionsInput): Observable<void> { let url_ = this.baseUrl + "/api/services/app/Role/UpdateRolePermissions"; const content_ = JSON.stringify(input ? input.toJS() : null); return this.http.request(url_, { body: content_, method: "put", headers: new Headers({ "Content-Type": "application/json; charset=UTF-8", "Accept": "application/json; charset=UTF-8" }) }).map((response) => { return this.processUpdateRolePermissions(response); }).catch((response: any, caught: any) => { if (response instanceof Response) { try { return Observable.of(this.processUpdateRolePermissions(response)); } catch (e) { return <Observable<void>><any>Observable.throw(e); } } else return <Observable<void>><any>Observable.throw(response); }); } protected processUpdateRolePermissions(response: Response): void { const responseText = response.text(); const status = response.status; if (status === 200) { return null; } else if (status !== 200 && status !== 204) { this.throwException("An unexpected server error occurred.", status, responseText); } return null; } protected throwException(message: string, status: number, response: string, result?: any): any { if(result !== null && result !== undefined) throw result; else throw new SwaggerException(message, status, response); } } @Injectable() export class SessionServiceProxy { private http: Http = null; private baseUrl: string = undefined; protected jsonParseReviver: (key: string, value: any) => any = undefined; constructor(@Inject(Http) http: Http, @Optional() @Inject(API_BASE_URL) baseUrl?: string) { this.http = http; this.baseUrl = baseUrl ? baseUrl : ""; } /** * @return Success */ getCurrentLoginInformations(): Observable<GetCurrentLoginInformationsOutput> { let url_ = this.baseUrl + "/api/services/app/Session/GetCurrentLoginInformations"; const content_ = ""; return this.http.request(url_, { body: content_, method: "get", headers: new Headers({ "Content-Type": "application/json; charset=UTF-8", "Accept": "application/json; charset=UTF-8" }) }).map((response) => { return this.processGetCurrentLoginInformations(response); }).catch((response: any, caught: any) => { if (response instanceof Response) { try { return Observable.of(this.processGetCurrentLoginInformations(response)); } catch (e) { return <Observable<GetCurrentLoginInformationsOutput>><any>Observable.throw(e); } } else return <Observable<GetCurrentLoginInformationsOutput>><any>Observable.throw(response); }); } protected processGetCurrentLoginInformations(response: Response): GetCurrentLoginInformationsOutput { const responseText = response.text(); const status = response.status; if (status === 200) { let result200: GetCurrentLoginInformationsOutput = null; let resultData200 = responseText === "" ? null : JSON.parse(responseText, this.jsonParseReviver); result200 = resultData200 ? GetCurrentLoginInformationsOutput.fromJS(resultData200) : new GetCurrentLoginInformationsOutput(); return result200; } else if (status !== 200 && status !== 204) { this.throwException("An unexpected server error occurred.", status, responseText); } return null; } protected throwException(message: string, status: number, response: string, result?: any): any { if(result !== null && result !== undefined) throw result; else throw new SwaggerException(message, status, response); } } @Injectable() export class TenantServiceProxy { private http: Http = null; private baseUrl: string = undefined; protected jsonParseReviver: (key: string, value: any) => any = undefined; constructor(@Inject(Http) http: Http, @Optional() @Inject(API_BASE_URL) baseUrl?: string) { this.http = http; this.baseUrl = baseUrl ? baseUrl : ""; } /** * @return Success */ getTenants(): Observable<ListResultDtoOfTenantListDto> { let url_ = this.baseUrl + "/api/services/app/Tenant/GetTenants"; const content_ = ""; return this.http.request(url_, { body: content_, method: "get", headers: new Headers({ "Content-Type": "application/json; charset=UTF-8", "Accept": "application/json; charset=UTF-8" }) }).map((response) => { return this.processGetTenants(response); }).catch((response: any, caught: any) => { if (response instanceof Response) { try { return Observable.of(this.processGetTenants(response)); } catch (e) { return <Observable<ListResultDtoOfTenantListDto>><any>Observable.throw(e); } } else return <Observable<ListResultDtoOfTenantListDto>><any>Observable.throw(response); }); } protected processGetTenants(response: Response): ListResultDtoOfTenantListDto { const responseText = response.text(); const status = response.status; if (status === 200) { let result200: ListResultDtoOfTenantListDto = null; let resultData200 = responseText === "" ? null : JSON.parse(responseText, this.jsonParseReviver); result200 = resultData200 ? ListResultDtoOfTenantListDto.fromJS(resultData200) : new ListResultDtoOfTenantListDto(); return result200; } else if (status !== 200 && status !== 204) { this.throwException("An unexpected server error occurred.", status, responseText); } return null; } /** * @return Success */ createTenant(input: CreateTenantInput): Observable<void> { let url_ = this.baseUrl + "/api/services/app/Tenant/CreateTenant"; const content_ = JSON.stringify(input ? input.toJS() : null); return this.http.request(url_, { body: content_, method: "post", headers: new Headers({ "Content-Type": "application/json; charset=UTF-8", "Accept": "application/json; charset=UTF-8" }) }).map((response) => { return this.processCreateTenant(response); }).catch((response: any, caught: any) => { if (response instanceof Response) { try { return Observable.of(this.processCreateTenant(response)); } catch (e) { return <Observable<void>><any>Observable.throw(e); } } else return <Observable<void>><any>Observable.throw(response); }); } protected processCreateTenant(response: Response): void { const responseText = response.text(); const status = response.status; if (status === 200) { return null; } else if (status !== 200 && status !== 204) { this.throwException("An unexpected server error occurred.", status, responseText); } return null; } protected throwException(message: string, status: number, response: string, result?: any): any { if(result !== null && result !== undefined) throw result; else throw new SwaggerException(message, status, response); } } @Injectable() export class TokenAuthServiceProxy { private http: Http = null; private baseUrl: string = undefined; protected jsonParseReviver: (key: string, value: any) => any = undefined; constructor(@Inject(Http) http: Http, @Optional() @Inject(API_BASE_URL) baseUrl?: string) { this.http = http; this.baseUrl = baseUrl ? baseUrl : ""; } /** * @return Success */ authenticate(model: AuthenticateModel): Observable<AuthenticateResultModel> { let url_ = this.baseUrl + "/api/TokenAuth/Authenticate"; const content_ = JSON.stringify(model ? model.toJS() : null); return this.http.request(url_, { body: content_, method: "post", headers: new Headers({ "Content-Type": "application/json; charset=UTF-8", "Accept": "application/json; charset=UTF-8" }) }).map((response) => { return this.processAuthenticate(response); }).catch((response: any, caught: any) => { if (response instanceof Response) { try { return Observable.of(this.processAuthenticate(response)); } catch (e) { return <Observable<AuthenticateResultModel>><any>Observable.throw(e); } } else return <Observable<AuthenticateResultModel>><any>Observable.throw(response); }); } protected processAuthenticate(response: Response): AuthenticateResultModel { const responseText = response.text(); const status = response.status; if (status === 200) { let result200: AuthenticateResultModel = null; let resultData200 = responseText === "" ? null : JSON.parse(responseText, this.jsonParseReviver); result200 = resultData200 ? AuthenticateResultModel.fromJS(resultData200) : new AuthenticateResultModel(); return result200; } else if (status !== 200 && status !== 204) { this.throwException("An unexpected server error occurred.", status, responseText); } return null; } /** * @return Success */ getExternalAuthenticationProviders(): Observable<ExternalLoginProviderInfoModel[]> { let url_ = this.baseUrl + "/api/TokenAuth/GetExternalAuthenticationProviders"; const content_ = ""; return this.http.request(url_, { body: content_, method: "get", headers: new Headers({ "Content-Type": "application/json; charset=UTF-8", "Accept": "application/json; charset=UTF-8" }) }).map((response) => { return this.processGetExternalAuthenticationProviders(response); }).catch((response: any, caught: any) => { if (response instanceof Response) { try { return Observable.of(this.processGetExternalAuthenticationProviders(response)); } catch (e) { return <Observable<ExternalLoginProviderInfoModel[]>><any>Observable.throw(e); } } else return <Observable<ExternalLoginProviderInfoModel[]>><any>Observable.throw(response); }); } protected processGetExternalAuthenticationProviders(response: Response): ExternalLoginProviderInfoModel[] { const responseText = response.text(); const status = response.status; if (status === 200) { let result200: ExternalLoginProviderInfoModel[] = null; let resultData200 = responseText === "" ? null : JSON.parse(responseText, this.jsonParseReviver); if (resultData200 && resultData200.constructor === Array) { result200 = []; for (let item of resultData200) result200.push(ExternalLoginProviderInfoModel.fromJS(item)); } return result200; } else if (status !== 200 && status !== 204) { this.throwException("An unexpected server error occurred.", status, responseText); } return null; } /** * @return Success */ externalAuthenticate(model: ExternalAuthenticateModel): Observable<ExternalAuthenticateResultModel> { let url_ = this.baseUrl + "/api/TokenAuth/ExternalAuthenticate"; const content_ = JSON.stringify(model ? model.toJS() : null); return this.http.request(url_, { body: content_, method: "post", headers: new Headers({ "Content-Type": "application/json; charset=UTF-8", "Accept": "application/json; charset=UTF-8" }) }).map((response) => { return this.processExternalAuthenticate(response); }).catch((response: any, caught: any) => { if (response instanceof Response) { try { return Observable.of(this.processExternalAuthenticate(response)); } catch (e) { return <Observable<ExternalAuthenticateResultModel>><any>Observable.throw(e); } } else return <Observable<ExternalAuthenticateResultModel>><any>Observable.throw(response); }); } protected processExternalAuthenticate(response: Response): ExternalAuthenticateResultModel { const responseText = response.text(); const status = response.status; if (status === 200) { let result200: ExternalAuthenticateResultModel = null; let resultData200 = responseText === "" ? null : JSON.parse(responseText, this.jsonParseReviver); result200 = resultData200 ? ExternalAuthenticateResultModel.fromJS(resultData200) : new ExternalAuthenticateResultModel(); return result200; } else if (status !== 200 && status !== 204) { this.throwException("An unexpected server error occurred.", status, responseText); } return null; } protected throwException(message: string, status: number, response: string, result?: any): any { if(result !== null && result !== undefined) throw result; else throw new SwaggerException(message, status, response); } } @Injectable() export class UserServiceProxy { private http: Http = null; private baseUrl: string = undefined; protected jsonParseReviver: (key: string, value: any) => any = undefined; constructor(@Inject(Http) http: Http, @Optional() @Inject(API_BASE_URL) baseUrl?: string) { this.http = http; this.baseUrl = baseUrl ? baseUrl : ""; } /** * @return Success */ prohibitPermission(input: ProhibitPermissionInput): Observable<void> { let url_ = this.baseUrl + "/api/services/app/User/ProhibitPermission"; const content_ = JSON.stringify(input ? input.toJS() : null); return this.http.request(url_, { body: content_, method: "post", headers: new Headers({ "Content-Type": "application/json; charset=UTF-8", "Accept": "application/json; charset=UTF-8" }) }).map((response) => { return this.processProhibitPermission(response); }).catch((response: any, caught: any) => { if (response instanceof Response) { try { return Observable.of(this.processProhibitPermission(response)); } catch (e) { return <Observable<void>><any>Observable.throw(e); } } else return <Observable<void>><any>Observable.throw(response); }); } protected processProhibitPermission(response: Response): void { const responseText = response.text(); const status = response.status; if (status === 200) { return null; } else if (status !== 200 && status !== 204) { this.throwException("An unexpected server error occurred.", status, responseText); } return null; } /** * @return Success */ removeFromRole(userId: number, roleName: string): Observable<void> { let url_ = this.baseUrl + "/api/services/app/User/RemoveFromRole?"; if (userId !== undefined) url_ += "userId=" + encodeURIComponent("" + userId) + "&"; if (roleName !== undefined) url_ += "roleName=" + encodeURIComponent("" + roleName) + "&"; const content_ = ""; return this.http.request(url_, { body: content_, method: "delete", headers: new Headers({ "Content-Type": "application/json; charset=UTF-8", "Accept": "application/json; charset=UTF-8" }) }).map((response) => { return this.processRemoveFromRole(response); }).catch((response: any, caught: any) => { if (response instanceof Response) { try { return Observable.of(this.processRemoveFromRole(response)); } catch (e) { return <Observable<void>><any>Observable.throw(e); } } else return <Observable<void>><any>Observable.throw(response); }); } protected processRemoveFromRole(response: Response): void { const responseText = response.text(); const status = response.status; if (status === 200) { return null; } else if (status !== 200 && status !== 204) { this.throwException("An unexpected server error occurred.", status, responseText); } return null; } /** * @return Success */ getUsers(): Observable<ListResultDtoOfUserListDto> { let url_ = this.baseUrl + "/api/services/app/User/GetUsers"; const content_ = ""; return this.http.request(url_, { body: content_, method: "get", headers: new Headers({ "Content-Type": "application/json; charset=UTF-8", "Accept": "application/json; charset=UTF-8" }) }).map((response) => { return this.processGetUsers(response); }).catch((response: any, caught: any) => { if (response instanceof Response) { try { return Observable.of(this.processGetUsers(response)); } catch (e) { return <Observable<ListResultDtoOfUserListDto>><any>Observable.throw(e); } } else return <Observable<ListResultDtoOfUserListDto>><any>Observable.throw(response); }); } protected processGetUsers(response: Response): ListResultDtoOfUserListDto { const responseText = response.text(); const status = response.status; if (status === 200) { let result200: ListResultDtoOfUserListDto = null; let resultData200 = responseText === "" ? null : JSON.parse(responseText, this.jsonParseReviver); result200 = resultData200 ? ListResultDtoOfUserListDto.fromJS(resultData200) : new ListResultDtoOfUserListDto(); return result200; } else if (status !== 200 && status !== 204) { this.throwException("An unexpected server error occurred.", status, responseText); } return null; } /** * @return Success */ createUser(input: CreateUserInput): Observable<void> { let url_ = this.baseUrl + "/api/services/app/User/CreateUser"; const content_ = JSON.stringify(input ? input.toJS() : null); return this.http.request(url_, { body: content_, method: "post", headers: new Headers({ "Content-Type": "application/json; charset=UTF-8", "Accept": "application/json; charset=UTF-8" }) }).map((response) => { return this.processCreateUser(response); }).catch((response: any, caught: any) => { if (response instanceof Response) { try { return Observable.of(this.processCreateUser(response)); } catch (e) { return <Observable<void>><any>Observable.throw(e); } } else return <Observable<void>><any>Observable.throw(response); }); } protected processCreateUser(response: Response): void { const responseText = response.text(); const status = response.status; if (status === 200) { return null; } else if (status !== 200 && status !== 204) { this.throwException("An unexpected server error occurred.", status, responseText); } return null; } protected throwException(message: string, status: number, response: string, result?: any): any { if(result !== null && result !== undefined) throw result; else throw new SwaggerException(message, status, response); } } export class IsTenantAvailableInput { tenancyName: string; constructor(data?: any) { if (data !== undefined) { this.tenancyName = data["tenancyName"] !== undefined ? data["tenancyName"] : null; } } static fromJS(data: any): IsTenantAvailableInput { return new IsTenantAvailableInput(data); } toJS(data?: any) { data = data === undefined ? {} : data; data["tenancyName"] = this.tenancyName !== undefined ? this.tenancyName : null; return data; } toJSON() { return JSON.stringify(this.toJS()); } clone() { const json = this.toJSON(); return new IsTenantAvailableInput(JSON.parse(json)); } } export class IsTenantAvailableOutput { state: IsTenantAvailableOutputState; tenantId: number; constructor(data?: any) { if (data !== undefined) { this.state = data["state"] !== undefined ? data["state"] : null; this.tenantId = data["tenantId"] !== undefined ? data["tenantId"] : null; } } static fromJS(data: any): IsTenantAvailableOutput { return new IsTenantAvailableOutput(data); } toJS(data?: any) { data = data === undefined ? {} : data; data["state"] = this.state !== undefined ? this.state : null; data["tenantId"] = this.tenantId !== undefined ? this.tenantId : null; return data; } toJSON() { return JSON.stringify(this.toJS()); } clone() { const json = this.toJSON(); return new IsTenantAvailableOutput(JSON.parse(json)); } } export class RegisterInput { name: string; surname: string; userName: string; emailAddress: string; password: string; captchaResponse: string; constructor(data?: any) { if (data !== undefined) { this.name = data["name"] !== undefined ? data["name"] : null; this.surname = data["surname"] !== undefined ? data["surname"] : null; this.userName = data["userName"] !== undefined ? data["userName"] : null; this.emailAddress = data["emailAddress"] !== undefined ? data["emailAddress"] : null; this.password = data["password"] !== undefined ? data["password"] : null; this.captchaResponse = data["captchaResponse"] !== undefined ? data["captchaResponse"] : null; } } static fromJS(data: any): RegisterInput { return new RegisterInput(data); } toJS(data?: any) { data = data === undefined ? {} : data; data["name"] = this.name !== undefined ? this.name : null; data["surname"] = this.surname !== undefined ? this.surname : null; data["userName"] = this.userName !== undefined ? this.userName : null; data["emailAddress"] = this.emailAddress !== undefined ? this.emailAddress : null; data["password"] = this.password !== undefined ? this.password : null; data["captchaResponse"] = this.captchaResponse !== undefined ? this.captchaResponse : null; return data; } toJSON() { return JSON.stringify(this.toJS()); } clone() { const json = this.toJSON(); return new RegisterInput(JSON.parse(json)); } } export class RegisterOutput { canLogin: boolean; constructor(data?: any) { if (data !== undefined) { this.canLogin = data["canLogin"] !== undefined ? data["canLogin"] : null; } } static fromJS(data: any): RegisterOutput { return new RegisterOutput(data); } toJS(data?: any) { data = data === undefined ? {} : data; data["canLogin"] = this.canLogin !== undefined ? this.canLogin : null; return data; } toJSON() { return JSON.stringify(this.toJS()); } clone() { const json = this.toJSON(); return new RegisterOutput(JSON.parse(json)); } } export class ChangeUiThemeInput { theme: string; constructor(data?: any) { if (data !== undefined) { this.theme = data["theme"] !== undefined ? data["theme"] : null; } } static fromJS(data: any): ChangeUiThemeInput { return new ChangeUiThemeInput(data); } toJS(data?: any) { data = data === undefined ? {} : data; data["theme"] = this.theme !== undefined ? this.theme : null; return data; } toJSON() { return JSON.stringify(this.toJS()); } clone() { const json = this.toJSON(); return new ChangeUiThemeInput(JSON.parse(json)); } } export class UpdateRolePermissionsInput { roleId: number; grantedPermissionNames: string[] = []; constructor(data?: any) { if (data !== undefined) { this.roleId = data["roleId"] !== undefined ? data["roleId"] : null; if (data["grantedPermissionNames"] && data["grantedPermissionNames"].constructor === Array) { this.grantedPermissionNames = []; for (let item of data["grantedPermissionNames"]) this.grantedPermissionNames.push(item); } } } static fromJS(data: any): UpdateRolePermissionsInput { return new UpdateRolePermissionsInput(data); } toJS(data?: any) { data = data === undefined ? {} : data; data["roleId"] = this.roleId !== undefined ? this.roleId : null; if (this.grantedPermissionNames && this.grantedPermissionNames.constructor === Array) { data["grantedPermissionNames"] = []; for (let item of this.grantedPermissionNames) data["grantedPermissionNames"].push(item); } return data; } toJSON() { return JSON.stringify(this.toJS()); } clone() { const json = this.toJSON(); return new UpdateRolePermissionsInput(JSON.parse(json)); } } export class GetCurrentLoginInformationsOutput { application: ApplicationInfoDto; user: UserLoginInfoDto; tenant: TenantLoginInfoDto; constructor(data?: any) { if (data !== undefined) { this.application = data["application"] ? ApplicationInfoDto.fromJS(data["application"]) : null; this.user = data["user"] ? UserLoginInfoDto.fromJS(data["user"]) : null; this.tenant = data["tenant"] ? TenantLoginInfoDto.fromJS(data["tenant"]) : null; } } static fromJS(data: any): GetCurrentLoginInformationsOutput { return new GetCurrentLoginInformationsOutput(data); } toJS(data?: any) { data = data === undefined ? {} : data; data["application"] = this.application ? this.application.toJS() : null; data["user"] = this.user ? this.user.toJS() : null; data["tenant"] = this.tenant ? this.tenant.toJS() : null; return data; } toJSON() { return JSON.stringify(this.toJS()); } clone() { const json = this.toJSON(); return new GetCurrentLoginInformationsOutput(JSON.parse(json)); } } export class ApplicationInfoDto { version: string; releaseDate: moment.Moment; features: { [key: string] : boolean; }; constructor(data?: any) { if (data !== undefined) { this.version = data["version"] !== undefined ? data["version"] : null; this.releaseDate = data["releaseDate"] ? moment(data["releaseDate"].toString()) : null; if (data["features"]) { this.features = {}; for (let key in data["features"]) { if (data["features"].hasOwnProperty(key)) this.features[key] = data["features"][key] !== undefined ? data["features"][key] : null; } } } } static fromJS(data: any): ApplicationInfoDto { return new ApplicationInfoDto(data); } toJS(data?: any) { data = data === undefined ? {} : data; data["version"] = this.version !== undefined ? this.version : null; data["releaseDate"] = this.releaseDate ? this.releaseDate.toISOString() : null; if (this.features) { data["features"] = {}; for (let key in this.features) { if (this.features.hasOwnProperty(key)) data["features"][key] = this.features[key] !== undefined ? this.features[key] : null; } } return data; } toJSON() { return JSON.stringify(this.toJS()); } clone() { const json = this.toJSON(); return new ApplicationInfoDto(JSON.parse(json)); } } export class UserLoginInfoDto { name: string; surname: string; userName: string; emailAddress: string; id: number; constructor(data?: any) { if (data !== undefined) { this.name = data["name"] !== undefined ? data["name"] : null; this.surname = data["surname"] !== undefined ? data["surname"] : null; this.userName = data["userName"] !== undefined ? data["userName"] : null; this.emailAddress = data["emailAddress"] !== undefined ? data["emailAddress"] : null; this.id = data["id"] !== undefined ? data["id"] : null; } } static fromJS(data: any): UserLoginInfoDto { return new UserLoginInfoDto(data); } toJS(data?: any) { data = data === undefined ? {} : data; data["name"] = this.name !== undefined ? this.name : null; data["surname"] = this.surname !== undefined ? this.surname : null; data["userName"] = this.userName !== undefined ? this.userName : null; data["emailAddress"] = this.emailAddress !== undefined ? this.emailAddress : null; data["id"] = this.id !== undefined ? this.id : null; return data; } toJSON() { return JSON.stringify(this.toJS()); } clone() { const json = this.toJSON(); return new UserLoginInfoDto(JSON.parse(json)); } } export class TenantLoginInfoDto { tenancyName: string; name: string; id: number; constructor(data?: any) { if (data !== undefined) { this.tenancyName = data["tenancyName"] !== undefined ? data["tenancyName"] : null; this.name = data["name"] !== undefined ? data["name"] : null; this.id = data["id"] !== undefined ? data["id"] : null; } } static fromJS(data: any): TenantLoginInfoDto { return new TenantLoginInfoDto(data); } toJS(data?: any) { data = data === undefined ? {} : data; data["tenancyName"] = this.tenancyName !== undefined ? this.tenancyName : null; data["name"] = this.name !== undefined ? this.name : null; data["id"] = this.id !== undefined ? this.id : null; return data; } toJSON() { return JSON.stringify(this.toJS()); } clone() { const json = this.toJSON(); return new TenantLoginInfoDto(JSON.parse(json)); } } export class ListResultDtoOfTenantListDto { items: TenantListDto[]; constructor(data?: any) { if (data !== undefined) { if (data["items"] && data["items"].constructor === Array) { this.items = []; for (let item of data["items"]) this.items.push(TenantListDto.fromJS(item)); } } } static fromJS(data: any): ListResultDtoOfTenantListDto { return new ListResultDtoOfTenantListDto(data); } toJS(data?: any) { data = data === undefined ? {} : data; if (this.items && this.items.constructor === Array) { data["items"] = []; for (let item of this.items) data["items"].push(item.toJS()); } return data; } toJSON() { return JSON.stringify(this.toJS()); } clone() { const json = this.toJSON(); return new ListResultDtoOfTenantListDto(JSON.parse(json)); } } export class TenantListDto { tenancyName: string; name: string; id: number; constructor(data?: any) { if (data !== undefined) { this.tenancyName = data["tenancyName"] !== undefined ? data["tenancyName"] : null; this.name = data["name"] !== undefined ? data["name"] : null; this.id = data["id"] !== undefined ? data["id"] : null; } } static fromJS(data: any): TenantListDto { return new TenantListDto(data); } toJS(data?: any) { data = data === undefined ? {} : data; data["tenancyName"] = this.tenancyName !== undefined ? this.tenancyName : null; data["name"] = this.name !== undefined ? this.name : null; data["id"] = this.id !== undefined ? this.id : null; return data; } toJSON() { return JSON.stringify(this.toJS()); } clone() { const json = this.toJSON(); return new TenantListDto(JSON.parse(json)); } } export class CreateTenantInput { tenancyName: string; name: string; adminEmailAddress: string; connectionString: string; constructor(data?: any) { if (data !== undefined) { this.tenancyName = data["tenancyName"] !== undefined ? data["tenancyName"] : null; this.name = data["name"] !== undefined ? data["name"] : null; this.adminEmailAddress = data["adminEmailAddress"] !== undefined ? data["adminEmailAddress"] : null; this.connectionString = data["connectionString"] !== undefined ? data["connectionString"] : null; } } static fromJS(data: any): CreateTenantInput { return new CreateTenantInput(data); } toJS(data?: any) { data = data === undefined ? {} : data; data["tenancyName"] = this.tenancyName !== undefined ? this.tenancyName : null; data["name"] = this.name !== undefined ? this.name : null; data["adminEmailAddress"] = this.adminEmailAddress !== undefined ? this.adminEmailAddress : null; data["connectionString"] = this.connectionString !== undefined ? this.connectionString : null; return data; } toJSON() { return JSON.stringify(this.toJS()); } clone() { const json = this.toJSON(); return new CreateTenantInput(JSON.parse(json)); } } export class AuthenticateModel { userNameOrEmailAddress: string; password: string; rememberClient: boolean; constructor(data?: any) { if (data !== undefined) { this.userNameOrEmailAddress = data["userNameOrEmailAddress"] !== undefined ? data["userNameOrEmailAddress"] : null; this.password = data["password"] !== undefined ? data["password"] : null; this.rememberClient = data["rememberClient"] !== undefined ? data["rememberClient"] : null; } } static fromJS(data: any): AuthenticateModel { return new AuthenticateModel(data); } toJS(data?: any) { data = data === undefined ? {} : data; data["userNameOrEmailAddress"] = this.userNameOrEmailAddress !== undefined ? this.userNameOrEmailAddress : null; data["password"] = this.password !== undefined ? this.password : null; data["rememberClient"] = this.rememberClient !== undefined ? this.rememberClient : null; return data; } toJSON() { return JSON.stringify(this.toJS()); } clone() { const json = this.toJSON(); return new AuthenticateModel(JSON.parse(json)); } } export class AuthenticateResultModel { accessToken: string; encryptedAccessToken: string; expireInSeconds: number; userId: number; constructor(data?: any) { if (data !== undefined) { this.accessToken = data["accessToken"] !== undefined ? data["accessToken"] : null; this.encryptedAccessToken = data["encryptedAccessToken"] !== undefined ? data["encryptedAccessToken"] : null; this.expireInSeconds = data["expireInSeconds"] !== undefined ? data["expireInSeconds"] : null; this.userId = data["userId"] !== undefined ? data["userId"] : null; } } static fromJS(data: any): AuthenticateResultModel { return new AuthenticateResultModel(data); } toJS(data?: any) { data = data === undefined ? {} : data; data["accessToken"] = this.accessToken !== undefined ? this.accessToken : null; data["encryptedAccessToken"] = this.encryptedAccessToken !== undefined ? this.encryptedAccessToken : null; data["expireInSeconds"] = this.expireInSeconds !== undefined ? this.expireInSeconds : null; data["userId"] = this.userId !== undefined ? this.userId : null; return data; } toJSON() { return JSON.stringify(this.toJS()); } clone() { const json = this.toJSON(); return new AuthenticateResultModel(JSON.parse(json)); } } export class ExternalLoginProviderInfoModel { name: string; clientId: string; constructor(data?: any) { if (data !== undefined) { this.name = data["name"] !== undefined ? data["name"] : null; this.clientId = data["clientId"] !== undefined ? data["clientId"] : null; } } static fromJS(data: any): ExternalLoginProviderInfoModel { return new ExternalLoginProviderInfoModel(data); } toJS(data?: any) { data = data === undefined ? {} : data; data["name"] = this.name !== undefined ? this.name : null; data["clientId"] = this.clientId !== undefined ? this.clientId : null; return data; } toJSON() { return JSON.stringify(this.toJS()); } clone() { const json = this.toJSON(); return new ExternalLoginProviderInfoModel(JSON.parse(json)); } } export class ExternalAuthenticateModel { authProvider: string; providerKey: string; providerAccessCode: string; constructor(data?: any) { if (data !== undefined) { this.authProvider = data["authProvider"] !== undefined ? data["authProvider"] : null; this.providerKey = data["providerKey"] !== undefined ? data["providerKey"] : null; this.providerAccessCode = data["providerAccessCode"] !== undefined ? data["providerAccessCode"] : null; } } static fromJS(data: any): ExternalAuthenticateModel { return new ExternalAuthenticateModel(data); } toJS(data?: any) { data = data === undefined ? {} : data; data["authProvider"] = this.authProvider !== undefined ? this.authProvider : null; data["providerKey"] = this.providerKey !== undefined ? this.providerKey : null; data["providerAccessCode"] = this.providerAccessCode !== undefined ? this.providerAccessCode : null; return data; } toJSON() { return JSON.stringify(this.toJS()); } clone() { const json = this.toJSON(); return new ExternalAuthenticateModel(JSON.parse(json)); } } export class ExternalAuthenticateResultModel { accessToken: string; encryptedAccessToken: string; expireInSeconds: number; waitingForActivation: boolean; constructor(data?: any) { if (data !== undefined) { this.accessToken = data["accessToken"] !== undefined ? data["accessToken"] : null; this.encryptedAccessToken = data["encryptedAccessToken"] !== undefined ? data["encryptedAccessToken"] : null; this.expireInSeconds = data["expireInSeconds"] !== undefined ? data["expireInSeconds"] : null; this.waitingForActivation = data["waitingForActivation"] !== undefined ? data["waitingForActivation"] : null; } } static fromJS(data: any): ExternalAuthenticateResultModel { return new ExternalAuthenticateResultModel(data); } toJS(data?: any) { data = data === undefined ? {} : data; data["accessToken"] = this.accessToken !== undefined ? this.accessToken : null; data["encryptedAccessToken"] = this.encryptedAccessToken !== undefined ? this.encryptedAccessToken : null; data["expireInSeconds"] = this.expireInSeconds !== undefined ? this.expireInSeconds : null; data["waitingForActivation"] = this.waitingForActivation !== undefined ? this.waitingForActivation : null; return data; } toJSON() { return JSON.stringify(this.toJS()); } clone() { const json = this.toJSON(); return new ExternalAuthenticateResultModel(JSON.parse(json)); } } export class ProhibitPermissionInput { userId: number; permissionName: string; constructor(data?: any) { if (data !== undefined) { this.userId = data["userId"] !== undefined ? data["userId"] : null; this.permissionName = data["permissionName"] !== undefined ? data["permissionName"] : null; } } static fromJS(data: any): ProhibitPermissionInput { return new ProhibitPermissionInput(data); } toJS(data?: any) { data = data === undefined ? {} : data; data["userId"] = this.userId !== undefined ? this.userId : null; data["permissionName"] = this.permissionName !== undefined ? this.permissionName : null; return data; } toJSON() { return JSON.stringify(this.toJS()); } clone() { const json = this.toJSON(); return new ProhibitPermissionInput(JSON.parse(json)); } } export class ListResultDtoOfUserListDto { items: UserListDto[]; constructor(data?: any) { if (data !== undefined) { if (data["items"] && data["items"].constructor === Array) { this.items = []; for (let item of data["items"]) this.items.push(UserListDto.fromJS(item)); } } } static fromJS(data: any): ListResultDtoOfUserListDto { return new ListResultDtoOfUserListDto(data); } toJS(data?: any) { data = data === undefined ? {} : data; if (this.items && this.items.constructor === Array) { data["items"] = []; for (let item of this.items) data["items"].push(item.toJS()); } return data; } toJSON() { return JSON.stringify(this.toJS()); } clone() { const json = this.toJSON(); return new ListResultDtoOfUserListDto(JSON.parse(json)); } } export class UserListDto { name: string; surname: string; userName: string; fullName: string; emailAddress: string; isEmailConfirmed: boolean; lastLoginTime: moment.Moment; isActive: boolean; creationTime: moment.Moment; id: number; constructor(data?: any) { if (data !== undefined) { this.name = data["name"] !== undefined ? data["name"] : null; this.surname = data["surname"] !== undefined ? data["surname"] : null; this.userName = data["userName"] !== undefined ? data["userName"] : null; this.fullName = data["fullName"] !== undefined ? data["fullName"] : null; this.emailAddress = data["emailAddress"] !== undefined ? data["emailAddress"] : null; this.isEmailConfirmed = data["isEmailConfirmed"] !== undefined ? data["isEmailConfirmed"] : null; this.lastLoginTime = data["lastLoginTime"] ? moment(data["lastLoginTime"].toString()) : null; this.isActive = data["isActive"] !== undefined ? data["isActive"] : null; this.creationTime = data["creationTime"] ? moment(data["creationTime"].toString()) : null; this.id = data["id"] !== undefined ? data["id"] : null; } } static fromJS(data: any): UserListDto { return new UserListDto(data); } toJS(data?: any) { data = data === undefined ? {} : data; data["name"] = this.name !== undefined ? this.name : null; data["surname"] = this.surname !== undefined ? this.surname : null; data["userName"] = this.userName !== undefined ? this.userName : null; data["fullName"] = this.fullName !== undefined ? this.fullName : null; data["emailAddress"] = this.emailAddress !== undefined ? this.emailAddress : null; data["isEmailConfirmed"] = this.isEmailConfirmed !== undefined ? this.isEmailConfirmed : null; data["lastLoginTime"] = this.lastLoginTime ? this.lastLoginTime.toISOString() : null; data["isActive"] = this.isActive !== undefined ? this.isActive : null; data["creationTime"] = this.creationTime ? this.creationTime.toISOString() : null; data["id"] = this.id !== undefined ? this.id : null; return data; } toJSON() { return JSON.stringify(this.toJS()); } clone() { const json = this.toJSON(); return new UserListDto(JSON.parse(json)); } } export class CreateUserInput { userName: string; name: string; surname: string; emailAddress: string; password: string; isActive: boolean; constructor(data?: any) { if (data !== undefined) { this.userName = data["userName"] !== undefined ? data["userName"] : null; this.name = data["name"] !== undefined ? data["name"] : null; this.surname = data["surname"] !== undefined ? data["surname"] : null; this.emailAddress = data["emailAddress"] !== undefined ? data["emailAddress"] : null; this.password = data["password"] !== undefined ? data["password"] : null; this.isActive = data["isActive"] !== undefined ? data["isActive"] : null; } } static fromJS(data: any): CreateUserInput { return new CreateUserInput(data); } toJS(data?: any) { data = data === undefined ? {} : data; data["userName"] = this.userName !== undefined ? this.userName : null; data["name"] = this.name !== undefined ? this.name : null; data["surname"] = this.surname !== undefined ? this.surname : null; data["emailAddress"] = this.emailAddress !== undefined ? this.emailAddress : null; data["password"] = this.password !== undefined ? this.password : null; data["isActive"] = this.isActive !== undefined ? this.isActive : null; return data; } toJSON() { return JSON.stringify(this.toJS()); } clone() { const json = this.toJSON(); return new CreateUserInput(JSON.parse(json)); } } export enum IsTenantAvailableOutputState { _1 = 1, _2 = 2, _3 = 3, } export class SwaggerException extends Error { message: string; status: number; response: string; result?: any; constructor(message: string, status: number, response: string, result?: any) { super(); this.message = message; this.status = status; this.response = response; this.result = result; } }
the_stack
import { CoreCancellablePromise } from '@classes/cancellable-promise'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreUtils } from '@services/utils/utils'; import { CoreEventObserver } from '@singletons/events'; /** * Singleton with helper functions for dom. */ export class CoreDom { // Avoid creating singleton instances. private constructor() { // Nothing to do. } /** * Perform a dom closest function piercing the shadow DOM. * * @param node DOM Element. * @param selector Selector to search. * @return Closest ancestor or null if not found. */ static closest<T = HTMLElement>(node: HTMLElement | Node | null, selector: string): T | null { if (!node) { return null; } if (node instanceof ShadowRoot) { return CoreDom.closest(node.host, selector); } if (node instanceof HTMLElement) { if (node.matches(selector)) { return node as unknown as T; } else { return CoreDom.closest<T>(node.parentNode, selector); } } return CoreDom.closest<T>(node.parentNode, selector); } /** * Retrieve the position of a element relative to another element. * * @param element Element to get the position. * @param parent Parent element to get relative position. * @return X and Y position. */ static getRelativeElementPosition(element: HTMLElement, parent: HTMLElement): CoreCoordinates { // Get the top, left coordinates of two elements const elementRectangle = element.getBoundingClientRect(); const parentRectangle = parent.getBoundingClientRect(); // Calculate the top and left positions. return { x: elementRectangle.x - parentRectangle.x, y: elementRectangle.y - parentRectangle.y, }; } /** * Check whether an element has been added to the DOM. * * @param element Element. * @return True if element has been added to the DOM, false otherwise. */ static isElementInDom(element: HTMLElement): boolean { return element.getRootNode({ composed: true }) === document; } /** * Check whether an element is intersecting the intersectionRatio in viewport. * * @param element * @param intersectionRatio Intersection ratio (From 0 to 1). * @return True if in viewport. */ static isElementInViewport(element: HTMLElement, intersectionRatio = 1): boolean { const elementRectangle = element.getBoundingClientRect(); const elementArea = elementRectangle.width * elementRectangle.height; if (elementArea == 0) { return false; } const intersectionRectangle = { top: Math.max(0, elementRectangle.top), left: Math.max(0, elementRectangle.left), bottom: Math.min(window.innerHeight, elementRectangle.bottom), right: Math.min(window.innerWidth, elementRectangle.right), }; const intersectionArea = (intersectionRectangle.right - intersectionRectangle.left) * (intersectionRectangle.bottom - intersectionRectangle.top); return intersectionArea / elementArea >= intersectionRatio; } /** * Check whether an element is visible or not. * * @param element Element. * @param checkSize Wether to check size to check for visibility. * @return True if element is visible inside the DOM. */ static isElementVisible(element: HTMLElement, checkSize = true): boolean { if (checkSize && (element.clientWidth === 0 || element.clientHeight === 0)) { return false; } const style = getComputedStyle(element); if (style.opacity === '0' || style.display === 'none' || style.visibility === 'hidden') { return false; } return CoreDom.isElementInDom(element); } /** * Runs a function when an element has been slotted. * * @param element HTML Element inside an ion-content to wait for slot. * @param callback Function to execute on resize. */ static onElementSlot(element: HTMLElement, callback: (ev?: Event) => void): void { if (!element.slot) { // Element not declared to be slotted. return; } const slotName = element.slot; if (element.assignedSlot?.name === slotName) { // Slot already assigned. callback(); return; } const content = element.closest('ion-content'); if (!content || !content.shadowRoot) { // Cannot find content. return; } const slots = content.shadowRoot.querySelectorAll('slot'); const slot = Array.from(slots).find((slot) => slot.name === slotName); if (!slot) { // Slot not found. return; } const slotListener = () => { if (element.assignedSlot?.name !== slotName) { return; } callback(); // It would happen only once. slot.removeEventListener('slotchange', slotListener); }; slot.addEventListener('slotchange', slotListener);; } /** * Window resize is widely checked and may have many performance issues, debouce usage is needed to avoid calling it too much. * This function helps setting up the debounce feature and remove listener easily. * * @param resizeFunction Function to execute on resize. * @param debounceDelay Debounce time in ms. * @return Event observer to call off when finished. */ static onWindowResize(resizeFunction: (ev?: Event) => void, debounceDelay = 20): CoreEventObserver { const resizeListener = CoreUtils.debounce(async (ev?: Event) => { await CoreDomUtils.waitForResizeDone(); resizeFunction(ev); }, debounceDelay); window.addEventListener('resize', resizeListener); return { off: (): void => { window.removeEventListener('resize', resizeListener); }, }; } /** * Scroll to a certain element. * * @param element The element to scroll to. * @param selector Selector to find the element to scroll to inside the defined element. * @param scrollOptions Scroll Options. * @return Wether the scroll suceeded. */ static async scrollToElement(element: HTMLElement, selector?: string, scrollOptions: CoreScrollOptions = {}): Promise<boolean> { if (selector) { const foundElement = await CoreDom.waitToBeInsideElement(element, selector); if (!foundElement) { // Element not found. return false; } element = foundElement; } await CoreDom.waitToBeVisible(element, false); const content = element.closest<HTMLIonContentElement>('ion-content') ?? undefined; if (!content) { // Content to scroll, not found. return false; } try { const position = CoreDom.getRelativeElementPosition(element, content); const scrollElement = await content.getScrollElement(); scrollOptions.duration = scrollOptions.duration ?? 200; scrollOptions.addXAxis = scrollOptions.addXAxis ?? 0; scrollOptions.addYAxis = scrollOptions.addYAxis ?? 0; await content.scrollToPoint( position.x + scrollElement.scrollLeft + scrollOptions.addXAxis, position.y + scrollElement.scrollTop + scrollOptions.addYAxis, scrollOptions.duration, ); return true; } catch { return false; } } /** * Search for an input with error (core-input-error directive) and scrolls to it if found. * * @param container The element that contains the element that must be scrolled. * @return True if the element is found, false otherwise. */ static async scrollToInputError(container: HTMLElement): Promise<boolean> { return CoreDom.scrollToElement(container, '.core-input-error'); } /** * Has the scroll reached bottom? * * @param scrollElement Scroll Element. * @param marginError Error margin when calculating. * @return Wether the scroll reached the bottom. */ static scrollIsBottom(scrollElement?: HTMLElement, marginError = 0): boolean { if (!scrollElement) { return true; } return scrollElement.scrollTop + scrollElement.clientHeight >= scrollElement.scrollHeight - marginError; } /** * Move element to content so it can be slotted. * * @param element HTML Element. * @param slot Slot name. * @return Promise resolved when done. */ static slotOnContent(element: HTMLElement, slot = 'fixed'): CoreCancellablePromise<void> { element.setAttribute('slot', slot); if (element.parentElement?.nodeName === 'ION-CONTENT') { return CoreCancellablePromise.resolve(); } const domPromise = CoreDom.waitToBeInDOM(element); return new CoreCancellablePromise<void>( async (resolve) => { await domPromise; // Move element to the nearest ion-content if it's not the parent if (element.parentElement?.nodeName !== 'ION-CONTENT') { element.closest('ion-content')?.appendChild(element); } resolve(); }, () => { domPromise.cancel(); }, ); } /** * Wait an element to be added to the root DOM. * * @param element Element to wait. * @return Cancellable promise. */ static waitToBeInDOM(element: HTMLElement): CoreCancellablePromise<void> { const root = element.getRootNode({ composed: true }); if (root === document) { // Already in DOM. return CoreCancellablePromise.resolve(); } let observer: MutationObserver; return new CoreCancellablePromise<void>( (resolve) => { observer = new MutationObserver(() => { const root = element.getRootNode({ composed: true }); if (root !== document) { return; } observer?.disconnect(); resolve(); }); observer.observe(document.body, { subtree: true, childList: true }); }, () => { observer?.disconnect(); }, ); } /** * Wait an element to be in dom of another element using a selector * * @param container Element to wait. * @return Cancellable promise. */ static async waitToBeInsideElement(container: HTMLElement, selector: string): Promise<CoreCancellablePromise<HTMLElement>> { await CoreDom.waitToBeInDOM(container); let element = container.querySelector<HTMLElement>(selector); if (element) { // Already in DOM. return CoreCancellablePromise.resolve(element); } let observer: MutationObserver; return new CoreCancellablePromise<HTMLElement>( (resolve) => { observer = new MutationObserver(() => { element = container.querySelector<HTMLElement>(selector); if (!element) { return; } observer?.disconnect(); resolve(element); }); observer.observe(container, { subtree: true, childList: true }); }, () => { observer?.disconnect(); }, ); } /** * Watch whenever an elements visibility changes within the viewport. * * @param element Element to watch. * @param intersectionRatio Intersection ratio (From 0 to 1). * @param callback Callback when visibility changes. * @return Function to stop watching. */ static watchElementInViewport( element: HTMLElement, intersectionRatio: number, callback: (visible: boolean) => void, ): () => void; /** * Watch whenever an elements visibility changes within the viewport. * * @param element Element to watch. * @param callback Callback when visibility changes. * @return Function to stop watching. */ static watchElementInViewport(element: HTMLElement, callback: (visible: boolean) => void): () => void; static watchElementInViewport( element: HTMLElement, intersectionRatioOrCallback: number | ((visible: boolean) => void), callback?: (visible: boolean) => void, ): () => void { const visibleCallback = callback ?? intersectionRatioOrCallback as (visible: boolean) => void; const intersectionRatio = typeof intersectionRatioOrCallback === 'number' ? intersectionRatioOrCallback : 1; let visible = CoreDom.isElementInViewport(element, intersectionRatio); const setVisible = (newValue: boolean) => { if (visible === newValue) { return; } visible = newValue; visibleCallback(visible); }; if (!('IntersectionObserver' in window)) { const interval = setInterval(() => setVisible(CoreDom.isElementInViewport(element, intersectionRatio)), 50); return () => clearInterval(interval); } const observer = new IntersectionObserver(([{ isIntersecting, intersectionRatio }]) => { setVisible(isIntersecting && intersectionRatio >= intersectionRatio); }); observer.observe(element); return () => observer.disconnect(); } /** * Wait an element to be in dom and visible. * * @param element Element to wait. * @param intersectionRatio Intersection ratio (From 0 to 1). * @return Cancellable promise. */ static waitToBeInViewport(element: HTMLElement, intersectionRatio = 1): CoreCancellablePromise<void> { let unsubscribe: (() => void) | undefined; const visiblePromise = CoreDom.waitToBeVisible(element); return new CoreCancellablePromise<void>( async (resolve) => { await visiblePromise; if (CoreDom.isElementInViewport(element, intersectionRatio)) { return resolve(); } unsubscribe = this.watchElementInViewport(element, intersectionRatio, inViewport => { if (!inViewport) { return; } resolve(); unsubscribe?.(); }); }, () => { visiblePromise.cancel(); unsubscribe?.(); }, ); } /** * Wait an element to be in dom and visible. * * @param element Element to wait. * @param checkSize Wether to check size to check for visibility. * @return Cancellable promise. */ static waitToBeVisible(element: HTMLElement, checkSize = true): CoreCancellablePromise<void> { const domPromise = CoreDom.waitToBeInDOM(element); let interval: number | undefined; // Mutations did not observe for visibility properties. return new CoreCancellablePromise<void>( async (resolve) => { await domPromise; if (CoreDom.isElementVisible(element, checkSize)) { return resolve(); } interval = window.setInterval(() => { if (!CoreDom.isElementVisible(element, checkSize)) { return; } resolve(); window.clearInterval(interval); }, 50); }, () => { domPromise.cancel(); window.clearInterval(interval); }, ); } /** * Listen to click and Enter/Space keys in an element. * * @param element Element to listen to events. * @param callback Callback to call when clicked or the key is pressed. */ static onActivate(element: HTMLElement, callback: (event: MouseEvent | KeyboardEvent) => void): void { element.addEventListener('click', (event) => callback(event)); element.addEventListener('keydown', (event) => { if ((event.key == ' ' || event.key == 'Enter')) { event.preventDefault(); event.stopPropagation(); } }); element.addEventListener('keyup', (event) => { if ((event.key == ' ' || event.key == 'Enter')) { callback(event); } }); } } /** * Coordinates of an element. */ export type CoreCoordinates = { x: number; // X axis coordinates. y: number; // Y axis coordinates. }; /** * Scroll options. */ export type CoreScrollOptions = { duration?: number; addYAxis?: number; addXAxis?: number; };
the_stack
import { CollectionService } from './collection.service'; import { createServiceFactory, SpectatorService, SpyObject } from '@ngneat/spectator'; import { AngularFirestore, SETTINGS } from '@angular/fire/firestore'; import { EntityStore, QueryEntity, StoreConfig, EntityState, ActiveState } from '@datorama/akita'; import { Injectable } from '@angular/core'; import firebase from 'firebase/app'; import 'firebase/firestore'; import { interval } from 'rxjs'; import { switchMap, map, finalize, takeWhile } from 'rxjs/operators'; import { AngularFireModule } from '@angular/fire'; interface Movie { title: string; id?: string; } interface MovieState extends EntityState<Movie, string>, ActiveState<string> { } @Injectable() @StoreConfig({ name: 'movies' }) class MovieStore extends EntityStore<MovieState> { constructor() { super(); } } @Injectable() class MovieQuery extends QueryEntity<MovieState> { constructor(store: MovieStore) { super(store); } } @Injectable() class MovieService extends CollectionService<MovieState> { constructor(store: MovieStore, db: AngularFirestore) { super(store, 'movies', db); } } describe('CollectionService', () => { let spectator: SpectatorService<MovieService>; let service: MovieService; let store: SpyObject<MovieStore>; let query: SpyObject<MovieQuery>; let db: AngularFirestore; const createService = createServiceFactory({ service: MovieService, imports: [AngularFireModule.initializeApp({ apiKey: "AIzaSyD8fRfGLDsh8u8pXoKwzxiDHMqg-b1IpN0", authDomain: "akita-ng-fire-f93f0.firebaseapp.com", databaseURL: "https://akita-ng-fire-f93f0.firebaseio.com", projectId: "akita-ng-fire-f93f0", storageBucket: "akita-ng-fire-f93f0.appspot.com", messagingSenderId: "561612331472", appId: "1:561612331472:web:307acb3b5d26ec0cb8c1d5" })], providers: [ MovieStore, MovieQuery, AngularFirestore, { provide: SETTINGS, useValue: { host: 'localhost:8080', ssl: false } }, ] }); const collections = ['movies', 'col/doc/movies', 'movies/1/stakeholders', 'movies/2/stakeholders']; beforeEach(async () => { spectator = createService(); service = spectator.service; store = spectator.get(MovieStore); query = spectator.get(MovieQuery); db = spectator.get(AngularFirestore); // Clear Database & store const snaps = await Promise.all(collections.map(col => db.collection(col).ref.get())); const docs = snaps.reduce((acc, snap) => acc.concat(snap.docs), [] as firebase.firestore.QueryDocumentSnapshot[]); await Promise.all(docs.filter(doc => doc.exists).map(({ ref }) => ref.delete())); store.set({ entities: {}, ids: [] }); }); it('should exist', () => { expect(spectator.service).toBeTruthy(); }); it('getValue return null when does not exist', async () => { const movie = await service.getValue('1'); expect(movie).toBeNull(); }); it('getValue return value when exists', async () => { await db.doc('movies/1').set({ id: '1', title: 'Star Wars' }); const movie = await service.getValue('1'); expect(movie).toEqual({ id: '1', title: 'Star Wars' }); }); it('getValue with Query', async () => { await db.doc('movies/1').set({ title: 'Star Wars' }); await db.doc('movies/2').set({ title: 'Lord of the ring' }); await db.doc('movies/3').set({ title: 'Lord of the ring' }); const movies = await service.getValue(ref => ref.where('title', '==', 'Star Wars')); expect(movies.length).toEqual(1); }); it('getValue return an array', async () => { await db.doc('movies/1').set({ title: 'Star Wars' }); await db.doc('movies/2').set({ title: 'Lord of the ring' }); const movies = await service.getValue(); expect(movies.length).toEqual(2); }); it('Firestore should be empty', async () => { const snap = await db.doc('movies/1').ref.get(); expect(snap.exists).toBeFalsy(); }); it('Add', async () => { await service.add({ id: '1', title: 'Star Wars' }); const movie = await service.getValue('1'); expect(movie).toEqual({ id: '1', title: 'Star Wars' }); }); it('Add movies and verify that ids are set correctly', async () => { const ids = await service.add([{ id: '1', title: 'Star Wars' }, { id: '2', title: 'Lord of the ring' }]); expect(ids).toEqual(['1', '2']); }); it('Add movies and should not alter the ids when there is no id key in state', async () => { const ids = await service.add([{ uid: '1', title: 'Star Wars' }, { uid: '2', title: 'Lord of the ring' }]); expect(ids).not.toEqual(['1', '2']); }); it('Add many', async () => { await service.add([{ title: 'Star Wars' }, { title: 'Lord of the ring' }]); const movies = await service.getValue() as any[]; expect(movies.length).toEqual(2); }); it('Remove One', async () => { await service.add({ id: '1', title: 'Star Wars ' }); await service.remove('1'); const movie = await service.getValue('1'); expect(movie).toBeNull(); }); it('Remove many', async () => { await service.add([{ id: '1', title: 'Star Wars' }, { id: '2', title: 'Lord of the ring' }]); await service.remove(['1', '2']); const movies = await service.getValue(); expect(movies.length).toEqual(0); }); it('Remove all', async () => { await service.add([{ id: '1', title: 'Star Wars' }, { id: '2', title: 'Lord of the ring' }]); await service.removeAll(); const movies = await service.getValue(); expect(movies.length).toEqual(0); }); it('Update one', async () => { await service.add([{ id: '1', title: 'Star Wars' }, { id: '2', title: 'Lord of the ring' }]); await service.update('1', { title: 'Star Wars 2' }); const movie = await service.getValue('1'); expect(movie.title).toEqual('Star Wars 2'); }); it('Update with callback', async () => { await service.add({ id: '1', title: 'Star Wars' }); await service.update('1', (m) => ({ title: m.title + ' 2' })); const movie = await service.getValue('1'); expect(movie.title).toEqual('Star Wars 2'); }); it('Update many with ids', async () => { await service.add([{ id: '1', title: 'Star Wars' }, { id: '2', title: 'Lord of the ring' }]); await service.update(['1', '2'], { title: 'Star Wars 2' }); const movies = await service.getValue(['1', '2']); const changes = movies.filter(movie => movie.title === 'Star Wars 2'); expect(changes.length).toEqual(2); }); it('Update many with object array', async () => { await service.add([ { id: '1', title: 'Star Wars' }, { id: '2', title: 'Lord of the ring' } ]); await service.update([ { id: '1', title: 'Star Wars 2' }, { id: '2', title: 'Lord of the ring 2' } ]); const movies = await service.getValue(['1', '2']); expect(movies[0].title).toEqual('Star Wars 2'); expect(movies[1].title).toEqual('Lord of the ring 2'); }); // service.syncCollection().subscribe() it('SyncCollection', async () => { const sub = service.syncCollection().subscribe(); await service.add({ id: '1', title: 'Star Wars' }); const hasId = store['_value']().ids.includes('1'); sub.unsubscribe(); expect(hasId).toBeTruthy(); }); it('SyncCollection with queryFn', async () => { const sub = service.syncCollection(ref => ref.where('title', '==', 'Star Wars')).subscribe(); await service.add([ { title: 'Star Wars' }, { title: 'Lord of the Rings' }, ]); sub.unsubscribe(); expect(query.getCount()).toEqual(1); }); it('SyncCollection with path', async () => { const sub = service.syncCollection('col/doc/movies').subscribe(); await db.collection('col/doc/movies').add({ title: 'Star Wars' }); sub.unsubscribe(); expect(query.getCount()).toEqual(1); }); it('SyncCollection with path AND query', async () => { const sub = service.syncCollection('col/doc/movies', ref => ref.limit(1)).subscribe(); await db.collection('col/doc/movies').add({ title: 'Star Wars' }); await db.collection('col/doc/movies').add({ title: 'Lord of the Rings' }); sub.unsubscribe(); expect(query.getCount()).toEqual(1); }); it('SyncCollection with queryFn AND params', async () => { Object.defineProperty(service, 'path', { get: () => 'movies/:movieId/stakeholders' }); const sub = service.syncCollection(ref => ref.where('status', '==', 'pending'), { params: { movieId: '1' } }).subscribe(); await db.collection('movies/1/stakeholders').add({ status: 'pending' }); await db.collection('movies/1/stakeholders').add({ status: 'accepted' }); await db.collection('movies/2/stakeholders').add({ status: 'pending' }); sub.unsubscribe(); expect(query.getCount()).toEqual(1); }); // service.syncCollectionGroup().subscribe() it('SyncCollectionGroup', async () => { const sub = service.syncCollectionGroup('stakeholders').subscribe(); await db.collection('movies/1/stakeholders').add({ name: 'Uri' }); await db.collection('movies/2/stakeholders').add({ name: 'Yann' }); sub.unsubscribe(); expect(query.getCount()).toEqual(2); }); it('SyncCollectionGroup with Query', async () => { const sub = service.syncCollectionGroup('stakeholders', ref => ref.limit(1)).subscribe(); await db.collection('movies/1/stakeholders').add({ name: 'Uri' }); await db.collection('movies/2/stakeholders').add({ name: 'Yann' }); sub.unsubscribe(); expect(query.getCount()).toEqual(1); }); // service.syncDoc({ id: '' }).subscribe() it('SyncDoc with id', async () => { const sub = service.syncDoc({ id: '2' }).subscribe(); await service.add([ { id: '1', title: 'Star Wars' }, { id: '2', title: 'Lord of the Ring' } ]); sub.unsubscribe(); expect(query.getCount()).toEqual(1); }); it('SyncDoc with path', async () => { const sub = service.syncDoc({ path: 'col/doc/movies/1' }).subscribe(); await db.doc('col/doc/movies/1').set({ title: 'Star Wars' }); sub.unsubscribe(); expect(query.getCount()).toEqual(1); }); // service.syncActive().subscribe() it('SyncActive', async () => { const sub = service.syncActive({ id: '1' }).subscribe(); await service.add([ { id: '1', title: 'Star Wars' }, { id: '2', title: 'Lord of the Ring' } ]); const { active, ids } = query.getValue(); sub.unsubscribe(); expect(ids.length).toEqual(1); expect(active).toEqual('1'); }); it('SyncActive many', async () => { const sub = service.syncActive(['1', '2'] as any).subscribe(); await service.add([ { id: '1', title: 'Star Wars' }, { id: '2', title: 'Lord of the Ring' } ]); const { active, ids } = query.getValue(); sub.unsubscribe(); expect(ids.length).toEqual(2); expect(active).toEqual(['1', '2']); }); // service.syncManyDocs().subscribe() it('SyncManyDocs', async () => { const sub = service.syncManyDocs(['1', '2']).subscribe(); await service.add([ { id: '1', title: 'Star Wars' }, { id: '2', title: 'Lord of the Ring' }, { id: '3', title: 'Harry Potter' }, ]); sub.unsubscribe(); expect(query.getCount()).toEqual(2); }); it('SyncManyDocs with ids updated', async (done) => { await service.add([ { id: '1', title: 'Star Wars' }, { id: '2', title: 'Lord of the Ring' }, { id: '3', title: 'Harry Potter' }, ]); const array = [['2'], ['2', '3'], ['1']]; let i = 0; interval(100).pipe( finalize(() => done()), takeWhile(index => index !== array.length), map((index) => array[index]), switchMap(ids => service.syncManyDocs(ids)), map(() => query.getCount()), ).subscribe(size => { expect(size).toEqual(array[i].length); i++; }); }); it('SyncManyDocs with firestore updates', async (done) => { await service.add([ { id: '1', title: 'Star Wars' }, { id: '2', title: 'Lord of the Ring' }, { id: '3', title: 'Harry Potter' }, ]); let i = 0; const expected = [3, 2, 3, 3, 2, 1]; service.syncManyDocs(['1', '2', '3']).pipe( finalize(() => done()), takeWhile(() => i !== expected.length - 1), map(() => query.getCount()), ).subscribe(size => { expect(size).toEqual(expected[i]); i++; }); setTimeout(() => service.remove('1'), 500); setTimeout(() => service.add({ id: '1', title: 'Star Wars 2' }), 1000); setTimeout(() => service.update('1', { title: 'Star Wars' }), 1500); // This creates 2 events from firestore (remove '1' and remove '2') setTimeout(() => service.remove(['1', '2']), 2000); }); });
the_stack
import React from "react"; import { SelectedNodeActions } from "./SelectedNodeActions"; import { assignIds } from "../Helpers"; import ComponentTypes, { NodeInformation } from "../schema/ComponentTypes"; import Grid from "../Grid"; import Row from "../Row"; import Section from "../Section"; import { Action, IdType, NodeProperty, ResumeNode, AddChild } from "../utility/Types"; import Toolbar, { ToolbarSection } from "./toolbar/ToolbarMaker"; import Column from "../Column"; import toolbarOptions from "../schema/ToolbarOptions"; import HtmlIdAdder from "./HtmlIdAdder"; import ResumeHotKeys from "./ResumeHotkeys"; import { ToolbarItemData } from "./toolbar/ToolbarButton"; interface AddOptionProps { options: string | Array<string>; addChild: AddChild; id: IdType; } /** * Return the button or menu for adding children to a node * @param options */ function addOptions(data: AddOptionProps): ToolbarItemData { const options = data.options; const nodeInfo = (type: string) => ComponentTypes.defaultValue(type); if (Array.isArray(options)) { if (options.length === 0) { return {}; } return { text: "Insert", icon: "ui-add", items: options.map((nodeType: string) => { const info = nodeInfo(nodeType); const node: NodeInformation = nodeInfo(nodeType); return { icon: info.icon, text: info.text, action: () => data.addChild(data.id, assignIds(node.node)) } as ToolbarItemData }) } } const node: NodeInformation = nodeInfo(data.options as string); return { action: () => data.addChild(data.id, assignIds(node.node)), text: `Add ${node.text}` } } function ClipboardMenu(data: EditingBarProps): ToolbarItemData[] { /** * Get the keyboard shortcut associated with key * @param key Resume hotkey key */ const getShortcut = (key: string): string => { return ResumeHotKeys.keyMap[key]['sequence']; } return [ { text: 'Cut', icon: "ui-cut", action: data.cutClipboard, shortcut: getShortcut('CUT_SELECTED') }, { text: 'Copy', icon: "ui-copy", action: data.copyClipboard, shortcut: getShortcut('COPY_SELECTED') }, { text: 'Paste', icon: "ui-clip-board", action: data.pasteClipboard, shortcut: getShortcut('PASTE_SELECTED') } ]; } interface EditingBarSubProps extends EditingBarProps { isOverflowing: boolean; } function SelectedNodeToolbar(props: EditingBarSubProps) { const id = props.selectedNodeId; if (id && props.selectedNode) { const type = props.selectedNode.type; let moveUpText = "rounded-up"; let moveDownText = "rounded-down"; const childTypes = ComponentTypes.childTypes(type); const htmlId = props.selectedNode.htmlId ? `#${props.selectedNode.htmlId}` : 'CSS'; if (type === Column.type) { moveUpText = "rounded-left"; moveDownText = "rounded-right"; } return new Map<string, ToolbarSection>([ [`Current Node (${props.selectedNode.type})`, { icon: "gear", items: [ addOptions({ id: id, addChild: props.addChild, options: childTypes }), { action: props.delete, icon: 'ui-delete', text: 'Delete', condensedButton: true }, { icon: 'clip-board', text: 'Clipboard', condensedButton: true, items: ClipboardMenu(props), }, ...toolbarOptions(props.selectedNode, props.updateSelected), { action: props.unselect, text: 'Unselect' } ] }], ["Move", { icon: "drag2", items: [ { action: props.moveUp, icon: moveUpText, text: 'Move Up', condensedButton: true }, { action: props.moveDown, icon: moveDownText, text: 'Move Down', condensedButton: true } ] }], [htmlId, { icon: "ui-tag", items: [ { content: <HtmlIdAdder key={props.selectedNode.uuid} htmlId={props.selectedNode.htmlId} cssClasses={props.selectedNode.classNames} addHtmlId={props.addHtmlId} addCssClasses={props.addCssClasses} /> } ] }] ]); } return new Map<string, ToolbarSection>(); } interface EditingSectionProps { saveLocal?: Action; undo?: Action; redo?: Action; } export interface EditingBarProps extends SelectedNodeActions, EditingSectionProps { selectedNodeId?: IdType; selectedNode?: ResumeNode, addHtmlId: (htmlId: string) => void; addCssClasses: (classes: string) => void; addChild: AddChild; updateSelected: (key: string, data: NodeProperty) => void; unselect: Action; } interface EditingBarState { isOverflowing: boolean; overflowWidth: number; } /** A responsive top editing bar */ export default class TopEditingBar extends React.Component<EditingBarProps, EditingBarState> { toolbarRef = React.createRef<HTMLDivElement>(); constructor(props) { super(props); this.state = { isOverflowing: false, // The breakpoint at which toolbar begins to overflow overflowWidth: -1 }; this.updateResizer = this.updateResizer.bind(this); } /** Screen width at which toolbar should shrink regardless of anything */ get clipWidth() { return 800; } get editingSection(): ToolbarItemData[] { return [ { action: this.props.saveLocal, icon: "save", text: "Save", condensedButton: true }, { action: this.props.undo, icon: "undo", text: "Undo", condensedButton: true }, { action: this.props.redo, icon: "redo", text: "Redo", condensedButton: true } ]; } componentDidMount() { window.addEventListener("resize", this.updateResizer); // Perform initial resize this.updateResizer(); } componentDidUpdate(prevProps: EditingBarProps) { // When the selected node changes, so does the toolbar // which means we need to update the overflow widths if (prevProps.selectedNodeId !== this.props.selectedNodeId) { this.setState({ overflowWidth: -1 }); this.updateResizer(); } } /** * Resize the toolbar on resize * @param event */ updateResizer() { const container = this.toolbarRef.current; if (container) { // Get width of parent container // Note: Since container.parentElement is almost always defined // the fallback only exists so TypeScript doesn't yell at us const parentWidth = container.parentElement ? container.parentElement.clientWidth : window.innerWidth; // Case 1: Editing bar is overflowing // Case 2: Editing bar has been shrunk, but parent container // isn't large enough for editing bar to fully expand // Case 3: Screen width is smaller than a certain breakpoint const isOverflowing = (container.scrollWidth > container.clientWidth) || (parentWidth < this.state.overflowWidth) || (window.innerWidth < this.clipWidth); // This sets the breakpoint at which the editing bar should // collapse if (this.state.overflowWidth < 0 && isOverflowing) { this.setState({ overflowWidth: container.scrollWidth }); } this.setState({ isOverflowing: isOverflowing }); } }; render() { const props = this.props; const id = props.selectedNodeId; let data = new Map<string, ToolbarSection>([ ["Editing", { icon: 'ui-edit', items: this.editingSection }], ]); if (id && props.selectedNode) { let selectedNodeOptions = SelectedNodeToolbar({ ...props, isOverflowing: this.state.isOverflowing }); selectedNodeOptions.forEach((value, key) => { data.set(key, value); }); } else { data.set("Resume Components", { items: [ { action: () => props.addChild([], assignIds({ type: Section.type })), icon: "book-mark", text: "Add Section" }, { action: () => props.addChild([], assignIds(ComponentTypes.defaultValue(Row.type).node)), icon: "swoosh-right", text: "Add Rows & Columns" }, { action: () => props.addChild([], assignIds(ComponentTypes.defaultValue(Grid.type).node)), icon: "table", text: "Add Grid" } ] }); } let children = <Toolbar data={data} collapse={this.state.isOverflowing} />; const className = this.state.isOverflowing ? "toolbar-collapsed" : ""; return <div ref={this.toolbarRef} id="toolbar" className={className}>{children}</div> } }
the_stack
import "./frida" import { usercall, userpurge } from "./usercall" export class Symbols { static map = { "CharacterManager::GetInstance": { address: ptr(0x4fa5a0), returnType: 'pointer', argTypes: [], abi: 'mscdecl', }, "Vehicle::SetPosition": { address: ptr(0x4E9C30), returnType: 'void', argTypes: [ 'pointer', 'pointer' ], }, "CoinManager::AdjustBankValue": { address: ptr(0x505C80), returnType: 'void', argTypes: [ 'int' ], abi: 'fastcall', }, "CoinManager::GetInstance": { address: ptr(0x505300), returnType: 'pointer', argTypes: [], abi: 'mscdecl', }, "CoinManager::SpawnInstantCoins": { address: userpurge(["eax"], 3, 0x505690), returnType: 'void', argTypes: ['pointer', 'int', 'pointer'], }, "CoinManager::SpawnCoins": { address: userpurge(["edx", "ecx", "eax"], 5, 0x5055D0), returnType: 'void', argTypes: ['pointer', 'pointer', 'int', 'int', 'pointer'], }, "CoinManager::LoseCoins": { address: userpurge(["ebx", "eax", "esi"], 3, 0x505BC0), returnType: 'void', argTypes: [ 'pointer', 'int', 'pointer' ], }, "CoinManager::OnVehicleDestroyed": { address: userpurge(["eax", "ecx"], 2, 0x505A50), returnType: 'void', argTypes: [ 'pointer', 'pointer' ], }, "CharacterSheetManager::GetNumberOfTokens": { address: ptr(0x462F10), returnType: 'int', argTypes: [], abi: 'mscdecl', }, "CommandLineOptions::sOptions": { address: ptr(0x6C8FD0), }, "InputManager::GetInstance": { address: ptr(0x435210), returnType: 'pointer', argTypes: [], abi: 'mscdecl' }, "InputManager::GetController": { address: userpurge(["ecx", "eax"], 2, 0x435450), returnType: 'pointer', argTypes: ['pointer','int'], }, "Mappable::DispatchOnButton": { address: userpurge(["eax", "ebx"], 4, 0x435C30), returnType: 'void', argTypes: ['pointer','int','int','pointer'], }, "Mappable::IsActive": { address: userpurge(["eax"], 1, 0x435E40), returnType: 'char', argTypes: ['pointer'], }, "Mappable::IsButtonDown": { address: userpurge(["ecx"], 2, 0x435E50), returnType: 'bool', argTypes: ['int', 'pointer'], }, "Mappable::UpdateButtonState": { address: userpurge(["esi", "eax", "ecx"], 4, 0x435D40), returnType: 'void', argTypes: ['pointer','pointer','int','int'], }, "Button::mTickCount": { address: ptr(0x6C900C), }, "Mapper::GetLogicalIndex": { address: userpurge(["eax", "ecx"], 2, 0x435F20), returnType: 'int', argTypes: ['pointer','int'], }, "Mappable::GetActiveMapper": { address: userpurge(["eax"], 1, 0x435DE0), returnType: 'pointer', argTypes: ['pointer'], }, "RenderManager::GetInstance": { address: ptr(0x4A8E60), returnType: 'pointer', argTypes: [], }, "RenderManager::pWorldScene": { address: userpurge(["eax"], 1, 0x4A8E90), returnType: 'pointer', argTypes: ['pointer'], }, "IntersectManager::GetInstance": { address: ptr(0x4B42A0), returnType: 'pointer', argTypes: [], }, "IntersectManager::FindClosestRoad": { address: ptr(0x4B43A0), returnType: 'pointer', argTypes: ['pointer', 'pointer', 'float', 'pointer', 'pointer'], abi: 'thiscall', }, "RoadSegment::GetCorner": { address: userpurge(["edx", "eax", "ecx"], 3, 0x4C01E0), returnType: 'pointer', argTypes: ['pointer', 'pointer', 'int'], }, "IntersectManager::FindStaticPhysElems": { address: userpurge(["ecx", "edi"], 4, 0x4B4C00), returnType: 'void', argTypes: ['pointer', 'pointer', 'pointer', 'float'], }, "StaticPhysDSG::GetPosition": { address: ptr(0x4A5880), returnType: 'void', argTypes: ['pointer', 'pointer'], abi: 'thiscall', }, "DynaPhysDSG::ApplyForce": { address: ptr(0x49FBA0), returnType: 'void', argTypes: ['pointer', 'pointer', 'float'], abi: 'thiscall', }, "DynaPhysDSG::RestTest": { address: ptr(0x49F800), returnType: 'bool', argTypes: ['pointer'], abi: 'thiscall', }, "DynaPhysDSG::IsAtRest": { address: ptr(0x49F7D0), returnType: 'bool', argTypes: ['pointer'], abi: 'thiscall', }, "IntersectManager::FindDynaPhysElems": { address: userpurge(["ecx", "ebx"], 4, 0x4B4DF0), returnType: 'void', argTypes: ['pointer', 'pointer', 'float', 'pointer'], }, "Vehicle::GetPosition": { address: userpurge(["ecx"], 2, 0x4EC670), returnType: 'void', argTypes: ['pointer', 'pointer'], }, "AnimCollisionEntityDSG::GetPosition": { address: ptr(0x4A6680), returnType: 'void', argTypes: ['pointer', 'pointer'], abi: 'thiscall', }, "IntersectManager::FindAnimPhysElems": { address: userpurge(["ecx", "ebx"], 4, 0x4B4FF0), returnType: 'int', argTypes: ['pointer', 'pointer', 'float', 'pointer'], }, "tName::Init": { address: ptr(0x56F520), returnType: 'pointer', argTypes: ['pointer', 'pointer'], abi: 'thiscall', }, "FeText::Init": { address: ptr(0x53F8B0), returnType: 'pointer', argTypes: ['pointer', 'pointer', 'int', 'int', 'bool'], abi: 'thiscall', }, "FeText::AddHardCodedString": { address: ptr(0x540160), returnType: 'void', argTypes: ['pointer', 'pointer'], abi: 'thiscall', }, "FeText::Display": { address: ptr(0x53FC00), returnType: 'void', argTypes: ['pointer'], abi: 'thiscall' }, "FeParent::Resize": { address: ptr(0x544BA0), returnType: 'void', argTypes: ['pointer', 'int'], abi: 'thiscall', }, "FeText::SetTextStyle": { address: ptr(0x540020), returnType: 'void', argTypes: ['pointer', 'pointer'], abi: 'thiscall', }, "FeApp::GetInstance": { address: ptr(0x5369F0), returnType: 'pointer', argTypes: [], }, "tName::MakeUID": { address: ptr(0x56f3D0), returnType: 'void', argTypes: ['pointer', 'pointer'], abi: 'cdecl', }, "AvatarManager::GetInstance": { address: ptr(0x4D7A30), returnType: 'pointer', argTypes: [], }, "AvatarManager::GetAvatarForPlayer": { address: userpurge(["ecx", "eax"], 2, 0x4d7f40), returnType: 'pointer', argTypes: ['pointer', 'int'], }, "Avatar::GetCharacter": { address: userpurge(["eax"], 1, 0x4a7900), returnType: 'pointer', argTypes: ['pointer'], }, "Avatar::GetVehicle": { address: userpurge(["eax"], 1, 0x4C7800), returnType: 'pointer', argTypes: ['pointer'], }, "Avatar::SetCharacter": { address: userpurge(["ecx", "edx"], 2, 0x4d70c0), returnType: 'void', argTypes: ['pointer', 'pointer'], }, "Avatar::SetVehicle": { address: userpurge(["edi", "esi"], 2, 0x4d7100), returnType: 'void', argTypes: ['pointer', 'pointer'], }, "Avatar::SetInCarController": { address: ptr(0x4D7180), returnType: 'void', argTypes: ['pointer'], }, "Avatar::SetCameraTargetToVehicle": { address: userpurge(["esi"], 2, 0x4d72f0), returnType: 'void', argTypes: ['pointer', 'bool'], }, "Avatar::GetIntoVehicleStart": { address: userpurge(["eax"], 2, 0x4D7360), returnType: 'void', argTypes: ['pointer', 'pointer'], }, "Avatar::GetIntoVehicleEnd": { address: userpurge(["eax"], 2, 0x4d7440), returnType: 'void', argTypes: ['pointer', 'pointer'], }, "Avatar::GetOutOfVehicleStart": { address: userpurge(["edi"], 2, 0x4d7460), returnType: 'void', argTypes: ['pointer', 'pointer'], }, "Avatar::SetOutOfCarController": { address: ptr(0x4d74f0), returnType: 'void', argTypes: ['pointer'], }, "Avatar::SetCameraTargetToCharacter": { address: userpurge(["esi"], 2, 0x4d75e0), returnType: 'void', argTypes: ['pointer', 'bool'], }, "Avatar::GetOutOfVehicleEnd": { address: userpurge(["ebx", "eax"], 2, 0x4D7630), returnType: 'void', argTypes: ['pointer', 'pointer'], }, "Avatar::IsInCar": { address: userpurge(["eax"], 1, 0x4d76d0), returnType: 'bool', argTypes: ['pointer'], }, "Avatar::GetPosition": { address: userpurge(["eax", "esi"], 2, 0x4d76f0), returnType: 'void', argTypes: ['pointer', 'pointer'], }, "Avatar::GetVelocity": { address: userpurge(["eax", "esi"], 2, 0x4D7780), returnType: 'void', argTypes: ['pointer', 'pointer'], }, "Avatar::OnCheatEntered": { address: ptr(0x4D77F0), returnType: 'void', argTypes: ['int', 'bool'], }, "Avatar::GetLastPathInfo": { address: ptr(0x4d7820), returnType: 'void', argTypes: ['pointer', 'pointer', 'pointer', 'pointer', 'pointer'], }, "Avatar::GetSpeedMps": { address: userpurge(["esi"], 1, 0x4d77c0), returnType: 'float', argTypes: ['pointer'], }, "Avatar::GetRaceInfo": { address: userpurge(["eax", "edx"], 4, 0x4D79B0), returnType: 'void', argTypes: ['pointer', 'pointer', 'pointer', 'pointer'], }, "Avatar::SetRaceInfo": { address: userpurge(["eax", "edx"], 4, 0x4d79d4), returnType: 'void', argTypes: ['pointer', 'int', 'float', 'int'], }, "Avatar::Update": { address: userpurge(["eax"], 2, 0x4d7810), returnType: 'void', argTypes: ['pointer', 'float'], }, "Avatar::SetControllerId": { address: userpurge(["eax", "ecx"], 2, 0x4d70b0), returnType: 'void', argTypes: ['pointer', 'int'], }, "Avatar::GetHeading": { address: userpurge(["edi", "eax"], 2, 0x4d7750), returnType: 'void', argTypes: ['pointer', 'pointer'], }, "Character::RelocateAndReset": { address: ptr(0x4f38d0), returnType: 'void', argTypes: ['pointer', 'pointer', 'float', 'bool', 'bool'], }, "AvatarManager::PutCharacterOnGround": { address: userpurge(["eax"], 3, 0x4d80e0), returnType: 'void', argTypes: ['pointer', 'pointer', 'pointer'], }, "FeParent::RemoveChild": { address: ptr(0x544B60), returnType: 'void', argTypes: ['pointer', 'pointer'], abi: 'thiscall', }, "FeParent::ReplaceChild": { address: ptr(0x544B80), returnType: 'void', argTypes: ['pointer', 'pointer', 'pointer'], abi: 'thiscall', }, "WorldScene::Render": { address: userpurge(["ebx"], 2, 0x49cc40), returnType: 'void', argTypes: ['pointer', 'int'], }, "WorldScene::RenderScene": { address: ptr(0x49C0F0), returnType: 'void', argTypes: ['pointer', 'int', 'pointer'], }, "KERNEL32!EnterCriticalSection": { address: Module.getExportByName("KERNEL32", "EnterCriticalSection"), returnType: 'void', argTypes: ['pointer'], }, "KERNEL32!LeaveCriticalSection": { address: Module.getExportByName("KERNEL32", "LeaveCriticalSection"), returnType: 'void', argTypes: ['pointer'], }, "KERNEL32!DeleteCriticalSection": { address: Module.getExportByName("KERNEL32", "LeaveCriticalSection"), returnType: 'void', argTypes: ['pointer'], }, "KERNEL32!InitializeCriticalSection": { address: Module.getExportByName("KERNEL32", "InitializeCriticalSection"), returnType: 'void', argTypes: ['pointer'], }, "IntersectManager::FindFenceElems": { address: userpurge(["ecx", "edi"], 4, 0x4B49C0), returnType: 'void', argTypes: ['pointer', 'pointer', 'int', 'pointer'], }, "WorldRenderLayer::Render": { address: userpurge(["ecx", "ebx", "edi", "esi"], 4, 0x4AAC00), returnType: 'void', argTypes: ['int', 'int', 'int', 'int'], }, "WorldPhysicsManager::Update": { address: userpurge(["eax"], 2, 0x004DD410), returnType: 'void', argTypes: ['pointer', 'int'], }, "Context::Update": { address: userpurge(["edi", "esi"], 2, 0x42FB20), returnType: 'void', argTypes: ["pointer", "pointer"], }, "GameplayManager::GetInstance": { address: ptr(0x448080), returnType: 'pointer', argTypes: [], }, "ActionButtonManager::GetInstance": { address: ptr(0x406140), returnType: 'pointer', argTypes: [], }, "ActorManager::GetInstance": { address: ptr(0x416170), returnType: 'pointer', argTypes: [], }, "Sparkle::GetInstance": { address: ptr(0x506A60), returnType: 'pointer', argTypes: [], }, "Sparkle::AddSparks": { address: userpurge(["eax"], 4, 0x506fd0), returnType: 'void', argTypes: ['pointer', 'pointer', 'pointer', 'float'], }, "Mission::GetCurrentStage": { address: ptr(0x44d3f0), returnType: 'pointer', argTypes: ['pointer'], abi: 'thiscall', }, "MissionScriptLoader::GetInstance": { address: ptr(0x44eda0), returnType: 'pointer', argTypes: [], }, "MissionObjective::GetObjectiveType": { address: userpurge(["eax"], 1, 0x40e8e0), returnType: 'int', argTypes: ['pointer'], }, "SuperCamManager::GetInstance": { address: ptr(0x42A270), returnType: 'pointer', argTypes: [], }, "SuperCamCentral::GetSuperCam": { address: userpurge(["ebx"], 2, 0x429400), returnType: 'pointer', argTypes: ['pointer', 'int'], }, "SuperCamManager::GetSCC": { address: userpurge(["ecx", "eax"], 2, 0x42a2d0), returnType: 'pointer', argTypes: ['pointer', 'int'], }, "SuperCam::SetCameraValues": { address: ptr(0x427410), returnType: 'void', argTypes: ['pointer', 'int', 'float', 'float', 'float', 'float', 'float', 'float', 'pointer'], }, "SuperCam::GetPosition": { address: userpurge(["ecx", "eax"], 2, 0x4271A0), returnType: 'void', argTypes: ['pointer', 'pointer'], }, "SuperCam::GetTarget": { address: userpurge(["ecx", "eax"], 2, 0x427200), returnType: 'void', argTypes: ['pointer', 'pointer'], }, "IntersectionList": { address: ptr(0x41AF80), returnType: 'pointer', argTypes: ['pointer'], }, "IntersectionList::FillIntersectionListDynamics": { address: ptr(0x41BF60), returnType: 'int', argTypes: ['pointer', 'pointer', 'float', 'bool', 'pointer'], }, "~IntersectionList": { address: ptr(0x41B050), returnType: 'void', argTypes: ['pointer'], abi: 'thiscall', }, "DynaPhysDSG::IsCollisionEnabled": { address: ptr(0x49FC60), returnType: 'bool', argTypes: ['pointer'], abi: 'thiscall', }, "IntersectionList::TestIntersectionDynamics": { address: userpurge(["eax", "edi"], 5, 0x41B490), returnType: 'bool', argTypes: ['pointer', 'pointer', 'pointer', 'pointer', 'pointer'], }, "__builtin_vec_new": { address: ptr(0x445600), returnType: 'pointer', argTypes: ['int'], abi: 'cdecl', }, "EventManager::AddListener": { address: userpurge(["ebx", "edi"], 3, 0x4329E0), returnType: 'void', argTypes: ['pointer', 'int', 'pointer'], }, "EventManager::GetInstance": { address: ptr(0x4329A0), returnType: 'pointer', argTypes: [], }, "EventManager::TriggerEvent": { address: userpurge(["edx"], 3, 0x432ad0), returnType: 'void', argTypes: ['pointer', 'int', 'pointer'], }, }; static find(name: string): NativeFunction { if (!Symbols.map[name]) throw "Unknown Symbol " + name; if (Symbols.map[name].cached) return Symbols.map[name].cached; return Symbols.map[name].cached = new NativeFunction( Symbols.map[name].address, Symbols.map[name].returnType, Symbols.map[name].argTypes, Symbols.map[name].abi ? Symbols.map[name].abi : 'stdcall' ); } static addr(name: string): NativePointer { // This check handles the case of the entry being a usercall/userpurge // wrapper. return "origAddress" in Symbols.map[name].address ? Symbols.map[name].address.origAddress : Symbols.map[name].address; } /** * Convenient wrapper to lookup and call a symbol in one call. * @param name Symbol to call. * @param args Parameters to subroutine. */ static call<T>(name: string, ...args: Array<NativePointer | number | boolean>): T { let func = Symbols.find(name); return <T>func.apply(func, args); } }
the_stack
import { Vector3 } from './Vector3' import { Sphere } from './Sphere' import { Plane } from './Plane' import { Box3 } from './Box3' import { Matrix4 } from './Matrix4' const _vector = new Vector3() const _segCenter = new Vector3() const _segDir = new Vector3() const _diff = new Vector3() const _edge1 = new Vector3() const _edge2 = new Vector3() const _normal = new Vector3() /** * @author bhouston / http://clara.io */ export class Ray { constructor(public origin: Vector3 = new Vector3(), public direction: Vector3 = new Vector3(0, 0, -1)) {} public set(origin: Vector3, direction: Vector3): Ray { this.origin.copy(origin) this.direction.copy(direction) return this } public clone(): Ray { return new Ray().copy(this) } public copy(ray: Ray): Ray { this.origin.copy(ray.origin) this.direction.copy(ray.direction) return this } public at(t: f32, target: Vector3): Vector3 { // previously it checked to make sure that `target: Vector3` is set. // We can assert that Vector3 is a reference with the signature at // compile time. return target.copy(this.direction).multiplyScalar(t).add(this.origin) } public lookAt(v: Vector3): Ray { this.direction.copy(v).sub(this.origin).normalize() return this } public recast(t: f32): Ray { this.origin.copy(this.at(t, _vector)) return this } public closestPointToPoint(point: Vector3, target: Vector3): Vector3 { target.subVectors(point, this.origin) const directionDistance = target.dot(this.direction) if (directionDistance < 0) { return target.copy(this.origin) } return target.copy(this.direction).multiplyScalar(directionDistance).add(this.origin) } public distanceToPoint(point: Vector3): f32 { return Mathf.sqrt(this.distanceSqToPoint(point)) } public distanceSqToPoint(point: Vector3): f32 { const directionDistance = _vector.subVectors(point, this.origin).dot(this.direction) // point behind the ray if (directionDistance < 0) { return this.origin.distanceToSquared(point) } _vector.copy(this.direction).multiplyScalar(directionDistance).add(this.origin) return _vector.distanceToSquared(point) } public distanceSqToSegment( v0: Vector3, v1: Vector3, optionalPointOnRay: Vector3 | null, optionalPointOnSegment: Vector3 | null ): f32 { // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteDistRaySegment.h // It returns the min distance between the ray and the segment // defined by v0 and v1 // It can also set two optional targets : // - The closest point on the ray // - The closest point on the segment _segCenter.copy(v0).add(v1).multiplyScalar(0.5) _segDir.copy(v1).sub(v0).normalize() _diff.copy(this.origin).sub(_segCenter) const segExtent = v0.distanceTo(v1) * 0.5 const a01 = -this.direction.dot(_segDir) const b0 = _diff.dot(this.direction) const b1 = -_diff.dot(_segDir) const c = _diff.lengthSq() const det = abs<f32>(1 - a01 * a01) let s0: f32, s1: f32, sqrDist: f32, extDet: f32 if (det > 0) { // The ray and segment are not parallel. s0 = a01 * b1 - b0 s1 = a01 * b0 - b1 extDet = segExtent * det if (s0 >= 0) { if (s1 >= -extDet) { if (s1 <= extDet) { // region 0 // Minimum at interior points of ray and segment. const invDet = <f32>1 / det s0 *= invDet s1 *= invDet sqrDist = s0 * (s0 + a01 * s1 + 2 * b0) + s1 * (a01 * s0 + s1 + 2 * b1) + c } else { // region 1 s1 = segExtent s0 = max<f32>(0, -(a01 * s1 + b0)) sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c } } else { // region 5 s1 = -segExtent s0 = max<f32>(0, -(a01 * s1 + b0)) sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c } } else { if (s1 <= -extDet) { // region 4 s0 = max<f32>(0, -(-a01 * segExtent + b0)) s1 = s0 > 0 ? -segExtent : min<f32>(max<f32>(-segExtent, -b1), segExtent) sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c } else if (s1 <= extDet) { // region 3 s0 = 0 s1 = min<f32>(max<f32>(-segExtent, -b1), segExtent) sqrDist = s1 * (s1 + 2 * b1) + c } else { // region 2 s0 = max<f32>(0, -(a01 * segExtent + b0)) s1 = s0 > 0 ? segExtent : min<f32>(max<f32>(-segExtent, -b1), segExtent) sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c } } } else { // Ray and segment are parallel. s1 = a01 > 0 ? -segExtent : segExtent s0 = max<f32>(0, -(a01 * s1 + b0)) sqrDist = -s0 * s0 + s1 * (s1 + 2 * b1) + c } if (optionalPointOnRay) { optionalPointOnRay.copy(this.direction).multiplyScalar(s0).add(this.origin) } if (optionalPointOnSegment) { optionalPointOnSegment.copy(_segDir).multiplyScalar(s1).add(_segCenter) } return sqrDist } public intersectSphere(sphere: Sphere, target: Vector3): Vector3 | null { _vector.subVectors(sphere.center, this.origin) const tca = _vector.dot(this.direction) const d2 = _vector.dot(_vector) - tca * tca const radius2 = sphere.radius * sphere.radius if (d2 > radius2) return null const thc = Mathf.sqrt(radius2 - d2) // t0 = first intersect point - entrance on front of sphere const t0 = tca - thc // t1 = second intersect point - exit point on back of sphere const t1 = tca + thc // test to see if both t0 and t1 are behind the ray - if so, return null if (t0 < 0 && t1 < 0) return null // test to see if t0 is behind the ray: // if it is, the ray is inside the sphere, so return the second exit point scaled by t1, // in order to always return an intersect point that is in front of the ray. // else t0 is in front of the ray, so return the first collision point scaled by t0 return this.at(select<f32>(t1, t0, t0 < 0), target) } public intersectsSphere(sphere: Sphere): bool { return this.distanceSqToPoint(sphere.center) <= sphere.radius * sphere.radius } /** * This method used to return null, but it never returns a negative number, so a * result of -1 is equivalent to a null result. */ public distanceToPlane(plane: Plane): f32 { const denominator = plane.normal.dot(this.direction) if (denominator === 0) { // line is coplanar, return origin if (plane.distanceToPoint(this.origin) === 0) { return 0 } // Null is preferable to undefined since undefined means.... it is undefined return -1 } const t = -(this.origin.dot(plane.normal) + plane.constant) / denominator // Return if the ray never intersects the plane return t >= 0 ? t : -1 } public intersectPlane(plane: Plane, target: Vector3): Vector3 | null { const t = this.distanceToPlane(plane) // this used to be a null check if (t === -1) { return null } return this.at(t, target) } public intersectsPlane(plane: Plane): bool { // check if the ray lies on the plane first const distToPoint = plane.distanceToPoint(this.origin) if (distToPoint === 0) { return true } const denominator = plane.normal.dot(this.direction) if (denominator * distToPoint < 0) { return true } // ray origin is behind the plane (and is pointing behind it) return false } public intersectsBox(box: Box3): bool { return this.intersectBox(box, _vector) != null } public intersectBox(box: Box3, target: Vector3): Vector3 | null { let tmin: f32, tmax: f32, tymin: f32, tymax: f32, tzmin: f32, tzmax: f32 const invdirx = <f32>1 / this.direction.x, invdiry = <f32>1 / this.direction.y, invdirz = <f32>1 / this.direction.z const origin = this.origin if (invdirx >= 0) { tmin = (box.min.x - origin.x) * invdirx tmax = (box.max.x - origin.x) * invdirx } else { tmin = (box.max.x - origin.x) * invdirx tmax = (box.min.x - origin.x) * invdirx } if (invdiry >= 0) { tymin = (box.min.y - origin.y) * invdiry tymax = (box.max.y - origin.y) * invdiry } else { tymin = (box.max.y - origin.y) * invdiry tymax = (box.min.y - origin.y) * invdiry } if (tmin > tymax || tymin > tmax) return null // These lines also handle the case where tmin or tmax is NaN // (result of 0 * Infinity). x !== x returns true if x is NaN if (tymin > tmin || tmin !== tmin) tmin = tymin if (tymax < tmax || tmax !== tmax) tmax = tymax if (invdirz >= 0) { tzmin = (box.min.z - origin.z) * invdirz tzmax = (box.max.z - origin.z) * invdirz } else { tzmin = (box.max.z - origin.z) * invdirz tzmax = (box.min.z - origin.z) * invdirz } if (tmin > tzmax || tzmin > tmax) return null if (tzmin > tmin || tmin !== tmin) tmin = tzmin if (tzmax < tmax || tmax !== tmax) tmax = tzmax //return point closest to the ray (positive side) if (tmax < 0) return null return this.at(tmin >= 0 ? tmin : tmax, target) } public intersectTriangle( a: Vector3, b: Vector3, c: Vector3, backfaceCulling: bool, target: Vector3 ): Vector3 | null { // Compute the offset origin, edges, and normal. // from http://www.geometrictools.com/GTEngine/Include/Mathematics/GteIntrRay3Triangle3.h _edge1.subVectors(b, a) _edge2.subVectors(c, a) _normal.crossVectors(_edge1, _edge2) // Solve Q + t*D = b1*E1 + b2*E2 (Q = kDiff, D = ray direction, // E1 = kEdge1, E2 = kEdge2, N = Cross(E1,E2)) by // |Dot(D,N)|*b1 = sign(Dot(D,N))*Dot(D,Cross(Q,E2)) // |Dot(D,N)|*b2 = sign(Dot(D,N))*Dot(D,Cross(E1,Q)) // |Dot(D,N)|*t = -sign(Dot(D,N))*Dot(Q,N) let DdN = this.direction.dot(_normal) let sign: f32 if (DdN > 0) { if (backfaceCulling) return null sign = 1 } else if (DdN < 0) { sign = -1 DdN = -DdN } else { return null } _diff.subVectors(this.origin, a) const DdQxE2 = sign * this.direction.dot(_edge2.crossVectors(_diff, _edge2)) // b1 < 0, no intersection if (DdQxE2 < 0) { return null } const DdE1xQ = sign * this.direction.dot(_edge1.cross(_diff)) // b2 < 0, no intersection if (DdE1xQ < 0) { return null } // b1+b2 > 1, no intersection if (DdQxE2 + DdE1xQ > DdN) { return null } // Line intersects triangle, check if ray does. const QdN = -sign * _diff.dot(_normal) // t < 0, no intersection if (QdN < 0) { return null } // Ray intersects triangle. return this.at(QdN / DdN, target) } public applyMatrix4(matrix4: Matrix4): Ray { this.origin.applyMatrix4(matrix4) this.direction.transformDirection(matrix4) return this } // @operator("==") public equals(ray: Ray): bool { return ray.origin.equals(this.origin) && ray.direction.equals(this.direction) } }
the_stack
export type PrefixedProps = { /** @deprecated since 0.4.3 */ _alignContent: string /** @deprecated since 0.4.3 */ _alignItems: string /** @deprecated since 0.4.3 */ _alignSelf: string _alignmentBaseline: string _all: string /** @deprecated since 0.4.3 */ _animation: string /** @deprecated since 0.4.3 */ _animationDelay: string /** @deprecated since 0.4.3 */ _animationDirection: string /** @deprecated since 0.4.3 */ _animationDuration: string /** @deprecated since 0.4.3 */ _animationFillMode: string /** @deprecated since 0.4.3 */ _animationIterationCount: string /** @deprecated since 0.4.3 */ _animationName: string /** @deprecated since 0.4.3 */ _animationPlayState: string /** @deprecated since 0.4.3 */ _animationTimingFunction: string _appearance: string _aspectRatio: string _azimuth: string /** @deprecated since 0.4.3 */ _backfaceVisibility: string _background: string _backgroundAttachment: string _backgroundBlendMode: string /** @deprecated since 0.5.4 */ _backgroundClip: string /** @deprecated since 0.4.3 */ _backgroundColor: string /** @deprecated since 0.4.3 */ _backgroundImage: string /** @deprecated since 0.5.4 */ _backgroundOrigin: string /** @deprecated since 0.4.3 */ _backgroundPosition: string /** @deprecated since 0.5.4 */ _backgroundRepeat: string /** @deprecated since 0.4.3 */ _backgroundSize: string _baselineShift: string _baselineSource: string _blockEllipsis: string _blockSize: string _blockStep: string _blockStepAlign: string _blockStepInsert: string _blockStepRound: string _blockStepSize: string _bookmarkLabel: string _bookmarkLevel: string _bookmarkState: string /** @deprecated since 0.4.3 */ _border: string _borderBlock: string _borderBlockColor: string _borderBlockEnd: string _borderBlockEndColor: string _borderBlockEndStyle: string _borderBlockEndWidth: string _borderBlockStart: string _borderBlockStartColor: string _borderBlockStartStyle: string _borderBlockStartWidth: string _borderBlockStyle: string _borderBlockWidth: string /** @deprecated since 0.4.3 */ _borderBottom: string /** @deprecated since 0.4.3 */ _borderBottomColor: string /** @deprecated since 0.4.3 */ _borderBottomLeftRadius: string /** @deprecated since 0.4.3 */ _borderBottomRightRadius: string /** @deprecated since 0.4.3 */ _borderBottomStyle: string /** @deprecated since 0.4.3 */ _borderBottomWidth: string _borderBoundary: string /** @deprecated since 0.4.5 */ _borderCollapse: string /** @deprecated since 0.4.3 */ _borderColor: string _borderEndEndRadius: string _borderEndStartRadius: string _borderImage: string /** @deprecated since 0.4.5 */ _borderImageOutset: string /** @deprecated since 0.4.5 */ _borderImageRepeat: string _borderImageSlice: string /** @deprecated since 0.4.5 */ _borderImageSource: string /** @deprecated since 0.4.5 */ _borderImageWidth: string _borderInline: string _borderInlineColor: string _borderInlineEnd: string _borderInlineEndColor: string _borderInlineEndStyle: string _borderInlineEndWidth: string _borderInlineStart: string _borderInlineStartColor: string _borderInlineStartStyle: string _borderInlineStartWidth: string _borderInlineStyle: string _borderInlineWidth: string /** @deprecated since 0.4.3 */ _borderLeft: string /** @deprecated since 0.4.3 */ _borderLeftColor: string /** @deprecated since 0.4.3 */ _borderLeftStyle: string /** @deprecated since 0.4.3 */ _borderLeftWidth: string /** @deprecated since 0.4.3 */ _borderRadius: string /** @deprecated since 0.4.3 */ _borderRight: string /** @deprecated since 0.4.3 */ _borderRightColor: string /** @deprecated since 0.4.3 */ _borderRightStyle: string /** @deprecated since 0.4.3 */ _borderRightWidth: string /** @deprecated since 0.4.5 */ _borderSpacing: string _borderStartEndRadius: string _borderStartStartRadius: string /** @deprecated since 0.4.3 */ _borderStyle: string /** @deprecated since 0.4.3 */ _borderTop: string /** @deprecated since 0.4.3 */ _borderTopColor: string /** @deprecated since 0.4.3 */ _borderTopLeftRadius: string /** @deprecated since 0.4.3 */ _borderTopRightRadius: string /** @deprecated since 0.4.3 */ _borderTopStyle: string /** @deprecated since 0.4.3 */ _borderTopWidth: string /** @deprecated since 0.4.3 */ _borderWidth: string /** @deprecated since 0.4.3 */ _bottom: string _boxDecorationBreak: string /** @deprecated since 0.4.3 */ _boxShadow: string /** @deprecated since 0.4.3 */ _boxSizing: string _boxSnap: string /** @deprecated since 0.4.3 */ _breakAfter: string /** @deprecated since 0.4.3 */ _breakBefore: string /** @deprecated since 0.4.3 */ _breakInside: string _captionSide: string _caret: string _caretColor: string _caretShape: string _chains: string _clear: string _clip: string _clipPath: string _clipRule: string /** @deprecated since 0.4.3 */ _color: string _colorAdjust: string _colorInterpolationFilters: string _colorScheme: string _columnCount: string _columnFill: string _columnGap: string _columnRule: string _columnRuleColor: string _columnRuleStyle: string _columnRuleWidth: string _columnSpan: string _columnWidth: string _columns: string _contain: string _containIntrinsicSize: string _content: string _contentVisibility: string _continue: string _counterIncrement: string _counterReset: string _counterSet: string _cue: string _cueAfter: string _cueBefore: string _cursor: string _direction: string /** @deprecated since 0.4.3 */ _display: string _dominantBaseline: string _elevation: string _emptyCells: string _fill: string _fillBreak: string _fillColor: string _fillImage: string _fillOpacity: string _fillOrigin: string _fillPosition: string _fillRepeat: string _fillRule: string _fillSize: string _filter: string /** @deprecated since 0.4.3 */ _flex: string /** @deprecated since 0.4.3 */ _flexBasis: string /** @deprecated since 0.4.3 */ _flexDirection: string /** @deprecated since 0.4.3 */ _flexFlow: string /** @deprecated since 0.4.3 */ _flexGrow: string /** @deprecated since 0.4.3 */ _flexShrink: string /** @deprecated since 0.4.3 */ _flexWrap: string _float: string _floatDefer: string _floatOffset: string _floatReference: string _floodColor: string _floodOpacity: string _flow: string _flowFrom: string _flowInto: string _font: string /** @deprecated since 0.4.3 */ _fontFamily: string _fontFeatureSettings: string /** @deprecated since 0.4.3 */ _fontKerning: string _fontLanguageOverride: string /** @deprecated since 0.4.3 */ _fontOpticalSizing: string _fontPalette: string /** @deprecated since 0.4.3 */ _fontSize: string /** @deprecated since 0.4.3 */ _fontSizeAdjust: string /** @deprecated since 0.4.3 */ _fontStretch: string /** @deprecated since 0.4.3 */ _fontStyle: string /** @deprecated since 0.4.3 */ _fontSynthesis: string /** @deprecated since 0.4.3 */ _fontSynthesisSmallCaps: string /** @deprecated since 0.4.3 */ _fontSynthesisStyle: string /** @deprecated since 0.4.3 */ _fontSynthesisWeight: string _fontVariant: string _fontVariantAlternates: string /** @deprecated since 0.4.3 */ _fontVariantCaps: string _fontVariantEastAsian: string /** @deprecated since 0.4.3 */ _fontVariantEmoji: string /** @deprecated since 0.4.3 */ _fontVariantLigatures: string /** @deprecated since 0.4.3 */ _fontVariantNumeric: string /** @deprecated since 0.4.3 */ _fontVariantPosition: string /** @deprecated since 0.4.3 */ _fontVariationSettings: string /** @deprecated since 0.4.3 */ _fontWeight: string _footnoteDisplay: string _footnotePolicy: string _forcedColorAdjust: string _gap: string _glyphOrientationVertical: string _grid: string _gridArea: string _gridAutoColumns: string _gridAutoFlow: string _gridAutoRows: string _gridColumn: string _gridColumnEnd: string _gridColumnStart: string _gridRow: string _gridRowEnd: string _gridRowStart: string _gridTemplate: string _gridTemplateAreas: string _gridTemplateColumns: string _gridTemplateRows: string _hangingPunctuation: string /** @deprecated since 0.4.3 */ _height: string _hyphenateCharacter: string _hyphenateLimitChars: string _hyphenateLimitLast: string _hyphenateLimitLines: string _hyphenateLimitZone: string _hyphens: string _imageOrientation: string _imageRendering: string _imageResolution: string _initialLetter: string _initialLetterAlign: string _initialLetterWrap: string _inlineSize: string _inlineSizing: string _inset: string _insetBlock: string _insetBlockEnd: string _insetBlockStart: string _insetInline: string _insetInlineEnd: string _insetInlineStart: string _isolation: string /** @deprecated since 0.4.3 */ _justifyContent: string /** @deprecated since 0.4.4 */ _justifyItems: string /** @deprecated since 0.4.4 */ _justifySelf: string _leadingTrim: string /** @deprecated since 0.4.3 */ _left: string /** @deprecated since 0.4.3 */ _letterSpacing: string _lightingColor: string _lineBreak: string _lineClamp: string _lineGrid: string /** @deprecated since 0.4.3 */ _lineHeight: string _lineHeightStep: string _linePadding: string _lineSnap: string /** @deprecated since 0.5.2 */ _listStyle: string /** @deprecated since 0.5.2 */ _listStyleImage: string /** @deprecated since 0.5.2 */ _listStylePosition: string /** @deprecated since 0.5.2 */ _listStyleType: string /** @deprecated since 0.4.3 */ _margin: string _marginBlock: string _marginBlockEnd: string _marginBlockStart: string /** @deprecated since 0.4.3 */ _marginBottom: string _marginBreak: string _marginInline: string _marginInlineEnd: string _marginInlineStart: string /** @deprecated since 0.4.3 */ _marginLeft: string /** @deprecated since 0.4.3 */ _marginRight: string /** @deprecated since 0.4.3 */ _marginTop: string _marginTrim: string _marker: string _markerEnd: string _markerKnockoutLeft: string _markerKnockoutRight: string _markerMid: string _markerPattern: string _markerSegment: string _markerSide: string _markerStart: string _mask: string _maskBorder: string _maskBorderMode: string _maskBorderOutset: string _maskBorderRepeat: string _maskBorderSlice: string _maskBorderSource: string _maskBorderWidth: string _maskClip: string _maskComposite: string _maskImage: string _maskMode: string _maskOrigin: string _maskPosition: string _maskRepeat: string _maskSize: string _maskType: string _maxBlockSize: string _maxHeight: string _maxInlineSize: string _maxLines: string /** @deprecated since 0.4.3 */ _maxWidth: string _minBlockSize: string /** @deprecated since 0.4.3 */ _minHeight: string _minInlineSize: string _minIntrinsicSizing: string _minWidth: string _mixBlendMode: string _navDown: string _navLeft: string _navRight: string _navUp: string _objectFit: string _objectPosition: string _offset: string _offsetAnchor: string _offsetDistance: string _offsetPath: string _offsetPosition: string _offsetRotate: string /** @deprecated since 0.4.3 */ _opacity: string /** @deprecated since 0.4.3 */ _order: string _orphans: string /** @deprecated since 0.4.3 */ _outline: string /** @deprecated since 0.4.3 */ _outlineColor: string _outlineOffset: string /** @deprecated since 0.4.3 */ _outlineStyle: string /** @deprecated since 0.4.3 */ _outlineWidth: string /** @deprecated since 0.4.3 */ _overflow: string _overflowAnchor: string _overflowBlock: string _overflowClipMargin: string _overflowInline: string _overflowWrap: string /** @deprecated since 0.4.3 */ _overflowX: string /** @deprecated since 0.4.3 */ _overflowY: string _overscrollBehavior: string _overscrollBehaviorBlock: string _overscrollBehaviorInline: string _overscrollBehaviorX: string _overscrollBehaviorY: string /** @deprecated since 0.4.3 */ _padding: string _paddingBlock: string _paddingBlockEnd: string _paddingBlockStart: string /** @deprecated since 0.4.3 */ _paddingBottom: string _paddingInline: string _paddingInlineEnd: string _paddingInlineStart: string /** @deprecated since 0.4.3 */ _paddingLeft: string /** @deprecated since 0.4.3 */ _paddingRight: string /** @deprecated since 0.4.3 */ _paddingTop: string _page: string _pageBreakAfter: string _pageBreakBefore: string _pageBreakInside: string _pause: string _pauseAfter: string _pauseBefore: string _perspective: string _perspectiveOrigin: string _pitch: string _pitchRange: string _placeContent: string _placeItems: string _placeSelf: string _playDuring: string /** @deprecated since 0.4.3 */ _position: string _propertyName: string _quotes: string _regionFragment: string _resize: string _rest: string _restAfter: string _restBefore: string _richness: string /** @deprecated since 0.4.3 */ _right: string _rotate: string _rowGap: string _rubyAlign: string _rubyMerge: string _rubyOverhang: string _rubyPosition: string _running: string _scale: string _scrollBehavior: string _scrollMargin: string _scrollMarginBlock: string _scrollMarginBlockEnd: string _scrollMarginBlockStart: string _scrollMarginBottom: string _scrollMarginInline: string _scrollMarginInlineEnd: string _scrollMarginInlineStart: string _scrollMarginLeft: string _scrollMarginRight: string _scrollMarginTop: string _scrollPadding: string _scrollPaddingBlock: string _scrollPaddingBlockEnd: string _scrollPaddingBlockStart: string _scrollPaddingBottom: string _scrollPaddingInline: string _scrollPaddingInlineEnd: string _scrollPaddingInlineStart: string _scrollPaddingLeft: string _scrollPaddingRight: string _scrollPaddingTop: string _scrollSnapAlign: string _scrollSnapStop: string _scrollSnapType: string _scrollbarColor: string _scrollbarGutter: string _scrollbarWidth: string _shapeImageThreshold: string _shapeInside: string _shapeMargin: string _shapeOutside: string _spatialNavigationAction: string _spatialNavigationContain: string _spatialNavigationFunction: string _speak: string _speakAs: string _speakHeader: string _speakNumeral: string _speakPunctuation: string _speechRate: string _stress: string _stringSet: string _stroke: string _strokeAlign: string _strokeAlignment: string _strokeBreak: string _strokeColor: string _strokeDashCorner: string _strokeDashJustify: string _strokeDashadjust: string _strokeDasharray: string _strokeDashcorner: string _strokeDashoffset: string _strokeImage: string _strokeLinecap: string _strokeLinejoin: string _strokeMiterlimit: string _strokeOpacity: string _strokeOrigin: string _strokePosition: string _strokeRepeat: string _strokeSize: string _strokeWidth: string _tabSize: string _tableLayout: string /** @deprecated since 0.4.3 */ _textAlign: string _textAlignAll: string _textAlignLast: string _textCombineUpright: string _textDecoration: string _textDecorationColor: string _textDecorationLine: string _textDecorationSkip: string _textDecorationSkipBox: string _textDecorationSkipInk: string _textDecorationSkipInset: string _textDecorationSkipSelf: string _textDecorationSkipSpaces: string _textDecorationStyle: string _textDecorationThickness: string _textEdge: string /** @deprecated since 0.4.3 */ _textEmphasis: string /** @deprecated since 0.4.3 */ _textEmphasisColor: string /** @deprecated since 0.4.3 */ _textEmphasisPosition: string /** @deprecated since 0.4.3 */ _textEmphasisSkip: string _textEmphasisStyle: string _textGroupAlign: string /** @deprecated since 0.4.3 */ _textIndent: string /** @deprecated since 0.4.3 */ _textJustify: string /** @deprecated since 0.4.3 */ _textOrientation: string _textOverflow: string _textShadow: string _textSpaceCollapse: string _textSpaceTrim: string _textSpacing: string /** @deprecated since 0.4.3 */ _textTransform: string /** @deprecated since 0.4.3 */ _textUnderlineOffset: string /** @deprecated since 0.4.3 */ _textUnderlinePosition: string /** @deprecated since 0.4.3 */ _textWrap: string /** @deprecated since 0.4.3 */ _top: string /** @deprecated since 0.4.3 */ _transform: string /** @deprecated since 0.4.3 */ _transformBox: string /** @deprecated since 0.4.3 */ _transformOrigin: string /** @deprecated since 0.4.3 */ _transformStyle: string /** @deprecated since 0.4.3 */ _transition: string /** @deprecated since 0.4.3 */ _transitionDelay: string /** @deprecated since 0.4.3 */ _transitionDuration: string /** @deprecated since 0.4.3 */ _transitionProperty: string /** @deprecated since 0.4.3 */ _transitionTimingFunction: string /** @deprecated since 0.4.3 */ _translate: string /** @deprecated since 0.4.3 */ _unicodeBidi: string /** @deprecated since 0.4.3 */ _userSelect: string /** @deprecated since 0.4.3 */ _verticalAlign: string /** @deprecated since 0.4.3 */ _visibility: string _voiceBalance: string _voiceDuration: string _voiceFamily: string _voicePitch: string _voiceRange: string /** @deprecated since 0.4.3 */ _voiceRate: string /** @deprecated since 0.4.3 */ _voiceStress: string /** @deprecated since 0.4.3 */ _voiceVolume: string /** @deprecated since 0.4.3 */ _volume: string /** @deprecated since 0.4.3 */ _whiteSpace: string /** @deprecated since 0.4.3 */ _widows: string /** @deprecated since 0.4.3 */ _width: string /** @deprecated since 0.4.3 */ _willChange: string _wordBoundaryDetection: string _wordBoundaryExpansion: string _wordBreak: string /** @deprecated since 0.4.3 */ _wordSpacing: string _wordWrap: string _wrapAfter: string _wrapBefore: string _wrapFlow: string _wrapInside: string _wrapThrough: string /** @deprecated since 0.4.3 */ _writingMode: string /** @deprecated since 0.4.3 */ _zIndex: string }
the_stack
import { Nodes, PhaseFlags } from '../nodes'; import { walkPreOrder } from '../walker'; import { annotations } from '../annotations'; import { UnreachableCode, LysScopeError } from '../NodeError'; import { ParsingContext } from '../ParsingContext'; import { InjectableTypes } from '../types'; import { findParentDelegate } from '../nodeHelpers'; import { getDocument, fixParents, collectImports } from './helpers'; import { Scope } from '../Scope'; import assert = require('assert'); import { LysError } from '../../utils/errorPrinter'; const CORE_LIB = 'system::core'; const valueNodeAnnotation = new annotations.IsValueNode(); const findValueNodes = walkPreOrder((node: Nodes.Node) => { /** * This phase traverses all nodes and adds an annotation to the value nodes, value nodes are those nodes that * must have a value. * Value nodes are usually the RHS of an assigment node, the LHS of match nodes, function call arguments and so on. */ if (node instanceof Nodes.FunctionCallNode) { node.argumentsNode.forEach($ => $.annotate(valueNodeAnnotation)); } if (node instanceof Nodes.VarDeclarationNode) { node.value.annotate(valueNodeAnnotation); } if (node instanceof Nodes.AssignmentNode) { node.rhs.annotate(valueNodeAnnotation); node.lhs.annotate(new annotations.IsAssignationLHS()); } if (node instanceof Nodes.MemberNode) { if (node.lhs instanceof Nodes.MemberNode) { node.lhs.annotate(valueNodeAnnotation); } } if (node instanceof Nodes.FunctionNode) { let returnsVoidValue = false; if (node.functionReturnType) { // TODO: dehardcode this... Unit type may be a good approach returnsVoidValue = node.functionReturnType instanceof Nodes.ReferenceNode && node.functionReturnType.variable.text === 'void'; } if (!returnsVoidValue) { if (node.body) { node.body.annotate(valueNodeAnnotation); } else { // TODO: warn } } } if (node instanceof Nodes.BinaryExpressionNode) { node.lhs.annotate(valueNodeAnnotation); node.rhs.annotate(valueNodeAnnotation); } if (node instanceof Nodes.IsExpressionNode) { node.lhs.annotate(valueNodeAnnotation); } if (node instanceof Nodes.AsExpressionNode) { node.lhs.annotate(valueNodeAnnotation); } if (node instanceof Nodes.IfNode) { node.condition.annotate(valueNodeAnnotation); if (node.falsePart) { if (node.hasAnnotation(annotations.IsValueNode)) { node.truePart.annotate(valueNodeAnnotation); node.falsePart.annotate(valueNodeAnnotation); } } } if (node instanceof Nodes.PatternMatcherNode) { node.lhs.annotate(valueNodeAnnotation); if (node.hasAnnotation(annotations.IsValueNode)) { node.matchingSet.forEach($ => { $.annotate(valueNodeAnnotation); $.rhs.annotate(valueNodeAnnotation); }); } } if (node instanceof Nodes.BlockNode) { if (node.hasAnnotation(annotations.IsValueNode) && node.statements.length > 0) { node.statements[node.statements.length - 1].annotate(valueNodeAnnotation); } } }); const createScopes = walkPreOrder((node: Nodes.Node, parsingContext: ParsingContext, parent: Nodes.Node | null) => { if (parent) { if (!node.scope) { node.scope = parent.scope; } if (node instanceof Nodes.MatcherNode) { node.rhs.scope = node.scope!.newChildScope('MatcherRHS'); if (node.declaredName) { node.rhs.scope.set(node.declaredName, 'VALUE', false); } if (node instanceof Nodes.MatchCaseIsNode) { if (node.deconstructorNames) { const takenNames = new Map<string, Nodes.Node>(); node.deconstructorNames.forEach($ => { if ($.name !== '_') { if (takenNames.has($.name)) { parsingContext.messageCollector.error(new LysScopeError('Duplicated name', $)); } else { takenNames.set($.name, $); node.rhs.scope!.set($, 'VALUE', false); } } }); } } } else if (node instanceof Nodes.OverloadedFunctionNode) { node.scope!.set(node.functionName, 'FUNCTION', node.isPublic); } else if (node instanceof Nodes.TraitDirectiveNode) { node.scope!.set(node.traitName, 'TRAIT', node.isPublic); node.scope = node.scope!.newChildScope(node.traitName.name + '.'); node.selfTypeName = new Nodes.NameIdentifierNode(node.traitName.astNode, 'Self'); node.scope.set(node.selfTypeName, 'TYPE', false); } else if (node instanceof Nodes.VarDeclarationNode) { if (node.variableName.name in InjectableTypes) { parsingContext.messageCollector.error( new LysScopeError('Cannot declare a variable with the name of an system type', node.variableName) ); } node.value.scope = node.scope!.newChildScope(node.variableName.name + '_Declaration'); node.scope!.set(node.variableName, 'VALUE', parent instanceof Nodes.VarDirectiveNode && parent.isPublic); } else if (node instanceof Nodes.ImplDirective) { node.scope = node.scope!.newChildScope(node.targetImpl.variable.text + '.'); if (node.baseImpl) { node.selfTypeName = new Nodes.NameIdentifierNode(node.targetImpl.astNode, 'Self'); node.scope.set(node.selfTypeName, 'TYPE', false); } } else if (node instanceof Nodes.TypeDirectiveNode) { node.scope!.set(node.variableName, 'TYPE', node.isPublic); } else if (node instanceof Nodes.FunctionNode) { if (node.functionName) { if (!(parent instanceof Nodes.DirectiveNode)) { node.scope!.set(node.functionName, 'VALUE', false); } else if (!node.functionName.internalIdentifier) { node.functionName.internalIdentifier = node.scope!.getInternalIdentifier(node.functionName); } } if (node.body) { // if (node.body == false) a message is emited in the semantic phase const functionBody = node.body; if (node.functionName) { node.body.scope = node.scope!.newChildScope(node.functionName.name + '_Body'); } else { node.body.scope = node.scope!.newChildScope('Body'); } node.parameters.forEach($ => { functionBody.scope!.set($.parameterName, 'VALUE', false); }); } node.processParameters(); } else if (node instanceof Nodes.BlockNode) { node.scope = node.scope!.newChildScope('Block'); } } }); function collectNamespaces( namespace: Nodes.ImplDirective | Nodes.TraitDirectiveNode, directives: Nodes.DirectiveNode[], parsingContext: ParsingContext ) { const { namespaceNames } = namespace; const nameToShow = namespace instanceof Nodes.ImplDirective ? namespace.targetImpl.variable.text : namespace.traitName.name; function registerNameIdentifier(nameNode: Nodes.NameIdentifierNode) { if (namespaceNames.has(nameNode.name) && namespaceNames.get(nameNode.name) !== nameNode) { parsingContext.messageCollector.error( `The name "${nameNode.name}" is already registered in the impl "${nameToShow}"`, nameNode.astNode ); parsingContext.messageCollector.error( `This is the registered name "${nameNode.name}" of "${nameToShow}"`, namespaceNames.get(nameNode.name)!.astNode ); } else { namespaceNames.set(nameNode.name, nameNode); } } directives.forEach(node => { if (node instanceof Nodes.OverloadedFunctionNode) { registerNameIdentifier(node.functionName); } else if (node instanceof Nodes.VarDirectiveNode) { registerNameIdentifier(node.decl.variableName); } else if (node instanceof Nodes.TypeDirectiveNode) { registerNameIdentifier(node.variableName); } else { parsingContext.messageCollector.error(`Don't know how to register this directive ${node.nodeName}`, node.astNode); } }); } const resolveVariables = walkPreOrder(undefined, (node: Nodes.Node, parsingContext: ParsingContext) => { if (node instanceof Nodes.IsExpressionNode || node instanceof Nodes.IfNode || node instanceof Nodes.MatcherNode) { const typeName = 'boolean'; try { node.scope!.get(typeName); } catch (e) { throw new LysScopeError(e.toString(), node); } const resolved = node.scope!.get(typeName); node.booleanReference = resolved; node.scope!.incrementUsage(typeName); } else if (node instanceof Nodes.LiteralNode) { try { node.scope!.get(node.typeName); } catch (e) { throw new LysScopeError(e.toString(), node); } const resolved = node.scope!.get(node.typeName); node.resolvedReference = resolved; node.scope!.incrementUsage(node.typeName); } else if (node instanceof Nodes.ReferenceNode) { try { node.scope!.getQName(node.variable); } catch (e) { throw new LysScopeError(e.toString(), node.variable); } const resolved = node.scope!.getQName(node.variable); const document = getDocument(node); const isGlobal = !resolved.isLocalReference || resolved.scope === document.scope; node.isLocal = !isGlobal; node.resolvedReference = resolved; node.scope!.incrementUsageQName(node.variable); } else if (node instanceof Nodes.ImplDirective) { if (node.targetImpl.resolvedReference) { collectNamespaces(node, node.directives, parsingContext); } else { throw new LysScopeError(`Impl is not resolved`, node); } } else if (node instanceof Nodes.TraitDirectiveNode) { collectNamespaces(node, node.directives, parsingContext); } else if (node instanceof Nodes.ImportDirectiveNode) { try { parsingContext.getPhase(node.module.text, PhaseFlags.NameInitialization); } catch (e) { parsingContext.messageCollector.error(`Unable to load module ${node.module.text}: ` + e, node.astNode); } } }); const findImplicitImports = walkPreOrder((node: Nodes.Node, parsingContext: ParsingContext) => { if (node instanceof Nodes.ImportDirectiveNode) { const document = getDocument(node); if (node.module.text === document.moduleName) { // TODO: test this parsingContext.messageCollector.error('Self import is not allowed', node.astNode); } const importAll = node.allItems ? new Set(['*']) : new Set<string>(); node.scope!.registerImport(node.module.text, importAll); } else if (node instanceof Nodes.ReferenceNode) { if (node.variable.names.length > 1) { const { moduleName, variable } = node.variable.deconstruct(); const document = getDocument(node); if (moduleName === document.moduleName) { // TODO: test this parsingContext.messageCollector.error('Self import is not allowed', node.astNode); } node.scope!.registerImport(moduleName, new Set([variable])); } } }); const injectImplicitCalls = walkPreOrder((node: Nodes.Node, _: ParsingContext) => { if (node instanceof Nodes.FunctionCallNode && node.functionNode instanceof Nodes.ReferenceNode) { if (node.functionNode.resolvedReference && node.functionNode.resolvedReference.type === 'TYPE') { const member = new Nodes.MemberNode( node.functionNode.astNode, node.functionNode, '.', new Nodes.NameIdentifierNode(node.functionNode.astNode, 'apply') ); member.scope = node.functionNode.scope; node.functionNode = member; } } }); function injectCoreImport(document: Nodes.DocumentNode, parsingContext: ParsingContext) { if (document.moduleName.startsWith(CORE_LIB)) { return; } if (document.hasAnnotation(annotations.NoStd)) { return; } const coreLib = parsingContext.getPhase(CORE_LIB, PhaseFlags.Semantic, false); coreLib.directives.reverse().forEach(directive => { if (directive instanceof Nodes.ImportDirectiveNode) { const newDirective = new Nodes.ImportDirectiveNode(directive.astNode, directive.module); newDirective.allItems = directive.allItems; newDirective.alias = directive.alias; document.directives.unshift(newDirective); } else { throw new LysError('Only import directives are allowed in system::core, found: ' + directive.nodeName); } }); } function summarizeImports(document: Nodes.DocumentNode, parsingContext: ParsingContext) { collectImports(document.importedModules, document, parsingContext); document.importedModules.delete(document.moduleName); document.importedModules.forEach(moduleName => { const requiredDocument = parsingContext.getPhase(moduleName, PhaseFlags.Semantic); if (requiredDocument !== document) { requiredDocument.importedBy.add(document.moduleName); } }); } const unreachableAnnotation = new annotations.IsUnreachable(); const validateLoops = walkPreOrder( (node: Nodes.Node, parsingContext: ParsingContext) => { if (node instanceof Nodes.ContinueNode || node instanceof Nodes.BreakNode) { const relevantParent = findParentDelegate(node, $ => { return ( $ instanceof Nodes.LoopNode || $ instanceof Nodes.FunctionNode || $.hasAnnotation(annotations.IsValueNode) ); }); if (relevantParent instanceof Nodes.LoopNode) { node.annotate(new annotations.CurrentLoop(relevantParent)); } else { if (relevantParent instanceof Nodes.FunctionNode) { parsingContext.messageCollector.error(`Invalid location: No loop was found`, node.astNode); } else { parsingContext.messageCollector.error(`Invalid location. Parent block must return a value`, node.astNode); if (relevantParent) { parsingContext.messageCollector.error(`Not all paths return a value`, relevantParent.astNode); } } } } }, (node, parsingContext) => { if (node instanceof Nodes.BlockNode) { let nextAreUnreachable = false; node.statements.forEach($ => { if (nextAreUnreachable) { parsingContext.messageCollector.error(new UnreachableCode($)); $.annotate(unreachableAnnotation); } if ($ instanceof Nodes.ContinueNode || $ instanceof Nodes.BreakNode) { if ($.hasAnnotation(annotations.CurrentLoop)) { nextAreUnreachable = true; } } }); } } ); const validateMutability = walkPreOrder((node: Nodes.Node, parsingContext: ParsingContext) => { if (node instanceof Nodes.AssignmentNode) { if (node.lhs instanceof Nodes.ReferenceNode && node.lhs.resolvedReference) { if (!node.lhs.resolvedReference.referencedNode.hasAnnotation(annotations.MutableDeclaration)) { parsingContext.messageCollector.error( `${node.lhs.resolvedReference.referencedNode.name} is immutable, reassignment is not allowed.`, node.lhs.astNode ); } } } }); export function executeNameInitializationPhase(moduleName: string, parsingContext: ParsingContext) { const document = parsingContext.getPhase(moduleName, PhaseFlags.NameInitialization - 1); assert(document.analysis.nextPhase === PhaseFlags.NameInitialization); assert(document.moduleName === moduleName); document.scope = new Scope(parsingContext, document.moduleName, null, ''); injectCoreImport(document, parsingContext); createScopes(document, parsingContext, null); fixParents(document, parsingContext); findImplicitImports(document, parsingContext, null); document.analysis.nextPhase++; return; } export function executeScopePhase(moduleName: string, parsingContext: ParsingContext) { const document = parsingContext.getPhase(moduleName, PhaseFlags.Scope - 1); assert(document.analysis.nextPhase === PhaseFlags.Scope); resolveVariables(document, parsingContext, null); findValueNodes(document, parsingContext, null); injectImplicitCalls(document, parsingContext, null); validateLoops(document, parsingContext); validateMutability(document, parsingContext); summarizeImports(document, parsingContext); document.analysis.nextPhase++; }
the_stack
import {Request, Response} from "express"; import * as mongoose from "mongoose"; import {RetCodes} from "../../base/RetCodes"; import {RouteType, ReqRouter} from "./CgiBase"; import {PostModel} from "../data/BlogModules"; import CgiHelper from "./CgiHelper"; export function postRouter() { class _ { static postPreviewProjection = { _id: 1, title: 1, previewContent: 1, previewImage: 1, publishTimestamp: 1, modifyTimestamp: 1, watchCount: 1, praiseCount: 1 }; @ReqRouter.RouteCgi('/praise_post/:postId') static praisePost(req: Request, rsp: Response) { PostModel .where('_id', req.params.postId) .update({$inc: {'praiseCount': 1}}, (err: any, affectedRow: number) => { if (err || affectedRow <= 0) { CgiHelper.notifyError(rsp, err); } else { CgiHelper.notifySuccess(rsp); } }); } @ReqRouter.RouteCgi('/post_list/:categoryId/:pageIndex/:count') static postList(req: Request, rsp: Response) { let condition: any = null; if (req.params.categoryId && req.params.categoryId !== 'all') { condition = {categories: {$in: [req.params.categoryId]}}; } _._postPreviewListInternal(rsp, condition, req.params.pageIndex, req.params.count); } @ReqRouter.RouteCgi('/tag_post_list/:tagName/:pageIndex/:count') static tagPostList(req: Request, rsp: Response) { let condition: any = {tags: {$in: [req.params.tagName]}}; _._postPreviewListInternal(rsp, condition, req.params.pageIndex, req.params.count); } static _postPreviewListInternal(rsp: Response, condition: any, pageIndex: any, reqCount: any) { reqCount = parseInt(reqCount); if (reqCount <= 0) { reqCount = 10; } new Promise((resolve: Function, reject: Function) => { PostModel.count(condition, (err: any, count: number) => { if (err) { reject(err); return; } if (count <= 0) { rsp.json({ ret: RetCodes.OK, posts: [], pageCount: 0 }); return; } resolve(count); }); }).then((count: number) => { let start: number = Math.max(0, parseInt(pageIndex)) * reqCount; PostModel.find(condition, _.postPreviewProjection, (err: any, res: any[]) => { if (err) { CgiHelper.notifyError(rsp, err); return; } rsp.json({ ret: RetCodes.OK, posts: res, pageCount: Math.ceil(count / reqCount) }); }).limit(reqCount) .skip(start) .sort({'publishTimestamp': -1}); }).catch((err: any) => { CgiHelper.notifyError(rsp, err); }); } @ReqRouter.RouteCgi('/post_detail/:postId') static postDetail(req: Request, rsp: Response) { PostModel.where('_id', req.params.postId).findOne((err: any, res: any) => { if (err) { CgiHelper.notifyError(rsp, err); return; } if (!res) { CgiHelper.notifyError(rsp, err, RetCodes.Post.POST_NOT_EXIST); return; } rsp.json({ ret: RetCodes.OK, post: res }); if (!req.query.fromInternal || req.query.fromInternal.toString().toLowerCase() !== 'true') { PostModel.where('_id', req.params.postId) .update({$inc: {'watchCount': 1}}).exec(); } }); } @ReqRouter.RouteCgi('/post_tag_list') static postTagList(req: Request, rsp: Response) { PostModel.aggregate() .project({name: '$tags'}) .unwind('$name') .group({_id: '$name', count: {$sum: 1}}) .sort({'count': -1}) .exec((err: any, result: any) => { if (err || !result) { CgiHelper.notifyError(rsp, err); return; } for (let item of result) { item.name = item._id; item._id = null; } rsp.json({ ret: RetCodes.OK, tags: result }); }); } @ReqRouter.RouteCgi('/post_timeline_list') static postTimelineList(req: Request, rsp: Response) { let group = { keyf: (doc: any) => { let date = new Date(doc.publishTimestamp); return { year: date.getFullYear(), month: date.getMonth() + 1, date: `${date.getFullYear()}年${date.getMonth() + 1}月` }; }, condition: {}, initial: {count: 0}, reduce: (doc: any, result: any) => { ++result.count; }, finalize: () => { } }; PostModel.collection.group( group.keyf, group.condition, group.initial, group.reduce, group.finalize, true, (err: any, result: any[]) => { if (err) { CgiHelper.notifyError(rsp, err); return; } result = result.sort((a: any, b: any) => { if (a.year > b.year) { return -1; } else if (a.year < b.year) { return 1; } if (a.month > b.month) { return -1; } else if (a.month < b.month) { return 1; } return 0; }); rsp.json({ ret: RetCodes.OK, list: result }); }); } @ReqRouter.RouteCgi('/timeline_post_list_detail/:year/:month/:pageIndex/:count') static timelinePostListDetail(req: Request, rsp: Response) { let nextYear = req.params.year; let nextMonth = req.params.month; if (req.params.month >= 12) { ++nextYear; nextMonth = 0; } let condition = { publishTimestamp: { $gte: new Date(req.params.year, req.params.month - 1, 1), $lt: new Date(nextYear, nextMonth, 1) } }; _._postPreviewListInternal(rsp, condition, req.params.pageIndex, req.params.count); } @ReqRouter.AdminRouteCgi('/remove_post/:postId', RouteType.POST) static removePost(req: Request, rsp: Response) { PostModel.remove({_id: req.params.postId}, (err: any) => { if (err) { CgiHelper.notifyError(rsp, err); return; } CgiHelper.uploader.removeFilesByPostId(req.params.postId); CgiHelper.notifySuccess(rsp); }); } @ReqRouter.AdminRouteCgi('/modify_publish_timestamp/:postId', RouteType.POST) static modifyPostPublishTimestamp(req: Request, rsp: Response) { let millSeconds = Math.max(0, parseInt(req.query.time)); if (millSeconds == 0) { CgiHelper.notifyError(rsp); return; } PostModel.update( {_id: req.params.postId}, { $set: {publishTimestamp: new Date(millSeconds)} }, (err: any, raw: any) => { if (err) { CgiHelper.notifyError(rsp, err); return; } CgiHelper.notifySuccess(rsp); } ); } static _getPostContent(req: Request, callback: (post: any) => void) { CgiHelper.receivePostDataString(req, (data: string) => { if (data) { try { callback(JSON.parse(data)); return; } catch (e) { console.log(e); } } callback(null); }); } @ReqRouter.AdminRouteCgi('/add_post', RouteType.POST) static addPost(req: Request, rsp: Response) { _._getPostContent(req, (post: any) => { if (post) { _.savePost(rsp, post); } else { CgiHelper.notifyError(rsp); } }); } @ReqRouter.AdminRouteCgi('/modify_post/:postId', RouteType.POST) static modifyPost(req: Request, rsp: Response) { _._getPostContent(req, (post: any) => { if (post) { post._id = req.params.postId; _.savePost(rsp, post); } else { CgiHelper.notifyError(rsp); } }); } static savePost(rsp: Response, post: any) { post.modifyTimestamp = new Date(); let success = (_id: string) => { rsp.json({ ret: RetCodes.OK, post: { _id: _id } }); }; let postId = post._id; if (post.content) { if (!postId || postId.length <= 0) { let id: any = new mongoose.Types.ObjectId(); postId = id.toHexString(); } _.handlePostTempImage(postId, post); let imgReg = /!\[.*\]\((.*)\)/i; let matched = post.content.match(imgReg); if (matched && matched.length >= 2) { post.previewImage = matched[1]; } } if (post._id && post._id.length > 0) { PostModel .where('_id', post._id) .update({$set: post}, (err: any, affectedRows: number) => { if (err) { CgiHelper.notifyError(rsp, err); } else { success(post._id); } }); } else { post._id = postId; post.publishTimestamp = new Date(); PostModel.insertMany([post], (err: any, doc: any[]) => { if (err || !doc || doc.length <= 0) { CgiHelper.notifyError(rsp, err); } else { success(doc[0]._id); } }); } } static handlePostTempImage(postId: string, post: any) { let reg = /!\[.*\]\(\/upload_images\/(.+)\)/ig; let matches = post.content.match(reg); if (!matches || matches.length <= 0) { return; } let imgNameReg = /!\[(.*)\]\(\/upload_images\/(.+)\)/i; for (let item of matches) { let match = item.match(imgNameReg); if (!match || match.length < 3) { continue; } CgiHelper.uploader.moveImageFile(postId, match[2]); post.content = post.content.replace( item, `![${match[1]}](/images/${postId}/${match[2]})]`); } } } }
the_stack
import { parseHtmlFragment } from '@tko/utils' import components from '../dist' import '@tko/utils/helpers/jasmine-13-helper' describe('Components: Default loader', function () { var waitsFor = window.waitsFor var testComponentName = 'test-component' afterEach(function () { components.unregister(testComponentName) }) it('Allows registration of arbitrary component config objects, reports that they are registered, and allows unregistration', function () { components.register(testComponentName, {}) expect(components.isRegistered(testComponentName)).toBe(true) expect(components.isRegistered('other-component')).toBe(false) components.unregister(testComponentName, {}) components.unregister('nonexistent-component', {}) // No error - it's just a no-op, since it's harmless expect(components.isRegistered(testComponentName)).toBe(false) }) it('Allows registering component names that may conflict with properties on Object.prototype', function () { var prototypeProperty = 'toString' expect(components.isRegistered(prototypeProperty)).toBe(false) components.register(prototypeProperty, { ignoreCustomElementWarning: true }) expect(components.isRegistered(prototypeProperty)).toBe(true) components.unregister(prototypeProperty) expect(components.isRegistered(prototypeProperty)).toBe(false) }) it('Throws if you try to register a component that is already registered', function () { components.register(testComponentName, {}) expect(function () { components.register(testComponentName, {}) }).toThrow() }) it('Throws if you try to register a falsy value', function () { expect(function () { components.register(testComponentName, null) }).toThrow() expect(function () { components.register(testComponentName, undefined) }).toThrow() }) it('getConfig supplies config objects from the in-memory registry', function () { var expectedConfig = {}, didComplete = false components.register(testComponentName, expectedConfig) components.defaultLoader.getConfig(testComponentName, function (actualConfig) { expect(actualConfig).toBe(expectedConfig) didComplete = true }) waitsFor(function () { return didComplete }, 100) }) it('getConfig supplies null for unknown components', function () { var didComplete = false components.defaultLoader.getConfig(testComponentName, function (actualConfig) { expect(actualConfig).toBe(null) didComplete = true }) waitsFor(function () { return didComplete }, 100) }) it('Can load a template and viewmodel simultaneously', function () { // Set up a configuration in which both template and viewmodel have to be loaded asynchronously var templateProviderCallback, viewModelProviderCallback, createViewModelFunction = function () {}, domNodeArray = [], didResolveDefinition = false, config = { template: { require: 'path/templateModule' }, viewModel: { require: 'path/viewModelModule' } } this.restoreAfter(window, 'require') window.require = function (modules, callback) { expect(modules.length).toBe(1) switch (modules[0]) { case 'path/templateModule': templateProviderCallback = callback break case 'path/viewModelModule': viewModelProviderCallback = callback break default: throw new Error('Unexpected requirement for module ' + modules[0]) } } // Start the loading process testConfigObject(config, function (definition) { didResolveDefinition = true expect(definition.template).toBe(domNodeArray) expect(definition.createViewModel).toBe(createViewModelFunction) }) // Both modules start loading before either completes expect(typeof templateProviderCallback).toBe('function') expect(typeof viewModelProviderCallback).toBe('function') // When the first one completes, nothing else happens viewModelProviderCallback({ createViewModel: createViewModelFunction }) expect(didResolveDefinition).toBe(false) // When the other one completes, the definition is supplied templateProviderCallback(domNodeArray) expect(didResolveDefinition).toBe(true) }) it('Can resolve templates and viewmodels recursively', function () { // Set up a component which is a module in which: // - template is a further module which supplies markup // - viewModel is a further module which supplies a constructor mockAmdEnvironment(this, { componentmodule: { template: { require: 'templatemodule' }, viewModel: { require: 'viewmodelmodule' } }, templatemodule: '<div>Hello world</div>', viewmodelmodule: { viewModel: function (params) { this.receivedValue = params.suppliedValue } } }) // Resolve it all testConfigObject({ require: 'componentmodule' }, function (definition) { expect(definition.template.length).toBe(1) expect(definition.template[0]).toContainText('Hello world') var viewModel = definition.createViewModel({ suppliedValue: 12.3 }, null /* componentInfo */) expect(viewModel.receivedValue).toBe(12.3) }) }) it('Can be asked to resolve a template directly', function () { var templateConfig = '<span>Markup string</span><div>More</div>', didLoad = false components.defaultLoader.loadTemplate('any-component', templateConfig, function (result) { expect(result.length).toBe(2) expect(result[0].tagName).toBe('SPAN') expect(result[1].tagName).toBe('DIV') expect(result[0].innerHTML).toBe('Markup string') expect(result[1].innerHTML).toBe('More') didLoad = true }) expect(didLoad).toBe(true) }) it('Can be asked to resolve a viewmodel directly', function () { var testConstructor = function (params) { this.suppliedParams = params }, didLoad = false components.defaultLoader.loadViewModel('any-component', testConstructor, function (result) { // Result is of the form: function(params, componentInfo) { ... } var testParams = {}, resultInstance = result(testParams, null /* componentInfo */) expect(resultInstance instanceof testConstructor).toBe(true) expect(resultInstance.suppliedParams).toBe(testParams) didLoad = true }) expect(didLoad).toBe(true) }) it('Will load templates via \'loadTemplate\' on any other registered loader that precedes it', function () { var testLoader = { loadTemplate: function (componentName, templateConfig, callback) { expect(componentName).toBe(testComponentName) expect(templateConfig.customThing).toBe(123) callback(parseHtmlFragment('<div>Hello world</div>')) }, loadViewModel: function (componentName, viewModelConfig, callback) { // Fall through to other loaders callback(null) } } this.restoreAfter(components, 'loaders') components.loaders = [testLoader, components.defaultLoader] var config = { template: { customThing: 123 }, // The custom loader understands this format and will handle it viewModel: { instance: {} } // The default loader understands this format and will handle it } testConfigObject(config, function (definition) { expect(definition.template.length).toBe(1) expect(definition.template[0]).toContainText('Hello world') var viewModel = definition.createViewModel(null, null) expect(viewModel).toBe(config.viewModel.instance) }) }) it('Will load viewmodels via \'loadViewModel\' on any other registered loader that precedes it', function () { var testParams = {}, testComponentInfo = {}, testViewModel = {} var testLoader = { loadTemplate: function (componentName, templateConfig, callback) { // Fall through to other loaders callback(null) }, loadViewModel: function (componentName, viewModelConfig, callback) { expect(componentName).toBe(testComponentName) expect(viewModelConfig.customThing).toBe(456) callback(function (params, componentInfo) { expect(params).toBe(testParams) expect(componentInfo).toBe(testComponentInfo) return testViewModel }) } } this.restoreAfter(components, 'loaders') components.loaders = [testLoader, components.defaultLoader] var config = { template: '<div>Hello world</div>', // The default loader understands this format and will handle it viewModel: { customThing: 456 } // The custom loader understands this format and will handle it } testConfigObject(config, function (definition) { expect(definition.template.length).toBe(1) expect(definition.template[0]).toContainText('Hello world') var viewModel = definition.createViewModel(testParams, testComponentInfo) expect(viewModel).toBe(testViewModel) }) }) describe('Configuration formats', function () { describe('Templates are normalised to arrays of DOM nodes', function () { it('Can be configured as a DOM node array', function () { var domNodeArray = [document.createElement('div'), document.createElement('p')] testConfigObject({ template: domNodeArray }, function (definition) { expect(definition.template).toBe(domNodeArray) }) }) it('Can be configured as a document fragment', function () { var docFrag = document.createDocumentFragment(), elem = document.createElement('div') docFrag.appendChild(elem) testConfigObject({ template: docFrag }, function (definition) { expect(definition.template).toEqual([elem]) }) }) it('Can be configured as a string of markup', function () { testConfigObject({ template: '<p>Some text</p><div>More stuff</div>' }, function (definition) { // Converts to standard array-of-DOM-nodes format expect(definition.template.length).toBe(2) expect(definition.template[0].tagName).toBe('P') expect(definition.template[0]).toContainText('Some text') expect(definition.template[1].tagName).toBe('DIV') expect(definition.template[1]).toContainText('More stuff') }) }) it('Can be configured as an element ID', function () { testTemplateFromElement('<div id="my-container-elem">{0}</div>', 'my-container-elem', function (templateSourceElem) { // Doesn't destroy the input element expect(templateSourceElem.childNodes.length).toBe(2) }) }) it('Can be configured as the ID of a <script> element', function () { // Special case: the script's text should be interpreted as a markup string testTemplateFromElement('<script id="my-script-elem" type="text/html">{0}</script>', 'my-script-elem') }) it('Can be configured as the ID of a <textarea> element', function () { // Special case: the textarea's value should be interpreted as a markup string testTemplateFromElement('<textarea id="my-textarea-elem">{0}</textarea>', 'my-textarea-elem') }) it('Can be configured as the ID of a <template> element', function () { // Special case: the template's .content should be the source of nodes document.createElement('template') // Polyfill needed by IE <= 8 testTemplateFromElement('<template id="my-template-elem">{0}</template>', 'my-template-elem') }) it('Can be configured as a regular element instance', function () { testTemplateFromElement('<div>{0}</div>', /* elementId */ null, function (templateSourceElem) { // Doesn't destroy the input element expect(templateSourceElem.childNodes.length).toBe(2) }) }) it('Can be configured as a <script> element instance', function () { // Special case: the script's text should be interpreted as a markup string testTemplateFromElement('<script type="text/html">{0}</script>', /* elementId */ null) }) it('Can be configured as a <textarea> element instance', function () { // Special case: the textarea's value should be interpreted as a markup string testTemplateFromElement('<textarea>{0}</textarea>', /* elementId */ null) }) it('Can be configured as a <template> element instance', function () { // Special case: the template's .content should be the source of nodes document.createElement('template') // Polyfill needed by IE <= 8 testTemplateFromElement('<template>{0}</template>', /* elementId */ null) }) it('Can be configured as an AMD module whose value is a DOM node array', function () { var domNodeArray = [document.createElement('div'), document.createElement('p')] mockAmdEnvironment(this, { 'some/module/path': domNodeArray }) testConfigObject({ template: { require: 'some/module/path' } }, function (definition) { expect(definition.template).toBe(domNodeArray) }) }) it('Can be configured as an AMD module whose value is a document fragment', function () { var docFrag = document.createDocumentFragment(), elem = document.createElement('div') docFrag.appendChild(elem) mockAmdEnvironment(this, { 'some/module/path': docFrag }) testConfigObject({ template: { require: 'some/module/path' } }, function (definition) { expect(definition.template).toEqual([elem]) }) }) it('Can be configured as an AMD module whose value is markup', function () { mockAmdEnvironment(this, { 'some/module/path': '<div>Hello world</div><p>The end</p>' }) testConfigObject({ template: { require: 'some/module/path' } }, function (definition) { expect(definition.template.length).toBe(2) expect(definition.template[0].tagName).toBe('DIV') expect(definition.template[0]).toContainText('Hello world') expect(definition.template[1].tagName).toBe('P') expect(definition.template[1]).toContainText('The end') }) }) // In the future we might also support arbitrary objects acting as component templates, // possibly with a config syntax like "template: { custom: arbitraryObject }", which // would be passed through (without normalisation) to a custom template engine. }) describe('Viewmodels', function () { it('Can be configured as a createViewModel function', function () { var createViewModel = function () {} testConfigObject({ viewModel: { createViewModel: createViewModel } }, function (definition) { expect(definition.createViewModel).toBe(createViewModel) }) }) it('Can be configured as a constructor function', function () { var myConstructor = function (params) { this.receivedValue = params.suppliedValue } testConfigObject({ viewModel: myConstructor }, function (definition) { var viewModel = definition.createViewModel({ suppliedValue: 123 }, null /* componentInfo */) expect(viewModel.receivedValue).toBe(123) }) }) it('Can be configured as an object instance', function () { var myInstance = {} testConfigObject({ viewModel: { instance: myInstance } }, function (definition) { var viewModel = definition.createViewModel(null /* params */, null /* componentInfo */) expect(viewModel).toBe(myInstance) }) }) it('Can be configured as an AMD module that supplies a createViewModel factory', function () { var createViewModel = function () {} mockAmdEnvironment(this, { 'some/module/path': { createViewModel: createViewModel } }) testConfigObject({ viewModel: { require: 'some/module/path' } }, function (definition) { expect(definition.createViewModel).toBe(createViewModel) }) }) it('Can be configured as an AMD module that is a constructor function', function () { var myConstructor = function (params) { this.receivedValue = params.suppliedValue } mockAmdEnvironment(this, { 'some/module/path': myConstructor }) testConfigObject({ viewModel: { require: 'some/module/path' } }, function (definition) { var viewModel = definition.createViewModel({ suppliedValue: 234 }, null /* componentInfo */) expect(viewModel.receivedValue).toBe(234) }) }) it('Can be configured as an AMD module that supplies a viewmodel configuration', function () { var myConstructor = function (params) { this.receivedValue = params.suppliedValue } mockAmdEnvironment(this, { 'some/module/path': { viewModel: myConstructor } }) testConfigObject({ viewModel: { require: 'some/module/path' } }, function (definition) { var viewModel = definition.createViewModel({ suppliedValue: 345 }, null /* componentInfo */) expect(viewModel.receivedValue).toBe(345) }) }) }) describe('Combined viewmodel/templates', function () { it('Can be configured as an AMD module', function () { var moduleObject = { // The module can have any values that are valid as the input to the whole resolution process template: [], viewModel: function (params) { this.receivedValue = params.suppliedValue } } mockAmdEnvironment(this, { 'some/module/path': moduleObject }) testConfigObject({ require: 'some/module/path' }, function (definition) { expect(definition.template).toBe(moduleObject.template) var viewModel = definition.createViewModel({ suppliedValue: 567 }, null /* componentInfo */) expect(viewModel.receivedValue).toBe(567) }) }) }) }) function testConfigObject (configObject, assertionCallback) { components.unregister(testComponentName) components.register(testComponentName, configObject) var didComplete = false components.get(testComponentName, function (definition) { assertionCallback(definition) didComplete = true }) waitsFor(function () { return didComplete }, 1000) } function testTemplateFromElement (wrapperMarkup, elementId, extraAssertsCallback) { var testElem = document.createElement('div') document.body.appendChild(testElem) // Needed so it can be found by ID, and because IE<=8 won't parse its .innerHTML properly otherwise // The 'ignored' prefix is needed for IE <= 8, which silently strips any <script> elements // that are not preceded by something else. Nobody knows why. testElem.innerHTML = 'ignored' + wrapperMarkup.replace('{0}', '<p>Some text</p><div>More stuff</div>') // If an element ID is supplied, use that (we're testing selection by ID) // otherwise use the element instance itself (we're testing explicitly-supplied element instances) var templateElem = testElem.childNodes[1], templateConfigValue = elementId || templateElem testConfigObject({ template: { element: templateConfigValue } }, function (definition) { // Converts to standard array-of-DOM-nodes format expect(definition.template.length).toBe(2) expect(definition.template[0].tagName).toBe('P') expect(definition.template[0]).toContainText('Some text') expect(definition.template[1].tagName).toBe('DIV') expect(definition.template[1]).toContainText('More stuff') if (extraAssertsCallback) { extraAssertsCallback(templateElem) } if (testElem.parentNode) { testElem.parentNode.removeChild(testElem) } }) } function mockAmdEnvironment (spec, definedModules) { spec.restoreAfter(window, 'require') window.require = function (modules, callback) { expect(modules.length).toBe(1) if (modules[0] in definedModules) { setTimeout(function () { callback(definedModules[modules[0]]) }, 20) } else { throw new Error('Undefined module: ' + modules[0]) } } } })
the_stack
import * as React from "react"; import { Trans, t } from "@lingui/macro"; import { withI18n } from "@lingui/react"; import { RequestUtil } from "mesosphere-shared-reactjs"; import { Modal } from "reactjs-components"; import { Link } from "react-router"; import ModalHeading from "#SRC/js/components/modals/ModalHeading"; import { generatePrintableRSAKeypair } from "#SRC/js/utils/crypto"; import * as EventTypes from "../constants/EventTypes"; import ServiceAccountForm from "./ServiceAccountForm"; import getACLServiceAccountsStore from "../stores/ACLServiceAccountsStore"; import { ServiceAccountFormData, Errors, getErrors, requiredFieldPresent, hasErrors, defaultFormData, validUid, validSecretPath, } from "../../../utils/ServiceAccountFormUtil"; const ACLServiceAccountsStore = getACLServiceAccountsStore(); const { ACL_SERVICE_ACCOUNT_CREATE_SUCCESS, ACL_SERVICE_ACCOUNT_DELETE_ERROR, ACL_SERVICE_ACCOUNT_CREATE_ERROR, ACL_SERVICE_ACCOUNT_UPDATE_SUCCESS, ACL_SERVICE_ACCOUNT_UPDATE_ERROR, } = EventTypes; interface ServiceAccountFormModalProps { account?: ServiceAccountFormData; onClose: () => void; onSubmit?: (data: ServiceAccountFormData) => void; open: boolean; i18n: any; } interface ServiceAccountFormModalState { // Disabled while request active pendingRequest: boolean; // Indicates service account creation succeeded but secret creation failed and then service account deletion failed failedToComplete: boolean; // Once the user has typed into the secret id, use that value. Otherwise, it will be automatically derived from the account id manuallyEnteredSecretId: boolean; formData: ServiceAccountFormData; errors: Errors; } class ServiceAccountFormModal extends React.Component< ServiceAccountFormModalProps > { state: ServiceAccountFormModalState = { pendingRequest: false, failedToComplete: false, formData: this.getFormDataFromAccount(this.props.account) || defaultFormData(), manuallyEnteredSecretId: false, errors: {}, }; public componentDidMount() { ACLServiceAccountsStore.addChangeListener( ACL_SERVICE_ACCOUNT_CREATE_SUCCESS, this.onAclStoreCreateSuccess ); ACLServiceAccountsStore.addChangeListener( ACL_SERVICE_ACCOUNT_DELETE_ERROR, this.onAclStoreDeleteError ); ACLServiceAccountsStore.addChangeListener( ACL_SERVICE_ACCOUNT_CREATE_ERROR, this.onAclStoreCreateError ); ACLServiceAccountsStore.addChangeListener( ACL_SERVICE_ACCOUNT_UPDATE_ERROR, this.onAclStoreUpdateError ); ACLServiceAccountsStore.addChangeListener( ACL_SERVICE_ACCOUNT_UPDATE_SUCCESS, this.onAclStoreUpdateSuccess ); } public componentWillUnmount() { ACLServiceAccountsStore.removeChangeListener( ACL_SERVICE_ACCOUNT_CREATE_SUCCESS, this.onAclStoreCreateSuccess ); ACLServiceAccountsStore.addChangeListener( ACL_SERVICE_ACCOUNT_DELETE_ERROR, this.onAclStoreDeleteError ); ACLServiceAccountsStore.removeChangeListener( ACL_SERVICE_ACCOUNT_CREATE_ERROR, this.onAclStoreCreateError ); ACLServiceAccountsStore.removeChangeListener( ACL_SERVICE_ACCOUNT_UPDATE_ERROR, this.onAclStoreUpdateError ); ACLServiceAccountsStore.removeChangeListener( ACL_SERVICE_ACCOUNT_UPDATE_SUCCESS, this.onAclStoreUpdateSuccess ); } public prefillSecretIdMaybe( data: ServiceAccountFormData ): ServiceAccountFormData { if ( !this.props.account && data.uid && !this.state.manuallyEnteredSecretId ) { data.secret_path = `${data.uid.trim()}-secret`; } return data; } public getFormDataFromAccount(account: any): ServiceAccountFormData | null { if (account != null) { return { description: account.description, }; } return null; } // If the service account was created, but the create secret has failed, the // action will delete the created account. If the delete fails, the modal will // be in a deadend, failed state (failedToComplete) public createOrRollback(): void { const { formData } = this.state; if (formData.key_method === "auto-generate") { generatePrintableRSAKeypair().then(([privateKey, publicKey]) => { formData.public_key = publicKey; formData.private_key = privateKey; ACLServiceAccountsStore.add(formData); }); return; } ACLServiceAccountsStore.add(formData); } public onAclStoreCreateSuccess = (): void => { this.setState({ pendingRequest: false, errors: {}, formData: defaultFormData(), failedToComplete: false, manuallyEnteredSecretId: false, }); this.props.onClose(); }; public onAclStoreDeleteError = (): void => { const prevFormData = this.state.formData; this.setState({ pendingRequest: false, formData: defaultFormData(), errors: { unanchored: ( <div> <Trans render="p"> The service account{" "} <Link to={`/organization/service-accounts/${prevFormData.uid}`}> {prevFormData.uid} </Link>{" "} was created but we were not able to also save the private key as a secret. </Trans> <Trans render="p"> Please delete this service account and try again or use the CLI. </Trans> </div> ), }, }); }; public onAclStoreCreateError = ( errorMsg: string, _: any, xhr: XMLHttpRequest ): void => { const response = RequestUtil.parseResponseBody(xhr); let errors = getErrors(response.code, errorMsg); if (Object.keys(errors).length === 0) { errors = errorMsg.toLowerCase().indexOf("secret") >= 0 ? { secret_path: errorMsg } : { unanchored: errorMsg }; } this.setState({ pendingRequest: false, errors, }); }; public onAclStoreUpdateSuccess = (): void => { this.setState({ pendingRequest: false, errors: {}, }); this.props.onClose(); }; public onAclStoreUpdateError = (errorMsg: string): void => { this.setState({ pendingRequest: false, errors: { description: errorMsg, }, }); }; public handleServiceAccountClose = (): void => { const { account, onClose } = this.props; this.setState({ errors: {}, failedToComplete: false, pendingRequest: false, manuallyEnteredSecretId: false, formData: this.getFormDataFromAccount(account) || defaultFormData(), }); onClose(); }; public handleSubmit = (): void => { const { formData, failedToComplete, pendingRequest } = this.state; if (pendingRequest) { return; } if (failedToComplete) { this.handleServiceAccountClose(); } const validationErrors = this.validateFormData(); if (hasErrors(validationErrors)) { this.setState({ errors: validationErrors, }); return; } this.setState({ pendingRequest: true }); if (this.props.account == null) { this.createOrRollback(); } else if (this.props.onSubmit) { this.props.onSubmit(formData); } }; public getHeader() { const { account } = this.props; const title = account != null ? ( <Trans>Edit Service Account</Trans> ) : ( <Trans>Create Service Account</Trans> ); return <ModalHeading>{title}</ModalHeading>; } public handleFormChange = (e: React.FormEvent<HTMLFormElement>): void => { const { name, value } = e.target as HTMLInputElement; const { formData } = this.state; const newFormData = { ...formData, [name]: value, }; if (name === "secret_path") { this.setState({ manuallyEnteredSecretId: true, formData: newFormData, }); } else { this.setState({ formData: this.prefillSecretIdMaybe(newFormData), }); } }; public getModalContent(): React.ReactNode { const { formData, errors } = this.state; const { account } = this.props; return ( <ServiceAccountForm formData={formData} onChange={this.handleFormChange} isEdit={account != null} errors={errors} /> ); } public getCtaText(): React.ReactNode { const { account } = this.props; const { failedToComplete, pendingRequest } = this.state; if (failedToComplete) { return <Trans>OK</Trans>; } if (account == null) { // Creating new account if (pendingRequest) { return <Trans>Creating...</Trans>; } return <Trans>Create Service Account</Trans>; } // Editing account if (pendingRequest) { return <Trans>Saving...</Trans>; } return <Trans>Save</Trans>; } public getFooter() { const { failedToComplete, pendingRequest } = this.state; return ( <div className="flush-bottom flex flex-direction-top-to-bottom flex-align-items-stretch-screen-small flex-direction-left-to-right-screen-small flex-justify-items-space-between-screen-medium"> {!failedToComplete && ( <button className="button button-primary-link flush-left" onClick={this.handleServiceAccountClose} > <Trans>Cancel</Trans> </button> )} <button className="button button-primary" onClick={this.handleSubmit} disabled={pendingRequest} > {this.getCtaText()} </button> </div> ); } public validateFormData(): Errors { const { formData } = this.state; const { account, i18n } = this.props; const missingMessage = i18n._(t`Field cannot be empty.`); const invalidMessage = i18n._(t`Invalid ID`); const errors: Errors = {}; if (account == null) { if (!requiredFieldPresent("uid", formData)) { errors.uid = missingMessage; } else { if (!validUid(formData.uid)) { errors.uid = invalidMessage; } } if (formData.key_method === "auto-generate") { if (!requiredFieldPresent("secret_path", formData)) { errors.secret_path = missingMessage; } else { if (!validSecretPath(formData.secret_path)) { errors.secret_path = invalidMessage; } } } else { if (!requiredFieldPresent("public_key", formData)) { errors.public_key = missingMessage; } } } return errors; } public render() { const { open } = this.props; return ( <Modal open={open} onClose={this.handleServiceAccountClose} footer={this.getFooter()} showFooter={true} modalClass="modal" header={this.getHeader()} showHeader={true} > {this.getModalContent()} </Modal> ); } } export default withI18n()(ServiceAccountFormModal);
the_stack
import * as React from 'react'; import { useCallback, useEffect, useState } from 'react'; import { ConcordId, ConcordKey, RequestError } from '../../../api/common'; import { Button, Container, Divider, Form, Loader, Menu, Table } from 'semantic-ui-react'; import { FindUserField2, RequestErrorActivity } from '../../organisms'; import { UserEntry } from '../../../api/user'; import { TeamRoleDropdown } from '../../molecules'; import { addUsers as apiAddUsers, listUsers as apiListUsers, MemberType, NewTeamUserEntry, TeamRole, TeamUserEntry } from '../../../api/org/team'; interface Entry extends NewTeamUserEntry { added?: boolean; deleted?: boolean; updated?: boolean; } interface LdapGroupRole { ldapGroup: string; role: TeamRole; } interface LdapEntry extends TeamUserEntry { rolesFromLdapGroup: LdapGroupRole[]; } interface Props { orgName: ConcordKey; teamName: ConcordKey; } const renderUser = (e: NewTeamUserEntry) => { if (!e.userDomain) { return e.displayName ? `${e.displayName} (${e.username})` : e.username; } return e.displayName ? `${e.displayName} (${e.username}@${e.userDomain})` : `${e.username}@${e.userDomain}`; }; const renderUserLdapGroups = (e: LdapEntry, rowId: number) => { return e.rolesFromLdapGroup.map((r, rIdx) => ( <Table.Row key={rIdx}> {(e.rolesFromLdapGroup.length <= 1 || rIdx === 0) && ( <Table.Cell rowSpan={e.rolesFromLdapGroup.length}>{e.username}</Table.Cell> )} <Table.Cell>{r.ldapGroup}</Table.Cell> <Table.Cell>{r.role}</Table.Cell> </Table.Row> )); }; export default ({ orgName, teamName }: Props) => { const [loading, setLoading] = useState(false); const [editMode, setEditMode] = useState(false); const [submitting, setSubmitting] = useState(false); const [singleUsers, setSingleUsers] = useState<Entry[]>([]); const [ldapUsers, setLdapUsers] = useState<LdapEntry[]>([]); const [error, setError] = useState<RequestError>(); const [dirty, setDirty] = useState(false); const load = useCallback(async () => { try { setLoading(true); setError(undefined); let result = (await apiListUsers(orgName, teamName)).map((r) => ({ ...r })); setSingleUsers( result.filter((r) => r.memberType === MemberType.SINGLE).map((r) => ({ ...r })) ); let aggregatedUsers = new Map<ConcordId, LdapEntry>(); result .filter((r) => r.memberType === MemberType.LDAP_GROUP) .forEach((r) => { if (aggregatedUsers.has(r.userId)) { let u = aggregatedUsers.get(r.userId); if (u !== undefined) { u.rolesFromLdapGroup.push({ ldapGroup: r.ldapGroupSource || 'not found', role: r.role }); } } else { aggregatedUsers.set(r.userId, { ...r, rolesFromLdapGroup: [ { ldapGroup: r.ldapGroupSource || 'not found', role: r.role } ] }); } }); setLdapUsers(Array.from(aggregatedUsers, ([k, v]) => v)); } catch (e) { setError(e); } finally { setLoading(false); setDirty(false); } }, [orgName, teamName]); // initial load useEffect(() => { load(); }, [load]); // set dirty to true on any changes useEffect(() => { setDirty(!!singleUsers.find((e) => e.added || e.deleted || e.updated)); }, [singleUsers]); const cancel = () => { setEditMode(false); load(); }; const addMember = (u: UserEntry) => { setSingleUsers((prev) => { const e: Entry = { added: true, userId: u.id, role: TeamRole.MEMBER, username: u.name, userDomain: u.domain, displayName: u.displayName }; return [e, ...prev]; }); }; const deleteMember = (idx: number) => { setSingleUsers((prev) => { let e = prev[idx]; if (e.added) { let result = [...prev]; result.splice(idx, 1); return result; } e.deleted = true; e.updated = false; return [...prev]; }); }; const undoMember = (idx: number) => { setSingleUsers((prev) => { prev[idx].deleted = false; return [...prev]; }); }; const updateRole = (idx: number, role: TeamRole) => { setSingleUsers((prev) => { let e = prev[idx]; e.role = role; if (!e.deleted && !e.added) { e.updated = true; } return [...prev]; }); }; const save = useCallback(async () => { const sanitizedData = singleUsers .filter((e) => !e.deleted) .map((e) => ({ userId: e.userId, role: e.role, memberType: MemberType.SINGLE })); try { setSubmitting(true); await apiAddUsers(orgName, teamName, true, sanitizedData); } catch (e) { setError(e); return; } finally { setSubmitting(false); } load(); }, [orgName, teamName, singleUsers, load]); if (loading) { return <Loader active={true} />; } return ( <> {error && <RequestErrorActivity error={error} />} <Menu secondary={true} widths={3}> {editMode && ( <Menu.Item disabled={submitting}> <Container fluid={true} textAlign="left"> <Form> <Form.Field> <FindUserField2 placeholder="Add a team member" onSelect={(u) => addMember(u)} /> </Form.Field> </Form> </Container> </Menu.Item> )} <Menu.Item position="right"> <Container textAlign="right"> {editMode && ( <> <Button primary={true} content="Save changes" disabled={!dirty} loading={loading || submitting} onClick={(ev) => save()} /> <Button basic={true} negative={true} icon="cancel" content="Cancel" disabled={loading || submitting} onClick={() => cancel()} /> </> )} {!editMode && ( <Button icon="edit" content="Edit" onClick={() => setEditMode(true)} /> )} </Container> </Menu.Item> </Menu> {singleUsers.length === 0 && <h3>No team members.</h3>} {singleUsers.length > 0 && ( <Table> <Table.Header> <Table.Row> <Table.HeaderCell>Username</Table.HeaderCell> <Table.HeaderCell collapsing={true}>Type</Table.HeaderCell> <Table.HeaderCell collapsing={true}>Role</Table.HeaderCell> {editMode && <Table.HeaderCell collapsing={true} />} </Table.Row> </Table.Header> <Table.Body> {singleUsers.map((e, idx) => ( <Table.Row key={idx} negative={e.deleted} positive={e.added} warning={e.updated}> <Table.Cell>{renderUser(e)}</Table.Cell> <Table.Cell>{e.userType}</Table.Cell> <Table.Cell> {editMode ? ( <TeamRoleDropdown value={e.role} disabled={submitting} onRoleChange={(value) => updateRole(idx, value)} /> ) : ( e.role )} </Table.Cell> {editMode && ( <Table.Cell> <Button basic={true} negative={!e.deleted} icon={e.deleted ? 'undo' : 'delete'} disabled={submitting} onClick={() => e.deleted ? undoMember(idx) : deleteMember(idx) } /> </Table.Cell> )} </Table.Row> ))} </Table.Body> </Table> )} {ldapUsers.length > 0 && ( <> <Divider horizontal>LDAP Group Members</Divider> <Table selectable> <Table.Header> <Table.Row> <Table.HeaderCell collapsing={true}>Username</Table.HeaderCell> <Table.HeaderCell collapsing={true}>Source</Table.HeaderCell> <Table.HeaderCell collapsing={true}>Role</Table.HeaderCell> </Table.Row> </Table.Header> <Table.Body> {ldapUsers.map((e, idx) => renderUserLdapGroups(e, idx))} </Table.Body> </Table> </> )} </> ); };
the_stack
import { GraphQLResolveInfo, GraphQLSchema } from 'graphql' import { IResolvers } from 'graphql-tools/dist/Interfaces' import { Options } from 'graphql-binding' import { makePrismaBindingClass, BasePrismaOptions } from 'prisma-binding' export interface Query { phoneNumbers: <T = PhoneNumber[]>(args: { where?: PhoneNumberWhereInput, orderBy?: PhoneNumberOrderByInput, skip?: Int, after?: String, before?: String, first?: Int, last?: Int }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> , phoneNumber: <T = PhoneNumber | null>(args: { where: PhoneNumberWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> , phoneNumbersConnection: <T = PhoneNumberConnection>(args: { where?: PhoneNumberWhereInput, orderBy?: PhoneNumberOrderByInput, skip?: Int, after?: String, before?: String, first?: Int, last?: Int }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> , node: <T = Node | null>(args: { id: ID_Output }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> } export interface Mutation { createPhoneNumber: <T = PhoneNumber>(args: { data: PhoneNumberCreateInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> , updatePhoneNumber: <T = PhoneNumber | null>(args: { data: PhoneNumberUpdateInput, where: PhoneNumberWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> , deletePhoneNumber: <T = PhoneNumber | null>(args: { where: PhoneNumberWhereUniqueInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> , upsertPhoneNumber: <T = PhoneNumber>(args: { where: PhoneNumberWhereUniqueInput, create: PhoneNumberCreateInput, update: PhoneNumberUpdateInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> , updateManyPhoneNumbers: <T = BatchPayload>(args: { data: PhoneNumberUpdateInput, where?: PhoneNumberWhereInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> , deleteManyPhoneNumbers: <T = BatchPayload>(args: { where?: PhoneNumberWhereInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<T> } export interface Subscription { phoneNumber: <T = PhoneNumberSubscriptionPayload | null>(args: { where?: PhoneNumberSubscriptionWhereInput }, info?: GraphQLResolveInfo | string, options?: Options) => Promise<AsyncIterator<T>> } export interface Exists { PhoneNumber: (where?: PhoneNumberWhereInput) => Promise<boolean> } export interface Prisma { query: Query mutation: Mutation subscription: Subscription exists: Exists request: <T = any>(query: string, variables?: {[key: string]: any}) => Promise<T> delegate(operation: 'query' | 'mutation', fieldName: string, args: { [key: string]: any; }, infoOrQuery?: GraphQLResolveInfo | string, options?: Options): Promise<any>; delegateSubscription(fieldName: string, args?: { [key: string]: any; }, infoOrQuery?: GraphQLResolveInfo | string, options?: Options): Promise<AsyncIterator<any>>; getAbstractResolvers(filterSchema?: GraphQLSchema | string): IResolvers; } export interface BindingConstructor<T> { new(options: BasePrismaOptions): T } /** * Type Defs */ const typeDefs = `type AggregatePhoneNumber { count: Int! } type BatchPayload { """The number of nodes that have been affected by the Batch operation.""" count: Long! } scalar DateTime """ The \`Long\` scalar type represents non-fractional signed whole numeric values. Long can represent values between -(2^63) and 2^63 - 1. """ scalar Long type Mutation { createPhoneNumber(data: PhoneNumberCreateInput!): PhoneNumber! updatePhoneNumber(data: PhoneNumberUpdateInput!, where: PhoneNumberWhereUniqueInput!): PhoneNumber deletePhoneNumber(where: PhoneNumberWhereUniqueInput!): PhoneNumber upsertPhoneNumber(where: PhoneNumberWhereUniqueInput!, create: PhoneNumberCreateInput!, update: PhoneNumberUpdateInput!): PhoneNumber! updateManyPhoneNumbers(data: PhoneNumberUpdateInput!, where: PhoneNumberWhereInput): BatchPayload! deleteManyPhoneNumbers(where: PhoneNumberWhereInput): BatchPayload! } enum MutationType { CREATED UPDATED DELETED } """An object with an ID""" interface Node { """The id of the object.""" id: ID! } """Information about pagination in a connection.""" type PageInfo { """When paginating forwards, are there more items?""" hasNextPage: Boolean! """When paginating backwards, are there more items?""" hasPreviousPage: Boolean! """When paginating backwards, the cursor to continue.""" startCursor: String """When paginating forwards, the cursor to continue.""" endCursor: String } type PhoneNumber { hashedPhoneNumber: String! address: String! createdAt: DateTime! updatedAt: DateTime! } """A connection to a list of items.""" type PhoneNumberConnection { """Information to aid in pagination.""" pageInfo: PageInfo! """A list of edges.""" edges: [PhoneNumberEdge]! aggregate: AggregatePhoneNumber! } input PhoneNumberCreateInput { hashedPhoneNumber: String! address: String! } """An edge in a connection.""" type PhoneNumberEdge { """The item at the end of the edge.""" node: PhoneNumber! """A cursor for use in pagination.""" cursor: String! } enum PhoneNumberOrderByInput { hashedPhoneNumber_ASC hashedPhoneNumber_DESC address_ASC address_DESC createdAt_ASC createdAt_DESC updatedAt_ASC updatedAt_DESC id_ASC id_DESC } type PhoneNumberPreviousValues { hashedPhoneNumber: String! address: String! createdAt: DateTime! updatedAt: DateTime! } type PhoneNumberSubscriptionPayload { mutation: MutationType! node: PhoneNumber updatedFields: [String!] previousValues: PhoneNumberPreviousValues } input PhoneNumberSubscriptionWhereInput { """Logical AND on all given filters.""" AND: [PhoneNumberSubscriptionWhereInput!] """Logical OR on all given filters.""" OR: [PhoneNumberSubscriptionWhereInput!] """Logical NOT on all given filters combined by AND.""" NOT: [PhoneNumberSubscriptionWhereInput!] """ The subscription event gets dispatched when it's listed in mutation_in """ mutation_in: [MutationType!] """ The subscription event gets only dispatched when one of the updated fields names is included in this list """ updatedFields_contains: String """ The subscription event gets only dispatched when all of the field names included in this list have been updated """ updatedFields_contains_every: [String!] """ The subscription event gets only dispatched when some of the field names included in this list have been updated """ updatedFields_contains_some: [String!] node: PhoneNumberWhereInput } input PhoneNumberUpdateInput { hashedPhoneNumber: String address: String } input PhoneNumberWhereInput { """Logical AND on all given filters.""" AND: [PhoneNumberWhereInput!] """Logical OR on all given filters.""" OR: [PhoneNumberWhereInput!] """Logical NOT on all given filters combined by AND.""" NOT: [PhoneNumberWhereInput!] hashedPhoneNumber: String """All values that are not equal to given value.""" hashedPhoneNumber_not: String """All values that are contained in given list.""" hashedPhoneNumber_in: [String!] """All values that are not contained in given list.""" hashedPhoneNumber_not_in: [String!] """All values less than the given value.""" hashedPhoneNumber_lt: String """All values less than or equal the given value.""" hashedPhoneNumber_lte: String """All values greater than the given value.""" hashedPhoneNumber_gt: String """All values greater than or equal the given value.""" hashedPhoneNumber_gte: String """All values containing the given string.""" hashedPhoneNumber_contains: String """All values not containing the given string.""" hashedPhoneNumber_not_contains: String """All values starting with the given string.""" hashedPhoneNumber_starts_with: String """All values not starting with the given string.""" hashedPhoneNumber_not_starts_with: String """All values ending with the given string.""" hashedPhoneNumber_ends_with: String """All values not ending with the given string.""" hashedPhoneNumber_not_ends_with: String address: String """All values that are not equal to given value.""" address_not: String """All values that are contained in given list.""" address_in: [String!] """All values that are not contained in given list.""" address_not_in: [String!] """All values less than the given value.""" address_lt: String """All values less than or equal the given value.""" address_lte: String """All values greater than the given value.""" address_gt: String """All values greater than or equal the given value.""" address_gte: String """All values containing the given string.""" address_contains: String """All values not containing the given string.""" address_not_contains: String """All values starting with the given string.""" address_starts_with: String """All values not starting with the given string.""" address_not_starts_with: String """All values ending with the given string.""" address_ends_with: String """All values not ending with the given string.""" address_not_ends_with: String createdAt: DateTime """All values that are not equal to given value.""" createdAt_not: DateTime """All values that are contained in given list.""" createdAt_in: [DateTime!] """All values that are not contained in given list.""" createdAt_not_in: [DateTime!] """All values less than the given value.""" createdAt_lt: DateTime """All values less than or equal the given value.""" createdAt_lte: DateTime """All values greater than the given value.""" createdAt_gt: DateTime """All values greater than or equal the given value.""" createdAt_gte: DateTime updatedAt: DateTime """All values that are not equal to given value.""" updatedAt_not: DateTime """All values that are contained in given list.""" updatedAt_in: [DateTime!] """All values that are not contained in given list.""" updatedAt_not_in: [DateTime!] """All values less than the given value.""" updatedAt_lt: DateTime """All values less than or equal the given value.""" updatedAt_lte: DateTime """All values greater than the given value.""" updatedAt_gt: DateTime """All values greater than or equal the given value.""" updatedAt_gte: DateTime } input PhoneNumberWhereUniqueInput { hashedPhoneNumber: String } type Query { phoneNumbers(where: PhoneNumberWhereInput, orderBy: PhoneNumberOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): [PhoneNumber]! phoneNumber(where: PhoneNumberWhereUniqueInput!): PhoneNumber phoneNumbersConnection(where: PhoneNumberWhereInput, orderBy: PhoneNumberOrderByInput, skip: Int, after: String, before: String, first: Int, last: Int): PhoneNumberConnection! """Fetches an object given its ID""" node( """The ID of an object""" id: ID! ): Node } type Subscription { phoneNumber(where: PhoneNumberSubscriptionWhereInput): PhoneNumberSubscriptionPayload } ` export const Prisma = makePrismaBindingClass<BindingConstructor<Prisma>>({typeDefs}) /** * Types */ export type PhoneNumberOrderByInput = 'hashedPhoneNumber_ASC' | 'hashedPhoneNumber_DESC' | 'address_ASC' | 'address_DESC' | 'createdAt_ASC' | 'createdAt_DESC' | 'updatedAt_ASC' | 'updatedAt_DESC' | 'id_ASC' | 'id_DESC' export type MutationType = 'CREATED' | 'UPDATED' | 'DELETED' export interface PhoneNumberCreateInput { hashedPhoneNumber: String address: String } export interface PhoneNumberWhereUniqueInput { hashedPhoneNumber?: String } export interface PhoneNumberUpdateInput { hashedPhoneNumber?: String address?: String } export interface PhoneNumberSubscriptionWhereInput { AND?: PhoneNumberSubscriptionWhereInput[] | PhoneNumberSubscriptionWhereInput OR?: PhoneNumberSubscriptionWhereInput[] | PhoneNumberSubscriptionWhereInput NOT?: PhoneNumberSubscriptionWhereInput[] | PhoneNumberSubscriptionWhereInput mutation_in?: MutationType[] | MutationType updatedFields_contains?: String updatedFields_contains_every?: String[] | String updatedFields_contains_some?: String[] | String node?: PhoneNumberWhereInput } export interface PhoneNumberWhereInput { AND?: PhoneNumberWhereInput[] | PhoneNumberWhereInput OR?: PhoneNumberWhereInput[] | PhoneNumberWhereInput NOT?: PhoneNumberWhereInput[] | PhoneNumberWhereInput hashedPhoneNumber?: String hashedPhoneNumber_not?: String hashedPhoneNumber_in?: String[] | String hashedPhoneNumber_not_in?: String[] | String hashedPhoneNumber_lt?: String hashedPhoneNumber_lte?: String hashedPhoneNumber_gt?: String hashedPhoneNumber_gte?: String hashedPhoneNumber_contains?: String hashedPhoneNumber_not_contains?: String hashedPhoneNumber_starts_with?: String hashedPhoneNumber_not_starts_with?: String hashedPhoneNumber_ends_with?: String hashedPhoneNumber_not_ends_with?: String address?: String address_not?: String address_in?: String[] | String address_not_in?: String[] | String address_lt?: String address_lte?: String address_gt?: String address_gte?: String address_contains?: String address_not_contains?: String address_starts_with?: String address_not_starts_with?: String address_ends_with?: String address_not_ends_with?: String createdAt?: DateTime createdAt_not?: DateTime createdAt_in?: DateTime[] | DateTime createdAt_not_in?: DateTime[] | DateTime createdAt_lt?: DateTime createdAt_lte?: DateTime createdAt_gt?: DateTime createdAt_gte?: DateTime updatedAt?: DateTime updatedAt_not?: DateTime updatedAt_in?: DateTime[] | DateTime updatedAt_not_in?: DateTime[] | DateTime updatedAt_lt?: DateTime updatedAt_lte?: DateTime updatedAt_gt?: DateTime updatedAt_gte?: DateTime } /* * An object with an ID */ export interface Node { id: ID_Output } export interface AggregatePhoneNumber { count: Int } export interface PhoneNumber { hashedPhoneNumber: String address: String createdAt: DateTime updatedAt: DateTime } export interface PhoneNumberPreviousValues { hashedPhoneNumber: String address: String createdAt: DateTime updatedAt: DateTime } export interface PhoneNumberSubscriptionPayload { mutation: MutationType node?: PhoneNumber updatedFields?: String[] previousValues?: PhoneNumberPreviousValues } /* * An edge in a connection. */ export interface PhoneNumberEdge { node: PhoneNumber cursor: String } /* * A connection to a list of items. */ export interface PhoneNumberConnection { pageInfo: PageInfo edges: PhoneNumberEdge[] aggregate: AggregatePhoneNumber } /* * Information about pagination in a connection. */ export interface PageInfo { hasNextPage: Boolean hasPreviousPage: Boolean startCursor?: String endCursor?: String } export interface BatchPayload { count: Long } /* The `Boolean` scalar type represents `true` or `false`. */ export type Boolean = boolean /* The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text. */ export type String = string /* The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `"4"`) or integer (such as `4`) input value will be accepted as an ID. */ export type ID_Input = string | number export type ID_Output = string export type DateTime = Date | string /* The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1. */ export type Int = number /* The `Long` scalar type represents non-fractional signed whole numeric values. Long can represent values between -(2^63) and 2^63 - 1. */ export type Long = string
the_stack
interface AVAudio3DAngularOrientation { yaw: number; pitch: number; roll: number; } declare var AVAudio3DAngularOrientation: interop.StructType<AVAudio3DAngularOrientation>; interface AVAudio3DMixing extends NSObjectProtocol { obstruction: number; occlusion: number; pointSourceInHeadMode: AVAudio3DMixingPointSourceInHeadMode; position: AVAudio3DPoint; rate: number; renderingAlgorithm: AVAudio3DMixingRenderingAlgorithm; reverbBlend: number; sourceMode: AVAudio3DMixingSourceMode; } declare var AVAudio3DMixing: { prototype: AVAudio3DMixing; }; declare const enum AVAudio3DMixingPointSourceInHeadMode { Mono = 0, Bypass = 1 } declare const enum AVAudio3DMixingRenderingAlgorithm { EqualPowerPanning = 0, SphericalHead = 1, HRTF = 2, SoundField = 3, StereoPassThrough = 5, HRTFHQ = 6, Auto = 7 } declare const enum AVAudio3DMixingSourceMode { SpatializeIfMono = 0, Bypass = 1, PointSource = 2, AmbienceBed = 3 } interface AVAudio3DPoint { x: number; y: number; z: number; } declare var AVAudio3DPoint: interop.StructType<AVAudio3DPoint>; interface AVAudio3DVectorOrientation { forward: AVAudio3DPoint; up: AVAudio3DPoint; } declare var AVAudio3DVectorOrientation: interop.StructType<AVAudio3DVectorOrientation>; declare var AVAudioBitRateStrategy_Constant: string; declare var AVAudioBitRateStrategy_LongTermAverage: string; declare var AVAudioBitRateStrategy_Variable: string; declare var AVAudioBitRateStrategy_VariableConstrained: string; declare class AVAudioBuffer extends NSObject implements NSCopying, NSMutableCopying { static alloc(): AVAudioBuffer; // inherited from NSObject static new(): AVAudioBuffer; // inherited from NSObject readonly audioBufferList: interop.Pointer | interop.Reference<AudioBufferList>; readonly format: AVAudioFormat; readonly mutableAudioBufferList: interop.Pointer | interop.Reference<AudioBufferList>; copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; mutableCopyWithZone(zone: interop.Pointer | interop.Reference<any>): any; } declare class AVAudioChannelLayout extends NSObject implements NSSecureCoding { static alloc(): AVAudioChannelLayout; // inherited from NSObject static layoutWithLayout(layout: interop.Pointer | interop.Reference<AudioChannelLayout>): AVAudioChannelLayout; static layoutWithLayoutTag(layoutTag: number): AVAudioChannelLayout; static new(): AVAudioChannelLayout; // inherited from NSObject readonly channelCount: number; readonly layout: interop.Pointer | interop.Reference<AudioChannelLayout>; readonly layoutTag: number; static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding constructor(o: { coder: NSCoder; }); // inherited from NSCoding constructor(o: { layout: interop.Pointer | interop.Reference<AudioChannelLayout>; }); constructor(o: { layoutTag: number; }); encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; initWithLayout(layout: interop.Pointer | interop.Reference<AudioChannelLayout>): this; initWithLayoutTag(layoutTag: number): this; } declare const enum AVAudioCommonFormat { OtherFormat = 0, PCMFormatFloat32 = 1, PCMFormatFloat64 = 2, PCMFormatInt16 = 3, PCMFormatInt32 = 4 } declare class AVAudioCompressedBuffer extends AVAudioBuffer { static alloc(): AVAudioCompressedBuffer; // inherited from NSObject static new(): AVAudioCompressedBuffer; // inherited from NSObject readonly byteCapacity: number; byteLength: number; readonly data: interop.Pointer | interop.Reference<any>; readonly maximumPacketSize: number; readonly packetCapacity: number; packetCount: number; readonly packetDescriptions: interop.Pointer | interop.Reference<AudioStreamPacketDescription>; constructor(o: { format: AVAudioFormat; packetCapacity: number; }); constructor(o: { format: AVAudioFormat; packetCapacity: number; maximumPacketSize: number; }); initWithFormatPacketCapacity(format: AVAudioFormat, packetCapacity: number): this; initWithFormatPacketCapacityMaximumPacketSize(format: AVAudioFormat, packetCapacity: number, maximumPacketSize: number): this; } declare class AVAudioConnectionPoint extends NSObject { static alloc(): AVAudioConnectionPoint; // inherited from NSObject static new(): AVAudioConnectionPoint; // inherited from NSObject readonly bus: number; readonly node: AVAudioNode; constructor(o: { node: AVAudioNode; bus: number; }); initWithNodeBus(node: AVAudioNode, bus: number): this; } declare class AVAudioConverter extends NSObject { static alloc(): AVAudioConverter; // inherited from NSObject static new(): AVAudioConverter; // inherited from NSObject readonly applicableEncodeBitRates: NSArray<number>; readonly applicableEncodeSampleRates: NSArray<number>; readonly availableEncodeBitRates: NSArray<number>; readonly availableEncodeChannelLayoutTags: NSArray<number>; readonly availableEncodeSampleRates: NSArray<number>; bitRate: number; bitRateStrategy: string; channelMap: NSArray<number>; dither: boolean; downmix: boolean; readonly inputFormat: AVAudioFormat; magicCookie: NSData; readonly maximumOutputPacketSize: number; readonly outputFormat: AVAudioFormat; primeInfo: AVAudioConverterPrimeInfo; primeMethod: AVAudioConverterPrimeMethod; sampleRateConverterAlgorithm: string; sampleRateConverterQuality: number; constructor(o: { fromFormat: AVAudioFormat; toFormat: AVAudioFormat; }); convertToBufferErrorWithInputFromBlock(outputBuffer: AVAudioBuffer, outError: interop.Pointer | interop.Reference<NSError>, inputBlock: (p1: number, p2: interop.Pointer | interop.Reference<AVAudioConverterInputStatus>) => AVAudioBuffer): AVAudioConverterOutputStatus; convertToBufferFromBufferError(outputBuffer: AVAudioPCMBuffer, inputBuffer: AVAudioPCMBuffer): boolean; initFromFormatToFormat(fromFormat: AVAudioFormat, toFormat: AVAudioFormat): this; reset(): void; } declare const enum AVAudioConverterInputStatus { HaveData = 0, NoDataNow = 1, EndOfStream = 2 } declare const enum AVAudioConverterOutputStatus { HaveData = 0, InputRanDry = 1, EndOfStream = 2, Error = 3 } interface AVAudioConverterPrimeInfo { leadingFrames: number; trailingFrames: number; } declare var AVAudioConverterPrimeInfo: interop.StructType<AVAudioConverterPrimeInfo>; declare const enum AVAudioConverterPrimeMethod { Pre = 0, Normal = 1, None = 2 } declare class AVAudioEngine extends NSObject { static alloc(): AVAudioEngine; // inherited from NSObject static new(): AVAudioEngine; // inherited from NSObject readonly attachedNodes: NSSet<AVAudioNode>; autoShutdownEnabled: boolean; readonly inputNode: AVAudioInputNode; readonly isInManualRenderingMode: boolean; readonly mainMixerNode: AVAudioMixerNode; readonly manualRenderingBlock: (p1: number, p2: interop.Pointer | interop.Reference<AudioBufferList>, p3: interop.Pointer | interop.Reference<number>) => AVAudioEngineManualRenderingStatus; readonly manualRenderingFormat: AVAudioFormat; readonly manualRenderingMaximumFrameCount: number; readonly manualRenderingMode: AVAudioEngineManualRenderingMode; readonly manualRenderingSampleTime: number; musicSequence: interop.Pointer | interop.Reference<any>; readonly outputNode: AVAudioOutputNode; readonly running: boolean; attachNode(node: AVAudioNode): void; connectMIDIToFormatBlock(sourceNode: AVAudioNode, destinationNode: AVAudioNode, format: AVAudioFormat, tapBlock: (p1: number, p2: number, p3: number, p4: string) => number): void; connectMIDIToNodesFormatBlock(sourceNode: AVAudioNode, destinationNodes: NSArray<AVAudioNode> | AVAudioNode[], format: AVAudioFormat, tapBlock: (p1: number, p2: number, p3: number, p4: string) => number): void; connectToConnectionPointsFromBusFormat(sourceNode: AVAudioNode, destNodes: NSArray<AVAudioConnectionPoint> | AVAudioConnectionPoint[], sourceBus: number, format: AVAudioFormat): void; connectToFormat(node1: AVAudioNode, node2: AVAudioNode, format: AVAudioFormat): void; connectToFromBusToBusFormat(node1: AVAudioNode, node2: AVAudioNode, bus1: number, bus2: number, format: AVAudioFormat): void; detachNode(node: AVAudioNode): void; disableManualRenderingMode(): void; disconnectMIDIFrom(sourceNode: AVAudioNode, destinationNode: AVAudioNode): void; disconnectMIDIFromNodes(sourceNode: AVAudioNode, destinationNodes: NSArray<AVAudioNode> | AVAudioNode[]): void; disconnectMIDIInput(node: AVAudioNode): void; disconnectMIDIOutput(node: AVAudioNode): void; disconnectNodeInput(node: AVAudioNode): void; disconnectNodeInputBus(node: AVAudioNode, bus: number): void; disconnectNodeOutput(node: AVAudioNode): void; disconnectNodeOutputBus(node: AVAudioNode, bus: number): void; enableManualRenderingModeFormatMaximumFrameCountError(mode: AVAudioEngineManualRenderingMode, pcmFormat: AVAudioFormat, maximumFrameCount: number): boolean; inputConnectionPointForNodeInputBus(node: AVAudioNode, bus: number): AVAudioConnectionPoint; outputConnectionPointsForNodeOutputBus(node: AVAudioNode, bus: number): NSArray<AVAudioConnectionPoint>; pause(): void; prepare(): void; renderOfflineToBufferError(numberOfFrames: number, buffer: AVAudioPCMBuffer): AVAudioEngineManualRenderingStatus; reset(): void; startAndReturnError(): boolean; stop(): void; } declare var AVAudioEngineConfigurationChangeNotification: string; declare const enum AVAudioEngineManualRenderingError { InvalidMode = -80800, Initialized = -80801, NotRunning = -80802 } declare const enum AVAudioEngineManualRenderingMode { Offline = 0, Realtime = 1 } declare const enum AVAudioEngineManualRenderingStatus { Error = -1, Success = 0, InsufficientDataFromInputNode = 1, CannotDoInCurrentContext = 2 } declare const enum AVAudioEnvironmentDistanceAttenuationModel { Exponential = 1, Inverse = 2, Linear = 3 } declare class AVAudioEnvironmentDistanceAttenuationParameters extends NSObject { static alloc(): AVAudioEnvironmentDistanceAttenuationParameters; // inherited from NSObject static new(): AVAudioEnvironmentDistanceAttenuationParameters; // inherited from NSObject distanceAttenuationModel: AVAudioEnvironmentDistanceAttenuationModel; maximumDistance: number; referenceDistance: number; rolloffFactor: number; } declare class AVAudioEnvironmentNode extends AVAudioNode implements AVAudioMixing { static alloc(): AVAudioEnvironmentNode; // inherited from NSObject static new(): AVAudioEnvironmentNode; // inherited from NSObject readonly applicableRenderingAlgorithms: NSArray<number>; readonly distanceAttenuationParameters: AVAudioEnvironmentDistanceAttenuationParameters; listenerAngularOrientation: AVAudio3DAngularOrientation; listenerPosition: AVAudio3DPoint; listenerVectorOrientation: AVAudio3DVectorOrientation; readonly nextAvailableInputBus: number; outputType: AVAudioEnvironmentOutputType; outputVolume: number; readonly reverbParameters: AVAudioEnvironmentReverbParameters; readonly debugDescription: string; // inherited from NSObjectProtocol readonly description: string; // inherited from NSObjectProtocol readonly hash: number; // inherited from NSObjectProtocol readonly isProxy: boolean; // inherited from NSObjectProtocol obstruction: number; // inherited from AVAudio3DMixing occlusion: number; // inherited from AVAudio3DMixing pan: number; // inherited from AVAudioStereoMixing pointSourceInHeadMode: AVAudio3DMixingPointSourceInHeadMode; // inherited from AVAudio3DMixing position: AVAudio3DPoint; // inherited from AVAudio3DMixing rate: number; // inherited from AVAudio3DMixing renderingAlgorithm: AVAudio3DMixingRenderingAlgorithm; // inherited from AVAudio3DMixing reverbBlend: number; // inherited from AVAudio3DMixing sourceMode: AVAudio3DMixingSourceMode; // inherited from AVAudio3DMixing readonly superclass: typeof NSObject; // inherited from NSObjectProtocol volume: number; // inherited from AVAudioMixing readonly // inherited from NSObjectProtocol class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; destinationForMixerBus(mixer: AVAudioNode, bus: number): AVAudioMixingDestination; isEqual(object: any): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; performSelector(aSelector: string): any; performSelectorWithObject(aSelector: string, object: any): any; performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any; respondsToSelector(aSelector: string): boolean; retainCount(): number; self(): this; } declare const enum AVAudioEnvironmentOutputType { Auto = 0, Headphones = 1, BuiltInSpeakers = 2, ExternalSpeakers = 3 } declare class AVAudioEnvironmentReverbParameters extends NSObject { static alloc(): AVAudioEnvironmentReverbParameters; // inherited from NSObject static new(): AVAudioEnvironmentReverbParameters; // inherited from NSObject enable: boolean; readonly filterParameters: AVAudioUnitEQFilterParameters; level: number; loadFactoryReverbPreset(preset: AVAudioUnitReverbPreset): void; } declare class AVAudioFile extends NSObject { static alloc(): AVAudioFile; // inherited from NSObject static new(): AVAudioFile; // inherited from NSObject readonly fileFormat: AVAudioFormat; framePosition: number; readonly length: number; readonly processingFormat: AVAudioFormat; readonly url: NSURL; constructor(o: { forReading: NSURL; commonFormat: AVAudioCommonFormat; interleaved: boolean; }); constructor(o: { forReading: NSURL; }); constructor(o: { forWriting: NSURL; settings: NSDictionary<string, any>; commonFormat: AVAudioCommonFormat; interleaved: boolean; }); constructor(o: { forWriting: NSURL; settings: NSDictionary<string, any>; }); initForReadingCommonFormatInterleavedError(fileURL: NSURL, format: AVAudioCommonFormat, interleaved: boolean): this; initForReadingError(fileURL: NSURL): this; initForWritingSettingsCommonFormatInterleavedError(fileURL: NSURL, settings: NSDictionary<string, any>, format: AVAudioCommonFormat, interleaved: boolean): this; initForWritingSettingsError(fileURL: NSURL, settings: NSDictionary<string, any>): this; readIntoBufferError(buffer: AVAudioPCMBuffer): boolean; readIntoBufferFrameCountError(buffer: AVAudioPCMBuffer, frames: number): boolean; writeFromBufferError(buffer: AVAudioPCMBuffer): boolean; } declare var AVAudioFileTypeKey: string; declare class AVAudioFormat extends NSObject implements NSSecureCoding { static alloc(): AVAudioFormat; // inherited from NSObject static new(): AVAudioFormat; // inherited from NSObject readonly channelCount: number; readonly channelLayout: AVAudioChannelLayout; readonly commonFormat: AVAudioCommonFormat; readonly formatDescription: any; readonly interleaved: boolean; magicCookie: NSData; readonly sampleRate: number; readonly settings: NSDictionary<string, any>; readonly standard: boolean; readonly streamDescription: interop.Pointer | interop.Reference<AudioStreamBasicDescription>; static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding constructor(o: { standardFormatWithSampleRate: number; channelLayout: AVAudioChannelLayout; }); constructor(o: { standardFormatWithSampleRate: number; channels: number; }); constructor(o: { CMAudioFormatDescription: any; }); constructor(o: { coder: NSCoder; }); // inherited from NSCoding constructor(o: { commonFormat: AVAudioCommonFormat; sampleRate: number; channels: number; interleaved: boolean; }); constructor(o: { commonFormat: AVAudioCommonFormat; sampleRate: number; interleaved: boolean; channelLayout: AVAudioChannelLayout; }); constructor(o: { settings: NSDictionary<string, any>; }); constructor(o: { streamDescription: interop.Pointer | interop.Reference<AudioStreamBasicDescription>; }); constructor(o: { streamDescription: interop.Pointer | interop.Reference<AudioStreamBasicDescription>; channelLayout: AVAudioChannelLayout; }); encodeWithCoder(coder: NSCoder): void; initStandardFormatWithSampleRateChannelLayout(sampleRate: number, layout: AVAudioChannelLayout): this; initStandardFormatWithSampleRateChannels(sampleRate: number, channels: number): this; initWithCMAudioFormatDescription(formatDescription: any): this; initWithCoder(coder: NSCoder): this; initWithCommonFormatSampleRateChannelsInterleaved(format: AVAudioCommonFormat, sampleRate: number, channels: number, interleaved: boolean): this; initWithCommonFormatSampleRateInterleavedChannelLayout(format: AVAudioCommonFormat, sampleRate: number, interleaved: boolean, layout: AVAudioChannelLayout): this; initWithSettings(settings: NSDictionary<string, any>): this; initWithStreamDescription(asbd: interop.Pointer | interop.Reference<AudioStreamBasicDescription>): this; initWithStreamDescriptionChannelLayout(asbd: interop.Pointer | interop.Reference<AudioStreamBasicDescription>, layout: AVAudioChannelLayout): this; } declare class AVAudioIONode extends AVAudioNode { static alloc(): AVAudioIONode; // inherited from NSObject static new(): AVAudioIONode; // inherited from NSObject readonly audioUnit: interop.Pointer | interop.Reference<any>; readonly presentationLatency: number; readonly voiceProcessingEnabled: boolean; setVoiceProcessingEnabledError(enabled: boolean): boolean; } declare class AVAudioInputNode extends AVAudioIONode implements AVAudioMixing { static alloc(): AVAudioInputNode; // inherited from NSObject static new(): AVAudioInputNode; // inherited from NSObject voiceProcessingAGCEnabled: boolean; voiceProcessingBypassed: boolean; voiceProcessingInputMuted: boolean; readonly debugDescription: string; // inherited from NSObjectProtocol readonly description: string; // inherited from NSObjectProtocol readonly hash: number; // inherited from NSObjectProtocol readonly isProxy: boolean; // inherited from NSObjectProtocol obstruction: number; // inherited from AVAudio3DMixing occlusion: number; // inherited from AVAudio3DMixing pan: number; // inherited from AVAudioStereoMixing pointSourceInHeadMode: AVAudio3DMixingPointSourceInHeadMode; // inherited from AVAudio3DMixing position: AVAudio3DPoint; // inherited from AVAudio3DMixing rate: number; // inherited from AVAudio3DMixing renderingAlgorithm: AVAudio3DMixingRenderingAlgorithm; // inherited from AVAudio3DMixing reverbBlend: number; // inherited from AVAudio3DMixing sourceMode: AVAudio3DMixingSourceMode; // inherited from AVAudio3DMixing readonly superclass: typeof NSObject; // inherited from NSObjectProtocol volume: number; // inherited from AVAudioMixing readonly // inherited from NSObjectProtocol class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; destinationForMixerBus(mixer: AVAudioNode, bus: number): AVAudioMixingDestination; isEqual(object: any): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; performSelector(aSelector: string): any; performSelectorWithObject(aSelector: string, object: any): any; performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any; respondsToSelector(aSelector: string): boolean; retainCount(): number; self(): this; setManualRenderingInputPCMFormatInputBlock(format: AVAudioFormat, block: (p1: number) => interop.Pointer | interop.Reference<AudioBufferList>): boolean; } declare class AVAudioMixerNode extends AVAudioNode implements AVAudioMixing { static alloc(): AVAudioMixerNode; // inherited from NSObject static new(): AVAudioMixerNode; // inherited from NSObject readonly nextAvailableInputBus: number; outputVolume: number; readonly debugDescription: string; // inherited from NSObjectProtocol readonly description: string; // inherited from NSObjectProtocol readonly hash: number; // inherited from NSObjectProtocol readonly isProxy: boolean; // inherited from NSObjectProtocol obstruction: number; // inherited from AVAudio3DMixing occlusion: number; // inherited from AVAudio3DMixing pan: number; // inherited from AVAudioStereoMixing pointSourceInHeadMode: AVAudio3DMixingPointSourceInHeadMode; // inherited from AVAudio3DMixing position: AVAudio3DPoint; // inherited from AVAudio3DMixing rate: number; // inherited from AVAudio3DMixing renderingAlgorithm: AVAudio3DMixingRenderingAlgorithm; // inherited from AVAudio3DMixing reverbBlend: number; // inherited from AVAudio3DMixing sourceMode: AVAudio3DMixingSourceMode; // inherited from AVAudio3DMixing readonly superclass: typeof NSObject; // inherited from NSObjectProtocol volume: number; // inherited from AVAudioMixing readonly // inherited from NSObjectProtocol class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; destinationForMixerBus(mixer: AVAudioNode, bus: number): AVAudioMixingDestination; isEqual(object: any): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; performSelector(aSelector: string): any; performSelectorWithObject(aSelector: string, object: any): any; performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any; respondsToSelector(aSelector: string): boolean; retainCount(): number; self(): this; } interface AVAudioMixing extends AVAudio3DMixing, AVAudioStereoMixing { volume: number; destinationForMixerBus(mixer: AVAudioNode, bus: number): AVAudioMixingDestination; } declare var AVAudioMixing: { prototype: AVAudioMixing; }; declare class AVAudioMixingDestination extends NSObject implements AVAudioMixing { static alloc(): AVAudioMixingDestination; // inherited from NSObject static new(): AVAudioMixingDestination; // inherited from NSObject readonly connectionPoint: AVAudioConnectionPoint; readonly debugDescription: string; // inherited from NSObjectProtocol readonly description: string; // inherited from NSObjectProtocol readonly hash: number; // inherited from NSObjectProtocol readonly isProxy: boolean; // inherited from NSObjectProtocol obstruction: number; // inherited from AVAudio3DMixing occlusion: number; // inherited from AVAudio3DMixing pan: number; // inherited from AVAudioStereoMixing pointSourceInHeadMode: AVAudio3DMixingPointSourceInHeadMode; // inherited from AVAudio3DMixing position: AVAudio3DPoint; // inherited from AVAudio3DMixing rate: number; // inherited from AVAudio3DMixing renderingAlgorithm: AVAudio3DMixingRenderingAlgorithm; // inherited from AVAudio3DMixing reverbBlend: number; // inherited from AVAudio3DMixing sourceMode: AVAudio3DMixingSourceMode; // inherited from AVAudio3DMixing readonly superclass: typeof NSObject; // inherited from NSObjectProtocol volume: number; // inherited from AVAudioMixing readonly // inherited from NSObjectProtocol class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; destinationForMixerBus(mixer: AVAudioNode, bus: number): AVAudioMixingDestination; isEqual(object: any): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; performSelector(aSelector: string): any; performSelectorWithObject(aSelector: string, object: any): any; performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any; respondsToSelector(aSelector: string): boolean; retainCount(): number; self(): this; } declare class AVAudioNode extends NSObject { static alloc(): AVAudioNode; // inherited from NSObject static new(): AVAudioNode; // inherited from NSObject readonly AUAudioUnit: AUAudioUnit; readonly engine: AVAudioEngine; readonly lastRenderTime: AVAudioTime; readonly latency: number; readonly numberOfInputs: number; readonly numberOfOutputs: number; readonly outputPresentationLatency: number; inputFormatForBus(bus: number): AVAudioFormat; installTapOnBusBufferSizeFormatBlock(bus: number, bufferSize: number, format: AVAudioFormat, tapBlock: (p1: AVAudioPCMBuffer, p2: AVAudioTime) => void): void; nameForInputBus(bus: number): string; nameForOutputBus(bus: number): string; outputFormatForBus(bus: number): AVAudioFormat; removeTapOnBus(bus: number): void; reset(): void; } declare class AVAudioOutputNode extends AVAudioIONode { static alloc(): AVAudioOutputNode; // inherited from NSObject static new(): AVAudioOutputNode; // inherited from NSObject } declare class AVAudioPCMBuffer extends AVAudioBuffer { static alloc(): AVAudioPCMBuffer; // inherited from NSObject static new(): AVAudioPCMBuffer; // inherited from NSObject readonly floatChannelData: interop.Pointer | interop.Reference<interop.Pointer | interop.Reference<number>>; readonly frameCapacity: number; frameLength: number; readonly int16ChannelData: interop.Pointer | interop.Reference<interop.Pointer | interop.Reference<number>>; readonly int32ChannelData: interop.Pointer | interop.Reference<interop.Pointer | interop.Reference<number>>; readonly stride: number; constructor(o: { PCMFormat: AVAudioFormat; bufferListNoCopy: interop.Pointer | interop.Reference<AudioBufferList>; deallocator: (p1: interop.Pointer | interop.Reference<AudioBufferList>) => void; }); constructor(o: { PCMFormat: AVAudioFormat; frameCapacity: number; }); initWithPCMFormatBufferListNoCopyDeallocator(format: AVAudioFormat, bufferList: interop.Pointer | interop.Reference<AudioBufferList>, deallocator: (p1: interop.Pointer | interop.Reference<AudioBufferList>) => void): this; initWithPCMFormatFrameCapacity(format: AVAudioFormat, frameCapacity: number): this; } declare class AVAudioPlayer extends NSObject { static alloc(): AVAudioPlayer; // inherited from NSObject static new(): AVAudioPlayer; // inherited from NSObject channelAssignments: NSArray<AVAudioSessionChannelDescription>; currentTime: number; readonly data: NSData; delegate: AVAudioPlayerDelegate; readonly deviceCurrentTime: number; readonly duration: number; enableRate: boolean; readonly format: AVAudioFormat; meteringEnabled: boolean; readonly numberOfChannels: number; numberOfLoops: number; pan: number; readonly playing: boolean; rate: number; readonly settings: NSDictionary<string, any>; readonly url: NSURL; volume: number; constructor(o: { contentsOfURL: NSURL; }); constructor(o: { contentsOfURL: NSURL; fileTypeHint: string; }); constructor(o: { data: NSData; }); constructor(o: { data: NSData; fileTypeHint: string; }); averagePowerForChannel(channelNumber: number): number; initWithContentsOfURLError(url: NSURL): this; initWithContentsOfURLFileTypeHintError(url: NSURL, utiString: string): this; initWithDataError(data: NSData): this; initWithDataFileTypeHintError(data: NSData, utiString: string): this; pause(): void; peakPowerForChannel(channelNumber: number): number; play(): boolean; playAtTime(time: number): boolean; prepareToPlay(): boolean; setVolumeFadeDuration(volume: number, duration: number): void; stop(): void; updateMeters(): void; } interface AVAudioPlayerDelegate extends NSObjectProtocol { audioPlayerBeginInterruption?(player: AVAudioPlayer): void; audioPlayerDecodeErrorDidOccurError?(player: AVAudioPlayer, error: NSError): void; audioPlayerDidFinishPlayingSuccessfully?(player: AVAudioPlayer, flag: boolean): void; audioPlayerEndInterruption?(player: AVAudioPlayer): void; audioPlayerEndInterruptionWithFlags?(player: AVAudioPlayer, flags: number): void; audioPlayerEndInterruptionWithOptions?(player: AVAudioPlayer, flags: number): void; } declare var AVAudioPlayerDelegate: { prototype: AVAudioPlayerDelegate; }; declare class AVAudioPlayerNode extends AVAudioNode implements AVAudioMixing { static alloc(): AVAudioPlayerNode; // inherited from NSObject static new(): AVAudioPlayerNode; // inherited from NSObject readonly playing: boolean; readonly debugDescription: string; // inherited from NSObjectProtocol readonly description: string; // inherited from NSObjectProtocol readonly hash: number; // inherited from NSObjectProtocol readonly isProxy: boolean; // inherited from NSObjectProtocol obstruction: number; // inherited from AVAudio3DMixing occlusion: number; // inherited from AVAudio3DMixing pan: number; // inherited from AVAudioStereoMixing pointSourceInHeadMode: AVAudio3DMixingPointSourceInHeadMode; // inherited from AVAudio3DMixing position: AVAudio3DPoint; // inherited from AVAudio3DMixing rate: number; // inherited from AVAudio3DMixing renderingAlgorithm: AVAudio3DMixingRenderingAlgorithm; // inherited from AVAudio3DMixing reverbBlend: number; // inherited from AVAudio3DMixing sourceMode: AVAudio3DMixingSourceMode; // inherited from AVAudio3DMixing readonly superclass: typeof NSObject; // inherited from NSObjectProtocol volume: number; // inherited from AVAudioMixing readonly // inherited from NSObjectProtocol class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; destinationForMixerBus(mixer: AVAudioNode, bus: number): AVAudioMixingDestination; isEqual(object: any): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; nodeTimeForPlayerTime(playerTime: AVAudioTime): AVAudioTime; pause(): void; performSelector(aSelector: string): any; performSelectorWithObject(aSelector: string, object: any): any; performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any; play(): void; playAtTime(when: AVAudioTime): void; playerTimeForNodeTime(nodeTime: AVAudioTime): AVAudioTime; prepareWithFrameCount(frameCount: number): void; respondsToSelector(aSelector: string): boolean; retainCount(): number; scheduleBufferAtTimeOptionsCompletionCallbackTypeCompletionHandler(buffer: AVAudioPCMBuffer, when: AVAudioTime, options: AVAudioPlayerNodeBufferOptions, callbackType: AVAudioPlayerNodeCompletionCallbackType, completionHandler: (p1: AVAudioPlayerNodeCompletionCallbackType) => void): void; scheduleBufferAtTimeOptionsCompletionHandler(buffer: AVAudioPCMBuffer, when: AVAudioTime, options: AVAudioPlayerNodeBufferOptions, completionHandler: () => void): void; scheduleBufferCompletionCallbackTypeCompletionHandler(buffer: AVAudioPCMBuffer, callbackType: AVAudioPlayerNodeCompletionCallbackType, completionHandler: (p1: AVAudioPlayerNodeCompletionCallbackType) => void): void; scheduleBufferCompletionHandler(buffer: AVAudioPCMBuffer, completionHandler: () => void): void; scheduleFileAtTimeCompletionCallbackTypeCompletionHandler(file: AVAudioFile, when: AVAudioTime, callbackType: AVAudioPlayerNodeCompletionCallbackType, completionHandler: (p1: AVAudioPlayerNodeCompletionCallbackType) => void): void; scheduleFileAtTimeCompletionHandler(file: AVAudioFile, when: AVAudioTime, completionHandler: () => void): void; scheduleSegmentStartingFrameFrameCountAtTimeCompletionCallbackTypeCompletionHandler(file: AVAudioFile, startFrame: number, numberFrames: number, when: AVAudioTime, callbackType: AVAudioPlayerNodeCompletionCallbackType, completionHandler: (p1: AVAudioPlayerNodeCompletionCallbackType) => void): void; scheduleSegmentStartingFrameFrameCountAtTimeCompletionHandler(file: AVAudioFile, startFrame: number, numberFrames: number, when: AVAudioTime, completionHandler: () => void): void; self(): this; stop(): void; } declare const enum AVAudioPlayerNodeBufferOptions { Loops = 1, Interrupts = 2, InterruptsAtLoop = 4 } declare const enum AVAudioPlayerNodeCompletionCallbackType { DataConsumed = 0, DataRendered = 1, DataPlayedBack = 2 } declare const enum AVAudioQuality { Min = 0, Low = 32, Medium = 64, High = 96, Max = 127 } declare class AVAudioRecorder extends NSObject { static alloc(): AVAudioRecorder; // inherited from NSObject static new(): AVAudioRecorder; // inherited from NSObject channelAssignments: NSArray<AVAudioSessionChannelDescription>; readonly currentTime: number; delegate: AVAudioRecorderDelegate; readonly deviceCurrentTime: number; readonly format: AVAudioFormat; meteringEnabled: boolean; readonly recording: boolean; readonly settings: NSDictionary<string, any>; readonly url: NSURL; constructor(o: { URL: NSURL; format: AVAudioFormat; }); constructor(o: { URL: NSURL; settings: NSDictionary<string, any>; }); averagePowerForChannel(channelNumber: number): number; deleteRecording(): boolean; initWithURLFormatError(url: NSURL, format: AVAudioFormat): this; initWithURLSettingsError(url: NSURL, settings: NSDictionary<string, any>): this; pause(): void; peakPowerForChannel(channelNumber: number): number; prepareToRecord(): boolean; record(): boolean; recordAtTime(time: number): boolean; recordAtTimeForDuration(time: number, duration: number): boolean; recordForDuration(duration: number): boolean; stop(): void; updateMeters(): void; } interface AVAudioRecorderDelegate extends NSObjectProtocol { audioRecorderBeginInterruption?(recorder: AVAudioRecorder): void; audioRecorderDidFinishRecordingSuccessfully?(recorder: AVAudioRecorder, flag: boolean): void; audioRecorderEncodeErrorDidOccurError?(recorder: AVAudioRecorder, error: NSError): void; audioRecorderEndInterruption?(recorder: AVAudioRecorder): void; audioRecorderEndInterruptionWithFlags?(recorder: AVAudioRecorder, flags: number): void; audioRecorderEndInterruptionWithOptions?(recorder: AVAudioRecorder, flags: number): void; } declare var AVAudioRecorderDelegate: { prototype: AVAudioRecorderDelegate; }; declare const enum AVAudioRoutingArbitrationCategory { Playback = 0, PlayAndRecord = 1, PlayAndRecordVoice = 2 } declare class AVAudioSequencer extends NSObject { static alloc(): AVAudioSequencer; // inherited from NSObject static new(): AVAudioSequencer; // inherited from NSObject currentPositionInBeats: number; currentPositionInSeconds: number; readonly playing: boolean; rate: number; readonly tempoTrack: AVMusicTrack; readonly tracks: NSArray<AVMusicTrack>; readonly userInfo: NSDictionary<string, any>; constructor(o: { audioEngine: AVAudioEngine; }); beatsForHostTimeError(inHostTime: number): number; beatsForSeconds(seconds: number): number; dataWithSMPTEResolutionError(SMPTEResolution: number): NSData; hostTimeForBeatsError(inBeats: number): number; initWithAudioEngine(engine: AVAudioEngine): this; loadFromDataOptionsError(data: NSData, options: AVMusicSequenceLoadOptions): boolean; loadFromURLOptionsError(fileURL: NSURL, options: AVMusicSequenceLoadOptions): boolean; prepareToPlay(): void; secondsForBeats(beats: number): number; startAndReturnError(): boolean; stop(): void; writeToURLSMPTEResolutionReplaceExistingError(fileURL: NSURL, resolution: number, replace: boolean): boolean; } declare class AVAudioSession extends NSObject { static alloc(): AVAudioSession; // inherited from NSObject static new(): AVAudioSession; // inherited from NSObject static sharedInstance(): AVAudioSession; readonly IOBufferDuration: number; readonly allowHapticsAndSystemSoundsDuringRecording: boolean; readonly availableCategories: NSArray<string>; readonly availableInputs: NSArray<AVAudioSessionPortDescription>; readonly availableModes: NSArray<string>; readonly category: string; readonly categoryOptions: AVAudioSessionCategoryOptions; readonly currentHardwareInputNumberOfChannels: number; readonly currentHardwareOutputNumberOfChannels: number; readonly currentHardwareSampleRate: number; readonly currentRoute: AVAudioSessionRouteDescription; delegate: AVAudioSessionDelegate; readonly inputAvailable: boolean; readonly inputDataSource: AVAudioSessionDataSourceDescription; readonly inputDataSources: NSArray<AVAudioSessionDataSourceDescription>; readonly inputGain: number; readonly inputGainSettable: boolean; readonly inputIsAvailable: boolean; readonly inputLatency: number; readonly inputNumberOfChannels: number; readonly inputOrientation: AVAudioStereoOrientation; readonly maximumInputNumberOfChannels: number; readonly maximumOutputNumberOfChannels: number; readonly mode: string; readonly otherAudioPlaying: boolean; readonly outputDataSource: AVAudioSessionDataSourceDescription; readonly outputDataSources: NSArray<AVAudioSessionDataSourceDescription>; readonly outputLatency: number; readonly outputNumberOfChannels: number; readonly outputVolume: number; readonly preferredHardwareSampleRate: number; readonly preferredIOBufferDuration: number; readonly preferredInput: AVAudioSessionPortDescription; readonly preferredInputNumberOfChannels: number; readonly preferredInputOrientation: AVAudioStereoOrientation; readonly preferredOutputNumberOfChannels: number; readonly preferredSampleRate: number; readonly prefersNoInterruptionsFromSystemAlerts: boolean; readonly promptStyle: AVAudioSessionPromptStyle; readonly recordPermission: AVAudioSessionRecordPermission; readonly routeSharingPolicy: AVAudioSessionRouteSharingPolicy; readonly sampleRate: number; readonly secondaryAudioShouldBeSilencedHint: boolean; readonly supportsMultichannelContent: boolean; overrideOutputAudioPortError(portOverride: AVAudioSessionPortOverride): boolean; prepareRouteSelectionForPlaybackWithCompletionHandler(completionHandler: (p1: boolean, p2: AVAudioSessionRouteSelection) => void): void; requestRecordPermission(response: (p1: boolean) => void): void; setActiveError(active: boolean): boolean; setActiveWithFlagsError(active: boolean, flags: number): boolean; setActiveWithOptionsError(active: boolean, options: AVAudioSessionSetActiveOptions): boolean; setAggregatedIOPreferenceError(inIOType: AVAudioSessionIOType): boolean; setAllowHapticsAndSystemSoundsDuringRecordingError(inValue: boolean): boolean; setCategoryError(category: string): boolean; setCategoryModeOptionsError(category: string, mode: string, options: AVAudioSessionCategoryOptions): boolean; setCategoryModeRouteSharingPolicyOptionsError(category: string, mode: string, policy: AVAudioSessionRouteSharingPolicy, options: AVAudioSessionCategoryOptions): boolean; setCategoryWithOptionsError(category: string, options: AVAudioSessionCategoryOptions): boolean; setInputDataSourceError(dataSource: AVAudioSessionDataSourceDescription): boolean; setInputGainError(gain: number): boolean; setModeError(mode: string): boolean; setOutputDataSourceError(dataSource: AVAudioSessionDataSourceDescription): boolean; setPreferredHardwareSampleRateError(sampleRate: number): boolean; setPreferredIOBufferDurationError(duration: number): boolean; setPreferredInputError(inPort: AVAudioSessionPortDescription): boolean; setPreferredInputNumberOfChannelsError(count: number): boolean; setPreferredInputOrientationError(orientation: AVAudioStereoOrientation): boolean; setPreferredOutputNumberOfChannelsError(count: number): boolean; setPreferredSampleRateError(sampleRate: number): boolean; setPrefersNoInterruptionsFromSystemAlertsError(inValue: boolean): boolean; setSupportsMultichannelContentError(inValue: boolean): boolean; } declare const enum AVAudioSessionActivationOptions { None = 0 } declare var AVAudioSessionCategoryAmbient: string; declare var AVAudioSessionCategoryAudioProcessing: string; declare var AVAudioSessionCategoryMultiRoute: string; declare const enum AVAudioSessionCategoryOptions { MixWithOthers = 1, DuckOthers = 2, AllowBluetooth = 4, DefaultToSpeaker = 8, InterruptSpokenAudioAndMixWithOthers = 17, AllowBluetoothA2DP = 32, AllowAirPlay = 64, OverrideMutedMicrophoneInterruption = 128 } declare var AVAudioSessionCategoryPlayAndRecord: string; declare var AVAudioSessionCategoryPlayback: string; declare var AVAudioSessionCategoryRecord: string; declare var AVAudioSessionCategorySoloAmbient: string; declare class AVAudioSessionChannelDescription extends NSObject { static alloc(): AVAudioSessionChannelDescription; // inherited from NSObject static new(): AVAudioSessionChannelDescription; // inherited from NSObject readonly channelLabel: number; readonly channelName: string; readonly channelNumber: number; readonly owningPortUID: string; } declare class AVAudioSessionDataSourceDescription extends NSObject { static alloc(): AVAudioSessionDataSourceDescription; // inherited from NSObject static new(): AVAudioSessionDataSourceDescription; // inherited from NSObject readonly dataSourceID: number; readonly dataSourceName: string; readonly location: string; readonly orientation: string; readonly preferredPolarPattern: string; readonly selectedPolarPattern: string; readonly supportedPolarPatterns: NSArray<string>; setPreferredPolarPatternError(pattern: string): boolean; } interface AVAudioSessionDelegate extends NSObjectProtocol { beginInterruption?(): void; endInterruption?(): void; endInterruptionWithFlags?(flags: number): void; inputIsAvailableChanged?(isInputAvailable: boolean): void; } declare var AVAudioSessionDelegate: { prototype: AVAudioSessionDelegate; }; declare const enum AVAudioSessionIOType { NotSpecified = 0, Aggregated = 1 } declare const AVAudioSessionInterruptionFlags_ShouldResume: number; declare var AVAudioSessionInterruptionNotification: string; declare var AVAudioSessionInterruptionOptionKey: string; declare const enum AVAudioSessionInterruptionOptions { ShouldResume = 1 } declare const enum AVAudioSessionInterruptionReason { Default = 0, AppWasSuspended = 1, BuiltInMicMuted = 2 } declare var AVAudioSessionInterruptionReasonKey: string; declare const enum AVAudioSessionInterruptionType { Began = 1, Ended = 0 } declare var AVAudioSessionInterruptionTypeKey: string; declare var AVAudioSessionInterruptionWasSuspendedKey: string; declare var AVAudioSessionLocationLower: string; declare var AVAudioSessionLocationUpper: string; declare var AVAudioSessionMediaServicesWereLostNotification: string; declare var AVAudioSessionMediaServicesWereResetNotification: string; declare var AVAudioSessionModeDefault: string; declare var AVAudioSessionModeGameChat: string; declare var AVAudioSessionModeMeasurement: string; declare var AVAudioSessionModeMoviePlayback: string; declare var AVAudioSessionModeSpokenAudio: string; declare var AVAudioSessionModeVideoChat: string; declare var AVAudioSessionModeVideoRecording: string; declare var AVAudioSessionModeVoiceChat: string; declare var AVAudioSessionModeVoicePrompt: string; declare var AVAudioSessionOrientationBack: string; declare var AVAudioSessionOrientationBottom: string; declare var AVAudioSessionOrientationFront: string; declare var AVAudioSessionOrientationLeft: string; declare var AVAudioSessionOrientationRight: string; declare var AVAudioSessionOrientationTop: string; declare var AVAudioSessionPolarPatternCardioid: string; declare var AVAudioSessionPolarPatternOmnidirectional: string; declare var AVAudioSessionPolarPatternStereo: string; declare var AVAudioSessionPolarPatternSubcardioid: string; declare var AVAudioSessionPortAVB: string; declare var AVAudioSessionPortAirPlay: string; declare var AVAudioSessionPortBluetoothA2DP: string; declare var AVAudioSessionPortBluetoothHFP: string; declare var AVAudioSessionPortBluetoothLE: string; declare var AVAudioSessionPortBuiltInMic: string; declare var AVAudioSessionPortBuiltInReceiver: string; declare var AVAudioSessionPortBuiltInSpeaker: string; declare var AVAudioSessionPortCarAudio: string; declare class AVAudioSessionPortDescription extends NSObject { static alloc(): AVAudioSessionPortDescription; // inherited from NSObject static new(): AVAudioSessionPortDescription; // inherited from NSObject readonly UID: string; readonly channels: NSArray<AVAudioSessionChannelDescription>; readonly dataSources: NSArray<AVAudioSessionDataSourceDescription>; readonly hasHardwareVoiceCallProcessing: boolean; readonly portName: string; readonly portType: string; readonly preferredDataSource: AVAudioSessionDataSourceDescription; readonly selectedDataSource: AVAudioSessionDataSourceDescription; readonly spatialAudioEnabled: boolean; setPreferredDataSourceError(dataSource: AVAudioSessionDataSourceDescription): boolean; } declare var AVAudioSessionPortDisplayPort: string; declare var AVAudioSessionPortFireWire: string; declare var AVAudioSessionPortHDMI: string; declare var AVAudioSessionPortHeadphones: string; declare var AVAudioSessionPortHeadsetMic: string; declare var AVAudioSessionPortLineIn: string; declare var AVAudioSessionPortLineOut: string; declare const enum AVAudioSessionPortOverride { None = 0, Speaker = 1936747378 } declare var AVAudioSessionPortPCI: string; declare var AVAudioSessionPortThunderbolt: string; declare var AVAudioSessionPortUSBAudio: string; declare var AVAudioSessionPortVirtual: string; declare const enum AVAudioSessionPromptStyle { None = 1852796517, Short = 1936224884, Normal = 1852992876 } declare const enum AVAudioSessionRecordPermission { Undetermined = 1970168948, Denied = 1684369017, Granted = 1735552628 } declare var AVAudioSessionRouteChangeNotification: string; declare var AVAudioSessionRouteChangePreviousRouteKey: string; declare const enum AVAudioSessionRouteChangeReason { Unknown = 0, NewDeviceAvailable = 1, OldDeviceUnavailable = 2, CategoryChange = 3, Override = 4, WakeFromSleep = 6, NoSuitableRouteForCategory = 7, RouteConfigurationChange = 8 } declare var AVAudioSessionRouteChangeReasonKey: string; declare class AVAudioSessionRouteDescription extends NSObject { static alloc(): AVAudioSessionRouteDescription; // inherited from NSObject static new(): AVAudioSessionRouteDescription; // inherited from NSObject readonly inputs: NSArray<AVAudioSessionPortDescription>; readonly outputs: NSArray<AVAudioSessionPortDescription>; } declare const enum AVAudioSessionRouteSharingPolicy { Default = 0, LongFormAudio = 1, LongForm = 1, Independent = 2, LongFormVideo = 3 } declare const AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation: number; declare const enum AVAudioSessionSetActiveOptions { NotifyOthersOnDeactivation = 1 } declare var AVAudioSessionSilenceSecondaryAudioHintNotification: string; declare const enum AVAudioSessionSilenceSecondaryAudioHintType { Begin = 1, End = 0 } declare var AVAudioSessionSilenceSecondaryAudioHintTypeKey: string; declare var AVAudioSessionSpatialAudioEnabledKey: string; declare var AVAudioSessionSpatialPlaybackCapabilitiesChangedNotification: string; declare class AVAudioSinkNode extends AVAudioNode { static alloc(): AVAudioSinkNode; // inherited from NSObject static new(): AVAudioSinkNode; // inherited from NSObject constructor(o: { receiverBlock: (p1: interop.Pointer | interop.Reference<AudioTimeStamp>, p2: number, p3: interop.Pointer | interop.Reference<AudioBufferList>) => number; }); initWithReceiverBlock(block: (p1: interop.Pointer | interop.Reference<AudioTimeStamp>, p2: number, p3: interop.Pointer | interop.Reference<AudioBufferList>) => number): this; } declare class AVAudioSourceNode extends AVAudioNode implements AVAudioMixing { static alloc(): AVAudioSourceNode; // inherited from NSObject static new(): AVAudioSourceNode; // inherited from NSObject readonly debugDescription: string; // inherited from NSObjectProtocol readonly description: string; // inherited from NSObjectProtocol readonly hash: number; // inherited from NSObjectProtocol readonly isProxy: boolean; // inherited from NSObjectProtocol obstruction: number; // inherited from AVAudio3DMixing occlusion: number; // inherited from AVAudio3DMixing pan: number; // inherited from AVAudioStereoMixing pointSourceInHeadMode: AVAudio3DMixingPointSourceInHeadMode; // inherited from AVAudio3DMixing position: AVAudio3DPoint; // inherited from AVAudio3DMixing rate: number; // inherited from AVAudio3DMixing renderingAlgorithm: AVAudio3DMixingRenderingAlgorithm; // inherited from AVAudio3DMixing reverbBlend: number; // inherited from AVAudio3DMixing sourceMode: AVAudio3DMixingSourceMode; // inherited from AVAudio3DMixing readonly superclass: typeof NSObject; // inherited from NSObjectProtocol volume: number; // inherited from AVAudioMixing readonly // inherited from NSObjectProtocol constructor(o: { format: AVAudioFormat; renderBlock: (p1: interop.Pointer | interop.Reference<boolean>, p2: interop.Pointer | interop.Reference<AudioTimeStamp>, p3: number, p4: interop.Pointer | interop.Reference<AudioBufferList>) => number; }); constructor(o: { renderBlock: (p1: interop.Pointer | interop.Reference<boolean>, p2: interop.Pointer | interop.Reference<AudioTimeStamp>, p3: number, p4: interop.Pointer | interop.Reference<AudioBufferList>) => number; }); class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; destinationForMixerBus(mixer: AVAudioNode, bus: number): AVAudioMixingDestination; initWithFormatRenderBlock(format: AVAudioFormat, block: (p1: interop.Pointer | interop.Reference<boolean>, p2: interop.Pointer | interop.Reference<AudioTimeStamp>, p3: number, p4: interop.Pointer | interop.Reference<AudioBufferList>) => number): this; initWithRenderBlock(block: (p1: interop.Pointer | interop.Reference<boolean>, p2: interop.Pointer | interop.Reference<AudioTimeStamp>, p3: number, p4: interop.Pointer | interop.Reference<AudioBufferList>) => number): this; isEqual(object: any): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; performSelector(aSelector: string): any; performSelectorWithObject(aSelector: string, object: any): any; performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any; respondsToSelector(aSelector: string): boolean; retainCount(): number; self(): this; } interface AVAudioStereoMixing extends NSObjectProtocol { pan: number; } declare var AVAudioStereoMixing: { prototype: AVAudioStereoMixing; }; declare const enum AVAudioStereoOrientation { None = 0, Portrait = 1, PortraitUpsideDown = 2, LandscapeRight = 3, LandscapeLeft = 4 } declare class AVAudioTime extends NSObject { static alloc(): AVAudioTime; // inherited from NSObject static hostTimeForSeconds(seconds: number): number; static new(): AVAudioTime; // inherited from NSObject static secondsForHostTime(hostTime: number): number; static timeWithAudioTimeStampSampleRate(ts: interop.Pointer | interop.Reference<AudioTimeStamp>, sampleRate: number): AVAudioTime; static timeWithHostTime(hostTime: number): AVAudioTime; static timeWithHostTimeSampleTimeAtRate(hostTime: number, sampleTime: number, sampleRate: number): AVAudioTime; static timeWithSampleTimeAtRate(sampleTime: number, sampleRate: number): AVAudioTime; readonly audioTimeStamp: AudioTimeStamp; readonly hostTime: number; readonly hostTimeValid: boolean; readonly sampleRate: number; readonly sampleTime: number; readonly sampleTimeValid: boolean; constructor(o: { audioTimeStamp: interop.Pointer | interop.Reference<AudioTimeStamp>; sampleRate: number; }); constructor(o: { hostTime: number; }); constructor(o: { hostTime: number; sampleTime: number; atRate: number; }); constructor(o: { sampleTime: number; atRate: number; }); extrapolateTimeFromAnchor(anchorTime: AVAudioTime): AVAudioTime; initWithAudioTimeStampSampleRate(ts: interop.Pointer | interop.Reference<AudioTimeStamp>, sampleRate: number): this; initWithHostTime(hostTime: number): this; initWithHostTimeSampleTimeAtRate(hostTime: number, sampleTime: number, sampleRate: number): this; initWithSampleTimeAtRate(sampleTime: number, sampleRate: number): this; } declare class AVAudioUnit extends AVAudioNode { static alloc(): AVAudioUnit; // inherited from NSObject static instantiateWithComponentDescriptionOptionsCompletionHandler(audioComponentDescription: AudioComponentDescription, options: AudioComponentInstantiationOptions, completionHandler: (p1: AVAudioUnit, p2: NSError) => void): void; static new(): AVAudioUnit; // inherited from NSObject readonly audioComponentDescription: AudioComponentDescription; readonly audioUnit: interop.Pointer | interop.Reference<any>; readonly manufacturerName: string; readonly name: string; readonly version: number; loadAudioUnitPresetAtURLError(url: NSURL): boolean; } declare class AVAudioUnitComponent extends NSObject { static alloc(): AVAudioUnitComponent; // inherited from NSObject static new(): AVAudioUnitComponent; // inherited from NSObject readonly allTagNames: NSArray<string>; readonly audioComponent: interop.Pointer | interop.Reference<any>; readonly audioComponentDescription: AudioComponentDescription; readonly hasMIDIInput: boolean; readonly hasMIDIOutput: boolean; readonly localizedTypeName: string; readonly manufacturerName: string; readonly name: string; readonly sandboxSafe: boolean; readonly typeName: string; readonly version: number; readonly versionString: string; } declare class AVAudioUnitComponentManager extends NSObject { static alloc(): AVAudioUnitComponentManager; // inherited from NSObject static new(): AVAudioUnitComponentManager; // inherited from NSObject static sharedAudioUnitComponentManager(): AVAudioUnitComponentManager; readonly standardLocalizedTagNames: NSArray<string>; readonly tagNames: NSArray<string>; componentsMatchingDescription(desc: AudioComponentDescription): NSArray<AVAudioUnitComponent>; componentsMatchingPredicate(predicate: NSPredicate): NSArray<AVAudioUnitComponent>; componentsPassingTest(testHandler: (p1: AVAudioUnitComponent, p2: interop.Pointer | interop.Reference<boolean>) => boolean): NSArray<AVAudioUnitComponent>; } declare var AVAudioUnitComponentManagerRegistrationsChangedNotification: string; declare var AVAudioUnitComponentTagsDidChangeNotification: string; declare class AVAudioUnitDelay extends AVAudioUnitEffect { static alloc(): AVAudioUnitDelay; // inherited from NSObject static new(): AVAudioUnitDelay; // inherited from NSObject delayTime: number; feedback: number; lowPassCutoff: number; wetDryMix: number; } declare class AVAudioUnitDistortion extends AVAudioUnitEffect { static alloc(): AVAudioUnitDistortion; // inherited from NSObject static new(): AVAudioUnitDistortion; // inherited from NSObject preGain: number; wetDryMix: number; loadFactoryPreset(preset: AVAudioUnitDistortionPreset): void; } declare const enum AVAudioUnitDistortionPreset { DrumsBitBrush = 0, DrumsBufferBeats = 1, DrumsLoFi = 2, MultiBrokenSpeaker = 3, MultiCellphoneConcert = 4, MultiDecimated1 = 5, MultiDecimated2 = 6, MultiDecimated3 = 7, MultiDecimated4 = 8, MultiDistortedFunk = 9, MultiDistortedCubed = 10, MultiDistortedSquared = 11, MultiEcho1 = 12, MultiEcho2 = 13, MultiEchoTight1 = 14, MultiEchoTight2 = 15, MultiEverythingIsBroken = 16, SpeechAlienChatter = 17, SpeechCosmicInterference = 18, SpeechGoldenPi = 19, SpeechRadioTower = 20, SpeechWaves = 21 } declare class AVAudioUnitEQ extends AVAudioUnitEffect { static alloc(): AVAudioUnitEQ; // inherited from NSObject static new(): AVAudioUnitEQ; // inherited from NSObject readonly bands: NSArray<AVAudioUnitEQFilterParameters>; globalGain: number; constructor(o: { numberOfBands: number; }); initWithNumberOfBands(numberOfBands: number): this; } declare class AVAudioUnitEQFilterParameters extends NSObject { static alloc(): AVAudioUnitEQFilterParameters; // inherited from NSObject static new(): AVAudioUnitEQFilterParameters; // inherited from NSObject bandwidth: number; bypass: boolean; filterType: AVAudioUnitEQFilterType; frequency: number; gain: number; } declare const enum AVAudioUnitEQFilterType { Parametric = 0, LowPass = 1, HighPass = 2, ResonantLowPass = 3, ResonantHighPass = 4, BandPass = 5, BandStop = 6, LowShelf = 7, HighShelf = 8, ResonantLowShelf = 9, ResonantHighShelf = 10 } declare class AVAudioUnitEffect extends AVAudioUnit { static alloc(): AVAudioUnitEffect; // inherited from NSObject static new(): AVAudioUnitEffect; // inherited from NSObject bypass: boolean; constructor(o: { audioComponentDescription: AudioComponentDescription; }); initWithAudioComponentDescription(audioComponentDescription: AudioComponentDescription): this; } declare class AVAudioUnitGenerator extends AVAudioUnit implements AVAudioMixing { static alloc(): AVAudioUnitGenerator; // inherited from NSObject static new(): AVAudioUnitGenerator; // inherited from NSObject bypass: boolean; readonly debugDescription: string; // inherited from NSObjectProtocol readonly description: string; // inherited from NSObjectProtocol readonly hash: number; // inherited from NSObjectProtocol readonly isProxy: boolean; // inherited from NSObjectProtocol obstruction: number; // inherited from AVAudio3DMixing occlusion: number; // inherited from AVAudio3DMixing pan: number; // inherited from AVAudioStereoMixing pointSourceInHeadMode: AVAudio3DMixingPointSourceInHeadMode; // inherited from AVAudio3DMixing position: AVAudio3DPoint; // inherited from AVAudio3DMixing rate: number; // inherited from AVAudio3DMixing renderingAlgorithm: AVAudio3DMixingRenderingAlgorithm; // inherited from AVAudio3DMixing reverbBlend: number; // inherited from AVAudio3DMixing sourceMode: AVAudio3DMixingSourceMode; // inherited from AVAudio3DMixing readonly superclass: typeof NSObject; // inherited from NSObjectProtocol volume: number; // inherited from AVAudioMixing readonly // inherited from NSObjectProtocol constructor(o: { audioComponentDescription: AudioComponentDescription; }); class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; destinationForMixerBus(mixer: AVAudioNode, bus: number): AVAudioMixingDestination; initWithAudioComponentDescription(audioComponentDescription: AudioComponentDescription): this; isEqual(object: any): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; performSelector(aSelector: string): any; performSelectorWithObject(aSelector: string, object: any): any; performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any; respondsToSelector(aSelector: string): boolean; retainCount(): number; self(): this; } declare class AVAudioUnitMIDIInstrument extends AVAudioUnit implements AVAudioMixing { static alloc(): AVAudioUnitMIDIInstrument; // inherited from NSObject static new(): AVAudioUnitMIDIInstrument; // inherited from NSObject readonly debugDescription: string; // inherited from NSObjectProtocol readonly description: string; // inherited from NSObjectProtocol readonly hash: number; // inherited from NSObjectProtocol readonly isProxy: boolean; // inherited from NSObjectProtocol obstruction: number; // inherited from AVAudio3DMixing occlusion: number; // inherited from AVAudio3DMixing pan: number; // inherited from AVAudioStereoMixing pointSourceInHeadMode: AVAudio3DMixingPointSourceInHeadMode; // inherited from AVAudio3DMixing position: AVAudio3DPoint; // inherited from AVAudio3DMixing rate: number; // inherited from AVAudio3DMixing renderingAlgorithm: AVAudio3DMixingRenderingAlgorithm; // inherited from AVAudio3DMixing reverbBlend: number; // inherited from AVAudio3DMixing sourceMode: AVAudio3DMixingSourceMode; // inherited from AVAudio3DMixing readonly superclass: typeof NSObject; // inherited from NSObjectProtocol volume: number; // inherited from AVAudioMixing readonly // inherited from NSObjectProtocol constructor(o: { audioComponentDescription: AudioComponentDescription; }); class(): typeof NSObject; conformsToProtocol(aProtocol: any /* Protocol */): boolean; destinationForMixerBus(mixer: AVAudioNode, bus: number): AVAudioMixingDestination; initWithAudioComponentDescription(description: AudioComponentDescription): this; isEqual(object: any): boolean; isKindOfClass(aClass: typeof NSObject): boolean; isMemberOfClass(aClass: typeof NSObject): boolean; performSelector(aSelector: string): any; performSelectorWithObject(aSelector: string, object: any): any; performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any; respondsToSelector(aSelector: string): boolean; retainCount(): number; self(): this; sendControllerWithValueOnChannel(controller: number, value: number, channel: number): void; sendMIDIEventData1(midiStatus: number, data1: number): void; sendMIDIEventData1Data2(midiStatus: number, data1: number, data2: number): void; sendMIDISysExEvent(midiData: NSData): void; sendPitchBendOnChannel(pitchbend: number, channel: number): void; sendPressureForKeyWithValueOnChannel(key: number, value: number, channel: number): void; sendPressureOnChannel(pressure: number, channel: number): void; sendProgramChangeBankMSBBankLSBOnChannel(program: number, bankMSB: number, bankLSB: number, channel: number): void; sendProgramChangeOnChannel(program: number, channel: number): void; startNoteWithVelocityOnChannel(note: number, velocity: number, channel: number): void; stopNoteOnChannel(note: number, channel: number): void; } declare var AVAudioUnitManufacturerNameApple: string; declare class AVAudioUnitReverb extends AVAudioUnitEffect { static alloc(): AVAudioUnitReverb; // inherited from NSObject static new(): AVAudioUnitReverb; // inherited from NSObject wetDryMix: number; loadFactoryPreset(preset: AVAudioUnitReverbPreset): void; } declare const enum AVAudioUnitReverbPreset { SmallRoom = 0, MediumRoom = 1, LargeRoom = 2, MediumHall = 3, LargeHall = 4, Plate = 5, MediumChamber = 6, LargeChamber = 7, Cathedral = 8, LargeRoom2 = 9, MediumHall2 = 10, MediumHall3 = 11, LargeHall2 = 12 } declare class AVAudioUnitSampler extends AVAudioUnitMIDIInstrument { static alloc(): AVAudioUnitSampler; // inherited from NSObject static new(): AVAudioUnitSampler; // inherited from NSObject globalTuning: number; masterGain: number; overallGain: number; stereoPan: number; loadAudioFilesAtURLsError(audioFiles: NSArray<NSURL> | NSURL[]): boolean; loadInstrumentAtURLError(instrumentURL: NSURL): boolean; loadSoundBankInstrumentAtURLProgramBankMSBBankLSBError(bankURL: NSURL, program: number, bankMSB: number, bankLSB: number): boolean; } declare class AVAudioUnitTimeEffect extends AVAudioUnit { static alloc(): AVAudioUnitTimeEffect; // inherited from NSObject static new(): AVAudioUnitTimeEffect; // inherited from NSObject bypass: boolean; constructor(o: { audioComponentDescription: AudioComponentDescription; }); initWithAudioComponentDescription(audioComponentDescription: AudioComponentDescription): this; } declare class AVAudioUnitTimePitch extends AVAudioUnitTimeEffect { static alloc(): AVAudioUnitTimePitch; // inherited from NSObject static new(): AVAudioUnitTimePitch; // inherited from NSObject overlap: number; pitch: number; rate: number; } declare var AVAudioUnitTypeEffect: string; declare var AVAudioUnitTypeFormatConverter: string; declare var AVAudioUnitTypeGenerator: string; declare var AVAudioUnitTypeMIDIProcessor: string; declare var AVAudioUnitTypeMixer: string; declare var AVAudioUnitTypeMusicDevice: string; declare var AVAudioUnitTypeMusicEffect: string; declare var AVAudioUnitTypeOfflineEffect: string; declare var AVAudioUnitTypeOutput: string; declare var AVAudioUnitTypePanner: string; declare class AVAudioUnitVarispeed extends AVAudioUnitTimeEffect { static alloc(): AVAudioUnitVarispeed; // inherited from NSObject static new(): AVAudioUnitVarispeed; // inherited from NSObject rate: number; } interface AVBeatRange { start: number; length: number; } declare var AVBeatRange: interop.StructType<AVBeatRange>; declare var AVChannelLayoutKey: string; declare var AVEncoderAudioQualityForVBRKey: string; declare var AVEncoderAudioQualityKey: string; declare var AVEncoderBitDepthHintKey: string; declare var AVEncoderBitRateKey: string; declare var AVEncoderBitRatePerChannelKey: string; declare var AVEncoderBitRateStrategyKey: string; declare var AVFormatIDKey: string; declare var AVLinearPCMBitDepthKey: string; declare var AVLinearPCMIsBigEndianKey: string; declare var AVLinearPCMIsFloatKey: string; declare var AVLinearPCMIsNonInterleaved: string; declare class AVMIDIPlayer extends NSObject { static alloc(): AVMIDIPlayer; // inherited from NSObject static new(): AVMIDIPlayer; // inherited from NSObject currentPosition: number; readonly duration: number; readonly playing: boolean; rate: number; constructor(o: { contentsOfURL: NSURL; soundBankURL: NSURL; }); constructor(o: { data: NSData; soundBankURL: NSURL; }); initWithContentsOfURLSoundBankURLError(inURL: NSURL, bankURL: NSURL): this; initWithDataSoundBankURLError(data: NSData, bankURL: NSURL): this; play(completionHandler: () => void): void; prepareToPlay(): void; stop(): void; } declare const enum AVMusicSequenceLoadOptions { SMF_PreserveTracks = 0, SMF_ChannelsToTracks = 1 } declare class AVMusicTrack extends NSObject { static alloc(): AVMusicTrack; // inherited from NSObject static new(): AVMusicTrack; // inherited from NSObject destinationAudioUnit: AVAudioUnit; destinationMIDIEndpoint: number; lengthInBeats: number; lengthInSeconds: number; loopRange: AVBeatRange; loopingEnabled: boolean; muted: boolean; numberOfLoops: number; offsetTime: number; soloed: boolean; readonly timeResolution: number; } declare const enum AVMusicTrackLoopCount { Forever = -1 } declare var AVNumberOfChannelsKey: string; declare var AVSampleRateConverterAlgorithmKey: string; declare var AVSampleRateConverterAlgorithm_Mastering: string; declare var AVSampleRateConverterAlgorithm_MinimumPhase: string; declare var AVSampleRateConverterAlgorithm_Normal: string; declare var AVSampleRateConverterAudioQualityKey: string; declare var AVSampleRateKey: string; declare const enum AVSpeechBoundary { Immediate = 0, Word = 1 } declare var AVSpeechSynthesisIPANotationAttribute: string; declare class AVSpeechSynthesisVoice extends NSObject implements NSSecureCoding { static alloc(): AVSpeechSynthesisVoice; // inherited from NSObject static currentLanguageCode(): string; static new(): AVSpeechSynthesisVoice; // inherited from NSObject static speechVoices(): NSArray<AVSpeechSynthesisVoice>; static voiceWithIdentifier(identifier: string): AVSpeechSynthesisVoice; static voiceWithLanguage(languageCode: string): AVSpeechSynthesisVoice; readonly audioFileSettings: NSDictionary<string, any>; readonly gender: AVSpeechSynthesisVoiceGender; readonly identifier: string; readonly language: string; readonly name: string; readonly quality: AVSpeechSynthesisVoiceQuality; static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding constructor(o: { coder: NSCoder; }); // inherited from NSCoding encodeWithCoder(coder: NSCoder): void; initWithCoder(coder: NSCoder): this; } declare const enum AVSpeechSynthesisVoiceGender { Unspecified = 0, Male = 1, Female = 2 } declare var AVSpeechSynthesisVoiceIdentifierAlex: string; declare const enum AVSpeechSynthesisVoiceQuality { Default = 1, Enhanced = 2 } declare class AVSpeechSynthesizer extends NSObject { static alloc(): AVSpeechSynthesizer; // inherited from NSObject static new(): AVSpeechSynthesizer; // inherited from NSObject delegate: AVSpeechSynthesizerDelegate; mixToTelephonyUplink: boolean; outputChannels: NSArray<AVAudioSessionChannelDescription>; readonly paused: boolean; readonly speaking: boolean; usesApplicationAudioSession: boolean; continueSpeaking(): boolean; pauseSpeakingAtBoundary(boundary: AVSpeechBoundary): boolean; speakUtterance(utterance: AVSpeechUtterance): void; stopSpeakingAtBoundary(boundary: AVSpeechBoundary): boolean; writeUtteranceToBufferCallback(utterance: AVSpeechUtterance, bufferCallback: (p1: AVAudioBuffer) => void): void; } interface AVSpeechSynthesizerDelegate extends NSObjectProtocol { speechSynthesizerDidCancelSpeechUtterance?(synthesizer: AVSpeechSynthesizer, utterance: AVSpeechUtterance): void; speechSynthesizerDidContinueSpeechUtterance?(synthesizer: AVSpeechSynthesizer, utterance: AVSpeechUtterance): void; speechSynthesizerDidFinishSpeechUtterance?(synthesizer: AVSpeechSynthesizer, utterance: AVSpeechUtterance): void; speechSynthesizerDidPauseSpeechUtterance?(synthesizer: AVSpeechSynthesizer, utterance: AVSpeechUtterance): void; speechSynthesizerDidStartSpeechUtterance?(synthesizer: AVSpeechSynthesizer, utterance: AVSpeechUtterance): void; speechSynthesizerWillSpeakRangeOfSpeechStringUtterance?(synthesizer: AVSpeechSynthesizer, characterRange: NSRange, utterance: AVSpeechUtterance): void; } declare var AVSpeechSynthesizerDelegate: { prototype: AVSpeechSynthesizerDelegate; }; declare class AVSpeechUtterance extends NSObject implements NSCopying, NSSecureCoding { static alloc(): AVSpeechUtterance; // inherited from NSObject static new(): AVSpeechUtterance; // inherited from NSObject static speechUtteranceWithAttributedString(string: NSAttributedString): AVSpeechUtterance; static speechUtteranceWithString(string: string): AVSpeechUtterance; readonly attributedSpeechString: NSAttributedString; pitchMultiplier: number; postUtteranceDelay: number; preUtteranceDelay: number; prefersAssistiveTechnologySettings: boolean; rate: number; readonly speechString: string; voice: AVSpeechSynthesisVoice; volume: number; static readonly supportsSecureCoding: boolean; // inherited from NSSecureCoding constructor(o: { attributedString: NSAttributedString; }); constructor(o: { coder: NSCoder; }); // inherited from NSCoding constructor(o: { string: string; }); copyWithZone(zone: interop.Pointer | interop.Reference<any>): any; encodeWithCoder(coder: NSCoder): void; initWithAttributedString(string: NSAttributedString): this; initWithCoder(coder: NSCoder): this; initWithString(string: string): this; } declare var AVSpeechUtteranceDefaultSpeechRate: number; declare var AVSpeechUtteranceMaximumSpeechRate: number; declare var AVSpeechUtteranceMinimumSpeechRate: number;
the_stack
import fs from 'fs' import assert from 'assert' import Network from '../../src/service/network' import config from '../../src/config' import Config from '../../src/service/config' import { NetworkCreateType } from '../../src/model/type/network.type' describe('Network service:', function () { this.timeout(10000) let networkService: Network let networkCreateJson: NetworkCreateType before(() => { networkCreateJson = JSON.parse(fs.readFileSync('./cicd/test_script/network-create.json').toString()) }) describe('createNetworkFolder', () => { before(() => { (new Config(config)).init() }) after(() => { fs.unlinkSync(`${config.infraConfig.bdkPath}/.env`) fs.rmSync(`${config.infraConfig.bdkPath}/${config.networkName}`, { recursive: true }) }) it('should exist network folder in specified path', () => { networkService = new Network(config) networkService.createNetworkFolder() assert.strictEqual(fs.existsSync(`${config.infraConfig.bdkPath}/${config.networkName}`), true) }) }) describe('cryptogen', () => { before(() => { (new Config(config)).init() networkService = new Network(config) networkService.createNetworkFolder() }) after(() => { fs.unlinkSync(`${config.infraConfig.bdkPath}/.env`) fs.rmSync(`${config.infraConfig.bdkPath}/${config.networkName}`, { recursive: true }) }) it('should generate ca file when function cryptogen done', async () => { await networkService.cryptogen(networkCreateJson) /** * config-yaml */ assert.strictEqual(fs.existsSync(`${config.infraConfig.bdkPath}/${config.networkName}/config-yaml/crypto-config.yaml`), true) /** * ordererOrganizations */ networkCreateJson.ordererOrgs.forEach((ordererOrg) => { const ordererOrgPath = `${config.infraConfig.bdkPath}/${config.networkName}/ordererOrganizations/${ordererOrg.domain}` // folder assert.strictEqual(fs.existsSync(`${ordererOrgPath}`), true) // ca assert.strictEqual(fs.existsSync(`${ordererOrgPath}/ca/ca.${ordererOrg.domain}-cert.pem`), true) assert.strictEqual(fs.existsSync(`${ordererOrgPath}/ca/priv_sk`), true) // tlsca assert.strictEqual(fs.existsSync(`${ordererOrgPath}/tlsca/tlsca.${ordererOrg.domain}-cert.pem`), true) assert.strictEqual(fs.existsSync(`${ordererOrgPath}/tlsca/priv_sk`), true) // yaml assert.strictEqual(fs.existsSync(`${ordererOrgPath}/users/Admin@${ordererOrg.domain}/msp/config.yaml`), true) // tls assert.strictEqual(fs.existsSync(`${ordererOrgPath}/users/Admin@${ordererOrg.domain}/tls/ca.crt`), true) assert.strictEqual(fs.existsSync(`${ordererOrgPath}/users/Admin@${ordererOrg.domain}/tls/client.crt`), true) assert.strictEqual(fs.existsSync(`${ordererOrgPath}/users/Admin@${ordererOrg.domain}/tls/client.key`), true) // orderers ordererOrg.hostname.forEach((hostname) => { const hostPath = `${ordererOrgPath}/orderers/${hostname}.${ordererOrg.domain}` // folder assert.strictEqual(fs.existsSync(hostPath), true) // msp assert.strictEqual(fs.existsSync(`${hostPath}/msp/config.yaml`), true) assert.strictEqual(fs.existsSync(`${hostPath}/msp/signcerts/${hostname}.${ordererOrg.domain}-cert.pem`), true) // tls assert.strictEqual(fs.existsSync(`${hostPath}/tls/ca.crt`), true) assert.strictEqual(fs.existsSync(`${hostPath}/tls/server.crt`), true) assert.strictEqual(fs.existsSync(`${hostPath}/tls/server.key`), true) }) }) /** * peerOrganizations */ networkCreateJson.peerOrgs.forEach((peerOrg) => { const peerOrgPath = `${config.infraConfig.bdkPath}/${config.networkName}/peerOrganizations/${peerOrg.domain}` // folder assert.strictEqual(fs.existsSync(`${peerOrgPath}`), true) // ca assert.strictEqual(fs.existsSync(`${peerOrgPath}/ca/ca.${peerOrg.domain}-cert.pem`), true) assert.strictEqual(fs.existsSync(`${peerOrgPath}/ca/priv_sk`), true) // tlsca assert.strictEqual(fs.existsSync(`${peerOrgPath}/tlsca/tlsca.${peerOrg.domain}-cert.pem`), true) assert.strictEqual(fs.existsSync(`${peerOrgPath}/tlsca/priv_sk`), true) // yaml assert.strictEqual(fs.existsSync(`${peerOrgPath}/users/Admin@${peerOrg.domain}/msp/config.yaml`), true) // tls assert.strictEqual(fs.existsSync(`${peerOrgPath}/users/Admin@${peerOrg.domain}/tls/ca.crt`), true) assert.strictEqual(fs.existsSync(`${peerOrgPath}/users/Admin@${peerOrg.domain}/tls/client.crt`), true) assert.strictEqual(fs.existsSync(`${peerOrgPath}/users/Admin@${peerOrg.domain}/tls/client.key`), true) // peers peerCount for (let index = 0; index < peerOrg.peerCount; index++) { const hostname = `peer${index}` const hostPath = `${peerOrgPath}/peers/${hostname}.${peerOrg.domain}` // folder assert.strictEqual(fs.existsSync(hostPath), true) // msp assert.strictEqual(fs.existsSync(`${hostPath}/msp/config.yaml`), true) assert.strictEqual(fs.existsSync(`${hostPath}/msp/signcerts/${hostname}.${peerOrg.domain}-cert.pem`), true) // tls assert.strictEqual(fs.existsSync(`${hostPath}/tls/ca.crt`), true) assert.strictEqual(fs.existsSync(`${hostPath}/tls/server.crt`), true) assert.strictEqual(fs.existsSync(`${hostPath}/tls/server.key`), true) } }) }) }) describe('copyTLSCa', () => { before(async () => { (new Config(config)).init() networkService = new Network(config) networkService.createNetworkFolder() await networkService.cryptogen(networkCreateJson) }) after(() => { fs.unlinkSync(`${config.infraConfig.bdkPath}/.env`) fs.rmSync(`${config.infraConfig.bdkPath}/${config.networkName}`, { recursive: true }) }) it('should copy the TLS CA to the specified folder under the blockchain network', () => { networkService.copyTLSCa(networkCreateJson) assert.strictEqual(fs.existsSync(`${config.infraConfig.bdkPath}/${config.networkName}/tlsca`), true) networkCreateJson.ordererOrgs.forEach((ordererOrg) => { ordererOrg.hostname.forEach((hostname) => { assert.strictEqual(fs.existsSync(`${config.infraConfig.bdkPath}/${config.networkName}/tlsca/${hostname}.${ordererOrg.domain}`), true) }) }) networkCreateJson.peerOrgs.forEach((peerOrg) => { for (let index = 0; index < peerOrg.peerCount; index++) { assert.strictEqual(fs.existsSync(`${config.infraConfig.bdkPath}/${config.networkName}/tlsca/peer${index}.${peerOrg.domain}`), true) } }) }) }) describe('createGenesisBlock', () => { before(async () => { (new Config(config)).init() networkService = new Network(config) networkService.createNetworkFolder() await networkService.cryptogen(networkCreateJson) networkService.copyTLSCa(networkCreateJson) }) after(() => { fs.unlinkSync(`${config.infraConfig.bdkPath}/.env`) fs.rmSync(`${config.infraConfig.bdkPath}/${config.networkName}`, { recursive: true }) }) it('should generate genesis.block file and org-json file', async () => { await networkService.createGenesisBlock(networkCreateJson) assert.strictEqual(fs.existsSync(`${config.infraConfig.bdkPath}/${config.networkName}/channel-artifacts/system-channel/genesis.block`), true) assert.strictEqual(fs.existsSync(`${config.infraConfig.bdkPath}/${config.networkName}/config-yaml/configtx.yaml`), true) networkCreateJson.ordererOrgs.forEach((ordererOrg) => { assert.strictEqual(fs.existsSync(`${config.infraConfig.bdkPath}/${config.networkName}/config-yaml/orgs/orderer-${ordererOrg.name}.json`), true) assert.strictEqual(fs.existsSync(`${config.infraConfig.bdkPath}/${config.networkName}/org-json/${ordererOrg.name}-consenter.json`), true) assert.strictEqual(fs.existsSync(`${config.infraConfig.bdkPath}/${config.networkName}/org-json/${ordererOrg.name}.json`), true) }) networkCreateJson.peerOrgs.forEach((peerOrg) => { assert.strictEqual(fs.existsSync(`${config.infraConfig.bdkPath}/${config.networkName}/config-yaml/orgs/peer-${peerOrg.name}.json`), true) assert.strictEqual(fs.existsSync(`${config.infraConfig.bdkPath}/${config.networkName}/org-json/${peerOrg.name}.json`), true) }) }) }) describe('createConnectionProfile', () => { before(async () => { (new Config(config)).init() networkService = new Network(config) networkService.createNetworkFolder() await networkService.cryptogen(networkCreateJson) networkService.copyTLSCa(networkCreateJson) await networkService.createGenesisBlock(networkCreateJson) }) after(() => { fs.unlinkSync(`${config.infraConfig.bdkPath}/.env`) fs.rmSync(`${config.infraConfig.bdkPath}/${config.networkName}`, { recursive: true }) }) it('should generate peer connection profile file', () => { networkService.createConnectionProfile(networkCreateJson) networkCreateJson.peerOrgs.forEach((peerOrg) => { const filePath = `${config.infraConfig.bdkPath}/${config.networkName}/peerOrganizations/${peerOrg.domain}` assert.strictEqual(fs.existsSync(`${filePath}/connection-${peerOrg.name}.json`), true) assert.strictEqual(fs.existsSync(`${filePath}/connection-${peerOrg.name}.yaml`), true) }) }) it.skip('should throw error when peerOrgs is undefined', () => { // TODO }) }) describe('createDockerCompose', () => { before(async () => { (new Config(config)).init() networkService = new Network(config) networkService.createNetworkFolder() await networkService.cryptogen(networkCreateJson) networkService.copyTLSCa(networkCreateJson) await networkService.createGenesisBlock(networkCreateJson) networkService.createConnectionProfile(networkCreateJson) }) after(() => { fs.unlinkSync(`${config.infraConfig.bdkPath}/.env`) fs.rmSync(`${config.infraConfig.bdkPath}/${config.networkName}`, { recursive: true }) }) it('should generate orderer/peer docker-compose file', () => { networkService.createDockerCompose(networkCreateJson) const dockerCompsoePath = `${config.infraConfig.bdkPath}/${config.networkName}/docker-compose` const dockerEnvPath = `${config.infraConfig.bdkPath}/${config.networkName}/env` assert.strictEqual(fs.existsSync(`${dockerCompsoePath}`), true) assert.strictEqual(fs.existsSync(`${dockerEnvPath}`), true) networkCreateJson.ordererOrgs.forEach((ordererOrg) => { ordererOrg.hostname.forEach((hostname) => { assert.strictEqual(fs.existsSync(`${dockerCompsoePath}/docker-compose-orderer-${hostname}.${ordererOrg.domain}.yaml`), true) assert.strictEqual(fs.existsSync(`${dockerEnvPath}/orderer-${hostname}.${ordererOrg.domain}.env`), true) }) }) networkCreateJson.peerOrgs.forEach((peerOrg) => { for (let index = 0; index < peerOrg.peerCount; index++) { assert.strictEqual(fs.existsSync(`${dockerCompsoePath}/docker-compose-peer-peer${index}.${peerOrg.domain}.yaml`), true) assert.strictEqual(fs.existsSync(`${dockerEnvPath}/peer-peer${index}.${peerOrg.domain}.env`), true) } }) }) }) describe('delete', () => { beforeEach(() => { (new Config(config)).init() networkService = new Network(config) networkService.createNetworkFolder() }) after(() => { fs.unlinkSync(`${config.infraConfig.bdkPath}/.env`) fs.rmSync(`${config.infraConfig.bdkPath}/${config.networkName}`, { recursive: true, force: true }) }) it.skip('should shutdown docker container', async () => { await networkService.cryptogen(networkCreateJson) networkService.copyTLSCa(networkCreateJson) await networkService.createGenesisBlock(networkCreateJson) networkService.createConnectionProfile(networkCreateJson) networkService.createDockerCompose(networkCreateJson) // TODO start container await networkService.delete(config.networkName) assert.strictEqual(fs.existsSync(`${config.infraConfig.bdkPath}/${config.networkName}`), false) }) it('should delete network folder in specified path', async () => { await networkService.delete(config.networkName) assert.strictEqual(fs.existsSync(`${config.infraConfig.bdkPath}/${config.networkName}`), false) }) }) })
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace Formmsdyn_workorderservicetask_Information { interface tab_tab_6_Sections { tab_6_section_1: DevKit.Controls.Section; } interface tab_tab_7_Sections { tab_7_section_1: DevKit.Controls.Section; } interface tab_tab_6 extends DevKit.Controls.ITab { Section: tab_tab_6_Sections; } interface tab_tab_7 extends DevKit.Controls.ITab { Section: tab_tab_7_Sections; } interface Tabs { tab_6: tab_tab_6; tab_7: tab_tab_7; } interface Body { Tab: Tabs; msdyn_ActualDuration: DevKit.Controls.Integer; /** Agreement Booking Service Task linked to this Work Order Service Task */ msdyn_AgreementBookingServiceTask: DevKit.Controls.Lookup; /** Agreement Booking Service Task linked to this Work Order Service Task */ msdyn_AgreementBookingServiceTask_1: DevKit.Controls.Lookup; /** Unique identifier for Resource Booking associated with Work Order Service Task. */ msdyn_Booking: DevKit.Controls.Lookup; /** Unique identifier for Resource Booking associated with Work Order Service Task. */ msdyn_Booking_1: DevKit.Controls.Lookup; /** Unique identifier for Customer Asset associated with Work Order Service Task. */ msdyn_CustomerAsset: DevKit.Controls.Lookup; /** Unique identifier for Customer Asset associated with Work Order Service Task. */ msdyn_CustomerAsset_1: DevKit.Controls.Lookup; msdyn_Description: DevKit.Controls.String; msdyn_Description_1: DevKit.Controls.String; msdyn_EstimatedDuration: DevKit.Controls.Integer; /** Unique identifier for Inspection Template associated with Work Order Service Task. */ msdyn_Inspection: DevKit.Controls.Lookup; /** Unique identifier for Inspection Definition associated with Work Order Service Task. */ msdyn_inspectiondefinitionid: DevKit.Controls.Lookup; /** Depicts whether inspection template is enabled for Work Order Service Task Type. */ msdyn_InspectionEnabled: DevKit.Controls.Boolean; /** Depicts the result of Inspection that the user enters */ msdyn_inspectiontaskresult: DevKit.Controls.OptionSet; /** Shows the order of this task within the work order service tasks. */ msdyn_LineOrder: DevKit.Controls.Integer; /** Enter the name of the custom entity. */ msdyn_name: DevKit.Controls.String; msdyn_PercentComplete: DevKit.Controls.Double; /** For internal use only */ msdyn_surveyboundedoutput: DevKit.Controls.String; /** Unique identifier for Service Task Type associated with Work Order Service Task. */ msdyn_TaskType: DevKit.Controls.Lookup; /** Unique identifier for Work Order associated with Work Order Service Task. */ msdyn_WorkOrder: DevKit.Controls.Lookup; /** Unique identifier for Work Order Incident associated with Work Order Service Task. */ msdyn_WorkOrderIncident: DevKit.Controls.Lookup; /** Unique identifier for Work Order Incident associated with Work Order Service Task. */ msdyn_WorkOrderIncident_1: DevKit.Controls.Lookup; notescontrol: DevKit.Controls.Note; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } interface Footer extends DevKit.Controls.IFooter { /** Status of the Work Order Service Task */ statecode: DevKit.Controls.OptionSet; } interface Navigation { navProcessSessions: DevKit.Controls.NavigationItem } } class Formmsdyn_workorderservicetask_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form msdyn_workorderservicetask_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form msdyn_workorderservicetask_Information */ Body: DevKit.Formmsdyn_workorderservicetask_Information.Body; /** The Footer section of form msdyn_workorderservicetask_Information */ Footer: DevKit.Formmsdyn_workorderservicetask_Information.Footer; /** The Navigation of form msdyn_workorderservicetask_Information */ Navigation: DevKit.Formmsdyn_workorderservicetask_Information.Navigation; } namespace FormWork_Order_Service_Task_Mobile { interface tab__1932B377_2E7E_4880_9B0E_477CC529B5FE_Sections { _1932B377_2E7E_4880_9B0E_477CC529B5FE_SECTION_2: DevKit.Controls.Section; _594A0AD8_A9A3_4509_9E40_52F6789D7512: DevKit.Controls.Section; fstab_general_section_duration: DevKit.Controls.Section; fstab_sub_grids_section: DevKit.Controls.Section; InspectionFormSection_Mobile: DevKit.Controls.Section; tab_3_section_1: DevKit.Controls.Section; } interface tab__1932B377_2E7E_4880_9B0E_477CC529B5FE extends DevKit.Controls.ITab { Section: tab__1932B377_2E7E_4880_9B0E_477CC529B5FE_Sections; } interface Tabs { _1932B377_2E7E_4880_9B0E_477CC529B5FE: tab__1932B377_2E7E_4880_9B0E_477CC529B5FE; } interface Body { Tab: Tabs; msdyn_ActualDuration: DevKit.Controls.Integer; /** Unique identifier for Resource Booking associated with Work Order Service Task. */ msdyn_Booking: DevKit.Controls.Lookup; /** Unique identifier for Customer Asset associated with Work Order Service Task. */ msdyn_CustomerAsset: DevKit.Controls.Lookup; msdyn_Description: DevKit.Controls.String; msdyn_EstimatedDuration: DevKit.Controls.Integer; /** Unique identifier for Inspection Template associated with Work Order Service Task. */ msdyn_Inspection: DevKit.Controls.Lookup; /** Unique identifier for Inspection Definition associated with Work Order Service Task. */ msdyn_inspectiondefinitionid: DevKit.Controls.Lookup; /** Depicts whether inspection template is enabled for Work Order Service Task Type. */ msdyn_InspectionEnabled: DevKit.Controls.Boolean; /** Depicts the result of Inspection that the user enters */ msdyn_inspectiontaskresult: DevKit.Controls.OptionSet; /** Enter the name of the custom entity. */ msdyn_name: DevKit.Controls.String; msdyn_PercentComplete: DevKit.Controls.Double; /** For internal use only */ msdyn_surveyboundedoutput: DevKit.Controls.String; /** Unique identifier for Service Task Type associated with Work Order Service Task. */ msdyn_TaskType: DevKit.Controls.Lookup; /** Unique identifier for Work Order associated with Work Order Service Task. */ msdyn_WorkOrder: DevKit.Controls.Lookup; /** Unique identifier for Work Order Incident associated with Work Order Service Task. */ msdyn_WorkOrderIncident: DevKit.Controls.Lookup; notescontrol: DevKit.Controls.Note; /** Owner Id */ OwnerId: DevKit.Controls.Lookup; } interface Navigation { navAsyncOperations: DevKit.Controls.NavigationItem, navProcessSessions: DevKit.Controls.NavigationItem } } class FormWork_Order_Service_Task_Mobile extends DevKit.IForm { /** * DynamicsCrm.DevKit form Work_Order_Service_Task_Mobile * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Work_Order_Service_Task_Mobile */ Body: DevKit.FormWork_Order_Service_Task_Mobile.Body; /** The Navigation of form Work_Order_Service_Task_Mobile */ Navigation: DevKit.FormWork_Order_Service_Task_Mobile.Navigation; } class msdyn_workorderservicetaskApi { /** * DynamicsCrm.DevKit msdyn_workorderservicetaskApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Unique identifier of the user who created the record. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was created. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Shows the sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who modified the record. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Shows the date and time when the record was last updated. The date and time are displayed in the time zone selected in Microsoft Dynamics 365 options. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who last updated the record on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; msdyn_ActualDuration: DevKit.WebApi.IntegerValue; /** Agreement Booking Service Task linked to this Work Order Service Task */ msdyn_AgreementBookingServiceTask: DevKit.WebApi.LookupValue; /** Unique identifier for Resource Booking associated with Work Order Service Task. */ msdyn_Booking: DevKit.WebApi.LookupValue; /** Unique identifier for Customer Asset associated with Work Order Service Task. */ msdyn_CustomerAsset: DevKit.WebApi.LookupValue; msdyn_Description: DevKit.WebApi.StringValue; msdyn_EstimatedDuration: DevKit.WebApi.IntegerValue; /** Unique identifier for Inspection Template associated with Work Order Service Task. */ msdyn_Inspection: DevKit.WebApi.LookupValue; /** Unique identifier for Inspection Definition associated with Work Order Service Task. */ msdyn_inspectiondefinitionid: DevKit.WebApi.LookupValue; /** Depicts whether inspection template is enabled for Work Order Service Task Type. */ msdyn_InspectionEnabled: DevKit.WebApi.BooleanValue; /** Unique identifier for Inspection Response associated with Work Order Service Task. */ msdyn_inspectionresponseid: DevKit.WebApi.LookupValue; /** Output of the Inspection. */ msdyn_InspectionResult: DevKit.WebApi.OptionSetValue; /** Depicts the result of Inspection that the user enters */ msdyn_inspectiontaskresult: DevKit.WebApi.OptionSetValue; /** For internal use only. */ msdyn_InternalFlags: DevKit.WebApi.StringValue; /** Shows the order of this task within the work order service tasks. */ msdyn_LineOrder: DevKit.WebApi.IntegerValue; /** Enter the name of the custom entity. */ msdyn_name: DevKit.WebApi.StringValue; msdyn_PercentComplete: DevKit.WebApi.DoubleValue; /** For internal use only */ msdyn_surveyboundedoutput: DevKit.WebApi.StringValue; /** Unique identifier for Service Task Type associated with Work Order Service Task. */ msdyn_TaskType: DevKit.WebApi.LookupValue; /** Unique identifier for Work Order associated with Work Order Service Task. */ msdyn_WorkOrder: DevKit.WebApi.LookupValue; /** Unique identifier for Work Order Incident associated with Work Order Service Task. */ msdyn_WorkOrderIncident: DevKit.WebApi.LookupValue; /** Shows the entity instances. */ msdyn_workorderservicetaskId: DevKit.WebApi.GuidValue; /** Shows the date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Enter the user who is assigned to manage the record. This field is updated every time the record is assigned to a different user */ OwnerId_systemuser: DevKit.WebApi.LookupValue; /** Enter the team who is assigned to manage the record. This field is updated every time the record is assigned to a different team */ OwnerId_team: DevKit.WebApi.LookupValue; /** Unique identifier for the business unit that owns the record */ OwningBusinessUnit: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the team that owns the record. */ OwningTeam: DevKit.WebApi.LookupValueReadonly; /** Unique identifier for the user that owns the record. */ OwningUser: DevKit.WebApi.LookupValueReadonly; /** Status of the Work Order Service Task */ statecode: DevKit.WebApi.OptionSetValue; /** Reason for the status of the Work Order Service Task */ statuscode: DevKit.WebApi.OptionSetValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Shows the time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace msdyn_workorderservicetask { enum msdyn_InspectionResult { /** 100000001 */ Fail, /** 100000002 */ Invalid, /** 100000000 */ Pass } enum msdyn_inspectiontaskresult { /** 192350001 */ Fail, /** 192350003 */ NA, /** 192350002 */ Partial_Success, /** 192350000 */ Pass } enum statecode { /** 0 */ Active, /** 1 */ Inactive } enum statuscode { /** 1 */ Active, /** 2 */ Inactive } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information','Work Order Service Task - Mobile'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import { WebDNNWebGLContext, WebGLUniformItem, } from "../../../../interface/backend/webgl/webglContext"; import { WebGLTensor } from "../../../../interface/backend/webgl/webglTensor"; import { OperatorEntry } from "../../../../interface/core/operator"; import { Tensor } from "../../../../interface/core/tensor"; import { ConvTranspose } from "../../../base/convtranspose"; import { shaderGenHeader, shaderGenOutput, shaderGenTensorNDGet, shaderGenTensorNDGetUniformItem, shaderGenTensorOutputCoordsWithReturn, shaderGenTensorOutputUniform, shaderGenTensorOutputUniformItem, } from "../../shaderHelper"; export class WebGLConvTranspose extends ConvTranspose { constructor() { super("webgl"); } async run(context: WebDNNWebGLContext, inputs: Tensor[]): Promise<Tensor[]> { context.assertsWebGLTensorArray(inputs); const inputX = inputs[0], inputW = inputs[1], inputB = inputs[2]; // TODO: 2D以外対応 if (inputX.ndim !== 4) { throw new Error("ConvTranspose other than 2D is not yet supported"); } const { batch, dilations, group, kernelShape, pads, strides, inShape, outShape, chIn, chInPerGroup, chOut, chOutPerGroup, } = this.calcShape(inputX.dims, inputW.dims); if ( inputX.dimPerPixel !== 1 || inputW.dimPerPixel !== 1 || (inputB && inputB.dimPerPixel !== 1) ) { throw new Error(); } const inputTransposeData = context.emptyTensor([ chIn * batch * inShape[0] * inShape[1], ]); await this.transposeInput( context, inputX, inputTransposeData, group, batch, inShape[0] * inShape[1], chInPerGroup ); const weightTransposeData = context.emptyTensor([ chOut * kernelShape[0] * kernelShape[1] * chInPerGroup, ]); await this.transposeWeight( context, inputW, weightTransposeData, group, chInPerGroup, chOutPerGroup, kernelShape[0] * kernelShape[1] ); const matmulData = context.emptyTensor([ chOut * batch * inShape[0] * inShape[1] * kernelShape[0] * kernelShape[1], ]); await this.matmul( context, inputTransposeData, weightTransposeData, matmulData, group, batch * inShape[0] * inShape[1], chOutPerGroup * kernelShape[0] * kernelShape[1], chInPerGroup ); inputTransposeData.dispose(); weightTransposeData.dispose(); const output = context.emptyTensor([ batch, chOut, outShape[0], outShape[1], ]); if (inputB) { const col2ImData = context.emptyTensor([ batch * chOut * outShape[0] * outShape[1], ]); await this.col2im( context, matmulData, col2ImData, batch, dilations, group, kernelShape, pads, strides, inShape, outShape, chOutPerGroup ); matmulData.dispose(); await this.bias( context, col2ImData, inputB, output, batch, chOut, outShape[0] * outShape[1] ); col2ImData.dispose(); } else { await this.col2im( context, matmulData, output, batch, dilations, group, kernelShape, pads, strides, inShape, outShape, chOutPerGroup ); matmulData.dispose(); } return [output]; } private async col2im( context: WebDNNWebGLContext, dI: WebGLTensor, dY: WebGLTensor, batch: number, dilations: number[], group: number, kernelShape: number[], pads: number[], strides: number[], inShape: number[], outShape: number[], chOutPerGroup: number ) { // dI: group, batch, inShape[0], inShape[1], chOutPerGroup, kernelShape[0], kernelShape[1] // dY: batch, group, chOutPerGroup, outShape[0], outShape[1] const kernelName = `convtranspose_col2im_${kernelShape[0]}_${kernelShape[1]}_${strides[0]}_${strides[1]}_${pads[0]}_${pads[1]}_${dilations[0]}_${dilations[1]}`; if (!context.hasKernel(kernelName)) { const kernelSource = `${shaderGenHeader(context.webgl2)} ${shaderGenTensorOutputUniform(1)} #define K0 ${kernelShape[0]} #define K1 ${kernelShape[1]} #define S0 ${strides[0]} #define S1 ${strides[1]} #define P0 ${pads[0]} #define P1 ${pads[1]} #define D0 ${dilations[0]} #define D1 ${dilations[1]} uniform int GROUP; uniform int BATCH; uniform int O0; uniform int O1; uniform int COPG; uniform int IS0; uniform int IS1; ${shaderGenTensorNDGet("tex_input", 1, context.webgl2)} void main() { ${shaderGenTensorOutputCoordsWithReturn(1)} int rem = tex_output_flat; int quo = rem / O1; int o1 = rem - quo * O1; rem = quo; quo = rem / O0; int o0 = rem - quo * O0; rem = quo; quo = rem / COPG; int co = rem - quo * COPG; rem = quo; quo = rem / GROUP; int g = rem - quo * GROUP; int b = quo; float s = 0.0; for (int k0 = 0; k0 < K0; k0++) { for (int k1 = 0; k1 < K1; k1++) { int i0s = o0 + P0 - k0 * D0; int i1s = o1 + P1 - k1 * D1; int i0 = i0s / S0; if (i0s - i0 * S0 != 0 || i0 < 0 || i0 >= IS0) { continue; } int i1 = i1s / S1; if (i1s - i1 * S1 != 0 || i1 < 0 || i1 >= IS1) { continue; } s += get_tex_input((((((g * BATCH + b) * IS0 + i0) * IS1 + i1) * COPG + co) * K0 + k0) * K1 + k1); } } ${shaderGenOutput("s", context.webgl2)} return; } `; context.addKernel(kernelName, kernelSource); } const uniforms: WebGLUniformItem[] = [ ...shaderGenTensorNDGetUniformItem("tex_input", [1], dI, context.webgl2), ...shaderGenTensorOutputUniformItem([dY.length], dY, context.webgl2), { name: "GROUP", type: "int", value: group }, { name: "BATCH", type: "int", value: batch }, { name: "O0", type: "int", value: outShape[0] }, { name: "O1", type: "int", value: outShape[1] }, { name: "COPG", type: "int", value: chOutPerGroup }, { name: "IS0", type: "int", value: inShape[0] }, { name: "IS1", type: "int", value: inShape[1] }, ]; await context.runKernel( kernelName, [{ tensor: dI, name: "tex_input" }], dY, uniforms ); } private async matmul( context: WebDNNWebGLContext, dTX: WebGLTensor, dTW: WebGLTensor, dI: WebGLTensor, group: number, bin: number, cks: number, chInPerGroup: number ) { /* dTX(group, batch*inShape[0]*inShape[1]=bin, chInPerGroup) * dTW(group, chOutPerGroup*kernelShape[0]*kernelShape[1]=cks, chInPerGroup) -> dI(group, bin, cks) * ループ回数は定数が必要 */ const kernelName = `convtranspose_matmul_${chInPerGroup}`; if (!context.hasKernel(kernelName)) { const kernelSource = `${shaderGenHeader(context.webgl2)} ${shaderGenTensorOutputUniform(1)} #define cipg ${chInPerGroup} uniform int GROUP; uniform int BIN; uniform int CKS; ${shaderGenTensorNDGet("tex_input_w", 1, context.webgl2)} ${shaderGenTensorNDGet("tex_input_i", 1, context.webgl2)} void main() { ${shaderGenTensorOutputCoordsWithReturn(1)} int rem = tex_output_flat; int quo = rem / CKS; int x = rem - quo * CKS; rem = quo; quo = rem / BIN; int y = rem - quo * BIN; int g = quo; float s = 0.0; for (int ip = 0; ip < cipg; ip++) { s += get_tex_input_i((g * BIN + y) * cipg + ip) * get_tex_input_w((g * CKS + x) * cipg + ip); } ${shaderGenOutput("s", context.webgl2)} return; } `; context.addKernel(kernelName, kernelSource); } const uniforms: WebGLUniformItem[] = [ ...shaderGenTensorNDGetUniformItem( "tex_input_w", [1], dTW, context.webgl2 ), ...shaderGenTensorNDGetUniformItem( "tex_input_i", [1], dTX, context.webgl2 ), ...shaderGenTensorOutputUniformItem([dI.length], dI, context.webgl2), { name: "GROUP", type: "int", value: group }, { name: "BIN", type: "int", value: bin }, { name: "CKS", type: "int", value: cks }, ]; await context.runKernel( kernelName, [ { tensor: dTW, name: "tex_input_w" }, { tensor: dTX, name: "tex_input_i" }, ], dI, uniforms ); } private async transposeInput( context: WebDNNWebGLContext, dX: WebGLTensor, dTX: WebGLTensor, group: number, batch: number, inarea: number, chInPerGroup: number ) { // dX(batch, group, chInPerGroup, inShape[0], inShape[1]) -> dTX(group, batch, inShape[0], inShape[1], chInPerGroup) const kernelName = `convtranspose_transpose_input`; const kernelSource = `${shaderGenHeader(context.webgl2)} ${shaderGenTensorOutputUniform(4)} ${shaderGenTensorNDGet("tex_input", 4, context.webgl2)} void main() { ${shaderGenTensorOutputCoordsWithReturn(4)} float s = get_tex_input(tex_output_0, tex_output_1, tex_output_2, tex_output_3); ${shaderGenOutput("s", context.webgl2)} return; } `; context.addKernel(kernelName, kernelSource); const uniforms: WebGLUniformItem[] = [ ...shaderGenTensorNDGetUniformItem( "tex_input", [chInPerGroup * inarea, group * chInPerGroup * inarea, 1, inarea], dX, context.webgl2 ), ...shaderGenTensorOutputUniformItem( [group, batch, inarea, chInPerGroup], dTX, context.webgl2 ), ]; await context.runKernel( kernelName, [{ tensor: dX, name: "tex_input" }], dTX, uniforms ); } private async transposeWeight( context: WebDNNWebGLContext, dW: WebGLTensor, dTW: WebGLTensor, group: number, chInPerGroup: number, chOutPerGroup: number, karea: number ) { // dW(group, chInPerGroup, chOutPerGroup, kernelShape[0], kernelShape[1]) -> dTW(group, chOutPerGroup, kernelShape[0], kernelShape[1], cInPerGroup) const kernelName = `convtranspose_transpose_weight`; const kernelSource = `${shaderGenHeader(context.webgl2)} ${shaderGenTensorOutputUniform(4)} ${shaderGenTensorNDGet("tex_input", 4, context.webgl2)} void main() { ${shaderGenTensorOutputCoordsWithReturn(4)} float s = get_tex_input(tex_output_0, tex_output_1, tex_output_2, tex_output_3); ${shaderGenOutput("s", context.webgl2)} return; } `; context.addKernel(kernelName, kernelSource); const uniforms: WebGLUniformItem[] = [ ...shaderGenTensorNDGetUniformItem( "tex_input", [chInPerGroup * chOutPerGroup * karea, karea, 1, chOutPerGroup * karea], dW, context.webgl2 ), ...shaderGenTensorOutputUniformItem( [group, chOutPerGroup, karea, chInPerGroup], dTW, context.webgl2 ), ]; await context.runKernel( kernelName, [{ tensor: dW, name: "tex_input" }], dTW, uniforms ); } private async bias( context: WebDNNWebGLContext, dI: WebGLTensor, dB: WebGLTensor, dO: WebGLTensor, batch: number, chOut: number, outarea: number ) { const kernelName = `convtranspose_bias`; if (!context.hasKernel(kernelName)) { const kernelSource = `${shaderGenHeader(context.webgl2)} ${shaderGenTensorOutputUniform(1)} uniform int BATCH; uniform int COUT; uniform int OUTAREA; ${shaderGenTensorNDGet("tex_input_i", 1, context.webgl2)} ${shaderGenTensorNDGet("tex_input_b", 1, context.webgl2)} void main() { ${shaderGenTensorOutputCoordsWithReturn(1)} int rem = tex_output_flat; int quo = rem / OUTAREA; int x = rem - quo * OUTAREA; rem = quo; quo = rem / COUT; int c = rem - quo * COUT; int b = quo; float s = 0.0; s = get_tex_input_i(tex_output_flat) + get_tex_input_b(c); ${shaderGenOutput("s", context.webgl2)} return; } `; context.addKernel(kernelName, kernelSource); } const uniforms: WebGLUniformItem[] = [ ...shaderGenTensorNDGetUniformItem( "tex_input_i", [1], dI, context.webgl2 ), ...shaderGenTensorNDGetUniformItem( "tex_input_b", [1], dB, context.webgl2 ), ...shaderGenTensorOutputUniformItem([dO.length], dO, context.webgl2), { name: "BATCH", type: "int", value: batch }, { name: "COUT", type: "int", value: chOut }, { name: "OUTAREA", type: "int", value: outarea }, ]; await context.runKernel( kernelName, [ { tensor: dI, name: "tex_input_i" }, { tensor: dB, name: "tex_input_b" }, ], dO, uniforms ); } } export function getOpEntries(): OperatorEntry[] { return [ { opType: "ConvTranspose", backend: "webgl", opsetMin: 1, factory: () => new WebGLConvTranspose(), }, ]; }
the_stack
import uuid from 'uuid'; import { nodeRevise } from './utils/schema-utils'; import { objectReadOnly, deepClone, hasOwnProperty, evaluateSelector, createShadow } from './utils/common-utils'; import SchemaTree from './SchemaTree'; import EventEmitter from './Event'; import Watcher from './Watcher'; import TaskQueue from './TaskQueue'; /** * 组件插件生命周期方法 */ enum COMP_HANDLER { onComponentInitial = 'onComponentInitial', // 8 afterPageRender = 'afterPageRender', // 14 这时组件一般(不能保证)已经渲染 // onDestroy = 'onDestroy', // 15 } /** * 页面插件生命周期方法 */ enum PAGE_HANDLER { onNodePreprocess = 'onNodePreprocess', // 2 对节点有动态修改 onPageInitial = 'onPageInitial', // 7 beforeRender = 'beforeRender', // 9 afterRender = 'afterRender', // 13 onDestroy = 'onDestroy', // 16 } // render: 'render', 11 /** * 模型插件生命周期方法 */ enum MODEL_HANDLER { // onModelInitial: 'onModelInitial',//1 注:class类型,直接new class onNodePreprocess = 'onNodePreprocess', // 3 schema预处理 onComponentsWrap = 'onComponentsWrap', // 4 onSchemaInstantiated = 'onSchemaInstantiated', // 5 schema实例化 onModelApiCreated = 'onModelApiCreated', // 6 模型接口创建 onReadyToRender = 'onReadyToRender', // 10 即将进行渲染 afterRender = 'afterRender', // 12 onDestroy = 'onDestroy', // 17 } // 三类插件在plugins参数的项中的键名 const pluginKeyMap: PluginKeyMap = { modelPlugins: 'modelPlugin', pagePlugins: 'pagePlugin', componentPlugins: 'componentPlugin' }; // tslint:disable-next-line: no-empty const noop = () => { }; const defArgs = () => ([]); /** * SifoModel 插件管理模型 */ export default class Model { // tslint:disable-next-line: no-any [key: string]: any; instanceId: string; namespace: string; refreshApi: DefaultFunc; externals: ModelOptions['externals']; initialSchema: SchemaNode; plugins: SifoPlugin[]; modelPluginIds: (string | ModelPlugin)[]; initialComponents: object; components: ModelOptions['components']; mApi: ModelApi | null; schemaReadied: boolean; targetSchema: SchemaNode; rendered: boolean; modelApiRef: ModelOptions['modelApiRef']; globalDataContainer: DynamicObject; taskQueue: TaskQueue; shadowBox: ShadowBox | null; controller: Controller; /** * * @param namespace 命名空间 * @param refreshApi 刷新执行接口,如有传callback参数,应在刷新完成后回调 * @param schema schema * @param plugins 插件 * @param modelOptions 可选参数 */ constructor( namespace: string, refreshApi: DefaultFunc, schema: SchemaNode, plugins: SifoPlugin[], modelOptions: ModelOptions = { modelApiRef: noop }, controller: Controller, ) { const { externals, components, modelApiRef, getModelPluginArgs } = modelOptions; // 模型选项 /** * 初始环境 ** */ this.instanceId = uuid(); // 用来唯一标识模型实例 this.namespace = namespace || this.instanceId; // 命名空间用来唯一标识模型, this.refreshApi = refreshApi; this.externals = externals || {}; // 任意externals this.initialSchema = schema || {}; // 初始的schema this.plugins = plugins || []; this.getModelPluginArgs = getModelPluginArgs || defArgs; this.initialComponents = objectReadOnly(components || {}); // 不能改原始组件映射关系 this.components = {}; this.mApi = null; // 模型接口 this.schemaReadied = false; this.targetSchema = {}; // 经过处理的schema,用来创建树实例 this.rendered = false; // 标识是否已经渲染 this.modelApiRef = modelApiRef || noop; // 对外暴露modelApi /** * 数据容器 ** */ this.globalDataContainer = {}; // 全局数据容器 this.modelPluginIds = []; // 记录加载过的模型插件 // 执行队列 this.taskQueue = new TaskQueue(); // 影子盒 this.shadowBox = null; // 控制器 this.controller = controller; } /** * 重置,清空数据,重置状态,给 modelApiRef 传 null 值 */ reset = () => { /* 这几个值不能重置,因为在reloadPage中会要使用 this.initialSchema this.externals this.plugins this.initialComponents this.taskQueue */ this.rendered = false; this.eventEmitter = null; // 事件 this.watcher = null; // 观测 this.schemaInstance = null; // schema实例 this.globalDataContainer = {}; this.modelPluginIds = []; /** * 插件 ** */ this.modelPlugins = []; // 模型插件-管模型功能 this.pagePlugins = []; // 页面插件-管页面生命周期 this.componentPlugins = []; // 组件插件 // 如果有上层需要管理多个model,必然是有个地方存储了这个model,应用modelApiRef来接model方法 this.mApi = null; this.schemaReadied = false; // 使用modelApiRef方式向外暴露mApi,此处调用是防止内存泄漏 if (this.modelApiRef) { this.modelApiRef(null); } // 影子盒 this.shadowBox = null; } /** * 开始运行 */ run = () => { if (!this.refreshApi || typeof this.refreshApi !== 'function') { console.error('[sifo-model] refresh api is not defined!'); return; } this.runLifecycle(); } // 执行生命周期方法 runLifecycle = () => { // 改成执行队列,就可以支持被终止了 this.taskQueue.push( [ this.reset, this.onModelInitial, this.onNodePreprocess, this.onComponentsWrap, this.onSchemaInstantiated, this.onModelApiCreated, this.onPageInitial, this.onComponentInitial, this.beforeRender, this.onReadyToRender, this.openSchema, this.render ] ).run(); // this.afterRender(); 在render内调用,不显式写在此处 // this.destroy(); 由外部调用 } /** * 将插件分到相应的handler中去 */ splitPlugins = (plugins: SifoPlugin[]) => { if (!Array.isArray(plugins)) { throw new Error('[sifo-model] plugins expected array'); } Object.keys(pluginKeyMap).forEach((key: string) => { // tslint:disable-next-line: no-any plugins.forEach((pluginsItem: any) => { const plgName = pluginKeyMap[key]; const plugin = pluginsItem[plgName]; if (!plugin) { return; } if (key === 'modelPlugins') { // 模型插件是class形式 // tslint:disable-next-line: no-any let modelPlugin: any = plugin; let getModelPluginArgs = this.getModelPluginArgs; if (typeof modelPlugin === 'object') { const { argsProvider, plugin: mPlg } = <ModelPluginProvider> modelPlugin; if (!mPlg) return; modelPlugin = mPlg; if (argsProvider && typeof argsProvider === 'function') { getModelPluginArgs = argsProvider; } } // 获取模型创建参数 const Id = modelPlugin.ID; if (!(this.modelPluginIds.indexOf(modelPlugin) === -1 && this.modelPluginIds.indexOf(Id) === -1)) { console.info(`[sifo-model] ${plgName}: ${Id || 'No_ID_Model_Plugin'} already exist.`); return; } // 模型插件既要判断ID也要判断本身 if (Id) { // 有可能被多次引入 this.modelPluginIds.push(Id); } this.modelPluginIds.push(plugin); const info = { instanceId: this.instanceId, namespace: this.namespace, externals: this.externals }; try { let newParams = getModelPluginArgs(Id, info); // [a, b] if (!newParams || !Array.isArray(newParams)) newParams = [newParams]; const mPlugin = new modelPlugin(...newParams); this[key].push(mPlugin); } catch (e) { console.error(`[sifo-model] new ${plgName} ${Id || 'No_ID_Model_Plugin'} failed. errMsg: ${e}`); } } else { if (this[key].indexOf(plugin) === -1) { this[key].push(plugin); } else { console.info(`[sifo-model] a ${plgName} duplicated`); } } }); }); } /** * 模型初始化 */ onModelInitial = () => { /* 此处隐式 onModelInitial,模型插件是class类型,在splitPlugins中实例化 */ this.splitPlugins(this.plugins); } /** * schema节点预处理周期 */ onNodePreprocess = () => { const pageHandlers: AnyPluginHandler[] = this.getPageHandlers(PAGE_HANDLER.onNodePreprocess); const targetSchema = this.doNodePreprocess(<PrePluginHandler[]> pageHandlers, this.initialSchema); const modelHandlers: AnyPluginHandler[] = this.getModelHandlers(MODEL_HANDLER.onNodePreprocess); this.targetSchema = this.doNodePreprocess(<PrePluginHandler[]> modelHandlers, targetSchema); } doNodePreprocess = (handlers: PrePluginHandler[], dealSchema: object) => { let targetSchema = deepClone(dealSchema); // 拷贝,可能有function,不能用JSON.stringify if (!handlers || handlers.length === 0) { return targetSchema; } const informations = { instanceId: this.instanceId, namespace: this.namespace, externals: this.externals }; // 这是个按层遍历方法 targetSchema = nodeRevise(targetSchema, (node: SchemaNode) => { let newNode = node; for (let i = 0; i < handlers.length; i += 1) { // 周期方法onNodePreprocess是普通函数,参数是node对象,应返回处理后的node const retNode = handlers[i]({ ...newNode }, informations); newNode = retNode || newNode; } newNode.attributes = { ...newNode.attributes }; // 防止为null return newNode; }); return targetSchema; } /** * 组件包装 */ onComponentsWrap = () => { const handlers = this.getModelHandlers(MODEL_HANDLER.onComponentsWrap); const actualComponents = { ...this.initialComponents }; for (let i = 0; i < handlers.length; i += 1) { // 周期方法onComponentsWrap是普通函数,唯一参数是actualComponents对象 const eHandler: AnyPluginHandler = handlers[i]; const wrappedComps = (<PrePluginHandler> eHandler)({ ...actualComponents }); if (wrappedComps) { Object.assign(actualComponents, wrappedComps); } } this.components = Object.assign({}, this.initialComponents, actualComponents); } /** * 创建schema实例 */ onSchemaInstantiated = () => { this.schemaInstance = new SchemaTree(this.targetSchema); const handlers = this.getModelHandlers(MODEL_HANDLER.onSchemaInstantiated); const event = { eventType: MODEL_HANDLER.onSchemaInstantiated, schemaInstance: this.schemaInstance, namespace: this.namespace, instanceId: this.instanceId, externals: this.externals, }; this.reducer(handlers, event); } /** * 构建modelApi */ createModelApi: () => ModelApi = () => ( { namespace: this.namespace, instanceId: this.instanceId, getExternals: () => this.externals, getGlobalData: this.getGlobalData, setGlobalData: this.setGlobalData, getAttributes: this.getAttributes, setAttributes: this.setAttributes, replaceComponent: this.replaceComponent, // 动态更改渲染组件 getComponentName: this.getComponentName, // 获取指定id的渲染组件名 queryNodeIds: this.queryNodeIds, // 查询节点Id,返回的是数组 /* 注:可考虑支持这些功能,但会涉及很多地方的处理 --> schema应该是一份完全的数据,不应该有动态节点变化 removeChildren/addChildren/copyNode 要处理schemaInstance重建(以最新的schema为基础), EventEmitter的instance更换-局部更新 模型插件监听这些事件做相应变化(如保存的状态,是否合法等),过滤所有方法属性, id处理等 */ addEventListener: this.addEventListener, removeEventListener: this.removeEventListener, watch: this.watch, removeWatch: this.removeWatch, dispatchWatch: this.dispatchWatch, hasEventListener: this.hasEventListener, // 对指定事件是否有进行监听 reloadPage: this.reloadPage, refresh: this.refresh, // 批量修改schema的属性后,调用刷新使更新生效 getInitialSchema: () => deepClone(this.initialSchema), // 初始的schema,用深拷贝 getSchema: () => { if (this.schemaInstance) { // mApi 取到的schema应该是不能直接改的,用浅拷贝,也就是拷贝的节点层 return nodeRevise(this.schemaInstance.parsedTree, (node: SchemaNode) => { const clonedNode = { ...node, attributes: { ...node.attributes } }; return clonedNode; }); } return null; }, getComponents: () => ({ ...this.components }), // 注: registPlugins: this.registPlugins, // 注册插件是否在插件给?=> 暂不放开,注意模型插件的权限 // to think: registComponent,有时可能需要由外部组件来包装已存在组件,达到保留原组件逻辑的情况下修改渲染样式 // 不放开 schemaLoopUp: this.loopUp, // 不放开 schemaLoopDown: this.loopDown, } ) /** * 创建模型api, 可在此修改模型方法 */ onModelApiCreated = () => { const mApi: ModelApi = this.createModelApi(); const shadowBox = createShadow(mApi); this.shadowBox = shadowBox; this.mApi = this.shadowBox.shadow as ModelApi; // 创建事件注册对象 this.eventEmitter = new EventEmitter(this.mApi); this.watcher = new Watcher(this.eventEmitter); this.eventEmitter.injectWatcher(this.watcher); // 接口mApi依赖的对象在此时都应该创建完毕 const handlers = this.getModelHandlers(MODEL_HANDLER.onModelApiCreated); // mApi扩展中间件实现 const applyModelApiMiddleware = (apiName: string, middleware: ModelApiMiddleware) => { if (!this.mApi || !apiName || !middleware) { return; } const originFunc = this.mApi[apiName]; if (!originFunc) { this.mApi[apiName] = middleware(v => v, true); // 兼容多模型插件时出现此方法 } else { if (typeof originFunc !== 'function') { return; } this.mApi[apiName] = middleware(originFunc, false); } }; const event = { applyModelApiMiddleware, eventType: MODEL_HANDLER.onModelApiCreated, }; this.reducer(handlers, event); // 锁定mApi方法,防止被修改 const refApi = objectReadOnly({ ...this.mApi, // ref 的 mApi.getSchema 是频繁方法,不适合频繁clone getSchema: () => { // 在插件未执行完之前,不返回渲染 schema,因为这时候 schema 还处在半加工状态 if (!this.schemaReadied) { return {}; } return this.schemaInstance.parsedTree; }, }) as ModelApi; objectReadOnly(this.mApi); if (this.modelApiRef) { this.modelApiRef(refApi); } } /** * 界面初始化,处理一些全局的逻辑 */ onPageInitial = () => { const handlers = this.getPageHandlers(PAGE_HANDLER.onPageInitial); const event = { eventType: PAGE_HANDLER.onPageInitial }; this.reducer(handlers, event); } /** * 组件初始化,修改组件属性 */ onComponentInitial = () => { this.schemaInstance.loopDown((node: SchemaNode) => { const { id, attributes } = node; const attribute = objectReadOnly({ ...attributes }); // 防止直接修改,否则可能影响eventListener // onComponentInitial内通过model.setAttributes方法更新属性。 if (id) { const handlers = this.getComponentHandlers( id, COMP_HANDLER.onComponentInitial ); const event = { key: id, eventType: COMP_HANDLER.onComponentInitial, __attributes: attribute }; this.reducer(handlers, event); } }); } /** * 渲染前 */ beforeRender = () => { const handlers = this.getPageHandlers(PAGE_HANDLER.beforeRender); const event = { eventType: PAGE_HANDLER.beforeRender }; this.reducer(handlers, event); } /** * 即将渲染 */ onReadyToRender = () => { const handlers = this.getModelHandlers(MODEL_HANDLER.onReadyToRender); const event = { eventType: MODEL_HANDLER.onReadyToRender, }; this.reducer(handlers, event); } /** * 放开渲染 schema,在此之前 refApi 的 getSchema 方法不会返回 */ openSchema = () => { this.schemaReadied = true; } /** * 渲染 */ render = () => { this.refreshApi(() => { // 由于render方法内无法被discard,也就是执行了render一定会执行到这里,所以异步push不会导致推入到新队列的问题 this.taskQueue.push([ () => { this.rendered = true; }, // 放开标识,更新即时渲染,不能放到最后,否则在周期结束后得不到最新渲染 this.afterRender, this.afterPageRender, ]).run(); }); } /** * 渲染后 */ afterRender = () => { /** * 1. The second parameter to setState() is an optional callback function * that will be executed once setState is completed and the component is re-rendered(updated). * 2. react setState callback 是一个 task,如果再用 setTimeout,就会再产生一个 task, * 而如果在 run 开始时就发起一个请求,在 response 后进行 reloadPage, * 此时的 response 可能在第一个 task 后,也可能在第二个 task 后注入 microtask queue 中(不兼容时可能是个task) */ // setTimeout(() => { const mHandlers = this.getModelHandlers(MODEL_HANDLER.afterRender); const mEvent = { eventType: MODEL_HANDLER.afterRender }; this.reducer(mHandlers, mEvent); const handlers = this.getPageHandlers(PAGE_HANDLER.afterRender); const event = { eventType: PAGE_HANDLER.afterRender }; this.reducer(handlers, event); // }, 0); } afterPageRender = () => { this.schemaInstance.loopDown((node: SchemaNode) => { const { id, attributes } = node; const attribute = objectReadOnly({ ...attributes }); // 防止直接修改,否则可能影响eventListener if (id) { const handlers = this.getComponentHandlers( id, COMP_HANDLER.afterPageRender ); const event = { key: id, eventType: COMP_HANDLER.afterPageRender, __attributes: attribute }; this.reducer(handlers, event); } }); } /** * 销毁,由外部触发,以进行相关销毁操作 */ destroy = () => { this.taskQueue.discard(); if (this.shadowBox) { this.shadowBox.shadowMagic(); } this.rendered = false; // 屏蔽refreshApi的调用,但允许mApi的调用 if (this.modelApiRef) { this.modelApiRef(null); } const pageHandlers: AnyPluginHandler[] = this.getPageHandlers(PAGE_HANDLER.onDestroy); const pEvent = { eventType: PAGE_HANDLER.onDestroy, }; this.reducer(pageHandlers, pEvent); const modelHandlers: AnyPluginHandler[] = this.getModelHandlers(MODEL_HANDLER.onDestroy); const mEvent = { eventType: MODEL_HANDLER.onDestroy, }; this.reducer(modelHandlers, mEvent); // 由于在销毁时可能还有异步回调执行,为使执行不报错,故不进行清理,GC 会自动处理 this.reset(); // 清空数据 } registPlugins = (plugins: SifoPlugin[]) => { this.splitPlugins(plugins); } getModelHandlers(event: Exclude<keyof ModelPlugin, 'ID'>): AnyPluginHandler[] { const handlers: AnyPluginHandler[] = []; this.modelPlugins.forEach((handler: ModelPlugin) => { if (handler && hasOwnProperty(handler, event)) { const item = handler[event]; if (item) { handlers.push(item); } } }); return handlers; } getPageHandlers(event: keyof (PagePlugin)): AnyPluginHandler[] { const handlers: AnyPluginHandler[] = []; this.pagePlugins.forEach((handler: PagePlugin) => { if (handler && hasOwnProperty(handler, event)) { const item = handler[event]; if (item) { handlers.push(item); } } }); return handlers; } getComponentHandlers(id: string, event: keyof (ComponentPluginItem)) { const handlers: AnyPluginHandler[] = []; this.componentPlugins.forEach((plgSet: ComponentPluginSet) => { if (plgSet[id] && hasOwnProperty(plgSet[id], event)) { const compHandler: ComponentPluginItem = plgSet[id]; const item = compHandler[event]; if (item) { handlers.push(item); } } }); return handlers; } /** * 插件reducer * @param {*} handlers * @param {*} event * @param {*} cancelable */ reducer(handlers: PluginHandler[], event: DynamicObject, cancelable: boolean = false) { const args: PluginEventArgs = <PluginEventArgs> objectReadOnly({ event, mApi: this.mApi }); if (cancelable) { args.event.cancel = false; } for (let i = 0; i < handlers.length; i += 1) { handlers[i](args); if (cancelable && args.event.cancel === true) { return; } } return; } /** * 向上遍历,loopFunc如果返回false,则不继续遍历 */ loopUp = (loopFunc: DefaultFunc, id: string) => { this.schemaInstance.loopUp(loopFunc, id); } /** * 向下遍历,默认从根节点开始,loopFunc如果返回false,则不继续遍历 */ loopDown = (loopFunc: DefaultFunc, id: string) => { this.schemaInstance.loopDown(loopFunc, id); } /** * 设置指定节点的属性 * @param {string} id 指定节点的 id * @param {object} attributes 指定节点的属性 * @param {boolean} refreshImmediately 是否立即刷新,默认为true, 批量设置时建议在设置完后调用refresh接口刷新 */ setAttributes: ModelApi['setAttributes'] = (id: string, attributes: DynamicObject, refreshImmediately = true) => { const item = this.schemaInstance.nodeMap[id]; if (item) { const usedAttrs: DynamicObject = {}; Object.keys(attributes || {}).forEach(attrName => { if (this.eventEmitter.hasHandler(id, attrName)) { console.error(`[sifo-model] ${id}.${attrName} is in EventListener, please use addEventListener`); return; } usedAttrs[attrName] = attributes[attrName]; }); item.attributes = { ...item.attributes, ...usedAttrs }; if (refreshImmediately) { return this.refresh(); } } return new Promise(resolve => resolve('id_not_found')); } /** * 更换渲染组件 */ replaceComponent: ModelApi['replaceComponent'] = (id: string, componentName: string) => { const item = this.schemaInstance.nodeMap[id]; if (item) { item.component = componentName; this.refresh(); } } /** * 获取指定id的渲染组件名 */ getComponentName: ModelApi['getComponentName'] = (id: string) => { const item = this.schemaInstance.nodeMap[id]; if (item) { return item.component; } return undefined; } getAttributes: ModelApi['getAttributes'] = (id: string) => { const node = this.schemaInstance.nodeMap[id]; if (!node) { return undefined; } return { ...node.attributes }; // 防止直接修改 } getGlobalData: ModelApi['getGlobalData'] = key => { if (key) { return this.globalDataContainer[key]; } return this.globalDataContainer; } setGlobalData: ModelApi['setGlobalData'] = (key, data) => { this.globalDataContainer[key] = data; } queryNodeIds: ModelApi['queryNodeIds'] = (selector, direction = 'loopDown', id = '') => { const func = direction === 'loopUp' ? this.loopUp : this.loopDown; const ids: string[] = []; func((node) => { if (evaluateSelector(node, selector)) { ids.push(node.id); } }, id); return ids; } refresh: ModelApi['refresh'] = () => { if (!this.rendered) { return Promise.resolve(); } return new Promise(resolve => this.refreshApi(resolve)); } /** * (公开方法)重新加载 包含schema * @param {*} params 新的初始数据 */ reloadPage: ModelApi['reloadPage'] = (params = {}) => { if (this.shadowBox) { this.shadowBox.shadowMagic(['reloadPage']); } this.taskQueue.discard(); // 调用控制器的reloadPage this.controller.reloadPage(params); } // 如果有方法是直接绑定在属性上,是否让后续插件覆盖? => 覆盖,eventListener优先级高于普通属性 // tslint:disable-next-line: max-line-length addEventListener: ModelApi['addEventListener'] = (id: string, eventName: string, handler: SifoEventListener, prepose: boolean = false) => { let item = this.schemaInstance.nodeMap[id]; if (!item) { console.error(`[sifo-model] addEventListener id:${id} not found`); return; } const eventHandler = this.eventEmitter.addEventListener(id, eventName, handler, prepose); // 这里不能用setAttributes方法修改属性,因为setAttributes要保护监听方法不被覆盖 item.attributes = { ...item.attributes, // 此中可能已经有[eventName]了 [eventName]: eventHandler }; if (this.mApi) { this.mApi.setAttributes(id, {}, true); // 通知属性变化 } } // tslint:disable-next-line: max-line-length removeEventListener: ModelApi['removeEventListener'] = (id: string, eventName: string, handler: SifoEventListener, prepose: boolean = false) => { this.eventEmitter.removeEventListener(id, eventName, handler, prepose); } // tslint:disable-next-line: max-line-length hasEventListener: ModelApi['hasEventListener'] = (id: string, eventName: string) => this.eventEmitter.hasHandler(id, eventName); watch: ModelApi['watch'] = (key: string, handler: SifoEventListener) => { this.watcher.watch(key, handler); } removeWatch: ModelApi['removeWatch'] = (key: string, handler: SifoEventListener) => { this.watcher.removeWatch(key, handler); } dispatchWatch: ModelApi['dispatchWatch'] = (key: string, ...payloads: DispatchPayload[]) => { const item = this.schemaInstance.nodeMap[key]; // 此dispatch用于做事件分发,对于schema节点无效 if (item) { console.error('[sifo-model] dispatchWatch is invalid on schema Id'); return; } this.watcher.dispatchWatch([{ [key]: payloads }]); } }
the_stack
import * as vscode from "vscode"; import { exec } from "child_process"; import * as fs from "fs"; import * as path from "path"; import * as os from "os"; import opn from './open'; import { browserConfig } from './browser'; const through = require("through2"); const minimatch = require('minimatch'); import { sassLoader } from './compile/sass'; import { javascriptLoader } from './compile/javascript'; import { lessLoader } from './compile/less'; import { typescriptLoader } from './compile/typescript'; import { typescriptxLoader } from './compile/typescriptx'; import { pugLoader } from './compile/pug'; import { stylusLoader } from './compile/stylus'; export const successMessage = "✔ Compilation Successed!"; export const errorMessage = "❌ Compilation Failed!"; export enum LANGUAGE_SUFFIX { JAVASCRIPT = ".js", SCSS = ".scss", SASS = ".sass", LESS = ".less", JADE = ".jade", TYPESCRIPT = ".ts", TYPESCRIPTX = ".tsx", PUG = ".pug", STYLUS = ".styl" } export const suffixs = [ LANGUAGE_SUFFIX.JAVASCRIPT, LANGUAGE_SUFFIX.SCSS, LANGUAGE_SUFFIX.SASS, LANGUAGE_SUFFIX.LESS, LANGUAGE_SUFFIX.JADE, LANGUAGE_SUFFIX.TYPESCRIPT, LANGUAGE_SUFFIX.TYPESCRIPTX, LANGUAGE_SUFFIX.PUG, LANGUAGE_SUFFIX.STYLUS ]; export interface OutputDirectoryPath { [LANGUAGE_SUFFIX.JAVASCRIPT]: string; [LANGUAGE_SUFFIX.SCSS]: string; [LANGUAGE_SUFFIX.SASS]: string; [LANGUAGE_SUFFIX.LESS]: string; [LANGUAGE_SUFFIX.JADE]: string; [LANGUAGE_SUFFIX.TYPESCRIPT]: string; [LANGUAGE_SUFFIX.TYPESCRIPTX]: string; [LANGUAGE_SUFFIX.PUG]: string; [LANGUAGE_SUFFIX.STYLUS]: string; } export interface CompileStatus { [LANGUAGE_SUFFIX.JAVASCRIPT]: boolean | undefined; [LANGUAGE_SUFFIX.SCSS]: boolean | undefined; [LANGUAGE_SUFFIX.SASS]: boolean | undefined; [LANGUAGE_SUFFIX.LESS]: boolean | undefined; [LANGUAGE_SUFFIX.JADE]: boolean | undefined; [LANGUAGE_SUFFIX.TYPESCRIPT]: boolean | undefined; [LANGUAGE_SUFFIX.TYPESCRIPTX]: boolean | undefined; [LANGUAGE_SUFFIX.PUG]: boolean | undefined; [LANGUAGE_SUFFIX.STYLUS]: boolean | undefined; } export interface CompileOptions { generateMinifiedHtml: boolean | undefined, generateMinifiedHtmlOnly: boolean | undefined, generateMinifiedCss: boolean | undefined, generateMinifiedCssOnly: boolean | undefined, generateMinifiedJs: boolean | undefined, generateMinifiedJsOnly: boolean | undefined, } export interface loaderOption { fileName: string outputPath: string; notificationStatus: boolean | undefined; compileOptions: CompileOptions; selectedText?: string; } let isDocker: boolean; export const docker = () => { const hasDockerEnv = () => { try { fs.statSync('/.dockerenv'); return true; } catch (_) { return false; } } const hasDockerCGroup = () => { try { return fs.readFileSync('/proc/self/cgroup', 'utf8').includes('docker'); } catch (_) { return false; } } if (isDocker === undefined) { isDocker = hasDockerEnv() || hasDockerCGroup(); } return isDocker; }; const wsll = () => { if (process.platform !== 'linux') { return false; } if (os.release().toLowerCase().includes('microsoft')) { if (docker()) { return false; } return true; } try { return fs.readFileSync('/proc/version', 'utf8').toLowerCase().includes('microsoft') ? !docker() : false; } catch (_) { return false; } }; export const wsl = process.env.__IS_WSL_TEST__ ? wsll : wsll(); export const standardizedBrowserName = (name: string = ''): string => { let _name = name.toLowerCase(); const browser = browserConfig.browsers.find(item => { return item.acceptName.indexOf(_name) !== -1; }); return browser ? browser.standardName : ''; }; export const defaultBrowser = (): string => { const config = vscode.workspace.getConfiguration(browserConfig.app); return config ? config.default : ''; }; export const open = (path: string, browser: string | string[]) => { opn(path, { app: browser }).catch((err: any) => { vscode.window.showErrorMessage(`Open browser failed!! Please check if you have installed the browser ${browser} correctly!`); }); }; export const openBrowser = (path: any): void => { const browser = standardizedBrowserName(defaultBrowser()); open(path, browser); }; export type FileSuffix = | LANGUAGE_SUFFIX.JAVASCRIPT | LANGUAGE_SUFFIX.SCSS | LANGUAGE_SUFFIX.SASS | LANGUAGE_SUFFIX.LESS | LANGUAGE_SUFFIX.JADE | LANGUAGE_SUFFIX.TYPESCRIPT | LANGUAGE_SUFFIX.TYPESCRIPTX | LANGUAGE_SUFFIX.PUG | LANGUAGE_SUFFIX.STYLUS; export const readFileContext = (path: string): string => { return fs.readFileSync(path).toString(); }; export const fileType = (filename: string) => { const index1 = filename.lastIndexOf("."); const index2 = filename.length; const type = filename.substring(index1, index2); return type as FileSuffix; }; export const command = (cmd: string) => { return new Promise<string>((resolve, reject) => { exec(cmd, (err, stdout, stderr) => { resolve(stdout); }); }); }; export const transformPort = (data: string): string => { let port: string = ""; data.split(/[\n|\r]/).forEach((item) => { if (item.indexOf("LISTEN") !== -1 && !port) { let reg = item.split(/\s+/); if (/\d+/.test(reg[1])) { port = reg[1]; } } }); return port; }; export const empty = function (code: string) { let stream = through.obj((file: any, encoding: any, callback: Function) => { if (!file.isBuffer()) { return callback(); } file.contents = Buffer.from(code || ""); stream.push(file); callback(); }); return stream; }; export const complieFile = (uri: string) => { readFileName({ fileName: uri }); }; export const complieDir = (uri: string) => { const files = fs.readdirSync(uri); files.forEach((filename) => { const fileUrl = path.join(uri, filename); const fileStats = fs.statSync(fileUrl); if (fileStats.isDirectory()) { complieDir(fileUrl); } else { complieFile(fileUrl); } }); }; // 获取当前选中的文本 export const getSelectedText = () => { const documentText = vscode.window.activeTextEditor?.document.getText(); if (!documentText) { return ""; } const activeSelection = vscode.window.activeTextEditor?.selection; if (activeSelection?.isEmpty) { return ""; } const selectStartOffset = vscode.window.activeTextEditor?.document.offsetAt( activeSelection?.start as vscode.Position ); const selectEndOffset = vscode.window.activeTextEditor?.document.offsetAt( activeSelection?.end as vscode.Position ); let selectedText = documentText.slice(selectStartOffset, selectEndOffset).trim(); selectedText = selectedText.replace(/\s\s+/g, " "); return selectedText; } // 获取工作区位置 export const getWorkspaceRoot = (doc: vscode.TextDocument) => { if (!vscode.workspace.workspaceFolders || vscode.workspace.workspaceFolders.length === 0) return; if (!doc || doc.isUntitled) return vscode.workspace.workspaceFolders[0].uri.fsPath; const folder = vscode.workspace.getWorkspaceFolder(doc.uri); if (!folder) return; return folder.uri.fsPath; }; export const readFileName = async ({ fileName, selectedText }: { fileName: string; selectedText?: string }) => { let workspaceRootPath = vscode.workspace.rootPath; let fileSuffix: FileSuffix = fileType(fileName); let config = vscode.workspace.getConfiguration("compile-hero"); let outputDirectoryPath: OutputDirectoryPath = { [LANGUAGE_SUFFIX.JAVASCRIPT]: config.get<string>("javascript-output-directory") || "", [LANGUAGE_SUFFIX.SCSS]: config.get<string>("scss-output-directory") || "", [LANGUAGE_SUFFIX.SASS]: config.get<string>("sass-output-directory") || "", [LANGUAGE_SUFFIX.LESS]: config.get<string>("less-output-directory") || "", [LANGUAGE_SUFFIX.JADE]: config.get<string>("jade-output-directory") || "", [LANGUAGE_SUFFIX.TYPESCRIPT]: config.get<string>("typescript-output-directory") || "", [LANGUAGE_SUFFIX.TYPESCRIPTX]: config.get<string>("typescriptx-output-directory") || "", [LANGUAGE_SUFFIX.PUG]: config.get<string>("pug-output-directory") || "", [LANGUAGE_SUFFIX.STYLUS]: config.get<string>("stylus-output-directory") || "", }; let compileStatus: CompileStatus = { [LANGUAGE_SUFFIX.JAVASCRIPT]: config.get<boolean>("javascript-output-toggle"), [LANGUAGE_SUFFIX.SCSS]: config.get<boolean>("scss-output-toggle"), [LANGUAGE_SUFFIX.SASS]: config.get<boolean>("sass-output-toggle"), [LANGUAGE_SUFFIX.LESS]: config.get<boolean>("less-output-toggle"), [LANGUAGE_SUFFIX.JADE]: config.get<boolean>("jade-output-toggle"), [LANGUAGE_SUFFIX.TYPESCRIPT]: config.get<boolean>("typescript-output-toggle"), [LANGUAGE_SUFFIX.TYPESCRIPTX]: config.get<boolean>("typescriptx-output-toggle"), [LANGUAGE_SUFFIX.PUG]: config.get<boolean>("pug-output-toggle"), [LANGUAGE_SUFFIX.STYLUS]: config.get<boolean>("stylus-output-toggle"), }; let ignore = config.get<string[] | string>("ignore") || []; let watch = config.get<string[] | string>("watch") || []; if (workspaceRootPath && fileName.startsWith(workspaceRootPath)) { let relativePath = path.relative(workspaceRootPath, fileName); if (!Array.isArray(ignore)) { ignore = [ignore] }; if (ignore.some(glob => minimatch(relativePath, glob))) return; // 如果设置了 watch,则监听保存的文件路径是否符合,如果不设置,则所有文件都会被监听 if (!Array.isArray(watch)) { watch = [watch] }; if (watch.length > 0 && !watch.some(glob => minimatch(relativePath, glob))) return; }; let notificationStatus: boolean | undefined = config.get<boolean>("notification-toggle"); let compileOptions: CompileOptions = { generateMinifiedHtml: config.get<boolean>("generate-minified-html"), generateMinifiedHtmlOnly: config.get<boolean>("generate-minified-html-only"), generateMinifiedCss: config.get<boolean>("generate-minified-css"), generateMinifiedCssOnly: config.get<boolean>("generate-minified-css-only"), generateMinifiedJs: config.get<boolean>("generate-minified-javascript"), generateMinifiedJsOnly: config.get<boolean>("generate-minified-javascript-only"), }; if (!compileStatus[fileSuffix]) return; let outputPath = path.resolve(fileName, "../", outputDirectoryPath[fileSuffix]); let loaderOption: loaderOption = { fileName, outputPath, notificationStatus, compileOptions, selectedText }; switch (fileSuffix) { case LANGUAGE_SUFFIX.SCSS: case LANGUAGE_SUFFIX.SASS: sassLoader(loaderOption); break; case LANGUAGE_SUFFIX.JAVASCRIPT: javascriptLoader(loaderOption); break; case LANGUAGE_SUFFIX.LESS: lessLoader(loaderOption); break; case LANGUAGE_SUFFIX.TYPESCRIPT: typescriptLoader(loaderOption); break; case LANGUAGE_SUFFIX.TYPESCRIPTX: typescriptxLoader(loaderOption); break; case LANGUAGE_SUFFIX.JADE: case LANGUAGE_SUFFIX.PUG: pugLoader(loaderOption); break; case LANGUAGE_SUFFIX.STYLUS: stylusLoader(loaderOption); break; } }; export function veriableCheck(uri: string, fileSuffix: string, workspaceRootPath: string) { let veriableError: string; if ((uri.indexOf("}/") < 0) && ((uri.length - uri.indexOf("}")) > 1) && (uri.indexOf("$") >= 0)) { veriableError = fileSuffix + "; '/' must be used at the end of the variable or '}' must be the last character."; vscode.window.showErrorMessage(veriableError); return false; } else if (uri.indexOf("${workspaceFolder}") >= 0) { uri = uri.replace("${workspaceFolder}", String(workspaceRootPath)); } else if (uri.indexOf("${folderPath}") >= 0) { uri = uri.replace("${folderPath}", String(workspaceRootPath)); } else if (uri.indexOf("$") >= 0) { let findStartNumber: number = uri.indexOf("$"); let findEndNumber: number; if (uri.indexOf("}") < 0) { if (uri.indexOf("/") < 0) { findEndNumber = uri.length; } else { findEndNumber = uri.indexOf("/"); } } else { findEndNumber = uri.indexOf("}"); } findEndNumber++; veriableError = fileSuffix + "; Output directory unsupported variable: " + uri.slice(findStartNumber, findEndNumber); vscode.window.showErrorMessage(veriableError); return false; } return uri; };
the_stack
import { EventEmitter } from "./event" import { UIInput } from "./ui-input" import { UIRangeInputInit } from "../common/messages" import { dlog, hostEnv } from "./util" import { config } from "./config" export { UIRangeInputInit } const captureEvent = {passive:false,capture:true} interface UIRangeInputEvents { "input" :number "change" :number } export class UIRangeInput extends EventEmitter<UIRangeInputEvents> implements UIInput<number> { el :HTMLDivElement track :HTMLDivElement knob :HTMLDivElement tooltipLabel :HTMLDivElement readonly min :number = 0 readonly max :number = 100 readonly step :number = 0 readonly _prec :number = 0 // number of decimals of step readonly _scale :number // user space (= max - min) readonly knobSize = 8 // dp; should match css var --rangeKnobSize readonly overshoot = Math.round(this.knobSize / 4) // how much the knob overshoots the track // dp of distance to 0% or 100% within where we snap to 0% or 100% on pointerup readonly snapThreshold = this.knobSize / 2 // dp // trackRect :ClientRect readonly minOffset = -this.overshoot maxOffset = 0 displayScale = 1 dragged = false _lastInputTimestamp = 0 _pointerDownX = 0 // position at last pointerdown event _trackPageXOffset = 0 // track offset in page coordinates _knobPointerXOffset = 0 // offset knob-to-pointer knobX = 0 // current position of knob in display point units _value = 0 // scaled value in range [min - max] _startValue = 0 // _value at start of pointer session _bigJumpTimer :any = null // timer used by _setKnobX for enabling animation constructor(init? :UIRangeInputInit) { super() let el = this.el = document.createElement("div") el.className = "rangeControl uninit" let track = this.track = document.createElement("div") track.className = "track" el.appendChild(track) let knob = this.knob = document.createElement("div") knob.className = "knob" track.appendChild(knob) let tooltip = document.createElement("div") tooltip.className = "tooltip" // tooltip.style.paddingLeft = `${this.overshoot*2}px` knob.appendChild(tooltip) let tooltipLabel = this.tooltipLabel = document.createElement("div") tooltip.appendChild(tooltipLabel) if (hostEnv.hasPointerEvents) { el.addEventListener("pointerdown", this.onPointerDown, captureEvent) el.addEventListener("pointerup", this.onPointerUp, captureEvent) } else { // Note: Safari <=12 (ships with macOS 10.14) does not have pointer events. // Pointer events arrived in Safari 13 (macOS 10.15). el.addEventListener("mousedown", this.onPointerDown, captureEvent) el.addEventListener("mouseup", this.onPointerUp, captureEvent) } if (init) { if (init.min !== undefined) { this.min = init.min } if (init.max !== undefined) { this.max = init.max } if (init.step !== undefined) { this.step = Math.abs(init.step) } if (init.value !== undefined) { this._value = Math.min(this.max, Math.max(this.min, Number(init.value))) } } this._scale = this.max - this.min if (this.step == 0) { // nice default step. Divvy up the track in 1000 parts let x = Math.abs(this._scale) / 1000 this.step = ( x < 0.0001 ? 0.0001 : x < 0.001 ? 0.001 : x < 0.01 ? 0.01 : x < 0.1 ? 0.1 : 1 ) } else { // step must not be larger than 50% of the scale this.step = Math.min(this.step, Math.round(this._scale / 2)) } let prec = (n :number) => { let v = (""+n).split(".", 2) return v.length == 2 ? v[1].length : 0 } // decimal precision this._prec = Math.max( prec(this.step), prec(this.min), prec(this.max) ) tooltipLabel.innerText = this._value.toFixed(this._prec) } get value() { return this._value } set value(v :number) { this.setValue(v) } layout() { let findPageOffset = (el :HTMLElement) => ( (el.offsetLeft - el.scrollLeft + el.clientLeft) + (el.offsetParent && el.offsetParent !== document.documentElement ? findPageOffset(el.offsetParent as HTMLElement) : 0 ) ) this._trackPageXOffset = findPageOffset(this.track) this._knobPointerXOffset = Math.round((this.knobSize + this.knob.clientWidth) / 3) this.maxOffset = this.track.clientWidth - (this.knobSize - this.overshoot) let vpercent = (this._value - this.min) / this._scale let dp = vpercent * (this.maxOffset - this.minOffset) this.knobX = dp this.knob.style.transform = `translate(${dp}px, 0)` } onMountDOM() { // for some strange reason, we can't measure our element until the next frame... requestAnimationFrame(() => { this.layout() requestAnimationFrame(() => this.el.classList.remove("uninit")) }) config.addListener("change", this.onConfigChange) } onUnmountDOM() { config.removeListener("change", this.onConfigChange) } onConfigChange = (ev:{key:string}) => { const keysAffectingEditorSize = { windowSize: 1, uiScale: 1, showLineNumbers: 1, codeFolding: 1, menuVisible: 1, } if (ev.key in keysAffectingEditorSize) { this.layout() } } onPointerDown = (ev :PointerEvent) => { ev.stopPropagation() ev.preventDefault() if (hostEnv.hasPointerEvents) { this.track.onpointermove = this.onPointerMove this.track.setPointerCapture(ev.pointerId) } else { document.onmousemove = this.onPointerMove document.onmouseup = this.onPointerUp } // this.trackRect = this.track.getBoundingClientRect() as ClientRect this.maxOffset = this.track.clientWidth - (this.knobSize - this.overshoot) this.displayScale = window.devicePixelRatio || 1 this.dragged = false this._lastInputTimestamp = ev.timeStamp this._pointerDownX = this.knobX // knobX BEFORE pointerdown this._startValue = this._value // let x = ev.offsetX // if (ev.target == this.el) { // x = x - this.track.offsetLeft // } // this.moveKnob(x) this.moveKnob(ev) this.knob.classList.add("changing") } onPointerMove = (ev :PointerEvent) => { if (!this.dragged) { this.dragged = true this.knob.classList.add("dragging") this.knob.classList.add("dragging-fine") } this.moveKnob(ev) this._lastInputTimestamp = ev.timeStamp } onPointerUp = (ev :PointerEvent) => { if (hostEnv.hasPointerEvents) { this.track.onpointermove = null this.track.releasePointerCapture(ev.pointerId) } else { document.onmousemove = null document.onmouseup = null } ev.stopPropagation() ev.preventDefault() if (this.dragged) { this.dragged = false this.knob.classList.remove("dragging") this.knob.classList.remove("dragging-fine") } // time since last input let timeDelta = ev.timeStamp - this._lastInputTimestamp let movementDelta = Math.abs(this._pointerDownX - this.knobX) let changedValue = false if (timeDelta < 200 && movementDelta >= this.snapThreshold) { // snap to extremes if the user moved and released the knob in less than 200ms, // and the knob moved more than or equal to snapThreshold. if (this.knobX - this.minOffset < this.snapThreshold) { // snap knob to 0% this.setValue(this.min) changedValue = true } else if (this.maxOffset - this.knobX < this.snapThreshold) { // snap knob to 100% this.setValue(this.max) changedValue = true } } if (!changedValue) { this.moveKnob(ev) } this.knob.classList.remove("changing") if (this._startValue != this._value) { this.triggerEvent("change", this._value) } } moveKnob(ev :PointerEvent) { let x = Math.min( this.maxOffset, Math.max( this.minOffset, // convert: pointer position in page space -> track space (ev.pageX - this._trackPageXOffset) - this._knobPointerXOffset ) ) // convert: track space -> percent [0-1] let v = (x - this.minOffset) / (this.maxOffset - this.minOffset) // convert: percent -> user space this.setValue((v * this._scale) + this.min, ev.shiftKey) } // setValueUnscaled sets value by unscaled percentage. v should be in the range [0–1] // returns true if value was updated // setValueUnscaled(v :number, snap? :bool) :bool { // convert: percent -> user space return this.setValue((v * this._scale) + this.min, snap) } // setValue sets value in current scale. v should be in the range [this.min–this.max) // returns true if value was updated // setValue(value :number, snap? :bool) :bool { let prec = this._prec if (value != this.max && value != this.min) { // round to step (snap=SHIFT -- snap to 10th step) let stepinv :number if (snap) { prec = Math.max(0, this._prec - 1) stepinv = 0.1 / this.step } else { stepinv = 1 / this.step } value = Math.round(value * stepinv) / stepinv value = Math.max(this.min, Math.min(this.max, Number(value.toFixed(this._prec)))) } // skip update if value is identical if (this._value == value) { return false } this._value = value // update tooltip, rounding number to current step // Note: _prec is set in constructor to number of decimals of step this.tooltipLabel.innerText = value.toFixed(prec) // convert: user value -> percent let vp = (value - this.min) / this._scale // convert: percent -> track space let knobX = (vp * (this.maxOffset - this.minOffset)) + this.minOffset this._setKnobX(knobX) this.triggerEvent("input", this._value) return true } _setKnobX(dp :number) { // true if changed dp = Math.round(dp * this.displayScale) / this.displayScale // round to pixels if (this.dragged) { if (Math.abs(this.knobX - dp) > 10) { // big jump clearTimeout(this._bigJumpTimer) this.knob.classList.remove("dragging-fine") this._bigJumpTimer = setTimeout(() => { this._bigJumpTimer = null this.knob.classList.add("dragging-fine") }, 100) } else if (this._bigJumpTimer !== null) { clearTimeout(this._bigJumpTimer) this.knob.classList.add("dragging-fine") } } this.knobX = dp this.knob.style.transform = `translate(${dp}px, 0)` } }
the_stack
import crypto from "crypto"; import { Injectable, forwardRef, Inject } from "@nestjs/common"; import { InjectRepository, InjectConnection } from "@nestjs/typeorm"; import { Repository, Connection, Like, MoreThan, EntityManager } from "typeorm"; import { escapeLike } from "@/database/database.utils"; import { LockService } from "@/redis/lock.service"; import { SubmissionService } from "@/submission/submission.service"; import { SubmissionEntity } from "@/submission/submission.entity"; import { SubmissionStatus } from "@/submission/submission-status.enum"; import { ConfigService } from "@/config/config.service"; import { AuthEmailVerificationCodeService } from "@/auth/auth-email-verification-code.service"; import { AuditLogObjectType, AuditService } from "@/audit/audit.service"; import { delay, DELAY_FOR_SECURITY } from "@/common/delay"; import { UserEntity } from "./user.entity"; import { UserPrivilegeService, UserPrivilegeType } from "./user-privilege.service"; import { UserInformationDto } from "./dto/user-information.dto"; import { UserInformationEntity } from "./user-information.entity"; import { UserPreference } from "./user-preference.interface"; import { UserPreferenceEntity } from "./user-preference.entity"; import { UpdateUserProfileResponseError, UserMetaDto, UserAvatarDto, UserAvatarType, UpdateUserSelfEmailResponseError } from "./dto"; @Injectable() export class UserService { constructor( @InjectConnection() private readonly connection: Connection, @InjectRepository(UserEntity) private readonly userRepository: Repository<UserEntity>, @InjectRepository(UserInformationEntity) private readonly userInformationRepository: Repository<UserInformationEntity>, @InjectRepository(UserPreferenceEntity) private readonly userPreferenceRepository: Repository<UserPreferenceEntity>, @Inject(forwardRef(() => AuthEmailVerificationCodeService)) private readonly authEmailVerificationCodeService: AuthEmailVerificationCodeService, @Inject(forwardRef(() => LockService)) private readonly lockService: LockService, @Inject(forwardRef(() => ConfigService)) private readonly configService: ConfigService, @Inject(forwardRef(() => SubmissionService)) private readonly submissionService: SubmissionService, @Inject(forwardRef(() => UserPrivilegeService)) private readonly userPrivilegeService: UserPrivilegeService, private readonly auditService: AuditService ) { this.auditService.registerObjectTypeQueryHandler(AuditLogObjectType.User, async (userId, locale, currentUser) => { const user = await this.findUserById(userId); return !user ? null : await this.getUserMeta(user, currentUser); }); } async findUserById(id: number): Promise<UserEntity> { return await this.userRepository.findOne({ id }); } async findUserInformationByUserId(id: number): Promise<UserInformationDto> { return await this.userInformationRepository.findOne({ userId: id }); } async findUsersByExistingIds(userIds: number[]): Promise<UserEntity[]> { if (userIds.length === 0) return []; const uniqueIds = Array.from(new Set(userIds)); const records = await this.userRepository.findByIds(uniqueIds); const map = Object.fromEntries(records.map(record => [record.id, record])); return userIds.map(userId => map[userId]); } async findUserByUsername(username: string): Promise<UserEntity> { return await this.userRepository.findOne({ username }); } async findUserByEmail(email: string): Promise<UserEntity> { return await this.userRepository.findOne({ email }); } private getUserAvatar(user: UserEntity): UserAvatarDto { const type = user.avatarInfo.substr(0, user.avatarInfo.indexOf(":")); const plainKey = user.avatarInfo.slice(user.avatarInfo.indexOf(":") + 1); switch (type) { case "github": return { type: UserAvatarType.GitHub, key: plainKey }; case "qq": return { type: UserAvatarType.QQ, key: plainKey }; case "gravatar": default: return { type: UserAvatarType.Gravatar, key: crypto .createHash("md5") .update((plainKey || user.email).trim().toLowerCase()) .digest("hex") }; } } /** * If the current user is admin or have manage user pervilege, the email will be returned * even if the user set public email to false. */ async getUserMeta(user: UserEntity, currentUser: UserEntity): Promise<UserMetaDto> { return { id: user.id, username: user.username, email: user.publicEmail || (currentUser && (currentUser.id === user.id || (await this.userPrivilegeService.userHasPrivilege(currentUser, UserPrivilegeType.ManageUser)))) ? user.email : null, avatar: this.getUserAvatar(user), nickname: user.nickname, bio: user.bio, isAdmin: user.isAdmin, acceptedProblemCount: user.acceptedProblemCount, submissionCount: user.submissionCount, rating: user.rating, registrationTime: user.registrationTime }; } async userExists(id: number): Promise<boolean> { return (await this.userRepository.count({ id })) !== 0; } async checkUsernameAvailability(username: string): Promise<boolean> { return ( (await this.userRepository.count({ username })) === 0 ); } async checkEmailAvailability(email: string): Promise<boolean> { return ( (await this.userRepository.count({ email })) === 0 ); } /** * The username and email won't be updated if null. * The information (bio, sex, org, location) will be always updated. */ async updateUserProfile( user: UserEntity, username: string, email: string, publicEmail: boolean, avatarInfo: string, nickname: string, bio: string, information: UserInformationDto ): Promise<UpdateUserProfileResponseError> { const changingUsername = username != null; const changingEmail = email != null && !this.configService.config.preference.security.requireEmailVerification; try { if (changingUsername) user.username = username; if (changingEmail) user.email = email; user.publicEmail = publicEmail; user.avatarInfo = avatarInfo; user.nickname = nickname; user.bio = bio; const userInformation = await this.findUserInformationByUserId(user.id); userInformation.organization = information.organization; userInformation.location = information.location; userInformation.url = information.url; userInformation.telegram = information.telegram; userInformation.qq = information.qq; userInformation.github = information.github; await this.connection.transaction("READ COMMITTED", async transactionalEntityManager => { await transactionalEntityManager.save(userInformation); await transactionalEntityManager.save(user); }); } catch (e) { if (changingUsername && !(await this.checkUsernameAvailability(username))) return UpdateUserProfileResponseError.DUPLICATE_USERNAME; if (changingEmail && !(await this.checkEmailAvailability(email))) return UpdateUserProfileResponseError.DUPLICATE_EMAIL; throw e; } return null; } async updateUserSelfEmail( user: UserEntity, email: string, emailVerificationCode: string ): Promise<UpdateUserSelfEmailResponseError> { if (this.configService.config.preference.security.requireEmailVerification) { // Delay for security await delay(DELAY_FOR_SECURITY); if (!(await this.authEmailVerificationCodeService.verify(email, emailVerificationCode))) return UpdateUserSelfEmailResponseError.INVALID_EMAIL_VERIFICATION_CODE; } try { user.email = email; await this.userRepository.save(user); } catch (e) { if (!(await this.checkEmailAvailability(email))) return UpdateUserSelfEmailResponseError.DUPLICATE_EMAIL; throw e; } if (this.configService.config.preference.security.requireEmailVerification) { await this.authEmailVerificationCodeService.revoke(email, emailVerificationCode); } return null; } async searchUser(query: string, wildcard: "Start" | "End" | "Both", maxTakeCount: number): Promise<UserEntity[]> { query = escapeLike(query); if (wildcard === "Start" || wildcard === "Both") query = `%${query}`; if (wildcard === "End" || wildcard === "Both") query += "%"; return await this.userRepository.find({ where: { username: Like(query) }, order: { username: "ASC" }, take: maxTakeCount }); } async getUserList( sortBy: "acceptedProblemCount" | "rating", skipCount: number, takeCount: number ): Promise<[users: UserEntity[], count: number]> { return await this.userRepository.findAndCount({ order: { [sortBy]: "DESC" }, skip: skipCount, take: takeCount }); } async onDeleteProblem(problemId: number, transactionalEntityManager: EntityManager): Promise<void> { // submissionCount await transactionalEntityManager.query( "UPDATE `user` " + "INNER JOIN " + "(SELECT `submitterId`, COUNT(*) AS `count` FROM `submission` WHERE `problemId` = ? GROUP BY `submitterId`) `statistics`" + "ON `user`.`id` = `statistics`.`submitterId` " + "SET `submissionCount` = `submissionCount` - `statistics`.`count`", [problemId] ); // acceptedProblemCount const queryAcceptedUsers = transactionalEntityManager .createQueryBuilder() .select("DISTINCT(submitterId)") .from(SubmissionEntity, "submission") .where("problemId = :problemId", { problemId }) .andWhere("status = :status", { status: SubmissionStatus.Accepted }); await transactionalEntityManager .createQueryBuilder() .update(UserEntity, { acceptedProblemCount: () => "acceptedProblemCount - 1" }) .where(() => `id IN (${queryAcceptedUsers.getQuery()})`) .setParameters(queryAcceptedUsers.expressionMap.parameters) .execute(); } async updateUserSubmissionCount(userId: number, incSubmissionCount: number): Promise<void> { if (incSubmissionCount !== 0) { await this.userRepository.increment({ id: userId }, "submissionCount", incSubmissionCount); } } async updateUserAcceptedCount( userId: number, problemId: number, type: "NON_AC_TO_AC" | "AC_TO_NON_AC" ): Promise<void> { await this.lockService.lock(`updateUserAcceptedCount_${userId}_${problemId}`, async () => { if (type === "NON_AC_TO_AC") { if ((await this.submissionService.getUserProblemAcceptedSubmissionCount(userId, problemId)) === 1) { await this.userRepository.increment({ id: userId }, "acceptedProblemCount", 1); } } else { if ((await this.submissionService.getUserProblemAcceptedSubmissionCount(userId, problemId)) === 0) { await this.userRepository.increment({ id: userId }, "acceptedProblemCount", -1); } } }); } async getUserRank(user: UserEntity): Promise<number> { return ( 1 + (await this.userRepository.count( this.configService.config.preference.misc.sortUserByRating ? { rating: MoreThan(user.rating) } : { acceptedProblemCount: MoreThan(user.acceptedProblemCount) } )) ); } async getUserPreference(user: UserEntity): Promise<UserPreference> { const userPreference = await this.userPreferenceRepository.findOne({ userId: user.id }); return userPreference.preference; } async updateUserPreference(user: UserEntity, preference: UserPreference): Promise<void> { const userPreference = await this.userPreferenceRepository.findOne({ userId: user.id }); userPreference.preference = preference; await this.userPreferenceRepository.save(userPreference); } }
the_stack
import {ActionManager} from "./ActionManager"; import {NameManager } from './NameManager'; const LITERAL_TYPES = { string: "lit", number: "num", function: "fun", boolean: "bool", StringLiteral: "lit", NumericLiteral: "num", Identifier: "iden", BooleanLiteral: "bool" }; const DECLARATION_TYPES = Object.assign( { VariableDeclarator: "var" }, LITERAL_TYPES ); function mapType(type, value) { if (DECLARATION_TYPES[type]) { return DECLARATION_TYPES[type]; } if (type === "ArrowFunctionExpression" || type === "FunctionExpression") { return "fun"; } if (type === "ArrayExpression") { return "arr"; } if (type === "ObjectExpression") { return "obj"; } if (value instanceof Array) { return "arr"; } if (value instanceof Object) { return "obj"; } throw new Error(`Unknown type ${typeof value} of ${value}`); } const LITERALS = { NumericLiteral: "num", Identifier: "iden", BooleanLiteral: "bol", StringLiteral: "str" }; const COMPARE_OPERATORS = ["!=", "==", ">=", "<=", "<", ">", "===", "!=="]; const OPERATORS = [ "===", "!==", "!=", "==", ">=", "<=", "<", ">", "+", "-", "*", "/", "%", "&&", "||" ]; function isSimpleForm(_node) { return OPERATORS.includes(_node.operator); } function tryTurnThisExpressionToIdentifier(_node) { if (_node.type === "ThisExpression") { _node.type = "Identifier"; _node.name = "this"; } } /** * Return whether a variable is reassigned in an expression or a statement * * @param {name of a variable} name * @param {the node where the variable might be reassigned} node */ function isReassigned(name, node) { if (!node || typeof node !== "object") { return false; } if ( node.left && node.left.name === name && node.type === "AssignmentExpression" ) { return true; } if (node.type === "UpdateExpression" && node.argument.name === name) { return true; } if (node instanceof Array) { for (const sub of node) { if (isReassigned(name, sub)) { return true; } } return false; } for (const key in node) { if (node.hasOwnProperty(key) && isReassigned(name, node[key])) { return true; } } return false; } function isIteratingFromZeroToN(_node) { if (!_node.init || _node.init.declarations.length !== 1) { return false; } try { if (_node.init.declarations[0].init.value !== 0) { return false; } if (_node.test.left.name !== _node.init.declarations[0].id.name) { return false; } if (_node.test.operator !== "<") { return false; } if (!(_node.test.right.type in LITERALS)) { return false; } if (_node.update.operator !== "++") { return false; } } catch (e) { return false; } return true; } /** * Convert JS AST to Wenyan Lang ASC * * @param {Ast} ast * @param {string} js */ export function ast2asc(ast, js) { const nameManager = new NameManager(ast); const signatureCache = {}; const nodes = ast.program.body; const NEW_SIGNATURE = "JS_NEW()"; const NEW_FUNC_NAME = "造物"; // const INDEX_SIGNATURE = "JS_INDEX()"; const INDEX_FUNC = "求索"; const INDEX_ASSIGN_SIGNATURE = "JS_INDEX_ASSIGN()"; const INDEX_ASSIGN_FUNC = "賦值"; const JS_SUBSCRIPT = "JsSubscript()"; const JS_SUBSCRIPT_FUN = "獲取"; nameManager.registerName(NEW_FUNC_NAME, 'func'); nameManager.registerName(INDEX_FUNC, 'func'); nameManager.registerName(INDEX_ASSIGN_FUNC, 'func'); nameManager.registerName(JS_SUBSCRIPT_FUN, 'func'); const actionManager = new ActionManager(nameManager); const polyfillAM = new ActionManager(nameManager); // handle a++ let postProcess = []; for (var node of nodes) { process(node); consumePostProcess(); } let ans = actionManager.getActions(); if (polyfillAM.actions.length) { polyfillAM.addComment('============'); ans = polyfillAM.actions.concat(ans); } return ans; function consumePostProcess() { for (var func of postProcess) { func(); } postProcess = []; } function process(_node) { switch (_node.type) { case "VariableDeclaration": handleDeclaration(_node); break; case "ExpressionStatement": handleExpressionStatement(_node.expression); break; case "UpdateExpression": case "CallExpression": handleExpressionStatement(_node); break; case "DoWhileStatement": case "WhileStatement": actionManager.addWhileTrue(); if (_node.type === "WhileStatement") { breakWhenTestIsFalse(_node.test); } processNodesAndHandlePostProcess(_node.body.body); if (_node.type === "DoWhileStatement") { breakWhenTestIsFalse(_node.test); } actionManager.addEnd(); break; case "IfStatement": addIfTestExpression(_node); if (_node.consequent.body) { processNodesAndHandlePostProcess(_node.consequent.body); } else { process(_node.consequent); } if (_node.alternate) { actionManager.addElse(); if (_node.alternate.body) { processNodesAndHandlePostProcess(_node.alternate.body); } else { process(_node.alternate); } } actionManager.addEnd(); break; case "BreakStatement": actionManager.addBreak(); break; case "LogicalExpression": case "BinaryExpression": wrapBinaryExpression(_node); break; case "ObjectExpression": assert(_node._name != null, ); addVarOp([_node._name], [], "obj"); initObjectProperties(_node._name, _node.properties); break; case "ReturnStatement": { actionManager.addReturn(getTripleProp(_node.argument, false)); break; } case "ForStatement": handleForStatement(_node); break; case "ForOfStatement": assert(_node.right.type === "Identifier"); actionManager.addFor( _node.right.name, getTripleProp(_node.left, false)[1] ); processNodesAndHandlePostProcess(_node.body.body); actionManager.addEnd(); break; case "MemberExpression": handleMemberExpression(_node); break; case "ArrayExpression": handleArrayExpression(_node); break; case "UnaryExpression": wrapUnaryExpression(_node); break; case "FunctionExpression": { wrapFunctionExpression(_node); break; } case "FunctionDeclaration": addVarOp([_node.id.name], [], "fun"); addFunction(_node); break; case "NewExpression": wrapJsNewExpression(_node); break; case "SequenceExpression": processNodesAndHandlePostProcess(_node.expressions); break; case "AssignmentExpression": handleAssignmentExpression(_node); break; case "EmptyStatement": break; default: notImpErr(_node); } } function wrapUnaryExpression(_node) { if (_node.operator === '!') { actionManager.addNot(getTripleProp(_node.argument, true)); } else if (_node.operator === '-') { actionManager.addOp( '-', ['num', 0, _node.start], getTripleProp(_node.argument, true), ); } else { notImpErr(); } } function breakWhenTestIsFalse(test) { const v = getTripleProp(test); if (v[0] === "bool") { if (v[1]) { // <del> if (!true) {break} </del> return; } else { // <del> if (!false) </del> break actionManager.addBreak(); } return; } actionManager.addIf( [v, ["cmp", "=="], ["num", 0]] ) actionManager.addBreak(); actionManager.addEnd(); } function wrapBinaryExpression(_node) { if (isSimpleForm(_node)) { // TODO: remove name hotfix when op== op<= is supported officially actionManager.addOp( _node.operator, getTripleProp(_node.left, false), getTripleProp(_node.right, true), _node._name ); } else { notImpErr(_node); } } function wrapFunctionExpression(_node) { // Maybe there is a better way to wrap this in future const name = nameManager.getNextTmpName('func'); addVarOp([name], [], "fun"); addFunction(_node); addVarOp([], [["iden", name]], "fun"); } function handleArrayExpression(_node) { const name = _node._name || nameManager.getNextTmpName('arr'); addVarOp([name], [], "arr"); actionManager.addPush( name, _node.elements.map((x) => getTripleProp(x, false)) ); if (_node._name == null) { // Stage this variable addVarOp([], [["iden", name]], "arr"); } } function addNamingOp(names) { actionManager.addName(names); for (const name of names) { nameManager.registerName(name, "obj"); } } function addReassignOp({lhs, rhs, lhssubs = undefined}) { if (lhs[0] === "iden") { nameManager.registerName(lhs[1]); } actionManager.addReassign(lhs, rhs, lhssubs); } function addVarOp(names, values, type, polyfill = false) { const count = Math.max(names.length, values.length); for (let i = 0; i < count; i++) { if (names[i]) { assert(typeof names[i] === "string"); } if (values[i]) { assert(values[i] instanceof Array); assert(values[i][0] == null || typeof values[i][0] === "string"); } } if (polyfill) { polyfillAM.addVar(names, values, type); } else { actionManager.addVar(names, values, type) } for (const name of names) { nameManager.registerName(name, type); } } function saveStagedToNewVar() { const newName = nameManager.getNextTmpName(); addNamingOp([newName]); return newName; } function getIfProp(_node) { if (_node.type === "MemberExpression") { if ( _node.object.type === "Identifier" && _node.property.type === "Identifier" && _node.property.name === "length" ) { return [ ["iden", _node.object.name], ["ctnr", "len"] ]; } else if ( _node.object.type === "Identifier" && _node.property.type === "BinaryExpression" && _node.property.operator === "-" && _node.property.right.type === "NumericLiteral" && _node.property.right.value === 1 ) { return [ ["iden", _node.object.name], ["ctnr", "subs"], getTripleProp(_node.property.left, false) ]; } else { return [getTripleProp(_node, false)]; } } else if (_node.type in LITERAL_TYPES) { return [getTripleProp(_node, false)]; } else if (_node.type.endsWith("Expression")) { return [getTripleProp(_node, false)]; } else { notImpErr(_node); } } /** * This function is used to wrap the global object * which has not been supported by wenyan. * * 1. It will create necessary function * 2. Invoke the function * * @param {*} _node */ function wrapJsGlobalFunction(_node) { // FIXME: it also wrap function call on rhs assert(_node.type === "CallExpression"); let signature = ""; const args = []; function _getSignature(target) { if (target.type === "Identifier") { signature += target.name; } else if (target.type === "MemberExpression") { _getSignature(target.object); signature += "."; _getSignature(target.property); } else if (target.type === "CallExpression") { _getSignature(target.callee); signature += "("; for (let i = 0; i < target.arguments.length; i++) { // Chinese char may introduce error // const name = "子" + LAMBDA[i]; const name = "_a" + i; signature += `${name},`; args.push(name); } signature += ")"; } else { notImpErr(); } } _getSignature(_node); let funcName; if (signature in signatureCache) { funcName = signatureCache[signature]; } else { funcName = nameManager.getNextTmpName('func'); signatureCache[signature] = funcName; // TODO: refactor, extract all func together addVarOp([funcName], [], "fun", false); actionManager.addFun( _node.arguments.map((x, index) => { return {type: "obj", name: args[index]}; }), ); actionManager.addFunBody(); actionManager.addReturn(['data', signature]); actionManager.addFunEnd(); } actionManager.addCall( funcName, _node.arguments.map((x) => getTripleProp(x, false)), ); } function wrapJsNativeFunction(signature, funcName, args, value) { if (!(signature in signatureCache)) { addVarOp([funcName], [], "fun", true); polyfillAM.addFun(args); polyfillAM.addFunBody(); polyfillAM.addReturn(['data', value]); polyfillAM.addFunEnd(); signatureCache[signature] = funcName; } } function wrapJsNewExpression(_node) { assertStrongly(_node.type === "NewExpression", _node); wrapJsNativeFunction( NEW_SIGNATURE, NEW_FUNC_NAME, [{type: "obj", name: "蓝图"}], "new 蓝图(...Array.prototype.slice.call(arguments, 1))" ); actionManager.addCall( NEW_FUNC_NAME, [_node.callee] .concat(_node.arguments) .map((x) => getTripleProp(x, false)) ); } // function wrapJsIndexing(_node) { // wrapJsNativeFunction( // INDEX_SIGNATURE, // INDEX_FUNC, // [{ type: "obj", name: "道" }], // "typeof 道 === 'string'? 道 : 道 + 1" // ); // ans.push({ // op: "call", // fun: INDEX_FUNC, // args: [getTripleProp(_node)], // pos: _node.start // }); // } function wrapJsSubscript(obj, field) { wrapJsNativeFunction( JS_SUBSCRIPT, JS_SUBSCRIPT_FUN, [ {type: "obj", name: "對象"}, {type: "obj", name: "域"} ], "對象[域]" ); actionManager.addCall( JS_SUBSCRIPT_FUN, [obj, field] ); } function wrapJsIndexAssignment(lhs, lhssubs, rhs) { wrapJsNativeFunction( INDEX_ASSIGN_SIGNATURE, INDEX_ASSIGN_FUNC, [ {type: "obj", name: "對象"}, {type: "obj", name: "域"}, {type: "obj", name: "值"} ], "對象[域] = 值;" ); actionManager.addCall( INDEX_ASSIGN_FUNC, [lhs, lhssubs, rhs] ); } /** * Get the triple tuple representation (used in Wenyan ASC) of a node * * @param {Node} _node * @param {boolean} canUseStaged */ function getTripleProp(_node, canUseStaged = false) { if (_node == null) { return undefined; } function wrap() { if (canUseStaged) { return ["ans", null]; } const name = nameManager.getNextTmpName(); addNamingOp([name]); return ["iden", name, _node.start]; } if (_node.type === "CallExpression") { handleUniversalCallExp(_node); return wrap(); } if (_node.type === "MemberExpression" || _node.type === "CallExpression") { process(_node); return wrap(); } if (_node.type === "ArrayExpression") { _node._name = nameManager.getNextTmpName(); process(_node); return ["iden", _node._name, _node.start]; } if (_node.type === "VariableDeclaration") { const names = handleDeclaration(_node); assert(names.length === 1); return ["iden", names[0], _node.start]; } if ( _node.type === "BinaryExpression" || _node.type === "LogicalExpression" || _node.type === "ObjectExpression" || _node.type === "FunctionExpression" || _node.type === "NewExpression" ) { // TODO: remove this hotfix in the future version if ( _node.type === "ObjectExpression" || COMPARE_OPERATORS.includes(_node.operator) ) { _node._name = nameManager.getNextTmpName(); process(_node); return ["iden", _node._name, _node.start]; } process(_node); return wrap(); } if (_node.type === "UnaryExpression") { if (_node.operator === "-") { if (_node.argument.type === "NumericLiteral") { return ["num", -_node.argument.value]; } actionManager.addOp( '-', ['num', 0], getTripleProp(_node.argument, true) ); return wrap(); } else if (_node.operator === "!") { actionManager.addNot( getTripleProp(_node.argument, true), ); return wrap(); } else { notImpErr(_node); } } if (_node.type === "UpdateExpression") { handleUpdateExpression(_node); return getTripleProp(_node.argument); } if (_node.type === 'AssignmentExpression') { handleAssignmentExpression(_node); return getTripleProp(_node.left) } tryTurnThisExpressionToIdentifier(_node); if (!(_node.type in LITERAL_TYPES)) { notImpErr(_node); } if (_node.type === "Identifier") { if (canUseStaged && actionManager.tryToCompress(_node.name)) { return ["ans", null]; } return ["iden", _node.name, _node.start]; } if (_node.type === "StringLiteral") { if (_node.value != null) { return ["lit", `"${_node.value}"`, _node.start]; } return ["lit", null, _node.start]; } return [LITERAL_TYPES[_node.type], _node.value, _node.start]; } function handleUniversalCallExp(_node) { if (nameManager.has(_node.callee.name)) { actionManager.addCall( _node.callee.name, _node.arguments.map((x) => getTripleProp(x, false)), ); } else { wrapJsGlobalFunction(_node); } } function assertStrongly(cond, _node, msg = "") { if (!cond) { const errorSnippet = js.slice(_node.start, _node.end); console.log(errorSnippet); throw new Error(`AssertError: line ${_node.loc.start.line}, col ${_node.loc.start.column}; \t"${errorSnippet}" \t${msg} This is weird 😣. If you see this message, it means our tests haven't covered this case. Please submit an issue to help us fix it! https://github.com/zxch3n/wenyanizer/issues/new `); } } function assert(cond, msg='') { if (!cond) { throw new Error(msg + JSON.stringify(node.loc.start)); } } function notImpErr(_node = node, msg = "") { const errorSnippet = js.slice(_node.start, _node.end); console.log(errorSnippet); throw new Error(`NotImplementedError: line ${_node.loc.start.line}, col ${_node.loc.start.column}; \t"${errorSnippet}" \t${msg} The grammar is not supported yet. `); } function addFunction(funcNode) { actionManager.addFun( funcNode.params.map((x) => { const props = getTripleProp(x); return { name: props[1], type: "obj" }; }), ); if (funcNode.id) { // Skip Anonymous Function nameManager.registerName(funcNode.id.name, "fun"); } actionManager.addFunBody(); processNodesAndHandlePostProcess(funcNode.body.body); actionManager.addFunEnd(); // clear the stack actionManager.addDiscard(); } function createTempVarToWrap(values, type = undefined, names = []) { const tripleRep = values.map((x) => getTripleProp(x, false)); ({type} = preprocessTypeValueBeforeDeclare( type || tripleRep[0][0], values[0] )); if (type === "iden") { type = nameManager.getType(values[0]); assert(type != null); } addVarOp(names, tripleRep, type); } function getTest(test) { if (test.type === "BinaryExpression") { if (COMPARE_OPERATORS.includes(test.operator)) { return [ ...getIfProp(test.left), ["cmp", test.operator], ...getIfProp(test.right) ]; } else if (test in LITERAL_TYPES) { return [getTripleProp(test, false)]; } else { notImpErr(test); } } else if (test.type in LITERAL_TYPES) { return [getTripleProp(test, false)]; } else if ( test.type === "LogicalExpression" || test.type === "BinaryExpression" || test.type === "UnaryExpression" ) { return [getTripleProp(test, false)]; } else if (test.type === "CallExpression") { // FIXME: unsure return [getTripleProp(test, false)]; } else { notImpErr(test); } notImpErr(test); } function addIfTestExpression(_node) { actionManager.addIf(getTest(_node.test)); } function handleExpressionStatement(_node) { switch (_node.type) { case "CallExpression": handleCallExpression(_node); break; case "ExpressionStatement": process(_node.expression); break; case "AssignmentExpression": handleAssignmentExpression(_node); break; case "UpdateExpression": handleUpdateExpression(_node); break; default: notImpErr(_node, `Unknown expression ${_node.expression.type}`); } } function handleUpdateExpressionImmediately(_node) { assertStrongly(_node.operator === "++" || _node.operator === "--", _node); if (_node.argument.type === "MemberExpression") { handleAssignWithLhsMemberExpression({ ..._node, left: _node.argument, right: { ..._node, type: "BinaryExpression", operator: _node.operator[0], left: _node.argument, right: { ..._node, type: "NumericLiteral", value: 1 } }, type: "AssignmentExpression" }); return; } assertStrongly(_node.argument.type === "Identifier", _node); actionManager.addOp( _node.operator[0], ["iden", _node.argument.name], ["num", 1, _node.start] ); addReassignOp({ lhs: ["iden", _node.argument.name], rhs: ["ans", null] }); } function handleUpdateExpression(_node) { // Use _done flag to avoid execute update multiple times // because getTripleProp may invoke this node from different ancester. // I may need to cache getTripleProp if (_node._done) { return; } _node._done = true; if (_node.prefix) { handleUpdateExpressionImmediately(_node); } else { postProcess.push(() => { handleUpdateExpressionImmediately(_node); }); } } function handleCallExpression(_node) { if (_node.callee.type === "Identifier") { actionManager.addCall( _node.callee.name, _node.arguments.map((x) => getTripleProp(x, false)), ); } else if (_node.callee.object.name === "console") { let isShinkable = true; const n = _node.arguments.length; for (let j = 0; j < n; j++) { const name = _node.arguments[j].name; if ( !nameManager.namesOnlyUsedOnce.has(name) || ans[ans.length - n + j].names[0] !== name || (ans[ans.length - n + j].op !== 'var' && ans[ans.length - n + j].op !== 'name') ) { isShinkable = false; break; } } if (isShinkable) { // Remove the declaration target for (let j = 0; j < n; j++) { if (ans[ans.length - n + j].op === "var") { ans[ans.length - n + j].names = []; } else if (ans[ans.length - n + j].op === "name") { ans.splice(ans.length - n + j, 1); } } } else { createTempVarToWrap(_node.arguments); } actionManager.addPrint(); } else if ( _node.callee.type === "MemberExpression" && _node.callee.property.name === "push" ) { assert(_node.callee.object.type === "Identifier"); actionManager.addPush( _node.callee.object.name, _node.arguments.map((x) => getTripleProp(x, false)) ); } else if (_node.callee.type.endsWith("MemberExpression")) { // Concat let isConcat = true; let isSliceOne = false; let callExp = _node; const allArr = []; while (callExp && callExp.type === "CallExpression") { if (callExp.arguments.length !== 1) { isConcat = false; break; } allArr.push(callExp.arguments[0].name); if (callExp.callee.property.name !== "concat") { isConcat = false; break; } callExp = callExp.callee.object; } if ( _node.callee.property.name === "slice" && _node.arguments.length === 1 && _node.arguments[0].value === 1 && _node.callee.object.type === "Identifier" ) { isSliceOne = true; } if (isConcat) { allArr.push(callExp.name); actionManager.addCat(allArr.reverse()); return; } else if (isSliceOne) { actionManager.addSubscript(_node.callee.object.name, ['ctnr', 'rest']); return; } handleUniversalCallExp(_node); } else { notImpErr(_node); } } function handleAssignmentExpression(_node) { if (_node.operator.length === 2) { // if op in {+=, -=, *=, ...} assertStrongly(_node.operator[1] === "=", _node); _node.right = { type: "BinaryExpression", operator: _node.operator[0], left: _node.left, right: _node.right }; _node.operator = "="; } assertStrongly(_node.operator === "=", _node); if (_node.left.type === "Identifier") { if (_node.right.type === "FunctionExpression") { { // Assert we have initialized the function const last = actionManager.actions[actionManager.actions.length - 1]; if (last.op !== "var" || last.names[0] !== _node.left.name) { notImpErr(_node); } } addFunction(_node.right); } else { addReassignOp({ lhs: ["iden", _node.left.name], rhs: getTripleProp(_node.right, true) }); } } else if (_node.left.type === "MemberExpression") { handleAssignWithLhsMemberExpression(_node); } else { assertStrongly( false, _node, "Assignment with left hand side of type that is nor Identifier nor MemberExpression" ); } } function handleAssignWithLhsMemberExpression(_node) { let lhsName = undefined; if (_node.left.object.type === "MemberExpression") { // Cases like: `a['b']['c'] = 5` process(_node.left.object); lhsName = nameManager.getNextTmpName(); addNamingOp([lhsName]); } tryTurnThisExpressionToIdentifier(_node.left.object); if (_node.left.object.type !== "Identifier" && !lhsName) { notImpErr(_node); } const lhs = lhsName ? ["iden", lhsName] : ["iden", _node.left.object.name]; if ( _node.left.property.type === "BinaryExpression" && _node.left.property.operator === "-" && _node.left.property.right.value === 1 ) { // Cases such as: a[b - 1], a[9 - 1] const lhssubs = getTripleProp(_node.left.property.left, false); addReassignOp({ lhs, lhssubs, rhs: getTripleProp(_node.right, true) }); } else if (_node.left.property.type === "StringLiteral") { // Cases like: a['123'] addReassignOp({ lhs, lhssubs: ["lit", `"${_node.left.property.value}"`], rhs: getTripleProp(_node.right, true) }); } else if (_node.left.property.type === "NumericLiteral") { // Cases: a[0] addReassignOp({ lhs, lhssubs: ["num", _node.left.property.value + 1], rhs: getTripleProp(_node.right, true) }); } else if (js[_node.left.object.end] === ".") { addReassignOp({ lhs, lhssubs: ["lit", `"${_node.left.property.name}"`], rhs: getTripleProp(_node.right, true) }); } else { // wrapJsIndexing(_node.left.property); // const name = getNextTmpName(); // addNamingOp([name]); wrapJsIndexAssignment( getTripleProp(_node.left.object), getTripleProp(_node.left.property), getTripleProp(_node.right, false) ); // Clear the stack actionManager.addDiscard(); } } function handleDeclaration(_node, defaultType = "obj") { const names = []; for (let i = 0; i < _node.declarations.length; i++) { const declarator = _node.declarations[i]; const name = declarator.id.name; if (declarator.init == null) { addVarOp([name], [], defaultType); names.push(name); } else if (declarator.init.type === "NewExpression") { wrapJsNewExpression(declarator.init); addNamingOp([name]); } else if ( declarator.init.type === "BinaryExpression" || declarator.init.type === "CallExpression" || declarator.init.type === "MemberExpression" || declarator.init.type === "UnaryExpression" || declarator.init.type === "LogicalExpression" ) { declarator.init._name = name; process(declarator.init); if (COMPARE_OPERATORS.includes(declarator.init.operator)) { // FIXME: This is a ad-hoc fix for https://github.com/LingDong-/wenyan-lang/issues/317 } else if (nameManager.has(name)) { addReassignOp({ lhs: ["iden", name], rhs: ["ans", null] }); } else { addNamingOp([name]); } names.push(name); } else { let value = declarator.init.value || declarator.init.name; const dtype = mapType(declarator.init.type || typeof value, value); appendDeclaration(dtype, value, name); names.push(name); if (dtype === "fun") { if ( declarator.init.body.extra && declarator.init.body.extra.raw === "0" ) { // Empty function return; } else if ( declarator.init.type === "ArrowFunctionExpression" || declarator.init.type === "FunctionExpression" ) { addFunction(declarator.init); } else { notImpErr(declarator); } } if (dtype === "obj" && declarator.init.properties.length) { // TODO: use new Syntax when object initialization is available initObjectProperties(name, declarator.init.properties); } if (dtype === "arr" && declarator.init.elements.length) { actionManager.addPush( name, declarator.init.elements.map((x) => getTripleProp(x, false)) ); } } } return names; } function initObjectProperties(name, properties) { for (const property of properties) { addReassignOp({ lhs: ["iden", name], lhssubs: ["lit", `"${property.key.name || property.key.value}"`], rhs: getTripleProp(property.value, true) }); } } function appendDeclaration(dtype, value, name) { let type; let toIgnoreValues; ({type, toIgnoreValues, value} = preprocessTypeValueBeforeDeclare( dtype, value )); addVarOp([name], toIgnoreValues ? [] : [[dtype, value]], type); } function preprocessTypeValueBeforeDeclare(dtype, value) { let type = dtype; let toIgnoreValues = type === "fun" || type === "arr" || type === "obj"; if (type === "iden") { type = nameManager.getType(value) || "obj"; } if (type === "bool") { type = "bol"; } if (dtype === "lit") { type = "str"; if (value) { value = `"${value}"`; } else { toIgnoreValues = true; } } return {type, toIgnoreValues, value}; } function handleMemberExpression(_node) { let object = _node.object; if ( _node.object.type === "CallExpression" || object.type === "MemberExpression" ) { process(_node.object); const newVar = saveStagedToNewVar(); object = { name: newVar, type: "Identifier" }; } tryTurnThisExpressionToIdentifier(object); assertStrongly(object.type === "Identifier", _node); if (_node.property.type.endsWith("Expression")) { if (_node.property.operator === "-" && _node.property.right.value === 1) { // a[b - 1] actionManager.addSubscript( object.name, getTripleProp(_node.property.left, true) ); } else { // a[Math.floor(b * 100 - 10)] wrapJsSubscript(getTripleProp(object), getTripleProp(_node.property)); } } else if (_node.property.type in LITERAL_TYPES) { if (_node.property.name === "length") { actionManager.addLength(object.name); } else if (_node.property.name != null) { if (_node.computed) { // a[b] wrapJsSubscript( getTripleProp(_node.object), getTripleProp(_node.property) ); } else { // a.b actionManager.addSubscript(object.name, ["lit", `"${_node.property.name}"`]); } } else if (_node.property.value != null) { if (_node.property.type === "StringLiteral") { actionManager.addSubscript(object.name, ["lit", `"${_node.property.value}"`]); } else { assert(_node.property.type === "NumericLiteral"); actionManager.addSubscript(object.name, ["num", _node.property.value + 1]); } } else { // TODO: add this part when wenyan has type assertion // 1. if target is string, target[index] // 2. if target is number, target[index + 1] notImpErr(_node); } } else { notImpErr(_node); } } function handleForStatement(_node) { let initName = ''; let _isReassigned = false; if (_node.init && _node.init.declarations) { for (const dec of _node.init.declarations) { initName = dec.id.name; if (isReassigned(dec.id.name, _node.body)) { _isReassigned = true; break; } } } // whether it is in the format of `for (let i = 0; i < n; i++)` let shouldAddManualBreak = _isReassigned || !_node.init || !_node.init.declarations || !_node.init.declarations.length || _node.init.declarations[0].init.value !== 0 || !_node.update || _node.update.operator !== "++" || _node.update.argument.name !== initName || (_node.test && (_node.test.left.name !== initName || _node.test.operator !== "<" || !(_node.test.right.type in LITERAL_TYPES))); const shouldInit = shouldAddManualBreak || (_node.init && _node.init.declarations && _node.init.declarations[0] && !_node.init.declarations[0].id.name.startsWith("_rand")); if (shouldInit && _node.init) { process(_node.init); } if (shouldAddManualBreak) { actionManager.addWhileTrue(); } else if (isIteratingFromZeroToN(_node)) { actionManager.addWhilen(getTripleProp(_node.test.right)); } else { notImpErr(_node); } // Test whether should break if (_node.test && shouldAddManualBreak) { breakWhenTestIsFalse(_node.test); } processNodesAndHandlePostProcess(_node.body.body); if (shouldInit && _node.update) { // Update before break test process(_node.update); } // update i++ immediately consumePostProcess(); actionManager.addEnd(); } function processNodesAndHandlePostProcess(body) { for (const subNode of body) { consumePostProcess(); process(subNode); } consumePostProcess(); } }
the_stack
import EventTarget from '../../polyfillLoaders/EventTarget.js'; import {Layout, Positions, ScrollDirection, Size, dimension, position} from './Layout.js'; type UpdateVisibleIndicesOptions = { emit?: boolean } export interface BaseLayoutConfig { direction?: ScrollDirection } export function dim1(direction: ScrollDirection): dimension { return direction === 'horizontal' ? 'width': 'height'; } export function dim2(direction: ScrollDirection): dimension { return direction === 'horizontal' ? 'height': 'width'; } export function pos1(direction: ScrollDirection): position { return direction === 'horizontal' ? 'left': 'top'; } export function pos2(direction: ScrollDirection): position { return direction === 'horizontal' ? 'top': 'left'; } export abstract class BaseLayout<C extends BaseLayoutConfig> implements Layout { /** * The last set viewport scroll position. */ private _latestCoords: Positions = {left: 0, top: 0}; /** * Scrolling direction. */ private _direction: ScrollDirection | null = null; /** * Dimensions of the viewport. */ private _viewportSize: Size = {width: 0, height: 0}; /** * Flag for debouncing asynchnronous reflow requests. */ private _pendingReflow = false; private _pendingLayoutUpdate = false; /** * Index of the item that has been scrolled to via the public API. When the * viewport is otherwise scrolled, this value is set back to -1. */ protected _scrollToIndex = -1; /** * When a child is scrolled to, the offset from the top of the child and the * top of the viewport. Value is a proportion of the item size. */ private _scrollToAnchor = 0; /** * The index of the first item intersecting the viewport. */ protected _firstVisible = 0; /** * The index of the last item intersecting the viewport. */ protected _lastVisible = 0; private _eventTargetPromise: Promise<void> = (EventTarget().then((Ctor) => { this._eventTarget = new Ctor(); })); /** * Pixel offset in the scroll direction of the first child. */ protected _physicalMin = 0; /** * Pixel offset in the scroll direction of the last child. */ protected _physicalMax = 0; /** * Index of the first child. */ protected _first = -1; /** * Index of the last child. */ protected _last = -1; /** * Length in the scrolling direction. */ protected _sizeDim: dimension = 'height'; /** * Length in the non-scrolling direction. */ protected _secondarySizeDim: dimension = 'width'; /** * Position in the scrolling direction. */ protected _positionDim: position = 'top'; /** * Position in the non-scrolling direction. */ protected _secondaryPositionDim: position = 'left'; /** * Current scroll offset in pixels. */ protected _scrollPosition = 0; /** * Difference between current scroll offset and scroll offset calculated due * to a reflow. */ protected _scrollError = 0; /** * Total number of items that could possibly be displayed. Used to help * calculate the scroll size. */ protected _totalItems = 0; /** * The total (estimated) length of all items in the scrolling direction. */ protected _scrollSize = 1; /** * Number of pixels beyond the viewport to still include * in the active range of items. */ // TODO (graynorton): Probably want to make this something we calculate based // on viewport size, item size, other factors, possibly still with a dial of some kind protected _overhang = 1000; private _eventTarget: EventTarget | null = null; protected get _defaultConfig() : C { return { direction: 'vertical' } as C } constructor(config?: C) { // Delay setting config so that subclasses do setup work first Promise.resolve().then(() => this.config = config || this._defaultConfig); } set config(config: C) { Object.assign(this, Object.assign({}, this._defaultConfig, config)); } get config(): C { return { direction: this.direction } as C; } /** * Maximum index of children + 1, to help estimate total height of the scroll * space. */ get totalItems(): number { return this._totalItems; } set totalItems(num) { const _num = Number(num); if (_num !== this._totalItems) { this._totalItems = _num; this._scheduleReflow(); } } /** * Primary scrolling direction. */ get direction(): ScrollDirection { return this._direction!; } set direction(dir) { // Force it to be either horizontal or vertical. dir = (dir === 'horizontal') ? dir : 'vertical'; if (dir !== this._direction) { this._direction = dir; this._sizeDim = (dir === 'horizontal') ? 'width' : 'height'; this._secondarySizeDim = (dir === 'horizontal') ? 'height' : 'width'; this._positionDim = (dir === 'horizontal') ? 'left' : 'top'; this._secondaryPositionDim = (dir === 'horizontal') ? 'top' : 'left'; this._triggerReflow(); } } /** * Height and width of the viewport. */ get viewportSize(): Size { return this._viewportSize; } set viewportSize(dims) { const {_viewDim1, _viewDim2} = this; Object.assign(this._viewportSize, dims); if (_viewDim2 !== this._viewDim2) { // this._viewDim2Changed(); this._scheduleLayoutUpdate(); } else if (_viewDim1 !== this._viewDim1) { this._checkThresholds(); } } /** * Scroll offset of the viewport. */ get viewportScroll(): Positions { return this._latestCoords; } set viewportScroll(coords) { Object.assign(this._latestCoords, coords); const oldPos = this._scrollPosition; this._scrollPosition = this._latestCoords[this._positionDim]; if (oldPos !== this._scrollPosition) { this._scrollPositionChanged(oldPos, this._scrollPosition); this._updateVisibleIndices({emit: true}); } this._checkThresholds(); } /** * Perform a reflow if one has been scheduled. */ reflowIfNeeded(force: boolean = false) { if (force || this._pendingReflow) { this._pendingReflow = false; this._reflow(); } } /** * Scroll to the child at the given index, and the given position within that * child. */ scrollToIndex(index: number, position = 'start') { if (!Number.isFinite(index)) return; index = Math.min(this.totalItems, Math.max(0, index)); this._scrollToIndex = index; if (position === 'nearest') { position = index > this._first + this._num / 2 ? 'end' : 'start'; } switch (position) { case 'start': this._scrollToAnchor = 0; break; case 'center': this._scrollToAnchor = 0.5; break; case 'end': this._scrollToAnchor = 1; break; default: throw new TypeError( 'position must be one of: start, center, end, nearest'); } this._scheduleReflow(); } async dispatchEvent(evt: Event) { await this._eventTargetPromise; this._eventTarget!.dispatchEvent(evt); } async addEventListener(type: string, listener: EventListener | EventListenerObject | null, options?: boolean | AddEventListenerOptions | undefined) { await this._eventTargetPromise; this._eventTarget!.addEventListener(type, listener, options); } async removeEventListener(type: string, callback: EventListener | EventListenerObject | null, options?: boolean | EventListenerOptions | undefined) { await this._eventTargetPromise; this._eventTarget!.removeEventListener(type, callback, options); } /** * Get the top and left positioning of the item at idx. */ protected abstract _getItemPosition(idx: number): Positions; /** * Update _first and _last based on items that should be in the current * range. */ protected abstract _getActiveItems(): void protected abstract _getItemSize(_idx: number): Size /** * Calculates (precisely or by estimating, if needed) the total length of all items in * the scrolling direction, including spacing, caching the value in the `_scrollSize` field. * * Should return a minimum value of 1 to ensure at least one item is rendered. * TODO (graynorton): Possibly no longer required, but leaving here until it can be verified. */ protected abstract _updateScrollSize(): void protected _updateLayout(): void { // Override } // protected _viewDim2Changed(): void { // this._scheduleLayoutUpdate(); // } /** * The height or width of the viewport, whichever corresponds to the scrolling direction. */ protected get _viewDim1(): number { return this._viewportSize[this._sizeDim]; } /** * The height or width of the viewport, whichever does NOT correspond to the scrolling direction. */ protected get _viewDim2(): number { return this._viewportSize[this._secondarySizeDim]; } protected _scheduleReflow() { this._pendingReflow = true; } protected _scheduleLayoutUpdate() { this._pendingLayoutUpdate = true; this._scheduleReflow(); } // For triggering a reflow based on incoming changes to // the layout config. protected _triggerReflow() { this._scheduleLayoutUpdate(); // TODO graynorton@: reflowIfNeeded() isn't really supposed // to be called internally. Address in larger cleanup // of virtualizer / layout interaction pattern. // this.reflowIfNeeded(true); Promise.resolve().then(() => this.reflowIfNeeded()); } protected _reflow() { if (this._pendingLayoutUpdate) { this._updateLayout(); this._pendingLayoutUpdate = false; } this._updateScrollSize(); this._getActiveItems(); this._scrollIfNeeded(); this._updateVisibleIndices(); this._emitScrollSize(); this._emitRange(); this._emitChildPositions(); this._emitScrollError(); } protected _scrollIfNeeded() { if (this._scrollToIndex === -1) { return; } const index = this._scrollToIndex; const anchor = this._scrollToAnchor; const pos = this._getItemPosition(index)[this._positionDim]; const size = this._getItemSize(index)[this._sizeDim]; const curAnchorPos = this._scrollPosition + this._viewDim1 * anchor; const newAnchorPos = pos + size * anchor; // Ensure scroll position is an integer within scroll bounds. const scrollPosition = Math.floor(Math.min( this._scrollSize - this._viewDim1, Math.max(0, this._scrollPosition - curAnchorPos + newAnchorPos))); this._scrollError += this._scrollPosition - scrollPosition; this._scrollPosition = scrollPosition; } protected _emitRange(inProps: unknown = undefined) { const detail = Object.assign( { first: this._first, last: this._last, num: this._num, stable: true, firstVisible: this._firstVisible, lastVisible: this._lastVisible, }, inProps); this.dispatchEvent(new CustomEvent('rangechange', {detail})); } protected _emitScrollSize() { const detail = { [this._sizeDim]: this._scrollSize, }; this.dispatchEvent(new CustomEvent('scrollsizechange', {detail})); } protected _emitScrollError() { if (this._scrollError) { const detail = { [this._positionDim]: this._scrollError, [this._secondaryPositionDim]: 0, }; this.dispatchEvent(new CustomEvent('scrollerrorchange', {detail})); this._scrollError = 0; } } /** * Get or estimate the top and left positions of items in the current range. * Emit an itempositionchange event with these positions. */ protected _emitChildPositions() { const detail: {[key: number]: Positions} = {}; for (let idx = this._first; idx <= this._last; idx++) { detail[idx] = this._getItemPosition(idx); } this.dispatchEvent(new CustomEvent('itempositionchange', {detail})); } /** * Number of items to display. */ private get _num(): number { if (this._first === -1 || this._last === -1) { return 0; } return this._last - this._first + 1; } private _checkThresholds() { if (this._viewDim1 === 0 && this._num > 0) { this._scheduleReflow(); } else { const min = Math.max(0, this._scrollPosition - this._overhang); const max = Math.min( this._scrollSize, this._scrollPosition + this._viewDim1 + this._overhang); if (this._physicalMin > min || this._physicalMax < max) { this._scheduleReflow(); } } } /** * Find the indices of the first and last items to intersect the viewport. * Emit a visibleindiceschange event when either index changes. */ protected _updateVisibleIndices(options?: UpdateVisibleIndicesOptions) { if (this._first === -1 || this._last === -1) return; let firstVisible = this._first; while ( firstVisible < this._last && Math.round( this._getItemPosition(firstVisible)[this._positionDim] + this._getItemSize(firstVisible)[this._sizeDim] ) <= Math.round (this._scrollPosition) ) { firstVisible++; } let lastVisible = this._last; while ( lastVisible > this._first && Math.round(this._getItemPosition(lastVisible)[this._positionDim]) >= Math.round(this._scrollPosition + this._viewDim1) ) { lastVisible--; } if (firstVisible !== this._firstVisible || lastVisible !== this._lastVisible) { this._firstVisible = firstVisible; this._lastVisible = lastVisible; if (options && options.emit) { this._emitRange(); } } } private _scrollPositionChanged(oldPos: number, newPos: number) { // When both values are bigger than the max scroll position, keep the // current _scrollToIndex, otherwise invalidate it. const maxPos = this._scrollSize - this._viewDim1; if (oldPos < maxPos || newPos < maxPos) { this._scrollToIndex = -1; } } }
the_stack
import { ConcreteRequest } from "relay-runtime"; import { FragmentRefs } from "relay-runtime"; export type TrackOrderSectionTestsQueryVariables = {}; export type TrackOrderSectionTestsQueryResponse = { readonly commerceOrder: { readonly internalID: string; readonly " $fragmentRefs": FragmentRefs<"TrackOrderSection_section">; } | null; }; export type TrackOrderSectionTestsQuery = { readonly response: TrackOrderSectionTestsQueryResponse; readonly variables: TrackOrderSectionTestsQueryVariables; }; /* query TrackOrderSectionTestsQuery { commerceOrder(id: "some-id") { __typename internalID ...TrackOrderSection_section id } } fragment TrackOrderSection_section on CommerceOrder { __isCommerceOrder: __typename state lineItems(first: 1) { edges { node { shipment { status trackingUrl trackingNumber deliveryStart deliveryEnd estimatedDeliveryWindow id } fulfillments(first: 1) { edges { node { createdAt trackingId estimatedDelivery id } } } id } } } } */ const node: ConcreteRequest = (function(){ var v0 = [ { "kind": "Literal", "name": "id", "value": "some-id" } ], v1 = { "alias": null, "args": null, "kind": "ScalarField", "name": "internalID", "storageKey": null }, v2 = [ { "kind": "Literal", "name": "first", "value": 1 } ], v3 = { "alias": null, "args": null, "kind": "ScalarField", "name": "id", "storageKey": null }, v4 = { "enumValues": null, "nullable": false, "plural": false, "type": "String" }, v5 = { "enumValues": null, "nullable": false, "plural": false, "type": "ID" }, v6 = { "enumValues": null, "nullable": true, "plural": false, "type": "String" }; return { "fragment": { "argumentDefinitions": [], "kind": "Fragment", "metadata": null, "name": "TrackOrderSectionTestsQuery", "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": null, "kind": "LinkedField", "name": "commerceOrder", "plural": false, "selections": [ (v1/*: any*/), { "args": null, "kind": "FragmentSpread", "name": "TrackOrderSection_section" } ], "storageKey": "commerceOrder(id:\"some-id\")" } ], "type": "Query", "abstractKey": null }, "kind": "Request", "operation": { "argumentDefinitions": [], "kind": "Operation", "name": "TrackOrderSectionTestsQuery", "selections": [ { "alias": null, "args": (v0/*: any*/), "concreteType": null, "kind": "LinkedField", "name": "commerceOrder", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "__typename", "storageKey": null }, (v1/*: any*/), { "kind": "TypeDiscriminator", "abstractKey": "__isCommerceOrder" }, { "alias": null, "args": null, "kind": "ScalarField", "name": "state", "storageKey": null }, { "alias": null, "args": (v2/*: any*/), "concreteType": "CommerceLineItemConnection", "kind": "LinkedField", "name": "lineItems", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceLineItemEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceLineItem", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceShipment", "kind": "LinkedField", "name": "shipment", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "status", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "trackingUrl", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "trackingNumber", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "deliveryStart", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "deliveryEnd", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "estimatedDeliveryWindow", "storageKey": null }, (v3/*: any*/) ], "storageKey": null }, { "alias": null, "args": (v2/*: any*/), "concreteType": "CommerceFulfillmentConnection", "kind": "LinkedField", "name": "fulfillments", "plural": false, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceFulfillmentEdge", "kind": "LinkedField", "name": "edges", "plural": true, "selections": [ { "alias": null, "args": null, "concreteType": "CommerceFulfillment", "kind": "LinkedField", "name": "node", "plural": false, "selections": [ { "alias": null, "args": null, "kind": "ScalarField", "name": "createdAt", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "trackingId", "storageKey": null }, { "alias": null, "args": null, "kind": "ScalarField", "name": "estimatedDelivery", "storageKey": null }, (v3/*: any*/) ], "storageKey": null } ], "storageKey": null } ], "storageKey": "fulfillments(first:1)" }, (v3/*: any*/) ], "storageKey": null } ], "storageKey": null } ], "storageKey": "lineItems(first:1)" }, (v3/*: any*/) ], "storageKey": "commerceOrder(id:\"some-id\")" } ] }, "params": { "id": "4d73e28aef4cb359d265716253bb0866", "metadata": { "relayTestingSelectionTypeInfo": { "commerceOrder": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceOrder" }, "commerceOrder.__isCommerceOrder": (v4/*: any*/), "commerceOrder.__typename": (v4/*: any*/), "commerceOrder.id": (v5/*: any*/), "commerceOrder.internalID": (v5/*: any*/), "commerceOrder.lineItems": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceLineItemConnection" }, "commerceOrder.lineItems.edges": { "enumValues": null, "nullable": true, "plural": true, "type": "CommerceLineItemEdge" }, "commerceOrder.lineItems.edges.node": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceLineItem" }, "commerceOrder.lineItems.edges.node.fulfillments": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceFulfillmentConnection" }, "commerceOrder.lineItems.edges.node.fulfillments.edges": { "enumValues": null, "nullable": true, "plural": true, "type": "CommerceFulfillmentEdge" }, "commerceOrder.lineItems.edges.node.fulfillments.edges.node": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceFulfillment" }, "commerceOrder.lineItems.edges.node.fulfillments.edges.node.createdAt": (v4/*: any*/), "commerceOrder.lineItems.edges.node.fulfillments.edges.node.estimatedDelivery": (v6/*: any*/), "commerceOrder.lineItems.edges.node.fulfillments.edges.node.id": (v5/*: any*/), "commerceOrder.lineItems.edges.node.fulfillments.edges.node.trackingId": (v6/*: any*/), "commerceOrder.lineItems.edges.node.id": (v5/*: any*/), "commerceOrder.lineItems.edges.node.shipment": { "enumValues": null, "nullable": true, "plural": false, "type": "CommerceShipment" }, "commerceOrder.lineItems.edges.node.shipment.deliveryEnd": (v6/*: any*/), "commerceOrder.lineItems.edges.node.shipment.deliveryStart": (v6/*: any*/), "commerceOrder.lineItems.edges.node.shipment.estimatedDeliveryWindow": (v6/*: any*/), "commerceOrder.lineItems.edges.node.shipment.id": (v5/*: any*/), "commerceOrder.lineItems.edges.node.shipment.status": (v6/*: any*/), "commerceOrder.lineItems.edges.node.shipment.trackingNumber": (v6/*: any*/), "commerceOrder.lineItems.edges.node.shipment.trackingUrl": (v6/*: any*/), "commerceOrder.state": { "enumValues": [ "ABANDONED", "APPROVED", "CANCELED", "FULFILLED", "PENDING", "REFUNDED", "SUBMITTED" ], "nullable": false, "plural": false, "type": "CommerceOrderStateEnum" } } }, "name": "TrackOrderSectionTestsQuery", "operationKind": "query", "text": null } }; })(); (node as any).hash = 'ee9d582dd24c59d3fa11cdfe30c28560'; export default node;
the_stack
namespace ts { interface TestProjectSpecification { configFileName?: string; references?: ReadonlyArray<string | ProjectReference>; files: { [fileName: string]: string }; outputFiles?: { [fileName: string]: string }; config?: object; options?: Partial<CompilerOptions>; } interface TestSpecification { [path: string]: TestProjectSpecification; } function assertHasError(message: string, errors: ReadonlyArray<Diagnostic>, diag: DiagnosticMessage) { if (!errors.some(e => e.code === diag.code)) { const errorString = errors.map(e => ` ${e.file ? e.file.fileName : "[global]"}: ${e.messageText}`).join("\r\n"); assert(false, `${message}: Did not find any diagnostic for ${diag.message} in:\r\n${errorString}`); } } function assertNoErrors(message: string, errors: ReadonlyArray<Diagnostic>) { if (errors && errors.length > 0) { assert(false, `${message}: Expected no errors, but found:\r\n${errors.map(e => ` ${e.messageText}`).join("\r\n")}`); } } function combineAllPaths(...paths: string[]) { let result = paths[0]; for (let i = 1; i < paths.length; i++) { result = combinePaths(result, paths[i]); } return result; } const emptyModule = "export { };"; /** * Produces the text of a source file which imports all of the * specified module names */ function moduleImporting(...names: string[]) { return names.map((n, i) => `import * as mod_${i} from ${n}`).join("\r\n"); } function testProjectReferences(spec: TestSpecification, entryPointConfigFileName: string, checkResult: (prog: Program, host: fakes.CompilerHost) => void) { const files = createMap<string>(); for (const key in spec) { const sp = spec[key]; const configFileName = combineAllPaths("/", key, sp.configFileName || "tsconfig.json"); const options = { compilerOptions: { composite: true, outDir: "bin", ...sp.options }, references: (sp.references || []).map(r => { if (typeof r === "string") { return { path: r }; } return r; }), ...sp.config }; const configContent = JSON.stringify(options); const outDir = options.compilerOptions.outDir; files.set(configFileName, configContent); for (const sourceFile of Object.keys(sp.files)) { files.set(sourceFile, sp.files[sourceFile]); } if (sp.outputFiles) { for (const outFile of Object.keys(sp.outputFiles)) { files.set(combineAllPaths("/", key, outDir, outFile), sp.outputFiles[outFile]); } } } const vfsys = new vfs.FileSystem(false, { files: { "/lib.d.ts": TestFSWithWatch.libFile.content } }); files.forEach((v, k) => { vfsys.mkdirpSync(getDirectoryPath(k)); vfsys.writeFileSync(k, v); }); const host = new fakes.CompilerHost(new fakes.System(vfsys)); const { config, error } = readConfigFile(entryPointConfigFileName, name => host.readFile(name)); // We shouldn't have any errors about invalid tsconfig files in these tests assert(config && !error, flattenDiagnosticMessageText(error && error.messageText, "\n")); const file = parseJsonConfigFileContent(config, parseConfigHostFromCompilerHost(host), getDirectoryPath(entryPointConfigFileName), {}, entryPointConfigFileName); file.options.configFilePath = entryPointConfigFileName; const prog = createProgram({ rootNames: file.fileNames, options: file.options, host, projectReferences: file.projectReferences }); checkResult(prog, host); } describe("project-references meta check", () => { it("default setup was created correctly", () => { const spec: TestSpecification = { "/primary": { files: { "/primary/a.ts": emptyModule }, references: [] }, "/reference": { files: { "/secondary/b.ts": moduleImporting("../primary/a") }, references: ["../primary"] } }; testProjectReferences(spec, "/primary/tsconfig.json", prog => { assert.isTrue(!!prog, "Program should exist"); assertNoErrors("Sanity check should not produce errors", prog.getOptionsDiagnostics()); }); }); }); /** * Validate that we enforce the basic settings constraints for referenced projects */ describe("project-references constraint checking for settings", () => { it("errors when declaration = false", () => { const spec: TestSpecification = { "/primary": { files: { "/primary/a.ts": emptyModule }, references: [], options: { declaration: false } } }; testProjectReferences(spec, "/primary/tsconfig.json", program => { const errs = program.getOptionsDiagnostics(); assertHasError("Reports an error about the wrong decl setting", errs, Diagnostics.Composite_projects_may_not_disable_declaration_emit); }); }); it("errors when the referenced project doesn't have composite:true", () => { const spec: TestSpecification = { "/primary": { files: { "/primary/a.ts": emptyModule }, references: [], options: { composite: false } }, "/reference": { files: { "/secondary/b.ts": moduleImporting("../primary/a") }, references: ["../primary"] } }; testProjectReferences(spec, "/reference/tsconfig.json", program => { const errs = program.getOptionsDiagnostics(); assertHasError("Reports an error about 'composite' not being set", errs, Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true); }); }); it("errors when the file list is not exhaustive", () => { const spec: TestSpecification = { "/primary": { files: { "/primary/a.ts": "import * as b from './b'", "/primary/b.ts": "export {}" }, config: { files: ["a.ts"] } } }; testProjectReferences(spec, "/primary/tsconfig.json", program => { const errs = program.getOptionsDiagnostics(); assertHasError("Reports an error about b.ts not being in the list", errs, Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern); }); }); it("errors when the referenced project doesn't exist", () => { const spec: TestSpecification = { "/primary": { files: { "/primary/a.ts": emptyModule }, references: ["../foo"] } }; testProjectReferences(spec, "/primary/tsconfig.json", program => { const errs = program.getOptionsDiagnostics(); assertHasError("Reports an error about a missing file", errs, Diagnostics.File_0_does_not_exist); }); }); it("errors when a prepended project reference doesn't set outFile", () => { const spec: TestSpecification = { "/primary": { files: { "/primary/a.ts": emptyModule }, references: [{ path: "../someProj", prepend: true }] }, "/someProj": { files: { "/someProj/b.ts": "const x = 100;" } } }; testProjectReferences(spec, "/primary/tsconfig.json", program => { const errs = program.getOptionsDiagnostics(); assertHasError("Reports an error about outFile not being set", errs, Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set); }); }); it("errors when a prepended project reference output doesn't exist", () => { const spec: TestSpecification = { "/primary": { files: { "/primary/a.ts": "const y = x;" }, references: [{ path: "../someProj", prepend: true }] }, "/someProj": { files: { "/someProj/b.ts": "const x = 100;" }, options: { outFile: "foo.js" } } }; testProjectReferences(spec, "/primary/tsconfig.json", program => { const errs = program.getOptionsDiagnostics(); assertHasError("Reports an error about outFile being missing", errs, Diagnostics.Output_file_0_from_project_1_does_not_exist); }); }); }); /** * Path mapping behavior */ describe("project-references path mapping", () => { it("redirects to the output .d.ts file", () => { const spec: TestSpecification = { "/alpha": { files: { "/alpha/a.ts": "export const m: number = 3;" }, references: [], outputFiles: { "a.d.ts": emptyModule } }, "/beta": { files: { "/beta/b.ts": "import { m } from '../alpha/a'" }, references: ["../alpha"] } }; testProjectReferences(spec, "/beta/tsconfig.json", program => { assertNoErrors("File setup should be correct", program.getOptionsDiagnostics()); assertHasError("Found a type error", program.getSemanticDiagnostics(), Diagnostics.Module_0_has_no_exported_member_1); }); }); }); describe("project-references nice-behavior", () => { it("issues a nice error when the input file is missing", () => { const spec: TestSpecification = { "/alpha": { files: { "/alpha/a.ts": "export const m: number = 3;" }, references: [] }, "/beta": { files: { "/beta/b.ts": "import { m } from '../alpha/a'" }, references: ["../alpha"] } }; testProjectReferences(spec, "/beta/tsconfig.json", program => { assertHasError("Issues a useful error", program.getSemanticDiagnostics(), Diagnostics.Output_file_0_has_not_been_built_from_source_file_1); }); }); }); /** * 'composite' behavior */ describe("project-references behavior changes under composite: true", () => { it("doesn't infer the rootDir from source paths", () => { const spec: TestSpecification = { "/alpha": { files: { "/alpha/src/a.ts": "export const m: number = 3;" }, options: { declaration: true, outDir: "bin" }, references: [] } }; testProjectReferences(spec, "/alpha/tsconfig.json", (program, host) => { program.emit(); assert.deepEqual(host.outputs.map(e => e.file).sort(), ["/alpha/bin/src/a.d.ts", "/alpha/bin/src/a.js"]); }); }); }); describe("errors when a file in a composite project occurs outside the root", () => { it("Errors when a file is outside the rootdir", () => { const spec: TestSpecification = { "/alpha": { files: { "/alpha/src/a.ts": "import * from '../../beta/b'", "/beta/b.ts": "export { }" }, options: { declaration: true, outDir: "bin" }, references: [] } }; testProjectReferences(spec, "/alpha/tsconfig.json", (program) => { assertHasError("Issues an error about the rootDir", program.getOptionsDiagnostics(), Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files); assertHasError("Issues an error about the fileList", program.getOptionsDiagnostics(), Diagnostics.File_0_is_not_in_project_file_list_Projects_must_list_all_files_or_use_an_include_pattern); }); }); }); }
the_stack
import * as GeoJSON from "geojson"; // Note: Terraformer module exports namespace so it can be augmented by // terraformer-wkt-parser and potentially others export as namespace Terraformer; // Export Terraformer for AMD require export = Terraformer; declare namespace Terraformer { export interface Envelope { x: number; y: number; w: number; h: number; } export type BBox = number[]; // [number, number, number, number] export type Coordinate = GeoJSON.Position; export type Coordinates = GeoJSON.Position[]; /** * Terraformer Primitives are JavaScript objects that map directly to their GeoJSON couterparts. * Converting a GeoJSON object into a Terraformer Primitive will allow you use convenience methods like * point.within(polygon). * * Every Primitive inherits from the Terraformer.Primitive base class, thus all other Primitives share the * Terraformer.Primitive methods. * * There is a Primitive for every type of GeoJSON object, plus a Circle Primitive which represents a circle as a * polygon. */ export class Primitive<T extends GeoJSON.GeoJsonObject> implements GeoJSON.GeoJsonObject { public type: GeoJSON.GeoJsonTypes; /** * You create a new Terraformer.Primitive object by passing it a valid GeoJSON Object. This will return a * Terraformer.Primitive with the same type as your GeoJSON object. * @param geojson GeoJSON Primitive */ constructor(geojson: T); /** * Converts this GeoJSON object’s coordinates to the web mercator spatial reference. */ public toMercator(): this; /** * Converts this GeoJSON object’s coordinates to geographic coordinates. */ public toGeographic(): this; /** * Returns an object with x, y, w and h suitable for passing to most indexes. */ public envelope(): Envelope; // /** // * Returns the GeoJSON Bounding Box for this primitive. // */ // bbox(): number[]; // Terraformer docs have this function, but conflicts with GeoJSON typescript definitions for // // optional bbox property. /** * Returns the convex hull of this primitive as a Polygon. Will return null if the convex hull cannot be calculated * or a valid Polygon cannot be created. */ public convexHull(): GeoJSON.Polygon | null; /** * Returns true if the passed GeoJSON Geometry object is completely contained inside this primitive. * @param geometry The geometry that potentially is inside of this one. * @returns Returns true if the passed GeoJSON Geometry object is completely contained inside this primitive. */ public contains(geometry: GeoJSON.GeometryObject): boolean; /** * Returns true if the passed GeoJSON Geometry object is completely within this primitive. * @param geometry GeoJSON geometry */ public within(geometry: GeoJSON.GeometryObject): boolean; /** * Returns true if the passed GeoJSON Geometry intersects this primitive. * @param geometry GeoJSON geometry */ public intersects(geometry: GeoJSON.GeometryObject): boolean; } export class Point extends Primitive<GeoJSON.Point> implements GeoJSON.Point { public type: "Point"; public coordinates: GeoJSON.Position; constructor(p: GeoJSON.Point); constructor(x: number, y: number); constructor(xy: GeoJSON.Position); } export class MultiPoint extends Primitive<GeoJSON.MultiPoint> implements GeoJSON.MultiPoint { public type: "MultiPoint"; public coordinates: GeoJSON.Position[]; public forEach: ( point: Point, index: number, coordinates: Coordinates ) => null; constructor(geojsonMP: GeoJSON.MultiPoint); constructor(coordinates: Coordinates); public get(index: number): Point; public addPoint(coordinate: Coordinate): this; public insertPoint(coordinate: Coordinate, index: number): this; public removePoint(index: number): this; public removePoint(coordinate: Coordinate): this; } export class LineString extends Primitive<GeoJSON.LineString> implements GeoJSON.LineString { public type: "LineString"; public coordinates: GeoJSON.Position[]; constructor(geoJson: GeoJSON.LineString); constructor(coordinates: Coordinates); public addVertex(coordinate: Coordinate): this; public insertVertex(coordinate: Coordinate, index: number): this; public removeVertex(index: number): this; } export class MultiLineString extends Primitive<GeoJSON.MultiLineString> implements GeoJSON.MultiLineString { public type: "MultiLineString"; public coordinates: Coordinate[][]; public forEach: ( linestring: LineString, index: number, coordinates: Coordinates ) => null; constructor(geoJson: GeoJSON.MultiLineString); constructor(coordinates: Coordinates[]); public get(index: number): LineString; } export class Polygon extends Primitive<GeoJSON.Polygon> implements GeoJSON.Polygon { public type: "Polygon"; public coordinates: Coordinate[][]; constructor(geoJson: GeoJSON.Polygon); constructor(coordinates: Coordinates[]); public addVertex(coordinate: Coordinate): this; public insertVertex(coordinate: Coordinate, index: number): this; public removeVertex(index: number): this; public close(): this; public hasHoles(): boolean; public holes(): Polygon[]; } export class MultiPolygon extends Primitive<GeoJSON.MultiPolygon> implements GeoJSON.MultiPolygon { public type: "MultiPolygon"; public coordinates: Coordinates[][]; public forEach: ( polygon: Polygon, index: number, coordinates: Coordinates ) => null; constructor(geoJson: GeoJSON.Polygon); constructor(geoJson: GeoJSON.MultiPolygon); constructor(coordinates: Coordinates[]); constructor(coordinates: Coordinates[][]); public get(index: number): Polygon; } export class Feature<T extends GeoJSON.GeometryObject> implements GeoJSON.Feature<T> { public type: "Feature"; public geometry: T; public properties: any; constructor(geometry: T); constructor(geoJson: GeoJSON.Feature<T>); } export class FeatureCollection<T extends GeoJSON.GeometryObject> implements GeoJSON.FeatureCollection<T> { public type: "FeatureCollection"; public features: Array<GeoJSON.Feature<T>>; public forEach: ( feature: Feature<T>, index: number, coordinates: Coordinates ) => null; constructor(geoJson: GeoJSON.FeatureCollection<T>); constructor(features: Array<GeoJSON.Feature<T>>); public get(index: number): Feature<T>; } export class GeometryCollection implements GeoJSON.GeometryCollection { public type: "GeometryCollection"; public geometries: GeoJSON.GeometryObject[]; public forEach: ( geometry: GeoJSON.GeometryObject, index: number, coordinates: Coordinates ) => null; constructor(geoJson: GeoJSON.GeometryCollection); constructor(geoJson: GeoJSON.FeatureCollection<GeoJSON.GeometryObject>); constructor(features: GeoJSON.GeometryObject[]); public get(index: number): Primitive<GeoJSON.GeometryObject>; } /** * The GeoJSON spec does not provide a way to visualize circles. * Terraformer.Circle is actual a GeoJSON Feature object that contains a Polygon representing a circle with a certain number of sides. * @example * circle = new Terraformer.Circle([-122.27, 45.65], 500, 64); * * circle.contains(point); */ export class Circle extends Primitive<GeoJSON.Feature<GeoJSON.Polygon>> implements GeoJSON.Feature<GeoJSON.Polygon> { public type: "Feature"; public geometry: GeoJSON.Polygon; public properties: any; public steps: (steps?: number) => number; /** * Returns the radius circle. If the radius parameter is passed the circle will be recalculated witht he new radius before returning. */ public radius: (radius?: number) => number; /** * Returns the center of the circle. If the center parameter is passed the circle will be recalculated with the new center before returning. */ public center: (center?: Coordinate) => Coordinates; /** * Terraformer.Circle is created with a center, radius, and steps. * @param [center=null] Required A GeoJSON Coordinate in [x,y] format. * @param [radius=250] The radius of the circle in meters. * @param [steps=32] How many steps will be used to create the polygon that represents the circle. */ constructor(center: Coordinate, radius?: number, steps?: number); /** * Recalculates the circle */ public recalculate(): this; /** * Returns the number of steps to produce the polygon representing the circle. If the steps parameter is passed the circle will be recalculated witht he new step count before returning. */ } /** * Terraformer also has numerous helper methods for working with GeoJSON and geographic data. * These tools work with a mix of lower level GeoJSON constructs like Coordinates, * Coordinate Arrays and GeoJSON objects and Terraformer Primitives */ export class Tools { // Spatial Reference Conversions /** * Converts this GeoJSON object’s coordinates to the web mercator spatial reference. This is an in-place modification of the passed object. * @param geojson GeoJSON object */ public static toMercator( geojson: GeoJSON.GeoJsonObject ): GeoJSON.GeoJsonObject; /** * Converts this GeoJSON object’s coordinates to geographic coordinates. This is an in-place modification of the passed object. * @param geojson GeoJSON object */ public static toGeographic( geojson: GeoJSON.GeoJsonObject ): GeoJSON.GeoJsonObject; /** * Runs the passed function against every Coordinate in the geojson object. Your function will be passed a Coordinate and will be expected to return a Coordinate. * @param geojson GeoJSON object * @param converter Function to convert one coordinate to a different coordinate. */ public static applyConverter( geojson: GeoJSON.GeoJsonObject, converter: (coordinate: Coordinate) => Coordinate ): GeoJSON.GeoJsonObject; /** * Converts the passed Coordinate to web mercator spatial reference. * @param coordinate Coordinate */ public static positionToMercator(coordinate: Coordinate): Coordinate; /** * Converts the passed Coordinate to geographic coordinates. * @param coordinate Coordinate to convert */ public static positionToGeographic(coordinate: Coordinate): Coordinate; // Calculations /** * Returns a GeoJSON bounding box for the passed geoJSON. * @param geojson */ public static calculateBounds(geojson: GeoJSON.GeoJsonObject): BBox; /** * Returns an object with x, y, w, h. Suitable for passing to most indexes. * @param geojson */ public static calculateEnvelope(geojson: GeoJSON.GeoJsonObject): Envelope; /** * Returns an array of coordinates representing the convex hull the the passed geoJSON. * @param geojson */ public static convexHull(geojson: Coordinates): Coordinates; // Comparisons /** * Accepts an array of coordinates and a coordinate and returns true if the point falls within the coordinate array. * @param coordinates Array of coordinates * @param coordinate Coordinate that will be searched for in the array. */ public static coordinatesContainPoint( coordinates: Coordinates, coordinate: Coordinate ): Boolean; /** * Accepts the geometry of a polygon and a coordinate and returns true if the point falls within the polygon. * @param polygon * @param coordinate */ public static polygonContainsPoint( polygon: GeoJSON.Polygon, coordinate: Coordinate ): Boolean; /** * Accepts the geometry of a polygon and a coordinate and returns true if the point falls within the polygon. * @param polygon * @param coordinate */ public static polygonContainsPoint( polygon: GeoJSON.Position[][], coordinate: Coordinate ): Boolean; /** * Accepts two arrays of coordinates and returns true if they cross each other at any point. * @param c1 * @param c2 * @example * var pt = [0,0]; * var pt2 = [-111.873779, 40.647303]; * * var polygon = { * "type": "Polygon", * "coordinates": [[ * [-112.074279, 40.52215], * [-112.074279, 40.853293], * [-111.610107, 40.853293], * [-111.610107, 40.52215], * [-112.074279, 40.52215] * ]] * }; * * var polygonGeometry = polygon.coordinates; * * Terraformer.Tools.polygonContainsPoint(polygonGeometry, pt); * // returns false * Terraformer.Tools.polygonContainsPoint(polygonGeometry, pt2); * // returns true */ public static arrayIntersectsArray( c1: Coordinates[], c2: Coordinates[] ): Boolean; /** * Accepts two individual coordinate pairs and returns true if the passed coordinate pairs are equal to each other. * @param c1 * @param c2 */ public static coordinatesEqual(c1: Coordinate, c2: Coordinate): Boolean; } }
the_stack
import { actions$, configureStore, createFeatureStore } from '../store'; import StoreCore from '../store-core'; import { Action, Reducer, StoreExtension } from '../models'; import { createFeatureSelector, createSelector } from '../selector'; import { Observable, of } from 'rxjs'; import { ofType } from '../utils'; import { catchError, map, mapTo, mergeMap, take, withLatestFrom } from 'rxjs/operators'; import { ReduxDevtoolsExtension } from '../extensions/redux-devtools.extension'; import { cold, hot } from 'jest-marbles'; import { FeatureStore } from '../feature-store'; import { counterInitialState, counterReducer, CounterState, resetStoreConfig, store, } from './_spec-helpers'; import { LoggerExtension } from '../extensions/logger.extension'; const asyncUser: Partial<UserState> = { firstName: 'Steven', lastName: 'Seagal', age: 30, }; const updatedAsyncUser: Partial<UserState> = { firstName: 'Steven', lastName: 'Seagal', age: 31, }; function fakeApiGet(): Observable<UserState> { return cold('---a', { a: asyncUser }); } function fakeApiUpdate(): Observable<UserState> { return cold('-a', { a: updatedAsyncUser }); } function fakeApiWithError(): Observable<UserState> { return cold('-#'); } interface UserState { firstName: string; lastName: string; age: number; err: string; } const userInitialState: UserState = { firstName: 'Bruce', lastName: 'Willis', age: 30, err: undefined, }; function userReducer(state: UserState = userInitialState, action: Action): UserState { switch (action.type) { case 'updateUser': case 'loadUserSuccess': case 'saveUserSuccess': return { ...state, ...action.payload, }; case 'resetUser': return userInitialState; case 'incAge': return { ...state, age: state.age + 1, }; case 'error': return { ...state, err: action.payload, }; default: return state; } } const getUserFeatureState = createFeatureSelector<UserState>('user'); const getFirstName = createSelector(getUserFeatureState, (user) => user.firstName); const getAge = createSelector(getUserFeatureState, (user) => user.age); const getCounterFeatureState = createFeatureSelector<CounterState>('counter'); const getCounter1 = createSelector(getCounterFeatureState, (state) => state.counter); const getCounter2FeatureState = createFeatureSelector<CounterState>('counter2'); const getCounter2 = createSelector(getCounter2FeatureState, (state) => state.counter); class CounterFeatureState extends FeatureStore<CounterState> { constructor() { super('counter3', counterInitialState); } increment() { this.setState((state) => ({ counter: state.counter + 1 })); } } const getCounter3FeatureState = createFeatureSelector<CounterState>('counter3'); const getCounter3 = createSelector(getCounter3FeatureState, (state) => state.counter); describe('Store Config', () => { afterEach(() => { resetStoreConfig(); }); it('should initialize the store with an empty object', () => { const spy = jest.fn(); store.select((state) => state).subscribe(spy); expect(spy).toHaveBeenCalledWith({}); expect(spy).toHaveBeenCalledTimes(1); }); it('should initialize the store with an empty object when root reducers have no initial state', () => { StoreCore.config({ reducers: { test: (state) => { return state; }, }, }); const spy = jest.fn(); store.select((state) => state).subscribe(spy); expect(spy).toHaveBeenCalledWith({}); expect(spy).toHaveBeenCalledTimes(1); }); it('should initialize a Feature state with a root reducer', () => { StoreCore.config({ reducers: { user: userReducer }, }); const spy = jest.fn(); store.select((state) => state).subscribe(spy); expect(spy).toHaveBeenCalledWith({ user: userInitialState, }); }); it('should initialize the store with root initial state', () => { const rootInitialState = { user: { name: 'Nicolas' }, }; StoreCore.config({ initialState: rootInitialState, reducers: { user: userReducer, user2: userReducer, }, }); const spy = jest.fn(); store.select((state) => state).subscribe(spy); expect(spy).toHaveBeenCalledWith({ user: { name: 'Nicolas' }, // userReducer initial state is overwritten by the root initial state user2: userInitialState, // Root initial state does not affect User2 initial state }); }); it('should throw when calling Store.config after a Feature Store was initialized', () => { createFeatureStore('tooEarlyInstantiatedFeatureStore', {}); expect(() => StoreCore.config({})).toThrowError( '`configureStore` detected reducers. Did you instantiate FeatureStores before calling `configureStore`?' ); }); describe('Root Meta Reducers', () => { const nextStateSpy = jest.fn(); it('should call root meta reducer with root initial state', () => { const rootMetaReducerSpy = jest.fn(); const rootInitialState = { user: {}, }; function rootMetaReducer1(reducer) { return (state, action) => { rootMetaReducerSpy(state); return reducer(state, action); }; } StoreCore.config({ metaReducers: [rootMetaReducer1], initialState: rootInitialState, }); expect(rootMetaReducerSpy).toHaveBeenCalledWith(rootInitialState); }); it('should call root meta reducers from left to right', () => { const callOrder = []; function rootMetaReducer1(reducer) { return (state, action) => { callOrder.push('meta1'); return reducer(state, action); }; } function rootMetaReducer2(reducer) { return (state, action) => { callOrder.push('meta2'); return reducer(state, action); }; } StoreCore.config({ metaReducers: [rootMetaReducer1, rootMetaReducer2], }); expect(callOrder).toEqual(['meta1', 'meta2']); }); it('should call root meta reducers from extensions depending on sortOrder', () => { const callOrder = []; function rootMetaReducerForExtension(reducer) { return (state, action) => { callOrder.push('meta1'); return reducer(state, action); }; } class Extension extends StoreExtension { init(): void { StoreCore.addMetaReducers(rootMetaReducerForExtension); } } function rootMetaReducerForExtension2(reducer) { return (state, action) => { callOrder.push('meta2'); return reducer(state, action); }; } class Extension2 extends StoreExtension { sortOrder = 100; init(): void { StoreCore.addMetaReducers(rootMetaReducerForExtension2); } } function rootMetaReducerForExtension3(reducer) { return (state, action) => { callOrder.push('meta3'); return reducer(state, action); }; } class Extension3 extends StoreExtension { init(): void { StoreCore.addMetaReducers(rootMetaReducerForExtension3); } } StoreCore.config({ extensions: [new Extension(), new Extension2(), new Extension3()], }); expect(callOrder).toEqual(['meta1', 'meta3', 'meta2']); }); it( 'should run reducers in order: ' + '1.) root meta reducers ' + '2.) root meta reducers from extensions' + '3.) feature meta reducers, ' + '4.) feature reducer', () => { function rootMetaReducerForExtension(reducer: Reducer<any>): Reducer<any> { return (state, action) => { if (action.type === 'metaTest') { state = { ...state, metaTestFeature: state.metaTestFeature + 'x', }; } return reducer(state, action); }; } class Extension extends StoreExtension { init(): void { StoreCore.addMetaReducers(rootMetaReducerForExtension); } } function aFeatureReducer(state: string = 'a', action: Action): string { switch (action.type) { case 'metaTest': return state + 'e'; default: return state; } } function rootMetaReducer1(reducer: Reducer<any>): Reducer<any> { return (state, action) => { if (action.type === 'metaTest') { state = { ...state, metaTestFeature: state.metaTestFeature + 'b', }; } return reducer(state, action); }; } function rootMetaReducer2(reducer: Reducer<any>): Reducer<any> { return (state, action) => { if (action.type === 'metaTest') { state = { ...state, metaTestFeature: state.metaTestFeature + 'c', }; } return reducer(state, action); }; } function inTheMiddleRootMetaReducer(reducer) { return (state, action) => { const nextState = reducer(state, action); nextStateSpy(nextState); return reducer(state, action); }; } function featureMetaReducer(reducer: Reducer<string>): Reducer<string> { return (state, action) => { if (action.type === 'metaTest') { state = state + 'd'; } return reducer(state, action); }; } const getMetaTestFeature = createFeatureSelector<string>('metaTestFeature'); StoreCore.config({ metaReducers: [rootMetaReducer1, inTheMiddleRootMetaReducer, rootMetaReducer2], extensions: [new Extension()], }); StoreCore.addFeature<string>('metaTestFeature', aFeatureReducer, { metaReducers: [featureMetaReducer], }); const spy = jest.fn(); StoreCore.select(getMetaTestFeature).subscribe(spy); StoreCore.dispatch({ type: 'metaTest' }); expect(spy).toHaveBeenCalledWith('abcxde'); } ); it('should calculate nextState also if nextState is calculated by a metaReducer in the "middle"', () => { expect(nextStateSpy).toHaveBeenCalledWith( expect.objectContaining({ metaTestFeature: 'a' }) ); expect(nextStateSpy).toHaveBeenCalledWith( expect.objectContaining({ metaTestFeature: 'abcxde' }) ); }); }); }); describe('Store', () => { beforeAll(() => { resetStoreConfig(); StoreCore.config({ reducers: { user: userReducer }, }); }); it('should run the redux reducers when a new Feature state is added', () => { const reducerSpy = jest.fn(); function someReducer() { reducerSpy(); } store.feature('oneMoreFeature', someReducer); store.feature('oneMoreFeature2', (state) => state); expect(reducerSpy).toHaveBeenCalledTimes(2); }); it('should throw when reusing feature name', () => { expect(() => store.feature<UserState>('oneMoreFeature', userReducer)).toThrowError(); }); it('should update the Feature state', () => { const user = { firstName: 'Nicolas', lastName: 'Cage', }; store.dispatch({ type: 'updateUser', payload: user, }); const spy = jest.fn(); store.select(getFirstName).subscribe(spy); expect(spy).toHaveBeenCalledWith(user.firstName); expect(spy).toHaveBeenCalledTimes(1); }); it('should update the Feature state #1', () => { const age$ = store.select(getAge); hot('-a-b').subscribe(() => store.dispatch({ type: 'incAge' })); expect(age$).toBeObservable(hot('ab-c', { a: 30, b: 31, c: 32 })); }); it('should update the Feature state #2', () => { const age$ = store.select(getAge); hot('(ab)').subscribe(() => store.dispatch({ type: 'incAge' })); expect(age$).toBeObservable(hot('(abc)', { a: 32, b: 33, c: 34 })); }); it('should return undefined if feature does not exist yet', () => { const featureSelector = createFeatureSelector('notExistingFeature'); const spy = jest.fn(); store.select(featureSelector).subscribe(spy); expect(spy).toHaveBeenCalledWith(undefined); expect(spy).toHaveBeenCalledTimes(1); }); it('should create and execute an effect', () => { store.dispatch({ type: 'resetUser' }); store.effect( actions$.pipe( ofType('loadUser'), mergeMap(() => fakeApiGet().pipe( map((user) => ({ type: 'loadUserSuccess', payload: user, })) ) ) ) ); store.dispatch({ type: 'loadUser' }); // Lets be crazy and add another effect while the other effect is busy cold('-a').subscribe(() => { store.effect( actions$.pipe( ofType('saveUser'), mergeMap(() => fakeApiUpdate().pipe( map((user) => ({ type: 'saveUserSuccess', payload: user, })) ) ) ) ); store.dispatch({ type: 'saveUser' }); }); expect(store.select(getUserFeatureState)).toBeObservable( hot('a-xb', { a: userInitialState, b: asyncUser, x: updatedAsyncUser }) ); }); it('should create and execute an effect and handle side effect error', () => { store.dispatch({ type: 'resetUser' }); store.effect( actions$.pipe( ofType('someAction'), mergeMap(() => fakeApiWithError().pipe( map(() => ({ type: 'whatever', })), catchError(() => of({ type: 'error', payload: 'error' })) ) ) ) ); store.dispatch({ type: 'someAction' }); expect(store.select(getUserFeatureState)).toBeObservable( hot('ab', { a: userInitialState, b: { ...userInitialState, err: 'error' } }) ); }); it('should log', () => { console.log = jest.fn(); const user: UserState = { firstName: 'John', lastName: 'Travolta', age: 35, err: undefined, }; const newState = { user, }; const action: Action = { type: 'updateUser', payload: user, }; StoreCore.addExtension(new LoggerExtension()); store.dispatch(action); expect(console.log).toHaveBeenCalledWith( expect.stringContaining('%cupdateUser'), expect.stringContaining('color: #25c2a0'), expect.stringContaining('Action:'), action, expect.stringContaining('State: '), newState ); }); it('should add extension', () => { const spy = jest.spyOn(StoreCore, 'addExtension'); StoreCore.addExtension(new ReduxDevtoolsExtension({})); expect(spy).toHaveBeenCalledTimes(1); expect(StoreCore['extensions'].length).toBe(2); }); it('should call the reducer before running the effect', () => { const callOrder = []; const someReducer = (state = { value: 0 }, action: Action) => { switch (action.type) { case 'someAction2': callOrder.push('reducer'); return { ...state, value: state.value + 1, }; default: return state; } }; const onEffectStarted = (): Observable<Action> => { callOrder.push('effect'); return of({ type: 'whatever' }); }; const valueSpy = jest.fn(); store.feature('someFeature', someReducer); store.effect( actions$.pipe( ofType('someAction2'), withLatestFrom(store.select((state) => state.someFeature.value)), mergeMap(([, value]) => { valueSpy(value); return onEffectStarted(); }) ) ); store.dispatch({ type: 'someAction2' }); expect(callOrder).toEqual(['reducer', 'effect']); expect(valueSpy).toHaveBeenCalledWith(1); // Effect can select the updated state immediately }); it('should queue actions', () => { const callLimit = 5000; store.feature<CounterState>('counter', counterReducer); const spy = jest.fn().mockImplementation(() => { store.dispatch({ type: 'counter' }); }); const counter1$ = store.select(getCounter1); counter1$.pipe(take(callLimit)).subscribe(spy); expect(spy).toHaveBeenCalledTimes(callLimit); expect(spy).toHaveBeenNthCalledWith(callLimit, callLimit); }); it('should queue effect actions', () => { const callLimit = 5000; function counter2Reducer(state: CounterState = counterInitialState, action: Action) { switch (action.type) { case 'counterEffectSuccess': return { ...state, counter: state.counter + 1, }; default: return state; } } store.feature<CounterState>('counter2', counter2Reducer); store.effect( actions$.pipe( ofType('counterEffectStart'), mergeMap(() => of({ type: 'counterEffectSuccess' })) ) ); const spy2 = jest.fn().mockImplementation(() => { store.dispatch({ type: 'counterEffectStart' }); }); const counter2$ = store.select(getCounter2); counter2$.pipe(take(callLimit)).subscribe(spy2); expect(spy2).toHaveBeenCalledTimes(callLimit); expect(spy2).toHaveBeenNthCalledWith(callLimit, callLimit); }); it('should select state from a Feature (which was created with `extends Feature)', () => { const counterFeatureState = new CounterFeatureState(); counterFeatureState.increment(); const spy = jest.fn(); store.select(getCounter3).subscribe(spy); expect(spy).toHaveBeenCalledWith(2); expect(spy).toHaveBeenCalledTimes(1); }); it('should overwrite reducers default state with a provided initialState', () => { const featureKey = 'counterWithCustomInitialState'; const customInitialState: CounterState = { counter: 2, }; store.feature<CounterState>(featureKey, counterReducer, { initialState: customInitialState, }); const spy = jest.fn(); store.select((state) => state[featureKey]).subscribe(spy); expect(spy).toHaveBeenCalledWith(customInitialState); }); it('should resubscribe the effect 10 times (if side effect error is not handled)', () => { const spy = jest.fn(); console.error = jest.fn(); function apiCallWithError() { spy(); throw new Error(); return of('someValue'); } store.effect( actions$.pipe( ofType('someAction3'), mergeMap(() => { return apiCallWithError().pipe(mapTo({ type: 'someActionSuccess' })); }) ) ); store.dispatch({ type: 'someAction3' }); store.dispatch({ type: 'someAction3' }); store.dispatch({ type: 'someAction3' }); store.dispatch({ type: 'someAction3' }); store.dispatch({ type: 'someAction3' }); store.dispatch({ type: 'someAction3' }); store.dispatch({ type: 'someAction3' }); store.dispatch({ type: 'someAction3' }); store.dispatch({ type: 'someAction3' }); store.dispatch({ type: 'someAction3' }); store.dispatch({ type: 'someAction3' }); store.dispatch({ type: 'someAction3' }); // #12 will not trigger the Api call anymore store.dispatch({ type: 'someAction3' }); // #13 will not trigger the Api call anymore expect(spy).toHaveBeenCalledTimes(11); // Api call is performed 11 Times. First time + 10 re-subscriptions function getErrorMsg(times) { return `MiniRx resubscribed the Effect. ONLY ${times} time(s) remaining!`; } expect(console.error).toHaveBeenCalledWith( expect.stringContaining(getErrorMsg(9)), expect.any(Error) ); expect(console.error).toHaveBeenCalledWith( expect.stringContaining(getErrorMsg(8)), expect.any(Error) ); expect(console.error).toHaveBeenCalledWith( expect.stringContaining(getErrorMsg(7)), expect.any(Error) ); expect(console.error).toHaveBeenCalledWith( expect.stringContaining(getErrorMsg(6)), expect.any(Error) ); expect(console.error).toHaveBeenCalledWith( expect.stringContaining(getErrorMsg(5)), expect.any(Error) ); expect(console.error).toHaveBeenCalledWith( expect.stringContaining(getErrorMsg(4)), expect.any(Error) ); expect(console.error).toHaveBeenCalledWith( expect.stringContaining(getErrorMsg(3)), expect.any(Error) ); expect(console.error).toHaveBeenCalledWith( expect.stringContaining(getErrorMsg(2)), expect.any(Error) ); expect(console.error).toHaveBeenCalledWith( expect.stringContaining(getErrorMsg(1)), expect.any(Error) ); expect(console.error).toHaveBeenCalledWith( expect.stringContaining(getErrorMsg(0)), expect.any(Error) ); expect(console.error).toHaveBeenCalledTimes(10); // Re-subscription with error logging stopped after 10 times }); it('should throw when creating store again with functional creation method', () => { expect(() => configureStore({})).toThrow(); }); it('should not emit a new AppState when dispatching unknown Actions', () => { const spy = jest.fn(); store.select((state) => state).subscribe(spy); expect(spy).toHaveBeenCalledTimes(1); spy.mockReset(); store.dispatch({ type: 'unknownAction' }); expect(spy).toHaveBeenCalledTimes(0); }); it('should add and remove reducers', () => { const featureKey = 'tempCounter'; const spy = jest.fn(); StoreCore.addFeature<CounterState>(featureKey, counterReducer); store.select((state) => state).subscribe(spy); expect(spy).toHaveBeenCalledWith( expect.objectContaining({ tempCounter: counterInitialState }) ); StoreCore.removeFeature(featureKey); expect(spy).toHaveBeenCalledWith( expect.not.objectContaining({ tempCounter: counterInitialState }) ); }); }); describe('Store Feature MetaReducers', () => { const getMetaTestFeature = createFeatureSelector<CounterStringState>('metaTestFeature2'); const getCount = createSelector(getMetaTestFeature, (state) => state.count); interface CounterStringState { count: string; } function aFeatureReducer( state: CounterStringState = { count: '0' }, action: Action ): CounterStringState { switch (action.type) { case 'metaTest2': return { ...state, count: state.count + '3', }; default: return state; } } function featureMetaReducer1(reducer): Reducer<CounterStringState> { return (state, action: Action) => { if (action.type === 'metaTest2') { state = { ...state, count: state.count + '1', }; } return reducer(state, action); }; } function featureMetaReducer2(reducer): Reducer<CounterStringState> { return (state, action: Action) => { if (action.type === 'metaTest2') { state = { ...state, count: state.count + '2', }; } return reducer(state, action); }; } const nextStateSpy = jest.fn(); function inTheMiddleMetaReducer(reducer) { return (state, action) => { const nextState = reducer(state, action); nextStateSpy(nextState); return reducer(state, action); }; } it('should run meta reducers first, then the normal reducer', () => { StoreCore.addFeature<CounterStringState>('metaTestFeature2', aFeatureReducer, { metaReducers: [featureMetaReducer1, inTheMiddleMetaReducer, featureMetaReducer2], }); const spy = jest.fn(); StoreCore.select(getCount).subscribe(spy); StoreCore.dispatch({ type: 'metaTest2' }); expect(spy).toHaveBeenCalledWith('0'); expect(spy).toHaveBeenCalledWith('0123'); }); it('should calculate nextState also if nextState is calculated by a metaReducer in the "middle"', () => { expect(nextStateSpy).toHaveBeenCalledWith({ count: '0' }); expect(nextStateSpy).toHaveBeenCalledWith({ count: '0123' }); expect(nextStateSpy).toHaveBeenCalledTimes(2); }); });
the_stack
import { test } from '@japa/runner' import { ApplicationContract } from '@ioc:Adonis/Core/Application' import { Connection } from '../../src/Connection' import { QueryClient } from '../../src/QueryClient' import { TransactionClient } from '../../src/TransactionClient' import { fs, setup, cleanup, getConfig, resetTables, setupApplication } from '../../test-helpers' let app: ApplicationContract test.group('Transaction | query', (group) => { group.setup(async () => { app = await setupApplication() await setup() }) group.teardown(async () => { await cleanup() await fs.cleanup() }) group.each.teardown(async () => { await resetTables() }) test('perform select query under a transaction', async ({ assert }) => { const connection = new Connection('primary', getConfig(), app.logger) connection.connect() const db = await new QueryClient( 'dual', connection, app.container.use('Adonis/Core/Event') ).transaction() const results = await db.query().from('users') await db.commit() assert.isArray(results) assert.lengthOf(results, 0) await connection.disconnect() }) test('commit insert', async ({ assert }) => { const connection = new Connection('primary', getConfig(), app.logger) connection.connect() const db = await new QueryClient( 'dual', connection, app.container.use('Adonis/Core/Event') ).transaction() await db.insertQuery().table('users').insert({ username: 'virk' }) await db.commit() const results = await new QueryClient( 'dual', connection, app.container.use('Adonis/Core/Event') ) .query() .from('users') assert.isArray(results) assert.lengthOf(results, 1) assert.equal(results[0].username, 'virk') await connection.disconnect() }) test('rollback insert', async ({ assert }) => { const connection = new Connection('primary', getConfig(), app.logger) connection.connect() const db = await new QueryClient( 'dual', connection, app.container.use('Adonis/Core/Event') ).transaction() await db.insertQuery().table('users').insert({ username: 'virk' }) await db.rollback() const results = await new QueryClient( 'dual', connection, app.container.use('Adonis/Core/Event') ) .query() .from('users') assert.isArray(results) assert.lengthOf(results, 0) await connection.disconnect() }) test('perform nested transactions with save points', async ({ assert }) => { const connection = new Connection('primary', getConfig(), app.logger) connection.connect() /** * Transaction 1 */ const db = await new QueryClient( 'dual', connection, app.container.use('Adonis/Core/Event') ).transaction() await db.insertQuery().table('users').insert({ username: 'virk' }) /** * Transaction 2: Save point */ const db1 = await db.transaction() await db1.insertQuery().table('users').insert({ username: 'nikk' }) /** * Rollback 2 */ await db1.rollback() /** * Commit first */ await db.commit() const results = await new QueryClient( 'dual', connection, app.container.use('Adonis/Core/Event') ) .query() .from('users') assert.isArray(results) assert.lengthOf(results, 1) assert.equal(results[0].username, 'virk') await connection.disconnect() }) test('emit after commit event', async ({ assert }) => { const stack: string[] = [] const connection = new Connection('primary', getConfig(), app.logger) connection.connect() const db = await new QueryClient( 'dual', connection, app.container.use('Adonis/Core/Event') ).transaction() db.on('commit', (trx) => { stack.push('commit') assert.instanceOf(trx, TransactionClient) }) await db.insertQuery().table('users').insert({ username: 'virk' }) await db.commit() assert.deepEqual(db.listenerCount('commit'), 0) assert.deepEqual(db.listenerCount('rollback'), 0) assert.deepEqual(stack, ['commit']) await connection.disconnect() }) test('emit after rollback event', async ({ assert }) => { const stack: string[] = [] const connection = new Connection('primary', getConfig(), app.logger) connection.connect() const db = await new QueryClient( 'dual', connection, app.container.use('Adonis/Core/Event') ).transaction() db.on('rollback', (trx) => { stack.push('rollback') assert.instanceOf(trx, TransactionClient) }) await db.insertQuery().table('users').insert({ username: 'virk' }) await db.rollback() assert.deepEqual(db.listenerCount('commit'), 0) assert.deepEqual(db.listenerCount('rollback'), 0) assert.deepEqual(stack, ['rollback']) await connection.disconnect() }) test('commit insert inside a self managed transaction', async ({ assert }) => { const connection = new Connection('primary', getConfig(), app.logger) connection.connect() await new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')).transaction( async (db) => { await db.insertQuery().table('users').insert({ username: 'virk' }) } ) const results = await new QueryClient( 'dual', connection, app.container.use('Adonis/Core/Event') ) .query() .from('users') assert.isArray(results) assert.lengthOf(results, 1) assert.equal(results[0].username, 'virk') await connection.disconnect() }) test('rollback insert inside a self managed transaction', async ({ assert }) => { assert.plan(3) const connection = new Connection('primary', getConfig(), app.logger) connection.connect() try { await new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')).transaction( async (db) => { await db.insertQuery().table('users').insert({ username: 'virk' }) throw new Error('should rollback') } ) } catch (error) { assert.equal(error.message, 'should rollback') } const results = await new QueryClient( 'dual', connection, app.container.use('Adonis/Core/Event') ) .query() .from('users') assert.isArray(results) assert.lengthOf(results, 0) await connection.disconnect() }) test('perform nested managed transactions', async ({ assert }) => { const connection = new Connection('primary', getConfig(), app.logger) connection.connect() /** * Transaction 1 */ await new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')).transaction( async (db) => { await db.insertQuery().table('users').insert({ username: 'virk' }) /** * Transaction 2: Save point */ await db.transaction(async (db1) => { await db1.insertQuery().table('users').insert({ username: 'nikk' }) /** * Manual callback, should work fine */ await db1.rollback() }) } ) const results = await new QueryClient( 'dual', connection, app.container.use('Adonis/Core/Event') ) .query() .from('users') assert.isArray(results) assert.lengthOf(results, 1) assert.equal(results[0].username, 'virk') await connection.disconnect() }) test('nest transaction queries inside profiler row', async ({ assert }) => { const stack: { id: string; parentId: string | undefined; label: string; data: any }[] = [] const connection = new Connection('primary', getConfig(), app.logger) connection.connect() const profiler = app.profiler const client = new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')) client.profiler = profiler profiler.process((log) => { stack.push({ id: log['id'], parentId: log.parent_id, label: log.label, data: log.data }) }) const db = await client.transaction() await db.insertQuery().table('users').insert({ username: 'virk' }) await db.commit() assert.lengthOf(stack, 2) assert.equal(stack[0].label, 'db:query') assert.equal(stack[1].label, 'trx:begin') assert.equal(stack[0].parentId, stack[1].id) assert.deepEqual(stack[1].data, { state: 'commit' }) await connection.disconnect() }) test('nest save points queries inside profiler row', async ({ assert }) => { const stack: { id: string; parentId: string | undefined; label: string; data: any }[] = [] const connection = new Connection('primary', getConfig(), app.logger) connection.connect() const profiler = app.profiler const client = new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')) client.profiler = profiler profiler.process((log) => { stack.push({ id: log['id'], parentId: log.parent_id, label: log.label, data: log.data }) }) const db = await client.transaction() const nested = await db.transaction() await nested.insertQuery().table('users').insert({ username: 'virk' }) await nested.rollback() await db.commit() assert.lengthOf(stack, 3) assert.equal(stack[0].label, 'db:query') assert.equal(stack[1].label, 'trx:begin') assert.equal(stack[2].label, 'trx:begin') assert.equal(stack[0].parentId, stack[1].id) assert.deepEqual(stack[1].data, { state: 'rollback' }) assert.deepEqual(stack[2].data, { state: 'commit' }) assert.equal(stack[1].parentId, stack[2].id) await connection.disconnect() }) test('nest transaction queries inside managed transaction', async ({ assert }) => { const stack: { id: string; parentId: string | undefined; label: string; data: any }[] = [] const connection = new Connection('primary', getConfig(), app.logger) connection.connect() const profiler = app.profiler const client = new QueryClient('dual', connection, app.container.use('Adonis/Core/Event')) client.profiler = profiler profiler.process((log) => { stack.push({ id: log['id'], parentId: log.parent_id, label: log.label, data: log.data }) }) await client.transaction(async (db) => { await db.insertQuery().table('users').insert({ username: 'virk' }) }) assert.lengthOf(stack, 2) assert.equal(stack[0].label, 'db:query') assert.equal(stack[1].label, 'trx:begin') assert.equal(stack[0].parentId, stack[1].id) assert.deepEqual(stack[1].data, { state: 'commit' }) await connection.disconnect() }) test('execute after commit hook', async ({ assert }) => { const stack: string[] = [] const connection = new Connection('primary', getConfig(), app.logger) connection.connect() const db = await new QueryClient( 'dual', connection, app.container.use('Adonis/Core/Event') ).transaction() db.after('commit', async () => { stack.push('commit') }) await db.insertQuery().table('users').insert({ username: 'virk' }) await db.commit() assert.deepEqual(stack, ['commit']) await connection.disconnect() }) test('execute after rollback hook', async ({ assert }) => { const stack: string[] = [] const connection = new Connection('primary', getConfig(), app.logger) connection.connect() const db = await new QueryClient( 'dual', connection, app.container.use('Adonis/Core/Event') ).transaction() db.after('rollback', async () => { stack.push('rollback') }) await db.insertQuery().table('users').insert({ username: 'virk' }) await db.rollback() assert.deepEqual(db.listenerCount('commit'), 0) assert.deepEqual(db.listenerCount('rollback'), 0) assert.deepEqual(stack, ['rollback']) await connection.disconnect() }) })
the_stack
import { TestBed } from '@angular/core/testing'; import { ParamChangeObjectFactory } from 'domain/exploration/ParamChangeObjectFactory'; import { StateObjectFactory } from 'domain/state/StateObjectFactory'; import { EventEmitter } from '@angular/core'; // TODO(#7222): Remove usage of importAllAngularServices once upgraded to // Angular 8. import { importAllAngularServices } from 'tests/unit-test-utils.ajs'; describe('Preview Tab Component', function() { importAllAngularServices(); var ctrl = null; var $flushPendingTasks = null; var $q = null; var $rootScope = null; var $scope = null; var $uibModal = null; var contextService = null; var editableExplorationBackendApiService = null; var explorationEngineService = null; var explorationInitStateNameService = null; var explorationFeaturesService = null; var explorationPlayerStateService = null; var explorationParamChangesService = null; var explorationStatesService = null; var graphDataService = null; var learnerParamsService = null; var numberAttemptsService = null; var routerService = null; var stateEditorService = null; var stateObjectFactory = null; var paramChangeObjectFactory = null; var parameterMetadataService = null; var mockUpdateActiveStateIfInEditorEventEmitter = new EventEmitter(); var mockPlayerStateChangeEventEmitter = new EventEmitter(); var explorationId = 'exp1'; var stateName = 'State1'; var changeObjectName = 'change'; var exploration = { init_state_name: stateName, param_changes: [], param_specs: {}, states: {}, title: 'Exploration Title', language_code: 'en', correctness_feedback_enabled: true }; var parameters = [{ paramName: 'paramName1' }, { paramName: 'paramName2' }]; beforeEach(angular.mock.module('oppia', function($provide) { $provide.value('NgbModal', { open: () => { return { result: Promise.resolve() }; } }); })); beforeEach(function() { paramChangeObjectFactory = TestBed.inject(ParamChangeObjectFactory); stateObjectFactory = TestBed.inject(StateObjectFactory); }); beforeEach(angular.mock.module(function($provide) { $provide.value('ExplorationDataService', { getDataAsync: () => $q.resolve({ param_changes: [ paramChangeObjectFactory.createEmpty(changeObjectName).toBackendDict() ], states: [stateObjectFactory.createDefaultState(stateName)], init_state_name: stateName }) }); })); describe('when there are manual param changes', function() { beforeEach(angular.mock.inject(function($injector, $componentController) { $flushPendingTasks = $injector.get('$flushPendingTasks'); $rootScope = $injector.get('$rootScope'); $q = $injector.get('$q'); $uibModal = $injector.get('$uibModal'); contextService = $injector.get('ContextService'); spyOn(contextService, 'getExplorationId').and.returnValue(explorationId); editableExplorationBackendApiService = $injector.get( 'EditableExplorationBackendApiService'); explorationEngineService = $injector.get('ExplorationEngineService'); explorationFeaturesService = $injector.get('ExplorationFeaturesService'); explorationInitStateNameService = $injector.get( 'ExplorationInitStateNameService'); explorationPlayerStateService = $injector.get( 'ExplorationPlayerStateService'); explorationParamChangesService = $injector.get( 'ExplorationParamChangesService'); explorationStatesService = $injector.get('ExplorationStatesService'); graphDataService = $injector.get('GraphDataService'); learnerParamsService = $injector.get('LearnerParamsService'); parameterMetadataService = $injector.get('ParameterMetadataService'); routerService = $injector.get('RouterService'); stateEditorService = $injector.get('StateEditorService'); spyOn(parameterMetadataService, 'getUnsetParametersInfo').and.returnValue( parameters); spyOn( editableExplorationBackendApiService, 'fetchApplyDraftExplorationAsync') .and.returnValue($q.resolve(exploration)); explorationParamChangesService.savedMemento = [ paramChangeObjectFactory.createEmpty(changeObjectName).toBackendDict() ]; spyOnProperty( explorationEngineService, 'onUpdateActiveStateIfInEditor').and.returnValue( mockUpdateActiveStateIfInEditorEventEmitter); spyOnProperty( explorationPlayerStateService, 'onPlayerStateChange').and.returnValue( mockPlayerStateChangeEventEmitter); $scope = $rootScope.$new(); ctrl = $componentController('previewTab', { $scope: $scope, ParamChangeObjectFactory: paramChangeObjectFactory }); ctrl.$onInit(); })); afterEach(() => { ctrl.$onDestroy(); }); it('should initialize controller properties after its initialization', function() { spyOn(stateEditorService, 'getActiveStateName').and.returnValue( stateName); // Get data from exploration data service. $scope.$apply(); expect(ctrl.isExplorationPopulated).toBe(false); expect(ctrl.previewWarning).toBe('Preview started from \"State1\"'); }); it('should init param changes if they are undefined', function() { spyOn(explorationParamChangesService, 'init').and.callThrough(); spyOn(explorationStatesService, 'init'); spyOn(explorationInitStateNameService, 'init').and.callThrough(); spyOn(graphDataService, 'recompute'); spyOn(stateEditorService, 'getActiveStateName').and.returnValue(null); spyOn(stateEditorService, 'setActiveStateName'); explorationParamChangesService.savedMemento = undefined; // Get data from exploration data service. $scope.$apply(); expect(explorationParamChangesService.init).toHaveBeenCalledWith( [paramChangeObjectFactory.createEmpty(changeObjectName)] ); expect(explorationStatesService.init).toHaveBeenCalledWith( [stateObjectFactory.createDefaultState(stateName)] ); expect(explorationInitStateNameService.init).toHaveBeenCalledWith( stateName ); expect(graphDataService.recompute).toHaveBeenCalled(); expect(stateEditorService.setActiveStateName).toHaveBeenCalledWith( stateName ); expect(explorationParamChangesService.savedMemento).toEqual( [paramChangeObjectFactory.createEmpty(changeObjectName)] ); expect(explorationInitStateNameService.savedMemento).toEqual(stateName); }); it('should set active state name when broadcasting' + ' updateActiveStateIfInEditor', function() { spyOn(stateEditorService, 'setActiveStateName'); spyOn(stateEditorService, 'getActiveStateName').and.returnValue( stateName); mockUpdateActiveStateIfInEditorEventEmitter.emit('State2'); expect(stateEditorService.setActiveStateName).toHaveBeenCalledWith( 'State2'); }); it('should get all learner params when broadcasting playerStateChange', function() { spyOn(learnerParamsService, 'getAllParams').and.returnValue({ foo: [] }); mockPlayerStateChangeEventEmitter.emit(); expect(ctrl.allParams).toEqual({ foo: [] }); }); it('should evaluate whenever parameter summary is shown', function() { spyOn(explorationFeaturesService, 'areParametersEnabled') .and.returnValue(true); expect(ctrl.showParameterSummary()).toBe(false); spyOn(learnerParamsService, 'getAllParams').and.returnValue({ foo: [] }); mockPlayerStateChangeEventEmitter.emit(); expect(ctrl.showParameterSummary()).toBe(true); }); it('should open set params modal', function() { spyOn(stateEditorService, 'getActiveStateName').and.returnValue( stateName); spyOn($uibModal, 'open').and.callThrough(); // Get data from exploration data service. $scope.$apply(); expect($uibModal.open).toHaveBeenCalled(); }); it('should load preview state when closing set params modal', function() { spyOn($uibModal, 'open').and.returnValue({ result: $q.resolve() }); spyOn(explorationEngineService, 'initSettingsFromEditor'); spyOn(stateEditorService, 'getActiveStateName').and.returnValue( stateName); // Get data from exploration data service and resolve promise in open // modal. $scope.$apply(); var expectedParamChanges = parameters.map(parameter => ( paramChangeObjectFactory.createEmpty(parameter.paramName))); expect( explorationEngineService.initSettingsFromEditor).toHaveBeenCalledWith( stateName, expectedParamChanges); expect(ctrl.isExplorationPopulated).toBeTrue(); }); it('should go to main tab when dismissing set params modal', function() { spyOn($uibModal, 'open').and.returnValue({ result: $q.reject() }); spyOn(routerService, 'navigateToMainTab'); spyOn(stateEditorService, 'getActiveStateName').and.returnValue( stateName); // Get data from exploration data service and resolve promise in open // modal. $scope.$apply(); expect(routerService.navigateToMainTab).toHaveBeenCalled(); }); }); describe('when there are no manual param changes', function() { beforeEach(angular.mock.inject(function($injector, $componentController) { $flushPendingTasks = $injector.get('$flushPendingTasks'); var $rootScope = $injector.get('$rootScope'); $q = $injector.get('$q'); $uibModal = $injector.get('$uibModal'); contextService = $injector.get('ContextService'); spyOn(contextService, 'getExplorationId').and.returnValue(explorationId); editableExplorationBackendApiService = $injector.get( 'EditableExplorationBackendApiService'); explorationInitStateNameService = $injector.get( 'ExplorationInitStateNameService'); explorationEngineService = $injector.get('ExplorationEngineService'); explorationParamChangesService = $injector.get( 'ExplorationParamChangesService'); numberAttemptsService = $injector.get('NumberAttemptsService'); parameterMetadataService = $injector.get('ParameterMetadataService'); routerService = $injector.get('RouterService'); stateEditorService = $injector.get('StateEditorService'); explorationInitStateNameService.init(stateName); spyOn(stateEditorService, 'getActiveStateName').and.returnValue( stateName); spyOn(parameterMetadataService, 'getUnsetParametersInfo') .and.returnValue([]); spyOn( editableExplorationBackendApiService, 'fetchApplyDraftExplorationAsync') .and.returnValue($q.resolve(exploration)); explorationParamChangesService.savedMemento = [ paramChangeObjectFactory.createEmpty(changeObjectName).toBackendDict() ]; // Mock init just to call the callback directly. spyOn(explorationEngineService, 'init').and.callFake(function( explorationDict, explorationVersion, preferredAudioLanguage, autoTtsEnabled, preferredContentLanguageCodes, successCallback) { successCallback(); }); $scope = $rootScope.$new(); ctrl = $componentController('previewTab', { $scope: $scope, ParamChangeObjectFactory: paramChangeObjectFactory }); ctrl.$onInit(); })); it('should initialize controller properties after its initialization', function() { // Get data from exploration data service. $scope.$apply(); expect(ctrl.isExplorationPopulated).toBe(false); expect(ctrl.previewWarning).toBe(''); }); it('should load preview state when closing set params modal', function() { spyOn($uibModal, 'open'); spyOn(explorationEngineService, 'initSettingsFromEditor'); // Get data from exploration data service and resolve promise in open // modal. $scope.$apply(); expect($uibModal.open).not.toHaveBeenCalled(); expect( explorationEngineService.initSettingsFromEditor) .toHaveBeenCalledWith(stateName, []); expect(ctrl.isExplorationPopulated).toBe(true); }); it('should reset preview settings', function() { spyOn($uibModal, 'open').and.returnValue({ result: $q.reject() }); spyOn(numberAttemptsService, 'reset').and.callThrough(); spyOn(explorationEngineService, 'initSettingsFromEditor'); // Get data from exploration data service and resolve promise in open // modal. $scope.$apply(); ctrl.resetPreview(); $flushPendingTasks(); expect(numberAttemptsService.reset).toHaveBeenCalled(); expect( explorationEngineService.initSettingsFromEditor) .toHaveBeenCalledWith(stateName, []); expect(ctrl.isExplorationPopulated).toBe(true); }); }); });
the_stack
import RandomGen5Teams from '../gen5/random-teams'; import {Utils} from '../../../lib'; import {toID} from '../../../sim/dex'; import {PRNG} from '../../../sim'; import type {MoveCounter} from '../../random-teams'; // These moves can be used even if we aren't setting up to use them: const SetupException = ['dracometeor', 'overheat']; // Give recovery moves priority over certain other defensive status moves const recoveryMoves = [ 'healorder', 'milkdrink', 'moonlight', 'morningsun', 'painsplit', 'recover', 'rest', 'roost', 'slackoff', 'softboiled', 'synthesis', 'wish', ]; const defensiveStatusMoves = ['aromatherapy', 'haze', 'healbell', 'roar', 'whirlwind', 'willowisp', 'yawn']; export class RandomGen4Teams extends RandomGen5Teams { constructor(format: string | Format, prng: PRNG | PRNGSeed | null) { super(format, prng); this.moveEnforcementCheckers = { Bug: (movePool, moves, abilities, types, counter) => ( !counter.get('Bug') && (movePool.includes('bugbuzz') || movePool.includes('megahorn')) ), Dark: (movePool, moves, abilities, types, counter) => ( (!counter.get('Dark') || (counter.get('Dark') === 1 && moves.has('pursuit'))) && movePool.includes('suckerpunch') && counter.setupType !== 'Special' ), Dragon: (movePool, moves, abilities, types, counter) => !counter.get('Dragon'), Electric: (movePool, moves, abilities, types, counter) => !counter.get('Electric'), Fighting: (movePool, moves, abilities, types, counter) => ( !counter.get('Fighting') && (!!counter.setupType || !counter.get('Status') || movePool.includes('closecombat') || movePool.includes('highjumpkick')) ), Fire: (movePool, moves, abilities, types, counter) => !counter.get('Fire'), Flying: (movePool, moves, abilities, types, counter) => !counter.get('Flying') && ( (counter.setupType !== 'Special' && movePool.includes('bravebird')) || (abilities.has('Serene Grace') && movePool.includes('airslash')) ), Grass: (movePool, moves, abilities, types, counter) => ( !counter.get('Grass') && ['leafblade', 'leafstorm', 'seedflare', 'woodhammer'].some(m => movePool.includes(m)) ), Ground: (movePool, moves, abilities, types, counter) => !counter.get('Ground'), Ice: (movePool, moves, abilities, types, counter) => ( !counter.get('Ice') && (!types.has('Water') || !counter.get('Water')) ), Rock: (movePool, moves, abilities, types, counter) => ( !counter.get('Rock') && (movePool.includes('headsmash') || movePool.includes('stoneedge')) ), Steel: (movePool, moves, abilities, types, counter) => !counter.get('Steel') && movePool.includes('meteormash'), Water: (movePool, moves, abilities, types, counter) => ( !counter.get('Water') && (moves.has('raindance') || !types.has('Ice') || !counter.get('Ice')) ), Adaptability: (movePool, moves, abilities, types, counter, species) => ( !counter.setupType && species.types.length > 1 && (!counter.get(species.types[0]) || !counter.get(species.types[1])) ), Guts: (movePool, moves, abilities, types) => types.has('Normal') && movePool.includes('facade'), 'Slow Start': movePool => movePool.includes('substitute'), }; } shouldCullMove( move: Move, types: Set<string>, moves: Set<string>, abilities: Set<string>, counter: MoveCounter, movePool: string[], teamDetails: RandomTeamsTypes.TeamDetails, species: Species, isLead: boolean, ): {cull: boolean, isSetup?: boolean} { const restTalk = moves.has('rest') && moves.has('sleeptalk'); switch (move.id) { // Not very useful without their supporting moves case 'batonpass': return {cull: !counter.setupType && !counter.get('speedsetup') && !moves.has('substitute')}; case 'eruption': case 'waterspout': return {cull: counter.get('Physical') + counter.get('Special') < 4}; case 'focuspunch': return {cull: !moves.has('substitute') || counter.damagingMoves.size < 2 || moves.has('hammerarm')}; case 'raindance': return {cull: abilities.has('Hydration') ? !moves.has('rest') : counter.get('Physical') + counter.get('Special') < 2}; case 'refresh': return {cull: !(moves.has('calmmind') && (moves.has('recover') || moves.has('roost')))}; case 'rest': return {cull: movePool.includes('sleeptalk') || (abilities.has('Hydration') && !moves.has('raindance'))}; case 'sleeptalk': if (movePool.length > 1) { const rest = movePool.indexOf('rest'); if (rest >= 0) this.fastPop(movePool, rest); } return {cull: !moves.has('rest')}; case 'sunnyday': return {cull: !moves.has('solarbeam')}; case 'weatherball': return {cull: !moves.has('raindance') && !moves.has('sunnyday')}; // Set up once and only if we have the moves for it case 'bellydrum': case 'bulkup': case 'curse': case 'dragondance': case 'swordsdance': const notEnoughPhysicalMoves = ( counter.get('Physical') + counter.get('physicalpool') < 2 && !moves.has('batonpass') && (!moves.has('rest') || !moves.has('sleeptalk')) ); const badPhysicalMoveset = counter.setupType !== 'Physical' || counter.get('physicalsetup') > 1; return {cull: moves.has('sunnyday') || notEnoughPhysicalMoves || badPhysicalMoveset, isSetup: true}; case 'calmmind': case 'nastyplot': case 'tailglow': const notEnoughSpecialMoves = ( counter.get('Special') + counter.get('specialpool') < 2 && !moves.has('batonpass') && (!moves.has('rest') || !moves.has('sleeptalk')) ); const badSpecialMoveset = counter.setupType !== 'Special' || counter.get('specialsetup') > 1; return {cull: notEnoughSpecialMoves || badSpecialMoveset, isSetup: true}; case 'agility': case 'rockpolish': return {cull: restTalk || (counter.damagingMoves.size < 2 && !moves.has('batonpass')), isSetup: !counter.setupType}; // Bad after setup case 'destinybond': return {cull: !!counter.setupType || moves.has('explosion')}; case 'explosion': case 'selfdestruct': return {cull: ( counter.setupType === 'Special' || Array.from(moves).some(id => recoveryMoves.includes(id) || defensiveStatusMoves.includes(id)) || ['batonpass', 'protect', 'substitute'].some(m => moves.has(m)) )}; case 'foresight': case 'roar': case 'whirlwind': return {cull: !!counter.setupType && !abilities.has('Speed Boost')}; case 'healingwish': case 'lunardance': return {cull: !!counter.setupType || moves.has('rest') || moves.has('substitute')}; case 'protect': return {cull: ( !['Guts', 'Quick Feet', 'Speed Boost'].some(abil => abilities.has(abil)) || ['rest', 'softboiled', 'toxic', 'wish'].some(m => moves.has(m)) )}; case 'wish': return {cull: ( !['batonpass', 'protect', 'uturn'].some(m => moves.has(m)) || moves.has('rest') || !!counter.get('speedsetup') )}; case 'rapidspin': return {cull: !!teamDetails.rapidSpin || (!!counter.setupType && counter.get('Physical') + counter.get('Special') < 2)}; case 'reflect': case 'lightscreen': case 'fakeout': return {cull: !!counter.setupType || !!counter.get('speedsetup') || moves.has('substitute')}; case 'spikes': return {cull: !!counter.setupType || !!counter.get('speedsetup') || moves.has('substitute')}; case 'stealthrock': return {cull: ( !!counter.setupType || !!counter.get('speedsetup') || moves.has('rest') || moves.has('substitute') || !!teamDetails.stealthRock )}; case 'switcheroo': case 'trick': return {cull: ( counter.get('Physical') + counter.get('Special') < 3 || !!counter.setupType || ['fakeout', 'lightscreen', 'reflect', 'suckerpunch', 'trickroom'].some(m => moves.has(m)) )}; case 'toxic': case 'toxicspikes': return {cull: ( !!counter.setupType || !!counter.get('speedsetup') || !!teamDetails.toxicSpikes || moves.has('willowisp') )}; case 'trickroom': return {cull: ( !!counter.setupType || !!counter.get('speedsetup') || counter.damagingMoves.size < 2 || moves.has('lightscreen') || moves.has('reflect') || restTalk )}; case 'uturn': return {cull: ( (types.has('Bug') && counter.get('stab') < 2 && counter.damagingMoves.size > 1) || (abilities.has('Speed Boost') && moves.has('protect')) || !!counter.setupType || !!counter.get('speedsetup') || moves.has('batonpass') || moves.has('substitute') )}; // Bit redundant to have both // Attacks: case 'bodyslam': case 'slash': return {cull: moves.has('facade') || moves.has('return')}; case 'doubleedge': return {cull: ['bodyslam', 'facade', 'return'].some(m => moves.has(m))}; case 'endeavor': return {cull: !isLead}; case 'headbutt': return {cull: !moves.has('bodyslam') && !moves.has('thunderwave')}; case 'judgment': case 'swift': return {cull: counter.setupType !== 'Special' && counter.get('stab') > 1}; case 'quickattack': return {cull: moves.has('thunderwave')}; case 'firepunch': case 'flamethrower': return {cull: moves.has('fireblast') || moves.has('overheat') && !counter.setupType}; case 'lavaplume': case 'fireblast': if (move.id === 'fireblast' && moves.has('lavaplume') && !counter.get('speedsetup')) return {cull: true}; if (move.id === 'lavaplume' && moves.has('fireblast') && counter.get('speedsetup')) return {cull: true}; if (moves.has('flareblitz') && counter.setupType !== 'Special') return {cull: true}; break; case 'overheat': return {cull: counter.setupType === 'Special' || ['batonpass', 'fireblast', 'flareblitz'].some(m => moves.has(m))}; case 'aquajet': return {cull: moves.has('dragondance') || (moves.has('waterfall') && counter.get('Physical') < 3)}; case 'hydropump': return {cull: moves.has('surf')}; case 'waterfall': return {cull: ( moves.has('aquatail') || (counter.setupType !== 'Physical' && (moves.has('hydropump') || moves.has('surf'))) )}; case 'chargebeam': return {cull: moves.has('thunderbolt') && counter.get('Special') < 3}; case 'discharge': return {cull: moves.has('thunderbolt')}; case 'energyball': return {cull: ( moves.has('leafblade') || moves.has('woodhammer') || (moves.has('sunnyday') && moves.has('solarbeam')) || (moves.has('leafstorm') && counter.get('Physical') + counter.get('Special') < 4) )}; case 'grassknot': case 'leafblade': case 'seedbomb': return {cull: moves.has('woodhammer') || (moves.has('sunnyday') && moves.has('solarbeam'))}; case 'leafstorm': return {cull: ( !!counter.setupType || moves.has('batonpass') || moves.has('powerwhip') || (moves.has('sunnyday') && moves.has('solarbeam')) )}; case 'solarbeam': return {cull: counter.setupType === 'Physical' || !moves.has('sunnyday')}; case 'icepunch': return {cull: !counter.setupType && moves.has('icebeam')}; case 'aurasphere': case 'drainpunch': case 'focusblast': return {cull: moves.has('closecombat') && counter.setupType !== 'Special'}; case 'brickbreak': case 'closecombat': case 'crosschop': case 'lowkick': return {cull: moves.has('substitute') && moves.has('focuspunch')}; case 'machpunch': return {cull: ( counter.damagingMoves.size <= counter.get('Fighting') || (types.has('Fighting') && counter.get('stab') < 2 && !abilities.has('Technician')) )}; case 'seismictoss': return {cull: moves.has('nightshade') || counter.get('Physical') + counter.get('Special') >= 1}; case 'superpower': return {cull: moves.has('dragondance') || !!counter.get('speedsetup')}; case 'gunkshot': return {cull: moves.has('poisonjab')}; case 'earthpower': return {cull: moves.has('earthquake')}; case 'airslash': return {cull: !counter.setupType && moves.has('bravebird')}; case 'zenheadbutt': return {cull: moves.has('psychocut')}; case 'rockblast': case 'rockslide': return {cull: moves.has('stoneedge')}; case 'shadowclaw': return {cull: moves.has('shadowforce') || moves.has('suckerpunch') && !types.has('Ghost')}; case 'dracometeor': return {cull: moves.has('calmmind') || restTalk || (!!counter.setupType && counter.get('stab') < 2)}; case 'dragonclaw': return {cull: moves.has('outrage')}; case 'dragonpulse': return {cull: moves.has('dracometeor') && moves.has('outrage')}; case 'crunch': case 'nightslash': return {cull: moves.has('suckerpunch')}; case 'pursuit': return {cull: !!counter.setupType || moves.has('payback')}; case 'flashcannon': return {cull: (moves.has('ironhead') || movePool.includes('ironhead')) && counter.setupType !== 'Special'}; // Status: case 'encore': return {cull: ['roar', 'taunt', 'whirlwind'].some(m => moves.has(m)) || restTalk}; case 'haze': case 'taunt': return {cull: restTalk}; case 'leechseed': case 'painsplit': return {cull: !!counter.setupType || !!counter.get('speedsetup') || moves.has('rest')}; case 'recover': case 'slackoff': return {cull: restTalk}; case 'stunspore': return {cull: ( !!counter.setupType || moves.has('toxic') || movePool.includes('sleeppowder') || movePool.includes('spore') )}; case 'substitute': return {cull: ['pursuit', 'rapidspin', 'rest', 'taunt'].some(m => moves.has(m))}; case 'thunderwave': return {cull: ( !!counter.setupType || moves.has('toxic') || moves.has('trickroom') || (moves.has('bodyslam') && abilities.has('Serene Grace')) )}; case 'yawn': return {cull: moves.has('thunderwave') || moves.has('toxic')}; } return {cull: false}; } shouldCullAbility( ability: string, types: Set<string>, moves: Set<string>, abilities: Set<string>, counter: MoveCounter, movePool: string[], teamDetails: RandomTeamsTypes.TeamDetails, species: Species, ) { switch (ability) { case 'Anger Point': case 'Ice Body': case 'Steadfast': return true; case 'Blaze': return !counter.get('Fire'); case 'Chlorophyll': return !moves.has('sunnyday') && !teamDetails.sun; case 'Compound Eyes': case 'No Guard': return !counter.get('inaccurate'); case 'Early Bird': return !moves.has('rest'); case 'Gluttony': return !moves.has('bellydrum'); case 'Hustle': return counter.get('Physical') < 2; case 'Mold Breaker': return !moves.has('earthquake'); case 'Overgrow': return !counter.get('Grass'); case 'Reckless': case 'Rock Head': return !counter.get('recoil'); case 'Sand Veil': return !teamDetails.sand; case 'Serene Grace': return !counter.get('serenegrace') || species.id === 'blissey'; case 'Simple': return !counter.setupType && !moves.has('cosmicpower'); case 'Skill Link': return !counter.get('skilllink'); case 'Snow Cloak': return !teamDetails.hail; case 'Solar Power': return !counter.get('Special') || !moves.has('sunnyday') && !teamDetails.sun; case 'Speed Boost': return moves.has('uturn'); case 'Swift Swim': return !moves.has('raindance') && !teamDetails.rain; case 'Swarm': return !counter.get('Bug'); case 'Synchronize': return counter.get('Status') < 2; case 'Technician': return !counter.get('technician') || moves.has('toxic'); case 'Tinted Lens': return counter.get('damage') >= counter.damagingMoves.size; case 'Torrent': return !counter.get('Water'); } return false; } getHighPriorityItem( ability: string, types: Set<string>, moves: Set<string>, counter: MoveCounter, teamDetails: RandomTeamsTypes.TeamDetails, species: Species, isLead: boolean, ): string | undefined { if (species.requiredItem) return species.requiredItem; if (species.requiredItems) return this.sample(species.requiredItems); if (species.name === 'Farfetch\u2019d') return 'Stick'; if (species.name === 'Marowak') return 'Thick Club'; if (species.name === 'Shedinja' || species.name === 'Smeargle') return 'Focus Sash'; if (species.name === 'Unown') return 'Choice Specs'; if (species.name === 'Wobbuffet') { return moves.has('destinybond') ? 'Custap Berry' : this.sample(['Leftovers', 'Sitrus Berry']); } if (moves.has('switcheroo') || moves.has('trick')) { if ( species.baseStats.spe >= 60 && species.baseStats.spe <= 108 && !counter.get('priority') && this.randomChance(2, 3) ) { return 'Choice Scarf'; } else { return (counter.get('Physical') > counter.get('Special')) ? 'Choice Band' : 'Choice Specs'; } } if (moves.has('bellydrum')) return 'Sitrus Berry'; if (ability === 'Magic Guard' || ability === 'Speed Boost' && counter.get('Status') < 2) return 'Life Orb'; if (ability === 'Poison Heal' || ability === 'Toxic Boost') return 'Toxic Orb'; if (moves.has('rest') && !moves.has('sleeptalk') && ability !== 'Natural Cure' && ability !== 'Shed Skin') { return (moves.has('raindance') && ability === 'Hydration') ? 'Damp Rock' : 'Chesto Berry'; } if (moves.has('raindance') && ability === 'Swift Swim' && counter.get('Status') < 2) return 'Life Orb'; if (moves.has('sunnyday')) return (ability === 'Chlorophyll' && counter.get('Status') < 2) ? 'Life Orb' : 'Heat Rock'; if (moves.has('lightscreen') && moves.has('reflect')) return 'Light Clay'; if ((ability === 'Guts' || ability === 'Quick Feet') && moves.has('facade')) return 'Toxic Orb'; if (ability === 'Unburden') return 'Sitrus Berry'; if (species.baseStats.hp + species.baseStats.def + species.baseStats.spd <= 150) { return isLead ? 'Focus Sash' : 'Life Orb'; } if (moves.has('endeavor')) return 'Focus Sash'; } getMediumPriorityItem( ability: string, moves: Set<string>, counter: MoveCounter, species: Species, isDoubles: boolean, isLead: boolean ): string | undefined { if ( ability === 'Slow Start' || ['curse', 'leechseed', 'protect', 'roar', 'sleeptalk', 'whirlwind'].some(m => moves.has(m)) || (ability === 'Serene Grace' && ['bodyslam', 'headbutt', 'ironhead'].some(m => moves.has(m))) ) { return 'Leftovers'; } if (counter.get('Physical') >= 4 && !moves.has('fakeout') && !moves.has('rapidspin') && !moves.has('suckerpunch')) { return ( species.baseStats.spe >= 60 && species.baseStats.spe <= 108 && !counter.get('priority') && !moves.has('bodyslam') && this.randomChance(2, 3) ) ? 'Choice Scarf' : 'Choice Band'; } if ( (counter.get('Special') >= 4 || ( counter.get('Special') >= 3 && ['batonpass', 'uturn', 'waterspout', 'selfdestruct'].some(m => moves.has(m)) )) && !moves.has('chargebeam') ) { return ( species.baseStats.spe >= 60 && species.baseStats.spe <= 108 && ability !== 'Speed Boost' && !counter.get('priority') && this.randomChance(2, 3) ) ? 'Choice Scarf' : 'Choice Specs'; } if (moves.has('outrage') && counter.setupType) return 'Lum Berry'; if (moves.has('substitute')) { return (counter.damagingMoves.size < 2 || !counter.get('drain') && (counter.damagingMoves.size < 3 || species.baseStats.hp >= 60 || species.baseStats.def + species.baseStats.spd >= 180) ) ? 'Leftovers' : 'Life Orb'; } if (ability === 'Guts') return 'Toxic Orb'; if ( isLead && !counter.get('recoil') && !Array.from(moves).some(id => !!recoveryMoves.includes(id)) && species.baseStats.hp + species.baseStats.def + species.baseStats.spd < 225 ) { return 'Focus Sash'; } if (counter.damagingMoves.size >= 4) { return ( counter.get('Normal') || counter.get('Dragon') > 1 || moves.has('chargebeam') || moves.has('suckerpunch') ) ? 'Life Orb' : 'Expert Belt'; } if (counter.damagingMoves.size >= 3 && !moves.has('superfang') && !moves.has('metalburst')) { const totalBulk = species.baseStats.hp + species.baseStats.def + species.baseStats.spd; return ( counter.get('speedsetup') || counter.get('priority') || moves.has('dragondance') || moves.has('trickroom') || totalBulk < 235 || (species.baseStats.spe >= 70 && (totalBulk < 260 || (!!counter.get('recovery') && totalBulk < 285))) ) ? 'Life Orb' : 'Leftovers'; } } getLowPriorityItem( ability: string, types: Set<string>, moves: Set<string>, abilities: Set<string>, counter: MoveCounter, teamDetails: RandomTeamsTypes.TeamDetails, species: Species, ) { if (types.has('Poison')) return 'Black Sludge'; if (this.dex.getEffectiveness('Rock', species) >= 1 || moves.has('roar')) return 'Leftovers'; if (counter.get('Status') <= 1 && ['metalburst', 'rapidspin', 'superfang'].every(m => !moves.has(m))) return 'Life Orb'; return 'Leftovers'; } randomSet( species: string | Species, teamDetails: RandomTeamsTypes.TeamDetails = {}, isLead = false ): RandomTeamsTypes.RandomSet { species = this.dex.species.get(species); let forme = species.name; if (typeof species.battleOnly === 'string') forme = species.battleOnly; if (species.cosmeticFormes) { forme = this.sample([species.name].concat(species.cosmeticFormes)); } const movePool = (species.randomBattleMoves || Object.keys(this.dex.species.getLearnset(species.id)!)).slice(); const rejectedPool: string[] = []; const moves = new Set<string>(); let ability = ''; let item: string | undefined; const evs = {hp: 85, atk: 85, def: 85, spa: 85, spd: 85, spe: 85}; const ivs: SparseStatsTable = {hp: 31, atk: 31, def: 31, spa: 31, spd: 31, spe: 31}; const types = new Set(species.types); const abilities = new Set(Object.values(species.abilities)); let availableHP = 0; for (const setMoveid of movePool) { if (setMoveid.startsWith('hiddenpower')) availableHP++; } let counter: MoveCounter; let hasHiddenPower = false; do { // Choose next 4 moves from learnset/viable moves and add them to moves list: while (moves.size < 4 && movePool.length) { const moveid = this.sampleNoReplace(movePool); if (moveid.startsWith('hiddenpower')) { availableHP--; if (hasHiddenPower) continue; hasHiddenPower = true; } moves.add(moveid); } while (moves.size < 4 && rejectedPool.length) { const moveid = this.sampleNoReplace(rejectedPool); if (moveid.startsWith('hiddenpower')) { if (hasHiddenPower) continue; hasHiddenPower = true; } moves.add(moveid); } counter = this.queryMoves(moves, species.types, abilities, movePool); if (types.has('Dark') && moves.has('suckerpunch') && species.types.length === 1) { counter.add('stab'); } // Iterate through the moves again, this time to cull them: for (const moveid of moves) { const move = this.dex.moves.get(moveid); let {cull, isSetup} = this.shouldCullMove( move, types, moves, abilities, counter, movePool, teamDetails, species, isLead ); // Increased/decreased priority moves are unneeded with moves that boost only speed if (move.priority !== 0 && !!counter.get('speedsetup')) cull = true; // This move doesn't satisfy our setup requirements: if ( (move.category === 'Physical' && counter.setupType === 'Special') || (move.category === 'Special' && counter.setupType === 'Physical') ) { // Reject STABs last in case the setup type changes later on if ( !SetupException.includes(moveid) && (!types.has(move.type) || counter.get('stab') > 1 || counter.get(move.category) < 2) ) { cull = true; } } if ( counter.setupType && !isSetup && move.category !== counter.setupType && counter.get(counter.setupType) < 2 && !moves.has('batonpass') ) { // Mono-attacking with setup and RestTalk or recovery + status healing is allowed if ( moveid !== 'rest' && moveid !== 'sleeptalk' && !(recoveryMoves.includes(moveid) && (moves.has('healbell') || moves.has('refresh'))) && !((moveid === 'healbell' || moveid === 'refresh') && Array.from(moves).some(id => recoveryMoves.includes(id))) && ( // Reject Status moves only if there is nothing else to reject move.category !== 'Status' || ( counter.get(counter.setupType) + counter.get('Status') > 3 && counter.get('physicalsetup') + counter.get('specialsetup') < 2 ) ) ) { cull = true; } } if ( moveid === 'hiddenpower' && counter.setupType === 'Special' && species.types.length > 1 && counter.get('Special') <= 2 && !types.has(move.type) && !counter.get('Physical') && counter.get('specialpool') && (!(types.has('Ghost') && move.type === 'Fighting' || types.has('Electric') && move.type === 'Ice')) ) { // Hidden Power isn't good enough cull = true; } // Reject defensive status moves if a reliable recovery move is available but not selected. // Toxic is only defensive if used with another status move other than Protect (Toxic + 3 attacks and Toxic + Protect are ok). if ( !Array.from(moves).some(id => recoveryMoves.includes(id)) && movePool.some(id => recoveryMoves.includes(id)) && ( defensiveStatusMoves.includes(moveid) || (moveid === 'toxic' && ((counter.get('Status') > 1 && !moves.has('protect')) || counter.get('Status') > 2)) ) ) { cull = true; } const runEnforcementChecker = (checkerName: string) => { if (!this.moveEnforcementCheckers[checkerName]) return false; return this.moveEnforcementCheckers[checkerName]( movePool, moves, abilities, types, counter, species as Species, teamDetails ); }; const moveIsRejectable = ( !move.weather && !move.damage && (move.category !== 'Status' || !move.flags.heal) && (move.category === 'Status' || !types.has(move.type) || (move.basePower && move.basePower < 40 && !move.multihit)) && // These moves cannot be rejected in favor of a forced move !['judgment', 'sleeptalk'].includes(moveid) && // Setup-supported moves should only be rejected under specific circumstances (counter.get('physicalsetup') + counter.get('specialsetup') < 2 && ( !counter.setupType || counter.setupType === 'Mixed' || (move.category !== counter.setupType && move.category !== 'Status') || counter.get(counter.setupType) + counter.get('Status') > 3 )) ); if (!cull && !isSetup && moveIsRejectable) { // There may be more important moves that this Pokemon needs const canRollForcedMoves = ( // These moves should always be rolled movePool.includes('spore') || (!Array.from(moves).some(id => recoveryMoves.includes(id)) && ( movePool.includes('softboiled') || (species.baseSpecies === 'Arceus' && movePool.includes('recover')) )) ); // Pokemon should usually have at least one STAB move const requiresStab = ( !counter.get('stab') && !counter.get('damage') && ( species.types.length > 1 || (species.types[0] !== 'Normal' && species.types[0] !== 'Psychic') || !moves.has('icebeam') || species.baseStats.spa >= species.baseStats.spd ) ); if ( canRollForcedMoves || requiresStab || (species.requiredMove && movePool.includes(toID(species.requiredMove))) || (counter.get('defensesetup') && !counter.get('recovery') && !moves.has('rest')) ) { cull = true; } else { // Pokemon should have moves that benefit their typing or ability for (const type of types) { if (runEnforcementChecker(type)) cull = true; } for (const abil of abilities) { if (runEnforcementChecker(abil)) cull = true; } } } // Sleep Talk shouldn't be selected without Rest if (moveid === 'rest' && cull) { const sleeptalk = movePool.indexOf('sleeptalk'); if (sleeptalk >= 0) { if (movePool.length < 2) { cull = false; } else { this.fastPop(movePool, sleeptalk); } } } // Remove rejected moves from the move list if (cull && ( movePool.length - availableHP || availableHP && (moveid.startsWith('hiddenpower') || !hasHiddenPower) )) { if (move.category !== 'Status' && (!moveid.startsWith('hiddenpower') || !availableHP)) rejectedPool.push(moveid); moves.delete(moveid); if (moveid.startsWith('hiddenpower')) hasHiddenPower = false; break; } if (cull && rejectedPool.length) { moves.delete(moveid); if (moveid.startsWith('hiddenpower')) hasHiddenPower = false; break; } } } while (moves.size < 4 && (movePool.length || rejectedPool.length)); if (hasHiddenPower) { let hpType; for (const move of moves) { if (move.startsWith('hiddenpower')) { hpType = move.substr(11); break; } } if (!hpType) throw new Error(`hasHiddenPower is true, but no Hidden Power move was found.`); const HPivs = this.dex.types.get(hpType).HPivs; let iv: StatID; for (iv in HPivs) { ivs[iv] = HPivs[iv]!; } } const abilityData = Array.from(abilities).map(a => this.dex.abilities.get(a)); Utils.sortBy(abilityData, abil => -abil.rating); let ability0 = abilityData[0]; let ability1 = abilityData[1]; if (abilityData[1]) { if (ability0.rating <= ability1.rating && this.randomChance(1, 2)) { [ability0, ability1] = [ability1, ability0]; } else if (ability0.rating - 0.6 <= ability1.rating && this.randomChance(2, 3)) { [ability0, ability1] = [ability1, ability0]; } ability = ability0.name; while (this.shouldCullAbility(ability, types, moves, abilities, counter, movePool, teamDetails, species)) { if (ability === ability0.name && ability1.rating >= 1) { ability = ability1.name; } else { // Default to the highest rated ability if all are rejected ability = abilityData[0].name; break; } } if (abilities.has('Hydration') && moves.has('raindance') && moves.has('rest')) { ability = 'Hydration'; } else if (abilities.has('Swift Swim') && moves.has('raindance')) { ability = 'Swift Swim'; } else if (abilities.has('Technician') && moves.has('machpunch') && types.has('Fighting') && counter.get('stab') < 2) { ability = 'Technician'; } } else { ability = ability0.name; } item = this.getHighPriorityItem(ability, types, moves, counter, teamDetails, species, isLead); if (item === undefined) item = this.getMediumPriorityItem(ability, moves, counter, species, false, isLead); if (item === undefined) { item = this.getLowPriorityItem(ability, types, moves, abilities, counter, teamDetails, species); } // For Trick / Switcheroo if (item === 'Leftovers' && types.has('Poison')) { item = 'Black Sludge'; } const levelScale: {[k: string]: number} = { AG: 74, Uber: 76, OU: 80, '(OU)': 82, UUBL: 82, UU: 84, NUBL: 86, NU: 88, }; const customScale: {[k: string]: number} = { Delibird: 100, Ditto: 100, 'Farfetch\u2019d': 100, Unown: 100, }; let level = levelScale[species.tier] || (species.nfe ? 90 : 80); if (customScale[species.name]) level = customScale[species.name]; // Prepare optimal HP let hp = Math.floor( Math.floor( 2 * species.baseStats.hp + (ivs.hp || 31) + Math.floor(evs.hp / 4) + 100 ) * level / 100 + 10 ); if (moves.has('substitute') && item === 'Sitrus Berry') { // Two Substitutes should activate Sitrus Berry while (hp % 4 > 0) { evs.hp -= 4; hp = Math.floor( Math.floor( 2 * species.baseStats.hp + (ivs.hp || 31) + Math.floor(evs.hp / 4) + 100 ) * level / 100 + 10 ); } } else if (moves.has('bellydrum') && item === 'Sitrus Berry') { // Belly Drum should activate Sitrus Berry if (hp % 2 > 0) evs.hp -= 4; } else { // Maximize number of Stealth Rock switch-ins const srWeakness = this.dex.getEffectiveness('Rock', species); if (srWeakness > 0 && hp % (4 / srWeakness) === 0) evs.hp -= 4; } // Minimize confusion damage if (!counter.get('Physical') && !moves.has('transform')) { evs.atk = 0; ivs.atk = hasHiddenPower ? (ivs.atk || 31) - 28 : 0; } if (['gyroball', 'metalburst', 'trickroom'].some(m => moves.has(m))) { evs.spe = 0; ivs.spe = hasHiddenPower ? (ivs.spe || 31) - 28 : 0; } return { name: species.baseSpecies, species: forme, gender: species.gender, shiny: this.randomChance(1, 1024), moves: Array.from(moves), ability, evs, ivs, item, level, }; } } export default RandomGen4Teams;
the_stack
import * as assert from 'assert'; import { expect } from 'chai'; import * as TypeMoq from 'typemoq'; import { Disposable, Terminal, Uri } from 'vscode'; import { IActiveResourceService, ICommandManager, IWorkspaceService } from '../../client/common/application/types'; import { Commands } from '../../client/common/constants'; import { TerminalService } from '../../client/common/terminal/service'; import { ITerminalActivator, ITerminalServiceFactory } from '../../client/common/terminal/types'; import { IConfigurationService, IPythonSettings, ITerminalSettings } from '../../client/common/types'; import { IServiceContainer } from '../../client/ioc/types'; import { TerminalProvider } from '../../client/providers/terminalProvider'; suite('Terminal Provider', () => { let serviceContainer: TypeMoq.IMock<IServiceContainer>; let commandManager: TypeMoq.IMock<ICommandManager>; let workspace: TypeMoq.IMock<IWorkspaceService>; let activeResourceService: TypeMoq.IMock<IActiveResourceService>; let terminalProvider: TerminalProvider; const resource = Uri.parse('a'); setup(() => { serviceContainer = TypeMoq.Mock.ofType<IServiceContainer>(); commandManager = TypeMoq.Mock.ofType<ICommandManager>(); activeResourceService = TypeMoq.Mock.ofType<IActiveResourceService>(); workspace = TypeMoq.Mock.ofType<IWorkspaceService>(); serviceContainer.setup((c) => c.get(ICommandManager)).returns(() => commandManager.object); serviceContainer.setup((c) => c.get(IWorkspaceService)).returns(() => workspace.object); serviceContainer.setup((c) => c.get(IActiveResourceService)).returns(() => activeResourceService.object); }); teardown(() => { try { terminalProvider.dispose(); } catch { // No catch clause. } }); test('Ensure command is registered', () => { terminalProvider = new TerminalProvider(serviceContainer.object); commandManager.verify( (c) => c.registerCommand(TypeMoq.It.isValue(Commands.Create_Terminal), TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.once(), ); }); test('Ensure command handler is disposed', () => { const disposable = TypeMoq.Mock.ofType<Disposable>(); commandManager .setup((c) => c.registerCommand(TypeMoq.It.isValue(Commands.Create_Terminal), TypeMoq.It.isAny(), TypeMoq.It.isAny()), ) .returns(() => disposable.object); terminalProvider = new TerminalProvider(serviceContainer.object); terminalProvider.dispose(); disposable.verify((d) => d.dispose(), TypeMoq.Times.once()); }); test('Ensure terminal is created and displayed when command is invoked', () => { const disposable = TypeMoq.Mock.ofType<Disposable>(); let commandHandler: undefined | (() => void); commandManager .setup((c) => c.registerCommand(TypeMoq.It.isValue(Commands.Create_Terminal), TypeMoq.It.isAny(), TypeMoq.It.isAny()), ) .returns((_cmd, callback) => { commandHandler = callback; return disposable.object; }); activeResourceService .setup((a) => a.getActiveResource()) .returns(() => resource) .verifiable(TypeMoq.Times.once()); workspace.setup((w) => w.workspaceFolders).returns(() => undefined); terminalProvider = new TerminalProvider(serviceContainer.object); expect(commandHandler).not.to.be.equal(undefined, 'Handler not set'); const terminalServiceFactory = TypeMoq.Mock.ofType<ITerminalServiceFactory>(); serviceContainer .setup((c) => c.get(TypeMoq.It.isValue(ITerminalServiceFactory))) .returns(() => terminalServiceFactory.object); const terminalService = TypeMoq.Mock.ofType<TerminalService>(); terminalServiceFactory .setup((t) => t.createTerminalService(TypeMoq.It.isValue(resource), TypeMoq.It.isValue('Python'))) .returns(() => terminalService.object); commandHandler!.call(terminalProvider); activeResourceService.verifyAll(); terminalService.verify((t) => t.show(false), TypeMoq.Times.once()); }); suite('terminal.activateCurrentTerminal setting', () => { let pythonSettings: TypeMoq.IMock<IPythonSettings>; let terminalSettings: TypeMoq.IMock<ITerminalSettings>; let configService: TypeMoq.IMock<IConfigurationService>; let terminalActivator: TypeMoq.IMock<ITerminalActivator>; let terminal: TypeMoq.IMock<Terminal>; setup(() => { configService = TypeMoq.Mock.ofType<IConfigurationService>(); serviceContainer .setup((c) => c.get(TypeMoq.It.isValue(IConfigurationService))) .returns(() => configService.object); pythonSettings = TypeMoq.Mock.ofType<IPythonSettings>(); activeResourceService = TypeMoq.Mock.ofType<IActiveResourceService>(); terminalSettings = TypeMoq.Mock.ofType<ITerminalSettings>(); pythonSettings.setup((s) => s.terminal).returns(() => terminalSettings.object); terminalActivator = TypeMoq.Mock.ofType<ITerminalActivator>(); serviceContainer .setup((c) => c.get(TypeMoq.It.isValue(ITerminalActivator))) .returns(() => terminalActivator.object); serviceContainer .setup((c) => c.get(TypeMoq.It.isValue(IActiveResourceService))) .returns(() => activeResourceService.object); terminal = TypeMoq.Mock.ofType<Terminal>(); terminal.setup((c) => c.creationOptions).returns(() => ({ hideFromUser: false })); }); test('If terminal.activateCurrentTerminal setting is set, provided terminal should be activated', async () => { terminalSettings.setup((t) => t.activateEnvInCurrentTerminal).returns(() => true); configService .setup((c) => c.getSettings(resource)) .returns(() => pythonSettings.object) .verifiable(TypeMoq.Times.once()); activeResourceService .setup((a) => a.getActiveResource()) .returns(() => resource) .verifiable(TypeMoq.Times.once()); terminalProvider = new TerminalProvider(serviceContainer.object); await terminalProvider.initialize(terminal.object); terminalActivator.verify( (a) => a.activateEnvironmentInTerminal(terminal.object, TypeMoq.It.isAny()), TypeMoq.Times.once(), ); configService.verifyAll(); activeResourceService.verifyAll(); }); test('If terminal.activateCurrentTerminal setting is not set, provided terminal should not be activated', async () => { terminalSettings.setup((t) => t.activateEnvInCurrentTerminal).returns(() => false); configService .setup((c) => c.getSettings(resource)) .returns(() => pythonSettings.object) .verifiable(TypeMoq.Times.once()); activeResourceService .setup((a) => a.getActiveResource()) .returns(() => resource) .verifiable(TypeMoq.Times.once()); terminalProvider = new TerminalProvider(serviceContainer.object); await terminalProvider.initialize(terminal.object); terminalActivator.verify( (a) => a.activateEnvironmentInTerminal(TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.never(), ); activeResourceService.verifyAll(); configService.verifyAll(); }); test('If terminal.activateCurrentTerminal setting is set, but hideFromUser is true, provided terminal should not be activated', async () => { terminalSettings.setup((t) => t.activateEnvInCurrentTerminal).returns(() => true); configService .setup((c) => c.getSettings(resource)) .returns(() => pythonSettings.object) .verifiable(TypeMoq.Times.once()); activeResourceService .setup((a) => a.getActiveResource()) .returns(() => resource) .verifiable(TypeMoq.Times.once()); terminal.setup((c) => c.creationOptions).returns(() => ({ hideFromUser: true })); terminalProvider = new TerminalProvider(serviceContainer.object); await terminalProvider.initialize(terminal.object); terminalActivator.verify( (a) => a.activateEnvironmentInTerminal(TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.never(), ); activeResourceService.verifyAll(); configService.verifyAll(); }); test('terminal.activateCurrentTerminal setting is set but provided terminal is undefined', async () => { terminalSettings.setup((t) => t.activateEnvInCurrentTerminal).returns(() => true); configService .setup((c) => c.getSettings(resource)) .returns(() => pythonSettings.object) .verifiable(TypeMoq.Times.once()); activeResourceService .setup((a) => a.getActiveResource()) .returns(() => resource) .verifiable(TypeMoq.Times.once()); terminalProvider = new TerminalProvider(serviceContainer.object); await terminalProvider.initialize(undefined); terminalActivator.verify( (a) => a.activateEnvironmentInTerminal(TypeMoq.It.isAny(), TypeMoq.It.isAny()), TypeMoq.Times.never(), ); activeResourceService.verifyAll(); configService.verifyAll(); }); test('Exceptions are swallowed if initializing terminal provider fails', async () => { terminalSettings.setup((t) => t.activateEnvInCurrentTerminal).returns(() => true); configService.setup((c) => c.getSettings(resource)).throws(new Error('Kaboom')); activeResourceService.setup((a) => a.getActiveResource()).returns(() => resource); terminalProvider = new TerminalProvider(serviceContainer.object); try { await terminalProvider.initialize(undefined); } catch (ex) { assert(false, `No error should be thrown, ${ex}`); } }); }); });
the_stack
import { applyBindings } from '@tko/bind' import { observable, observableArray } from '@tko/observable' import { DataBindProvider } from '@tko/provider.databind' import { options } from '@tko/utils' import { bindings as templateBindings, renderTemplate, anonymousTemplate } from '../dist' import { bindings as coreBindings } from '@tko/binding.core' import '@tko/utils/helpers/jasmine-13-helper' describe('Native template engine', function () { function ensureNodeExistsAndIsEmpty (id, tagName, type) { var existingNode = document.getElementById(id) if (existingNode != null) { existingNode.parentNode.removeChild(existingNode) } var resultNode = document.createElement(tagName || 'div') resultNode.id = id if (type) { resultNode.setAttribute('type', type) } document.body.appendChild(resultNode) return resultNode } beforeEach(jasmine.prepareTestNode) beforeEach(function () { var provider = new DataBindProvider() options.bindingProviderInstance = provider provider.bindingHandlers.set(coreBindings) provider.bindingHandlers.set(templateBindings) }) describe('Named templates', function () { function testRenderTemplate (templateElem, templateElemId, templateElementProp) { templateElementProp || (templateElementProp = 'innerHTML') templateElem[templateElementProp] = "name: <div data-bind='text: name'></div>" renderTemplate(templateElemId, { name: 'bert' }, null, testNode) expect(testNode).toContainHtml('name: <div data-bind="text: name">bert</div>') // A second render also works renderTemplate(templateElemId, { name: 'tom' }, null, testNode) expect(testNode).toContainHtml('name: <div data-bind="text: name">tom</div>') // A change to the element contents is picked up templateElem[templateElementProp] = "welcome <div data-bind='text: name'></div>" renderTemplate(templateElemId, { name: 'dave' }, null, testNode) expect(testNode).toContainHtml('welcome <div data-bind="text: name">dave</div>') } it('can display static content from regular DOM element', function () { var testDivTemplate = ensureNodeExistsAndIsEmpty('testDivTemplate') testDivTemplate.innerHTML = 'this is some static content' renderTemplate('testDivTemplate', null, null, testNode) expect(testNode).toContainHtml('this is some static content') }) it('can fetch template from regular DOM element and data-bind on results', function () { var testDivTemplate = ensureNodeExistsAndIsEmpty('testDivTemplate') testRenderTemplate(testDivTemplate, 'testDivTemplate') }) it('can fetch template from <script> elements and data-bind on results', function () { var testScriptTemplate = ensureNodeExistsAndIsEmpty('testScriptTemplate', 'script', 'text/html') testRenderTemplate(testScriptTemplate, 'testScriptTemplate', 'text') }) it('can fetch template from <textarea> elements and data-bind on results', function () { var testTextAreaTemplate = ensureNodeExistsAndIsEmpty('testTextAreaTemplate', 'textarea'), prop = 'value' testRenderTemplate(testTextAreaTemplate, 'testTextAreaTemplate', prop) }) it('can fetch template from <template> elements and data-bind on results', function () { var testTemplateTemplate = ensureNodeExistsAndIsEmpty('testTemplateTemplate', 'template') testRenderTemplate(testTemplateTemplate, 'testTemplateTemplate') }) }) describe('Anonymous templates', function () { it('can display static content', function () { new anonymousTemplate(testNode).text('this is some static content') testNode.innerHTML = 'irrelevant initial content' renderTemplate(testNode, null, null, testNode) expect(testNode).toContainHtml('this is some static content') }) it('can data-bind on results', function () { new anonymousTemplate(testNode).text("name: <div data-bind='text: name'></div>") testNode.innerHTML = 'irrelevant initial content' renderTemplate(testNode, { name: 'bert' }, null, testNode) expect(testNode).toContainHtml('name: <div data-bind="text: name">bert</div>') }) it('can be supplied by not giving a template name', function () { testNode.innerHTML = "<div data-bind='template: { data: someItem }'>Value: <span data-bind='text: val'></span></div>" var viewModel = { someItem: { val: 'abc' } } applyBindings(viewModel, testNode) expect(testNode.childNodes[0]).toContainText('Value: abc') }) it('work in conjunction with foreach', function () { testNode.innerHTML = "<div data-bind='template: { foreach: myItems }'><b>Item: <span data-bind='text: itemProp'></span></b></div>" var myItems = observableArray([{ itemProp: 'Alpha' }, { itemProp: 'Beta' }, { itemProp: 'Gamma' }]) applyBindings({ myItems: myItems }, testNode) expect(testNode.childNodes[0].childNodes[0]).toContainText('Item: Alpha') expect(testNode.childNodes[0].childNodes[1]).toContainText('Item: Beta') expect(testNode.childNodes[0].childNodes[2]).toContainText('Item: Gamma') // Can cause re-rendering myItems.push({ itemProp: 'Pushed' }) expect(testNode.childNodes[0].childNodes[0]).toContainText('Item: Alpha') expect(testNode.childNodes[0].childNodes[1]).toContainText('Item: Beta') expect(testNode.childNodes[0].childNodes[2]).toContainText('Item: Gamma') expect(testNode.childNodes[0].childNodes[3]).toContainText('Item: Pushed') myItems.splice(1, 1) expect(testNode.childNodes[0].childNodes[0]).toContainText('Item: Alpha') expect(testNode.childNodes[0].childNodes[1]).toContainText('Item: Gamma') expect(testNode.childNodes[0].childNodes[2]).toContainText('Item: Pushed') }) it('may be nested', function () { testNode.innerHTML = "<div data-bind='template: { foreach: items }'>" + "<div data-bind='template: { foreach: children }'>" + "(Val: <span data-bind='text: $data'></span>, Invocations: <span data-bind='text: $root.invocationCount()'></span>, Parents: <span data-bind='text: $parents.length'></span>)" + '</div>' + '</div>' var viewModel = { invocations: 0, // Verifying # invocations to be sure we're not rendering anything multiple times and discarding the results items: observableArray([{ children: observableArray(['A1', 'A2', 'A3']) }, { children: observableArray(['B1', 'B2']) }]) } viewModel.invocationCount = function () { return ++this.invocations }.bind(viewModel) applyBindings(viewModel, testNode) expect(testNode.childNodes[0].childNodes[0]).toContainText('(Val: A1, Invocations: 1, Parents: 2)(Val: A2, Invocations: 2, Parents: 2)(Val: A3, Invocations: 3, Parents: 2)') expect(testNode.childNodes[0].childNodes[1]).toContainText('(Val: B1, Invocations: 4, Parents: 2)(Val: B2, Invocations: 5, Parents: 2)') // Check we can insert without causing anything else to rerender viewModel.items()[1].children.unshift('ANew') expect(testNode.childNodes[0].childNodes[0]).toContainText('(Val: A1, Invocations: 1, Parents: 2)(Val: A2, Invocations: 2, Parents: 2)(Val: A3, Invocations: 3, Parents: 2)') expect(testNode.childNodes[0].childNodes[1]).toContainText('(Val: ANew, Invocations: 6, Parents: 2)(Val: B1, Invocations: 4, Parents: 2)(Val: B2, Invocations: 5, Parents: 2)') }) it('re-renders nested templates', function () { var node = document.createElement('div') let inner = 0 let outer = 0 node.innerHTML = ` <div data-bind='template: { data: x }'> <i data-bind='incrementInner'></i> <div data-bind='template: { data: $parent.y }'> <i data-bind='incrementOuter'></i> </div> </div> ` options.bindingProviderInstance.bindingHandlers.set('incrementOuter', () => outer++) options.bindingProviderInstance.bindingHandlers.set('incrementInner', () => inner++) const x = observable() const y = observable() applyBindings({ x, y }, node) expect(inner).toEqual(1) expect(outer).toEqual(1) x('a') expect(inner).toEqual(2) expect(outer).toEqual(2) y('a') expect(inner).toEqual(2) expect(outer).toEqual(3) }) it('with no content should be rejected', function () { window.testDivTemplate.innerHTML = "<div data-bind='template: { data: someItem }'></div>" var viewModel = { someItem: { val: 'abc' } } expect(function () { applyBindings(viewModel, window.testDivTemplate) }).toThrowContaining('no template content') }) }) describe('Data-bind syntax', function () { it('should expose parent binding context as $parent if binding with an explicit \"data\" value', function () { testNode.innerHTML = "<div data-bind='template: { data: someItem }'>" + "ValueBound: <span data-bind='text: $parent.parentProp'></span>" + '</div>' applyBindings({ someItem: {}, parentProp: 'Hello' }, testNode) expect(testNode.childNodes[0]).toContainText('ValueBound: Hello') }) it('should expose all ancestor binding contexts as $parents, with top frame also given as $root', function () { testNode.innerHTML = "<div data-bind='template: { data: outerItem }'>" + "<div data-bind='template: { data: middleItem }'>" + "<div data-bind='template: { data: innerItem }'>(" + "data: <span data-bind='text: $data.val'></span>, " + "parent: <span data-bind='text: $parent.val'></span>, " + "parents[0]: <span data-bind='text: $parents[0].val'></span>, " + "parents[1]: <span data-bind='text: $parents[1].val'></span>, " + "parents.length: <span data-bind='text: $parents.length'></span>, " + "root: <span data-bind='text: $root.val'></span>" + ')</div>' + '</div>' + '</div>' applyBindings({ val: 'ROOT', outerItem: { val: 'OUTER', middleItem: { val: 'MIDDLE', innerItem: { val: 'INNER' } } } }, testNode) expect(testNode.childNodes[0].childNodes[0].childNodes[0]).toContainText('(data: INNER, parent: MIDDLE, parents[0]: MIDDLE, parents[1]: OUTER, parents.length: 3, root: ROOT)') }) }) })
the_stack
import {Connection} from "../connection/Connection"; import {ObjectLiteral} from "../common/ObjectLiteral"; import {QueryRunner} from "../query-runner/QueryRunner"; import {RelationMetadata} from "../metadata/RelationMetadata"; /** * Wraps entities and creates getters/setters for their relations * to be able to lazily load relations when accessing these relations. */ export class RelationLoader { // ------------------------------------------------------------------------- // Constructor // ------------------------------------------------------------------------- constructor(private connection: Connection) { } // ------------------------------------------------------------------------- // Public Methods // ------------------------------------------------------------------------- /** * Loads relation data for the given entity and its relation. */ load(relation: RelationMetadata, entityOrEntities: ObjectLiteral|ObjectLiteral[], queryRunner?: QueryRunner): Promise<any[]> { // todo: check all places where it uses non array if (queryRunner && queryRunner.isReleased) queryRunner = undefined; // get new one if already closed if (relation.isManyToOne || relation.isOneToOneOwner) { return this.loadManyToOneOrOneToOneOwner(relation, entityOrEntities, queryRunner); } else if (relation.isOneToMany || relation.isOneToOneNotOwner) { return this.loadOneToManyOrOneToOneNotOwner(relation, entityOrEntities, queryRunner); } else if (relation.isManyToManyOwner) { return this.loadManyToManyOwner(relation, entityOrEntities, queryRunner); } else { // many-to-many non owner return this.loadManyToManyNotOwner(relation, entityOrEntities, queryRunner); } } /** * Loads data for many-to-one and one-to-one owner relations. * * (ow) post.category<=>category.post * loaded: category from post * example: SELECT category.id AS category_id, category.name AS category_name FROM category category * INNER JOIN post Post ON Post.category=category.id WHERE Post.id=1 */ loadManyToOneOrOneToOneOwner(relation: RelationMetadata, entityOrEntities: ObjectLiteral|ObjectLiteral[], queryRunner?: QueryRunner): Promise<any> { const entities = Array.isArray(entityOrEntities) ? entityOrEntities : [entityOrEntities]; const columns = relation.entityMetadata.primaryColumns; const joinColumns = relation.isOwning ? relation.joinColumns : relation.inverseRelation!.joinColumns; const conditions = joinColumns.map(joinColumn => { return `${relation.entityMetadata.name}.${joinColumn.propertyName} = ${relation.propertyName}.${joinColumn.referencedColumn!.propertyName}`; }).join(" AND "); const joinAliasName = relation.entityMetadata.name; const qb = this.connection .createQueryBuilder(queryRunner) .select(relation.propertyName) // category .from(relation.type, relation.propertyName) // Category, category .innerJoin(relation.entityMetadata.target as Function, joinAliasName, conditions); if (columns.length === 1) { qb.where(`${joinAliasName}.${columns[0].propertyPath} IN (:...${joinAliasName + "_" + columns[0].propertyName})`); qb.setParameter(joinAliasName + "_" + columns[0].propertyName, entities.map(entity => columns[0].getEntityValue(entity))); } else { const condition = entities.map((entity, entityIndex) => { return columns.map((column, columnIndex) => { const paramName = joinAliasName + "_entity_" + entityIndex + "_" + columnIndex; qb.setParameter(paramName, column.getEntityValue(entity)); return joinAliasName + "." + column.propertyPath + " = :" + paramName; }).join(" AND "); }).map(condition => "(" + condition + ")").join(" OR "); qb.where(condition); } return qb.getMany(); // return qb.getOne(); todo: fix all usages } /** * Loads data for one-to-many and one-to-one not owner relations. * * SELECT post * FROM post post * WHERE post.[joinColumn.name] = entity[joinColumn.referencedColumn] */ loadOneToManyOrOneToOneNotOwner(relation: RelationMetadata, entityOrEntities: ObjectLiteral|ObjectLiteral[], queryRunner?: QueryRunner): Promise<any> { const entities = Array.isArray(entityOrEntities) ? entityOrEntities : [entityOrEntities]; const aliasName = relation.propertyName; const columns = relation.inverseRelation!.joinColumns; const qb = this.connection .createQueryBuilder(queryRunner) .select(aliasName) .from(relation.inverseRelation!.entityMetadata.target, aliasName); if (columns.length === 1) { qb.where(`${aliasName}.${columns[0].propertyPath} IN (:...${aliasName + "_" + columns[0].propertyName})`); qb.setParameter(aliasName + "_" + columns[0].propertyName, entities.map(entity => columns[0].referencedColumn!.getEntityValue(entity))); } else { const condition = entities.map((entity, entityIndex) => { return columns.map((column, columnIndex) => { const paramName = aliasName + "_entity_" + entityIndex + "_" + columnIndex; qb.setParameter(paramName, column.referencedColumn!.getEntityValue(entity)); return aliasName + "." + column.propertyPath + " = :" + paramName; }).join(" AND "); }).map(condition => "(" + condition + ")").join(" OR "); qb.where(condition); } return qb.getMany(); // return relation.isOneToMany ? qb.getMany() : qb.getOne(); todo: fix all usages } /** * Loads data for many-to-many owner relations. * * SELECT category * FROM category category * INNER JOIN post_categories post_categories * ON post_categories.postId = :postId * AND post_categories.categoryId = category.id */ loadManyToManyOwner(relation: RelationMetadata, entityOrEntities: ObjectLiteral|ObjectLiteral[], queryRunner?: QueryRunner): Promise<any> { const entities = Array.isArray(entityOrEntities) ? entityOrEntities : [entityOrEntities]; const mainAlias = relation.propertyName; const joinAlias = relation.junctionEntityMetadata!.tableName; const joinColumnConditions = relation.joinColumns.map(joinColumn => { return `${joinAlias}.${joinColumn.propertyName} IN (:...${joinColumn.propertyName})`; }); const inverseJoinColumnConditions = relation.inverseJoinColumns.map(inverseJoinColumn => { return `${joinAlias}.${inverseJoinColumn.propertyName}=${mainAlias}.${inverseJoinColumn.referencedColumn!.propertyName}`; }); const parameters = relation.joinColumns.reduce((parameters, joinColumn) => { parameters[joinColumn.propertyName] = entities.map(entity => joinColumn.referencedColumn!.getEntityValue(entity)); return parameters; }, {} as ObjectLiteral); return this.connection .createQueryBuilder(queryRunner) .select(mainAlias) .from(relation.type, mainAlias) .innerJoin(joinAlias, joinAlias, [...joinColumnConditions, ...inverseJoinColumnConditions].join(" AND ")) .setParameters(parameters) .getMany(); } /** * Loads data for many-to-many not owner relations. * * SELECT post * FROM post post * INNER JOIN post_categories post_categories * ON post_categories.postId = post.id * AND post_categories.categoryId = post_categories.categoryId */ loadManyToManyNotOwner(relation: RelationMetadata, entityOrEntities: ObjectLiteral|ObjectLiteral[], queryRunner?: QueryRunner): Promise<any> { const entities = Array.isArray(entityOrEntities) ? entityOrEntities : [entityOrEntities]; const mainAlias = relation.propertyName; const joinAlias = relation.junctionEntityMetadata!.tableName; const joinColumnConditions = relation.inverseRelation!.joinColumns.map(joinColumn => { return `${joinAlias}.${joinColumn.propertyName} = ${mainAlias}.${joinColumn.referencedColumn!.propertyName}`; }); const inverseJoinColumnConditions = relation.inverseRelation!.inverseJoinColumns.map(inverseJoinColumn => { return `${joinAlias}.${inverseJoinColumn.propertyName} IN (:...${inverseJoinColumn.propertyName})`; }); const parameters = relation.inverseRelation!.inverseJoinColumns.reduce((parameters, joinColumn) => { parameters[joinColumn.propertyName] = entities.map(entity => joinColumn.referencedColumn!.getEntityValue(entity)); return parameters; }, {} as ObjectLiteral); return this.connection .createQueryBuilder(queryRunner) .select(mainAlias) .from(relation.type, mainAlias) .innerJoin(joinAlias, joinAlias, [...joinColumnConditions, ...inverseJoinColumnConditions].join(" AND ")) .setParameters(parameters) .getMany(); } /** * Wraps given entity and creates getters/setters for its given relation * to be able to lazily load data when accessing this relation. */ enableLazyLoad(relation: RelationMetadata, entity: ObjectLiteral, queryRunner?: QueryRunner) { const relationLoader = this; const dataIndex = "__" + relation.propertyName + "__"; // in what property of the entity loaded data will be stored const promiseIndex = "__promise_" + relation.propertyName + "__"; // in what property of the entity loading promise will be stored const resolveIndex = "__has_" + relation.propertyName + "__"; // indicates if relation data already was loaded or not, we need this flag if loaded data is empty const setData = (entity: ObjectLiteral, value: any) => { entity[dataIndex] = value; entity[resolveIndex] = true; delete entity[promiseIndex]; return value; }; const setPromise = (entity: ObjectLiteral, value: Promise<any>) => { delete entity[resolveIndex]; delete entity[dataIndex]; entity[promiseIndex] = value; value.then( // ensure different value is not assigned yet result => entity[promiseIndex] === value ? setData(entity, result) : result ); return value; }; Object.defineProperty(entity, relation.propertyName, { get: function() { if (this[resolveIndex] === true || this[dataIndex] !== undefined) // if related data already was loaded then simply return it return Promise.resolve(this[dataIndex]); if (this[promiseIndex]) // if related data is loading then return a promise relationLoader loads it return this[promiseIndex]; // nothing is loaded yet, load relation data and save it in the model once they are loaded const loader = relationLoader.load(relation, this, queryRunner).then( result => relation.isOneToOne || relation.isManyToOne ? (result.length === 0 ? null : result[0]) : result ); return setPromise(this, loader); }, set: function(value: any|Promise<any>) { if (value instanceof Promise) { // if set data is a promise then wait for its resolve and save in the object setPromise(this, value); } else { // if its direct data set (non promise, probably not safe-typed) setData(this, value); } }, configurable: true }); } }
the_stack
import { browserVersion, isChrome, isMobile } from '@/ts/utils/runtimeConsts'; import { sub } from '@/ts/instances/subInstance'; import Subscription from '@/ts/classes/Subscription'; import { CallsInfoModel, IncomingCallModel } from '@/ts/types/model'; import { BooleanIdentifier, JsAudioAnalyzer, MediaIdentifier, NumberIdentifier, SetDevices, VideoType } from '@/ts/types/types'; import { CHROME_EXTENSION_ID, CHROME_EXTENSION_URL } from '@/ts/utils/consts'; import { extractError, getChromeVersion } from '@/ts/utils/pureFunctions'; import { createMicrophoneLevelVoice, getAverageAudioLevel, removeAudioProcesssor } from '@/ts/utils/audioprocc'; import CallSenderPeerConnection from '@/ts/webrtc/call/CallSenderPeerConnection'; import CallReceiverPeerConnection from '@/ts/webrtc/call/CallReceiverPeerConnection'; import { CallStatus, HandlerType, HandlerTypes } from '@/ts/types/messages/baseMessagesInterfaces'; import { AcceptCallMessage, OfferCall, ReplyCallMessage } from '@/ts/types/messages/wsInMessages'; import { ChangeStreamMessage, CheckTransferDestroy, ConnectToRemoteMessage, DestroyPeerConnectionMessage, RouterNavigateMessage } from '@/ts/types/messages/innerMessages'; import { FileAndCallTransfer } from '@/ts/webrtc/FileAndCallTransfer'; import { stopVideo } from '@/ts/utils/htmlApi'; export default class CallHandler extends FileAndCallTransfer { protected readonly handlers: HandlerTypes<keyof CallHandler, 'webrtcTransfer:*'> = { answerCall: this.answerCall, videoAnswerCall: this.videoAnswerCall, declineCall: this.declineCall, replyCall: <HandlerType<'replyCall', 'webrtcTransfer:*'>>this.replyCall, acceptCall: <HandlerType<'acceptCall', 'webrtcTransfer:*'>>this.acceptCall, checkTransferDestroy: <HandlerType<'checkTransferDestroy', 'webrtcTransfer:*'>>this.checkTransferDestroy }; private canvas: HTMLCanvasElement|null = null; private localStream: MediaStream | null = null; private audioProcessor: JsAudioAnalyzer | null = null; private callStatus: CallStatus = 'not_inited'; private acceptedPeers: string[] = []; private get callInfo(): CallsInfoModel { return this.store.roomsDict[this.roomId].callInfo; } public checkTransferDestroy(payload: CheckTransferDestroy) { this.removeOpponent(payload.wsOpponentId); super.checkTransferDestroy(payload); } public inflateDevices(devices: MediaDeviceInfo[]): void { let n: number, k: number, c: number = 0; const microphones: { [id: string]: string } = {}; const speakers: { [id: string]: string } = {}; const webcams: { [id: string]: string } = {}; const payload: SetDevices = { microphones, webcams, speakers, roomId: this.roomId }; if (devices) { devices.forEach((device: MediaDeviceInfo) => { switch (device.kind) { case 'audioinput': microphones[device.deviceId] = device.label || 'Microphone ' + (++n); break; case 'audiooutput': speakers[device.deviceId] = device.label || 'Speaker ' + (++k); break; case 'videoinput': webcams[device.deviceId] = device.label || 'Camera ' + (++c); } }); } this.store.setDevices(payload); } public getConnectionId(): string | null { return this.connectionId; } public acceptCall(message: AcceptCallMessage) { if (this.callStatus !== 'received_offer') { // if we're call initiator if (!this.connectionId) { throw Error('Conn is is null'); } const payload: ConnectToRemoteMessage = { action: 'connectToRemote', handler: Subscription.getPeerConnectionId(this.connectionId, message.opponentWsId), stream: this.localStream }; sub.notify(payload); } else { this.acceptedPeers.push(message.opponentWsId); } } public async getDesktopShareFromExtension(): Promise<string> { if (!isChrome) { throw new Error('ScreenCast feature is only available from chrome atm'); } else if (isMobile) { throw new Error('ScreenCast is not available for mobile phones yet'); } else { await this.pingExtension(); this.logger.log('Ping to extension succeeded')(); const response = await new Promise<{streamId: string; data: string}>((resolve, reject) => { chrome.runtime.sendMessage(CHROME_EXTENSION_ID, {type: 'PYCHAT_SCREEN_SHARE_REQUEST'}, resolve); }); if (response && response.data === 'success') { this.logger.log('Getting desktop share succeeded')(); return response.streamId; } else { throw new Error('Failed to capture desktop stream'); } } } public async captureInput(): Promise<MediaStream|null> { this.logger.debug('capturing input')(); // start // we can't await promise one by one // because 2nd promise would be called after some period of time // which would destroy user gesture Event. // and browsers like safari won't let capture userMedia w/o existing user gesture let micPromise = this.captureMic(); let shareScreenPromise = this.captureScreenShare(); let painterPromise = this.capturePainterShare(); // end let streams: (MediaStream|null)[] = await Promise.all([micPromise, shareScreenPromise, painterPromise]); let stream = this.combineStreams(...streams) return stream; } public processAudio(audioProc: JsAudioAnalyzer) { return () => { if (!this.callInfo.showMic) { return; } if (audioProc.volumeValuesCount < 101) { audioProc.prevVolumeValues += getAverageAudioLevel(audioProc); audioProc.volumeValuesCount++; if (audioProc.volumeValuesCount === 100 && audioProc.prevVolumeValues === 0) { let url = isChrome ? 'setting in chrome://settings/content' : 'your browser settings'; url += navigator.platform.indexOf('Linux') >= 0 ? '. Open pavucontrol for more info' : ' . Right click on volume icon in system tray -> record devices -> input -> microphone'; this.store.growlError(`Unable to capture input from microphone. Check your microphone connection or ${url}`); } } const payload: NumberIdentifier = { id: this.roomId, state: Math.sqrt(getAverageAudioLevel(audioProc)) }; this.store.setCurrentMicLevel(payload); }; } setCanvasElement(canvas: HTMLCanvasElement) { this.logger.debug('Setting canvas to {}', canvas)(); this.canvas = canvas; } public async toggleDevice(videoType: VideoType) { const track = this.getTrack(videoType); if (track && track.readyState === 'live') { this.logger.log('toggleDevice')(); let state = false; if (videoType === VideoType.AUDIO) { state = this.callInfo.showMic; } else if (videoType === VideoType.SHARE) { state = this.callInfo.shareScreen; } else if (videoType === VideoType.VIDEO) { state = this.callInfo.showVideo; } else if (videoType === VideoType.PAINT) { state = this.callInfo.sharePaint; } track.enabled = state; } else { await this.updateConnection(); } } public async updateConnection() { this.logger.log('updateConnection')(); let stream: MediaStream|null = null; // TODO I removed this if below because otherwise if we created a connection w/o stream (no audio/ web/ share screen) we won't be able to add it in future // find out why this was necessary // if (this.localStream?.active) { try { stream = await this.captureInput(); this.stopLocalStream(); this.attachLocalStream(stream); const message: ChangeStreamMessage = { handler: Subscription.allPeerConnectionsForTransfer(this.connectionId!), action: 'streamChanged', allowZeroSubscribers: true, newStream: stream!, }; sub.notify(message) } catch (e) { this.handleStream(e, stream); } // } } public getTrack(kind: VideoType) { // TODO let track = null; let tracks = []; if (this.localStream) { if (kind === VideoType.VIDEO || kind === VideoType.SHARE || kind === VideoType.PAINT) { tracks = this.localStream.getVideoTracks(); } else if (kind === VideoType.AUDIO) { tracks = this.localStream.getAudioTracks(); } else { throw Error('invalid track name'); } if (tracks.length > 0) { const isShare = tracks[0].isShare; const isCanvas = tracks[0].isCanvas; if (isShare && kind === VideoType.SHARE) { track = tracks[0]; } if (isCanvas && kind === VideoType.PAINT) { track = tracks[0]; } else if (!isShare && !isCanvas && kind === VideoType.VIDEO) { track = tracks[0]; } else if (kind === VideoType.AUDIO) { track = tracks[0]; } } } return track; } // setAudio(value) { // let audioTrack = this.getTrack('audio'); // if (!audioTrack) { // let payload: BooleanIdentifier = { // id: this.roomId, // state: false, // }; // this.store.setMicToState(payload); // } // } public setCallIconsState() { // if (this.callInfo.showMic) { // let audioTrack = this.getTrack('audio'); // if (!audioTrack) { // let payload: BooleanIdentifier = { // id: this.roomId, // state: false, // } // this.store.setMicToState(payload); // } // } // let videoTrack = this.getTrack('video'); // if (this.) // this.setVideo(videoTrack && videoTrack.enabled); // this.setAudio(audioTrack && audioTrack.enabled); // this.setDesktopCapture(this.getTrack('share') != null); // this.autoSetLocalVideoVisibility(); } public async offerCall() { let stream: MediaStream | null = null; try { stream = await this.captureInput(); this.logger.log('got local stream {}', stream)(); if (stream) { this.attachLocalStream(stream); } const payload: BooleanIdentifier = { state: true, id: this.roomId }; this.setCallStatus('sent_offer'); this.store.setCallActiveToState(payload); let e = await this.wsHandler.offerCall(this.roomId, browserVersion); this.setConnectionId(e.connId); } catch (e) { this.handleStream(e, stream); } } public createCallPeerConnection({ opponentWsId, userId }: { opponentWsId: string; userId: number }) { if (sub.getNumberOfSubscribers(Subscription.getPeerConnectionId(this.connectionId!, opponentWsId)) !== 0) { this.logger.warn(`Peer connection ${opponentWsId} won't be created as it's already exists`)(); return } if (opponentWsId > this.wsHandler.getWsConnectionId()) { new CallSenderPeerConnection(this.roomId, this.connectionId!, opponentWsId, userId, this.wsHandler, this.store); } else { new CallReceiverPeerConnection(this.roomId, this.connectionId!, opponentWsId, userId, this.wsHandler, this.store); } } protected setConnectionId(connId: string | null) { if (this.connectionId ) { if (!connId) { sub.unsubscribe(Subscription.getTransferId(this.connectionId), this) } else { this.logger.error('Received new connectionId while old one stil exists')(); } } if (this.connectionId !== connId && connId) { sub.subscribe(Subscription.getTransferId(connId), this); } super.setConnectionId(connId); } public addOpponent(connId: string, userId: number, opponentWsId: string): void { this.logger.debug(`Adding opponent ${connId} ${userId} ${opponentWsId}`)(); this.setConnectionId(connId); this.acceptedPeers.push(opponentWsId); this.createCallPeerConnection({opponentWsId, userId}); this.store.setCallActiveButNotJoinedYet({state: true, id: this.roomId}); } public removeUserOpponent(userId: number): void { this.acceptedPeers = this.acceptedPeers.filter(wsId => parseInt(wsId.split(":")[0], 10) != userId); } public removeOpponent(opponentWsId: string): void { let index = this.acceptedPeers.indexOf(opponentWsId); if (index >= 0) { this.acceptedPeers.splice(index); } if (this.acceptedPeers.length === 0) { this.store.setCallActiveButNotJoinedYet({state: false, id: this.roomId}); } } public replyCall(message: ReplyCallMessage) { this.createCallPeerConnection(message); } public initAndDisplayOffer(message: OfferCall) { this.setCallStatus('received_offer'); if (this.connectionId) { this.logger.error('Old connId still exists {}', this.connectionId)(); } this.setConnectionId(message.connId); this.logger.log('CallHandler initialized')(); this.wsHandler.replyCall(message.connId, browserVersion); const payload2: IncomingCallModel = { connId: message.connId, roomId: message.roomId, userId: message.userId }; this.acceptedPeers.push(message.opponentWsId); this.store.setIncomingCall(payload2); this.createCallPeerConnection(message); } public answerCall() { this.doAnswer(false); } public async doAnswer(withVideo: boolean) { this.store.setIncomingCall(null); this.store.setCallActiveToState({ id: this.roomId, state: true }); this.store.setVideoToState({ type: 'webcam', id: this.roomId, state: withVideo }); this.store.setMicToState({ id: this.roomId, state: true }); this.setCallStatus('accepted'); const stream = await this.captureInput(); this.attachLocalStream(stream); this.wsHandler.acceptCall(this.connectionId!); this.connectToRemote(); let message1: RouterNavigateMessage = { handler: 'router', action: 'navigate', to: `/chat/${this.roomId}` }; sub.notify(message1); } public async joinCall() { this.store.setCallActiveButNotJoinedYet({ id: this.roomId, state: false }); this.store.setCallActiveToState({ id: this.roomId, state: true }); this.setCallStatus('accepted'); const stream = await this.captureInput(); this.attachLocalStream(stream); this.wsHandler.joinCall(this.connectionId!); this.connectToRemote(); } private connectToRemote() { this.acceptedPeers.forEach((e) => { const message: ConnectToRemoteMessage = { action: 'connectToRemote', stream: this.localStream, handler: Subscription.getPeerConnectionId(this.connectionId!, e) }; sub.notify(message); }); } public videoAnswerCall() { this.doAnswer(true); } public destroyAudioProcessor() { if (this.audioProcessor ) { removeAudioProcesssor(this.audioProcessor!); } } public stopLocalStream() { this.destroyAudioProcessor(); stopVideo(this.localStream); } public onDestroy() { this.stopLocalStream(); const payload2: MediaIdentifier = { id: this.roomId, media: null }; this.store.setLocalStreamSrc(payload2); this.setConnectionId(null); const payload: BooleanIdentifier = { state: false, id: this.roomId }; this.store.setCallActiveToState(payload); this.store.setCallActiveButNotJoinedYet({ id: this.roomId, state: false }); this.acceptedPeers.length = 0; // = [] } public declineCall() { this.store.setIncomingCall(null); this.wsHandler.destroyCallConnection(this.connectionId!, 'decline'); this.onDestroy(); } public hangCall() { this.logger.debug('on hangCall called')(); if (this.connectionId) { this.wsHandler.destroyCallConnection(this.connectionId!, 'hangup'); } else { this.logger.warn('Current call doesnt have conenctionId yet, skipping hangup')(); } const hadConnections = this.connectionId && sub.getNumberOfSubscribers(Subscription.allPeerConnectionsForTransfer(this.connectionId!)) > 0; if (hadConnections) { if (!this.connectionId) { this.logger.error(`Can't close connections since it's null`)(); return; } let message: DestroyPeerConnectionMessage = { action: 'destroy', handler: Subscription.allPeerConnectionsForTransfer(this.connectionId!), allowZeroSubscribers: true }; sub.notify(message); } else { this.onDestroy(); } } private async pingExtension(): Promise<void> { return new Promise<void>((resolve, reject) => { const error = {rawError: `To share your screen you need chrome extension.<b> <a href="${CHROME_EXTENSION_URL}" target="_blank">Click to install</a></b>`}; if (chrome.runtime && chrome.runtime.sendMessage) { let triggered = false; const timedCB = setTimeout(function () { !triggered && reject(error); triggered = true; }, 500); chrome.runtime.sendMessage(CHROME_EXTENSION_ID, { type: 'PYCHAT_SCREEN_SHARE_PING' }, (response) => { if (triggered) { this.logger.error('extension responded after timeout')(); } else if (response && response.data === 'success') { clearTimeout(timedCB); resolve(); } else { clearTimeout(timedCB); reject(response && response.data || error); } }); } else { reject(error); } }); } private async captureMic(): Promise<MediaStream|null> { let stream: MediaStream|null = null; let showMic = this.callInfo.showMic; let showVideo = this.callInfo.showVideo; if (showMic || showVideo) { // inflate devices b4 capture, in this case we can disable video if user enabled it but has no webcam if (navigator.mediaDevices.enumerateDevices) { const devices: MediaDeviceInfo[] = await navigator.mediaDevices.enumerateDevices(); this.inflateDevices(devices); if (showMic !== this.callInfo.showMic) { this.store.growlError("Unable to capture audio, because no microphones found") } if (showVideo !== this.callInfo.showVideo) { this.store.growlError("Unable to capture video, because no webcam found") } if (!this.callInfo.showMic && !this.callInfo.showVideo) { return null; //inflate devices could have set them to null if they are absent } } let audio: any = this.callInfo.showMic; if (this.callInfo.currentMic && audio) { audio = {deviceId: this.callInfo.currentMic}; } let video: any = this.callInfo.showVideo; // convert null to bolean, if we pass null to getUserMedia it tries to capture if (this.callInfo.currentWebcam && video) { video = {deviceId: this.callInfo.currentWebcam}; } this.logger.debug('navigator.mediaDevices.getUserMedia({audio, video})')(); stream = await navigator.mediaDevices.getUserMedia({audio, video}); this.logger.debug('navigator.mediaDevices.getUserMedia({audio, video})')(); if (!stream) { throw new Error('Unable to capture stream'); } } return stream; } private async capturePainterShare(): Promise<MediaStream|null> { if (this.callInfo.sharePaint) { // TODO install definitely type // @ts-expect-error if (!this.canvas.captureStream) { throw Error('Current browser doesn\'t support canvas stream'); } // @ts-expect-error let stream = this.canvas.captureStream(); const tracks: any[] = stream.getVideoTracks(); if (!(tracks && tracks.length > 0)) { throw Error('No video tracks from captured from canvas'); } tracks[0].isCanvas = true; return stream; } return null; } private async captureScreenShare(): Promise<MediaStream|null> { let stream: MediaStream|null = null; if (this.callInfo.shareScreen) { const chromeVersion = getChromeVersion(); if (navigator.mediaDevices && navigator.mediaDevices.getDisplayMedia) { this.logger.debug('Getting shareScreen from navigator.getDisplayMedia')(); stream = await navigator.mediaDevices.getDisplayMedia({video: true}); } else { if (chromeVersion && chromeVersion > 70) { this.store.growlInfo('You can now use chrome://flags/#enable-experimental-web-platform-features to share your screen'); } const streamId: string = await this.getDesktopShareFromExtension(); this.logger.debug('Resolving userMedia from dekstopShare')(); stream = await navigator.mediaDevices.getUserMedia(<MediaStreamConstraints><unknown>{ // TODO update ts to support this audio: false, video: { mandatory: { chromeMediaSource: 'desktop', chromeMediaSourceId: streamId, maxWidth: window.screen.width, maxHeight: window.screen.height } } }); } const tracks: any[] = stream.getVideoTracks(); if (!(tracks && tracks.length > 0)) { throw Error('No video tracks from captured screen'); } tracks[0].isShare = true; } return stream; } private combineStreams (...streams: (MediaStream|null)[]): MediaStream|null { let stream: MediaStream|null = null; streams.forEach(s => { if (s) { if (!stream) { stream = s; } else { for (let t of s.getTracks()) { stream.addTrack(t); } } } }); return stream; } private handleStream(e: string, endStream: MediaStream|null) { const what = []; if (this.callInfo.showMic) { what.push('audio'); } if (this.callInfo.showVideo) { what.push('video'); } if (this.callInfo.shareScreen) { what.push('screenshare'); } const message = `<span>Failed to capture ${what.join(', ')} source</span>, because ${extractError(e)}`; stopVideo(endStream); this.store.growlErrorRaw(message); this.logger.error('onFailedCaptureSource {}', e)(); } private attachLocalStream(stream: MediaStream|null) { this.logger.log('Local stream has been attached'); if (stream) { this.localStream = stream; this.audioProcessor = createMicrophoneLevelVoice(stream, this.processAudio.bind(this)); const payload: MediaIdentifier = { id: this.roomId, media: stream }; this.store.setLocalStreamSrc(payload); } this.setCallIconsState(); } private setCallStatus(status: CallStatus) { this.logger.log('Setting call status to {}', status)(); this.callStatus = status; } }
the_stack
import { prefix, triggerEvent, fillParams, calculatePosition, fillEndParams, getRotationRad, getRefTargets, } from "../utils"; import { IObject, hasClass, getRad, throttle, } from "@daybrush/utils"; import { RotatableProps, OnRotateGroup, OnRotateGroupEnd, Renderer, OnRotateGroupStart, OnRotateStart, OnRotate, OnRotateEnd, MoveableClientRect, SnappableProps, SnappableState, MoveableManagerInterface, MoveableGroupInterface, DraggableProps, OnDragStart, } from "../types"; import { triggerChildAbles } from "../groupUtils"; import Draggable from "./Draggable"; import { minus, plus, rotate as rotateMatrix } from "@scena/matrix"; import CustomGesto from "../gesto/CustomGesto"; import { checkSnapRotate } from "./Snappable"; import { fillTransformStartEvent, convertTransformFormat, getRotateDist, getOriginDirection, getDirectionOffset, fillTransformEvent, setDefaultTransformIndex, resolveTransformEvent, getTransformDirection, } from "../gesto/GestoUtils"; import { renderDirectionControls } from "../renderDirections"; /** * @namespace Rotatable * @memberof Moveable * @description Rotatable indicates whether the target can be rotated. */ function setRotateStartInfo( moveable: MoveableManagerInterface<any, any>, datas: IObject<any>, clientX: number, clientY: number, origin: number[], rect: MoveableClientRect) { const n = moveable.state.is3d ? 4 : 3; const nextOrigin = calculatePosition(moveable.state.rootMatrix, origin, n); const startAbsoluteOrigin = plus([rect.left, rect.top], nextOrigin); datas.startAbsoluteOrigin = startAbsoluteOrigin; datas.prevDeg = getRad(startAbsoluteOrigin, [clientX, clientY]) / Math.PI * 180; datas.prevSnapDeg = datas.prevDeg; datas.startDeg = datas.prevDeg; datas.loop = 0; } function getParentDeg( moveable: MoveableManagerInterface<any, any>, moveableRect: any, datas: IObject<any>, parentDist: number, direction: number, startValue: number, ) { const { prevDeg, } = datas; // const absoluteDeg = startValue + parentDist; const dist = checkSnapRotate( moveable, moveableRect, datas.origin, parentDist, ); datas.prevDeg = dist; const delta = dist - prevDeg; return [delta, dist, startValue + dist]; } function getDeg( moveable: MoveableManagerInterface<any, any>, moveableRect: any, datas: IObject<any>, deg: number, direction: number, startValue: number, throttleRotate: number, isSnap?: boolean, ) { const { prevDeg, prevSnapDeg, startDeg, loop: prevLoop, } = datas; if (prevDeg > deg && prevDeg > 270 && deg < 90) { // 360 => 0 ++datas.loop; } else if (prevDeg < deg && prevDeg < 90 && deg > 270) { // 0 => 360 --datas.loop; } const loop = datas.loop; const absolutePrevSnapDeg = prevLoop * 360 + prevSnapDeg - startDeg + startValue; let absoluteDeg = loop * 360 + deg - startDeg + startValue; datas.prevDeg = absoluteDeg - loop * 360 + startDeg - startValue; absoluteDeg = throttle(absoluteDeg, throttleRotate); let dist = direction * (absoluteDeg - startValue); if (isSnap) { dist = checkSnapRotate(moveable, moveableRect, datas.origin, dist); absoluteDeg = dist / direction + startValue; } datas.prevSnapDeg = absoluteDeg - loop * 360 + startDeg - startValue; const delta = direction * (absoluteDeg - absolutePrevSnapDeg); return [delta, dist, startValue + dist]; } function getRotateInfo( moveable: MoveableManagerInterface<any, any>, moveableRect: any, datas: IObject<any>, direction: number, clientX: number, clientY: number, startValue: number, throttleRotate: number, ) { return getDeg( moveable, moveableRect, datas, getRad(datas.startAbsoluteOrigin, [clientX, clientY]) / Math.PI * 180, direction, startValue, throttleRotate, true, ); } export function getReversePositionX(dir: string) { if (dir === "left") { return "right"; } else if (dir === "right") { return "left"; } return dir; } export function getReversePositionY(dir: string) { if (dir === "top") { return "bottom"; } else if (dir === "bottom") { return "top"; } return dir; } export function getRotationPositions( rotationPosition: RotatableProps["rotationPosition"], [pos1, pos2, pos3, pos4]: number[][], direction: number, ) { if (rotationPosition === "none") { return; } const [dir1, dir2] = (rotationPosition || "top").split("-"); let radPoses = [pos1, pos2]; // if (scale[0] < 0) { // dir1 = getReversePositionX(dir1); // dir2 = getReversePositionX(dir2); // } // if (scale[1] < 0) { // dir1 = getReversePositionY(dir1); // dir2 = getReversePositionY(dir2); // } if (dir1 === "left") { radPoses = [pos3, pos1]; } else if (dir1 === "right") { radPoses = [pos2, pos4]; } else if (dir1 === "bottom") { radPoses = [pos4, pos3]; } let pos = [ (radPoses[0][0] + radPoses[1][0]) / 2, (radPoses[0][1] + radPoses[1][1]) / 2, ]; const rad = getRotationRad(radPoses, direction); if (dir2) { const isStart = dir2 === "top" || dir2 === "left"; const isReverse = dir1 === "bottom" || dir1 === "left"; pos = radPoses[(isStart && !isReverse) || (!isStart && isReverse) ? 0 : 1]; } return [pos, rad] as const; } export function dragControlCondition(moveable: MoveableManagerInterface<RotatableProps>, e: any) { if (e.isRequest) { return e.requestAble === "rotatable"; } const target = e.inputEvent.target as HTMLElement; if (hasClass(target, prefix("rotation-control"))) { return true; } const rotationTarget = moveable.props.rotationTarget; if (rotationTarget) { return getRefTargets(rotationTarget, true).some(element => { if (!element) { return false; } return target === element || target.contains(element); }); } return false; } export default { name: "rotatable", canPinch: true, props: { rotatable: Boolean, rotationPosition: String, throttleRotate: Number, renderDirections: Object, rotationTarget: Object, } as const, events: { onRotateStart: "rotateStart", onRotate: "rotate", onRotateEnd: "rotateEnd", onRotateGroupStart: "rotateGroupStart", onRotateGroup: "rotateGroup", onRotateGroupEnd: "rotateGroupEnd", } as const, css: [ `.rotation { position: absolute; height: 40px; width: 1px; transform-origin: 50% 100%; height: calc(40px * var(--zoom)); top: auto; left: 0; bottom: 100%; will-change: transform; } .rotation .rotation-line { display: block; width: 100%; height: 100%; transform-origin: 50% 50%; } .rotation .rotation-control { border-color: #4af; border-color: var(--moveable-color); background:#fff; cursor: alias; }`, ], render(moveable: MoveableManagerInterface<RotatableProps>, React: Renderer): any { const { rotatable, rotationPosition, zoom, renderDirections, } = moveable.props; const { renderPoses, direction, } = moveable.state; if (!rotatable) { return null; } const positions = getRotationPositions(rotationPosition!, renderPoses, direction); const jsxs = []; if (positions) { const [pos, rad] = positions; jsxs.push( <div key="rotation" className={prefix("rotation")} style={{ // tslint:disable-next-line: max-line-length transform: `translate(-50%) translate(${pos[0]}px, ${pos[1]}px) rotate(${rad}rad)`, }}> <div className={prefix("line rotation-line")} style={{ transform: `scaleX(${zoom})`, }}></div> <div className={prefix("control rotation-control")} style={{ transform: `translate(0.5px) scale(${zoom})`, }}></div> </div> ); } if (renderDirections) { jsxs.push(...renderDirectionControls(moveable, [], React)); } return jsxs; }, dragControlCondition, dragControlStart( moveable: MoveableManagerInterface<RotatableProps & SnappableProps & DraggableProps, SnappableState>, e: any) { const { datas, clientX, clientY, parentRotate, parentFlag, isPinch, isRequest, } = e; const { target, left, top, origin, beforeOrigin, direction, beforeDirection, targetTransform, moveableClientRect, } = moveable.state; if (!isRequest && !target) { return false; } const rect = moveable.getRect(); datas.rect = rect; datas.transform = targetTransform; datas.left = left; datas.top = top; datas.fixedPosition = getDirectionOffset(moveable, getOriginDirection(moveable)); datas.absoluteInfo = { origin: rect.origin, startValue: rect.rotation, }; setRotateStartInfo(moveable, datas.absoluteInfo, clientX, clientY, origin, moveableClientRect); if (isRequest || isPinch || parentFlag) { const externalRotate = parentRotate || 0; datas.beforeInfo = { origin: rect.beforeOrigin, prevDeg: externalRotate, startDeg: externalRotate, prevSnapDeg: externalRotate, loop: 0, }; datas.afterInfo = { origin: rect.origin, prevDeg: externalRotate, startDeg: externalRotate, prevSnapDeg: externalRotate, loop: 0, }; } else { datas.beforeInfo = { origin: rect.beforeOrigin }; datas.afterInfo = { origin: rect.origin }; setRotateStartInfo(moveable, datas.beforeInfo, clientX, clientY, beforeOrigin, moveableClientRect); setRotateStartInfo(moveable, datas.afterInfo, clientX, clientY, origin, moveableClientRect); } datas.direction = direction; datas.beforeDirection = beforeDirection; datas.startValue = 0; datas.datas = {}; setDefaultTransformIndex(e, "rotate"); const params = fillParams<OnRotateStart>(moveable, e, { set: (rotatation: number) => { datas.startValue = rotatation * Math.PI / 180; }, ...fillTransformStartEvent(e), dragStart: Draggable.dragStart( moveable, new CustomGesto().dragStart([0, 0], e), ) as OnDragStart | false, }); const result = triggerEvent(moveable, "onRotateStart", params); datas.isRotate = result !== false; moveable.state.snapRenderInfo = { request: e.isRequest, }; return datas.isRotate ? params : false; }, dragControl( moveable: MoveableManagerInterface<RotatableProps & DraggableProps>, e: any, ) { const { datas, clientX, clientY, parentRotate, parentFlag, isPinch, groupDelta } = e; const { beforeDirection, beforeInfo, afterInfo, absoluteInfo, isRotate, startValue, rect, } = datas; if (!isRotate) { return; } resolveTransformEvent(e, "rotate"); const targetDirection = getTransformDirection(e); const direction = beforeDirection * targetDirection; const { throttleRotate = 0, parentMoveable, } = moveable.props; let delta: number; let dist: number; let rotate: number; let beforeDelta: number; let beforeDist: number; let beforeRotate: number; let absoluteDelta: number; let absoluteDist: number; let absoluteRotate: number; const startDeg = 180 / Math.PI * startValue; const absoluteStartDeg = absoluteInfo.startValue; if (!parentFlag && "parentDist" in e) { const parentDist = e.parentDist; [delta, dist, rotate] = getParentDeg(moveable, rect, afterInfo, parentDist, direction, startDeg); [beforeDelta, beforeDist, beforeRotate] = getParentDeg(moveable, rect, beforeInfo, parentDist, beforeDirection, startDeg); [absoluteDelta, absoluteDist, absoluteRotate] = getParentDeg(moveable, rect, absoluteInfo, parentDist, direction, absoluteStartDeg); } else if (isPinch || parentFlag) { [delta, dist, rotate] = getDeg(moveable, rect, afterInfo, parentRotate, direction, startDeg, throttleRotate); [beforeDelta, beforeDist, beforeRotate] = getDeg(moveable, rect, beforeInfo, parentRotate, beforeDirection, startDeg, throttleRotate); [absoluteDelta, absoluteDist, absoluteRotate] = getDeg(moveable, rect, absoluteInfo, parentRotate, direction, absoluteStartDeg, throttleRotate); } else { [delta, dist, rotate] = getRotateInfo(moveable, rect, afterInfo, direction, clientX, clientY, startDeg, throttleRotate); [beforeDelta, beforeDist, beforeRotate] = getRotateInfo( moveable, rect, beforeInfo, beforeDirection, clientX, clientY, startDeg, throttleRotate, ); [absoluteDelta, absoluteDist, absoluteRotate] = getRotateInfo( moveable, rect, absoluteInfo, direction, clientX, clientY, absoluteStartDeg, throttleRotate, ); } if (!absoluteDelta && !delta && !beforeDelta && !parentMoveable) { return; } const nextTransform = convertTransformFormat( datas, `rotate(${rotate}deg)`, `rotate(${dist}deg)`, ); const inverseDist = getRotateDist(moveable, dist, datas.fixedPosition, datas); const inverseDelta = minus( plus(groupDelta || [0, 0], inverseDist), datas.prevInverseDist || [0, 0], ); datas.prevInverseDist = inverseDist; const params = fillParams<OnRotate>(moveable, e, { delta, dist, rotate, beforeDist, beforeDelta, beforeRotate, absoluteDist, absoluteDelta, absoluteRotate, isPinch: !!isPinch, ...fillTransformEvent( moveable, nextTransform, inverseDelta, isPinch, e, ), }); triggerEvent(moveable, "onRotate", params); return params; }, dragControlEnd(moveable: MoveableManagerInterface<RotatableProps>, e: any) { const { datas, isDrag } = e; if (!datas.isRotate) { return false; } datas.isRotate = false; triggerEvent(moveable, "onRotateEnd", fillEndParams<OnRotateEnd>(moveable, e, {})); return isDrag; }, dragGroupControlCondition: dragControlCondition, dragGroupControlStart(moveable: MoveableGroupInterface<any, any>, e: any) { const { datas } = e; const { left: parentLeft, top: parentTop, beforeOrigin: parentBeforeOrigin, } = moveable.state; const params = this.dragControlStart(moveable, e); if (!params) { return false; } params.set(datas.beforeDirection * moveable.rotation); const events = triggerChildAbles( moveable, this, "dragControlStart", e, (child, ev) => { const { left, top, beforeOrigin } = child.state; const childClient = plus( minus([left, top], [parentLeft, parentTop]), minus(beforeOrigin, parentBeforeOrigin), ); ev.datas.groupClient = childClient; return { ...ev, parentRotate: 0 }; }, ); const nextParams: OnRotateGroupStart = { ...params, targets: moveable.props.targets!, events, }; const result = triggerEvent(moveable, "onRotateGroupStart", nextParams); datas.isRotate = result !== false; return datas.isRotate ? params : false; }, dragGroupControl(moveable: MoveableGroupInterface<any, any>, e: any) { const { datas } = e; if (!datas.isRotate) { return; } const params = this.dragControl(moveable, e); if (!params) { return; } const direction = datas.beforeDirection; const parentRotate = params.beforeDist; const deg = params.beforeDelta; const rad = deg / 180 * Math.PI; const events = triggerChildAbles( moveable, this, "dragControl", e, (_, ev) => { const [prevX, prevY] = ev.datas.groupClient; const [clientX, clientY] = rotateMatrix([prevX, prevY], rad * direction); const delta = [clientX - prevX, clientY - prevY]; ev.datas.groupClient = [clientX, clientY]; return { ...ev, parentRotate, groupDelta: delta }; }, ); moveable.rotation = direction * params.beforeRotate; const nextParams: OnRotateGroup = { targets: moveable.props.targets!, events, set: (rotation: number) => { moveable.rotation = rotation; }, ...params, }; triggerEvent(moveable, "onRotateGroup", nextParams); return nextParams; }, dragGroupControlEnd(moveable: MoveableGroupInterface<any, any>, e: any) { const { isDrag, datas } = e; if (!datas.isRotate) { return; } this.dragControlEnd(moveable, e); triggerChildAbles(moveable, this, "dragControlEnd", e); const nextParams = fillEndParams<OnRotateGroupEnd>(moveable, e, { targets: moveable.props.targets!, }); triggerEvent(moveable, "onRotateGroupEnd", nextParams); return isDrag; }, /** * @method Moveable.Rotatable#request * @param {object} [e] - the Resizable's request parameter * @param {number} [e.deltaRotate=0] - delta number of rotation * @param {number} [e.rotate=0] - absolute number of moveable's rotation * @return {Moveable.Requester} Moveable Requester * @example * // Instantly Request (requestStart - request - requestEnd) * moveable.request("rotatable", { deltaRotate: 10 }, true); * * * moveable.request("rotatable", { rotate: 10 }, true); * * // requestStart * const requester = moveable.request("rotatable"); * * // request * requester.request({ deltaRotate: 10 }); * requester.request({ deltaRotate: 10 }); * requester.request({ deltaRotate: 10 }); * * requester.request({ rotate: 10 }); * requester.request({ rotate: 20 }); * requester.request({ rotate: 30 }); * * // requestEnd * requester.requestEnd(); */ request(moveable: MoveableManagerInterface<RotatableProps>) { const datas = {}; let distRotate = 0; const startRotation = moveable.getRotation(); return { isControl: true, requestStart() { return { datas }; }, request(e: IObject<any>) { if ("deltaRotate" in e) { distRotate += e.deltaRotate; } else if ("rotate" in e) { distRotate = e.rotate - startRotation; } return { datas, parentDist: distRotate }; }, requestEnd() { return { datas, isDrag: true }; }, }; }, }; /** * Whether or not target can be rotated. (default: false) * @name Moveable.Rotatable#rotatable * @example * import Moveable from "moveable"; * * const moveable = new Moveable(document.body); * * moveable.rotatable = true; */ /** * You can specify the position of the rotation. (default: "top") * @name Moveable.Rotatable#rotationPosition * @example * import Moveable from "moveable"; * * const moveable = new Moveable(document.body, { * rotationPosition: "top", * }); * * moveable.rotationPosition = "bottom" */ /** * throttle of angle(degree) when rotate. * @name Moveable.Rotatable#throttleRotate * @example * import Moveable from "moveable"; * * const moveable = new Moveable(document.body); * * moveable.throttleRotate = 1; */ /** * When the rotate starts, the rotateStart event is called. * @memberof Moveable.Rotatable * @event rotateStart * @param {Moveable.Rotatable.OnRotateStart} - Parameters for the rotateStart event * @example * import Moveable from "moveable"; * * const moveable = new Moveable(document.body, { rotatable: true }); * moveable.on("rotateStart", ({ target }) => { * console.log(target); * }); */ /** * When rotating, the rotate event is called. * @memberof Moveable.Rotatable * @event rotate * @param {Moveable.Rotatable.OnRotate} - Parameters for the rotate event * @example * import Moveable from "moveable"; * * const moveable = new Moveable(document.body, { rotatable: true }); * moveable.on("rotate", ({ target, transform, dist }) => { * target.style.transform = transform; * }); */ /** * When the rotate finishes, the rotateEnd event is called. * @memberof Moveable.Rotatable * @event rotateEnd * @param {Moveable.Rotatable.OnRotateEnd} - Parameters for the rotateEnd event * @example * import Moveable from "moveable"; * * const moveable = new Moveable(document.body, { rotatable: true }); * moveable.on("rotateEnd", ({ target, isDrag }) => { * console.log(target, isDrag); * }); */ /** * When the group rotate starts, the `rotateGroupStart` event is called. * @memberof Moveable.Rotatable * @event rotateGroupStart * @param {Moveable.Rotatable.OnRotateGroupStart} - Parameters for the `rotateGroupStart` event * @example * import Moveable from "moveable"; * * const moveable = new Moveable(document.body, { * target: [].slice.call(document.querySelectorAll(".target")), * rotatable: true * }); * moveable.on("rotateGroupStart", ({ targets }) => { * console.log("onRotateGroupStart", targets); * }); */ /** * When the group rotate, the `rotateGroup` event is called. * @memberof Moveable.Rotatable * @event rotateGroup * @param {Moveable.Rotatable.OnRotateGroup} - Parameters for the `rotateGroup` event * @example * import Moveable from "moveable"; * * const moveable = new Moveable(document.body, { * target: [].slice.call(document.querySelectorAll(".target")), * rotatable: true * }); * moveable.on("rotateGroup", ({ targets, events }) => { * console.log("onRotateGroup", targets); * events.forEach(ev => { * const target = ev.target; * // ev.drag is a drag event that occurs when the group rotate. * const left = ev.drag.beforeDist[0]; * const top = ev.drag.beforeDist[1]; * const deg = ev.beforeDist; * }); * }); */ /** * When the group rotate finishes, the `rotateGroupEnd` event is called. * @memberof Moveable.Rotatable * @event rotateGroupEnd * @param {Moveable.Rotatable.OnRotateGroupEnd} - Parameters for the `rotateGroupEnd` event * @example * import Moveable from "moveable"; * * const moveable = new Moveable(document.body, { * target: [].slice.call(document.querySelectorAll(".target")), * rotatable: true * }); * moveable.on("rotateGroupEnd", ({ targets, isDrag }) => { * console.log("onRotateGroupEnd", targets, isDrag); * }); */
the_stack
* @packageDocumentation * @hidden */ /* eslint-disable import/no-mutable-exports */ /* eslint-disable @typescript-eslint/restrict-template-expressions */ /* eslint-disable @typescript-eslint/no-unsafe-return */ import { EDITOR, TEST } from 'internal:constants'; import { legacyCC } from '../../core/global-exports'; import { IBaseConstraint, IPointToPointConstraint, IHingeConstraint, IConeTwistConstraint } from '../spec/i-physics-constraint'; import { IBoxShape, ISphereShape, ICapsuleShape, ITrimeshShape, ICylinderShape, IConeShape, ITerrainShape, ISimplexShape, IPlaneShape, IBaseShape, } from '../spec/i-physics-shape'; import { IPhysicsWorld } from '../spec/i-physics-world'; import { IRigidBody } from '../spec/i-rigid-body'; import { errorID, IVec3Like, warn } from '../../core'; import { EColliderType, EConstraintType } from './physics-enum'; import { PhysicsMaterial } from '.'; export type IPhysicsEngineId = 'builtin' | 'cannon.js' | 'ammo.js' | 'physx' | string; interface IPhysicsWrapperObject { PhysicsWorld?: Constructor<IPhysicsWorld>, RigidBody?: Constructor<IRigidBody>, BoxShape?: Constructor<IBoxShape>, SphereShape?: Constructor<ISphereShape>, CapsuleShape?: Constructor<ICapsuleShape>, TrimeshShape?: Constructor<ITrimeshShape>, CylinderShape?: Constructor<ICylinderShape>, ConeShape?: Constructor<IConeShape>, TerrainShape?: Constructor<ITerrainShape>, SimplexShape?: Constructor<ISimplexShape>, PlaneShape?: Constructor<IPlaneShape>, PointToPointConstraint?: Constructor<IPointToPointConstraint>, HingeConstraint?: Constructor<IHingeConstraint>, ConeTwistConstraint?: Constructor<IConeTwistConstraint>, } type IPhysicsBackend = { [key: string]: IPhysicsWrapperObject; } interface IPhysicsSelector { /** * @en * The id of the physics engine being used by the physics system. * @zh * 物理系统正在使用的物理引擎的唯一标志。 */ readonly id: IPhysicsEngineId, /** * @en * The wrapper of the physics engine being used by the physics system. * @zh * 物理系统使用的物理引擎的封装层。 */ readonly wrapper: IPhysicsWrapperObject, /** * @en * All physics engine backends that the physics module has registered. * @zh * 物理模块已注册的所有物理引擎后端。 */ readonly backend: IPhysicsBackend, /** * @en * An instance of the physical world through which you can access the lowlevel objects. * @zh * 物理世界实例,通过它可以访问到底层对象。 */ readonly physicsWorld: IPhysicsWorld | null; /** * @en * To register the backend, the system will use the last backend registered before initialization, * and the registration after that needs to be switched manually. * @zh * 注册后端,系统将使用在初始化前注册的最后一个后端,此后注册的需要手动切换。 */ register: (id: IPhysicsEngineId, wrapper: IPhysicsWrapperObject) => void, /** * @en * Switch to the physics backend corresponding to the id in the registry. * @zh * 切换为注册表里对应 id 的物理后端。 */ switchTo: (id: IPhysicsEngineId) => void, // polyfill [x: string]: any, } function updateLegacyMacro (id: string) { legacyCC._global.CC_PHYSICS_BUILTIN = id === 'builtin'; legacyCC._global.CC_PHYSICS_CANNON = id === 'cannon.js'; legacyCC._global.CC_PHYSICS_AMMO = id === 'ammo.js'; } function register (id: IPhysicsEngineId, wrapper: IPhysicsWrapperObject): void { if (!EDITOR && !TEST) console.info(`[PHYSICS]: register ${id}.`); selector.backend[id] = wrapper; if (!selector.physicsWorld || selector.id === id) { updateLegacyMacro(id); const mutableSelector = selector as Mutable<IPhysicsSelector>; mutableSelector.id = id; mutableSelector.wrapper = wrapper; } } export interface IWorldInitData { gravity: IVec3Like; allowSleep: boolean; defaultMaterial: PhysicsMaterial; } let worldInitData: IWorldInitData | null; function switchTo (id: IPhysicsEngineId) { if (!selector.runInEditor) return; const mutableSelector = selector as Mutable<IPhysicsSelector>; if (selector.physicsWorld && id !== selector.id && selector.backend[id] != null) { selector.physicsWorld.destroy(); if (!TEST) console.info(`[PHYSICS]: switch from ${selector.id} to ${id}.`); updateLegacyMacro(id); mutableSelector.id = id; mutableSelector.wrapper = selector.backend[id]; mutableSelector.physicsWorld = createPhysicsWorld(); } else { if (!EDITOR && !TEST) console.info(`[PHYSICS]: using ${id}.`); mutableSelector.physicsWorld = createPhysicsWorld(); } if (worldInitData) { const world = mutableSelector.physicsWorld; world.setGravity(worldInitData.gravity); world.setAllowSleep(worldInitData.allowSleep); world.setDefaultMaterial(worldInitData.defaultMaterial); } } /** * @en * The physics selector is used to register and switch the physics engine backend. * @zh * 物理选择器用于注册和切换物理引擎后端。 */ export const selector: IPhysicsSelector = { id: '', switchTo, register, wrapper: {} as any, backend: {} as any, physicsWorld: null as any, /// hide for now /// runInEditor: !EDITOR, }; export function constructDefaultWorld (data: IWorldInitData) { if (!worldInitData) worldInitData = data; if (!selector.runInEditor) return; if (!selector.physicsWorld) { if (!TEST) console.info(`[PHYSICS]: using ${selector.id}.`); const mutableSelector = selector as Mutable<IPhysicsSelector>; const world = mutableSelector.physicsWorld = createPhysicsWorld(); world.setGravity(worldInitData.gravity); world.setAllowSleep(worldInitData.allowSleep); world.setDefaultMaterial(worldInitData.defaultMaterial); } } /// Utility Function For Create Wrapper Entity /// const FUNC = (...v: any) => 0 as any; const ENTIRE_WORLD: IPhysicsWorld = { impl: null, setGravity: FUNC, setAllowSleep: FUNC, setDefaultMaterial: FUNC, step: FUNC, syncAfterEvents: FUNC, syncSceneToPhysics: FUNC, raycast: FUNC, raycastClosest: FUNC, emitEvents: FUNC, destroy: FUNC, }; enum ECheckType { World, RigidBody, // COLLIDER // BoxCollider, SphereCollider, CapsuleCollider, MeshCollider, CylinderCollider, ConeCollider, TerrainCollider, SimplexCollider, PlaneCollider, // JOINT // PointToPointConstraint, HingeConstraint, ConeTwistConstraint, } function check (obj: any, type: ECheckType) { if (obj == null) { if (selector.id) { warn(`${selector.id} physics does not support ${ECheckType[type]}`); } else { errorID(9600); } return true; } return false; } export function createPhysicsWorld (): IPhysicsWorld { if (check(selector.wrapper.PhysicsWorld, ECheckType.World)) { return ENTIRE_WORLD; } return new selector.wrapper.PhysicsWorld!(); } const ENTIRE_RIGID_BODY: IRigidBody = { impl: null, rigidBody: null as unknown as any, isAwake: false, isSleepy: false, isSleeping: false, initialize: FUNC, onEnable: FUNC, onDisable: FUNC, onDestroy: FUNC, setType: FUNC, setMass: FUNC, setLinearDamping: FUNC, setAngularDamping: FUNC, useGravity: FUNC, setLinearFactor: FUNC, setAngularFactor: FUNC, setAllowSleep: FUNC, wakeUp: FUNC, sleep: FUNC, clearState: FUNC, clearForces: FUNC, clearVelocity: FUNC, setSleepThreshold: FUNC, getSleepThreshold: FUNC, getLinearVelocity: FUNC, setLinearVelocity: FUNC, getAngularVelocity: FUNC, setAngularVelocity: FUNC, applyForce: FUNC, applyLocalForce: FUNC, applyImpulse: FUNC, applyLocalImpulse: FUNC, applyTorque: FUNC, applyLocalTorque: FUNC, setGroup: FUNC, getGroup: FUNC, addGroup: FUNC, removeGroup: FUNC, setMask: FUNC, getMask: FUNC, addMask: FUNC, removeMask: FUNC, isUsingCCD: FUNC, useCCD: FUNC, }; export function createRigidBody (): IRigidBody { if (check(selector.wrapper.RigidBody, ECheckType.RigidBody)) { return ENTIRE_RIGID_BODY; } return new selector.wrapper.RigidBody!(); } /// CREATE COLLIDER /// const CREATE_COLLIDER_PROXY = { INITED: false }; interface IEntireShape extends IBoxShape, ISphereShape, ICapsuleShape, ITrimeshShape, ICylinderShape, IConeShape, ITerrainShape, ISimplexShape, IPlaneShape { } const ENTIRE_SHAPE: IEntireShape = { impl: null, collider: null as unknown as any, attachedRigidBody: null, initialize: FUNC, onLoad: FUNC, onEnable: FUNC, onDisable: FUNC, onDestroy: FUNC, setGroup: FUNC, getGroup: FUNC, addGroup: FUNC, removeGroup: FUNC, setMask: FUNC, getMask: FUNC, addMask: FUNC, removeMask: FUNC, setMaterial: FUNC, setAsTrigger: FUNC, setCenter: FUNC, getAABB: FUNC, getBoundingSphere: FUNC, updateSize: FUNC, updateRadius: FUNC, setRadius: FUNC, setCylinderHeight: FUNC, setDirection: FUNC, setHeight: FUNC, setShapeType: FUNC, setVertices: FUNC, setMesh: FUNC, setTerrain: FUNC, setNormal: FUNC, setConstant: FUNC, updateEventListener: FUNC, }; export function createShape (type: EColliderType): IBaseShape { initColliderProxy(); return CREATE_COLLIDER_PROXY[type](); } function initColliderProxy () { if (CREATE_COLLIDER_PROXY.INITED) return; CREATE_COLLIDER_PROXY.INITED = true; CREATE_COLLIDER_PROXY[EColliderType.BOX] = function createBoxShape (): IBoxShape { if (check(selector.wrapper.BoxShape, ECheckType.BoxCollider)) { return ENTIRE_SHAPE; } return new selector.wrapper.BoxShape!(); }; CREATE_COLLIDER_PROXY[EColliderType.SPHERE] = function createSphereShape (): ISphereShape { if (check(selector.wrapper.SphereShape, ECheckType.SphereCollider)) { return ENTIRE_SHAPE; } return new selector.wrapper.SphereShape!(); }; CREATE_COLLIDER_PROXY[EColliderType.CAPSULE] = function createCapsuleShape (): ICapsuleShape { if (check(selector.wrapper.CapsuleShape, ECheckType.CapsuleCollider)) { return ENTIRE_SHAPE; } return new selector.wrapper.CapsuleShape!(); }; CREATE_COLLIDER_PROXY[EColliderType.CYLINDER] = function createCylinderShape (): ICylinderShape { if (check(selector.wrapper.CylinderShape, ECheckType.CylinderCollider)) { return ENTIRE_SHAPE; } return new selector.wrapper.CylinderShape!(); }; CREATE_COLLIDER_PROXY[EColliderType.CONE] = function createConeShape (): IConeShape { if (check(selector.wrapper.ConeShape, ECheckType.ConeCollider)) { return ENTIRE_SHAPE; } return new selector.wrapper.ConeShape!(); }; CREATE_COLLIDER_PROXY[EColliderType.MESH] = function createTrimeshShape (): ITrimeshShape { if (check(selector.wrapper.TrimeshShape, ECheckType.MeshCollider)) { return ENTIRE_SHAPE; } return new selector.wrapper.TrimeshShape!(); }; CREATE_COLLIDER_PROXY[EColliderType.TERRAIN] = function createTerrainShape (): ITerrainShape { if (check(selector.wrapper.TerrainShape, ECheckType.TerrainCollider)) { return ENTIRE_SHAPE; } return new selector.wrapper.TerrainShape!(); }; CREATE_COLLIDER_PROXY[EColliderType.SIMPLEX] = function createSimplexShape (): ISimplexShape { if (check(selector.wrapper.SimplexShape, ECheckType.SimplexCollider)) { return ENTIRE_SHAPE; } return new selector.wrapper.SimplexShape!(); }; CREATE_COLLIDER_PROXY[EColliderType.PLANE] = function createPlaneShape (): IPlaneShape { if (check(selector.wrapper.PlaneShape, ECheckType.PlaneCollider)) { return ENTIRE_SHAPE; } return new selector.wrapper.PlaneShape!(); }; } /// CREATE CONSTRAINT /// const CREATE_CONSTRAINT_PROXY = { INITED: false }; interface IEntireConstraint extends IPointToPointConstraint, IHingeConstraint, IConeTwistConstraint { } const ENTIRE_CONSTRAINT: IEntireConstraint = { impl: null, initialize: FUNC, onLoad: FUNC, onEnable: FUNC, onDisable: FUNC, onDestroy: FUNC, setEnableCollision: FUNC, setConnectedBody: FUNC, setPivotA: FUNC, setPivotB: FUNC, setAxis: FUNC, }; export function createConstraint (type: EConstraintType): IBaseConstraint { initConstraintProxy(); return CREATE_CONSTRAINT_PROXY[type](); } function initConstraintProxy () { if (CREATE_CONSTRAINT_PROXY.INITED) return; CREATE_CONSTRAINT_PROXY.INITED = true; CREATE_CONSTRAINT_PROXY[EConstraintType.POINT_TO_POINT] = function createPointToPointConstraint (): IPointToPointConstraint { if (check(selector.wrapper.PointToPointConstraint, ECheckType.PointToPointConstraint)) { return ENTIRE_CONSTRAINT; } return new selector.wrapper.PointToPointConstraint!(); }; CREATE_CONSTRAINT_PROXY[EConstraintType.HINGE] = function createHingeConstraint (): IHingeConstraint { if (check(selector.wrapper.HingeConstraint, ECheckType.HingeConstraint)) { return ENTIRE_CONSTRAINT; } return new selector.wrapper.HingeConstraint!(); }; CREATE_CONSTRAINT_PROXY[EConstraintType.CONE_TWIST] = function createConeTwistConstraint (): IConeTwistConstraint { if (check(selector.wrapper.ConeTwistConstraint, ECheckType.ConeTwistConstraint)) { return ENTIRE_CONSTRAINT; } return new selector.wrapper.ConeTwistConstraint!(); }; }
the_stack
module android.app{ import AndroidUI = androidui.AndroidUI; import View = android.view.View; import ViewGroup = android.view.ViewGroup; import ViewRootImpl = android.view.ViewRootImpl; import KeyEvent = android.view.KeyEvent; import Animation = android.view.animation.Animation; import FrameLayout = android.widget.FrameLayout; import MotionEvent = android.view.MotionEvent; import Window = android.view.Window; import WindowManager = android.view.WindowManager; import LayoutInflater = android.view.LayoutInflater; import Bundle = android.os.Bundle; import Handler = android.os.Handler; import Log = android.util.Log; import Context = android.content.Context; import Intent = android.content.Intent; import Runnable = java.lang.Runnable; export class Activity extends Context implements Window.Callback, KeyEvent.Callback{ private static TAG:string = "Activity"; private static DEBUG_LIFECYCLE:boolean = false; /** Standard activity result: operation canceled. */ static RESULT_CANCELED:number = 0; /** Standard activity result: operation succeeded. */ static RESULT_OK:number = -1; /** Start of user-defined activity results. */ static RESULT_FIRST_USER:number = 1; private mCallActivity:Activity;//activity that launch the activity (will null if restore) private mIntent:Intent; private mCalled:boolean; private mResumed:boolean; private mStopped:boolean; private mFinished:boolean; private mStartedActivity:boolean; private mDestroyed:boolean; private mWindow:Window; private mWindowAdded:boolean = false; private mVisibleFromClient:boolean = true; private mResultCode:number = Activity.RESULT_CANCELED; private mResultData:Intent = null; private mMenu:android.view.Menu; private mMenuPopuoHelper:android.view.menu.MenuPopupHelper; //mHandler:Handler = new Handler(); /** Return the intent that started this activity. */ getIntent():Intent { return this.mIntent; } /** * Change the intent returned by {@link #getIntent}. This holds a * reference to the given intent; it does not copy it. Often used in * conjunction with {@link #onNewIntent}. * * @param newIntent The new Intent object to return from getIntent * * @see #getIntent * @see #onNewIntent */ setIntent(newIntent:Intent):void { this.mIntent = newIntent; } /** Return the application that owns this activity. */ getApplication():android.app.Application { return this.getApplicationContext(); } /** * Retrieve the window manager for showing custom windows. * NOTE: all windows will add to this activity's window. * @see getGlobalWindowManager */ getWindowManager():android.view.WindowManager{ return this.mWindow.getChildWindowManager(); } /** * Retrieve the window manager for application * NOTE: all windows will add to application level, same as activity * @see getWindowManager */ getGlobalWindowManager():android.view.WindowManager{ return this.getApplicationContext().getWindowManager(); } /** * Retrieve the current {@link android.view.Window} for the activity. * This can be used to directly access parts of the Window API that * are not available through Activity/Screen. * * @return Window The current window, or null if the activity is not * visual. */ getWindow():Window { return this.mWindow; } /** * Calls {@link android.view.Window#getCurrentFocus} on the * Window of this Activity to return the currently focused view. * * @return View The current View with focus or null. * * @see #getWindow * @see android.view.Window#getCurrentFocus */ getCurrentFocus():View { return this.mWindow != null ? this.mWindow.getCurrentFocus() : null; } /** * Called when the activity is starting. This is where most initialization * should go: calling {@link #setContentView(int)} to inflate the * activity's UI, using {@link #findViewById} to programmatically interact * with widgets in the UI, calling * {@link #managedQuery(android.net.Uri , String[], String, String[], String)} to retrieve * cursors for data being displayed, etc. * * <p>You can call {@link #finish} from within this function, in * which case onDestroy() will be immediately called without any of the rest * of the activity lifecycle ({@link #onStart}, {@link #onResume}, * {@link #onPause}, etc) executing. * * <p><em>Derived classes must call through to the super class's * implementation of this method. If they do not, an exception will be * thrown.</em></p> * * @param savedInstanceState If the activity is being re-initialized after * previously being shut down then this Bundle contains the data it most * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b> * * @see #onStart * @see #onSaveInstanceState * @see #onRestoreInstanceState * @see #onPostCreate */ protected onCreate(savedInstanceState?:Bundle):void { if (Activity.DEBUG_LIFECYCLE) Log.v(Activity.TAG, "onCreate " + this + ": " + savedInstanceState); //if (this.mLastNonConfigurationInstances != null) { // this.mAllLoaderManagers = this.mLastNonConfigurationInstances.loaders; //} //if (this.mActivityInfo.parentActivityName != null) { // if (this.mActionBar == null) { // this.mEnableDefaultActionBarUp = true; // } else { // this.mActionBar.setDefaultDisplayHomeAsUpEnabled(true); // } //} //if (savedInstanceState != null) { // let p:Parcelable = savedInstanceState.getParcelable(Activity.FRAGMENTS_TAG); // this.mFragments.restoreAllState(p, this.mLastNonConfigurationInstances != null ? this.mLastNonConfigurationInstances.fragments : null); //} //this.mFragments.dispatchCreate(); this.getApplication().dispatchActivityCreated(this, savedInstanceState); this.mCalled = true; } /** * The hook for {@link ActivityThread} to restore the state of this activity. * * Calls {@link #onSaveInstanceState(android.os.Bundle)} and * {@link #restoreManagedDialogs(android.os.Bundle)}. * * @param savedInstanceState contains the saved state */ performRestoreInstanceState(savedInstanceState:Bundle):void { this.onRestoreInstanceState(savedInstanceState); //this.restoreManagedDialogs(savedInstanceState); } /** * This method is called after {@link #onStart} when the activity is * being re-initialized from a previously saved state, given here in * <var>savedInstanceState</var>. Most implementations will simply use {@link #onCreate} * to restore their state, but it is sometimes convenient to do it here * after all of the initialization has been done or to allow subclasses to * decide whether to use your default implementation. The default * implementation of this method performs a restore of any view state that * had previously been frozen by {@link #onSaveInstanceState}. * * <p>This method is called between {@link #onStart} and * {@link #onPostCreate}. * * @param savedInstanceState the data most recently supplied in {@link #onSaveInstanceState}. * * @see #onCreate * @see #onPostCreate * @see #onResume * @see #onSaveInstanceState */ protected onRestoreInstanceState(savedInstanceState:Bundle):void { //TODO restoreHierarchyState? //if (this.mWindow != null) { // let windowState:Bundle = savedInstanceState.getBundle(Activity.WINDOW_HIERARCHY_TAG); // if (windowState != null) { // this.mWindow.restoreHierarchyState(windowState); // } //} } /** * Called when activity start-up is complete (after {@link #onStart} * and {@link #onRestoreInstanceState} have been called). Applications will * generally not implement this method; it is intended for system * classes to do final initialization after application code has run. * * <p><em>Derived classes must call through to the super class's * implementation of this method. If they do not, an exception will be * thrown.</em></p> * * @param savedInstanceState If the activity is being re-initialized after * previously being shut down then this Bundle contains the data it most * recently supplied in {@link #onSaveInstanceState}. <b><i>Note: Otherwise it is null.</i></b> * @see #onCreate */ protected onPostCreate(savedInstanceState:Bundle):void { //if (!this.isChild()) { // this.mTitleReady = true; this.onTitleChanged(this.getTitle()); //} this.mCalled = true; } /** * Called after {@link #onCreate} &mdash; or after {@link #onRestart} when * the activity had been stopped, but is now again being displayed to the * user. It will be followed by {@link #onResume}. * * <p><em>Derived classes must call through to the super class's * implementation of this method. If they do not, an exception will be * thrown.</em></p> * * @see #onCreate * @see #onStop * @see #onResume */ protected onStart():void { if (Activity.DEBUG_LIFECYCLE) Log.v(Activity.TAG, "onStart " + this); this.mCalled = true; //if (!this.mLoadersStarted) { // this.mLoadersStarted = true; // if (this.mLoaderManager != null) { // this.mLoaderManager.doStart(); // } else if (!this.mCheckedForLoaderManager) { // this.mLoaderManager = this.getLoaderManager("(root)", this.mLoadersStarted, false); // } // this.mCheckedForLoaderManager = true; //} this.getApplication().dispatchActivityStarted(this); } /** * Called after {@link #onStop} when the current activity is being * re-displayed to the user (the user has navigated back to it). It will * be followed by {@link #onStart} and then {@link #onResume}. * * <p>For activities that are using raw {@link Cursor} objects (instead of * creating them through * {@link #managedQuery(android.net.Uri , String[], String, String[], String)}, * this is usually the place * where the cursor should be requeried (because you had deactivated it in * {@link #onStop}. * * <p><em>Derived classes must call through to the super class's * implementation of this method. If they do not, an exception will be * thrown.</em></p> * * @see #onStop * @see #onStart * @see #onResume */ protected onRestart():void { this.mCalled = true; } /** * Called after {@link #onRestoreInstanceState}, {@link #onRestart}, or * {@link #onPause}, for your activity to start interacting with the user. * This is a good place to begin animations, open exclusive-access devices * (such as the camera), etc. * * <p>Keep in mind that onResume is not the best indicator that your activity * is visible to the user; a system window such as the keyguard may be in * front. Use {@link #onWindowFocusChanged} to know for certain that your * activity is visible to the user (for example, to resume a game). * * <p><em>Derived classes must call through to the super class's * implementation of this method. If they do not, an exception will be * thrown.</em></p> * * @see #onRestoreInstanceState * @see #onRestart * @see #onPostResume * @see #onPause */ protected onResume():void { if (Activity.DEBUG_LIFECYCLE) Log.v(Activity.TAG, "onResume " + this); this.getApplication().dispatchActivityResumed(this); this.mCalled = true; } /** * Called when activity resume is complete (after {@link #onResume} has * been called). Applications will generally not implement this method; * it is intended for system classes to do final setup after application * resume code has run. * * <p><em>Derived classes must call through to the super class's * implementation of this method. If they do not, an exception will be * thrown.</em></p> * * @see #onResume */ protected onPostResume():void { const win:Window = this.getWindow(); if (win != null) win.makeActive(); //if (this.mActionBar != null) this.mActionBar.setShowHideAnimationEnabled(true); this.mCalled = true; } /** * This is called for activities that set launchMode to "singleTop" in * their package, or if a client used the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} * flag when calling {@link #startActivity}. In either case, when the * activity is re-launched while at the top of the activity stack instead * of a new instance of the activity being started, onNewIntent() will be * called on the existing instance with the Intent that was used to * re-launch it. * * <p>An activity will always be paused before receiving a new intent, so * you can count on {@link #onResume} being called after this method. * * <p>Note that {@link #getIntent} still returns the original Intent. You * can use {@link #setIntent} to update it to this new Intent. * * @param intent The new intent that was started for the activity. * * @see #getIntent * @see #setIntent * @see #onResume */ protected onNewIntent(intent:Intent):void { } /** * The hook for {@link ActivityThread} to save the state of this activity. * * Calls {@link #onSaveInstanceState(android.os.Bundle)} * and {@link #saveManagedDialogs(android.os.Bundle)}. * * @param outState The bundle to save the state to. */ performSaveInstanceState(outState:Bundle):void { this.onSaveInstanceState(outState); //this.saveManagedDialogs(outState); if (Activity.DEBUG_LIFECYCLE) Log.v(Activity.TAG, "onSaveInstanceState " + this + ": " + outState); } /** * Called to retrieve per-instance state from an activity before being killed * so that the state can be restored in {@link #onCreate} or * {@link #onRestoreInstanceState} (the {@link Bundle} populated by this method * will be passed to both). * * <p>This method is called before an activity may be killed so that when it * comes back some time in the future it can restore its state. For example, * if activity B is launched in front of activity A, and at some point activity * A is killed to reclaim resources, activity A will have a chance to save the * current state of its user interface via this method so that when the user * returns to activity A, the state of the user interface can be restored * via {@link #onCreate} or {@link #onRestoreInstanceState}. * * <p>Do not confuse this method with activity lifecycle callbacks such as * {@link #onPause}, which is always called when an activity is being placed * in the background or on its way to destruction, or {@link #onStop} which * is called before destruction. One example of when {@link #onPause} and * {@link #onStop} is called and not this method is when a user navigates back * from activity B to activity A: there is no need to call {@link #onSaveInstanceState} * on B because that particular instance will never be restored, so the * system avoids calling it. An example when {@link #onPause} is called and * not {@link #onSaveInstanceState} is when activity B is launched in front of activity A: * the system may avoid calling {@link #onSaveInstanceState} on activity A if it isn't * killed during the lifetime of B since the state of the user interface of * A will stay intact. * * <p>The default implementation takes care of most of the UI per-instance * state for you by calling {@link android.view.View#onSaveInstanceState()} on each * view in the hierarchy that has an id, and by saving the id of the currently * focused view (all of which is restored by the default implementation of * {@link #onRestoreInstanceState}). If you override this method to save additional * information not captured by each individual view, you will likely want to * call through to the default implementation, otherwise be prepared to save * all of the state of each view yourself. * * <p>If called, this method will occur before {@link #onStop}. There are * no guarantees about whether it will occur before or after {@link #onPause}. * * @param outState Bundle in which to place your saved state. * * @see #onCreate * @see #onRestoreInstanceState * @see #onPause */ protected onSaveInstanceState(outState:Bundle):void { //outState.putBundle(Activity.WINDOW_HIERARCHY_TAG, this.mWindow.saveHierarchyState()); //let p:Parcelable = this.mFragments.saveAllState(); //if (p != null) { // outState.putParcelable(Activity.FRAGMENTS_TAG, p); //} this.getApplication().dispatchActivitySaveInstanceState(this, outState); } /** * Called as part of the activity lifecycle when an activity is going into * the background, but has not (yet) been killed. The counterpart to * {@link #onResume}. * * <p>When activity B is launched in front of activity A, this callback will * be invoked on A. B will not be created until A's {@link #onPause} returns, * so be sure to not do anything lengthy here. * * <p>This callback is mostly used for saving any persistent state the * activity is editing, to present a "edit in place" model to the user and * making sure nothing is lost if there are not enough resources to start * the new activity without first killing this one. This is also a good * place to do things like stop animations and other things that consume a * noticeable amount of CPU in order to make the switch to the next activity * as fast as possible, or to close resources that are exclusive access * such as the camera. * * <p>In situations where the system needs more memory it may kill paused * processes to reclaim resources. Because of this, you should be sure * that all of your state is saved by the time you return from * this function. In general {@link #onSaveInstanceState} is used to save * per-instance state in the activity and this method is used to store * global persistent data (in content providers, files, etc.) * * <p>After receiving this call you will usually receive a following call * to {@link #onStop} (after the next activity has been resumed and * displayed), however in some cases there will be a direct call back to * {@link #onResume} without going through the stopped state. * * <p><em>Derived classes must call through to the super class's * implementation of this method. If they do not, an exception will be * thrown.</em></p> * * @see #onResume * @see #onSaveInstanceState * @see #onStop */ protected onPause():void { if (Activity.DEBUG_LIFECYCLE) Log.v(Activity.TAG, "onPause " + this); this.getApplication().dispatchActivityPaused(this); this.mCalled = true; } /** * AndroidUI:call when app into the background */ protected onUserLeaveHint():void { } /** * Called when you are no longer visible to the user. You will next * receive either {@link #onRestart}, {@link #onDestroy}, or nothing, * depending on later user activity. * * <p>Note that this method may never be called, in low memory situations * where the system does not have enough memory to keep your activity's * process running after its {@link #onPause} method is called. * * <p><em>Derived classes must call through to the super class's * implementation of this method. If they do not, an exception will be * thrown.</em></p> * * @see #onRestart * @see #onResume * @see #onSaveInstanceState * @see #onDestroy */ protected onStop():void { if (Activity.DEBUG_LIFECYCLE) Log.v(Activity.TAG, "onStop " + this); //if (this.mActionBar != null) this.mActionBar.setShowHideAnimationEnabled(false); this.getApplication().dispatchActivityStopped(this); //this.mTranslucentCallback = null; this.mCalled = true; } /** * Perform any final cleanup before an activity is destroyed. This can * happen either because the activity is finishing (someone called * {@link #finish} on it, or because the system is temporarily destroying * this instance of the activity to save space. You can distinguish * between these two scenarios with the {@link #isFinishing} method. * * <p><em>Note: do not count on this method being called as a place for * saving data! For example, if an activity is editing data in a content * provider, those edits should be committed in either {@link #onPause} or * {@link #onSaveInstanceState}, not here.</em> This method is usually implemented to * free resources like threads that are associated with an activity, so * that a destroyed activity does not leave such things around while the * rest of its application is still running. There are situations where * the system will simply kill the activity's hosting process without * calling this method (or any others) in it, so it should not be used to * do things that are intended to remain around after the process goes * away. * * <p><em>Derived classes must call through to the super class's * implementation of this method. If they do not, an exception will be * thrown.</em></p> * * @see #onPause * @see #onStop * @see #finish * @see #isFinishing */ protected onDestroy():void { if (Activity.DEBUG_LIFECYCLE) Log.v(Activity.TAG, "onDestroy " + this); this.mCalled = true; //// dismiss any dialogs we are managing. //if (this.mManagedDialogs != null) { // const numDialogs:number = this.mManagedDialogs.size(); // for (let i:number = 0; i < numDialogs; i++) { // const md:Activity.ManagedDialog = this.mManagedDialogs.valueAt(i); // if (md.mDialog.isShowing()) { // md.mDialog.dismiss(); // } // } // this.mManagedDialogs = null; //} //// close any cursors we are managing. //{ // let numCursors:number = this.mManagedCursors.size(); // for (let i:number = 0; i < numCursors; i++) { // let c:Activity.ManagedCursor = this.mManagedCursors.get(i); // if (c != null) { // c.mCursor.close(); // } // } // this.mManagedCursors.clear(); //} //// Close any open search dialog //if (this.mSearchManager != null) { // this.mSearchManager.stopSearch(); //} this.getApplication().dispatchActivityDestroyed(this); } /** * Finds a view that was identified by the id attribute from the XML that * was processed in {@link #onCreate}. * * @return The view if found or null otherwise. */ findViewById(id:string):View { return this.getWindow().findViewById(id); } /** * Set the activity content to an explicit view. This view is placed * directly into the activity's view hierarchy. It can itself be a complex * view hierarchy. When calling this method, the layout parameters of the * specified view are ignored. Both the width and the height of the view are * set by default to {@link ViewGroup.LayoutParams#MATCH_PARENT}. To use * your own layout parameters, invoke * {@link #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)} * instead. * * @param view The desired content to display. * * @see #setContentView(int) * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams) */ setContentView(view:View|HTMLElement|string, params?:ViewGroup.LayoutParams){ if(!(view instanceof View)){ view = this.getLayoutInflater().inflate(<HTMLElement|string>view); } this.getWindow().setContentView(<View>view, params); //this.initActionBar(); } addContentView(view:View, params:ViewGroup.LayoutParams){ this.mWindow.addContentView(view, params); } /** * Sets whether this activity is finished when touched outside its window's * bounds. */ setFinishOnTouchOutside(finish:boolean):void { this.mWindow.setCloseOnTouchOutside(finish); } /** * Called when a key was pressed down and not handled by any of the views * inside of the activity. So, for example, key presses while the cursor * is inside a TextView will not trigger the event (unless it is a navigation * to another object) because TextView handles its own key presses. * * <p>If the focused view didn't want this event, this method is called. * * <p>The default implementation takes care of {@link KeyEvent#KEYCODE_BACK} * by calling {@link #onBackPressed()}, though the behavior varies based * on the application compatibility mode: for * {@link android.os.Build.VERSION_CODES#ECLAIR} or later applications, * it will set up the dispatch to call {@link #onKeyUp} where the action * will be performed; for earlier applications, it will perform the * action immediately in on-down, as those versions of the platform * behaved. * * <p>Other additional default key handling may be performed * if configured with {@link #setDefaultKeyMode}. * * @return Return <code>true</code> to prevent this event from being propagated * further, or <code>false</code> to indicate that you have not handled * this event and it should continue to be propagated. * @see #onKeyUp * @see android.view.KeyEvent */ onKeyDown(keyCode:number, event:KeyEvent):boolean { if (keyCode == KeyEvent.KEYCODE_BACK) { event.startTracking(); return true; } //if (this.mDefaultKeyMode == Activity.DEFAULT_KEYS_DISABLE) { // return false; //} else if (this.mDefaultKeyMode == Activity.DEFAULT_KEYS_SHORTCUT) { // if (this.getWindow().performPanelShortcut(Window.FEATURE_OPTIONS_PANEL, keyCode, event, Menu.FLAG_ALWAYS_PERFORM_CLOSE)) { // return true; // } // return false; //} else { // // Common code for DEFAULT_KEYS_DIALER & DEFAULT_KEYS_SEARCH_* // let clearSpannable:boolean = false; // let handled:boolean; // if ((event.getRepeatCount() != 0) || event.isSystem()) { // clearSpannable = true; // handled = false; // } else { // handled = TextKeyListener.getInstance().onKeyDown(null, this.mDefaultKeySsb, keyCode, event); // if (handled && this.mDefaultKeySsb.length() > 0) { // // something useable has been typed - dispatch it now. // const str:string = this.mDefaultKeySsb.toString(); // clearSpannable = true; // switch(this.mDefaultKeyMode) { // case Activity.DEFAULT_KEYS_DIALER: // let intent:Intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + str)); // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // this.startActivity(intent); // break; // case Activity.DEFAULT_KEYS_SEARCH_LOCAL: // this.startSearch(str, false, null, false); // break; // case Activity.DEFAULT_KEYS_SEARCH_GLOBAL: // this.startSearch(str, false, null, true); // break; // } // } // } // if (clearSpannable) { // this.mDefaultKeySsb.clear(); // this.mDefaultKeySsb.clearSpans(); // Selection.setSelection(this.mDefaultKeySsb, 0); // } // return handled; //} return false; } /** * Default implementation of {@link KeyEvent.Callback#onKeyLongPress(int, KeyEvent) * KeyEvent.Callback.onKeyLongPress()}: always returns false (doesn't handle * the event). */ onKeyLongPress(keyCode:number, event:KeyEvent):boolean { return false; } /** * Called when a key was released and not handled by any of the views * inside of the activity. So, for example, key presses while the cursor * is inside a TextView will not trigger the event (unless it is a navigation * to another object) because TextView handles its own key presses. * * <p>The default implementation handles KEYCODE_BACK to stop the activity * and go back. * * @return Return <code>true</code> to prevent this event from being propagated * further, or <code>false</code> to indicate that you have not handled * this event and it should continue to be propagated. * @see #onKeyDown * @see KeyEvent */ onKeyUp(keyCode:number, event:KeyEvent):boolean { if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking() && !event.isCanceled()) { this.onBackPressed(); return true; } return false; } /** * Called when the activity has detected the user's press of the back * key. The default implementation simply finishes the current activity, * but you can override this to do whatever you want. */ onBackPressed():void { //if (!this.mFragments.popBackStackImmediate()) { this.finish(); //} } /** * Called when a touch screen event was not handled by any of the views * under it. This is most useful to process touch events that happen * outside of your window bounds, where there is no view to receive it. * * @param event The touch screen event being processed. * * @return Return true if you have consumed the event, false if you haven't. * The default implementation always returns false. */ onTouchEvent(event:MotionEvent):boolean { if (this.mWindow.shouldCloseOnTouch(this, event)) { this.finish(); return true; } return false; } /** * Called when a generic motion event was not handled by any of the * views inside of the activity. * <p> * Generic motion events describe joystick movements, mouse hovers, track pad * touches, scroll wheel movements and other input events. The * {@link MotionEvent#getSource() source} of the motion event specifies * the class of input that was received. Implementations of this method * must examine the bits in the source before processing the event. * The following code example shows how this is done. * </p><p> * Generic motion events with source class * {@link android.view.InputDevice#SOURCE_CLASS_POINTER} * are delivered to the view under the pointer. All other generic motion events are * delivered to the focused view. * </p><p> * See {@link View#onGenericMotionEvent(MotionEvent)} for an example of how to * handle this event. * </p> * * @param event The generic motion event being processed. * * @return Return true if you have consumed the event, false if you haven't. * The default implementation always returns false. */ onGenericMotionEvent(event:MotionEvent):boolean { return false; } /** * Called whenever a key, touch, or trackball event is dispatched to the * activity. Implement this method if you wish to know that the user has * interacted with the device in some way while your activity is running. * This callback and {@link #onUserLeaveHint} are intended to help * activities manage status bar notifications intelligently; specifically, * for helping activities determine the proper time to cancel a notfication. * * <p>All calls to your activity's {@link #onUserLeaveHint} callback will * be accompanied by calls to {@link #onUserInteraction}. This * ensures that your activity will be told of relevant user activity such * as pulling down the notification pane and touching an item there. * * <p>Note that this callback will be invoked for the touch down action * that begins a touch gesture, but may not be invoked for the touch-moved * and touch-up actions that follow. * * @see #onUserLeaveHint() */ onUserInteraction():void { } onWindowAttributesChanged(params:WindowManager.LayoutParams):void { // this activity is not embedded. //if (this.mParent == null) { let decor:View = this.getWindow().getDecorView(); if (decor != null && decor.getParent() != null) { this.getWindowManager().updateWindowLayout(this.getWindow(), params); } //} } onContentChanged():void { } /** * Called when the current {@link Window} of the activity gains or loses * focus. This is the best indicator of whether this activity is visible * to the user. The default implementation clears the key tracking * state, so should always be called. * * <p>Note that this provides information about global focus state, which * is managed independently of activity lifecycles. As such, while focus * changes will generally have some relation to lifecycle changes (an * activity that is stopped will not generally get window focus), you * should not rely on any particular order between the callbacks here and * those in the other lifecycle methods such as {@link #onResume}. * * <p>As a general rule, however, a resumed activity will have window * focus... unless it has displayed other dialogs or popups that take * input focus, in which case the activity itself will not have focus * when the other windows have it. Likewise, the system may display * system-level windows (such as the status bar notification panel or * a system alert) which will temporarily take window input focus without * pausing the foreground activity. * * @param hasFocus Whether the window of this activity has focus. * * @see #hasWindowFocus() * @see #onResume * @see View#onWindowFocusChanged(boolean) */ onWindowFocusChanged(hasFocus:boolean):void { } /** * Called when the main window associated with the activity has been * attached to the window manager. * See {@link View#onAttachedToWindow() View.onAttachedToWindow()} * for more information. * @see View#onAttachedToWindow */ onAttachedToWindow():void { } /** * Called when the main window associated with the activity has been * detached from the window manager. * See {@link View#onDetachedFromWindow() View.onDetachedFromWindow()} * for more information. * @see View#onDetachedFromWindow */ onDetachedFromWindow():void { } /** * Returns true if this activity's <em>main</em> window currently has window focus. * Note that this is not the same as the view itself having focus. * * @return True if this activity's main window currently has window focus. * * @see #onWindowAttributesChanged(android.view.WindowManager.LayoutParams) */ hasWindowFocus():boolean { let w:Window = this.getWindow(); if (w != null) { let d:View = w.getDecorView(); if (d != null) { return d.hasWindowFocus(); } } return false; } /** * Called to process key events. You can override this to intercept all * key events before they are dispatched to the window. Be sure to call * this implementation for key events that should be handled normally. * * @param event The key event. * * @return boolean Return true if this event was consumed. */ dispatchKeyEvent(event:KeyEvent):boolean { this.onUserInteraction(); let win:Window = this.getWindow(); if (win.superDispatchKeyEvent(event)) { return true; } let decor:View = win.getDecorView(); return event.dispatch(this, decor != null ? decor.getKeyDispatcherState() : null, this); } /** * Called to process touch screen events. You can override this to * intercept all touch screen events before they are dispatched to the * window. Be sure to call this implementation for touch screen events * that should be handled normally. * * @param ev The touch screen event. * * @return boolean Return true if this event was consumed. */ dispatchTouchEvent(ev:MotionEvent):boolean { if (ev.getAction() == MotionEvent.ACTION_DOWN) { this.onUserInteraction(); } if (this.getWindow().superDispatchTouchEvent(ev)) { return true; } return this.onTouchEvent(ev); } /** * Called to process generic motion events. You can override this to * intercept all generic motion events before they are dispatched to the * window. Be sure to call this implementation for generic motion events * that should be handled normally. * * @param ev The generic motion event. * * @return boolean Return true if this event was consumed. */ dispatchGenericMotionEvent(ev:MotionEvent):boolean { this.onUserInteraction(); if (this.getWindow().superDispatchGenericMotionEvent(ev)) { return true; } return this.onGenericMotionEvent(ev); } /** * Request that key events come to this activity. Use this if your * activity has no views with focus, but the activity still wants * a chance to process key events. * * @see android.view.Window#takeKeyEvents */ takeKeyEvents(_get:boolean):void { this.getWindow().takeKeyEvents(_get); } /** * Declare that the options menu has changed, so should be recreated. * The {@link #onCreateOptionsMenu(Menu)} method will be called the next * time it needs to be displayed. */ private invalidateOptionsMenu():void { let menu = new android.view.Menu(this); if(this.onCreateOptionsMenu(menu)){ menu.setCallback({ onMenuItemSelected : (menu, item)=>{ let handle = this.onOptionsItemSelected(item); this.onOptionsMenuClosed(menu); return handle; } }); this.mMenu = menu; this.mMenuPopuoHelper = this.invalidateOptionsMenuPopupHelper(menu); } } protected invalidateOptionsMenuPopupHelper(menu:android.view.Menu):android.view.menu.MenuPopupHelper { //TODO support menu for fullscreen activity return null; // this.mMenuPopuoHelper = new android.view.menu.MenuPopupHelper(this, menu, this.getActionBar().mActionRight); } /** * Initialize the contents of the Activity's standard options menu. You * should place your menu items in to <var>menu</var>. * * <p>This is only called once, the first time the options menu is * displayed. To update the menu every time it is displayed, see * {@link #onPrepareOptionsMenu}. * * <p>The default implementation populates the menu with standard system * menu items. These are placed in the {@link Menu#CATEGORY_SYSTEM} group so that * they will be correctly ordered with application-defined menu items. * Deriving classes should always call through to the base implementation. * * <p>You can safely hold on to <var>menu</var> (and any items created * from it), making modifications to it as desired, until the next * time onCreateOptionsMenu() is called. * * <p>When you add items to the menu, you can implement the Activity's * {@link #onOptionsItemSelected} method to handle them there. * * @param menu The options menu in which you place your items. * * @return You must return true for the menu to be displayed; * if you return false it will not be shown. * * @see #onPrepareOptionsMenu * @see #onOptionsItemSelected */ onCreateOptionsMenu(menu:android.view.Menu):boolean { return true; } /** * Prepare the Screen's standard options menu to be displayed. This is * called right before the menu is shown, every time it is shown. You can * use this method to efficiently enable/disable items or otherwise * dynamically modify the contents. * * <p>The default implementation updates the system menu items based on the * activity's state. Deriving classes should always call through to the * base class implementation. * * @param menu The options menu as last shown or first initialized by * onCreateOptionsMenu(). * * @return You must return true for the menu to be displayed; * if you return false it will not be shown. * * @see #onCreateOptionsMenu */ onPrepareOptionsMenu(menu:android.view.Menu):boolean { return true; } /** * This hook is called whenever an item in your options menu is selected. * The default implementation simply returns false to have the normal * processing happen (calling the item's Runnable or sending a message to * its Handler as appropriate). You can use this method for any items * for which you would like to do processing without those other * facilities. * * <p>Derived classes should call through to the base class for it to * perform the default menu handling.</p> * * @param item The menu item that was selected. * * @return boolean Return false to allow normal menu processing to * proceed, true to consume it here. * * @see #onCreateOptionsMenu */ onOptionsItemSelected(item:android.view.MenuItem):boolean { return false; } /** * This hook is called whenever the options menu is being closed (either by the user canceling * the menu with the back/menu button, or when an item is selected). * * @param menu The options menu as last shown or first initialized by * onCreateOptionsMenu(). */ onOptionsMenuClosed(menu:android.view.Menu):void { } /** * Programmatically opens the options menu. If the options menu is already * open, this method does nothing. */ openOptionsMenu():void { if(this.mMenuPopuoHelper) this.mMenuPopuoHelper.show(); } /** * Progammatically closes the options menu. If the options menu is already * closed, this method does nothing. */ closeOptionsMenu():void { if(this.mMenuPopuoHelper) this.mMenuPopuoHelper.dismiss(); } /** * Launch an activity for which you would like a result when it finished. * When this activity exits, your * onActivityResult() method will be called with the given requestCode. * Using a negative requestCode is the same as calling * {@link #startActivity} (the activity is not launched as a sub-activity). * * <p>Note that this method should only be used with Intent protocols * that are defined to return a result. In other protocols (such as * {@link Intent#ACTION_MAIN} or {@link Intent#ACTION_VIEW}), you may * not get the result when you expect. For example, if the activity you * are launching uses the singleTask launch mode, it will not run in your * task and thus you will immediately receive a cancel result. * * <p>As a special case, if you call startActivityForResult() with a requestCode * >= 0 during the initial onCreate(Bundle savedInstanceState)/onResume() of your * activity, then your window will not be displayed until a result is * returned back from the started activity. This is to avoid visible * flickering when redirecting to another activity. * * <p>This method throws {@link android.content.ActivityNotFoundException} * if there was no Activity found to run the given Intent. * * @param intent The intent to start. * @param requestCode If >= 0, this code will be returned in * onActivityResult() when the activity exits. * @param options Additional options for how the Activity should be started. * See {@link android.content.Context#startActivity(Intent, Bundle) * Context.startActivity(Intent, Bundle)} for more details. * * @throws android.content.ActivityNotFoundException * * @see #startActivity */ startActivityForResult(intent:Intent|string, requestCode:number, options?:Bundle):void { if(typeof intent === 'string') intent = new Intent(<string>intent); if(requestCode>=0) (<Intent>intent).mRequestCode = requestCode; this.androidUI.mActivityThread.execStartActivity(this, <Intent>intent, options); // let ar:Instrumentation.ActivityResult = this.mInstrumentation.execStartActivity(this, this.mMainThread.getApplicationThread(), this.mToken, this, intent, requestCode, options); // if (ar != null) { // this.mMainThread.sendActivityResult(this.mToken, this.mEmbeddedID, requestCode, ar.getResultCode(), ar.getResultData()); // } if (requestCode >= 0) { // If this start is requesting a result, we can avoid making // the activity visible until the result is received. Setting // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the // activity hidden during this time, to avoid flickering. // This can only be done when a result is requested because // that guarantees we will get information back when the // activity is finished, no matter what happens to it. this.mStartedActivity = true; } const decor:View = this.mWindow != null ? this.mWindow.peekDecorView() : null; if (decor != null) { decor.cancelPendingInputEvents(); } // TODO Consider clearing/flushing other event sources and events for child windows. } /** * Launch a new activity. You will not receive any information about when * the activity exits. This implementation overrides the base version, * providing information about * the activity performing the launch. Because of this additional * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not * required; if not specified, the new activity will be added to the * task of the caller. * * <p>This method throws {@link android.content.ActivityNotFoundException} * if there was no Activity found to run the given Intent. * * @param intents The intents to start. * @param options Additional options for how the Activity should be started. * See {@link android.content.Context#startActivity(Intent, Bundle) * Context.startActivity(Intent, Bundle)} for more details. * * @throws android.content.ActivityNotFoundException * * @see {@link #startActivities(Intent[])} * @see #startActivityForResult */ startActivities(intents:Intent[], options?:Bundle):void { for(let intent of intents){ this.startActivity(intent, options); } } /** * Launch a new activity. You will not receive any information about when * the activity exits. This implementation overrides the base version, * providing information about * the activity performing the launch. Because of this additional * information, the {@link Intent#FLAG_ACTIVITY_NEW_TASK} launch flag is not * required; if not specified, the new activity will be added to the * task of the caller. * * <p>This method throws {@link android.content.ActivityNotFoundException} * if there was no Activity found to run the given Intent. * * @param intent The intent to start. * @param options Additional options for how the Activity should be started. * See {@link android.content.Context#startActivity(Intent, Bundle) * Context.startActivity(Intent, Bundle)} for more details. * * @throws android.content.ActivityNotFoundException * * @see {@link #startActivity(Intent)} * @see #startActivityForResult */ startActivity(intent:Intent|string, options?:Bundle):void { if (options != null) { this.startActivityForResult(intent, -1, options); } else { // Note we want to go through this call for compatibility with // applications that may have overridden the method. this.startActivityForResult(intent, -1); } } /** * A special variation to launch an activity only if a new activity * instance is needed to handle the given Intent. In other words, this is * just like {@link #startActivityForResult(Intent, int)} except: if you are * using the {@link Intent#FLAG_ACTIVITY_SINGLE_TOP} flag, or * singleTask or singleTop * {@link android.R.styleable#AndroidManifestActivity_launchMode launchMode}, * and the activity * that handles <var>intent</var> is the same as your currently running * activity, then a new instance is not needed. In this case, instead of * the normal behavior of calling {@link #onNewIntent} this function will * return and you can handle the Intent yourself. * * <p>This function can only be called from a top-level activity; if it is * called from a child activity, a runtime exception will be thrown. * * @param intent The intent to start. * @param requestCode If >= 0, this code will be returned in * onActivityResult() when the activity exits, as described in * {@link #startActivityForResult}. * @param options Additional options for how the Activity should be started. * See {@link android.content.Context#startActivity(Intent, Bundle) * Context.startActivity(Intent, Bundle)} for more details. * * @return If a new activity was launched then true is returned; otherwise * false is returned and you must handle the Intent yourself. * * @see #startActivity * @see #startActivityForResult */ startActivityIfNeeded(intent:Intent, requestCode:number, options?:Bundle):boolean { if(this.androidUI.mActivityThread.canBackTo(intent)){ return false; } this.startActivityForResult(intent, requestCode, options); return true; //let result:number = ActivityManager.START_RETURN_INTENT_TO_CALLER; //try { // intent.migrateExtraStreamToClipData(); // intent.prepareToLeaveProcess(); // result = ActivityManagerNative.getDefault().startActivity(this.mMainThread.getApplicationThread(), this.getBasePackageName(), intent, intent.resolveTypeIfNeeded(this.getContentResolver()), this.mToken, this.mEmbeddedID, requestCode, ActivityManager.START_FLAG_ONLY_IF_NEEDED, null, null, options); //} catch (e){ //} //Instrumentation.checkStartActivityResult(result, intent); //if (requestCode >= 0) { // // If this start is requesting a result, we can avoid making // // the activity visible until the result is received. Setting // // this code during onCreate(Bundle savedInstanceState) or onResume() will keep the // // activity hidden during this time, to avoid flickering. // // This can only be done when a result is requested because // // that guarantees we will get information back when the // // activity is finished, no matter what happens to it. // this.mStartedActivity = true; //} //return result != ActivityManager.START_RETURN_INTENT_TO_CALLER; } /** * Call before one of the flavors of {@link #startActivity(Intent)} * or {@link #finish} to specify an explicit transition animation to * perform next. */ overrideNextTransition(enterAnimation:Animation, exitAnimation:Animation, resumeAnimation:Animation, hideAnimation:Animation):void { this.androidUI.mActivityThread.overrideNextWindowAnimation(enterAnimation, exitAnimation, resumeAnimation, hideAnimation); } /** * Call this to set the result that your activity will return to its * caller. * * <p>As of {@link android.os.Build.VERSION_CODES#GINGERBREAD}, the Intent * you supply here can have {@link Intent#FLAG_GRANT_READ_URI_PERMISSION * Intent.FLAG_GRANT_READ_URI_PERMISSION} and/or {@link Intent#FLAG_GRANT_WRITE_URI_PERMISSION * Intent.FLAG_GRANT_WRITE_URI_PERMISSION} set. This will grant the * Activity receiving the result access to the specific URIs in the Intent. * Access will remain until the Activity has finished (it will remain across the hosting * process being killed and other temporary destruction) and will be added * to any existing set of URI permissions it already holds. * * @param resultCode The result code to propagate back to the originating * activity, often RESULT_CANCELED or RESULT_OK * @param data The data to propagate back to the originating activity. * * @see #RESULT_CANCELED * @see #RESULT_OK * @see #RESULT_FIRST_USER * @see #setResult(int) */ setResult(resultCode:number, data?:Intent):void { { this.mResultCode = resultCode; this.mResultData = data; } } /** * Return the name of the activity that invoked this activity. This is * who the data in {@link #setResult setResult()} will be sent to. You * can use this information to validate that the recipient is allowed to * receive the data. * * <p class="note">Note: if the calling activity is not expecting a result (that is it * did not use the {@link #startActivityForResult} * form that includes a request code), then the calling package will be * null. * * @return The className of the activity that will receive your * reply, or null if none. */ getCallingActivity():string { //FIXME not support yet return null; } /** * Control whether this activity's main window is visible. This is intended * only for the special case of an activity that is not going to show a * UI itself, but can't just finish prior to onResume() because it needs * to wait for a service binding or such. Setting this to false allows * you to prevent your UI from being shown during that time. * * <p>The default value for this is taken from the * {@link android.R.attr#windowNoDisplay} attribute of the activity's theme. */ setVisible(visible:boolean):void { if (this.mVisibleFromClient != visible) { this.mVisibleFromClient = visible; //if (this.mVisibleFromServer) { // if (visible) // this.makeVisible(); // else // this.getWindow().getDecorView().setVisibility(View.INVISIBLE); //} } } makeVisible():void { if (!this.mWindowAdded) { let wm:WindowManager = this.getGlobalWindowManager(); wm.addWindow(this.getWindow()); this.mWindowAdded = true; } this.getWindow().getDecorView().setVisibility(View.VISIBLE); } /** * Check to see whether this activity is in the process of finishing, * either because you called {@link #finish} on it or someone else * has requested that it finished. This is often used in * {@link #onPause} to determine whether the activity is simply pausing or * completely finishing. * * @return If the activity is finishing, returns true; else returns false. * * @see #finish */ isFinishing():boolean { return this.mFinished; } /** * Returns true if the final {@link #onDestroy()} call has been made * on the Activity, so this instance is now dead. */ isDestroyed():boolean { return this.mDestroyed; } /** * Call this when your activity is done and should be closed. The * ActivityResult is propagated back to whoever launched you via * onActivityResult(). */ finish():void { let resultCode:number = this.mResultCode; let resultData:Intent = this.mResultData; try { this.androidUI.mActivityThread.scheduleDestroyActivity(this); //if (resultData != null) { // resultData.prepareToLeaveProcess(); //} //if (ActivityManagerNative.getDefault().finishActivity(this.mToken, resultCode, resultData)) { // this.mFinished = true; //} } catch (e){ } } /** * Force finish another activity that you had previously started with * {@link #startActivityForResult}. * * @param requestCode The request code of the activity that you had * given to startActivityForResult(). If there are multiple * activities started with this request code, they * will all be finished. */ finishActivity(requestCode:number):void { this.androidUI.mActivityThread.scheduleDestroyActivityByRequestCode(requestCode); } /** * Called when an activity you launched exits, giving you the requestCode * you started it with, the resultCode it returned, and any additional * data from it. The <var>resultCode</var> will be * {@link #RESULT_CANCELED} if the activity explicitly returned that, * didn't return any result, or crashed during its operation. * * <p>You will receive this call immediately before onResume() when your * activity is re-starting. * * @param requestCode The integer request code originally supplied to * startActivityForResult(), allowing you to identify who this * result came from. * @param resultCode The integer result code returned by the child activity * through its setResult(). * @param data An Intent, which can return result data to the caller * (various data can be attached to Intent "extras"). * * @see #startActivityForResult * @see #createPendingResult * @see #setResult(int) */ protected onActivityResult(requestCode:number, resultCode:number, data:Intent):void { } /** * Change the title associated with this activity. If this is a * top-level activity, the title for its window will change. If it * is an embedded activity, the parent can do whatever it wants * with it. */ setTitle(title:string):void { this.getWindow().setTitle(title); this.onTitleChanged(title); } getTitle():string { return this.getWindow().getAttributes().getTitle(); } protected onTitleChanged(title:string, color?:number):void { //if (this.mTitleReady) { const win:Window = this.getWindow(); if (win != null) { win.setTitle(title); //if (color != 0) { // win.setTitleColor(color); //} } //} } /** * Runs the specified action on the UI thread. If the current thread is the UI * thread, then the action is executed immediately. If the current thread is * not the UI thread, the action is posted to the event queue of the UI thread. * * @param action the action to run on the UI thread */ runOnUiThread(action:Runnable):void { action.run(); } /** * Navigate from this activity to the activity specified by upIntent, finishing this activity * in the process. If the activity indicated by upIntent already exists in the task's history, * this activity and all others before the indicated activity in the history stack will be * finished. * * <p>If the indicated activity does not appear in the history stack, this will finish * each activity in this task until the root activity of the task is reached, resulting in * an "in-app home" behavior. This can be useful in apps with a complex navigation hierarchy * when an activity may be reached by a path not passing through a canonical parent * activity.</p> * * <p>This method should be used when performing up navigation from within the same task * as the destination. If up navigation should cross tasks in some cases, see * {@link #shouldUpRecreateTask(Intent)}.</p> * * @param upIntent An intent representing the target destination for up navigation * * @return true if up navigation successfully reached the activity indicated by upIntent and * upIntent was delivered to it. false if an instance of the indicated activity could * not be found and this activity was simply finished normally. */ navigateUpTo(upIntent:Intent, upToRootIfNotFound=true):boolean { if(this.androidUI.mActivityThread.scheduleBackTo(upIntent)){ return true; } if(upToRootIfNotFound) this.androidUI.mActivityThread.scheduleBackToRoot(); return false; // //let destInfo:ComponentName = upIntent.getComponent(); // //if (destInfo == null) { // // destInfo = upIntent.resolveActivity(this.getPackageManager()); // // if (destInfo == null) { // // return false; // // } // // upIntent = new Intent(upIntent); // // upIntent.setComponent(destInfo); // //} // let resultCode:number = this.mResultCode; // let resultData:Intent = this.mResultData; // //if (resultData != null) { // //resultData.prepareToLeaveProcess(); // //} // //try { // // upIntent.prepareToLeaveProcess(); // // return ActivityManagerNative.getDefault().navigateUpTo(this.mToken, upIntent, resultCode, resultData); // //} catch (e){ // // return false; // //} // // return false; } constructor(androidUI:androidui.AndroidUI) { super(androidUI); this.mWindow = new Window(this); this.mWindow.setWindowAnimations(android.R.anim.activity_open_enter_ios, android.R.anim.activity_close_exit_ios, android.R.anim.activity_close_enter_ios, android.R.anim.activity_open_exit_ios); this.mWindow.setDimAmount(0.7); this.mWindow.getAttributes().flags |= WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH; this.mWindow.setCallback(this); } private performCreate(icicle:Bundle):void { this.onCreate(icicle); this.invalidateOptionsMenu(); //this.mVisibleFromClient = !this.mWindow.getWindowStyle().getBoolean(com.android.internal.R.styleable.Window_windowNoDisplay, false); //this.mFragments.dispatchActivityCreated(); } private performStart():void { //this.mFragments.noteStateNotSaved(); this.mCalled = false; //this.mFragments.execPendingActions(); this.onStart();//this.mInstrumentation.callActivityOnStart(this); if (!this.mCalled) { throw Error(`new SuperNotCalledException("Activity " + this.mComponent.toShortString() + " did not call through to super.onStart()")`); } //this.mFragments.dispatchStart(); //if (this.mAllLoaderManagers != null) { // const N:number = this.mAllLoaderManagers.size(); // let loaders:LoaderManagerImpl = new Array<LoaderManagerImpl>(N); // for (let i:number = N - 1; i >= 0; i--) { // loaders[i] = this.mAllLoaderManagers.valueAt(i); // } // for (let i:number = 0; i < N; i++) { // let lm:LoaderManagerImpl = loaders[i]; // lm.finishRetain(); // lm.doReportStart(); // } //} } private performRestart():void { //this.mFragments.noteStateNotSaved(); if (this.mStopped) { this.mStopped = false; //if (this.mToken != null && this.mParent == null) { // WindowManagerGlobal.getInstance().setStoppedState(this.mToken, false); //} //{ // const N:number = this.mManagedCursors.size(); // for (let i:number = 0; i < N; i++) { // let mc:Activity.ManagedCursor = this.mManagedCursors.get(i); // if (mc.mReleased || mc.mUpdated) { // if (!mc.mCursor.requery()) { // if (this.getApplicationInfo().targetSdkVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) { // throw Error(`new IllegalStateException("trying to requery an already closed cursor " + mc.mCursor)`); // } // } // mc.mReleased = false; // mc.mUpdated = false; // } // } //} this.mCalled = false; this.onRestart();//this.mInstrumentation.callActivityOnRestart(this); if (!this.mCalled) { throw Error(`new SuperNotCalledException("Activity " + this.mComponent.toShortString() + " did not call through to super.onRestart()")`); } this.performStart(); } } private performResume():void { this.performRestart(); //this.mFragments.execPendingActions(); //this.mLastNonConfigurationInstances = null; this.mCalled = false; // mResumed is set by the instrumentation this.mResumed = true; this.onResume();//this.mInstrumentation.callActivityOnResume(this); if (!this.mCalled) { throw Error(`new SuperNotCalledException("Activity " + this.mComponent.toShortString() + " did not call through to super.onResume()")`); } // Now really resume, and install the current status bar and menu. this.mCalled = false; //this.mFragments.dispatchResume(); //this.mFragments.execPendingActions(); this.onPostResume(); if (!this.mCalled) { throw Error(`new SuperNotCalledException("Activity " + this.mComponent.toShortString() + " did not call through to super.onPostResume()")`); } } private performPause():void { if(this.mResumed) { //this.mDoReportFullyDrawn = false; //this.mFragments.dispatchPause(); this.mCalled = false; this.onPause(); this.mResumed = false; if (!this.mCalled) { throw Error(`new SuperNotCalledException("Activity ${this.constructor.name} did not call through to super.onPause()")`); } this.mResumed = false; } } private performUserLeaving():void { this.onUserInteraction(); this.onUserLeaveHint(); } private performStop():void { //this.mDoReportFullyDrawn = false; //if (this.mLoadersStarted) { // this.mLoadersStarted = false; // if (this.mLoaderManager != null) { // if (!this.mChangingConfigurations) { // this.mLoaderManager.doStop(); // } else { // this.mLoaderManager.doRetain(); // } // } //} if (!this.mStopped) { //if (this.mWindow != null) { // this.mWindow.closeAllPanels(); //} //if (this.mToken != null && this.mParent == null) { // WindowManagerGlobal.getInstance().setStoppedState(this.mToken, true); //} //this.mFragments.dispatchStop(); this.mCalled = false; this.onStop();//this.mInstrumentation.callActivityOnStop(this); if (!this.mCalled) { throw Error(`new SuperNotCalledException("Activity " + this.mComponent.toShortString() + " did not call through to super.onStop()")`); } //{ // const N:number = this.mManagedCursors.size(); // for (let i:number = 0; i < N; i++) { // let mc:Activity.ManagedCursor = this.mManagedCursors.get(i); // if (!mc.mReleased) { // mc.mCursor.deactivate(); // mc.mReleased = true; // } // } //} this.mStopped = true; } this.mResumed = false; } private performDestroy():void { this.mDestroyed = true; this.mWindow.destroy(); //this.mFragments.dispatchDestroy(); this.onDestroy(); //if (this.mLoaderManager != null) { // this.mLoaderManager.doDestroy(); //} } isResumed():boolean { return this.mResumed; } dispatchActivityResult(who:string, requestCode:number, resultCode:number, data:Intent):void { // if (false) Log.v(Activity.TAG, "Dispatching result: who=" + who + ", reqCode=" + requestCode + ", resCode=" + resultCode + ", data=" + data); //this.mFragments.noteStateNotSaved(); //if (who == null) { this.onActivityResult(requestCode, resultCode, data); //} else { //let frag:Fragment = this.mFragments.findFragmentByWho(who); //if (frag != null) { // frag.onActivityResult(requestCode, resultCode, data); //} //} } } }
the_stack
import { ChangeDetectorRef, NgZone } from '@angular/core'; import { async, ComponentFixture, inject, TestBed } from '@angular/core/testing'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { Store } from '@ngrx/store'; import { createBasicStoreModule } from '@stratosui/store/testing'; import { BehaviorSubject, of as observableOf } from 'rxjs'; import { switchMap } from 'rxjs/operators'; import { ListView } from '../../../../../store/src/actions/list.actions'; import { GeneralAppState } from '../../../../../store/src/app-state'; import { EntityMonitorFactory } from '../../../../../store/src/monitors/entity-monitor.factory.service'; import { PaginationMonitorFactory } from '../../../../../store/src/monitors/pagination-monitor.factory'; import { APIResource } from '../../../../../store/src/types/api.types'; import { EndpointModel } from '../../../../../store/src/types/endpoint.types'; import { CoreTestingModule } from '../../../../test-framework/core-test.modules'; import { CoreModule } from '../../../core/core.module'; import { CurrentUserPermissionsService } from '../../../core/permissions/current-user-permissions.service'; import { SharedModule } from '../../shared.module'; import { EndpointCardComponent } from './list-types/endpoint/endpoint-card/endpoint-card.component'; import { EndpointListHelper } from './list-types/endpoint/endpoint-list.helpers'; import { EndpointsListConfigService } from './list-types/endpoint/endpoints-list-config.service'; import { ListComponent } from './list.component'; import { ListConfig, ListViewTypes } from './list.component.types'; class MockedNgZone { run = fn => fn(); runOutsideAngular = fn => fn(); } describe('ListComponent', () => { describe('basic tests', () => { function createBasicListConfig(): ListConfig<APIResource> { return { allowSelection: false, cardComponent: null, defaultView: 'table' as ListView, enableTextFilter: false, getColumns: () => null, getDataSource: () => null, getGlobalActions: () => null, getInitialised: () => null, getMultiActions: () => null, getMultiFiltersConfigs: () => null, getFilters: () => null, getSingleActions: () => null, isLocal: false, pageSizeOptions: [1], text: null, viewType: ListViewTypes.BOTH }; } function setup(config: ListConfig<APIResource>, test: (component: ListComponent<APIResource>) => void) { TestBed.configureTestingModule({ imports: [ createBasicStoreModule(), ], providers: [ { provide: ChangeDetectorRef, useValue: { detectChanges: () => { } } }, // Fun fact, NgZone will execute something on import which causes an undefined error { provide: MockedNgZone, useValue: new MockedNgZone() }, EndpointListHelper ] }); inject([Store, ChangeDetectorRef, NgZone], ( iStore: Store<GeneralAppState>, cd: ChangeDetectorRef, ngZone: MockedNgZone ) => { const component = new ListComponent<APIResource>(iStore, cd, config, ngZone as NgZone); test(component); })(); } it('initialised - default', (done) => { const config = createBasicListConfig(); config.getInitialised = null; setup(config, (component) => { const componentDeTyped = (component as any); spyOn<any>(componentDeTyped, 'initialise'); expect(componentDeTyped.initialise).not.toHaveBeenCalled(); component.ngOnInit(); component.initialised$.subscribe(res => { expect(componentDeTyped.initialise).toHaveBeenCalled(); expect(res).toBe(true); done(); }); }); }); it('initialised - custom', (done) => { const config = createBasicListConfig(); spyOn<any>(config, 'getInitialised').and.returnValue(observableOf(true)); setup(config, (component) => { const componentDeTyped = (component as any); spyOn<any>(componentDeTyped, 'initialise'); expect(componentDeTyped.initialise).not.toHaveBeenCalled(); component.ngOnInit(); expect(config.getInitialised).toHaveBeenCalled(); component.initialised$.subscribe(res => { expect(componentDeTyped.initialise).toHaveBeenCalled(); expect(res).toBe(true); done(); }); }); }); }); describe('full test bed', () => { let component: ListComponent<EndpointModel>; let fixture: ComponentFixture<ListComponent<EndpointModel>>; beforeEach(async(() => { TestBed.configureTestingModule({ providers: [ { provide: ListConfig, useClass: EndpointsListConfigService }, // ApplicationStateService, PaginationMonitorFactory, EntityMonitorFactory, EndpointListHelper, CurrentUserPermissionsService ], imports: [ CoreModule, SharedModule, CoreTestingModule, createBasicStoreModule(), NoopAnimationsModule ], }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent<ListComponent<EndpointModel>>(ListComponent); component = fixture.componentInstance; component.columns = []; }); it('should be created', () => { fixture.detectChanges(); expect(component).toBeTruthy(); }); describe('Header', () => { it('Nothing enabled', () => { component.config.getMultiFiltersConfigs = () => []; component.config.getFilters = () => []; component.config.enableTextFilter = false; component.config.viewType = ListViewTypes.CARD_ONLY; component.config.defaultView = 'card' as ListView; component.config.cardComponent = EndpointCardComponent; component.config.text.title = null; const columns = component.config.getColumns(); columns.forEach(column => column.sort = false); component.config.getColumns = () => columns; fixture.detectChanges(); const hostElement = fixture.nativeElement; // No multi filters const multiFilterSection: HTMLElement = hostElement.querySelector('.list-component__header__left--multi-filters'); expect(multiFilterSection.hidden).toBeFalsy(); expect(multiFilterSection.childElementCount).toBe(0); const headerRightSection = hostElement.querySelector('.list-component__header__right'); // No text filter const filterSection: HTMLElement = headerRightSection.querySelector('.filter'); expect(filterSection.hidden).toBeTruthy(); // No sort const sortSection: HTMLElement = headerRightSection.querySelector('.sort'); expect(sortSection.hidden).toBeTruthy(); component.initialised$.pipe( switchMap(() => component.hasControls$) ).subscribe(hasControls => { expect(hasControls).toBeFalsy(); }); }); it('Everything enabled', () => { component.config.getMultiFiltersConfigs = () => { return [ { key: 'filterTestKey', label: 'filterTestLabel', list$: observableOf([ { label: 'filterItemLabel', item: 'filterItemItem', value: 'filterItemValue' }, { label: 'filterItemLabel2', item: 'filterItemItem2', value: 'filterItemValue2' } ]), loading$: observableOf(false), select: new BehaviorSubject(false) } ]; }; component.config.getFilters = () => ([ { default: true, key: 'a', label: 'A', placeholder: 'Filter by A' }, { key: 'b', label: 'B', placeholder: 'Filter by B' } ]); component.config.enableTextFilter = true; component.config.viewType = ListViewTypes.CARD_ONLY; component.config.defaultView = 'card' as ListView; component.config.cardComponent = EndpointCardComponent; component.config.getColumns = () => [ { columnId: 'filterTestKey', headerCell: () => 'a', cellDefinition: { getValue: (row) => `${row}` }, sort: true, } ]; fixture.detectChanges(); const hostElement = fixture.nativeElement; // multi filters const multiFilterSection: HTMLElement = hostElement.querySelector('.list-component__header__left--multi-filters'); expect(multiFilterSection.hidden).toBeFalsy(); expect(multiFilterSection.childElementCount).toBe(1); // text filter const headerRightSection = hostElement.querySelector('.list-component__header__right'); const filterSection: HTMLElement = headerRightSection.querySelector('.filter'); expect(filterSection.hidden).toBeFalsy(); // sort - hard to test for sort, as it relies on // const sortSection: HTMLElement = headerRightSection.querySelector('.sort'); // expect(sortSection.hidden).toBeFalsy(); }); it('First filter hidden if only one option', async(() => { component.config.getMultiFiltersConfigs = () => { return [ { key: 'filterTestKey', label: 'filterTestLabel', list$: observableOf([ { label: 'filterItemLabel', item: 'filterItemItem', value: 'filterItemValue' }, ]), loading$: observableOf(false), select: new BehaviorSubject(false) } ]; }; component.config.enableTextFilter = true; component.config.viewType = ListViewTypes.CARD_ONLY; component.config.defaultView = 'card' as ListView; component.config.cardComponent = EndpointCardComponent; component.config.getColumns = () => [ { columnId: 'filterTestKey', headerCell: () => 'a', cellDefinition: { getValue: (row) => `${row}` }, sort: true, } ]; fixture.detectChanges(); const hostElement = fixture.nativeElement; // multi filters const multiFilterSection: HTMLElement = hostElement.querySelector('.list-component__header__left--multi-filters'); expect(multiFilterSection.hidden).toBeFalsy(); expect(multiFilterSection.childElementCount).toBe(0); })); }); it('No rows', () => { fixture.detectChanges(); const hostElement = fixture.nativeElement; // No paginator const sortSection: HTMLElement = hostElement.querySelector('.list-component__paginator'); expect(sortSection.hidden).toBeTruthy(); // Shows empty message const noEntriesMessage: HTMLElement = hostElement.querySelector('.list-component__default-no-entries'); expect(noEntriesMessage.hidden).toBeFalsy(); }); }); });
the_stack
import {coerceNumberProperty, NumberInput} from '@angular/cdk/coercion'; import {Platform, _getShadowRoot} from '@angular/cdk/platform'; import {ViewportRuler} from '@angular/cdk/scrolling'; import {DOCUMENT} from '@angular/common'; import { ChangeDetectionStrategy, Component, ElementRef, Inject, InjectionToken, Input, Optional, ViewEncapsulation, OnInit, ChangeDetectorRef, OnDestroy, NgZone, } from '@angular/core'; import {CanColor, mixinColor, ThemePalette} from '@angular/material/core'; import {ANIMATION_MODULE_TYPE} from '@angular/platform-browser/animations'; import {Subscription} from 'rxjs'; /** Possible mode for a progress spinner. */ export type ProgressSpinnerMode = 'determinate' | 'indeterminate'; /** * Base reference size of the spinner. * @docs-private */ const BASE_SIZE = 100; /** * Base reference stroke width of the spinner. * @docs-private */ const BASE_STROKE_WIDTH = 10; // Boilerplate for applying mixins to MatProgressSpinner. /** @docs-private */ const _MatProgressSpinnerBase = mixinColor( class { constructor(public _elementRef: ElementRef) {} }, 'primary', ); /** Default `mat-progress-spinner` options that can be overridden. */ export interface MatProgressSpinnerDefaultOptions { /** Default color of the spinner. */ color?: ThemePalette; /** Diameter of the spinner. */ diameter?: number; /** Width of the spinner's stroke. */ strokeWidth?: number; /** * Whether the animations should be force to be enabled, ignoring if the current environment is * using NoopAnimationsModule. */ _forceAnimations?: boolean; } /** Injection token to be used to override the default options for `mat-progress-spinner`. */ export const MAT_PROGRESS_SPINNER_DEFAULT_OPTIONS = new InjectionToken<MatProgressSpinnerDefaultOptions>('mat-progress-spinner-default-options', { providedIn: 'root', factory: MAT_PROGRESS_SPINNER_DEFAULT_OPTIONS_FACTORY, }); /** @docs-private */ export function MAT_PROGRESS_SPINNER_DEFAULT_OPTIONS_FACTORY(): MatProgressSpinnerDefaultOptions { return {diameter: BASE_SIZE}; } // .0001 percentage difference is necessary in order to avoid unwanted animation frames // for example because the animation duration is 4 seconds, .1% accounts to 4ms // which are enough to see the flicker described in // https://github.com/angular/components/issues/8984 const INDETERMINATE_ANIMATION_TEMPLATE = ` @keyframes mat-progress-spinner-stroke-rotate-DIAMETER { 0% { stroke-dashoffset: START_VALUE; transform: rotate(0); } 12.5% { stroke-dashoffset: END_VALUE; transform: rotate(0); } 12.5001% { stroke-dashoffset: END_VALUE; transform: rotateX(180deg) rotate(72.5deg); } 25% { stroke-dashoffset: START_VALUE; transform: rotateX(180deg) rotate(72.5deg); } 25.0001% { stroke-dashoffset: START_VALUE; transform: rotate(270deg); } 37.5% { stroke-dashoffset: END_VALUE; transform: rotate(270deg); } 37.5001% { stroke-dashoffset: END_VALUE; transform: rotateX(180deg) rotate(161.5deg); } 50% { stroke-dashoffset: START_VALUE; transform: rotateX(180deg) rotate(161.5deg); } 50.0001% { stroke-dashoffset: START_VALUE; transform: rotate(180deg); } 62.5% { stroke-dashoffset: END_VALUE; transform: rotate(180deg); } 62.5001% { stroke-dashoffset: END_VALUE; transform: rotateX(180deg) rotate(251.5deg); } 75% { stroke-dashoffset: START_VALUE; transform: rotateX(180deg) rotate(251.5deg); } 75.0001% { stroke-dashoffset: START_VALUE; transform: rotate(90deg); } 87.5% { stroke-dashoffset: END_VALUE; transform: rotate(90deg); } 87.5001% { stroke-dashoffset: END_VALUE; transform: rotateX(180deg) rotate(341.5deg); } 100% { stroke-dashoffset: START_VALUE; transform: rotateX(180deg) rotate(341.5deg); } } `; /** * `<mat-progress-spinner>` component. */ @Component({ selector: 'mat-progress-spinner, mat-spinner', exportAs: 'matProgressSpinner', host: { 'role': 'progressbar', // `mat-spinner` is here for backward compatibility. 'class': 'mat-progress-spinner mat-spinner', // set tab index to -1 so screen readers will read the aria-label // Note: there is a known issue with JAWS that does not read progressbar aria labels on FireFox 'tabindex': '-1', '[class._mat-animation-noopable]': `_noopAnimations`, '[style.width.px]': 'diameter', '[style.height.px]': 'diameter', '[attr.aria-valuemin]': 'mode === "determinate" ? 0 : null', '[attr.aria-valuemax]': 'mode === "determinate" ? 100 : null', '[attr.aria-valuenow]': 'mode === "determinate" ? value : null', '[attr.mode]': 'mode', }, inputs: ['color'], templateUrl: 'progress-spinner.html', styleUrls: ['progress-spinner.css'], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, }) export class MatProgressSpinner extends _MatProgressSpinnerBase implements OnInit, OnDestroy, CanColor { private _diameter = BASE_SIZE; private _value = 0; private _strokeWidth: number; private _resizeSubscription = Subscription.EMPTY; /** * Element to which we should add the generated style tags for the indeterminate animation. * For most elements this is the document, but for the ones in the Shadow DOM we need to * use the shadow root. */ private _styleRoot: Node; /** * Tracks diameters of existing instances to de-dupe generated styles (default d = 100). * We need to keep track of which elements the diameters were attached to, because for * elements in the Shadow DOM the style tags are attached to the shadow root, rather * than the document head. */ private static _diameters = new WeakMap<Node, Set<number>>(); /** Whether the _mat-animation-noopable class should be applied, disabling animations. */ _noopAnimations: boolean; /** A string that is used for setting the spinner animation-name CSS property */ _spinnerAnimationLabel: string; /** The diameter of the progress spinner (will set width and height of svg). */ @Input() get diameter(): number { return this._diameter; } set diameter(size: NumberInput) { this._diameter = coerceNumberProperty(size); this._spinnerAnimationLabel = this._getSpinnerAnimationLabel(); // If this is set before `ngOnInit`, the style root may not have been resolved yet. if (this._styleRoot) { this._attachStyleNode(); } } /** Stroke width of the progress spinner. */ @Input() get strokeWidth(): number { return this._strokeWidth || this.diameter / 10; } set strokeWidth(value: NumberInput) { this._strokeWidth = coerceNumberProperty(value); } /** Mode of the progress circle */ @Input() mode: ProgressSpinnerMode = 'determinate'; /** Value of the progress circle. */ @Input() get value(): number { return this.mode === 'determinate' ? this._value : 0; } set value(newValue: NumberInput) { this._value = Math.max(0, Math.min(100, coerceNumberProperty(newValue))); } constructor( elementRef: ElementRef<HTMLElement>, _platform: Platform, @Optional() @Inject(DOCUMENT) private _document: any, @Optional() @Inject(ANIMATION_MODULE_TYPE) animationMode: string, @Inject(MAT_PROGRESS_SPINNER_DEFAULT_OPTIONS) defaults?: MatProgressSpinnerDefaultOptions, /** * @deprecated `changeDetectorRef`, `viewportRuler` and `ngZone` * parameters to become required. * @breaking-change 14.0.0 */ changeDetectorRef?: ChangeDetectorRef, viewportRuler?: ViewportRuler, ngZone?: NgZone, ) { super(elementRef); const trackedDiameters = MatProgressSpinner._diameters; this._spinnerAnimationLabel = this._getSpinnerAnimationLabel(); // The base size is already inserted via the component's structural styles. We still // need to track it so we don't end up adding the same styles again. if (!trackedDiameters.has(_document.head)) { trackedDiameters.set(_document.head, new Set<number>([BASE_SIZE])); } this._noopAnimations = animationMode === 'NoopAnimations' && !!defaults && !defaults._forceAnimations; if (elementRef.nativeElement.nodeName.toLowerCase() === 'mat-spinner') { this.mode = 'indeterminate'; } if (defaults) { if (defaults.color) { this.color = this.defaultColor = defaults.color; } if (defaults.diameter) { this.diameter = defaults.diameter; } if (defaults.strokeWidth) { this.strokeWidth = defaults.strokeWidth; } } // Safari has an issue where the circle isn't positioned correctly when the page has a // different zoom level from the default. This handler triggers a recalculation of the // `transform-origin` when the page zoom level changes. // See `_getCircleTransformOrigin` for more info. // @breaking-change 14.0.0 Remove null checks for `_changeDetectorRef`, // `viewportRuler` and `ngZone`. if (_platform.isBrowser && _platform.SAFARI && viewportRuler && changeDetectorRef && ngZone) { this._resizeSubscription = viewportRuler.change(150).subscribe(() => { // When the window is resize while the spinner is in `indeterminate` mode, we // have to mark for check so the transform origin of the circle can be recomputed. if (this.mode === 'indeterminate') { ngZone.run(() => changeDetectorRef.markForCheck()); } }); } } ngOnInit() { const element = this._elementRef.nativeElement; // Note that we need to look up the root node in ngOnInit, rather than the constructor, because // Angular seems to create the element outside the shadow root and then moves it inside, if the // node is inside an `ngIf` and a ShadowDom-encapsulated component. this._styleRoot = _getShadowRoot(element) || this._document.head; this._attachStyleNode(); element.classList.add('mat-progress-spinner-indeterminate-animation'); } ngOnDestroy() { this._resizeSubscription.unsubscribe(); } /** The radius of the spinner, adjusted for stroke width. */ _getCircleRadius() { return (this.diameter - BASE_STROKE_WIDTH) / 2; } /** The view box of the spinner's svg element. */ _getViewBox() { const viewBox = this._getCircleRadius() * 2 + this.strokeWidth; return `0 0 ${viewBox} ${viewBox}`; } /** The stroke circumference of the svg circle. */ _getStrokeCircumference(): number { return 2 * Math.PI * this._getCircleRadius(); } /** The dash offset of the svg circle. */ _getStrokeDashOffset() { if (this.mode === 'determinate') { return (this._getStrokeCircumference() * (100 - this._value)) / 100; } return null; } /** Stroke width of the circle in percent. */ _getCircleStrokeWidth() { return (this.strokeWidth / this.diameter) * 100; } /** Gets the `transform-origin` for the inner circle element. */ _getCircleTransformOrigin(svg: HTMLElement): string { // Safari has an issue where the `transform-origin` doesn't work as expected when the page // has a different zoom level from the default. The problem appears to be that a zoom // is applied on the `svg` node itself. We can work around it by calculating the origin // based on the zoom level. On all other browsers the `currentScale` appears to always be 1. const scale = ((svg as unknown as SVGSVGElement).currentScale ?? 1) * 50; return `${scale}% ${scale}%`; } /** Dynamically generates a style tag containing the correct animation for this diameter. */ private _attachStyleNode(): void { const styleRoot = this._styleRoot; const currentDiameter = this._diameter; const diameters = MatProgressSpinner._diameters; let diametersForElement = diameters.get(styleRoot); if (!diametersForElement || !diametersForElement.has(currentDiameter)) { const styleTag: HTMLStyleElement = this._document.createElement('style'); styleTag.setAttribute('mat-spinner-animation', this._spinnerAnimationLabel); styleTag.textContent = this._getAnimationText(); styleRoot.appendChild(styleTag); if (!diametersForElement) { diametersForElement = new Set<number>(); diameters.set(styleRoot, diametersForElement); } diametersForElement.add(currentDiameter); } } /** Generates animation styles adjusted for the spinner's diameter. */ private _getAnimationText(): string { const strokeCircumference = this._getStrokeCircumference(); return ( INDETERMINATE_ANIMATION_TEMPLATE // Animation should begin at 5% and end at 80% .replace(/START_VALUE/g, `${0.95 * strokeCircumference}`) .replace(/END_VALUE/g, `${0.2 * strokeCircumference}`) .replace(/DIAMETER/g, `${this._spinnerAnimationLabel}`) ); } /** Returns the circle diameter formatted for use with the animation-name CSS property. */ private _getSpinnerAnimationLabel(): string { // The string of a float point number will include a period ‘.’ character, // which is not valid for a CSS animation-name. return this.diameter.toString().replace('.', '_'); } }
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { AssociateAdminAccountCommand, AssociateAdminAccountCommandInput, AssociateAdminAccountCommandOutput, } from "./commands/AssociateAdminAccountCommand"; import { DeleteAppsListCommand, DeleteAppsListCommandInput, DeleteAppsListCommandOutput, } from "./commands/DeleteAppsListCommand"; import { DeleteNotificationChannelCommand, DeleteNotificationChannelCommandInput, DeleteNotificationChannelCommandOutput, } from "./commands/DeleteNotificationChannelCommand"; import { DeletePolicyCommand, DeletePolicyCommandInput, DeletePolicyCommandOutput, } from "./commands/DeletePolicyCommand"; import { DeleteProtocolsListCommand, DeleteProtocolsListCommandInput, DeleteProtocolsListCommandOutput, } from "./commands/DeleteProtocolsListCommand"; import { DisassociateAdminAccountCommand, DisassociateAdminAccountCommandInput, DisassociateAdminAccountCommandOutput, } from "./commands/DisassociateAdminAccountCommand"; import { GetAdminAccountCommand, GetAdminAccountCommandInput, GetAdminAccountCommandOutput, } from "./commands/GetAdminAccountCommand"; import { GetAppsListCommand, GetAppsListCommandInput, GetAppsListCommandOutput } from "./commands/GetAppsListCommand"; import { GetComplianceDetailCommand, GetComplianceDetailCommandInput, GetComplianceDetailCommandOutput, } from "./commands/GetComplianceDetailCommand"; import { GetNotificationChannelCommand, GetNotificationChannelCommandInput, GetNotificationChannelCommandOutput, } from "./commands/GetNotificationChannelCommand"; import { GetPolicyCommand, GetPolicyCommandInput, GetPolicyCommandOutput } from "./commands/GetPolicyCommand"; import { GetProtectionStatusCommand, GetProtectionStatusCommandInput, GetProtectionStatusCommandOutput, } from "./commands/GetProtectionStatusCommand"; import { GetProtocolsListCommand, GetProtocolsListCommandInput, GetProtocolsListCommandOutput, } from "./commands/GetProtocolsListCommand"; import { GetViolationDetailsCommand, GetViolationDetailsCommandInput, GetViolationDetailsCommandOutput, } from "./commands/GetViolationDetailsCommand"; import { ListAppsListsCommand, ListAppsListsCommandInput, ListAppsListsCommandOutput, } from "./commands/ListAppsListsCommand"; import { ListComplianceStatusCommand, ListComplianceStatusCommandInput, ListComplianceStatusCommandOutput, } from "./commands/ListComplianceStatusCommand"; import { ListMemberAccountsCommand, ListMemberAccountsCommandInput, ListMemberAccountsCommandOutput, } from "./commands/ListMemberAccountsCommand"; import { ListPoliciesCommand, ListPoliciesCommandInput, ListPoliciesCommandOutput, } from "./commands/ListPoliciesCommand"; import { ListProtocolsListsCommand, ListProtocolsListsCommandInput, ListProtocolsListsCommandOutput, } from "./commands/ListProtocolsListsCommand"; import { ListTagsForResourceCommand, ListTagsForResourceCommandInput, ListTagsForResourceCommandOutput, } from "./commands/ListTagsForResourceCommand"; import { PutAppsListCommand, PutAppsListCommandInput, PutAppsListCommandOutput } from "./commands/PutAppsListCommand"; import { PutNotificationChannelCommand, PutNotificationChannelCommandInput, PutNotificationChannelCommandOutput, } from "./commands/PutNotificationChannelCommand"; import { PutPolicyCommand, PutPolicyCommandInput, PutPolicyCommandOutput } from "./commands/PutPolicyCommand"; import { PutProtocolsListCommand, PutProtocolsListCommandInput, PutProtocolsListCommandOutput, } from "./commands/PutProtocolsListCommand"; import { TagResourceCommand, TagResourceCommandInput, TagResourceCommandOutput } from "./commands/TagResourceCommand"; import { UntagResourceCommand, UntagResourceCommandInput, UntagResourceCommandOutput, } from "./commands/UntagResourceCommand"; import { FMSClient } from "./FMSClient"; /** * <p>This is the <i>Firewall Manager API Reference</i>. This guide is for * developers who need detailed information about the Firewall Manager API actions, data * types, and errors. For detailed information about Firewall Manager features, see the * <a href="https://docs.aws.amazon.com/waf/latest/developerguide/fms-chapter.html">Firewall Manager Developer Guide</a>.</p> * <p>Some API actions require explicit resource permissions. For information, see the developer guide topic * <a href="https://docs.aws.amazon.com/waf/latest/developerguide/fms-api-permissions-ref.html">Firewall Manager required permissions for API actions</a>. * </p> */ export class FMS extends FMSClient { /** * <p>Sets the Firewall Manager administrator account. The account must be * a member of the organization in Organizations whose resources you want to protect. * Firewall Manager sets the permissions that allow the account to administer your Firewall Manager policies.</p> * <p>The account that you associate with Firewall Manager is called the Firewall Manager administrator account. </p> */ public associateAdminAccount( args: AssociateAdminAccountCommandInput, options?: __HttpHandlerOptions ): Promise<AssociateAdminAccountCommandOutput>; public associateAdminAccount( args: AssociateAdminAccountCommandInput, cb: (err: any, data?: AssociateAdminAccountCommandOutput) => void ): void; public associateAdminAccount( args: AssociateAdminAccountCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: AssociateAdminAccountCommandOutput) => void ): void; public associateAdminAccount( args: AssociateAdminAccountCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AssociateAdminAccountCommandOutput) => void), cb?: (err: any, data?: AssociateAdminAccountCommandOutput) => void ): Promise<AssociateAdminAccountCommandOutput> | void { const command = new AssociateAdminAccountCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Permanently deletes an Firewall Manager applications list.</p> */ public deleteAppsList( args: DeleteAppsListCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteAppsListCommandOutput>; public deleteAppsList( args: DeleteAppsListCommandInput, cb: (err: any, data?: DeleteAppsListCommandOutput) => void ): void; public deleteAppsList( args: DeleteAppsListCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteAppsListCommandOutput) => void ): void; public deleteAppsList( args: DeleteAppsListCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteAppsListCommandOutput) => void), cb?: (err: any, data?: DeleteAppsListCommandOutput) => void ): Promise<DeleteAppsListCommandOutput> | void { const command = new DeleteAppsListCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes an Firewall Manager association with the IAM role and the Amazon Simple * Notification Service (SNS) topic that is used to record Firewall Manager SNS logs.</p> */ public deleteNotificationChannel( args: DeleteNotificationChannelCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteNotificationChannelCommandOutput>; public deleteNotificationChannel( args: DeleteNotificationChannelCommandInput, cb: (err: any, data?: DeleteNotificationChannelCommandOutput) => void ): void; public deleteNotificationChannel( args: DeleteNotificationChannelCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteNotificationChannelCommandOutput) => void ): void; public deleteNotificationChannel( args: DeleteNotificationChannelCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteNotificationChannelCommandOutput) => void), cb?: (err: any, data?: DeleteNotificationChannelCommandOutput) => void ): Promise<DeleteNotificationChannelCommandOutput> | void { const command = new DeleteNotificationChannelCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Permanently deletes an Firewall Manager policy. </p> */ public deletePolicy( args: DeletePolicyCommandInput, options?: __HttpHandlerOptions ): Promise<DeletePolicyCommandOutput>; public deletePolicy(args: DeletePolicyCommandInput, cb: (err: any, data?: DeletePolicyCommandOutput) => void): void; public deletePolicy( args: DeletePolicyCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeletePolicyCommandOutput) => void ): void; public deletePolicy( args: DeletePolicyCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeletePolicyCommandOutput) => void), cb?: (err: any, data?: DeletePolicyCommandOutput) => void ): Promise<DeletePolicyCommandOutput> | void { const command = new DeletePolicyCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Permanently deletes an Firewall Manager protocols list.</p> */ public deleteProtocolsList( args: DeleteProtocolsListCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteProtocolsListCommandOutput>; public deleteProtocolsList( args: DeleteProtocolsListCommandInput, cb: (err: any, data?: DeleteProtocolsListCommandOutput) => void ): void; public deleteProtocolsList( args: DeleteProtocolsListCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteProtocolsListCommandOutput) => void ): void; public deleteProtocolsList( args: DeleteProtocolsListCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteProtocolsListCommandOutput) => void), cb?: (err: any, data?: DeleteProtocolsListCommandOutput) => void ): Promise<DeleteProtocolsListCommandOutput> | void { const command = new DeleteProtocolsListCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Disassociates the account that has been set as the Firewall Manager administrator * account. To set a different account as the administrator account, you must submit an * <code>AssociateAdminAccount</code> request.</p> */ public disassociateAdminAccount( args: DisassociateAdminAccountCommandInput, options?: __HttpHandlerOptions ): Promise<DisassociateAdminAccountCommandOutput>; public disassociateAdminAccount( args: DisassociateAdminAccountCommandInput, cb: (err: any, data?: DisassociateAdminAccountCommandOutput) => void ): void; public disassociateAdminAccount( args: DisassociateAdminAccountCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DisassociateAdminAccountCommandOutput) => void ): void; public disassociateAdminAccount( args: DisassociateAdminAccountCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DisassociateAdminAccountCommandOutput) => void), cb?: (err: any, data?: DisassociateAdminAccountCommandOutput) => void ): Promise<DisassociateAdminAccountCommandOutput> | void { const command = new DisassociateAdminAccountCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns the Organizations account that is associated with Firewall Manager * as the Firewall Manager administrator.</p> */ public getAdminAccount( args: GetAdminAccountCommandInput, options?: __HttpHandlerOptions ): Promise<GetAdminAccountCommandOutput>; public getAdminAccount( args: GetAdminAccountCommandInput, cb: (err: any, data?: GetAdminAccountCommandOutput) => void ): void; public getAdminAccount( args: GetAdminAccountCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetAdminAccountCommandOutput) => void ): void; public getAdminAccount( args: GetAdminAccountCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetAdminAccountCommandOutput) => void), cb?: (err: any, data?: GetAdminAccountCommandOutput) => void ): Promise<GetAdminAccountCommandOutput> | void { const command = new GetAdminAccountCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about the specified Firewall Manager applications list.</p> */ public getAppsList(args: GetAppsListCommandInput, options?: __HttpHandlerOptions): Promise<GetAppsListCommandOutput>; public getAppsList(args: GetAppsListCommandInput, cb: (err: any, data?: GetAppsListCommandOutput) => void): void; public getAppsList( args: GetAppsListCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetAppsListCommandOutput) => void ): void; public getAppsList( args: GetAppsListCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetAppsListCommandOutput) => void), cb?: (err: any, data?: GetAppsListCommandOutput) => void ): Promise<GetAppsListCommandOutput> | void { const command = new GetAppsListCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns detailed compliance information about the specified member account. Details * include resources that are in and out of compliance with the specified policy. </p> * <ul> * <li> * <p>Resources are * considered noncompliant for WAF and Shield Advanced policies if the specified policy has * not been applied to them.</p> * </li> * <li> * <p>Resources are considered noncompliant for security group policies if * they are in scope of the policy, they violate one or more of the policy rules, and remediation * is disabled or not possible.</p> * </li> * <li> * <p>Resources are considered noncompliant for Network Firewall policies * if a firewall is missing in the VPC, if the firewall endpoint isn't set up in an expected Availability Zone and subnet, * if a subnet created by the Firewall Manager doesn't have the expected route table, * and for modifications to a firewall policy that violate the Firewall Manager policy's rules.</p> * </li> * <li> * <p>Resources are considered noncompliant for DNS Firewall policies * if a DNS Firewall rule group is missing from the rule group associations for the VPC. </p> * </li> * </ul> */ public getComplianceDetail( args: GetComplianceDetailCommandInput, options?: __HttpHandlerOptions ): Promise<GetComplianceDetailCommandOutput>; public getComplianceDetail( args: GetComplianceDetailCommandInput, cb: (err: any, data?: GetComplianceDetailCommandOutput) => void ): void; public getComplianceDetail( args: GetComplianceDetailCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetComplianceDetailCommandOutput) => void ): void; public getComplianceDetail( args: GetComplianceDetailCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetComplianceDetailCommandOutput) => void), cb?: (err: any, data?: GetComplianceDetailCommandOutput) => void ): Promise<GetComplianceDetailCommandOutput> | void { const command = new GetComplianceDetailCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Information * about the Amazon Simple Notification Service (SNS) topic that is used to * record Firewall Manager SNS logs.</p> */ public getNotificationChannel( args: GetNotificationChannelCommandInput, options?: __HttpHandlerOptions ): Promise<GetNotificationChannelCommandOutput>; public getNotificationChannel( args: GetNotificationChannelCommandInput, cb: (err: any, data?: GetNotificationChannelCommandOutput) => void ): void; public getNotificationChannel( args: GetNotificationChannelCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetNotificationChannelCommandOutput) => void ): void; public getNotificationChannel( args: GetNotificationChannelCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetNotificationChannelCommandOutput) => void), cb?: (err: any, data?: GetNotificationChannelCommandOutput) => void ): Promise<GetNotificationChannelCommandOutput> | void { const command = new GetNotificationChannelCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about the specified Firewall Manager policy.</p> */ public getPolicy(args: GetPolicyCommandInput, options?: __HttpHandlerOptions): Promise<GetPolicyCommandOutput>; public getPolicy(args: GetPolicyCommandInput, cb: (err: any, data?: GetPolicyCommandOutput) => void): void; public getPolicy( args: GetPolicyCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetPolicyCommandOutput) => void ): void; public getPolicy( args: GetPolicyCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetPolicyCommandOutput) => void), cb?: (err: any, data?: GetPolicyCommandOutput) => void ): Promise<GetPolicyCommandOutput> | void { const command = new GetPolicyCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>If you created a Shield Advanced policy, returns policy-level attack summary information * in the event of a potential DDoS attack. Other policy types are currently unsupported.</p> */ public getProtectionStatus( args: GetProtectionStatusCommandInput, options?: __HttpHandlerOptions ): Promise<GetProtectionStatusCommandOutput>; public getProtectionStatus( args: GetProtectionStatusCommandInput, cb: (err: any, data?: GetProtectionStatusCommandOutput) => void ): void; public getProtectionStatus( args: GetProtectionStatusCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetProtectionStatusCommandOutput) => void ): void; public getProtectionStatus( args: GetProtectionStatusCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetProtectionStatusCommandOutput) => void), cb?: (err: any, data?: GetProtectionStatusCommandOutput) => void ): Promise<GetProtectionStatusCommandOutput> | void { const command = new GetProtectionStatusCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about the specified Firewall Manager protocols list.</p> */ public getProtocolsList( args: GetProtocolsListCommandInput, options?: __HttpHandlerOptions ): Promise<GetProtocolsListCommandOutput>; public getProtocolsList( args: GetProtocolsListCommandInput, cb: (err: any, data?: GetProtocolsListCommandOutput) => void ): void; public getProtocolsList( args: GetProtocolsListCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetProtocolsListCommandOutput) => void ): void; public getProtocolsList( args: GetProtocolsListCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetProtocolsListCommandOutput) => void), cb?: (err: any, data?: GetProtocolsListCommandOutput) => void ): Promise<GetProtocolsListCommandOutput> | void { const command = new GetProtocolsListCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Retrieves violations for a resource based on the specified Firewall Manager policy and Amazon Web Services account.</p> */ public getViolationDetails( args: GetViolationDetailsCommandInput, options?: __HttpHandlerOptions ): Promise<GetViolationDetailsCommandOutput>; public getViolationDetails( args: GetViolationDetailsCommandInput, cb: (err: any, data?: GetViolationDetailsCommandOutput) => void ): void; public getViolationDetails( args: GetViolationDetailsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetViolationDetailsCommandOutput) => void ): void; public getViolationDetails( args: GetViolationDetailsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetViolationDetailsCommandOutput) => void), cb?: (err: any, data?: GetViolationDetailsCommandOutput) => void ): Promise<GetViolationDetailsCommandOutput> | void { const command = new GetViolationDetailsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns an array of <code>AppsListDataSummary</code> objects.</p> */ public listAppsLists( args: ListAppsListsCommandInput, options?: __HttpHandlerOptions ): Promise<ListAppsListsCommandOutput>; public listAppsLists( args: ListAppsListsCommandInput, cb: (err: any, data?: ListAppsListsCommandOutput) => void ): void; public listAppsLists( args: ListAppsListsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListAppsListsCommandOutput) => void ): void; public listAppsLists( args: ListAppsListsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListAppsListsCommandOutput) => void), cb?: (err: any, data?: ListAppsListsCommandOutput) => void ): Promise<ListAppsListsCommandOutput> | void { const command = new ListAppsListsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns an array of <code>PolicyComplianceStatus</code> objects. Use * <code>PolicyComplianceStatus</code> to get a summary of which member accounts are protected * by the specified policy. </p> */ public listComplianceStatus( args: ListComplianceStatusCommandInput, options?: __HttpHandlerOptions ): Promise<ListComplianceStatusCommandOutput>; public listComplianceStatus( args: ListComplianceStatusCommandInput, cb: (err: any, data?: ListComplianceStatusCommandOutput) => void ): void; public listComplianceStatus( args: ListComplianceStatusCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListComplianceStatusCommandOutput) => void ): void; public listComplianceStatus( args: ListComplianceStatusCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListComplianceStatusCommandOutput) => void), cb?: (err: any, data?: ListComplianceStatusCommandOutput) => void ): Promise<ListComplianceStatusCommandOutput> | void { const command = new ListComplianceStatusCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a <code>MemberAccounts</code> object that lists the member accounts in the * administrator's Amazon Web Services organization.</p> * <p>The <code>ListMemberAccounts</code> must be submitted by the account that is set as the * Firewall Manager administrator.</p> */ public listMemberAccounts( args: ListMemberAccountsCommandInput, options?: __HttpHandlerOptions ): Promise<ListMemberAccountsCommandOutput>; public listMemberAccounts( args: ListMemberAccountsCommandInput, cb: (err: any, data?: ListMemberAccountsCommandOutput) => void ): void; public listMemberAccounts( args: ListMemberAccountsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListMemberAccountsCommandOutput) => void ): void; public listMemberAccounts( args: ListMemberAccountsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListMemberAccountsCommandOutput) => void), cb?: (err: any, data?: ListMemberAccountsCommandOutput) => void ): Promise<ListMemberAccountsCommandOutput> | void { const command = new ListMemberAccountsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns an array of <code>PolicySummary</code> objects.</p> */ public listPolicies( args: ListPoliciesCommandInput, options?: __HttpHandlerOptions ): Promise<ListPoliciesCommandOutput>; public listPolicies(args: ListPoliciesCommandInput, cb: (err: any, data?: ListPoliciesCommandOutput) => void): void; public listPolicies( args: ListPoliciesCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListPoliciesCommandOutput) => void ): void; public listPolicies( args: ListPoliciesCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListPoliciesCommandOutput) => void), cb?: (err: any, data?: ListPoliciesCommandOutput) => void ): Promise<ListPoliciesCommandOutput> | void { const command = new ListPoliciesCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns an array of <code>ProtocolsListDataSummary</code> objects.</p> */ public listProtocolsLists( args: ListProtocolsListsCommandInput, options?: __HttpHandlerOptions ): Promise<ListProtocolsListsCommandOutput>; public listProtocolsLists( args: ListProtocolsListsCommandInput, cb: (err: any, data?: ListProtocolsListsCommandOutput) => void ): void; public listProtocolsLists( args: ListProtocolsListsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListProtocolsListsCommandOutput) => void ): void; public listProtocolsLists( args: ListProtocolsListsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListProtocolsListsCommandOutput) => void), cb?: (err: any, data?: ListProtocolsListsCommandOutput) => void ): Promise<ListProtocolsListsCommandOutput> | void { const command = new ListProtocolsListsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Retrieves the list of tags for the specified Amazon Web Services resource. </p> */ public listTagsForResource( args: ListTagsForResourceCommandInput, options?: __HttpHandlerOptions ): Promise<ListTagsForResourceCommandOutput>; public listTagsForResource( args: ListTagsForResourceCommandInput, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListTagsForResourceCommandOutput) => void ): void; public listTagsForResource( args: ListTagsForResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsForResourceCommandOutput) => void), cb?: (err: any, data?: ListTagsForResourceCommandOutput) => void ): Promise<ListTagsForResourceCommandOutput> | void { const command = new ListTagsForResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates an Firewall Manager applications list.</p> */ public putAppsList(args: PutAppsListCommandInput, options?: __HttpHandlerOptions): Promise<PutAppsListCommandOutput>; public putAppsList(args: PutAppsListCommandInput, cb: (err: any, data?: PutAppsListCommandOutput) => void): void; public putAppsList( args: PutAppsListCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: PutAppsListCommandOutput) => void ): void; public putAppsList( args: PutAppsListCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutAppsListCommandOutput) => void), cb?: (err: any, data?: PutAppsListCommandOutput) => void ): Promise<PutAppsListCommandOutput> | void { const command = new PutAppsListCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Designates the IAM role and Amazon Simple Notification Service (SNS) topic that * Firewall Manager uses to record SNS logs.</p> * <p>To perform this action outside of the console, you must configure the SNS topic to allow the Firewall Manager * role <code>AWSServiceRoleForFMS</code> to publish SNS logs. For more information, see * <a href="https://docs.aws.amazon.com/waf/latest/developerguide/fms-api-permissions-ref.html">Firewall Manager required permissions for API actions</a> in the <i>Firewall Manager Developer Guide</i>.</p> */ public putNotificationChannel( args: PutNotificationChannelCommandInput, options?: __HttpHandlerOptions ): Promise<PutNotificationChannelCommandOutput>; public putNotificationChannel( args: PutNotificationChannelCommandInput, cb: (err: any, data?: PutNotificationChannelCommandOutput) => void ): void; public putNotificationChannel( args: PutNotificationChannelCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: PutNotificationChannelCommandOutput) => void ): void; public putNotificationChannel( args: PutNotificationChannelCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutNotificationChannelCommandOutput) => void), cb?: (err: any, data?: PutNotificationChannelCommandOutput) => void ): Promise<PutNotificationChannelCommandOutput> | void { const command = new PutNotificationChannelCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates an Firewall Manager policy.</p> * <p>Firewall Manager provides the following types of policies: </p> * <ul> * <li> * <p>An WAF policy (type WAFV2), which defines rule groups to run first in the * corresponding WAF web ACL and rule groups to run last in the web ACL.</p> * </li> * <li> * <p>An WAF Classic policy (type WAF), which defines a rule group. </p> * </li> * <li> * <p>A Shield Advanced policy, which applies Shield Advanced protection to specified * accounts and resources.</p> * </li> * <li> * <p>A security group policy, which manages VPC security groups across your Amazon Web Services * organization. </p> * </li> * <li> * <p>An Network Firewall policy, which provides firewall rules to filter network traffic in specified * Amazon VPCs.</p> * </li> * <li> * <p>A DNS Firewall policy, which provides Route 53 Resolver DNS Firewall rules to filter DNS queries for * specified VPCs.</p> * </li> * </ul> * <p>Each policy is specific to one of the types. If you want to enforce more than one * policy type across accounts, create multiple policies. You can create multiple * policies for each type.</p> * <p>You must be subscribed to Shield Advanced to create a Shield Advanced policy. For more * information about subscribing to Shield Advanced, see * <a href="https://docs.aws.amazon.com/waf/latest/DDOSAPIReference/API_CreateSubscription.html">CreateSubscription</a>.</p> */ public putPolicy(args: PutPolicyCommandInput, options?: __HttpHandlerOptions): Promise<PutPolicyCommandOutput>; public putPolicy(args: PutPolicyCommandInput, cb: (err: any, data?: PutPolicyCommandOutput) => void): void; public putPolicy( args: PutPolicyCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: PutPolicyCommandOutput) => void ): void; public putPolicy( args: PutPolicyCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutPolicyCommandOutput) => void), cb?: (err: any, data?: PutPolicyCommandOutput) => void ): Promise<PutPolicyCommandOutput> | void { const command = new PutPolicyCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates an Firewall Manager protocols list.</p> */ public putProtocolsList( args: PutProtocolsListCommandInput, options?: __HttpHandlerOptions ): Promise<PutProtocolsListCommandOutput>; public putProtocolsList( args: PutProtocolsListCommandInput, cb: (err: any, data?: PutProtocolsListCommandOutput) => void ): void; public putProtocolsList( args: PutProtocolsListCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: PutProtocolsListCommandOutput) => void ): void; public putProtocolsList( args: PutProtocolsListCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutProtocolsListCommandOutput) => void), cb?: (err: any, data?: PutProtocolsListCommandOutput) => void ): Promise<PutProtocolsListCommandOutput> | void { const command = new PutProtocolsListCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Adds one or more tags to an Amazon Web Services resource.</p> */ public tagResource(args: TagResourceCommandInput, options?: __HttpHandlerOptions): Promise<TagResourceCommandOutput>; public tagResource(args: TagResourceCommandInput, cb: (err: any, data?: TagResourceCommandOutput) => void): void; public tagResource( args: TagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: TagResourceCommandOutput) => void ): void; public tagResource( args: TagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: TagResourceCommandOutput) => void), cb?: (err: any, data?: TagResourceCommandOutput) => void ): Promise<TagResourceCommandOutput> | void { const command = new TagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes one or more tags from an Amazon Web Services resource.</p> */ public untagResource( args: UntagResourceCommandInput, options?: __HttpHandlerOptions ): Promise<UntagResourceCommandOutput>; public untagResource( args: UntagResourceCommandInput, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UntagResourceCommandOutput) => void ): void; public untagResource( args: UntagResourceCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UntagResourceCommandOutput) => void), cb?: (err: any, data?: UntagResourceCommandOutput) => void ): Promise<UntagResourceCommandOutput> | void { const command = new UntagResourceCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
import {PipelineValidationService} from "../../services/pipeline-validation.service"; import {JsplumbService} from "../../services/jsplumb.service"; import {PipelineEditorService} from "../../services/pipeline-editor.service"; import {JsplumbBridge} from "../../services/jsplumb-bridge.service"; import {ShepherdService} from "../../../services/tour/shepherd.service"; import {Component, EventEmitter, Input, NgZone, OnDestroy, OnInit, Output} from "@angular/core"; import { InvocablePipelineElementUnion, PipelineElementConfig, PipelineElementUnion } from "../../model/editor.model"; import { CustomOutputStrategy, DataProcessorInvocation, DataSinkInvocation, Pipeline, PipelineCanvasMetadata, PipelinePreviewModel, SpDataSet, SpDataStream } from "../../../core-model/gen/streampipes-model"; import {ObjectProvider} from "../../services/object-provider.service"; import {CustomizeComponent} from "../../dialog/customize/customize.component"; import {PanelType} from "../../../core-ui/dialog/base-dialog/base-dialog.model"; import {DialogService} from "../../../core-ui/dialog/base-dialog/base-dialog.service"; import {EditorService} from "../../services/editor.service"; import {MatchingResultMessage} from "../../../core-model/gen/streampipes-model-client"; import {MatchingErrorComponent} from "../../dialog/matching-error/matching-error.component"; import {Tuple2} from "../../../core-model/base/Tuple2"; import {ConfirmDialogComponent} from "../../../core-ui/dialog/confirm-dialog/confirm-dialog.component"; import {MatDialog} from "@angular/material/dialog"; import {forkJoin} from "rxjs"; import {JsplumbFactoryService} from "../../services/jsplumb-factory.service"; import {PipelinePositioningService} from "../../services/pipeline-positioning.service"; @Component({ selector: 'pipeline', templateUrl: './pipeline.component.html', styleUrls: ['./pipeline.component.css'] }) export class PipelineComponent implements OnInit, OnDestroy { @Input() pipelineValid: boolean; @Input() canvasId: string; @Input() rawPipelineModel: PipelineElementConfig[]; @Input() allElements: PipelineElementUnion[]; @Input() preview: boolean; @Input() pipelineCached: boolean; @Output() pipelineCachedChanged: EventEmitter<boolean> = new EventEmitter<boolean>(); @Input() pipelineCacheRunning: boolean; @Input() pipelineCanvasMetadata: PipelineCanvasMetadata; @Output() pipelineCacheRunningChanged: EventEmitter<boolean> = new EventEmitter<boolean>(); availablePipelineElementCache: PipelineElementUnion[]; plumbReady: boolean; currentMouseOverElement: string; currentPipelineModel: Pipeline; idCounter: any; currentZoomLevel: any; TransitionService: any; canvasWidth: string = "100%"; canvasHeight: string = "100%"; JsplumbBridge: JsplumbBridge; previewModeActive: boolean = false; pipelinePreview: PipelinePreviewModel; constructor(private JsplumbService: JsplumbService, private PipelineEditorService: PipelineEditorService, private PipelinePositioningService: PipelinePositioningService, private JsplumbFactoryService: JsplumbFactoryService, private ObjectProvider: ObjectProvider, private EditorService: EditorService, private ShepherdService: ShepherdService, private PipelineValidationService: PipelineValidationService, private dialogService: DialogService, private dialog: MatDialog, private ngZone: NgZone,) { this.plumbReady = false; this.currentMouseOverElement = ""; this.currentPipelineModel = new Pipeline(); this.idCounter = 0; this.currentZoomLevel = 1; } ngOnInit() { this.JsplumbBridge = this.JsplumbFactoryService.getJsplumbBridge(this.preview); this.JsplumbBridge.setContainer(this.canvasId); this.initAssembly(); this.initPlumb(); } ngAfterViewInit() { } validatePipeline() { setTimeout(() => { this.ngZone.run(() => { this.pipelineValid = this.PipelineValidationService .isValidPipeline(this.rawPipelineModel.filter(pe => !(pe.settings.disabled)), this.preview); }); }); } ngOnDestroy() { this.deletePipelineElementPreview(false); this.JsplumbBridge.deleteEveryEndpoint(); this.plumbReady = false; } updateMouseover(elementId) { this.currentMouseOverElement = elementId; } updateOptionsClick(elementId) { if (this.currentMouseOverElement == elementId) { this.currentMouseOverElement = ""; } else { this.currentMouseOverElement = elementId; } } getElementCss(currentPipelineElementSettings) { return "position:absolute;" + (this.preview ? "width:75px;" : "width:110px;") + (this.preview ? "height:75px;" : "height:110px;") + "left: " + currentPipelineElementSettings.position.x + "px; " + "top: " + currentPipelineElementSettings.position.y + "px; " } getElementCssClasses(currentPipelineElement) { return currentPipelineElement.type + " " + (currentPipelineElement.settings.openCustomize ? "" : "") + currentPipelineElement.settings.connectable + " " + currentPipelineElement.settings.displaySettings; } isStreamInPipeline() { return this.isInPipeline('stream'); } isSetInPipeline() { return this.isInPipeline('set'); } isInPipeline(type) { return this.rawPipelineModel.some(x => (x.type == type && !(x.settings.disabled))); } showMixedStreamAlert() { this.dialog.open(ConfirmDialogComponent, { width: '500px', data: { "title": "Currently, it is not possible to mix data streams and data sets in a single pipeline.", "confirmAndCancel": false, "okTitle": "Ok", }, }); } findPipelineElementByElementId(elementId: string) { return this.allElements.find(a => a.elementId === elementId); } initAssembly() { ($('#assembly') as any).droppable({ tolerance: "fit", drop: (element, ui) => { let pipelineElementId = ui.draggable.data("pe"); let pipelineElement: PipelineElementUnion = this.findPipelineElementByElementId(pipelineElementId); if (ui.draggable.hasClass('draggable-icon')) { this.EditorService.makePipelineAssemblyEmpty(false); let newElementId = pipelineElement.elementId + ":" + this.JsplumbService.makeId(5); let pipelineElementConfig = this.JsplumbService.createNewPipelineElementConfig(pipelineElement, this.PipelineEditorService.getCoordinates(ui, this.currentZoomLevel), false, false, newElementId); if ((this.isStreamInPipeline() && pipelineElementConfig.type == 'set') || this.isSetInPipeline() && pipelineElementConfig.type == 'stream') { this.showMixedStreamAlert(); } else { this.rawPipelineModel.push(pipelineElementConfig); if (ui.draggable.hasClass('set')) { setTimeout(() => { this.EditorService.updateDataSet(pipelineElementConfig.payload).subscribe(data => { (pipelineElementConfig.payload as SpDataSet).eventGrounding = data.eventGrounding; (pipelineElementConfig.payload as SpDataSet).datasetInvocationId = data.invocationId; this.JsplumbService.dataStreamDropped(pipelineElementConfig.payload.dom, pipelineElementConfig.payload as SpDataSet, true, false); }); }, 0); } else if (ui.draggable.hasClass('stream')) { this.checkTopicModel(pipelineElementConfig); } else if (ui.draggable.hasClass('sepa')) { setTimeout(() => { this.JsplumbService.dataProcessorDropped(pipelineElementConfig.payload.dom, pipelineElementConfig.payload as DataProcessorInvocation, true, false); }, 10); } else if (ui.draggable.hasClass('action')) { setTimeout(() => { this.JsplumbService.dataSinkDropped(pipelineElementConfig.payload.dom, pipelineElementConfig.payload as DataSinkInvocation, true, false); }, 10); } if (this.ShepherdService.isTourActive()) { this.ShepherdService.trigger("drop-" + pipelineElementConfig.type); } } } this.JsplumbBridge.repaintEverything(); this.validatePipeline(); this.triggerPipelineCacheUpdate(); } }); //End #assembly.droppable() } checkTopicModel(pipelineElementConfig: PipelineElementConfig) { setTimeout(() => { this.JsplumbService.dataStreamDropped(pipelineElementConfig.payload.dom, pipelineElementConfig.payload as SpDataStream, true, false); }, 10); var streamDescription = pipelineElementConfig.payload as SpDataStream; if (streamDescription .eventGrounding .transportProtocols[0] .topicDefinition["@class"] === "org.apache.streampipes.model.grounding.WildcardTopicDefinition") { //this.EditorDialogManager.showCustomizeStreamDialog(streamDescription); } } handleDeleteOption(pipelineElement: PipelineElementConfig) { this.JsplumbBridge.removeAllEndpoints(pipelineElement.payload.dom); this.rawPipelineModel.forEach(pe => { if (pe.payload.dom == pipelineElement.payload.dom) { pe.settings.disabled = true; } }); if (this.rawPipelineModel.every(pe => pe.settings.disabled)) { this.EditorService.makePipelineAssemblyEmpty(true); } this.JsplumbBridge.repaintEverything(); this.validatePipeline(); this.triggerPipelineCacheUpdate(); } initPlumb() { //this.JsplumbService.prepareJsplumb(); this.JsplumbBridge.unbind("connection"); this.JsplumbBridge.bind("connectionMoved", (info, originalEvent) => { var pe = this.ObjectProvider.findElement(info.newTargetEndpoint.elementId, this.rawPipelineModel); var oldPe = this.ObjectProvider.findElement(info.originalTargetEndpoint.elementId, this.rawPipelineModel); (oldPe.payload as InvocablePipelineElementUnion).configured = false; (pe.payload as InvocablePipelineElementUnion).configured = false; }); this.JsplumbBridge.bind("connectionDetached", (info, originalEvent) => { var pe = this.ObjectProvider.findElement(info.targetEndpoint.elementId, this.rawPipelineModel); (pe.payload as InvocablePipelineElementUnion).configured = false; pe.settings.openCustomize = true; info.targetEndpoint.setType("empty"); this.validatePipeline(); }); this.JsplumbBridge.bind("connectionDrag", connection => { this.JsplumbBridge.selectEndpoints().each(function (endpoint) { if (endpoint.isTarget && endpoint.connections.length === 0) { endpoint.setType("highlight"); } }); }); this.JsplumbBridge.bind("connectionAborted", connection => { this.JsplumbBridge.selectEndpoints().each(endpoint => { if (endpoint.isTarget && endpoint.connections.length === 0) { endpoint.setType("empty"); } }); }) this.JsplumbBridge.bind("connection", (info, originalEvent) => { var pe = this.ObjectProvider.findElement(info.target.id, this.rawPipelineModel); if (pe.settings.openCustomize) { this.currentPipelineModel = this.ObjectProvider.makePipeline(this.rawPipelineModel); pe.settings.loadingStatus = true; this.ObjectProvider.updatePipeline(this.currentPipelineModel) .subscribe(pipelineModificationMessage => { pe.settings.loadingStatus = false; info.targetEndpoint.setType("token"); this.validatePipeline(); this.modifyPipeline(pipelineModificationMessage.pipelineModifications); if (this.JsplumbService.isFullyConnected(pe, this.preview)) { let payload = pe.payload as InvocablePipelineElementUnion; if ((payload.staticProperties && payload.staticProperties.length > 0) || this.isCustomOutput(pe)) { this.showCustomizeDialog({a: false, b: pe}); } else { (pe.payload as InvocablePipelineElementUnion).configured = true; pe.settings.completed = true; this.announceConfiguredElement(pe); } } }, status => { pe.settings.loadingStatus = false; this.JsplumbBridge.detach(info.connection); if (Array.isArray(status.error)) { let matchingResultMessage = (status.error as any[]).map(e => MatchingResultMessage.fromData(e as MatchingResultMessage)); this.showMatchingErrorDialog(matchingResultMessage); } else { this.showErrorDialog(status.error.title, status.error.description); } }); } }); window.onresize = (event) => { this.JsplumbBridge.repaintEverything(); }; setTimeout(() => { this.plumbReady = true; }, 100); } modifyPipeline(pipelineModifications) { if (pipelineModifications) { pipelineModifications.forEach(modification => { var id = modification.domId; if (id !== "undefined") { var pe = this.ObjectProvider.findElement(id, this.rawPipelineModel); (pe.payload as InvocablePipelineElementUnion).staticProperties = modification.staticProperties; (pe.payload as DataProcessorInvocation).outputStrategies = modification.outputStrategies; (pe.payload as InvocablePipelineElementUnion).inputStreams = modification.inputStreams; } }); } } isCustomOutput(pe) { var custom = false; pe.payload.outputStrategies.forEach(strategy => { if (strategy instanceof CustomOutputStrategy) { custom = true; } }); return custom; } triggerPipelineCacheUpdate() { setTimeout(() => { this.pipelineCacheRunning = true; this.pipelineCacheRunningChanged.emit(this.pipelineCacheRunning); this.PipelinePositioningService.collectPipelineElementPositions(this.pipelineCanvasMetadata, this.rawPipelineModel); let updateCachedPipeline = this.EditorService.updateCachedPipeline(this.rawPipelineModel); let updateCachedCanvasMetadata = this.EditorService.updateCachedCanvasMetadata(this.pipelineCanvasMetadata); forkJoin([updateCachedPipeline, updateCachedCanvasMetadata]).subscribe(msg => { this.pipelineCacheRunning = false; this.pipelineCacheRunningChanged.emit(this.pipelineCacheRunning) this.pipelineCached = true; this.pipelineCachedChanged.emit(this.pipelineCached); }); }); } showErrorDialog(title, description) { this.dialog.open(ConfirmDialogComponent, { width: '500px', data: { "title": title, "subtitle": description, "okTitle": "Ok", "confirmAndCancel": false }, }); } showMatchingErrorDialog(matchingResultMessage: MatchingResultMessage[]) { this.dialogService.open(MatchingErrorComponent, { panelType: PanelType.STANDARD_PANEL, title: "Invalid Connection", data: { "matchingResultMessage": matchingResultMessage } }); } showCustomizeDialog(pipelineElementInfo: Tuple2<Boolean, PipelineElementConfig>) { const dialogRef = this.dialogService.open(CustomizeComponent, { panelType: PanelType.SLIDE_IN_PANEL, title: "Customize " + pipelineElementInfo.b.payload.name, width: "50vw", data: { "pipelineElement": pipelineElementInfo.b, "restrictedEditMode": pipelineElementInfo.a } }); dialogRef.afterClosed().subscribe(c => { if (c) { pipelineElementInfo.b.settings.openCustomize = false; (pipelineElementInfo.b.payload as InvocablePipelineElementUnion).configured = true; if (!(pipelineElementInfo.b.payload instanceof DataSinkInvocation)) { this.JsplumbBridge.activateEndpoint("out-" + pipelineElementInfo.b.payload.dom, pipelineElementInfo.b.settings.completed); } this.JsplumbBridge.getSourceEndpoint(pipelineElementInfo.b.payload.dom).setType("token"); this.triggerPipelineCacheUpdate(); this.announceConfiguredElement(pipelineElementInfo.b); if (this.previewModeActive) { this.deletePipelineElementPreview(true); } } this.validatePipeline(); }); } announceConfiguredElement(pe: PipelineElementConfig) { this.EditorService.announceConfiguredElement(pe.payload.dom); } initiatePipelineElementPreview() { if (!this.previewModeActive) { let pipeline = this.ObjectProvider.makePipeline(this.rawPipelineModel); this.EditorService.initiatePipelinePreview(pipeline).subscribe(response => { this.pipelinePreview = response; this.previewModeActive = true; }); } else { this.deletePipelineElementPreview(false); } } deletePipelineElementPreview(resume: boolean) { if (this.previewModeActive) { this.EditorService.deletePipelinePreviewRequest(this.pipelinePreview.previewId).subscribe(response => { this.previewModeActive = false; if (resume) { this.initiatePipelineElementPreview(); } }); } } }
the_stack
import { Directive, OnInit } from '@angular/core'; import { AbstractControl, FormGroup, ValidatorFn } from '@angular/forms'; // Third party imports import { distinctUntilChanged, takeUntil } from 'rxjs/operators'; import { Subject } from 'rxjs'; // App imports import { AppEdition } from 'src/app/shared/constants/branding.constants'; import AppServices from 'src/app/shared/service/appServices'; import { BasicSubscriber } from 'src/app/shared/abstracts/basic-subscriber'; import { EditionData } from 'src/app/shared/service/branding.service'; import { FormUtility } from '../components/steps/form-utility'; import { IpFamilyEnum } from 'src/app/shared/constants/app.constants'; import { Notification, NotificationTypes } from 'src/app/shared/components/alert-notification/alert-notification.component'; import { StepCompletedPayload, StepDescriptionChangePayload, TanzuEvent, TanzuEventType } from 'src/app/shared/service/Messenger'; import { StepMapping } from '../field-mapping/FieldMapping'; import { StepRegistrantData } from '../wizard-base/wizard-base'; import { UserDataIdentifier } from '../../../../../shared/service/user-data.service'; import { ValidatorEnum } from './../constants/validation.constants'; export interface StepDescriptionTriggers { clusterTypeDescriptor?: boolean, fields?: string[], } /** * Abstract class that's available for stepper component to extend. * It captures the common logic that should happen to most if not all * stepper components. */ @Directive() export abstract class StepFormDirective extends BasicSubscriber implements OnInit { wizardName: string; formName; formGroup: FormGroup; edition: AppEdition = AppEdition.TCE; validatorEnum = ValidatorEnum; errorNotification: string = ''; configFileNotification: Notification; private clusterTypeDescription: string = ''; modeClusterStandalone: boolean; ipFamily: IpFamilyEnum = IpFamilyEnum.IPv4; clusterTypeDescriptorUsedInDescription: boolean; // This map is made available to HTML pages to display labels before fields htmlFieldLabels: Map<string, string>; protected quietly = { onlySelf: true, emitEvent: false }; // convenient when setting field values protected eventFileImported: TanzuEventType; protected eventFileImportError: TanzuEventType; protected abstract storeUserData(); // This method is expected to be overridden by any step that provides a dynamic description of itself // (dynamic meaning depending on user-entered data). It is public to make it available for testing. dynamicDescription(): string { return null; } setStepRegistrantData(stepRegistrantData: StepRegistrantData) { this.formName = stepRegistrantData.step; this.formGroup = stepRegistrantData.formGroup; this.wizardName = stepRegistrantData.wizard; this.eventFileImported = stepRegistrantData.eventFileImported; this.eventFileImportError = stepRegistrantData.eventFileImportError; } protected registerDefaultFileImportErrorHandler(eventFailure: TanzuEventType) { AppServices.messenger.subscribe<string>(eventFailure, data => { // Capture the import file error message this.configFileNotification = { notificationType: NotificationTypes.ERROR, message: data.payload }; }); } ngOnInit(): void { this.getFormName(); this.subscribeToStepStartedEvents(); this.subscribeToStepCompletedEvents(); // set branding and cluster type on branding change for base wizard components AppServices.messenger.subscribe<EditionData>(TanzuEventType.BRANDING_CHANGED, data => { this.edition = data.payload.edition; this.setClusterTypeDescriptor(data.payload.clusterTypeDescriptor); }, this.unsubscribe); this.modeClusterStandalone = AppServices.appDataService.isModeClusterStandalone(); } /** * Infer form name from the formGroup object. */ getFormName() { if (this.formGroup && this.formGroup.parent && this.formGroup.parent.controls) { for (const name of Object.keys(this.formGroup.parent.controls)) { if (this.formGroup.parent.controls[name] === this.formGroup) { this.formName = name; break; } } } } // This method could be protected, since it's primarily intended for subclasses, // but since it's helpful for tests to be able to use it, we make it public getFieldValue(fieldName: string, suppressWarnings?: boolean): any { if (!this.formGroup) { if (!suppressWarnings) { console.error('getFieldValue(' + fieldName + ') called without a formGroup set'); } return; } if (!this.formGroup.controls[fieldName]) { if (!suppressWarnings) { console.error('getFieldValue(' + fieldName + ') called but no control by that name'); } return; } return this.formGroup.controls[fieldName].value; } getStoredValue(fieldName: string, stepMapping: StepMapping, defaultValue?: any) { const fieldMapping = AppServices.fieldMapUtilities.getFieldMapping(fieldName, stepMapping); const result = AppServices.userDataService.retrieveStoredValue(this.wizardName, this.formName, fieldMapping); if (result === undefined || result === null) { return defaultValue; } return result; } hasSavedData() { return AppServices.userDataService.hasStoredStepData(this.wizardName, this.formName); } // This method could be protected, since it's primarily intended for subclasses, // but since it's helpful for tests to be able to use it, we make it public setFieldValue(fieldName: string, value: any): void { const control = this.getControl(fieldName); if (control === undefined || control === null) { console.log('WARNING: setFieldValue() could not find field ' + fieldName + ' to set value to ' + value); } else { control.setValue(value); } } protected getControl(fieldName: string): AbstractControl { const control = this.formGroup.get(fieldName); if (control === undefined || control === null) { console.log('WARNING: getControl() could not find field ' + fieldName); } return control; } protected clearFieldSavedData(fieldName: string) { AppServices.userDataService.clear(this.createUserDataIdentifier(fieldName)); } protected clearControlValue(controlName: string, clearSavedData?: boolean) { this.setControlValueSafely(controlName, '' , { onlySelf: true, emitEvent: false}); if (clearSavedData) { this.clearFieldSavedData(controlName); } } protected saveFieldData(fieldName: string, value: string) { AppServices.userDataService.store(this.createUserDataIdentifier(fieldName), { display: value, value }); } private findField(fieldName: string, methodName: string): AbstractControl { if (!fieldName) { console.warn(`${methodName}(): called with empty fieldName`); return null; } const field = this.formGroup.controls[fieldName]; if (!field) { console.warn(`${methodName}(): unable to find field with name ${fieldName}`); return null; } return field; } disarmField(fieldName: string, clearSavedData?: boolean, options?: { onlySelf?: boolean; emitEvent?: boolean; }) { const field = this.findField(fieldName, 'disarmField'); if (field) { field.clearValidators(); field.setValue('', options); field.updateValueAndValidity(options); if (clearSavedData) { this.clearFieldSavedData(fieldName); } } } resurrectField(fieldName: string, validators: ValidatorFn[], value?: string, options?: { onlySelf?: boolean; emitEvent?: boolean; }) { const field = this.findField(fieldName, 'resurrectField'); if (field) { field.setValidators(validators); field.updateValueAndValidity(options); if (value !== undefined && field.value !== value) { field.setValue(value || null, options); } } } resurrectFieldWithStoredValue(fieldName: string, stepMapping: StepMapping, validators: ValidatorFn[], defaultValue?: string, options?: { onlySelf?: boolean; emitEvent?: boolean; }) { const value = this.getStoredValue(fieldName, stepMapping, defaultValue); this.resurrectField(fieldName, validators, value, options); } showFormError(formControlname) { return this.formGroup.controls[formControlname].invalid && (this.formGroup.controls[formControlname].dirty || this.formGroup.controls[formControlname].touched) } /** * Checks if an array is empty */ isEmptyArray(arr: any[]): boolean { return !(arr && arr.length > 0); } // subclasses can ask us to make sure a StepDescriptionChange is triggered on various occasions protected registerStepDescriptionTriggers(triggers: StepDescriptionTriggers) { if (triggers.fields) { this.registerFieldsAffectingStepDescription(triggers.fields); } this.clusterTypeDescriptorUsedInDescription = triggers.clusterTypeDescriptor; } private registerFieldsAffectingStepDescription(fields: string[]) { fields.forEach(field => { this.registerOnValueChange(field, () => { this.triggerStepDescriptionChange(); }); }) } /** * Registers a callback when a field value changes. * This method does more than the "onchange" event handler * in that onchange only captures changes through the UI, while * this method registers handler for all value change event including * the one changed programmatically. * @param fieldName the field whose value to be monitored * @param callback the function to be called when a value changes. */ registerOnValueChange(fieldName: string, callback: (newValue: any) => void) { this.getControl(fieldName).valueChanges.pipe( distinctUntilChanged((prev, curr) => JSON.stringify(prev) === JSON.stringify(curr)), takeUntil(this.unsubscribe) ).subscribe(newValue => callback(newValue)); } registerOnIpFamilyChange(fieldName: string, ipv4Validators: ValidatorFn[], ipv6Validators: ValidatorFn[], cb?: () => void) { AppServices.messenger.subscribe<IpFamilyEnum>(TanzuEventType.VSPHERE_IP_FAMILY_CHANGE, data => { if (data.payload === IpFamilyEnum.IPv4) { this.resurrectField( fieldName, ipv4Validators, this.formGroup.get(fieldName).value, {emitEvent: false, onlySelf: true} ); } else { this.resurrectField( fieldName, ipv6Validators, this.formGroup.get(fieldName).value, {emitEvent: false, onlySelf: true} ); } this.ipFamily = data.payload; if (cb) { cb(); } }, this.unsubscribe); } protected setControlValueSafely(controlName: string, value: any, options?: { onlySelf?: boolean, emitEvent?: boolean }) { const control = this.formGroup.get(controlName); if (control) { control.setValue(value, options); } } protected setFieldWithStoredValue(field: string, stepMapping: StepMapping, defaultValue?: any, options?: { onlySelf?: boolean; emitEvent?: boolean }) { const fieldMapping = AppServices.fieldMapUtilities.getFieldMapping(field, stepMapping); const storedValue = AppServices.userDataService.retrieveStoredValue(this.wizardName, this.formName, fieldMapping); const value = storedValue === null || storedValue === undefined ? defaultValue : storedValue; this.setControlValueSafely(field, value, options); } // HTML convenience methods // get clusterTypeDescriptorTitleCase() { return FormUtility.titleCase(this.clusterTypeDescriptor); } // // HTML convenience methods protected triggerStepDescriptionChange() { const descriptionChangePayload: StepDescriptionChangePayload = { wizard: this.wizardName, step: this.formName, description: this.dynamicDescription(), } AppServices.messenger.publish({ type: TanzuEventType.STEP_DESCRIPTION_CHANGE, payload: descriptionChangePayload, }); } // NOTE: this method is public to facilitate testing, otherwise it would be private public setClusterTypeDescriptor(descriptor: string) { if (this.clusterTypeDescription !== descriptor) { this.clusterTypeDescription = descriptor; if (this.clusterTypeDescriptorUsedInDescription) { this.triggerStepDescriptionChange(); } } } get clusterTypeDescriptor() { return this.clusterTypeDescription; } private subscribeToStepCompletedEvents() { AppServices.messenger.subscribe<StepCompletedPayload>(TanzuEventType.STEP_COMPLETED, event => { if (event.payload.wizard === this.wizardName && event.payload.step === this.formName) { this.onStepCompleted(); } }); } private subscribeToStepStartedEvents() { AppServices.messenger.subscribe<StepCompletedPayload>(TanzuEventType.STEP_STARTED, event => { if (event.payload.wizard === this.wizardName && event.payload.step === this.formName) { this.onStepStarted(); } }); } // Extending classes may want to override this protected onStepStarted() { } private onStepCompleted() { this.storeUserData(); } // convenience methods protected createUserDataIdentifier(field: string): UserDataIdentifier { return { wizard: this.wizardName, step: this.formName, field}; } protected storeUserDataFromMapping(stepMapping: StepMapping) { AppServices.userDataFormService.storeFromMapping(this.wizardName, this.formName, stepMapping, this.formGroup); } protected storeDefaultDisplayOrder(stepMapping: StepMapping) { this.storeDisplayOrder(this.defaultDisplayOrder(stepMapping)); } protected storeDisplayOrder(displayOrder: string[]) { AppServices.userDataService.storeStepDisplayOrder(this.wizardName, this.formName, displayOrder); } protected storeDefaultLabels(stepMapping: StepMapping) { this.storeLabels(this.defaultLabels(stepMapping)); } protected storeLabels(titles: Map<string, string>) { AppServices.userDataService.storeStepLabels(this.wizardName, this.formName, titles); } protected defaultDisplayOrder(stepMapping: StepMapping): string[] { return AppServices.fieldMapUtilities.getLabeledFieldsWithStoredData(this.wizardName, this.formName, stepMapping); } protected defaultLabels(stepMapping: StepMapping): Map<string, string> { return AppServices.fieldMapUtilities.getFieldLabelMap(stepMapping); } protected restoreField(field: string, stepMapping: StepMapping, values?: any[]) { const identifier = this.createUserDataIdentifier(field); const existingIdFieldMapping = AppServices.fieldMapUtilities.getFieldMapping(field, stepMapping); AppServices.userDataFormService.restoreField(identifier, existingIdFieldMapping, this.formGroup, values); } // This method is designed to expose the protected unsubscribe field (from our base class) to allow its use in subscribing to pipes get unsubscribeOnDestroy(): Subject<void> { return this.unsubscribe; } protected registerDefaultFileImportedHandler(eventSuccess: TanzuEventType, stepMapping: StepMapping) { AppServices.messenger.subscribe<string>(eventSuccess, this.defaultFileImportedHandler(stepMapping)); } // This is a convenience method for child classes that want to register a callback based on this behavior PLUS something of their own protected defaultFileImportedHandler(stepMapping: StepMapping) : (event: TanzuEvent<any>) => void { const step = this; return data => { this.configFileNotification = { notificationType: NotificationTypes.SUCCESS, message: data.payload }; // The file import saves the data to local storage, so we reinitialize this step's form from there AppServices.userDataFormService.restoreForm(step.wizardName, step.formName, step.formGroup, stepMapping); } } }
the_stack
import {Annotation, AnnotationId, AnnotationPropertySerializer, AnnotationPropertySpec, AnnotationReference, AnnotationSourceSignals, AnnotationType, annotationTypeHandlers, annotationTypes, fixAnnotationAfterStructuredCloning, makeAnnotationId, SerializedAnnotations} from 'neuroglancer/annotation'; import {ANNOTATION_COMMIT_UPDATE_RESULT_RPC_ID, ANNOTATION_COMMIT_UPDATE_RPC_ID, ANNOTATION_GEOMETRY_CHUNK_SOURCE_RPC_ID, ANNOTATION_METADATA_CHUNK_SOURCE_RPC_ID, ANNOTATION_REFERENCE_ADD_RPC_ID, ANNOTATION_REFERENCE_DELETE_RPC_ID, ANNOTATION_SUBSET_GEOMETRY_CHUNK_SOURCE_RPC_ID, AnnotationGeometryChunkSpecification} from 'neuroglancer/annotation/base'; import {getAnnotationTypeRenderHandler} from 'neuroglancer/annotation/type_handler'; import {Chunk, ChunkManager, ChunkSource} from 'neuroglancer/chunk_manager/frontend'; import {getObjectKey} from 'neuroglancer/segmentation_display_state/base'; import {SliceViewSourceOptions} from 'neuroglancer/sliceview/base'; import {MultiscaleSliceViewChunkSource, SliceViewChunk, SliceViewChunkSource, SliceViewChunkSourceOptions, SliceViewSingleResolutionSource} from 'neuroglancer/sliceview/frontend'; import {StatusMessage} from 'neuroglancer/status'; import {Borrowed, Owned} from 'neuroglancer/util/disposable'; import {ENDIANNESS, Endianness} from 'neuroglancer/util/endian'; import * as matrix from 'neuroglancer/util/matrix'; import {NullarySignal, Signal} from 'neuroglancer/util/signal'; import {Buffer} from 'neuroglancer/webgl/buffer'; import {GL} from 'neuroglancer/webgl/context'; import {registerRPC, registerSharedObjectOwner, RPC, SharedObject} from 'neuroglancer/worker_rpc'; export interface AnnotationGeometryChunkSourceOptions extends SliceViewChunkSourceOptions { spec: AnnotationGeometryChunkSpecification; parent: Borrowed<MultiscaleAnnotationSource>; } export function computeNumPickIds(serializedAnnotations: SerializedAnnotations) { let numPickIds = 0; const {typeToIds} = serializedAnnotations; for (const annotationType of annotationTypes) { numPickIds += getAnnotationTypeRenderHandler(annotationType).pickIdsPerInstance * typeToIds[annotationType].length; } return numPickIds; } export class AnnotationGeometryData { buffer: Buffer|undefined; bufferValid = false; serializedAnnotations: SerializedAnnotations; numPickIds: number = 0; constructor(x: SerializedAnnotations) { this.serializedAnnotations = { data: x.data, typeToIds: x.typeToIds, typeToOffset: x.typeToOffset, typeToIdMaps: x.typeToIdMaps }; } freeGPUMemory(gl: GL) { gl; const {buffer} = this; if (buffer !== undefined) { buffer.dispose(); this.bufferValid = false; this.buffer = undefined; } } } export class AnnotationSubsetGeometryChunk extends Chunk { source: AnnotationSubsetGeometryChunkSource; // undefined indicates chunk not found data: AnnotationGeometryData|undefined; constructor(source: AnnotationSubsetGeometryChunkSource, x: any) { super(source); if (x.data !== undefined) { this.data = new AnnotationGeometryData(x); } } freeGPUMemory(gl: GL) { super.freeGPUMemory(gl); const {data} = this; if (data !== undefined) { data.freeGPUMemory(gl); } } dispose() { this.data = undefined; } } export class AnnotationGeometryChunk extends SliceViewChunk { source: AnnotationGeometryChunkSource; // undefined indicates chunk not found data: AnnotationGeometryData|undefined; constructor(source: AnnotationGeometryChunkSource, x: any) { super(source, x); if (x.data !== undefined) { this.data = new AnnotationGeometryData(x); } } freeGPUMemory(gl: GL) { super.freeGPUMemory(gl); const {data} = this; if (data !== undefined) { data.freeGPUMemory(gl); } } dispose() { this.data = undefined; } } @registerSharedObjectOwner(ANNOTATION_GEOMETRY_CHUNK_SOURCE_RPC_ID) export class AnnotationGeometryChunkSource extends SliceViewChunkSource<AnnotationGeometryChunkSpecification, AnnotationGeometryChunk> { OPTIONS: AnnotationGeometryChunkSourceOptions; parent: Borrowed<MultiscaleAnnotationSource>; immediateChunkUpdates = true; /** * Transforms positions in the MultiscaleAnnotationSource coordinate space to grid cell * coordinates. Equal to the inverse of `this.spec.chunkToMultiscaleTransform`, with rows divided * by `this.spec.chunkDataSize`. */ multiscaleToChunkTransform: Float32Array; constructor(chunkManager: Borrowed<ChunkManager>, options: AnnotationGeometryChunkSourceOptions) { super(chunkManager, options); const parent = this.parent = options.parent; parent.spatiallyIndexedSources.add(this); const {rank, chunkDataSize} = this.spec; const multiscaleToChunkTransform = this.multiscaleToChunkTransform = new Float32Array((rank + 1) ** 2); matrix.inverse( multiscaleToChunkTransform, rank + 1, this.spec.chunkToMultiscaleTransform, rank + 1, rank + 1); for (let i = 0; i < rank; ++i) { for (let j = 0; j < rank + 1; ++j) { multiscaleToChunkTransform[(rank + 1) * j + i] /= chunkDataSize[i]; } } } disposed() { this.parent.spatiallyIndexedSources.delete(this); super.disposed(); } initializeCounterpart(rpc: RPC, options: any) { options['parent'] = this.parent.rpcId; super.initializeCounterpart(rpc, options); } addChunk(key: string, chunk: AnnotationGeometryChunk) { super.addChunk(key, chunk); // TODO: process local deletions } getChunk(x: any) { return new AnnotationGeometryChunk(this, x); } } @registerSharedObjectOwner(ANNOTATION_SUBSET_GEOMETRY_CHUNK_SOURCE_RPC_ID) export class AnnotationSubsetGeometryChunkSource extends ChunkSource { immediateChunkUpdates = true; chunks: Map<string, AnnotationSubsetGeometryChunk>; constructor( chunkManager: Borrowed<ChunkManager>, public parent: Borrowed<MultiscaleAnnotationSource>, public relationshipIndex: number) { super(chunkManager, {}); } addChunk(key: string, chunk: AnnotationSubsetGeometryChunk) { super.addChunk(key, chunk); // TODO: process local deletions } getChunk(x: any): AnnotationSubsetGeometryChunk { return new AnnotationSubsetGeometryChunk(this, x); } } export class AnnotationMetadataChunk extends Chunk { annotation: Annotation|null; constructor(source: Borrowed<AnnotationMetadataChunkSource>, x: any) { super(source); this.annotation = fixAnnotationAfterStructuredCloning(x.annotation); } } @registerSharedObjectOwner(ANNOTATION_METADATA_CHUNK_SOURCE_RPC_ID) export class AnnotationMetadataChunkSource extends ChunkSource { chunks: Map<string, AnnotationMetadataChunk>; constructor( chunkManager: Borrowed<ChunkManager>, public parent: Borrowed<MultiscaleAnnotationSource>) { super(chunkManager); } getChunk(x: any): AnnotationMetadataChunk { return new AnnotationMetadataChunk(this, x); } addChunk(key: string, chunk: AnnotationMetadataChunk) { super.addChunk(key, chunk); const {references} = this.parent; const reference = references.get(key); if (reference !== undefined) { reference.value = chunk.annotation; reference.changed.dispatch(); } } deleteChunk(key: string) { const {references} = this.parent; const reference = references.get(key); if (reference !== undefined) { reference.value = undefined; reference.changed.dispatch(); } } } export function updateAnnotation( chunk: AnnotationGeometryData, annotation: Annotation, propertySerializer: AnnotationPropertySerializer) { // Find insertion point. const {rank} = propertySerializer; const type = annotation.type; const {serializedAnnotations} = chunk; const ids = serializedAnnotations.typeToIds[type]; const idMap = serializedAnnotations.typeToIdMaps[type]; const handler = annotationTypeHandlers[type]; const numGeometryBytes = handler.serializedBytes(rank); const numBytes = numGeometryBytes + propertySerializer.serializedBytes; let index = idMap.get(annotation.id); let offset = 0; if (index === undefined) { // Doesn't already exist. index = idMap.size; ids.push(annotation.id); idMap.set(annotation.id, index); const newData = new Uint8Array(serializedAnnotations.data.length + numBytes); offset = serializedAnnotations.typeToOffset[type] + numBytes * index; newData.set(serializedAnnotations.data.subarray(0, offset), 0); newData.set(serializedAnnotations.data.subarray(offset), offset + numBytes); serializedAnnotations.data = newData; for (const otherType of annotationTypes) { if (otherType > type) { serializedAnnotations.typeToOffset![otherType] += numBytes; } } } else { offset = serializedAnnotations.typeToOffset[type] + numBytes * index; } const dv = new DataView( serializedAnnotations.data.buffer, serializedAnnotations.data.byteOffset, serializedAnnotations.data.byteLength); let bufferOffset = serializedAnnotations.typeToOffset[type] + index * numBytes; const isLittleEndian = ENDIANNESS === Endianness.LITTLE; handler.serialize(dv, bufferOffset, isLittleEndian, rank, annotation); bufferOffset += numGeometryBytes; propertySerializer.serialize(dv, bufferOffset, isLittleEndian, annotation.properties); chunk.bufferValid = false; } export function deleteAnnotation( chunk: AnnotationGeometryData, type: AnnotationType, id: AnnotationId, propertySerializer: AnnotationPropertySerializer): boolean { const {serializedAnnotations} = chunk; const idMap = serializedAnnotations.typeToIdMaps[type]; const index = idMap.get(id); if (index === undefined) { return false; } const ids = serializedAnnotations.typeToIds[type]; const handler = annotationTypeHandlers[type]; const {rank} = propertySerializer; const numGeometryBytes = handler.serializedBytes(rank); const numBytes = numGeometryBytes + propertySerializer.serializedBytes; ids.splice(index, 1); idMap.delete(id); for (let i = index, count = ids.length; i < count; ++i) { idMap.set(ids[i], i); } const {typeToOffset} = serializedAnnotations; const offset = typeToOffset[type] + numBytes * index; const {data} = serializedAnnotations; const newData = new Uint8Array(data.length - numBytes); newData.set(data.subarray(0, offset), 0); newData.set(data.subarray(offset + numBytes), offset); serializedAnnotations.data = newData; for (const otherType of annotationTypes) { if (otherType > type) { typeToOffset[otherType] -= numBytes; } } chunk.bufferValid = false; return true; } interface LocalUpdateUndoState { /** * If commitInProgress === undefined, this must be undefined. Otherwise, it specifies a commit * that has been requested and which will be initiated as soon as the in-progress request * completes. */ pendingCommit: Annotation|null|undefined; reference: Owned<AnnotationReference>; /** * The state of the annotation prior to any local modifications. */ existingAnnotation: Annotation|undefined; /** * If not undefined, a commit has been sent to the backend, and we are waiting for the result. */ commitInProgress: Annotation|null|undefined; type: AnnotationType; } export function makeTemporaryChunk() { const typeToIds: string[][] = []; const typeToOffset: number[] = []; const typeToIdMaps: Map<string, number>[] = []; for (const annotationType of annotationTypes) { typeToIds[annotationType] = []; typeToOffset[annotationType] = 0; typeToIdMaps[annotationType] = new Map(); } return new AnnotationGeometryChunk( <AnnotationGeometryChunkSource><any>undefined, {data: new Uint8Array(0), numPickIds: 0, typeToOffset, typeToIds, typeToIdMaps}); } export class MultiscaleAnnotationSource extends SharedObject implements MultiscaleSliceViewChunkSource<AnnotationGeometryChunkSource>, AnnotationSourceSignals { OPTIONS: {}; key: any; metadataChunkSource = this.registerDisposer(new AnnotationMetadataChunkSource(this.chunkManager, this)); segmentFilteredSources: Owned<AnnotationSubsetGeometryChunkSource>[]; spatiallyIndexedSources = new Set<Borrowed<AnnotationGeometryChunkSource>>(); rank: number; readonly relationships: readonly string[]; readonly properties: Readonly<AnnotationPropertySpec>[]; readonly annotationPropertySerializer: AnnotationPropertySerializer; constructor(public chunkManager: Borrowed<ChunkManager>, options: { rank: number, relationships: readonly string[], properties: Readonly<AnnotationPropertySpec>[] }) { super(); this.rank = options.rank; this.properties = options.properties; this.annotationPropertySerializer = new AnnotationPropertySerializer(this.rank, this.properties); const segmentFilteredSources: Owned<AnnotationSubsetGeometryChunkSource>[] = this.segmentFilteredSources = []; const {relationships} = options; this.relationships = relationships; for (let i = 0, count = relationships.length; i < count; ++i) { segmentFilteredSources.push( this.registerDisposer(new AnnotationSubsetGeometryChunkSource(chunkManager, this, i))); } } hasNonSerializedProperties() { return this.relationships.length > 0; } getSources(_options: SliceViewSourceOptions): SliceViewSingleResolutionSource<AnnotationGeometryChunkSource>[][] { throw new Error('not implemented'); } temporary = makeTemporaryChunk(); references = new Map<AnnotationId, Borrowed<AnnotationReference>>(); localUpdates = new Map<AnnotationId, LocalUpdateUndoState>(); initializeCounterpart(rpc: RPC, options: any) { this.metadataChunkSource.initializeCounterpart(rpc, {}); for (const source of this.segmentFilteredSources) { source.initializeCounterpart(rpc, {}); } options.segmentFilteredSource = this.segmentFilteredSources.map(x => x.addCounterpartRef()); options.metadataChunkSource = this.metadataChunkSource.addCounterpartRef(); options.chunkManager = this.chunkManager.rpcId; super.initializeCounterpart(rpc, options); } add(annotation: Annotation, commit: boolean = true): AnnotationReference { annotation.id = makeAnnotationId(); const reference = new AnnotationReference(annotation.id); reference.value = annotation; this.references.set(reference.id, reference); reference.registerDisposer(() => { this.references.delete(reference.id); }); this.applyLocalUpdate( reference, /*existing=*/ false, /*commit=*/ commit, /*newAnnotation=*/ annotation); return reference; } private applyLocalUpdate( reference: Borrowed<AnnotationReference>, existing: boolean, commit: boolean, newAnnotation: Annotation|null): void { const {localUpdates} = this; const {id} = reference; let localUpdate = this.localUpdates.get(id); const annotation = reference.value; if (annotation == null) { throw new Error(`Cannot create local update from null annotation`); } if (localUpdate === undefined) { localUpdate = { type: annotation.type, reference: reference.addRef(), existingAnnotation: existing ? annotation : undefined, pendingCommit: undefined, commitInProgress: undefined, }; localUpdates.set(id, localUpdate); this.forEachPossibleChunk(annotation, chunk => { const {data} = chunk; if (data === undefined) return; deleteAnnotation(data, annotation.type, id, this.annotationPropertySerializer); }); if (newAnnotation !== null) { // Add to temporary chunk. updateAnnotation(this.temporary.data!, newAnnotation, this.annotationPropertySerializer); } } else { if (newAnnotation === null) { // Annotation has a local update already, so we need to delete it from the temporary chunk. deleteAnnotation( this.temporary.data!, annotation.type, annotation.id, this.annotationPropertySerializer); } else { // Modify existing entry in temporary chunk. updateAnnotation(this.temporary.data!, newAnnotation, this.annotationPropertySerializer); } reference.value = newAnnotation; } if (commit) { if (localUpdate.commitInProgress !== undefined) { localUpdate.pendingCommit = newAnnotation; } else { if (newAnnotation === null && localUpdate.existingAnnotation === undefined) { // Local update, which we would now like to delete, has never been committed. // Therefore we can just delete it locally. localUpdates.delete(id); localUpdate.reference.dispose(); return; } this.sendCommitRequest(localUpdate, newAnnotation); } } this.notifyChanged(reference.id, newAnnotation || undefined); } private sendCommitRequest(localUpdate: LocalUpdateUndoState, newAnnotation: Annotation|null) { this.updateCommitsInProgress(1); localUpdate.commitInProgress = newAnnotation; this.rpc!.invoke(ANNOTATION_COMMIT_UPDATE_RPC_ID, { id: this.rpcId, annotationId: localUpdate.existingAnnotation && localUpdate.reference.id, newAnnotation, }); } delete(reference: Borrowed<AnnotationReference>) { this.applyLocalUpdate(reference, /*existing=*/ true, /*commit=*/ true, /*newAnnotation=*/ null); } update(reference: AnnotationReference, newAnnotation: Annotation) { this.applyLocalUpdate( reference, /*existing=*/ true, /*commit=*/ false, /*newAnnotation=*/ newAnnotation); } private notifyChanged(id: AnnotationId, annotation: Annotation|undefined) { const reference = this.references.get(id); const chunk = this.metadataChunkSource.chunks.get(id); if (chunk !== undefined) { chunk.annotation = annotation || null; } if (reference !== undefined) { reference.value = annotation || null; reference.changed.dispatch(); } this.chunkManager.chunkQueueManager.visibleChunksChanged.dispatch(); } /** * Must be called after `add` or `update` to commit the result. */ commit(reference: Borrowed<AnnotationReference>) { this.applyLocalUpdate(reference, /*existing=*/ true, /*commit=*/ true, reference.value!); } getReference(id: AnnotationId): Owned<AnnotationReference> { let existing = this.references.get(id); if (existing !== undefined) { return existing.addRef(); } existing = new AnnotationReference(id); this.references.set(id, existing); this.rpc!.invoke(ANNOTATION_REFERENCE_ADD_RPC_ID, {id: this.rpcId, annotation: id}); existing.registerDisposer(() => { this.references.delete(id); this.rpc!.invoke(ANNOTATION_REFERENCE_DELETE_RPC_ID, {id: this.rpcId, annotation: id}); }); const chunk = this.metadataChunkSource.chunks.get(id); if (chunk !== undefined) { existing.value = chunk.annotation; } return existing; } private forEachPossibleChunk( annotation: Annotation, callback: (chunk: AnnotationGeometryChunk|AnnotationSubsetGeometryChunk) => void) { annotation; const {relatedSegments} = annotation; if (relatedSegments !== undefined) { const numRelationships = relatedSegments.length; const {segmentFilteredSources} = this; for (let i = 0; i < numRelationships; ++i) { const segments = relatedSegments[i]; if (segments === undefined) return; const source = segmentFilteredSources[i]; for (const segment of segments) { const chunk = source.chunks.get(getObjectKey(segment)); if (chunk === undefined) { continue; } callback(chunk); } } } const {rank} = this; const tempLower = new Float32Array(rank); const tempUpper = new Float32Array(rank); const tempChunk = new Float32Array(rank); for (const source of this.spatiallyIndexedSources) { switch (annotation.type) { case AnnotationType.POINT: matrix.transformPoint( tempLower, source.multiscaleToChunkTransform, rank + 1, annotation.point, rank); tempUpper.set(tempLower); break; case AnnotationType.LINE: case AnnotationType.AXIS_ALIGNED_BOUNDING_BOX: matrix.transformPoint( tempLower, source.multiscaleToChunkTransform, rank + 1, annotation.pointA, rank); matrix.transformPoint( tempUpper, source.multiscaleToChunkTransform, rank + 1, annotation.pointB, rank); break; case AnnotationType.ELLIPSOID: matrix.transformPoint( tempLower, source.multiscaleToChunkTransform, rank + 1, annotation.center, rank); matrix.transformVector( tempUpper, source.multiscaleToChunkTransform, rank + 1, annotation.radii, rank); for (let i = 0; i < rank; ++i) { const c = tempLower[i]; const r = tempUpper[i]; tempLower[i] = c - r; tempUpper[i] = c + r; } break; } let totalChunks = 1; for (let i = 0; i < rank; ++i) { const a = tempLower[i]; const b = tempUpper[i]; const lower = Math.min(a, b); const upper = Math.max(a, b); // In the case that the point lies directly on a boundary, ensure it is included in both // chunks, since we don't know how the datasource handles this case. tempLower[i] = Math.ceil(lower - 1); tempUpper[i] = Math.floor(upper + 1); totalChunks *= (tempUpper[i] - tempLower[i]); } const {chunks} = source; for (let chunkIndex = 0; chunkIndex < totalChunks; ++chunkIndex) { let remainder = chunkIndex; for (let i = 0; i < rank; ++i) { const lower = tempLower[i]; const upper = tempUpper[i]; const size = upper - lower; const x = tempChunk[i] = remainder % size; remainder = (remainder - x) / size; } const chunk = chunks.get(tempChunk.join()); if (chunk !== undefined) { callback(chunk); } } } } static encodeOptions(_options: {}): {[key: string]: any} { return {}; } handleSuccessfulUpdate(id: AnnotationId, newAnnotation: Annotation|null) { const localUpdate = this.localUpdates.get(id); if (localUpdate === undefined || localUpdate.commitInProgress === undefined) { throw new Error(`Received invalid successful update notification`); } this.updateCommitsInProgress(-1); if (newAnnotation !== null && localUpdate.reference.id !== newAnnotation.id) { if (localUpdate.commitInProgress === null) { throw new Error(`Received invalid successful update notification`); } localUpdate.reference.id = newAnnotation.id; this.references.delete(id); this.references.set(newAnnotation.id, localUpdate.reference); this.localUpdates.delete(id); this.localUpdates.set(newAnnotation.id, localUpdate); if (localUpdate.reference.value !== null) { localUpdate.reference.value!.id = newAnnotation.id; deleteAnnotation( this.temporary.data!, localUpdate.type, id, this.annotationPropertySerializer); updateAnnotation( this.temporary.data!, localUpdate.reference.value!, this.annotationPropertySerializer); } localUpdate.reference.changed.dispatch(); } localUpdate.existingAnnotation = newAnnotation || undefined; localUpdate.commitInProgress = undefined; let {pendingCommit} = localUpdate; localUpdate.pendingCommit = undefined; if (newAnnotation === null) { pendingCommit = undefined; } if (pendingCommit !== undefined) { if (pendingCommit !== null) { pendingCommit.id = newAnnotation!.id; } this.sendCommitRequest(localUpdate, pendingCommit); } else { this.revertLocalUpdate(localUpdate); } } private numCommitsInProgress = 0; private commitStatus: StatusMessage|undefined; disposed() { const {commitStatus} = this; if (commitStatus !== undefined) { commitStatus.dispose(); } } private updateCommitsInProgress(amount: number) { this.numCommitsInProgress += amount; if (this.numCommitsInProgress === 0) { if (this.commitStatus !== undefined) { this.commitStatus.dispose(); this.commitStatus = undefined; } } else if (this.commitStatus === undefined) { const status = this.commitStatus = new StatusMessage(/*delay=*/ true); status.setText('Commiting annotations'); } } handleFailedUpdate(id: AnnotationId, message: string) { const localUpdate = this.localUpdates.get(id); if (localUpdate === undefined || localUpdate.commitInProgress === undefined) { throw new Error(`Received invalid update notification`); } const status = new StatusMessage(); status.setErrorMessage(`Error commiting annotation update: ${message}`); this.revertLocalUpdate(localUpdate); this.updateCommitsInProgress(-1); } private revertLocalUpdate(localUpdate: LocalUpdateUndoState) { deleteAnnotation( this.temporary.data!, localUpdate.type, localUpdate.reference.id, this.annotationPropertySerializer); const {existingAnnotation} = localUpdate; if (existingAnnotation !== undefined) { this.forEachPossibleChunk(existingAnnotation, chunk => { const {data} = chunk; if (data === undefined) return; updateAnnotation(data, existingAnnotation, this.annotationPropertySerializer); }); } const {reference} = localUpdate; const {id} = reference; reference.value = existingAnnotation || null; reference.changed.dispatch(); reference.dispose(); this.localUpdates.delete(id); } // FIXME changed = new NullarySignal(); * [Symbol.iterator](): Iterator<Annotation> {} readonly = false; childAdded: Signal<(annotation: Annotation) => void>; childUpdated: Signal<(annotation: Annotation) => void>; childDeleted: Signal<(annotationId: string) => void>; } registerRPC(ANNOTATION_COMMIT_UPDATE_RESULT_RPC_ID, function(x) { const source = <MultiscaleAnnotationSource>this.get(x.id); const annotationId: AnnotationId = x.annotationId; const error: string|undefined = x.error; if (error !== undefined) { source.handleFailedUpdate(annotationId, error); } else { const newAnnotation: Annotation|null = fixAnnotationAfterStructuredCloning(x.newAnnotation); source.handleSuccessfulUpdate(annotationId, newAnnotation); } });
the_stack
import { RepresentationRegistry } from '../globals' import { defaults } from '../utils' import StructureRepresentation, { StructureRepresentationParameters, StructureRepresentationData } from './structure-representation' import MolecularSurface, { MolecularSurfaceParameters } from '../surface/molecular-surface' import SurfaceBuffer from '../buffer/surface-buffer' import ContourBuffer from '../buffer/contour-buffer' import DoubleSidedBuffer from '../buffer/doublesided-buffer' import Selection from '../selection/selection' import Viewer from '../viewer/viewer'; // @ts-ignore: unused import Volume required for declaration only import { Structure, Vector3, Volume } from '../ngl'; import StructureView from '../structure/structure-view'; import { SurfaceDataFields } from './surface-representation'; import Surface, {SurfaceData} from '../surface/surface'; export interface MolecularSurfaceRepresentationParameters extends StructureRepresentationParameters { surfaceType: 'vws'|'sas'|'ms'|'ses'|'av' probeRadius: number smooth: number scaleFactor: number cutoff: number contour: boolean background: boolean opaqueBack: boolean filterSele: string colorVolume: any useWorker: boolean } export interface MolecularSurfaceInfo { molsurf?: MolecularSurface sele?: string surface?: Surface } /** * Molecular Surface Representation */ class MolecularSurfaceRepresentation extends StructureRepresentation { protected surfaceType: 'vws'|'sas'|'ms'|'ses'|'av' protected probeRadius: number protected smooth: number protected scaleFactor: number protected cutoff: number protected contour: boolean protected background: boolean protected opaqueBack: boolean protected filterSele: string protected colorVolume: any protected useWorker: boolean protected __infoList: MolecularSurfaceInfo[] protected __forceNewMolsurf: boolean protected __sele: string protected __surfaceParams: string constructor (structure: Structure, viewer: Viewer, params: Partial<MolecularSurfaceRepresentationParameters>) { super(structure, viewer, params) this.type = 'surface' this.parameters = Object.assign({ surfaceType: { type: 'select', rebuild: true, options: { 'vws': 'vws', 'sas': 'sas', 'ms': 'ms', 'ses': 'ses', 'av': 'av' } }, probeRadius: { type: 'number', precision: 1, max: 20, min: 0, rebuild: true }, smooth: { type: 'integer', precision: 1, max: 10, min: 0, rebuild: true }, scaleFactor: { type: 'number', precision: 1, max: 5, min: 0, rebuild: true }, cutoff: { type: 'number', precision: 2, max: 50, min: 0, rebuild: true }, contour: { type: 'boolean', rebuild: true }, background: { type: 'boolean', rebuild: true // FIXME }, opaqueBack: { type: 'boolean', buffer: true }, filterSele: { type: 'text', rebuild: true }, colorVolume: { type: 'hidden' }, useWorker: { type: 'boolean', rebuild: true } }, this.parameters, { radius: null, scale: null }) this.__infoList = [] // TODO find a more direct way this.structure.signals.refreshed.add(() => { this.__forceNewMolsurf = true }) this.toBePrepared = true this.init(params) } init (params: Partial<MolecularSurfaceRepresentationParameters>) { const p = params || {} p.colorScheme = defaults(p.colorScheme, 'uniform') p.colorValue = defaults(p.colorValue, 0xDDDDDD) p.disablePicking = defaults(p.disablePicking, true) this.surfaceType = defaults(p.surfaceType, 'ms') this.probeRadius = defaults(p.probeRadius, 1.4) this.smooth = defaults(p.smooth, 2) this.scaleFactor = defaults(p.scaleFactor, 2.0) this.cutoff = defaults(p.cutoff, 0.0) this.contour = defaults(p.contour, false) this.background = defaults(p.background, false) this.opaqueBack = defaults(p.opaqueBack, true) this.filterSele = defaults(p.filterSele, '') this.colorVolume = defaults(p.colorVolume, undefined) this.useWorker = defaults(p.useWorker, true) super.init(params) } prepareData (sview: StructureView, i: number, callback: (i: number) => void) { let info: MolecularSurfaceInfo = this.__infoList[ i ] if (!info) { info = {} this.__infoList[ i ] = info } if (!info.molsurf || info.sele !== sview.selection.string) { if (this.filterSele) { const sviewFilter = sview.structure.getView(new Selection(this.filterSele)) const bbSize = sviewFilter.boundingBox.getSize(new Vector3()) const maxDim = Math.max(bbSize.x, bbSize.y, bbSize.z) const asWithin = sview.getAtomSetWithinPoint(sviewFilter.center, (maxDim / 2) + 6.0) sview = sview.getView( new Selection(sview.getAtomSetWithinSelection(asWithin, 3).toSeleString()) ) if (sview.atomCount === 0) { callback(i) return } } info.sele = sview.selection.string info.molsurf = new MolecularSurface(sview) const p = this.getSurfaceParams() const onSurfaceFinish = (surface: Surface) => { info.surface = surface callback(i) } if (this.useWorker) { info.molsurf.getSurfaceWorker(p as MolecularSurfaceParameters, onSurfaceFinish) } else { onSurfaceFinish(info.molsurf.getSurface(p as {name: string, type: 'av'|'edt' } & MolecularSurfaceRepresentationParameters)) } } else { callback(i) } } prepare (callback: () => void) { if (this.__forceNewMolsurf || this.__sele !== this.selection.string || this.__surfaceParams !== JSON.stringify(this.getSurfaceParams())) { this.__infoList.forEach((info: MolecularSurfaceInfo) => { if (info && info.molsurf) { info.molsurf.dispose() } }) this.__infoList.length = 0 } if (this.structureView.atomCount === 0) { callback() return } const after = () => { this.__sele = this.selection.string this.__surfaceParams = JSON.stringify(this.getSurfaceParams()) this.__forceNewMolsurf = false callback() } const name = this.assembly === 'default' ? this.defaultAssembly : this.assembly const assembly = this.structure.biomolDict[ name ] if (assembly) { assembly.partList.forEach((part, i) => { const sview = part.getView(this.structureView) this.prepareData(sview as StructureView, i, (_i) => { if (_i === assembly.partList.length - 1) after() }) }) } else { this.prepareData(this.structureView, 0, after) } } createData (sview: StructureView, i: number) { const info = this.__infoList[ i ] const surface = info.surface if (!surface) { // Surface creation bailed (no surface generated for this sview) return } const surfaceData = { position: surface!.getPosition(), color: surface!.getColor(this.getColorParams()), index: surface!.getFilteredIndex(this.filterSele, sview) } const bufferList = [] if (surface.contour) { const contourBuffer = new ContourBuffer( surfaceData, this.getBufferParams({ wireframe: false }) ) bufferList.push(contourBuffer) } else { Object.assign(surfaceData, { normal: surface.getNormal(), picking: surface.getPicking(sview.getStructure()) }) const surfaceBuffer = new SurfaceBuffer( surfaceData, this.getBufferParams({ background: this.background, opaqueBack: this.opaqueBack, dullInterior: false }) ) if (this.getBufferParams().side == 'double') { const doubleSidedBuffer = new DoubleSidedBuffer(surfaceBuffer) bufferList.push(doubleSidedBuffer) } else { bufferList.push(surfaceBuffer) } } return { bufferList, info } as StructureRepresentationData } updateData (what: SurfaceDataFields, data: StructureRepresentationData) { const surfaceData: Partial<SurfaceData> = {} if (what.position || what.radius) { this.__forceNewMolsurf = true this.build() return } if (what.color) { surfaceData.color = data.info.surface.getColor(this.getColorParams()) } if (what.index) { surfaceData.index = data.info.surface.getFilteredIndex(this.filterSele, data.sview) } data.bufferList[ 0 ].setAttributes(surfaceData) } setParameters (params: Partial<MolecularSurfaceRepresentationParameters>, what: Partial<SurfaceDataFields> = {}, rebuild?: boolean) { if (params && params.filterSele) { what.index = true } if (params && params.colorVolume !== undefined) { what.color = true } // forbid setting wireframe to true when contour is true if (params && params.wireframe && ( params.contour || (params.contour === undefined && this.contour) ) ) { params.wireframe = false } super.setParameters(params, what, rebuild) return this } getSurfaceParams (params: Partial<MolecularSurfaceRepresentationParameters> = {}) { const p = Object.assign({ type: this.surfaceType as string, probeRadius: this.probeRadius as number, scaleFactor: this.scaleFactor as number, smooth: this.smooth && !this.contour, cutoff: this.cutoff as number, contour: this.contour as boolean, useWorker: this.useWorker as boolean, radiusParams: this.getRadiusParams() }, params) return p } getColorParams () { const p = super.getColorParams() p.volume = this.colorVolume return p } getAtomRadius () { return 0 } clear () { super.clear() } dispose () { this.__infoList.forEach((info: MolecularSurfaceInfo) => { if (info && info.molsurf) { info.molsurf.dispose() } }) this.__infoList.length = 0 super.dispose() } } RepresentationRegistry.add('surface', MolecularSurfaceRepresentation) export default MolecularSurfaceRepresentation
the_stack
import _ from 'lodash'; import { getCLIPath, getSocialProviders, KEY_DOWN_ARROW, KEY_UP_ARROW, nspawn as spawn, setTransformerVersionFlag } from '..'; export type AddAuthUserPoolOnlyNoOAuthSettings = { resourceName: string; userPoolName: string; }; export type AddAuthUserPoolOnlyWithOAuthSettings = AddAuthUserPoolOnlyNoOAuthSettings & { domainPrefix: string; signInUrl1: string; signInUrl2: string; signOutUrl1: string; signOutUrl2: string; facebookAppId: string; facebookAppSecret: string; googleAppId: string; googleAppSecret: string; amazonAppId: string; amazonAppSecret: string; appleAppClientId: string; appleAppTeamId: string; appleAppKeyID: string; appleAppPrivateKey: string; }; export type AddAuthIdentityPoolAndUserPoolWithOAuthSettings = AddAuthUserPoolOnlyWithOAuthSettings & { identityPoolName: string; allowUnauthenticatedIdentities: boolean; thirdPartyAuth: boolean; idpFacebookAppId: string; idpGoogleAppId: string; idpAmazonAppId: string; idpAppleAppId: string; }; export function addAuthWithDefault(cwd: string, settings: any = {}): Promise<void> { return new Promise((resolve, reject) => { spawn(getCLIPath(), ['add', 'auth'], { cwd, stripColors: true }) .wait('Do you want to use the default authentication') .sendCarriageReturn() .wait('How do you want users to be able to sign in') .sendCarriageReturn() .wait('Do you want to configure advanced settings?') .sendCarriageReturn() .sendEof() .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); }); } export function runAmplifyAuthConsole(cwd: string): Promise<void> { return new Promise((resolve, reject) => { spawn(getCLIPath(), ['auth', 'console'], { cwd, stripColors: true }) .wait('Which console') .sendCarriageReturn() .wait('Identity Pool console:') .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); }); } export function removeAuthWithDefault(cwd: string): Promise<void> { return new Promise((resolve, reject) => { spawn(getCLIPath(), ['remove', 'auth'], { cwd, stripColors: true }) .wait('Choose the resource you would want to remove') .sendCarriageReturn() .wait('Are you sure you want to delete the resource? This') .sendConfirmYes() .sendEof() .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); }); } export function addAuthWithGroupTrigger(cwd: string, settings: any): Promise<void> { return new Promise((resolve, reject) => { spawn(getCLIPath(), ['add', 'auth'], { cwd, stripColors: true }) .wait('Do you want to use the default authentication and security configuration?') .sendCarriageReturn() .wait('How do you want users to be able to sign in') .sendCarriageReturn() .wait('Do you want to configure advanced settings?') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('What attributes are required for signing up?') .sendCarriageReturn() .wait('Do you want to enable any of the following capabilities?') .send(KEY_DOWN_ARROW) .send(KEY_DOWN_ARROW) .send(' ') .sendCarriageReturn() .wait('Enter the name of the group to which users will be added.') .send('mygroup') .sendCarriageReturn() .wait('Do you want to edit your add-to-group function now?') .sendConfirmNo() .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); }); } interface AddApiOptions { apiName: string; testingWithLatestCodebase: boolean; transformerVersion: number; } const defaultOptions: AddApiOptions = { apiName: '\r', testingWithLatestCodebase: true, transformerVersion: 2, }; export function addAuthViaAPIWithTrigger(cwd: string, opts: Partial<AddApiOptions> = {}): Promise<void> { const options = _.assign(defaultOptions, opts); return new Promise((resolve, reject) => { spawn(getCLIPath(options.testingWithLatestCodebase), ['add', 'api'], { cwd, stripColors: true }) .wait('Select from one of the below mentioned services:') .sendCarriageReturn() .wait(/.*Here is the GraphQL API that we will create. Select a setting to edit or continue.*/) .sendKeyUp(2) .sendCarriageReturn() .wait('Choose the default authorization type for the API') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Do you want to use the default authentication and security configuration?') .sendCarriageReturn() .wait('How do you want users to be able to sign in') .sendCarriageReturn() .wait('Do you want to configure advanced settings?') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('What attributes are required for signing up?') .sendCarriageReturn() .wait('Do you want to enable any of the following capabilities?') .send(KEY_DOWN_ARROW) .send(KEY_DOWN_ARROW) .send(' ') .sendCarriageReturn() .wait('Enter the name of the group to which users will be added.') .send('mygroup') .sendCarriageReturn() .wait('Do you want to edit your add-to-group function now?') .sendConfirmNo() .wait(/.*Configure additional auth types.*/) .sendConfirmNo() .wait(/.*Here is the GraphQL API that we will create. Select a setting to edit or continue.*/) .sendCarriageReturn() .wait('Choose a schema template:') .sendCarriageReturn() .wait('Do you want to edit the schema now?') .sendConfirmNo() .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); setTransformerVersionFlag(cwd, options.transformerVersion); }); } export function addAuthwithUserPoolGroupsViaAPIWithTrigger(cwd: string, opts: Partial<AddApiOptions> = {}): Promise<void> { const options = _.assign(defaultOptions, opts); return new Promise((resolve, reject) => { spawn(getCLIPath(options.testingWithLatestCodebase), ['add', 'api'], { cwd, stripColors: true }) .wait('Select from one of the below mentioned services:') .sendCarriageReturn() .wait(/.*Here is the GraphQL API that we will create. Select a setting to edit or continue.*/) .sendKeyUp(2) .sendCarriageReturn() .wait('Choose the default authorization type for the API') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Do you want to use the default authentication and security configuration?') .send(KEY_DOWN_ARROW) .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Select the authentication/authorization services that you want to use:') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Provide a friendly name for your resource that will be used to label this category in the project:') .sendCarriageReturn() .wait('Provide a name for your user pool:') .sendCarriageReturn() .wait('How do you want users to be able to sign in') .sendCarriageReturn() .wait('Do you want to add User Pool Groups?') .sendCarriageReturn() .wait('Provide a name for your user pool group:') .sendLine('admin') .wait('Do you want to add another User Pool Group') .sendCarriageReturn() .wait('Sort the user pool groups in order of preference') .sendCarriageReturn() .wait('Do you want to add an admin queries API?') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Multifactor authentication (MFA) user login options:') .sendCarriageReturn() .wait('Email based user registration/forgot password:') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Specify an SMS verification message:') .sendCarriageReturn() .wait('Do you want to override the default password policy for this User Pool?') .sendCarriageReturn() .wait('What attributes are required for signing up?') .sendCarriageReturn() .wait(`Specify the app's refresh token expiration period (in days):`) .sendCarriageReturn() .wait('Do you want to specify the user attributes this app can read and write?') .sendCarriageReturn() .wait('Do you want to enable any of the following capabilities?') .send(KEY_DOWN_ARROW) .send(KEY_DOWN_ARROW) .send(' ') .sendCarriageReturn() .wait('Do you want to use an OAuth flow?') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Do you want to configure Lambda Triggers for Cognito?') .sendCarriageReturn() .wait('Which triggers do you want to enable for Cognito') .sendCarriageReturn() .wait('What functionality do you want to use for Post Confirmation') .sendCarriageReturn() .wait('Enter the name of the group to which users will be added.') .send('mygroup') .sendCarriageReturn() .wait('Do you want to edit your add-to-group function now?') .sendConfirmNo() .wait(/.*Configure additional auth types.*/) .sendConfirmNo() .wait(/.*Here is the GraphQL API that we will create. Select a setting to edit or continue.*/) .sendCarriageReturn() .wait('Choose a schema template:') .sendCarriageReturn() .wait('Do you want to edit the schema now?') .sendConfirmNo() .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); setTransformerVersionFlag(cwd, options.transformerVersion); }); } export function addAuthWithCustomTrigger(cwd: string, settings: any): Promise<void> { return new Promise((resolve, reject) => { spawn(getCLIPath(), ['add', 'auth'], { cwd, stripColors: true }) .wait('Do you want to use the default authentication and security configuration?') .send(KEY_DOWN_ARROW) .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Select the authentication/authorization services that you want to use:') .sendCarriageReturn() .wait('Provide a friendly name') .sendCarriageReturn() .wait('Enter a name for your identity pool.') .sendCarriageReturn() .wait('Allow unauthenticated logins?') .sendCarriageReturn() .wait('Do you want to enable 3rd party authentication providers in your identity pool?') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Provide a name for your user pool:') .sendCarriageReturn() .wait('How do you want users to be able to sign in?') .sendCarriageReturn() .wait('Do you want to add User Pool Groups?') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Do you want to add an admin queries API?') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Multifactor authentication (MFA) user login options:') .sendCarriageReturn() .wait('Email based user registration/forgot password:') .sendCarriageReturn() .wait('Specify an email verification subject:') .sendCarriageReturn() .wait('Specify an email verification message:') .sendCarriageReturn() .wait('Do you want to override the default password policy for this User Pool?') .sendCarriageReturn() .wait(' What attributes are required for signing up?') .sendCarriageReturn() .wait("Specify the app's refresh token expiration period (in days):") .sendCarriageReturn() .wait('Do you want to specify the user attributes this app can read and write?') .sendCarriageReturn() .wait('Do you want to enable any of the following capabilities?') .send(KEY_DOWN_ARROW) .send(KEY_DOWN_ARROW) .send(KEY_DOWN_ARROW) .send(' ') .sendCarriageReturn() .wait('Do you want to use an OAuth flow?') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Do you want to configure Lambda Triggers for Cognito?') .sendCarriageReturn() .wait('Which triggers do you want to enable for Cognito') .sendCarriageReturn() .wait('What functionality do you want to use for Pre Sign-up') .send(KEY_DOWN_ARROW) .send(KEY_DOWN_ARROW) .send(KEY_DOWN_ARROW) .send(' ') .sendCarriageReturn() .wait('Enter a comma-delimited list of disallowed email domains') .send('amazon.com') .sendCarriageReturn() .wait('Successfully') .wait(`Do you want to edit your email-filter-denylist${settings.useInclusiveTerminology === false ? '-legacy' : ''} function now?`) .sendLine('n') .wait('Do you want to edit your custom function now') .sendLine('n') .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); }); } export function updateAuthSignInSignOutUrl(cwd: string, settings: any): Promise<void> { const testingWithLatestCodebase = settings.testingWithLatestCodebase ?? false; return new Promise((resolve, reject) => { const chain = spawn(getCLIPath(testingWithLatestCodebase), ['update', 'auth'], { cwd, stripColors: true }); if (settings?.overrides?.category === 'auth') { chain.wait('A migration is needed to support latest updates on auth resources').sendConfirmYes(); } chain .wait('What do you want to do?') .send(KEY_DOWN_ARROW) .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Which redirect signin URIs do you want to edit?') .sendCtrlA() .sendCarriageReturn() .wait(`Update ${settings.signinUrl}`) .sendCarriageReturn() .send(settings.updatesigninUrl) .sendCarriageReturn() .wait('Do you want to add redirect signin URIs?') .sendConfirmNo() .wait('Which redirect signout URIs do you want to edit?') .sendCtrlA() .sendCarriageReturn() .wait(`Update ${settings.signoutUrl}`) .send(settings.updatesignoutUrl) .sendCarriageReturn() .wait('Do you want to add redirect signout URIs?') .sendConfirmNo() .sendEof() .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); }); } export function updateAuthToRemoveFederation(cwd: string, settings: any): Promise<void> { const testingWithLatestCodebase = settings.testingWithLatestCodebase ?? false; return new Promise((resolve, reject) => { const chain = spawn(getCLIPath(testingWithLatestCodebase), ['update', 'auth'], { cwd, stripColors: true }); if (settings?.overrides?.category === 'auth') { chain.wait('A migration is needed to support latest updates on auth resources').sendConfirmYes(); } chain .wait('What do you want to do?') .sendCarriageReturn() .wait('"amplify publish" will build all your local backend and frontend resources') .sendEof() .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); }); } export function updateAuthWithoutCustomTrigger(cwd: string, settings: any): Promise<void> { const testingWithLatestCodebase = settings.testingWithLatestCodebase ?? false; return new Promise((resolve, reject) => { const chain = spawn(getCLIPath(testingWithLatestCodebase), ['update', 'auth'], { cwd, stripColors: true }); if (settings?.overrides?.category === 'auth') { chain.wait('A migration is needed to support latest updates on auth resources').sendConfirmYes(); } chain .wait('What do you want to do?') .send(KEY_DOWN_ARROW) .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Select the authentication/authorization services that you want to use:') .sendCarriageReturn() .wait('Allow unauthenticated logins?') .sendCarriageReturn() .wait('Do you want to enable 3rd party authentication providers in your identity pool?') .sendCarriageReturn() .wait('Do you want to add User Pool Groups?') .sendCarriageReturn() .wait('Do you want to add an admin queries API?') .sendCarriageReturn() .wait('Multifactor authentication (MFA) user login options:') .sendCarriageReturn() .wait('Email based user registration/forgot password:') .sendCarriageReturn() .wait('Specify an email verification subject:') .sendCarriageReturn() .wait('Specify an email verification message:') .sendCarriageReturn() .wait('Do you want to override the default password policy for this User Pool?') .sendCarriageReturn() .wait("Specify the app's refresh token expiration period (in days):") .sendCarriageReturn() .wait('Do you want to specify the user attributes this app can read and write?') .sendCarriageReturn() .wait('Do you want to enable any of the following capabilities?') .sendCarriageReturn() .wait('Do you want to use an OAuth flow?') .sendCarriageReturn() .wait('Do you want to configure Lambda Triggers for Cognito?') .sendCarriageReturn() .wait('Which triggers do you want to enable for Cognito') .sendCarriageReturn() .wait('What functionality do you want to use for Pre Sign-up') .send(KEY_DOWN_ARROW) .send(KEY_DOWN_ARROW) .send(KEY_DOWN_ARROW) .send(' ') .sendCarriageReturn() .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); }); } export function addAuthWithRecaptchaTrigger(cwd: string, settings: any): Promise<void> { return new Promise((resolve, reject) => { spawn(getCLIPath(), ['add', 'auth'], { cwd, stripColors: true }) .wait('Do you want to use the default authentication and security configuration?') .sendCarriageReturn() .wait('How do you want users to be able to sign in?') .sendCarriageReturn() .wait('Do you want to configure advanced settings?') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('What attributes are required for signing up?') .sendCarriageReturn() .wait('Do you want to enable any of the following capabilities?') .send(' ') .sendCarriageReturn() .wait('Do you want to edit your captcha-define-challenge function now?') .sendConfirmNo() .wait('Do you want to edit your captcha-create-challenge function now?') .sendConfirmNo() .wait('Enter the Google reCaptcha secret key:') .send('dummykey') .sendCarriageReturn() .wait('Do you want to edit your captcha-verify function now?') .sendConfirmNo() .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); }); } export function updateAuthRemoveRecaptchaTrigger(cwd: string, settings: any): Promise<void> { const testingWithLatestCodebase = settings.testingWithLatestCodebase ?? false; console.log(testingWithLatestCodebase); console.log(settings); return new Promise((resolve, reject) => { const chain = spawn(getCLIPath(testingWithLatestCodebase), ['update', 'auth'], { cwd, stripColors: true }); if (settings?.overrides?.category === 'auth') { chain.wait('A migration is needed to support latest updates on auth resources').sendConfirmYes(); } chain .wait('What do you want to do') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Select the authentication/authorization services') .sendCarriageReturn() .wait('Allow unauthenticated logins?') .sendCarriageReturn() .wait('Do you want to enable 3rd party authentication providers') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Do you want to add User Pool Groups?') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Do you want to add an admin queries API?') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Multifactor authentication (MFA) user login options') .sendCarriageReturn() .wait('Email based user registration/forgot password') .sendCarriageReturn() .wait('Specify an email verification subject:') .sendCarriageReturn() .wait('Specify an email verification message') .sendCarriageReturn() .wait('Do you want to override the default password policy for this') .sendCarriageReturn() .wait('Specify the app') .sendCarriageReturn() .wait('Do you want to specify the user attributes') .sendCarriageReturn() .wait('Do you want to enable any of the following capabilities') .send('a') .send('a') .sendCarriageReturn() .wait('Do you want to use an OAuth') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Do you want to configure Lambda Triggers for Cognito') .sendConfirmNo() .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); }); } export function addAuthWithSignInSignOutUrl(cwd: string, settings: any): Promise<void> { return new Promise((resolve, reject) => { spawn(getCLIPath(), ['add', 'auth'], { cwd, stripColors: true }) .wait('Do you want to use the default authentication and security configuration?') .sendLine(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('How do you want users to be able to sign in?') .sendCarriageReturn() .wait('Do you want to configure advanced settings?') .sendCarriageReturn() .wait('What domain name prefix do you want to use?') .sendCarriageReturn() .wait('Enter your redirect signin URI:') .sendLine(settings.signinUrl) .wait('Do you want to add another redirect signin URI') .sendConfirmNo() .sendCarriageReturn() .wait('Enter your redirect signout URI:') .sendLine(settings.signoutUrl) .sendCarriageReturn() .wait('Do you want to add another redirect signout URI') .sendConfirmNo() .sendCarriageReturn() .wait('Select the social providers you want to configure for your user pool:') .sendCarriageReturn() .sendEof() .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); }); } export function addAuthWithDefaultSocial_v4_30(cwd: string, settings: any): Promise<void> { return new Promise((resolve, reject) => { const { FACEBOOK_APP_ID, FACEBOOK_APP_SECRET, GOOGLE_APP_ID, GOOGLE_APP_SECRET, AMAZON_APP_ID, AMAZON_APP_SECRET } = getSocialProviders(true); spawn(getCLIPath(), ['add', 'auth'], { cwd, stripColors: true }) .wait('Do you want to use the default authentication and security configuration?') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('How do you want users to be able to sign in?') .sendCarriageReturn() .wait('Do you want to configure advanced settings?') .sendCarriageReturn() .wait('What domain name prefix do you want to use?') .sendCarriageReturn() .wait('Enter your redirect signin URI:') .sendLine('https://www.google.com/') .wait('Do you want to add another redirect signin URI') .sendConfirmNo() .wait('Enter your redirect signout URI:') .sendLine('https://www.nytimes.com/') .wait('Do you want to add another redirect signout URI') .sendConfirmNo() .wait('Select the social providers you want to configure for your user pool:') .send('a') .sendCarriageReturn() .wait('Enter your Facebook App ID for your OAuth flow:') .send(FACEBOOK_APP_ID) .sendCarriageReturn() .wait('Enter your Facebook App Secret for your OAuth flow:') .send(FACEBOOK_APP_SECRET) .sendCarriageReturn() .wait('Enter your Google Web Client ID for your OAuth flow:') .send(GOOGLE_APP_ID) .sendCarriageReturn() .wait('Enter your Google Web Client Secret for your OAuth flow:') .send(GOOGLE_APP_SECRET) .sendCarriageReturn() .wait('Enter your Amazon App ID for your OAuth flow:') .send(AMAZON_APP_ID) .sendCarriageReturn() .wait('Enter your Amazon App Secret for your OAuth flow:') .send(AMAZON_APP_SECRET) .sendCarriageReturn() .sendEof() .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); }); } export function addAuthWithDefaultSocial(cwd: string, settings: any): Promise<void> { return new Promise((resolve, reject) => { const { FACEBOOK_APP_ID, FACEBOOK_APP_SECRET, GOOGLE_APP_ID, GOOGLE_APP_SECRET, AMAZON_APP_ID, AMAZON_APP_SECRET, APPLE_APP_ID, APPLE_TEAM_ID, APPLE_KEY_ID, APPLE_PRIVATE_KEY, } = getSocialProviders(true); spawn(getCLIPath(), ['add', 'auth'], { cwd, stripColors: true }) .wait('Do you want to use the default authentication and security configuration?') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('How do you want users to be able to sign in?') .sendCarriageReturn() .wait('Do you want to configure advanced settings?') .sendCarriageReturn() .wait('What domain name prefix do you want to use?') .sendCarriageReturn() .wait('Enter your redirect signin URI:') .sendLine('https://www.google.com/') .wait('Do you want to add another redirect signin URI') .sendConfirmNo() .wait('Enter your redirect signout URI:') .sendLine('https://www.nytimes.com/') .wait('Do you want to add another redirect signout URI') .sendConfirmNo() .wait('Select the social providers you want to configure for your user pool:') .send('a') .sendCarriageReturn() .wait('Enter your Facebook App ID for your OAuth flow:') .send(FACEBOOK_APP_ID) .sendCarriageReturn() .wait('Enter your Facebook App Secret for your OAuth flow:') .send(FACEBOOK_APP_SECRET) .sendCarriageReturn() .wait('Enter your Google Web Client ID for your OAuth flow:') .send(GOOGLE_APP_ID) .sendCarriageReturn() .wait('Enter your Google Web Client Secret for your OAuth flow:') .send(GOOGLE_APP_SECRET) .sendCarriageReturn() .wait('Enter your Amazon App ID for your OAuth flow:') .send(AMAZON_APP_ID) .sendCarriageReturn() .wait('Enter your Amazon App Secret for your OAuth flow:') .send(AMAZON_APP_SECRET) .sendCarriageReturn() .wait('Enter your Services ID for your OAuth flow:') .send(APPLE_APP_ID) .sendCarriageReturn() .wait('Enter your Team ID for your OAuth flow:') .send(APPLE_TEAM_ID) .sendCarriageReturn() .wait('Enter your Key ID for your OAuth flow:') .send(APPLE_KEY_ID) .sendCarriageReturn() .wait('Enter your Private Key for your OAuth flow:') .send(APPLE_PRIVATE_KEY) .sendCarriageReturn() .sendEof() .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); }); } export function addAuthUserPoolOnly(cwd: string, settings: any): Promise<void> { return new Promise((resolve, reject) => { const { FACEBOOK_APP_ID, FACEBOOK_APP_SECRET, GOOGLE_APP_ID, GOOGLE_APP_SECRET, AMAZON_APP_ID, AMAZON_APP_SECRET, APPLE_APP_ID, APPLE_TEAM_ID, APPLE_KEY_ID, APPLE_PRIVATE_KEY, } = getSocialProviders(true); spawn(getCLIPath(), ['add', 'auth'], { cwd, stripColors: true }) .wait('Do you want to use the default authentication and security configuration?') .sendKeyDown(2) .sendCarriageReturn() .wait('Select the authentication/authorization services that you want to use') .sendKeyDown() .sendCarriageReturn() .wait('Provide a friendly name for your resource that will be used') .sendCarriageReturn() .wait('Provide a name for your user pool') .sendCarriageReturn() .wait('How do you want users to be able to sign in') .sendCarriageReturn() .wait('Do you want to add User Pool Groups?') .sendCarriageReturn() .wait('Provide a name for your user pool group') .sendLine('userPoolGroup1') .wait('Do you want to add another User Pool Group') .sendConfirmYes() .wait('Provide a name for your user pool group') .sendLine('userPoolGroup2') .wait('Do you want to add another User Pool Group') .sendCarriageReturn() .wait('Sort the user pool groups in order of preference') .sendCarriageReturn() .wait('Do you want to add an admin queries API?') .sendCarriageReturn() .wait('Do you want to restrict access to the admin queries API') .sendCarriageReturn() .wait('Select the group to restrict access with') .sendCarriageReturn() .wait('Multifactor authentication (MFA) user login options') .sendKeyDown() .sendCarriageReturn() .wait('For user login, select the MFA types') .sendLine('a') .wait('Specify an SMS authentication message') .sendCarriageReturn() .wait('Email based user registration/forgot password') .sendCarriageReturn() .wait('Specify an email verification subject') .sendCarriageReturn() .wait('Specify an email verification message') .sendCarriageReturn() .wait('Do you want to override the default password policy') .sendConfirmYes() .wait('Enter the minimum password length for this User Pool') .sendCarriageReturn() .wait('Select the password character requirements for your userpool') .sendLine('a') .wait('What attributes are required for signing up?') .sendCarriageReturn() .wait('Specify the app') .sendCarriageReturn() .wait('Do you want to specify the user attributes this app') .sendConfirmYes() .wait('Specify read attributes') .sendCarriageReturn() .wait('Specify write attributes') .sendCarriageReturn() .wait('Do you want to enable any of the following capabilities?') .sendCarriageReturn() .wait('Do you want to use an OAuth flow') .sendCarriageReturn() .wait('What domain name prefix do you want to use?') .sendCarriageReturn() .wait('Enter your redirect signin URI') .sendLine('https://signin1/') .wait('Do you want to add another redirect signin URI') .sendConfirmNo() .wait('Enter your redirect signout URI') .sendLine('https://signout1/') .wait('Do you want to add another redirect signout URI') .sendConfirmNo() .wait('Select the OAuth flows enabled for this project') .sendCarriageReturn() .wait('Select the OAuth scopes enabled for this project') .sendCarriageReturn() .wait('Select the social providers you want to configure for your user pool') .sendLine('a') .wait('Enter your Facebook App ID for your OAuth flow') .sendLine(FACEBOOK_APP_ID) .wait('Enter your Facebook App Secret for your OAuth flow') .sendLine(FACEBOOK_APP_SECRET) .wait('Enter your Google Web Client ID for your OAuth flow') .sendLine(GOOGLE_APP_ID) .wait('Enter your Google Web Client Secret for your OAuth flow') .sendLine(GOOGLE_APP_SECRET) .wait('Enter your Amazon App ID for your OAuth flow') .sendLine(AMAZON_APP_ID) .wait('Enter your Amazon App Secret for your OAuth flow') .sendLine(AMAZON_APP_SECRET) .wait('Enter your Services ID for your OAuth flow') .sendLine(APPLE_APP_ID) .wait('Enter your Team ID for your OAuth flow') .sendLine(APPLE_TEAM_ID) .wait('Enter your Key ID for your OAuth flow') .sendLine(APPLE_KEY_ID) .wait('Enter your Private Key for your OAuth flow') .sendLine(APPLE_PRIVATE_KEY) .wait('Do you want to configure Lambda Triggers for Cognito') .sendConfirmYes() .wait('Which triggers do you want to enable for Cognito') .send('a') .sendLine(' ') .wait('What functionality do you want to use for Create Auth Challenge') .sendKeyDown(3) .sendLine(' ') .wait('What functionality do you want to use for Custom Message') .sendKeyDown(2) .sendLine(' ') .wait('What functionality do you want to use for Define Auth Challenge') .sendKeyDown(3) .sendLine(' ') .wait('What functionality do you want to use for Post Authentication') .sendCarriageReturn() .wait('What functionality do you want to use for Post Confirmation') .sendCarriageReturn() .wait('What functionality do you want to use for Pre Authentication') .sendCarriageReturn() .wait('What functionality do you want to use for Pre Sign-up') .sendCarriageReturn() .wait('What functionality do you want to use for Verify') .sendCarriageReturn() .wait('What functionality do you want to use for Pre Token') .sendCarriageReturn() .wait('Do you want to edit your custom function now') .sendConfirmNo() .wait('Successfully') .wait('Do you want to edit your custom function now') .sendConfirmNo() .wait('Successfully') .wait('Do you want to edit your custom function now') .sendConfirmNo() .sendEof() .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); }); } // creates 2 groups: Admins, Users export function addAuthWithGroups(cwd: string): Promise<void> { return new Promise((resolve, reject) => { spawn(getCLIPath(), ['add', 'auth'], { cwd, stripColors: true }) .wait('Do you want to use the default authentication and security configuration') .sendKeyDown(2) .sendCarriageReturn() // Manual configuration .wait('Select the authentication/authorization services that you want to use') .sendCarriageReturn() // for sign-up/-in and IAM controls .wait('Provide a friendly name for your resource that will be used') .sendCarriageReturn() // Default .wait('Enter a name for your identity pool') .sendCarriageReturn() // Default .wait('Allow unauthenticated logins') .sendCarriageReturn() // No .wait('Do you want to enable 3rd party authentication providers') .sendKeyDown() .sendCarriageReturn() // No .wait('Provide a name for your user pool') .sendCarriageReturn() // Default .wait('Warning: you will not be able to edit these selections') .wait('How do you want users to be able to sign in') .sendCarriageReturn() // Username .wait('Do you want to add User Pool Groups') .sendCarriageReturn() // Yes .wait('Provide a name for your user pool group') .sendLine('Admins') .wait('Do you want to add another User Pool Group') .sendConfirmYes() .wait('Provide a name for your user pool group') .sendLine('Users') .wait('Do you want to add another User Pool Group') .sendConfirmNo() .wait('Sort the user pool groups in order of preference') .sendCarriageReturn() // As is, Admins, Users .wait('Do you want to add an admin queries API') .sendKeyDown() .sendCarriageReturn() // No .wait('Multifactor authentication (MFA) user login options') .sendCarriageReturn() // Select Off .wait('Email based user registration/forgot password') .sendCarriageReturn() // Enabled .wait('Specify an email verification subject') .sendCarriageReturn() // Your verification code .wait('Specify an email verification message') .sendCarriageReturn() // Your verification code is {####} .wait('Do you want to override the default password policy') .sendConfirmNo() .wait('What attributes are required for signing up') .sendCarriageReturn() // Email .wait("Specify the app's refresh token expiration period") .sendCarriageReturn() // 30 .wait('Do you want to specify the user attributes this app can read and write') .sendConfirmNo() .wait('Do you want to enable any of the following capabilities') .sendCarriageReturn() // None .wait('Do you want to use an OAuth flow') .sendKeyDown() .sendCarriageReturn() // No .wait('Do you want to configure Lambda Triggers for Cognito') .sendConfirmNo() .sendEof() .run((err: Error) => (err ? reject(err) : resolve())); }); } // creates 2 groups: Admins, Users export function addAuthWithGroupsAndAdminAPI(cwd: string, settings?: any): Promise<void> { return new Promise((resolve, reject) => { spawn(getCLIPath(), ['add', 'auth'], { cwd, stripColors: true }) .wait('Do you want to use the default authentication and security configuration') .sendKeyDown(2) .sendCarriageReturn() // Manual configuration .wait('Select the authentication/authorization services that you want to use') .sendCarriageReturn() // for sign-up/-in and IAM controls .wait('Provide a friendly name for your resource that will be used') .sendCarriageReturn() // Default .wait('Enter a name for your identity pool') .sendCarriageReturn() // Default .wait('Allow unauthenticated logins') .sendCarriageReturn() // No .wait('Do you want to enable 3rd party authentication providers') .sendKeyDown() .sendCarriageReturn() // No .wait('Provide a name for your user pool') .sendCarriageReturn() // Default .wait('Warning: you will not be able to edit these selections') .wait('How do you want users to be able to sign in') .sendCarriageReturn() // Username .wait('Do you want to add User Pool Groups') .sendCarriageReturn() // Yes .wait('Provide a name for your user pool group') .sendLine('Admins') .wait('Do you want to add another User Pool Group') .sendConfirmYes() .wait('Provide a name for your user pool group') .sendLine('Users') .wait('Do you want to add another User Pool Group') .sendConfirmNo() .wait('Sort the user pool groups in order of preference') .sendCarriageReturn() // As is, Admins, Users .wait('Do you want to add an admin queries API') .sendCarriageReturn() // Yes .wait('Do you want to restrict access to the admin queries API') .sendConfirmYes() .wait('Select the group to restrict access with') .sendCarriageReturn() // Admins .wait('Multifactor authentication (MFA) user login options') .sendCarriageReturn() // OFF .wait('Email based user registration/forgot password') .sendCarriageReturn() // Enabled .wait('Specify an email verification subject') .sendCarriageReturn() // Your verification code .wait('Specify an email verification message') .sendCarriageReturn() // Your verification code is {####} .wait('Do you want to override the default password policy') .sendConfirmNo() .wait('What attributes are required for signing up') .sendCarriageReturn() // Email .wait("Specify the app's refresh token expiration period") .sendCarriageReturn() // 30 .wait('Do you want to specify the user attributes this app can read and write') .sendConfirmNo() .wait('Do you want to enable any of the following capabilities') .sendCarriageReturn() // None .wait('Do you want to use an OAuth flow') .sendKeyDown() .sendCarriageReturn() // No .wait('Do you want to configure Lambda Triggers for Cognito') .sendConfirmNo() .sendEof() .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); }); } export function addAuthWithMaxOptions(cwd: string, settings: any): Promise<void> { const { FACEBOOK_APP_ID, FACEBOOK_APP_SECRET, GOOGLE_APP_ID, GOOGLE_APP_SECRET, AMAZON_APP_ID, AMAZON_APP_SECRET, APPLE_APP_ID, APPLE_TEAM_ID, APPLE_KEY_ID, APPLE_PRIVATE_KEY, } = getSocialProviders(true); return new Promise((resolve, reject) => { const chain = spawn(getCLIPath(), ['add', 'auth'], { cwd, stripColors: true }) .wait('Do you want to use the default authentication and security configuration?') .send(KEY_DOWN_ARROW) .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Select the authentication/authorization services that you want to use') .sendCarriageReturn() .wait('Provide a friendly name for your resource that will be used') .sendCarriageReturn() .wait('Enter a name for your identity pool') .sendCarriageReturn() .wait('Allow unauthenticated logins') .sendCarriageReturn() .wait('Do you want to enable 3rd party authentication providers') .sendCarriageReturn() .wait('Select the third party identity providers you want to') .send('a') .sendCarriageReturn() .wait('Enter your Facebook App ID for your identity pool') .send('fbIDPOOL') .sendCarriageReturn() .wait('Enter your Google Web Client ID for your identity pool:') .send('googleIDPOOL') .sendCarriageReturn(); if (settings.frontend === 'ios') { chain.wait('Enter your Google iOS Client ID for your identity pool').send('googleiosclientId').sendCarriageReturn(); } if (settings.frontend === 'android') { chain.wait('Enter your Google Android Client ID for your identity pool').send('googleandroidclientid').sendCarriageReturn(); } chain .wait('Enter your Amazon App ID for your identity pool') .send('amazonIDPOOL') .sendCarriageReturn() .wait('Enter your Bundle Identifier for your identity pool') .send('appleIDPOOL') .sendCarriageReturn() .wait('Provide a name for your user pool') .sendCarriageReturn() .wait('How do you want users to be able to sign in') .sendCarriageReturn() .wait('Do you want to add User Pool Groups?') .sendCarriageReturn() .wait('Provide a name for your user pool group') .send('userPoolGroup1') .sendCarriageReturn() .wait('Do you want to add another User Pool Group') .send('y') .sendCarriageReturn() .wait('Provide a name for your user pool group') .send('userPoolGroup2') .sendCarriageReturn() .wait('Do you want to add another User Pool Group') .sendCarriageReturn() .wait('Sort the user pool groups in order of preference') .sendCarriageReturn() .wait('Do you want to add an admin queries API?') .sendCarriageReturn() .wait('Do you want to restrict access to the admin queries API') .sendCarriageReturn() .wait('Select the group to restrict access with') .sendCarriageReturn() .wait('Multifactor authentication (MFA) user login options') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('For user login, select the MFA types') .send('a') .sendCarriageReturn() .wait('Specify an SMS authentication message') .sendCarriageReturn() .wait('Email based user registration/forgot password') .sendCarriageReturn() .wait('Specify an email verification subject') .sendCarriageReturn() .wait('Specify an email verification message') .sendCarriageReturn() .wait('Do you want to override the default password policy') .sendConfirmYes() .wait('Enter the minimum password length for this User Pool') .sendCarriageReturn() .wait('Select the password character requirements for your userpool') .send('a') .sendCarriageReturn() .wait('What attributes are required for signing up?') .sendCarriageReturn() .wait('Specify the app') .sendCarriageReturn() .wait('Do you want to specify the user attributes this app') .sendConfirmYes() .wait('Specify read attributes') .sendCarriageReturn() .wait('Specify write attributes') .sendCarriageReturn() .wait('Do you want to enable any of the following capabilities?') .sendCarriageReturn() .wait('Do you want to use an OAuth flow') .sendCarriageReturn() .wait('What domain name prefix do you want to use?') .sendCarriageReturn() .wait('Enter your redirect signin URI') .sendLine('https://signin1/') .wait('Do you want to add another redirect signin URI') .sendConfirmNo() .wait('Enter your redirect signout URI') .sendLine('https://signout1/') .wait('Do you want to add another redirect signout URI') .sendConfirmNo(); if (settings.frontend !== 'ios' && settings.frontend !== 'android' && settings.frontend !== 'flutter') { chain.wait('Select the OAuth flows enabled for this project').sendCarriageReturn(); } chain .wait('Select the OAuth scopes enabled for this project') .sendCarriageReturn() .wait('Select the social providers you want to configure for your user pool') .send('a') .sendCarriageReturn() .wait('Enter your Facebook App ID for your OAuth flow') .sendLine(FACEBOOK_APP_ID) .wait('Enter your Facebook App Secret for your OAuth flow') .sendLine(FACEBOOK_APP_SECRET) .wait('Enter your Google Web Client ID for your OAuth flow') .sendLine(GOOGLE_APP_ID) .wait('Enter your Google Web Client Secret for your OAuth flow') .sendLine(GOOGLE_APP_SECRET) .wait('Enter your Amazon App ID for your OAuth flow') .sendLine(AMAZON_APP_ID) .wait('Enter your Amazon App Secret for your OAuth flow') .sendLine(AMAZON_APP_SECRET) .wait('Enter your Services ID for your OAuth flow') .sendLine(APPLE_APP_ID) .wait('Enter your Team ID for your OAuth flow') .sendLine(APPLE_TEAM_ID) .wait('Enter your Key ID for your OAuth flow') .sendLine(APPLE_KEY_ID) .wait('Enter your Private Key for your OAuth flow') .sendLine(APPLE_PRIVATE_KEY) .wait('Do you want to configure Lambda Triggers for Cognito') .sendConfirmYes() .wait('Which triggers do you want to enable for Cognito') .send('a') .send(' ') .sendCarriageReturn() .wait('What functionality do you want to use for Create Auth Challenge') .send(KEY_DOWN_ARROW) .send(KEY_DOWN_ARROW) .send(KEY_DOWN_ARROW) .send(' ') .sendCarriageReturn() .wait('What functionality do you want to use for Custom Message') .send(KEY_DOWN_ARROW) .send(KEY_DOWN_ARROW) .send(' ') .sendCarriageReturn() .wait('What functionality do you want to use for Define Auth Challenge') .send(KEY_DOWN_ARROW) .send(KEY_DOWN_ARROW) .send(KEY_DOWN_ARROW) .send(' ') .sendCarriageReturn() .wait('What functionality do you want to use for Post Authentication') .sendCarriageReturn() .wait('What functionality do you want to use for Post Confirmation') .sendCarriageReturn() .wait('What functionality do you want to use for Pre Authentication') .sendCarriageReturn() .wait('What functionality do you want to use for Pre Sign-up') .sendCarriageReturn() .wait('What functionality do you want to use for Verify') .sendCarriageReturn() .wait('What functionality do you want to use for Pre Token') .sendCarriageReturn() .wait('Do you want to edit your custom function now') .sendConfirmNo() .wait('Successfully') .wait('Do you want to edit your custom function now') .sendConfirmNo() .wait('Successfully') .wait('Do you want to edit your custom function now') .sendConfirmNo() .wait('Successfully') .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); }); } //add default auth with pre token generation trigger export function addAuthWithPreTokenGenerationTrigger(projectDir: string): Promise<void> { return new Promise((resolve, reject) => { spawn(getCLIPath(), ['add', 'auth'], { cwd: projectDir, stripColors: true }) .wait('Do you want to use the default authentication and security configuration') .sendCarriageReturn() .wait('How do you want users to be able to sign in') .sendCarriageReturn() .wait('Do you want to configure advanced settings') .sendLine(KEY_DOWN_ARROW) .wait('What attributes are required for signing up?') .sendCarriageReturn() .wait('Do you want to enable any of the following capabilities') .send(KEY_UP_ARROW) //Override ID Token Claims .sendLine(' ') .wait('Successfully added the Lambda function locally') .wait('Do you want to edit your alter-claims function now') .sendLine('n') .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); }); } export function updateAuthAddUserGroups(projectDir: string, groupNames: string[], settings?: any): Promise<void> { if (groupNames.length == 0) { return; } const testingWithLatestCodebase = settings && settings.testingWithLatestCodebase ? settings.testingWithLatestCodebase : false; return new Promise((resolve, reject) => { const chain = spawn(getCLIPath(testingWithLatestCodebase), ['update', 'auth'], { cwd: projectDir, stripColors: true }); if (settings?.overrides?.category === 'auth') { chain.wait('A migration is needed to support latest updates on auth resources').sendConfirmYes(); } chain .wait('What do you want to do?') .send(KEY_DOWN_ARROW) .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Provide a name for your user pool group') .send(groupNames[0]) .sendCarriageReturn(); if (groupNames.length > 1) { let index = 1; while (index < groupNames.length) { chain .wait('Do you want to add another User Pool Group') .sendConfirmYes() .wait('Provide a name for your user pool group') .send(groupNames[index++]); } } chain .wait('Do you want to add another User Pool Group') .sendCarriageReturn() .wait('Sort the user pool groups in order of preference') .sendCarriageReturn() .wait('"amplify publish" will build all your local backend and frontend resources'); chain.run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); }); } export function addAuthUserPoolOnlyWithOAuth(cwd: string, settings: AddAuthUserPoolOnlyWithOAuthSettings): Promise<void> { return new Promise((resolve, reject) => { spawn(getCLIPath(), ['add', 'auth'], { cwd, stripColors: true }) .wait('Do you want to use the default authentication and security configuration?') .sendKeyDown(2) .sendCarriageReturn() .wait('Select the authentication/authorization services that you want to use') .sendKeyDown() .sendCarriageReturn() .wait('Provide a friendly name for your resource that will be used') .sendLine(settings.resourceName) .wait('Provide a name for your user pool') .sendLine(settings.userPoolName) .wait('How do you want users to be able to sign in') .sendCarriageReturn() // Username .wait('Do you want to add User Pool Groups?') .sendKeyDown() // No .sendCarriageReturn() .wait('Do you want to add an admin queries API?') .sendKeyDown() // No .sendCarriageReturn() .wait('Multifactor authentication (MFA) user login options') .sendCarriageReturn() // OFF .wait('Email based user registration/forgot password') .sendCarriageReturn() // Enabled .wait('Specify an email verification subject') .sendCarriageReturn() .wait('Specify an email verification message') .sendCarriageReturn() .wait('Do you want to override the default password policy') .sendConfirmNo() .wait('What attributes are required for signing up?') .sendCarriageReturn() .wait("Specify the app's refresh token expiration period (in days)") .sendCarriageReturn() .wait('Do you want to specify the user attributes this app can read and write') .sendConfirmNo() .wait('Do you want to enable any of the following capabilities?') .sendCarriageReturn() .wait('Do you want to use an OAuth flow') .sendCarriageReturn() // Yes .wait('What domain name prefix do you want to use?') .sendLine(settings.domainPrefix) .wait('Enter your redirect signin URI') .sendLine(settings.signInUrl1) .wait('Do you want to add another redirect signin URI') .sendConfirmYes() .wait('Enter your redirect signin URI') .sendLine(settings.signInUrl2) .wait('Do you want to add another redirect signin URI') .sendConfirmNo() .wait('Enter your redirect signout URI') .sendLine(settings.signOutUrl1) .wait('Do you want to add another redirect signout URI') .sendConfirmYes() .wait('Enter your redirect signout URI') .sendLine(settings.signOutUrl2) .wait('Do you want to add another redirect signout URI') .sendConfirmNo() .wait('Select the OAuth flows enabled for this project') .sendCarriageReturn() // Authorization Grant .wait('Select the OAuth scopes enabled for this project') .sendCarriageReturn() // All .wait('Select the social providers you want to configure for your user pool') .sendLine('a') // Select all .wait('Enter your Facebook App ID for your OAuth flow') .sendLine(settings.facebookAppId) .wait('Enter your Facebook App Secret for your OAuth flow') .sendLine(settings.facebookAppSecret) .wait('Enter your Google Web Client ID for your OAuth flow') .sendLine(settings.googleAppId) .wait('Enter your Google Web Client Secret for your OAuth flow') .sendLine(settings.googleAppSecret) .wait('Enter your Amazon App ID for your OAuth flow') .sendLine(settings.amazonAppId) .wait('Enter your Amazon App Secret for your OAuth flow') .sendLine(settings.amazonAppSecret) .wait('Enter your Services ID for your OAuth flow:') .sendLine(settings.appleAppClientId) .wait('Enter your Team ID for your OAuth flow:') .sendLine(settings.appleAppTeamId) .wait('Enter your Key ID for your OAuth flow:') .sendLine(settings.appleAppKeyID) .wait('Enter your Private Key for your OAuth flow:') .sendLine(settings.appleAppPrivateKey) .wait('Do you want to configure Lambda Triggers for Cognito') .sendConfirmNo() .sendEof() .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); }); } export function addAuthIdentityPoolAndUserPoolWithOAuth( cwd: string, settings: AddAuthIdentityPoolAndUserPoolWithOAuthSettings, ): Promise<void> { return new Promise((resolve, reject) => { let chain = spawn(getCLIPath(), ['add', 'auth'], { cwd, stripColors: true }) .wait('Do you want to use the default authentication and security configuration?') .sendKeyDown(2) .sendCarriageReturn() .wait('Select the authentication/authorization services that you want to use') .sendCarriageReturn() .wait('Provide a friendly name for your resource that will be used') .sendLine(settings.resourceName) .wait('Enter a name for your identity pool') .sendLine(settings.identityPoolName) .wait('Allow unauthenticated logins'); if (settings.allowUnauthenticatedIdentities) { chain.sendKeyUp().sendCarriageReturn(); } else { chain.sendConfirmNo(); } chain .wait('Do you want to enable 3rd party authentication providers') .sendConfirmYes() .wait('Select the third party identity providers you want to') .send('a') .sendCarriageReturn() .wait('Enter your Facebook App ID for your identity pool') .sendLine(settings.idpFacebookAppId) .wait('Enter your Google Web Client ID for your identity pool:') .sendLine(settings.idpGoogleAppId) .wait('Enter your Amazon App ID for your identity pool') .sendLine(settings.idpAmazonAppId) .wait('Enter your Bundle Identifier for your identity pool') .sendLine(settings.idpAppleAppId) .wait('Provide a name for your user pool') .sendLine(settings.userPoolName) .wait('How do you want users to be able to sign in') .sendCarriageReturn() // Username .wait('Do you want to add User Pool Groups?') .sendKeyDown() // No .sendCarriageReturn() .wait('Do you want to add an admin queries API?') .sendKeyDown() // No .sendCarriageReturn() .wait('Multifactor authentication (MFA) user login options') .sendCarriageReturn() // OFF .wait('Email based user registration/forgot password') .sendCarriageReturn() // Enabled .wait('Specify an email verification subject') .sendCarriageReturn() .wait('Specify an email verification message') .sendCarriageReturn() .wait('Do you want to override the default password policy') .sendConfirmNo() .wait('What attributes are required for signing up?') .sendCarriageReturn() .wait("Specify the app's refresh token expiration period (in days)") .sendCarriageReturn() .wait('Do you want to specify the user attributes this app can read and write') .sendConfirmNo() .wait('Do you want to enable any of the following capabilities?') .sendCarriageReturn() .wait('Do you want to use an OAuth flow') .sendCarriageReturn() // Yes .wait('What domain name prefix do you want to use?') .sendLine(settings.domainPrefix) .wait('Enter your redirect signin URI') .sendLine(settings.signInUrl1) .wait('Do you want to add another redirect signin URI') .sendConfirmYes() .wait('Enter your redirect signin URI') .sendLine(settings.signInUrl2) .wait('Do you want to add another redirect signin URI') .sendConfirmNo() .wait('Enter your redirect signout URI') .sendLine(settings.signOutUrl1) .wait('Do you want to add another redirect signout URI') .sendConfirmYes() .wait('Enter your redirect signout URI') .sendLine(settings.signOutUrl2) .wait('Do you want to add another redirect signout URI') .sendConfirmNo() .wait('Select the OAuth flows enabled for this project') .sendCarriageReturn() // Authorization Grant .wait('Select the OAuth scopes enabled for this project') .sendCarriageReturn() // All .wait('Select the social providers you want to configure for your user pool') .sendLine('a') // Select all .wait('Enter your Facebook App ID for your OAuth flow') .sendLine(settings.facebookAppId) .wait('Enter your Facebook App Secret for your OAuth flow') .sendLine(settings.facebookAppSecret) .wait('Enter your Google Web Client ID for your OAuth flow') .sendLine(settings.googleAppId) .wait('Enter your Google Web Client Secret for your OAuth flow') .sendLine(settings.googleAppSecret) .wait('Enter your Amazon App ID for your OAuth flow') .sendLine(settings.amazonAppId) .wait('Enter your Amazon App Secret for your OAuth flow') .sendLine(settings.amazonAppSecret) .wait('Enter your Services ID for your OAuth flow:') .sendLine(settings.appleAppClientId) .wait('Enter your Team ID for your OAuth flow:') .sendLine(settings.appleAppTeamId) .wait('Enter your Key ID for your OAuth flow:') .sendLine(settings.appleAppKeyID) .wait('Enter your Private Key for your OAuth flow:') .sendLine(settings.appleAppPrivateKey) .wait('Do you want to configure Lambda Triggers for Cognito') .sendConfirmNo() .sendEof() .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); }); } export function addAuthUserPoolOnlyNoOAuth(cwd: string, settings: AddAuthUserPoolOnlyNoOAuthSettings): Promise<void> { return new Promise((resolve, reject) => { spawn(getCLIPath(), ['add', 'auth'], { cwd, stripColors: true }) .wait('Do you want to use the default authentication and security configuration?') .sendKeyDown(2) .sendCarriageReturn() .wait('Select the authentication/authorization services that you want to use') .sendKeyDown() .sendCarriageReturn() .wait('Provide a friendly name for your resource that will be used') .sendLine(settings.resourceName) .wait('Provide a name for your user pool') .sendLine(settings.userPoolName) .wait('How do you want users to be able to sign in') .sendCarriageReturn() // Username .wait('Do you want to add User Pool Groups?') .sendKeyDown() // No .sendCarriageReturn() .wait('Do you want to add an admin queries API?') .sendKeyDown() // No .sendCarriageReturn() .wait('Multifactor authentication (MFA) user login options') .sendCarriageReturn() // OFF .wait('Email based user registration/forgot password') .sendCarriageReturn() // Enabled .wait('Specify an email verification subject') .sendCarriageReturn() .wait('Specify an email verification message') .sendCarriageReturn() .wait('Do you want to override the default password policy') .sendConfirmNo() .wait('What attributes are required for signing up?') .sendCarriageReturn() .wait("Specify the app's refresh token expiration period (in days)") .sendCarriageReturn() .wait('Do you want to specify the user attributes this app can read and write') .sendConfirmNo() .wait('Do you want to enable any of the following capabilities?') .sendCarriageReturn() .wait('Do you want to use an OAuth flow') .sendKeyDown() // No .sendCarriageReturn() .wait('Do you want to configure Lambda Triggers for Cognito') .sendConfirmNo() .sendEof() .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); }); } export function updateAuthAddAdminQueries(projectDir: string, groupName: string = 'adminQueriesGroup', settings: any = {}): Promise<void> { const testingWithLatestCodebase = settings.testingWithLatestCodebase ?? false; return new Promise((resolve, reject) => { const chain = spawn(getCLIPath(testingWithLatestCodebase), ['update', 'auth'], { cwd: projectDir, stripColors: true }); if (settings?.overrides?.category === 'auth') { chain.wait('A migration is needed to support latest updates on auth resources').sendYes(); } chain .wait('What do you want to do?') .sendKeyUp() .sendCarriageReturn() // Create or update Admin queries API .wait('Do you want to restrict access to the admin queries API to a specific Group') .sendConfirmYes() .wait('Select the group to restrict access with') .sendCarriageReturn() // Enter a custom group .wait('Provide a group name') .send(groupName) .sendCarriageReturn() .sendEof() .run((err: Error) => { if (err) { reject(err); } else { resolve(); } }); }); } export function updateAuthWithoutTrigger(cwd: string, settings: any): Promise<void> { const testingWithLatestCodebase = settings.testingWithLatestCodebase ?? false; return new Promise((resolve, reject) => { const chain = spawn(getCLIPath(testingWithLatestCodebase), ['update', 'auth'], { cwd, stripColors: true }); if (settings?.overrides?.category === 'auth') { chain.wait('A migration is needed to support latest updates on auth resources').sendConfirmYes(); } chain .wait('What do you want to do?') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Select the authentication/authorization services that you want to use:') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Do you want to add User Pool Groups?') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Do you want to add an admin queries API?') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Multifactor authentication (MFA) user login options:') .sendCarriageReturn() .wait('Email based user registration/forgot password:') .sendCarriageReturn() .wait('Specify an email verification subject:') .sendCarriageReturn() .wait('Specify an email verification message:') .sendCarriageReturn() .wait('Do you want to override the default password policy for this User Pool?') .sendCarriageReturn() .wait("Specify the app's refresh token expiration period (in days):") .sendCarriageReturn() .wait('Do you want to specify the user attributes this app can read and write?') .sendCarriageReturn() .wait('Do you want to enable any of the following capabilities?') .sendCarriageReturn() .wait('Do you want to use an OAuth flow?') .send(KEY_DOWN_ARROW) .sendCarriageReturn() .wait('Do you want to configure Lambda Triggers for Cognito?') .sendConfirmNo() .run((err: Error) => { if (!err) { resolve(); } else { reject(err); } }); }); } export function updateAuthAdminQueriesWithExtMigration(cwd: string, settings: { testingWithLatestCodebase: boolean }): Promise<void> { return spawn(getCLIPath(settings.testingWithLatestCodebase), ['update', 'auth'], { cwd, stripColors: true }) .wait('Do you want to migrate auth resource') .sendYes() .wait('What do you want to do') .sendKeyUp() .sendCarriageReturn() // Create or update Admin queries API .wait('Do you want to restrict access to the admin queries API to a specific Group') .sendYes() .sendCarriageReturn() .wait('Select the group to restrict access with') .sendCarriageReturn() // Enter a custom group .wait('Provide a group name') .sendLine('mycustomgroup') .wait('A migration is needed to support latest updates') .sendYes() .runAsync(); }
the_stack
import * as Path from 'path' import * as fileSystem from '../../lib/file-system' import { getBlobContents } from './show' import { Repository } from '../../models/repository' import { WorkingDirectoryFileChange, FileChange, AppFileStatusKind, } from '../../models/status' import { DiffType, IRawDiff, IDiff, IImageDiff, Image, LineEndingsChange, parseLineEndingText, ILargeTextDiff, IUnrenderableDiff, } from '../../models/diff' import { spawnAndComplete } from './spawn' import { DiffParser } from '../diff-parser' import { getOldPathOrDefault } from '../get-old-path' import { getCaptures } from '../helpers/regex' /** * V8 has a limit on the size of string it can create (~256MB), and unless we want to * trigger an unhandled exception we need to do the encoding conversion by hand. * * This is a hard limit on how big a buffer can be and still be converted into * a string. */ const MaxDiffBufferSize = 70e6 // 70MB in decimal /** * Where `MaxDiffBufferSize` is a hard limit, this is a suggested limit. Diffs * bigger than this _could_ be displayed but it might cause some slowness. */ const MaxReasonableDiffSize = MaxDiffBufferSize / 16 // ~4.375MB in decimal /** * The longest line length we should try to display. If a diff has a line longer * than this, we probably shouldn't attempt it */ const MaxCharactersPerLine = 5000 /** * Utility function to check whether parsing this buffer is going to cause * issues at runtime. * * @param buffer A buffer of binary text from a spawned process */ function isValidBuffer(buffer: Buffer) { return buffer.length <= MaxDiffBufferSize } /** Is the buffer too large for us to reasonably represent? */ function isBufferTooLarge(buffer: Buffer) { return buffer.length >= MaxReasonableDiffSize } /** Is the diff too large for us to reasonably represent? */ function isDiffTooLarge(diff: IRawDiff) { for (const hunk of diff.hunks) { for (const line of hunk.lines) { if (line.text.length > MaxCharactersPerLine) { return true } } } return false } /** * Defining the list of known extensions we can render inside the app */ const imageFileExtensions = new Set([ '.png', '.jpg', '.jpeg', '.gif', '.ico', '.webp', '.bmp', '.avif', ]) /** * Render the difference between a file in the given commit and its parent * * @param commitish A commit SHA or some other identifier that ultimately dereferences * to a commit. */ export async function getCommitDiff( repository: Repository, file: FileChange, commitish: string, hideWhitespaceInDiff: boolean = false ): Promise<IDiff> { const args = [ 'log', commitish, ...(hideWhitespaceInDiff ? ['-w'] : []), '-m', '-1', '--first-parent', '--patch-with-raw', '-z', '--no-color', '--', file.path, ] if ( file.status.kind === AppFileStatusKind.Renamed || file.status.kind === AppFileStatusKind.Copied ) { args.push(file.status.oldPath) } const { output } = await spawnAndComplete( args, repository.path, 'getCommitDiff' ) return buildDiff(output, repository, file, commitish) } /** * Render the diff for a file within the repository working directory. The file will be * compared against HEAD if it's tracked, if not it'll be compared to an empty file meaning * that all content in the file will be treated as additions. */ export async function getWorkingDirectoryDiff( repository: Repository, file: WorkingDirectoryFileChange, hideWhitespaceInDiff: boolean = false ): Promise<IDiff> { // `--no-ext-diff` should be provided wherever we invoke `git diff` so that any // diff.external program configured by the user is ignored const args = [ 'diff', ...(hideWhitespaceInDiff ? ['-w'] : []), '--no-ext-diff', '--patch-with-raw', '-z', '--no-color', ] const successExitCodes = new Set([0]) if ( file.status.kind === AppFileStatusKind.New || file.status.kind === AppFileStatusKind.Untracked ) { // `git diff --no-index` seems to emulate the exit codes from `diff` irrespective of // whether you set --exit-code // // this is the behavior: // - 0 if no changes found // - 1 if changes found // - and error otherwise // // citation in source: // https://github.com/git/git/blob/1f66975deb8402131fbf7c14330d0c7cdebaeaa2/diff-no-index.c#L300 successExitCodes.add(1) args.push('--no-index', '--', '/dev/null', file.path) } else if (file.status.kind === AppFileStatusKind.Renamed) { // NB: Technically this is incorrect, the best kind of incorrect. // In order to show exactly what will end up in the commit we should // perform a diff between the new file and the old file as it appears // in HEAD. By diffing against the index we won't show any changes // already staged to the renamed file which differs from our other diffs. // The closest I got to that was running hash-object and then using // git diff <blob> <blob> but that seems a bit excessive. args.push('--', file.path) } else { args.push('HEAD', '--', file.path) } const { output, error } = await spawnAndComplete( args, repository.path, 'getWorkingDirectoryDiff', successExitCodes ) const lineEndingsChange = parseLineEndingsWarning(error) return buildDiff(output, repository, file, 'HEAD', lineEndingsChange) } async function getImageDiff( repository: Repository, file: FileChange, commitish: string ): Promise<IImageDiff> { let current: Image | undefined = undefined let previous: Image | undefined = undefined // Are we looking at a file in the working directory or a file in a commit? if (file instanceof WorkingDirectoryFileChange) { // No idea what to do about this, a conflicted binary (presumably) file. // Ideally we'd show all three versions and let the user pick but that's // a bit out of scope for now. if (file.status.kind === AppFileStatusKind.Conflicted) { return { kind: DiffType.Image } } // Does it even exist in the working directory? if (file.status.kind !== AppFileStatusKind.Deleted) { current = await getWorkingDirectoryImage(repository, file) } if ( file.status.kind !== AppFileStatusKind.New && file.status.kind !== AppFileStatusKind.Untracked ) { // If we have file.oldPath that means it's a rename so we'll // look for that file. previous = await getBlobImage( repository, getOldPathOrDefault(file), 'HEAD' ) } } else { // File status can't be conflicted for a file in a commit if (file.status.kind !== AppFileStatusKind.Deleted) { current = await getBlobImage(repository, file.path, commitish) } // File status can't be conflicted for a file in a commit if ( file.status.kind !== AppFileStatusKind.New && file.status.kind !== AppFileStatusKind.Untracked ) { // TODO: commitish^ won't work for the first commit // // If we have file.oldPath that means it's a rename so we'll // look for that file. previous = await getBlobImage( repository, getOldPathOrDefault(file), `${commitish}^` ) } } return { kind: DiffType.Image, previous: previous, current: current, } } export async function convertDiff( repository: Repository, file: FileChange, diff: IRawDiff, commitish: string, lineEndingsChange?: LineEndingsChange ): Promise<IDiff> { const extension = Path.extname(file.path).toLowerCase() if (diff.isBinary) { // some extension we don't know how to parse, never mind if (!imageFileExtensions.has(extension)) { return { kind: DiffType.Binary, } } else { return getImageDiff(repository, file, commitish) } } return { kind: DiffType.Text, text: diff.contents, hunks: diff.hunks, lineEndingsChange, maxLineNumber: diff.maxLineNumber, } } /** * Map a given file extension to the related data URL media type */ function getMediaType(extension: string) { if (extension === '.png') { return 'image/png' } if (extension === '.jpg' || extension === '.jpeg') { return 'image/jpg' } if (extension === '.gif') { return 'image/gif' } if (extension === '.ico') { return 'image/x-icon' } if (extension === '.webp') { return 'image/webp' } if (extension === '.bmp') { return 'image/bmp' } if (extension === '.avif') { return 'image/avif' } // fallback value as per the spec return 'text/plain' } /** * `git diff` will write out messages about the line ending changes it knows * about to `stderr` - this rule here will catch this and also the to/from * changes based on what the user has configured. */ const lineEndingsChangeRegex = /warning: (CRLF|CR|LF) will be replaced by (CRLF|CR|LF) in .*/ /** * Utility function for inspecting the stderr output for the line endings * warning that Git may report. * * @param error A buffer of binary text from a spawned process */ function parseLineEndingsWarning(error: Buffer): LineEndingsChange | undefined { if (error.length === 0) { return undefined } const errorText = error.toString('utf-8') const match = lineEndingsChangeRegex.exec(errorText) if (match) { const from = parseLineEndingText(match[1]) const to = parseLineEndingText(match[2]) if (from && to) { return { from, to } } } return undefined } /** * Utility function used by get(Commit|WorkingDirectory)Diff. * * Parses the output from a diff-like command that uses `--path-with-raw` */ function diffFromRawDiffOutput(output: Buffer): IRawDiff { // for now we just assume the diff is UTF-8, but given we have the raw buffer // we can try and convert this into other encodings in the future const result = output.toString('utf-8') const pieces = result.split('\0') const parser = new DiffParser() return parser.parse(pieces[pieces.length - 1]) } function buildDiff( buffer: Buffer, repository: Repository, file: FileChange, commitish: string, lineEndingsChange?: LineEndingsChange ): Promise<IDiff> { if (!isValidBuffer(buffer)) { // the buffer's diff is too large to be renderable in the UI return Promise.resolve<IUnrenderableDiff>({ kind: DiffType.Unrenderable }) } const diff = diffFromRawDiffOutput(buffer) if (isBufferTooLarge(buffer) || isDiffTooLarge(diff)) { // we don't want to render by default // but we keep it as an option by // passing in text and hunks const largeTextDiff: ILargeTextDiff = { kind: DiffType.LargeText, text: diff.contents, hunks: diff.hunks, lineEndingsChange, maxLineNumber: diff.maxLineNumber, } return Promise.resolve(largeTextDiff) } return convertDiff(repository, file, diff, commitish, lineEndingsChange) } /** * Retrieve the binary contents of a blob from the object database * * Returns an image object containing the base64 encoded string, * as <img> tags support the data URI scheme instead of * needing to reference a file:// URI * * https://en.wikipedia.org/wiki/Data_URI_scheme */ export async function getBlobImage( repository: Repository, path: string, commitish: string ): Promise<Image> { const extension = Path.extname(path) const contents = await getBlobContents(repository, commitish, path) return new Image( contents.toString('base64'), getMediaType(extension), contents.length ) } /** * Retrieve the binary contents of a blob from the working directory * * Returns an image object containing the base64 encoded string, * as <img> tags support the data URI scheme instead of * needing to reference a file:// URI * * https://en.wikipedia.org/wiki/Data_URI_scheme */ export async function getWorkingDirectoryImage( repository: Repository, file: FileChange ): Promise<Image> { const contents = await fileSystem.readFile( Path.join(repository.path, file.path) ) return new Image( contents.toString('base64'), getMediaType(Path.extname(file.path)), contents.length ) } /** * List the modified binary files' paths in the given repository * * @param repository to run git operation in * @param ref ref (sha, branch, etc) to compare the working index against * * if you're mid-merge pass `'MERGE_HEAD'` to ref to get a diff of `HEAD` vs `MERGE_HEAD`, * otherwise you should probably pass `'HEAD'` to get a diff of the working tree vs `HEAD` */ export async function getBinaryPaths( repository: Repository, ref: string ): Promise<ReadonlyArray<string>> { const { output } = await spawnAndComplete( ['diff', '--numstat', '-z', ref], repository.path, 'getBinaryPaths' ) const captures = getCaptures(output.toString('utf8'), binaryListRegex) if (captures.length === 0) { return [] } // flatten the list (only does one level deep) const flatCaptures = captures.reduce((acc, val) => acc.concat(val)) return flatCaptures } const binaryListRegex = /-\t-\t(?:\0.+\0)?([^\0]*)/gi
the_stack
* @fileoverview Serialized representation of the changes in a repository */ import isObject from "lodash/isObject"; import isString from "lodash/isString"; import cloneDeep from "lodash/cloneDeep"; import isEmpty from "lodash/isEmpty"; import extend from "lodash/extend"; import each from "lodash/each"; //@ts-ignore import { ConsoleUtils, joinPaths, constants } from "@fluid-experimental/property-common"; import { TypeIdHelper } from "./helpers/typeidHelper"; import { ChangeSetArrayFunctions } from './changeset_operations/array'; import { ArrayChangeSetIterator } from "./changeset_operations/arrayChangesetIterator"; import { ConflictType } from './changeset_operations/changesetConflictTypes' // Add the indexed collection functions into the prototype of the ChangeSet import { ChangeSetIndexedCollectionFunctions } from "./changeset_operations/indexedCollection"; import { isEmptyChangeSet } from "./changeset_operations/isEmptyChangeset"; import { isReservedKeyword } from "./isReservedKeyword"; import { Utils } from "./utils"; import { TemplateValidator } from "./templateValidator"; import { ArrayIteratorOperationTypes } from "./changeset_operations/operationTypes" const { PROPERTY_PATH_DELIMITER, MSG } = constants; const { extractContext, isPrimitiveType } = TypeIdHelper; export interface ApplyChangeSetOptions { /** * Additional meta information which help later to obtain more compact changeset during the apply operation. */ applyAfterMetaInformation?: Map<any, any>, /** * Throw error for template definition mismatches. */ throwOnTemplateMismatch?: boolean } export interface RebaseChangeSetOptions extends ApplyChangeSetOptions { rebaseMetaInformation?: object } /** * The plain serialization data structure used to encode a ChangeSet. */ export type SerializedChangeSet = any; //@TODO Maybe we should add full type for the ChangeSet export type ChangeSetType = any; export interface ConflictInfo { /** * Path to the position where the conflict occurred. If the conflicting change is of type * MISMATCH_TEMPLATES then the path will be undefined. */ path?: string | undefined; /** * Type of the conflict */ type: ConflictType; conflictingChange?: SerializedChangeSet; } /** * The ChangeSet represents an operation to be done (or that was done) on the data. It encapsulate one or * many addition/insertion and deletion of properties. The ChangeSetObject also provides functionality * to merge and swap change sets. */ export class ChangeSet { static ConflictType = ConflictType; static isEmptyChangeSet = isEmptyChangeSet; static isReservedKeyword = isReservedKeyword; declare public _cleanIndexedCollectionChangeSet: typeof ChangeSetIndexedCollectionFunctions._cleanIndexedCollectionChangeSet; declare public _performApplyAfterOnPropertyArray: typeof ChangeSetArrayFunctions._performApplyAfterOnPropertyArray; declare public _rebaseArrayChangeSetForProperty: typeof ChangeSetArrayFunctions._rebaseArrayChangeSetForProperty; declare public _rebaseChangeSetForString: typeof ChangeSetArrayFunctions._rebaseChangeSetForString; declare public _performApplyAfterOnPropertyIndexedCollection: typeof ChangeSetIndexedCollectionFunctions._performApplyAfterOnPropertyIndexedCollection; declare public _rebaseIndexedCollectionChangeSetForProperty: typeof ChangeSetIndexedCollectionFunctions._rebaseIndexedCollectionChangeSetForProperty; _changes: SerializedChangeSet; _isNormalized: boolean; /** * @param [in_changes] - The serialized changes to store in this change set if a string is supplied, * we assume it to be a serialized JSON representation of the change set. If none is supplied, an empty changeset will be created. */ constructor(in_changes?: ChangeSetType) { if (in_changes === undefined || in_changes === null) { this._changes = {}; } else if (isString(in_changes)) { // Stringified Serialized JSON this._changes = JSON.parse(in_changes); } else if (in_changes instanceof ChangeSet) { this._changes = cloneDeep(in_changes._changes); } else { // Serialized Changeset this._changes = in_changes; } this._isNormalized = false; } /** * Creates a string representation of the change set * @returns JSON encoding of the changes in this change set */ toString(): string { return JSON.stringify(this._changes); }; /** * Returns the serialized changes. * * @returns The serialized changeset */ getSerializedChangeSet(): SerializedChangeSet { return this._changes; }; /** * Indicates whether this is a normalized ChangeSet. If this is set to true, squashes will not remove empty entries * from the ChangeSet. * * @param in_isNormalized - is this a normalized ChangeSet? */ setIsNormalized(in_isNormalized: boolean) { this._isNormalized = in_isNormalized; }; /** * Indicates whether this is a normalized ChangeSet. If this is set to true, squashes will not remove empty entries * from the ChangeSet. * * @returns Is this a normalized ChangeSet? */ getIsNormalized(): boolean { return this._isNormalized; }; /** * Clones the ChangeSet * * @returns The cloned ChangeSet */ clone(): ChangeSet { return new ChangeSet(cloneDeep(this._changes)); }; /** * Updates this ChangeSet. The result will be the concatenation of the two ChangeSets. First the changes in this * ChangeSet are executed, then the changes in the supplied in_changeSet are applied. The result will be * stored in this ChangeSet. This function assumes that the second ChangeSet is relative to the state after * application of the first ChangeSet. * * @param in_changeSet - The changeset to apply * @param in_options - Optional additional parameters */ applyChangeSet(in_changeSet: SerializedChangeSet, in_options?: ApplyChangeSetOptions) { let changes = in_changeSet; if (in_changeSet instanceof ChangeSet) { changes = in_changeSet.getSerializedChangeSet(); } if (!isObject(this._changes) || Array.isArray(this._changes)) { const oldValue = isObject(changes) && (changes as SerializedChangeSet).value !== undefined ? (changes as SerializedChangeSet).value : changes; this._changes = Array.isArray(oldValue) ? oldValue.slice() : oldValue; } else { this._performApplyAfterOnProperty(this._changes, changes, !this._isNormalized, in_options); } }; /** * Applies a changeset to a given property (recursively). The ChangeSet is assumed to be relative to the same * property root and it will be applied behind the base ChangeSet (assuming that the changes are relative to the * state after the base ChangeSet has been applied. It will change the base ChangeSet.) * * @param io_basePropertyChanges - The ChangeSet describing the initial state * @param in_appliedPropertyChanges - The ChangeSet to apply to this state * @param in_removeEmpty - Should empty ChangeSets be removed? * @param in_options - Optional additional parameters */ private _performApplyAfterOnProperty( io_basePropertyChanges: SerializedChangeSet, in_appliedPropertyChanges: SerializedChangeSet, in_removeEmpty: boolean, in_options?: ApplyChangeSetOptions) { // Apply dynamic property operations if (in_appliedPropertyChanges.insert || in_appliedPropertyChanges.modify || in_appliedPropertyChanges.remove) { this._performApplyAfterOnPropertyIndexedCollection(io_basePropertyChanges, in_appliedPropertyChanges, "NodeProperty", in_options); // TODO: recursively propagate the typeid? } if (!isEmpty(in_appliedPropertyChanges.insertTemplates)) { io_basePropertyChanges.insertTemplates = io_basePropertyChanges.insertTemplates || {}; extend(io_basePropertyChanges.insertTemplates, in_appliedPropertyChanges.insertTemplates); } // Apply ChangeSet to the properties const modifiedTypeids = Object.keys(in_appliedPropertyChanges); for (let i = 0; i < modifiedTypeids.length; i++) { const typeid = modifiedTypeids[i]; // The reserved keywords have already been handled above if (ChangeSet.isReservedKeyword(typeid)) { continue; } io_basePropertyChanges[typeid] = io_basePropertyChanges[typeid] || {}; const baseChanges = io_basePropertyChanges[typeid]; const changedKeys = Object.keys(in_appliedPropertyChanges[typeid]); for (let j = 0; j < changedKeys.length; j++) { this.performApplyAfterOnPropertyWithTypeid(changedKeys[j], baseChanges, in_appliedPropertyChanges[typeid], typeid, in_removeEmpty, in_options); } // Remove the type when it no longer contains any changed keys if (in_removeEmpty && isEmpty(io_basePropertyChanges[typeid])) { delete io_basePropertyChanges[typeid]; } } }; /** * Helper function used to apply a new value to a given ChangeSet. * It is used to handle setting a primitive value, which might either be represented * via a literal or an object with a member value. * applies in_appliedValue to the io_baseChanges at the given in_baseKey * @param io_baseChanges - base changes (modified) * @param in_baseKey - key * @param in_appliedValue - applied changes to be applied */ private _applyValue(io_baseChanges: SerializedChangeSet, in_baseKey: string, in_appliedValue: SerializedChangeSet) { const newValue = (in_appliedValue && in_appliedValue.hasOwnProperty("value")) ? in_appliedValue.value : in_appliedValue; if (io_baseChanges[in_baseKey] && io_baseChanges[in_baseKey].hasOwnProperty("value")) { io_baseChanges[in_baseKey].value = newValue; } else { if (io_baseChanges[in_baseKey] === undefined && in_appliedValue && in_appliedValue.hasOwnProperty("oldValue")) { io_baseChanges[in_baseKey] = { value: newValue, oldValue: in_appliedValue.oldValue, }; } else { io_baseChanges[in_baseKey] = newValue; } } }; /** * Decides based on the given Typeid which applyAfter operation to perform. * Note: This function is not directly called on the ChangeSet but on the object containing it together with a key * since it needs to be able to overwrite this entry * * @param in_changedKey - The key of the entry in the object * @param in_baseChanges - The object containing the state before the applyAfter * @param in_appliedPropertyChanges - The object containing the ChangeSet with the modification * @param in_typeid - The typeid of the property to modify * @param in_removeEmpty - Should empty ChangeSets be removed? * @param in_options - Optional additional parameters */ public performApplyAfterOnPropertyWithTypeid( in_changedKey: string, in_baseChanges: SerializedChangeSet, in_appliedPropertyChanges: { [x: string]: any; }, in_typeid: string, in_removeEmpty: boolean, in_options?: ApplyChangeSetOptions) { const splitTypeid = extractContext(in_typeid); if (splitTypeid.context === "set" || splitTypeid.context === "map") { in_baseChanges[in_changedKey] = in_baseChanges[in_changedKey] || {}; this._performApplyAfterOnPropertyIndexedCollection(in_baseChanges[in_changedKey], in_appliedPropertyChanges[in_changedKey], splitTypeid.typeid, in_options); // Remove the key, when it no longer contains a changeset if (in_removeEmpty && isEmpty(in_baseChanges[in_changedKey])) { delete in_baseChanges[in_changedKey]; } } else if (splitTypeid.context === "array" || splitTypeid.typeid === "String") { in_baseChanges[in_changedKey] = in_baseChanges[in_changedKey] !== undefined ? in_baseChanges[in_changedKey] : {}; let baseIsSetChange = false; let oldValue; if (splitTypeid.typeid === "String" && (isString(in_baseChanges[in_changedKey]) || (in_baseChanges[in_changedKey] && in_baseChanges[in_changedKey].hasOwnProperty("value")))) { oldValue = in_baseChanges[in_changedKey].oldValue; // we need to convert the format to allow the application of the changes // since _performApplyAfterOnPropertyArray only understands insert/modify/remove commands if (in_baseChanges[in_changedKey] && in_baseChanges[in_changedKey].hasOwnProperty("value")) { in_baseChanges[in_changedKey] = { insert: [ [0, in_baseChanges[in_changedKey].value], ], }; } else { in_baseChanges[in_changedKey] = { insert: [ [0, in_baseChanges[in_changedKey]], ], }; } baseIsSetChange = true; } let appliedChanges = in_appliedPropertyChanges[in_changedKey]; if (isObject(appliedChanges) && appliedChanges.hasOwnProperty("value")) { appliedChanges = (appliedChanges as SerializedChangeSet).value; } if (splitTypeid.typeid === "String" && isString(appliedChanges)) { // we've got a 'set' command and just overwrite the changes if (baseIsSetChange && oldValue !== undefined) { in_baseChanges[in_changedKey] = { value: appliedChanges, oldValue, }; } else { in_baseChanges[in_changedKey] = appliedChanges; } } else { // we have incremental changes (or a standard array) this._performApplyAfterOnPropertyArray(in_baseChanges[in_changedKey], in_appliedPropertyChanges[in_changedKey], splitTypeid.typeid, in_options); if (baseIsSetChange) { // we have to convert back to a string, if it had been converted before let newValue; if (isEmpty(in_baseChanges[in_changedKey])) { newValue = ""; } else { newValue = in_baseChanges[in_changedKey].insert[0][1]; } if (oldValue !== undefined) { in_baseChanges[in_changedKey] = { value: newValue, oldValue, }; } else { in_baseChanges[in_changedKey] = newValue; } } } // Remove the key, when it no longer contains a changeset if (in_removeEmpty && ChangeSet.isEmptyChangeSet(in_baseChanges[in_changedKey])) { delete in_baseChanges[in_changedKey]; } } else if (splitTypeid.isEnum) { // Enum types can simply be overwritten this._applyValue(in_baseChanges, in_changedKey, in_appliedPropertyChanges[in_changedKey]); } else if (splitTypeid.context === "single") { if (isPrimitiveType(splitTypeid.typeid)) { // Primitive types can simply be overwritten, however we have an exception for // 64 bit integers (until javascript natively supports them) if (splitTypeid.typeid === "Int64" || splitTypeid.typeid === "Uint64") { let appliedVal = in_appliedPropertyChanges[in_changedKey]; if (appliedVal && appliedVal.hasOwnProperty("value")) { appliedVal = appliedVal.value; } this._applyValue(in_baseChanges, in_changedKey, appliedVal.slice()); } else { this._applyValue(in_baseChanges, in_changedKey, in_appliedPropertyChanges[in_changedKey]); } } else { if (in_baseChanges[in_changedKey]) { // Otherwise we have to continue the merging recursively this._performApplyAfterOnProperty(in_baseChanges[in_changedKey], in_appliedPropertyChanges[in_changedKey], false, in_options); } else { // If the key doesn't exist, yet, we can just copy it in_baseChanges[in_changedKey] = cloneDeep(in_appliedPropertyChanges[in_changedKey]); } } } else { throw new Error(MSG.UNKNOWN_CONTEXT + splitTypeid.context); } }; /** * Rebases a given ChangeSet behind the current ChangeSet. * * This function takes a ChangeSet which is assumed to be relative to the same base state as the ChangeSet stored in * this class and transforms it in such a way that it can be applied after this ChangeSet. The function will modify * the supplied ChangeSet * * @param io_changeSet - * The ChangeSet that is rebased behind the state obtained by application of this ChangeSet * @param out_conflicts A list of paths that resulted in conflicts together with the type of the conflict * @param in_options - Optional additional parameters * @returns The rebased ChangeSet (the same object as io_changeSet, it will be * modified in place) */ public _rebaseChangeSet(io_changeSet: SerializedChangeSet, out_conflicts: ConflictInfo[], in_options?: RebaseChangeSetOptions): SerializedChangeSet { // We actually only pass this request to the recursive internal function return this._rebaseChangeSetForProperty(this._changes, io_changeSet, "", out_conflicts, in_options); }; /** * Internal helper function that performs a rebase on a single property * * @param in_ownPropertyChangeSet - * The ChangeSet for the property stored in this class * @param io_rebasePropertyChangeSet - * The ChangeSet for the property to be rebased * @param in_basePath - * Base path to get to the property processed by this function * @param out_conflicts - * A list of paths that resulted in conflicts together with the type of the conflict * @param in_options - Optional additional parameters * @returns The rebased ChangeSet for this property */ private _rebaseChangeSetForProperty( in_ownPropertyChangeSet: SerializedChangeSet, io_rebasePropertyChangeSet: SerializedChangeSet, in_basePath: string, out_conflicts: ConflictInfo[], in_options: ApplyChangeSetOptions): SerializedChangeSet { // Process the children in this ChangeSet if ((in_ownPropertyChangeSet.insert || in_ownPropertyChangeSet.modify || in_ownPropertyChangeSet.remove) && (io_rebasePropertyChangeSet.insert || io_rebasePropertyChangeSet.modify || io_rebasePropertyChangeSet.remove)) { this._rebaseIndexedCollectionChangeSetForProperty(in_ownPropertyChangeSet, io_rebasePropertyChangeSet, in_basePath, "NodeProperty", // TODO: recursively propagate the typeid? false, // don't use square brackets (use dots instead) out_conflicts, in_options); } if (!isEmpty(io_rebasePropertyChangeSet.insertTemplates)) { const typeids = Object.keys(io_rebasePropertyChangeSet.insertTemplates); const templateMismatchChangeSet = { insertTemplates: {} }; const templateMismatchConflict = { type: ChangeSet.ConflictType.MISMATCH_TEMPLATES, conflictingChange: templateMismatchChangeSet, }; each(typeids, function(typeid) { const template = io_rebasePropertyChangeSet.insertTemplates[typeid]; if (in_ownPropertyChangeSet.insertTemplates && in_ownPropertyChangeSet.insertTemplates[typeid]) { const isEqual = TemplateValidator.Utils.psetDeepEquals( template, in_ownPropertyChangeSet.insertTemplates[template.typeid], ); if (!isEqual) { if (in_options && in_options.throwOnTemplateMismatch) { throw new Error(MSG.TEMPLATE_MISMATCH + typeid); } templateMismatchChangeSet.insertTemplates[typeid] = in_ownPropertyChangeSet.insertTemplates[template.typeid]; // TODO: Remove this warning message once we offer a conflict resolution API console.warn(MSG.TEMPLATE_MISMATCH + typeid); } delete io_rebasePropertyChangeSet.insertTemplates[typeid]; } }); // Remove insertTemplates key if it is empty if (isEmpty(io_rebasePropertyChangeSet.insertTemplates)) { delete io_rebasePropertyChangeSet.insertTemplates; } if (!isEmpty(templateMismatchConflict.conflictingChange.insertTemplates)) { out_conflicts.push(templateMismatchConflict); } } // Check for collisions in the property assignments const changedTypeids = Object.keys(in_ownPropertyChangeSet); // We currently do not yet have any const changeSet = {}; for (let i = 0; i < changedTypeids.length; i++) { const typeid = changedTypeids[i]; const paths = Object.keys(in_ownPropertyChangeSet[typeid]); // Update the oldValue of primitive property of a changeset // for simple changeset with 'modify', property type, name, value // find the oldValue of the property and update it if (typeid === "modify" && "modify" in io_rebasePropertyChangeSet) { for (let j = 0; j < paths.length; j++) { const tempTypeid = paths[i]; if ((isPrimitiveType(tempTypeid)) && tempTypeid in io_rebasePropertyChangeSet.modify) { const tempPaths = Object.keys(in_ownPropertyChangeSet.modify[tempTypeid]); for (let z = 0; z < tempPaths.length; z++) { if (tempPaths[z] in io_rebasePropertyChangeSet.modify[tempTypeid]) { let rebasedPropContent = io_rebasePropertyChangeSet.modify[tempTypeid][tempPaths[z]]; if (isObject(rebasedPropContent) && "oldValue" in rebasedPropContent) { (rebasedPropContent as SerializedChangeSet).oldValue = in_ownPropertyChangeSet.modify[tempTypeid][tempPaths[z]].value; } } } } } } else if (isPrimitiveType(typeid)) { // for complex changeset, the function will be called recursively, when the function is at the level where // io_rebasePropertyChangeSet && in_ownPropertyChangeSet contain only property type, name and value, we update // oldValue of io_rebasePropertyChangeSet. for (let j = 0; j < paths.length; j++) { if (typeid in io_rebasePropertyChangeSet && paths[j] in io_rebasePropertyChangeSet[typeid]) { let rebasedPropContent = io_rebasePropertyChangeSet[typeid][paths[j]]; if (isObject(rebasedPropContent) && "oldValue" in rebasedPropContent) { // if oldValue already be update above, we don't need to update if (io_rebasePropertyChangeSet[typeid][paths[j]].oldValue !== in_ownPropertyChangeSet[typeid][paths[j]].value) { io_rebasePropertyChangeSet[typeid][paths[j]].oldValue = in_ownPropertyChangeSet[typeid][paths[j]].value; } } } } } // The reserved keywords have already been handled above and changes which are not present in // the other ChangeSet can be ignored if (ChangeSet.isReservedKeyword(typeid) || !io_rebasePropertyChangeSet[typeid]) { continue; } // Check, whether we have a collision in a path update for (let j = 0; j < paths.length; j++) { if (io_rebasePropertyChangeSet[typeid][paths[j]] !== undefined) { in_ownPropertyChangeSet[typeid] = in_ownPropertyChangeSet[typeid] || {}; const newPath = joinPaths(in_basePath, paths[j], PROPERTY_PATH_DELIMITER); // Perform the rebase operation on the ChangeSet for this entry const setConflict = this.rebaseChangeSetForPropertyEntryWithTypeid(paths[j], in_ownPropertyChangeSet[typeid], io_rebasePropertyChangeSet[typeid], typeid, newPath, true, out_conflicts, in_options); // If there has been a non-recursive set collision we handle it here separately if (setConflict) { // If we have two writes to primitive types, this is a conflict changeSet[typeid] = changeSet[typeid] || {}; // Store the change. Note: We make a deep copy here, as this is a reference into our // own internal ChangeSet and we want to be sure, nobody changes our internal data-structures changeSet[typeid][paths[j]] = cloneDeep(in_ownPropertyChangeSet[typeid][paths[j]]); } // Remove the typeid, when it no longer contains any keys if (isEmpty(io_rebasePropertyChangeSet[typeid])) { delete io_rebasePropertyChangeSet[typeid]; } } } } // If there were conflicts in the set operations, report them if (!isEmpty(changeSet)) { const conflict = { path: in_basePath, type: ChangeSet.ConflictType.COLLIDING_SET, conflictingChange: changeSet, }; out_conflicts.push(conflict); } return io_rebasePropertyChangeSet; }; /** * Decides based on the given Typeid which rebase operation to perform * Note: This function is not directly called on the ChangeSet but on the object containing it together with a key * since it needs to be able to overwrite this entry * * @param in_key - The key of the entry in the object * @param in_ownPropertyChangeSet - The object containing the ChangeSet for the property * stored in this class * @param io_rebasePropertyChangeSet - The object containing the ChangeSet for the property to * be rebased * @param in_typeid - The typeid of the property to rebase * @param in_basePath - Base path to get to the property processed by this function * @param in_removeEmpty - Should empty ChangeSets be removed? * @param out_conflicts - A list of paths that resulted in * conflicts together with the type of the conflict * * @returns Has there been a simple set collision? Those have to be handled separately * TODO: We should unify the handling of set collisions * @private */ private rebaseChangeSetForPropertyEntryWithTypeid( in_key: string, in_ownPropertyChangeSet: SerializedChangeSet, io_rebasePropertyChangeSet: SerializedChangeSet, in_typeid: string, in_basePath: string, in_removeEmpty: boolean, out_conflicts: any, in_options: ApplyChangeSetOptions): boolean { const splitTypeid = extractContext(in_typeid); if (splitTypeid.context === "set" || splitTypeid.context === "map") { this._rebaseIndexedCollectionChangeSetForProperty(in_ownPropertyChangeSet[in_key], io_rebasePropertyChangeSet[in_key], in_basePath, splitTypeid.typeid, true, // use square brackets out_conflicts, in_options); // Remove the key, when it no longer contains a changeset if (in_removeEmpty && isEmpty(io_rebasePropertyChangeSet[in_key])) { delete io_rebasePropertyChangeSet[in_key]; } } else if (splitTypeid.context === "array") { this._rebaseArrayChangeSetForProperty(in_ownPropertyChangeSet[in_key], io_rebasePropertyChangeSet[in_key], in_basePath, out_conflicts, splitTypeid.typeid, in_options); // Remove the key, when it no longer contains a changeset if (in_removeEmpty && isEmpty(io_rebasePropertyChangeSet[in_key])) { delete io_rebasePropertyChangeSet[in_key]; } } else if (splitTypeid.typeid === "String") { this._rebaseChangeSetForString(in_ownPropertyChangeSet[in_key], io_rebasePropertyChangeSet, in_key, in_basePath, out_conflicts, in_options); // Remove the key, when it no longer contains a changeset if (in_removeEmpty && isEmpty(io_rebasePropertyChangeSet[in_key])) { delete io_rebasePropertyChangeSet[in_key]; } } else if (splitTypeid.context === "single") { // We only can have a conflict when the path exists in both ChangeSets if (in_ownPropertyChangeSet[in_key] !== undefined) { if (isPrimitiveType(splitTypeid.typeid) || splitTypeid.isEnum) { return true; } else { // Otherwise, we have to continue recursively // Make sure the paths exist in_ownPropertyChangeSet[in_key] = in_ownPropertyChangeSet[in_key] || {}; // And then perform the recursive rebase this._rebaseChangeSetForProperty(in_ownPropertyChangeSet[in_key], io_rebasePropertyChangeSet[in_key], in_basePath, out_conflicts, in_options); } } } else { throw new Error(MSG.UNKNOWN_CONTEXT + splitTypeid.context); } return false; }; /** * recursive helper function for ChangeSet.prototype._toReversibleChangeSet * which converts a irreversible changeset to a reversible changeset * or updates the former state of a reversible changeset * @param in_context the traversal context */ // eslint-disable-next-line complexity private _recursivelyBuildReversibleChangeSet(in_context: Utils.TraversalContext) { const opType = in_context.getOperationType(); if (opType === "modify") { const type = in_context.getTypeid(); const splitType = in_context.getSplitTypeID(); let nestedChangeset = in_context.getNestedChangeSet(); let current = in_context.getUserData().parallelState; if (in_context.getPropertyContainerType() === "root") { current = in_context.getUserData().oldState; } else if (current) { if (in_context.getPropertyContainerType() !== "template") { current = current.insert; } if (in_context.getPropertyContainerType() !== "array") { current = current && current[in_context.getTypeid()]; current = current && current[in_context.getLastSegment()]; } else { current = current && current[0][1][in_context.getLastSegment()]; } } in_context.setUserData({ parallelState: current, oldState: in_context.getUserData().oldState, }); if (isPrimitiveType(type)) { if (current === undefined) { throw new Error(`${MSG.INVALID_PATH + in_context.getFullPath()}. Making primitive value reversible.`); } let oldValue = current; // store it in reversibleChangeSet if (type === "String" && !isString(nestedChangeset)) { // String is a special case let oldString; if (isString(oldValue)) { oldString = oldValue; } if (nestedChangeset.modify) { for (let i = 0; i < nestedChangeset.modify.length; i++) { let entry = nestedChangeset.modify[i]; let entryOffset = entry[0]; const entryLength = entry[1].length; entry[2] = oldString.slice(entryOffset, entryOffset + entryLength); } } if (nestedChangeset.remove) { for (let i = 0; i < nestedChangeset.remove.length; i++) { let entry = nestedChangeset.remove[i]; let entryOffset = entry[0]; let removeRangeLength = entry[1]; if (isString(removeRangeLength)) { removeRangeLength = entry[1].length; } entry[1] = oldString.slice(entryOffset, entryOffset + removeRangeLength); } } } else { if (nestedChangeset && nestedChangeset.hasOwnProperty("value")) { nestedChangeset.oldValue = oldValue; } else { const newChangeSet = { value: nestedChangeset, oldValue, }; in_context.replaceNestedChangeSet(newChangeSet); } } } else if (splitType.context === "array") { if (current === undefined) { throw new Error(`${MSG.INVALID_PATH + in_context.getFullPath()}. Making array value reversible.`); } let oldValue = current.insert ? current.insert[0][1] : []; let nestedChangeset = in_context.getNestedChangeSet(); if (nestedChangeset.modify) { if (isPrimitiveType(splitType.typeid)) { for (let i = 0; i < nestedChangeset.modify.length; i++) { let entry = nestedChangeset.modify[i]; let entryOffset = entry[0]; let oldEntries = []; for (let j = 0; j < entry[1].length; j++) { oldEntries.push(cloneDeep(oldValue[entryOffset + j])); } entry[2] = oldEntries; } } } if (nestedChangeset.remove) { for (let i = 0; i < nestedChangeset.remove.length; i++) { let entry = nestedChangeset.remove[i]; let entryOffset = entry[0]; let oldEntries = []; let removeRangeLength = entry[1]; if (Array.isArray(removeRangeLength)) { removeRangeLength = entry[1].length; } for (let j = 0; j < removeRangeLength; j++) { oldEntries.push(cloneDeep(oldValue[entryOffset + j])); } entry[1] = oldEntries; } } } else if (splitType.context === "map" || // node property test: (we have to do the test this way, because of inheritance) (nestedChangeset.insert || nestedChangeset.modify || nestedChangeset.remove)) { // This prevents an error, if the changeset only contains an insert operation. In that case // we don't actually need the corresponding old state and thus do not need to throw an error // This type of situation can occur in the materialized history, if an insert happens right at a chunk boundary. if (Object.keys(nestedChangeset).length === 1 && nestedChangeset.insert) { in_context._traversalStopped = true; return; } if (current === undefined) { throw new Error(`${MSG.INVALID_PATH + in_context.getFullPath()}. Making map value reversible.`); } let oldValue = current.insert; if (isPrimitiveType(splitType.typeid)) { if (nestedChangeset.modify) { const modifiedKeys = Object.keys(nestedChangeset.modify); for (let i = 0; i < modifiedKeys.length; i++) { let entry = nestedChangeset.modify[modifiedKeys[i]]; if (typeof entry === "object" && entry.hasOwnProperty("value")) { entry = entry.value; } nestedChangeset.modify[modifiedKeys[i]] = { value: entry, oldValue: cloneDeep(oldValue[modifiedKeys[i]]), }; } } let newRemove = {}; if (nestedChangeset.remove) { let removedKeys = nestedChangeset.remove; if (!Array.isArray(removedKeys)) { removedKeys = Object.keys(removedKeys); } for (let i = 0; i < removedKeys.length; i++) { newRemove[removedKeys[i]] = cloneDeep(oldValue[removedKeys[i]]); } nestedChangeset.remove = newRemove; } } else { let nestedChangeset = in_context.getNestedChangeSet(); if (nestedChangeset.modify) { // this case is handeled recursively } let newRemove = {}; if (nestedChangeset.remove) { if (Array.isArray(nestedChangeset.remove)) { let removedKeys = nestedChangeset.remove; for (let i = 0; i < removedKeys.length; i++) { let searchedKey = removedKeys[i]; // search for this key in the old keys: const oldTypeKeys = Object.keys(oldValue); for (let k = 0; k < oldTypeKeys.length; k++) { if (oldValue[oldTypeKeys[k]].hasOwnProperty(searchedKey)) { let entry = oldValue[oldTypeKeys[k]][searchedKey]; if (!newRemove[oldTypeKeys[k]]) { newRemove[oldTypeKeys[k]] = {}; } newRemove[oldTypeKeys[k]][removedKeys[i]] = cloneDeep(entry); } } } nestedChangeset.remove = newRemove; } else { // we already have a reversibleChangeSet and need to update the oldValues const removedTypes = Object.keys(nestedChangeset.remove); for (let t = 0; t < removedTypes.length; t++) { let removedKeys = Object.keys(nestedChangeset.remove[removedTypes[t]]); for (let i = 0; i < removedKeys.length; i++) { let searchedKey = removedKeys[i]; let entry = oldValue[removedTypes[t]][searchedKey]; nestedChangeset.remove[removedTypes[t]][removedKeys[i]] = entry; } } } } } } } }; /** * Converts an irreversible changeset to a reversible changeset * or updates the former state of a reversible changeset * WARNING: This function is still experimental and needs more testing * and it's set to private for now. It will be converted to a public API function * in a later release. * @param in_oldSerializedState the old state */ public _toReversibleChangeSet(in_oldSerializedState: SerializedChangeSet) { ConsoleUtils.assert(in_oldSerializedState !== undefined, `${MSG.ASSERTION_FAILED}Missing function parameter "in_oldSerializedState" of "_toReversibleChangeSet".`); if (!isObject(in_oldSerializedState) || Array.isArray(in_oldSerializedState)) { if (!isObject(this._changes) || Array.isArray(this._changes)) { this._changes = { oldValue: Array.isArray(in_oldSerializedState) ? in_oldSerializedState.slice() : in_oldSerializedState, value: this._changes, }; } else { (this._changes as SerializedChangeSet).oldValue = Array.isArray(in_oldSerializedState) ? in_oldSerializedState.slice() : in_oldSerializedState; } } else { const workspace = { oldState: in_oldSerializedState }; Utils.traverseChangeSetRecursively(this._changes, { preCallback: this._recursivelyBuildReversibleChangeSet, userData: workspace, }); } }; /** * Converts a reversible changeset to an irreversible changeset * WARNING: This function is still experimental and needs more testing * and it's set to private for now. It will be converted to a public API function * in a later release. * @param in_withoutRoot - Bypass a fix where the root of a changeset is cleaned */ public _stripReversibleChangeSet(in_withoutRoot: boolean) { // eslint-disable-next-line complexity const callback = function(in_context) { const opType = in_context.getOperationType(); if (opType === "remove" || opType === "modify") { const type = in_context.getTypeid(); if (!type) { return; } const splitType = in_context.getSplitTypeID(); if (isPrimitiveType(type)) { // remove old state let nestedChangeset = in_context.getNestedChangeSet(); if (type === "String" && !isString(nestedChangeset)) { // String is a special case if (nestedChangeset.modify) { for (let i = 0; i < nestedChangeset.modify.length; i++) { let entry = nestedChangeset.modify[i]; entry.splice(2, 1); } } if (nestedChangeset.remove) { for (let i = 0; i < nestedChangeset.remove.length; i++) { let entry = nestedChangeset.remove[i]; let removeRangeLength = entry[1]; if (isString(removeRangeLength)) { removeRangeLength = entry[1].length; } entry[1] = removeRangeLength; } } if (nestedChangeset && nestedChangeset.hasOwnProperty("value")) { in_context.replaceNestedChangeSet(nestedChangeset.value); } } else if (nestedChangeset && nestedChangeset.hasOwnProperty("value")) { in_context.replaceNestedChangeSet(nestedChangeset.value); } } else if (splitType.context === "array") { let nestedChangeset = in_context.getNestedChangeSet(); if (nestedChangeset.modify) { for (let i = 0; i < nestedChangeset.modify.length; i++) { let entry = nestedChangeset.modify[i]; entry.splice(2, 1); } } if (nestedChangeset.remove) { for (let i = 0; i < nestedChangeset.remove.length; i++) { let entry = nestedChangeset.remove[i]; let removeRangeLength = entry[1]; if (Array.isArray(removeRangeLength)) { removeRangeLength = entry[1].length; } entry[1] = removeRangeLength; } } // TODO: Remove in_withoutRoot when it will not be used anymore } else if (splitType.context === "map" || (!in_withoutRoot && splitType.context === "single")) { // For NodeProperty / inserts at the root let nestedChangeset = in_context.getNestedChangeSet(); if (isPrimitiveType(splitType.typeid)) { if (nestedChangeset.modify) { const modifiedKeys = Object.keys(nestedChangeset.modify); for (let i = 0; i < modifiedKeys.length; i++) { let entry = nestedChangeset.modify[modifiedKeys[i]]; if (typeof entry === "object" && entry.hasOwnProperty("value")) { entry = entry.value; } nestedChangeset.modify[modifiedKeys[i]] = entry; } } if (nestedChangeset.remove) { let removedKeys = nestedChangeset.remove; if (!Array.isArray(removedKeys)) { removedKeys = Object.keys(removedKeys); nestedChangeset.remove = removedKeys; } } } else { let nestedChangeset = in_context.getNestedChangeSet(); if (nestedChangeset.modify) { // this case is handeled recursively } if (nestedChangeset.remove) { if (!Array.isArray(nestedChangeset.remove)) { // we have a reversibleChangeSet and need to convert let newRemove = []; const removedTypes = Object.keys(nestedChangeset.remove); for (let t = 0; t < removedTypes.length; t++) { let removedKeys = Object.keys(nestedChangeset.remove[removedTypes[t]]); for (let i = 0; i < removedKeys.length; i++) { newRemove.push(removedKeys[i]); } } nestedChangeset.remove = newRemove; } } } } } }; if (isObject(this._changes) && (this._changes as SerializedChangeSet).oldValue !== undefined && (this._changes as SerializedChangeSet).value !== undefined) { this._changes = (this._changes as SerializedChangeSet).value; return; } Utils.traverseChangeSetRecursively(this._changes, { preCallback: callback, }); }; /** * Helper function to extract the first level paths from a given change set * @param in_changeSet The ChangeSet to extract paths from * @param isPrimitiveCollection Is this a primitive type collection? * * @returns List of paths found at the first level of the change set */ private _extractFirstLevelPaths(in_changeSet: SerializedChangeSet, isPrimitiveCollection: boolean): string[] { let paths; if (isPrimitiveCollection) { paths = Object.keys(in_changeSet); } else { paths = []; each(in_changeSet, function(nestedChangeSet) { each(nestedChangeSet, function(nestedChangeSet2, path) { paths.push(path); }); }); } return paths; }; /** * recursive helper function for ChangeSet.prototype._toInverseChangeSet * @param in_context the traversal context */ private _recursivelyInvertReversibleChangeset(in_context: Utils.TraversalContext) { in_context.setUserData(in_context.getUserData() || {}); // Figure out if we have already visited this path by verifying that the full path // is contained within the list of processed deleted or inserted paths const isWithinInsertOrDelete = in_context.getUserData()[in_context.getFullPath()]; if (isWithinInsertOrDelete && in_context.getOperationType() !== "modify") { // We are within an insert or remove sub tree. Skip this iteration. in_context._traversalStopped = true; return; } if (in_context.getOperationType() === "remove" || in_context.getOperationType() === "modify") { const type = in_context.getTypeid(); const splitType = in_context.getSplitTypeID(); if (!splitType) { ConsoleUtils.assert(false, `${MSG.ASSERTION_FAILED}Missing "splitType" in "in_context":${JSON.stringify(in_context)}`); } const nestedChangeset = in_context.getNestedChangeSet(); if ((isPrimitiveType(type) && type !== "String") || (type === "String" && isString(nestedChangeset.oldValue))) { // check if we were called with an irreversible changeset if (in_context.getOperationType() === "modify" && (!isObject(nestedChangeset) || typeof (nestedChangeset as SerializedChangeSet).oldValue === "undefined")) { throw new Error(MSG.OLD_VALUE_NOT_FOUND); } // switch oldValue and value let tmp = nestedChangeset.oldValue; nestedChangeset.oldValue = nestedChangeset.value; nestedChangeset.value = tmp; } else if ((type === "String" && !isString(nestedChangeset.oldValue)) || splitType.context === "array") { // String and Arrays need special treatment: const arrayIterator = new ArrayChangeSetIterator(nestedChangeset); const resultChangeset: SerializedChangeSet = {}; if (nestedChangeset.modify) { resultChangeset.modify = []; } if (nestedChangeset.insert) { resultChangeset.remove = []; } if (nestedChangeset.remove) { resultChangeset.insert = []; } // Successively invert the changes from the changeSet while (!arrayIterator.atEnd()) { switch (arrayIterator.opDescription.type) { case ArrayIteratorOperationTypes.INSERT: // Handle inserts resultChangeset.remove.push([ arrayIterator.opDescription.operation[0] + arrayIterator.opDescription.offset, arrayIterator.opDescription.operation[1], ]); break; case ArrayIteratorOperationTypes.REMOVE: // Handle removes resultChangeset.insert.push([ arrayIterator.opDescription.operation[0] + arrayIterator.opDescription.offset, arrayIterator.opDescription.operation[1], ]); break; case ArrayIteratorOperationTypes.MODIFY: // Handle modifies if (isPrimitiveType(splitType.typeid)) { resultChangeset.modify.push([ arrayIterator.opDescription.operation[0] + arrayIterator.opDescription.offset, arrayIterator.opDescription.operation[2], arrayIterator.opDescription.operation[1], ]); } else { resultChangeset.modify.push([ arrayIterator.opDescription.operation[0] + arrayIterator.opDescription.offset, arrayIterator.opDescription.operation[1], ]); } break; default: console.error(`applyChangeset: ${MSG.UNKNOWN_OPERATION}${arrayIterator.opDescription.type}`); } arrayIterator.next(); } in_context.replaceNestedChangeSet(resultChangeset); } else { // Covers NodeProperty, Map and Set if (nestedChangeset.modify) { if (isPrimitiveType(splitType.typeid) && splitType.context === "map") { const modifiedKeys = Object.keys(nestedChangeset.modify); for (let i = 0; i < modifiedKeys.length; i++) { const entry = nestedChangeset.modify[modifiedKeys[i]]; let tmp = entry.value; entry.value = entry.oldValue; entry.oldValue = tmp; } } } const oldInsert = nestedChangeset.insert; let replacedInsert = false; if (nestedChangeset.remove) { nestedChangeset.insert = nestedChangeset.remove; replacedInsert = true; nestedChangeset.remove = undefined; delete nestedChangeset.remove; const isPrimitiveTypeid = isPrimitiveType(in_context.getSplitTypeID().typeid); each(this._extractFirstLevelPaths(nestedChangeset.insert, isPrimitiveTypeid), function(path) { const fullPath = joinPaths(in_context.getFullPath(), path, PROPERTY_PATH_DELIMITER); in_context.getUserData()[fullPath] = true; }); } if (oldInsert) { if (replacedInsert) { nestedChangeset.remove = cloneDeep(oldInsert); } else { nestedChangeset.remove = oldInsert; nestedChangeset.insert = undefined; delete nestedChangeset.insert; } const isPrimitiveTypeid = isPrimitiveType(in_context.getSplitTypeID().typeid); each(this._extractFirstLevelPaths(nestedChangeset.remove, isPrimitiveTypeid), function(path) { const fullPath = joinPaths(in_context.getFullPath(), path, PROPERTY_PATH_DELIMITER); in_context.getUserData()[fullPath] = true; }); } } } }; /** * Inverts a reversible ChangeSets * WARNING: This function is still experimental and needs more testing * and it's set to private for now. It will be converted to a public API function * in a later release */ public toInverseChangeSet() { if (this._changes.value !== undefined && this._changes.oldValue !== undefined) { const tmp = this._changes.value; this._changes.value = this._changes.oldValue; this._changes.oldValue = tmp; } else { Utils.traverseChangeSetRecursively(this._changes, { preCallback: this._recursivelyInvertReversibleChangeset.bind(this), }); } } } ChangeSet.prototype._performApplyAfterOnPropertyArray = ChangeSetArrayFunctions._performApplyAfterOnPropertyArray; ChangeSet.prototype._rebaseArrayChangeSetForProperty = ChangeSetArrayFunctions._rebaseArrayChangeSetForProperty; ChangeSet.prototype._rebaseChangeSetForString = ChangeSetArrayFunctions._rebaseChangeSetForString; // Add the indexed collection functions into the prototype of the ChangeSet ChangeSet.prototype._performApplyAfterOnPropertyIndexedCollection = ChangeSetIndexedCollectionFunctions._performApplyAfterOnPropertyIndexedCollection; ChangeSet.prototype._cleanIndexedCollectionChangeSet = ChangeSetIndexedCollectionFunctions._cleanIndexedCollectionChangeSet; ChangeSet.prototype._rebaseIndexedCollectionChangeSetForProperty = ChangeSetIndexedCollectionFunctions._rebaseIndexedCollectionChangeSetForProperty;
the_stack