text stringlengths 2.5k 6.39M | kind stringclasses 3
values |
|---|---|
// -----------------------------------------------------------------------------------
// Arc Generator
// -----------------------------------------------------------------------------------
export interface DefaultArcObject {
innerRadius: number;
outerRadius: number;
startAngle: number;
endAngle: number;
padAngle: number;
}
export interface Arc<This, Datum> {
(this: This, d: Datum, ...args: any[]): string | undefined;
centroid(d: Datum, ...args: any[]): [number, number];
innerRadius(): (this: This, d: Datum, ...args: any[]) => number;
innerRadius(radius: number): this;
innerRadius(radius: (this: This, d: Datum, ...args: any[]) => number): this;
outerRadius(): (this: This, d: Datum, ...args: any[]) => number;
outerRadius(radius: number): this;
outerRadius(radius: (this: This, d: Datum, ...args: any[]) => number): this;
cornerRadius(): (this: This, d: Datum, ...args: any[]) => number;
cornerRadius(radius: number): this;
cornerRadius(radius: (this: This, d: Datum, ...args: any[]) => number): this;
startAngle(): (this: This, d: Datum, ...args: any[]) => number;
startAngle(angle: number): this;
startAngle(angle: (this: This, d: Datum, ...args: any[]) => number): this;
endAngle(): (this: This, d: Datum, ...args: any[]) => number;
endAngle(angle: number): this;
endAngle(angle: (this: This, d: Datum, ...args: any[]) => number): this;
padAngle(): (this: This, d: Datum, ...args: any[]) => number;
padAngle(angle: number): this;
padAngle(angle: (this: This, d: Datum, ...args: any[]) => number): this;
context(): CanvasRenderingContext2D | null;
context(context: CanvasRenderingContext2D): this;
context(context: null): this;
}
export function arc(): Arc<any, DefaultArcObject>;
export function arc<Datum>(): Arc<any, Datum>;
export function arc<This, Datum>(): Arc<This, Datum>;
// -----------------------------------------------------------------------------------
// Pie Generator
// -----------------------------------------------------------------------------------
export interface PieArcDatum<T> {
data: T;
value: number;
index: number;
startAngle: number;
endAngle: number;
padAngle: number;
}
export interface Pie<This, Datum> {
(this: This, data: Array<Datum>, ...args: any[]): Array<PieArcDatum<Datum>>;
value(): (d: Datum, i: number, data: Array<Datum>) => number;
value(value: number): this;
value(value: (d: Datum, i: number, data: Array<Datum>) => number): this;
sort(): ((a: Datum, b: Datum) => number) | null;
sort(comparator: (a: Datum, b: Datum) => number): this;
sort(comparator: null): this;
sortValues(): ((a: number, b: number) => number) | null;
sortValues(comparator: (a: number, b: number) => number): this;
sortValues(comparator: null): this;
startAngle(): (this: This, data: Array<Datum>, ...args: any[]) => number;
startAngle(angle: number): this;
startAngle(angle: (this: This, data: Array<Datum>, ...args: any[]) => number): this;
endAngle(): (this: This, data: Array<Datum>, ...args: any[]) => number;
endAngle(angle: number): this;
endAngle(angle: (this: This, data: Array<Datum>, ...args: any[]) => number): this;
padAngle(): (this: This, data: Array<Datum>, ...args: any[]) => number;
padAngle(angle: number): this;
padAngle(angle: (this: This, data: Array<Datum>, ...args: any[]) => number): this;
}
export function pie(): Pie<any, number | { valueOf(): number }>;
export function pie<Datum>(): Pie<any, Datum>;
export function pie<This, Datum>(): Pie<This, Datum>;
// -----------------------------------------------------------------------------------
// Line Generators
// -----------------------------------------------------------------------------------
export interface Line<Datum> {
(data: Array<Datum>): string | undefined;
x(): (d: Datum, index: number, data: Array<Datum>) => number;
x(x: number): this;
x(x: (d: Datum, index: number, data: Array<Datum>) => number): this;
y(): (d: Datum, index: number, data: Array<Datum>) => number;
y(y: number): this;
y(y: (d: Datum, index: number, data: Array<Datum>) => number): this;
defined(): (d: Datum, index: number, data: Array<Datum>) => boolean;
defined(defined: boolean): this;
defined(defined: (d: Datum, index: number, data: Array<Datum>) => boolean): this;
curve(): CurveFactory | CurveFactoryLineOnly;
curve(curve: CurveFactory | CurveFactoryLineOnly): this;
context(): CanvasRenderingContext2D | null;
context(context: CanvasRenderingContext2D): this;
context(context: null): this;
}
export function line(): Line<[number, number]>;
export function line<Datum>(): Line<Datum>;
export function line<This, Datum>(): Line<Datum>;
export interface RadialLine<Datum> {
(data: Array<Datum>): string | undefined;
angle(): (d: Datum, index: number, data: Array<Datum>) => number;
angle(angle: number): this;
angle(angle: (d: Datum, index: number, data: Array<Datum>) => number): this;
radius(): (d: Datum, index: number, data: Array<Datum>) => number;
radius(radius: number): this;
radius(radius: (d: Datum, index: number, data: Array<Datum>) => number): this;
defined(): (d: Datum, index: number, data: Array<Datum>) => boolean;
defined(defined: boolean): this;
defined(defined: (d: Datum, index: number, data: Array<Datum>) => boolean): this;
curve(): CurveFactory | CurveFactoryLineOnly;
curve(curve: CurveFactory | CurveFactoryLineOnly): this;
context(): CanvasRenderingContext2D | null;
context(context: CanvasRenderingContext2D): this;
context(context: null): this;
}
export function radialLine(): RadialLine<[number, number]>;
export function radialLine<Datum>(): RadialLine<Datum>;
// -----------------------------------------------------------------------------------
// Area Generators
// -----------------------------------------------------------------------------------
export interface Area<Datum> {
(data: Array<Datum>): string | undefined;
x(): (d: Datum, index: number, data: Array<Datum>) => number;
x(x: number): this;
x(x: (d: Datum, index: number, data: Array<Datum>) => number): this;
x0(): (d: Datum, index: number, data: Array<Datum>) => number;
x0(x0: number): this;
x0(x0: (d: Datum, index: number, data: Array<Datum>) => number): this;
x1(): ((d: Datum, index: number, data: Array<Datum>) => number) | null;
x1(x: number): this;
x1(x: (d: Datum, index: number, data: Array<Datum>) => number): this;
y(): (d: Datum, index: number, data: Array<Datum>) => number;
y(y: number): this;
y(y: (d: Datum, index: number, data: Array<Datum>) => number): this;
y0(): (d: Datum, index: number, data: Array<Datum>) => number;
y0(y: number): this;
y0(y: (d: Datum, index: number, data: Array<Datum>) => number): this;
y1(): (d: Datum, index: number, data: Array<Datum>) => number;
y1(y: number): this;
y1(y: (d: Datum, index: number, data: Array<Datum>) => number): this;
defined(): (d: Datum, index: number, data: Array<Datum>) => boolean;
defined(defined: boolean): this;
defined(defined: (d: Datum, index: number, data: Array<Datum>) => boolean): this;
curve(): CurveFactory;
curve(curve: CurveFactory): this;
context(): CanvasRenderingContext2D | null;
context(context: CanvasRenderingContext2D): this;
context(context: null): this;
lineX0(): Line<Datum>;
lineY0(): Line<Datum>;
lineX1(): Line<Datum>;
lineY1(): Line<Datum>;
}
export function area(): Area<[number, number]>;
export function area<Datum>(): Area<Datum>;
export interface RadialArea<Datum> {
(data: Array<Datum>): string | undefined;
angle(): (d: Datum, index: number, data: Array<Datum>) => number;
angle(angle: number): this;
angle(angle: (d: Datum, index: number, data: Array<Datum>) => number): this;
startAngle(): (d: Datum, index: number, data: Array<Datum>) => number;
startAngle(angle: number): this;
startAngle(angle: (d: Datum, index: number, data: Array<Datum>) => number): this;
endAngle(): ((d: Datum, index: number, data: Array<Datum>) => number) | null;
endAngle(angle: number): this;
endAngle(angle: (d: Datum, index: number, data: Array<Datum>) => number): this;
radius(): (d: Datum, index: number, data: Array<Datum>) => number;
radius(radius: number): this;
radius(radius: (d: Datum, index: number, data: Array<Datum>) => number): this;
innerRadius(): (d: Datum, index: number, data: Array<Datum>) => number;
innerRadius(radius: number): this;
innerRadius(radius: (d: Datum, index: number, data: Array<Datum>) => number): this;
outerRadius(): (d: Datum, index: number, data: Array<Datum>) => number;
outerRadius(radius: number): this;
outerRadius(radius: (d: Datum, index: number, data: Array<Datum>) => number): this;
defined(): (d: Datum, index: number, data: Array<Datum>) => boolean;
defined(defined: boolean): this;
defined(defined: (d: Datum, index: number, data: Array<Datum>) => boolean): this;
curve(): CurveFactory;
curve(curve: CurveFactory): this;
context(): CanvasRenderingContext2D | null;
context(context: CanvasRenderingContext2D): this;
context(context: null): this;
lineStartAngle(): RadialLine<Datum>;
lineInnerRadius(): RadialLine<Datum>;
lineEndAngle(): RadialLine<Datum>;
lineOuterRadius(): RadialLine<Datum>;
}
export function radialArea(): RadialArea<[number, number]>;
export function radialArea<Datum>(): RadialArea<Datum>;
// -----------------------------------------------------------------------------------
// Curve Factories
// -----------------------------------------------------------------------------------
export interface CurveGeneratorLineOnly {
lineStart(): void;
lineEnd(): void;
point(x: number, y: number): void;
}
export interface CurveFactoryLineOnly {
(context: CanvasRenderingContext2D | null): CurveGeneratorLineOnly;
}
export interface CurveGenerator extends CurveGeneratorLineOnly {
areaStart(): void;
areaEnd(): void;
}
export interface CurveFactory {
(context: CanvasRenderingContext2D | null): CurveGenerator;
}
export var curveBasis: CurveFactory;
export var curveBasisOpen: CurveFactory;
export var curveBasisClosed: CurveFactory;
export interface CurveBundleFactory extends CurveFactoryLineOnly {
beta(beta: number): this;
}
export var curveBundle: CurveBundleFactory;
export interface CurveCardinalFactory extends CurveFactory {
tension(tension: number): this;
}
export var curveCardinal: CurveCardinalFactory;
export var curveCardinalOpen: CurveCardinalFactory;
export var curveCardinalClosed: CurveCardinalFactory;
export interface CurveCatmullRomFactory extends CurveFactory {
alpha(alpha: number): this;
}
export var curveCatmullRom: CurveCatmullRomFactory;
export var curveCatmullRomOpen: CurveCatmullRomFactory;
export var curveCatmullRomClosed: CurveCatmullRomFactory;
export var curveLinear: CurveFactory;
export var curveLinearClosed: CurveFactory;
export var curveMonotoneX: CurveFactory;
export var curveMonotoneY: CurveFactory;
export var curveNatural: CurveFactory;
export var curveStep: CurveFactory;
export var curveStepAfter: CurveFactory;
export var curveStepBefore: CurveFactory;
// -----------------------------------------------------------------------------------
// SYMBOLS
// -----------------------------------------------------------------------------------
export interface SymbolType {
draw(context: CanvasPathMethods, size: number): void;
}
export interface Symbol<This, Datum> {
(this: This, d?: Datum, ...args: any[]): undefined | string;
size(): (this: This, d: Datum, ...args: any[]) => number;
size(size: number): this;
size(size: (this: This, d: Datum, ...args: any[]) => number): this;
type(): (this: This, d: Datum, ...args: any[]) => SymbolType;
type(type: SymbolType): this;
type(type: (this: This, d: Datum, ...args: any[]) => SymbolType): this;
context(): CanvasRenderingContext2D | null;
context(context: CanvasRenderingContext2D): this;
context(context: null): this;
}
export function symbol(): Symbol<any, any>;
export function symbol<Datum>(): Symbol<any, Datum>;
export function symbol<This, Datum>(): Symbol<This, Datum>;
export var symbols: Array<SymbolType>;
export var symbolCircle: SymbolType;
export var symbolCross: SymbolType;
export var symbolDiamond: SymbolType;
export var symbolSquare: SymbolType;
export var symbolStar: SymbolType;
export var symbolTriangle: SymbolType;
export var symbolWye: SymbolType;
// -----------------------------------------------------------------------------------
// STACKS
// -----------------------------------------------------------------------------------
// SeriesPoint is a [number, number] two-element Array with added
// data and index properties related to the data element which formed the basis for the
// SeriesPoint
export interface SeriesPoint<Datum> extends Array<number> {
0: number;
1: number;
index: number;
data: Datum;
}
export interface Series<Datum, Key> extends Array<SeriesPoint<Datum>> {
key: Key;
}
export interface Stack<This, Datum, Key> {
(data: Array<Datum>, ...args: any[]): Array<Series<Datum, Key>>;
keys(): (this: This, data: Array<Datum>, ...args: any[]) => Array<Key>;
keys(keys: Array<Key>): this;
keys(keys: (this: This, data: Array<Datum>, ...args: any[]) => Array<Key>): this;
value(): (d: Datum, key: Key, j: number, data: Array<Datum>) => number;
value(value: number): this;
value(value: (d: Datum, key: Key, j: number, data: Array<Datum>) => number): this;
order(): (series: Series<Datum, Key>) => Array<number>;
order(order: null): this;
order(order: Array<number>): this;
order(order: (series: Series<Datum, Key>) => Array<number>): this;
offset(): (series: Series<Datum, Key>, order: Array<number>) => void;
offset(offset: null): this;
offset(offset: (series: Series<Datum, Key>, order: Array<number>) => void): this;
}
export function stack(): Stack<any, { [key: string]: number }, string>;
export function stack<Datum>(): Stack<any, Datum, string>;
export function stack<Datum, Key>(): Stack<any, Datum, Key>;
export function stack<This, Datum, Key>(): Stack<This, Datum, Key>;
export function stackOrderAscending(series: Series<any, any>): Array<number>;
export function stackOrderDescending(series: Series<any, any>): Array<number>
export function stackOrderInsideOut(series: Series<any, any>): Array<number>
export function stackOrderNone(series: Series<any, any>): Array<number>
export function stackOrderReverse(series: Series<any, any>): Array<number>
export function stackOffsetExpand(series: Series<any, any>, order: Array<number>): void;
export function stackOffsetNone(series: Series<any, any>, order: Array<number>): void;
export function stackOffsetSilhouette(series: Series<any, any>, order: Array<number>): void;
export function stackOffsetWiggle(series: Series<any, any>, order: Array<number>): void; | the_stack |
import { connect } from '@wagmi/core'
import { MockConnector } from '@wagmi/core/connectors/mock'
import {
act,
actConnect,
actDisconnect,
getSigners,
renderHook,
setupClient,
} from '../../../test'
import { UseConnectArgs, UseConnectConfig, useConnect } from './useConnect'
import { useDisconnect } from './useDisconnect'
import { UseNetworkArgs, UseNetworkConfig, useNetwork } from './useNetwork'
function useNetworkWithConnectAndDisconnect(
config: {
connect?: UseConnectArgs & UseConnectConfig
network?: UseNetworkArgs & UseNetworkConfig
} = {},
) {
return {
connect: useConnect(config.connect),
disconnect: useDisconnect(),
network: useNetwork(config.network),
}
}
describe('useNetwork', () => {
describe('mounts', () => {
it('is connected', async () => {
const client = setupClient()
await connect({ connector: client.connectors[0] })
const { result, waitFor } = renderHook(() => useNetwork(), {
initialProps: { client },
})
await waitFor(() => expect(result.current.isIdle).toBeTruthy())
const { activeChain, chains, ...res } = result.current
expect(activeChain?.id).toEqual(1)
expect(chains.length).toEqual(5)
expect(res).toMatchInlineSnapshot(`
{
"data": undefined,
"error": null,
"isError": false,
"isIdle": true,
"isLoading": false,
"isSuccess": false,
"pendingChainId": undefined,
"reset": [Function],
"status": "idle",
"switchNetwork": [Function],
"switchNetworkAsync": [Function],
"variables": undefined,
}
`)
})
it('is not connected', async () => {
const { result, waitFor } = renderHook(() => useNetwork())
await waitFor(() => expect(result.current.isIdle).toBeTruthy())
const { chains, ...res } = result.current
expect(chains.length).toEqual(5)
expect(res).toMatchInlineSnapshot(`
{
"activeChain": undefined,
"data": undefined,
"error": null,
"isError": false,
"isIdle": true,
"isLoading": false,
"isSuccess": false,
"pendingChainId": undefined,
"reset": [Function],
"status": "idle",
"switchNetwork": undefined,
"switchNetworkAsync": undefined,
"variables": undefined,
}
`)
})
})
describe('configuration', () => {
it('chainId', async () => {
const { result, waitFor } = renderHook(() => useNetwork({ chainId: 1 }))
await waitFor(() => expect(result.current.isIdle).toBeTruthy())
const { chains, ...res } = result.current
expect(chains.length).toEqual(5)
expect(res).toMatchInlineSnapshot(`
{
"activeChain": undefined,
"data": undefined,
"error": null,
"isError": false,
"isIdle": true,
"isLoading": false,
"isSuccess": false,
"pendingChainId": undefined,
"reset": [Function],
"status": "idle",
"switchNetwork": undefined,
"switchNetworkAsync": undefined,
"variables": undefined,
}
`)
})
})
describe('return value', () => {
describe('switchNetwork', () => {
it('uses configuration', async () => {
const utils = renderHook(() =>
useNetworkWithConnectAndDisconnect({
network: {
chainId: 4,
},
}),
)
const { result, waitFor } = utils
await actConnect({ utils })
await act(async () => result.current.network.switchNetwork?.())
await waitFor(() =>
expect(result.current.network.isSuccess).toBeTruthy(),
)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { activeChain, chains, data, ...res } = result.current.network
expect(activeChain?.id).toMatchInlineSnapshot(`4`)
expect(data?.id).toMatchInlineSnapshot(`4`)
expect(res).toMatchInlineSnapshot(`
{
"error": null,
"isError": false,
"isIdle": false,
"isLoading": false,
"isSuccess": true,
"pendingChainId": 4,
"reset": [Function],
"status": "success",
"switchNetwork": [Function],
"switchNetworkAsync": [Function],
"variables": {
"chainId": 4,
},
}
`)
})
it('uses deferred args', async () => {
const utils = renderHook(() => useNetworkWithConnectAndDisconnect())
const { result, waitFor } = utils
await actConnect({ utils })
await act(async () => result.current.network.switchNetwork?.(4))
await waitFor(() =>
expect(result.current.network.isSuccess).toBeTruthy(),
)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { activeChain, chains, data, ...res } = result.current.network
expect(activeChain?.id).toMatchInlineSnapshot(`4`)
expect(data?.id).toMatchInlineSnapshot(`4`)
expect(res).toMatchInlineSnapshot(`
{
"error": null,
"isError": false,
"isIdle": false,
"isLoading": false,
"isSuccess": true,
"pendingChainId": 4,
"reset": [Function],
"status": "success",
"switchNetwork": [Function],
"switchNetworkAsync": [Function],
"variables": {
"chainId": 4,
},
}
`)
})
it('fails', async () => {
const connector = new MockConnector({
options: {
flags: { failSwitchChain: true },
signer: getSigners()[0],
},
})
const utils = renderHook(() =>
useNetworkWithConnectAndDisconnect({
connect: { connector },
}),
)
const { result, waitFor } = utils
await actConnect({ utils, connector })
await act(async () => result.current.network.switchNetwork?.(4))
await waitFor(() => expect(result.current.network.isError).toBeTruthy())
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { activeChain, chains, ...res } = result.current.network
expect(res).toMatchInlineSnapshot(`
{
"data": undefined,
"error": [UserRejectedRequestError: User rejected request],
"isError": true,
"isIdle": false,
"isLoading": false,
"isSuccess": false,
"pendingChainId": 4,
"reset": [Function],
"status": "error",
"switchNetwork": [Function],
"switchNetworkAsync": [Function],
"variables": {
"chainId": 4,
},
}
`)
})
it('unsupported chain', async () => {
const utils = renderHook(() =>
useNetworkWithConnectAndDisconnect({
network: { chainId: 69 },
}),
)
const { result, waitFor } = utils
await actConnect({ utils })
await act(async () => result.current.network.switchNetwork?.())
await waitFor(() =>
expect(result.current.network.isSuccess).toBeTruthy(),
)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { activeChain, chains, data, ...res } = result.current.network
expect(activeChain?.id).toMatchInlineSnapshot(`69`)
expect(activeChain?.unsupported).toMatchInlineSnapshot(`true`)
expect(data?.id).toMatchInlineSnapshot(`69`)
expect(res).toMatchInlineSnapshot(`
{
"error": null,
"isError": false,
"isIdle": false,
"isLoading": false,
"isSuccess": true,
"pendingChainId": 69,
"reset": [Function],
"status": "success",
"switchNetwork": [Function],
"switchNetworkAsync": [Function],
"variables": {
"chainId": 69,
},
}
`)
})
})
describe('switchNetworkAsync', () => {
it('uses configuration', async () => {
const utils = renderHook(() =>
useNetworkWithConnectAndDisconnect({
network: {
chainId: 4,
},
}),
)
const { result, waitFor } = utils
await actConnect({ utils })
await act(async () => {
const res = await result.current.network.switchNetworkAsync?.()
expect(res).toMatchInlineSnapshot(`
{
"blockExplorers": {
"default": {
"name": "Etherscan",
"url": "https://rinkeby.etherscan.io",
},
"etherscan": {
"name": "Etherscan",
"url": "https://rinkeby.etherscan.io",
},
},
"id": 4,
"name": "Rinkeby",
"nativeCurrency": {
"decimals": 18,
"name": "Rinkeby Ether",
"symbol": "rETH",
},
"network": "rinkeby",
"rpcUrls": {
"alchemy": "https://eth-rinkeby.alchemyapi.io/v2",
"default": "https://eth-rinkeby.alchemyapi.io/v2/_gg7wSSi0KMBsdKnGVfHDueq6xMB9EkC",
"infura": "https://rinkeby.infura.io/v3",
},
"testnet": true,
}
`)
})
await waitFor(() =>
expect(result.current.network.isSuccess).toBeTruthy(),
)
})
it('throws error', async () => {
const connector = new MockConnector({
options: {
flags: { failSwitchChain: true },
signer: getSigners()[0],
},
})
const utils = renderHook(() =>
useNetworkWithConnectAndDisconnect({
connect: { connector },
}),
)
const { result, waitFor } = utils
await actConnect({ utils, connector })
await act(async () => {
await expect(
result.current.network.switchNetworkAsync?.(4),
).rejects.toThrowErrorMatchingInlineSnapshot(
`"User rejected request"`,
)
})
await waitFor(() => expect(result.current.network.isError).toBeTruthy())
})
})
})
describe('behavior', () => {
it('updates on connect and disconnect', async () => {
const utils = renderHook(() => useNetworkWithConnectAndDisconnect())
const { result } = utils
await actConnect({ utils })
expect(result.current.network.activeChain?.id).toMatchInlineSnapshot(`1`)
await actDisconnect({ utils })
expect(result.current.network.activeChain).toMatchInlineSnapshot(
`undefined`,
)
})
it('connector does not support programmatic switching', async () => {
const connector = new MockConnector({
options: {
flags: { noSwitchChain: true },
signer: getSigners()[0],
},
})
const utils = renderHook(() =>
useNetworkWithConnectAndDisconnect({
connect: { connector },
}),
)
const { result } = utils
await actConnect({ utils, connector })
await act(async () => {
try {
result.current.network.switchNetwork?.(4)
} catch (error) {
expect(error).toMatchInlineSnapshot(
`[TypeError: result.current.network.switchNetwork is not a function]`,
)
}
})
})
})
}) | the_stack |
import React from "react";
import ReactModal from "react-modal";
import { Switch, Route } from "react-router";
import { ErrorModal, ErrorModalData } from "./components/ErrorModal";
import cstyles from "./components/Common.module.css";
import routes from "./constants/routes.json";
import Dashboard from "./components/Dashboard";
import Send, { SendManyJson } from "./components/Send";
import Receive from "./components/Receive";
import LoadingScreen from "./components/LoadingScreen";
import AppState, {
AddressBalance,
TotalBalance,
Transaction,
SendPageState,
ToAddr,
RPCConfig,
Info,
ReceivePageState,
AddressBookEntry,
PasswordState,
ServerSelectState,
SendProgress,
} from "./components/AppState";
import RPC from "./rpc";
import Utils from "./utils/utils";
import { ZcashURITarget } from "./utils/uris";
import Zcashd from "./components/Zcashd";
import AddressBook from "./components/Addressbook";
import AddressbookImpl from "./utils/AddressbookImpl";
import Sidebar from "./components/Sidebar";
import Transactions from "./components/Transactions";
import PasswordModal from "./components/PasswordModal";
import ServerSelectModal from "./components/ServerSelectModal";
type Props = {};
export default class RouteApp extends React.Component<Props, AppState> {
rpc: RPC;
constructor(props: Props) {
super(props);
this.state = new AppState();
// Create the initial ToAddr box
// eslint-disable-next-line react/destructuring-assignment
this.state.sendPageState.toaddrs = [new ToAddr(Utils.getNextToAddrID())];
// Set the Modal's app element
ReactModal.setAppElement("#root");
this.rpc = new RPC(
this.setTotalBalance,
this.setAddressesWithBalances,
this.setTransactionList,
this.setAllAddresses,
this.setInfo,
this.setZecPrice
);
}
componentDidMount() {
// Read the address book
(async () => {
const addressBook = await AddressbookImpl.readAddressBook();
if (addressBook) {
this.setState({ addressBook });
}
})();
}
componentWillUnmount() {}
getFullState = (): AppState => {
return this.state;
};
openErrorModal = (title: string, body: string | JSX.Element) => {
const errorModalData = new ErrorModalData();
errorModalData.modalIsOpen = true;
errorModalData.title = title;
errorModalData.body = body;
this.setState({ errorModalData });
};
closeErrorModal = () => {
const errorModalData = new ErrorModalData();
errorModalData.modalIsOpen = false;
this.setState({ errorModalData });
};
openServerSelectModal = () => {
const serverSelectState = new ServerSelectState();
serverSelectState.modalIsOpen = true;
this.setState({ serverSelectState });
};
closeServerSelectModal = () => {
const serverSelectState = new ServerSelectState();
serverSelectState.modalIsOpen = false;
this.setState({ serverSelectState });
};
openPassword = (
confirmNeeded: boolean,
passwordCallback: (p: string) => void,
closeCallback: () => void,
helpText?: string | JSX.Element
) => {
const passwordState = new PasswordState();
passwordState.showPassword = true;
passwordState.confirmNeeded = confirmNeeded;
passwordState.helpText = helpText || "";
// Set the callbacks, but before calling them back, we close the modals
passwordState.passwordCallback = (password: string) => {
this.setState({ passwordState: new PasswordState() });
// Call the callback after a bit, so as to give time to the modal to close
setTimeout(() => passwordCallback(password), 10);
};
passwordState.closeCallback = () => {
this.setState({ passwordState: new PasswordState() });
// Call the callback after a bit, so as to give time to the modal to close
setTimeout(() => closeCallback(), 10);
};
this.setState({ passwordState });
};
// This will:
// 1. Check if the wallet is encrypted and locked
// 2. If it is, open the password dialog
// 3. Attempt to unlock wallet.
// a. If unlock suceeds, do the callback
// b. If the unlock fails, show an error
// 4. If wallet is not encrypted or already unlocked, just call the successcallback.
openPasswordAndUnlockIfNeeded = (successCallback: () => void) => {
// Check if it is locked
const { info } = this.state;
if (info.encrypted && info.locked) {
this.openPassword(
false,
(password: string) => {
(async () => {
const success = await this.unlockWallet(password);
if (success) {
// If the unlock succeeded, do the submit
successCallback();
} else {
this.openErrorModal("Wallet unlock failed", "Could not unlock the wallet with the password.");
}
})();
},
// Close callback is a no-op
() => {}
);
} else {
successCallback();
}
};
unlockWallet = async (password: string): Promise<boolean> => {
const success = await this.rpc.unlockWallet(password);
return success;
};
lockWallet = async (): Promise<boolean> => {
const success = await this.rpc.lockWallet();
return success;
};
encryptWallet = async (password: string): Promise<boolean> => {
const success = await this.rpc.encryptWallet(password);
return success;
};
decryptWallet = async (password: string): Promise<boolean> => {
const success = await this.rpc.decryptWallet(password);
return success;
};
setTotalBalance = (totalBalance: TotalBalance) => {
this.setState({ totalBalance });
};
setAddressesWithBalances = (addressesWithBalance: AddressBalance[]) => {
this.setState({ addressesWithBalance });
const { sendPageState } = this.state;
// If there is no 'from' address, we'll set a default one
if (!sendPageState.fromaddr) {
// Find a z-address with the highest balance
const defaultAB = addressesWithBalance
.filter((ab) => Utils.isSapling(ab.address))
.reduce((prev: AddressBalance | null, ab) => {
// We'll start with a sapling address
if (!prev) {
return ab;
} else if (prev.balance < ab.balance) {
// Find the sapling address with the highest balance
return ab;
} else {
return prev;
}
}, null);
if (defaultAB) {
const newSendPageState = new SendPageState();
newSendPageState.fromaddr = defaultAB.address;
newSendPageState.toaddrs = sendPageState.toaddrs;
this.setState({ sendPageState: newSendPageState });
}
}
};
setTransactionList = (transactions: Transaction[]) => {
this.setState({ transactions });
};
setAllAddresses = (addresses: string[]) => {
this.setState({ addresses });
};
setSendPageState = (sendPageState: SendPageState) => {
this.setState({ sendPageState });
};
importPrivKeys = async (keys: string[], birthday: string): Promise<boolean> => {
console.log(keys);
// eslint-disable-next-line no-plusplus
for (let i = 0; i < keys.length; i++) {
// eslint-disable-next-line no-await-in-loop
const result = await RPC.doImportPrivKey(keys[i], birthday);
if (result === "OK") {
return true;
// eslint-disable-next-line no-else-return
} else {
this.openErrorModal(
"Failed to import key",
<span>
A private key failed to import.
<br />
The error was:
<br />
{result}
</span>
);
return false;
}
}
return true;
};
setSendTo = (targets: ZcashURITarget[] | ZcashURITarget) => {
// Clear the existing send page state and set up the new one
const { sendPageState } = this.state;
const newSendPageState = new SendPageState();
newSendPageState.toaddrs = [];
newSendPageState.fromaddr = sendPageState.fromaddr;
// If a single object is passed, accept that as well.
let tgts = targets;
if (!Array.isArray(tgts)) {
tgts = [targets as ZcashURITarget];
}
tgts.forEach((tgt) => {
const to = new ToAddr(Utils.getNextToAddrID());
if (tgt.address) {
to.to = tgt.address;
}
if (tgt.amount) {
to.amount = tgt.amount;
}
if (tgt.memoString) {
to.memo = tgt.memoString;
}
newSendPageState.toaddrs.push(to);
});
this.setState({ sendPageState: newSendPageState });
};
setRPCConfig = (rpcConfig: RPCConfig) => {
this.setState({ rpcConfig });
console.log(rpcConfig);
this.rpc.configure(rpcConfig);
};
setZecPrice = (price?: number) => {
console.log(`Price = ${price}`);
const { info } = this.state;
const newInfo = new Info();
Object.assign(newInfo, info);
if (price) {
newInfo.zecPrice = price;
}
this.setState({ info: newInfo });
};
setRescanning = (rescanning: boolean, prevSyncId: number) => {
this.setState({ rescanning });
this.setState({ prevSyncId });
};
setInfo = (newInfo: Info) => {
// If the price is not set in this object, copy it over from the current object
const { info } = this.state;
if (!newInfo.zecPrice) {
// eslint-disable-next-line no-param-reassign
newInfo.zecPrice = info.zecPrice;
}
console.log(newInfo);
this.setState({ info: newInfo });
};
sendTransaction = async (sendJson: SendManyJson[], setSendProgress: (p?: SendProgress) => void): Promise<string> => {
try {
const txid = await this.rpc.sendTransaction(sendJson, setSendProgress);
if (txid.toLowerCase().startsWith("error")) {
throw txid;
}
return txid;
} catch (err) {
console.log("route sendtx error", err);
throw err;
}
};
// Get a single private key for this address, and return it as a string.
// Wallet needs to be unlocked
getPrivKeyAsString = (address: string): string => {
const pk = RPC.getPrivKeyAsString(address);
return pk;
};
// Getter methods, which are called by the components to update the state
fetchAndSetSinglePrivKey = async (address: string) => {
this.openPasswordAndUnlockIfNeeded(async () => {
let key = await RPC.getPrivKeyAsString(address);
if (key === "") {
key = "<No Key Available>";
}
const addressPrivateKeys = new Map();
addressPrivateKeys.set(address, key);
this.setState({ addressPrivateKeys });
});
};
fetchAndSetSingleViewKey = async (address: string) => {
this.openPasswordAndUnlockIfNeeded(async () => {
const key = await RPC.getViewKeyAsString(address);
const addressViewKeys = new Map();
addressViewKeys.set(address, key);
this.setState({ addressViewKeys });
});
};
addAddressBookEntry = (label: string, address: string) => {
// Add an entry into the address book
const { addressBook } = this.state;
const newAddressBook = addressBook.concat(new AddressBookEntry(label, address));
// Write to disk. This method is async
AddressbookImpl.writeAddressBook(newAddressBook);
this.setState({ addressBook: newAddressBook });
};
removeAddressBookEntry = (label: string) => {
const { addressBook } = this.state;
const newAddressBook = addressBook.filter((i) => i.label !== label);
// Write to disk. This method is async
AddressbookImpl.writeAddressBook(newAddressBook);
this.setState({ addressBook: newAddressBook });
};
createNewAddress = async (zaddress: boolean) => {
this.openPasswordAndUnlockIfNeeded(async () => {
// Create a new address
const newaddress = RPC.createNewAddress(zaddress);
console.log(`Created new Address ${newaddress}`);
// And then fetch the list of addresses again to refresh (totalBalance gets all addresses)
this.rpc.fetchTotalBalance();
const { receivePageState } = this.state;
const newRerenderKey = receivePageState.rerenderKey + 1;
const newReceivePageState = new ReceivePageState();
newReceivePageState.newAddress = newaddress;
newReceivePageState.rerenderKey = newRerenderKey;
this.setState({ receivePageState: newReceivePageState });
});
};
doRefresh = () => {
this.rpc.refresh(false);
};
clearTimers = () => {
this.rpc.clearTimers();
};
render() {
const {
totalBalance,
transactions,
addressesWithBalance,
addressPrivateKeys,
addressViewKeys,
addresses,
addressBook,
sendPageState,
receivePageState,
rpcConfig,
info,
rescanning,
prevSyncId,
errorModalData,
serverSelectState,
passwordState,
} = this.state;
const standardProps = {
openErrorModal: this.openErrorModal,
closeErrorModal: this.closeErrorModal,
setSendTo: this.setSendTo,
info,
openPasswordAndUnlockIfNeeded: this.openPasswordAndUnlockIfNeeded,
};
const hasLatestBlock = info && info.latestBlock > 0 ? true : false;
return (
<>
<ErrorModal
title={errorModalData.title}
body={errorModalData.body}
modalIsOpen={errorModalData.modalIsOpen}
closeModal={this.closeErrorModal}
/>
<PasswordModal
modalIsOpen={passwordState.showPassword}
confirmNeeded={passwordState.confirmNeeded}
passwordCallback={passwordState.passwordCallback}
closeCallback={passwordState.closeCallback}
helpText={passwordState.helpText}
/>
<ServerSelectModal
modalIsOpen={serverSelectState.modalIsOpen}
closeModal={this.closeServerSelectModal}
openErrorModal={this.openErrorModal}
/>
<div style={{ overflow: "hidden" }}>
{hasLatestBlock && (
<div className={cstyles.sidebarcontainer}>
<Sidebar
setInfo={this.setInfo}
setRescanning={this.setRescanning}
getPrivKeyAsString={this.getPrivKeyAsString}
addresses={addresses}
importPrivKeys={this.importPrivKeys}
transactions={transactions}
lockWallet={this.lockWallet}
encryptWallet={this.encryptWallet}
decryptWallet={this.decryptWallet}
openPassword={this.openPassword}
clearTimers={this.clearTimers}
{...standardProps}
/>
</div>
)}
<div className={cstyles.contentcontainer}>
<Switch>
<Route
path={routes.SEND}
render={() => (
<Send
addresses={addresses}
sendTransaction={this.sendTransaction}
sendPageState={sendPageState}
setSendPageState={this.setSendPageState}
totalBalance={totalBalance}
addressBook={addressBook}
{...standardProps}
/>
)}
/>
<Route
path={routes.RECEIVE}
render={() => (
<Receive
rerenderKey={receivePageState.rerenderKey}
addresses={addresses}
addressesWithBalance={addressesWithBalance}
addressPrivateKeys={addressPrivateKeys}
addressViewKeys={addressViewKeys}
receivePageState={receivePageState}
addressBook={addressBook}
{...standardProps}
fetchAndSetSinglePrivKey={this.fetchAndSetSinglePrivKey}
fetchAndSetSingleViewKey={this.fetchAndSetSingleViewKey}
createNewAddress={this.createNewAddress}
/>
)}
/>
<Route
path={routes.ADDRESSBOOK}
render={() => (
<AddressBook
addressBook={addressBook}
addAddressBookEntry={this.addAddressBookEntry}
removeAddressBookEntry={this.removeAddressBookEntry}
{...standardProps}
/>
)}
/>
<Route
path={routes.DASHBOARD}
// eslint-disable-next-line react/jsx-props-no-spreading
render={() => (
<Dashboard totalBalance={totalBalance} info={info} addressesWithBalance={addressesWithBalance} />
)}
/>
<Route
path={routes.TRANSACTIONS}
render={() => (
<Transactions
transactions={transactions}
info={info}
addressBook={addressBook}
setSendTo={this.setSendTo}
/>
)}
/>
<Route
path={routes.ZCASHD}
render={() => (
<Zcashd
info={info}
rpcConfig={rpcConfig}
refresh={this.doRefresh}
openServerSelectModal={this.openServerSelectModal}
/>
)}
/>
<Route
path={routes.LOADING}
render={() => (
<LoadingScreen
setRPCConfig={this.setRPCConfig}
rescanning={rescanning}
prevSyncId={prevSyncId}
setRescanning={this.setRescanning}
setInfo={this.setInfo}
openServerSelectModal={this.openServerSelectModal}
/>
)}
/>
</Switch>
</div>
</div>
</>
);
}
} | the_stack |
import { SiteBodyCreate } from '../model/siteBodyCreate';
import { SiteBodyUpdate } from '../model/siteBodyUpdate';
import { SiteContainerEntry } from '../model/siteContainerEntry';
import { SiteContainerPaging } from '../model/siteContainerPaging';
import { SiteEntry } from '../model/siteEntry';
import { SiteMemberEntry } from '../model/siteMemberEntry';
import { SiteMemberPaging } from '../model/siteMemberPaging';
import { SiteMembershipBodyCreate } from '../model/siteMembershipBodyCreate';
import { SiteMembershipBodyUpdate } from '../model/siteMembershipBodyUpdate';
import { SiteMembershipRequestBodyCreate } from '../model/siteMembershipRequestBodyCreate';
import { SiteMembershipRequestBodyUpdate } from '../model/siteMembershipRequestBodyUpdate';
import { SiteMembershipRequestEntry } from '../model/siteMembershipRequestEntry';
import { SiteMembershipRequestPaging } from '../model/siteMembershipRequestPaging';
import { SiteMembershipRequestWithPersonPaging } from '../model/siteMembershipRequestWithPersonPaging';
import { SitePaging } from '../model/sitePaging';
import { SiteRoleEntry } from '../model/siteRoleEntry';
import { SiteRolePaging } from '../model/siteRolePaging';
import { BaseApi } from './base.api';
import { throwIfNotDefined } from '../../../assert';
import { buildCollectionParam } from '../../../alfrescoApiClient';
import { SiteGroupEntry } from '../model/siteGroupEntry';
import { SiteGroupPaging } from '../model/siteGroupPaging';
/**
* Sites service.
* @module SitesApi
*/
export class SitesApi extends BaseApi {
/**
* Approve a site membership request
*
* Approve a site membership request.
*
* @param siteId The identifier of a site.
* @param inviteeId The invitee user name.
* @param opts Optional parameters
* @param opts.siteMembershipApprovalBody Accepting a request to join, optionally, allows assignment of a role to the user.
* @return Promise<{}>
*/
approveSiteMembershipRequest(siteId: string, inviteeId: string, opts?: any): Promise<any> {
throwIfNotDefined(siteId, 'siteId');
throwIfNotDefined(inviteeId, 'inviteeId');
opts = opts || {};
const postBody = opts['siteMembershipApprovalBody'];
const pathParams = {
'siteId': siteId, 'inviteeId': inviteeId
};
const queryParams = {
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/sites/{siteId}/site-membership-requests/{inviteeId}/approve', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts );
}
/**
* Create a site
*
* **Note:** this endpoint is available in Alfresco 5.2 and newer versions.
Creates a default site with the given details. Unless explicitly specified, the site id will be generated
from the site title. The site id must be unique and only contain alphanumeric and/or dash characters.
Note: the id of a site cannot be updated once the site has been created.
For example, to create a public site called \"Marketing\" the following body could be used:
JSON
{
\"title\": \"Marketing\",
\"visibility\": \"PUBLIC\"
}
The creation of the (surf) configuration files required by Share can be skipped via the **skipConfiguration** query parameter.
**Note:** if skipped then such a site will **not** work within Share.
The addition of the site to the user's site favorites can be skipped via the **skipAddToFavorites** query parameter.
The creator will be added as a member with Site Manager role.
When you create a site, a container called **documentLibrary** is created for you in the new site.
This container is the root folder for content stored in the site.
*
* @param siteBodyCreate The site details
* @param opts Optional parameters
* @param opts.skipConfiguration Flag to indicate whether the Share-specific (surf) configuration files for the site should not be created. (default to false)
* @param opts.skipAddToFavorites Flag to indicate whether the site should not be added to the user's site favorites. (default to false)
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<SiteEntry>
*/
createSite(siteBodyCreate: SiteBodyCreate, opts?: any): Promise<SiteEntry> {
throwIfNotDefined(siteBodyCreate, 'siteBodyCreate');
opts = opts || {};
const postBody = siteBodyCreate;
const pathParams = {
};
const queryParams = {
'skipConfiguration': opts['skipConfiguration'],
'skipAddToFavorites': opts['skipAddToFavorites'],
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/sites', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , SiteEntry);
}
/**
* Create a site membership
*
* Creates a site membership for person **personId** on site **siteId**.
You can set the **role** to one of four types:
* SiteConsumer
* SiteCollaborator
* SiteContributor
* SiteManager
**Note:** You can create more than one site membership by
specifying a list of people in the JSON body like this:
JSON
[
{
\"role\": \"SiteConsumer\",
\"id\": \"joe\"
},
{
\"role\": \"SiteConsumer\",
\"id\": \"fred\"
}
]
If you specify a list as input, then a paginated list rather than an entry is returned in the response body. For example:
JSON
{
\"list\": {
\"pagination\": {
\"count\": 2,
\"hasMoreItems\": false,
\"totalItems\": 2,
\"skipCount\": 0,
\"maxItems\": 100
},
\"entries\": [
{
\"entry\": {
...
}
},
{
\"entry\": {
...
}
}
]
}
}
*
* @param siteId The identifier of a site.
* @param siteMembershipBodyCreate The person to add and their role
* @param opts Optional parameters
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<SiteMemberEntry>
*/
createSiteMembership(siteId: string, siteMembershipBodyCreate: SiteMembershipBodyCreate, opts?: any): Promise<SiteMemberEntry> {
throwIfNotDefined(siteId, 'siteId');
throwIfNotDefined(siteMembershipBodyCreate, 'siteMembershipBodyCreate');
opts = opts || {};
const postBody = siteMembershipBodyCreate;
const pathParams = {
'siteId': siteId
};
const queryParams = {
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/sites/{siteId}/members', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , SiteMemberEntry);
}
/**
* Create a site membership request
*
* Create a site membership request for yourself on the site with the identifier of **id**, specified in the JSON body.
The result of the request differs depending on the type of site.
* For a **public** site, you join the site immediately as a SiteConsumer.
* For a **moderated** site, your request is added to the site membership request list. The request waits for approval from the Site Manager.
* You cannot request membership of a **private** site. Members are invited by the site administrator.
You can use the -me- string in place of <personId> to specify the currently authenticated user.
**Note:** You can create site membership requests for more than one site by
specifying a list of sites in the JSON body like this:
JSON
[
{
\"message\": \"Please can you add me\",
\"id\": \"test-site-1\",
\"title\": \"Request for test site 1\",
},
{
\"message\": \"Please can you add me\",
\"id\": \"test-site-2\",
\"title\": \"Request for test site 2\",
}
]
If you specify a list as input, then a paginated list rather than an entry is returned in the response body. For example:
JSON
{
\"list\": {
\"pagination\": {
\"count\": 2,
\"hasMoreItems\": false,
\"totalItems\": 2,
\"skipCount\": 0,
\"maxItems\": 100
},
\"entries\": [
{
\"entry\": {
...
}
},
{
\"entry\": {
...
}
}
]
}
}
*
* @param personId The identifier of a person.
* @param siteMembershipRequestBodyCreate Site membership request details
* @param opts Optional parameters
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<SiteMembershipRequestEntry>
*/
createSiteMembershipRequestForPerson(personId: string, siteMembershipRequestBodyCreate: SiteMembershipRequestBodyCreate, opts?: any): Promise<SiteMembershipRequestEntry> {
throwIfNotDefined(personId, 'personId');
throwIfNotDefined(siteMembershipRequestBodyCreate, 'siteMembershipRequestBodyCreate');
opts = opts || {};
const postBody = siteMembershipRequestBodyCreate;
const pathParams = {
'personId': personId
};
const queryParams = {
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/people/{personId}/site-membership-requests', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , SiteMembershipRequestEntry);
}
/**
* Delete a site
*
* **Note:** this endpoint is available in Alfresco 5.2 and newer versions.
Deletes the site with **siteId**.
*
* @param siteId The identifier of a site.
* @param opts Optional parameters
* @param opts.permanent Flag to indicate whether the site should be permanently deleted i.e. bypass the trashcan. (default to false)
* @return Promise<{}>
*/
deleteSite(siteId: string, opts?: any): Promise<any> {
throwIfNotDefined(siteId, 'siteId');
opts = opts || {};
const postBody: null = null;
const pathParams = {
'siteId': siteId
};
const queryParams = {
'permanent': opts['permanent']
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/sites/{siteId}', 'DELETE',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts );
}
/**
* Delete a site membership
*
* Deletes person **personId** as a member of site **siteId**.
You can use the -me- string in place of <personId> to specify the currently authenticated user.
*
* @param siteId The identifier of a site.
* @param personId The identifier of a person.
* @return Promise<{}>
*/
deleteSiteMembership(siteId: string, personId: string): Promise<any> {
throwIfNotDefined(siteId, 'siteId');
throwIfNotDefined(personId, 'personId');
const postBody: null = null;
const pathParams = {
'siteId': siteId, 'personId': personId
};
const queryParams = {
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/sites/{siteId}/members/{personId}', 'DELETE',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts );
}
/**
* Delete a site membership
*
* Deletes person **personId** as a member of site **siteId**.
You can use the -me- string in place of <personId> to specify the currently authenticated user.
*
* @param personId The identifier of a person.
* @param siteId The identifier of a site.
* @return Promise<{}>
*/
deleteSiteMembershipForPerson(personId: string, siteId: string): Promise<any> {
throwIfNotDefined(personId, 'personId');
throwIfNotDefined(siteId, 'siteId');
const postBody: null = null;
const pathParams = {
'personId': personId, 'siteId': siteId
};
const queryParams = {
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/people/{personId}/sites/{siteId}', 'DELETE',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts );
}
/**
* Delete a site membership request
*
* Deletes the site membership request to site **siteId** for person **personId**.
You can use the -me- string in place of <personId> to specify the currently authenticated user.
*
* @param personId The identifier of a person.
* @param siteId The identifier of a site.
* @return Promise<{}>
*/
deleteSiteMembershipRequestForPerson(personId: string, siteId: string): Promise<any> {
throwIfNotDefined(personId, 'personId');
throwIfNotDefined(siteId, 'siteId');
const postBody: null = null;
const pathParams = {
'personId': personId, 'siteId': siteId
};
const queryParams = {
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/people/{personId}/site-membership-requests/{siteId}', 'DELETE',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts );
}
/**
* Get a site
*
* Gets information for site **siteId**.
You can use the **relations** parameter to include one or more related
entities in a single response and so reduce network traffic.
The entity types in Alfresco are organized in a tree structure.
The **sites** entity has two children, **containers** and **members**.
The following relations parameter returns all the container and member
objects related to the site **siteId**:
containers,members
*
* @param siteId The identifier of a site.
* @param opts Optional parameters
* @param opts.relations Use the relations parameter to include one or more related entities in a single response.
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<SiteEntry>
*/
getSite(siteId: string, opts?: any): Promise<SiteEntry> {
throwIfNotDefined(siteId, 'siteId');
opts = opts || {};
const postBody: null = null;
const pathParams = {
'siteId': siteId
};
const queryParams = {
'relations': buildCollectionParam(opts['relations'], 'csv'),
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/sites/{siteId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , SiteEntry);
}
/**
* Get a site container
*
* Gets information on the container **containerId** in site **siteId**.
*
* @param siteId The identifier of a site.
* @param containerId The unique identifier of a site container.
* @param opts Optional parameters
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<SiteContainerEntry>
*/
getSiteContainer(siteId: string, containerId: string, opts?: any): Promise<SiteContainerEntry> {
throwIfNotDefined(siteId, 'siteId');
throwIfNotDefined(containerId, 'containerId');
opts = opts || {};
const postBody: null = null;
const pathParams = {
'siteId': siteId, 'containerId': containerId
};
const queryParams = {
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/sites/{siteId}/containers/{containerId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , SiteContainerEntry);
}
/**
* Get a site membership
*
* Gets site membership information for person **personId** on site **siteId**.
You can use the -me- string in place of <personId> to specify the currently authenticated user.
*
* @param siteId The identifier of a site.
* @param personId The identifier of a person.
* @param opts Optional parameters
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<SiteMemberEntry>
*/
getSiteMembership(siteId: string, personId: string, opts?: any): Promise<SiteMemberEntry> {
throwIfNotDefined(siteId, 'siteId');
throwIfNotDefined(personId, 'personId');
opts = opts || {};
const postBody: null = null;
const pathParams = {
'siteId': siteId, 'personId': personId
};
const queryParams = {
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/sites/{siteId}/members/{personId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , SiteMemberEntry);
}
/**
* Get a site membership
*
* Gets site membership information for person **personId** on site **siteId**.
You can use the -me- string in place of <personId> to specify the currently authenticated user.
*
* @param personId The identifier of a person.
* @param siteId The identifier of a site.
* @return Promise<SiteRoleEntry>
*/
getSiteMembershipForPerson(personId: string, siteId: string): Promise<SiteRoleEntry> {
throwIfNotDefined(personId, 'personId');
throwIfNotDefined(siteId, 'siteId');
const postBody: null = null;
const pathParams = {
'personId': personId, 'siteId': siteId
};
const queryParams = {
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/people/{personId}/sites/{siteId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , SiteRoleEntry);
}
/**
* Get a site membership request
*
* Gets the site membership request for site **siteId** for person **personId**, if one exists.
You can use the -me- string in place of <personId> to specify the currently authenticated user.
*
* @param personId The identifier of a person.
* @param siteId The identifier of a site.
* @param opts Optional parameters
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<SiteMembershipRequestEntry>
*/
getSiteMembershipRequestForPerson(personId: string, siteId: string, opts?: any): Promise<SiteMembershipRequestEntry> {
throwIfNotDefined(personId, 'personId');
throwIfNotDefined(siteId, 'siteId');
opts = opts || {};
const postBody: null = null;
const pathParams = {
'personId': personId, 'siteId': siteId
};
const queryParams = {
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/people/{personId}/site-membership-requests/{siteId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , SiteMembershipRequestEntry);
}
/**
* Get site membership requests
*
* Get the list of site membership requests the user can action.
You can use the **where** parameter to filter the returned site membership requests by **siteId**. For example:
(siteId=mySite)
The **where** parameter can also be used to filter by ***personId***. For example:
where=(personId=person)
This may be combined with the siteId filter, as shown below:
where=(siteId=mySite AND personId=person))
*
* @param opts Optional parameters
* @param opts.skipCount The number of entities that exist in the collection before those included in this list.
If not supplied then the default value is 0.
(default to 0)
* @param opts.maxItems The maximum number of items to return in the list.
If not supplied then the default value is 100.
(default to 100)
* @param opts.where A string to restrict the returned objects by using a predicate.
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<SiteMembershipRequestWithPersonPaging>
*/
getSiteMembershipRequests(opts?: any): Promise<SiteMembershipRequestWithPersonPaging> {
opts = opts || {};
const postBody: null = null;
const pathParams = {
};
const queryParams = {
'skipCount': opts['skipCount'],
'maxItems': opts['maxItems'],
'where': opts['where'],
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/site-membership-requests', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , SiteMembershipRequestWithPersonPaging);
}
/**
* List site containers
*
* Gets a list of containers for the site **siteId**.
*
* @param siteId The identifier of a site.
* @param opts Optional parameters
* @param opts.skipCount The number of entities that exist in the collection before those included in this list.
If not supplied then the default value is 0.
(default to 0)
* @param opts.maxItems The maximum number of items to return in the list.
If not supplied then the default value is 100.
(default to 100)
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<SiteContainerPaging>
*/
listSiteContainers(siteId: string, opts?: any): Promise<SiteContainerPaging> {
throwIfNotDefined(siteId, 'siteId');
opts = opts || {};
const postBody: null = null;
const pathParams = {
'siteId': siteId
};
const queryParams = {
'skipCount': opts['skipCount'],
'maxItems': opts['maxItems'],
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/sites/{siteId}/containers', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , SiteContainerPaging);
}
/**
* List site membership requests
*
* Gets a list of the current site membership requests for person **personId**.
You can use the -me- string in place of <personId> to specify the currently authenticated user.
*
* @param personId The identifier of a person.
* @param opts Optional parameters
* @param opts.skipCount The number of entities that exist in the collection before those included in this list.
If not supplied then the default value is 0.
(default to 0)
* @param opts.maxItems The maximum number of items to return in the list.
If not supplied then the default value is 100.
(default to 100)
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<SiteMembershipRequestPaging>
*/
listSiteMembershipRequestsForPerson(personId: string, opts?: any): Promise<SiteMembershipRequestPaging> {
throwIfNotDefined(personId, 'personId');
opts = opts || {};
const postBody: null = null;
const pathParams = {
'personId': personId
};
const queryParams = {
'skipCount': opts['skipCount'],
'maxItems': opts['maxItems'],
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/people/{personId}/site-membership-requests', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , SiteMembershipRequestPaging);
}
/**
* List site memberships
*
* Gets a list of site memberships for site **siteId**.
*
* @param siteId The identifier of a site.
* @param opts Optional parameters
* @param opts.skipCount The number of entities that exist in the collection before those included in this list.
If not supplied then the default value is 0.
(default to 0)
* @param opts.maxItems The maximum number of items to return in the list.
If not supplied then the default value is 100.
(default to 100)
* @param opts.fields A list of field names.
**Note:** where class filter is available in Alfresco 7.0.0 and newer versions.
Optionally filter the list.
* where=(isMemberOfGroup=false|true)
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<SiteMemberPaging>
*/
listSiteMemberships(siteId: string, opts?: any): Promise<SiteMemberPaging> {
throwIfNotDefined(siteId, 'siteId');
opts = opts || {};
const postBody: null = null;
const pathParams = {
'siteId': siteId
};
const queryParams = {
'skipCount': opts['skipCount'],
'maxItems': opts['maxItems'],
'where': opts['where'],
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/sites/{siteId}/members', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , SiteMemberPaging);
}
/**
* List site memberships
*
* Gets a list of site membership information for person **personId**.
You can use the -me- string in place of <personId> to specify the currently authenticated user.
You can use the **where** parameter to filter the returned sites by **visibility** or site **preset**.
Example to filter by **visibility**, use any one of:
(visibility='PRIVATE')
(visibility='PUBLIC')
(visibility='MODERATED')
Example to filter by site **preset**:
(preset='site-dashboard')
The default sort order for the returned list is for sites to be sorted by ascending title.
You can override the default by using the **orderBy** parameter. You can specify one or more of the following fields in the **orderBy** parameter:
* id
* title
* role
*
* @param personId The identifier of a person.
* @param opts Optional parameters
* @param opts.skipCount The number of entities that exist in the collection before those included in this list.
If not supplied then the default value is 0.
(default to 0)
* @param opts.maxItems The maximum number of items to return in the list.
If not supplied then the default value is 100.
(default to 100)
* @param opts.orderBy A string to control the order of the entities returned in a list. You can use the **orderBy** parameter to
sort the list by one or more fields.
Each field has a default sort order, which is normally ascending order. Read the API method implementation notes
above to check if any fields used in this method have a descending default search order.
To sort the entities in a specific order, you can use the **ASC** and **DESC** keywords for any field.
* @param opts.relations Use the relations parameter to include one or more related entities in a single response.
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @param opts.where A string to restrict the returned objects by using a predicate.
* @return Promise<SiteRolePaging>
*/
listSiteMembershipsForPerson(personId: string, opts?: any): Promise<SiteRolePaging> {
throwIfNotDefined(personId, 'personId');
opts = opts || {};
const postBody: null = null;
const pathParams = {
'personId': personId
};
const queryParams = {
'skipCount': opts['skipCount'],
'maxItems': opts['maxItems'],
'orderBy': buildCollectionParam(opts['orderBy'], 'csv'),
'relations': buildCollectionParam(opts['relations'], 'csv'),
'fields': buildCollectionParam(opts['fields'], 'csv'),
'where': opts['where']
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/people/{personId}/sites', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , SiteRolePaging);
}
/**
* List sites
*
* Gets a list of sites in this repository.
You can use the **where** parameter to filter the returned sites by **visibility** or site **preset**.
Example to filter by **visibility**, use any one of:
(visibility='PRIVATE')
(visibility='PUBLIC')
(visibility='MODERATED')
Example to filter by site **preset**:
(preset='site-dashboard')
The default sort order for the returned list is for sites to be sorted by ascending title.
You can override the default by using the **orderBy** parameter. You can specify one or more of the following fields in the **orderBy** parameter:
* id
* title
* description
You can use the **relations** parameter to include one or more related
entities in a single response and so reduce network traffic.
The entity types in Alfresco are organized in a tree structure.
The **sites** entity has two children, **containers** and **members**.
The following relations parameter returns all the container and member
objects related to each site:
containers,members
*
* @param opts Optional parameters
* @param opts.skipCount The number of entities that exist in the collection before those included in this list.
If not supplied then the default value is 0.
(default to 0)
* @param opts.maxItems The maximum number of items to return in the list.
If not supplied then the default value is 100.
(default to 100)
* @param opts.orderBy A string to control the order of the entities returned in a list. You can use the **orderBy** parameter to
sort the list by one or more fields.
Each field has a default sort order, which is normally ascending order. Read the API method implementation notes
above to check if any fields used in this method have a descending default search order.
To sort the entities in a specific order, you can use the **ASC** and **DESC** keywords for any field.
* @param opts.relations Use the relations parameter to include one or more related entities in a single response.
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @param opts.where A string to restrict the returned objects by using a predicate.
* @return Promise<SitePaging>
*/
listSites(opts?: any): Promise<SitePaging> {
opts = opts || {};
const postBody: null = null;
const pathParams = {
};
const queryParams = {
'skipCount': opts['skipCount'],
'maxItems': opts['maxItems'],
'orderBy': buildCollectionParam(opts['orderBy'], 'csv'),
'relations': buildCollectionParam(opts['relations'], 'csv'),
'fields': buildCollectionParam(opts['fields'], 'csv'),
'where': opts['where']
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/sites', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , SitePaging);
}
/**
* Reject a site membership request
*
* Reject a site membership request.
*
* @param siteId The identifier of a site.
* @param inviteeId The invitee user name.
* @param opts Optional parameters
* @param opts.siteMembershipRejectionBody Rejecting a request to join, optionally, allows the inclusion of comment.
* @return Promise<{}>
*/
rejectSiteMembershipRequest(siteId: string, inviteeId: string, opts?: any): Promise<any> {
throwIfNotDefined(siteId, 'siteId');
throwIfNotDefined(inviteeId, 'inviteeId');
opts = opts || {};
const postBody = opts['siteMembershipRejectionBody'];
const pathParams = {
'siteId': siteId, 'inviteeId': inviteeId
};
const queryParams = {
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/sites/{siteId}/site-membership-requests/{inviteeId}/reject', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts );
}
/**
* Update a site
*
* **Note:** this endpoint is available in Alfresco 5.2 and newer versions.
Update the details for the given site **siteId**. Site Manager or otherwise a
(site) admin can update title, description or visibility.
Note: the id of a site cannot be updated once the site has been created.
*
* @param siteId The identifier of a site.
* @param siteBodyUpdate The site information to update.
* @param opts Optional parameters
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<SiteEntry>
*/
updateSite(siteId: string, siteBodyUpdate: SiteBodyUpdate, opts?: any): Promise<SiteEntry> {
throwIfNotDefined(siteId, 'siteId');
throwIfNotDefined(siteBodyUpdate, 'siteBodyUpdate');
opts = opts || {};
const postBody = siteBodyUpdate;
const pathParams = {
'siteId': siteId
};
const queryParams = {
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/sites/{siteId}', 'PUT',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , SiteEntry);
}
/**
* Update a site membership
*
* Update the membership of person **personId** in site **siteId**.
You can use the -me- string in place of <personId> to specify the currently authenticated user.
You can set the **role** to one of four types:
* SiteConsumer
* SiteCollaborator
* SiteContributor
* SiteManager
*
* @param siteId The identifier of a site.
* @param personId The identifier of a person.
* @param siteMembershipBodyUpdate The persons new role
* @param opts Optional parameters
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<SiteMemberEntry>
*/
updateSiteMembership(siteId: string, personId: string, siteMembershipBodyUpdate: SiteMembershipBodyUpdate, opts?: any): Promise<SiteMemberEntry> {
throwIfNotDefined(siteId, 'siteId');
throwIfNotDefined(personId, 'personId');
throwIfNotDefined(siteMembershipBodyUpdate, 'siteMembershipBodyUpdate');
opts = opts || {};
const postBody = siteMembershipBodyUpdate;
const pathParams = {
'siteId': siteId, 'personId': personId
};
const queryParams = {
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/sites/{siteId}/members/{personId}', 'PUT',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , SiteMemberEntry);
}
/**
* Update a site membership request
*
* Updates the message for the site membership request to site **siteId** for person **personId**.
You can use the -me- string in place of <personId> to specify the currently authenticated user.
*
* @param personId The identifier of a person.
* @param siteId The identifier of a site.
* @param siteMembershipRequestBodyUpdate The new message to display
* @param opts Optional parameters
* @param opts.fields A list of field names.
You can use this parameter to restrict the fields
returned within a response if, for example, you want to save on overall bandwidth.
The list applies to a returned individual
entity or entries within a collection.
If the API method also supports the **include**
parameter, then the fields specified in the **include**
parameter are returned in addition to those specified in the **fields** parameter.
* @return Promise<SiteMembershipRequestEntry>
*/
updateSiteMembershipRequestForPerson(personId: string, siteId: string, siteMembershipRequestBodyUpdate: SiteMembershipRequestBodyUpdate, opts?: any): Promise<SiteMembershipRequestEntry> {
throwIfNotDefined(personId, 'personId');
throwIfNotDefined(siteId, 'siteId');
throwIfNotDefined(siteMembershipRequestBodyUpdate, 'siteMembershipRequestBodyUpdate');
opts = opts || {};
const postBody = siteMembershipRequestBodyUpdate;
const pathParams = {
'personId': personId, 'siteId': siteId
};
const queryParams = {
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/people/{personId}/site-membership-requests/{siteId}', 'PUT',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , SiteMembershipRequestEntry);
}
/**
* Create a site membership for group
*
* Creates a site membership for group **groupId** on site **siteId**.
**Note:** this endpoint is available in Alfresco 7.0.0 and newer versions.
You can set the **role** to one of four types:
* SiteConsumer
* SiteCollaborator
* SiteContributor
* SiteManager
**Note:** You can create more than one site membership by
specifying a list of group in the JSON body like this:
```JSON
[
{
"role": "SiteConsumer",
"id": "authorityId"
},
{
"role": "SiteConsumer",
"id": "authorityId"
}
]
```
If you specify a list as input, then a paginated list rather than an entry is returned in the response body. For example:
```JSON
{
"list": {
"pagination": {
"count": 2,
"hasMoreItems": false,
"totalItems": 2,
"skipCount": 0,
"maxItems": 100
},
"entries": [
{
"entry": {
...
}
},
{
"entry": {
...
}
}
]
}
}
*
* @param siteId The identifier of a site.
* @param siteMembershipBodyCreate The group to add and it role
* @param opts Optional parameters
* @return Promise<SiteGroupEntry>
*/
createSiteGroupMembership(siteId: string, siteMembershipBodyCreate: SiteMembershipBodyCreate, opts?: any): Promise<SiteGroupEntry> {
throwIfNotDefined(siteId, 'siteId');
throwIfNotDefined(siteMembershipBodyCreate, 'siteMembershipBodyCreate');
opts = opts || {};
const postBody = siteMembershipBodyCreate;
const pathParams = {
'siteId': siteId
};
const queryParams = {
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {};
const formParams = {};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/sites/{siteId}/group-members', 'POST',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts, SiteGroupEntry);
}
/**
* List group membership for site
*
* Gets a list of group membership for site **siteId**.
**Note:** this endpoint is available in Alfresco 7.0.0 and newer versions.
* @param siteId The identifier of a site.
* @param opts Optional parameters
* @param opts.skipCount The number of entities that exist in the collection before those included in this list.
If not supplied then the default value is 0.
(default to 0)
* @param opts.maxItems The maximum number of items to return in the list.
If not supplied then the default value is 100.
(default to 100)
* @return Promise<SiteGroupPaging>
*/
listSiteGroups(siteId: string, opts?: any): Promise<SiteGroupPaging> {
throwIfNotDefined(siteId, 'siteId');
opts = opts || {};
const postBody: null = null;
const pathParams = {
'siteId': siteId
};
const queryParams = {
'skipCount': opts['skipCount'],
'maxItems': opts['maxItems'],
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/sites/{siteId}/group-members', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , SiteGroupPaging);
}
/**
* Get information about site membership of group
**Note:** this endpoint is available in Alfresco 7.0.0 and newer versions.
Gets site membership information for group **groupId** on site **siteId**.
*
* @param siteId The identifier of a site.
* @param groupId The authorityId of a group.
* @param opts Optional parameters
* @return Promise<SiteGroupEntry>
*/
getSiteGroupMembership(siteId: string, groupId: string, opts?: any): Promise<SiteGroupEntry> {
throwIfNotDefined(siteId, 'siteId');
throwIfNotDefined(groupId, 'groupId');
opts = opts || {};
const postBody: null = null;
const pathParams = {
'siteId': siteId,
'groupId': groupId
};
const queryParams = {
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/sites/{siteId}/group-members/{groupId}', 'GET',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , SiteGroupEntry);
}
/**
* Update site membership of group
*
* Update the membership of person **groupId** in site **siteId**.
**Note:** this endpoint is available in Alfresco 7.0.0 and newer versions.
You can set the **role** to one of four types:
* SiteConsumer
* SiteCollaborator
* SiteContributor
* SiteManager
*
* @param siteId The identifier of a site.
* @param groupId The authorityId of a group.
* @param siteMembershipBodyUpdate The group new role
* @param opts Optional parameters
* @return Promise<SiteGroupEntry>
*/
updateSiteGroupMembership(siteId: string, groupId: string, siteMembershipBodyUpdate: SiteMembershipBodyUpdate, opts?: any): Promise<SiteGroupEntry> {
throwIfNotDefined(siteId, 'siteId');
throwIfNotDefined(groupId, 'groupId');
throwIfNotDefined(siteMembershipBodyUpdate, 'siteMembershipBodyUpdate');
opts = opts || {};
const postBody = siteMembershipBodyUpdate;
const pathParams = {
'siteId': siteId,
'groupId': groupId
};
const queryParams = {
'fields': buildCollectionParam(opts['fields'], 'csv')
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/sites/{siteId}/group-members/{groupId}', 'PUT',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts , SiteGroupEntry);
}
/**
* Delete a group membership for site
*
* Deletes group **groupId** as a member of site **siteId**.
* @param siteId The identifier of a site.
* @param groupId The authorityId of a group.
* @return Promise<{}>
*/
deleteSiteGroupMembership(siteId: string, groupId: string): Promise<any> {
throwIfNotDefined(siteId, 'siteId');
throwIfNotDefined(groupId, 'groupId');
const postBody: null = null;
const pathParams = {
'siteId': siteId,
'groupId': groupId
};
const queryParams = {
};
const headerParams = {
};
const formParams = {
};
const contentTypes = ['application/json'];
const accepts = ['application/json'];
return this.apiClient.callApi(
'/sites/{siteId}/group-members/{groupId}', 'DELETE',
pathParams, queryParams, headerParams, formParams, postBody,
contentTypes, accepts);
}
} | the_stack |
import {
MapEnv,
StyleSetEvaluator,
Value,
ValueMap
} from "@here/harp-datasource-protocol/index-decoder";
import { TileKey } from "@here/harp-geoutils";
import { assert, ILogger, LoggerManager } from "@here/harp-utils";
import * as Long from "long";
import { ShapeUtils, Vector2, Vector3 } from "three";
import { DataAdapter } from "../../DataAdapter";
import { DecodeInfo } from "../../DecodeInfo";
import { IGeometryProcessor, ILineGeometry, IPolygonGeometry } from "../../IGeometryProcessor";
import {
ComposedDataFilter,
OmvFeatureFilter,
OmvFeatureModifier,
OmvGenericFeatureFilter,
OmvGenericFeatureModifier
} from "../../OmvDataFilter";
import {
FeatureModifierId,
OmvDecoderOptions,
OmvFeatureFilterDescription,
OmvGeometryType
} from "../../OmvDecoderDefs";
import { OmvPoliticalViewFeatureModifier } from "../../OmvPoliticalViewFeatureModifier";
import { isArrayBufferLike } from "../../OmvUtils";
import { StyleSetDataFilter } from "../../StyleSetDataFilter";
import {
FeatureAttributes,
GeometryCommands,
isClosePathCommand,
isLineToCommand,
isMoveToCommand,
OmvVisitor,
visitOmv
} from "./OmvData";
import { com } from "./proto/vector_tile";
const propertyCategories = [
"stringValue",
"floatValue",
"doubleValue",
"intValue",
"uintValue",
"sintValue",
"boolValue"
];
const logger = LoggerManager.instance.create("OmvDataAdapter", { enabled: false });
function simplifiedValue(value: com.mapbox.pb.Tile.IValue): Value {
const hasOwnProperty = Object.prototype.hasOwnProperty;
for (const category of propertyCategories) {
if (hasOwnProperty.call(value, category)) {
const v = value[category as keyof com.mapbox.pb.Tile.IValue];
if (v === undefined) {
throw new Error("unpexted undefined value");
}
return Long.isLong(v) ? (v as any).toNumber() : v;
}
}
throw new Error("not happening");
}
function decodeFeatureId(
feature: com.mapbox.pb.Tile.IFeature,
properties: ValueMap,
logger?: ILogger
): number | string | undefined {
if (properties.id !== undefined && properties.id !== null) {
return properties.id as number | string;
}
if (feature.hasOwnProperty("id")) {
const id = feature.id;
if (typeof id === "number") {
return id;
} else if (id) {
if (logger !== undefined && id.greaterThan(Number.MAX_SAFE_INTEGER)) {
logger.error(
"Invalid ID: Larger than largest available Number in feature: ",
feature
);
}
return id.toNumber();
}
}
return undefined;
}
function readAttributes(
layer: com.mapbox.pb.Tile.ILayer,
feature: com.mapbox.pb.Tile.IFeature
): ValueMap {
const attrs = new FeatureAttributes();
const attributes: ValueMap = {};
attrs.accept(layer, feature, {
visitAttribute: (name, value) => {
attributes[name] = simplifiedValue(value);
return true;
}
});
return attributes;
}
export function asGeometryType(feature: com.mapbox.pb.Tile.IFeature | undefined): OmvGeometryType {
if (feature === undefined) {
return OmvGeometryType.UNKNOWN;
}
switch (feature.type) {
case com.mapbox.pb.Tile.GeomType.UNKNOWN:
return OmvGeometryType.UNKNOWN;
case com.mapbox.pb.Tile.GeomType.POINT:
return OmvGeometryType.POINT;
case com.mapbox.pb.Tile.GeomType.LINESTRING:
return OmvGeometryType.LINESTRING;
case com.mapbox.pb.Tile.GeomType.POLYGON:
return OmvGeometryType.POLYGON;
default:
return OmvGeometryType.UNKNOWN;
} // switch
}
// Ensures ring winding follows Mapbox Vector Tile specification: outer rings must be clockwise,
// inner rings counter-clockwise.
// See https://docs.mapbox.com/vector-tiles/specification/
function checkWinding(multipolygon: IPolygonGeometry[]) {
const firstPolygon = multipolygon[0];
if (firstPolygon === undefined || firstPolygon.rings.length === 0) {
return;
}
// Opposite sign to ShapeUtils.isClockWise, since webMercator tile space has top-left origin.
// For example:
// Given the ring = [(1,2), (2,2), (2,1), (1,1)]
// ShapeUtils.area(ring) > 0 -> false
// ShapeUtils.isClockWise(ring) -> true
// ^
// | 1,2 -> 2,2
// | |
// | 1,1 <- 2,1
// |_______________>
//
// Tile space axis
// ______________>
// | 1,1 <- 2,1
// | |
// | 1,2 -> 2,2
// V
const isOuterRingClockWise = ShapeUtils.area(firstPolygon.rings[0]) > 0;
if (!isOuterRingClockWise) {
for (const polygon of multipolygon) {
for (const ring of polygon.rings) {
ring.reverse();
}
}
}
}
function roundUpCoordinates(coordinates: Vector2[], layerExtents: number) {
coordinates.forEach(p => {
if (p.x === layerExtents - 1) {
p.x = layerExtents;
}
});
}
function roundUpPolygonCoordinates(geometry: IPolygonGeometry[], layerExtents: number) {
geometry.forEach(polygon => polygon.rings.forEach(r => roundUpCoordinates(r, layerExtents)));
}
function roundUpLineCoordinates(geometry: ILineGeometry[], layerExtents: number) {
geometry.forEach(line => roundUpCoordinates(line.positions, layerExtents));
}
function createFeatureModifier(
filterDescription: OmvFeatureFilterDescription,
featureModifierId?: FeatureModifierId
): OmvFeatureModifier {
switch (featureModifierId) {
case FeatureModifierId.default:
return new OmvGenericFeatureModifier(filterDescription);
default:
assert(!"Unrecognized feature modifier id, using default!");
return new OmvGenericFeatureModifier(filterDescription);
}
}
/**
* The class `OmvDataAdapter` converts OMV protobuf geo data
* to geometries for the given `IGeometryProcessor`.
*/
export class OmvDataAdapter implements DataAdapter, OmvVisitor {
private readonly m_geometryCommands = new GeometryCommands();
private m_tileKey!: TileKey;
private m_layer!: com.mapbox.pb.Tile.ILayer;
private m_dataFilter?: OmvFeatureFilter;
private m_featureModifiers?: OmvFeatureModifier[];
private m_processor!: IGeometryProcessor;
private m_roundUpCoordinatesIfNeeded: boolean = false;
/**
* The [[OmvFeatureFilter]] used to filter features.
*/
get dataFilter(): OmvFeatureFilter | undefined {
return this.m_dataFilter;
}
/**
* Configures the OMV adapter.
*
* @param options - Configuration options.
* @param styleSetEvaluator - Style set evaluator instance, used for filtering.
*/
configure(options: OmvDecoderOptions, styleSetEvaluator: StyleSetEvaluator) {
if (options.filterDescription !== undefined) {
if (options.filterDescription !== null) {
// TODO: Feature modifier is always used only with feature filter.
// At best the filtering feature should be excluded from other feature
// modifiers and be performed solely via OmvGenericFeature modifier or filter.
const filterDescription = options.filterDescription;
const featureModifiersIds = options.featureModifiers;
// Create new filter from description.
this.m_dataFilter = new OmvGenericFeatureFilter(filterDescription);
// Create feature modifiers.
const featureModifiers: OmvFeatureModifier[] = [];
if (featureModifiersIds !== undefined) {
featureModifiersIds.forEach(fmId => {
featureModifiers.push(createFeatureModifier(filterDescription, fmId));
});
} else {
featureModifiers.push(
createFeatureModifier(filterDescription, FeatureModifierId.default)
);
}
this.m_featureModifiers = featureModifiers;
} else {
// null is the signal to clear the filter/modifier
this.m_dataFilter = undefined;
this.m_featureModifiers = undefined;
}
const styleSetDataFilter = new StyleSetDataFilter(styleSetEvaluator);
this.m_dataFilter = this.m_dataFilter
? new ComposedDataFilter([styleSetDataFilter, this.m_dataFilter])
: styleSetDataFilter;
}
if (options.politicalView !== undefined) {
const politicalView = options.politicalView;
let featureModifiers = this.m_featureModifiers;
// Remove existing political view modifiers, this actually setups default,
// commonly accepted point of view - without feature modifier.
if (featureModifiers) {
featureModifiers = featureModifiers.filter(
fm => !(fm instanceof OmvPoliticalViewFeatureModifier)
);
}
// If political view is indeed requested append feature modifier at the end of list.
if (politicalView.length !== 0) {
assert(
politicalView.length === 2,
"The political view must be specified as two letters ISO 3166-1 standard!"
);
const povFeatureModifier = new OmvPoliticalViewFeatureModifier(politicalView);
if (featureModifiers) {
featureModifiers.push(povFeatureModifier);
} else {
featureModifiers = [povFeatureModifier];
}
}
// Reset modifiers if nothing was added.
this.m_featureModifiers =
featureModifiers && featureModifiers.length > 0 ? featureModifiers : undefined;
}
this.m_roundUpCoordinatesIfNeeded = options.roundUpCoordinatesIfNeeded ?? false;
}
/**
* @override
*/
canProcess(data: ArrayBufferLike | {}): boolean {
return isArrayBufferLike(data);
}
/**
* @override
*/
process(data: ArrayBufferLike, decodeInfo: DecodeInfo, geometryProcessor: IGeometryProcessor) {
const { tileKey } = decodeInfo;
const payload = new Uint8Array(data);
const proto = com.mapbox.pb.Tile.decode(payload);
this.m_tileKey = tileKey;
this.m_processor = geometryProcessor;
visitOmv(proto, this);
}
/**
* Visits the OMV layer.
*
* @param layer - The OMV layer to process.
*/
visitLayer(layer: com.mapbox.pb.Tile.ILayer): boolean {
this.m_layer = layer;
const storageLevel = this.m_tileKey.level;
const layerName = layer.name;
if (
this.m_dataFilter !== undefined &&
!this.m_dataFilter.wantsLayer(layerName, storageLevel)
) {
return false;
}
return true;
}
/**
* Visits point features.
*
* @param feature - The OMV point features to process.
*/
visitPointFeature(feature: com.mapbox.pb.Tile.IFeature): void {
if (feature.geometry === undefined) {
return;
}
// Pass feature modifier method to processFeature if there's any modifier. Get it from any
// modifier, processFeature will later apply it to all using Function.apply().
const modifierFunc = this.m_featureModifiers?.[0].doProcessPointFeature;
const properties = this.filterAndModifyFeature(
feature,
this.m_dataFilter?.wantsPointFeature,
modifierFunc
);
if (!properties) {
return;
}
const layerName = this.m_layer.name;
const layerExtents = this.m_layer.extent ?? 4096;
const geometry: Vector3[] = [];
this.m_geometryCommands.accept(feature.geometry, {
type: "Point",
visitCommand: command => {
if (isMoveToCommand(command)) {
geometry.push(new Vector3(command.position.x, command.position.y, 0));
}
}
});
if (geometry.length === 0) {
return;
}
this.m_processor.processPointFeature(
layerName,
layerExtents,
geometry,
properties,
decodeFeatureId(feature, properties, logger)
);
}
/**
* Visits the line features.
*
* @param feature - The line features to process.
*/
visitLineFeature(feature: com.mapbox.pb.Tile.IFeature): void {
if (feature.geometry === undefined) {
return;
}
// Pass feature modifier method to processFeature if there's any modifier. Get it from any
// modifier, processFeature will later apply it to all using Function.apply().
const modifierFunc = this.m_featureModifiers?.[0].doProcessLineFeature;
const properties = this.filterAndModifyFeature(
feature,
this.m_dataFilter?.wantsLineFeature,
modifierFunc
);
if (!properties) {
return;
}
const layerName = this.m_layer.name;
const layerExtents = this.m_layer.extent ?? 4096;
const geometry: ILineGeometry[] = [];
let positions: Vector2[];
this.m_geometryCommands.accept(feature.geometry, {
type: "Line",
visitCommand: command => {
if (isMoveToCommand(command)) {
positions = [command.position];
geometry.push({ positions });
} else if (isLineToCommand(command)) {
positions.push(command.position);
}
}
});
if (geometry.length === 0) {
return;
}
if (this.mustRoundUpCoordinates) {
roundUpLineCoordinates(geometry, layerExtents);
}
this.m_processor.processLineFeature(
layerName,
layerExtents,
geometry,
properties,
decodeFeatureId(feature, properties, logger)
);
}
/**
* Visits the polygon features.
*
* @param feature - The polygon features to process.
*/
visitPolygonFeature(feature: com.mapbox.pb.Tile.IFeature): void {
if (feature.geometry === undefined) {
return;
}
// Pass feature modifier method to processFeature if there's any modifier. Get it from any
// modifier, processFeature will later apply it to all using Function.apply().
const modifierFunc = this.m_featureModifiers?.[0].doProcessPolygonFeature;
const properties = this.filterAndModifyFeature(
feature,
this.m_dataFilter?.wantsPolygonFeature,
modifierFunc
);
if (!properties) {
return;
}
const layerName = this.m_layer.name;
const layerExtents = this.m_layer.extent ?? 4096;
const geometry: IPolygonGeometry[] = [];
let currentPolygon: IPolygonGeometry | undefined;
let currentRing: Vector2[];
let exteriorWinding: number | undefined;
this.m_geometryCommands.accept(feature.geometry, {
type: "Polygon",
visitCommand: command => {
if (isMoveToCommand(command)) {
currentRing = [command.position];
} else if (isLineToCommand(command)) {
currentRing.push(command.position);
} else if (isClosePathCommand(command)) {
if (currentRing !== undefined && currentRing.length > 0) {
const currentRingWinding = Math.sign(ShapeUtils.area(currentRing));
// Winding order from XYZ spaces might be not MVT spec compliant, see HARP-11151.
// We take the winding of the very first ring as reference.
if (exteriorWinding === undefined) {
exteriorWinding = currentRingWinding;
}
// MVT spec defines that each exterior ring signals the beginning of a new polygon.
// see https://github.com/mapbox/vector-tile-spec/tree/master/2.1
if (currentRingWinding === exteriorWinding) {
// Create a new polygon and push it into the collection of polygons
currentPolygon = { rings: [] };
geometry.push(currentPolygon);
}
// Push the ring into the current polygon
currentRing.push(currentRing[0].clone());
currentPolygon?.rings.push(currentRing);
}
}
}
});
if (geometry.length === 0) {
return;
}
if (this.mustRoundUpCoordinates) {
roundUpPolygonCoordinates(geometry, layerExtents);
}
checkWinding(geometry);
this.m_processor.processPolygonFeature(
layerName,
layerExtents,
geometry,
properties,
decodeFeatureId(feature, properties, logger)
);
}
/**
* Applies any filter and modifiers to a given feature.
*
* @param feature - The feature to filter and modify.
* @param filterFunc - The filtering function.
* @param modifierFunc - The modifier function.
* @returns The modified feature properties or `undefined` if feature is filtered out.
*/
private filterAndModifyFeature(
feature: com.mapbox.pb.Tile.IFeature,
filterFunc?: (...args: any[]) => boolean,
modifierFunc?: (...args: any[]) => boolean
): ValueMap | undefined {
const storageLevel = this.m_tileKey.level;
const layerName = this.m_layer.name;
const geometryType = asGeometryType(feature);
if (
this.m_dataFilter &&
filterFunc!.apply(this.m_dataFilter, [layerName, geometryType, storageLevel]) === false
) {
return undefined;
}
const properties = readAttributes(this.m_layer, feature);
const env = new MapEnv(properties);
if (
this.m_featureModifiers?.find(fm => {
// TODO: The logic of feature ignore should be actually in the feature filtering
// mechanism - see OmvFeatureFilter.
assert(modifierFunc !== undefined);
return !modifierFunc!.apply(fm, [layerName, env, this.m_tileKey.level]);
}) !== undefined
) {
return undefined;
}
return properties;
}
private get mustRoundUpCoordinates(): boolean {
return (
this.m_roundUpCoordinatesIfNeeded &&
this.m_tileKey.level < 5 &&
this.m_tileKey.column === this.m_tileKey.columnCount() - 1
);
}
} | the_stack |
export * from "./MessageStreamInfo";
export interface EventTypeOptions {
S3Task: 0;
}
export interface EventTypeOptionsFlipped {
0: "S3Task";
}
type EventTypeValue = EventTypeOptions[keyof EventTypeOptions];
export type EventTypeMap = EventTypeValue;
/**
* The type of event, which determines how to interpret the status payload.
*/
export class EventType {
constructor(value?: EventTypeValue);
static fromMap(d: EventTypeMap): EventType;
asMap(): EventTypeMap;
static options: EventTypeOptions;
static optionsFlipped: EventTypeOptionsFlipped;
static S3Task: EventType;
}
export interface StatusOptions {
Success: 0;
Failure: 1;
InProgress: 2;
Warning: 3;
Canceled: 4;
}
export interface StatusOptionsFlipped {
0: "Success";
1: "Failure";
2: "InProgress";
3: "Warning";
4: "Canceled";
}
type StatusValue = StatusOptions[keyof StatusOptions];
export type StatusMap = StatusValue;
/**
* The status of the event.
*/
export class Status {
constructor(value?: StatusValue | null);
static fromMap(d: StatusMap): Status;
asMap(): StatusMap;
static options: StatusOptions;
static optionsFlipped: StatusOptionsFlipped;
static Success: Status;
static Failure: Status;
static InProgress: Status;
static Warning: Status;
static Canceled: Status;
}
export interface StatusLevelOptions {
ERROR: 0;
WARN: 1;
INFO: 2;
DEBUG: 3;
TRACE: 4;
}
export interface StatusLevelOptionsFlipped {
0: "ERROR";
1: "WARN";
2: "INFO";
3: "DEBUG";
4: "TRACE";
}
export type StatusLevelValue = StatusLevelOptions[keyof StatusLevelOptions];
export type StatusLevelMap = StatusLevelValue;
/**
* Defines the verbosity of status messages in a status-stream.
*/
export class StatusLevel {
constructor(value?: StatusLevelValue | null);
static fromMap(d: StatusLevelMap): StatusLevel;
asMap(): StatusLevelMap;
static options: StatusLevelOptions;
static optionsFlipped: StatusLevelOptionsFlipped;
static ERROR: StatusLevel;
static WARN: StatusLevel;
static INFO: StatusLevel;
static DEBUG: StatusLevel;
static TRACE: StatusLevel;
}
interface ValidationDef {
required: boolean;
maximum?: number;
minimum?: number;
minLength?: number;
maxLength?: number;
pattern?: string;
}
export type ValidationsMap = Record<string, ValidationDef>;
interface TypeDef {
type: { new (): unknown };
subtype: { new (): unknown } | null;
}
export type TypesMap = Record<string, TypeDef>;
export interface S3ExportTaskDefinitionMap {
inputUrl?: string;
bucket?: string;
key?: string;
userMetadata?: Record<string, unknown> | null;
}
export class S3ExportTaskDefinition {
/**
* @param inputUrl The URL of the file that contains the data to upload. The file should be local on the disk.
* @param bucket The name of the S3 bucket that this file should be uploaded to.
* @param key The key for the S3 object that this file should be uploaded to. The string can have placeholder expressions which are
* resolved at upload time. Valid expressions are strings that are valid Java DateTimeFormatter strings.
* See https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
* Example: myKeyNamePrefix/!{timestamp:yyyy/MM/dd}/myKeyNameSuffix.
* @param userMetadata User metadata. For key of a user metadata, callers should not include the internal "x-amz-meta-"
* prefix. Keys are case insensitive and will appear as lowercase strings on S3, even if they were originally
* specified with uppercase strings. Reserved key names start with "$aws-gg-" prefix.
*/
constructor(
inputUrl?: string | null,
bucket?: string | null,
key?: string | null,
userMetadata?: Record<string, unknown> | null,
);
/**
* The URL of the file that contains the data to upload. The file should be local on the disk.
*/
get inputUrl(): string;
/**
* @param value The URL of the file that contains the data to upload. The file should be local on the disk.
*/
set inputUrl(value: string);
/**
* @param value The URL of the file that contains the data to upload. The file should be local on the disk.
* @returns
*/
withInputUrl(value: string): S3ExportTaskDefinition;
/**
* The name of the S3 bucket that this file should be uploaded to.
*/
get bucket(): string;
/**
* @param value The name of the S3 bucket that this file should be uploaded to.
*/
set bucket(value: string);
/**
* @param value The name of the S3 bucket that this file should be uploaded to.
* @returns
*/
withBucket(value: string): S3ExportTaskDefinition;
/**
* The key for the S3 object that this file should be uploaded to.
* The string can have placeholder expressions which are resolved at upload time.
* Valid expressions are strings that are valid Java DateTimeFormatter strings.
* See https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
* Example: myKeyNamePrefix/!{timestamp:yyyy/MM/dd}/myKeyNameSuffix.
* @returns
*/
get key(): string;
/**
* @param value The key for the S3 object that this file should be uploaded to.
* The string can have placeholder expressions which are resolved at upload time.
* Valid expressions are strings that are valid Java DateTimeFormatter strings.
* See https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
* Example: myKeyNamePrefix/!{timestamp:yyyy/MM/dd}/myKeyNameSuffix.
*/
set key(value: string);
/**
* @param value The key for the S3 object that this file should be uploaded to.
* The string can have placeholder expressions which are resolved at upload time.
* Valid expressions are strings that are valid Java DateTimeFormatter strings.
* See https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html
* Example: myKeyNamePrefix/!{timestamp:yyyy/MM/dd}/myKeyNameSuffix.
* @returns
*/
withKey(value: string): S3ExportTaskDefinition;
/**
* User metadata. For key of a user metadata, callers should not include the internal "x-amz-meta-" prefix.
* Keys are case insensitive and will appear as lowercase strings on S3, even if they were originally specified with uppercase strings.
* Reserved key names start with "$aws-gg-" prefix.
* @returns
*/
get userMetadata(): Record<string, unknown> | null;
/**
* @param value User metadata. For key of a user metadata, callers should not include the internal "x-amz-meta-" prefix.
* Keys are case insensitive and will appear as lowercase strings on S3, even if they were originally specified with uppercase strings.
* Reserved key names start with "$aws-gg-" prefix.
*/
set userMetadata(value: Record<string, unknown> | null);
/**
* @param value User metadata. For key of a user metadata, callers should not include the internal "x-amz-meta-" prefix.
* Keys are case insensitive and will appear as lowercase strings on S3, even if they were originally specified with uppercase strings.
* Reserved key names start with "$aws-gg-" prefix.
* @returns
*/
withUserMetadata(value: Record<string, unknown> | null): S3ExportTaskDefinition;
static fromMap(d: S3ExportTaskDefinitionMap): S3ExportTaskDefinition;
asMap(): S3ExportTaskDefinitionMap;
}
/**
* Message object containing metadata and the user's payload.
*/
export class Message {
/**
* @param streamName The name of the stream which this message is in.
* @param sequenceNumber The sequence number of this message within the stream.
* @param ingestTime The time that the message was ingested to Stream Manager. Data is Unix epoch time in milliseconds.
* @param payload The binary message data.
*/
constructor(
streamName?: string | null,
sequenceNumber?: number | null,
ingestTime?: number | null,
payload?: Buffer | null,
);
/**
* The name of the stream which this message is in.
*/
get streamName(): string | null;
/**
* @param value The name of the stream which this message is in.
*/
set streamName(value: string | null);
/**
* @param value The name of the stream which this message is in.
* @returns The caller
*/
withStreamName(value: string | null): this;
/**
* The sequence number of this message within the stream.
*/
get sequenceNumber(): number | null;
/**
* @param value The sequence number of this message within the stream.
*/
set sequenceNumber(value: number | null);
/**
* @param value The sequence number of this message within the stream.
* @returns The caller
*/
withSequenceNumber(value: number | null): this;
/**
* The time that the message was ingested to Stream Manager. Data is Unix epoch time in milliseconds.
*/
get ingestTime(): number | null;
/**
* @param value The time that the message was ingested to Stream Manager. Data is Unix epoch time in milliseconds.
*/
set ingestTime(value: number | null);
/**
* @param value The time that the message was ingested to Stream Manager. Data is Unix epoch time in milliseconds.
* @returns The caller
*/
withIngestTime(value: number | null): this;
/**
* The binary message data.
*/
get payload(): Buffer | null;
/**
* @param value The binary message data.
*/
set payload(value: Buffer | null);
/**
* @param value The binary message data.
* @returns The caller
*/
withPayload(value: Buffer | null): this;
static fromMap(d: MessageMap): Message;
asMap(): MessageMap;
static validationsMap: MessageValidationsMap;
static typesMap: MessageTypesMap;
static formatsMap: Record<string, never>;
}
export interface MessageMap {
streamName?: string | null;
sequenceNumber?: number | null;
ingestTime?: number | null;
payload?: Buffer | null;
}
export interface MessageValidationsMap extends ValidationsMap {
streamName: ValidationDef;
sequenceNumber: ValidationDef;
ingestTime: ValidationDef;
payload: ValidationDef;
}
export interface MessageTypesMap {
streamName: TypeDef;
sequenceNumber: TypeDef;
ingestTime: TypeDef;
payload: TypeDef;
}
/**
* Context associated with a status message. Describes which stream, export config, message, the status is associated with.
*/
export class StatusContext {
/**
* @param s3ExportTaskDefinition The task definition of an S3 upload task if the status is associated with it, ie, if the eventType = S3Task.
* @param exportIdentifier The export identifier the status is associated with.
* @param streamName The name of the stream the status is associated with.
* @param sequenceNumber The sequence number of the message the status is associated with.
*/
constructor(
s3ExportTaskDefinition?: S3ExportTaskDefinition | null,
exportIdentifier?: string | null,
streamName?: string | null,
sequenceNumber?: number | null,
);
/**
* The task definition of an S3 upload task if the status is associated with it, ie, if the eventType = S3Task.
* @returns
*/
get s3ExportTaskDefinition(): S3ExportTaskDefinition | null;
/**
* @param value The task definition of an S3 upload task if the status is associated with it, ie, if the eventType = S3Task.
*/
set s3ExportTaskDefinition(value: S3ExportTaskDefinition | null);
/**
* @param value The task definition of an S3 upload task if the status is associated with it, ie, if the eventType = S3Task.
* @returns
*/
withS3ExportTaskDefinition(value: S3ExportTaskDefinition | null): this;
/**
* The export identifier the status is associated with.
* @returns
*/
get exportIdentifier(): string | null;
/**
* @param value The export identifier the status is associated with.
*/
set exportIdentifier(value: string | null);
/**
* @param value The export identifier the status is associated with.
* @returns
*/
withExportIdentifier(value: string | null): this;
/**
* The name of the stream the status is associated with.
* @returns
*/
get streamName(): string | null;
/**
* @param value The name of the stream the status is associated with.
*/
set streamName(value: string | null);
/**
* @param value The name of the stream the status is associated with.
* @returns
*/
withStreamName(value: string | null): this;
/**
* The sequence number of the message the status is associated with.
* @returns
*/
get sequenceNumber(): number | null;
/**
* @param value The sequence number of the message the status is associated with.
*/
set sequenceNumber(value: number | null);
/**
* @param value The sequence number of the message the status is associated with.
* @returns
*/
withSequenceNumber(value: number | null): this;
static fromMap(d: StatusContextMap): StatusContext;
asMap(): StatusContextMap;
static typesMap: TypesMap;
static validationsMap: ValidationsMap;
static formatsMap: Record<string, never>;
}
export interface StatusContextMap {
s3ExportTaskDefinition?: S3ExportTaskDefinitionMap;
exportIdentifier?: string;
streamName?: string;
sequenceNumber?: number;
}
/**
* Status object appended to a status-stream.
*/
export class StatusMessage {
/**
* @param eventType
* @param statusLevel
* @param status
* @param statusContext
* @param message String describing the status message.
* @param timestampEpochMs The time this status was added to the status-stream (in milliseconds since epoch).
*/
constructor(
eventType?: EventType | null,
statusLevel?: StatusLevel | null,
status?: Status | null,
statusContext?: StatusContext | null,
message?: string | null,
timestampEpochMs?: number | null,
);
/**
* @returns
*/
get eventType(): EventType | null;
/**
* @param value
*/
set eventType(value: EventType | null);
/**
* @param value
* @returns
*/
withEventType(value: EventType | null): this;
/**
* @returns
*/
get statusLevel(): StatusLevel | null;
/**
* @param value
*/
set statusLevel(value: StatusLevel | null);
/**
* @param value
* @returns
*/
withStatusLevel(value: StatusLevel | null): this;
/**
* @returns
*/
get status(): Status | null;
/**
* @param value
*/
set status(value: Status | null);
/**
* @param value
* @returns
*/
withStatus(value: Status | null): this;
/**
* @returns
*/
get statusContext(): StatusContext | null;
/**
* @param value
*/
set statusContext(value: StatusContext | null);
/**
* @param value
* @returns
*/
withStatusContext(value: StatusContext | null): this;
/**
* String describing the status message.
* @returns
*/
get message(): string | null;
/**
* @param value String describing the status message.
*/
set message(value: string | null);
/**
* @param value String describing the status message.
* @returns
*/
withMessage(value: string | null): this;
/**
* The time this status was added to the status-stream (in milliseconds since epoch).
* @returns
*/
get timestampEpochMs(): number | null;
/**
* @param value The time this status was added to the status-stream (in milliseconds since epoch).
*/
set timestampEpochMs(value: number | null);
/**
* @param value The time this status was added to the status-stream (in milliseconds since epoch).
* @returns
*/
withTimestampEpochMs(value: number | null): this;
static fromMap(d: StatusMessageMap): StatusMessage;
asMap(): StatusMessageMap;
static typesMap: TypesMap;
static validationsMap: ValidationsMap;
static formatsMap: Record<string, never>;
}
export interface StatusMessageMap {
eventType: EventTypeMap;
statusLevel: StatusLevelMap;
status: StatusMap;
statusContext: StatusContextMap;
message?: string;
timestampEpochMs?: number;
}
/**
* Options for the ReadMessages API. All fields are optional.
*/
export class ReadMessagesOptions {
/**
* @param desiredStartSequenceNumber The desired beginning sequence number to start reading from.
* If the desired sequence number is less than the current minimum of the stream, then it will instead start reading from the current minimum.
* @param minMessageCount The minimum number of messages that will be returned.
* If not enough messages are available for reading, then NotEnoughMessages exception will be thrown.
* The minimum values is 1 and the maximum value is 2147483647.
* @param maxMessageCount The maximum number of messages that will be returned.
* The minimum values is the value of the minimum message count and the maximum value is 2147483647.
* @param readTimeoutMillis The time to wait for messages in milliseconds. Default is 0, meaning that the server will not wait for messages.
* If it can fulfill the minimum messages it will return them, but otherwise NotEnoughMessages exception will be thrown.
* If the timeout is greater than zero, then the server will wait up to that time for more messages to be appended to the stream,
* waiting until the minimum number of messages is reached. The maximum value is the value of the client timeout.
*/
constructor(
desiredStartSequenceNumber?: number | null,
minMessageCount?: number | null,
maxMessageCount?: number | null,
readTimeoutMillis?: number | null,
);
/**
* The desired beginning sequence number to start reading from. If the desired sequence number is less than
* the current minimum of the stream, then it will instead start reading from the current minimum.
* @returns
*/
get desiredStartSequenceNumber(): number | null;
/**
* @param value The desired beginning sequence number to start reading from. If the desired sequence number is less than
* the current minimum of the stream, then it will instead start reading from the current minimum.
*/
set desiredStartSequenceNumber(value: number | null);
/**
* @param value The desired beginning sequence number to start reading from. If the desired sequence number is less than
* the current minimum of the stream, then it will instead start reading from the current minimum.
* @returns
*/
withDesiredStartSequenceNumber(value: number | null): this;
/**
* The minimum number of messages that will be returned. If not enough messages are available for reading, then NotEnoughMessages
* exception will be thrown. The minimum values is 1 and the maximum value is 2147483647.
* @returns
*/
get minMessageCount(): number | null;
/**
* @param value The minimum number of messages that will be returned. If not enough messages are available for reading,
* then NotEnoughMessages exception will be thrown. The minimum values is 1 and the maximum value is 2147483647.
*/
set minMessageCount(value: number | null);
/**
* @param value The minimum number of messages that will be returned. If not enough messages are available for reading, then
* NotEnoughMessages exception will be thrown. The minimum values is 1 and the maximum value is 2147483647.
* @returns
*/
withMinMessageCount(value: number | null): this;
/**
* The maximum number of messages that will be returned.
* The minimum values is the value of the minimum message count and the maximum value is 2147483647.
* @returns
*/
get maxMessageCount(): number | null;
/**
* @param value The maximum number of messages that will be returned.
* The minimum values is the value of the minimum message count and the maximum value is 2147483647.
*/
set maxMessageCount(value: number | null);
/**
* @param value The maximum number of messages that will be returned.
* The minimum values is the value of the minimum message count and the maximum value is 2147483647.
* @returns
*/
withMaxMessageCount(value: number | null): this;
/**
* The time to wait for messages in milliseconds. Default is 0, meaning that the server will not wait for messages.
* If it can fulfill the minimum messages it will return them, but otherwise NotEnoughMessages exception will be thrown.
* If the timeout is greater than zero, then the server will wait up to that time for more messages to be appended to the stream,
* waiting until the minimum number of messages is reached.
* The maximum value is the value of the client timeout.
* @returns
*/
get readTimeoutMillis(): number | null;
/**
* @param value The time to wait for messages in milliseconds. Default is 0, meaning that the server will not wait for messages.
* If it can fulfill the minimum messages it will return them, but otherwise NotEnoughMessages exception will be thrown.
* If the timeout is greater than zero, then the server will wait up to that time for more messages to be appended to the stream,
* waiting until the minimum number of messages is reached.
* The maximum value is the value of the client timeout.
*/
set readTimeoutMillis(value: number | null);
/**
* @param value The time to wait for messages in milliseconds. Default is 0, meaning that the server will not wait for messages.
* If it can fulfill the minimum messages it will return them, but otherwise NotEnoughMessages exception will be thrown.
* If the timeout is greater than zero, then the server will wait up to that time for more messages to be appended to the stream,
* waiting until the minimum number of messages is reached.
* The maximum value is the value of the client timeout.
* @returns
*/
withReadTimeoutMillis(value: number | null): this;
static fromMap(d: ReadMessagesOptionsMap): ReadMessagesOptions;
asMap(): ReadMessagesOptionsMap;
static typesMap: TypesMap;
static validationsMap: ValidationsMap;
static formatsMap: Record<string, never>;
}
export interface ReadMessagesOptionsMap {
desiredStartSequenceNumber?: number;
minMessageCount?: number;
maxMessageCount?: number;
readTimeoutMillis?: number;
}
/**
* StrategyOnFull is used in the MessageStreamDefinition when creating a stream.
* It defines the behavior when the stream has reached the maximum size.
* RejectNewData: any append message request after the stream is full will be rejected with an exception.
* OverwriteOldestData: the oldest stream segments will be deleted until there is room for the new message.
*/
export class StrategyOnFull {
constructor(value?: StrategyOnFullValue | null);
static fromMap(d: StrategyOnFullMap): StrategyOnFull;
asMap(): StrategyOnFullMap;
static options: StrategyOnFullOptions;
static optionsFlipped: StrategyOnFullOptionsFlipped;
static readonly RejectNewData: StrategyOnFull;
static readonly OverwriteOldestData: StrategyOnFull;
}
export interface StrategyOnFullOptions {
RejectNewData: 0;
OverwriteOldestData: 1;
}
export type StrategyOnFullValue = keyof StrategyOnFullOptionsFlipped;
export type StrategyOnFullMap = StrategyOnFullValue;
export interface StrategyOnFullOptionsFlipped {
0: "RejectNewData";
1: "OverwriteOldestData";
}
/**
* Stream persistence. If set to File, the file system will be used to persist messages long-term and is resilient to restarts.
* Memory should be used when performance matters more than durability as it only stores the stream in memory and never writes to the disk.
*/
export class Persistence {
constructor(value?: PersistenceValue | null);
static fromMap(d: PersistenceMap): Persistence;
asMap(): PersistenceMap;
static options: PersistenceOptions;
static optionsFlipped: PersistenceOptionsFlipped;
static File: Persistence;
static Memory: Persistence;
}
export interface PersistenceOptions {
File: 0;
Memory: 1;
}
export interface PersistenceOptionsFlipped {
0: "File";
1: "Memory";
}
export type PersistenceValue = keyof PersistenceOptionsFlipped;
export type PersistenceMap = PersistenceValue;
/**
* ExportFormat is used to define how messages are batched and formatted in the export payload.
* RAW_NOT_BATCHED: Each message in a batch will be sent as an individual HTTP POST with the payload as the body (even if batchSize is set).
* JSON_BATCHED: Each batch of messages will be sent as a JSON list of Message objects as the body.
*/
export class ExportFormat {
constructor(value: ExportFormatValue);
static fromMap(d: ExportFormatMap): ExportFormat;
asMap(): ExportFormatMap;
static options: ExportFormatOptions;
static optionsFlipped: ExportFormatOptionsFlipped;
static RAW_NOT_BATCHED: ExportFormat;
static JSON_BATCHED: ExportFormat;
}
export interface ExportFormatOptions {
RAW_NOT_BATCHED: 0;
JSON_BATCHED: 1;
}
export interface ExportFormatOptionsFlipped {
0: "RAW_NOT_BATCHED";
1: "JSON_BATCHED";
}
export type ExportFormatValue = keyof ExportFormatOptions;
export type ExportFormatMap = ExportFormatValue;
declare class StreamConfigBase<TMap extends StreamConfigBaseMap> {
/**
* A unique identifier to identify this individual upload stream.
* Must be an alphanumeric string including spaces, commas, periods, hyphens, and underscores with length between 1 and 255.
* @returns
*/
get identifier(): string | null;
/**
* @param value A unique identifier to identify this individual upload stream.
* Must be an alphanumeric string including spaces, commas, periods, hyphens, and underscores with length between 1 and 255.
*/
set identifier(value: string | null);
/**
* @param value A unique identifier to identify this individual upload stream.
* Must be an alphanumeric string including spaces, commas, periods, hyphens, and underscores with length between 1 and 255.
*/
withIdentifier(value: string | null): this;
/**
* The time in milliseconds between the earliest un-uploaded message and the current time. If this time is exceeded,
* messages will be uploaded in the next batch. If unspecified messages will be eligible for upload immediately.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The minimum value is 60000 milliseconds and the maximum is 9223372036854 milliseconds.
* @returns
*/
get batchIntervalMillis(): number | null;
/**
* @param value The time in milliseconds between the earliest un-uploaded message and the current time. If this time is exceeded,
* messages will be uploaded in the next batch. If unspecified messages will be eligible for upload immediately.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The minimum value is 60000 milliseconds and the maximum is 9223372036854 milliseconds.
*/
set batchIntervalMillis(value: number | null);
/**
* @param value The time in milliseconds between the earliest un-uploaded message and the current time. If this time is exceeded,
* messages will be uploaded in the next batch. If unspecified messages will be eligible for upload immediately.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The minimum value is 60000 milliseconds and the maximum is 9223372036854 milliseconds.
*/
withBatchIntervalMillis(value: number | null): this;
/**
* Priority for this upload stream. Lower values are higher priority. If not specified it will have the lowest priority.
* @returns
*/
get priority(): number | null;
/**
* @param value Priority for this upload stream. Lower values are higher priority. If not specified it will have the lowest priority.
*/
set priority(value: number | null);
/**
* @param value Priority for this upload stream. Lower values are higher priority. If not specified it will have the lowest priority.
*/
withPriority(value: number | null): this;
/**
* The sequence number of the message to use as the starting message in the export. Default is 0.
* The sequence number provided should be less than the newest sequence number in the stream, i.e.,
* sequence number of the last messaged appended.
* To find the newest sequence number, describe the stream and then check the storage status of the returned MessageStreamInfo object.
* @returns
*/
get startSequenceNumber(): number | null;
/**
* @param value The sequence number of the message to use as the starting message in the export. Default is 0.
* The sequence number provided should be less than the newest sequence number in the stream, i.e.,
* sequence number of the last messaged appended.
* To find the newest sequence number, describe the stream and then check the storage status of the returned MessageStreamInfo object.
*/
set startSequenceNumber(value: number | null);
/**
* @param value The sequence number of the message to use as the starting message in the export. Default is 0.
* The sequence number provided should be less than the newest sequence number in the stream, i.e.,
* sequence number of the last messaged appended.
* To find the newest sequence number, describe the stream and then check the storage status of the returned MessageStreamInfo object.
*/
withStartSequenceNumber(value: number | null): this;
/**
* Enable or disable this export. Default is false.
* @returns
*/
get disabled(): boolean | null;
/**
* @param value Enable or disable this export. Default is false.
*/
set disabled(value: boolean | null);
/**
* @param value Enable or disable this export. Default is false.
*/
withDisabled(value: boolean | null): this;
asMap(): TMap;
static typesMap: TypesMap;
static formatsMap: Record<string, never>;
static validationsMap: ValidationsMap;
}
interface StreamConfigBaseMap {
identifier?: string | null;
batchSize?: number | null;
batchIntervalMillis?: number | null;
priority?: number | null;
startSequenceNumber?: number | null;
disabled?: boolean | null;
}
/**
* This export destination is not supported! The interface may change at any time without notice and should not be relied on for any production use.
* There are no guarantees around its correctness.
* This configures an HTTP endpoint which sends a POST request to the provided URI. Each request contains a single message in the body of the request.
*/
export class HTTPConfig extends StreamConfigBase<HTTPConfigMap> {
/**
* @param identifier A unique identifier to identify this individual upload stream.
* Must be an alphanumeric string including spaces, commas, periods, hyphens, and underscores with length between 1 and 255.
* @param uri URL for HTTP endpoint which should receive the POST requests for export.
* @param batchSize The maximum size of a batch to send to the destination. Messages will be queued until the batch size is reached,
* after which they will then be uploaded. If unspecified the default will be 500.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The minimum batch size is 1 and the maximum is 500.
* @param batchIntervalMillis The time in milliseconds between the earliest un-uploaded message and the current time.
* If this time is exceeded, messages will be uploaded in the next batch. If unspecified messages will be eligible for upload immediately.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The minimum value is 60000 milliseconds and the maximum is 9223372036854 milliseconds.
* @param priority Priority for this upload stream. Lower values are higher priority. If not specified it will have the lowest priority.
* @param startSequenceNumber The sequence number of the message to use as the starting message in the export. Default is 0.
* The sequence number provided should be less than the newest sequence number in the stream, i.e.,
* sequence number of the last messaged appended. To find the newest sequence number, describe the stream and then check the storage status
* of the returned MessageStreamInfo object.
* @param disabled Enable or disable this export. Default is false.
* @param exportFormat Defines how messages are batched and formatted in the export payload.
*/
constructor(
identifier?: string | null,
uri?: string | null,
batchSize?: number | null,
batchIntervalMillis?: number | null,
priority?: number | null,
startSequenceNumber?: number | null,
disabled?: boolean | null,
exportFormat?: ExportFormat | null,
);
/**
* URL for HTTP endpoint which should receive the POST requests for export.
* @returns
*/
get uri(): string | null;
/**
* @param value URL for HTTP endpoint which should receive the POST requests for export.
*/
set uri(value: string | null);
/**
* @param value URL for HTTP endpoint which should receive the POST requests for export.
* @returns
*/
withUri(value: string | null): HTTPConfig;
/**
* The maximum size of a batch to send to the destination. Messages will be queued until the batch size is reached,
* after which they will then be uploaded.
* If unspecified the default will be 500.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The minimum batch size is 1 and the maximum is 500.
* @returns
*/
get batchSize(): number | null;
/**
* @param value The maximum size of a batch to send to the destination. Messages will be queued until the batch size is reached,
* after which they will then be uploaded.
* If unspecified the default will be 500.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The minimum batch size is 1 and the maximum is 500.
*/
set batchSize(value: number | null);
/**
* @param value The maximum size of a batch to send to the destination. Messages will be queued until the batch size is reached,
* after which they will then be uploaded.
* If unspecified the default will be 500.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The minimum batch size is 1 and the maximum is 500.
*/
withBatchSize(value: number | null): HTTPConfig;
/**
* Defines how messages are batched and formatted in the export payload.
* @returns
*/
get exportFormat(): ExportFormat | null;
/**
* @param value Defines how messages are batched and formatted in the export payload.
*/
set exportFormat(value: ExportFormat | null);
/**
* @param value Defines how messages are batched and formatted in the export payload.
* @returns
*/
withExportFormat(value: ExportFormat | null): HTTPConfig;
static fromMap(d: HTTPConfigMap): HTTPConfig;
}
export interface HTTPConfigMap extends StreamConfigBaseMap {
identifier?: string | null;
uri?: string | null;
exportFormat?: ExportFormatMap;
}
/**
* Configuration object for IoT Analytics export destination.
*/
export class IoTAnalyticsConfig extends StreamConfigBase<IoTAnalyticsConfigMap> {
/**
* @param identifier A unique identifier to identify this individual upload stream.
* Must be an alphanumeric string including spaces, commas, periods, hyphens, and underscores with length between 1 and 255.
* @param iotChannel The name of the IoT Analytics Channel that this exporter should upload to.
* @param iotMsgIdPrefix A string prefixed to each unique message id. After this prefix, StreamManager may append
* more data to make the message ID unique.
* This prefix must be less than 32 characters.
* @param batchSize The maximum size of a batch to send to IoT Analytics. Messages will be queued until the batch size is reached,
* after which they will then be uploaded.
* If unspecified the default will be 100.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The batch size must be between 1 and 100.
* @param batchIntervalMillis The time in milliseconds between the earliest un-uploaded message and the current time.
* If this time is exceeded, messages will be uploaded in the next batch. If unspecified messages will be eligible for upload immediately.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The minimum value is 60000 milliseconds and the maximum is 9223372036854 milliseconds.
* @param priority Priority for this upload stream. Lower values are higher priority. If not specified it will have the lowest priority.
* @param startSequenceNumber The sequence number of the message to use as the starting message in the export.
* Default is 0.
* The sequence number provided should be less than the newest sequence number in the stream, i.e., sequence number of the last messaged appended.
* To find the newest sequence number, describe the stream and then check the storage status of the returned MessageStreamInfo object.
* @param disabled Enable or disable this export. Default is false.
*/
constructor(
identifier?: string | null,
iotChannel?: string | null,
iotMsgIdPrefix?: string | null,
batchSize?: number | null,
batchIntervalMillis?: number | null,
priority?: number | null,
startSequenceNumber?: number | null,
disabled?: boolean | null,
);
/**
* The name of the IoT Analytics Channel that this exporter should upload to.
* @returns
*/
get iotChannel(): string | null;
/**
* @param value The name of the IoT Analytics Channel that this exporter should upload to.
*/
set iotChannel(value: string | null);
/**
* @param value The name of the IoT Analytics Channel that this exporter should upload to.
* @returns
*/
withIotChannel(value: string | null): IoTAnalyticsConfig;
/**
* A string prefixed to each unique message id. After this prefix, StreamManager may append more data to make the message ID unique.
* This prefix must be less than 32 characters.
* @returns
*/
get iotMsgIdPrefix(): string | null;
/**
* @param value A string prefixed to each unique message id. After this prefix, StreamManager may append more data to make the message ID unique.
* This prefix must be less than 32 characters.
*/
set iotMsgIdPrefix(value: string | null);
/**
* @param value A string prefixed to each unique message id. After this prefix, StreamManager may append more data to make the message ID unique.
* This prefix must be less than 32 characters.
* @returns
*/
withIotMsgIdPrefix(value: string | null): IoTAnalyticsConfig;
/**
* The maximum size of a batch to send to IoT Analytics. Messages will be queued until the batch size is reached,
* after which they will then be uploaded.
* If unspecified the default will be 100.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The batch size must be between 1 and 100.
* @returns
*/
get batchSize(): number | null;
/**
* @param value The maximum size of a batch to send to IoT Analytics. Messages will be queued until the batch size is reached,
* after which they will then be uploaded.
* If unspecified the default will be 100.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The batch size must be between 1 and 100.
*/
set batchSize(value: number | null);
/**
* @param value The maximum size of a batch to send to IoT Analytics. Messages will be queued until the batch size is reached,
* after which they will then be uploaded.
* If unspecified the default will be 100.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The batch size must be between 1 and 100.
*/
withBatchSize(value: number | null): IoTAnalyticsConfig;
static fromMap(d: IoTAnalyticsConfigMap): IoTAnalyticsConfig;
}
export interface IoTAnalyticsConfigMap extends StreamConfigBaseMap {
identifier?: string | null;
iotChannel?: string | null;
iotMsgIdPrefix?: string | null;
}
/**
* Configuration object for Kinesis data streams export destination.
*/
export class KinesisConfig extends StreamConfigBase<KinesisConfigMap> {
/**
* @param identifier A unique identifier to identify this individual upload stream.
* Must be an alphanumeric string including spaces, commas, periods, hyphens, and underscores with length between 1 and 255.
* @param kinesisStreamName The name of the Kinesis data stream that this exporter should upload to.
* @param batchSize The maximum size of a batch to send to Kinesis. Messages will be queued until the batch size is reached,
* after which they will then be uploaded.
* If unspecified the default will be 500.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The batch size must be between 1 and 500.
* @param batchIntervalMillis The time in milliseconds between the earliest un-uploaded message and the current time.
* If this time is exceeded, messages will be uploaded in the next batch. If unspecified messages will be eligible for upload immediately.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The minimum value is 60000 milliseconds and the maximum is 9223372036854 milliseconds.
* @param priority Priority for this upload stream. Lower values are higher priority. If not specified it will have the lowest priority.
* @param startSequenceNumber The sequence number of the message to use as the starting message in the export. Default is 0.
* The sequence number provided should be less than the newest sequence number in the stream, i.e., sequence number of the last messaged appended.
* To find the newest sequence number, describe the stream and then check the storage status of the returned MessageStreamInfo object.
* @param disabled Enable or disable this export. Default is false.
*/
constructor(
identifier?: string | null,
kinesisStreamName?: string | null,
batchSize?: number | null,
batchIntervalMillis?: number | null,
priority?: number | null,
startSequenceNumber?: number | null,
disabled?: boolean | null,
);
/**
* The name of the Kinesis data stream that this exporter should upload to.
* @returns
*/
get kinesisStreamName(): string | null;
/**
* @param value The name of the Kinesis data stream that this exporter should upload to.
*/
set kinesisStreamName(value: string | null);
/**
* @param value The name of the Kinesis data stream that this exporter should upload to.
* @returns
*/
withKinesisStreamName(value: string | null): KinesisConfig;
/**
* The maximum size of a batch to send to Kinesis. Messages will be queued until the batch size is reached, after which they will then be uploaded.
* If unspecified the default will be 500.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The batch size must be between 1 and 500.
* @returns
*/
get batchSize(): number | null;
/**
* @param value The maximum size of a batch to send to Kinesis. Messages will be queued until the batch size is reached, after which they will then be uploaded.
* If unspecified the default will be 500.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The batch size must be between 1 and 500.
*/
set batchSize(value: number | null);
/**
* @param value The maximum size of a batch to send to Kinesis. Messages will be queued until the batch size is reached, after which they will then be uploaded.
* If unspecified the default will be 500.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The batch size must be between 1 and 500.
*/
withBatchSize(value: number | null): KinesisConfig;
static fromMap(d: KinesisConfigMap): KinesisConfig;
}
export interface KinesisConfigMap extends StreamConfigBaseMap {
identifier?: string | null;
kinesisStreamName?: string | null;
}
/**
* Configuration object for IotSiteWise data streams export destination. Minimum version requirements: StreamManager server version 1.1 (or AWS IoT Greengrass Core 1.11.0)
*/
export class IoTSiteWiseConfig extends StreamConfigBase<IoTSiteWiseConfigMap> {
/**
* @param identifier A unique identifier to identify this individual upload stream.
* Must be an alphanumeric string including spaces, commas, periods, hyphens, and underscores with length between 1 and 255.
* @param batchSize The maximum size of a batch to send to the destination. Messages will be queued until the batch size is reached, after which they will then be uploaded.
* If unspecified the default will be 10.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The minimum batch size is 1 and the maximum is 10.
* @param batchIntervalMillis The time in milliseconds between the earliest un-uploaded message and the current time.
* If this time is exceeded, messages will be uploaded in the next batch. If unspecified messages will be eligible for upload immediately.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The minimum value is 60000 milliseconds and the maximum is 9223372036854 milliseconds.
* @param priority Priority for this upload stream. Lower values are higher priority. If not specified it will have the lowest priority.
* @param startSequenceNumber The sequence number of the message to use as the starting message in the export. Default is 0.
* The sequence number provided should be less than the newest sequence number in the stream, i.e., sequence number of the last messaged appended.
* To find the newest sequence number, describe the stream and then check the storage status of the returned MessageStreamInfo object.
* @param disabled Enable or disable this export. Default is false.
*/
constructor(
identifier?: string | null,
batchSize?: number | null,
batchIntervalMillis?: number | null,
priority?: number | null,
startSequenceNumber?: number | null,
disabled?: boolean | null,
);
/**
* The maximum size of a batch to send to the destination. Messages will be queued until the batch size is reached, after which they will then be uploaded.
* If unspecified the default will be 10.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The minimum batch size is 1 and the maximum is 10.
* @returns
*/
get batchSize(): number | null;
/**
* @param value The maximum size of a batch to send to the destination. Messages will be queued until the batch size is reached, after which they will then be uploaded.
* If unspecified the default will be 10.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The minimum batch size is 1 and the maximum is 10.
*/
set batchSize(value: number | null);
/**
* @param value The maximum size of a batch to send to the destination. Messages will be queued until the batch size is reached, after which they will then be uploaded.
* If unspecified the default will be 10.
* If both batchSize and batchIntervalMillis are specified, then messages will be eligible for upload when either condition is met.
* The minimum batch size is 1 and the maximum is 10.
*/
withBatchSize(value: number | null): IoTSiteWiseConfig;
static fromMap(d: IoTSiteWiseConfigMap): IoTSiteWiseConfig;
}
export interface IoTSiteWiseConfigMap extends StreamConfigBaseMap {
identifier?: string | null;
}
/**
* Configuration for status in a status-stream.
*/
export class StatusConfig {
/**
* @param statusLevel Defines the verbosity of status messages in a status-stream.
* @param statusStreamName The name of the stream to which status messages are appended.
* The status-stream should be created before associating it with another stream.
*/
constructor(statusLevel?: StatusLevel | null, statusStreamName?: string | null);
/**
* Defines the verbosity of status messages in a status-stream.
* @returns
*/
get statusLevel(): StatusLevel | null;
/**
* @param value Defines the verbosity of status messages in a status-stream.
*/
set statusLevel(value: StatusLevel | null);
/**
* @param value Defines the verbosity of status messages in a status-stream.
* @returns
*/
withStatusLevel(value: StatusLevel | null): StatusConfig;
/**
* The name of the stream to which status messages are appended.
* The status-stream should be created before associating it with another stream.
* @returns
*/
get statusStreamName(): string | null;
/**
* @param value The name of the stream to which status messages are appended.
* The status-stream should be created before associating it with another stream.
*/
set statusStreamName(value: string | null);
/**
* @param value The name of the stream to which status messages are appended.
* The status-stream should be created before associating it with another stream.
* @returns
*/
withStatusStreamName(value: string | null): StatusConfig;
static fromMap(d: StatusConfigMap): StatusConfig;
asMap(): StatusConfigMap;
static typesMap: TypesMap;
static formatsMap: Record<string, never>;
static validationsMap: ValidationsMap;
}
export interface StatusConfigMap {
statusLevel?: StatusLevelMap;
statusStreamName?: string;
}
/**
* Configuration object for S3 export tasks executor. Minimum version requirements: StreamManager server version 1.1 (or AWS IoT Greengrass Core 1.11.0)
*/
export class S3ExportTaskExecutorConfig {
/**
* @param identifier A unique identifier to identify this individual upload task.
* Must be an alphanumeric string including spaces, commas, periods, hyphens, and underscores with length between 1 and 255.
* @param sizeThresholdForMultipartUploadBytes The size threshold in bytes for when to use multipart uploads.
* Uploads over this size will automatically use a multipart upload strategy, while uploads equal or smaller than this threshold will use a single connection to upload the whole object.
* @param priority Priority for this upload task. Lower values are higher priority. If not specified it will have the lowest priority.
* @param disabled Enable or disable this export. Default is false.
* @param statusConfig Event status configuration that specifies the target status stream and verbosity.
*/
constructor(
identifier?: string | null,
sizeThresholdForMultipartUploadBytes?: number | null,
priority?: number | null,
disabled?: boolean | null,
statusConfig?: StatusConfig | null,
);
/**
* A unique identifier to identify this individual upload task.
* Must be an alphanumeric string including spaces, commas, periods, hyphens, and underscores with length between 1 and 255.
* @returns
*/
get identifier(): string | null;
/**
* @param value A unique identifier to identify this individual upload task.
* Must be an alphanumeric string including spaces, commas, periods, hyphens, and underscores with length between 1 and 255.
*/
set identifier(value: string | null);
/**
* @param value A unique identifier to identify this individual upload task.
* Must be an alphanumeric string including spaces, commas, periods, hyphens, and underscores with length between 1 and 255.
* @returns
*/
withIdentifier(value: string | null): this;
/**
* The size threshold in bytes for when to use multipart uploads.
* Uploads over this size will automatically use a multipart upload strategy, while uploads equal or smaller than this threshold will use a single connection to upload the whole object.
* @returns
*/
get sizeThresholdForMultipartUploadBytes(): number | null;
/**
* @param value The size threshold in bytes for when to use multipart uploads.
* Uploads over this size will automatically use a multipart upload strategy, while uploads equal or smaller than this threshold will use a single connection to upload the whole object.
*/
set sizeThresholdForMultipartUploadBytes(value: number | null);
/**
* @param value The size threshold in bytes for when to use multipart uploads.
* Uploads over this size will automatically use a multipart upload strategy, while uploads equal or smaller than this threshold will use a single connection to upload the whole object.
* @returns
*/
withSizeThresholdForMultipartUploadBytes(value: number | null): this;
/**
* Priority for this upload task. Lower values are higher priority. If not specified it will have the lowest priority.
* @returns
*/
get priority(): number | null;
/**
* @param value Priority for this upload task. Lower values are higher priority. If not specified it will have the lowest priority.
*/
set priority(value: number | null);
/**
* @param value Priority for this upload task. Lower values are higher priority. If not specified it will have the lowest priority.
* @returns
*/
withPriority(value: number | null): this;
/**
* Enable or disable this export. Default is false.
* @returns
*/
get disabled(): boolean | null;
/**
* @param value Enable or disable this export. Default is false.
*/
set disabled(value: boolean | null);
/**
* @param value Enable or disable this export. Default is false.
* @returns
*/
withDisabled(value: boolean | null): this;
/**
* Event status configuration that specifies the target status stream and verbosity.
* @returns
*/
get statusConfig(): StatusConfig | null;
/**
* @param value Event status configuration that specifies the target status stream and verbosity.
*/
set statusConfig(value: StatusConfig | null);
/**
* @param value Event status configuration that specifies the target status stream and verbosity.
* @returns
*/
withStatusConfig(value: StatusConfig | null): this;
static fromMap(d: S3ExportTaskExecutorConfigMap): S3ExportTaskExecutorConfig;
asMap(): S3ExportTaskDefinitionMap;
static typesMap: TypesMap;
static formatsMap: Record<string, never>;
static validationsMap: ValidationsMap;
}
export interface S3ExportTaskExecutorConfigMap {
identifier?: string | null;
sizeThresholdForMultipartUploadBytes?: number | null;
priority?: number | null;
disabled?: boolean | null;
statusConfig?: StatusConfig | null;
}
/**
* Defines how and where the stream is uploaded.
*/
export class ExportDefinition {
/**
* @param http Defines how the stream is uploaded to an HTTP endpoint.
* @param iotAnalytics Defines how the stream is uploaded to IoT Analytics.
* @param kinesis Defines how the stream is uploaded to Kinesis.
* @param IotSitewise Defines how the stream is uploaded to IoT SiteWise.
* @param s3TaskExecutor Defines the list of configs for S3 task executors.
*/
constructor(
http?: HTTPConfig[] | null,
iotAnalytics?: IoTAnalyticsConfig[] | null,
kinesis?: KinesisConfig[] | null,
IotSitewise?: IoTSiteWiseConfig[] | null,
s3TaskExecutor?: S3ExportTaskExecutorConfig[] | null,
);
/**
* Defines how the stream is uploaded to an HTTP endpoint.
* @returns
*/
get http(): HTTPConfig[] | null;
/**
* @param value Defines how the stream is uploaded to an HTTP endpoint.
*/
set http(value: HTTPConfig[] | null);
/**
* @param value Defines how the stream is uploaded to an HTTP endpoint.
* @returns
*/
withHttp(value: HTTPConfig[] | null): this;
/**
* Defines how the stream is uploaded to IoT Analytics.
* @returns
*/
get iotAnalytics(): IoTAnalyticsConfig[] | null;
/**
* @param value Defines how the stream is uploaded to IoT Analytics.
*/
set iotAnalytics(value: IoTAnalyticsConfig[] | null);
/**
* @param value Defines how the stream is uploaded to IoT Analytics.
* @returns
*/
withIotAnalytics(value: IoTAnalyticsConfig[] | null): this;
/**
* Defines how the stream is uploaded to Kinesis.
* @returns
*/
get kinesis(): KinesisConfig[] | null;
/**
* @param value Defines how the stream is uploaded to Kinesis.
*/
set kinesis(value: KinesisConfig[] | null);
/**
* @param value Defines how the stream is uploaded to Kinesis.
* @returns
*/
withKinesis(value: KinesisConfig[] | null): this;
/**
* Defines how the stream is uploaded to IoT SiteWise.
* @returns
*/
get IotSitewise(): IoTSiteWiseConfig[] | null;
/**
* @param value Defines how the stream is uploaded to IoT SiteWise.
*/
set IotSitewise(value: IoTSiteWiseConfig[] | null);
/**
* @param value Defines how the stream is uploaded to IoT SiteWise.
* @returns
*/
withIotSitewise(value: IoTSiteWiseConfig[] | null): this;
/**
* Defines the list of configs for S3 task executors.
* @returns
*/
get s3TaskExecutor(): S3ExportTaskExecutorConfig[] | null;
/**
* @param value Defines the list of configs for S3 task executors.
*/
set s3TaskExecutor(value: S3ExportTaskExecutorConfig[] | null);
/**
* @param value Defines the list of configs for S3 task executors.
* @returns
*/
withS3TaskExecutor(value: S3ExportTaskExecutorConfig[] | null): this;
static fromMap(d: ExportDefinitionMap): ExportDefinition;
asMap(): ExportDefinitionMap;
static typesMap: TypesMap;
static formatsMap: Record<string, never>;
static validationsMap: ValidationsMap;
}
export interface ExportDefinitionMap {
http?: HTTPConfigMap[] | null;
kinesis?: KinesisConfigMap[] | null;
iotAnalytics?: IoTAnalyticsConfigMap[] | null;
IotSitewise?: IoTSiteWiseConfigMap[] | null;
s3TaskExecutor?: S3ExportTaskExecutorConfigMap[] | null;
}
/**
* Object defining a message stream used in the CreateMessageStream and UpdateMessageStream API.
*/
export class MessageStreamDefinition {
/**
* @param name The unique name of the stream.
* Must be an alphanumeric string including spaces, commas, periods, hyphens, and underscores with length between 1 and 255.
* @param maxSize The maximum size in bytes for the entire stream. Set to 256MB by default with a minimum of 1KB and a maximum of 8192PB.
* @param streamSegmentSize The size of each segment of the stream. Set to 16MB by default with a minimum of 1KB and a maximum of 2GB.
* Data is only deleted segment by segment, so the segment size is the smallest amount of data which can be deleted.
* @param timeToLiveMillis Time to live for each message in milliseconds. Data may be deleted at any time after the TTL expires; deletion is not guaranteed to occur immediately when the TTL expires.
* The minimum value is 60000 milliseconds and the maximum is 9223372036854 milliseconds.
* @param strategyOnFull What to do when the maximum size of the stream is reached.
* RejectNewData: any append message request after the stream is full will be rejected with an exception.
* OverwriteOldestData: the oldest stream segments will be deleted until there is room for the new message.
* @param persistence Stream persistence. If set to File, the file system will be used to persist messages long-term and is resilient to restarts.
* Memory should be used when performance matters more than durability as it only stores the stream in memory and never writes to the disk.
* @param flushOnWrite This only applies when Persistence is set to File mode.
* Waits for the filesystem to complete the write for every message. This is safer, but slower. Default is false.
* @param exportDefinition Defines how and where the stream is uploaded. See the definition of the ExportDefinition object for more detail.
*/
constructor(
name?: string | null,
maxSize?: number | null,
streamSegmentSize?: number | null,
timeToLiveMillis?: number | null,
strategyOnFull?: StrategyOnFull | null,
persistence?: Persistence | null,
flushOnWrite?: boolean | null,
exportDefinition?: ExportDefinition | null,
);
/**
* The unique name of the stream.
* Must be an alphanumeric string including spaces, commas, periods, hyphens, and underscores with length between 1 and 255.
* @returns
*/
get name(): string | null;
/**
* @param value The unique name of the stream.
* Must be an alphanumeric string including spaces, commas, periods, hyphens, and underscores with length between 1 and 255.
*/
set name(value: string | null);
/**
* @param value The unique name of the stream.
* Must be an alphanumeric string including spaces, commas, periods, hyphens, and underscores with length between 1 and 255.
* @returns
*/
withName(value: string | null): this;
/**
* The maximum size in bytes for the entire stream. Set to 256MB by default with a minimum of 1KB and a maximum of 8192PB.
* @returns
*/
get maxSize(): number | null;
/**
* @param value The maximum size in bytes for the entire stream. Set to 256MB by default with a minimum of 1KB and a maximum of 8192PB.
*/
set maxSize(value: number | null);
/**
* @param value The maximum size in bytes for the entire stream. Set to 256MB by default with a minimum of 1KB and a maximum of 8192PB.
* @returns
*/
withMaxSize(value: number | null): this;
/**
* The size of each segment of the stream. Set to 16MB by default with a minimum of 1KB and a maximum of 2GB.
* Data is only deleted segment by segment, so the segment size is the smallest amount of data which can be deleted.
* @returns
*/
get streamSegmentSize(): number | null;
/**
* @param value The size of each segment of the stream. Set to 16MB by default with a minimum of 1KB and a maximum of 2GB.
* Data is only deleted segment by segment, so the segment size is the smallest amount of data which can be deleted.
*/
set streamSegmentSize(value: number | null);
/**
* @param value The size of each segment of the stream. Set to 16MB by default with a minimum of 1KB and a maximum of 2GB.
* Data is only deleted segment by segment, so the segment size is the smallest amount of data which can be deleted.
* @returns
*/
withStreamSegmentSize(value: number | null): this;
/**
* Time to live for each message in milliseconds. Data may be deleted at any time after the TTL expires; deletion is not guaranteed to occur immediately when the TTL expires.
* The minimum value is 60000 milliseconds and the maximum is 9223372036854 milliseconds.
* @returns
*/
get timeToLiveMillis(): number | null;
/**
* @param value Time to live for each message in milliseconds. Data may be deleted at any time after the TTL expires; deletion is not guaranteed to occur immediately when the TTL expires.
* The minimum value is 60000 milliseconds and the maximum is 9223372036854 milliseconds.
*/
set timeToLiveMillis(value: number | null);
/**
* @param value Time to live for each message in milliseconds. Data may be deleted at any time after the TTL expires; deletion is not guaranteed to occur immediately when the TTL expires.
* The minimum value is 60000 milliseconds and the maximum is 9223372036854 milliseconds.
* @returns
*/
withTimeToLiveMillis(value: number | null): this;
/**
* What to do when the maximum size of the stream is reached.
* RejectNewData: any append message request after the stream is full will be rejected with an exception.
* OverwriteOldestData: the oldest stream segments will be deleted until there is room for the new message.
* @returns
*/
get strategyOnFull(): StrategyOnFull | null;
/**
* @param value What to do when the maximum size of the stream is reached.
* RejectNewData: any append message request after the stream is full will be rejected with an exception.
* OverwriteOldestData: the oldest stream segments will be deleted until there is room for the new message.
*/
set strategyOnFull(value: StrategyOnFull | null);
/**
* @param value What to do when the maximum size of the stream is reached.
* RejectNewData: any append message request after the stream is full will be rejected with an exception.
* OverwriteOldestData: the oldest stream segments will be deleted until there is room for the new message.
* @returns
*/
withStrategyOnFull(value: StrategyOnFull | null): this;
/**
* Stream persistence. If set to File, the file system will be used to persist messages long-term and is resilient to restarts.
* Memory should be used when performance matters more than durability as it only stores the stream in memory and never writes to the disk.
* @returns
*/
get persistence(): Persistence | null;
/**
* @param value Stream persistence. If set to File, the file system will be used to persist messages long-term and is resilient to restarts.
* Memory should be used when performance matters more than durability as it only stores the stream in memory and never writes to the disk.
*/
set persistence(value: Persistence | null);
/**
* @param value Stream persistence. If set to File, the file system will be used to persist messages long-term and is resilient to restarts.
* Memory should be used when performance matters more than durability as it only stores the stream in memory and never writes to the disk.
* @returns
*/
withPersistence(value: Persistence | null): this;
/**
* This only applies when Persistence is set to File mode.
* Waits for the filesystem to complete the write for every message. This is safer, but slower. Default is false.
* @returns
*/
get flushOnWrite(): boolean | null;
/**
* @param value This only applies when Persistence is set to File mode.
* Waits for the filesystem to complete the write for every message. This is safer, but slower. Default is false.
*/
set flushOnWrite(value: boolean | null);
/**
* @param value This only applies when Persistence is set to File mode.
* Waits for the filesystem to complete the write for every message. This is safer, but slower. Default is false.
* @returns
*/
withFlushOnWrite(value: boolean | null): this;
/**
* Defines how and where the stream is uploaded. See the definition of the ExportDefinition object for more detail.
* @returns
*/
get exportDefinition(): ExportDefinition | null;
/**
* @param value Defines how and where the stream is uploaded. See the definition of the ExportDefinition object for more detail.
*/
set exportDefinition(value: ExportDefinition | null);
/**
* @param value Defines how and where the stream is uploaded. See the definition of the ExportDefinition object for more detail.
* @returns
*/
withExportDefinition(value: ExportDefinition | null): this;
static fromMap(d: MessageStreamDefinitionMap): MessageStreamDefinition;
asMap(): MessageStreamDefinitionMap;
static typesMap: TypesMap;
static formatsMap: Record<string, never>;
static validationsMap: ValidationsMap;
}
export interface MessageStreamDefinitionMap {
name?: string | null;
maxSize?: number | null;
streamSegmentSize?: number | null;
timeToLiveMillis?: number | null;
strategyOnFull?: StrategyOnFullMap | null;
persistence?: PersistenceMap | null;
flushOnWrite?: boolean | null;
exportDefinition?: ExportDefinitionMap | null;
}
export {}; | the_stack |
import { describe, expect, it } from '@jest/globals';
import { ImportPostman } from './postman';
import { HttpsSchemaGetpostmanComJsonCollectionV210, Request1 } from './postman-2.1.types';
describe('postman', () => {
const postmanSchema = ({
requests = [],
version = 'v2.0.0',
}: {
requests?: Request1[];
version?: string;
} = {}) => JSON.parse(JSON.stringify({
info: {
name: 'Postman Schema',
schema: `https:\/\/schema.getpostman.com\/json\/collection\/${version}\/collection.json`,
},
item: [
{
request: {},
name: 'Projects',
item: [
...requests,
{
name: 'Request 1',
request: {
},
},
],
},
],
})) as HttpsSchemaGetpostmanComJsonCollectionV210;
describe('headers', () => {
describe('awsv4', () => {
it('should not duplicate headers', () => {
const request: Request1 = {
header: [
{
key: 'Authorization',
value: 'AWS4-HMAC-SHA256 Credential=<accessKeyId>/20220110/<region>/<service>/aws4_request, SignedHeaders=accept;content-type;host;x-amz-date;x-amz-security-token, Signature=ed270ed6ad1cad3513f6edad9692e4496e321e44954c70a86504eea5e0ef1ff5',
},
{
key: 'X-Amz-Security-Token',
value: 'someTokenSomethingSomething',
},
],
};
const schema = postmanSchema({ requests: [request] });
const postman = new ImportPostman(schema);
const { authentication, headers } = postman.importRequestItem({ request }, 'n/a');
expect(authentication).toEqual({
accessKeyId: '<accessKeyId>',
disabled: false,
region: '<region>',
secretAccessKey: '',
service: '<service>',
sessionToken: 'someTokenSomethingSomething',
type: 'iam',
});
expect(headers).toEqual([]);
});
});
describe('basic', () => {
it('returns a simple basic auth and does not duplicate authorization header', () => {
const username = 'ziltoid';
const password = 'theOmniscient';
const token = Buffer.from(`${username}:${password}`).toString('base64');
const nonAuthHeader = {
key: 'Another-key',
value: 'Another-value',
};
const request: Request1 = {
header: [
{
key: 'Authorization',
value: `Basic ${token}`,
},
nonAuthHeader,
],
};
const schema = postmanSchema({ requests: [request] });
const postman = new ImportPostman(schema);
const { authentication, headers } = postman.importRequestItem({ request }, 'n/a');
expect(authentication).toEqual({
type: 'basic',
disabled: false,
username: 'ziltoid',
password: 'theOmniscient',
});
expect(headers).toEqual([{
name: nonAuthHeader.key,
value: nonAuthHeader.value,
}]);
});
});
describe('bearer', () => {
it('returns simple token', () => {
const nonAuthHeader = {
key: 'Another-key',
value: 'Another-value',
};
const request: Request1 = {
header: [{
key: 'Authorization',
value: 'Bearer {{token}}',
}, nonAuthHeader],
};
const schema = postmanSchema({ requests: [request] });
const postman = new ImportPostman(schema);
const { authentication, headers } = postman.importRequestItem({ request }, 'n/a');
expect(authentication).toEqual({
type: 'bearer',
disabled: false,
token: '{{token}}',
prefix: '',
});
expect(headers).toEqual([{
name: nonAuthHeader.key,
value: nonAuthHeader.value,
}]);
});
it('handles multiple spaces', () => {
const request: Request1 = {
header: [{
key: 'Authorization',
value: 'Bearer {{token}}',
}],
};
const schema = postmanSchema({ requests: [request] });
const postman = new ImportPostman(schema);
const { authentication } = postman.importRequestItem({ request }, 'n/a');
expect(authentication).toEqual({
type: 'bearer',
disabled: false,
token: '{{token}}',
prefix: '',
});
});
it('handles no token', () => {
const request: Request1 = {
header: [{
key: 'Authorization',
value: 'Bearer ',
}],
};
const schema = postmanSchema({ requests: [request] });
const postman = new ImportPostman(schema);
const { authentication, headers } = postman.importRequestItem({ request }, 'n/a');
expect(authentication).toEqual({
type: 'bearer',
disabled: false,
token: '',
prefix: '',
});
expect(headers).toEqual([]);
});
});
describe('digest', () => {
it('returns simple digest authentication', () => {
const username = 'Gandalf';
const digest = `Digest username="${username}", realm="Realm", nonce="Nonce", uri="//api/v1/report?start_date_min=2019-01-01T00%3A00%3A00%2B00%3A00&start_date_max=2019-01-01T23%3A59%3A59%2B00%3A00&projects[]=%2Fprojects%2F1&include_child_projects=1&search_query=meeting&columns[]=project&include_project_data=1&sort[]=-duration", algorithm="MD5", response="f3f762321e158aefe103529eda4ddb7c", opaque="Opaque"`;
const request: Request1 = {
header: [{
key: 'Authorization',
value: digest,
}],
};
const schema = postmanSchema({ requests: [request] });
const postman = new ImportPostman(schema);
const { authentication, headers } = postman.importRequestItem({ request }, 'n/a');
expect(authentication).toEqual({
type: 'digest',
disabled: false,
username: username,
password: '',
});
expect(headers).toEqual([]);
});
});
describe('oauth1', () => {
it('returns simple oauth1 authentication', () => {
const oauth1 = 'OAuth realm="Realm",oauth_consumer_key="Consumer%20Key",oauth_token="Access%20Token",oauth_signature_method="HMAC-SHA1",oauth_timestamp="Timestamp",oauth_nonce="Nonce",oauth_version="Version",oauth_callback="Callback%20URL",oauth_verifier="Verifier",oauth_signature="TwJvZVasVWTL6X%2Bz3lmuiyvaX2Q%3D"';
const request: Request1 = {
header: [{
key: 'Authorization',
value: oauth1,
}],
};
const schema = postmanSchema({ requests: [request] });
const postman = new ImportPostman(schema);
const { authentication, headers } = postman.importRequestItem({ request }, 'n/a');
expect(authentication).toEqual({
callback: 'Callback%20URL',
consumerKey: 'Consumer%20Key',
consumerSecret: '',
disabled: false,
nonce: 'Nonce',
privateKey: '',
realm: 'Realm',
signatureMethod: 'HMAC-SHA1',
timestamp: 'Timestamp',
tokenKey: 'Access%20Token',
tokenSecret: '',
type: 'oauth1',
verifier: 'Verifier',
version: 'Version',
});
expect(headers).toEqual([]);
});
});
describe('oauth2', () => {
// we don't have a importOauth2AuthenticationFromHeader with which to write a test for since importBearerAuthenticationFromHeader handles this case
});
});
describe('oauth2', () => {
const request: Request1 = {
auth: {
type: 'oauth2',
oauth2: [
{
key: 'clientSecret',
value: 'exampleClientSecret',
type: 'string',
},
{
key: 'clientId',
value: 'exampleClientId',
type: 'string',
},
{
key: 'accessTokenUrl',
value: 'exampleAccessTokenUrl',
type: 'string',
},
{
key: 'authUrl',
value: 'exampleAuthorizeUrl',
type: 'string',
},
{
key: 'redirect_uri',
value: 'exampleCallbackUrl',
type: 'string',
},
{
key: 'grant_type',
value: 'authorization_code',
type: 'string',
},
{
key: 'tokenName',
value: 'Access token',
type: 'string',
},
{
key: 'challengeAlgorithm',
value: 'S256',
type: 'string',
},
{
key: 'addTokenTo',
value: 'header',
type: 'string',
},
{
key: 'client_authentication',
value: 'header',
type: 'string',
},
],
},
};
it('returns empty oauth2 if Postman v2.0.0', () => {
const schema = postmanSchema({ requests: [request], version: 'v2.0.0' });
const postman = new ImportPostman(schema);
const { authentication } = postman.importRequestItem({ request }, 'n/a');
expect(authentication).toEqual({
accessTokenUrl: '',
authorizationUrl: '',
disabled: true,
grantType: 'authorization_code',
password: '',
type: 'oauth2',
username: '',
});
});
it('returns oauth2 if Postman v2.1.0', () => {
const schema = postmanSchema({ requests: [request], version: 'v2.1.0' });
const postman = new ImportPostman(schema);
const { authentication } = postman.importRequestItem({ request }, 'n/a');
expect(authentication).toEqual({
accessTokenUrl: 'exampleAccessTokenUrl',
authorizationUrl: 'exampleAuthorizeUrl',
clientId: 'exampleClientId',
clientSecret: 'exampleClientSecret',
disabled: false,
grantType: 'authorization_code',
password: '',
redirectUrl: 'exampleCallbackUrl',
type: 'oauth2',
username: '',
});
});
});
}); | the_stack |
import {promisify} from 'util';
import {Response} from 'express';
import {
Authorized,
BadRequestError,
Body,
ContentType,
Controller,
CurrentUser,
Delete,
ForbiddenError,
Get,
NotFoundError,
Param,
Post,
Res,
UseBefore
} from 'routing-controllers';
import passportJwtMiddleware from '../security/passportJwtMiddleware';
import {Unit} from '../models/units/Unit';
import {IDownload} from '../../../shared/models/IDownload';
import {IFileUnit} from '../../../shared/models/units/IFileUnit';
import {Lecture} from '../models/Lecture';
import {IUser} from '../../../shared/models/IUser';
import {Course} from '../models/Course';
import config from '../config/main';
import {errorCodes} from '../config/errorCodes';
import * as fs from 'fs';
import * as path from 'path';
import {File} from '../models/mediaManager/File';
import {ICourse} from '../../../shared/models/ICourse';
import * as mongoose from 'mongoose';
import {CreateOptions} from 'html-pdf';
import crypto = require('crypto');
import archiver = require('archiver');
const pdf = require('html-pdf');
const phantomjs = require('phantomjs-prebuilt');
const binPath = phantomjs.path;
// Set all routes which should use json to json, the standard is blob streaming data
@Controller('/download')
@UseBefore(passportJwtMiddleware)
export class DownloadController {
private markdownCss: string;
constructor() {
setInterval(this.cleanupCache, config.timeToLiveCacheValue * 60);
this.markdownCss = this.readMarkdownCss();
}
cleanupCache() {
const expire = Date.now() - 3600 * 1000;
const files = fs.readdirSync(config.tmpFileCacheFolder);
for (const fileName of files) {
if (/download_(\w+).zip/.test(fileName) === false) {
continue;
}
const filePath = path.join(config.tmpFileCacheFolder, fileName);
const fileStat = fs.statSync(filePath);
if (fileStat.ctimeMs >= expire) {
continue;
}
fs.unlinkSync(filePath);
}
}
replaceCharInFilename(filename: string) {
return filename.replace(/[^a-zA-Z0-9 -]/g, '') // remove special characters
.replace(/ /g, '-') // replace space by dashes
.replace(/-+/g, '-');
}
async calcPackage(pack: IDownload) {
let localTotalSize = 0;
const localTooLargeFiles: Array<String> = [];
for (const lec of pack.lectures) {
for (const unit of lec.units) {
const localUnit = await Unit
.findOne({_id: unit.unitId})
.orFail(new NotFoundError());
if (localUnit.__t === 'file') {
const fileUnit = <IFileUnit><any>localUnit;
fileUnit.files.forEach((file, index) => {
if (unit.files.indexOf(index) > -1) {
if ((file.size / 1024) > config.maxFileSize) {
localTooLargeFiles.push(file.link);
}
localTotalSize += (file.size / 1024);
}
});
}
}
}
return {totalSize: localTotalSize, tooLargeFiles: localTooLargeFiles};
}
/**
* @api {get} /api/download/:id Request archived file
* @apiName GetDownload
* @apiGroup Download
*
* @apiParam {String} id Course name.
* @apiParam {Response} response Response (input).
*
* @apiSuccess {Response} response Response (output).
*
* @apiSuccessExample {json} Success-Response:
* UEsFBgAAAAAAAAAAAAAAAAAAAAAAAA==
*
* @apiError NotFoundError File could not be found.
* @apiError ForbiddenError Invalid id i.e. filename (e.g. '../something').
*/
@Get('/:id')
async getArchivedFile(@Param('id') id: string, @Res() response: Response) {
const tmpFileCacheFolder = path.resolve(config.tmpFileCacheFolder);
const filePath = path.join(tmpFileCacheFolder, 'download_' + id + '.zip');
// Assures that the filePath actually points to a file within the tmpFileCacheFolder.
// This is because the id parameter could be something like '../forbiddenFile' ('../' via %2E%2E%2F in the URL).
if (path.dirname(filePath) !== tmpFileCacheFolder) {
throw new ForbiddenError(errorCodes.file.forbiddenPath.code);
}
if (!fs.existsSync(filePath)) {
throw new NotFoundError();
}
response.setHeader('Connection', 'keep-alive');
response.setHeader('Access-Control-Expose-Headers', 'Content-Disposition');
await promisify<string, void>(response.download.bind(response))(filePath);
return response;
}
async createFileHash() {
return crypto.randomBytes(16).toString('hex');
}
/**
* @api {post} /api/download/pdf/individual Post download request individual PDF
* @apiName PostDownload
* @apiGroup Download
*
* @apiParam {IDownload} data Course data.
* @apiParam {IUser} currentUser Currently logged in user.
*
* @apiSuccess {String} hash Hash value.
*
* @apiSuccessExample {json} Success-Response:
* "da39a3ee5e6b4b0d3255bfef95601890afd80709"
*
* @apiError NotFoundError
* @apiError ForbiddenError
* @apiError BadRequestError
*/
@Post('/pdf/individual')
@ContentType('application/json')
async postDownloadRequestPDFIndividual(@Body() data: IDownload, @CurrentUser() user: IUser) {
if (!data.lectures.length) {
throw new BadRequestError();
}
const course = await Course
.findOne({_id: data.courseName})
.orFail(new NotFoundError());
this.userCanExportCourse(course, user);
const size = await this.calcPackage(data);
if (size.totalSize > config.maxZipSize || size.tooLargeFiles.length !== 0) {
throw new BadRequestError();
}
const hash = await this.createFileHash();
const filePath = path.join(path.resolve(config.tmpFileCacheFolder), 'download_' + hash + '.zip');
const output = fs.createWriteStream(filePath);
const archive = archiver('zip', {
zlib: {level: 9}
});
archive.on('error', (err: Error) => {
throw err;
});
archive.pipe(output);
let lecCounter = 1;
for (const lec of data.lectures) {
const localLecture = await Lecture.findOne({_id: lec.lectureId});
const lcName = this.replaceCharInFilename(localLecture.name);
let unitCounter = 1;
for (const unit of lec.units) {
const localUnit = await Unit
.findOne({_id: unit.unitId})
.orFail(new NotFoundError());
if (localUnit.__t === 'file') {
for (const fileId of unit.files) {
const file = await File.findById(fileId);
archive.file('uploads/' + file.link, {name: lecCounter + '_' + lcName + '/' + unitCounter + '_' + file.name});
}
} else {
const options: CreateOptions = {
phantomPath: binPath,
format: 'A4',
border: {
left: '1cm',
right: '1cm'
},
footer: {
contents: {
default: '<div id="pageFooter">{{page}}/{{pages}}</div>'
}
}
};
let html = '<!DOCTYPE html>\n' +
'<html>\n' +
' <head>' +
' <style>' +
' #pageHeader {text-align: center;border-bottom: 1px solid;padding-bottom: 5px;}' +
' #pageFooter {text-align: center;border-top: 1px solid;padding-top: 5px;}' +
' html,body {font-family: \'Helvetica\', \'Arial\', sans-serif; font-size: 12px; line-height: 1.5;}' +
' .codeBox {border: 1px solid grey; font-family: Monaco,Menlo,source-code-pro,monospace; padding: 10px}' +
' #firstPage {page-break-after: always;}' +
' .bottomBoxWrapper {height:800px; position: relative}' +
' .bottomBox {position: absolute; bottom: 0;}' + this.markdownCss +
' </style>' +
' </head>';
html += await localUnit.toHtmlForIndividualPDF();
html += '</html>';
const name = lecCounter + '_' + lcName + '/' + unitCounter + '_' + this.replaceCharInFilename(localUnit.name) + '.pdf';
const buffer = await this.createPdf(html, options);
archive.append(buffer, {name});
}
unitCounter++;
}
lecCounter++;
}
return new Promise((resolve) => {
output.on('close', () => resolve(hash));
archive.finalize();
});
}
/**
* @api {post} /api/download/pdf/single Post download request single PDF
* @apiName PostDownload
* @apiGroup Download
*
* @apiParam {IDownload} data Course data.
* @apiParam {IUser} currentUser Currently logged in user.
*
* @apiSuccess {String} hash Hash value.
*
* @apiSuccessExample {json} Success-Response:
* "da39a3ee5e6b4b0d3255bfef95601890afd80709"
*
* @apiError NotFoundError
* @apiError ForbiddenError
* @apiError BadRequestError
*/
@Post('/pdf/single')
@ContentType('application/json')
async postDownloadRequestPDFSingle(@Body() data: IDownload, @CurrentUser() user: IUser) {
if (!data.lectures.length) {
throw new BadRequestError();
}
const course = await Course
.findOne({_id: data.courseName})
.orFail(new NotFoundError());
this.userCanExportCourse(course, user);
const size = await this.calcPackage(data);
if (size.totalSize > config.maxZipSize || size.tooLargeFiles.length !== 0) {
throw new BadRequestError();
}
data.courseName += 'Single';
const hash = await this.createFileHash();
const filePath = path.join(path.resolve(config.tmpFileCacheFolder), 'download_' + hash + '.zip');
const output = fs.createWriteStream(filePath);
const archive = archiver('zip', {
zlib: {level: 9}
});
archive.on('error', (err: Error) => {
throw err;
});
archive.pipe(output);
const options: CreateOptions = {
phantomPath: binPath,
format: 'A4',
border: {
left: '1cm',
right: '1cm',
top: '0',
bottom: '0'
},
footer: {
contents: {
default: '<div id="pageFooter">{{page}}/{{pages}}</div>'
}
},
header: {
contents: '<div id="pageHeader">' + course.name + '</div>',
height: '20mm'
}
};
let html = '<!DOCTYPE html>\n' +
'<html>\n' +
' <head>' +
' <style>' +
' #pageHeader {text-align: center;border-bottom: 1px solid;padding-bottom: 5px;}' +
' #pageFooter {text-align: center;border-top: 1px solid;padding-top: 5px;}' +
' html, body {font-family: \'Helvetica\', \'Arial\', sans-serif; font-size: 12px; line-height: 1.5;}' +
' .codeBox {border: 1px solid grey; font-family: Monaco,Menlo,source-code-pro,monospace; padding: 10px}' +
' #firstPage {page-break-after: always;}' +
' #nextPage {page-break-before: always;}' +
' .bottomBoxWrapper {height:800px; position: relative}' +
' .bottomBox {position: absolute; bottom: 0;}' + this.markdownCss +
' </style>' +
' </head>' +
' <body>' +
' ';
let solutions = '<div id="nextPage"><h2><u>Solutions</u></h2>';
let lecCounter = 1;
let firstSol = false;
for (const lec of data.lectures) {
const localLecture = await Lecture.findOne({_id: lec.lectureId});
const lcName = this.replaceCharInFilename(localLecture.name);
let unitCounter = 1;
let solCounter = 1;
if (lecCounter > 1) {
html += '<div id="nextPage" ><h2>Lecture: ' + localLecture.name + '</h2>';
} else {
html += '<div><h2>Lecture: ' + localLecture.name + '</h2>';
}
for (const unit of lec.units) {
const localUnit = await Unit
.findOne({_id: unit.unitId})
.orFail(new NotFoundError());
if (localUnit.__t === 'file') {
for (const fileId of unit.files) {
const file = await File.findById(fileId);
archive.file(path.join(config.uploadFolder, file.link),
{name: lecCounter + '_' + lcName + '/' + unitCounter + '_' + file.name});
}
} else if ((localUnit.__t === 'code-kata' || localUnit.__t === 'task') && lecCounter > 1 && unitCounter > 1) {
html += '<div id="nextPage" >' + await localUnit.toHtmlForSinglePDF() + '</div>';
} else {
html += await localUnit.toHtmlForSinglePDF();
}
if (localUnit.__t === 'code-kata' || localUnit.__t === 'task') {
if (!firstSol && solCounter === 1) {
solutions += '<div><h2>Lecture: ' + localLecture.name + '</h2>';
firstSol = true;
} else if (solCounter === 1) {
solutions += '<div id="nextPage" ><h2>Lecture: ' + localLecture.name + '</h2>';
} else {
solutions += '<div id="nextPage" >';
}
solutions += await localUnit.toHtmlForSinglePDFSolutions() + '</div>';
solCounter++;
} else if (localUnit.__t !== 'file') {
solutions += await localUnit.toHtmlForSinglePDFSolutions();
}
unitCounter++;
}
html += '</div>';
lecCounter++;
}
html += solutions;
html += '</div></body>' +
'</html>';
const name = this.replaceCharInFilename(course.name) + '.pdf';
const buffer = await this.createPdf(html, options);
archive.append(buffer, {name});
return new Promise((resolve) => {
output.on('close', () => resolve(hash));
archive.finalize();
});
}
private readMarkdownCss() {
try {
return fs.readFileSync(path.resolve(__dirname, '../../styles/md/bundle.css'), 'utf8');
} catch (e) {
console.error(e);
return null;
}
}
private createPdf(html: string, options: CreateOptions): Promise<Buffer> {
return new Promise<Buffer>((resolve, reject) => {
pdf.create(html, options).toBuffer((err: Error, buffer: Buffer) => {
if (err) {
reject(err);
}
resolve(buffer);
});
});
}
/**
* @param course
* @param user
*/
private userCanExportCourse(course: ICourse, user: IUser): boolean {
if (user.role === 'admin') {
return true;
}
if (mongoose.Types.ObjectId(user._id).equals(course.courseAdmin._id)) {
return true;
}
if (course.students.indexOf(user._id) !== -1) {
return true;
}
if (course.teachers.indexOf(user._id) !== -1) {
return true;
}
throw new ForbiddenError();
}
/**
* @api {delete} /api/download/ Request to clean up the cache.
* @apiName DeleteCache
* @apiGroup Download
* @apiPermission admin
*
* @apiSuccess {Object} result Empty object.
*
* @apiSuccessExample {json} Success-Response:
* {}
*/
@Delete('/cache')
@Authorized(['admin'])
deleteCache() {
this.cleanupCache();
return {};
}
} | the_stack |
* Facility for drawing a scale bar to indicate pixel size in physical length
* units.
*
* The physical length with which the scale bar is labeled will be of the form:
*
* significand * 10^exponent
*
* Any exponent may be used, but the significand in the range [1, 10] will be
* equal to one of a
* discrete set of allowed significand values, in order to ensure that the scale
* bar is easy to
* understand.
*/
import {RenderViewport} from 'neuroglancer/display_context';
import {DisplayDimensionRenderInfo, RelativeDisplayScales} from 'neuroglancer/navigation_state';
import {TrackableValue} from 'neuroglancer/trackable_value';
import {RefCounted} from 'neuroglancer/util/disposable';
import {verifyFloat, verifyObjectProperty, verifyString} from 'neuroglancer/util/json';
import {pickSiPrefix} from 'neuroglancer/util/si_units';
import {GL} from 'neuroglancer/webgl/context';
import {OffscreenCopyHelper} from 'neuroglancer/webgl/offscreen';
import {setTextureFromCanvas} from 'neuroglancer/webgl/texture';
/**
* Default set of allowed significand values. 1 is implicitly part of the set.
*/
const DEFAULT_ALLOWED_SIGNIFICANDS = [
1.5,
2,
3,
5,
7.5,
10,
];
export interface LengthUnit {
unit: string;
lengthInNanometers: number;
}
export const ALLOWED_UNITS: LengthUnit[] = [
{unit: 'km', lengthInNanometers: 1e12},
{unit: 'm', lengthInNanometers: 1e9},
{unit: 'mm', lengthInNanometers: 1e6},
{unit: 'µm', lengthInNanometers: 1e3},
{unit: 'nm', lengthInNanometers: 1},
{unit: 'pm', lengthInNanometers: 1e-3},
];
export function pickLengthUnit(lengthInNanometers: number) {
const numAllowedUnits = ALLOWED_UNITS.length;
let unit = ALLOWED_UNITS[numAllowedUnits - 1];
for (let i = 0; i < numAllowedUnits; ++i) {
const allowedUnit = ALLOWED_UNITS[i];
if (lengthInNanometers >= allowedUnit.lengthInNanometers) {
unit = allowedUnit;
break;
}
}
return unit;
}
export function pickVolumeUnit(volumeInCubicNanometers: number) {
const numAllowedUnits = ALLOWED_UNITS.length;
let unit = ALLOWED_UNITS[numAllowedUnits - 1];
for (let i = 0; i < numAllowedUnits; ++i) {
const allowedUnit = ALLOWED_UNITS[i];
if (volumeInCubicNanometers >= Math.pow(allowedUnit.lengthInNanometers, 3)) {
unit = allowedUnit;
break;
}
}
return unit;
}
export class ScaleBarDimensions {
/**
* Allowed significand values. 1 is not included, but is always considered
* part of the set.
*/
allowedSignificands = DEFAULT_ALLOWED_SIGNIFICANDS;
/**
* The target length in pixels. The closest
*/
targetLengthInPixels: number = 0;
/**
* Pixel size in base physical units.
*/
physicalSizePerPixel: number = 0;
/**
* Base physical unit, e.g. "m" (for meters) or "s" (for seconds).
*/
physicalBaseUnit: string;
// The following three fields are computed from the previous three fields.
/**
* Length that scale bar should be drawn, in pixels.
*/
lengthInPixels: number;
/**
* Physical length with which to label the scale bar.
*/
physicalLength: number;
physicalUnit: string;
prevPhysicalSizePerPixel: number = 0;
prevTargetLengthInPixels: number = 0;
prevPhysicalUnit: string = '\0';
/**
* Updates physicalLength, physicalUnit, and lengthInPixels to be the optimal values corresponding
* to targetLengthInPixels and physicalSizePerPixel.
*
* @returns true if the scale bar has changed, false if it is unchanged.
*/
update() {
let {physicalSizePerPixel, targetLengthInPixels} = this;
if (this.prevPhysicalSizePerPixel === physicalSizePerPixel &&
this.prevTargetLengthInPixels === targetLengthInPixels &&
this.prevPhysicalUnit === this.physicalUnit) {
return false;
}
this.prevPhysicalSizePerPixel = physicalSizePerPixel;
this.prevTargetLengthInPixels = targetLengthInPixels;
this.prevPhysicalUnit = this.physicalUnit;
const targetPhysicalSize = targetLengthInPixels * physicalSizePerPixel;
const exponent = Math.floor(Math.log10(targetPhysicalSize));
const tenToThePowerExponent = 10 ** exponent;
const targetSignificand = targetPhysicalSize / tenToThePowerExponent;
// Determine significand value in this.allowedSignificands that is closest
// to targetSignificand.
let bestSignificand = 1;
for (let allowedSignificand of this.allowedSignificands) {
if (Math.abs(allowedSignificand - targetSignificand) <
Math.abs(bestSignificand - targetSignificand)) {
bestSignificand = allowedSignificand;
} else {
// If distance did not decrease, then it can only increase from here.
break;
}
}
const physicalSize = bestSignificand * tenToThePowerExponent;
const siPrefix = pickSiPrefix(physicalSize);
this.lengthInPixels = Math.round(physicalSize / physicalSizePerPixel);
this.physicalUnit = `${siPrefix.prefix}${this.physicalBaseUnit}`;
this.physicalLength = bestSignificand * 10 ** (exponent - siPrefix.exponent);
return true;
}
}
function makeScaleBarTexture(
dimensions: ScaleBarDimensions, gl: GL, texture: WebGLTexture|null, label: string,
options: ScaleBarTextureOptions) {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d')!;
const textHeight = options.textHeightInPixels * options.scaleFactor;
const font = `bold ${textHeight}px ${options.fontName}`;
ctx.font = font;
ctx.fillStyle = 'white';
const text = `${label}${dimensions.physicalLength} ${dimensions.physicalUnit}`;
const textMetrics = ctx.measureText(text);
const innerWidth = Math.max(dimensions.lengthInPixels, textMetrics.width);
const barHeight = options.barHeightInPixels * options.scaleFactor;
const barTopMargin = options.barTopMarginInPixels * options.scaleFactor;
const innerHeight = barHeight + barTopMargin + textHeight;
const padding = options.paddingInPixels * options.scaleFactor;
const totalHeight = innerHeight + 2 * padding;
const totalWidth = innerWidth + 2 * padding;
canvas.width = totalWidth;
canvas.height = totalHeight;
ctx.font = font;
ctx.textAlign = 'center';
ctx.fillStyle = 'rgba(0, 0, 0, 0.3)';
ctx.fillRect(0, 0, totalWidth, totalHeight);
ctx.fillStyle = 'white';
ctx.fillText(text, totalWidth / 2, totalHeight - padding - barHeight - barTopMargin);
ctx.fillRect(padding, totalHeight - padding - barHeight, dimensions.lengthInPixels, barHeight);
setTextureFromCanvas(gl, texture, canvas);
return {width: totalWidth, height: totalHeight};
}
export class ScaleBarTexture extends RefCounted {
texture: WebGLTexture|null = null;
width = 0;
height = 0;
label = '';
factor = 1;
private priorOptions: ScaleBarTextureOptions|undefined = undefined;
private prevLabel: string = '';
constructor(public gl: GL, public dimensions = new ScaleBarDimensions()) {
super();
}
update(options: ScaleBarTextureOptions) {
const {dimensions, label} = this;
let {texture} = this;
if (!dimensions.update() && texture !== null && options === this.priorOptions &&
label == this.prevLabel) {
return;
}
if (texture === null) {
texture = this.texture = this.gl.createTexture();
}
const {width, height} = makeScaleBarTexture(dimensions, this.gl, texture, label, options);
this.priorOptions = options;
this.prevLabel = label;
this.width = width;
this.height = height;
}
disposed() {
this.gl.deleteTexture(this.texture);
this.texture = null;
super.disposed();
}
}
export class MultipleScaleBarTextures extends RefCounted {
private scaleBarCopyHelper = this.registerDisposer(OffscreenCopyHelper.get(this.gl));
private scaleBars: ScaleBarTexture[] = [];
constructor(public gl: GL) {
super();
for (let i = 0; i < 3; ++i) {
this.scaleBars.push(this.registerDisposer(new ScaleBarTexture(gl)));
}
}
draw(
viewport: RenderViewport, displayDimensionRenderInfo: DisplayDimensionRenderInfo,
relativeDisplayScales: RelativeDisplayScales, effectiveZoom: number,
options: ScaleBarOptions) {
const {scaleBars} = this;
const {
displayRank,
displayDimensionIndices,
canonicalVoxelFactors,
globalDimensionNames,
displayDimensionUnits,
displayDimensionScales,
} = displayDimensionRenderInfo;
const {factors} = relativeDisplayScales;
const targetLengthInPixels = Math.min(
options.maxWidthFraction * viewport.logicalWidth,
options.maxWidthInPixels * options.scaleFactor);
let numScaleBars = 0;
for (let i = 0; i < displayRank; ++i) {
const dim = displayDimensionIndices[i];
const unit = displayDimensionUnits[i];
const factor = factors[dim];
let barIndex;
let scaleBar: ScaleBarTexture;
let scaleBarDimensions: ScaleBarDimensions;
for (barIndex = 0; barIndex < numScaleBars; ++barIndex) {
scaleBar = scaleBars[barIndex];
scaleBarDimensions = scaleBar.dimensions;
if (scaleBarDimensions.physicalBaseUnit === unit && scaleBar.factor === factor) {
break;
}
}
if (barIndex === numScaleBars) {
++numScaleBars;
scaleBar = scaleBars[barIndex];
scaleBar.label = '';
scaleBarDimensions = scaleBar.dimensions;
scaleBar.factor = factor;
scaleBarDimensions.physicalBaseUnit = unit;
scaleBarDimensions.targetLengthInPixels = targetLengthInPixels;
scaleBarDimensions.physicalSizePerPixel =
displayDimensionScales[i] * effectiveZoom / canonicalVoxelFactors[i];
}
scaleBar!.label += `${globalDimensionNames[dim]} `;
}
const {gl, scaleBarCopyHelper} = this;
let bottomPixelOffset = options.bottomPixelOffset * options.scaleFactor;
for (let barIndex = numScaleBars - 1; barIndex >= 0; --barIndex) {
const scaleBar = scaleBars[barIndex];
if (numScaleBars === 1) {
scaleBar.label = '';
} else {
scaleBar.label += ': ';
}
scaleBar.update(options);
gl.viewport(
options.leftPixelOffset * options.scaleFactor -
viewport.visibleLeftFraction * viewport.logicalWidth,
bottomPixelOffset -
(1 - (viewport.visibleTopFraction + viewport.visibleHeightFraction)) *
viewport.logicalHeight,
scaleBar.width, scaleBar.height);
scaleBarCopyHelper.draw(scaleBar.texture);
bottomPixelOffset +=
scaleBar.height + options.marginPixelsBetweenScaleBars * options.scaleFactor;
}
}
}
export interface ScaleBarTextureOptions {
textHeightInPixels: number;
barTopMarginInPixels: number;
fontName: string;
barHeightInPixels: number;
paddingInPixels: number;
scaleFactor: number;
}
export interface ScaleBarOptions extends ScaleBarTextureOptions {
maxWidthInPixels: number;
maxWidthFraction: number;
leftPixelOffset: number;
bottomPixelOffset: number;
marginPixelsBetweenScaleBars: number;
}
export const defaultScaleBarTextureOptions: ScaleBarTextureOptions = {
scaleFactor: 1,
textHeightInPixels: 15,
barHeightInPixels: 8,
barTopMarginInPixels: 5,
fontName: 'sans-serif',
paddingInPixels: 2,
};
export const defaultScaleBarOptions: ScaleBarOptions = {
...defaultScaleBarTextureOptions,
maxWidthInPixels: 100,
maxWidthFraction: 0.25,
leftPixelOffset: 10,
bottomPixelOffset: 10,
marginPixelsBetweenScaleBars: 5,
};
function parseScaleBarOptions(obj: any): ScaleBarOptions {
const result = {
...defaultScaleBarOptions,
};
for (const k of <(Exclude<keyof ScaleBarOptions, 'fontName'>)[]>[
'textHeightInPixels', 'barTopMarginInPixels', 'barHeightInPixels', 'paddingInPixels',
'scaleFactor', 'maxWidthInPixels', 'maxWidthFraction', 'leftPixelOffset',
'bottomPixelOffset'
]) {
verifyObjectProperty(obj, k, x => {
if (x !== undefined) {
result[k] = verifyFloat(x);
}
});
}
verifyObjectProperty(obj, 'fontName', x => {
if (x !== undefined) {
result.fontName = verifyString(x);
}
});
return result;
}
export class TrackableScaleBarOptions extends TrackableValue<ScaleBarOptions> {
constructor() {
super(defaultScaleBarOptions, parseScaleBarOptions);
}
} | the_stack |
import * as Kilt from '@kiltprotocol/sdk-js'
import { IDidDetails, KeyRelationship } from '@kiltprotocol/sdk-js'
import type {
SubmittableExtrinsic,
IRequestForAttestation,
MessageBody,
IDidKeyDetails,
} from '@kiltprotocol/sdk-js'
import { mnemonicGenerate } from '@polkadot/util-crypto'
const NODE_URL = 'ws://127.0.0.1:9944'
let tx: SubmittableExtrinsic
let authorizedTx: SubmittableExtrinsic
async function main(): Promise<void> {
/* 1. Initialize KILT SDK and set up node endpoint */
await Kilt.init({ address: NODE_URL })
/* 2. How to generate an account with light DIDs */
// Initialize a keyring
const keyring = new Kilt.Utils.Keyring({
ss58Format: 38,
type: 'ed25519',
})
// Initialize the demo keystore
const keystore = new Kilt.Did.DemoKeystore()
// Create a mnemonic seed
const claimerMnemonic = mnemonicGenerate()
// Generate a new keypair for authentication with the generated seed
const claimerSigningKeypair = await keystore.generateKeypair({
alg: Kilt.Did.SigningAlgorithms.Ed25519,
seed: claimerMnemonic,
})
const claimerEncryptionKeypair = await keystore.generateKeypair({
alg: Kilt.Did.EncryptionAlgorithms.NaclBox,
seed: claimerMnemonic,
})
// Create a light DID from the generated authentication key.
const claimerLightDid = new Kilt.Did.LightDidDetails({
authenticationKey: {
publicKey: claimerSigningKeypair.publicKey,
type: Kilt.Did.DemoKeystore.getKeypairTypeForAlg(
claimerSigningKeypair.alg
),
},
encryptionKey: {
publicKey: claimerEncryptionKeypair.publicKey,
type: Kilt.Did.DemoKeystore.getKeypairTypeForAlg(
claimerEncryptionKeypair.alg
),
},
})
// Example `did:kilt:light:014rXt3vRYupKgtUJgjGjQG45PBa6uDbDzF48iFn96F9RYrBMB:oWFlomlwdWJsaWNLZXlYIABgPwMAHGu5yMbBpdiiFH2djWzJqbSpUc0ymDIVlqV0ZHR5cGVmeDI1NTE5`.
console.log(claimerLightDid.did)
/* 3.1. Building a CTYPE */
const ctype = Kilt.CType.fromSchema({
$schema: 'http://kilt-protocol.org/draft-01/ctype#',
title: 'Drivers License',
properties: {
name: {
type: 'string',
},
age: {
type: 'integer',
},
},
type: 'object',
})
/* To store the CTYPE on the blockchain, you have to call: */
const accountMnemonic =
'receive clutch item involve chaos clutch furnace arrest claw isolate okay together'
const account = keyring.addFromMnemonic(accountMnemonic)
const fullDid = await Kilt.Did.createOnChainDidFromSeed(
account,
keystore,
accountMnemonic,
// using ed25519 as key type because this is how the endowed account is set up
Kilt.Did.SigningAlgorithms.Ed25519
)
tx = await ctype.store()
authorizedTx = await fullDid.authorizeExtrinsic(tx, keystore, account.address)
await Kilt.BlockchainUtils.signAndSubmitTx(authorizedTx, account, {
resolveOn: Kilt.BlockchainUtils.IS_IN_BLOCK,
reSign: true,
})
/* signAndSubmitTx can be passed SubscriptionPromise.Options, to control resolve and reject criteria, set tip value, or activate re-sign-re-send capabilities:
// await Kilt.BlockchainUtils.signAndSubmitTx(tx, account, {
// resolveOn: Kilt.BlockchainUtils.IS_FINALIZED,
// rejectOn: Kilt.BlockchainUtils.IS_ERROR,
// reSign: true,
// tip: 10_000_000,
// })
/* or manually step by step */
// const chain = Kilt.connect()
// chain.signTx(account, tx, 10_000)
// await Kilt.BlockchainUtils.submitSignedTx(tx)
/* At the end of the process, the `CType` object should contain the following. */
console.log(ctype)
/* To construct a claim, we need to know the structure of the claim that is defined in a CTYPE */
const rawClaim = {
name: 'Alice',
age: 29,
}
/* Now we can easily create the KILT compliant claim */
const claim = Kilt.Claim.fromCTypeAndClaimContents(
ctype,
rawClaim,
claimerLightDid.did
)
/* As a result we get the following KILT claim: */
console.log(claim)
/* 5.1.1. Requesting an Attestation */
const requestForAttestation = Kilt.RequestForAttestation.fromClaim(claim)
await requestForAttestation.signWithDid(keystore, claimerLightDid)
/* The `requestForAttestation` object looks like this: */
console.log(requestForAttestation)
/* Before we can send the request for an attestation to an Attester, we should first fetch the on chain did and create an encryption key. */
const attesterFullDid = (await Kilt.Did.resolveDoc(fullDid.did))
?.details as IDidDetails
/* Creating an encryption key */
/* First, we create the request for an attestation message in which the Claimer automatically encodes the message with the public key of the Attester: */
const messageBody: MessageBody = {
content: { requestForAttestation },
type: Kilt.Message.BodyType.REQUEST_ATTESTATION,
}
const message = new Kilt.Message(
messageBody,
claimerLightDid.did,
attesterFullDid.did
)
/* The complete `message` looks as follows: */
console.log(message)
const attesterEncryptionKey = attesterFullDid.getKeys(
KeyRelationship.keyAgreement
)[0] as IDidKeyDetails<string>
const claimerEncryptionKey = claimerLightDid.getKeys(
KeyRelationship.keyAgreement
)[0] as IDidKeyDetails<string>
/* The message can be encrypted as follows: */
const encryptedMessage = await message.encrypt(
claimerEncryptionKey,
attesterEncryptionKey,
keystore
)
/* Therefore, **during decryption** both the **sender account and the validity of the message are checked automatically**. */
const decrypted = await Kilt.Message.decrypt(encryptedMessage, keystore)
/* At this point the Attester has the original request for attestation object: */
if (decrypted.body.type === Kilt.Message.BodyType.REQUEST_ATTESTATION) {
const extractedRequestForAttestation: IRequestForAttestation =
decrypted.body.content.requestForAttestation
/* The Attester creates the attestation based on the IRequestForAttestation object she received: */
const attestation = Kilt.Attestation.fromRequestAndDid(
extractedRequestForAttestation,
attesterFullDid.did
)
/* The complete `attestation` object looks as follows: */
console.log(attestation)
/* Now the Attester can store and authorize the attestation on the blockchain, which also costs tokens: */
tx = await attestation.store()
authorizedTx = await fullDid.authorizeExtrinsic(
tx,
keystore,
account.address
)
await Kilt.BlockchainUtils.signAndSubmitTx(authorizedTx, account, {
resolveOn: Kilt.BlockchainUtils.IS_IN_BLOCK,
reSign: true,
})
/* The request for attestation is fulfilled with the attestation, but it needs to be combined into the `Credential` object before sending it back to the Claimer: */
const credential = Kilt.Credential.fromRequestAndAttestation(
extractedRequestForAttestation,
attestation
)
/* The complete `credential` object looks as follows: */
console.log(credential)
/* The Attester has to send the `credential` object back to the Claimer in the following message: */
const messageBodyBack: MessageBody = {
content: credential,
type: Kilt.Message.BodyType.SUBMIT_ATTESTATION,
}
const messageBack = new Kilt.Message(
messageBodyBack,
attesterFullDid.did,
claimerLightDid.did
)
/* The complete `messageBack` message then looks as follows: */
console.log(messageBack)
/* After receiving the message, the Claimer just needs to save it and can use it later for verification: */
if (messageBack.body.type === Kilt.Message.BodyType.SUBMIT_ATTESTATION) {
const myCredential = Kilt.Credential.fromCredential({
...messageBack.body.content,
request: requestForAttestation,
})
/* 6. Verify a Claim */
/* As in the attestation, you need a second account to act as the verifier: */
const verifierMnemonic = mnemonicGenerate()
const verifierSigningKeypair = await keystore.generateKeypair({
alg: Kilt.Did.SigningAlgorithms.Ed25519,
seed: verifierMnemonic,
})
const verifierEncryptionKeypair = await keystore.generateKeypair({
alg: Kilt.Did.EncryptionAlgorithms.NaclBox,
seed: verifierMnemonic,
})
// Create the verifier's light DID from the generated authentication key.
const verifierLightDID = new Kilt.Did.LightDidDetails({
authenticationKey: {
publicKey: verifierSigningKeypair.publicKey,
type: Kilt.Did.DemoKeystore.getKeypairTypeForAlg(
verifierSigningKeypair.alg
),
},
encryptionKey: {
publicKey: verifierEncryptionKeypair.publicKey,
type: Kilt.Did.DemoKeystore.getKeypairTypeForAlg(
verifierEncryptionKeypair.alg
),
},
})
/* 6.1. Request presentation for CTYPE */
const messageBodyForClaimer: MessageBody = {
type: Kilt.Message.BodyType.REQUEST_CREDENTIAL,
content: { cTypes: [{ cTypeHash: ctype.hash }] },
}
const messageForClaimer = new Kilt.Message(
messageBodyForClaimer,
verifierLightDID.did,
claimerLightDid.did
)
/* Now the claimer can send a message to verifier including the credential: */
console.log('Requested from verifier:', messageForClaimer.body.content)
const copiedCredential = Kilt.Credential.fromCredential(
JSON.parse(JSON.stringify(myCredential))
)
const credentialForVerifier = await copiedCredential.createPresentation({
selectedAttributes: ['name'],
signer: keystore,
claimerDid: claimerLightDid,
})
const messageBodyForVerifier: MessageBody = {
content: [credentialForVerifier],
type: Kilt.Message.BodyType.SUBMIT_CREDENTIAL,
}
const messageForVerifier = new Kilt.Message(
messageBodyForVerifier,
claimerLightDid.did,
verifierLightDID.did
)
const verifierEncryptionKey = verifierLightDID.getKeys(
KeyRelationship.keyAgreement
)[0] as IDidKeyDetails<string>
/* The message can be encrypted as follows: */
const encryptedMessageForVerifier = await messageForVerifier.encrypt(
claimerEncryptionKey,
verifierEncryptionKey,
keystore
)
/* Therefore, **during decryption** both the **sender account and the validity of the message are checked automatically**. */
const decryptedMessageForVerifier = await Kilt.Message.decrypt(
encryptedMessageForVerifier,
keystore
)
/* 6.2 Verify presentation */
/* When verifying the claimer's message, the verifier has to use their session which was created during the CTYPE request: */
if (
decryptedMessageForVerifier.body.type ===
Kilt.Message.BodyType.SUBMIT_CREDENTIAL
) {
const claims = decryptedMessageForVerifier.body.content
console.log('before verifying', credentialForVerifier)
const verifiablePresentation = Kilt.Credential.fromCredential(claims[0])
const isValid = await verifiablePresentation.verify()
console.log('Verification success?', isValid)
console.log('Credential from verifier perspective:\n', claims)
}
}
}
}
// execute
main().finally(() => Kilt.disconnect()) | the_stack |
import {
colors,
doc,
type DocNode,
type DocNodeInterface,
type DocNodeNamespace,
httpErrors,
type LoadResponse,
} from "./deps.ts";
import { assert } from "./util.ts";
/** An object which represents an "index" of a library/package. */
export interface IndexStructure {
/** An object that describes the structure of the library, where the key is
* the containing folder and the value is an array of modules that represent
* the the "contents" of the folder. */
structure: SerializeMap<string[]>;
/** For modules in the structure, any doc node entries available for the
* module. */
entries: SerializeMap<DocNode[]>;
}
interface ApiModuleData {
data: {
name: string;
description: string;
"star_count": number;
};
}
interface PackageMetaListing {
path: string;
size: number;
type: "file" | "dir";
}
interface PackageMeta {
"uploaded_at": string;
"directory_listing": PackageMetaListing[];
"upload_options": {
type: string;
repository: string;
ref: string;
};
}
interface PackageVersions {
latest: string;
versions: string[];
}
const EXT = [".ts", ".tsx", ".mts", ".cts", ".js", ".jsx", ".mjs", ".cjs"];
const INDEX_MODULES = ["mod", "lib", "main", "index"].flatMap((idx) =>
EXT.map((ext) => `${idx}${ext}`)
);
const MAX_CACHE_SIZE = parseInt(Deno.env.get("MAX_CACHE_SIZE") ?? "", 10) ||
25_000_000;
const RE_IGNORED_MODULE =
/(\/[_.].|(test|.+_test)\.(js|jsx|mjs|cjs|ts|tsx|mts|cts)$)/i;
const RE_MODULE_EXT = /\.(?:js|jsx|mjs|cjs|ts|tsx|mts|cts)$/i;
const RE_PRIVATE_PATH = /\/([_.].|testdata)/;
const S3_BUCKET =
"http://deno-registry2-prod-storagebucket-b3a31d16.s3-website-us-east-1.amazonaws.com/";
const DENO_API = "https://api.deno.land/modules/";
export class SerializeMap<V> extends Map<string, V> {
toJSON(): Record<string, V> {
return Object.fromEntries(this.entries());
}
}
const cachedSpecifiers = new Set<string>();
const cachedResources = new Map<string, LoadResponse>();
const cachedEntries = new Map<string, DocNode[]>();
let cacheSize = 0;
const cachedIndexes = new Map<string, IndexStructure | undefined>();
const cachedPackageData = new Map<string, ApiModuleData | undefined>();
const cachedPackageMeta = new Map<
string,
Map<string, PackageMeta | undefined>
>();
const cachedPackageVersions = new Map<string, PackageVersions | undefined>();
let cacheCheckQueued = false;
/** Check the cache, evicting any cached data using a LRU schema, until the
* cache is below the threshold. */
function checkCache() {
if (cacheSize > MAX_CACHE_SIZE) {
const toEvict: string[] = [];
for (const specifier of cachedSpecifiers) {
const loadResponse = cachedResources.get(specifier);
assert(loadResponse);
assert(loadResponse.kind === "module");
toEvict.push(specifier);
cacheSize -= loadResponse.content.length;
if (cacheSize <= MAX_CACHE_SIZE) {
break;
}
}
console.log(
` ${colors.yellow("evicting")}: ${
colors.bold(`${toEvict.length} specifiers`)
} from cache`,
);
for (const evict of toEvict) {
cachedResources.delete(evict);
cachedSpecifiers.delete(evict);
cachedEntries.delete(evict);
}
}
cacheCheckQueued = false;
}
/** Determine if a given specifier actually resolves to a redirected
* specifier, caching the load responses */
export async function checkRedirect(
specifier: string,
): Promise<string | undefined> {
if (!specifier.startsWith("http")) {
return undefined;
}
const cached = cachedResources.get(specifier);
let finalSpecifier = specifier;
if (cached) {
finalSpecifier = cached.specifier;
} else {
try {
const res = await fetch(specifier, { redirect: "follow" });
if (res.status !== 200) {
// ensure that resources are not leaked
await res.arrayBuffer();
}
const content = await res.text();
const xTypeScriptTypes = res.headers.get("x-typescript-types");
const headers: Record<string, string> = {};
for (const [key, value] of res.headers) {
headers[key.toLowerCase()] = value;
}
cachedResources.set(specifier, {
specifier: res.url,
kind: "module",
headers,
content,
});
cachedSpecifiers.add(specifier);
cacheSize += content.length;
enqueueCheck();
finalSpecifier = xTypeScriptTypes
? new URL(xTypeScriptTypes, res.url).toString()
: res.url;
} catch {
// just swallow errors
}
}
return specifier === finalSpecifier ? undefined : finalSpecifier;
}
function enqueueCheck() {
if (!cacheCheckQueued) {
cacheCheckQueued = true;
queueMicrotask(checkCache);
}
}
function getDirs(path: string, packageMeta: PackageMeta) {
if (path.endsWith("/")) {
path = path.slice(0, -1);
}
if (isDir(path, packageMeta)) {
const dirs: string[] = [];
for (const { path: p, type } of packageMeta.directory_listing) {
if (
p.startsWith(path) && type === "dir" &&
!p.slice(path.length).match(RE_PRIVATE_PATH)
) {
dirs.push(p);
}
}
return dirs;
}
}
export async function getEntries(url: string): Promise<DocNode[]> {
let entries = cachedEntries.get(url);
if (!entries) {
try {
entries = mergeEntries(await doc(url, { load }));
cachedEntries.set(url, entries);
} catch (e) {
if (e instanceof Error) {
if (e.message.includes("Unable to load specifier")) {
throw new httpErrors.NotFound(`The module "${url}" cannot be found`);
} else {
throw new httpErrors.BadRequest(`Bad request: ${e.message}`);
}
} else {
throw new httpErrors.InternalServerError("Unexpected object.");
}
}
}
return entries;
}
function getIndex(dir: string, packageMeta: PackageMeta) {
const files: string[] = [];
for (const { path, type } of packageMeta.directory_listing) {
if (path.startsWith(dir) && type === "file") {
files.push(path);
}
}
for (const index of INDEX_MODULES) {
const needle = `${dir}/${index}`;
const item = files.find((file) => file.toLowerCase() === needle);
if (item) {
return item;
}
}
}
export async function getLatest(pkg: string): Promise<string | undefined> {
const packageVersions = await getPackageVersions(pkg);
return packageVersions?.latest;
}
function getModules(path: string, packageMeta: PackageMeta) {
if (path.endsWith("/")) {
path = path.slice(0, -1);
}
if (isDir(path, packageMeta)) {
const modules: string[] = [];
for (const { path: p, type } of packageMeta.directory_listing) {
const slice = p.slice(path.length);
if (
p.startsWith(path) && type === "file" && slice.lastIndexOf("/") === 0 &&
p.match(RE_MODULE_EXT) &&
!slice.match(RE_IGNORED_MODULE)
) {
modules.push(p);
}
}
if (modules.length) {
return modules;
}
}
}
export async function getPackageDescription(
pkg: string,
): Promise<string | undefined> {
if (!cachedPackageData.has(pkg)) {
const res = await fetch(`${DENO_API}${pkg}`);
let body: ApiModuleData | undefined;
if (res.status === 200) {
body = await res.json();
}
cachedPackageData.set(pkg, body);
}
return cachedPackageData.get(pkg)?.data.description;
}
async function getPackageMeta(
pkg: string,
version: string,
): Promise<PackageMeta | undefined> {
if (!cachedPackageMeta.has(pkg)) {
cachedPackageMeta.set(pkg, new Map());
}
const versionCache = cachedPackageMeta.get(pkg)!;
if (!versionCache.get(version)) {
const res = await fetch(
`${S3_BUCKET}${pkg}/versions/${version}/meta/meta.json`,
);
if (res.status === 200) {
const packageMeta = await res.json() as PackageMeta;
versionCache.set(version, packageMeta);
} else {
versionCache.set(version, undefined);
}
}
return versionCache.get(version);
}
export async function getPackageVersions(
pkg: string,
): Promise<PackageVersions | undefined> {
if (!cachedPackageVersions.has(pkg)) {
const res = await fetch(`${S3_BUCKET}${pkg}/meta/versions.json`);
if (res.status === 200) {
const packageVersions = await res.json() as PackageVersions;
cachedPackageVersions.set(pkg, packageVersions);
} else {
cachedPackageVersions.set(pkg, undefined);
}
}
return cachedPackageVersions.get(pkg);
}
async function getIndexEntries(
proto: string,
host: string,
pkg: string,
version: string,
structure: Map<string, string[]>,
): Promise<SerializeMap<DocNode[]>> {
const indexEntries = new SerializeMap<DocNode[]>();
for (const mods of structure.values()) {
for (const mod of mods) {
const url = pkg === "std"
? `${proto}/${host}/std@${version}${mod}`
: `${proto}/${host}/x/${pkg}@${version}${mod}`;
try {
const entries = await getEntries(url);
if (entries.length) {
indexEntries.set(mod, entries);
}
} catch {
// we just swallow errors here
}
}
}
return indexEntries;
}
export async function getIndexStructure(
proto: string,
host: string,
pkg: string,
version: string,
path = "/",
): Promise<IndexStructure | undefined> {
const packageMeta = await getPackageMeta(pkg, version);
if (packageMeta) {
const dirs = getDirs(path, packageMeta);
if (dirs) {
const structure = new SerializeMap<string[]>();
for (const dir of dirs) {
const index = getIndex(dir, packageMeta);
if (index) {
structure.set(dir, [index]);
} else {
const modules = getModules(dir, packageMeta);
if (modules) {
structure.set(dir, modules);
}
}
}
if (structure.size) {
const entries = await getIndexEntries(
proto,
host,
pkg,
version,
structure,
);
if (entries.size) {
return { structure, entries };
}
}
}
}
}
function isDir(path: string, packageMeta: PackageMeta) {
if (path === "") {
return true;
}
for (const { path: p, type } of packageMeta.directory_listing) {
if (path === p) {
return type === "dir";
}
}
return false;
}
async function load(
specifier: string,
): Promise<LoadResponse | undefined> {
const url = new URL(specifier);
try {
switch (url.protocol) {
case "file:": {
console.error(`local specifier requested: ${specifier}`);
return undefined;
}
case "http:":
case "https:": {
if (cachedResources.has(specifier)) {
cachedSpecifiers.delete(specifier);
cachedSpecifiers.add(specifier);
return cachedResources.get(specifier);
}
const response = await fetch(String(url), { redirect: "follow" });
if (response.status !== 200) {
// ensure that resources are not leaked
await response.arrayBuffer();
return undefined;
}
const content = await response.text();
const headers: Record<string, string> = {};
for (const [key, value] of response.headers) {
headers[key.toLowerCase()] = value;
}
const loadResponse: LoadResponse = {
kind: "module",
specifier: response.url,
headers,
content,
};
cachedResources.set(specifier, loadResponse);
cachedSpecifiers.add(specifier);
cacheSize += content.length;
enqueueCheck();
return loadResponse;
}
default:
return undefined;
}
} catch {
return undefined;
}
}
const decoder = new TextDecoder();
export async function maybeCacheStatic(url: string, host: string) {
if (url.startsWith("deno") && !cachedEntries.has(url)) {
try {
const [lib, version] = host.split("@");
const data = await Deno.readFile(
new URL(
`./static/${lib}${version ? `_${version}` : ""}.json`,
import.meta.url,
),
);
const entries = mergeEntries(JSON.parse(decoder.decode(data)));
cachedEntries.set(url, entries);
} catch (e) {
console.log("error fetching static");
console.log(e);
}
}
}
export async function getStaticIndex(
pkg: string,
version: string,
): Promise<IndexStructure | undefined> {
const key = `${pkg}_${version}`;
if (!cachedIndexes.has(key)) {
try {
const data = await Deno.readFile(
new URL(`./static/${key}.json`, import.meta.url),
);
const index = JSON.parse(decoder.decode(data), (key, value) => {
if (
typeof value === "object" &&
(key === "structure" || key === "entries")
) {
return new SerializeMap(Object.entries(value));
} else {
return value;
}
}) as IndexStructure;
cachedIndexes.set(key, index);
} catch {
// just swallow errors here
}
}
return cachedIndexes.get(key);
}
function mergeEntries(entries: DocNode[]) {
const merged: DocNode[] = [];
const namespaces = new Map<string, DocNodeNamespace>();
const interfaces = new Map<string, DocNodeInterface>();
for (const node of entries) {
if (node.kind === "namespace") {
const namespace = namespaces.get(node.name);
if (namespace) {
namespace.namespaceDef.elements.push(...node.namespaceDef.elements);
if (!namespace.jsDoc) {
namespace.jsDoc = node.jsDoc;
}
} else {
namespaces.set(node.name, node);
merged.push(node);
}
} else if (node.kind === "interface") {
const int = interfaces.get(node.name);
if (int) {
int.interfaceDef.callSignatures.push(
...node.interfaceDef.callSignatures,
);
int.interfaceDef.indexSignatures.push(
...node.interfaceDef.indexSignatures,
);
int.interfaceDef.methods.push(...node.interfaceDef.methods);
int.interfaceDef.properties.push(...node.interfaceDef.properties);
if (!int.jsDoc) {
int.jsDoc = node.jsDoc;
}
} else {
interfaces.set(node.name, node);
merged.push(node);
}
} else {
merged.push(node);
}
}
return merged;
} | the_stack |
// clang-format off
import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js';
import {AppProtocolEntry, HandlerEntry, ProtocolEntry, ProtocolHandlersElement, SiteSettingsPrefsBrowserProxyImpl} from 'chrome://settings/lazy_load.js';
import {assertEquals, assertFalse, assertTrue} from 'chrome://webui-test/chai_assert.js';
import {TestSiteSettingsPrefsBrowserProxy} from './test_site_settings_prefs_browser_proxy.js';
// clang-format on
/** @fileoverview Suite of tests for protocol_handlers. */
suite('ProtocolHandlers', function() {
/**
* A dummy protocol handler element created before each test.
*/
let testElement: ProtocolHandlersElement;
/**
* A list of ProtocolEntry fixtures.
*/
const protocols: ProtocolEntry[] = [
{
handlers: [{
host: 'www.google.com',
protocol: 'mailto',
protocol_display_name: 'email',
spec: 'http://www.google.com/%s',
is_default: true
}],
protocol: 'mailto',
protocol_display_name: 'email',
},
{
handlers: [
{
host: 'www.google1.com',
protocol: 'webcal',
protocol_display_name: 'web calendar',
spec: 'http://www.google1.com/%s',
is_default: true
},
{
host: 'www.google2.com',
protocol: 'webcal',
protocol_display_name: 'web calendar',
spec: 'http://www.google2.com/%s',
is_default: false
}
],
protocol: 'webcal',
protocol_display_name: 'web calendar',
}
];
/**
* A list of AppProtocolEntry fixtures.
*/
const appAllowedProtocols: AppProtocolEntry[] = [
{
handlers: [{
host: 'www.google.com',
protocol: 'mailto',
protocol_display_name: 'email',
spec: 'http://www.google.com/%s',
app_id: 'testID'
}],
protocol: 'mailto',
protocol_display_name: 'email',
},
{
handlers: [
{
host: 'www.google1.com',
protocol: 'webcal',
protocol_display_name: 'web calendar',
spec: 'http://www.google1.com/%s',
app_id: 'testID1'
},
{
host: 'www.google2.com',
protocol: 'webcal',
protocol_display_name: 'web calendar',
spec: 'http://www.google2.com/%s',
app_id: 'testID2'
}
],
protocol: 'webcal',
protocol_display_name: 'web calendar',
}
];
/**
* A list of AppProtocolEntry fixtures. This list should only contain
* entries that do not overlap `appAllowedProtocols`.
*/
const appDisallowedProtocols: AppProtocolEntry[] = [
{
handlers: [{
host: 'www.google1.com',
protocol: 'mailto',
protocol_display_name: 'email',
spec: 'http://www.google1.com/%s',
app_id: 'testID1'
}],
protocol: 'mailto',
protocol_display_name: 'email',
},
{
handlers: [
{
host: 'www.google.com',
protocol: 'webcal',
protocol_display_name: 'web calendar',
spec: 'http://www.google.com/%s',
app_id: 'testID'
},
{
host: 'www.google3.com',
protocol: 'webcal',
protocol_display_name: 'web calendar',
spec: 'http://www.google3.com/%s',
app_id: 'testID3'
}
],
protocol: 'webcal',
protocol_display_name: 'web calendar',
}
];
/**
* A list of IgnoredProtocolEntry fixtures.
*/
const ignoredProtocols: HandlerEntry[] = [{
host: 'www.google.com',
protocol: 'web+ignored',
protocol_display_name: 'web+ignored',
spec: 'https://www.google.com/search?q=ignored+%s',
is_default: false
}];
/**
* The mock proxy object to use during test.
*/
let browserProxy: TestSiteSettingsPrefsBrowserProxy;
setup(async function() {
browserProxy = new TestSiteSettingsPrefsBrowserProxy();
SiteSettingsPrefsBrowserProxyImpl.setInstance(browserProxy);
});
teardown(function() {
testElement.remove();
});
/** @return {!Promise} */
function initPage() {
browserProxy.reset();
document.body.innerHTML = '';
testElement = document.createElement('protocol-handlers');
document.body.appendChild(testElement);
return browserProxy.whenCalled('observeAppProtocolHandlers')
.then(function() {
flush();
});
}
test('set protocol handlers default called', () => {
return initPage().then(() => {
testElement.shadowRoot!
.querySelector<HTMLElement>('#protcolHandlersRadioBlock')!.click();
return browserProxy.whenCalled('setProtocolHandlerDefault');
});
});
test('empty list', function() {
return initPage().then(function() {
const listFrames =
testElement.shadowRoot!.querySelectorAll('.list-frame');
assertEquals(0, listFrames.length);
});
});
test('non-empty list', function() {
browserProxy.setProtocolHandlers(protocols);
return initPage().then(function() {
const listFrames =
testElement.shadowRoot!.querySelectorAll('.list-frame');
const listItems = testElement.shadowRoot!.querySelectorAll('.list-item');
// There are two protocols: ["mailto", "webcal"].
assertEquals(2, listFrames.length);
// There are three total handlers within the two protocols.
assertEquals(3, listItems.length);
// Check that item hosts are rendered correctly.
const hosts = testElement.shadowRoot!.querySelectorAll('.protocol-host');
assertEquals('www.google.com', hosts[0]!.textContent!.trim());
assertEquals('www.google1.com', hosts[1]!.textContent!.trim());
assertEquals('www.google2.com', hosts[2]!.textContent!.trim());
// Check that item default subtexts are rendered correctly.
const defText = testElement.shadowRoot!.querySelectorAll<HTMLElement>(
'.protocol-default');
assertFalse(defText[0]!.hidden);
assertFalse(defText[1]!.hidden);
assertTrue(defText[2]!.hidden);
});
});
test('non-empty ignored protocols', () => {
browserProxy.setIgnoredProtocols(ignoredProtocols);
return initPage().then(() => {
const listFrames =
testElement.shadowRoot!.querySelectorAll('.list-frame');
const listItems = testElement.shadowRoot!.querySelectorAll('.list-item');
// There is a single blocked protocols section
assertEquals(1, listFrames.length);
// There is one total handlers within the two protocols.
assertEquals(1, listItems.length);
// Check that item hosts are rendered correctly.
const hosts = testElement.shadowRoot!.querySelectorAll('.protocol-host');
assertEquals('www.google.com', hosts[0]!.textContent!.trim());
// Check that item default subtexts are rendered correctly.
const defText = testElement.shadowRoot!.querySelectorAll<HTMLElement>(
'.protocol-protocol');
assertFalse(defText[0]!.hidden);
});
});
/**
* A reusable function to test different action buttons.
* @param button id of the button to test.
* @param handler name of browserProxy handler to react.
*/
async function testButtonFlow(button: string, browserProxyHandler: string) {
await initPage();
// Initiating the elements
const menuButtons = testElement.shadowRoot!.querySelectorAll<HTMLElement>(
'cr-icon-button.icon-more-vert');
assertEquals(3, menuButtons.length);
const dialog = testElement.shadowRoot!.querySelector('cr-action-menu')!;
const indexPairs = [[0, 0], [1, 0], [1, 1]];
for (let menuIndex = 0; menuIndex < indexPairs.length; menuIndex++) {
const protocolIndex = indexPairs[menuIndex]![0]!;
const handlerIndex = indexPairs[menuIndex]![1]!;
// Test the button for the first protocol handler
browserProxy.reset();
assertFalse(dialog.open);
menuButtons[menuIndex]!.click();
assertTrue(dialog.open);
if (testElement.$.defaultButton.disabled) {
testElement.shadowRoot!.querySelector('cr-action-menu')!.close();
assertFalse(dialog.open);
continue;
}
testElement.shadowRoot!.querySelector<HTMLElement>(`#${button}`)!.click();
assertFalse(dialog.open);
const [protocol, url] =
await browserProxy.whenCalled(browserProxyHandler);
// BrowserProxy's handler is expected to be called with
// arguments as [protocol, url].
assertEquals(protocols[protocolIndex]!.protocol, protocol);
assertEquals(protocols[protocolIndex]!.handlers[handlerIndex]!.spec, url);
}
}
test('remove button works', function() {
browserProxy.setProtocolHandlers(protocols);
return testButtonFlow('removeButton', 'removeProtocolHandler');
});
test('default button works', function() {
browserProxy.setProtocolHandlers(protocols);
return testButtonFlow('defaultButton', 'setProtocolDefault').then(() => {
const menuButtons = testElement.shadowRoot!.querySelectorAll<HTMLElement>(
'cr-icon-button.icon-more-vert');
const closeMenu = () =>
testElement.shadowRoot!.querySelector('cr-action-menu')!.close();
menuButtons[0]!.click();
flush();
assertTrue(testElement.$.defaultButton.disabled);
closeMenu();
menuButtons[1]!.click();
flush();
assertTrue(testElement.$.defaultButton.disabled);
closeMenu();
menuButtons[2]!.click();
flush();
assertFalse(testElement.$.defaultButton.disabled);
});
});
test('remove button for ignored works', () => {
browserProxy.setIgnoredProtocols(ignoredProtocols);
return initPage()
.then(() => {
testElement.shadowRoot!
.querySelector<HTMLElement>('#removeIgnoredButton')!.click();
return browserProxy.whenCalled('removeProtocolHandler');
})
.then(args => {
const protocol = args[0];
const url = args[1];
// BrowserProxy's handler is expected to be called with arguments as
// [protocol, url].
assertEquals(ignoredProtocols[0]!.protocol, protocol);
assertEquals(ignoredProtocols[0]!.spec, url);
});
});
test('non-empty web app allowed protocols', async () => {
browserProxy.setAppAllowedProtocolHandlers(appAllowedProtocols);
await initPage();
const listFrames = testElement.shadowRoot!.querySelectorAll('.list-frame');
const listItems = testElement.shadowRoot!.querySelectorAll('.list-item');
// There are two protocols: ["mailto", "webcal"].
assertEquals(2, listFrames.length);
// There are three total handlers within the two protocols.
assertEquals(3, listItems.length);
// Check that item hosts are rendered correctly.
const hosts = testElement.shadowRoot!.querySelectorAll('.protocol-host');
assertEquals('www.google.com', hosts[0]!.textContent!.trim());
assertEquals('www.google1.com', hosts[1]!.textContent!.trim());
assertEquals('www.google2.com', hosts[2]!.textContent!.trim());
});
test('remove web app allowed protocols', async () => {
browserProxy.setAppAllowedProtocolHandlers(appAllowedProtocols);
await initPage();
// Remove the first app protocol.
testElement.shadowRoot!
.querySelector<HTMLElement>('#removeAppHandlerButton')!.click();
const args = await browserProxy.whenCalled('removeAppAllowedHandler');
// BrowserProxy's handler is expected to be called with
// arguments as [protocol, url, app_id].
assertEquals(appAllowedProtocols[0]!.protocol, args[0]);
assertEquals(appAllowedProtocols[0]!.handlers[0]!.spec, args[1]);
assertEquals(appAllowedProtocols[0]!.handlers[0]!.app_id, args[2]);
});
test('non-empty web app disallowed protocols', async () => {
browserProxy.setAppDisallowedProtocolHandlers(appDisallowedProtocols);
await initPage();
const listFrames = testElement.shadowRoot!.querySelectorAll('.list-frame');
const listItems = testElement.shadowRoot!.querySelectorAll('.list-item');
// There are two protocols: ["mailto", "webcal"].
assertEquals(2, listFrames.length);
// There are three total handlers within the two protocols.
assertEquals(3, listItems.length);
// Check that item hosts are rendered correctly.
const hosts = testElement.shadowRoot!.querySelectorAll('.protocol-host');
assertEquals('www.google1.com', hosts[0]!.textContent!.trim());
assertEquals('www.google.com', hosts[1]!.textContent!.trim());
assertEquals('www.google3.com', hosts[2]!.textContent!.trim());
});
test('remove web app disallowed protocols', async () => {
browserProxy.setAppDisallowedProtocolHandlers(appDisallowedProtocols);
await initPage();
// Remove the first app protocol.
testElement.shadowRoot!
.querySelector<HTMLElement>('#removeAppHandlerButton')!.click();
const args = await browserProxy.whenCalled('removeAppDisallowedHandler');
// BrowserProxy's handler is expected to be called with
// arguments as [protocol, url, app_id].
assertEquals(appDisallowedProtocols[0]!.protocol, args[0]);
assertEquals(appDisallowedProtocols[0]!.handlers[0]!.spec, args[1]);
assertEquals(appDisallowedProtocols[0]!.handlers[0]!.app_id, args[2]);
});
test('non-empty web app allowed and disallowed protocols', async () => {
browserProxy.setAppAllowedProtocolHandlers(appAllowedProtocols);
browserProxy.setAppDisallowedProtocolHandlers(appDisallowedProtocols);
await initPage();
const listFrames = testElement.shadowRoot!.querySelectorAll('.list-frame');
const listItems = testElement.shadowRoot!.querySelectorAll('.list-item');
// There are two protocols ["mailto", "webcal"] for both allowed,
// and disallowed lists.
assertEquals(4, listFrames.length);
// There are three total handlers within the two protocols in both
// the allowed and disallowed lists.
assertEquals(6, listItems.length);
// Check that item hosts are rendered correctly.
const hosts = testElement.shadowRoot!.querySelectorAll('.protocol-host');
// Allowed list.
assertEquals('www.google.com', hosts[0]!.textContent!.trim());
assertEquals('www.google1.com', hosts[1]!.textContent!.trim());
assertEquals('www.google2.com', hosts[2]!.textContent!.trim());
// Disallowed list.
assertEquals('www.google1.com', hosts[3]!.textContent!.trim());
assertEquals('www.google.com', hosts[4]!.textContent!.trim());
assertEquals('www.google3.com', hosts[5]!.textContent!.trim());
});
test('remove web app allowed then disallowed protocols', async () => {
browserProxy.setAppAllowedProtocolHandlers(appAllowedProtocols);
browserProxy.setAppDisallowedProtocolHandlers(appDisallowedProtocols);
await initPage();
const removeButtons = testElement.shadowRoot!.querySelectorAll<HTMLElement>(
'cr-icon-button.icon-clear');
assertEquals(6, removeButtons.length);
// Remove the first allowed app protocol.
removeButtons[0]!.click();
const args1 = await browserProxy.whenCalled('removeAppAllowedHandler');
assertEquals(appAllowedProtocols[0]!.protocol, args1[0]);
assertEquals(appAllowedProtocols[0]!.handlers[0]!.spec, args1[1]);
assertEquals(appAllowedProtocols[0]!.handlers[0]!.app_id, args1[2]);
// Remove the first disallowed app protocol.
removeButtons[3]!.click();
const args2 = await browserProxy.whenCalled('removeAppDisallowedHandler');
assertEquals(appDisallowedProtocols[0]!.protocol, args2[0]);
assertEquals(appDisallowedProtocols[0]!.handlers[0]!.spec, args2[1]);
assertEquals(appDisallowedProtocols[0]!.handlers[0]!.app_id, args2[2]);
});
}); | the_stack |
import React, { Component } from "react";
import {
withStyles,
CircularProgress,
Typography,
Paper,
Button,
Chip,
Avatar,
Slide,
StyledComponentProps
} from "@material-ui/core";
import { styles } from "./PageLayout.styles";
import Post from "../components/Post";
import { Status } from "../types/Status";
import Mastodon, { StreamListener } from "megalodon";
import { withSnackbar, withSnackbarProps } from "notistack";
import Masonry from "react-masonry-css";
import { getUserDefaultBool } from "../utilities/settings";
import ArrowUpwardIcon from "@material-ui/icons/ArrowUpward";
/**
* The basic interface for a timeline page's properties.
*/
interface ITimelinePageProps extends withSnackbarProps, StyledComponentProps {
/**
* The API endpoint for the timeline to fetch after starting
* a stream.
*/
timeline: string;
/**
* The API endpoint for the timeline to stream.
*/
stream: string;
classes?: any;
}
/**
* The base interface for the timeline page's state.
*/
interface ITimelinePageState {
/**
* The list of posts from the timeline.
*/
posts?: [Status];
/**
* The list of posts stored temporarily while viewing the timeline.
*
* Can be cleared when user pushes "Show x posts" button.
*/
backlogPosts?: [Status] | null;
/**
* Whether the view is currently loading.
*/
viewIsLoading: boolean;
/**
* Whether the view loaded successfully.
*/
viewDidLoad?: boolean;
/**
* Whether the view errored.
*/
viewDidError?: boolean;
/**
* The view's error code, if it errored.
*/
viewDidErrorCode?: any;
/**
* Whether or not to use the masonry layout as defined in
* the user settings.
*/
isMasonryLayout?: boolean;
/**
* Whether posts should automatically load when scrolling.
*/
isInfiniteScroll?: boolean;
}
/**
* The base class for a timeline page.
*
* The timeline page streams a specific timeline. When the stream is connected,
* the page will fetch a particular timeline list of posts. The timeline page will
* also off-load incoming posts from the stream into a backlog that the user can
* then insert by clicking a button.
*/
class TimelinePage extends Component<ITimelinePageProps, ITimelinePageState> {
/**
* The client to use.
*/
client: Mastodon;
/**
* The page's stream listener.
*/
streamListener: StreamListener;
/**
* Construct the timeline page.
* @param props The timeline page's properties
*/
constructor(props: ITimelinePageProps) {
super(props);
// Initialize the state.
this.state = {
viewIsLoading: true,
backlogPosts: null,
isMasonryLayout: getUserDefaultBool("isMasonryLayout"),
isInfiniteScroll: getUserDefaultBool("isInfiniteScroll")
};
// Generate the client.
this.client = new Mastodon(
localStorage.getItem("access_token") as string,
(localStorage.getItem("baseurl") as string) + "/api/v1"
);
// Create the stream listener from the properties.
this.streamListener = this.client.stream(this.props.stream);
this.loadMoreTimelinePieces = this.loadMoreTimelinePieces.bind(this);
this.shouldLoadMorePosts = this.shouldLoadMorePosts.bind(this);
}
/**
* Connect the stream listener and listen for new posts.
*/
componentWillMount() {
this.streamListener.on("connect", () => {
// Get the latest posts from this timeline.
this.client
.get(this.props.timeline, { limit: 50 })
// If we succeeded, update the state and turn off loading.
.then((resp: any) => {
let statuses: [Status] = resp.data;
this.setState({
posts: statuses,
viewIsLoading: false,
viewDidLoad: true,
viewDidError: false
});
})
// Otherwise, update the state in error.
.catch((resp: any) => {
this.setState({
viewIsLoading: false,
viewDidLoad: true,
viewDidError: true,
viewDidErrorCode: String(resp)
});
// Notify the user with a snackbar.
this.props.enqueueSnackbar("Failed to get posts.", {
variant: "error"
});
});
});
// Store incoming posts into a backlog if possible.
this.streamListener.on("update", (status: Status) => {
let queue = this.state.backlogPosts;
if (queue !== null && queue !== undefined) {
queue.unshift(status);
} else {
queue = [status];
}
this.setState({ backlogPosts: queue });
});
// When a post is deleted in the backend, find the post in the list
// and remove it from the list.
this.streamListener.on("delete", (id: number) => {
let posts = this.state.posts;
if (posts) {
posts.forEach((post: Status) => {
if (posts && parseInt(post.id) === id) {
posts.splice(posts.indexOf(post), 1);
}
});
this.setState({ posts });
}
});
// Display an error if the stream encounters and error.
this.streamListener.on("error", (err: Error) => {
this.setState({
viewDidError: true,
viewDidErrorCode: err.message
});
this.props.enqueueSnackbar("An error occured.", {
variant: "error"
});
});
this.streamListener.on("heartbeat", () => {});
}
/**
* Insert a delay between repeated function calls
* codeburst.io/throttling-and-debouncing-in-javascript-646d076d0a44
* @param delay How long to wait before calling function (ms)
* @param fn The function to call
*/
debounced(delay: number, fn: Function) {
let lastCall = 0;
return function(...args: any) {
const now = new Date().getTime();
if (now - lastCall < delay) {
return;
}
lastCall = now;
return fn(...args);
};
}
/**
* Listen for when scroll position changes
*/
componentDidMount() {
if (this.state.isInfiniteScroll) {
window.addEventListener(
"scroll",
this.debounced(200, this.shouldLoadMorePosts)
);
}
}
/**
* Halt the stream and scroll listeners when unmounting the component.
*/
componentWillUnmount() {
this.streamListener.stop();
if (this.state.isInfiniteScroll) {
window.removeEventListener("scroll", this.shouldLoadMorePosts);
}
}
/**
* Insert the posts from the backlog into the current list of posts
* and clear the backlog.
*/
insertBacklog() {
window.scrollTo(0, 0);
let posts = this.state.posts;
let backlog = this.state.backlogPosts;
if (posts && backlog && backlog.length > 0) {
let push = backlog.concat(posts);
this.setState({ posts: push as [Status], backlogPosts: null });
}
}
/**
* Load the next set of posts, if it exists.
*/
loadMoreTimelinePieces() {
// Reinstate the loading status.
this.setState({ viewDidLoad: false, viewIsLoading: true });
// If there are any posts, get the next set.
if (this.state.posts) {
this.client
.get(this.props.timeline, {
max_id: this.state.posts[this.state.posts.length - 1].id,
limit: 50
})
// If we succeeded, append them to the end of the list of posts.
.then((resp: any) => {
let newPosts: [Status] = resp.data;
let posts = this.state.posts as [Status];
newPosts.forEach((post: Status) => {
posts.push(post);
});
this.setState({
viewIsLoading: false,
viewDidLoad: true,
posts
});
})
// If we errored, display the error and don't do anything.
.catch((err: Error) => {
this.setState({
viewIsLoading: false,
viewDidError: true,
viewDidErrorCode: err.message
});
this.props.enqueueSnackbar("Failed to get posts", {
variant: "error"
});
});
}
}
/**
* Load more posts when scroll is near the end of the page
*/
shouldLoadMorePosts(e: Event) {
let difference =
document.body.clientHeight - window.scrollY - window.innerHeight;
if (difference < 10000 && this.state.viewIsLoading === false) {
this.loadMoreTimelinePieces();
}
}
/**
* Render the timeline page.
*/
render() {
const { classes } = this.props;
const containerClasses = `${classes.pageLayoutMaxConstraints}${
this.state.isMasonryLayout ? " " + classes.pageLayoutMasonry : ""
}`;
return (
<div className={containerClasses}>
{this.state.backlogPosts ? (
<div className={classes.pageTopChipContainer}>
<div className={classes.pageTopChips}>
<Slide direction="down" in={true}>
<Chip
avatar={
<Avatar>
<ArrowUpwardIcon />
</Avatar>
}
label={`View ${
this.state.backlogPosts.length
} new post${
this.state.backlogPosts.length > 1
? "s"
: ""
}`}
color="primary"
className={classes.pageTopChip}
onClick={() => this.insertBacklog()}
clickable
/>
</Slide>
</div>
</div>
) : null}
{this.state.posts ? (
<div>
{this.state.isMasonryLayout ? (
<Masonry
breakpointCols={{
default: 4,
2000: 3,
1400: 2,
1050: 1
}}
className={classes.masonryGrid}
columnClassName={
classes["my-masonry-grid_column"]
}
>
{this.state.posts.map((post: Status) => {
return (
<div
className={classes.masonryGrid_item}
key={post.id}
>
<Post
post={post}
client={this.client}
/>
</div>
);
})}
</Masonry>
) : (
<div>
{this.state.posts.map((post: Status) => {
return (
<Post
key={post.id}
post={post}
client={this.client}
/>
);
})}
</div>
)}
<br />
{this.state.viewDidLoad && !this.state.viewDidError ? (
<div
style={{ textAlign: "center" }}
onClick={() => this.loadMoreTimelinePieces()}
>
<Button variant="contained">Load more</Button>
</div>
) : null}
</div>
) : (
<span />
)}
{this.state.viewDidError ? (
<Paper className={classes.errorCard}>
<Typography variant="h4">Bummer.</Typography>
<Typography variant="h6">
Something went wrong when loading this timeline.
</Typography>
<Typography>
{this.state.viewDidErrorCode
? this.state.viewDidErrorCode
: ""}
</Typography>
</Paper>
) : (
<span />
)}
{this.state.viewIsLoading ? (
<div style={{ textAlign: "center" }}>
<CircularProgress
className={classes.progress}
color="primary"
/>
</div>
) : (
<span />
)}
</div>
);
}
}
export default withStyles(styles)(withSnackbar(TimelinePage)); | the_stack |
import { AccessLevelList } from "../shared/access-level";
import { PolicyStatement, Operator } from "../shared";
/**
* Statement provider for service [secretsmanager](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awssecretsmanager.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
export class Secretsmanager extends PolicyStatement {
public servicePrefix = 'secretsmanager';
/**
* Statement provider for service [secretsmanager](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awssecretsmanager.html).
*
* @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement
*/
constructor (sid?: string) {
super(sid);
}
/**
* Enables the user to cancel an in-progress secret rotation.
*
* Access Level: Write
*
* Possible conditions:
* - .ifSecretId()
* - .ifResource()
* - .ifResourceTag()
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-actions
*/
public toCancelRotateSecret() {
return this.to('CancelRotateSecret');
}
/**
* Enables the user to create a secret that stores encrypted data that can be queried and rotated.
*
* Access Level: Write
*
* Possible conditions:
* - .ifName()
* - .ifDescription()
* - .ifKmsKeyId()
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
* - .ifResourceTag()
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-actions
*/
public toCreateSecret() {
return this.to('CreateSecret');
}
/**
* Enables the user to delete the resource policy attached to a secret.
*
* Access Level: Permissions management
*
* Possible conditions:
* - .ifSecretId()
* - .ifResource()
* - .ifResourceTag()
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-actions
*/
public toDeleteResourcePolicy() {
return this.to('DeleteResourcePolicy');
}
/**
* Enables the user to delete a secret.
*
* Access Level: Write
*
* Possible conditions:
* - .ifSecretId()
* - .ifResource()
* - .ifRecoveryWindowInDays()
* - .ifForceDeleteWithoutRecovery()
* - .ifResourceTag()
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-actions
*/
public toDeleteSecret() {
return this.to('DeleteSecret');
}
/**
* Enables the user to retrieve the metadata about a secret, but not the encrypted data.
*
* Access Level: Read
*
* Possible conditions:
* - .ifSecretId()
* - .ifResource()
* - .ifResourceTag()
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-actions
*/
public toDescribeSecret() {
return this.to('DescribeSecret');
}
/**
* Enables the user to generate a random string for use in password creation.
*
* Access Level: Read
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-actions
*/
public toGetRandomPassword() {
return this.to('GetRandomPassword');
}
/**
* Enables the user to get the resource policy attached to a secret.
*
* Access Level: Read
*
* Possible conditions:
* - .ifSecretId()
* - .ifResource()
* - .ifResourceTag()
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-actions
*/
public toGetResourcePolicy() {
return this.to('GetResourcePolicy');
}
/**
* Enables the user to retrieve and decrypt the encrypted data.
*
* Access Level: Read
*
* Possible conditions:
* - .ifSecretId()
* - .ifVersionId()
* - .ifVersionStage()
* - .ifResource()
* - .ifResourceTag()
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-actions
*/
public toGetSecretValue() {
return this.to('GetSecretValue');
}
/**
* Enables the user to list the available versions of a secret.
*
* Access Level: Read
*
* Possible conditions:
* - .ifSecretId()
* - .ifResource()
* - .ifResourceTag()
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-actions
*/
public toListSecretVersionIds() {
return this.to('ListSecretVersionIds');
}
/**
* Enables the user to list the available secrets.
*
* Access Level: List
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-actions
*/
public toListSecrets() {
return this.to('ListSecrets');
}
/**
* Enables the user to attach a resource policy to a secret.
*
* Access Level: Permissions management
*
* Possible conditions:
* - .ifSecretId()
* - .ifResource()
* - .ifResourceTag()
* - .ifBlockPublicPolicy()
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-actions
*/
public toPutResourcePolicy() {
return this.to('PutResourcePolicy');
}
/**
* Enables the user to create a new version of the secret with new encrypted data.
*
* Access Level: Write
*
* Possible conditions:
* - .ifSecretId()
* - .ifResource()
* - .ifResourceTag()
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-actions
*/
public toPutSecretValue() {
return this.to('PutSecretValue');
}
/**
* Remove regions from replication.
*
* Access Level: Write
*
* Possible conditions:
* - .ifSecretId()
* - .ifResource()
* - .ifResourceTag()
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-actions
*/
public toRemoveRegionsFromReplication() {
return this.to('RemoveRegionsFromReplication');
}
/**
* Converts an existing secret to a multi-Region secret and begins replicating the secret to a list of new regions.
*
* Access Level: Write
*
* Possible conditions:
* - .ifSecretId()
* - .ifResource()
* - .ifResourceTag()
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-actions
*/
public toReplicateSecretToRegions() {
return this.to('ReplicateSecretToRegions');
}
/**
* Enables the user to cancel deletion of a secret.
*
* Access Level: Write
*
* Possible conditions:
* - .ifSecretId()
* - .ifResource()
* - .ifResourceTag()
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-actions
*/
public toRestoreSecret() {
return this.to('RestoreSecret');
}
/**
* Enables the user to start rotation of a secret.
*
* Access Level: Write
*
* Possible conditions:
* - .ifSecretId()
* - .ifRotationLambdaARN()
* - .ifResource()
* - .ifResourceTag()
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-actions
*/
public toRotateSecret() {
return this.to('RotateSecret');
}
/**
* Removes the secret from replication and promotes the secret to a regional secret in the replica Region.
*
* Access Level: Write
*
* Possible conditions:
* - .ifSecretId()
* - .ifResource()
* - .ifResourceTag()
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-actions
*/
public toStopReplicationToReplica() {
return this.to('StopReplicationToReplica');
}
/**
* Enables the user to add tags to a secret.
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifSecretId()
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
* - .ifResource()
* - .ifResourceTag()
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-actions
*/
public toTagResource() {
return this.to('TagResource');
}
/**
* Enables the user to remove tags from a secret.
*
* Access Level: Tagging
*
* Possible conditions:
* - .ifSecretId()
* - .ifAwsTagKeys()
* - .ifResource()
* - .ifResourceTag()
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-actions
*/
public toUntagResource() {
return this.to('UntagResource');
}
/**
* Enables the user to update a secret with new metadata or with a new version of the encrypted data.
*
* Access Level: Write
*
* Possible conditions:
* - .ifSecretId()
* - .ifDescription()
* - .ifKmsKeyId()
* - .ifResource()
* - .ifResourceTag()
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-actions
*/
public toUpdateSecret() {
return this.to('UpdateSecret');
}
/**
* Enables the user to move a stage from one secret to another.
*
* Access Level: Write
*
* Possible conditions:
* - .ifSecretId()
* - .ifVersionStage()
* - .ifResource()
* - .ifResourceTag()
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-actions
*/
public toUpdateSecretVersionStage() {
return this.to('UpdateSecretVersionStage');
}
/**
* Enables the user to validate a resource policy before attaching policy.
*
* Access Level: Permissions management
*
* Possible conditions:
* - .ifSecretId()
* - .ifResource()
* - .ifResourceTag()
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-actions
*/
public toValidateResourcePolicy() {
return this.to('ValidateResourcePolicy');
}
protected accessLevelList: AccessLevelList = {
"Write": [
"CancelRotateSecret",
"CreateSecret",
"DeleteSecret",
"PutSecretValue",
"RemoveRegionsFromReplication",
"ReplicateSecretToRegions",
"RestoreSecret",
"RotateSecret",
"StopReplicationToReplica",
"UpdateSecret",
"UpdateSecretVersionStage"
],
"Permissions management": [
"DeleteResourcePolicy",
"PutResourcePolicy",
"ValidateResourcePolicy"
],
"Read": [
"DescribeSecret",
"GetRandomPassword",
"GetResourcePolicy",
"GetSecretValue",
"ListSecretVersionIds"
],
"List": [
"ListSecrets"
],
"Tagging": [
"TagResource",
"UntagResource"
]
};
/**
* Adds a resource of type Secret to the statement
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-resources
*
* @param secretId - Identifier for the secretId.
* @param account - Account of the resource; defaults to empty string: all accounts.
* @param region - Region of the resource; defaults to empty string: all regions.
* @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`.
*
* Possible conditions:
* - .ifAwsRequestTag()
* - .ifAwsTagKeys()
* - .ifResourceTag()
* - .ifResource()
*/
public onSecret(secretId: string, account?: string, region?: string, partition?: string) {
var arn = 'arn:${Partition}:secretsmanager:${Region}:${Account}:secret:${SecretId}';
arn = arn.replace('${SecretId}', secretId);
arn = arn.replace('${Account}', account || '*');
arn = arn.replace('${Region}', region || '*');
arn = arn.replace('${Partition}', partition || 'aws');
return this.on(arn);
}
/**
* Filters access by whether the resource policy blocks broad AWS account access.
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-contextkeys
*
* Applies to actions:
* - .toPutResourcePolicy()
*
* @param value `true` or `false`. **Default:** `true`
*/
public ifBlockPublicPolicy(value?: boolean) {
return this.if(`BlockPublicPolicy`, (typeof value !== 'undefined' ? value : true), 'Bool');
}
/**
* Filters access by the description text in the request.
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-contextkeys
*
* Applies to actions:
* - .toCreateSecret()
* - .toUpdateSecret()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifDescription(value: string | string[], operator?: Operator | string) {
return this.if(`Description`, value, operator || 'StringLike');
}
/**
* Filters access by whether the secret is to be deleted immediately without any recovery window.
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-contextkeys
*
* Applies to actions:
* - .toDeleteSecret()
*
* @param value `true` or `false`. **Default:** `true`
*/
public ifForceDeleteWithoutRecovery(value?: boolean) {
return this.if(`ForceDeleteWithoutRecovery`, (typeof value !== 'undefined' ? value : true), 'Bool');
}
/**
* Filters access by the ARN of the KMS key in the request.
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-contextkeys
*
* Applies to actions:
* - .toCreateSecret()
* - .toUpdateSecret()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifKmsKeyId(value: string | string[], operator?: Operator | string) {
return this.if(`KmsKeyId`, value, operator || 'StringLike');
}
/**
* Filters access by the friendly name of the secret in the request.
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-contextkeys
*
* Applies to actions:
* - .toCreateSecret()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifName(value: string | string[], operator?: Operator | string) {
return this.if(`Name`, value, operator || 'StringLike');
}
/**
* Filters access by the number of days that Secrets Manager waits before it can delete the secret.
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-contextkeys
*
* Applies to actions:
* - .toDeleteSecret()
*
* @param value The value(s) to check
* @param operator Works with [numeric operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_Numeric). **Default:** `NumericEquals`
*/
public ifRecoveryWindowInDays(value: number | number[], operator?: Operator | string) {
return this.if(`RecoveryWindowInDays`, value, operator || 'NumericEquals');
}
/**
* Filters access by a tag key and value pair.
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-contextkeys
*
* Applies to actions:
* - .toCancelRotateSecret()
* - .toCreateSecret()
* - .toDeleteResourcePolicy()
* - .toDeleteSecret()
* - .toDescribeSecret()
* - .toGetResourcePolicy()
* - .toGetSecretValue()
* - .toListSecretVersionIds()
* - .toPutResourcePolicy()
* - .toPutSecretValue()
* - .toRemoveRegionsFromReplication()
* - .toReplicateSecretToRegions()
* - .toRestoreSecret()
* - .toRotateSecret()
* - .toStopReplicationToReplica()
* - .toTagResource()
* - .toUntagResource()
* - .toUpdateSecret()
* - .toUpdateSecretVersionStage()
* - .toValidateResourcePolicy()
*
* Applies to resource types:
* - Secret
*
* @param tagKey The tag key to check
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifResourceTag(tagKey: string, value: string | string[], operator?: Operator | string) {
return this.if(`ResourceTag/${ tagKey }`, value, operator || 'StringLike');
}
/**
* Filters access by the ARN of the rotation Lambda function in the request.
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-contextkeys
*
* Applies to actions:
* - .toRotateSecret()
*
* @param value The value(s) to check
* @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike`
*/
public ifRotationLambdaARN(value: string | string[], operator?: Operator | string) {
return this.if(`RotationLambdaARN`, value, operator || 'ArnLike');
}
/**
* Filters access by the SecretID value in the request.
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-contextkeys
*
* Applies to actions:
* - .toCancelRotateSecret()
* - .toDeleteResourcePolicy()
* - .toDeleteSecret()
* - .toDescribeSecret()
* - .toGetResourcePolicy()
* - .toGetSecretValue()
* - .toListSecretVersionIds()
* - .toPutResourcePolicy()
* - .toPutSecretValue()
* - .toRemoveRegionsFromReplication()
* - .toReplicateSecretToRegions()
* - .toRestoreSecret()
* - .toRotateSecret()
* - .toStopReplicationToReplica()
* - .toTagResource()
* - .toUntagResource()
* - .toUpdateSecret()
* - .toUpdateSecretVersionStage()
* - .toValidateResourcePolicy()
*
* @param value The value(s) to check
* @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike`
*/
public ifSecretId(value: string | string[], operator?: Operator | string) {
return this.if(`SecretId`, value, operator || 'ArnLike');
}
/**
* Primary region in which the secret is created.
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-contextkeys
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifSecretPrimaryRegion(value: string | string[], operator?: Operator | string) {
return this.if(`SecretPrimaryRegion`, value, operator || 'StringLike');
}
/**
* Filters access by the unique identifier of the version of the secret in the request.
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-contextkeys
*
* Applies to actions:
* - .toGetSecretValue()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifVersionId(value: string | string[], operator?: Operator | string) {
return this.if(`VersionId`, value, operator || 'StringLike');
}
/**
* Filters access by the list of version stages in the request.
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-contextkeys
*
* Applies to actions:
* - .toGetSecretValue()
* - .toUpdateSecretVersionStage()
*
* @param value The value(s) to check
* @param operator Works with [string operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_String). **Default:** `StringLike`
*/
public ifVersionStage(value: string | string[], operator?: Operator | string) {
return this.if(`VersionStage`, value, operator || 'StringLike');
}
/**
* Filters access by the ARN of the rotation Lambda function associated with the secret.
*
* https://docs.aws.amazon.com/secretsmanager/latest/userguide/reference_iam-permissions.html#iam-contextkeys
*
* Applies to actions:
* - .toCancelRotateSecret()
* - .toDeleteResourcePolicy()
* - .toDeleteSecret()
* - .toDescribeSecret()
* - .toGetResourcePolicy()
* - .toGetSecretValue()
* - .toListSecretVersionIds()
* - .toPutResourcePolicy()
* - .toPutSecretValue()
* - .toRemoveRegionsFromReplication()
* - .toReplicateSecretToRegions()
* - .toRestoreSecret()
* - .toRotateSecret()
* - .toStopReplicationToReplica()
* - .toTagResource()
* - .toUntagResource()
* - .toUpdateSecret()
* - .toUpdateSecretVersionStage()
* - .toValidateResourcePolicy()
*
* Applies to resource types:
* - Secret
*
* @param allowRotationLambdaArn The tag key to check
* @param value The value(s) to check
* @param operator Works with [arn operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html#Conditions_ARN). **Default:** `ArnLike`
*/
public ifResource(allowRotationLambdaArn: string, value: string | string[], operator?: Operator | string) {
return this.if(`resource/${ allowRotationLambdaArn }`, value, operator || 'ArnLike');
}
} | the_stack |
'use strict';
import * as React from 'react';
import * as ReactTestRenderer from 'react-test-renderer';
import { createOperationDescriptor, PayloadData, PayloadError } from 'relay-runtime';
import { createMockEnvironment } from 'relay-test-utils-internal';
const { generateAndCompile } = require('./TestCompiler');
import { useMutation, RelayEnvironmentProvider } from '../src';
const { useState, useMemo } = React;
let environment;
let render;
let setEnvironment;
let setMutation;
let commit;
let isInFlightFn;
let CommentCreateMutation;
let instance;
let renderSpy;
const data = {
data: {
commentCreate: {
feedbackCommentEdge: {
__typename: 'CommentsEdge',
cursor: '<cursor>',
node: {
id: '<id>',
body: {
text: '<text>',
},
},
},
},
},
};
const optimisticResponse = {
commentCreate: {
feedbackCommentEdge: {
__typename: 'CommentsEdge',
cursor: '<cursor>',
node: {
id: '<id>',
body: {
text: 'optimistic <text>',
},
},
},
},
};
const variables = {
input: {
commentId: '<id>',
},
};
function expectFragmentResult(data, error): void {
// This ensures that useEffect runs
ReactTestRenderer.act(() => jest.runAllImmediates());
expect(renderSpy).toBeCalledTimes(1);
const [dataRender, errorRender] = renderSpy.mock.calls[0];
expect(data).toEqual(dataRender);
expect(error).toEqual(errorRender);
renderSpy.mockClear();
}
beforeEach(() => {
environment = createMockEnvironment();
isInFlightFn = jest.fn();
renderSpy = jest.fn();
({ CommentCreateMutation } = generateAndCompile(`
mutation CommentCreateMutation(
$input: CommentCreateInput
) {
commentCreate(input: $input) {
feedbackCommentEdge {
cursor
node {
id
body {
text
}
}
}
}
}`));
function Renderer({ initialMutation, commitInRender }): any {
const [mutation, setMutationFn] = useState(initialMutation);
setMutation = setMutationFn;
const [commitFn, { loading: isMutationInFlight, data, error }] = useMutation(mutation);
commit = commitFn;
if (commitInRender) {
// `commitInRender` never changes in the test
// eslint-disable-next-line react-hooks/rules-of-hooks
useMemo(() => {
commit({ variables });
}, []);
}
isInFlightFn(isMutationInFlight);
renderSpy(data, error);
return null;
}
function Container(props: any): any {
const [env, setEnv] = useState(props.environment);
setEnvironment = setEnv;
return (
<RelayEnvironmentProvider environment={env}>
<Renderer initialMutation={props.mutation} commitInRender={props.commitInRender} />
</RelayEnvironmentProvider>
);
}
render = function(env, mutation, commitInRender = false): any {
ReactTestRenderer.act(() => {
instance = ReactTestRenderer.create(
<Container environment={env} mutation={mutation} commitInRender={commitInRender} />,
);
});
};
});
it('returns correct in-flight state when the mutation is inflight and completes', () => {
render(environment, CommentCreateMutation);
expect(isInFlightFn).toBeCalledTimes(1);
expect(isInFlightFn).toBeCalledWith(false);
isInFlightFn.mockClear();
commit({ variables });
expect(isInFlightFn).toBeCalledTimes(1);
expect(isInFlightFn).toBeCalledWith(true);
isInFlightFn.mockClear();
const operation = environment.executeMutation.mock.calls[0][0].operation;
ReactTestRenderer.act(() => environment.mock.resolve(operation, data));
expect(isInFlightFn).toBeCalledTimes(1);
expect(isInFlightFn).toBeCalledWith(false);
});
it('returns correct in-flight state when commit called inside render', () => {
render(environment, CommentCreateMutation, true);
expect(isInFlightFn).toBeCalledTimes(2);
expect(isInFlightFn).toHaveBeenNthCalledWith(2, true);
isInFlightFn.mockClear();
const operation = environment.executeMutation.mock.calls[0][0].operation;
ReactTestRenderer.act(() => environment.mock.resolve(operation, data));
expect(isInFlightFn).toBeCalledTimes(1);
expect(isInFlightFn).toHaveBeenCalledWith(false);
});
it('calls onCompleted when mutation responses contains server errors', () => {
const onError = jest.fn();
const onCompleted = jest.fn();
render(environment, CommentCreateMutation);
commit({ variables, onError, onCompleted });
const operation = environment.executeMutation.mock.calls[0][0].operation;
isInFlightFn.mockClear();
renderSpy.mockClear();
ReactTestRenderer.act(() =>
environment.mock.resolve(operation, {
data: data.data as PayloadData,
errors: [
{
message: '<error0>',
},
{
message: '<error1>',
},
] as Array<PayloadError>,
}),
);
expect(onError).toBeCalledTimes(1); // changed
expect(onCompleted).toBeCalledTimes(0); // changed
const errors = [
{
message: '<error0>',
},
{
message: '<error1>',
},
];
expect(onError).toBeCalledWith(errors);
expect(isInFlightFn).toBeCalledWith(false);
expectFragmentResult(null, errors);
});
it('calls onError when mutation errors in commitMutation', () => {
const onError = jest.fn();
const onCompleted = jest.fn();
const throwingUpdater = (): void => {
throw new Error('<error0>');
};
render(environment, CommentCreateMutation);
commit({ variables, onError, onCompleted, updater: throwingUpdater });
isInFlightFn.mockClear();
const operation = environment.executeMutation.mock.calls[0][0].operation;
ReactTestRenderer.act(() => environment.mock.resolve(operation, data));
expect(onError).toBeCalledTimes(1);
expect(onError).toBeCalledWith(new Error('<error0>'));
expect(onCompleted).toBeCalledTimes(0);
expect(isInFlightFn).toBeCalledWith(false);
});
it('calls onComplete when mutation successfully resolved', () => {
const onError = jest.fn();
const onCompleted = jest.fn();
render(environment, CommentCreateMutation);
commit({ variables, onError, onCompleted });
isInFlightFn.mockClear();
const operation = environment.executeMutation.mock.calls[0][0].operation;
ReactTestRenderer.act(() => environment.mock.resolve(operation, data));
expect(onError).toBeCalledTimes(0);
expect(onCompleted).toBeCalledTimes(1);
expect(onCompleted).toBeCalledWith({
commentCreate: {
feedbackCommentEdge: {
cursor: '<cursor>',
node: {
id: '<id>',
body: {
text: '<text>',
},
},
},
},
});
expect(isInFlightFn).toBeCalledWith(false);
});
describe('change useMutation input', () => {
let newEnv;
let CommentCreateMutation2;
beforeEach(() => {
newEnv = createMockEnvironment();
({ CommentCreateMutation2 } = generateAndCompile(`
mutation CommentCreateMutation2(
$input: CommentCreateInput
) {
commentCreate(input: $input) {
feedbackCommentEdge {
cursor
node {
id
body {
text
}
}
}
}
}`));
});
it('can fetch from the new environment when the environment changes', () => {
render(environment, CommentCreateMutation);
isInFlightFn.mockClear();
commit({ variables });
expect(environment.executeMutation).toBeCalledTimes(1);
ReactTestRenderer.act(() => setEnvironment(newEnv));
commit({ variables });
expect(newEnv.executeMutation).toBeCalledTimes(1);
});
it('can fetch use the new query when the query changes', () => {
render(environment, CommentCreateMutation);
commit({ variables });
ReactTestRenderer.act(() => setMutation(CommentCreateMutation2));
commit({ variables });
const secondOperation = createOperationDescriptor(CommentCreateMutation2, variables);
expect(environment.executeMutation).toBeCalledTimes(2);
expect(environment.executeMutation.mock.calls[1][0].operation.request).toEqual(
secondOperation.request,
);
isInFlightFn.mockClear();
ReactTestRenderer.act(() => {
environment.mock.resolve(environment.executeMutation.mock.calls[0][0].operation, data);
environment.mock.resolve(secondOperation, data);
});
expect(isInFlightFn).toBeCalledTimes(1);
expect(isInFlightFn).toBeCalledWith(false);
});
});
describe('unmount', () => {
beforeEach(() => {
jest.spyOn(console, 'error').mockImplementationOnce(() => {});
});
it('does not setState on commit after unmount', () => {
render(environment, CommentCreateMutation);
ReactTestRenderer.act(() => instance.unmount());
isInFlightFn.mockClear();
commit({ variables });
expect(isInFlightFn).toBeCalledTimes(0);
expect(console.error).toBeCalledTimes(0);
});
it('does not setState on complete after unmount', () => {
render(environment, CommentCreateMutation);
ReactTestRenderer.act(() => commit({ variables }));
ReactTestRenderer.act(() => instance.unmount());
isInFlightFn.mockClear();
const operation = environment.executeMutation.mock.calls[0][0].operation;
ReactTestRenderer.act(() => environment.mock.resolve(operation, data));
expect(isInFlightFn).toBeCalledTimes(0);
expect(console.error).toBeCalledTimes(0);
});
it('does not dispose previous in-flight mutaiton ', () => {
const onCompleted = jest.fn();
render(environment, CommentCreateMutation);
commit({ variables, onCompleted });
ReactTestRenderer.act(() => instance.unmount());
const operation = environment.executeMutation.mock.calls[0][0].operation;
ReactTestRenderer.act(() => environment.mock.resolve(operation, data));
expect(onCompleted).toBeCalledTimes(1);
expect(onCompleted).toBeCalledWith({
commentCreate: {
feedbackCommentEdge: {
cursor: '<cursor>',
node: {
id: '<id>',
body: {
text: '<text>',
},
},
},
},
});
});
});
describe('optimistic response', () => {
it('calls onCompleted when mutation responses contains server errors', () => {
const onError = jest.fn();
const onCompleted = jest.fn();
render(environment, CommentCreateMutation);
renderSpy.mockClear();
commit({ variables, onError, onCompleted, optimisticResponse });
expectFragmentResult(optimisticResponse, null);
const operation = environment.executeMutation.mock.calls[0][0].operation;
isInFlightFn.mockClear();
renderSpy.mockClear();
ReactTestRenderer.act(() =>
environment.mock.resolve(operation, {
data: data.data as PayloadData,
errors: [
{
message: '<error0>',
},
{
message: '<error1>',
},
] as Array<PayloadError>,
}),
);
expect(onError).toBeCalledTimes(1); // changed
expect(onCompleted).toBeCalledTimes(0); // changed
const errors = [
{
message: '<error0>',
},
{
message: '<error1>',
},
];
expect(onError).toBeCalledWith(errors);
expect(isInFlightFn).toBeCalledWith(false);
expectFragmentResult(null, errors);
});
it('calls onComplete when mutation successfully resolved', () => {
const onError = jest.fn();
const onCompleted = jest.fn();
render(environment, CommentCreateMutation);
renderSpy.mockClear();
commit({ variables, onError, onCompleted, optimisticResponse });
expectFragmentResult(optimisticResponse, null);
isInFlightFn.mockClear();
const operation = environment.executeMutation.mock.calls[0][0].operation;
ReactTestRenderer.act(() => environment.mock.resolve(operation, data));
const result = {
commentCreate: {
feedbackCommentEdge: {
cursor: '<cursor>',
node: {
id: '<id>',
body: {
text: '<text>',
},
},
},
},
};
expect(onError).toBeCalledTimes(0);
expect(onCompleted).toBeCalledTimes(1);
expect(onCompleted).toBeCalledWith(result);
expect(isInFlightFn).toBeCalledWith(false);
expectFragmentResult(result, null);
});
}); | the_stack |
import { Component, OnInit, OnDestroy, Input } from '@angular/core';
import { CloudGemMetricApi } from './api-handler.class';
import { Http } from '@angular/http';
import { AwsService } from "app/aws/aws.service";
import { Observable } from 'rxjs/Observable';
import { MetricGraph } from 'app/view/game/module/shared/class/metric-graph.class';
import 'rxjs/add/operator/combineLatest'
const DYNAMODB_HARMONIZATION_COEFFICIENT = 0.0083528
@Component({
selector: 'metric-overview',
template: `
<div>Charts will become available as data becomes present. Charts will refresh automatically every 5 minutes. </div>
<ng-container>
<ng-container *ngFor="let chart of metricGraphs">
<graph [ref]="chart">
</graph>
</ng-container>
</ng-container>
`
})
export class MetricOverviewComponent implements OnInit, OnDestroy{
@Input('context') public context: any;
@Input('facetid') public facetid: string
private _apiHandler: CloudGemMetricApi;
metricGraphs = new Array<MetricGraph>();
amoebaGraph: MetricGraph;
colorScheme = {
domain: ['#6441A5', '#A10A28', '#C7B42C', '#8A0ECC', '#333333']
};
constructor(private http: Http, private aws: AwsService) { }
ngOnInit() {
this._apiHandler = new CloudGemMetricApi(this.context.ServiceUrl, this.http, this.aws);
this.facetid = this.facetid.toLocaleLowerCase()
if (this.facetid == 'Overview'.toLocaleLowerCase())
this.populateOverviewGraphs();
else if (this.facetid == 'SQS'.toLocaleLowerCase())
this.populatePipelineGraphs();
else if (this.facetid == 'Lambda'.toLocaleLowerCase())
this.populateAWSGraphs();
else if (this.facetid == 'DynamoDb'.toLocaleLowerCase())
this.populateDbGraphs();
}
ngOnDestroy() {
// When navigating to another gem remove all the interval timers to stop making requests.
this.metricGraphs.forEach(graph => {
graph.clearInterval();
});
}
/**
* PopulateGraphs
* Creates the multiple graphs on the metrics overview facet
*/
private populateOverviewGraphs() {
this.metricGraphs.push(new MetricGraph("Incoming Game Events", "Date", "Number of Events", ["Metrics Added"], [this._apiHandler.getRowsAdded()], [this.parseMetricsData], "ngx-charts-line-chart", [], ['Average'], undefined, undefined, 300000));
this.metricGraphs.push(new MetricGraph("Event Bandwidth Consumed", "Date", "Incoming Bytes", ["Processed Bytes"], [this._apiHandler.getProcessedBytes()], [this.parseMetricsData], "ngx-charts-line-chart", [], ['Average'], undefined, undefined, 300000));
this.metricGraphs.push(new MetricGraph("Event Duplication Error Rate", "Date", "Rate", ["Error Rate"], [this._apiHandler.getDuplicationRate()], [this.parseMetricsData], "ngx-charts-line-chart", [], ['Value'], undefined, undefined, 300000));
this.metricGraphs.push(new MetricGraph("Time To Save Events To S3", "Date", "Seconds", ["Save Duration"], [this._apiHandler.getSaveDuration()], [this.parseMetricsData], "ngx-charts-line-chart", [], ['Average'], undefined, undefined, 300000));
}
/**
* PopulateGraphs
* Creates the multiple graphs on the metrics overview facet
*/
private populatePipelineGraphs() {
this.metricGraphs.push(new MetricGraph("Processed SQS Messages", "Date", "Messages", ["Processed Messages"], [this._apiHandler.getProcessedMessages()], [this.parseMetricsData], "ngx-charts-line-chart", [], ['Average'], undefined, undefined, 300000));
this.metricGraphs.push(new MetricGraph("Time To Delete SQS Messages", "Date", "Seconds", ["Delete Duration"], [this._apiHandler.getDeleteDuration()], [this.parseMetricsData], "ngx-charts-line-chart", [], ['Average'], undefined , undefined, 300000));
}
/**
* PopulateGraphs
* Creates the multiple graphs on the metrics overview facet
*/
private populateDbGraphs() {
this.metricGraphs.push(new MetricGraph("Reads Consumed/Provisioned", "Date", "Average Capacity", ["Consumed", "Provisioned"],
[this._apiHandler.getCloudWatchMetrics("DynamoDB", "ConsumedReadCapacityUnits", "TableName", "MetricContext", "SampleCount", 60, 8),
this._apiHandler.getCloudWatchMetrics("DynamoDB", "ProvisionedReadCapacityUnits", "TableName", "MetricContext", "Sum", 60, 8)], [this.parseDynamoDbMetricsData, this.parseMetricsData], "ngx-charts-line-chart", [], ["SampleCount", "Sum"], this.colorScheme, undefined, 300000));
this.metricGraphs.push(new MetricGraph("Writes Consumed/Provisioned", "Date", "Average Capacity", ["Consumed", "Provisioned"],
[this._apiHandler.getCloudWatchMetrics("DynamoDB", "ConsumedWriteCapacityUnits", "TableName", "MetricContext", "SampleCount", 60, 8),
this._apiHandler.getCloudWatchMetrics("DynamoDB", "ProvisionedWriteCapacityUnits", "TableName", "MetricContext", "Sum", 60, 8)], [this.parseDynamoDbMetricsData, this.parseMetricsData], "ngx-charts-line-chart", [], ["SampleCount", "Sum"], this.colorScheme, undefined, 300000));
}
/**
* PopulateGraphs
* Creates the multiple graphs on the metrics overview facet
*/
private populateAWSGraphs() {
this.metricGraphs.push(new MetricGraph("Producer Lambda Invocations", "Date", "Invocations", ["Producer Invocations"], [this._apiHandler.getCloudWatchMetrics("Lambda", "Invocations", "FunctionName", "FIFOProducer", "SampleCount", 300, 8)], [this.parseMetricsData], "ngx-charts-line-chart", [], ["SampleCount"], undefined, undefined, 300000));
this.metricGraphs.push(new MetricGraph("Producer Lambda Errors", "Date", "Errors", ["Producer Errors"], [this._apiHandler.getCloudWatchMetrics("Lambda", "Errors", "FunctionName", "FIFOProducer", "Sum", 300, 8)], [this.parseMetricsData], "ngx-charts-line-chart", [], ["Sum"], undefined, undefined, 300000));
this.metricGraphs.push(new MetricGraph("Consumer Lambda Invocations", "Date", "Invocations", ["Consumer Invocations"], [this._apiHandler.getCloudWatchMetrics("Lambda", "Invocations", "FunctionName", "FIFOConsumer", "SampleCount", 300, 8)], [this.parseMetricsData], "ngx-charts-line-chart", [], ["SampleCount"], undefined, undefined, 300000));
this.metricGraphs.push(new MetricGraph("Consumer Lambda Duration", "Date", "Milliseconds", ["Consumer Invocations"], [this._apiHandler.getCloudWatchMetrics("Lambda", "Duration", "FunctionName", "FIFOConsumer", "Average", 300, 8)], [this.parseMetricsData], "ngx-charts-line-chart", [], ["Average"], undefined, undefined, 300000));
this.metricGraphs.push(new MetricGraph("Consumer Lambda Errors", "Date", "Errors", ["Consumer Errors"], [this._apiHandler.getCloudWatchMetrics("Lambda", "Errors", "FunctionName", "FIFOConsumer", "Sum", 300, 8)], [this.parseMetricsData], "ngx-charts-line-chart", [], ["Sum"], undefined, undefined, 300000));
this.metricGraphs.push(new MetricGraph("Amoeba Lambda Invocations", "Date", "Invocations",
["Amoeba"], [
this._apiHandler.getCloudWatchMetrics("Lambda", "Invocations", "FunctionName", "Amoeba", "SampleCount", 1200, 8)
], [this.parseMetricsData], "ngx-charts-line-chart", [], ["SampleCount"], this.colorScheme, undefined, 300000));
this.metricGraphs.push(new MetricGraph("Ameoba Errors", "Date", "Errors",
["Amoeba"], [
this._apiHandler.getCloudWatchMetrics("Lambda", "Errors", "FunctionName", "Amoeba", "Sum", 1200, 8),
], [this.parseMetricsData], "ngx-charts-line-chart", [], ["Sum"], this.colorScheme, undefined, 300000));
}
/**
* ParseMetricsData
* A helper method for parsing out the usful inform from a metrics gem REST endpoint and graphing it. It takes in an array of data
* and formats it for the ngx-charts graphing library.
* @param series_x_label
* @param series_y_name
* @param dataSeriesLabel
* @param response
*/
parseMetricsData = (series_x_label: string, series_y_name: string, dataSeriesLabel: string, response: any) => {
let data = response;
// At least 2 points required to create a line graph. If this data doesn't exist generate a 0 value for
// a single data point.
if (data.length <= 1 || !(data instanceof Array)) {
return {
"name": dataSeriesLabel,
"series": [
{
"name": "Insufficient Data Found",
"value": 0
}
]
}
}
return {
"name": dataSeriesLabel,
"series": data.sort((a, b) => {
return +new Date(a.Timestamp * 1000) - +new Date(b.Timestamp * 1000);
}).map((e) => {
return this.parseData(e, series_y_name)
})
}
}
/**
* ParseDynamoDB metrics
* A helper method for parsing out the usful inform from a metrics gem REST endpoint and graphing it. It takes in an array of data
* and formats it for the ngx-charts graphing library.
* @param series_x_label
* @param series_y_name
* @param dataSeriesLabel
* @param response
*/
parseDynamoDbMetricsData = (series_x_label: string, series_y_name: string, dataSeriesLabel: string, response: any) => {
let data = response;
// At least 2 points required to create a line graph. If this data doesn't exist generate a 0 value for
// a single data point.
if (data.length <= 1 || !(data instanceof Array)) {
return {
"name": dataSeriesLabel,
"series": [
{
"name": "Insufficient Data Found",
"value": 0
}
]
}
}
return {
"name": dataSeriesLabel,
"series": data.sort((a, b) => {
return +new Date(a.Timestamp * 1000) - +new Date(b.Timestamp * 1000);
}).map((e) => {
return this.parseData(e, series_y_name, true)
})
}
}
private precisionRound(number, precision): number {
var factor = Math.pow(10, precision);
return Math.round(number * factor) / factor;
}
private parseData(e, series_y_name, is_dynamo_db = false): any {
// convert UNIX timestamp (ms => s)
let date = new Date(e.Timestamp * 1000)
let day = date.getDate()
let hour = date.getHours()
let min = date.getMinutes()
let s_day = day < 10 ? `0${day}` : day
let s_hour = hour < 10 ? `0${hour}` : hour
let s_min = min < 10 ? `0${min}` : min
return {
"name": `${s_day} ${s_hour}:${s_min}m`,
"value": is_dynamo_db ? this.precisionRound(e[series_y_name] * DYNAMODB_HARMONIZATION_COEFFICIENT, 2) : e[series_y_name]
}
}
} | the_stack |
import { ReferencePointer } from './parser';
import { Util, ExtractionResult } from './util';
import { ObjectUtil } from './object-util'
import { Stream } from './stream';
export interface XRef {
id: number
pointer: number
generation: number
free: boolean
update: boolean
compressed?: boolean
}
interface SubSectionHeader {
id: number
count: number
end_ptr: number // points to the end of the sub section header
}
interface Trailer {
size: number
root: ReferencePointer
prev?: number
is_encrypted : boolean // true, if the document is enrypted otherwise false
encrypt?: ReferencePointer // reference to the encryption dictionary if document is encrypted
id? : Uint8Array[] // document id
}
var generateDefaultTrailer = () => {
return { size: -1, root: { obj: -1, generation: -1 }, is_encrypted : false}
}
export interface ObjectLookupTable {
[id: number]: XRef
}
export interface UpdateSection {
start_pointer: number
size: number
refs: XRef[]
prev?: number
root?: ReferencePointer
is_encrypted : boolean// true, if the document is enrypted otherwise false
encrypt?: ReferencePointer// reference to the encryption dictionary if document is encrypted
id?: Uint8Array[]// document id
}
/**
* Holds the complete information of one update section in the Cross-Reference-Stream Object format.
*
* */
export class CrossReferenceStreamObject {
public refs: XRef[] = []
constructor(private data: Uint8Array) { }
public trailer: Trailer = generateDefaultTrailer()
public streamLength: number = -1
public w: number[] = []
public index: number[] = []
private start_pointer: number = 0
/**
* Extracts a cross reference section that is a continuous definition of cross reference entries
* */
extractCrossReferenceSection(first_object_id: number, object_count: number, stream: Stream) {
let current_object_id = first_object_id
for (let i = 0; i < object_count; ++i) {
let _type = stream.getNBytesAsNumber(this.w[0])
let xref = undefined
switch (_type) {
case 0:
xref = { id: current_object_id++, pointer: stream.getNBytesAsNumber(this.w[1]), generation: this.w[2] === 0 ? 0 : stream.getNBytesAsNumber(this.w[2]), free: true, update: false }
break
case 1:
xref = { id: current_object_id++, pointer: stream.getNBytesAsNumber(this.w[1]), generation: this.w[2] === 0 ? 0 : stream.getNBytesAsNumber(this.w[2]), free: false, update: true }
break
case 2:
// in this case the pointer becomes the stream object id that contains the compressed object and the generation represents the index of the object in the stream
xref = { id: current_object_id++, pointer: stream.getNBytesAsNumber(this.w[1]), generation: this.w[2] === 0 ? 0 : stream.getNBytesAsNumber(this.w[2]), free: true, update: false, compressed: true }
break
}
if (xref)
this.refs.push(xref)
else
throw Error(`Invalid cross-reference-stream type ${_type}`)
}
}
/**
* Extracts the cross-reference-table from the stream
* */
extractStream(stream: Stream) {
let cross_reference_length = this.w.reduce((a, b) => a + b, 0)
// check if the data stream has a valid size
if (stream.getLength() !== cross_reference_length * this.index.filter((v, i) => i % 2 === 1).reduce((a, b) => a + b, 0))
throw Error(`Invalid stream length - is ${stream.getLength()} but should be ${cross_reference_length * this.index.filter((v, i) => i % 2 === 1).reduce((a, b) => a + b, 0)}`)
if (this.index.length % 2 === 1)
throw Error(`Invalid index flag ${this.index}`)
for (let i = 0; i < this.index.length; i += 2) {
this.extractCrossReferenceSection(this.index[i], this.index[i + 1], stream)
}
}
/**
* Parses the Cross-Reference-Stream-Object at the given index
* */
extract(xref: XRef) {
let index = xref.pointer
this.start_pointer = index
let crs_object = ObjectUtil.extractObject(this.data, xref)
let ptr_object_end = Util.locateSequence(Util.ENDOBJ, this.data, index)
this.data = this.data.slice(index, ptr_object_end)
// check type
if (crs_object.value["/Type"] !== "/XRef")
throw Error(`Invalid Cross-Reference-Stream-object type: ${crs_object.value["/Type"]}`)
// extract size
if (!crs_object.value["/Size"])
throw Error(`Invalid size value ${crs_object.value["/Size"]}`)
this.trailer.size = crs_object.value["/Size"]
// extract ROOT if it exists
if (crs_object.value["/Root"])
this.trailer.root = crs_object.value["/Root"]
// extract PREV if it exists
if (crs_object.value["/Prev"])
this.trailer.prev = crs_object.value["/Prev"]
// extract W parameter
this.w = crs_object.value["/W"]
if (!this.w || 0 === this.w.length)
throw Error("Invalid /W parameter in Cross-Reference-Stream-Object")
// extract Index parameter
this.index = crs_object.value["/Index"]
if (!this.index || 0 === this.index.length)
this.index = [0, crs_object.value["/Size"]]
if (!crs_object.stream)
throw Error("Missing stream at cross reference stream object")
let stream = crs_object.stream
if (!stream)
throw Error("Invalid stream object")
this.streamLength = crs_object.value["/Length"]
this.extractStream(stream)
// the cross-reference-stream object is also a known reference
this.refs.push({ id: crs_object.id.obj, pointer: this.start_pointer, generation: crs_object.id.generation, free: false, update: true })
}
/**
* Returs the update section representing this CrossReferenceStreamObject
* */
getUpdateSection(): UpdateSection {
return {
start_pointer: this.start_pointer,
size: this.trailer.size,
prev: this.trailer.prev,
root: this.trailer.root,
refs: this.refs,
is_encrypted: this.trailer.is_encrypted,
encrypt: this.trailer.encrypt,
id: this.trailer.id
}
}
}
/**
* Holds the complete information of one update section in the Cross-Reference-Table format. That comprises:
* - the body update
* - the crossiste reference table
* - the trailer
* */
export class CrossReferenceTable {
public refs: XRef[] = []
public start_pointer: number = -1
public trailer: Trailer = generateDefaultTrailer()
constructor(private data: Uint8Array) { }
/**
* Returns the reference with the given id
* */
getReference(id: number): XRef | undefined {
for (let ref of this.refs) {
if (ref.id === id)
return ref
}
return undefined
}
/**
* Returs the update section representing this CrossReferenceTable
* */
getUpdateSection(): UpdateSection {
return {
start_pointer: this.start_pointer,
size: this.trailer.size,
refs: this.refs,
prev: this.trailer.prev,
root: this.trailer.root,
is_encrypted: this.trailer.is_encrypted,
encrypt: this.trailer.encrypt,
id: this.trailer.id
}
}
/**
* Extracts the header of a sub section. For instance
*
* 0 1 // <--
* ...
*
* So the obejct id 0 and the number of sub section entries 1
* */
extractSubSectionHeader(index: number): SubSectionHeader {
let ptr = Util.locateDelimiter(this.data, index)
let obj_id = Util.extractNumber(this.data, index, ptr).result
ptr = Util.skipDelimiter(this.data, ptr + 1)
let ptr_ref_count = ptr
ptr = Util.locateDelimiter(this.data, ptr)
let reference_count = Util.extractNumber(this.data, ptr_ref_count, ptr).result
return { id: obj_id, count: reference_count, end_ptr: ptr }
}
/**
* Extracts the references of a sub section. The index points to the start of
* the first reference and count represents the number of references that are
* contained in the subsection.
*
* The first_object_id is the id provided in the sub section header
*
* By definition of the PDF standard one entry is 20 bytes long, but since the standard is rarely respected we better make it failsafe
* */
extractReferences(index: number, count: number, first_object_id: number): {refs: XRef[], end_index: number} {
let _refs: XRef[] = []
let res : ExtractionResult = { result: null, start_index: -1, end_index: index}
for (let i = 0; count === -1 || i < count; ++i) {
res = Util.readNextWord(this.data, res.end_index + 1)
let pointer = Util.extractNumber(res.result, 0).result
res = Util.readNextWord(this.data, res.end_index + 1)
let generation = Util.extractNumber(res.result, 0).result
res = Util.readNextWord(this.data, res.end_index + 1)
let ptr_flag = res.result
let isFree = ptr_flag[0] === 102 // 102 = f
_refs.push({
id: first_object_id + i,
pointer: pointer,
generation: generation,
free: isFree,
update: !isFree
})
// if the word trailer occurs stop since we reached the end
if (this.data[Util.skipSpaces(this.data, res.end_index + 1)] === 116) {
break
}
}
return {refs: _refs, end_index: res.end_index}
}
/**
* Extracts the trailer of the subsection that means the part stating with the 'trailer' keyword and
* in particular the trailer dictionary
* */
extractTrailer(index: number): Trailer {
// run forward to the dictionary start
index = Util.locateSequence(Util.DICT_START, this.data, index) + 2
let obj: any = {}
ObjectUtil.extractDictKeyRec(this.data, index, obj)
return {
size: obj["/Size"],
root: obj["/Root"],
prev: obj["/Prev"] ? obj["/Prev"] : undefined,
is_encrypted: obj["/Encrypt"] ? true : false,
encrypt: obj["/Encrypt"] ? obj["/Encrypt"] : undefined,
id: obj["/ID"] ? obj["/ID"] : undefined
}
}
/**
* Parses the Cross Reference Table at the given index
* */
extract(index: number, skipXREFString : boolean = false) {
this.start_pointer = index
let start_ptr = index
if (!skipXREFString)
start_ptr += 5 // + length(xref) + blank
start_ptr = Util.skipDelimiter(this.data, start_ptr)
// check if there actually is a subsection header
// if the line finishes with an 'f' we know that it starts with the first cross reference entry
let tmp_ptr = start_ptr
while(tmp_ptr < this.data.length && this.data[tmp_ptr] !== 102 && this.data[tmp_ptr] !== 13 && this.data[tmp_ptr] !== 10) tmp_ptr++
let first_header = {id: 0, count: -1, end_ptr: start_ptr - 1}
if (this.data[tmp_ptr] === 10 || this.data[tmp_ptr] === 13)
first_header = this.extractSubSectionHeader(start_ptr)
let ref_start = Util.skipDelimiter(this.data, first_header.end_ptr + 1)
// extract first reference
let reference_result = this.extractReferences(ref_start, first_header.count, first_header.id)
this.refs = this.refs.concat(reference_result.refs)
// extract remaining references
start_ptr = Util.skipSpaces(this.data, reference_result.end_index + 1)
while (first_header.count > 0 && this.data[start_ptr] !== 116) { // 116 = 't' start of the word trailer that concludes the crosssite reference section
let header = this.extractSubSectionHeader(start_ptr)
ref_start = Util.skipDelimiter(this.data, header.end_ptr + 1)
let references = this.extractReferences(ref_start, header.count, header.id)
this.refs = this.refs.concat(references.refs)
start_ptr = Util.skipSpaces(this.data, references.end_index + 1)
}
this.trailer = this.extractTrailer(start_ptr)
}
}
/**
* Represents the complete PDF document history and therefore holds the
* updated body parts, the crosssite references and the document trailers
* */
export class DocumentHistory {
public updates: UpdateSection[] = []
public trailerSize: number = -1
/**
* Holds object ids that were formerly freed and are now 'already' reused.
* This is used to prevent a freed object a second time */
private already_reused_ids: XRef[] = []
constructor(private data: Uint8Array) {
this.data = new Uint8Array(data)
}
/**
* Extracts the cross reference table starting at the given index
* */
extractCrossReferenceTable(index: number, skipXREFString : boolean = false): CrossReferenceTable {
let crt = new CrossReferenceTable(this.data)
crt.extract(index, skipXREFString)
return crt
}
/**
* Extracts the cross reference stream object starting at the given index
* */
extractCrossReferenceStreamObject(xref: XRef): CrossReferenceStreamObject {
let crs = new CrossReferenceStreamObject(this.data)
crs.extract(xref)
return crs
}
/**
* Extracts the last update section of a document (that means
* the most recent update locating at the end of the file)
*
* Handles missing or wrong pointers
* and also decides, whether the cross reference table is provided as stream object or regular
* */
extractDocumentEntry(): {pointer: number, sectionType: string} {
let ptr = this.data.length - 1
let ptr_startxref = Util.locateSequenceReversed(Util.STARTXREF, this.data, ptr, true) + 9
// identify cross reference section type
let section_type : string = "UNKNOWN"
let preceding_word_index = Util.skipSpacesReverse(this.data, ptr_startxref - 10)
if (Util.areArraysEqual(this.data.slice(preceding_word_index - 5, preceding_word_index + 1), Util.ENDOBJ)) {
section_type = "stream"
} else {
section_type = "trailer"
}
// try to locate cross reference table manually
let locateXREFStartManually = () => {
let new_ptr = Util.locateSequenceReversed(Util.XREF, this.data, this.data.length)
section_type = "trailer"
while (new_ptr > 0 && this.data[new_ptr - 1] === 116) {// 116 = 't' -> we are looking for 'xref' not 'startxref'
new_ptr = Util.locateSequenceReversed(Util.XREF, this.data, new_ptr - 1)
}
if (new_ptr === -1) { // than we try to identify the word 'trailer' and run backwards as long as we find a symbol that is not a number or 'f' or 'n' - what could possibly go wrong
section_type = "trailer_without_xref_start"
new_ptr = Util.locateSequenceReversed(Util.TRAILER, this.data, this.data.length)
if (new_ptr > 0) {
new_ptr--
while (new_ptr > 0 && (Util.isSpace(this.data[new_ptr]) || Util.isNumber(this.data[new_ptr]) || this.data[new_ptr] === 110 || //110 = 'n' 102 = 'f'
this.data[new_ptr] === 102)) --new_ptr
new_ptr = Util.skipSpaces(this.data, new_ptr + 1)
}
}
return {pointer: new_ptr, sectionType: section_type}
}
try {
ptr = Util.extractNumber(this.data, ptr_startxref).result
} catch (err) {
return locateXREFStartManually()
}
if (ptr > this.data.length) {
return locateXREFStartManually()
}
// start section with XREF?
if (section_type !== "stream" && !(this.data[ptr] === Util.XREF[0] && this.data[ptr + 1] === Util.XREF[1] && this.data[ptr + 2] === Util.XREF[2] && this.data[ptr + 3] === Util.XREF[3])) {
return locateXREFStartManually()
}
return {pointer: ptr, sectionType: section_type}
}
/**
* Extracts the entire update sections
*
* Needs to adapt depending whether the document uses a cross-reference table or a cross-reference stream object
* */
extractDocumentHistory() {
let document_entry = this.extractDocumentEntry()
let ptr = document_entry.pointer
if (ptr === -1) {
throw Error("Could not locate document entry")
}
let xref = {
id: -1,
pointer: ptr,
generation: 0,
free: false,
update: true
}
this.extractCrossReferenceTables(document_entry, xref)
// adapt pointer in case there is junk before the header
let pdf_header_start = Util.locateSequence(Util.VERSION, this.data, 0)
if (pdf_header_start !== 0 && pdf_header_start !== -1) {
for (let updateSection of this.updates) {
for(let ref of updateSection.refs) {
ref.pointer += pdf_header_start
}
}
}
}
/**
* Extracts the cross reference tables of the entire document
* */
extractCrossReferenceTables(document_entry : {pointer: number, sectionType: string}, xref : XRef) {
let ptr = document_entry.pointer
// Handle cross reference table
if (document_entry.sectionType === "trailer") {
let crt = this.extractCrossReferenceTable(ptr)
this.updates.push(crt.getUpdateSection())
let us = this.updates[0]
while (us.prev) {
crt = this.extractCrossReferenceTable(us.prev)
this.updates.push(crt.getUpdateSection())
us = this.updates[this.updates.length - 1]
}
} else if (document_entry.sectionType === "stream") { // handle cross reference stream object
let crs = this.extractCrossReferenceStreamObject(xref)
this.updates.push(crs.getUpdateSection())
let us = this.updates[0]
while (us.prev) {
let _xref = {
id: -1,
pointer: us.prev,
generation: 0,
free: false,
update: true
}
crs = this.extractCrossReferenceStreamObject(_xref)
this.updates.push(crs.getUpdateSection())
us = this.updates[this.updates.length - 1]
}
} else if (document_entry.sectionType === "trailer_without_xref_start") {
let crt = this.extractCrossReferenceTable(ptr, true)
this.updates.push(crt.getUpdateSection())
let us = this.updates[0]
while (us.prev) {
crt = this.extractCrossReferenceTable(us.prev)
this.updates.push(crt.getUpdateSection())
us = this.updates[this.updates.length - 1]
}
} else {
throw Error("Could not part cross reference table")
}
this.trailerSize = this.extractReferenceNumberCount()
}
/**
* Counts the number of specified objects
* */
extractReferenceNumberCount() : number {
let visited : number[] = []
let count = 0
for(let update of this.updates) {
for(let ref of update.refs) {
if (!visited.includes(ref.id)) {
count++
visited.push(ref.id)
}
}
}
return count
}
/**
* Primarily for clarification. The first element is the most recent. We parsed backwards.
* */
getRecentUpdate(): UpdateSection {
return this.updates[0]
}
/**
* Indicates whether the PDF document is encrypted
* */
isEncrypted() : boolean {
return this.getRecentUpdate().is_encrypted
}
/**
* By running through the PDf history we can for every object id determine the pointer address to the most recent version, and
* whether the object id is still in used.
*
* So the object lookup table has an entry for every existing object id, a pointer to the the most recent object definition, as long
* as the object exists, or an according indication otherwise.
* */
createObjectLookupTable(): ObjectLookupTable {
let objTable: { [id: number]: XRef } = {}
let update: UpdateSection = this.getRecentUpdate()
let i = 1
while (Object.keys(objTable).length < this.extractReferenceNumberCount()) {
let refs = update.refs
for (let ref of refs) {
if (!objTable.hasOwnProperty(ref.id)) {
objTable[ref.id] = ref
}
}
update = this.updates[i]
++i
}
return objTable
}
/**
* Returns the new object id. It primarily tries to reuse an existing id, but if no such exists it will return a
* new one
* */
getFreeObjectId(): ReferencePointer {
let objectLookupTable: ObjectLookupTable = this.createObjectLookupTable()
let free_header = objectLookupTable[0]
if (!free_header)
throw Error("Crosssite reference has no header for the linked list of free objects")
// if the pointer of object 0 points to 0 there is no freed object that can be reused
if (0 === free_header.pointer) {
if (-1 === this.trailerSize)
throw Error("Trailer size not set")
return { obj: this.trailerSize++, generation: 0, reused: false }
}
// get list head
let ptr = free_header.pointer
let freedHeaderList: XRef[] = []
while (ptr !== 0) {
freedHeaderList.push(free_header)
free_header = objectLookupTable[ptr]
if (!free_header.free) {
// handle the case of an incosistent xref
return { obj: this.trailerSize++, generation: 0, reused: false }
}
ptr = free_header.pointer
}
let getFreeHeader = (freeHeaderList: XRef[]) => {
for (let p of freeHeaderList.reverse()) {
if (p.generation < 65535 && // max generation number
-1 === this.already_reused_ids.indexOf(p)) { // not already reused
return p
}
}
return undefined
}
let reused_free_header = getFreeHeader(freedHeaderList)
if (reused_free_header) {
free_header = reused_free_header
// store used id to make sure it will not be selected again
this.already_reused_ids.push(free_header)
} else {
// handle the case that all freed object ids are already reused
return { obj: this.trailerSize++, generation: 0, reused: false }
}
return { obj: free_header.pointer, generation: objectLookupTable[free_header.id].generation, reused: true }
}
} | the_stack |
import { assert } from "chai";
import { Value, load } from "../../src/dom";
import { Decimal } from "../../src/IonDecimal";
import JSBI from "jsbi";
/**
* This file contains 'equals()' tests for each Ion data type:
* - Demonstrates equivalence of dom.Value with strict and non-strict(relaxed) modes.
* - Also shows equivalence with epsilon precision for Float values.
* - Demonstrates equivalence with JS values
*
* See the class-level documentation for more details on equals()
*/
describe("Equivalence", () => {
it("equals() for Null", () => {
let nullValue1: Value = load("null.blob")!;
let nullValue2: Value = load("null.blob")!;
let nullValue3: Value = load("null")!;
let nullValue4: Value = load("null.null")!;
let nullValue5: Value = load('"null"')!;
assert.isTrue(nullValue1.ionEquals(nullValue2));
assert.isFalse(nullValue1.ionEquals(nullValue3));
assert.isTrue(nullValue3.ionEquals(nullValue4));
assert.isFalse(nullValue3.ionEquals(nullValue5));
// Equivalence between JS Value and Ion DOM Value
assert.isTrue(nullValue3.equals(null));
assert.isFalse(nullValue3.ionEquals(null));
assert.isFalse(nullValue1.equals(null));
});
it("equals() for Boolean", () => {
let bool1: Value = load("foo::false")!;
let bool2: Value = load("foo::false")!;
let bool3: Value = load("false")!;
let bool4: Value = load("true")!;
assert.isTrue(bool1.ionEquals(bool2));
// annotations should match for strict comparison
assert.isFalse(bool1.ionEquals(bool3));
assert.isTrue(bool1.equals(bool3));
assert.isFalse(bool1.ionEquals(bool4));
// Equivalence between JS Value and Ion DOM Value
assert.isTrue(bool1.equals(false));
assert.isFalse(bool1.ionEquals(false));
assert.isFalse(bool1.equals(true));
assert.isTrue(bool1.equals(new Boolean(false)));
assert.isFalse(bool1.equals(new Boolean(true)));
});
it("equals() for Integer", () => {
let int1: Value = load("foo::bar::7")!;
let int2: Value = load("foo::bar::7")!;
let int3: Value = load("7")!;
let int4: Value = load("-10")!;
assert.isTrue(int1.ionEquals(int2));
// annotations should match for strict comparison
assert.isFalse(int1.ionEquals(int3));
assert.isTrue(int1.equals(int3));
assert.isFalse(int1.ionEquals(int4));
// Equivalence between JS Value and Ion DOM Value
assert.isTrue(int1.equals(7));
assert.isFalse(int1.ionEquals(7));
assert.isFalse(int1.equals(10));
assert.isTrue(int1.equals(new Number(7)));
assert.isFalse(int1.equals(new Number(10)));
assert.isTrue(int1.equals(JSBI.BigInt(7)));
assert.isFalse(int1.equals(JSBI.BigInt(10)));
});
it("equals() for Float", () => {
let float1: Value = load("baz::qux::15e-1")!;
let float2: Value = load("baz::qux::15e-1")!;
let float3: Value = load("15e-1")!;
let float4: Value = load("1.5")!;
let float5: Value = load("12e-1")!;
assert.isTrue(float1.ionEquals(float2));
// annotations should match for strict comparison
assert.isFalse(float1.ionEquals(float3));
assert.isTrue(float1.equals(float3));
// Decimal and Float values will not be equivalent
assert.isFalse(float1.ionEquals(float4));
// both values should be at least equivalent by epsilon value
assert.isTrue(float3.ionEquals(float5, {epsilon: 0.5}));
assert.isFalse(float3.ionEquals(float5, {epsilon: 0.2}));
// Equivalence between JS Value and Ion DOM Value
assert.isTrue(float1.equals(1.5));
assert.isFalse(float1.ionEquals(1.5));
assert.isFalse(float1.equals(1.2));
assert.isTrue(float1.equals(1.2, {epsilon: 0.5}));
assert.isTrue(float1.equals(new Number(1.5)));
assert.isFalse(float1.equals(new Number(1.2)));
assert.isTrue(
float1.equals(new Number(1.2), {epsilon: 0.5})
);
});
it("equals() for Decimal", () => {
let decimal1: Value = load("101.5")!;
let decimal2: Value = load("101.5")!;
let decimal3: Value = load("101")!;
assert.isTrue(decimal1.ionEquals(decimal2));
assert.isFalse(decimal1.ionEquals(decimal3));
assert.isFalse(decimal3.ionEquals(decimal1));
// Equivalence between JS Value and Ion DOM Value
assert.isTrue(
decimal1.equals(new Decimal("101.5"))
);
assert.isFalse(
decimal1.equals(new Decimal("105.8"))
);
});
it("equals() for Timestamp", () => {
let timestamp1: Value = load("DOB::2020-01-16T20:15:54.066Z")!;
let timestamp2: Value = load("DOB::2020-01-16T20:15:54.066Z")!;
let timestamp3: Value = load("DOB::2001T")!;
let timestamp4: Value = load("DOB::2001-01-01T")!;
assert.isTrue(timestamp1.ionEquals(timestamp2));
// In strict mode the precision and local offsets are also compared
assert.isFalse(timestamp1.ionEquals(timestamp3));
// Non strict mode precision and local offset are ignored along with annotations
assert.isTrue(timestamp3.equals(timestamp4));
// Equivalence between JS Value and Ion DOM Value
assert.isTrue(
timestamp1.equals(new Date("2020-01-16T20:15:54.066Z"))
);
assert.isFalse(
timestamp1.equals(new Date("2020-02-16T20:15:54.066Z"))
);
});
it("equals() for Symbol", () => {
let symbol1: Value = load('"Saturn"')!;
let symbol2: Value = load('"Saturn"')!;
let symbol3: Value = load('"Jupiter"')!;
assert.isTrue(symbol1.ionEquals(symbol2));
assert.isFalse(symbol1.ionEquals(symbol3));
// Equivalence between JS Value and Ion DOM Value
assert.isTrue(symbol1.equals("Saturn"));
assert.isTrue(
symbol1.equals(new String("Saturn"))
);
assert.isFalse(
symbol1.equals(new String("Jupiter"))
);
assert.isFalse(symbol1.equals("Jupiter"));
assert.isFalse(symbol1.ionEquals(new String("Saturn")));
assert.isFalse(symbol1.ionEquals("Saturn"));
});
it("equals() for String", () => {
let string1: Value = load('"Saturn"')!;
let string2: Value = load('"Saturn"')!;
let string3: Value = load('"Jupiter"')!;
assert.isTrue(string1.ionEquals(string2));
assert.isFalse(string1.ionEquals(string3));
// Equivalence between JS Value and Ion DOM Value
assert.isTrue(string1.equals("Saturn"));
assert.isTrue(
string1.equals(new String("Saturn"))
);
assert.isFalse(
string1.equals(new String("Jupiter"))
);
assert.isFalse(string1.equals("Jupiter"));
assert.isFalse(string1.ionEquals(new String("Saturn")));
assert.isFalse(string1.ionEquals("Saturn"));
});
it("equals() for Clob", () => {
let clob1: Value = load('month::{{"February"}}')!;
let clob2: Value = load('month::{{"February"}}')!;
let clob3: Value = load('month::{{"January"}}')!;
let clob4: Value = load('{{"Hello"}}')!;
assert.isTrue(clob1.ionEquals(clob2));
assert.isFalse(clob1.ionEquals(clob3));
// Equivalence between JS Value and Ion DOM Value
assert.isTrue(
clob4.equals(new Uint8Array([72, 101, 108, 108, 111]))
);
assert.isFalse(
clob4.equals(new Uint8Array([72, 101, 108, 108]))
);
});
it("equals() for Blob", () => {
let blob1: Value = load("quote::{{VG8gaW5maW5pdHkuLi4gYW5kIGJleW9uZCE=}}")!;
let blob2: Value = load("quote::{{VG8gaW5maW5pdHkuLi4gYW5kIGJleW9uZCE=}}")!;
let blob3: Value = load("quote::{{dHdvIHBhZGRpbmcgY2hhcmFjdGVycw==}}")!;
let blob4: Value = load("{{VG8gaW5maW5pdHkuLi4gYW5kIGJleW9uZCE=}}")!;
assert.isTrue(blob1.ionEquals(blob2));
assert.isFalse(blob1.ionEquals(blob3));
assert.isTrue(blob1.equals(blob4));
});
it("equals() for List", () => {
let list1: Value = load('planets::["Mercury", "Venus", "Earth", "Mars"]')!;
let list2: Value = load('planets::["Mercury", "Venus", "Earth", "Mars"]')!;
let list3: Value = load('planets::["Mercury", "Venus"]')!;
let list4: Value = load(
'planets::["Mercury", "Venus", "Earth", "Jupiter"]'
)!;
assert.isTrue(list1.ionEquals(list2));
assert.isFalse(list1.ionEquals(list3));
assert.isFalse(list3.ionEquals(list1));
assert.isFalse(list1.ionEquals(list4));
assert.isFalse(list4.ionEquals(list1));
// Equivalence between JS Value and Ion DOM Value
assert.isTrue(
list1.equals(["Mercury", "Venus", "Earth", "Mars"])
);
assert.isFalse(
list1.equals(["Mercury", "Venus", "Earth"])
);
});
it("equals() for SExpression", () => {
let sexp1: Value = load('planets::("Mercury" "Venus" "Earth" "Mars")')!;
let sexp2: Value = load('planets::("Mercury" "Venus" "Earth" "Mars")')!;
let sexp3: Value = load('planets::("Mercury" "Venus" "Earth")')!;
let sexp4: Value = load('planets::("Mercury" "Venus" "Earth" "Jupiter")')!;
assert.isTrue(sexp1.ionEquals(sexp2));
assert.isFalse(sexp1.ionEquals(sexp3));
assert.isFalse(sexp3.ionEquals(sexp1));
assert.isFalse(sexp1.ionEquals(sexp4));
assert.isFalse(sexp4.ionEquals(sexp1));
});
it("equals() for Struct", () => {
let struct1: Value = load(
"foo::bar::{" +
"name: {" +
'first: "John", ' +
'middle: "Jacob", ' +
'last: "Jingleheimer-Schmidt",' +
"}," +
"age: 41" +
"}"
)!;
let struct2: Value = load(
"foo::bar::{" +
"name: {" +
'first: "John", ' +
'middle: "Jacob", ' +
'last: "Jingleheimer-Schmidt",' +
"}," +
"age: 41" +
"}"
)!;
let struct3: Value = load(
"foo::bar::{" +
"name: {" +
'first: "Jessica", ' +
'middle: "Jacob", ' +
'last: "Jingleheimer-Schmidt",' +
"}," +
"age: 41" +
"}"
)!;
let struct4: Value = load(
"foo::bar::{" +
"name: {" +
'first: "John", ' +
'middle: "Jacob", ' +
'last: "Jingleheimer-Schmidt",' +
"}," +
"}"
)!;
let struct5: Value = load(
"{" +
"name: {" +
'first: "John", ' +
'middle: "Jacob", ' +
'last: "Jingleheimer-Schmidt",' +
"}," +
"}"
)!;
assert.isTrue(struct1.ionEquals(struct2));
assert.isFalse(struct1.ionEquals(struct3));
assert.isFalse(struct3.ionEquals(struct1));
assert.isFalse(struct1.ionEquals(struct4));
assert.isFalse(struct4.ionEquals(struct1));
// annotations should match for strict comparison
assert.isTrue(struct4.equals(struct5));
// Equivalence between JS Value and Ion DOM Value
assert.isTrue(
struct1.equals(
{
name: {
first: "John",
middle: "Jacob",
last: "Jingleheimer-Schmidt",
},
age: 41,
}
)
);
assert.isFalse(
struct1.equals(
{
name: {
first: "John",
middle: "Jacob",
last: "Jingleheimer-Schmidt",
},
}
)
);
});
it("equals() for Struct inside List", () => {
let value: Value = load(
'[{ foo: 7, bar: true, baz: 98.6, qux: "Hello" }]'
)!;
assert.isTrue(
value.equals([{ foo: 7, bar: true, baz: 98.6, qux: "Hello" }])
);
});
it("equals() for List inside Struct", () => {
let value: Value = load("{ foo: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] }")!;
assert.isTrue(
value.equals(
{ foo: [9, 8, 7, 6, 5, 4, 3, 2, 1, 0] }
)
);
});
it("equals() for Struct with duplicate fields", () => {
let value1: Value = load("{ foo: 'bar', foo: 'baz' }")!;
let value2: Value = load("{ foo: 'bar', foo: 'baz' }")!;
let value3: Value = load("{ foo: 'bar', foo: 'qux' }")!;
let value4: Value = load("{ foo: 1, baz: true, foo: 2 }")!;
let value5: Value = load("{ foo: 2, foo: 1, baz: true }")!;
assert.isTrue(value1.ionEquals(value2));
assert.isTrue(value2.ionEquals(value1));
assert.isFalse(value1.ionEquals(value3));
// Equivalence for unordered fields
assert.isTrue(value4.ionEquals(value5));
});
}); | the_stack |
import { MIRAssembly, MIRConceptType, MIRFieldDecl, MIRInvokeDecl, MIRInvokePrimitiveDecl, MIRObjectEntityTypeDecl, MIRPrimitiveInternalEntityTypeDecl } from "../../../compiler/mir_assembly";
import { MIRFieldKey, MIRInvokeKey, MIRResolvedTypeKey, MIRVirtualMethodKey } from "../../../compiler/mir_ops";
import { ICPPAssembly, ICPPConstDecl, ICPPEntityLayoutInfo, ICPPLayoutCategory, ICPPRecordLayoutInfo, TranspilerOptions } from "./icpp_assembly";
import { ICPPTypeEmitter } from "./icpptype_emitter";
import { ICPPBodyEmitter } from "./iccpbody_emitter";
import { constructCallGraphInfo } from "../../../compiler/mir_callg";
import { SourceInfo } from "../../../ast/parser";
function NOT_IMPLEMENTED(msg: string) {
throw new Error(`Not Implemented: ${msg}`);
}
enum ICPPParseTag {
BuiltinTag = 0x0,
ValidatorTag,
BoxedStructTag,
EnumTag,
StringOfTag,
DataStringTag,
DataBufferTag,
TupleStructTag,
TupleRefTag,
RecordStructTag,
RecordRefTag,
EntityObjectStructTag,
EntityObjectRefTag,
EntityConstructableStructTag,
EntityConstructableRefTag,
EphemeralListTag,
EntityDeclOfTag,
ListTag,
StackTag,
QueueTag,
SetTag,
MapTag,
PartialVector4Tag,
PartialVector8Tag,
ListTreeTag,
MapTreeTag,
RefUnionTag,
InlineUnionTag,
UniversalUnionTag
}
class ICPPEmitter {
readonly assembly: MIRAssembly;
readonly temitter: ICPPTypeEmitter;
readonly bemitter: ICPPBodyEmitter;
readonly icppasm: ICPPAssembly;
constructor(assembly: MIRAssembly, temitter: ICPPTypeEmitter, bemitter: ICPPBodyEmitter, icppasm: ICPPAssembly) {
this.assembly = assembly;
this.temitter = temitter;
this.bemitter = bemitter;
this.icppasm = icppasm;
}
private static initializeICPPAssembly(srcCode: { fname: string, contents: string }[], assembly: MIRAssembly, temitter: ICPPTypeEmitter): ICPPAssembly {
const decltypes = [...assembly.typeMap].filter((v) => !(assembly.entityDecls.get(v[0]) instanceof MIRPrimitiveInternalEntityTypeDecl)).map((v) => temitter.getICPPLayoutInfo(temitter.getMIRType(v[1].typeID)));
const alltypenames = [...assembly.typeMap].map((tt) => tt[0]);
const allproperties = new Set<string>(([] as string[]).concat(...decltypes.filter((tt) => tt instanceof ICPPRecordLayoutInfo).map((rt) => (rt as ICPPRecordLayoutInfo).propertynames)));
const allfields = new Set<MIRFieldKey>(([] as string[]).concat(...decltypes.filter((tt) => tt instanceof ICPPEntityLayoutInfo).map((rt) => (rt as ICPPEntityLayoutInfo).fieldnames)));
const allinvokes = new Set([...assembly.invokeDecls, ...assembly.primitiveInvokeDecls]
.filter((iiv) => !(iiv[1] instanceof MIRInvokePrimitiveDecl) || (iiv[1] as MIRInvokePrimitiveDecl).implkey !== "default")
.map((iiv) => iiv[0]));
const vcallarray = [...assembly.entityDecls].filter((edcl) => edcl[1] instanceof MIRObjectEntityTypeDecl).map((edcl) => [...(edcl[1] as MIRObjectEntityTypeDecl).vcallMap].map((ee) => ee[0]));
const allvinvokes = new Set<string>((([] as MIRVirtualMethodKey[]).concat(...vcallarray)));
return new ICPPAssembly(alltypenames, [...allproperties].sort(), [...allfields].sort().map((fkey) => assembly.fieldDecls.get(fkey) as MIRFieldDecl), srcCode, [...allinvokes].sort(), [...allvinvokes].sort());
}
private processVirtualEntityUpdates() {
//
//TODO: not implemented yet -- see SMT implementation
//
}
private processAssembly(assembly: MIRAssembly, istestbuild: boolean, entrypoints: MIRInvokeKey[]) {
const cginfo = constructCallGraphInfo(entrypoints, assembly, istestbuild);
const rcg = [...cginfo.topologicalOrder].reverse();
for (let i = 0; i < rcg.length; ++i) {
const cn = rcg[i];
const cscc = cginfo.recursive.find((scc) => scc.has(cn.invoke));
let worklist = cscc !== undefined ? [...cscc].sort() : [cn.invoke];
for (let mi = 0; mi < worklist.length; ++mi) {
const ikey = worklist[mi];
const idcl = (this.assembly.invokeDecls.get(ikey) || this.assembly.primitiveInvokeDecls.get(ikey)) as MIRInvokeDecl;
const finfo = this.bemitter.generateICPPInvoke(idcl);
this.processVirtualEntityUpdates();
if (finfo !== undefined) {
this.icppasm.invdecls.push(finfo);
}
}
}
this.bemitter.requiredProjectVirtualTupleIndex.forEach((rvpt) => {
const vtype = rvpt.argflowtype;
const opts = [...this.assembly.typeMap].filter((tme) => this.temitter.isUniqueTupleType(tme[1]) && this.assembly.subtypeOf(tme[1], vtype)).map((tme) => tme[1]);
this.icppasm.vinvokenames.add(rvpt.inv);
opts.forEach((ttup) => {
const oper = this.bemitter.generateProjectTupleIndexVirtual(rvpt, new SourceInfo(-1, -1, -1 ,-1), ttup);
this.icppasm.invdecls.push(oper);
this.icppasm.invokenames.add(oper.ikey);
let vte = this.icppasm.vtable.find((v) => v.oftype === ttup.typeID);
if(vte !== undefined) {
vte.vtable.push({vcall: rvpt.inv, inv: oper.ikey});
}
else {
vte = { oftype: ttup.typeID, vtable: [{vcall: rvpt.inv, inv: oper.ikey}] };
this.icppasm.vtable.push(vte);
}
});
});
this.bemitter.requiredProjectVirtualRecordProperty.forEach((rvpr) => {
const vtype = rvpr.argflowtype;
const opts = [...this.assembly.typeMap].filter((tme) => this.temitter.isUniqueRecordType(tme[1]) && this.assembly.subtypeOf(tme[1], vtype)).map((tme) => tme[1]);
this.icppasm.vinvokenames.add(rvpr.inv);
opts.forEach((trec) => {
const oper = this.bemitter.generateProjectRecordPropertyVirtual(rvpr, new SourceInfo(-1, -1, -1 ,-1), trec);
this.icppasm.invdecls.push(oper);
this.icppasm.invokenames.add(oper.ikey);
let vte = this.icppasm.vtable.find((v) => v.oftype === trec.typeID);
if(vte !== undefined) {
vte.vtable.push({vcall: rvpr.inv, inv: oper.ikey});
}
else {
vte = { oftype: trec.typeID, vtable: [{vcall: rvpr.inv, inv: oper.ikey}] };
this.icppasm.vtable.push(vte);
}
});
});
this.bemitter.requiredProjectVirtualEntityField.forEach((rvpe) => {
const vtype = rvpe.argflowtype;
const opts = [...this.assembly.typeMap].filter((tme) => this.temitter.isUniqueEntityType(tme[1]) && this.assembly.subtypeOf(tme[1], vtype)).map((tme) => tme[1]);
this.icppasm.vinvokenames.add(rvpe.inv);
opts.forEach((tentity) => {
const oper = this.bemitter.generateProjectEntityFieldVirtual(rvpe, new SourceInfo(-1, -1, -1 ,-1), tentity);
this.icppasm.invdecls.push(oper);
this.icppasm.invokenames.add(oper.ikey);
let vte = this.icppasm.vtable.find((v) => v.oftype === tentity.typeID);
if(vte !== undefined) {
vte.vtable.push({vcall: rvpe.inv, inv: oper.ikey});
}
else {
vte = { oftype: tentity.typeID, vtable: [{vcall: rvpe.inv, inv: oper.ikey}] };
this.icppasm.vtable.push(vte);
}
});
});
this.bemitter.requiredUpdateVirtualTuple.forEach((rvut) => {
NOT_IMPLEMENTED("requiredUpdateVirtualTuple");
});
this.bemitter.requiredUpdateVirtualRecord.forEach((rvur) => {
NOT_IMPLEMENTED("requiredUpdateVirtualTuple");
});
this.bemitter.requiredUpdateVirtualEntity.forEach((rvue) => {
NOT_IMPLEMENTED("requiredUpdateVirtualTuple");
});
this.bemitter.requiredUpdateEntityWithCheck.forEach((rvue) => {
const oper = this.bemitter.generateUpdateEntityFieldDirect(rvue, new SourceInfo(-1, -1, -1, -1));
this.icppasm.invdecls.push(oper);
this.icppasm.invokenames.add(oper.ikey);
});
this.bemitter.requiredSingletonConstructorsList.forEach((scl) => {
this.icppasm.invdecls.push(this.bemitter.generateSingletonConstructorList(scl));
this.icppasm.invokenames.add(scl.inv);
});
this.bemitter.requiredSingletonConstructorsMap.forEach((scm) => {
this.icppasm.invdecls.push(this.bemitter.generateSingletonConstructorMap(scm));
this.icppasm.invokenames.add(scm.inv);
});
this.bemitter.requiredTupleAppend.forEach((rvta) => {
NOT_IMPLEMENTED("requiredUpdateVirtualTuple");
});
this.bemitter.requiredRecordMerge.forEach((rvrm) => {
NOT_IMPLEMENTED("requiredUpdateVirtualTuple");
});
this.icppasm.cbuffsize = this.bemitter.constsize;
this.icppasm.cmask = "11111";
for(let i = 1; i < this.bemitter.constlayout.length; ++i) {
this.icppasm.cmask += this.bemitter.constlayout[i].storage.allocinfo.inlinedmask;
}
[...this.assembly.constantDecls].map((cd) => cd[1])
.sort((cda, cdb) => {
const idxa = rcg.findIndex((cgn) => cgn.invoke === cda.ivalue);
const idxb = rcg.findIndex((cgn) => cgn.invoke === cdb.ivalue);
return idxa - idxb;
})
.forEach((cdecl) => {
const decltype = this.temitter.getICPPLayoutInfo(this.temitter.getMIRType(cdecl.declaredType));
const offset = this.bemitter.constMap.get(cdecl.gkey) as number;
let optenumname: [string, string] | undefined = undefined;
if(cdecl.attributes.includes("enum")) {
optenumname = [cdecl.enclosingDecl as string, cdecl.shortname];
}
const icppdecl = new ICPPConstDecl(cdecl.gkey, optenumname, offset, cdecl.ivalue, decltype.tkey);
this.icppasm.constdecls.push(icppdecl);
this.icppasm.cbuffsize += decltype.allocinfo.inlinedatasize;
this.icppasm.cmask += decltype.allocinfo.inlinedmask;
});
this.icppasm.litdecls = this.bemitter.constlayout.slice(1)
.filter((cle) => cle.isliteral)
.map((cle) => {
return { offset: cle.offset, storage: cle.storage.allocinfo, value: cle.value };
});
const basetypes = [...this.assembly.typeMap].map((tt) => tt[1]).filter((tt) => tt.options.length === 1 && !(tt.options[0] instanceof MIRConceptType));
this.icppasm.typenames.forEach((tt) => {
const mirtype = this.temitter.getMIRType(tt);
const icpptype = this.temitter.getICPPLayoutInfo(mirtype);
this.icppasm.typedecls.push(icpptype);
if (icpptype.layout === ICPPLayoutCategory.UnionRef || icpptype.layout === ICPPLayoutCategory.UnionInline || icpptype.layout === ICPPLayoutCategory.UnionUniversal) {
const subtypes = basetypes.filter((btype) => this.assembly.subtypeOf(btype, mirtype)).map((tt) => tt.typeID).sort();
this.icppasm.subtypes.set(mirtype.typeID, new Set<MIRResolvedTypeKey>(subtypes));
}
if (this.temitter.isUniqueEntityType(mirtype) && (this.assembly.entityDecls.get(mirtype.typeID) instanceof MIRObjectEntityTypeDecl)) {
const mdecl = this.assembly.entityDecls.get(mirtype.typeID) as MIRObjectEntityTypeDecl;
let vte = this.icppasm.vtable.find((v) => v.oftype === mdecl.tkey);
if (vte === undefined) {
vte = { oftype: mdecl.tkey, vtable: [] };
this.icppasm.vtable.push(vte);
}
mdecl.vcallMap.forEach((tinv, tvcall) => {
(vte as { oftype: MIRResolvedTypeKey, vtable: { vcall: MIRVirtualMethodKey, inv: MIRInvokeKey }[] }).vtable.push({ vcall: tvcall, inv: tinv });
});
}
});
}
static generateICPPAssembly(srcCode: { fname: string, contents: string }[], assembly: MIRAssembly, istestbuild: boolean, vopts: TranspilerOptions, entrypoints: MIRInvokeKey[]): object {
const temitter = new ICPPTypeEmitter(assembly, vopts);
const bemitter = new ICPPBodyEmitter(assembly, temitter, vopts);
const icppasm = ICPPEmitter.initializeICPPAssembly(srcCode, assembly, temitter);
let icppemit = new ICPPEmitter(assembly, temitter, bemitter, icppasm);
icppemit.processAssembly(assembly, istestbuild, entrypoints);
return icppemit.icppasm.jsonEmit(assembly);
}
}
export {
ICPPParseTag, ICPPEmitter
} | the_stack |
import React, { ReactElement } from "react";
import { act, fireEvent, render, waitFor } from "@testing-library/react";
import { Dir, UserInteractionModeListener } from "@react-md/utils";
import { Slider, SliderProps } from "../Slider";
import { SliderStepOptions, SliderValue } from "../types";
import { useSlider } from "../useSlider";
interface TestProps
extends SliderStepOptions,
Pick<
SliderProps,
| "thumbProps"
| "onBlur"
| "onMouseDown"
| "onTouchStart"
| "vertical"
| "disabled"
| "getValueText"
| "discrete"
> {
defaultValue?: SliderValue;
}
function Test({
defaultValue,
disabled,
vertical,
thumbProps,
onBlur,
onMouseDown,
onTouchStart,
getValueText,
discrete,
...options
}: TestProps): ReactElement {
const [, controls] = useSlider(defaultValue, options);
return (
<Slider
{...controls}
baseId="slider"
label="Volume"
disabled={disabled}
vertical={vertical}
thumbProps={thumbProps}
discrete={discrete}
onBlur={onBlur}
onMouseDown={onMouseDown}
onTouchStart={onTouchStart}
getValueText={getValueText}
/>
);
}
describe("Slider", () => {
it("should render correctly", () => {
const { container, getByRole, rerender } = render(<Test />);
expect(container).toMatchSnapshot();
const slider = getByRole("slider");
slider.focus();
expect(container).toMatchSnapshot();
slider.blur();
expect(container).toMatchSnapshot();
rerender(<Test vertical />);
expect(container).toMatchSnapshot();
slider.focus();
expect(container).toMatchSnapshot();
slider.blur();
expect(container).toMatchSnapshot();
rerender(<Test disabled />);
expect(container).toMatchSnapshot();
rerender(<Test disabled vertical />);
expect(container).toMatchSnapshot();
});
it("should allow for custom valuetext", () => {
const { getByRole, rerender } = render(
<Test getValueText={(value) => `$${value}`} />
);
const slider = getByRole("slider");
expect(slider).toHaveAttribute("aria-valuenow", "0");
expect(slider).toHaveAttribute("aria-valuetext", "$0");
rerender(<Test getValueText={() => ""} />);
expect(slider).toHaveAttribute("aria-valuenow", "0");
expect(slider).not.toHaveAttribute("aria-valuetext");
rerender(<Test />);
expect(slider).toHaveAttribute("aria-valuenow", "0");
expect(slider).not.toHaveAttribute("aria-valuetext");
});
it("should call the prop events correctly", () => {
const onBlur = jest.fn();
const onKeyDown = jest.fn();
const onMouseDown = jest.fn();
const onTouchStart = jest.fn();
const { getByRole } = render(
<Test
thumbProps={{ onKeyDown }}
onBlur={onBlur}
onMouseDown={onMouseDown}
onTouchStart={onTouchStart}
/>
);
const slider = getByRole("slider");
fireEvent.keyDown(slider);
expect(onKeyDown).toBeCalledTimes(1);
fireEvent.mouseDown(slider, { altKey: true });
expect(onMouseDown).toBeCalledTimes(1);
fireEvent.touchStart(slider);
expect(onTouchStart).toBeCalledTimes(1);
fireEvent.blur(slider);
expect(onBlur).toBeCalledTimes(1);
});
it("should ensure the value stays within the range if it changes after initial render to prevent errors from being thrown", () => {
const props = {
defaultValue: 5,
min: 0,
max: 5,
step: 1,
};
const { rerender, getByRole } = render(<Test {...props} />);
const slider = getByRole("slider");
expect(slider).toHaveAttribute("aria-valuenow", "5");
rerender(<Test {...props} step={2} max={6} />);
expect(slider).toHaveAttribute("aria-valuenow", "6");
rerender(<Test {...props} step={3} max={6} />);
expect(slider).toHaveAttribute("aria-valuenow", "6");
rerender(<Test {...props} step={10} max={100} />);
expect(slider).toHaveAttribute("aria-valuenow", "10");
rerender(<Test {...props} step={1} min={50} max={100} />);
expect(slider).toHaveAttribute("aria-valuenow", "50");
});
it("should log an error if the slider does not have a valid label", () => {
function Test(
props: Pick<
SliderProps,
"label" | "thumbLabel" | "thumbLabelledBy" | "thumbProps"
>
): ReactElement {
const [, controls] = useSlider();
return <Slider {...props} {...controls} baseId="slider" />;
}
const error = jest.spyOn(console, "error").mockImplementation(() => {});
const { rerender } = render(<Test label="Label" />);
rerender(<Test thumbLabel="Label" />);
rerender(<Test thumbLabelledBy="some-id" />);
rerender(<Test thumbProps={{ "aria-label": "Label" }} />);
rerender(<Test thumbProps={{ "aria-labelledby": "some-id" }} />);
expect(error).not.toBeCalled();
rerender(<Test />);
expect(error).toBeCalledTimes(1);
error.mockRestore();
});
describe("keyboard behavior", () => {
it("should update the value correctly with specific keyboard keys", () => {
const { getByRole } = render(<Test />);
const slider = getByRole("slider");
expect(slider).toHaveAttribute("aria-valuenow", "0");
slider.focus();
fireEvent.keyDown(slider, { key: "ArrowRight" });
expect(slider).toHaveAttribute("aria-valuenow", "1");
fireEvent.keyDown(slider, { key: "PageUp" });
expect(slider).toHaveAttribute("aria-valuenow", "11");
fireEvent.keyDown(slider, { key: "ArrowLeft" });
expect(slider).toHaveAttribute("aria-valuenow", "10");
fireEvent.keyDown(slider, { key: "ArrowLeft" });
expect(slider).toHaveAttribute("aria-valuenow", "9");
fireEvent.keyDown(slider, { key: "PageDown" });
expect(slider).toHaveAttribute("aria-valuenow", "0");
fireEvent.keyDown(slider, { key: "End" });
expect(slider).toHaveAttribute("aria-valuenow", "100");
fireEvent.keyDown(slider, { key: "Home" });
expect(slider).toHaveAttribute("aria-valuenow", "0");
fireEvent.keyDown(slider, { key: "ArrowUp" });
expect(slider).toHaveAttribute("aria-valuenow", "1");
fireEvent.keyDown(slider, { key: "ArrowDown" });
expect(slider).toHaveAttribute("aria-valuenow", "0");
});
});
describe("drag behavior", () => {
afterEach(() => {
jest.useRealTimers();
});
it("should work correctly", () => {
jest.useFakeTimers();
const { container, getByRole } = render(<Test />);
const slider = getByRole("slider");
expect(slider).toHaveAttribute("aria-valuenow", "0");
const track =
container.querySelector<HTMLSpanElement>(".rmd-slider-track");
if (!track) {
throw new Error();
}
jest.spyOn(track, "getBoundingClientRect").mockImplementation(() => ({
x: 0,
y: 0,
height: 20,
width: 1000,
top: 0,
right: 1000,
left: 0,
bottom: 20,
toJSON: () => "",
}));
fireEvent.mouseDown(track, { clientX: 200, clientY: 0 });
expect(container).toMatchSnapshot();
expect(track.className).toContain("rmd-slider-track--animate");
expect(slider).toHaveAttribute("aria-valuenow", "20");
act(() => {
jest.runAllTimers();
});
expect(container).toMatchSnapshot();
expect(track.className).not.toContain("rmd-slider-track--animate");
fireEvent.mouseMove(window, { clientX: 500, clientY: 20 });
expect(container).toMatchSnapshot();
expect(slider).toHaveAttribute("aria-valuenow", "50");
fireEvent.mouseUp(window);
expect(container).toMatchSnapshot();
expect(track.className).toContain("rmd-slider-track--animate");
expect(slider).toHaveAttribute("aria-valuenow", "50");
fireEvent.mouseMove(window, { clientX: 200, clientY: 10 });
expect(slider).toHaveAttribute("aria-valuenow", "50");
expect(container).toMatchSnapshot();
});
it("should reverse the drag value for RTL languages", () => {
jest.useFakeTimers();
const { container, getByRole } = render(
<Dir defaultDir="rtl">
<Test />
</Dir>
);
const slider = getByRole("slider");
expect(slider).toHaveAttribute("aria-valuenow", "0");
const track =
container.querySelector<HTMLSpanElement>(".rmd-slider-track");
if (!track) {
throw new Error();
}
jest.spyOn(track, "getBoundingClientRect").mockImplementation(() => ({
x: 0,
y: 0,
height: 20,
width: 1000,
top: 0,
right: 1000,
left: 0,
bottom: 20,
toJSON: () => "",
}));
fireEvent.mouseDown(track, { clientX: 200, clientY: 0 });
expect(container).toMatchSnapshot();
expect(track.className).toContain("rmd-slider-track--animate");
expect(slider).toHaveAttribute("aria-valuenow", "80");
act(() => {
jest.runAllTimers();
});
expect(container).toMatchSnapshot();
expect(track.className).not.toContain("rmd-slider-track--animate");
fireEvent.mouseMove(window, { clientX: 500, clientY: 20 });
expect(container).toMatchSnapshot();
expect(slider).toHaveAttribute("aria-valuenow", "50");
fireEvent.mouseUp(window);
expect(container).toMatchSnapshot();
expect(track.className).toContain("rmd-slider-track--animate");
expect(slider).toHaveAttribute("aria-valuenow", "50");
fireEvent.mouseMove(window, { clientX: 200, clientY: 10 });
expect(slider).toHaveAttribute("aria-valuenow", "50");
expect(container).toMatchSnapshot();
});
});
describe("update behavior", () => {
it('should only update value value on blur or dragend when the updateOn is set to "blur"', () => {
const onChange = jest.fn();
function Test({ blur }: { blur: boolean }): ReactElement {
const [value, controls] = useSlider(0, {
onChange,
updateOn: blur ? "blur" : "change",
});
return (
<>
<span data-testid="value">{value}</span>
<Slider {...controls} baseId="slider" label="Slider" />
</>
);
}
const { getByRole, getByTestId, rerender } = render(
<Test blur={false} />
);
const value = getByTestId("value");
const slider = getByRole("slider");
expect(value.textContent).toBe("0");
expect(slider).toHaveAttribute("aria-valuenow", "0");
slider.focus();
fireEvent.keyDown(slider, { key: "ArrowRight" });
expect(onChange).not.toBeCalled();
expect(value.textContent).toBe("1");
expect(slider).toHaveAttribute("aria-valuenow", "1");
fireEvent.keyDown(slider, { key: "ArrowRight" });
expect(onChange).not.toBeCalled();
expect(value.textContent).toBe("2");
expect(slider).toHaveAttribute("aria-valuenow", "2");
slider.blur();
// it's pretty much useless to use `onChange` with updateOn === "change"
expect(onChange).not.toBeCalled();
rerender(<Test blur />);
expect(onChange).not.toBeCalled();
expect(value.textContent).toBe("2");
expect(slider).toHaveAttribute("aria-valuenow", "2");
fireEvent.keyDown(slider, { key: "ArrowRight" });
expect(onChange).not.toBeCalled();
expect(value.textContent).toBe("2");
expect(slider).toHaveAttribute("aria-valuenow", "3");
fireEvent.keyDown(slider, { key: "Home" });
expect(onChange).not.toBeCalled();
expect(value.textContent).toBe("2");
expect(slider).toHaveAttribute("aria-valuenow", "0");
fireEvent.blur(slider);
expect(onChange).toBeCalledWith(0);
expect(value.textContent).toBe("0");
expect(slider).toHaveAttribute("aria-valuenow", "0");
slider.focus();
fireEvent.keyDown(slider, { key: "ArrowRight" });
fireEvent.keyDown(slider, { key: "ArrowLeft" });
slider.blur();
// should not be called again if value hasn't changed
expect(onChange).toBeCalledTimes(1);
});
});
describe("discrete sliders", () => {
function DiscreteTest({ disabled }: { disabled?: boolean }): ReactElement {
return (
<UserInteractionModeListener>
<Test discrete disabled={disabled} />
</UserInteractionModeListener>
);
}
it("should show the toolwip when the thumb gains focus while the user interaction mode is keyboard", async () => {
const { getByRole, container } = render(<DiscreteTest />);
expect(container).toMatchSnapshot();
expect(() => getByRole("tooltip")).toThrow();
const slider = getByRole("slider");
// move into keyboard mode
fireEvent.keyDown(slider);
expect(() => getByRole("tooltip")).toThrow();
slider.focus();
const tooltip = getByRole("tooltip");
expect(container).toMatchSnapshot();
expect(tooltip.textContent).toBe("0");
fireEvent.keyDown(slider, { key: "ArrowRight" });
expect(tooltip.textContent).toBe("1");
slider.blur();
await waitFor(() => expect(() => getByRole("tooltip")).toThrow());
expect(container).toMatchSnapshot();
// move into mouse mode
fireEvent.mouseDown(window);
expect(() => getByRole("tooltip")).toThrow();
slider.focus();
expect(() => getByRole("tooltip")).toThrow();
});
it("should hide the tooltip if it becomes disabled while the tooltip is visible somehow", async () => {
const { getByRole, rerender } = render(<DiscreteTest />);
const slider = getByRole("slider");
// move into keyboard mode
fireEvent.keyDown(slider);
expect(() => getByRole("tooltip")).toThrow();
slider.focus();
expect(() => getByRole("tooltip")).not.toThrow();
rerender(<DiscreteTest disabled />);
await waitFor(() => expect(() => getByRole("tooltip")).toThrow());
});
it("should wait the animationDuration before enabling the visibility for mouse mode", () => {
jest.useFakeTimers();
const { container, getByRole } = render(<DiscreteTest />);
const track =
container.querySelector<HTMLSpanElement>(".rmd-slider-track");
if (!track) {
throw new Error();
}
jest.spyOn(track, "getBoundingClientRect").mockImplementation(() => ({
x: 0,
y: 0,
height: 20,
width: 1000,
top: 0,
right: 1000,
left: 0,
bottom: 20,
toJSON: () => "",
}));
// sanity force mouse mode
fireEvent.mouseDown(window);
fireEvent.mouseDown(track, { clientX: 200, clientY: 0 });
expect(() => getByRole("tooltip")).toThrow();
act(() => {
jest.runAllTimers();
});
expect(() => getByRole("tooltip")).not.toThrow();
jest.clearAllTimers();
jest.useRealTimers();
});
it("should not hide the tooltip if switching between keyboard to desktop mode and the track was clicked", () => {
jest.useFakeTimers();
const { container, getByRole } = render(<DiscreteTest />);
const slider = getByRole("slider");
const track =
container.querySelector<HTMLSpanElement>(".rmd-slider-track");
if (!track) {
throw new Error();
}
jest.spyOn(track, "getBoundingClientRect").mockImplementation(() => ({
x: 0,
y: 0,
height: 20,
width: 1000,
top: 0,
right: 1000,
left: 0,
bottom: 20,
toJSON: () => "",
}));
// move into keyboard mode
fireEvent.keyDown(slider);
slider.focus();
expect(() => getByRole("tooltip")).not.toThrow();
fireEvent.mouseDown(track, { clientX: 200, clientY: 0 });
expect(() => getByRole("tooltip")).not.toThrow();
act(() => {
jest.runAllTimers();
});
expect(() => getByRole("tooltip")).not.toThrow();
slider.blur();
act(() => {
jest.runAllTimers();
});
expect(() => getByRole("tooltip")).toThrow();
jest.clearAllTimers();
jest.useRealTimers();
});
});
}); | the_stack |
import { tokenizer } from "codsen-tokenizer";
import { collapse } from "string-collapse-white-space";
import { rApply } from "ranges-apply";
import { detectLang } from "detect-templating-language";
import { defaultOpts, Opts, ApplicableOpts, Res } from "./util";
import { version as v } from "../package.json";
const version: string = v;
import { Range } from "../../../scripts/common";
// return function is in single place to ensure no
// discrepancies in API when returning from multiple places
function returnHelper(
result: string,
applicableOpts: ApplicableOpts,
templatingLang: { name: null | string },
start: number
) {
/* istanbul ignore next */
if (arguments.length !== 4) {
throw new Error(
`stristri/returnHelper(): should be 3 input args but ${arguments.length} were given!`
);
}
/* istanbul ignore next */
if (typeof result !== "string") {
throw new Error("stristri/returnHelper(): first arg missing!");
}
/* istanbul ignore next */
if (typeof applicableOpts !== "object") {
throw new Error("stristri/returnHelper(): second arg missing!");
}
console.log(
`033 ${`\u001b[${33}m${`RETURN`}\u001b[${39}m`} = ${JSON.stringify(
{
result,
applicableOpts,
},
null,
4
)}`
);
return {
log: {
timeTakenInMilliseconds: Date.now() - start,
},
result,
applicableOpts,
templatingLang,
};
}
/**
* Extracts or deletes HTML, CSS, text and/or templating tags from string
*/
function stri(input: string, originalOpts?: Partial<Opts>): Res {
const start = Date.now();
console.log(
`058 ${`\u001b[${32}m${`INITIAL`}\u001b[${39}m`} ${`\u001b[${33}m${`input`}\u001b[${39}m`} = ${JSON.stringify(
input,
null,
4
)}`
);
// insurance
if (typeof input !== "string") {
throw new Error(
`stristri: [THROW_ID_01] the first input arg must be string! It was given as ${JSON.stringify(
input,
null,
4
)} (${typeof input})`
);
}
if (originalOpts && typeof originalOpts !== "object") {
throw new Error(
`stristri: [THROW_ID_02] the second input arg must be a plain object! It was given as ${JSON.stringify(
originalOpts,
null,
4
)} (${typeof originalOpts})`
);
}
const opts = {
...defaultOpts,
...originalOpts,
};
console.log(
`090 ${`\u001b[${32}m${`INITIAL`}\u001b[${39}m`} ${`\u001b[${33}m${`opts`}\u001b[${39}m`} = ${JSON.stringify(
opts,
null,
4
)}`
);
// Prepare blank applicable opts object, extract all bool keys,
// anticipate that there will be non-bool values in the future.
const applicableOpts: ApplicableOpts = {
html: false,
css: false,
text: false,
js: false,
templatingTags: false,
};
console.log(
`107 ${`\u001b[${32}m${`INITIAL`}\u001b[${39}m`} ${`\u001b[${33}m${`applicableOpts`}\u001b[${39}m`} = ${JSON.stringify(
applicableOpts,
null,
4
)}`
);
// quick ending
if (!input) {
console.log(`116 quick ending, empty input`);
returnHelper("", applicableOpts, detectLang(input), start);
}
const gatheredRanges: Range[] = [];
// comments like CSS comment
// /* some text */
// come as minimum 3 tokens,
// in case above we've got
// token type = comment (opening /*), token type = text, token type = comment (closing */)
// we need to treat the contents text tokens as either HTML or CSS, not as "text"
let withinHTMLComment = false; // used for children nodes of XML or HTML comment tags
let withinXML = false; // used for children nodes of XML or HTML comment tags
let withinCSS = false;
let withinScript = false;
tokenizer(input, {
tagCb: (token) => {
console.log(`${`\u001b[${36}m${`-`.repeat(80)}\u001b[${39}m`}`);
console.log(
`${`\u001b[${33}m${`token`}\u001b[${39}m`} = ${JSON.stringify(
token,
null,
4
)}`
);
/* istanbul ignore else */
if (token.type === "comment") {
console.log(`146 ${`\u001b[${35}m${`COMMENT TOKEN`}\u001b[${39}m`}`);
if (withinCSS) {
if (!applicableOpts.css) {
applicableOpts.css = true;
console.log(
`151 ${`\u001b[${33}m${`applicableOpts.css`}\u001b[${39}m`} = ${JSON.stringify(
applicableOpts.css,
null,
4
)}`
);
}
if (opts.css) {
gatheredRanges.push([token.start, token.end, " "]);
console.log(`160 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
}
} else {
// it's HTML comment
if (!applicableOpts.html) {
applicableOpts.html = true;
console.log(
`167 ${`\u001b[${33}m${`applicableOpts.html`}\u001b[${39}m`} = ${JSON.stringify(
applicableOpts.html,
null,
4
)}`
);
}
if (!token.closing && !withinXML && !withinHTMLComment) {
withinHTMLComment = true;
console.log(
`177 ${`\u001b[${33}m${`withinHTMLComment`}\u001b[${39}m`} = ${withinHTMLComment}`
);
} else if (token.closing && withinHTMLComment) {
withinHTMLComment = false;
console.log(
`182 ${`\u001b[${33}m${`withinHTMLComment`}\u001b[${39}m`} = ${withinHTMLComment}`
);
}
if (opts.html) {
gatheredRanges.push([token.start, token.end, " "]);
console.log(`187 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
}
}
} else if (token.type === "tag") {
console.log(`191 ${`\u001b[${35}m${`TAG TOKEN`}\u001b[${39}m`}`);
// mark applicable opts
if (!applicableOpts.html) {
applicableOpts.html = true;
console.log(
`196 ${`\u001b[${33}m${`applicableOpts.html`}\u001b[${39}m`} = ${
applicableOpts.html
}`
);
}
if (opts.html) {
gatheredRanges.push([token.start, token.end, " "]);
console.log(`203 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
}
if (token.tagName === "style" && !token.closing) {
withinCSS = true;
console.log(
`208 ${`\u001b[${33}m${`withinCSS`}\u001b[${39}m`} = ${withinCSS}`
);
} else if (
// closing CSS comment '*/' is met
withinCSS &&
token.tagName === "style" &&
token.closing
) {
withinCSS = false;
console.log(
`218 ${`\u001b[${33}m${`withinCSS`}\u001b[${39}m`} = ${withinCSS}`
);
}
if (token.tagName === "xml") {
if (!token.closing && !withinXML && !withinHTMLComment) {
withinXML = true;
console.log(
`226 ${`\u001b[${33}m${`withinXML`}\u001b[${39}m`} = ${withinXML}`
);
} else if (token.closing && withinXML) {
withinXML = false;
console.log(
`231 ${`\u001b[${33}m${`withinXML`}\u001b[${39}m`} = ${withinXML}`
);
}
}
if (token.tagName === "script" && !token.closing) {
withinScript = true;
console.log(
`239 ${`\u001b[${33}m${`withinScript`}\u001b[${39}m`} = ${withinScript}`
);
} else if (
withinScript &&
token.tagName === "script" &&
token.closing
) {
withinScript = false;
console.log(
`248 ${`\u001b[${33}m${`withinScript`}\u001b[${39}m`} = ${withinScript}`
);
}
} else if (["at", "rule"].includes(token.type)) {
console.log(`252 ${`\u001b[${35}m${`AT/RULE TOKEN`}\u001b[${39}m`}`);
// mark applicable opts
if (!applicableOpts.css) {
applicableOpts.css = true;
console.log(
`257 ${`\u001b[${33}m${`applicableOpts.css`}\u001b[${39}m`} = ${
applicableOpts.css
}`
);
}
if (opts.css) {
gatheredRanges.push([token.start, token.end, " "]);
console.log(`264 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
}
} else if (token.type === "text") {
console.log(`267 ${`\u001b[${35}m${`TEXT TOKEN`}\u001b[${39}m`}`);
// mark applicable opts
if (withinScript) {
applicableOpts.js = true;
console.log(
`272 ${`\u001b[${33}m${`applicableOpts.js`}\u001b[${39}m`} = ${
applicableOpts.js
}`
);
} else if (
!withinCSS &&
!withinHTMLComment &&
!withinXML &&
!applicableOpts.text &&
token.value.trim()
) {
applicableOpts.text = true;
console.log(
`285 ${`\u001b[${33}m${`applicableOpts.text`}\u001b[${39}m`} = ${
applicableOpts.text
}`
);
}
if (
(withinCSS && opts.css) ||
(withinScript && opts.js) ||
(withinHTMLComment && opts.html) ||
(!withinCSS &&
!withinHTMLComment &&
!withinXML &&
!withinScript &&
opts.text)
) {
if (withinScript) {
gatheredRanges.push([token.start, token.end]);
console.log(`302 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
} else if (token.value.includes("\n")) {
gatheredRanges.push([token.start, token.end, "\n"]);
console.log(`305 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
} else {
gatheredRanges.push([token.start, token.end, " "]);
console.log(`308 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
}
}
} else if (token.type === "esp") {
console.log(`312 ${`\u001b[${35}m${`ESP TOKEN`}\u001b[${39}m`}`);
// mark applicable opts
if (!applicableOpts.templatingTags) {
applicableOpts.templatingTags = true;
console.log(
`317 ${`\u001b[${33}m${`applicableOpts.templatingTags`}\u001b[${39}m`} = ${JSON.stringify(
applicableOpts.templatingTags,
null,
4
)}`
);
}
if (opts.templatingTags) {
gatheredRanges.push([token.start, token.end, " "]);
console.log(`326 ${`\u001b[${32}m${`PUSH`}\u001b[${39}m`}`);
}
}
console.log(`${`\u001b[${90}m${`----------------------`}\u001b[${39}m`}`);
console.log(
`${`\u001b[${90}m${`withinScript = ${withinScript}`}\u001b[${39}m`}`
);
},
reportProgressFunc: opts.reportProgressFunc,
reportProgressFuncFrom: opts.reportProgressFuncFrom,
reportProgressFuncTo: opts.reportProgressFuncTo * 0.95, // leave the last 5% for collapsing etc.
});
console.log(
`341 ${`\u001b[${32}m${`END`}\u001b[${39}m`} ${`\u001b[${33}m${`gatheredRanges`}\u001b[${39}m`} = ${JSON.stringify(
gatheredRanges,
null,
4
)}`
);
return returnHelper(
collapse(rApply(input, gatheredRanges), {
trimLines: true,
removeEmptyLines: true,
limitConsecutiveEmptyLinesTo: 1,
}).result,
applicableOpts,
detectLang(input),
start
);
}
export { stri, defaultOpts as defaults, version }; | the_stack |
import { Component, ViewChild } from '@angular/core';
import { NavController, NavParams, ModalController, PopoverController, Events } from 'ionic-angular';
//Components
import { OpenLoggerLoggerComponent } from '../../../components/logger/openlogger/openlogger-logger.component';
import { GenPopover } from '../../../components/gen-popover/gen-popover.component';
import { PinoutPopover } from '../../../components/pinout-popover/pinout-popover.component';
import { MathPopoverComponent, MathPassData, MathOutput } from '../../../components/math-popover/math-popover.component';
import { CursorPopoverComponent, CursorPassData, CursorChannel, CursorSelection } from '../../../components/cursor-popover/cursor-popover.component';
import { DigitalIoComponent } from '../../../components/digital-io/digital-io.component';
import { FgenComponent } from '../../../components/function-gen/function-gen.component';
import { LoggerChartComponent } from '../../../components/logger-chart/logger-chart.component';
import { DcSupplyComponent } from '../../../components/dc-supply/dc-supply.component';
import { LoggerTimelineComponent } from '../../../components/logger-timeline/logger-timeline.component';
//Pages
import { FileBrowserPage } from '../../file-browser/file-browser';
//Pipes
import { UnitFormatPipe } from '../../../pipes/unit-format.pipe';
//Services
import { LoggerPlotService } from '../../../services/logger-plot/logger-plot.service';
import { TooltipService } from '../../../services/tooltip/tooltip.service';
import { DeviceManagerService, DeviceService } from 'dip-angular2/services';
import { LoadingService } from '../../../services/loading/loading.service';
import { ToastService } from '../../../services/toast/toast.service';
declare var mathFunctions: any;
@Component({
templateUrl: "openlogger-logger.html"
})
export class OpenLoggerLoggerPage {
@ViewChild('loggerComponent') loggerComponent: OpenLoggerLoggerComponent;
@ViewChild('chart') loggerChart: LoggerChartComponent;
@ViewChild('timeline') timeline: LoggerTimelineComponent;
@ViewChild('gpioComponent') gpioComponent: DigitalIoComponent;
@ViewChild('fgenComponent') fGenComponent: FgenComponent;
@ViewChild('dcComponent') dcComponent: DcSupplyComponent;
private dismissCallback: () => void;
private unitFormatPipeInstance: UnitFormatPipe;
private selectedMathInfo: MathOutput[] = [];
private cursorInfo: CursorSelection;
private isRoot: boolean = false;
public activeDevice: DeviceService;
constructor(
private navCtrl: NavController,
private navParams: NavParams,
private loggerPlotService: LoggerPlotService,
private modalCtrl: ModalController,
private popoverCtrl: PopoverController,
public tooltipService: TooltipService,
private events: Events,
private deviceManagerService: DeviceManagerService,
private loadingService: LoadingService,
private toastService: ToastService
) {
this.dismissCallback = this.navParams.get('onLoggerDismiss');
this.isRoot = this.navParams.get('isRoot') || this.isRoot;
this.unitFormatPipeInstance = new UnitFormatPipe();
this.activeDevice = this.deviceManagerService.getActiveDevice();
this.readCurrentGpioStates()
.then((data) => {
console.log(data);
})
.catch((err) => {
console.log(err);
});
}
ngOnInit() {
this.cursorInfo = {
currentType: 'disabled',
currentChannels: {
c1: {
instrument: 'daq',
channel: 1
},
c2: {
instrument: 'daq',
channel: 1
}
}
};
this.getAwgStatus().then(() => this.getVoltages());
let toggle = this.fGenComponent.togglePromise.bind(this.fGenComponent);
this.fGenComponent.togglePower = (event, index) => {
if (this.loggerComponent.running) {
this.loggerComponent.messageQueue.push(() => toggle(event, index).catch(e => console.error(e)));
} else {
toggle(event, index).catch(e => console.error(e));
}
}
}
getAwgStatus(): Promise<any> {
return new Promise((resolve, reject) => {
let chans = [];
for (let i = 0; i < this.activeDevice.instruments.awg.numChans; i++) {
chans.push(i + 1);
}
this.activeDevice.instruments.awg.getCurrentState(chans).subscribe(
(data) => {
console.log(data);
this.fGenComponent.initializeFromGetStatus(data);
resolve(data);
},
(err) => {
console.log('error getting awg status');
console.log(err);
reject(err);
},
() => { }
);
});
}
getVoltages(): Promise<any> {
let chans = [];
for (let i = 0; i < this.activeDevice.instruments.dc.numChans; i++) {
chans.push(i + 1);
}
return new Promise((resolve, reject) => {
this.activeDevice.instruments.dc.getVoltages(chans).subscribe(
(data) => {
this.dcComponent.initializeFromGetStatus(data);
resolve(data);
},
(err) => {
console.log(err);
reject(err);
},
() => {
//console.log('getVoltage Done');
}
);
});
}
snapViewToFront() {
this.loggerComponent.viewMoved = false;
this.loggerComponent.setViewToEdge();
this.loggerPlotService.setViewToFront();
}
done() {
this.navParams.get('onLoggerDismiss')();
this.navCtrl.pop();
}
ngOnDestroy() {
this.loggerPlotService.resetService();
}
setFirstAvailableSeries() {
for (let idx = 0; idx < this.loggerComponent.selectedChannels.length; idx++) {
const chanIsActive = this.loggerComponent.selectedChannels[idx];
if (chanIsActive) return this.loggerPlotService.setActiveSeries(idx+1);
}
}
runLogger() {
let { tpdIndex, vpdIndices } = this.loggerPlotService;
this.loggerChart.loggerChart.digilentChart == undefined;
this.loggerChart.loggerChart.createChart();
this.loggerChart.loggerChart.chartLoad.emit();
this.timeline.loggerTimeline.chartLoad.emit();
// NOTE(andrew): remove this once a better solution to updating chart axis is found
this.loggerPlotService.setValPerDivAndUpdate('x', 1, this.loggerPlotService.tpdArray[tpdIndex]);
vpdIndices.forEach((vpdIndex, i) => {
this.loggerPlotService.setValPerDivAndUpdate('y', i + 1, this.loggerPlotService.vpdArray[vpdIndex]);
});
this.setFirstAvailableSeries();
this.loggerComponent.startLogger();
}
stopLogger() {
this.loggerComponent.stopLogger();
}
openFileBrowser() {
let modal = this.modalCtrl.create(FileBrowserPage, {hideExportButton: true});
modal.present();
}
presentExportPop(event) {
let popover = this.popoverCtrl.create(GenPopover, {
dataArray: ['Export CSV', 'Export PNG']
});
popover.onWillDismiss((data) => {
if (data == null) { return; }
if (data.option === 'Export CSV') {
this.loggerComponent.exportCsv('LoggerData');
}
else if (data.option === 'Export PNG') {
this.loggerComponent.exportCanvasAsPng();
}
});
popover.present({
ev: event
});
}
openDevicePinout(event) {
let popover = this.popoverCtrl.create(PinoutPopover, undefined, {
cssClass: 'pinoutPopover'
});
popover.present();
}
openMathPopover(event) {
let passData: MathPassData = {
chart: this.loggerPlotService.chart,
availableChans: [],
selectedChan: {
instrument: 'Analog',
channel: 1,
seriesOffset: 0
},
addedInfo: []
};
for (let i = 0; i < this.loggerComponent.daqChans.length; i++) {
if (this.loggerComponent.dataContainers[i].data.length > 1) {
passData.availableChans.push({
instrument: 'Analog',
channel: i + 1,
seriesOffset: i
});
}
}
let popover = this.popoverCtrl.create(MathPopoverComponent, {
passData: passData
});
popover.onWillDismiss(() => {
buttonSubjRef.unsubscribe();
});
popover.present({
ev: event
});
let buttonSubjRef = popover.instance.buttonSubject.subscribe(
(data: MathOutput) => {
console.log(data);
this.addMathInfo(data);
},
(err) => { },
() => { }
);
}
openCursorModal(event) {
let availableChannels: CursorChannel[] = [];
for (let i = 0; i < this.loggerComponent.daqChans.length; i++) {
if (this.loggerComponent.dataContainers[i].data.length > 1) {
availableChannels.push({
instrument: 'analog',
channel: i + 1
});
}
}
let passData: CursorPassData = {
availableChannels: availableChannels,
currentChannels: this.cursorInfo.currentChannels,
currentType: this.cursorInfo.currentType
}
let popover = this.popoverCtrl.create(CursorPopoverComponent, {
passData: passData
});
popover.onWillDismiss(() => {
buttonSubjRef.unsubscribe();
});
popover.present({
ev: event
});
let buttonSubjRef = popover.instance.cursorSelection.subscribe(
(data: CursorSelection) => {
console.log(data);
this.handleCursors(data);
},
(err) => { },
() => { }
);
}
removeCursors() {
let cursors = this.loggerPlotService.chart.getCursors();
let length = cursors.length;
for (let i = 0, j = 0; i < length; i++) {
if (cursors[j].name !== 'triggerLine') {
//cursor array shifts itself so always remove first entry in array
this.loggerPlotService.chart.removeCursor(cursors[j]);
}
else {
j++;
}
}
this.loggerPlotService.cursorPositions = [{ x: null, y: null }, { x: null, y: null }];
}
handleCursors(newCursorData: CursorSelection) {
this.cursorInfo = newCursorData;
this.removeCursors();
if (newCursorData.currentType === 'time') {
for (let i = 0; i < 2; i++) {
let seriesIndex;
let cursorNum = i === 0 ? newCursorData.currentChannels.c1 : newCursorData.currentChannels.c2;
seriesIndex = cursorNum.channel - 1;
let series = this.loggerPlotService.chart.getData();
let color = series[seriesIndex].color
let options = {
name: 'cursor' + (i + 1),
mode: 'x',
lineWidth: 2,
color: color,
snapToPlot: seriesIndex,
showIntersections: false,
showLabel: false,
symbol: 'none',
drawAnchor: true,
position: {
relativeX: 0.25 + i * 0.5,
relativeY: 0
},
dashes: 10 + 10 * i
}
this.loggerPlotService.chart.addCursor(options);
}
}
else if (newCursorData.currentType === 'track') {
for (let i = 0; i < 2; i++) {
let seriesIndex;
let cursorNum = i === 0 ? newCursorData.currentChannels.c1 : newCursorData.currentChannels.c2;
seriesIndex = cursorNum.channel - 1;
let series = this.loggerPlotService.chart.getData();
let color = series[seriesIndex].color
let options = {
name: 'cursor' + (i + 1),
mode: 'xy',
lineWidth: 2,
color: color,
showIntersections: false,
showLabel: false,
symbol: 'none',
drawAnchor: true,
snapToPlot: seriesIndex,
position: {
relativeX: 0.25 + i * 0.5,
relativeY: 0.25 + i * 0.5
},
dashes: 10 + 10 * i
}
this.loggerPlotService.chart.addCursor(options);
}
}
else if (newCursorData.currentType === 'voltage') {
for (let i = 0; i < 2; i++) {
let seriesIndex;
let cursorNum = i === 0 ? newCursorData.currentChannels.c1 : newCursorData.currentChannels.c2;
seriesIndex = cursorNum.channel - 1;
let series = this.loggerPlotService.chart.getData();
let color = series[seriesIndex].color
let options = {
name: 'cursor' + (i + 1),
mode: 'y',
lineWidth: 2,
color: color,
showIntersections: false,
showLabel: false,
symbol: 'none',
drawAnchor: true,
position: {
relativeX: 0.25 + i * 0.5,
relativeY: 0.25 + i * 0.5
},
dashes: 10 + 10 * i
}
this.loggerPlotService.chart.addCursor(options);
}
}
}
getCursorInfo(cursorInfo: string) {
if (cursorInfo === 'xDelta') {
let result = this.unitFormatPipeInstance.transform(Math.abs(this.loggerPlotService.cursorPositions[1].x - this.loggerPlotService.cursorPositions[0].x), 's');
return result;
}
else if (cursorInfo === 'yDelta') {
let result = this.unitFormatPipeInstance.transform(Math.abs(this.loggerPlotService.cursorPositions[1].y - this.loggerPlotService.cursorPositions[0].y), 'V');
return result;
}
else if (cursorInfo === 'xFreq') {
if (this.loggerPlotService.cursorPositions[1].x === this.loggerPlotService.cursorPositions[0].x) { return 'Inf' };
let result = this.unitFormatPipeInstance.transform((1 / Math.abs(this.loggerPlotService.cursorPositions[1].x - this.loggerPlotService.cursorPositions[0].x)), 'Hz');
return result;
}
else if (cursorInfo === 'cursorPosition0' || cursorInfo === 'cursorPosition1') {
let index = cursorInfo.slice(-1);
if (this.loggerPlotService.cursorPositions[index].x !== undefined) {
let xResult = this.unitFormatPipeInstance.transform(this.loggerPlotService.cursorPositions[index].x, 's');
let yResult = this.unitFormatPipeInstance.transform(this.loggerPlotService.cursorPositions[index].y, 'V');
return xResult + ' (' + yResult + ')';
}
else {
let yResult = this.unitFormatPipeInstance.transform(this.loggerPlotService.cursorPositions[index].y, 'V');
return yResult;
}
}
}
addMathInfo(mathOutput: MathOutput) {
for (let i = 0; i < this.selectedMathInfo.length; i++) {
if (this.selectedMathInfo[i].mathInfo === mathOutput.mathInfo && this.selectedMathInfo[i].mathChannel.seriesOffset === mathOutput.mathChannel.seriesOffset) {
this.selectedMathInfo.splice(i, 1);
return;
}
}
if (this.selectedMathInfo.length === 4) {
this.selectedMathInfo.shift();
}
this.selectedMathInfo.push(mathOutput);
this.updateMath();
}
updateMath() {
let extremes = this.loggerPlotService.chart.getAxes().xaxis;
let chartMin = extremes.min;
let chartMax = extremes.max;
for (let i = 0; i < this.selectedMathInfo.length; i++) {
if (this.loggerComponent.dataContainers[this.selectedMathInfo[i].mathChannel.seriesOffset].data.length < 2) {
this.selectedMathInfo[i].value = '----';
continue;
}
let seriesNum = this.selectedMathInfo[i].mathChannel.seriesOffset;
let series = this.loggerPlotService.chart.getData();
let minIndex = Math.round((chartMin - series[seriesNum].data[0][0]) / (series[seriesNum].data[1][0] - series[seriesNum].data[0][0]));
let maxIndex = Math.round((chartMax - series[seriesNum].data[0][0]) / (series[seriesNum].data[1][0] - series[seriesNum].data[0][0]));
if (minIndex < 0) {
minIndex = 0;
}
if (minIndex > series[seriesNum].data.length) {
minIndex = series[seriesNum].data.length - 1;
}
if (maxIndex < 0) {
maxIndex = 0;
}
if (maxIndex > series[seriesNum].data.length) {
maxIndex = series[seriesNum].data.length - 1;
}
this.selectedMathInfo[i].value = this.updateMathByName(this.selectedMathInfo[i], maxIndex, minIndex);
}
}
updateMathByName(selectedMathInfoObj: MathOutput, maxIndex: number, minIndex: number) {
switch (selectedMathInfoObj.mathInfo) {
case 'Frequency':
return this.unitFormatPipeInstance.transform(mathFunctions.getFrequency(this.loggerPlotService.chart, selectedMathInfoObj.mathChannel.seriesOffset, minIndex, maxIndex), 'Hz');
case 'Period':
return this.unitFormatPipeInstance.transform(mathFunctions.getPeriod(this.loggerPlotService.chart, selectedMathInfoObj.mathChannel.seriesOffset, minIndex, maxIndex), 's');
case 'Amplitude':
return this.unitFormatPipeInstance.transform(mathFunctions.getAmplitude(this.loggerPlotService.chart, selectedMathInfoObj.mathChannel.seriesOffset, minIndex, maxIndex), 'V');
case 'Peak to Peak':
return this.unitFormatPipeInstance.transform(mathFunctions.getPeakToPeak(this.loggerPlotService.chart, selectedMathInfoObj.mathChannel.seriesOffset, minIndex, maxIndex), 'Vpp');
case 'Maximum':
return this.unitFormatPipeInstance.transform(mathFunctions.getMax(this.loggerPlotService.chart, selectedMathInfoObj.mathChannel.seriesOffset, minIndex, maxIndex), 'V');
case 'Minimum':
return this.unitFormatPipeInstance.transform(mathFunctions.getMin(this.loggerPlotService.chart, selectedMathInfoObj.mathChannel.seriesOffset, minIndex, maxIndex), 'V');
case 'Mean':
return this.unitFormatPipeInstance.transform(mathFunctions.getMean(this.loggerPlotService.chart, selectedMathInfoObj.mathChannel.seriesOffset, minIndex, maxIndex), 'V');
case 'RMS':
return this.unitFormatPipeInstance.transform(mathFunctions.getRMS(this.loggerPlotService.chart, selectedMathInfoObj.mathChannel.seriesOffset, minIndex, maxIndex), 'V');
default:
return 'default'
}
}
readCurrentGpioStates(): Promise<any> {
return new Promise((resolve, reject) => {
let chanArray = [];
for (let i = 0; i < this.activeDevice.instruments.gpio.numChans; i++) {
chanArray.push(i);
}
this.activeDevice.instruments.gpio.read(chanArray).subscribe(
(data) => {
console.log(data);
resolve(data);
},
(err) => {
console.log(err);
if (err.gpio) {
let setToInputChanArray = [];
let inputStringArray = [];
for (let channel in err.gpio) {
for (let command in err.gpio[channel]) {
if (err.gpio[channel][command].statusCode === 1073741826 && err.gpio[channel][command].direction === 'tristate') {
setToInputChanArray.push(parseInt(channel));
inputStringArray.push('input');
}
else if (err.gpio[channel][command].statusCode === 1073741826 && err.gpio[channel][command].direction === 'output') {
this.gpioComponent.gpioVals[parseInt(channel) - 1] = err.gpio[channel][command].value !== 0;
this.gpioComponent.gpioDirections[parseInt(channel) - 1] = true;
}
}
}
if (setToInputChanArray.length > 0) {
this.activeDevice.instruments.gpio.setParameters(setToInputChanArray, inputStringArray).subscribe(
(data) => {
console.log(data);
resolve(data);
},
(err) => {
console.log(err);
reject(err);
},
() => { }
);
}
else {
resolve(err);
}
}
else {
reject(err);
}
},
() => { }
);
});
}
resetInstruments() {
let loading = this.loadingService.displayLoading('Resetting Instruments...');
this.activeDevice.resetInstruments().subscribe(
(data) => {
setTimeout(() => {
this.loggerComponent.getCurrentState(true)
.then((data) => {
return this.getAwgStatus();
})
.then((data) => {
return this.getVoltages();
})
// TODO: uncomment when gpio is implemented
.then((data) => {
this.gpioComponent.gpioDirections.forEach((val, index, array) => {
this.gpioComponent.gpioDirections[index] = false;
this.gpioComponent.gpioVals[index] = false;
});
return this.setGpioDirection('input');
})
.then((data) => {
loading.dismiss();
})
.catch((err) => {
console.log(err);
loading.dismiss();
});
}, data.device[0].wait);
},
(err) => {
loading.dismiss();
this.toastService.createToast('deviceResetError');
},
() => { }
);
}
setGpioDirection(direction: 'input' | 'output'): Promise<any> {
return new Promise((resolve, reject) => {
let chanArray = [];
let valArray = [];
for (let i = 0; i < this.activeDevice.instruments.gpio.numChans; i++) {
chanArray.push(i + 1);
valArray.push(direction);
}
this.activeDevice.instruments.gpio.setParameters(chanArray, valArray).subscribe(
(data) => {
resolve(data);
},
(err) => {
console.log(err);
reject(err);
},
() => { }
);
});
}
public fgenTutorialFinished(event) {
}
} | the_stack |
type ColumnType = Date|number|string;
enum ColumnTypeName {
DATE,
NUMBER,
STRING,
}
interface Column {
name: string;
type: ColumnTypeName;
}
/**
* Mode definition for which items, out of all items that are capable
* of showing details, actually show those details.
*/
enum InlineDetailsDisplayMode {
NONE, // Don't show any inline details elements
SINGLE_SELECT, // Show details only when a single item is selected
MULTIPLE_SELECT, // Show details for all selected items
ALL // Show details for all items
}
// TODO: the current behavior of ALL does not show all of the details when
// the page first renders, but only displays the details when the
// selection state for an item changes. We might want to change this
// behavior so that it figures out in advance that it should show
// all the details.
/** Fields that can be passed to the ItemListRow constructor. */
interface ItemListRowParameters {
columns: ColumnType[];
createDetailsElement?: () => HTMLElement;
icon?: string;
selected?: boolean;
}
/**
* Object representing a row in the item list
*/
class ItemListRow {
public selected: boolean;
public columns: ColumnType[];
public canShowDetails: boolean;
public showInlineDetails = false;
private _createDetailsElement: (() => HTMLElement) | undefined;
private _detailsElement: HTMLElement;
private _icon: string;
constructor(
{columns, icon, selected, createDetailsElement}: ItemListRowParameters) {
this.columns = columns;
this.selected = selected || false;
this.canShowDetails = (!!createDetailsElement);
this._createDetailsElement = createDetailsElement;
this._icon = icon || '';
}
/**
* If the given icon is a link, its src attribute should be set to that link,
* and the icon attribute should be empty. If instead it's an icon name,
* these two attributes should be reversed.
*/
get icon() { return this._hasLinkIcon() ? '' : this._icon; }
get src() { return this._hasLinkIcon() ? this._icon : ''; }
/**
* Updates our showInlineDetails flag after a selection change.
* If we are showing details for the first time for this row,
* create the details element and add it to the DOM.
*/
_updateInlineDetails(
inlineDetailsMode: InlineDetailsDisplayMode,
multipleSelected: boolean, rowDetailsElement: HTMLElement) {
const oldShowInlineDetails = this.showInlineDetails;
if (!this.canShowDetails) {
// If we don't know how to dislay details element, then we never do
this.showInlineDetails = false;
} else if (inlineDetailsMode === InlineDetailsDisplayMode.NONE) {
this.showInlineDetails = false;
} else if (inlineDetailsMode === InlineDetailsDisplayMode.ALL) {
this.showInlineDetails = true;
} else if (!this.selected) {
this.showInlineDetails = false;
} else if (!multipleSelected) {
this.showInlineDetails = true;
} else if (inlineDetailsMode === InlineDetailsDisplayMode.MULTIPLE_SELECT) {
this.showInlineDetails = true;
} else {
// Assume SINGLE_SELECT, but we know multiple items are selected
this.showInlineDetails = false;
}
if (this.showInlineDetails) {
if (!this._detailsElement) {
this._addDetailsElement(rowDetailsElement);
} else if (!oldShowInlineDetails) {
const detailsElementAsAny = this._detailsElement as any;
if (detailsElementAsAny.show) {
detailsElementAsAny.show();
}
}
}
}
// Create and add the details element for this item when we first display it.
private _addDetailsElement(rowDetailsElement: HTMLElement) {
if (!this._createDetailsElement) {
return;
}
// The list can get reused when we switch to display a different directory,
// so we need to clear potential old details.
Utils.deleteAllChildren(rowDetailsElement);
// Create and add the new details element
this._detailsElement = this._createDetailsElement();
rowDetailsElement.appendChild(this._detailsElement);
}
private _hasLinkIcon() {
return this._icon.startsWith('http://') || this._icon.startsWith('https://');
}
}
/**
* CustomEvent that gets dispatched when an item is clicked or double clicked
*/
class ItemClickEvent extends CustomEvent<any> {
detail: {
index: number;
};
}
/**
* Multi-column list element.
* This element takes a list of column names, and a list of row objects,
* each containing values for each of the columns, an icon name, and a selected
* property. The items are displayed in a table form. Clicking an item selects
* it and unselects all other items. Clicking the checkbox next to an item
* allows for multi-selection. Shift and ctrl keys can also be used to select
* multiple items.
* Double clicking an item fires an 'ItemClickEvent' event with this item's index.
* Selecting an item by single clicking it changes the selectedIndices
* property. This also notifies the host, which can listen to the
* selected-indices-changed event.
* If the "hide-header" attribute is specified, the header is hidden.
* If the "disable-selection" attribute is specified, the checkboxes are
* hidden, and clicking items does not select them.
*/
@Polymer.decorators.customElement('item-list')
class ItemListElement extends Polymer.Element {
/**
* List of data rows, each implementing the row interface
*/
@Polymer.decorators.property({type: Array})
public rows: ItemListRow[] = [];
/**
* List of string data columns names
*/
@Polymer.decorators.property({type: Array})
public columns: Column[] = [];
/**
* Whether to hide the header row
*/
@Polymer.decorators.property({type: Boolean})
public hideHeader = false;
/**
* Whether to disable item selection
*/
@Polymer.decorators.property({type: Boolean})
public disableSelection = false;
/**
* Whether to disable multi-selection
*/
@Polymer.decorators.property({type: Boolean})
public noMultiselect = false;
/**
* The list of currently selected indices
*/
@Polymer.decorators.property({
computed: '_computeSelectedIndices(rows.*)', notify: true, type: Array})
public selectedIndices: number[] = [];
/**
* Display mode for inline details
*/
@Polymer.decorators.property({type: Object})
public inlineDetailsMode = InlineDetailsDisplayMode.NONE;
@Polymer.decorators.property({type: Boolean})
_showFilterBox = false;
@Polymer.decorators.property({
computed: '_computeIsAllSelected(selectedIndices)', type: Boolean})
_isAllSelected: boolean;
@Polymer.decorators.property({
computed: '_computeHideCheckboxes(disableSelection, noMultiselect)', type: Boolean})
_hideCheckboxes: boolean;
_filterString: string;
private _currentSort = {
asc: true, // ascending or descending
column: -1, // index of current sort column
};
private _lastSelectedIndex = -1;
ready() {
super.ready();
// Add box-shadow to header container on scroll
const container = this.$.listContainer as HTMLDivElement;
const headerContainer = this.$.headerContainer as HTMLDivElement;
container.addEventListener('scroll', () => {
const yOffset = Math.min(container.scrollTop / 20, 5);
const shadow = '0px ' + yOffset + 'px 10px -5px #ccc';
headerContainer.style.boxShadow = shadow;
});
// Initial sort
this._sortBy(0);
}
resetFilter() {
this._filterString = '';
}
_formatColumnValue(value: ColumnType, i: number, columns: Column[]): string {
if (columns[i]) {
if (columns[i].type === ColumnTypeName.DATE) {
return (value as Date).toLocaleString();
} else {
return value.toString();
}
} else {
return '';
}
}
_columnButtonClicked(e: any) {
this._sortBy(e.model.itemsIndex);
}
_sortBy(column: number) {
// If sort is requested on the current sort column, reverse the sort order.
// Otherwise, set the current sort column to that.
if (this._currentSort.column === column) {
this._currentSort.asc = !this._currentSort.asc;
} else {
this._currentSort = {
asc: true,
column,
};
}
this.$.list.sort = (a: ItemListRow, b: ItemListRow) => {
// Bail out of sort if no columns have been set yet.
if (!this.columns.length) {
return;
}
if (a.columns[column] === b.columns[column]) {
return 0;
}
let compResult = -1;
if (this.columns[column].type === ColumnTypeName.STRING) {
if ((a.columns[column] as string).toLowerCase() >
(b.columns[column] as string).toLowerCase()) {
compResult = 1;
}
} else if (this.columns[column].type === ColumnTypeName.NUMBER) {
if ((a.columns[column] as number) > (b.columns[column] as number)) {
compResult = 1;
}
} else if (this.columns[column].type === ColumnTypeName.DATE) {
if ((a.columns[column] as Date) > (b.columns[column] as Date)) {
compResult = 1;
}
}
return this._currentSort.asc ? compResult : compResult * -1;
};
this._updateSortIcons();
}
@Polymer.decorators.observe(['rows', 'columns'])
_updateSortIcons() {
// Make sure all elements have rendered.
Polymer.dom.flush();
const iconEls = this.$.header.querySelectorAll('.sort-icon');
if (iconEls.length && this._currentSort.column > -1) {
iconEls.forEach((el: HTMLElement) => el.hidden = true);
iconEls[this._currentSort.column].hidden = false;
iconEls[this._currentSort.column].setAttribute('icon',
this._currentSort.asc ? 'arrow-upward' : 'arrow-downward');
}
}
_toggleFilter() {
this._showFilterBox = !this._showFilterBox;
// If the filter box is now visible, focus it.
// If not, reset the filter to go back to showing the full list.
if (this._showFilterBox) {
this.$.filterBox.focus();
} else {
this._filterString = '';
}
}
_computeFilter(filterString: string) {
if (!filterString) {
// set filter to null to disable filtering
return null;
} else {
// return a filter function for the current search string
filterString = filterString.toLowerCase();
return (item: ItemListRow) => {
const strVal = this._formatColumnValue(item.columns[0], 0, this.columns);
return strVal.toLowerCase().indexOf(filterString) > -1;
};
}
}
/**
* Returns value for the computed property selectedIndices, which is the list
* of indices of the currently selected items.
*/
_computeSelectedIndices() {
const selected: number[] = [];
this.rows.forEach((row, i) => {
if (row.selected) {
selected.push(i);
}
});
return selected;
}
/**
* Returns the value for the computed property isAllSelected, which is whether
* all items in the list are selected.
*/
_computeIsAllSelected() {
return this.rows.length > 0 && this.rows.length === this.selectedIndices.length;
}
/**
* Returns the value for the computed property hideCheckboxes.
*/
_computeHideCheckboxes(disableSelection: boolean, noMultiselect: boolean) {
return disableSelection || noMultiselect;
}
/**
* Selects an item in the list using its display index. Note the item must be
* visible in the rendered list.
* @param index display index of item to select
* @param single true if we are not being called in a bulk operation
*/
_selectItemByDisplayIndex(index: number, single?: boolean) {
const realIndex = this._displayIndexToRealIndex(index);
this._selectItemByRealIndex(realIndex, single);
}
/**
* Unselects an item in the list using its display index. Note the item must be
* visible in the rendered list.
* @param index display index of item to unselect
* @param single true if we are not being called in a bulk operation
*/
_unselectItemByDisplayIndex(index: number, single?: boolean) {
const realIndex = this._displayIndexToRealIndex(index);
this._unselectItemByRealIndex(realIndex, single);
}
/**
* Selects an item in the list using its real index.
*/
_selectItemByRealIndex(realIndex: number, single?: boolean) {
if (this.rows[realIndex].selected && !single) {
return; // Avoid lots of useless work when no change.
}
this.set('rows.' + realIndex + '.selected', true);
this._updateItemSelection(realIndex, true);
}
/**
* Unselects an item in the list using its real index.
*/
_unselectItemByRealIndex(realIndex: number, single?: boolean) {
if (!this.rows[realIndex].selected && !single) {
return; // Avoid lots of useless work when no change.
}
this.set('rows.' + realIndex + '.selected', false);
this._updateItemSelection(realIndex, false);
}
/**
* Updates the show-details flag for a row after selection change.
*/
_updateItemSelection(index: number, newValue: boolean) {
const multipleSelected = this.selectedIndices.length > 1;
this._updateInlineDetailsForRow(index, multipleSelected);
const previousSelectedCount =
this.selectedIndices.length + (newValue ? -1 : 1);
const previousMultipleSelected = previousSelectedCount > 1;
if (this.inlineDetailsMode === InlineDetailsDisplayMode.SINGLE_SELECT &&
multipleSelected !== previousMultipleSelected) {
/** If we are in SINGLE_SELECT mode and we have changed from having one
* item selected to many or vice-versa, we need to update all the other
* selected items.
*/
for (let i = 0; i < this.rows.length; i++) {
if (i !== index) {
this._updateInlineDetailsForRow(i, multipleSelected);
}
}
}
}
/**
* Updates the inline details for one row after a selection change.
*/
_updateInlineDetailsForRow(index: number, multipleSelected: boolean) {
const rowDetailsElement = this._getRowDetailsContainer(index);
this.rows[index]._updateInlineDetails(
this.inlineDetailsMode, multipleSelected, rowDetailsElement);
this.notifyPath('rows.' + index + '.showInlineDetails',
this.rows[index].showInlineDetails);
}
/**
* Selects all displayed items in the list.
*/
_selectAllDisplayedItems() {
const allElements = this.$.listContainer.querySelectorAll('paper-item') as NodeList;
allElements.forEach((_, i) => this._selectItemByDisplayIndex(i));
}
/**
* Unselects all displayed items in the list.
*/
_unselectAllDisplayedItems() {
const allElements = this.$.listContainer.querySelectorAll('paper-item') as NodeList;
allElements.forEach((_, i) => this._unselectItemByDisplayIndex(i));
}
/**
* Selects all items in the list.
*/
_selectAll() {
for (let i = 0; i < this.rows.length; ++i) {
this._selectItemByRealIndex(i);
}
}
/**
* Unselects all items in the list.
*/
_unselectAll() {
for (let i = 0; i < this.rows.length; ++i) {
this._unselectItemByRealIndex(i);
}
}
/**
* Called when the select/unselect all checkbox checked value is changed.
*/
_selectAllChanged() {
if (this.$.selectAllCheckbox.checked === true) {
this._selectAllDisplayedItems();
} else {
this._unselectAllDisplayedItems();
}
}
/**
* On row click, checks the click target, if it's the checkbox, adds it to
* the selected rows, otherwise selects it only.
* Note the distinction between displayIndex, which is the index of the item
* in the rendered list, and realIndex, which is the index of the item in the
* original list that was submitted to the item-list element. These might be
* different when filtering or sorting.
*/
_rowClicked(e: MouseEvent) {
if (this.disableSelection) {
return;
}
const target = e.target as HTMLDivElement;
const displayIndex = this.$.list.indexForElement(target);
const realIndex = this._displayIndexToRealIndex(displayIndex);
// If shift key is pressed and we had saved the last selected index, select
// all items from this index till the last selected.
if (!this.noMultiselect && e.shiftKey && this._lastSelectedIndex !== -1 &&
this.selectedIndices.length > 0) {
this._unselectAll();
const start = Math.min(this._lastSelectedIndex, displayIndex);
const end = Math.max(this._lastSelectedIndex, displayIndex);
for (let i = start; i <= end; ++i) {
this._selectItemByDisplayIndex(i);
}
} else if (!this.noMultiselect && (e.ctrlKey || e.metaKey)) {
// If ctrl (or Meta for MacOS) key is pressed, toggle its selection.
if (this.rows[realIndex].selected === false) {
this._selectItemByDisplayIndex(displayIndex, true);
} else {
this._unselectItemByDisplayIndex(displayIndex, true);
}
} else {
// No modifier keys are pressed, proceed normally to select/unselect the item.
// If the clicked element is the checkbox, the checkbox already toggles selection in
// the UI, so change the item's selection state to match the checkbox's new value.
// Otherwise, select this element, unselect all others.
if (target.tagName === 'PAPER-CHECKBOX') {
if (this.rows[realIndex].selected === false) {
// Remove this element from the selected elements list if it's being unselected
this._unselectItemByDisplayIndex(displayIndex, true);
} else {
// Add this element to the selected elements list if it's being selected,
this._selectItemByDisplayIndex(displayIndex, true);
}
} else {
this._unselectAll();
this._selectItemByDisplayIndex(displayIndex, true);
}
}
// Save this index to enable multi-selection using shift later.
this._lastSelectedIndex = displayIndex;
}
/**
* On row double click, fires an event with the clicked item's index.
*/
_rowDoubleClicked(e: MouseEvent) {
const realIndex = this.$.list.modelForElement(e.target).itemsIndex;
const ev = new ItemClickEvent('itemDoubleClick', { detail: {index: realIndex} });
this.dispatchEvent(ev);
}
private _getRowDetailsContainer(index: number) {
const nthDivSelector = 'div.row-details:nth-of-type(' + (index + 1) + ')';
return this.$.listContainer.querySelector(nthDivSelector);
}
private _displayIndexToRealIndex(index: number) {
const element = this.$.listContainer.querySelector(
'paper-item:nth-of-type(' + (index + 1 ) + ')');
return this.$.list.modelForElement(element).itemsIndex;
}
} | the_stack |
import { defineConfig } from '@agile-ts/utils';
import { logCodeManager } from '../logCodeManager';
import { Collection, CollectionKey, DefaultItem, ItemKey } from './collection';
import { Group, GroupKey } from './group';
import {
CreatePersistentConfigInterface,
getSharedStorageManager,
Persistent,
PersistentKey,
StorageKey,
} from '../storages';
export class CollectionPersistent<
DataType extends DefaultItem = DefaultItem
> extends Persistent {
// Collection the Persistent belongs to
public collection: () => Collection<DataType>;
static defaultGroupSideEffectKey = 'rebuildGroupStorageValue';
static storageItemKeyPattern = '_${collectionKey}_item_${itemKey}';
static storageGroupKeyPattern = '_${collectionKey}_group_${groupKey}';
/**
* Internal Class for managing the permanent persistence of a Collection.
*
* @internal
* @param collection - Collection to be persisted.
* @param config - Configuration object
*/
constructor(
collection: Collection<DataType>,
config: CreatePersistentConfigInterface = {}
) {
super(collection.agileInstance(), {
loadValue: false,
});
config = defineConfig(config, {
loadValue: true,
storageKeys: [],
defaultStorageKey: null as any,
});
this.collection = () => collection;
this.instantiatePersistent({
key: config.key,
storageKeys: config.storageKeys,
defaultStorageKey: config.defaultStorageKey,
});
// Load/Store persisted value/s for the first time
if (this.ready && config.loadValue) this.initialLoading();
}
/**
* Loads the persisted value into the Collection
* or persists the Collection value in the corresponding Storage.
* This behaviour depends on whether the Collection has been persisted before.
*
* @internal
*/
public async initialLoading() {
super.initialLoading().then(() => {
this.collection().isPersisted = true;
});
}
/**
* Loads Collection Instances (like Items or Groups) from the corresponding Storage
* and sets up side effects that dynamically update
* the Storage value when the Collection (Instances) changes.
*
* @internal
* @param storageItemKey - Prefix Storage key of the to load Collection Instances.
* | default = Persistent.key |
* @return Whether the loading of the persisted Collection Instances and setting up of the corresponding side effects was successful.
*/
public async loadPersistedValue(
storageItemKey?: PersistentKey
): Promise<boolean> {
if (!this.ready) return false;
const _storageItemKey = storageItemKey ?? this._key;
// Check if Collection is already persisted
// (indicated by the persistence of 'true' at '_storageItemKey')
const isPersisted = await getSharedStorageManager()?.get<DataType>(
_storageItemKey,
this.config.defaultStorageKey as any
);
// Return 'false' if Collection isn't persisted yet
if (!isPersisted) return false;
// Helper function to load persisted values into the Collection
const loadValuesIntoCollection = async () => {
const defaultGroup = this.collection().getDefaultGroup();
if (defaultGroup == null) return false;
const defaultGroupStorageKey = CollectionPersistent.getGroupStorageKey(
defaultGroup._key,
_storageItemKey
);
// Persist default Group and load its value manually to be 100% sure
// that it was loaded completely
defaultGroup.loadedInitialValue = false;
defaultGroup.persist({
key: defaultGroupStorageKey,
loadValue: false,
defaultStorageKey: this.config.defaultStorageKey || undefined,
storageKeys: this.storageKeys,
followCollectionPersistKeyPattern: false, // Because of the dynamic 'storageItemKey', the key is already formatted above
});
if (defaultGroup.persistent?.ready)
await defaultGroup.persistent.initialLoading();
// Persist Items found in the default Group's value
for (const itemKey of defaultGroup._value) {
const item = this.collection().getItem(itemKey);
const itemStorageKey = CollectionPersistent.getItemStorageKey(
itemKey,
_storageItemKey
);
// Persist an already present Item and load its value manually to be 100% sure
// that it was loaded completely
if (item != null) {
item.persist({
key: itemStorageKey,
loadValue: false,
defaultStorageKey: this.config.defaultStorageKey || undefined,
storageKeys: this.storageKeys,
followCollectionPersistKeyPattern: false, // Because of the dynamic 'storageItemKey', the key is already formatted above
});
if (item?.persistent?.ready) await item.persistent.initialLoading();
}
// Persist an already present placeholder Item
// or create a new placeholder Item to load the value in
// and load its value manually to be 100% sure
// that it was loaded completely.
// After a successful loading assign the now valid Item to the Collection.
else {
const placeholderItem = this.collection().getItemWithReference(
itemKey
);
placeholderItem?.persist({
key: itemStorageKey,
loadValue: false,
defaultStorageKey: this.config.defaultStorageKey as any,
storageKeys: this.storageKeys,
followCollectionPersistKeyPattern: false, // Because of the dynamic 'storageItemKey', the key is already formatted above
});
if (placeholderItem?.persistent?.ready) {
const loadedPersistedValueIntoItem = await placeholderItem.persistent.loadPersistedValue();
// If successfully loaded Item value, assign Item to Collection
if (loadedPersistedValueIntoItem) {
this.collection().assignItem(placeholderItem, {
overwrite: true, // Overwrite to overwrite the existing placeholder Item, if one exists
rebuildGroups: false, // Not necessary since the Groups that include the to assign Item were already rebuild while assigning the loaded value to the Item via 'loadPersistedValue()'
});
placeholderItem.isPersisted = true;
// Manually increase Collection size,
// since these Items already exist in the Collection (because of 'getItemWithReference()')
// but were placeholder before the persisted value got loaded
// -> Collection size wasn't increased in 'assignItem()'
this.collection().size += 1;
}
}
}
}
defaultGroup.loadedInitialValue = true;
return true;
};
const success = await loadValuesIntoCollection();
// Setup side effects to keep the Storage value in sync
// with the Collection (Instances) value
if (success) this.setupSideEffects(_storageItemKey);
return success;
}
/**
* Persists Collection Instances (like Items or Groups) in the corresponding Storage
* and sets up side effects that dynamically update
* the Storage value when the Collection (Instances) changes.
*
* @internal
* @param storageItemKey - Prefix Storage key of the to persist Collection Instances.
* | default = Persistent.key |
* @return Whether the persisting of the Collection Instances and the setting up of the corresponding side effects was successful.
*/
public async persistValue(storageItemKey?: PersistentKey): Promise<boolean> {
if (!this.ready) return false;
const _storageItemKey = storageItemKey ?? this._key;
const defaultGroup = this.collection().getDefaultGroup();
if (defaultGroup == null) return false;
const defaultGroupStorageKey = CollectionPersistent.getGroupStorageKey(
defaultGroup._key,
_storageItemKey
);
// Set flag in Storage to indicate that the Collection is persisted
getSharedStorageManager()?.set(_storageItemKey, true, this.storageKeys);
// Persist default Group
defaultGroup.persist({
key: defaultGroupStorageKey,
defaultStorageKey: this.config.defaultStorageKey || undefined,
storageKeys: this.storageKeys,
followCollectionPersistKeyPattern: false, // Because of the dynamic 'storageItemKey', the key is already formatted above
});
// Persist Items found in the default Group's value
for (const itemKey of defaultGroup._value) {
const item = this.collection().getItem(itemKey);
const itemStorageKey = CollectionPersistent.getItemStorageKey(
itemKey,
_storageItemKey
);
item?.persist({
key: itemStorageKey,
defaultStorageKey: this.config.defaultStorageKey || undefined,
storageKeys: this.storageKeys,
followCollectionPersistKeyPattern: false, // Because of the dynamic 'storageItemKey', the key is already formatted above
});
}
// Setup side effects to keep the Storage value in sync
// with the Collection (Instances) value
this.setupSideEffects(_storageItemKey);
this.isPersisted = true;
return true;
}
/**
* Sets up side effects to keep the Storage value in sync
* with the Collection (Instances) value.
*
* @internal
* @param storageItemKey - Prefix Storage key of the to remove Collection Instances.
* | default = Persistent.key |
*/
public setupSideEffects(storageItemKey?: PersistentKey): void {
const _storageItemKey = storageItemKey ?? this._key;
const defaultGroup = this.collection().getDefaultGroup();
if (defaultGroup == null) return;
// Add side effect to the default Group
// that adds and removes Items from the Storage based on the Group value
defaultGroup.addSideEffect<typeof defaultGroup>(
CollectionPersistent.defaultGroupSideEffectKey,
(instance) => this.rebuildStorageSideEffect(instance, _storageItemKey),
{ weight: 0 }
);
}
/**
* Removes the Collection from the corresponding Storage.
* -> Collection is no longer persisted
*
* @internal
* @param storageItemKey - Prefix Storage key of the persisted Collection Instances.
* | default = Persistent.key |
* @return Whether the removal of the Collection Instances was successful.
*/
public async removePersistedValue(
storageItemKey?: PersistentKey
): Promise<boolean> {
if (!this.ready) return false;
const _storageItemKey = storageItemKey ?? this._key;
const defaultGroup = this.collection().getDefaultGroup();
if (!defaultGroup) return false;
const defaultGroupStorageKey = CollectionPersistent.getGroupStorageKey(
defaultGroup._key,
_storageItemKey
);
// Remove Collection is persisted indicator flag from Storage
getSharedStorageManager()?.remove(_storageItemKey, this.storageKeys);
// Remove default Group from the Storage
defaultGroup.persistent?.removePersistedValue(defaultGroupStorageKey);
defaultGroup.removeSideEffect(
CollectionPersistent.defaultGroupSideEffectKey
);
// Remove Items found in the default Group's value from the Storage
for (const itemKey of defaultGroup._value) {
const item = this.collection().getItem(itemKey);
const itemStorageKey = CollectionPersistent.getItemStorageKey(
itemKey,
_storageItemKey
);
item?.persistent?.removePersistedValue(itemStorageKey);
}
this.isPersisted = false;
return true;
}
/**
* Formats the specified key so that it can be used as a valid Storage key
* and returns the formatted variant of it.
*
* If no formatable key (`undefined`/`null`) was provided,
* an attempt is made to use the Collection identifier key as Storage key.
*
* @internal
* @param key - Storage key to be formatted.
*/
public formatKey(key: StorageKey | undefined | null): StorageKey | undefined {
if (key == null && this.collection()._key) return this.collection()._key;
if (key == null) return;
if (this.collection()._key == null) this.collection()._key = key;
return key;
}
/**
* Adds and removes Items from the Storage based on the Group value.
*
* @internal
* @param group - Group whose Items are to be dynamically added or removed from the Storage.
* @param storageItemKey - Prefix Storage key of the persisted Collection Instances.
* | default = Persistent.key |
*/
public rebuildStorageSideEffect(
group: Group<DataType>,
storageItemKey?: PersistentKey
) {
const collection = group.collection();
const _storageItemKey = storageItemKey || collection.persistent?._key;
// Return if no Item got added or removed
// because then the changed Item performs the Storage update itself
if (group.previousStateValue.length === group._value.length) return;
// Extract Item keys that got added or removed from the Group
const addedKeys = group._value.filter(
(key) => !group.previousStateValue.includes(key)
);
const removedKeys = group.previousStateValue.filter(
(key) => !group._value.includes(key)
);
// Persist newly added Items
addedKeys.forEach((itemKey) => {
const item = collection.getItem(itemKey);
const itemStorageKey = CollectionPersistent.getItemStorageKey(
itemKey,
_storageItemKey
);
if (item != null && !item.isPersisted)
item.persist({
key: itemStorageKey,
defaultStorageKey: this.config.defaultStorageKey || undefined,
storageKeys: this.storageKeys,
followCollectionPersistKeyPattern: false, // Because of the dynamic 'storageItemKey', the key is already formatted above
});
});
// Remove removed Items from the Storage
removedKeys.forEach((itemKey) => {
const item = collection.getItem(itemKey);
const itemStorageKey = CollectionPersistent.getItemStorageKey(
itemKey,
_storageItemKey
);
if (item != null && item.isPersisted)
item.persistent?.removePersistedValue(itemStorageKey);
});
}
/**
* Builds valid Item Storage key based on the 'Collection Item Persist Pattern'.
*
* @internal
* @param itemKey - Key identifier of Item
* @param collectionKey - Key identifier of Collection
*/
public static getItemStorageKey(
itemKey: ItemKey | undefined | null,
collectionKey: CollectionKey | undefined | null
): string {
if (itemKey == null || collectionKey == null)
logCodeManager.log('1A:02:00');
if (itemKey == null) itemKey = 'unknown';
if (collectionKey == null) collectionKey = 'unknown';
return this.storageItemKeyPattern
.replace('${collectionKey}', collectionKey.toString())
.replace('${itemKey}', itemKey.toString());
}
/**
* Builds valid Item Storage key based on the 'Collection Group Persist Pattern'.
*
* @internal
* @param groupKey - Key identifier of Group
* @param collectionKey - Key identifier of Collection
*/
public static getGroupStorageKey(
groupKey: GroupKey | undefined | null,
collectionKey: CollectionKey | undefined | null
): string {
if (groupKey == null || collectionKey == null)
logCodeManager.log('1A:02:01');
if (groupKey == null) groupKey = 'unknown';
if (collectionKey == null) collectionKey = 'unknown';
return this.storageGroupKeyPattern
.replace('${collectionKey}', collectionKey.toString())
.replace('${groupKey}', groupKey.toString());
}
} | the_stack |
import Docker = require("dockerode");
import execa from "execa";
import * as fs from "fs";
import ld from "lodash";
import os from "os";
import * as sb from "stream-buffers";
import * as util from "util";
export async function dockerExec(container: Docker.Container, command: string[]): Promise<string> {
const exec = await container.exec({
AttachStdin: false,
AttachStdout: true,
AttachStderr: true,
Cmd: command
});
const output = await exec.start({});
const buf = new sb.WritableStreamBuffer();
const errBuf = new sb.WritableStreamBuffer();
exec.modem.demuxStream(output, buf, errBuf);
return new Promise<string>((res, rej) => {
output.on("end", async () => {
const inspectInfo = await exec.inspect();
if (inspectInfo.Running !== false) {
rej(new Error(`dockerExec: ${util.inspect(command)} stream ended with process still running?!`));
return;
}
if (inspectInfo.ExitCode !== 0) {
// tslint:disable-next-line:max-line-length
let msg = `dockerExec: ${util.inspect(command)} process ` +
`exited with error (code: ${inspectInfo.ExitCode})`;
const stderr = errBuf.getContentsAsString();
if (stderr) msg += "\n" + stderr;
rej(new Error(msg));
return;
}
res(buf.getContentsAsString() || "");
});
});
}
export async function dockerPull(docker: Docker, imageName: string, indent = ""): Promise<void> {
// tslint:disable:no-console
function printStatus(data: unknown) {
if (!(data instanceof Buffer)) throw new Error(`Unknown status: ${data}`);
// data is JSONL, so can contain multiple messages
const msgs = data.toString().split("\n").filter((m) => m.trim() !== "");
for (const mString of msgs) {
const msg = JSON.parse(mString);
let s = msg.status;
if (!s) {
console.log(`${indent}Docker pull status:`, msg);
continue;
}
if (msg.id) s += ` id=${msg.id}`;
const prog = msg.progressDetail;
if (prog && prog.current != null) s += ` Progress: ${prog.current}/${prog.total}`;
console.log(`${indent} ${s}`);
}
}
if (!imageName.includes(":")) {
throw new Error(`dockerPull: imageName must include tag or be an ID`);
}
console.log(`${indent}Pulling docker image ${imageName}`);
return new Promise<void>((res, rej) => {
let errored = false;
function mkErr(e: any) {
if (errored) return;
errored = true;
const msg = `Error pulling image: ${e}`;
console.log(`${indent}${msg}`);
rej(new Error(msg));
}
// NOTE(mark): tslint incorrectly complains about an unhandled
// promise from docker.pull on the line below, but the callback
// version of pull does not return a promise.
// tslint:disable-next-line:no-floating-promises
docker.pull(imageName, (err: any, stream: any) => {
if (err) return mkErr(err);
stream.on("error", (e: any) => {
return mkErr(e);
});
stream.on("data", (data: any) => {
try {
printStatus(data);
} catch (e) {
return mkErr(e);
}
});
stream.on("end", () => {
if (errored) return;
console.log(`${indent}Pull complete`);
res();
});
});
});
// tslint:enable:no-console
}
export async function deleteContainer(docker: Docker, name: string) {
let ctr: Docker.Container;
try {
ctr = docker.getContainer(name);
} catch (e) { return; }
try {
await ctr.stop();
} catch (e) { /**/ }
try {
await ctr.remove();
} catch (e) { /**/ }
}
export async function getNetwork(docker: Docker, container: Docker.Container) {
const info = await container.inspect();
const networkName = Object.keys(info.NetworkSettings.Networks)[0];
return docker.getNetwork(networkName);
}
export async function createNetwork(docker: Docker, name: string): Promise<Docker.Network> {
return docker.createNetwork({ Name: name });
}
export async function addToNetwork(container: Docker.Container, network: Docker.Network) {
try {
await network.connect({ Container: container.id });
} catch (e) {
if (!(typeof e.message === "string" &&
e.message.includes("already exists in network"))) {
throw e;
}
}
}
export async function removeFromNetwork(container: Docker.Container, network: Docker.Network) {
try {
await network.disconnect({ Container: container.id });
} catch (e) {
// Ignore error if not connected to this network
if (!(typeof e.message === "string" &&
e.message.includes("is not connected to network"))) {
throw e;
}
}
}
export function inContainer() {
try {
return fs.readFileSync("/proc/self/cgroup").toString().includes("/docker/");
} catch (err) {
return false;
}
}
export async function getSelfContainer(docker: Docker): Promise<Docker.Container | null> {
if (os.platform() === "win32") return null;
const entries = fs.readFileSync("/proc/self/cgroup").toString().split(/\r?\n/);
if (entries.length === 0) throw new Error("Cannot get own container id!");
const entry = entries[0];
const [, , path] = entry.split(":");
const psplit = path.split("/");
const id = ld.last(psplit);
if (id === undefined) throw new Error("Cannot get own container id!");
return docker.getContainer(id);
}
export function secondsSince(start: number): number {
return (Date.now() - start) / 1000;
}
export interface DockerUtilOpts {
dockerHost?: string;
}
function dockerArgs(opts: DockerUtilOpts, ...moreArgs: string[]) {
const args = [];
if (opts.dockerHost) args.push("-H", opts.dockerHost);
return args.concat(moreArgs);
}
/**
* Delete all Docker containers that match a filter string.
* @example
* Example for deleting containers created for an Adapt deployment:
* ```
* import { adaptDockerDeployIDKey } from "@adpt/cloud/docker";
* const filter = `label=${adaptDockerDeployIDKey}=${lDeployID}`;
* await deleteAllContainers(filter);
* ```
*/
export async function deleteAllContainers(filter: string, opts: DockerUtilOpts = {}) {
try {
let args = dockerArgs(opts, "ps", "-a", "-q", "--filter", filter);
const { stdout: ctrList } = await execa("docker", args);
if (!ctrList) return;
const ctrs = ctrList.split(/\s+/);
args = dockerArgs(opts, "rm", "-f", ...ctrs);
if (ctrs.length > 0) await execa("docker", args);
} catch (err) {
if (/invalid argument/.test(err.stderr || "")) throw err;
// tslint:disable-next-line: no-console
console.log(`Error deleting containers (ignored):`, err);
}
}
/**
* Delete all Docker networks that match a filter string.
* @example
* Example for deleting networks created for an Adapt deployment:
* ```
* import { adaptDockerDeployIDKey } from "@adpt/cloud/docker";
* const filter = `label=${adaptDockerDeployIDKey}=${lDeployID}`;
* await deleteAllNetworks(filter);
* ```
*/
export async function deleteAllNetworks(filter: string, opts: DockerUtilOpts = {}) {
try {
let args = dockerArgs(opts, "network", "ls", "-q", "--filter", filter);
const { stdout: netList } = await execa("docker", args);
if (!netList) return;
const nets = netList.split(/\s+/);
args = dockerArgs(opts, "network", "rm", ...nets);
if (nets.length > 0) await execa("docker", args);
} catch (err) {
if (/invalid argument/.test(err.stderr || "")) throw err;
// tslint:disable-next-line: no-console
console.log(`Error deleting networks (ignored):`, err);
}
}
/**
* Delete all Docker images or image tags that match a filter string.
* @remarks
* Note that this may only delete image tags and may not completely remove
* the actual layers stored if other tags reference the same layers.
* @example
* Example for deleting images created for an Adapt deployment:
* ```
* import { adaptDockerDeployIDKey } from "@adpt/cloud/docker";
* const filter = `label=${adaptDockerDeployIDKey}=${lDeployID}`;
* await deleteAllImages(filter);
* ```
*/
export async function deleteAllImages(filter: string, opts: DockerUtilOpts = {}) {
try {
let args = dockerArgs(opts, "image", "ls", "-q", "--filter", filter);
const { stdout: imgList } = await execa("docker", args);
if (!imgList) return;
const imgs = ld.uniq(imgList.split(/\s+/m));
args = dockerArgs(opts, "rmi", "-f", ...imgs);
if (imgs.length > 0) await execa("docker", args);
} catch (err) {
if (/invalid argument/.test(err.stderr || "")) throw err;
// tslint:disable-next-line: no-console
console.log(`Error deleting images (ignored):`, err);
}
}
/**
* Create a TCP proxy on localhost inside a container that forwards to
* another host and/or port. Does nothing if this code is not running in
* a container.
*
* @remarks
* This is primarily useful for tricking tools that change their behavior
* when they connect to localhost. For example, Docker and related tools
* allow HTTP connections to localhost without configuration.
*/
export async function proxyFromContainer(localPort: number, target: string) {
if (!inContainer()) return async () => {/* */};
await execa("apt-get", ["install", "socat"]);
const child = execa(
"socat", [`tcp-listen:${localPort},reuseaddr,fork`, `tcp:${target}`], {
stdio: "inherit",
});
return async () => {
child.kill();
};
} | the_stack |
declare var expect: Chai.ExpectStatic;
function addFetchSuite () {
describe('fetch', () => {
it('should be defined', () => {
expect(fetch).to.be.a('function')
})
it('should facilitate the making of requests', () => {
return fetch('http://localhost:8000/succeed')
.then(function (res: Response): Promise<string> {
if (res.status >= 400) {
throw new Error('Bad server response')
}
return res.text()
})
.then(function (data: string): void {
expect(data).to.equal('hello world.')
})
})
it('should catch bad responses', () => {
return fetch('http://localhost:8000/fail')
.then(function (res: Response): Promise<string> {
if (res.status >= 400) {
throw new Error('Bad server response')
}
return res.text()
})
.catch(function (err: Error): void {
expect(err).to.be.an.instanceof(Error, 'Bad server response')
})
})
it('should resolve promise on 500 error', () => {
return fetch('http://localhost:8000/error')
.then(function (res: Response): Promise<string> {
expect(res.status).to.equal(500)
expect(res.ok).to.equal(false)
return res.text()
})
.then(function (data: string): void {
expect(data).to.equal('error world.')
})
})
it('should reject when Request constructor throws', () => {
return fetch('http://localhost:8000/succeed', { method: 'GET', body: 'invalid' })
.then(function (): void {
expect.fail('Invalid Request init was accepted')
})
.catch(function (err: Error): void {
expect(err).to.be.an.instanceof(TypeError, 'Rejected with Error')
})
})
it('should send headers', () => {
return fetch('http://localhost:8000/request', {
headers: {
Accept: 'application/json',
'X-Test': '42'
}
})
.then(function (res: Response): Promise<any> {
return res.json()
})
.then(function (data: any): void {
expect(data.headers.accept).to.equal('application/json')
expect(data.headers['x-test']).to.equal('42')
})
})
it('with Request as argument', () => {
const request = new Request('http://localhost:8000/request', {
headers: {
Accept: 'application/json',
'X-Test': '42'
}
})
return fetch(request)
.then(function (res: Response): Promise<any> {
return res.json()
})
.then(function (data: any): void {
expect(data.headers.accept).to.equal('application/json')
expect(data.headers['x-test']).to.equal('42')
})
})
it('should reuse same Request multiple times', () => {
const request = new Request('http://localhost:8000/request', {
headers: {
Accept: 'application/json',
'X-Test': '42'
}
})
const responses: Response[] = []
return fetch(request)
.then(function (res: Response): Promise<Response> {
responses.push(res)
return fetch(request)
})
.then(function (res: Response): Promise<Response> {
responses.push(res)
return fetch(request)
})
.then(function (res: Response): Promise<any[]> {
responses.push(res)
return Promise.all(
responses.map(function (res) {
return res.json()
})
)
})
.then(function (data: any[]): void {
data.forEach(function (json: any) {
expect(json.headers.accept).to.equal('application/json')
expect(json.headers['x-test']).to.equal('42')
})
})
})
it('should populate body', () => {
return fetch('http://localhost:8000/succeed')
.then(function (res: Response): Promise<string> {
expect(res.status).to.equal(200)
expect(res.ok).to.equal(true)
return res.text()
})
.then(function (data: string): void {
expect(data).to.equal('hello world.')
})
})
it('should parse headers', () => {
return fetch('http://localhost:8000/request').then(function (res: Response) {
expect(res.headers.get('Date')).to.equal('Sat, 23 Sep 2017 15:41:16 GMT-0300')
expect(res.headers.get('Content-Type')).to.equal('application/json; charset=utf-8')
})
})
it('should support HTTP GET', () => {
return fetch('http://localhost:8000/request', {
method: 'get'
})
.then(function (res: Response): Promise<any> {
return res.json()
})
.then(function (data: any): void {
expect(data.method).to.equal('GET')
expect(data.body).to.deep.equal({})
})
})
it('should throw error on GET with body', () => {
expect(function (): void {
new Request('', {
method: 'get',
body: 'invalid'
})
}).to.throw(TypeError)
})
it('should throw error on HEAD with body', () => {
expect(function (): void {
new Request('', {
method: 'head',
body: 'invalid'
})
}).to.throw(TypeError)
})
it('should support HTTP POST', () => {
return fetch('http://localhost:8000/request', {
method: 'post',
body: 'name=Hubot'
})
.then(function (res: Response): Promise<any> {
return res.json()
})
.then(function (data: any): void {
expect(data.method).to.equal('POST')
expect(data.body).to.equal('name=Hubot')
})
})
it('should support HTTP PUT', () => {
return fetch('http://localhost:8000/request', {
method: 'put',
body: 'name=Hubot'
})
.then(function (res: Response): Promise<any> {
return res.json()
})
.then(function (data: any): void {
expect(data.method).to.equal('PUT')
expect(data.body).to.equal('name=Hubot')
})
})
it('should support HTTP PATCH', () => {
return fetch('http://localhost:8000/request', {
method: 'PATCH',
body: 'name=Hubot'
})
.then(function (res: Response): Promise<any> {
return res.json()
})
.then(function (data: any): void {
expect(data.method).to.equal('PATCH')
expect(data.body).to.equal('name=Hubot')
})
})
it('should support HTTP DELETE', () => {
return fetch('http://localhost:8000/request', {
method: 'delete'
})
.then(function (res: Response): Promise<any> {
return res.json()
})
.then(function (data: any): void {
expect(data.method).to.equal('DELETE')
expect(data.body).to.equal('')
})
})
})
describe('Request', () => {
it('should be defined', () => {
expect(Request).to.be.a('function')
})
it('should construct an url from string', () => {
const request = new Request('http://localhost:8000/')
expect(request.url).to.equal('http://localhost:8000/')
})
it('should construct url from object', () => {
const url = {
toString: function (): string {
return 'http://localhost:8000/'
}
}
const request = new Request(url as any)
expect(request.url).to.equal('http://localhost:8000/')
})
it('should get GET as the default method', () => {
const request = new Request('http://localhost:8000/')
expect(request.method).to.equal('GET')
})
it('should set a method', () => {
const request = new Request('http://localhost:8000/', {
method: 'post'
})
expect(request.method).to.equal('POST')
})
it('should set headers', () => {
const request = new Request('http://localhost:8000/', {
headers: {
accept: 'application/json',
'Content-Type': 'text/plain'
}
})
expect(request.headers.get('accept')).to.equal('application/json')
expect(request.headers.get('content-type')).to.equal('text/plain')
})
it('should set a body', () => {
const request = new Request('http://localhost:8000/', {
method: 'post',
body: 'Hello World!'
})
return request.text().then(function (data: string): void {
expect(data).to.equal('Hello World!')
})
})
it.skip('construct with Request', () => {
const request1 = new Request('http://localhost:8000/', {
method: 'post',
body: 'Hello World!',
headers: {
accept: 'application/json',
'Content-Type': 'text/plain'
}
})
const request2 = new Request(request1)
return request2.text().then(function (data: string): Promise<void> {
expect(data).to.equal('Hello World!')
expect(request2.method).to.equal('POST')
expect(request2.url).to.equal('http://localhost:8000/')
expect(request2.headers.get('accept')).to.equal('application/json')
expect(request2.headers.get('content-type')).to.equal('text/plain')
return request1.text().then(
function (): void {
expect.fail('original request body should have been consumed')
},
function (err: TypeError): void {
expect(err).to.be.an.instanceof(TypeError, 'expected TypeError for already read body')
}
)
})
})
it('should construct a Request from another Request', () => {
const request1 = new Request('http://localhost:8000/', {
method: 'post',
body: 'Hello World!',
headers: {
accept: 'application/json'
}
})
const request2 = new Request(request1)
expect(request2.method).to.equal('POST')
expect(request2.headers.get('accept')).to.equal('application/json')
return request2.text().then(function (data: string): void {
expect(data).to.equal('Hello World!')
})
})
it('should construct with Request with overriden headers', () => {
const request1 = new Request('http://localhost:8000/', {
method: 'post',
body: 'Hello World!',
headers: {
accept: 'application/json',
'X-Request-ID': '123'
}
})
const request2 = new Request(request1, {
headers: { 'x-test': '42' }
})
expect(request2.headers.get('accept')).to.equal(null)
expect(request2.headers.get('x-request-id')).to.equal(null)
expect(request2.headers.get('x-test')).to.equal('42')
})
it('should construct with Request and override body', () => {
const request1 = new Request('http://localhost:8000/', {
method: 'post',
body: 'Hello World!',
headers: {
'Content-Type': 'text/plain'
}
})
const request2 = new Request(request1, {
body: '{"wiggles": 5}',
headers: { 'Content-Type': 'application/json' }
})
return request2.json().then(function (data: any): void {
expect(data.wiggles).to.equal(5)
expect(request2.headers.get('content-type')).to.equal('application/json')
})
})
it('construct with used Request body', () => {
const request1 = new Request('http://localhost:8000/', {
method: 'post',
body: 'Hello World!'
})
return request1.text().then(function (): void {
expect(function () { new Request(request1) }).to.throw()
})
})
it('should not have implicit Content-Type', () => {
const req = new Request('http://localhost:8000/')
expect(req.headers.get('content-type')).to.equal(null)
})
it('POST with blank body should not have implicit Content-Type', () => {
const req = new Request('http://localhost:8000/', {
method: 'post'
})
expect(req.headers.get('content-type')).to.equal(null)
})
it('construct with string body sets Content-Type header', () => {
const req = new Request('http://localhost:8000/', {
method: 'post',
body: 'Hello World!'
})
expect(req.headers.get('content-type')).to.equal('text/plain;charset=UTF-8')
})
it('construct with body and explicit header uses header', () => {
const req = new Request('http://localhost:8000/', {
method: 'post',
headers: { 'Content-Type': 'image/png' },
body: 'Hello World!'
})
expect(req.headers.get('content-type')).to.equal('image/png')
})
it('construct with unsupported body type', () => {
const req = new Request('http://localhost:8000/', {
method: 'post',
body: {} as any
})
expect(req.headers.get('content-type')).to.equal('text/plain;charset=UTF-8')
return req.text().then(function (data: string): void {
expect(data, '[object Object]')
})
})
it('construct with null body', () => {
const req = new Request('http://localhost:8000/', {
method: 'post'
})
expect(req.headers.get('content-type')).to.equal(null)
return req.text().then(function (data: string): void {
expect(data).to.equal('')
})
})
it('should clone GET request', () => {
const req = new Request('http://localhost:8000/', {
headers: { 'content-type': 'text/plain' }
})
const clone = req.clone()
expect(clone.url).to.equal(req.url)
expect(clone.method).to.equal('GET')
expect(clone.headers.get('content-type')).to.equal('text/plain')
expect(clone.headers).to.not.equal(req.headers)
expect(req.bodyUsed).to.equal(false)
})
it('should clone POST request', () => {
const req = new Request('http://localhost:8000/', {
method: 'post',
headers: { 'content-type': 'text/plain' },
body: 'Hello World!'
})
const clone = req.clone()
expect(clone.method).to.equal('POST')
expect(clone.headers.get('content-type')).to.equal('text/plain')
expect(clone.headers).to.not.equal(req.headers)
expect(req.bodyUsed).to.equal(false)
return Promise.all([clone.text(), req.clone().text()]).then(function (data) {
expect(data).to.deep.equal(['Hello World!', 'Hello World!'])
})
})
it('clone with used Request body', () => {
const req = new Request('http://localhost:8000/', {
method: 'post',
body: 'Hello World!'
})
return req.text().then(function (): void {
expect(function () { req.clone() }).to.throw()
})
})
})
describe('Response', () => {
it('should be defined', () => {
expect(Response).to.be.a('function')
})
it('should default to status 200 OK', () => {
const res = new Response()
expect(res.status).to.equal(200)
// expect(res.statusText).to.equal('OK')
expect(res.ok).to.equal(true)
})
it('should default to status 200 OK when an explicit undefined status code is passed', () => {
const res = new Response('', { status: undefined })
expect(res.status).to.equal(200)
// expect(res.statusText).to.equal('OK')
expect(res.ok).to.equal(true)
})
it('should create Headers object from raw headers', () => {
const response = new Response('{"foo":"bar"}', {
headers: { 'content-type': 'application/json' }
})
expect(response.headers).to.be.an.instanceof(Headers)
return response.json().then(function (data: any): any {
expect(data.foo).to.equal('bar')
return data
})
})
it('should always creates a new Headers instance', () => {
const headers = new Headers({ 'x-hello': 'world' })
const res = new Response('', { headers: headers })
expect(res.headers.get('x-hello')).to.equal('world')
expect(res.headers).to.not.equal(headers)
})
it('should clone text response', () => {
const res = new Response('{"foo":"bar"}', {
headers: { 'content-type': 'application/json' }
})
const clone = res.clone()
expect(clone.headers).to.not.equal(res.headers, 'headers were cloned')
expect(clone.headers.get('content-type'), 'application/json')
return Promise.all([clone.json(), res.json()]).then(function (data: [any, any]): void {
expect(data[0]).to.deep.equal(data[1], 'json of cloned object is the same as original')
})
})
it('should construct with body and explicit header uses header', () => {
const response = new Response('Hello World!', {
headers: {
'Content-Type': 'text/plain'
}
})
expect(response.headers.get('content-type')).to.equal('text/plain')
})
it('should have no content when null is passed as first argument', () => {
const response = new Response(null)
expect(response.headers.get('content-type')).to.equal(null)
return response.text().then(function (data: string): void {
expect(data).to.equal('')
})
})
})
describe('Headers', () => {
it('should be defined', () => {
expect(Headers).to.be.a('function')
})
it('should set headers using object', () => {
const object = { 'Content-Type': 'application/json', Accept: 'application/json' }
const headers = new Headers(object)
expect(headers.get('Content-Type')).to.equal('application/json')
expect(headers.get('Accept')).to.equal('application/json')
})
it('should set headers using array', () => {
const array = [['Content-Type', 'application/json'], ['Accept', 'application/json']]
const headers = new Headers(array)
expect(headers.get('Content-Type')).to.equal('application/json')
expect(headers.get('Accept')).to.equal('application/json')
})
it('should set header name and value', () => {
const headers = new Headers()
headers.set('Content-Type', 'application/json')
expect(headers.get('Content-Type')).to.equal('application/json')
})
it('should overwrite header value if it exists', () => {
const headers = new Headers({ 'Content-Type': 'application/json' })
headers.set('Content-Type', 'text/xml')
expect(headers.get('Content-Type')).to.equal('text/xml')
})
it('should set a multi-value header', () => {
const headers = new Headers({ 'Accept-Encoding': ['gzip', 'compress'] } as any)
expect(headers.get('Accept-Encoding')).to.equal('gzip,compress')
})
it('should set header key as case insensitive', () => {
const headers = new Headers({ Accept: 'application/json' })
expect(headers.get('ACCEPT')).to.equal('application/json')
expect(headers.get('Accept')).to.equal('application/json')
expect(headers.get('accept')).to.equal('application/json')
})
it('should append a header to the existing ones', () => {
const headers = new Headers({ Accept: 'application/json' })
headers.append('Accept', 'text/plain')
expect(headers.get('Accept')).to.equal('application/json, text/plain')
})
it('should return null on no header found', () => {
const headers = new Headers()
expect(headers.get('Content-Type')).to.equal(null)
})
it('should set null header as a string value', () => {
const headers = new Headers({ Custom: null } as any)
expect(headers.get('Custom')).to.equal('null')
})
it('should set an undefined header as a string value', () => {
const headers = new Headers({ Custom: undefined } as any)
expect(headers.get('Custom')).to.equal('undefined')
})
it('should throw TypeError on invalid character in field name', () => {
/* eslint-disable no-new */
expect(function (): void { new Headers({ '<Accept>': 'application/json' }) }).to.throw()
expect(function (): void { new Headers({ 'Accept:': 'application/json' }) }).to.throw()
expect(function (): void {
const headers = new Headers()
headers.set({ field: 'value' } as any, 'application/json')
}).to.throw()
})
it('should not init an invalid header', () => {
/* eslint-disable no-new */
expect(function (): void { new Headers({ Héy: 'ok' }) }).to.throw()
})
it('should not set an invalid header', () => {
const headers = new Headers()
expect(function (): void { headers.set('Héy', 'ok') }).to.throw()
})
it('should not append an invalid header', () => {
const headers = new Headers()
expect(function (): void { headers.append('Héy', 'ok') }).to.throw()
})
it('should not get an invalid header', () => {
const headers = new Headers()
expect(function (): void { headers.get('Héy') }).to.throw()
})
it('should copy headers', () => {
const original = new Headers()
original.append('Accept', 'application/json')
original.append('Accept', 'text/plain')
original.append('Content-Type', 'text/html')
const headers = new Headers(original)
expect(headers.get('Accept')).to.equal('application/json, text/plain')
expect(headers.get('Content-type')).to.equal('text/html')
})
it('should detect if a header exists', () => {
const headers = new Headers({ Accept: 'application/json' })
expect(headers.has('Content-Type')).to.equal(false)
headers.append('Content-Type', 'application/json')
expect(headers.has('Content-Type')).to.equal(true)
})
it('should have headers that are set', () => {
const headers = new Headers()
headers.set('Content-Type', 'application/json')
expect(headers.has('Content-Type')).to.equal(true)
})
it('should delete header', () => {
const headers = new Headers({ Accept: 'application/json' })
expect(headers.has('Accept')).to.equal(true)
headers.delete('Accept')
expect(headers.has('Accept')).to.equal(false)
expect(headers.get('Content-Type')).to.equal(null)
})
it('should convert field name to string on set and get', () => {
const headers = new Headers()
headers.set(1 as any, 'application/json')
expect(headers.has('1')).to.equal(true)
expect(headers.get(1 as any)).to.equal('application/json')
})
it('should convert field value to string on set and get', () => {
const headers = new Headers()
headers.set('Content-Type', 1 as any)
headers.set('X-CSRF-Token', undefined as any)
expect(headers.get('Content-Type')).to.equal('1')
expect(headers.get('X-CSRF-Token')).to.equal('undefined')
})
it('should be iterable with forEach', () => {
const headers = new Headers()
headers.append('Accept', 'application/json')
headers.append('Accept', 'text/plain')
headers.append('Content-Type', 'text/html')
const results: {value: string, key: string, object: object}[] = []
headers.forEach(function (value, key, object) {
results.push({ value: value, key: key, object: object })
})
expect(results.length).to.equal(2)
expect({ key: 'accept', value: 'application/json, text/plain', object: headers }).to.deep.equal(results[0])
expect({ key: 'content-type', value: 'text/html', object: headers }).to.deep.equal(results[1])
})
it('should accept second thisArg argument for forEach', () => {
const headers = new Headers({ Accept: 'application/json' })
const thisArg = {}
headers.forEach(function (this: void): void {
expect(this).to.equal(thisArg)
}, thisArg)
})
it('should be iterable with keys', () => {
const headers = new Headers({
Accept: 'application/json, text/plain',
'Content-Type': 'text/html'
})
const iterator = headers.keys()
expect({ done: false, value: 'accept' }).to.deep.equal(iterator.next())
expect({ done: false, value: 'content-type' }).to.deep.equal(iterator.next())
expect({ done: true, value: undefined }).to.deep.equal(iterator.next())
})
it('should be iterable with values', () => {
const headers = new Headers({
Accept: 'application/json, text/plain',
'Content-Type': 'text/html'
})
const iterator = headers.values()
expect({ done: false, value: 'application/json, text/plain' }).to.deep.equal(iterator.next())
expect({ done: false, value: 'text/html' }).to.deep.equal(iterator.next())
expect({ done: true, value: undefined }).to.deep.equal(iterator.next())
})
it('should be iterable with entries', () => {
const headers = new Headers({
Accept: 'application/json, text/plain',
'Content-Type': 'text/html'
})
const iterator = headers.entries()
expect({ done: false, value: ['accept', 'application/json, text/plain'] }).to.deep.equal(iterator.next())
expect({ done: false, value: ['content-type', 'text/html'] }).to.deep.equal(iterator.next())
expect({ done: true, value: undefined }).to.deep.equal(iterator.next())
})
})
}
if (typeof module === 'object' && module.exports) {
module.exports = addFetchSuite;
} | the_stack |
import { HashSet, ObservableHashSet } from "../hash-set";
describe("ObservableHashSet<T>", () => {
it("should not throw on creation", () => {
expect(() => new ObservableHashSet<{ a: number }>([], item => item.a.toString())).not.toThrowError();
});
it("should be initializable", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.size).toBe(4);
});
it("has should work as expected", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.has({ a: 1 })).toBe(true);
expect(res.has({ a: 5 })).toBe(false);
});
it("forEach should work as expected", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
let a = 1;
res.forEach((item) => {
expect(item.a).toEqual(a++);
});
});
it("delete should work as expected", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.has({ a: 1 })).toBe(true);
expect(res.delete({ a: 1 })).toBe(true);
expect(res.has({ a: 1 })).toBe(false);
expect(res.has({ a: 5 })).toBe(false);
expect(res.delete({ a: 5 })).toBe(false);
expect(res.has({ a: 5 })).toBe(false);
});
it("toggle should work as expected", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.has({ a: 1 })).toBe(true);
res.toggle({ a: 1 });
expect(res.has({ a: 1 })).toBe(false);
expect(res.has({ a: 6 })).toBe(false);
res.toggle({ a: 6 });
expect(res.has({ a: 6 })).toBe(true);
});
it("add should work as expected", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.has({ a: 6 })).toBe(false);
res.add({ a: 6 });
expect(res.has({ a: 6 })).toBe(true);
});
it("add should treat the hash to be the same as equality", () => {
const res = new ObservableHashSet([
{ a: 1, foobar: "hello" },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.has({ a: 1 })).toBe(true);
res.add({ a: 1, foobar: "goodbye" });
expect(res.has({ a: 1 })).toBe(true);
});
it("clear should work as expected", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.size).toBe(4);
res.clear();
expect(res.size).toBe(0);
});
it("replace should work as expected", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.size).toBe(4);
res.replace([{ a: 13 }]);
expect(res.size).toBe(1);
expect(res.has({ a: 1 })).toBe(false);
expect(res.has({ a: 13 })).toBe(true);
});
it("toJSON should work as expected", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.toJSON()).toStrictEqual([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
]);
});
it("values should work as expected", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
const iter = res.values();
expect(iter.next()).toStrictEqual({
value: { a: 1 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 2 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 3 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 4 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: undefined,
done: true,
});
});
it("keys should work as expected", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
const iter = res.keys();
expect(iter.next()).toStrictEqual({
value: { a: 1 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 2 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 3 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 4 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: undefined,
done: true,
});
});
it("entries should work as expected", () => {
const res = new ObservableHashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
const iter = res.entries();
expect(iter.next()).toStrictEqual({
value: [{ a: 1 }, { a: 1 }],
done: false,
});
expect(iter.next()).toStrictEqual({
value: [{ a: 2 }, { a: 2 }],
done: false,
});
expect(iter.next()).toStrictEqual({
value: [{ a: 3 }, { a: 3 }],
done: false,
});
expect(iter.next()).toStrictEqual({
value: [{ a: 4 }, { a: 4 }],
done: false,
});
expect(iter.next()).toStrictEqual({
value: undefined,
done: true,
});
});
});
describe("HashSet<T>", () => {
it("should not throw on creation", () => {
expect(() => new HashSet<{ a: number }>([], item => item.a.toString())).not.toThrowError();
});
it("should be initializable", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.size).toBe(4);
});
it("has should work as expected", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.has({ a: 1 })).toBe(true);
expect(res.has({ a: 5 })).toBe(false);
});
it("forEach should work as expected", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
let a = 1;
res.forEach((item) => {
expect(item.a).toEqual(a++);
});
});
it("delete should work as expected", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.has({ a: 1 })).toBe(true);
expect(res.delete({ a: 1 })).toBe(true);
expect(res.has({ a: 1 })).toBe(false);
expect(res.has({ a: 5 })).toBe(false);
expect(res.delete({ a: 5 })).toBe(false);
expect(res.has({ a: 5 })).toBe(false);
});
it("toggle should work as expected", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.has({ a: 1 })).toBe(true);
res.toggle({ a: 1 });
expect(res.has({ a: 1 })).toBe(false);
expect(res.has({ a: 6 })).toBe(false);
res.toggle({ a: 6 });
expect(res.has({ a: 6 })).toBe(true);
});
it("add should work as expected", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.has({ a: 6 })).toBe(false);
res.add({ a: 6 });
expect(res.has({ a: 6 })).toBe(true);
});
it("add should treat the hash to be the same as equality", () => {
const res = new HashSet([
{ a: 1, foobar: "hello" },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.has({ a: 1 })).toBe(true);
res.add({ a: 1, foobar: "goodbye" });
expect(res.has({ a: 1 })).toBe(true);
});
it("clear should work as expected", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.size).toBe(4);
res.clear();
expect(res.size).toBe(0);
});
it("replace should work as expected", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.size).toBe(4);
res.replace([{ a: 13 }]);
expect(res.size).toBe(1);
expect(res.has({ a: 1 })).toBe(false);
expect(res.has({ a: 13 })).toBe(true);
});
it("toJSON should work as expected", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
expect(res.toJSON()).toStrictEqual([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
]);
});
it("values should work as expected", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
const iter = res.values();
expect(iter.next()).toStrictEqual({
value: { a: 1 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 2 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 3 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 4 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: undefined,
done: true,
});
});
it("keys should work as expected", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
const iter = res.keys();
expect(iter.next()).toStrictEqual({
value: { a: 1 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 2 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 3 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: { a: 4 },
done: false,
});
expect(iter.next()).toStrictEqual({
value: undefined,
done: true,
});
});
it("entries should work as expected", () => {
const res = new HashSet([
{ a: 1 },
{ a: 2 },
{ a: 3 },
{ a: 4 },
], item => item.a.toString());
const iter = res.entries();
expect(iter.next()).toStrictEqual({
value: [{ a: 1 }, { a: 1 }],
done: false,
});
expect(iter.next()).toStrictEqual({
value: [{ a: 2 }, { a: 2 }],
done: false,
});
expect(iter.next()).toStrictEqual({
value: [{ a: 3 }, { a: 3 }],
done: false,
});
expect(iter.next()).toStrictEqual({
value: [{ a: 4 }, { a: 4 }],
done: false,
});
expect(iter.next()).toStrictEqual({
value: undefined,
done: true,
});
});
}); | the_stack |
import { GraphQLInterfaceType, GraphQLObjectType } from './graphql';
import { isObject, isString, isFunction } from './utils/is';
import { resolveMaybeThunk, inspect, mapEachKey } from './utils/misc';
import { ObjectTypeComposer } from './ObjectTypeComposer';
import type {
GraphQLFieldConfig,
GraphQLFieldConfigMap,
GraphQLOutputType,
GraphQLInputObjectType,
GraphQLInputType,
GraphQLResolveInfo,
GraphQLTypeResolver,
} from './graphql';
import { InputTypeComposer } from './InputTypeComposer';
import { UnionTypeComposer } from './UnionTypeComposer';
import { EnumTypeComposer } from './EnumTypeComposer';
import type { TypeAsString, TypeDefinitionString } from './TypeMapper';
import { SchemaComposer } from './SchemaComposer';
import type {
ObjectTypeComposerFieldConfigMap,
ObjectTypeComposerFieldConfig,
ObjectTypeComposerFieldConfigDefinition,
ObjectTypeComposerFieldConfigAsObjectDefinition,
ObjectTypeComposerFieldConfigMapDefinition,
ObjectTypeComposerArgumentConfigMapDefinition,
ObjectTypeComposerArgumentConfig,
ObjectTypeComposerArgumentConfigDefinition,
ObjectTypeComposerArgumentConfigMap,
} from './ObjectTypeComposer';
import { ListComposer } from './ListComposer';
import { NonNullComposer } from './NonNullComposer';
import { ThunkComposer } from './ThunkComposer';
import type {
Thunk,
Extensions,
MaybePromise,
DirectiveArgs,
Directive,
ThunkWithSchemaComposer,
} from './utils/definitions';
import { toInputObjectType } from './utils/toInputType';
import type { ToInputTypeOpts } from './utils/toInputType';
import { typeByPath, TypeInPath } from './utils/typeByPath';
import {
getComposeTypeName,
getGraphQLType,
unwrapOutputTC,
unwrapInputTC,
isTypeNameString,
cloneTypeTo,
NamedTypeComposer,
} from './utils/typeHelpers';
import {
defineFieldMap,
convertObjectFieldMapToConfig,
convertInterfaceArrayAsThunk,
} from './utils/configToDefine';
import { graphqlVersion } from './utils/graphqlVersion';
import type { ComposeNamedInputType, ComposeNamedOutputType } from './utils/typeHelpers';
import { printInterface, SchemaPrinterOptions } from './utils/schemaPrinter';
import { getInterfaceTypeDefinitionNode } from './utils/definitionNode';
import { getSortMethodFromOption } from './utils/schemaPrinterSortTypes';
export type InterfaceTypeComposerDefinition<TSource, TContext> =
| TypeAsString
| TypeDefinitionString
| InterfaceTypeComposerAsObjectDefinition<TSource, TContext>
| GraphQLInterfaceType
| Readonly<InterfaceTypeComposerThunked<any, TContext>>;
export type InterfaceTypeComposerAsObjectDefinition<TSource, TContext> = {
name: string;
fields?: ObjectTypeComposerFieldConfigMapDefinition<TSource, TContext>;
interfaces?: null | ThunkWithSchemaComposer<
ReadonlyArray<InterfaceTypeComposerDefinition<any, TContext>>,
SchemaComposer<TContext>
>;
resolveType?: null | GraphQLTypeResolver<TSource, TContext>;
description?: null | string;
extensions?: Extensions;
directives?: Directive[];
};
export type InterfaceTypeComposerResolversMap<TContext> = Map<
ObjectTypeComposer<any, TContext> | GraphQLObjectType,
InterfaceTypeComposerResolverCheckFn<any, TContext>
>;
export type InterfaceTypeComposerResolverCheckFn<TSource, TContext> = (
value: TSource,
context: TContext,
info: GraphQLResolveInfo
) => MaybePromise<boolean | null | void>;
export type InterfaceTypeComposerThunked<TReturn, TContext> =
| InterfaceTypeComposer<TReturn, TContext>
| ThunkComposer<InterfaceTypeComposer<any, any>, GraphQLInterfaceType>;
/**
* Class that helps to create `GraphQLInterfaceType`s and provide ability to modify them.
*/
export class InterfaceTypeComposer<TSource = any, TContext = any> {
schemaComposer: SchemaComposer<TContext>;
_gqType: GraphQLInterfaceType;
_gqcFields: ObjectTypeComposerFieldConfigMap<TSource, TContext>;
_gqcInputTypeComposer: undefined | InputTypeComposer<TContext>;
_gqcInterfaces: Array<InterfaceTypeComposerThunked<TSource, TContext>> = [];
_gqcTypeResolvers: undefined | InterfaceTypeComposerResolversMap<TContext>;
_gqcFallbackResolveType: ObjectTypeComposer<any, TContext> | GraphQLObjectType | null = null;
_gqcExtensions?: Extensions;
_gqcDirectives?: Directive[];
_gqcIsModified?: boolean;
/**
* Create `InterfaceTypeComposer` with adding it by name to the `SchemaComposer`.
*/
static create<TSrc = any, TCtx = any>(
typeDef: InterfaceTypeComposerDefinition<TSrc, TCtx>,
schemaComposer: SchemaComposer<TCtx>
): InterfaceTypeComposer<TSrc, TCtx> {
if (!(schemaComposer instanceof SchemaComposer)) {
throw new Error(
'You must provide SchemaComposer instance as a second argument for `InterfaceTypeComposer.create(typeDef, schemaComposer)`'
);
}
if (schemaComposer.hasInstance(typeDef, InterfaceTypeComposer)) {
return schemaComposer.getIFTC(typeDef);
}
const iftc = this.createTemp(typeDef, schemaComposer);
schemaComposer.add(iftc);
return iftc;
}
/**
* Create `InterfaceTypeComposer` without adding it to the `SchemaComposer`. This method may be usefull in plugins, when you need to create type temporary.
*/
static createTemp<TSrc = any, TCtx = any>(
typeDef: InterfaceTypeComposerDefinition<TSrc, TCtx>,
schemaComposer?: SchemaComposer<TCtx>
): InterfaceTypeComposer<TSrc, TCtx> {
const sc = schemaComposer || new SchemaComposer();
let IFTC;
if (isString(typeDef)) {
const typeName: string = typeDef;
if (isTypeNameString(typeName)) {
IFTC = new InterfaceTypeComposer(
new GraphQLInterfaceType({
name: typeName,
fields: () => ({}),
}),
sc
);
} else {
IFTC = sc.typeMapper.convertSDLTypeDefinition(typeName);
if (!(IFTC instanceof InterfaceTypeComposer)) {
throw new Error(
'You should provide correct GraphQLInterfaceType type definition. ' +
'Eg. `interface MyType { id: ID!, name: String! }`'
);
}
}
} else if (typeDef instanceof GraphQLInterfaceType) {
IFTC = new InterfaceTypeComposer(typeDef, sc);
} else if (typeDef instanceof InterfaceTypeComposer) {
IFTC = typeDef;
} else if (isObject(typeDef) && !(typeDef instanceof InterfaceTypeComposer)) {
const type = new GraphQLInterfaceType({
...(typeDef as any),
fields: () => ({}),
});
IFTC = new InterfaceTypeComposer(type, sc);
const fields = (typeDef as any).fields;
if (isFunction(fields)) {
// `convertOutputFieldMapToConfig` helps to solve hoisting problems
// rewrap fields `() => { f1: { type: A } }` -> `{ f1: { type: () => A } }`
IFTC.addFields(convertObjectFieldMapToConfig(fields, sc));
} else if (isObject(fields)) {
IFTC.addFields(fields);
}
const interfaces = (typeDef as any).interfaces;
if (Array.isArray(interfaces)) IFTC.setInterfaces(interfaces);
else if (isFunction(interfaces)) {
// rewrap interfaces `() => [i1, i2]` -> `[()=>i1, ()=>i2]`
// helps to solve hoisting problems
IFTC.setInterfaces(convertInterfaceArrayAsThunk(interfaces, sc));
}
IFTC.setExtensions((typeDef as any).extensions);
if (Array.isArray((typeDef as any)?.directives)) {
IFTC.setDirectives((typeDef as any).directives);
}
} else {
throw new Error(
`You should provide GraphQLInterfaceTypeConfig or string with interface name or SDL definition. Provided:\n${inspect(
typeDef
)}`
);
}
return IFTC;
}
constructor(graphqlType: GraphQLInterfaceType, schemaComposer: SchemaComposer<TContext>) {
if (!(schemaComposer instanceof SchemaComposer)) {
throw new Error(
'You must provide SchemaComposer instance as a second argument for `new InterfaceTypeComposer(GraphQLInterfaceType, SchemaComposer)`'
);
}
if (!(graphqlType instanceof GraphQLInterfaceType)) {
throw new Error('InterfaceTypeComposer accept only GraphQLInterfaceType in constructor');
}
this.schemaComposer = schemaComposer;
this._gqType = graphqlType;
// add itself to TypeStorage on create
// it avoids recursive type use errors
this.schemaComposer.set(graphqlType, this);
this.schemaComposer.set(graphqlType.name, this);
if (graphqlVersion >= 15) {
this._gqcFields = convertObjectFieldMapToConfig(
(this._gqType as any)._fields,
this.schemaComposer
);
this._gqcInterfaces = convertInterfaceArrayAsThunk(
(this._gqType as any)._interfaces,
this.schemaComposer
);
} else if (graphqlVersion >= 14) {
this._gqcFields = convertObjectFieldMapToConfig(
(this._gqType as any)._fields,
this.schemaComposer
);
} else {
// read
const fields: Thunk<GraphQLFieldConfigMap<any, TContext>> = (this._gqType as any)._typeConfig
.fields;
this._gqcFields = this.schemaComposer.typeMapper.convertOutputFieldConfigMap(
(resolveMaybeThunk(fields) as any) || {},
this.getTypeName()
);
}
if (!this._gqType.astNode) {
this._gqType.astNode = getInterfaceTypeDefinitionNode(this);
}
this._gqcIsModified = false;
}
// -----------------------------------------------
// Field methods
// -----------------------------------------------
getFields(): ObjectTypeComposerFieldConfigMap<TSource, TContext> {
return this._gqcFields;
}
getFieldNames(): string[] {
return Object.keys(this._gqcFields);
}
getField(fieldName: string): ObjectTypeComposerFieldConfig<TSource, TContext> {
// If FieldConfig is a Thunk then unwrap it on first read.
// In most cases FieldConfig is an object,
// but for solving hoisting problems it's quite good to wrap it in function.
if (isFunction(this._gqcFields[fieldName])) {
const unwrappedFieldConfig = (this._gqcFields as any)[fieldName](this.schemaComposer);
this.setField(fieldName, unwrappedFieldConfig);
}
const field = this._gqcFields[fieldName];
if (!field) {
throw new Error(
`Cannot get field '${fieldName}' from type '${this.getTypeName()}'. Field does not exist.`
);
}
return field;
}
hasField(fieldName: string): boolean {
return !!this._gqcFields[fieldName];
}
setFields(fields: ObjectTypeComposerFieldConfigMapDefinition<TSource, TContext>): this {
this._gqcFields = {};
Object.keys(fields).forEach((name) => {
this.setField(name, fields[name]);
});
return this;
}
setField(
fieldName: string,
fieldConfig: ObjectTypeComposerFieldConfigDefinition<TSource, TContext>
): this {
(this._gqcFields as any)[fieldName] = isFunction(fieldConfig)
? fieldConfig
: this.schemaComposer.typeMapper.convertOutputFieldConfig(
fieldConfig,
fieldName,
this.getTypeName()
);
this._gqcIsModified = true;
return this;
}
/**
* Add new fields or replace existed in a GraphQL type
*/
addFields(newFields: ObjectTypeComposerFieldConfigMapDefinition<TSource, TContext>): this {
Object.keys(newFields).forEach((name) => {
this.setField(name, newFields[name]);
});
return this;
}
/**
* Remove fields from type by name or array of names.
* You also may pass name in dot-notation, in such case will be removed nested field.
*
* @example
* removeField('field1'); // remove 1 field
* removeField(['field1', 'field2']); // remove 2 fields
* removeField('field1.subField1'); // remove 1 nested field
*/
removeField(fieldNameOrArray: string | string[]): this {
const fieldNames = Array.isArray(fieldNameOrArray) ? fieldNameOrArray : [fieldNameOrArray];
fieldNames.forEach((fieldName) => {
const names = fieldName.split('.');
const name = names.shift();
if (!name) return;
if (names.length === 0) {
// single field
delete this._gqcFields[name];
this._gqcIsModified = true;
} else {
// nested field
// eslint-disable-next-line no-lonely-if
if (this.hasField(name)) {
const subTC = this.getFieldTC(name);
if (subTC instanceof ObjectTypeComposer || subTC instanceof EnumTypeComposer) {
subTC.removeField(names.join('.'));
}
}
}
});
return this;
}
removeOtherFields(fieldNameOrArray: string | string[]): this {
const keepFieldNames = Array.isArray(fieldNameOrArray) ? fieldNameOrArray : [fieldNameOrArray];
Object.keys(this._gqcFields).forEach((fieldName) => {
if (keepFieldNames.indexOf(fieldName) === -1) {
delete this._gqcFields[fieldName];
this._gqcIsModified = true;
}
});
return this;
}
reorderFields(names: string[]): this {
const orderedFields = {} as ObjectTypeComposerFieldConfigMap<TSource, TContext>;
const fields = this._gqcFields;
names.forEach((name) => {
if (fields[name]) {
orderedFields[name] = fields[name];
delete fields[name];
}
});
this._gqcFields = { ...orderedFields, ...fields };
this._gqcIsModified = true;
return this;
}
extendField(
fieldName: string,
partialFieldConfig: Partial<ObjectTypeComposerFieldConfigAsObjectDefinition<TSource, TContext>>
): this {
let prevFieldConfig;
try {
prevFieldConfig = this.getField(fieldName);
} catch (e) {
throw new Error(
`Cannot extend field '${fieldName}' from type '${this.getTypeName()}'. Field does not exist.`
);
}
this.setField(fieldName, {
...prevFieldConfig,
...partialFieldConfig,
extensions: {
...(prevFieldConfig.extensions || {}),
...(partialFieldConfig.extensions || {}),
},
directives: [...(prevFieldConfig.directives || []), ...(partialFieldConfig.directives || [])],
});
return this;
}
getFieldConfig(fieldName: string): GraphQLFieldConfig<TSource, TContext> {
const { type, args, ...rest } = this.getField(fieldName);
return {
type: type.getType(),
args:
args &&
mapEachKey(args, (ac) => ({
...ac,
type: ac.type.getType(),
})),
...rest,
};
}
getFieldType(fieldName: string): GraphQLOutputType {
return this.getField(fieldName).type.getType();
}
getFieldTypeName(fieldName: string): string {
return this.getField(fieldName).type.getTypeName();
}
/**
* Automatically unwrap from List, NonNull, ThunkComposer
* It's important! Cause greatly helps to modify fields types in a real code
* without manual unwrap writing.
*
* If you need to work with wrappers, you may use the following code:
* - `TC.getField().type` // returns real wrapped TypeComposer
* - `TC.isFieldNonNull()` // checks is field NonNull or not
* - `TC.makeFieldNonNull()` // for wrapping in NonNullComposer
* - `TC.makeFieldNullable()` // for unwrapping from NonNullComposer
* - `TC.isFieldPlural()` // checks is field wrapped in ListComposer or not
* - `TC.makeFieldPlural()` // for wrapping in ListComposer
* - `TC.makeFieldNonPlural()` // for unwrapping from ListComposer
*/
getFieldTC(fieldName: string): ComposeNamedOutputType<TContext> {
const anyTC = this.getField(fieldName).type;
return unwrapOutputTC(anyTC);
}
/**
* Alias for `getFieldTC()` but returns statically checked ObjectTypeComposer.
* If field have other type then error will be thrown.
*/
getFieldOTC(fieldName: string): ObjectTypeComposer<TSource, TContext> {
const tc = this.getFieldTC(fieldName);
if (!(tc instanceof ObjectTypeComposer)) {
throw new Error(
`${this.getTypeName()}.getFieldOTC('${fieldName}') must be ObjectTypeComposer, but received ${
tc.constructor.name
}. Maybe you need to use 'getFieldTC()' method which returns any type composer?`
);
}
return tc;
}
isFieldNonNull(fieldName: string): boolean {
return this.getField(fieldName).type instanceof NonNullComposer;
}
makeFieldNonNull(fieldNameOrArray: string | string[]): this {
const fieldNames = Array.isArray(fieldNameOrArray) ? fieldNameOrArray : [fieldNameOrArray];
fieldNames.forEach((fieldName) => {
const fc = this._gqcFields[fieldName];
if (fc && !(fc.type instanceof NonNullComposer)) {
fc.type = new NonNullComposer(fc.type);
this._gqcIsModified = true;
}
});
return this;
}
makeFieldNullable(fieldNameOrArray: string | string[]): this {
const fieldNames = Array.isArray(fieldNameOrArray) ? fieldNameOrArray : [fieldNameOrArray];
fieldNames.forEach((fieldName) => {
const fc = this._gqcFields[fieldName];
if (fc && fc.type instanceof NonNullComposer) {
fc.type = fc.type.ofType;
this._gqcIsModified = true;
}
});
return this;
}
isFieldPlural(fieldName: string): boolean {
const type = this.getField(fieldName).type;
return (
type instanceof ListComposer ||
(type instanceof NonNullComposer && type.ofType instanceof ListComposer)
);
}
makeFieldPlural(fieldNameOrArray: string | string[]): this {
const fieldNames = Array.isArray(fieldNameOrArray) ? fieldNameOrArray : [fieldNameOrArray];
fieldNames.forEach((fieldName) => {
const fc = this._gqcFields[fieldName];
if (fc && !(fc.type instanceof ListComposer)) {
fc.type = new ListComposer(fc.type);
this._gqcIsModified = true;
}
});
return this;
}
makeFieldNonPlural(fieldNameOrArray: string | string[]): this {
const fieldNames = Array.isArray(fieldNameOrArray) ? fieldNameOrArray : [fieldNameOrArray];
fieldNames.forEach((fieldName) => {
const fc = this._gqcFields[fieldName];
if (fc) {
if (fc.type instanceof ListComposer) {
fc.type = fc.type.ofType;
this._gqcIsModified = true;
} else if (fc.type instanceof NonNullComposer && fc.type.ofType instanceof ListComposer) {
fc.type =
fc.type.ofType.ofType instanceof NonNullComposer
? fc.type.ofType.ofType
: new NonNullComposer(fc.type.ofType.ofType);
this._gqcIsModified = true;
}
}
});
return this;
}
deprecateFields(fields: { [fieldName: string]: string } | string[] | string): this {
const existedFieldNames = this.getFieldNames();
if (typeof fields === 'string') {
if (existedFieldNames.indexOf(fields) === -1) {
throw new Error(
`Cannot deprecate non-existent field '${fields}' from interface type '${this.getTypeName()}'`
);
}
this.extendField(fields, { deprecationReason: 'deprecated' });
} else if (Array.isArray(fields)) {
fields.forEach((field) => {
if (existedFieldNames.indexOf(field) === -1) {
throw new Error(
`Cannot deprecate non-existent field '${field}' from interface type '${this.getTypeName()}'`
);
}
this.extendField(field, { deprecationReason: 'deprecated' });
});
} else {
const fieldMap = fields;
Object.keys(fieldMap).forEach((field) => {
if (existedFieldNames.indexOf(field) === -1) {
throw new Error(
`Cannot deprecate non-existent field '${field}' from interface type '${this.getTypeName()}'`
);
}
const deprecationReason: string = fieldMap[field];
this.extendField(field, { deprecationReason });
});
}
return this;
}
getFieldArgs<TArgs = any>(fieldName: string): ObjectTypeComposerArgumentConfigMap<TArgs> {
try {
const fc = this.getField(fieldName);
return fc.args || {};
} catch (e) {
throw new Error(
`Cannot get field args. Field '${fieldName}' from type '${this.getTypeName()}' does not exist.`
);
}
}
getFieldArgNames(fieldName: string): string[] {
return Object.keys(this.getFieldArgs(fieldName));
}
hasFieldArg(fieldName: string, argName: string): boolean {
try {
const fieldArgs = this.getFieldArgs(fieldName);
return !!fieldArgs[argName];
} catch (e) {
return false;
}
}
getFieldArg(fieldName: string, argName: string): ObjectTypeComposerArgumentConfig {
const fieldArgs = this.getFieldArgs(fieldName);
const arg = fieldArgs[argName];
if (!arg) {
throw new Error(
`Cannot get '${this.getTypeName()}.${fieldName}@${argName}'. Argument does not exist.`
);
}
return arg;
}
getFieldArgType(fieldName: string, argName: string): GraphQLInputType {
const ac = this.getFieldArg(fieldName, argName);
return ac.type.getType();
}
getFieldArgTypeName(fieldName: string, argName: string): string {
const ac = this.getFieldArg(fieldName, argName);
return ac.type.getTypeName();
}
/**
* Automatically unwrap from List, NonNull, ThunkComposer
* It's important! Cause greatly helps to modify args types in a real code
* without manual unwrap writing.
*
* If you need to work with wrappers, you may use the following code:
* `isFieldArgPlural()` – checks is arg wrapped in ListComposer or not
* `makeFieldArgPlural()` – for arg wrapping in ListComposer
* `makeFieldArgNonPlural()` – for arg unwrapping from ListComposer
* `isFieldArgNonNull()` – checks is arg wrapped in NonNullComposer or not
* `makeFieldArgNonNull()` – for arg wrapping in NonNullComposer
* `makeFieldArgNullable()` – for arg unwrapping from NonNullComposer
*/
getFieldArgTC(fieldName: string, argName: string): ComposeNamedInputType<TContext> {
const anyTC = this.getFieldArg(fieldName, argName).type;
return unwrapInputTC(anyTC);
}
/**
* Alias for `getFieldArgTC()` but returns statically checked InputTypeComposer.
* If field have other type then error will be thrown.
*/
getFieldArgITC(fieldName: string, argName: string): InputTypeComposer<TContext> {
const tc = this.getFieldArgTC(fieldName, argName);
if (!(tc instanceof InputTypeComposer)) {
throw new Error(
`${this.getTypeName()}.getFieldArgITC('${fieldName}', '${argName}') must be InputTypeComposer, but received ${
tc.constructor.name
}. Maybe you need to use 'getFieldArgTC()' method which returns any type composer?`
);
}
return tc;
}
setFieldArgs(fieldName: string, args: ObjectTypeComposerArgumentConfigMapDefinition<any>): this {
const fc = this.getField(fieldName);
fc.args = this.schemaComposer.typeMapper.convertArgConfigMap(
args,
fieldName,
this.getTypeName()
);
this._gqcIsModified = true;
return this;
}
addFieldArgs(
fieldName: string,
newArgs: ObjectTypeComposerArgumentConfigMapDefinition<any>
): this {
const fc = this.getField(fieldName);
fc.args = {
...fc.args,
...this.schemaComposer.typeMapper.convertArgConfigMap(newArgs, fieldName, this.getTypeName()),
};
this._gqcIsModified = true;
return this;
}
setFieldArg(
fieldName: string,
argName: string,
argConfig: ObjectTypeComposerArgumentConfigDefinition
): this {
const fc = this.getField(fieldName);
fc.args = fc.args || {};
fc.args[argName] = this.schemaComposer.typeMapper.convertArgConfig(
argConfig,
argName,
fieldName,
this.getTypeName()
);
this._gqcIsModified = true;
return this;
}
isFieldArgPlural(fieldName: string, argName: string): boolean {
const type = this.getFieldArg(fieldName, argName).type;
return (
type instanceof ListComposer ||
(type instanceof NonNullComposer && type.ofType instanceof ListComposer)
);
}
makeFieldArgPlural(fieldName: string, argNameOrArray: string | string[]): this {
const args = this.getField(fieldName).args;
if (!args) return this;
const argNames = Array.isArray(argNameOrArray) ? argNameOrArray : [argNameOrArray];
argNames.forEach((argName) => {
const ac = args[argName];
if (ac && !(ac.type instanceof ListComposer)) {
ac.type = new ListComposer(ac.type);
this._gqcIsModified = true;
}
});
return this;
}
makeFieldArgNonPlural(fieldName: string, argNameOrArray: string | string[]): this {
const args = this.getField(fieldName).args;
if (!args) return this;
const argNames = Array.isArray(argNameOrArray) ? argNameOrArray : [argNameOrArray];
argNames.forEach((argName) => {
const ac = args[argName];
if (ac) {
if (ac.type instanceof ListComposer) {
ac.type = ac.type.ofType;
this._gqcIsModified = true;
} else if (ac.type instanceof NonNullComposer && ac.type.ofType instanceof ListComposer) {
ac.type =
ac.type.ofType.ofType instanceof NonNullComposer
? ac.type.ofType.ofType
: new NonNullComposer(ac.type.ofType.ofType);
this._gqcIsModified = true;
}
}
});
return this;
}
isFieldArgNonNull(fieldName: string, argName: string): boolean {
const type = this.getFieldArg(fieldName, argName).type;
return type instanceof NonNullComposer;
}
makeFieldArgNonNull(fieldName: string, argNameOrArray: string | string[]): this {
const args = this.getField(fieldName).args;
if (!args) return this;
const argNames = Array.isArray(argNameOrArray) ? argNameOrArray : [argNameOrArray];
argNames.forEach((argName) => {
const ac = args[argName];
if (ac && !(ac.type instanceof NonNullComposer)) {
ac.type = new NonNullComposer(ac.type);
this._gqcIsModified = true;
}
});
return this;
}
makeFieldArgNullable(fieldName: string, argNameOrArray: string | string[]): this {
const args = this.getField(fieldName).args;
if (!args) return this;
const argNames = Array.isArray(argNameOrArray) ? argNameOrArray : [argNameOrArray];
argNames.forEach((argName) => {
const ac = args[argName];
if (ac && ac.type instanceof NonNullComposer) {
ac.type = ac.type.ofType;
this._gqcIsModified = true;
}
});
return this;
}
// -----------------------------------------------
// Type methods
// -----------------------------------------------
getType(): GraphQLInterfaceType {
if (this._gqcIsModified) {
this._gqcIsModified = false;
this._gqType.astNode = getInterfaceTypeDefinitionNode(this);
if (graphqlVersion >= 15) {
(this._gqType as any)._fields = () =>
defineFieldMap(
this._gqType,
mapEachKey(this._gqcFields, (_, name) => this.getFieldConfig(name)),
this._gqType.astNode
);
(this._gqType as any)._interfaces = () => this.getInterfacesTypes();
} else if (graphqlVersion >= 14) {
(this._gqType as any)._fields = () =>
defineFieldMap(
this._gqType,
mapEachKey(this._gqcFields, (_, name) => this.getFieldConfig(name)),
this._gqType.astNode
);
} else {
(this._gqType as any)._typeConfig.fields = () => {
return mapEachKey(this._gqcFields, (_, name) => this.getFieldConfig(name));
};
(this._gqType as any)._fields = {}; // clear builded fields in type
}
}
return this._gqType;
}
getTypePlural(): ListComposer<InterfaceTypeComposer<TSource, TContext>> {
return new ListComposer(this);
}
getTypeNonNull(): NonNullComposer<InterfaceTypeComposer<TSource, TContext>> {
return new NonNullComposer(this);
}
/**
* Get Type wrapped in List modifier
*
* @example
* const UserTC = schemaComposer.createInterfaceTC(`interface UserIface { name: String }`);
* schemaComposer.Query.addFields({
* users1: { type: UserTC.List }, // in SDL: users1: [UserIface]
* users2: { type: UserTC.NonNull.List }, // in SDL: users2: [UserIface!]
* users3: { type: UserTC.NonNull.List.NonNull }, // in SDL: users2: [UserIface!]!
* })
*/
get List(): ListComposer<InterfaceTypeComposer<TSource, TContext>> {
return new ListComposer(this);
}
/**
* Get Type wrapped in NonNull modifier
*
* @example
* const UserTC = schemaComposer.createInterfaceTC(`interface UserIface { name: String }`);
* schemaComposer.Query.addFields({
* users1: { type: UserTC.List }, // in SDL: users1: [UserIface]
* users2: { type: UserTC.NonNull.List }, // in SDL: users2: [UserIface!]!
* users3: { type: UserTC.NonNull.List.NonNull }, // in SDL: users2: [UserIface!]!
* })
*/
get NonNull(): NonNullComposer<InterfaceTypeComposer<TSource, TContext>> {
return new NonNullComposer(this);
}
getTypeName(): string {
return this._gqType.name;
}
setTypeName(name: string): this {
this._gqType.name = name;
this._gqcIsModified = true;
this.schemaComposer.add(this);
return this;
}
getDescription(): string {
return this._gqType.description || '';
}
setDescription(description: string): this {
this._gqType.description = description;
this._gqcIsModified = true;
return this;
}
/**
* You may clone this type with a new provided name as string.
* Or you may provide a new TypeComposer which will get all cloned
* settings from this type.
*/
clone(
newTypeNameOrTC: string | InterfaceTypeComposer<any, any>
): InterfaceTypeComposer<TSource, TContext> {
if (!newTypeNameOrTC) {
throw new Error('You should provide newTypeName:string for InterfaceTypeComposer.clone()');
}
const cloned =
newTypeNameOrTC instanceof InterfaceTypeComposer
? newTypeNameOrTC
: InterfaceTypeComposer.create(newTypeNameOrTC, this.schemaComposer);
cloned._gqcFields = mapEachKey(this._gqcFields, (fieldConfig) => ({
...fieldConfig,
args: mapEachKey(fieldConfig.args, (argConfig) => ({
...argConfig,
extensions: { ...argConfig.extensions },
directives: [...(argConfig.directives || [])],
})),
extensions: { ...fieldConfig.extensions },
directives: [...(fieldConfig.directives || [])],
}));
cloned._gqcInterfaces = [...this._gqcInterfaces];
if (this._gqcTypeResolvers) {
cloned._gqcTypeResolvers = new Map(this._gqcTypeResolvers);
}
cloned._gqcFallbackResolveType = this._gqcFallbackResolveType;
cloned._gqcExtensions = { ...this._gqcExtensions };
cloned.setDescription(this.getDescription());
cloned.setDirectives(this.getDirectives());
return cloned;
}
/**
* Clone this type to another SchemaComposer.
* Also will be cloned all sub-types.
*/
cloneTo(
anotherSchemaComposer: SchemaComposer<any>,
cloneMap: Map<any, any> = new Map()
): InterfaceTypeComposer<any, any> {
if (!anotherSchemaComposer) {
throw new Error('You should provide SchemaComposer for InterfaceTypeComposer.cloneTo()');
}
if (cloneMap.has(this)) return cloneMap.get(this) as any;
const cloned = InterfaceTypeComposer.create(this.getTypeName(), anotherSchemaComposer);
cloneMap.set(this, cloned);
cloned._gqcFields = mapEachKey(this._gqcFields, (fieldConfig) => ({
...fieldConfig,
type: cloneTypeTo(fieldConfig.type, anotherSchemaComposer, cloneMap),
args: mapEachKey(fieldConfig.args, (argConfig) => ({
...argConfig,
type: cloneTypeTo(argConfig.type, anotherSchemaComposer, cloneMap),
extensions: { ...argConfig.extensions },
directives: [...(argConfig.directives || [])],
})),
extensions: { ...fieldConfig.extensions },
directives: [...(fieldConfig.directives || [])],
})) as any;
cloned._gqcInterfaces = this._gqcInterfaces.map((i) =>
i.cloneTo(anotherSchemaComposer, cloneMap)
) as any;
cloned._gqcExtensions = { ...this._gqcExtensions };
cloned.setDescription(this.getDescription());
// clone this._gqcTypeResolvers
const typeResolversMap = this.getTypeResolvers();
if (typeResolversMap.size > 0) {
const clonedTypeResolvers: InterfaceTypeComposerResolversMap<any> = new Map();
typeResolversMap.forEach((fn, tc) => {
const clonedTC = cloneTypeTo(tc, anotherSchemaComposer, cloneMap) as
| ObjectTypeComposer<any, any>
| GraphQLObjectType;
clonedTypeResolvers.set(clonedTC, fn);
});
cloned.setTypeResolvers(clonedTypeResolvers);
}
if (this._gqcFallbackResolveType) {
cloned._gqcFallbackResolveType = cloneTypeTo(
this._gqcFallbackResolveType,
anotherSchemaComposer,
cloneMap
) as any;
}
return cloned;
}
merge(
type:
| GraphQLInterfaceType
| GraphQLObjectType
| InterfaceTypeComposer<any, any>
| ObjectTypeComposer<any, any>
): this {
let tc: ObjectTypeComposer | InterfaceTypeComposer;
if (type instanceof ObjectTypeComposer || type instanceof InterfaceTypeComposer) {
tc = type;
} else if (type instanceof GraphQLObjectType) {
tc = ObjectTypeComposer.createTemp(type, this.schemaComposer);
} else if (type instanceof GraphQLInterfaceType) {
tc = InterfaceTypeComposer.createTemp(type, this.schemaComposer);
} else {
throw new Error(
`Cannot merge ${inspect(
type
)} with InterfaceType(${this.getTypeName()}). Provided type should be GraphQLInterfaceType, GraphQLObjectType, InterfaceTypeComposer or ObjectTypeComposer.`
);
}
// deep clone all fields with args
const fields = { ...tc.getFields() } as ObjectTypeComposerFieldConfigMapDefinition<any, any>;
Object.keys(fields).forEach((fieldName) => {
fields[fieldName] = {
...(fields as any)[fieldName],
args: {
...(fields as any)[fieldName].args,
},
// set type as SDL string, it automatically will be remapped to the correct type instance in the current schema
type: tc.getFieldTypeName(fieldName),
};
tc.getFieldArgNames(fieldName).forEach((argName) => {
(fields as any)[fieldName].args[argName] = {
...(fields as any)[fieldName].args[argName],
// set type as SDL string, it automatically will be remapped to the correct type instance in the current schema
type: tc.getFieldArgTypeName(fieldName, argName),
};
});
});
this.addFields(fields);
// set interfaces as SDL string, it automatically will be remapped to the correct type instance in the current schema
this.addInterfaces(tc.getInterfaces().map((i) => i.getTypeName()));
// Feel free to add other properties for merging two TypeComposers.
// For simplicity it just merge fields and interfaces.
return this;
}
// -----------------------------------------------
// InputType methods
// -----------------------------------------------
getInputType(): GraphQLInputObjectType {
return this.getInputTypeComposer().getType();
}
hasInputTypeComposer(): boolean {
return !!this._gqcInputTypeComposer;
}
setInputTypeComposer(itc: InputTypeComposer<TContext>): this {
this._gqcInputTypeComposer = itc;
return this;
}
getInputTypeComposer(opts?: ToInputTypeOpts): InputTypeComposer<TContext> {
if (!this._gqcInputTypeComposer) {
this._gqcInputTypeComposer = toInputObjectType(this, opts);
}
return this._gqcInputTypeComposer;
}
/**
* An alias for `getInputTypeComposer()`
*/
getITC(opts?: ToInputTypeOpts): InputTypeComposer<TContext> {
return this.getInputTypeComposer(opts);
}
removeInputTypeComposer(): this {
this._gqcInputTypeComposer = undefined;
return this;
}
// -----------------------------------------------
// ResolveType methods
// -----------------------------------------------
getResolveType(): GraphQLTypeResolver<TSource, TContext> | undefined | null {
return this._gqType.resolveType;
}
setResolveType(fn: GraphQLTypeResolver<TSource, TContext> | undefined | null): this {
this._gqType.resolveType = fn;
this._gqcIsModified = true;
return this;
}
hasTypeResolver(type: ObjectTypeComposer<any, TContext> | GraphQLObjectType): boolean {
const typeResolversMap = this.getTypeResolvers();
return typeResolversMap.has(type);
}
getTypeResolvers(): InterfaceTypeComposerResolversMap<TContext> {
if (!this._gqcTypeResolvers) {
this._gqcTypeResolvers = new Map();
}
return this._gqcTypeResolvers;
}
getTypeResolverCheckFn(
type: ObjectTypeComposer<any, TContext> | GraphQLObjectType
): InterfaceTypeComposerResolverCheckFn<TSource, TContext> {
const typeResolversMap = this.getTypeResolvers();
if (!typeResolversMap.has(type)) {
throw new Error(
`Type resolve function in interface '${this.getTypeName()}' is not defined for type ${inspect(
type
)}.`
);
}
return typeResolversMap.get(type) as any;
}
getTypeResolverNames(): string[] {
const typeResolversMap = this.getTypeResolvers();
const names = [] as string[];
typeResolversMap.forEach((_, composeType) => {
if (composeType instanceof ObjectTypeComposer) {
names.push(composeType.getTypeName());
} else if (composeType && composeType.name) {
names.push(composeType.name);
}
});
return names;
}
getTypeResolverTypes(): GraphQLObjectType[] {
const typeResolversMap = this.getTypeResolvers();
const types = [] as GraphQLObjectType[];
typeResolversMap.forEach((_, composeType) => {
types.push(getGraphQLType(composeType) as GraphQLObjectType);
});
return types;
}
setTypeResolvers(typeResolversMap: InterfaceTypeComposerResolversMap<TContext>): this {
this._isTypeResolversValid(typeResolversMap);
this._gqcTypeResolvers = typeResolversMap;
this._initResolveTypeFn();
return this;
}
_initResolveTypeFn(): this {
const typeResolversMap = this._gqcTypeResolvers || new Map();
const fallbackType = this._gqcFallbackResolveType
? (getGraphQLType(this._gqcFallbackResolveType) as GraphQLObjectType)
: null;
// extract GraphQLObjectType from ObjectTypeComposer
const fastEntries = [] as Array<[any, InterfaceTypeComposerResolverCheckFn<any, any>]>;
if (graphqlVersion >= 16) {
for (const [composeType, checkFn] of typeResolversMap.entries()) {
// [string, InterfaceTypeComposerResolverCheckFn<any, any>]
fastEntries.push([getComposeTypeName(composeType, this.schemaComposer), checkFn]);
}
} else {
for (const [composeType, checkFn] of typeResolversMap.entries()) {
// [GraphQLObjectType, InterfaceTypeComposerResolverCheckFn<any, any>]
fastEntries.push([getGraphQLType(composeType) as GraphQLObjectType, checkFn]);
}
}
let resolveType: GraphQLTypeResolver<TSource, TContext>;
const isAsyncRuntime = this._isTypeResolversAsync(typeResolversMap);
if (isAsyncRuntime) {
resolveType = async (value, context, info) => {
for (const [_gqType, checkFn] of fastEntries) {
// should we run checkFn simultaneously or in serial?
// Current decision is: don't SPIKE event loop - run in serial (it may be changed in future)
// eslint-disable-next-line no-await-in-loop
if (await checkFn(value, context, info)) return _gqType;
}
return fallbackType;
};
} else {
resolveType = (value: any, context, info) => {
for (const [_gqType, checkFn] of fastEntries) {
if (checkFn(value, context, info)) return _gqType;
}
return fallbackType;
};
}
this.setResolveType(resolveType);
return this;
}
_isTypeResolversValid(typeResolversMap: InterfaceTypeComposerResolversMap<TContext>): true {
if (!(typeResolversMap instanceof Map)) {
throw new Error(
`For interface ${this.getTypeName()} you should provide Map object for type resolvers.`
);
}
for (const [composeType, checkFn] of typeResolversMap.entries()) {
this._isTypeResolverValid(composeType, checkFn);
}
return true;
}
_isTypeResolverValid(
composeType: ObjectTypeComposer<any, TContext> | GraphQLObjectType,
checkFn: InterfaceTypeComposerResolverCheckFn<any, TContext>
): true {
// checking composeType
try {
const type = getGraphQLType(composeType);
if (!(type instanceof GraphQLObjectType)) throw new Error('Must be GraphQLObjectType');
} catch (e) {
throw new Error(
`For interface type resolver ${this.getTypeName()} you must provide GraphQLObjectType or ObjectTypeComposer, but provided ${inspect(
composeType
)}`
);
}
// checking checkFn
if (!isFunction(checkFn)) {
throw new Error(
`Interface ${this.getTypeName()} has invalid check function for type ${inspect(
composeType
)}`
);
}
return true;
}
// eslint-disable-next-line class-methods-use-this
_isTypeResolversAsync(typeResolversMap: InterfaceTypeComposerResolversMap<TContext>): boolean {
let res = false;
for (const [, checkFn] of typeResolversMap.entries()) {
try {
const r = checkFn({} as any, {} as any, {} as any);
if (r instanceof Promise) {
r.catch(() => {});
res = true;
}
} catch (e) {
// noop
}
}
return res;
}
addTypeResolver<TSrc>(
type: ObjectTypeComposer<TSrc, TContext> | GraphQLObjectType,
checkFn: InterfaceTypeComposerResolverCheckFn<TSrc, TContext>
): this {
const typeResolversMap = this.getTypeResolvers();
this._isTypeResolverValid(type, checkFn);
typeResolversMap.set(type, checkFn);
this._initResolveTypeFn();
// ensure that interface added to ObjectType
if (type instanceof ObjectTypeComposer) {
type.addInterface(this);
}
// ensure that resolved type will be in Schema
this.schemaComposer.addSchemaMustHaveType(type);
return this;
}
removeTypeResolver(type: ObjectTypeComposer<any, TContext> | GraphQLObjectType): this {
const typeResolversMap = this.getTypeResolvers();
typeResolversMap.delete(type);
this._initResolveTypeFn();
return this;
}
setTypeResolverFallback(
type: ObjectTypeComposer<any, TContext> | GraphQLObjectType | null
): this {
if (type) {
// ensure that interface added to ObjectType
if (type instanceof ObjectTypeComposer) {
type.addInterface(this);
}
// ensure that resolved type will be in Schema
this.schemaComposer.addSchemaMustHaveType(type);
}
this._gqcFallbackResolveType = type;
this._initResolveTypeFn();
return this;
}
// -----------------------------------------------
// Sub-Interface methods
// -----------------------------------------------
getInterfaces(): Array<InterfaceTypeComposerThunked<TSource, TContext>> {
return this._gqcInterfaces;
}
getInterfacesTypes(): Array<GraphQLInterfaceType> {
return this._gqcInterfaces.map((i) => i.getType());
}
setInterfaces(interfaces: ReadonlyArray<InterfaceTypeComposerDefinition<any, TContext>>): this {
this._gqcInterfaces = convertInterfaceArrayAsThunk(interfaces, this.schemaComposer);
this._gqcIsModified = true;
return this;
}
hasInterface(iface: InterfaceTypeComposerDefinition<any, TContext>): boolean {
const typeName = getComposeTypeName(iface, this.schemaComposer);
return !!this._gqcInterfaces.find((i) => i.getTypeName() === typeName);
}
addInterface(
iface:
| InterfaceTypeComposerDefinition<any, TContext>
| InterfaceTypeComposerThunked<any, TContext>
): this {
if (!this.hasInterface(iface)) {
this._gqcInterfaces.push(
this.schemaComposer.typeMapper.convertInterfaceTypeDefinition(iface)
);
this._gqcIsModified = true;
}
return this;
}
addInterfaces(
ifaces: ReadonlyArray<
InterfaceTypeComposerDefinition<any, TContext> | InterfaceTypeComposerThunked<any, TContext>
>
): this {
if (!Array.isArray(ifaces)) {
throw new Error(
`InterfaceTypeComposer[${this.getTypeName()}].addInterfaces() accepts only array`
);
}
ifaces.forEach((iface) => this.addInterface(iface));
return this;
}
removeInterface(iface: InterfaceTypeComposerDefinition<any, TContext>): this {
const typeName = getComposeTypeName(iface, this.schemaComposer);
this._gqcInterfaces = this._gqcInterfaces.filter((i) => i.getTypeName() !== typeName);
this._gqcIsModified = true;
return this;
}
// -----------------------------------------------
// Extensions methods
//
// `Extensions` is a property on type/field/arg definitions to pass private extra metadata.
// It's used only on the server-side with the Code-First approach,
// mostly for 3rd party server middlewares & plugins.
// Property `extensions` may contain private server metadata of any type (even functions)
// and does not available via SDL.
//
// @see https://github.com/graphql/graphql-js/issues/1527
// @note
// If you need to provide public metadata to clients then use `directives` instead.
// -----------------------------------------------
getExtensions(): Extensions {
if (!this._gqcExtensions) {
return {};
} else {
return this._gqcExtensions;
}
}
setExtensions(extensions: Extensions | undefined): this {
this._gqcExtensions = extensions;
this._gqcIsModified = true;
return this;
}
extendExtensions(extensions: Extensions): this {
const current = this.getExtensions();
this.setExtensions({
...current,
...extensions,
});
return this;
}
clearExtensions(): this {
this.setExtensions({});
return this;
}
getExtension(extensionName: string): unknown {
const extensions = this.getExtensions();
return extensions[extensionName];
}
hasExtension(extensionName: string): boolean {
const extensions = this.getExtensions();
return extensionName in extensions;
}
setExtension(extensionName: string, value: unknown): this {
this.extendExtensions({
[extensionName]: value,
});
return this;
}
removeExtension(extensionName: string): this {
const extensions = { ...this.getExtensions() };
delete extensions[extensionName];
this.setExtensions(extensions);
return this;
}
getFieldExtensions(fieldName: string): Extensions {
const field = this.getField(fieldName);
return field.extensions || {};
}
setFieldExtensions(fieldName: string, extensions: Extensions): this {
const field = this.getField(fieldName);
this.setField(fieldName, { ...field, extensions });
return this;
}
extendFieldExtensions(fieldName: string, extensions: Extensions): this {
const current = this.getFieldExtensions(fieldName);
this.setFieldExtensions(fieldName, {
...current,
...extensions,
});
return this;
}
clearFieldExtensions(fieldName: string): this {
this.setFieldExtensions(fieldName, {});
return this;
}
getFieldExtension(fieldName: string, extensionName: string): unknown {
const extensions = this.getFieldExtensions(fieldName);
return extensions[extensionName];
}
hasFieldExtension(fieldName: string, extensionName: string): boolean {
const extensions = this.getFieldExtensions(fieldName);
return extensionName in extensions;
}
setFieldExtension(fieldName: string, extensionName: string, value: unknown): this {
this.extendFieldExtensions(fieldName, {
[extensionName]: value,
});
return this;
}
removeFieldExtension(fieldName: string, extensionName: string): this {
const extensions = { ...this.getFieldExtensions(fieldName) };
delete extensions[extensionName];
this.setFieldExtensions(fieldName, extensions);
return this;
}
getFieldArgExtensions(fieldName: string, argName: string): Extensions {
const ac = this.getFieldArg(fieldName, argName);
return ac.extensions || {};
}
setFieldArgExtensions(fieldName: string, argName: string, extensions: Extensions): this {
const ac = this.getFieldArg(fieldName, argName);
this.setFieldArg(fieldName, argName, { ...ac, extensions });
return this;
}
extendFieldArgExtensions(fieldName: string, argName: string, extensions: Extensions): this {
const current = this.getFieldArgExtensions(fieldName, argName);
this.setFieldArgExtensions(fieldName, argName, {
...current,
...extensions,
});
return this;
}
clearFieldArgExtensions(fieldName: string, argName: string): this {
this.setFieldArgExtensions(fieldName, argName, {});
return this;
}
getFieldArgExtension(fieldName: string, argName: string, extensionName: string): unknown {
const extensions = this.getFieldArgExtensions(fieldName, argName);
return extensions[extensionName];
}
hasFieldArgExtension(fieldName: string, argName: string, extensionName: string): boolean {
const extensions = this.getFieldArgExtensions(fieldName, argName);
return extensionName in extensions;
}
setFieldArgExtension(
fieldName: string,
argName: string,
extensionName: string,
value: unknown
): this {
this.extendFieldArgExtensions(fieldName, argName, {
[extensionName]: value,
});
return this;
}
removeFieldArgExtension(fieldName: string, argName: string, extensionName: string): this {
const extensions = { ...this.getFieldArgExtensions(fieldName, argName) };
delete extensions[extensionName];
this.setFieldArgExtensions(fieldName, argName, extensions);
return this;
}
// -----------------------------------------------
// Directive methods
//
// Directives provide the ability to work with public metadata which is available via SDL.
// Directives can be used on type/field/arg definitions. The most famous directives are
// `@deprecated(reason: "...")` and `@specifiedBy(url: "...")` which are present in GraphQL spec.
// GraphQL spec allows to you add any own directives.
//
// @example
// type Article @directive1 {
// name @directive2
// comments(limit: Int @directive3)
// }
//
// @note
// If you need private metadata then use `extensions` instead.
// -----------------------------------------------
getDirectives(): Array<Directive> {
return this._gqcDirectives || [];
}
setDirectives(directives: Array<Directive>): this {
this._gqcDirectives = directives;
this._gqcIsModified = true;
return this;
}
getDirectiveNames(): string[] {
return this.getDirectives().map((d) => d.name);
}
/**
* Returns arguments of first found directive by name.
* If directive does not exists then will be returned undefined.
*/
getDirectiveByName(directiveName: string): DirectiveArgs | undefined {
const directive = this.getDirectives().find((d) => d.name === directiveName);
if (!directive) return undefined;
return directive.args;
}
/**
* Set arguments of first found directive by name.
* If directive does not exists then will be created new one.
*/
setDirectiveByName(directiveName: string, args?: DirectiveArgs): this {
const directives = this.getDirectives();
const idx = directives.findIndex((d) => d.name === directiveName);
if (idx >= 0) {
directives[idx].args = args;
} else {
directives.push({ name: directiveName, args });
}
this.setDirectives(directives);
return this;
}
getDirectiveById(idx: number): DirectiveArgs | undefined {
const directive = this.getDirectives()[idx];
if (!directive) return undefined;
return directive.args;
}
getFieldDirectives(fieldName: string): Array<Directive> {
return this.getField(fieldName).directives || [];
}
setFieldDirectives(fieldName: string, directives: Array<Directive> | undefined): this {
const fc = this.getField(fieldName);
fc.directives = directives;
this._gqcIsModified = true;
return this;
}
getFieldDirectiveNames(fieldName: string): string[] {
return this.getFieldDirectives(fieldName).map((d) => d.name);
}
/**
* Returns arguments of first found directive by name.
* If directive does not exists then will be returned undefined.
*/
getFieldDirectiveByName(fieldName: string, directiveName: string): DirectiveArgs | undefined {
const directive = this.getFieldDirectives(fieldName).find((d) => d.name === directiveName);
if (!directive) return undefined;
return directive.args;
}
/**
* Set arguments of first found directive by name.
* If directive does not exists then will be created new one.
*/
setFieldDirectiveByName(fieldName: string, directiveName: string, args?: DirectiveArgs): this {
const directives = this.getFieldDirectives(fieldName);
const idx = directives.findIndex((d) => d.name === directiveName);
if (idx >= 0) {
directives[idx].args = args;
} else {
directives.push({ name: directiveName, args });
}
this.setFieldDirectives(fieldName, directives);
return this;
}
getFieldDirectiveById(fieldName: string, idx: number): DirectiveArgs | undefined {
const directive = this.getFieldDirectives(fieldName)[idx];
if (!directive) return undefined;
return directive.args;
}
getFieldArgDirectives(fieldName: string, argName: string): Array<Directive> {
return this.getFieldArg(fieldName, argName).directives || [];
}
setFieldArgDirectives(fieldName: string, argName: string, directives: Array<Directive>): this {
const ac = this.getFieldArg(fieldName, argName);
ac.directives = directives;
this._gqcIsModified = true;
return this;
}
getFieldArgDirectiveNames(fieldName: string, argName: string): string[] {
return this.getFieldArgDirectives(fieldName, argName).map((d) => d.name);
}
/**
* Returns arguments of first found directive by name.
* If directive does not exists then will be returned undefined.
*/
getFieldArgDirectiveByName(
fieldName: string,
argName: string,
directiveName: string
): DirectiveArgs | undefined {
const directive = this.getFieldArgDirectives(fieldName, argName).find(
(d) => d.name === directiveName
);
if (!directive) return undefined;
return directive.args;
}
/**
* Set arguments of first found directive by name.
* If directive does not exists then will be created new one.
*/
setFieldArgDirectiveByName(
fieldName: string,
argName: string,
directiveName: string,
args?: DirectiveArgs
): this {
const directives = this.getFieldArgDirectives(fieldName, argName);
const idx = directives.findIndex((d) => d.name === directiveName);
if (idx >= 0) {
directives[idx].args = args;
} else {
directives.push({ name: directiveName, args });
}
this.setFieldArgDirectives(fieldName, argName, directives);
return this;
}
getFieldArgDirectiveById(
fieldName: string,
argName: string,
idx: number
): DirectiveArgs | undefined {
const directive = this.getFieldArgDirectives(fieldName, argName)[idx];
if (!directive) return undefined;
return directive.args;
}
// -----------------------------------------------
// Misc methods
// -----------------------------------------------
get(path: string | string[]): TypeInPath<TContext> | void {
return typeByPath(this, path);
}
/**
* Returns all types which are used inside the current type
*/
getNestedTCs(
opts: {
exclude?: string[];
} = {},
passedTypes: Set<NamedTypeComposer<any>> = new Set()
): Set<NamedTypeComposer<any>> {
const exclude = Array.isArray(opts.exclude) ? opts.exclude : [];
this.getFieldNames().forEach((fieldName) => {
const tc = this.getFieldTC(fieldName);
if (!passedTypes.has(tc) && !exclude.includes(tc.getTypeName())) {
passedTypes.add(tc);
if (tc instanceof ObjectTypeComposer || tc instanceof UnionTypeComposer) {
tc.getNestedTCs(opts, passedTypes);
}
}
this.getFieldArgNames(fieldName).forEach((argName) => {
const itc = this.getFieldArgTC(fieldName, argName);
if (!passedTypes.has(itc) && !exclude.includes(itc.getTypeName())) {
passedTypes.add(itc);
if (itc instanceof InputTypeComposer) {
itc.getNestedTCs(opts, passedTypes);
}
}
});
this.getInterfaces().forEach((t) => {
const iftc = t instanceof ThunkComposer ? t.ofType : t;
if (!passedTypes.has(iftc) && !exclude.includes(iftc.getTypeName())) {
passedTypes.add(iftc);
iftc.getNestedTCs(opts, passedTypes);
}
});
});
return passedTypes;
}
/**
* Prints SDL for current type. Or print with all used types if `deep: true` option was provided.
*/
toSDL(
opts?: SchemaPrinterOptions & {
deep?: boolean;
exclude?: string[];
}
): string {
const { deep, ...innerOpts } = opts || {};
innerOpts.sortTypes = innerOpts.sortTypes || false;
const exclude = Array.isArray(innerOpts.exclude) ? innerOpts.exclude : [];
if (deep) {
let r = '';
r += printInterface(this.getType(), innerOpts);
const nestedTypes = Array.from(this.getNestedTCs({ exclude }));
const sortMethod = getSortMethodFromOption(innerOpts.sortAll || innerOpts.sortTypes);
if (sortMethod) {
nestedTypes.sort(sortMethod);
}
nestedTypes.forEach((t) => {
if (t !== this && !exclude.includes(t.getTypeName())) {
const sdl = t.toSDL(innerOpts);
if (sdl) r += `\n\n${sdl}`;
}
});
return r;
}
return printInterface(this.getType(), innerOpts);
}
} | the_stack |
import { Link } from '@tamagui/feather-icons'
import NextLink from 'next/link'
import NextRouter from 'next/router'
import rangeParser from 'parse-numeric-range'
import React from 'react'
import { ScrollView } from 'react-native'
import {
Button,
Group,
H1,
H2,
H3,
H4,
H5,
Image,
ImageProps,
Paragraph,
Separator,
Spacer,
Text,
Theme,
XStack,
XStackProps,
YStack,
} from 'tamagui'
import { Frontmatter } from '../frontmatter'
import { BenchmarkChart } from './BenchmarkChart'
import { Code, CodeInline } from './Code'
import * as Demos from './demos'
import { DocCodeBlock } from './DocsCodeBlock'
import { ExternalIcon } from './ExternalIcon'
import { HeroContainer } from './HeroContainer'
import { ExampleAnimations } from './HeroExampleAnimations'
import { Highlights } from './Highlights'
import { HR } from './HR'
import { LI } from './LI'
import { MediaPlayer } from './MediaPlayer'
import { Notice } from './Notice'
import { OffsetBox } from './OffsetBox'
import { Preview } from './Preview'
import { PropsTable } from './PropsTable'
import { SubTitle } from './SubTitle'
import { UL } from './UL'
export const components = {
Spacer,
ExampleAnimations,
ScrollView,
Text,
Paragraph,
OffsetBox,
YStack,
XStack,
BenchmarkChart,
Separator,
Code,
HeroContainer,
...Demos,
Highlights,
PropsTable,
Description: SubTitle,
UL,
LI,
DeployToVercel: () => {
return (
<a
href="https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Ftamagui%2Fstarters&root-directory=next-expo-solito/apps/next&envDescription=Set%20this%20environment%20variable%20to%201%20for%20Turborepo%20to%20cache%20your%20node_modules.&envLink=https%3A%2F%2Ftamagui.dev&project-name=tamagui-app&repo-name=tamagui-app&demo-title=Tamagui%20App%20%E2%9A%A1%EF%B8%8F&demo-description=Tamagui%20React%20Native%20%2B%20Next.js%20starter&demo-url=https%3A%2F%2Ftamagui.dev%2Fstarter&demo-image=https%3A%2F%2Ftamagui.dev%2Fblog%2Fintroducing-tamagui%2Fhero.png"
target="_blank"
>
<img
alt="Deploy with Vercel"
style={{ height: 32, width: 90 }}
src="https://vercel.com/button"
/>
</a>
)
},
Beta: () => (
<Button
accessibilityLabel="Beta blog post"
pe="none"
size="$2"
theme="pink_alt3"
pos="absolute"
t={-15}
r={-75}
rotate="5deg"
>
Beta
</Button>
),
IntroParagraph: ({ children, ...props }) => {
return (
<Paragraph tag="span" size="$5" className="paragraph" display="block" mt="$1" {...props}>
{children}
</Paragraph>
)
},
Note: (props) => (
<YStack
tag="aside"
mt="$5"
mb="$5"
borderRadius="$3"
// & & p
// fontSize: '$3',
// color: '$slate11',
// lineHeight: '23px',
// margin: 0,
{...props}
/>
),
Notice,
h1: (props) => <H1 width="max-content" pos="relative" mb="$2" {...props} />,
h2: ({ children, ...props }) => (
<H2 mt="$5" size="$9" letterSpacing={-0.5} data-heading {...props}>
{children}
</H2>
),
h3: ({ children, id, ...props }) => (
<LinkHeading mt="$5" mb="$1" id={id}>
<H3 size="$8" data-heading {...props}>
{children}
</H3>
{getNonTextChildren(children)}
</LinkHeading>
),
h4: (props) => <H4 mt="$6" {...props} />,
h5: (props) => <H5 mt="$5" {...props} />,
p: (props) => <Paragraph className="paragraph" display="block" my="$3" {...props} />,
a: ({ href = '', children, ...props }) => {
return (
<NextLink href={href} passHref>
{/* @ts-ignore */}
<Paragraph fontSize="inherit" tag="a" display="inline" cursor="pointer" {...props}>
{children}
{href.startsWith('http') ? (
<>
<Text fontSize="inherit" display="inline-flex" y={2} mr={2}>
<ExternalIcon />
</Text>
</>
) : null}
</Paragraph>
</NextLink>
)
},
hr: HR,
ul: ({ children }) => {
return (
<UL>{React.Children.toArray(children).map((x) => (typeof x === 'string' ? null : x))}</UL>
)
},
ol: (props) => <YStack {...props} tag="ol" mb="$3" />,
li: (props) => {
return (
<LI>
<Paragraph tag="span">{props.children}</Paragraph>
</LI>
)
},
strong: (props) => <Paragraph tag="strong" fontSize="inherit" {...props} fontWeight="700" />,
img: ({ ...props }) => (
<YStack my="$6">
{/* TODO make this a proper <Image /> component */}
<YStack tag="img" {...props} maxWidth="100%" />
</YStack>
),
pre: ({ children }) => <>{children}</>,
code: (props) => {
const {
hero,
line,
scrollable,
className,
children,
id,
showLineNumbers,
collapsible,
...rest
} = props
if (!className) {
return <CodeInline>{children}</CodeInline>
}
return (
<DocCodeBlock
isHighlightingLines={line !== undefined}
className={className}
isHero={hero !== undefined}
isCollapsible={hero !== undefined || collapsible !== undefined}
isScrollable={scrollable !== undefined}
showLineNumbers={showLineNumbers !== undefined}
{...rest}
>
{children}
</DocCodeBlock>
)
},
Image: ({ children, size, ...props }: ImageProps & { size?: 'hero' }) => (
<OffsetBox size={size} tag="figure" f={1} mx={0} mb="$3" ai="center" jc="center" ov="hidden">
<Image maxWidth="100%" {...props} />
<Text tag="figcaption" lineHeight={23} color="$colorPress" mt="$2">
{children}
</Text>
</OffsetBox>
),
Video: ({
small,
large,
src,
children = '',
muted = true,
autoPlay = true,
controls,
size,
...props
}) => (
<YStack tag="figure" mx={0} my="$6">
<OffsetBox size={size}>
<video
src={src}
autoPlay={autoPlay}
playsInline
muted={muted}
controls={controls}
loop
style={{ width: '100%', display: 'block' }}
></video>
</OffsetBox>
<Text tag="figcaption" lineHeight={23} mt="$2" color="$colorPress">
{children}
</Text>
</YStack>
),
blockquote: ({ children, ...props }) => {
return (
<YStack
my="$4"
pl="$4"
ml="$3"
borderLeftWidth={1}
borderColor="$borderColor"
jc="center"
{...props}
>
<Paragraph whiteSpace="revert" size="$4" color="$color" opacity={0.65}>
{/* @ts-ignore */}
{React.Children.toArray(children).map((x) => (x?.props?.children ? x.props.children : x))}
</Paragraph>
</YStack>
)
},
Preview: (props) => {
return <Preview {...props} mt="$5" />
},
RegisterLink: ({ id, index, href }) => {
const isExternal = href.startsWith('http')
React.useEffect(() => {
const codeBlock = document.getElementById(id)
if (!codeBlock) return
const allHighlightWords = codeBlock.querySelectorAll('.highlight-word')
const target = allHighlightWords[index - 1]
if (!target) return
const addClass = () => target.classList.add('on')
const removeClass = () => target.classList.remove('on')
const addClick = () => (isExternal ? window.location.replace(href) : NextRouter.push(href))
target.addEventListener('mouseenter', addClass)
target.addEventListener('mouseleave', removeClass)
target.addEventListener('click', addClick)
return () => {
target.removeEventListener('mouseenter', addClass)
target.removeEventListener('mouseleave', removeClass)
target.removeEventListener('click', addClick)
}
}, [])
return null
},
H: ({ id, index, ...props }) => {
const triggerRef = React.useRef<HTMLElement>(null)
React.useEffect(() => {
const trigger = triggerRef.current
const codeBlock = document.getElementById(id)
if (!codeBlock) return
const allHighlightWords = codeBlock.querySelectorAll('.highlight-word')
const targetIndex = rangeParser(index).map((i) => i - 1)
// exit if the `index` passed is bigger than the total number of highlighted words
if (Math.max(...targetIndex) >= allHighlightWords.length) return
const addClass = () => targetIndex.forEach((i) => allHighlightWords[i].classList.add('on'))
const removeClass = () =>
targetIndex.forEach((i) => allHighlightWords[i].classList.remove('on'))
trigger?.addEventListener('mouseenter', addClass)
trigger?.addEventListener('mouseleave', removeClass)
return () => {
trigger?.removeEventListener('mouseenter', addClass)
trigger?.removeEventListener('mouseleave', removeClass)
}
}, [])
return <Paragraph fontFamily="$mono" cursor="default" ref={triggerRef} {...props} />
},
MediaPlayerDemo: ({ theme, ...props }) => {
return (
<Theme name={theme}>
<MediaPlayer {...props} />
</Theme>
)
},
GroupDisabledDemo: () => {
return (
<Group als="center" disabled>
<Button>First</Button>
<Button>Second</Button>
<Button>Third</Button>
</Group>
)
},
DemoButton: () => <Button>Hello world</Button>,
}
const LinkHeading = ({ id, children, ...props }: { id: string } & XStackProps) => (
<XStack
tag="a"
href={`#${id}`}
id={id}
data-id={id}
display="inline-flex"
ai="center"
space
{...props}
>
{children}
<YStack tag="span" opacity={0.3}>
<Link size={12} color="var(--color)" aria-hidden />
</YStack>
</XStack>
)
export const FrontmatterContext = React.createContext<Frontmatter>({} as any)
// Custom provider for next-mdx-remote
// https://github.com/hashicorp/next-mdx-remote#using-providers
export function MDXProvider(props) {
const { frontmatter, children } = props
return (
<>
<FrontmatterContext.Provider value={frontmatter}>{children}</FrontmatterContext.Provider>
</>
)
}
const getNonTextChildren = (children) =>
React.Children.map(children, (x) => (typeof x !== 'string' ? x : null)).flat() | the_stack |
export namespace EventAnalyticsModels {
/**
*
* @export
* @class RequiredError
* @extends {Error}
*/
export class RequiredError extends Error {
name: "RequiredError" = "RequiredError";
constructor(public field: string, msg?: string) {
super(msg);
}
}
/**
*
* @export
* @interface DuplicateEventArrayOutput
*/
export interface DuplicateEventArrayOutput {
/**
*
* @type {Array<Event>}
* @memberof DuplicateEventArrayOutput
*/
output: Array<Event>;
}
/**
* An event object (a tuple of time and text)
* @export
* @interface Event
*/
export interface Event {
/**
* Timestamp of the event in the ISO 8601
* @type {string}
* @memberof Event
*/
_time: string;
/**
* The text of the event
* @type {string}
* @memberof Event
*/
text: string;
/**
* Quality check flag
* @type {number}
* @memberof Event
*/
textQc?: number;
}
/**
*
* @export
* @interface EventArrayOutput
*/
export interface EventArrayOutput {
/**
*
* @type {Array<Event>}
* @memberof EventArrayOutput
*/
output: Array<Event>;
}
/**
* Model containing startTime, endTime and number of events produced between startTime and endTime
* @export
* @interface EventCountOutput
*/
export interface EventCountOutput {
/**
*
* @type {Array<EventCountOutputItem>}
* @memberof EventCountOutput
*/
output: Array<EventCountOutputItem>;
}
/**
* Item containing one element from the count output
* @export
* @interface EventCountOutputItem
*/
export interface EventCountOutputItem {
/**
* Timestamp of the event in the ISO 8601
* @type {string}
* @memberof EventCountOutputItem
*/
startTime?: string;
/**
* Timestamp of the event in the ISO 8601
* @type {string}
* @memberof EventCountOutputItem
*/
endTime?: string;
/**
*
* @type {number}
* @memberof EventCountOutputItem
*/
eventCount?: number;
}
/**
* Contains the events and the metadata regarding the events structure
* @export
* @interface EventInput
*/
export interface EventInput {
/**
*
* @type {EventInputEventsMetadata}
* @memberof EventInput
*/
eventsMetadata: EventInputEventsMetadata;
/**
*
* @type {Array<Event>}
* @memberof EventInput
*/
events: Array<Event>;
}
/**
* Metadata for the events list
* @export
* @interface EventInputEventsMetadata
*/
export interface EventInputEventsMetadata {
/**
* The property name of the events list objects that contains the text of the event
* @type {string}
* @memberof EventInputEventsMetadata
*/
eventTextPropertyName?: string;
/**
* The window length represents the value in milliseconds of the period in which user wants to split input interval
* @type {number}
* @memberof EventInputEventsMetadata
*/
splitInterval?: number;
}
/**
* Data model describing the input for the <b>eventsSearch</b> functionality
* @export
* @interface EventSearchInputDataModel
*/
export interface EventSearchInputDataModel extends EventsInputModel {
/**
* List of events which will be removed from the input list
* @type {Array<string>}
* @memberof EventSearchInputDataModel
*/
filterList?: Array<string>;
}
/**
* Contains the events and the metadata regarding the events structure
* @export
* @interface EventsInputModel
*/
export interface EventsInputModel {
/**
*
* @type {EventsInputModelEventsMetadata}
* @memberof EventsInputModel
*/
eventsMetadata: EventsInputModelEventsMetadata;
/**
*
* @type {Array<Event>}
* @memberof EventsInputModel
*/
events: Array<Event>;
}
/**
* Metadata for the events list
* @export
* @interface EventsInputModelEventsMetadata
*/
export interface EventsInputModelEventsMetadata {
/**
* The property name of the events list objects that contains the text of the event
* @type {string}
* @memberof EventsInputModelEventsMetadata
*/
eventTextPropertyName?: string;
}
/**
* Object containing an event description and an operator that specifies the number of appearances required for the event
* @export
* @interface MatchingPattern
*/
export interface MatchingPattern {
/**
* Event identifier.
* @type {string}
* @memberof MatchingPattern
*/
eventText: string;
/**
* The minimum number of desired repetitions of the event inside the pattern.
* @type {number}
* @memberof MatchingPattern
*/
minRepetitions?: number;
/**
* The maximum number of desired repetitions of the event inside the pattern.
* @type {number}
* @memberof MatchingPattern
*/
maxRepetitions?: number;
}
/**
* The collection of patterns used for matching into the events list.
* @export
* @interface PatternDefinition
*/
export interface PatternDefinition {
/**
* The id used to reference the folder where the file with the pattern is stored.
* @type {string}
* @memberof PatternDefinition
*/
folderId?: string;
/**
* The id used to reference the file where the pattern is stored.
* @type {string}
* @memberof PatternDefinition
*/
fileId?: string;
/**
* The id used to reference a specific pattern. It is unique inside this collection.
* @type {string}
* @memberof PatternDefinition
*/
patternId?: string;
/**
*
* @type {Array<MatchingPattern>}
* @memberof PatternDefinition
*/
pattern?: Array<MatchingPattern>;
}
/**
* Data model describing one sequence that matches a pattern
* @export
* @interface PatternFoundByMatching
*/
export interface PatternFoundByMatching {
/**
* The index of the pattern based on request object
* @type {number}
* @memberof PatternFoundByMatching
*/
patternIndex?: number;
/**
*
* @type {any}
* @memberof PatternFoundByMatching
*/
timeWindow?: any;
/**
*
* @type {Array<MatchingPattern>}
* @memberof PatternFoundByMatching
*/
pattern?: Array<MatchingPattern>;
/**
*
* @type {Array<Event>}
* @memberof PatternFoundByMatching
*/
matchedEvents?: Array<Event>;
}
/**
* Data model describing the input for the <b>Pattern Matching</b> functionality
* @export
* @interface PatternMatchingInputDataModel
*/
export interface PatternMatchingInputDataModel {
/**
* The maximum time length (in milliseconds) of the sliding window where the pattern occurs
* @type {number}
* @memberof PatternMatchingInputDataModel
*/
maxPatternInterval?: number;
/**
*
* @type {Array<PatternDefinition>}
* @memberof PatternMatchingInputDataModel
*/
patternsList?: Array<PatternDefinition>;
/**
* List of events which will be removed from the input list
* @type {Array<string>}
* @memberof PatternMatchingInputDataModel
*/
nonEvents?: Array<string>;
/**
*
* @type {EventsInputModel}
* @memberof PatternMatchingInputDataModel
*/
eventsInput?: EventsInputModel;
}
/**
* Data model describing the output for the <b>Pattern Matching</b> functionality
* @export
* @interface PatternMatchingOutput
*/
export interface PatternMatchingOutput {
/**
*
* @type {Array<PatternFoundByMatching>}
* @memberof PatternMatchingOutput
*/
output?: Array<PatternFoundByMatching>;
}
/**
* The time interval of matched pattern, containing the following information startTimestam, endTimestamp.
* @export
* @interface TimeWindow
*/
export interface TimeWindow {
/**
* The start timestamp of the matched pattern.
* @type {string}
* @memberof TimeWindow
*/
startTimestamp: string;
/**
* The end timestamp of the matched pattern.
* @type {string}
* @memberof TimeWindow
*/
endTimestamp: string;
}
/**
* Tuple containing frequency of event and event text
* @export
* @interface TopEventOutput
*/
export interface TopEventOutput extends Array<TopEventOutputInner> {}
/**
*
* @export
* @interface TopEventOutputInner
*/
export interface TopEventOutputInner {
/**
*
* @type {number}
* @memberof TopEventOutputInner
*/
appearances?: number;
/**
*
* @type {string}
* @memberof TopEventOutputInner
*/
text?: string;
}
/**
* Data model describing the input for the <b>findTopEvents</b> functionality
* @export
* @interface TopEventsInputDataModel
*/
export interface TopEventsInputDataModel extends EventsInputModel {
/**
* How many top positions will be returned in the response. Has to be a positive integer. If not specified, the default value 10 will be used.
* @type {number}
* @memberof TopEventsInputDataModel
*/
numberOfTopPositionsRequired?: number;
}
/**
*
* @export
* @interface VndError
*/
export interface VndError {
/**
*
* @type {string}
* @memberof VndError
*/
logref?: string;
/**
*
* @type {string}
* @memberof VndError
*/
message?: string;
}
} | the_stack |
import { assert } from 'chai';
import { cache } from '../../src';
// @ts-ignore
import CacheMap from '@feathers-plus/cache';
let cacheMap: any;
let hookBeforeSingle: any;
let hookBeforeMulti: any;
let hookAfterSingle: any;
let hookAfterSingleNormalize: any;
let hookAfterMulti: any;
let hookAfterPaginated: any;
let hookBeforeUuid: any;
let hookAfterUuid: any;
let hookBeforeMultiMixed: any;
let hookAfterMultiMixed: any;
let map: any;
let cloneCount: any;
const makeCacheKey = (key: any) => -key;
describe('service cache', () => {
beforeEach(() => {
cacheMap = CacheMap({ max: 3 });
map = new Map();
cloneCount = 0;
hookBeforeSingle = {
type: 'before',
id: undefined,
method: undefined,
params: { provider: 'rest' },
data: { id: 1, first: 'John', last: 'Doe' }
};
hookBeforeMulti = {
type: 'before',
id: undefined,
method: undefined,
params: { provider: 'rest' },
data: [
{ id: 1, first: 'John', last: 'Doe' },
{ id: 2, first: 'Jane', last: 'Doe' }
]
};
hookAfterSingle = {
type: 'after',
id: undefined,
method: undefined,
params: { provider: 'rest' },
result: { id: 1, first: 'Jane', last: 'Doe' }
};
hookAfterSingleNormalize = {
type: 'after',
id: undefined,
method: undefined,
params: { provider: 'rest' },
result: { id: -1, first: 'Jane', last: 'Doe' }
};
hookAfterMulti = {
type: 'after',
id: undefined,
method: undefined,
params: { provider: 'rest' },
result: [
{ id: 1, first: 'John', last: 'Doe' },
{ id: 2, first: 'Jane', last: 'Doe' }
]
};
hookAfterPaginated = {
type: 'after',
method: 'find',
params: { provider: 'rest' },
result: {
total: 2,
data: [
{ id: 1, first: 'John', last: 'Doe' },
{ id: 2, first: 'Jane', last: 'Doe' }
]
}
};
hookBeforeUuid = {
type: 'before',
id: undefined,
method: undefined,
params: { provider: 'rest' },
data: { uuid: 1, first: 'John', last: 'Doe' },
service: { id: 'uuid' }
};
hookAfterUuid = {
type: 'after',
id: undefined,
method: undefined,
params: { provider: 'rest' },
result: { uuid: 1, first: 'Jane', last: 'Doe' },
service: { id: 'uuid' }
};
hookBeforeMultiMixed = {
type: 'before',
id: undefined,
method: undefined,
params: { provider: 'rest' },
data: [
{ _id: 1, first: 'John', last: 'Doe' },
{ id: 2, first: 'Jane', last: 'Doe' }
]
};
hookAfterMultiMixed = {
type: 'after',
id: undefined,
method: undefined,
params: { provider: 'rest' },
result: [
{ id: 1, first: 'John', last: 'Doe' },
{ _id: 2, first: 'Jane', last: 'Doe' }
]
};
});
describe('Can build a cache', () => {
it('Can build a cache', () => {
cacheMap.set('a', 'aa');
assert.equal(cacheMap.get('a'), 'aa', 'bad get after set');
cacheMap.delete('a');
assert.equal(cacheMap.get('a'), undefined, 'bad get after delete');
cacheMap.set('a', 'aa');
cacheMap.clear();
assert.equal(cacheMap.get('a'), undefined, 'bad get after clear');
});
});
describe('Clears cache', () => {
it('Before one-record update', () => {
hookBeforeSingle.method = 'update';
cacheMap.set(1, 123);
// @ts-ignore
cache(cacheMap, 'id')(hookBeforeSingle);
assert.deepEqual(cacheMap.get(1), undefined);
});
it('Before multi-record update', () => {
hookBeforeMulti.method = 'update';
cacheMap.set(1, 123);
cacheMap.set(2, 124);
// @ts-ignore
cache(cacheMap, 'id')(hookBeforeMulti);
assert.deepEqual(cacheMap.get(1), undefined);
assert.deepEqual(cacheMap.get(2), undefined);
});
it('Before one-record patch', () => {
hookBeforeSingle.method = 'patch';
cacheMap.set(1, 123);
// @ts-ignore
cache(cacheMap, 'id')(hookBeforeSingle);
assert.deepEqual(cacheMap.get(1), undefined);
});
it('Before multi-record patch', () => {
hookBeforeMulti.method = 'patch';
cacheMap.set(1, 123);
cacheMap.set(2, 789);
// @ts-ignore
cache(cacheMap, 'id')(hookBeforeMulti);
assert.deepEqual(cacheMap.get(1), undefined, 'id 1');
assert.deepEqual(cacheMap.get(2), undefined, 'id 2');
});
it('NOT before one-record create', () => {
hookBeforeSingle.method = 'create';
cacheMap.set(1, 123);
// @ts-ignore
cache(cacheMap, 'id')(hookBeforeSingle);
assert.deepEqual(cacheMap.get(1), 123);
});
it('NOT before multi-record remove', () => {
hookBeforeMulti.method = 'remove';
cacheMap.set(1, 123);
cacheMap.set(2, 321);
// @ts-ignore
cache(cacheMap, 'id')(hookBeforeMulti);
assert.deepEqual(cacheMap.get(1), 123);
assert.deepEqual(cacheMap.get(2), 321);
});
it('After multi-record remove', () => {
hookAfterMulti.method = 'remove';
cacheMap.set(1, 123);
cacheMap.set(2, 321);
// @ts-ignore
cache(cacheMap, 'id')(hookAfterMulti);
assert.deepEqual(cacheMap.get(1), undefined, 'id 1');
assert.deepEqual(cacheMap.get(2), undefined, 'id 2');
});
});
describe('Loads cache', () => {
it('After one-record create', () => {
hookAfterSingle.method = 'create';
// @ts-ignore
cache(cacheMap, 'id')(hookAfterSingle);
assert.deepEqual(cacheMap.get(1), { id: 1, first: 'Jane', last: 'Doe' });
});
it('After multi-record patch', () => {
hookAfterMulti.method = 'patch';
// @ts-ignore
cache(cacheMap, 'id')(hookAfterMulti);
assert.deepEqual(cacheMap.get(1), { id: 1, first: 'John', last: 'Doe' }, 'id 1');
assert.deepEqual(cacheMap.get(2), { id: 2, first: 'Jane', last: 'Doe' }, 'id 2');
});
it('After paginated find', () => {
// @ts-ignore
cache(cacheMap, 'id')(hookAfterPaginated);
assert.deepEqual(cacheMap.get(1), { id: 1, first: 'John', last: 'Doe' }, 'id 1');
assert.deepEqual(cacheMap.get(2), { id: 2, first: 'Jane', last: 'Doe' }, 'id 2');
});
it('NOT after remove', () => {
hookAfterMulti.method = 'remove';
// @ts-ignore
cache(cacheMap, 'id')(hookAfterMulti);
assert.deepEqual(cacheMap.get(1), undefined, 'id 1');
assert.deepEqual(cacheMap.get(2), undefined, 'id 2');
});
it('Normalizes record', () => {
hookAfterSingleNormalize.method = 'create';
// @ts-ignore
cache(cacheMap, 'id', { makeCacheKey })(hookAfterSingleNormalize);
assert.deepEqual(cacheMap.get(1), { id: -1, first: 'Jane', last: 'Doe' });
});
});
describe('Gets from cache', () => {
it('Before one-record get', () => {
hookBeforeSingle.method = 'get';
hookBeforeSingle.id = 1;
cacheMap.set(1, { foo: 'bar' });
// @ts-ignore
cache(cacheMap, 'id')(hookBeforeSingle);
assert.deepEqual(cacheMap.get(1), { foo: 'bar' }, 'cache');
assert.deepEqual(hookBeforeSingle.result, { foo: 'bar' });
});
it('Normalizes record', () => {
hookBeforeSingle.method = 'get';
hookBeforeSingle.id = -1;
cacheMap.set(1, { id: -1, foo: 'bar' });
// @ts-ignore
cache(cacheMap, 'id', { makeCacheKey })(hookBeforeSingle);
assert.deepEqual(cacheMap.get(1), { id: -1, foo: 'bar' }, 'cache');
assert.deepEqual(hookBeforeSingle.result, { id: -1, foo: 'bar' });
});
});
describe('Uses context.service.id', () => {
it('Clears cache before one-record update', () => {
hookBeforeUuid.method = 'update';
cacheMap.set(1, 123);
cache(cacheMap)(hookBeforeUuid);
assert.deepEqual(cacheMap.get(1), undefined);
});
it('Loads cache after one-record create', () => {
hookAfterUuid.method = 'create';
cache(cacheMap)(hookAfterUuid);
assert.deepEqual(cacheMap.get(1), { uuid: 1, first: 'Jane', last: 'Doe' });
});
it('Before one-record get', () => {
hookBeforeUuid.method = 'get';
hookBeforeUuid.id = 1;
cacheMap.set(1, { foo: 'bar' });
cache(cacheMap)(hookBeforeUuid);
assert.deepEqual(cacheMap.get(1), { foo: 'bar' }, 'cache');
assert.deepEqual(hookBeforeUuid.result, { foo: 'bar' });
});
});
describe('Uses item._id || item.id', () => {
it('Clears cache before multi-record patch', () => {
hookBeforeMultiMixed.method = 'patch';
cacheMap.set(1, 123);
cacheMap.set(2, 789);
cache(cacheMap)(hookBeforeMultiMixed);
assert.deepEqual(cacheMap.get(1), undefined, 'id 1');
assert.deepEqual(cacheMap.get(2), undefined, 'id 2');
});
it('Loads cache after multi-record patch', () => {
hookAfterMultiMixed.method = 'patch';
cache(cacheMap)(hookAfterMultiMixed);
assert.deepEqual(cacheMap.get(1), { id: 1, first: 'John', last: 'Doe' }, 'id 1');
assert.deepEqual(cacheMap.get(2), { _id: 2, first: 'Jane', last: 'Doe' }, 'id 2');
});
});
describe('Works with an ES6 Map', () => {
it('Clears cache before one-record update', () => {
hookBeforeUuid.method = 'update';
map.set(1, 123);
cache(map)(hookBeforeUuid);
assert.deepEqual(map.get(1), undefined);
});
it('Loads cache after one-record create', () => {
hookAfterUuid.method = 'create';
cache(map)(hookAfterUuid);
assert.deepEqual(map.get(1), { uuid: 1, first: 'Jane', last: 'Doe' });
});
});
describe('Misc', () => {
it('Uses option.clone', () => {
hookAfterUuid.method = 'create';
// @ts-ignore
cache(cacheMap, null, { clone })(hookAfterUuid);
assert.deepEqual(cacheMap.get(1), { uuid: 1, first: 'Jane', last: 'Doe' }, 'get');
assert.equal(cloneCount, 1, 'count');
});
});
});
function clone (obj: any) {
cloneCount += 1;
return Object.assign({}, obj);
} | the_stack |
import React, { useContext, useMemo, useRef, useState } from 'react';
import {
DATA_SOURCE_ENUM,
DATA_SOURCE_TEXT,
DATA_SOURCE_VERSION,
defaultColsText,
DEFAULT_MAPPING_TEXT,
FLINK_VERSIONS,
formItemLayout,
hbaseColsText,
hbaseColsText112,
HELP_DOC_URL,
KAFKA_DATA_LIST,
KAFKA_DATA_TYPE,
} from '@/constant';
import {
isHaveCollection,
isHaveDataPreview,
isHaveParallelism,
isHavePrimaryKey,
isHaveTableColumn,
isHaveTableList,
isHaveTopic,
isHaveUpdateMode,
isHaveUpdateStrategy,
isHaveUpsert,
isAvro,
isES,
isHbase,
isKafka,
isSqlServer,
isShowBucket,
isShowSchema,
isRedis,
isRDB,
} from '@/utils/is';
import type { FormInstance } from 'antd';
import {
Button,
Checkbox,
Form,
Input,
InputNumber,
message,
Popconfirm,
Radio,
Select,
Table,
Tooltip,
} from 'antd';
import { CloseOutlined, UpOutlined, DownOutlined } from '@ant-design/icons';
import Column from 'antd/lib/table/Column';
import { debounce, isUndefined } from 'lodash';
import { getColumnsByColumnsText } from '@/utils';
import { CustomParams } from '../customParams';
import type { IDataColumnsProps, IDataSourceUsedInSyncProps, IFlinkSinkProps } from '@/interface';
import Editor from '@/components/editor';
import { NAME_FIELD } from '.';
import { FormContext } from '@/services/rightBarService';
import DataPreviewModal from '@/components/streamCollection/source/dataPreviewModal';
const FormItem = Form.Item;
const { Option } = Select;
/**
* 默认可选择的数据源
*/
const DATA_SOURCE_OPTIONS = [
DATA_SOURCE_ENUM.HBASE,
DATA_SOURCE_ENUM.ES6,
DATA_SOURCE_ENUM.ES7,
DATA_SOURCE_ENUM.MYSQL,
];
interface IResultProps {
/**
* Form 表单 name 前缀
*/
index: number;
/**
* 数据源下拉菜单
*/
dataSourceOptionList: IDataSourceUsedInSyncProps[];
tableOptionType: Record<string, string[]>;
/**
* 表下拉菜单
*/
tableColumnOptionType: IDataColumnsProps[];
/**
* topic 下拉菜单
*/
topicOptionType: string[];
/**
* 当前 flink 版本
*/
componentVersion?: Valueof<typeof FLINK_VERSIONS>;
getTableType: (
params: { sourceId: number; type: DATA_SOURCE_ENUM; schema?: string },
searchKey?: string,
) => void;
}
enum COLUMNS_OPERATORS {
/**
* 导入一条字段
*/
ADD_ONE_LINE,
/**
* 导入全部字段
*/
ADD_ALL_LINES,
/**
* 删除全部字段
*/
DELETE_ALL_LINES,
/**
* 删除一条字段
*/
DELETE_ONE_LINE,
/**
* 编辑字段
*/
CHANGE_ONE_LINE,
}
/**
* 是否需要禁用更新模式
*/
const isDisabledUpdateMode = (
type: DATA_SOURCE_ENUM,
isHiveTable?: boolean,
version?: string,
): boolean => {
if (type === DATA_SOURCE_ENUM.IMPALA) {
if (isUndefined(isHiveTable) || isHiveTable === true) {
return true;
}
if (isHiveTable === false) {
return false;
}
return false;
}
return !isHaveUpsert(type, version);
};
/**
* 根据 type 渲染不同模式的 Option 组件
*/
const originOption = (type: string, arrData: any[]) => {
switch (type) {
case 'currencyType':
return arrData.map((v) => {
return (
<Option key={v} value={`${v}`}>
<Tooltip placement="topLeft" title={v}>
<span className="panel-tooltip">{v}</span>
</Tooltip>
</Option>
);
});
case 'columnType':
return arrData.map((v) => {
return (
<Option key={v.key} value={`${v.key}`}>
<Tooltip placement="topLeft" title={v.key}>
<span className="panel-tooltip">{v.key}</span>
</Tooltip>
</Option>
);
});
case 'primaryType':
return arrData.map((v) => {
return (
<Option key={v.column} value={`${v.column}`}>
{v.column}
</Option>
);
});
case 'kafkaPrimaryType':
return arrData.map((v) => {
return (
<Option key={v.field} value={`${v.field}`}>
{v.field}
</Option>
);
});
default:
return null;
}
};
export default function ResultForm({
index,
dataSourceOptionList = [],
tableOptionType = {},
tableColumnOptionType = [],
topicOptionType = [],
componentVersion = FLINK_VERSIONS.FLINK_1_12,
getTableType,
}: IResultProps) {
const { form } = useContext(FormContext) as {
form?: FormInstance<{ [NAME_FIELD]: Partial<IFlinkSinkProps>[] }>;
};
const [visible, setVisible] = useState(false);
const [params, setParams] = useState<Record<string, any>>({});
const [showAdvancedParams, setShowAdvancedParams] = useState(false);
const searchKey = useRef('');
// 表远程搜索
const debounceHandleTableSearch = debounce((value: string) => {
const currentData = form?.getFieldsValue()[NAME_FIELD][index];
if (currentData?.sourceId) {
searchKey.current = value;
getTableType(
{
sourceId: currentData.sourceId,
type: currentData.type!,
schema: currentData.schema,
},
value,
);
}
}, 300);
const getPlaceholder = (sourceType: DATA_SOURCE_ENUM) => {
if (isHbase(sourceType)) {
return componentVersion === FLINK_VERSIONS.FLINK_1_12
? hbaseColsText112
: hbaseColsText;
}
return defaultColsText;
};
const showPreviewModal = () => {
const {
sourceId,
index: tableIndex,
table,
type,
schema,
} = form?.getFieldValue(NAME_FIELD)[index];
let nextParams: Record<string, any> = {};
switch (type) {
case DATA_SOURCE_ENUM.ES7: {
if (!sourceId || !tableIndex) {
message.error('数据预览需要选择数据源和索引!');
return;
}
nextParams = { sourceId, tableName: tableIndex };
break;
}
case DATA_SOURCE_ENUM.REDIS:
case DATA_SOURCE_ENUM.UPRedis:
case DATA_SOURCE_ENUM.HBASE:
case DATA_SOURCE_ENUM.TBDS_HBASE:
case DATA_SOURCE_ENUM.HBASE_HUAWEI:
case DATA_SOURCE_ENUM.MYSQL:
case DATA_SOURCE_ENUM.UPDRDB:
case DATA_SOURCE_ENUM.HIVE:
case DATA_SOURCE_ENUM.INCEPTOR: {
if (!sourceId || !table) {
message.error('数据预览需要选择数据源和表!');
return;
}
nextParams = { sourceId, tableName: table };
break;
}
case DATA_SOURCE_ENUM.ORACLE: {
if (!sourceId || !table || !schema) {
message.error('数据预览需要选择数据源、表和schema!');
return;
}
nextParams = { sourceId, tableName: table, schema };
break;
}
case DATA_SOURCE_ENUM.SQLSERVER:
case DATA_SOURCE_ENUM.SQLSERVER_2017_LATER: {
if (!sourceId || !table) {
message.error('数据预览需要选择数据源和表!');
return;
}
nextParams = { sourceId, tableName: table, schema };
break;
}
default:
break;
}
setVisible(true);
setParams(nextParams);
};
const renderTableOptions = () =>
tableOptionType[searchKey.current]?.map((v) => (
<Option key={v} value={`${v}`}>
{v}
</Option>
)) || [];
const handleColumnsChanged = (
ops: COLUMNS_OPERATORS,
i?: number,
value?: Partial<{
type: string;
column: string | number;
}>,
) => {
switch (ops) {
case COLUMNS_OPERATORS.ADD_ALL_LINES: {
const nextValue = form!.getFieldsValue();
nextValue[NAME_FIELD][index].columns = tableColumnOptionType.map((column) => ({
column: column.key,
type: column.type,
}));
form!.setFieldsValue({ ...nextValue });
break;
}
case COLUMNS_OPERATORS.DELETE_ALL_LINES: {
const nextValue = form!.getFieldsValue();
nextValue[NAME_FIELD][index].columns = [];
nextValue[NAME_FIELD][index].primaryKey = [];
form!.setFieldsValue({ ...nextValue });
break;
}
case COLUMNS_OPERATORS.ADD_ONE_LINE: {
const nextValue = form!.getFieldsValue();
nextValue[NAME_FIELD][index].columns = nextValue[NAME_FIELD][index].columns || [];
nextValue[NAME_FIELD][index].columns!.push({});
form!.setFieldsValue({ ...nextValue });
break;
}
case COLUMNS_OPERATORS.DELETE_ONE_LINE: {
const nextValue = form!.getFieldsValue();
const deleteCol = nextValue[NAME_FIELD][index].columns?.splice(i!, 1) || [];
// 删除一条字段的副作用是若该行是 primrayKey 则删除
if (deleteCol.length) {
const { primaryKey } = nextValue[NAME_FIELD][index];
if (
Array.isArray(primaryKey) &&
primaryKey.findIndex((key) => key === deleteCol[0].column) !== -1
) {
const idx = primaryKey.findIndex((key) => key === deleteCol[0].column);
primaryKey.splice(idx, 1);
}
}
form!.setFieldsValue({ ...nextValue });
break;
}
case COLUMNS_OPERATORS.CHANGE_ONE_LINE: {
const nextValue = form!.getFieldsValue();
nextValue[NAME_FIELD][index].columns![i!] = value!;
form!.setFieldsValue({ ...nextValue });
break;
}
default:
break;
}
};
const topicOptionTypes = originOption('currencyType', topicOptionType);
const tableColumnOptionTypes = originOption('columnType', tableColumnOptionType);
// isShowPartition 为 false 为 kudu 表
const disableUpdateMode = false;
// 当前数据
const data = form?.getFieldsValue()[NAME_FIELD][index];
const schemaRequired = data?.type
? [
DATA_SOURCE_ENUM.POSTGRESQL,
DATA_SOURCE_ENUM.KINGBASE8,
DATA_SOURCE_ENUM.SQLSERVER,
DATA_SOURCE_ENUM.SQLSERVER_2017_LATER,
].includes(data?.type)
: false;
const isFlink112 = useMemo(
() => componentVersion === FLINK_VERSIONS.FLINK_1_12,
[componentVersion],
);
const primaryKeyOptionTypes = useMemo(
() =>
isFlink112 && isKafka(data?.type)
? originOption('kafkaPrimaryType', getColumnsByColumnsText(data?.columnsText))
: originOption('primaryType', data?.columns || []),
[isFlink112, data],
);
return (
<>
<FormItem
label="存储类型"
name={[index, 'type']}
rules={[{ required: true, message: '请选择存储类型' }]}
>
<Select
className="right-select"
showSearch
style={{ width: '100%' }}
filterOption={(input, option) =>
option?.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
>
{DATA_SOURCE_OPTIONS.map((item) => (
<Option key={item} value={item}>
{DATA_SOURCE_TEXT[item]}
</Option>
))}
</Select>
</FormItem>
<FormItem
label="数据源"
name={[index, 'sourceId']}
rules={[{ required: true, message: '请选择数据源' }]}
>
<Select
showSearch
placeholder="请选择数据源"
className="right-select"
filterOption={(input, option) =>
option?.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
}
>
{dataSourceOptionList.map((v) => (
<Option key={v.dataInfoId} value={v.dataInfoId}>
{v.dataName}
{DATA_SOURCE_VERSION[v.dataTypeCode] &&
` (${DATA_SOURCE_VERSION[v.dataTypeCode]})`}
</Option>
))}
</Select>
</FormItem>
<FormItem noStyle dependencies={[[index, 'type']]}>
{({ getFieldValue }) => (
<>
{isHaveCollection(getFieldValue(NAME_FIELD)[index].type) && (
<FormItem
label="Collection"
name={[index, 'collection']}
rules={[{ required: true, message: '请选择Collection' }]}
>
<Select
showSearch
allowClear
placeholder="请选择Collection"
className="right-select"
filterOption={(input, option) =>
option?.props.children
.toLowerCase()
.indexOf(input.toLowerCase()) >= 0
}
>
{renderTableOptions()}
</Select>
</FormItem>
)}
{isShowBucket(getFieldValue(NAME_FIELD)[index].type) && (
<>
<FormItem
label="Bucket"
name={[index, 'bucket']}
rules={[
{
required: Boolean(schemaRequired),
message: '请选择Bucket',
},
]}
>
<Select
showSearch
allowClear
placeholder="请选择Bucket"
className="right-select"
>
{renderTableOptions()}
</Select>
</FormItem>
<FormItem
label="ObjectName"
name={[index, 'objectName']}
rules={[{ required: true, message: '请输入ObjectName' }]}
tooltip="默认以标准存储,txt格式保存至S3 Bucket内"
>
<Input
placeholder="请输入ObjectName"
style={{ width: '90%' }}
/>
</FormItem>
</>
)}
{isShowSchema(getFieldValue(NAME_FIELD)[index].type) && (
<FormItem
label="Schema"
name={[index, 'schema']}
rules={[
{
required: Boolean(schemaRequired),
message: '请输入Schema',
},
]}
>
<Select
showSearch
allowClear
placeholder="请选择Schema"
className="right-select"
options={[]}
/>
</FormItem>
)}
{isHaveTopic(getFieldValue(NAME_FIELD)[index].type) && (
<FormItem
label="Topic"
name={[index, 'topic']}
rules={[{ required: true, message: '请选择Topic' }]}
>
<Select
placeholder="请选择Topic"
className="right-select"
showSearch
>
{topicOptionTypes}
</Select>
</FormItem>
)}
{isHaveTableList(getFieldValue(NAME_FIELD)[index].type) &&
![DATA_SOURCE_ENUM.S3, DATA_SOURCE_ENUM.CSP_S3].includes(
getFieldValue(NAME_FIELD)[index].type,
) && (
<FormItem
label="表"
name={[index, 'table']}
rules={[{ required: true, message: '请选择表' }]}
>
<Select
showSearch
placeholder="请选择表"
className="right-select"
onSearch={(value: string) =>
debounceHandleTableSearch(value)
}
filterOption={false}
>
{renderTableOptions()}
</Select>
</FormItem>
)}
{isRedis(getFieldValue(NAME_FIELD)[index].type) && (
<FormItem
label="表"
name={[index, 'table']}
rules={[{ required: true, message: '请输入表名' }]}
>
<Input placeholder="请输入表名" />
</FormItem>
)}
{isES(getFieldValue(NAME_FIELD)[index].type) && (
<FormItem
label="索引"
tooltip={
<span>
{
'支持输入{column_name}作为动态索引,动态索引需包含在映射表字段中,更多请参考'
}
<a
rel="noopener noreferrer"
target="_blank"
href={HELP_DOC_URL.INDEX}
>
帮助文档
</a>
</span>
}
name={[index, 'index']}
rules={[{ required: true, message: '请输入索引' }]}
>
<Input placeholder="请输入索引" />
</FormItem>
)}
{isHaveDataPreview(getFieldValue(NAME_FIELD)[index].type) && (
<FormItem
wrapperCol={{
offset: formItemLayout.labelCol.sm.span,
span: formItemLayout.wrapperCol.sm.span,
}}
>
<Button block type="link" onClick={showPreviewModal}>
数据预览
</Button>
</FormItem>
)}
{isRedis(getFieldValue(NAME_FIELD)[index].type) && (
<FormItem
label="主键"
name={[index, 'primaryKey']}
rules={[{ required: true, message: '请输入主键' }]}
>
<Input placeholder="结果表主键,多个字段用英文逗号隔开" />
</FormItem>
)}
{isES(getFieldValue(NAME_FIELD)[index].type) && (
<FormItem
label="id"
tooltip="id生成规则:填写字段的索引位置(从0开始)"
name={[index, 'esId']}
>
<Input placeholder="请输入id" />
</FormItem>
)}
{[DATA_SOURCE_ENUM.ES, DATA_SOURCE_ENUM.ES6].includes(
getFieldValue(NAME_FIELD)[index].type,
) && (
<FormItem
label="索引类型"
name={[index, 'esType']}
rules={[{ required: true, message: '请输入索引类型' }]}
>
<Input placeholder="请输入索引类型" />
</FormItem>
)}
{getFieldValue(NAME_FIELD)[index].type === DATA_SOURCE_ENUM.HBASE && (
<FormItem
label="rowKey"
tooltip={
isFlink112 ? (
<>
Hbase 表 rowkey 字段支持类型可参考
<a
href={HELP_DOC_URL.HBASE}
target="_blank"
rel="noopener noreferrer"
>
帮助文档
</a>
</>
) : (
"支持拼接规则:md5(fieldA+fieldB) + fieldC + '常量字符'"
)
}
>
<div style={{ display: 'flex' }}>
<FormItem
style={{ flex: 1 }}
name={[index, 'rowKey']}
rules={[
{ required: true, message: '请输入rowKey' },
isFlink112
? {
pattern: /^\w{1,64}$/,
message:
'只能由字母,数字和下划线组成,且不超过64个字符',
}
: {},
]}
>
<Input
placeholder={
isFlink112
? '请输入 rowkey'
: 'rowKey 格式:填写字段1+填写字段2'
}
/>
</FormItem>
{isFlink112 && (
<>
<span> 类型:</span>
<FormItem
style={{ flex: 1 }}
name={[index, 'rowKeyType']}
rules={[
{
required: true,
message: '请输入rowKey类型',
},
]}
>
<Input placeholder="请输入类型" />
</FormItem>
</>
)}
</div>
</FormItem>
)}
{[DATA_SOURCE_ENUM.TBDS_HBASE, DATA_SOURCE_ENUM.HBASE_HUAWEI].includes(
getFieldValue(NAME_FIELD)[index].type,
) && (
<FormItem
label="rowKey"
tooltip="支持拼接规则:md5(fieldA+fieldB) + fieldC + '常量字符'"
name={[index, 'rowKey']}
rules={[{ required: true, message: '请输入rowKey' }]}
>
<Input placeholder="rowKey 格式:填写字段1+填写字段2 " />
</FormItem>
)}
</>
)}
</FormItem>
<FormItem
label="映射表"
name={[index, 'tableName']}
rules={[{ required: true, message: '请输入映射表名' }]}
>
<Input placeholder="请输入映射表名" />
</FormItem>
{/* 隐藏 columns 字段,通过 table 修改 */}
<FormItem hidden name="columns" />
<FormItem
label="字段"
required
dependencies={[
[index, 'type'],
[index, 'columns'],
]}
>
{({ getFieldValue }) =>
isHaveTableColumn(getFieldValue(NAME_FIELD)[index].type) ? (
<div className="column-container">
<Table<IFlinkSinkProps['columns'][number]>
rowKey="column"
dataSource={getFieldValue(NAME_FIELD)[index].columns || []}
pagination={false}
size="small"
>
<Column<IFlinkSinkProps['columns'][number]>
title="字段"
dataIndex="column"
key="字段"
width="45%"
render={(text, record, i) => {
return (
<Select
value={text}
showSearch
className="sub-right-select column-table__select"
onChange={(val) =>
handleColumnsChanged(
COLUMNS_OPERATORS.CHANGE_ONE_LINE,
i,
{
column: val,
// assign type automatically
type: tableColumnOptionType.find(
(c) => c.key.toString() === val,
)?.type,
},
)
}
>
{tableColumnOptionTypes}
</Select>
);
}}
/>
<Column<IFlinkSinkProps['columns'][number]>
title="类型"
dataIndex="type"
key="类型"
width="45%"
render={(text: string, record, i) => (
<span
className={
text?.toLowerCase() === 'Not Support'.toLowerCase()
? 'has-error'
: ''
}
>
<Tooltip
title={text}
trigger={'hover'}
placement="topLeft"
overlayClassName="numeric-input"
>
<Input
value={text}
className="column-table__input"
onChange={(e) => {
handleColumnsChanged(
COLUMNS_OPERATORS.CHANGE_ONE_LINE,
i,
{
...record,
type: e.target.value,
},
);
}}
/>
</Tooltip>
</span>
)}
/>
<Column
key="delete"
render={(_, __, i) => {
return (
<CloseOutlined
style={{
fontSize: 12,
color: 'var(--editor-foreground)',
}}
onClick={() =>
handleColumnsChanged(
COLUMNS_OPERATORS.DELETE_ONE_LINE,
i,
)
}
/>
);
}}
/>
</Table>
<div className="column-btn">
<span>
<a
onClick={() =>
handleColumnsChanged(COLUMNS_OPERATORS.ADD_ONE_LINE)
}
>
添加输入
</a>
</span>
<span>
<a
onClick={() =>
handleColumnsChanged(COLUMNS_OPERATORS.ADD_ALL_LINES)
}
style={{ marginRight: 12 }}
>
导入全部字段
</a>
{getFieldValue(NAME_FIELD)[index]?.columns?.length ? (
<Popconfirm
title="确认清空所有字段?"
onConfirm={() =>
handleColumnsChanged(
COLUMNS_OPERATORS.DELETE_ALL_LINES,
)
}
okText="确认"
cancelText="取消"
>
<a>清空</a>
</Popconfirm>
) : (
<a style={{ color: 'var(--editor-foreground)' }}>清空</a>
)}
</span>
</div>
</div>
) : (
<FormItem name="columnsText" noStyle>
<Editor
style={{
minHeight: 202,
}}
sync
options={{
minimap: {
enabled: false,
},
}}
placeholder={getPlaceholder(getFieldValue(NAME_FIELD)[index].type!)}
/>
</FormItem>
)
}
</FormItem>
<FormItem noStyle dependencies={[[index, 'type']]}>
{({ getFieldValue }) => (
<>
{isKafka(getFieldValue(NAME_FIELD)[index].type) && (
<React.Fragment>
<FormItem
label="输出类型"
name={[index, 'sinkDataType']}
rules={[{ required: true, message: '请选择输出类型' }]}
>
<Select style={{ width: '100%' }}>
{getFieldValue(NAME_FIELD)[index].type ===
DATA_SOURCE_ENUM.KAFKA_CONFLUENT ? (
<Option
value={KAFKA_DATA_TYPE.TYPE_AVRO_CONFLUENT}
key={KAFKA_DATA_TYPE.TYPE_AVRO_CONFLUENT}
>
{KAFKA_DATA_TYPE.TYPE_AVRO_CONFLUENT}
</Option>
) : (
KAFKA_DATA_LIST.map(({ text, value }) => (
<Option value={value} key={text + value}>
{text}
</Option>
))
)}
</Select>
</FormItem>
<FormItem noStyle dependencies={[[index, 'sinkDataType']]}>
{({ getFieldValue: getField }) =>
isAvro(getField(NAME_FIELD)[index].sinkDataType) && (
<FormItem
label="Schema"
name={[index, 'schemaInfo']}
rules={[
{
required: !isFlink112,
message: '请输入Schema',
},
]}
>
<Input.TextArea
rows={9}
placeholder={`填写Avro Schema信息,示例如下:\n{\n\t"name": "testAvro",\n\t"type": "record",\n\t"fields": [{\n\t\t"name": "id",\n\t\t"type": "string"\n\t}]\n}`}
/>
</FormItem>
)
}
</FormItem>
</React.Fragment>
)}
{isHaveUpdateMode(getFieldValue(NAME_FIELD)[index].type) && (
<>
<FormItem
label="更新模式"
name={[index, 'updateMode']}
rules={[{ required: true, message: '请选择更新模式' }]}
>
<Radio.Group
disabled={isDisabledUpdateMode(
getFieldValue(NAME_FIELD)[index].type,
disableUpdateMode,
componentVersion,
)}
className="right-select"
>
<Radio value="append">追加(append)</Radio>
<Radio
value="upsert"
disabled={
getFieldValue(NAME_FIELD)[index].type ===
DATA_SOURCE_ENUM.CLICKHOUSE
}
>
更新(upsert)
</Radio>
</Radio.Group>
</FormItem>
<FormItem noStyle dependencies={[[index, 'updateMode']]}>
{({ getFieldValue: getField }) => (
<>
{getField(NAME_FIELD)[index].updateMode === 'upsert' &&
isHaveUpdateStrategy(
getFieldValue(NAME_FIELD)[index].type,
) && (
<FormItem
label="更新策略"
name={[index, 'allReplace']}
initialValue="false"
rules={[
{
required: true,
message: '请选择更新策略',
},
]}
>
<Select className="right-select">
<Option key="true" value="true">
Null值替换原有数据
</Option>
<Option key="false" value="false">
Null值不替换原有数据
</Option>
</Select>
</FormItem>
)}
{getField(NAME_FIELD)[index].updateMode === 'upsert' &&
(isHavePrimaryKey(
getFieldValue(NAME_FIELD)[index].type,
) ||
!isDisabledUpdateMode(
getFieldValue(NAME_FIELD)[index].type,
disableUpdateMode,
componentVersion,
)) && (
<FormItem
label="主键"
tooltip="主键必须存在于表字段中"
name={[index, 'primaryKey']}
rules={[
{
required: true,
message: '请输入主键',
},
]}
>
<Select
className="right-select"
listHeight={200}
mode="multiple"
showSearch
showArrow
filterOption={(input, option) =>
option?.props.children
.toLowerCase()
.indexOf(input.toLowerCase()) >=
0
}
>
{primaryKeyOptionTypes}
</Select>
</FormItem>
)}
</>
)}
</FormItem>
</>
)}
</>
)}
</FormItem>
{/* 高级参数按钮 */}
<FormItem wrapperCol={{ span: 24 }}>
<Button
block
type="link"
onClick={() => setShowAdvancedParams(!showAdvancedParams)}
>
高级参数{showAdvancedParams ? <UpOutlined /> : <DownOutlined />}
</Button>
</FormItem>
{/* 高级参数抽屉 */}
<FormItem hidden={!showAdvancedParams} noStyle dependencies={[[index, 'type']]}>
{({ getFieldValue }) => (
<>
{isHaveParallelism(getFieldValue(NAME_FIELD)[index].type) && (
<FormItem name={[index, 'parallelism']} label="并行度">
<InputNumber style={{ width: '100%' }} min={1} precision={0} />
</FormItem>
)}
{isES(getFieldValue(NAME_FIELD)[index].type) && isFlink112 && (
<FormItem name={[index, 'bulkFlushMaxActions']} label="数据输出条数">
<InputNumber
style={{ width: '100%' }}
min={1}
max={10000}
precision={0}
/>
</FormItem>
)}
{isKafka(getFieldValue(NAME_FIELD)[index].type) && (
<FormItem
label=""
name={[index, 'enableKeyPartitions']}
valuePropName="checked"
>
<Checkbox style={{ marginLeft: 90 }} defaultChecked={false}>
根据字段(Key)分区
</Checkbox>
</FormItem>
)}
{getFieldValue(NAME_FIELD)[index].type === DATA_SOURCE_ENUM.ES7 && (
<FormItem
label="索引映射"
tooltip={
<span>
ElasticSearch的索引映射配置,仅当动态索引时生效,更多请参考
<a
rel="noopener noreferrer"
target="_blank"
href={HELP_DOC_URL.INDEX}
>
帮助文档
</a>
</span>
}
name={[index, 'indexDefinition']}
>
<Input.TextArea
placeholder={DEFAULT_MAPPING_TEXT}
style={{ minHeight: '200px' }}
/>
</FormItem>
)}
<FormItem noStyle dependencies={[[index, 'enableKeyPartitions']]}>
{({ getFieldValue: getField }) =>
getField(NAME_FIELD)[index].enableKeyPartitions && (
<FormItem
label="分区字段"
name={[index, 'partitionKeys']}
rules={[{ required: true, message: '请选择分区字段' }]}
>
<Select
className="right-select"
mode="multiple"
showSearch
showArrow
filterOption={(input, option) =>
option?.props.children
.toLowerCase()
.indexOf(input.toLowerCase()) >= 0
}
>
{getColumnsByColumnsText(
getField(NAME_FIELD)[index].columnsText,
).map((column) => {
const fields = column.field?.trim();
return (
<Option value={fields} key={fields}>
{fields}
</Option>
);
})}
</Select>
</FormItem>
)
}
</FormItem>
{isRDB(getFieldValue(NAME_FIELD)[index].type) && (
<>
<FormItem
label="数据输出时间"
name={[index, 'batchWaitInterval']}
rules={[{ required: true, message: '请输入数据输出时间' }]}
>
<InputNumber
style={{ width: '100%' }}
min={0}
max={600000}
precision={0}
addonAfter="ms/次"
/>
</FormItem>
<FormItem
label="数据输出条数"
name={[index, 'batchSize']}
rules={[{ required: true, message: '请输入数据输出条数' }]}
>
<InputNumber
style={{ width: '100%' }}
min={0}
max={
getFieldValue(NAME_FIELD)[index].type ===
DATA_SOURCE_ENUM.KUDU
? 100000
: 10000
}
precision={0}
addonAfter="条/次"
/>
</FormItem>
</>
)}
{!isHaveParallelism(getFieldValue(NAME_FIELD)[index].type) && (
<FormItem
label="分区类型"
tooltip="分区类型包括 DAY、HOUR、MINUTE三种。若分区不存在则会自动创建,自动创建的分区时间以当前任务运行的服务器时间为准"
name={[index, 'partitionType']}
initialValue="DAY"
>
<Select className="right-select">
<Option value="DAY">DAY</Option>
<Option value="HOUR">HOUR</Option>
<Option value="MINUTE">MINUTE</Option>
</Select>
</FormItem>
)}
{/* 添加自定义参数 */}
{!isSqlServer(getFieldValue(NAME_FIELD)[index].type) && (
<CustomParams index={index} />
)}
</>
)}
</FormItem>
<FormItem shouldUpdate noStyle>
{({ getFieldValue }) => (
<DataPreviewModal
visible={visible}
type={getFieldValue(NAME_FIELD)[index].type}
onCancel={() => setVisible(false)}
params={params}
/>
)}
</FormItem>
</>
);
} | the_stack |
//@ts-check
///<reference path="devkit.d.ts" />
declare namespace DevKit {
namespace Formmsdyn_projecttask_Information {
interface Header extends DevKit.Controls.IHeader {
/** Select the project name. */
msdyn_project: DevKit.Controls.Lookup;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
/** Status of the Project Task */
statecode: DevKit.Controls.OptionSet;
}
interface tab__7A08287E_9B25_4EE0_A2DD_288055BD63A7_Sections {
_4FDEB155_C726_4210_A41F_97CE03BD0A9D: DevKit.Controls.Section;
_7A08287E_9B25_4EE0_A2DD_288055BD63A7_SECTION_4: DevKit.Controls.Section;
notes_section: DevKit.Controls.Section;
}
interface tab_tab_2_Sections {
tab_2_section_1: DevKit.Controls.Section;
tab_2_section_2: DevKit.Controls.Section;
}
interface tab__7A08287E_9B25_4EE0_A2DD_288055BD63A7 extends DevKit.Controls.ITab {
Section: tab__7A08287E_9B25_4EE0_A2DD_288055BD63A7_Sections;
}
interface tab_tab_2 extends DevKit.Controls.ITab {
Section: tab_tab_2_Sections;
}
interface Tabs {
_7A08287E_9B25_4EE0_A2DD_288055BD63A7: tab__7A08287E_9B25_4EE0_A2DD_288055BD63A7;
tab_2: tab_tab_2;
}
interface Body {
Tab: Tabs;
/** Enter a description of the project task. */
msdyn_description: DevKit.Controls.String;
/** Shows the duration in days for the task. */
msdyn_duration: DevKit.Controls.Double;
/** Shows the effort hours required for the task. */
msdyn_Effort: DevKit.Controls.Double;
/** Select the organizational unit of the resource who should perform the work. */
msdyn_OrganizationalUnitPricingDimension: DevKit.Controls.Lookup;
/** Select the summary or parent task in the hierarchy that contains a child task. */
msdyn_parenttask: DevKit.Controls.Lookup;
/** Select the project name. */
msdyn_project: DevKit.Controls.Lookup;
/** Select the resource role for the task. */
msdyn_ResourceCategoryPricingDimension: DevKit.Controls.Lookup;
/** Shows the scheduled duration of the project task, specified in minutes. */
msdyn_scheduleddurationminutes: DevKit.Controls.Integer;
/** Enter the scheduled end time of the project. */
msdyn_scheduledend: DevKit.Controls.Date;
/** Enter the scheduled start time of the project task. */
msdyn_scheduledstart: DevKit.Controls.Date;
/** Type the name of the custom entity. */
msdyn_subject: DevKit.Controls.String;
/** Select the transaction category for the task. */
msdyn_transactioncategory: DevKit.Controls.Lookup;
/** Shows the ID of the task in the work breakdown structure (WBS). */
msdyn_WBSID: DevKit.Controls.String;
notescontrol: DevKit.Controls.Note;
/** Owner Id */
OwnerId: DevKit.Controls.Lookup;
}
}
class Formmsdyn_projecttask_Information extends DevKit.IForm {
/**
* DynamicsCrm.DevKit form msdyn_projecttask_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_projecttask_Information */
Body: DevKit.Formmsdyn_projecttask_Information.Body;
/** The Header section of form msdyn_projecttask_Information */
Header: DevKit.Formmsdyn_projecttask_Information.Header;
}
class msdyn_projecttaskApi {
/**
* DynamicsCrm.DevKit msdyn_projecttaskApi
* @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;
/** Date and time when the project task was created. */
CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who created the record. */
CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Shows the exchange rate for the currency associated with the entity with respect to the base currency. */
ExchangeRate: DevKit.WebApi.DecimalValueReadonly;
/** Sequence number of the import that created this record. */
ImportSequenceNumber: DevKit.WebApi.IntegerValue;
/** Unique identifier of user who last modified the record. */
ModifiedBy: DevKit.WebApi.LookupValueReadonly;
/** Date and time when the record was modified. */
ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly;
/** Unique identifier of the delegate user who modified the record. */
ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly;
/** Enter the value of the actual cost consumed based on work reported to be completed on the task. */
msdyn_Actualcost: DevKit.WebApi.MoneyValue;
/** Value of the Actual Cost in base currency. */
msdyn_actualcost_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the actual duration of the project task in days */
msdyn_actualdurationminutes: DevKit.WebApi.IntegerValue;
/** Shows the hours submitted against the task. */
msdyn_ActualEffort: DevKit.WebApi.DoubleValue;
/** Enter the actual end time of the project task. */
msdyn_actualend_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Actual Sales Amount */
msdyn_ActualSales: DevKit.WebApi.MoneyValue;
/** Shows the value of the actual sales in the base currency. */
msdyn_actualsales_Base: DevKit.WebApi.MoneyValueReadonly;
/** Enter the actual start time of the project task. */
msdyn_actualstart_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue;
/** Shows whether the aggregation is happening upstream or downstream. */
msdyn_AggregationDirection: DevKit.WebApi.OptionSetValue;
/** Type the project team members that are assigned to task. */
msdyn_AssignedResources: DevKit.WebApi.StringValue;
/** Select the project team member that has been assigned to a task. */
msdyn_AssignedTeamMembers: DevKit.WebApi.LookupValue;
/** Shows whether auto scheduling was used for this task. */
msdyn_autoscheduling: DevKit.WebApi.BooleanValue;
/** Enter the forecast of the total cost to complete the task. */
msdyn_CostAtCompleteEstimate: DevKit.WebApi.MoneyValueReadonly;
/** Value of the Cost estimate at complete (EAC) in base currency. */
msdyn_costatcompleteestimate_Base: DevKit.WebApi.MoneyValueReadonly;
/** Enter the consumption of the total cost in percentage. */
msdyn_CostConsumptionPercentage: DevKit.WebApi.DecimalValueReadonly;
/** The cost estimate contour for the task */
msdyn_CostEstimateContour: DevKit.WebApi.StringValue;
/** Enter a description of the project task. */
msdyn_description: DevKit.WebApi.StringValue;
/** Shows the duration in days for the task. */
msdyn_duration: DevKit.WebApi.DoubleValue;
/** Shows the effort hours required for the task. */
msdyn_Effort: DevKit.WebApi.DoubleValue;
/** The effort distribution */
msdyn_EffortContour: DevKit.WebApi.StringValue;
/** Shows the forecast of total effort to complete the task. */
msdyn_EffortEstimateAtComplete: DevKit.WebApi.DoubleValue;
/** Shows whether the task is a line task */
msdyn_IsLineTask: DevKit.WebApi.BooleanValue;
/** Show whether this task is a milestone. */
msdyn_IsMilestone: DevKit.WebApi.BooleanValue;
/** The id of the project task in MS Project Client. */
msdyn_MSProjectClientId: DevKit.WebApi.StringValue;
/** Shows the number of resources that are estimated for the task. This is not the number of resources assigned to the task. */
msdyn_numberofresources: DevKit.WebApi.IntegerValue;
/** Select the organizational unit of the resource who should perform the work. */
msdyn_OrganizationalUnitPricingDimension: DevKit.WebApi.LookupValue;
/** Select the summary or parent task in the hierarchy that contains a child task. */
msdyn_parenttask: DevKit.WebApi.LookupValue;
/** Enter the value of the cost the service provider will incur based on the estimated work and cost rates in the pricelist. */
msdyn_plannedCost: DevKit.WebApi.MoneyValue;
/** Enter the value of cost estimated in base currency. */
msdyn_plannedcost_Base: DevKit.WebApi.MoneyValueReadonly;
/** Planned Sales Amount */
msdyn_PlannedSales: DevKit.WebApi.MoneyValue;
/** Shows the value of the planned sales in the base currency. */
msdyn_plannedsales_Base: DevKit.WebApi.MoneyValueReadonly;
/** Processing data for the plugin pipeline */
msdyn_PluginProcessingData: DevKit.WebApi.IntegerValue;
/** Enter the percentage indicating work completed. */
msdyn_Progress: DevKit.WebApi.DecimalValue;
/** Select the project name. */
msdyn_project: DevKit.WebApi.LookupValue;
/** Shows the entity instances. */
msdyn_projecttaskId: DevKit.WebApi.GuidValue;
/** Enter the cost left over that can be consumed for future work. */
msdyn_RemainingCost: DevKit.WebApi.MoneyValue;
/** Shows the value of the remaining cost in the base currency. */
msdyn_remainingcost_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the hours remaining to complete the task. */
msdyn_RemainingHours: DevKit.WebApi.DoubleValue;
/** Remaining Sales Amount */
msdyn_RemainingSales: DevKit.WebApi.MoneyValue;
/** Shows the value of the remaining sales in the base currency. */
msdyn_remainingsales_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the hours assigned by generic resource. */
msdyn_RequestedHours: DevKit.WebApi.DoubleValue;
/** Select the resource role for the task. */
msdyn_resourcecategory: DevKit.WebApi.LookupValue;
/** Select the resource role for the task. */
msdyn_ResourceCategoryPricingDimension: DevKit.WebApi.LookupValue;
/** Select the organizational unit of the resource who should perform the work. */
msdyn_ResourceOrganizationalUnitId: DevKit.WebApi.LookupValue;
/** Shows the utilization units for a resource that is assigned to a project task */
msdyn_ResourceUtilization: DevKit.WebApi.DecimalValue;
/** Shows the sales consumption percentage for this task. */
msdyn_SalesConsumptionPercentage: DevKit.WebApi.DecimalValueReadonly;
/** Shows the sales estimate at the completion of this task. */
msdyn_SalesEstimateAtComplete: DevKit.WebApi.MoneyValueReadonly;
/** Value of the Sales Estimate At Complete (EAC) in base currency. */
msdyn_salesestimateatcomplete_Base: DevKit.WebApi.MoneyValueReadonly;
/** The sales estimate contour */
msdyn_SalesEstimateContour: DevKit.WebApi.StringValue;
/** Shows the sales variance for this task. */
msdyn_SalesVariance: DevKit.WebApi.MoneyValueReadonly;
/** Shows the value of the sales variance in the base currency. */
msdyn_salesvariance_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the scheduled duration of the project task, specified in minutes. */
msdyn_scheduleddurationminutes: DevKit.WebApi.IntegerValue;
/** Enter the scheduled end time of the project. */
msdyn_scheduledend_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Shows the scheduled hours for the task. */
msdyn_ScheduledHours: DevKit.WebApi.DoubleValue;
/** Enter the scheduled start time of the project task. */
msdyn_scheduledstart_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue;
/** Shows the variance between the estimated work and the forecasted work based on the estimate at completion (EAC). */
msdyn_ScheduleVariance: DevKit.WebApi.DoubleValue;
/** Internal flag to avoid the update process on the estimate lines of the project task */
msdyn_skipupdateestimateline: DevKit.WebApi.BooleanValue;
/** Type the name of the custom entity. */
msdyn_subject: DevKit.WebApi.StringValue;
/** Select the transaction category for the task. */
msdyn_transactioncategory: DevKit.WebApi.LookupValue;
/** Enter the variance between the estimated cost and the forecasted cost based on the estimate at completion (EAC). */
msdyn_VarianceOfCost: DevKit.WebApi.MoneyValueReadonly;
/** Shows the value of the cost variance in the base currency. */
msdyn_varianceofcost_Base: DevKit.WebApi.MoneyValueReadonly;
/** Shows the ID of the task in the work breakdown structure (WBS). */
msdyn_WBSID: DevKit.WebApi.StringValue;
/** 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;
/** Contains the id of the process associated with the entity. */
processid: DevKit.WebApi.GuidValue;
/** Unique identifier of the Stage. */
StageId: DevKit.WebApi.GuidValue;
/** Status of the Project Task */
statecode: DevKit.WebApi.OptionSetValue;
/** Reason for the status of the Project Task */
statuscode: DevKit.WebApi.OptionSetValue;
/** For internal use only. */
TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue;
/** Shows the currency associated with the entity. */
TransactionCurrencyId: DevKit.WebApi.LookupValue;
/** A comma separated list of string values representing the unique identifiers of stages in a Business Process Flow Instance in the order that they occur. */
traversedpath: DevKit.WebApi.StringValue;
/** 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_projecttask {
enum msdyn_AggregationDirection {
/** 2 */
Both,
/** 1 */
Downstream,
/** 0 */
Upstream
}
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'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'} | the_stack |
import {
AUTH_ACTION as AA,
CONNECTION_ACTION as CA,
EVENT_ACTION as EA,
PARSER_ACTION as XA,
PRESENCE_ACTION as UA,
RECORD_ACTION as RA,
RPC_ACTION as PA,
TOPIC as T,
} from '../../../../constants'
export const MESSAGE_SEPERATOR = String.fromCharCode(30) // ASCII Record Seperator 1E
export const MESSAGE_PART_SEPERATOR = String.fromCharCode(31) // ASCII Unit Separator 1F
export const PAYLOAD_ENCODING = {
JSON: 0x00,
DEEPSTREAM: 0x01,
}
export const TOPIC = {
PARSER: { TEXT: 'X', BYTE: T.PARSER },
CONNECTION: { TEXT: 'C', BYTE: T.CONNECTION },
AUTH: { TEXT: 'A', BYTE: T.AUTH },
ERROR: { TEXT: 'X', BYTE: T.ERROR },
EVENT: { TEXT: 'E', BYTE: T.EVENT },
RECORD: { TEXT: 'R', BYTE: T.RECORD },
RPC: { TEXT: 'P', BYTE: T.RPC },
PRESENCE: { TEXT: 'U', BYTE: T.PRESENCE },
}
export const PARSER_ACTIONS = {
UNKNOWN_TOPIC: { BYTE: XA.UNKNOWN_TOPIC },
UNKNOWN_ACTION: { BYTE: XA.UNKNOWN_ACTION },
INVALID_MESSAGE: { BYTE: XA.INVALID_MESSAGE },
INVALID_META_PARAMS: { BYTE: XA.INVALID_META_PARAMS },
MESSAGE_PARSE_ERROR: { BYTE: XA.MESSAGE_PARSE_ERROR },
MAXIMUM_MESSAGE_SIZE_EXCEEDED: { BYTE: XA.MAXIMUM_MESSAGE_SIZE_EXCEEDED },
ERROR: { BYTE: XA.ERROR },
}
export const CONNECTION_ACTIONS = {
ERROR: { TEXT: 'E', BYTE: CA.ERROR },
PING: { TEXT: 'PI', BYTE: CA.PING },
PONG: { TEXT: 'PO', BYTE: CA.PONG },
ACCEPT: { TEXT: 'A', BYTE: CA.ACCEPT },
CHALLENGE: { TEXT: 'CH', BYTE: CA.CHALLENGE },
REJECTION: { TEXT: 'REJ', BYTE: CA.REJECT },
REDIRECT: { TEXT: 'RED', BYTE: CA.REDIRECT },
CLOSED: { BYTE: CA.CLOSED },
CLOSING: { BYTE: CA.CLOSING },
CONNECTION_AUTHENTICATION_TIMEOUT: { BYTE: CA.AUTHENTICATION_TIMEOUT },
INVALID_MESSAGE: { BYTE: CA.INVALID_MESSAGE },
}
export const AUTH_ACTIONS = {
ERROR: { TEXT: 'E', BYTE: AA.ERROR },
REQUEST: { TEXT: 'REQ', BYTE: AA.REQUEST },
AUTH_SUCCESSFUL: { BYTE: AA.AUTH_SUCCESSFUL, PAYLOAD_ENCODING: PAYLOAD_ENCODING.DEEPSTREAM },
AUTH_UNSUCCESSFUL: { BYTE: AA.AUTH_UNSUCCESSFUL, PAYLOAD_ENCODING: PAYLOAD_ENCODING.DEEPSTREAM },
TOO_MANY_AUTH_ATTEMPTS: { BYTE: AA.TOO_MANY_AUTH_ATTEMPTS },
// MESSAGE_PERMISSION_ERROR: { BYTE: AA.MESSAGE_PERMISSION_ERROR },
// MESSAGE_DENIED: { BYTE: AA.MESSAGE_DENIED },
INVALID_MESSAGE_DATA: { BYTE: AA.INVALID_MESSAGE_DATA },
INVALID_MESSAGE: { BYTE: AA.INVALID_MESSAGE },
}
export const EVENT_ACTIONS = {
ERROR: { TEXT: 'E', BYTE: EA.ERROR },
EMIT: { TEXT: 'EVT', BYTE: EA.EMIT, PAYLOAD_ENCODING: PAYLOAD_ENCODING.DEEPSTREAM },
SUBSCRIBE: { TEXT: 'S', BYTE: EA.SUBSCRIBE },
UNSUBSCRIBE: { TEXT: 'US', BYTE: EA.UNSUBSCRIBE },
LISTEN: { TEXT: 'L', BYTE: EA.LISTEN },
UNLISTEN: { TEXT: 'UL', BYTE: EA.UNLISTEN },
LISTEN_ACCEPT: { TEXT: 'LA', BYTE: EA.LISTEN_ACCEPT },
LISTEN_REJECT: { TEXT: 'LR', BYTE: EA.LISTEN_REJECT },
SUBSCRIPTION_FOR_PATTERN_FOUND: { TEXT: 'SP', BYTE: EA.SUBSCRIPTION_FOR_PATTERN_FOUND },
SUBSCRIPTION_FOR_PATTERN_REMOVED: { TEXT: 'SR', BYTE: EA.SUBSCRIPTION_FOR_PATTERN_REMOVED },
MESSAGE_PERMISSION_ERROR: { BYTE: EA.MESSAGE_PERMISSION_ERROR },
MESSAGE_DENIED: { BYTE: EA.MESSAGE_DENIED },
INVALID_MESSAGE_DATA: { BYTE: EA.INVALID_MESSAGE_DATA },
MULTIPLE_SUBSCRIPTIONS: { BYTE: EA.MULTIPLE_SUBSCRIPTIONS },
NOT_SUBSCRIBED: { BYTE: EA.NOT_SUBSCRIBED },
}
export const RECORD_ACTIONS = {
ERROR: { TEXT: 'E', BYTE: RA.ERROR },
CREATE: { TEXT: 'CR', BYTE: RA.CREATE },
READ: { TEXT: 'R', BYTE: RA.READ },
READ_RESPONSE: { BYTE: RA.READ_RESPONSE, PAYLOAD_ENCODING: PAYLOAD_ENCODING.JSON },
HEAD: { TEXT: 'HD', BYTE: RA.HEAD },
HEAD_RESPONSE: { BYTE: RA.HEAD_RESPONSE },
CREATEANDUPDATE: { TEXT: 'CU', BYTE: RA.CREATEANDUPDATE },
CREATEANDPATCH: { BYTE: RA.CREATEANDPATCH, PAYLOAD_ENCODING: PAYLOAD_ENCODING.DEEPSTREAM },
UPDATE: { TEXT: 'U', BYTE: RA.UPDATE, PAYLOAD_ENCODING: PAYLOAD_ENCODING.JSON },
PATCH: { TEXT: 'P', BYTE: RA.PATCH, PAYLOAD_ENCODING: PAYLOAD_ENCODING.DEEPSTREAM },
ERASE: { BYTE: RA.ERASE, PAYLOAD_ENCODING: PAYLOAD_ENCODING.DEEPSTREAM },
WRITE_ACKNOWLEDGEMENT: { TEXT: 'WA', BYTE: RA.WRITE_ACKNOWLEDGEMENT },
DELETE: { TEXT: 'D', BYTE: RA.DELETE },
DELETE_SUCCESS: { BYTE: RA.DELETE_SUCCESS },
DELETED: { BYTE: RA.DELETED },
LISTEN_RESPONSE_TIMEOUT: { BYTE: RA.LISTEN_RESPONSE_TIMEOUT },
SUBSCRIBEANDHEAD: { BYTE: RA.SUBSCRIBEANDHEAD },
// SUBSCRIBEANDHEAD_RESPONSE: { BYTE: RA.SUBSCRIBEANDHEAD_RESPONSE },
SUBSCRIBEANDREAD: { BYTE: RA.SUBSCRIBEANDREAD },
// SUBSCRIBEANDREAD_RESPONSE: { BYTE: RA.SUBSCRIBEANDREAD_RESPONSE },
SUBSCRIBECREATEANDREAD: { TEXT: 'CR', BYTE: RA.SUBSCRIBECREATEANDREAD },
// SUBSCRIBECREATEANDREAD_RESPONSE: { BYTE: RA.SUBSCRIBECREATEANDREAD_RESPONSE },
SUBSCRIBECREATEANDUPDATE: { BYTE: RA.SUBSCRIBECREATEANDUPDATE },
// SUBSCRIBECREATEANDUPDATE_RESPONSE: { BYTE: RA.SUBSCRIBECREATEANDUPDATE_RESPONSE },
SUBSCRIBE: { TEXT: 'S', BYTE: RA.SUBSCRIBE },
UNSUBSCRIBE: { TEXT: 'US', BYTE: RA.UNSUBSCRIBE },
LISTEN: { TEXT: 'L', BYTE: RA.LISTEN },
UNLISTEN: { TEXT: 'UL', BYTE: RA.UNLISTEN },
LISTEN_ACCEPT: { TEXT: 'LA', BYTE: RA.LISTEN_ACCEPT },
LISTEN_REJECT: { TEXT: 'LR', BYTE: RA.LISTEN_REJECT },
SUBSCRIPTION_HAS_PROVIDER: { TEXT: 'SH', BYTE: RA.SUBSCRIPTION_HAS_PROVIDER },
SUBSCRIPTION_HAS_NO_PROVIDER: { BYTE: RA.SUBSCRIPTION_HAS_NO_PROVIDER },
SUBSCRIPTION_FOR_PATTERN_FOUND: { TEXT: 'SP', BYTE: RA.SUBSCRIPTION_FOR_PATTERN_FOUND },
SUBSCRIPTION_FOR_PATTERN_REMOVED: { TEXT: 'SR', BYTE: RA.SUBSCRIPTION_FOR_PATTERN_REMOVED },
CACHE_RETRIEVAL_TIMEOUT: { BYTE: RA.CACHE_RETRIEVAL_TIMEOUT },
STORAGE_RETRIEVAL_TIMEOUT: { BYTE: RA.STORAGE_RETRIEVAL_TIMEOUT },
VERSION_EXISTS: { BYTE: RA.VERSION_EXISTS },
// HAS: { TEXT: 'H', BYTE: RA.HAS },
// HAS_RESPONSE: { BYTE: RA.HAS_RESPONSE },
SNAPSHOT: { TEXT: 'SN', BYTE: RA.READ },
RECORD_LOAD_ERROR: { BYTE: RA.RECORD_LOAD_ERROR },
RECORD_CREATE_ERROR: { BYTE: RA.RECORD_CREATE_ERROR },
RECORD_UPDATE_ERROR: { BYTE: RA.RECORD_UPDATE_ERROR },
RECORD_DELETE_ERROR: { BYTE: RA.RECORD_DELETE_ERROR },
// RECORD_READ_ERROR: { BYTE: RA.RECORD_READ_ERROR },
RECORD_NOT_FOUND: { BYTE: RA.RECORD_NOT_FOUND },
INVALID_VERSION: { BYTE: RA.INVALID_VERSION },
INVALID_PATCH_ON_HOTPATH: { BYTE: RA.INVALID_PATCH_ON_HOTPATH },
MESSAGE_PERMISSION_ERROR: { BYTE: RA.MESSAGE_PERMISSION_ERROR },
MESSAGE_DENIED: { BYTE: RA.MESSAGE_DENIED },
INVALID_MESSAGE_DATA: { BYTE: RA.INVALID_MESSAGE_DATA },
MULTIPLE_SUBSCRIPTIONS: { BYTE: RA.MULTIPLE_SUBSCRIPTIONS },
NOT_SUBSCRIBED: { BYTE: RA.NOT_SUBSCRIBED },
}
export const RPC_ACTIONS = {
ERROR: { BYTE: PA.ERROR },
REQUEST: { TEXT: 'REQ', BYTE: PA.REQUEST, PAYLOAD_ENCODING: PAYLOAD_ENCODING.DEEPSTREAM },
ACCEPT: { BYTE: PA.ACCEPT },
RESPONSE: { TEXT: 'RES', BYTE: PA.RESPONSE, PAYLOAD_ENCODING: PAYLOAD_ENCODING.DEEPSTREAM },
REJECT: { TEXT: 'REJ', BYTE: PA.REJECT },
REQUEST_ERROR: { TEXT: 'E', BYTE: PA.REQUEST_ERROR, PAYLOAD_ENCODING: PAYLOAD_ENCODING.DEEPSTREAM },
PROVIDE: { TEXT: 'S', BYTE: PA.PROVIDE },
UNPROVIDE: { TEXT: 'US', BYTE: PA.UNPROVIDE },
NO_RPC_PROVIDER: { BYTE: PA.NO_RPC_PROVIDER },
RESPONSE_TIMEOUT: { BYTE: PA.RESPONSE_TIMEOUT },
ACCEPT_TIMEOUT: { BYTE: PA.ACCEPT_TIMEOUT },
MULTIPLE_ACCEPT: { BYTE: PA.MULTIPLE_ACCEPT },
MULTIPLE_RESPONSE: { BYTE: PA.MULTIPLE_RESPONSE },
INVALID_RPC_CORRELATION_ID: { BYTE: PA.INVALID_RPC_CORRELATION_ID },
MESSAGE_PERMISSION_ERROR: { BYTE: PA.MESSAGE_PERMISSION_ERROR },
MESSAGE_DENIED: { BYTE: PA.MESSAGE_DENIED },
INVALID_MESSAGE_DATA: { BYTE: PA.INVALID_MESSAGE_DATA },
MULTIPLE_PROVIDERS: { BYTE: PA.MULTIPLE_PROVIDERS },
NOT_PROVIDED: { BYTE: PA.NOT_PROVIDED },
}
export const PRESENCE_ACTIONS = {
ERROR: { TEXT: 'E', BYTE: UA.ERROR },
QUERY_ALL: { BYTE: UA.QUERY_ALL },
QUERY_ALL_RESPONSE: { BYTE: UA.QUERY_ALL_RESPONSE, PAYLOAD_ENCODING: PAYLOAD_ENCODING.JSON },
QUERY: { TEXT: 'Q', BYTE: UA.QUERY },
QUERY_RESPONSE: { BYTE: UA.QUERY_RESPONSE, PAYLOAD_ENCODING: PAYLOAD_ENCODING.JSON },
PRESENCE_JOIN: { TEXT: 'PNJ', BYTE: UA.PRESENCE_JOIN },
PRESENCE_JOIN_ALL: { TEXT: 'PNJ', BYTE: UA.PRESENCE_JOIN_ALL },
PRESENCE_LEAVE: { TEXT: 'PNL', BYTE: UA.PRESENCE_LEAVE },
PRESENCE_LEAVE_ALL: { TEXT: 'PNL', BYTE: UA.PRESENCE_LEAVE_ALL },
SUBSCRIBE: { TEXT: 'S', BYTE: UA.SUBSCRIBE },
UNSUBSCRIBE: { TEXT: 'US', BYTE: UA.UNSUBSCRIBE },
SUBSCRIBE_ALL: { BYTE: UA.SUBSCRIBE_ALL },
UNSUBSCRIBE_ALL: { BYTE: UA.UNSUBSCRIBE_ALL },
INVALID_PRESENCE_USERS: { BYTE: UA.INVALID_PRESENCE_USERS },
MESSAGE_PERMISSION_ERROR: { BYTE: UA.MESSAGE_PERMISSION_ERROR },
MESSAGE_DENIED: { BYTE: UA.MESSAGE_DENIED },
// INVALID_MESSAGE_DATA: { BYTE: UA.INVALID_MESSAGE_DATA },
MULTIPLE_SUBSCRIPTIONS: { BYTE: UA.MULTIPLE_SUBSCRIPTIONS },
NOT_SUBSCRIBED: { BYTE: UA.NOT_SUBSCRIBED },
}
export const DEEPSTREAM_TYPES = {
STRING: 'S',
OBJECT: 'O',
NUMBER: 'N',
NULL: 'L',
TRUE: 'T',
FALSE: 'F',
UNDEFINED: 'U',
}
export const TOPIC_BYTE_TO_TEXT = convertMap(TOPIC, 'BYTE', 'TEXT')
export const TOPIC_TEXT_TO_BYTE = convertMap(TOPIC, 'TEXT', 'BYTE')
export const TOPIC_TEXT_TO_KEY = reverseMap(specifyMap(TOPIC, 'TEXT'))
export const TOPIC_BYTE_TO_KEY = reverseMap(specifyMap(TOPIC, 'BYTE'))
export const TOPIC_BYTES = specifyMap(TOPIC, 'BYTE')
export const ACTIONS_BYTE_TO_PAYLOAD: any = {}
export const ACTIONS_BYTE_TO_TEXT: any = {}
export const ACTIONS_TEXT_TO_BYTE: any = {}
export const ACTIONS_BYTES: any = {}
export const ACTIONS_TEXT_TO_KEY: any = {}
export const ACTIONS_BYTE_TO_KEY: any = {}
export const ACTIONS = {
[TOPIC.PARSER.BYTE]: PARSER_ACTIONS,
[TOPIC.CONNECTION.BYTE]: CONNECTION_ACTIONS,
[TOPIC.AUTH.BYTE]: AUTH_ACTIONS,
[TOPIC.EVENT.BYTE]: EVENT_ACTIONS,
[TOPIC.RECORD.BYTE]: RECORD_ACTIONS,
[TOPIC.RPC.BYTE]: RPC_ACTIONS,
[TOPIC.PRESENCE.BYTE]: PRESENCE_ACTIONS,
}
for (const key in ACTIONS) {
ACTIONS_BYTE_TO_PAYLOAD[key] = convertMap(ACTIONS[key], 'BYTE', 'PAYLOAD_ENCODING')
ACTIONS_BYTE_TO_TEXT[key] = convertMap(ACTIONS[key], 'BYTE', 'TEXT')
ACTIONS_TEXT_TO_BYTE[key] = convertMap(ACTIONS[key], 'TEXT', 'BYTE')
ACTIONS_BYTES[key] = specifyMap(ACTIONS[key], 'BYTE')
ACTIONS_TEXT_TO_KEY[key] = reverseMap(specifyMap(ACTIONS[key], 'TEXT'))
ACTIONS_BYTE_TO_KEY[key] = reverseMap(specifyMap(ACTIONS[key], 'BYTE'))
}
/**
* convertMap({ a: { x: 1 }, b: { x: 2 }, c: { x : 3 } }, 'x', 'y')
* ===
* { a: { y: 1 }, b: { y: 2 }, c: { y : 3 } }
*/
function convertMap (map: any, from: any, to: any) {
const result: any = {}
for (const key in map) {
result[map[key][from]] = map[key][to]
}
return result
}
/**
* specifyMap({ a: { x: 1 }, b: { x: 2 }, c: { x : 3 } }, 'x')
* ===
* { a: 1, b: 2, c: 3 }
*/
function specifyMap (map: any, innerKey: any) {
const result: any = {}
for (const key in map) {
result[key] = map[key][innerKey]
}
return result
}
/**
* Takes a key-value map and returns
* a map with { value: key } of the old map
*/
function reverseMap (map: any) {
const reversedMap: any = {}
for (const key in map) {
reversedMap[map[key]] = key
}
return reversedMap
} | the_stack |
import '../../../test/common-test-setup-karma';
import './gr-group-members';
import {GrGroupMembers, ItemType} from './gr-group-members';
import {
addListenerForTest,
mockPromise,
queryAll,
queryAndAssert,
stubBaseUrl,
stubRestApi,
} from '../../../test/test-utils';
import {
AccountId,
AccountInfo,
EmailAddress,
GroupId,
GroupInfo,
GroupName,
} from '../../../types/common';
import {GrButton} from '../../shared/gr-button/gr-button';
import {GrAutocomplete} from '../../shared/gr-autocomplete/gr-autocomplete';
import * as MockInteractions from '@polymer/iron-test-helpers/mock-interactions';
import {PageErrorEvent} from '../../../types/events.js';
const basicFixture = fixtureFromElement('gr-group-members');
suite('gr-group-members tests', () => {
let element: GrGroupMembers;
let groups: GroupInfo;
let groupMembers: AccountInfo[];
let includedGroups: GroupInfo[];
let groupStub: sinon.SinonStub;
setup(async () => {
groups = {
id: 'testId1' as GroupId,
name: 'Administrators' as GroupName,
owner: 'Administrators',
group_id: 1,
};
groupMembers = [
{
_account_id: 1000097 as AccountId,
name: 'Jane Roe',
email: 'jane.roe@example.com' as EmailAddress,
username: 'jane',
},
{
_account_id: 1000096 as AccountId,
name: 'Test User',
email: 'john.doe@example.com' as EmailAddress,
},
{
_account_id: 1000095 as AccountId,
name: 'Gerrit',
},
{
_account_id: 1000098 as AccountId,
},
];
includedGroups = [
{
url: 'https://group/url',
options: {
visible_to_all: false,
},
id: 'testId' as GroupId,
name: 'testName' as GroupName,
},
{
url: '/group/url',
options: {
visible_to_all: false,
},
id: 'testId2' as GroupId,
name: 'testName2' as GroupName,
},
{
url: '#/group/url',
options: {
visible_to_all: false,
},
id: 'testId3' as GroupId,
name: 'testName3' as GroupName,
},
];
stubRestApi('getSuggestedAccounts').callsFake(input => {
if (input.startsWith('test')) {
return Promise.resolve([
{
_account_id: 1000096 as AccountId,
name: 'test-account',
email: 'test.account@example.com' as EmailAddress,
username: 'test123',
},
{
_account_id: 1001439 as AccountId,
name: 'test-admin',
email: 'test.admin@example.com' as EmailAddress,
username: 'test_admin',
},
{
_account_id: 1001439 as AccountId,
name: 'test-git',
username: 'test_git',
},
]);
} else {
return Promise.resolve([]);
}
});
stubRestApi('getSuggestedGroups').callsFake(input => {
if (input.startsWith('test')) {
return Promise.resolve({
'test-admin': {
id: '1ce023d3fb4e4260776fb92cd08b52bbd21ce70a',
},
'test/Administrator (admin)': {
id: 'test%3Aadmin',
},
});
} else {
return Promise.resolve({});
}
});
stubRestApi('getGroupMembers').returns(Promise.resolve(groupMembers));
stubRestApi('getIsGroupOwner').returns(Promise.resolve(true));
stubRestApi('getIncludedGroup').returns(Promise.resolve(includedGroups));
element = basicFixture.instantiate();
await element.updateComplete;
stubBaseUrl('https://test/site');
element.groupId = 'testId1' as GroupId;
groupStub = stubRestApi('getGroupConfig').returns(Promise.resolve(groups));
return element.loadGroupDetails();
});
test('includedGroups', () => {
assert.equal(element.includedGroups!.length, 3);
assert.equal(
queryAll<HTMLAnchorElement>(element, '.nameColumn a')[0].href,
includedGroups[0].url
);
assert.equal(
queryAll<HTMLAnchorElement>(element, '.nameColumn a')[1].href,
'https://test/site/group/url'
);
assert.equal(
queryAll<HTMLAnchorElement>(element, '.nameColumn a')[2].href,
'https://test/site/group/url'
);
});
test('save members correctly', async () => {
element.groupOwner = true;
const memberName = 'test-admin';
const saveStub = stubRestApi('saveGroupMember').callsFake(() =>
Promise.resolve({})
);
const button = queryAndAssert<GrButton>(element, '#saveGroupMember');
assert.isTrue(button.hasAttribute('disabled'));
const groupMemberSearchInput = queryAndAssert<GrAutocomplete>(
element,
'#groupMemberSearchInput'
);
groupMemberSearchInput.text = memberName;
groupMemberSearchInput.value = '1234';
await element.updateComplete;
assert.isFalse(button.hasAttribute('disabled'));
return element.handleSavingGroupMember().then(() => {
assert.isTrue(button.hasAttribute('disabled'));
assert.isFalse(
queryAndAssert<HTMLHeadingElement>(
element,
'#Title'
).classList.contains('edited')
);
assert.equal(saveStub.lastCall.args[0], 'Administrators');
assert.equal(saveStub.lastCall.args[1], 1234);
});
});
test('save included groups correctly', async () => {
element.groupOwner = true;
const includedGroupName = 'testName';
const saveIncludedGroupStub = stubRestApi('saveIncludedGroup').callsFake(
() => Promise.resolve({id: '0' as GroupId})
);
const button = queryAndAssert<GrButton>(element, '#saveIncludedGroups');
assert.isTrue(button.hasAttribute('disabled'));
const includedGroupSearchInput = queryAndAssert<GrAutocomplete>(
element,
'#includedGroupSearchInput'
);
includedGroupSearchInput.text = includedGroupName;
includedGroupSearchInput.value = 'testId';
await element.updateComplete;
assert.isFalse(button.hasAttribute('disabled'));
return element.handleSavingIncludedGroups().then(() => {
assert.isTrue(button.hasAttribute('disabled'));
assert.isFalse(
queryAndAssert<HTMLHeadingElement>(
element,
'#Title'
).classList.contains('edited')
);
assert.equal(saveIncludedGroupStub.lastCall.args[0], 'Administrators');
assert.equal(saveIncludedGroupStub.lastCall.args[1], 'testId');
});
});
test('add included group 404 shows helpful error text', async () => {
element.groupOwner = true;
element.groupName = 'test' as GroupName;
const memberName = 'bad-name';
const alertStub = sinon.stub();
element.addEventListener('show-alert', alertStub);
const errorResponse = {...new Response(), status: 404, ok: false};
stubRestApi('saveIncludedGroup').callsFake((_, _non, errFn) => {
if (errFn !== undefined) {
errFn(errorResponse);
} else {
assert.fail('errFn is undefined');
}
return Promise.resolve(undefined);
});
const groupMemberSearchInput = queryAndAssert<GrAutocomplete>(
element,
'#groupMemberSearchInput'
);
groupMemberSearchInput.text = memberName;
groupMemberSearchInput.value = '1234';
await element.updateComplete;
element.handleSavingIncludedGroups().then(() => {
assert.isTrue(alertStub.called);
});
});
test('add included group network-error throws an exception', async () => {
element.groupOwner = true;
const memberName = 'bad-name';
stubRestApi('saveIncludedGroup').throws(new Error());
const groupMemberSearchInput = queryAndAssert<GrAutocomplete>(
element,
'#groupMemberSearchInput'
);
groupMemberSearchInput.text = memberName;
groupMemberSearchInput.value = '1234';
let exceptionThrown = false;
try {
await element.handleSavingIncludedGroups();
} catch (e) {
exceptionThrown = true;
}
assert.isTrue(exceptionThrown);
});
test('getAccountSuggestions empty', async () => {
const accounts = await element.getAccountSuggestions('nonexistent');
assert.equal(accounts.length, 0);
});
test('getAccountSuggestions non-empty', async () => {
const accounts = await element.getAccountSuggestions('test-');
assert.equal(accounts.length, 3);
assert.equal(accounts[0].name, 'test-account <test.account@example.com>');
assert.equal(accounts[1].name, 'test-admin <test.admin@example.com>');
assert.equal(accounts[2].name, 'test-git');
});
test('getGroupSuggestions empty', async () => {
const groups = await element.getGroupSuggestions('nonexistent');
assert.equal(groups.length, 0);
});
test('getGroupSuggestions non-empty', async () => {
const groups = await element.getGroupSuggestions('test');
assert.equal(groups.length, 2);
assert.equal(groups[0].name, 'test-admin');
assert.equal(groups[1].name, 'test/Administrator (admin)');
});
test('delete member', () => {
const deleteBtns = queryAll<GrButton>(element, '.deleteMembersButton');
MockInteractions.tap(deleteBtns[0]);
assert.equal(element.itemId, 1000097 as AccountId);
assert.equal(element.itemName, 'jane');
MockInteractions.tap(deleteBtns[1]);
assert.equal(element.itemId, 1000096 as AccountId);
assert.equal(element.itemName, 'Test User');
MockInteractions.tap(deleteBtns[2]);
assert.equal(element.itemId, 1000095 as AccountId);
assert.equal(element.itemName, 'Gerrit');
MockInteractions.tap(deleteBtns[3]);
assert.equal(element.itemId, 1000098 as AccountId);
assert.equal(element.itemName, '1000098');
});
test('delete included groups', () => {
const deleteBtns = queryAll<GrButton>(
element,
'.deleteIncludedGroupButton'
);
MockInteractions.tap(deleteBtns[0]);
assert.equal(element.itemId, 'testId' as GroupId);
assert.equal(element.itemName, 'testName');
MockInteractions.tap(deleteBtns[1]);
assert.equal(element.itemId, 'testId2' as GroupId);
assert.equal(element.itemName, 'testName2');
MockInteractions.tap(deleteBtns[2]);
assert.equal(element.itemId, 'testId3' as GroupId);
assert.equal(element.itemName, 'testName3');
});
test('computeGroupUrl', () => {
assert.isUndefined(element.computeGroupUrl(undefined));
let url = '#/admin/groups/uuid-529b3c2605bb1029c8146f9de4a91c776fe64498';
assert.equal(
element.computeGroupUrl(url),
'https://test/site/admin/groups/' +
'uuid-529b3c2605bb1029c8146f9de4a91c776fe64498'
);
url =
'https://gerrit.local/admin/groups/' +
'uuid-529b3c2605bb1029c8146f9de4a91c776fe64498';
assert.equal(element.computeGroupUrl(url), url);
});
test('fires page-error', async () => {
groupStub.restore();
element.groupId = 'testId1' as GroupId;
const response = {...new Response(), status: 404};
stubRestApi('getGroupConfig').callsFake((_, errFn) => {
if (errFn !== undefined) {
errFn(response);
}
return Promise.resolve(undefined);
});
const promise = mockPromise();
addListenerForTest(document, 'page-error', e => {
assert.deepEqual((e as PageErrorEvent).detail.response, response);
promise.resolve();
});
element.loadGroupDetails();
await promise;
});
test('_computeItemName', () => {
assert.equal(element.computeItemTypeName(ItemType.MEMBER), 'Member');
assert.equal(
element.computeItemTypeName(ItemType.INCLUDED_GROUP),
'Included Group'
);
});
}); | the_stack |
import * as chai from 'chai'
import * as chaiAsPromised from 'chai-as-promised'
import 'mocha'
import { LocalStorage } from '../../src'
import { MatrixClient } from '../../src/matrix-client/MatrixClient'
import * as sinon from 'sinon'
import { MatrixRoomStatus } from '../../src/matrix-client/models/MatrixRoom'
import { MatrixHttpClient } from '../../src/matrix-client/MatrixHttpClient'
import { MatrixClientEventType } from '../../src/matrix-client/models/MatrixClientEvent'
MatrixClient
// use chai-as-promised plugin
chai.use(chaiAsPromised)
const expect = chai.expect
describe(`MatrixClient`, () => {
let client: MatrixClient
beforeEach(() => {
sinon.restore()
client = MatrixClient.create({
baseUrl: `https://test.walletbeacon.io`,
storage: new LocalStorage()
})
;(client as any)._isReady.resolve()
})
it(`should create with options`, async () => {
expect(client).to.not.be.undefined
})
it(`should return joined rooms (case: empty)`, async () => {
expect(await client.joinedRooms).to.deep.equal([])
})
it(`should return joined rooms (case: 1 room)`, async () => {
const rooms = [{ status: MatrixRoomStatus.JOINED }]
const storeStub = sinon.stub((<any>client).store, 'get').returns(rooms)
expect(await client.joinedRooms).to.deep.equal(rooms)
expect(storeStub.callCount).to.equal(1)
expect(storeStub.firstCall.args[0]).to.equal('rooms')
})
it(`should return invited rooms (case: empty)`, async () => {
expect(await client.invitedRooms).to.deep.equal([])
})
it(`should return invited rooms (case: 1 room)`, async () => {
const rooms = [{ status: MatrixRoomStatus.INVITED }]
const storeStub = sinon.stub((<any>client).store, 'get').returns(rooms)
expect(await client.invitedRooms).to.deep.equal(rooms)
expect(storeStub.callCount).to.equal(1)
expect(storeStub.firstCall.args[0]).to.equal('rooms')
})
it(`should return left rooms (case: empty)`, async () => {
expect(await client.leftRooms).to.deep.equal([])
})
it(`should return left rooms (case: 1 room)`, async () => {
const rooms = [{ status: MatrixRoomStatus.LEFT }]
const storeStub = sinon.stub((<any>client).store, 'get').returns(rooms)
expect(await client.leftRooms).to.deep.equal(rooms)
expect(storeStub.callCount).to.equal(1)
expect(storeStub.firstCall.args[0]).to.equal('rooms')
})
it(`should start`, async () => {
const sendStub = sinon.stub(MatrixHttpClient.prototype, <any>'send')
const storeStub = sinon
.stub((<any>client).store, 'get')
.withArgs('isRunning')
.returns(false)
sendStub.withArgs('POST', '/login').resolves({
user_id: '@pubkey:url',
access_token: 'access-token',
home_server: 'url',
device_id: 'my-id'
})
const syncResponse = {
account_data: { events: [] },
to_device: { events: [] },
device_lists: { changed: [], left: [] },
presence: { events: [] },
rooms: { join: {}, invite: {}, leave: {} },
groups: { join: {}, invite: {}, leave: {} },
device_one_time_keys_count: {},
next_batch: 's793973_746830_0_1_1_1_1_17384_1'
}
const pollStub = sinon.stub(client, <any>'poll').resolves()
pollStub.callsArgWithAsync(1, syncResponse).resolves()
await client.start({
id: 'random-id',
password: `ed:sig:pubkey`,
deviceId: 'pubkey'
})
expect(storeStub.callCount).to.equal(1)
expect(sendStub.callCount).to.equal(1)
expect(pollStub.callCount).to.equal(1)
})
it(`should fail start if isRunning is false`, async () => {
const sendStub = sinon.stub(MatrixHttpClient.prototype, <any>'send')
const storeStub = sinon
.stub((<any>client).store, 'get')
.withArgs('isRunning')
.returns(false)
const storeUpdateStub = sinon.stub((<any>client).store, 'update').resolves()
sendStub.withArgs('POST', '/login').resolves({
user_id: '@pubkey:url',
access_token: 'access-token',
home_server: 'url',
device_id: 'my-id'
})
const pollStub = sinon.stub(client, <any>'poll').resolves()
pollStub.callsArgWithAsync(2, new Error('expected error')).resolves()
try {
await client.start({
id: 'random-id',
password: `ed:sig:pubkey`,
deviceId: 'pubkey'
})
} catch (e) {
expect(e.message).to.equal('expected error')
expect(storeStub.callCount).to.equal(1)
expect(sendStub.callCount).to.equal(1)
expect(pollStub.callCount).to.equal(1)
expect(storeUpdateStub.callCount).to.equal(2)
}
})
it(`should subscribe`, async () => {
const onStub = sinon.stub((<any>client).eventEmitter, 'on').resolves()
const cb = () => null
client.subscribe(MatrixClientEventType.MESSAGE, cb)
expect(onStub.callCount).to.equal(1)
expect(onStub.firstCall.args[0]).to.equal(MatrixClientEventType.MESSAGE)
expect(onStub.firstCall.args[1]).to.equal(cb)
})
it(`should unsubscribe one`, async () => {
const removeStub = sinon.stub((<any>client).eventEmitter, 'removeListener').resolves()
const removeAllStub = sinon.stub((<any>client).eventEmitter, 'removeAllListeners').resolves()
const cb = () => null
client.unsubscribe(MatrixClientEventType.MESSAGE, cb)
expect(removeAllStub.callCount).to.equal(0)
expect(removeStub.callCount).to.equal(1)
expect(removeStub.firstCall.args[0]).to.equal(MatrixClientEventType.MESSAGE)
expect(removeStub.firstCall.args[1]).to.equal(cb)
})
it(`should unsubscribe all events`, async () => {
const removeStub = sinon.stub((<any>client).eventEmitter, 'removeListener').resolves()
const removeAllStub = sinon.stub((<any>client).eventEmitter, 'removeAllListeners').resolves()
client.unsubscribeAll(MatrixClientEventType.MESSAGE)
expect(removeStub.callCount).to.equal(0)
expect(removeAllStub.callCount).to.equal(1)
expect(removeAllStub.firstCall.args[0]).to.equal(MatrixClientEventType.MESSAGE)
})
it(`should get a room by id`, async () => {
const getRoomStub = sinon.stub((<any>client).store, 'getRoom').resolves()
const id = 'my-id'
await client.getRoomById(id)
expect(getRoomStub.callCount).to.equal(1)
expect(getRoomStub.firstCall.args[0]).to.equal(id)
})
it(`should create a trusted private room`, async () => {
const getAccessTokenStub = sinon
.stub((<any>client).store, 'get')
.withArgs('accessToken')
.resolves('my-token')
const eventSyncSpy = sinon.spy((<any>client).roomService, 'createRoom')
const sendStub = sinon.stub(MatrixHttpClient.prototype, <any>'send')
sendStub.resolves({
room_id: 'my-id'
})
const syncSpy = sinon.spy(client, <any>'requiresAuthorization')
const roomId = await client.createTrustedPrivateRoom('1', '2', '3')
expect(getAccessTokenStub.callCount).to.equal(1)
expect(syncSpy.callCount).to.equal(1)
expect(eventSyncSpy.callCount).to.equal(1)
expect(roomId).to.equal('my-id')
})
it(`should invite a user to a room`, async () => {
const getAccessTokenStub = sinon
.stub((<any>client).store, 'get')
.withArgs('accessToken')
.resolves('my-token')
const sendStub = sinon.stub(MatrixHttpClient.prototype, <any>'send')
sendStub.withArgs('POST', '/rooms/my-id/invite').resolves({
type: 'room_invite'
})
const getRoomStub = sinon
.stub((<any>client).store, 'getRoom')
.returns({ id: 'my-id', status: MatrixRoomStatus.JOINED })
const eventSyncSpy = sinon.spy((<any>client).roomService, 'inviteToRoom')
const syncSpy = sinon.spy(client, <any>'requiresAuthorization')
await client.inviteToRooms('user', '1', '2', '3')
expect(getAccessTokenStub.callCount).to.equal(1)
expect(syncSpy.callCount).to.equal(1)
expect(getRoomStub.callCount).to.equal(3)
expect(eventSyncSpy.callCount).to.equal(3)
})
it(`should join rooms`, async () => {
const getAccessTokenStub = sinon
.stub((<any>client).store, 'get')
.withArgs('accessToken')
.resolves('my-token')
const getRoomStub = sinon.stub((<any>client).store, 'getRoom').returns('room')
const eventSyncStub = sinon.stub((<any>client).roomService, 'joinRoom').resolves()
const syncSpy = sinon.spy(client, <any>'requiresAuthorization')
await client.joinRooms('1', '2', '3')
expect(getAccessTokenStub.callCount).to.equal(1)
expect(syncSpy.callCount).to.equal(1)
expect(getRoomStub.callCount).to.equal(3)
expect(eventSyncStub.callCount).to.equal(3)
})
it(`should send a text message`, async () => {
return new Promise(async (resolve) => {
const getRoomStub = sinon.stub((<any>client).store, 'getRoom').returns('room')
const createTxnIdStub = sinon
.stub(<any>MatrixClient.prototype, 'createTxnId')
.resolves('random-id')
const eventSyncStub = sinon.stub((<any>client).eventService, 'sendMessage').resolves()
const syncStub = sinon
.stub(client, <any>'requiresAuthorization')
.callsArgWithAsync(1, 'myToken')
.resolves()
await client.sendTextMessage('123', 'my-message')
expect(getRoomStub.callCount, 'getRoomStub').to.equal(0)
setTimeout(() => {
expect(createTxnIdStub.callCount, 'createTxnId').to.equal(1)
expect(syncStub.callCount, 'syncStub').to.equal(1)
expect(eventSyncStub.callCount, 'eventSyncStub').to.equal(1)
resolve()
}, 0)
})
})
it(`should poll the server for updates`, async () => {
return new Promise(async (resolve) => {
const sendStub = sinon.stub(MatrixHttpClient.prototype, <any>'send')
sendStub.withArgs('GET', '/sync').resolves()
const successResponse = 'my-response'
const getStub = sinon.stub((<any>client).store, 'get').returns(3)
const syncStub = sinon.stub(client, <any>'sync').returns(successResponse)
// Stop the requests after 1s, otherwise it will retry forever
setTimeout(() => {
client.stop()
}, 1000)
;(<any>client)
.poll(
0,
(response: any) => {
expect(response).to.equal(successResponse)
expect(getStub.callCount).to.equal(0)
expect(syncStub.callCount).to.equal(1) // The second time polling is done, this will fail and invoke the error callback
},
async () => {}
)
.catch(() => {
resolve()
})
})
})
it(`should sync with the server`, async () => {
const getStub = sinon.stub((<any>client).store, 'get').returns('something')
const eventSyncStub = sinon.stub((<any>client).eventService, 'sync').resolves()
const syncStub = sinon
.stub(client, <any>'requiresAuthorization')
.callsArgWithAsync(1, 'myToken')
.resolves()
await (<any>client).sync()
expect(getStub.callCount).to.equal(2)
expect(syncStub.callCount).to.equal(1)
expect(eventSyncStub.callCount).to.equal(1)
})
it(`should send a sync request to the server`, async () => {
const getStub = sinon.stub((<any>client).store, 'get').returns('test-item')
const eventSyncStub = sinon.stub((<any>client).eventService, 'sync').resolves()
const syncStub = sinon
.stub(client, <any>'requiresAuthorization')
.callsArgWithAsync(1, 'myToken')
.resolves()
await (<any>client).sync()
expect(getStub.callCount).to.equal(2)
expect(syncStub.callCount).to.equal(1)
expect(eventSyncStub.callCount).to.equal(1)
})
it(`should check if an access token is present`, async () => {
const myToken = 'my-token'
const getStub = sinon.stub((<any>client).store, 'get').returns(myToken)
return new Promise(async (resolve, _reject) => {
const cb = (token) => {
expect(token).to.equal(myToken)
expect(getStub.callCount).to.equal(1)
resolve()
}
await (<any>client).requiresAuthorization('my-name', cb)
})
})
it(`should create a transaction id`, async () => {
const counter = 1
const getStub = sinon.stub((<any>client).store, 'get').returns(counter)
const updateStub = sinon.stub((<any>client).store, 'update').resolves()
const id = await (<any>client).createTxnId()
expect(getStub.callCount).to.equal(1)
expect(updateStub.callCount).to.equal(1)
expect(updateStub.firstCall.args[0]).to.deep.equal({
txnNo: counter + 1
})
expect(id.startsWith('m')).to.be.true
expect(id.includes('.')).to.be.true
expect(id.includes(counter)).to.be.true
})
}) | the_stack |
import * as msRest from "@azure/ms-rest-js";
import * as msRestAzure from "@azure/ms-rest-azure-js";
import * as Models from "../models";
import * as Mappers from "../models/policyStatesMappers";
import * as Parameters from "../models/parameters";
import { PolicyInsightsClientContext } from "../policyInsightsClientContext";
/** Class representing a PolicyStates. */
export class PolicyStates {
private readonly client: PolicyInsightsClientContext;
/**
* Create a PolicyStates.
* @param {PolicyInsightsClientContext} client Reference to the service client.
*/
constructor(client: PolicyInsightsClientContext) {
this.client = client;
}
/**
* Queries policy states for the resources under the management group.
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param managementGroupName Management group name.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyStatesListQueryResultsForManagementGroupResponse>
*/
listQueryResultsForManagementGroup(policyStatesResource: Models.PolicyStatesResource, managementGroupName: string, options?: Models.PolicyStatesListQueryResultsForManagementGroupOptionalParams): Promise<Models.PolicyStatesListQueryResultsForManagementGroupResponse>;
/**
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param managementGroupName Management group name.
* @param callback The callback
*/
listQueryResultsForManagementGroup(policyStatesResource: Models.PolicyStatesResource, managementGroupName: string, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
/**
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param managementGroupName Management group name.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForManagementGroup(policyStatesResource: Models.PolicyStatesResource, managementGroupName: string, options: Models.PolicyStatesListQueryResultsForManagementGroupOptionalParams, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
listQueryResultsForManagementGroup(policyStatesResource: Models.PolicyStatesResource, managementGroupName: string, options?: Models.PolicyStatesListQueryResultsForManagementGroupOptionalParams | msRest.ServiceCallback<Models.PolicyStatesQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): Promise<Models.PolicyStatesListQueryResultsForManagementGroupResponse> {
return this.client.sendOperationRequest(
{
policyStatesResource,
managementGroupName,
options
},
listQueryResultsForManagementGroupOperationSpec,
callback) as Promise<Models.PolicyStatesListQueryResultsForManagementGroupResponse>;
}
/**
* Summarizes policy states for the resources under the management group.
* @param managementGroupName Management group name.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyStatesSummarizeForManagementGroupResponse>
*/
summarizeForManagementGroup(managementGroupName: string, options?: Models.PolicyStatesSummarizeForManagementGroupOptionalParams): Promise<Models.PolicyStatesSummarizeForManagementGroupResponse>;
/**
* @param managementGroupName Management group name.
* @param callback The callback
*/
summarizeForManagementGroup(managementGroupName: string, callback: msRest.ServiceCallback<Models.SummarizeResults>): void;
/**
* @param managementGroupName Management group name.
* @param options The optional parameters
* @param callback The callback
*/
summarizeForManagementGroup(managementGroupName: string, options: Models.PolicyStatesSummarizeForManagementGroupOptionalParams, callback: msRest.ServiceCallback<Models.SummarizeResults>): void;
summarizeForManagementGroup(managementGroupName: string, options?: Models.PolicyStatesSummarizeForManagementGroupOptionalParams | msRest.ServiceCallback<Models.SummarizeResults>, callback?: msRest.ServiceCallback<Models.SummarizeResults>): Promise<Models.PolicyStatesSummarizeForManagementGroupResponse> {
return this.client.sendOperationRequest(
{
managementGroupName,
options
},
summarizeForManagementGroupOperationSpec,
callback) as Promise<Models.PolicyStatesSummarizeForManagementGroupResponse>;
}
/**
* Queries policy states for the resources under the subscription.
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param subscriptionId Microsoft Azure subscription ID.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyStatesListQueryResultsForSubscriptionResponse>
*/
listQueryResultsForSubscription(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, options?: Models.PolicyStatesListQueryResultsForSubscriptionOptionalParams): Promise<Models.PolicyStatesListQueryResultsForSubscriptionResponse>;
/**
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param subscriptionId Microsoft Azure subscription ID.
* @param callback The callback
*/
listQueryResultsForSubscription(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
/**
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param subscriptionId Microsoft Azure subscription ID.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForSubscription(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, options: Models.PolicyStatesListQueryResultsForSubscriptionOptionalParams, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
listQueryResultsForSubscription(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, options?: Models.PolicyStatesListQueryResultsForSubscriptionOptionalParams | msRest.ServiceCallback<Models.PolicyStatesQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): Promise<Models.PolicyStatesListQueryResultsForSubscriptionResponse> {
return this.client.sendOperationRequest(
{
policyStatesResource,
subscriptionId,
options
},
listQueryResultsForSubscriptionOperationSpec,
callback) as Promise<Models.PolicyStatesListQueryResultsForSubscriptionResponse>;
}
/**
* Summarizes policy states for the resources under the subscription.
* @param subscriptionId Microsoft Azure subscription ID.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyStatesSummarizeForSubscriptionResponse>
*/
summarizeForSubscription(subscriptionId: string, options?: Models.PolicyStatesSummarizeForSubscriptionOptionalParams): Promise<Models.PolicyStatesSummarizeForSubscriptionResponse>;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param callback The callback
*/
summarizeForSubscription(subscriptionId: string, callback: msRest.ServiceCallback<Models.SummarizeResults>): void;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param options The optional parameters
* @param callback The callback
*/
summarizeForSubscription(subscriptionId: string, options: Models.PolicyStatesSummarizeForSubscriptionOptionalParams, callback: msRest.ServiceCallback<Models.SummarizeResults>): void;
summarizeForSubscription(subscriptionId: string, options?: Models.PolicyStatesSummarizeForSubscriptionOptionalParams | msRest.ServiceCallback<Models.SummarizeResults>, callback?: msRest.ServiceCallback<Models.SummarizeResults>): Promise<Models.PolicyStatesSummarizeForSubscriptionResponse> {
return this.client.sendOperationRequest(
{
subscriptionId,
options
},
summarizeForSubscriptionOperationSpec,
callback) as Promise<Models.PolicyStatesSummarizeForSubscriptionResponse>;
}
/**
* Queries policy states for the resources under the resource group.
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param subscriptionId Microsoft Azure subscription ID.
* @param resourceGroupName Resource group name.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyStatesListQueryResultsForResourceGroupResponse>
*/
listQueryResultsForResourceGroup(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, resourceGroupName: string, options?: Models.PolicyStatesListQueryResultsForResourceGroupOptionalParams): Promise<Models.PolicyStatesListQueryResultsForResourceGroupResponse>;
/**
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param subscriptionId Microsoft Azure subscription ID.
* @param resourceGroupName Resource group name.
* @param callback The callback
*/
listQueryResultsForResourceGroup(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
/**
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param subscriptionId Microsoft Azure subscription ID.
* @param resourceGroupName Resource group name.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForResourceGroup(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, resourceGroupName: string, options: Models.PolicyStatesListQueryResultsForResourceGroupOptionalParams, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
listQueryResultsForResourceGroup(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, resourceGroupName: string, options?: Models.PolicyStatesListQueryResultsForResourceGroupOptionalParams | msRest.ServiceCallback<Models.PolicyStatesQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): Promise<Models.PolicyStatesListQueryResultsForResourceGroupResponse> {
return this.client.sendOperationRequest(
{
policyStatesResource,
subscriptionId,
resourceGroupName,
options
},
listQueryResultsForResourceGroupOperationSpec,
callback) as Promise<Models.PolicyStatesListQueryResultsForResourceGroupResponse>;
}
/**
* Summarizes policy states for the resources under the resource group.
* @param subscriptionId Microsoft Azure subscription ID.
* @param resourceGroupName Resource group name.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyStatesSummarizeForResourceGroupResponse>
*/
summarizeForResourceGroup(subscriptionId: string, resourceGroupName: string, options?: Models.PolicyStatesSummarizeForResourceGroupOptionalParams): Promise<Models.PolicyStatesSummarizeForResourceGroupResponse>;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param resourceGroupName Resource group name.
* @param callback The callback
*/
summarizeForResourceGroup(subscriptionId: string, resourceGroupName: string, callback: msRest.ServiceCallback<Models.SummarizeResults>): void;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param resourceGroupName Resource group name.
* @param options The optional parameters
* @param callback The callback
*/
summarizeForResourceGroup(subscriptionId: string, resourceGroupName: string, options: Models.PolicyStatesSummarizeForResourceGroupOptionalParams, callback: msRest.ServiceCallback<Models.SummarizeResults>): void;
summarizeForResourceGroup(subscriptionId: string, resourceGroupName: string, options?: Models.PolicyStatesSummarizeForResourceGroupOptionalParams | msRest.ServiceCallback<Models.SummarizeResults>, callback?: msRest.ServiceCallback<Models.SummarizeResults>): Promise<Models.PolicyStatesSummarizeForResourceGroupResponse> {
return this.client.sendOperationRequest(
{
subscriptionId,
resourceGroupName,
options
},
summarizeForResourceGroupOperationSpec,
callback) as Promise<Models.PolicyStatesSummarizeForResourceGroupResponse>;
}
/**
* Queries policy states for the resource.
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param resourceId Resource ID.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyStatesListQueryResultsForResourceResponse>
*/
listQueryResultsForResource(policyStatesResource: Models.PolicyStatesResource, resourceId: string, options?: Models.PolicyStatesListQueryResultsForResourceOptionalParams): Promise<Models.PolicyStatesListQueryResultsForResourceResponse>;
/**
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param resourceId Resource ID.
* @param callback The callback
*/
listQueryResultsForResource(policyStatesResource: Models.PolicyStatesResource, resourceId: string, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
/**
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param resourceId Resource ID.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForResource(policyStatesResource: Models.PolicyStatesResource, resourceId: string, options: Models.PolicyStatesListQueryResultsForResourceOptionalParams, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
listQueryResultsForResource(policyStatesResource: Models.PolicyStatesResource, resourceId: string, options?: Models.PolicyStatesListQueryResultsForResourceOptionalParams | msRest.ServiceCallback<Models.PolicyStatesQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): Promise<Models.PolicyStatesListQueryResultsForResourceResponse> {
return this.client.sendOperationRequest(
{
policyStatesResource,
resourceId,
options
},
listQueryResultsForResourceOperationSpec,
callback) as Promise<Models.PolicyStatesListQueryResultsForResourceResponse>;
}
/**
* Summarizes policy states for the resource.
* @param resourceId Resource ID.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyStatesSummarizeForResourceResponse>
*/
summarizeForResource(resourceId: string, options?: Models.PolicyStatesSummarizeForResourceOptionalParams): Promise<Models.PolicyStatesSummarizeForResourceResponse>;
/**
* @param resourceId Resource ID.
* @param callback The callback
*/
summarizeForResource(resourceId: string, callback: msRest.ServiceCallback<Models.SummarizeResults>): void;
/**
* @param resourceId Resource ID.
* @param options The optional parameters
* @param callback The callback
*/
summarizeForResource(resourceId: string, options: Models.PolicyStatesSummarizeForResourceOptionalParams, callback: msRest.ServiceCallback<Models.SummarizeResults>): void;
summarizeForResource(resourceId: string, options?: Models.PolicyStatesSummarizeForResourceOptionalParams | msRest.ServiceCallback<Models.SummarizeResults>, callback?: msRest.ServiceCallback<Models.SummarizeResults>): Promise<Models.PolicyStatesSummarizeForResourceResponse> {
return this.client.sendOperationRequest(
{
resourceId,
options
},
summarizeForResourceOperationSpec,
callback) as Promise<Models.PolicyStatesSummarizeForResourceResponse>;
}
/**
* Triggers a policy evaluation scan for all the resources under the subscription
* @param subscriptionId Microsoft Azure subscription ID.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
triggerSubscriptionEvaluation(subscriptionId: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> {
return this.beginTriggerSubscriptionEvaluation(subscriptionId,options)
.then(lroPoller => lroPoller.pollUntilFinished());
}
/**
* Triggers a policy evaluation scan for all the resources under the resource group.
* @param subscriptionId Microsoft Azure subscription ID.
* @param resourceGroupName Resource group name.
* @param [options] The optional parameters
* @returns Promise<msRest.RestResponse>
*/
triggerResourceGroupEvaluation(subscriptionId: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> {
return this.beginTriggerResourceGroupEvaluation(subscriptionId,resourceGroupName,options)
.then(lroPoller => lroPoller.pollUntilFinished());
}
/**
* Queries policy states for the subscription level policy set definition.
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param subscriptionId Microsoft Azure subscription ID.
* @param policySetDefinitionName Policy set definition name.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyStatesListQueryResultsForPolicySetDefinitionResponse>
*/
listQueryResultsForPolicySetDefinition(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, policySetDefinitionName: string, options?: Models.PolicyStatesListQueryResultsForPolicySetDefinitionOptionalParams): Promise<Models.PolicyStatesListQueryResultsForPolicySetDefinitionResponse>;
/**
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param subscriptionId Microsoft Azure subscription ID.
* @param policySetDefinitionName Policy set definition name.
* @param callback The callback
*/
listQueryResultsForPolicySetDefinition(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, policySetDefinitionName: string, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
/**
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param subscriptionId Microsoft Azure subscription ID.
* @param policySetDefinitionName Policy set definition name.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForPolicySetDefinition(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, policySetDefinitionName: string, options: Models.PolicyStatesListQueryResultsForPolicySetDefinitionOptionalParams, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
listQueryResultsForPolicySetDefinition(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, policySetDefinitionName: string, options?: Models.PolicyStatesListQueryResultsForPolicySetDefinitionOptionalParams | msRest.ServiceCallback<Models.PolicyStatesQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): Promise<Models.PolicyStatesListQueryResultsForPolicySetDefinitionResponse> {
return this.client.sendOperationRequest(
{
policyStatesResource,
subscriptionId,
policySetDefinitionName,
options
},
listQueryResultsForPolicySetDefinitionOperationSpec,
callback) as Promise<Models.PolicyStatesListQueryResultsForPolicySetDefinitionResponse>;
}
/**
* Summarizes policy states for the subscription level policy set definition.
* @param subscriptionId Microsoft Azure subscription ID.
* @param policySetDefinitionName Policy set definition name.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyStatesSummarizeForPolicySetDefinitionResponse>
*/
summarizeForPolicySetDefinition(subscriptionId: string, policySetDefinitionName: string, options?: Models.PolicyStatesSummarizeForPolicySetDefinitionOptionalParams): Promise<Models.PolicyStatesSummarizeForPolicySetDefinitionResponse>;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param policySetDefinitionName Policy set definition name.
* @param callback The callback
*/
summarizeForPolicySetDefinition(subscriptionId: string, policySetDefinitionName: string, callback: msRest.ServiceCallback<Models.SummarizeResults>): void;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param policySetDefinitionName Policy set definition name.
* @param options The optional parameters
* @param callback The callback
*/
summarizeForPolicySetDefinition(subscriptionId: string, policySetDefinitionName: string, options: Models.PolicyStatesSummarizeForPolicySetDefinitionOptionalParams, callback: msRest.ServiceCallback<Models.SummarizeResults>): void;
summarizeForPolicySetDefinition(subscriptionId: string, policySetDefinitionName: string, options?: Models.PolicyStatesSummarizeForPolicySetDefinitionOptionalParams | msRest.ServiceCallback<Models.SummarizeResults>, callback?: msRest.ServiceCallback<Models.SummarizeResults>): Promise<Models.PolicyStatesSummarizeForPolicySetDefinitionResponse> {
return this.client.sendOperationRequest(
{
subscriptionId,
policySetDefinitionName,
options
},
summarizeForPolicySetDefinitionOperationSpec,
callback) as Promise<Models.PolicyStatesSummarizeForPolicySetDefinitionResponse>;
}
/**
* Queries policy states for the subscription level policy definition.
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param subscriptionId Microsoft Azure subscription ID.
* @param policyDefinitionName Policy definition name.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyStatesListQueryResultsForPolicyDefinitionResponse>
*/
listQueryResultsForPolicyDefinition(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, policyDefinitionName: string, options?: Models.PolicyStatesListQueryResultsForPolicyDefinitionOptionalParams): Promise<Models.PolicyStatesListQueryResultsForPolicyDefinitionResponse>;
/**
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param subscriptionId Microsoft Azure subscription ID.
* @param policyDefinitionName Policy definition name.
* @param callback The callback
*/
listQueryResultsForPolicyDefinition(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, policyDefinitionName: string, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
/**
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param subscriptionId Microsoft Azure subscription ID.
* @param policyDefinitionName Policy definition name.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForPolicyDefinition(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, policyDefinitionName: string, options: Models.PolicyStatesListQueryResultsForPolicyDefinitionOptionalParams, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
listQueryResultsForPolicyDefinition(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, policyDefinitionName: string, options?: Models.PolicyStatesListQueryResultsForPolicyDefinitionOptionalParams | msRest.ServiceCallback<Models.PolicyStatesQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): Promise<Models.PolicyStatesListQueryResultsForPolicyDefinitionResponse> {
return this.client.sendOperationRequest(
{
policyStatesResource,
subscriptionId,
policyDefinitionName,
options
},
listQueryResultsForPolicyDefinitionOperationSpec,
callback) as Promise<Models.PolicyStatesListQueryResultsForPolicyDefinitionResponse>;
}
/**
* Summarizes policy states for the subscription level policy definition.
* @param subscriptionId Microsoft Azure subscription ID.
* @param policyDefinitionName Policy definition name.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyStatesSummarizeForPolicyDefinitionResponse>
*/
summarizeForPolicyDefinition(subscriptionId: string, policyDefinitionName: string, options?: Models.PolicyStatesSummarizeForPolicyDefinitionOptionalParams): Promise<Models.PolicyStatesSummarizeForPolicyDefinitionResponse>;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param policyDefinitionName Policy definition name.
* @param callback The callback
*/
summarizeForPolicyDefinition(subscriptionId: string, policyDefinitionName: string, callback: msRest.ServiceCallback<Models.SummarizeResults>): void;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param policyDefinitionName Policy definition name.
* @param options The optional parameters
* @param callback The callback
*/
summarizeForPolicyDefinition(subscriptionId: string, policyDefinitionName: string, options: Models.PolicyStatesSummarizeForPolicyDefinitionOptionalParams, callback: msRest.ServiceCallback<Models.SummarizeResults>): void;
summarizeForPolicyDefinition(subscriptionId: string, policyDefinitionName: string, options?: Models.PolicyStatesSummarizeForPolicyDefinitionOptionalParams | msRest.ServiceCallback<Models.SummarizeResults>, callback?: msRest.ServiceCallback<Models.SummarizeResults>): Promise<Models.PolicyStatesSummarizeForPolicyDefinitionResponse> {
return this.client.sendOperationRequest(
{
subscriptionId,
policyDefinitionName,
options
},
summarizeForPolicyDefinitionOperationSpec,
callback) as Promise<Models.PolicyStatesSummarizeForPolicyDefinitionResponse>;
}
/**
* Queries policy states for the subscription level policy assignment.
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param subscriptionId Microsoft Azure subscription ID.
* @param policyAssignmentName Policy assignment name.
* @param [options] The optional parameters
* @returns
* Promise<Models.PolicyStatesListQueryResultsForSubscriptionLevelPolicyAssignmentResponse>
*/
listQueryResultsForSubscriptionLevelPolicyAssignment(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, policyAssignmentName: string, options?: Models.PolicyStatesListQueryResultsForSubscriptionLevelPolicyAssignmentOptionalParams): Promise<Models.PolicyStatesListQueryResultsForSubscriptionLevelPolicyAssignmentResponse>;
/**
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param subscriptionId Microsoft Azure subscription ID.
* @param policyAssignmentName Policy assignment name.
* @param callback The callback
*/
listQueryResultsForSubscriptionLevelPolicyAssignment(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, policyAssignmentName: string, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
/**
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param subscriptionId Microsoft Azure subscription ID.
* @param policyAssignmentName Policy assignment name.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForSubscriptionLevelPolicyAssignment(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, policyAssignmentName: string, options: Models.PolicyStatesListQueryResultsForSubscriptionLevelPolicyAssignmentOptionalParams, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
listQueryResultsForSubscriptionLevelPolicyAssignment(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, policyAssignmentName: string, options?: Models.PolicyStatesListQueryResultsForSubscriptionLevelPolicyAssignmentOptionalParams | msRest.ServiceCallback<Models.PolicyStatesQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): Promise<Models.PolicyStatesListQueryResultsForSubscriptionLevelPolicyAssignmentResponse> {
return this.client.sendOperationRequest(
{
policyStatesResource,
subscriptionId,
policyAssignmentName,
options
},
listQueryResultsForSubscriptionLevelPolicyAssignmentOperationSpec,
callback) as Promise<Models.PolicyStatesListQueryResultsForSubscriptionLevelPolicyAssignmentResponse>;
}
/**
* Summarizes policy states for the subscription level policy assignment.
* @param subscriptionId Microsoft Azure subscription ID.
* @param policyAssignmentName Policy assignment name.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyStatesSummarizeForSubscriptionLevelPolicyAssignmentResponse>
*/
summarizeForSubscriptionLevelPolicyAssignment(subscriptionId: string, policyAssignmentName: string, options?: Models.PolicyStatesSummarizeForSubscriptionLevelPolicyAssignmentOptionalParams): Promise<Models.PolicyStatesSummarizeForSubscriptionLevelPolicyAssignmentResponse>;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param policyAssignmentName Policy assignment name.
* @param callback The callback
*/
summarizeForSubscriptionLevelPolicyAssignment(subscriptionId: string, policyAssignmentName: string, callback: msRest.ServiceCallback<Models.SummarizeResults>): void;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param policyAssignmentName Policy assignment name.
* @param options The optional parameters
* @param callback The callback
*/
summarizeForSubscriptionLevelPolicyAssignment(subscriptionId: string, policyAssignmentName: string, options: Models.PolicyStatesSummarizeForSubscriptionLevelPolicyAssignmentOptionalParams, callback: msRest.ServiceCallback<Models.SummarizeResults>): void;
summarizeForSubscriptionLevelPolicyAssignment(subscriptionId: string, policyAssignmentName: string, options?: Models.PolicyStatesSummarizeForSubscriptionLevelPolicyAssignmentOptionalParams | msRest.ServiceCallback<Models.SummarizeResults>, callback?: msRest.ServiceCallback<Models.SummarizeResults>): Promise<Models.PolicyStatesSummarizeForSubscriptionLevelPolicyAssignmentResponse> {
return this.client.sendOperationRequest(
{
subscriptionId,
policyAssignmentName,
options
},
summarizeForSubscriptionLevelPolicyAssignmentOperationSpec,
callback) as Promise<Models.PolicyStatesSummarizeForSubscriptionLevelPolicyAssignmentResponse>;
}
/**
* Queries policy states for the resource group level policy assignment.
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param subscriptionId Microsoft Azure subscription ID.
* @param resourceGroupName Resource group name.
* @param policyAssignmentName Policy assignment name.
* @param [options] The optional parameters
* @returns
* Promise<Models.PolicyStatesListQueryResultsForResourceGroupLevelPolicyAssignmentResponse>
*/
listQueryResultsForResourceGroupLevelPolicyAssignment(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, resourceGroupName: string, policyAssignmentName: string, options?: Models.PolicyStatesListQueryResultsForResourceGroupLevelPolicyAssignmentOptionalParams): Promise<Models.PolicyStatesListQueryResultsForResourceGroupLevelPolicyAssignmentResponse>;
/**
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param subscriptionId Microsoft Azure subscription ID.
* @param resourceGroupName Resource group name.
* @param policyAssignmentName Policy assignment name.
* @param callback The callback
*/
listQueryResultsForResourceGroupLevelPolicyAssignment(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, resourceGroupName: string, policyAssignmentName: string, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
/**
* @param policyStatesResource The virtual resource under PolicyStates resource type. In a given
* time range, 'latest' represents the latest policy state(s), whereas 'default' represents all
* policy state(s). Possible values include: 'default', 'latest'
* @param subscriptionId Microsoft Azure subscription ID.
* @param resourceGroupName Resource group name.
* @param policyAssignmentName Policy assignment name.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForResourceGroupLevelPolicyAssignment(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, resourceGroupName: string, policyAssignmentName: string, options: Models.PolicyStatesListQueryResultsForResourceGroupLevelPolicyAssignmentOptionalParams, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
listQueryResultsForResourceGroupLevelPolicyAssignment(policyStatesResource: Models.PolicyStatesResource, subscriptionId: string, resourceGroupName: string, policyAssignmentName: string, options?: Models.PolicyStatesListQueryResultsForResourceGroupLevelPolicyAssignmentOptionalParams | msRest.ServiceCallback<Models.PolicyStatesQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): Promise<Models.PolicyStatesListQueryResultsForResourceGroupLevelPolicyAssignmentResponse> {
return this.client.sendOperationRequest(
{
policyStatesResource,
subscriptionId,
resourceGroupName,
policyAssignmentName,
options
},
listQueryResultsForResourceGroupLevelPolicyAssignmentOperationSpec,
callback) as Promise<Models.PolicyStatesListQueryResultsForResourceGroupLevelPolicyAssignmentResponse>;
}
/**
* Summarizes policy states for the resource group level policy assignment.
* @param subscriptionId Microsoft Azure subscription ID.
* @param resourceGroupName Resource group name.
* @param policyAssignmentName Policy assignment name.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyStatesSummarizeForResourceGroupLevelPolicyAssignmentResponse>
*/
summarizeForResourceGroupLevelPolicyAssignment(subscriptionId: string, resourceGroupName: string, policyAssignmentName: string, options?: Models.PolicyStatesSummarizeForResourceGroupLevelPolicyAssignmentOptionalParams): Promise<Models.PolicyStatesSummarizeForResourceGroupLevelPolicyAssignmentResponse>;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param resourceGroupName Resource group name.
* @param policyAssignmentName Policy assignment name.
* @param callback The callback
*/
summarizeForResourceGroupLevelPolicyAssignment(subscriptionId: string, resourceGroupName: string, policyAssignmentName: string, callback: msRest.ServiceCallback<Models.SummarizeResults>): void;
/**
* @param subscriptionId Microsoft Azure subscription ID.
* @param resourceGroupName Resource group name.
* @param policyAssignmentName Policy assignment name.
* @param options The optional parameters
* @param callback The callback
*/
summarizeForResourceGroupLevelPolicyAssignment(subscriptionId: string, resourceGroupName: string, policyAssignmentName: string, options: Models.PolicyStatesSummarizeForResourceGroupLevelPolicyAssignmentOptionalParams, callback: msRest.ServiceCallback<Models.SummarizeResults>): void;
summarizeForResourceGroupLevelPolicyAssignment(subscriptionId: string, resourceGroupName: string, policyAssignmentName: string, options?: Models.PolicyStatesSummarizeForResourceGroupLevelPolicyAssignmentOptionalParams | msRest.ServiceCallback<Models.SummarizeResults>, callback?: msRest.ServiceCallback<Models.SummarizeResults>): Promise<Models.PolicyStatesSummarizeForResourceGroupLevelPolicyAssignmentResponse> {
return this.client.sendOperationRequest(
{
subscriptionId,
resourceGroupName,
policyAssignmentName,
options
},
summarizeForResourceGroupLevelPolicyAssignmentOperationSpec,
callback) as Promise<Models.PolicyStatesSummarizeForResourceGroupLevelPolicyAssignmentResponse>;
}
/**
* Triggers a policy evaluation scan for all the resources under the subscription
* @param subscriptionId Microsoft Azure subscription ID.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginTriggerSubscriptionEvaluation(subscriptionId: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
subscriptionId,
options
},
beginTriggerSubscriptionEvaluationOperationSpec,
options);
}
/**
* Triggers a policy evaluation scan for all the resources under the resource group.
* @param subscriptionId Microsoft Azure subscription ID.
* @param resourceGroupName Resource group name.
* @param [options] The optional parameters
* @returns Promise<msRestAzure.LROPoller>
*/
beginTriggerResourceGroupEvaluation(subscriptionId: string, resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> {
return this.client.sendLRORequest(
{
subscriptionId,
resourceGroupName,
options
},
beginTriggerResourceGroupEvaluationOperationSpec,
options);
}
/**
* Queries policy states for the resources under the management group.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyStatesListQueryResultsForManagementGroupNextResponse>
*/
listQueryResultsForManagementGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyStatesListQueryResultsForManagementGroupNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listQueryResultsForManagementGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForManagementGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
listQueryResultsForManagementGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyStatesQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): Promise<Models.PolicyStatesListQueryResultsForManagementGroupNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listQueryResultsForManagementGroupNextOperationSpec,
callback) as Promise<Models.PolicyStatesListQueryResultsForManagementGroupNextResponse>;
}
/**
* Queries policy states for the resources under the subscription.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyStatesListQueryResultsForSubscriptionNextResponse>
*/
listQueryResultsForSubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyStatesListQueryResultsForSubscriptionNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listQueryResultsForSubscriptionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForSubscriptionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
listQueryResultsForSubscriptionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyStatesQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): Promise<Models.PolicyStatesListQueryResultsForSubscriptionNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listQueryResultsForSubscriptionNextOperationSpec,
callback) as Promise<Models.PolicyStatesListQueryResultsForSubscriptionNextResponse>;
}
/**
* Queries policy states for the resources under the resource group.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyStatesListQueryResultsForResourceGroupNextResponse>
*/
listQueryResultsForResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyStatesListQueryResultsForResourceGroupNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listQueryResultsForResourceGroupNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForResourceGroupNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
listQueryResultsForResourceGroupNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyStatesQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): Promise<Models.PolicyStatesListQueryResultsForResourceGroupNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listQueryResultsForResourceGroupNextOperationSpec,
callback) as Promise<Models.PolicyStatesListQueryResultsForResourceGroupNextResponse>;
}
/**
* Queries policy states for the resource.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyStatesListQueryResultsForResourceNextResponse>
*/
listQueryResultsForResourceNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyStatesListQueryResultsForResourceNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listQueryResultsForResourceNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForResourceNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
listQueryResultsForResourceNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyStatesQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): Promise<Models.PolicyStatesListQueryResultsForResourceNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listQueryResultsForResourceNextOperationSpec,
callback) as Promise<Models.PolicyStatesListQueryResultsForResourceNextResponse>;
}
/**
* Queries policy states for the subscription level policy set definition.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyStatesListQueryResultsForPolicySetDefinitionNextResponse>
*/
listQueryResultsForPolicySetDefinitionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyStatesListQueryResultsForPolicySetDefinitionNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listQueryResultsForPolicySetDefinitionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForPolicySetDefinitionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
listQueryResultsForPolicySetDefinitionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyStatesQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): Promise<Models.PolicyStatesListQueryResultsForPolicySetDefinitionNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listQueryResultsForPolicySetDefinitionNextOperationSpec,
callback) as Promise<Models.PolicyStatesListQueryResultsForPolicySetDefinitionNextResponse>;
}
/**
* Queries policy states for the subscription level policy definition.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns Promise<Models.PolicyStatesListQueryResultsForPolicyDefinitionNextResponse>
*/
listQueryResultsForPolicyDefinitionNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyStatesListQueryResultsForPolicyDefinitionNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listQueryResultsForPolicyDefinitionNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForPolicyDefinitionNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
listQueryResultsForPolicyDefinitionNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyStatesQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): Promise<Models.PolicyStatesListQueryResultsForPolicyDefinitionNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listQueryResultsForPolicyDefinitionNextOperationSpec,
callback) as Promise<Models.PolicyStatesListQueryResultsForPolicyDefinitionNextResponse>;
}
/**
* Queries policy states for the subscription level policy assignment.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns
* Promise<Models.PolicyStatesListQueryResultsForSubscriptionLevelPolicyAssignmentNextResponse>
*/
listQueryResultsForSubscriptionLevelPolicyAssignmentNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyStatesListQueryResultsForSubscriptionLevelPolicyAssignmentNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listQueryResultsForSubscriptionLevelPolicyAssignmentNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForSubscriptionLevelPolicyAssignmentNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
listQueryResultsForSubscriptionLevelPolicyAssignmentNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyStatesQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): Promise<Models.PolicyStatesListQueryResultsForSubscriptionLevelPolicyAssignmentNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listQueryResultsForSubscriptionLevelPolicyAssignmentNextOperationSpec,
callback) as Promise<Models.PolicyStatesListQueryResultsForSubscriptionLevelPolicyAssignmentNextResponse>;
}
/**
* Queries policy states for the resource group level policy assignment.
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param [options] The optional parameters
* @returns
* Promise<Models.PolicyStatesListQueryResultsForResourceGroupLevelPolicyAssignmentNextResponse>
*/
listQueryResultsForResourceGroupLevelPolicyAssignmentNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.PolicyStatesListQueryResultsForResourceGroupLevelPolicyAssignmentNextResponse>;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param callback The callback
*/
listQueryResultsForResourceGroupLevelPolicyAssignmentNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
/**
* @param nextPageLink The NextLink from the previous successful call to List operation.
* @param options The optional parameters
* @param callback The callback
*/
listQueryResultsForResourceGroupLevelPolicyAssignmentNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): void;
listQueryResultsForResourceGroupLevelPolicyAssignmentNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.PolicyStatesQueryResults>, callback?: msRest.ServiceCallback<Models.PolicyStatesQueryResults>): Promise<Models.PolicyStatesListQueryResultsForResourceGroupLevelPolicyAssignmentNextResponse> {
return this.client.sendOperationRequest(
{
nextPageLink,
options
},
listQueryResultsForResourceGroupLevelPolicyAssignmentNextOperationSpec,
callback) as Promise<Models.PolicyStatesListQueryResultsForResourceGroupLevelPolicyAssignmentNextResponse>;
}
}
// Operation Specifications
const serializer = new msRest.Serializer(Mappers);
const listQueryResultsForManagementGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults",
urlParameters: [
Parameters.policyStatesResource,
Parameters.managementGroupsNamespace,
Parameters.managementGroupName
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.orderBy,
Parameters.select,
Parameters.from,
Parameters.to,
Parameters.filter,
Parameters.apply,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyStatesQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const summarizeForManagementGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize",
urlParameters: [
Parameters.policyStatesSummaryResource,
Parameters.managementGroupsNamespace,
Parameters.managementGroupName
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.from,
Parameters.to,
Parameters.filter
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.SummarizeResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForSubscriptionOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults",
urlParameters: [
Parameters.policyStatesResource,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.orderBy,
Parameters.select,
Parameters.from,
Parameters.to,
Parameters.filter,
Parameters.apply,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyStatesQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const summarizeForSubscriptionOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize",
urlParameters: [
Parameters.policyStatesSummaryResource,
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.from,
Parameters.to,
Parameters.filter
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.SummarizeResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults",
urlParameters: [
Parameters.policyStatesResource,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.orderBy,
Parameters.select,
Parameters.from,
Parameters.to,
Parameters.filter,
Parameters.apply,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyStatesQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const summarizeForResourceGroupOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize",
urlParameters: [
Parameters.policyStatesSummaryResource,
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.from,
Parameters.to,
Parameters.filter
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.SummarizeResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForResourceOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "{resourceId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults",
urlParameters: [
Parameters.policyStatesResource,
Parameters.resourceId
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.orderBy,
Parameters.select,
Parameters.from,
Parameters.to,
Parameters.filter,
Parameters.apply,
Parameters.expand,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyStatesQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const summarizeForResourceOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "{resourceId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize",
urlParameters: [
Parameters.policyStatesSummaryResource,
Parameters.resourceId
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.from,
Parameters.to,
Parameters.filter
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.SummarizeResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForPolicySetDefinitionOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults",
urlParameters: [
Parameters.policyStatesResource,
Parameters.subscriptionId,
Parameters.authorizationNamespace,
Parameters.policySetDefinitionName
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.orderBy,
Parameters.select,
Parameters.from,
Parameters.to,
Parameters.filter,
Parameters.apply,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyStatesQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const summarizeForPolicySetDefinitionOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize",
urlParameters: [
Parameters.policyStatesSummaryResource,
Parameters.subscriptionId,
Parameters.authorizationNamespace,
Parameters.policySetDefinitionName
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.from,
Parameters.to,
Parameters.filter
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.SummarizeResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForPolicyDefinitionOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults",
urlParameters: [
Parameters.policyStatesResource,
Parameters.subscriptionId,
Parameters.authorizationNamespace,
Parameters.policyDefinitionName
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.orderBy,
Parameters.select,
Parameters.from,
Parameters.to,
Parameters.filter,
Parameters.apply,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyStatesQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const summarizeForPolicyDefinitionOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize",
urlParameters: [
Parameters.policyStatesSummaryResource,
Parameters.subscriptionId,
Parameters.authorizationNamespace,
Parameters.policyDefinitionName
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.from,
Parameters.to,
Parameters.filter
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.SummarizeResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForSubscriptionLevelPolicyAssignmentOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults",
urlParameters: [
Parameters.policyStatesResource,
Parameters.subscriptionId,
Parameters.authorizationNamespace,
Parameters.policyAssignmentName
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.orderBy,
Parameters.select,
Parameters.from,
Parameters.to,
Parameters.filter,
Parameters.apply,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyStatesQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const summarizeForSubscriptionLevelPolicyAssignmentOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize",
urlParameters: [
Parameters.policyStatesSummaryResource,
Parameters.subscriptionId,
Parameters.authorizationNamespace,
Parameters.policyAssignmentName
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.from,
Parameters.to,
Parameters.filter
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.SummarizeResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForResourceGroupLevelPolicyAssignmentOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults",
urlParameters: [
Parameters.policyStatesResource,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.authorizationNamespace,
Parameters.policyAssignmentName
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.orderBy,
Parameters.select,
Parameters.from,
Parameters.to,
Parameters.filter,
Parameters.apply,
Parameters.skipToken
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyStatesQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const summarizeForResourceGroupLevelPolicyAssignmentOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize",
urlParameters: [
Parameters.policyStatesSummaryResource,
Parameters.subscriptionId,
Parameters.resourceGroupName,
Parameters.authorizationNamespace,
Parameters.policyAssignmentName
],
queryParameters: [
Parameters.apiVersion2,
Parameters.top,
Parameters.from,
Parameters.to,
Parameters.filter
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.SummarizeResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const beginTriggerSubscriptionEvaluationOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation",
urlParameters: [
Parameters.subscriptionId
],
queryParameters: [
Parameters.apiVersion2
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
202: {},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const beginTriggerResourceGroupEvaluationOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/latest/triggerEvaluation",
urlParameters: [
Parameters.subscriptionId,
Parameters.resourceGroupName
],
queryParameters: [
Parameters.apiVersion2
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {},
202: {},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForManagementGroupNextOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
queryParameters: [
Parameters.apiVersion2
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyStatesQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForSubscriptionNextOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
queryParameters: [
Parameters.apiVersion2
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyStatesQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForResourceGroupNextOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
queryParameters: [
Parameters.apiVersion2
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyStatesQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForResourceNextOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
queryParameters: [
Parameters.apiVersion2
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyStatesQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForPolicySetDefinitionNextOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
queryParameters: [
Parameters.apiVersion2
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyStatesQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForPolicyDefinitionNextOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
queryParameters: [
Parameters.apiVersion2
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyStatesQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForSubscriptionLevelPolicyAssignmentNextOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
queryParameters: [
Parameters.apiVersion2
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyStatesQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
};
const listQueryResultsForResourceGroupLevelPolicyAssignmentNextOperationSpec: msRest.OperationSpec = {
httpMethod: "POST",
baseUrl: "https://management.azure.com",
path: "{nextLink}",
urlParameters: [
Parameters.nextPageLink
],
queryParameters: [
Parameters.apiVersion2
],
headerParameters: [
Parameters.acceptLanguage
],
responses: {
200: {
bodyMapper: Mappers.PolicyStatesQueryResults
},
default: {
bodyMapper: Mappers.QueryFailure
}
},
serializer
}; | the_stack |
// Last module patch version validated against: 1.0.6
import { DSVParsedArray, DSVRowString } from 'd3-dsv';
export interface Request {
/**
* Aborts this request, if it is currently in-flight, and returns this request instance.
* See XMLHttpRequest’s abort.
*/
abort(): this;
/**
* Equivalent to `request.send` with the GET method: `request.send("GET")`.
*/
get(): this;
/**
* Equivalent to `request.send` with the GET method: `request.send("GET", data)`.
*/
get<RequestData>(data: RequestData): this;
/**
* Equivalent to `request.send` with the GET method: `request.send("GET", callback)`.
*/
get<ResponseData>(callback: (error: any, d: ResponseData) => void): this;
/**
* Equivalent to `request.send` with the GET method: `request.send("GET", data, callback)`.
*/
get<RequestData, ResponseData>(data: RequestData, callback: (error: any, d: ResponseData) => void): this;
/**
* Returns the current value of the request header with the specified name.
* Header names are case-insensitive.
*/
header(name: string): string;
/**
* Sets the request header with the specified name to the specified value and returns this request instance.
* If value is null, removes the request header with the specified name instead.
* Header names are case-insensitive.
*
* Request headers can only be modified before the request is sent.
* Therefore, you cannot pass a callback to the request constructor if you wish to specify a header;
* use `request.get` or similar instead.
*/
header(name: string, value: string | null): this;
/**
* Returns the current mime type, which defaults to null.
*/
mimeType(): string | null;
/**
* Sets the request mime type to the specified value and returns this request instance.
* If type is null, clears the current mime type (if any) instead.
*
* The mime type is used to both set the "Accept" request header and for `overrideMimeType`, where supported.
*
* The request mime type can only be modified before the request is sent.
* Therefore, you cannot pass a callback to the request constructor if you wish to override the mime type;
* use `request.get` or similar instead.
*/
mimeType(value: string | null): this;
/**
* Returns the currently-assigned listener for the "beforesend" type, if any.
*/
on(type: 'beforesend'): ((this: this, xhr: XMLHttpRequest) => void) | undefined;
/**
* Returns the currently-assigned listener for the "progress" type, if any.
*/
on(type: 'progress'): ((this: this, progressEvent: ProgressEvent) => void) | undefined;
/**
* Returns the currently-assigned listener for the "error" type, if any.
*/
on(type: 'error'): ((this: this, error: any) => void) | undefined;
/**
* Returns the currently-assigned listener for the "load" type, if any.
*/
on<ResponseData>(type: 'load'): ((this: this, data: ResponseData) => void) | undefined;
/**
* Returns the currently-assigned listener for the specified type, if any.
*/
on(type: string): ((this: this, data: any) => void) | undefined;
/**
* Removes the current event listener for the specified type, if any.
*/
on(type: string, listener: null): this;
/**
* Sets the event listener for the "beforesend" type,
* to allow custom headers and the like to be set before the request is sent,
* and returns this request instance.
*
* If an event listener was already registered for the same type, the existing listener is removed before the new listener is added.
* To register multiple listeners for the same type, the type may be followed by an optional name, such as `beforesend.foo`. See d3-dispatch for details.
*/
on(type: 'beforesend', listener: (this: this, xhr: XMLHttpRequest) => void): this;
/**
* Sets the event listener for the "progress" type,
* to monitor the progress of the request,
* and returns this request instance.
*
* If an event listener was already registered for the same type, the existing listener is removed before the new listener is added.
* To register multiple listeners for the same type, the type may be followed by an optional name, such as `progress.foo`. See d3-dispatch for details.
*/
on(type: 'progress', listener: (this: this, progressEvent: ProgressEvent) => void): this;
/**
* Sets the event listener for the "error" type,
* when the request completes unsuccessfully; this includes 4xx and 5xx response codes,
* and returns this request instance.
*
* If an event listener was already registered for the same type, the existing listener is removed before the new listener is added.
* To register multiple listeners for the same type, the type may be followed by an optional name, such as `error.foo`. See d3-dispatch for details.
*/
on(type: 'error', listener: (this: this, error: any) => void): this;
/**
* Sets the event listener for the "load" type,
* when the request completes successfully,
* and returns this request instance.
*
* If an event listener was already registered for the same type, the existing listener is removed before the new listener is added.
* To register multiple listeners for the same type, the type may be followed by an optional name, such as `load.foo`. See d3-dispatch for details.
*/
on<ResponseData>(type: 'load', listener: (this: this, data: ResponseData) => void): this;
/**
* Sets the event listener for the specified type,
* and returns this request instance.
*
* The type must be one of the following: "beforesend", "progress", "load", "error".
*
* If an event listener was already registered for the same type, the existing listener is removed before the new listener is added.
* To register multiple listeners for the same type, the type may be followed by an optional name, such as `load.foo`. See d3-dispatch for details.
*/
on(type: string, listener: (this: this, data: any) => void): this;
/**
* Returns the current password, which defaults to null.
*/
password(): string | null;
/**
* Sets the password for authentication to the specified string and returns this request instance.
*/
password(value: string | null): this;
/**
* Equivalent to `request.send` with the POST method: `request.send("POST")`.
*/
post(): this;
/**
* Equivalent to `request.send` with the POST method: `request.send("POST", data)`.
*/
post<RequestData>(data: RequestData): this;
/**
* Equivalent to `request.send` with the POST method: `request.send("POST", callback)`.
*/
post<ResponseData>(callback: (this: this, error: any, d: ResponseData) => void): this;
/**
* Equivalent to `request.send` with the POST method: `request.send("POST", data, callback)`.
*/
post<RequestData, ResponseData>(data: RequestData, callback: (this: this, error: any, d: ResponseData) => void): this;
/**
* Sets the response value function to the specified function and returns this request instance.
* The response value function is used to map the response XMLHttpRequest object to a useful data value.
* See the convenience methods `json` and `text` for examples.
*/
response<ResponseData>(callback: (this: this, response: XMLHttpRequest) => ResponseData): this;
/**
* Returns the current response type, which defaults to `` (the empty string).
*/
responseType(): XMLHttpRequestResponseType | undefined;
/**
* Sets the response type attribute of the request and returns this request instance. Typical values are: `` (the empty string), `arraybuffer`, `blob`, `document`, and `text`.
*/
responseType(value: XMLHttpRequestResponseType): this;
/**
* Issues this request using the specified method (such as GET or POST).
*
* The listeners "load" and "error" should be registered via `request.on`.
*/
send(method: string): this;
/**
* Issues this request using the specified method (such as GET or POST), posting the specified data in the request body, and returns this request instance.
*
* The listeners "load" and "error" should be registered via `request.on`.
*/
send<RequestData>(method: string, data: RequestData): this;
/**
* Issues this request using the specified method (such as GET or POST) and returns this request instance.
* The callback will be invoked asynchronously when the request succeeds or fails.
* The callback is invoked with two arguments: the error, if any, and the response value.
* The response value is undefined if an error occurs.
*/
send<ResponseData>(method: string, callback: (this: this, error: any | null, d: ResponseData | null) => void): this;
/**
* Issues this request using the specified method (such as GET or POST), posting the specified data in the request body, and returns this request instance.
* The callback will be invoked asynchronously when the request succeeds or fails.
* The callback is invoked with two arguments: the error, if any, and the response value.
* The response value is undefined if an error occurs.
*/
send<RequestData, ResponseData>(method: string, data: RequestData, callback: (this: this, error: any | null, d: ResponseData | null) => void): this;
/**
* Returns the current response timeout, which defaults to 0.
*/
timeout(): number;
/**
* Sets the timeout attribute of the request to the specified number of milliseconds and returns this request instance.
*/
timeout(value: number): this;
/**
* Returns the current user name, which defaults to null.
*/
user(): string | null;
/**
* Sets the user name for authentication to the specified string and returns this request instance.
*/
user(value: string | null): this;
}
export interface DsvRequest extends Request {
row<ParsedRow extends object>(value: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow): DsvRequest;
}
/**
* Returns a new request for the CSV file at the specified url with the default mime type `text/csv`.
*/
export function csv(url: string): DsvRequest;
/**
* Returns a new request for the CSV file at the specified url with the default mime type `text/csv`.
* And send a GET request.
*/
export function csv(url: string, callback: (this: DsvRequest, error: any, d: DSVParsedArray<DSVRowString>) => void): DsvRequest;
/**
* Returns a new request for the CSV file at the specified url with the default mime type `text/csv`.
* And send a GET request.
* Use a row conversion function to map and filter row objects to a more-specific representation; see `dsv.parse` for details.
*/
export function csv<ParsedRow extends object>(
url: string,
row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow,
callback: (this: DsvRequest, error: any, d: DSVParsedArray<ParsedRow>) => void
): DsvRequest;
/**
* Returns a new request for the HTML file at the specified url with the default mime type `text/html`. The HTML file is returned as a document fragment.
*/
export function html(url: string): Request;
/**
* Returns a new request for the HTML file at the specified url with the default mime type `text/html`. The HTML file is returned as a document fragment.
* And send a GET request.
*/
export function html(url: string, callback: (this: Request, error: any, d: DocumentFragment) => void): Request;
/**
* Returns a new request to get the JSON file at the specified url with the default mime type `application/json`.
*/
export function json(url: string): Request;
/**
* Returns a new request to get the JSON file at the specified url with the default mime type `application/json`.
* And send a GET request.
*/
export function json<ParsedObject extends { [key: string]: any }>(url: string, callback: (this: Request, error: any, d: ParsedObject) => void): Request;
/**
* Returns a new request for specified url. The returned request is not yet sent and can be further configured.
*
* See `d3.json`, `d3.csv`, `d3.tsv`, `d3.text`, `d3.html` and `d3.xml` for content-specific convenience constructors.
*/
export function request(url: string): Request;
/**
* Returns a new request for specified url. It is equivalent to calling `request.get` immediately after construction: `d3.request(url).get(callback)`.
* And send a GET request.
*
* If you wish to specify a request header or a mime type, you must not specify a callback to the constructor.
* Use `request.header` or `request.mimeType` followed by `request.get` instead.
*
* See `d3.json`, `d3.csv`, `d3.tsv`, `d3.text`, `d3.html` and `d3.xml` for content-specific convenience constructors.
*/
export function request(url: string, callback: (this: Request, error: any, d: XMLHttpRequest) => void): Request;
/**
* Returns a new request to get the text file at the specified url with the default mime type `text/plain`.
*/
export function text(url: string): Request;
/**
* Returns a new request to get the text file at the specified url with the default mime type `text/plain`.
* And send a GET request.
*/
export function text(url: string, callback: (this: Request, error: any, d: string) => void): Request;
/**
* Returns a new request for a TSV file at the specified url with the default mime type `text/tab-separated-values`.
*/
export function tsv(url: string): DsvRequest;
/**
* Returns a new request for a TSV file at the specified url with the default mime type `text/tab-separated-values`.
* And send a GET request.
*/
export function tsv(url: string, callback: (this: DsvRequest, error: any, d: DSVParsedArray<DSVRowString>) => void): DsvRequest;
/**
* Returns a new request for a TSV file at the specified url with the default mime type `text/tab-separated-values`.
* And send a GET request.
* Use a row conversion function to map and filter row objects to a more-specific representation; see `dsv.parse` for details.
*/
export function tsv<ParsedRow extends object>(
url: string,
row: (rawRow: DSVRowString, index: number, columns: string[]) => ParsedRow,
callback: (this: DsvRequest, error: any, d: DSVParsedArray<ParsedRow>) => void
): DsvRequest;
/**
* Returns a new request to get the XML file at the specified url with the default mime type `application/xml`.
*/
export function xml(url: string): Request;
/**
* Returns a new request to get the XML file at the specified url with the default mime type `application/xml`.
* And send a GET request.
*/
export function xml(url: string, callback: (this: Request, error: any, d: any) => void): Request; | the_stack |
* @module Tiles
*/
import { assert, BeEvent } from "@itwin/core-bentley";
import { MapLayerAccessClient, MapLayerAccessToken, MapLayerAccessTokenParams, MapLayerTokenEndpoint } from "@itwin/core-frontend";
import { ArcGisOAuth2Token, ArcGisTokenClientType } from "./ArcGisTokenGenerator";
import { ArcGisOAuth2Endpoint, ArcGisOAuth2EndpointType } from "./ArcGisOAuth2Endpoint";
import { ArcGisTokenManager } from "./ArcGisTokenManager";
import { ArcGisUrl } from "./ArcGisUrl";
/** @beta */
export interface ArcGisEnterpriseClientId {
/* Oauth API endpoint base URL (i.e. https://hostname/portal/sharing/oauth2/authorize)
used to identify uniquely each enterprise server. */
serviceBaseUrl: string;
/* Application's clientId for this enterprise server.*/
clientId: string;
}
/** @beta */
export interface ArcGisOAuthClientIds {
/* Application's OAuth clientId in ArcGIS online */
arcgisOnlineClientId?: string;
/* Application's OAuth clientId for each enterprise server used. */
enterpriseClientIds?: ArcGisEnterpriseClientId[];
}
/** @beta
* ArcGIS OAuth configurations parameters.
* See https://developers.arcgis.com/documentation/mapping-apis-and-services/security/arcgis-identity/serverless-web-apps/
* more details.
*/
export interface ArcGisOAuthConfig {
/* URL to which a user is sent once they complete sign in authorization.
Must match a URI you define in the developer dashboard, otherwise, the authorization will be rejected.
*/
redirectUri: string;
/* Optional expiration after which the token will expire. Defined in minutes with a maximum of two weeks (20160 minutes)*/
tokenExpiration?: number;
/* Application client Ids */
clientIds: ArcGisOAuthClientIds;
}
/** @beta */
export class ArcGisAccessClient implements MapLayerAccessClient {
public readonly onOAuthProcessEnd = new BeEvent();
private _redirectUri: string | undefined;
private _expiration: number | undefined;
private _clientIds: ArcGisOAuthClientIds | undefined;
public constructor() {
}
public initialize(oAuthConfig?: ArcGisOAuthConfig): boolean {
if (oAuthConfig) {
this._redirectUri = oAuthConfig.redirectUri;
this._expiration = oAuthConfig.tokenExpiration;
this._clientIds = oAuthConfig.clientIds;
this.initOauthCallbackFunction();
}
return true;
}
private initOauthCallbackFunction() {
(window as any).arcGisOAuth2Callback = (redirectLocation?: Location) => {
let eventSuccess = false;
let stateData;
if (redirectLocation && redirectLocation.hash.length > 0) {
const locationHash = redirectLocation.hash;
const hashParams = new URLSearchParams(locationHash.substring(1));
const token = hashParams.get("access_token") ?? undefined;
const expiresInStr = hashParams.get("expires_in") ?? undefined;
const userName = hashParams.get("username") ?? undefined;
const ssl = hashParams.get("ssl") === "true";
const stateStr = hashParams.get("state") ?? undefined;
const persist = hashParams.get("persist") === "true";
if (token !== undefined && expiresInStr !== undefined && userName !== undefined && ssl !== undefined && stateStr !== undefined) {
let endpointOrigin;
try {
const state = JSON.parse(stateStr);
stateData = state?.customData;
endpointOrigin = state?.endpointOrigin;
} catch {
}
const expiresIn = Number(expiresInStr);
const expiresAt = (expiresIn * 1000) + (+new Date()); // Converts the token expiration delay (seconds) into a timestamp (UNIX time)
if (endpointOrigin !== undefined) {
ArcGisTokenManager.setOAuth2Token(endpointOrigin, { token, expiresAt, ssl, userName, persist });
eventSuccess = true;
}
}
}
this.onOAuthProcessEnd.raiseEvent(eventSuccess, stateData);
};
}
public unInitialize() {
this._redirectUri = undefined;
this._expiration = undefined;
(window as any).arcGisOAuth2Callback = undefined;
}
public async getAccessToken(params: MapLayerAccessTokenParams): Promise<MapLayerAccessToken | undefined> {
// First lookup Oauth2 tokens, otherwise check try "legacy tokens" if credentials were provided
try {
const oauth2Token = await this.getOAuthTokenForMapLayerUrl(params.mapLayerUrl.toString());
if (oauth2Token)
return oauth2Token;
if (params.userName && params.password) {
return await ArcGisTokenManager.getToken(params.mapLayerUrl.toString(), params.userName, params.password, { client: ArcGisTokenClientType.referer });
}
} catch {
}
return undefined;
}
public async getTokenServiceEndPoint(mapLayerUrl: string): Promise<MapLayerTokenEndpoint | undefined> {
let tokenEndpoint: ArcGisOAuth2Endpoint | undefined;
try {
tokenEndpoint = await this.getOAuth2Endpoint(mapLayerUrl, ArcGisOAuth2EndpointType.Authorize);
if (tokenEndpoint) {
}
} catch { }
return tokenEndpoint;
}
public invalidateToken(token: MapLayerAccessToken): boolean {
let found = ArcGisTokenManager.invalidateToken(token);
if (!found) {
found = ArcGisTokenManager.invalidateOAuth2Token(token);
}
return found;
}
public get redirectUri() {
return this._redirectUri;
}
public getMatchingEnterpriseClientId(url: string) {
let clientId: string | undefined;
const clientIds = this.arcGisEnterpriseClientIds;
if (!clientIds) {
return undefined;
}
for (const entry of clientIds) {
if (url.toLowerCase().startsWith(entry.serviceBaseUrl)) {
clientId = entry.clientId;
}
}
return clientId;
}
public get expiration() {
return this._expiration;
}
public get arcGisOnlineClientId() {
return this._clientIds?.arcgisOnlineClientId;
}
public set arcGisOnlineClientId(clientId: string | undefined) {
if (this._clientIds === undefined) {
this._clientIds = { arcgisOnlineClientId: clientId };
}
this._clientIds.arcgisOnlineClientId = clientId;
}
public get arcGisEnterpriseClientIds() {
return this._clientIds?.enterpriseClientIds;
}
public setEnterpriseClientId(serviceBaseUrl: string, clientId: string) {
if (this._clientIds?.enterpriseClientIds) {
const foundIdx = this._clientIds.enterpriseClientIds.findIndex((entry) => entry.serviceBaseUrl === serviceBaseUrl);
if (foundIdx !== -1) {
this._clientIds.enterpriseClientIds[foundIdx].clientId = clientId;
} else {
this._clientIds.enterpriseClientIds.push({ serviceBaseUrl, clientId });
}
} else {
if (this._clientIds === undefined) {
this._clientIds = {};
}
this._clientIds.enterpriseClientIds = [{ serviceBaseUrl, clientId }];
}
}
public removeEnterpriseClientId(clientId: ArcGisEnterpriseClientId) {
if (this._clientIds?.enterpriseClientIds) {
this._clientIds.enterpriseClientIds = this._clientIds?.enterpriseClientIds?.filter((item) => item.serviceBaseUrl !== clientId.serviceBaseUrl);
}
}
/// //////////
/** @internal */
private async getOAuthTokenForMapLayerUrl(mapLayerUrl: string): Promise<ArcGisOAuth2Token | undefined> {
try {
const oauthEndpoint = await this.getOAuth2Endpoint(mapLayerUrl, ArcGisOAuth2EndpointType.Authorize);
if (oauthEndpoint !== undefined) {
const oauthEndpointUrl = new URL(oauthEndpoint.getUrl());
return ArcGisTokenManager.getOAuth2Token(oauthEndpointUrl.origin);
}
} catch { }
return undefined;
}
/**
* Test if Oauth2 endpoint is accessible and has an associated appId
* @internal
*/
private async validateOAuth2Endpoint(endpointUrl: string): Promise<boolean> {
// Check if we got a matching appId for that endpoint, otherwise its not worth going further
if (undefined === this.getMatchingEnterpriseClientId(endpointUrl)) {
return false;
}
let status: number | undefined;
try {
const data = await fetch(endpointUrl, { method: "GET" });
status = data.status;
} catch (error: any) {
status = error.status;
}
return status === 400; // Oauth2 API returns 400 (Bad Request) when there are missing parameters
}
// Derive the Oauth URL from a typical MapLayerURL
// i.e. https://hostname/server/rest/services/NewYork/NewYork3857/MapServer
// => https://hostname/portal/sharing/oauth2/authorize
private _oauthAuthorizeEndPointsCache = new Map<string, any>();
private _oauthTokenEndPointsCache = new Map<string, any>();
/**
* Get OAuth2 endpoint that must be cause to get the Oauth2 token
* @internal
*/
private async getOAuth2Endpoint(url: string, endpoint: ArcGisOAuth2EndpointType): Promise<ArcGisOAuth2Endpoint | undefined> {
// Return from cache if available
const cachedEndpoint = (endpoint === ArcGisOAuth2EndpointType.Authorize ? this._oauthAuthorizeEndPointsCache.get(url) : this._oauthTokenEndPointsCache.get(url));
if (cachedEndpoint !== undefined) {
return cachedEndpoint;
}
const cacheResult = (obj: ArcGisOAuth2Endpoint) => {
if (endpoint === ArcGisOAuth2EndpointType.Authorize) {
this._oauthAuthorizeEndPointsCache.set(url, obj);
} else {
this._oauthTokenEndPointsCache.set(url, obj);
}
};
const endpointStr = (endpoint === ArcGisOAuth2EndpointType.Authorize ? "authorize" : "token");
const urlObj = new URL(url);
if (urlObj.hostname.toLowerCase().endsWith("arcgis.com")) {
// ArcGIS Online (fixed)
// Doc: https://developers.arcgis.com/documentation/mapping-apis-and-services/security/oauth-2.0/
if (this.arcGisOnlineClientId === undefined) {
return undefined;
}
const oauth2Url = `https://www.arcgis.com/sharing/rest/oauth2/${endpointStr}`;
return new ArcGisOAuth2Endpoint(url, this.constructLoginUrl(oauth2Url, true), true);
} else {
// First attempt: derive the Oauth2 token URL from the 'tokenServicesUrl', exposed by the 'info request'
let restUrlFromTokenService: URL | undefined;
try {
restUrlFromTokenService = await ArcGisUrl.getRestUrlFromGenerateTokenUrl(urlObj);
} catch { }
if (restUrlFromTokenService !== undefined) {
// Validate the URL we just composed
try {
const oauth2Url = `${restUrlFromTokenService.toString()}oauth2/${endpointStr}`;
if (await this.validateOAuth2Endpoint(oauth2Url)) {
const oauthEndpoint = new ArcGisOAuth2Endpoint(oauth2Url, this.constructLoginUrl(oauth2Url, false), false);
cacheResult(oauthEndpoint);
return oauthEndpoint;
}
} catch { }
}
// If reach this point, that means we could not derive the token endpoint from 'tokenServicesUrl'
// lets use another approach.
// ArcGIS Enterprise Format https://<host>:<port>/<subdirectory>/sharing/rest/oauth2/authorize
const regExMatch = url.match(new RegExp(/([^&\/]+)\/rest\/services\/.*/, "i"));
if (regExMatch !== null && regExMatch.length >= 2) {
const subdirectory = regExMatch[1];
const port = (urlObj.port !== "80" && urlObj.port !== "443") ? `:${urlObj.port}` : "";
const newUrlObj = new URL(`${urlObj.protocol}//${urlObj.hostname}${port}/${subdirectory}/sharing/rest/oauth2/${endpointStr}`);
// Check again the URL we just composed
try {
const newUrl = newUrlObj.toString();
if (await this.validateOAuth2Endpoint(newUrl)) {
const oauthEndpoint = new ArcGisOAuth2Endpoint(newUrl, this.constructLoginUrl(newUrl, false), false);
cacheResult(oauthEndpoint);
return oauthEndpoint;
}
} catch { }
}
}
return undefined; // we could not find any valid oauth2 endpoint
}
/**
* Construct the complete Authorize url to starts the Oauth process
* @internal
*/
private constructLoginUrl(url: string, isArcgisOnline: boolean) {
const urlObj = new URL(url);
// Set the client id
if (isArcgisOnline) {
const clientId = this.arcGisOnlineClientId;
assert(clientId !== undefined);
if (clientId !== undefined) {
urlObj.searchParams.set("client_id", clientId);
}
} else {
const clientId = this.getMatchingEnterpriseClientId(url);
assert(clientId !== undefined);
if (undefined !== clientId) {
urlObj.searchParams.set("client_id", clientId);
}
}
urlObj.searchParams.set("response_type", "token");
if (this.expiration !== undefined) {
urlObj.searchParams.set("expiration", `${this.expiration}`);
}
if (this.redirectUri)
urlObj.searchParams.set("redirect_uri", this.redirectUri);
return urlObj.toString();
}
} | the_stack |
import type { Dictionary } from '@mikro-orm/core';
import { BigIntType, EnumType, Utils } from '@mikro-orm/core';
import type { AbstractSqlConnection, Column, Index, DatabaseTable, TableDifference } from '@mikro-orm/knex';
import { SchemaHelper } from '@mikro-orm/knex';
import type { Knex } from 'knex';
export class PostgreSqlSchemaHelper extends SchemaHelper {
static readonly DEFAULT_VALUES = {
'now()': ['now()', 'current_timestamp'],
'current_timestamp(?)': ['current_timestamp(?)'],
"('now'::text)::timestamp(?) with time zone": ['current_timestamp(?)'],
"('now'::text)::timestamp(?) without time zone": ['current_timestamp(?)'],
'null::character varying': ['null'],
'null::timestamp with time zone': ['null'],
'null::timestamp without time zone': ['null'],
};
getSchemaBeginning(charset: string): string {
return `set names '${charset}';\n${this.disableForeignKeysSQL()}\n\n`;
}
getSchemaEnd(): string {
return `${this.enableForeignKeysSQL()}\n`;
}
getListTablesSQL(): string {
return `select table_name, nullif(table_schema, 'public') as schema_name, `
+ `(select pg_catalog.obj_description(c.oid) from pg_catalog.pg_class c
where c.oid = (select ('"' || table_schema || '"."' || table_name || '"')::regclass::oid) and c.relname = table_name) as table_comment `
+ `from information_schema.tables `
+ `where table_schema not like 'pg_%' and table_schema != 'information_schema' `
+ `and table_name != 'geometry_columns' and table_name != 'spatial_ref_sys' and table_type != 'VIEW' order by table_name`;
}
async getColumns(connection: AbstractSqlConnection, tableName: string, schemaName = 'public'): Promise<Column[]> {
const sql = `select column_name,
column_default,
is_nullable,
udt_name,
coalesce(datetime_precision,
character_maximum_length) length,
numeric_precision,
numeric_scale,
data_type,
(select pg_catalog.col_description(c.oid, cols.ordinal_position::int)
from pg_catalog.pg_class c
where c.oid = (select ('"' || cols.table_schema || '"."' || cols.table_name || '"')::regclass::oid) and c.relname = cols.table_name) as column_comment
from information_schema.columns cols where table_schema = '${schemaName}' and table_name = '${tableName}'`;
const columns = await connection.execute<any[]>(sql);
const str = (val: string | number | undefined) => val != null ? '' + val : val;
return columns.map(col => {
const mappedType = connection.getPlatform().getMappedType(col.data_type);
const increments = col.column_default?.includes('nextval') && connection.getPlatform().isNumericColumn(mappedType);
return ({
name: col.column_name,
type: col.data_type.toLowerCase() === 'array' ? col.udt_name.replace(/^_(.*)$/, '$1[]') : col.udt_name,
mappedType,
length: col.length,
precision: col.numeric_precision,
scale: col.numeric_scale,
nullable: col.is_nullable === 'YES',
default: str(this.normalizeDefaultValue(col.column_default, col.length)),
unsigned: increments,
autoincrement: increments,
comment: col.column_comment,
});
});
}
async getIndexes(connection: AbstractSqlConnection, tableName: string, schemaName: string): Promise<Index[]> {
const sql = this.getIndexesSQL(tableName, schemaName);
const indexes = await connection.execute<any[]>(sql);
return this.mapIndexes(indexes.map(index => ({
columnNames: [index.column_name],
keyName: index.constraint_name,
unique: index.unique,
primary: index.primary,
})));
}
getForeignKeysSQL(tableName: string, schemaName = 'public'): string {
return `select kcu.table_name as table_name, rel_kcu.table_name as referenced_table_name,
case when rel_kcu.constraint_schema = 'public' then null else rel_kcu.constraint_schema end as referenced_schema_name,
kcu.column_name as column_name,
rel_kcu.column_name as referenced_column_name, kcu.constraint_name, rco.update_rule, rco.delete_rule
from information_schema.table_constraints tco
join information_schema.key_column_usage kcu
on tco.constraint_schema = kcu.constraint_schema
and tco.constraint_name = kcu.constraint_name
join information_schema.referential_constraints rco
on tco.constraint_schema = rco.constraint_schema
and tco.constraint_name = rco.constraint_name
join information_schema.key_column_usage rel_kcu
on rco.unique_constraint_schema = rel_kcu.constraint_schema
and rco.unique_constraint_name = rel_kcu.constraint_name
and kcu.ordinal_position = rel_kcu.ordinal_position
where tco.table_name = '${tableName}' and tco.table_schema = '${schemaName}' and tco.constraint_schema = '${schemaName}' and tco.constraint_type = 'FOREIGN KEY'
order by kcu.table_schema, kcu.table_name, kcu.ordinal_position, kcu.constraint_name`;
}
async getEnumDefinitions(connection: AbstractSqlConnection, tableName: string, schemaName = 'public'): Promise<Dictionary> {
const sql = `select conrelid::regclass as table_from, conname, pg_get_constraintdef(c.oid) as enum_def
from pg_constraint c join pg_namespace n on n.oid = c.connamespace
where contype = 'c' and conrelid = '"${schemaName}"."${tableName}"'::regclass order by contype`;
const enums = await connection.execute<any[]>(sql);
return enums.reduce((o, item) => {
// check constraints are defined as one of:
// `CHECK ((type = ANY (ARRAY['local'::text, 'global'::text])))`
// `CHECK (((enum_test)::text = ANY ((ARRAY['a'::character varying, 'b'::character varying, 'c'::character varying])::text[])))`
// `CHECK ((type = 'a'::text))`
const m1 = item.enum_def.match(/check \(\(\((\w+)\)::/i) || item.enum_def.match(/check \(\((\w+) = /i);
const m2 = item.enum_def.match(/\(array\[(.*)]\)/i) || item.enum_def.match(/ = (.*)\)/i);
/* istanbul ignore else */
if (m1 && m2) {
o[m1[1]] = m2[1].split(',').map((item: string) => item.trim().match(/^\(?'(.*)'/)![1]);
}
return o;
}, {} as Dictionary<string>);
}
createTableColumn(table: Knex.TableBuilder, column: Column, fromTable: DatabaseTable, changedProperties?: Set<string>) {
const compositePK = fromTable.getPrimaryKey()?.composite;
if (column.autoincrement && !compositePK && !changedProperties) {
if (column.mappedType instanceof BigIntType) {
return table.bigIncrements(column.name);
}
return table.increments(column.name);
}
if (column.mappedType instanceof EnumType && column.enumItems?.every(item => Utils.isString(item))) {
return table.enum(column.name, column.enumItems);
}
// serial is just a pseudo type, it cannot be used for altering
/* istanbul ignore next */
if (changedProperties && column.type.includes('serial')) {
column.type = column.type.replace('serial', 'int');
}
return table.specificType(column.name, column.type);
}
configureColumn(column: Column, col: Knex.ColumnBuilder, knex: Knex, changedProperties?: Set<string>) {
const guard = (key: string) => !changedProperties || changedProperties.has(key);
Utils.runIfNotEmpty(() => col.nullable(), column.nullable && guard('nullable'));
Utils.runIfNotEmpty(() => col.notNullable(), !column.nullable && guard('nullable'));
Utils.runIfNotEmpty(() => col.unsigned(), column.unsigned && guard('unsigned'));
Utils.runIfNotEmpty(() => col.comment(column.comment!), column.comment && !changedProperties);
this.configureColumnDefault(column, col, knex, changedProperties);
return col;
}
getPreAlterTable(tableDiff: TableDifference, safe: boolean): string {
// changing uuid column type requires to cast it to text first
const uuid = Object.values(tableDiff.changedColumns).find(col => col.changedProperties.has('type') && col.fromColumn.type === 'uuid');
if (!uuid) {
return '';
}
return `alter table "${tableDiff.name}" alter column "${uuid.column.name}" type text using ("${uuid.column.name}"::text)`;
}
getAlterColumnAutoincrement(tableName: string, column: Column): string {
const ret: string[] = [];
const quoted = (val: string) => this.platform.quoteIdentifier(val);
/* istanbul ignore else */
if (column.autoincrement) {
const seqName = this.platform.getIndexName(tableName, [column.name], 'sequence');
ret.push(`create sequence if not exists ${quoted(seqName)}`);
ret.push(`select setval('${seqName}', (select max(${quoted(column.name)}) from ${quoted(tableName)}))`);
ret.push(`alter table ${quoted(tableName)} alter column ${quoted(column.name)} set default nextval('${seqName}')`);
} else if (column.default == null) {
ret.push(`alter table ${quoted(tableName)} alter column ${quoted(column.name)} drop default`);
}
return ret.join(';\n');
}
getChangeColumnCommentSQL(tableName: string, to: Column): string {
const value = to.comment ? `'${to.comment}'` : 'null';
return `comment on column "${tableName}"."${to.name}" is ${value}`;
}
normalizeDefaultValue(defaultValue: string, length: number) {
if (!defaultValue) {
return defaultValue;
}
const match = defaultValue.match(/^'(.*)'::(.*)$/);
if (match) {
if (match[2] === 'integer') {
return +match[1];
}
return `'${match[1]}'`;
}
return super.normalizeDefaultValue(defaultValue, length, PostgreSqlSchemaHelper.DEFAULT_VALUES);
}
getDatabaseExistsSQL(name: string): string {
return `select 1 from pg_database where datname = '${name}'`;
}
getDatabaseNotExistsError(dbName: string): string {
return `database "${dbName}" does not exist`;
}
getManagementDbName(): string {
return 'postgres';
}
disableForeignKeysSQL(): string {
return `set session_replication_role = 'replica';`;
}
enableForeignKeysSQL(): string {
return `set session_replication_role = 'origin';`;
}
getRenameIndexSQL(tableName: string, index: Index, oldIndexName: string): string {
oldIndexName = this.platform.quoteIdentifier(oldIndexName);
const keyName = this.platform.quoteIdentifier(index.keyName);
return `alter index ${oldIndexName} rename to ${keyName}`;
}
private getIndexesSQL(tableName: string, schemaName = 'public'): string {
return `select relname as constraint_name, attname as column_name, idx.indisunique as unique, idx.indisprimary as primary
from pg_index idx
left join pg_class AS i on i.oid = idx.indexrelid
left join pg_attribute a on a.attrelid = idx.indrelid and a.attnum = ANY(idx.indkey) and a.attnum > 0
where indrelid = '"${schemaName}"."${tableName}"'::regclass`;
}
} | the_stack |
import * as actions from "@nteract/actions";
import { monocellNotebook } from "@nteract/commutable";
import { executeRequest, createMessage } from "@nteract/messaging";
import * as stateModule from "@nteract/types";
import Immutable from "immutable";
import { StateObservable } from "redux-observable";
import { empty, from, Observable, of, Subject } from "rxjs";
import { catchError, share, toArray } from "rxjs/operators";
import {
createExecuteCellStream,
executeCellStream,
sendExecuteRequestEpic
} from "../../src/execute";
describe("executeCellStream", () => {
test("dispatches actions for updating execution metadata", done => {
const message = createMessage("execute_request");
const msg_id = message.header.msg_id;
const kernelMsgs = [
{
parent_header: {
msg_id
},
header: {
msg_type: "execute_input"
},
content: {
execution_count: 0
}
},
{
parent_header: {
msg_id
},
header: {
msg_type: "status"
},
content: {
execution_state: "busy"
}
},
{
parent_header: {
msg_id
},
header: {
msg_type: "status"
},
content: {
execution_state: "idle"
}
},
{
parent_header: {
msg_id
},
header: {
msg_type: "execute_reply"
},
content: {
execution_count: 0
}
}
];
const sent = new Subject();
const received = new Subject();
const channels = Subject.create(sent, received);
sent.subscribe(() => {
kernelMsgs.map(msg => received.next(msg));
});
const obs = executeCellStream(channels, "0", message, "fakeContentRef");
const emittedActions = [];
obs.subscribe(action => {
emittedActions.push(action);
});
expect(emittedActions).toContainEqual(
expect.objectContaining(
actions.setInCell({
id: "0",
contentRef: "fakeContentRef",
path: ["metadata", "execution", "iopub.execute_input"],
value: expect.any(String)
})
)
);
expect(emittedActions).toContainEqual(
expect.objectContaining(
actions.setInCell({
id: "0",
contentRef: "fakeContentRef",
path: ["metadata", "execution", "shell.execute_reply"],
value: expect.any(String)
})
)
);
expect(emittedActions).toContainEqual(
expect.objectContaining(
actions.setInCell({
id: "0",
contentRef: "fakeContentRef",
path: ["metadata", "execution", "iopub.status.idle"],
value: expect.any(String)
})
)
);
expect(emittedActions).toContainEqual(
expect.objectContaining(
actions.setInCell({
id: "0",
contentRef: "fakeContentRef",
path: ["metadata", "execution", "iopub.status.busy"],
value: expect.any(String)
})
)
);
done();
});
});
describe("createExecuteCellStream", () => {
test("does not complete but does push until abort action", done => {
const frontendToShell = new Subject();
const shellToFrontend = new Subject();
const mockShell = Subject.create(frontendToShell, shellToFrontend);
const channels = mockShell;
const state$ = {
value: {
core: stateModule.makeStateRecord({
kernelRef: "fake",
entities: stateModule.makeEntitiesRecord({
kernels: stateModule.makeKernelsRecord({
byRef: Immutable.Map({
fake: stateModule.makeRemoteKernelRecord({
channels,
status: "busy"
})
})
}),
contents: stateModule.makeContentsRecord({
byRef: Immutable.Map({
fakeContentRef: stateModule.makeNotebookContentRecord({
model: stateModule.makeDocumentRecord({
kernelRef: "fake"
})
})
})
})
})
}),
app: {}
}
};
const action$ = from([]);
const message = executeRequest("source");
const observable = createExecuteCellStream(
action$,
channels,
message,
"id",
"fakeContentRef"
);
const actionBuffer = [];
observable.subscribe(
x => actionBuffer.push(x),
err => done.fail(err)
);
expect(actionBuffer).toEqual([
actions.clearOutputs({
id: "id",
contentRef: "fakeContentRef"
}),
actions.updateCellStatus({
id: "id",
status: "queued",
contentRef: "fakeContentRef"
})
]);
done();
});
});
describe("sendExecuteRequestEpic", () => {
const state = {
app: {
kernel: {
channels: "errorInExecuteCellObservable",
status: "idle"
},
githubToken: "blah"
}
};
const state$ = new StateObservable(new Subject(), state);
test("Errors on a bad action", done => {
// Make one hot action
const badAction$ = of(
actions.sendExecuteRequest({ id: "id", contentRef: "fakeContentRef" })
).pipe(share()) as Observable<any>;
const responseActions = sendExecuteRequestEpic(badAction$, state$).pipe(
catchError(error => {
expect(error.message).toEqual(
"No CellId provided in ExecuteCell action."
);
return empty();
})
);
responseActions.subscribe(
// Every action that goes through should get stuck on an array
(x: actions.ExecuteFailed) => {
expect(x.type).toEqual(actions.EXECUTE_FAILED);
done();
},
err => done.fail(err)
);
});
test("Errors on an action where source not a string", done => {
const badAction$ = of(
actions.sendExecuteRequest({ id: "id", contentRef: "fakeContentRef" })
).pipe(share()) as Observable<any>;
const responseActions = sendExecuteRequestEpic(badAction$, state$).pipe(
catchError(error => {
expect(error.message).toEqual("execute cell needs source string");
return empty();
})
);
responseActions.subscribe(
// Every action that goes through should get stuck on an array
(x: actions.ExecuteFailed) => {
expect(x.type).toEqual(actions.EXECUTE_FAILED);
done();
},
err => done.fail(err)
);
});
test("Informs about disconnected kernels, allows reconnection", async () => {
const disconnectedState = {
app: {},
core: stateModule.makeStateRecord({
kernelRef: "fake",
entities: stateModule.makeEntitiesRecord({
contents: stateModule.makeContentsRecord({
byRef: Immutable.Map({
fakeContent: stateModule.makeNotebookContentRecord()
})
}),
kernels: stateModule.makeKernelsRecord({
byRef: Immutable.Map({
fake: stateModule.makeRemoteKernelRecord({
channels: null,
status: "not connected"
})
})
})
})
})
};
const disconnectedState$ = new StateObservable(
new Subject(),
disconnectedState
);
const action$ = of(
actions.sendExecuteRequest({ id: "first", contentRef: "fakeContentRef" })
);
const responses = await sendExecuteRequestEpic(action$, disconnectedState$)
.pipe(toArray())
.toPromise();
expect(responses.map(response => response.type)).toEqual([
actions.EXECUTE_FAILED
]);
});
test("throws an error when attempting to execute non-notebook types", done => {
const state = {
app: {},
core: stateModule.makeStateRecord({
kernelRef: "fake",
entities: stateModule.makeEntitiesRecord({
contents: stateModule.makeContentsRecord({
byRef: Immutable.Map({
fakeContent: stateModule.makeDummyContentRecord()
})
}),
kernels: stateModule.makeKernelsRecord({
byRef: Immutable.Map({
fake: stateModule.makeRemoteKernelRecord({
channels: null,
status: "not connected"
})
})
})
})
})
};
const state$ = new StateObservable(new Subject(), state);
const action$ = of(
actions.sendExecuteRequest({ id: "first", contentRef: "fakeContent" })
);
let result = "";
sendExecuteRequestEpic(action$, state$).subscribe(
// Every action that goes through should get stuck on an array
(x: actions.ExecuteFailed) => {
result = x.payload.error.message;
done();
},
err => done.fail(err)
);
expect(result).toContain(
"Cannot send execute requests from non-notebook files"
);
});
test("throws an error when cell is not found", done => {
const state = {
app: {},
core: stateModule.makeStateRecord({
kernelRef: "fake",
entities: stateModule.makeEntitiesRecord({
contents: stateModule.makeContentsRecord({
byRef: Immutable.Map({
fakeContent: stateModule.makeNotebookContentRecord()
})
}),
kernels: stateModule.makeKernelsRecord({
byRef: Immutable.Map({
fake: stateModule.makeRemoteKernelRecord({
channels: null,
status: "not connected"
})
})
})
})
})
};
const state$ = new StateObservable(new Subject(), state);
const action$ = of(
actions.sendExecuteRequest({ id: "first", contentRef: "fakeContent" })
);
let result = "";
sendExecuteRequestEpic(action$, state$).subscribe(
// Every action that goes through should get stuck on an array
(x: actions.ExecuteFailed) => {
result = x.payload.error.message;
done();
},
err => done.fail(err)
);
expect(result).toContain("Could not find the cell with the given CellId");
});
test("throws an error when cell is not a code cell", done => {
let notebook = monocellNotebook;
let cellId: string = monocellNotebook.cellOrder.first();
notebook = notebook.setIn(["cellMap", cellId, "cell_type"], "markdown");
const state = {
app: {},
core: stateModule.makeStateRecord({
kernelRef: "fake",
entities: stateModule.makeEntitiesRecord({
contents: stateModule.makeContentsRecord({
byRef: Immutable.Map({
fakeContent: stateModule.makeNotebookContentRecord({
model: stateModule.makeDocumentRecord({
notebook
})
})
})
}),
kernels: stateModule.makeKernelsRecord({
byRef: Immutable.Map({
fake: stateModule.makeRemoteKernelRecord({
channels: null,
status: "not connected"
})
})
})
})
})
};
const state$ = new StateObservable(new Subject(), state);
const action$ = of(
actions.sendExecuteRequest({ id: cellId, contentRef: "fakeContent" })
);
let result = "";
sendExecuteRequestEpic(action$, state$).subscribe(
// Every action that goes through should get stuck on an array
(x: actions.ExecuteCanceled) => {
result = x.payload.code;
done();
},
err => done.fail(err)
);
expect(result).toContain("EXEC_INVALID_CELL_TYPE");
});
test("throws an error when cell is empty", done => {
const notebook = monocellNotebook;
let cellId: string = monocellNotebook.cellOrder.first();
const state = {
app: {},
core: stateModule.makeStateRecord({
kernelRef: "fake",
entities: stateModule.makeEntitiesRecord({
contents: stateModule.makeContentsRecord({
byRef: Immutable.Map({
fakeContent: stateModule.makeNotebookContentRecord({
model: stateModule.makeDocumentRecord({
notebook
})
})
})
}),
kernels: stateModule.makeKernelsRecord({
byRef: Immutable.Map({
fake: stateModule.makeRemoteKernelRecord({
channels: null,
status: "not connected"
})
})
})
})
})
};
const state$ = new StateObservable(new Subject(), state);
const action$ = of(
actions.sendExecuteRequest({ id: cellId, contentRef: "fakeContent" })
);
let result = "";
sendExecuteRequestEpic(action$, state$).subscribe(
// Every action that goes through should get stuck on an array
(x: actions.ExecuteCanceled) => {
result = x.payload.code;
done();
},
err => done.fail(err)
);
expect(result).toContain("EXEC_NO_SOURCE_ERROR");
});
test("throws an error when kernel is not connected", done => {
let notebook = monocellNotebook;
let cellId: string = monocellNotebook.cellOrder.first();
notebook = notebook.setIn(["cellMap", cellId, "source"], "print('test')");
const state = {
app: {},
core: stateModule.makeStateRecord({
kernelRef: "fake",
entities: stateModule.makeEntitiesRecord({
contents: stateModule.makeContentsRecord({
byRef: Immutable.Map({
fakeContent: stateModule.makeNotebookContentRecord({
model: stateModule.makeDocumentRecord({
notebook
})
})
})
}),
kernels: stateModule.makeKernelsRecord({
byRef: Immutable.Map({
fake: stateModule.makeRemoteKernelRecord({
channels: null,
status: "not connected"
})
})
})
})
})
};
const state$ = new StateObservable(new Subject(), state);
const action$ = of(
actions.sendExecuteRequest({ id: cellId, contentRef: "fakeContent" })
);
let result = "";
sendExecuteRequestEpic(action$, state$).subscribe(
// Every action that goes through should get stuck on an array
(x: actions.ExecuteFailed) => {
result = x.payload.error.message;
done();
},
err => done.fail(err)
);
expect(result).toContain("There is no connected kernel for this content");
});
test("throws an error when kernel channels is malformed", done => {
let notebook = monocellNotebook;
let cellId: string = monocellNotebook.cellOrder.first();
notebook = notebook.setIn(["cellMap", cellId, "source"], "print('test')");
const state = {
app: {},
core: stateModule.makeStateRecord({
kernelRef: "fake",
entities: stateModule.makeEntitiesRecord({
contents: stateModule.makeContentsRecord({
byRef: Immutable.Map({
fakeContent: stateModule.makeNotebookContentRecord({
model: stateModule.makeDocumentRecord({
notebook,
kernelRef: "fake"
})
})
})
}),
kernels: stateModule.makeKernelsRecord({
byRef: Immutable.Map({
fake: stateModule.makeRemoteKernelRecord({
channels: null,
status: "idle"
})
})
})
})
})
};
const state$ = new StateObservable(new Subject(), state);
const action$ = of(
actions.sendExecuteRequest({ id: cellId, contentRef: "fakeContent" })
);
let result = "";
sendExecuteRequestEpic(action$, state$).subscribe(
// Every action that goes through should get stuck on an array
(x: actions.ExecuteFailed) => {
result = x.payload.error.message;
done();
},
err => done.fail(err)
);
expect(result).toContain(
"The WebSocket associated with the target kernel is in a bad state"
);
});
}); | the_stack |
import { VectorChainReader } from "@connext/vector-contracts";
import {
ChannelSigner,
createTestChannelUpdate,
expect,
getRandomChannelSigner,
createTestChannelState,
mkSig,
createTestFullHashlockTransferState,
createTestUpdateParams,
mkAddress,
createTestChannelStateWithSigners,
getTransferId,
generateMerkleTreeData,
getRandomBytes32,
} from "@connext/vector-utils";
import {
ChainError,
ChannelUpdate,
FullChannelState,
FullTransferState,
Result,
UpdateType,
Values,
UpdateParams,
IChannelSigner,
DEFAULT_CHANNEL_TIMEOUT,
DEFAULT_TRANSFER_TIMEOUT,
MAXIMUM_TRANSFER_TIMEOUT,
MINIMUM_TRANSFER_TIMEOUT,
MAXIMUM_CHANNEL_TIMEOUT,
jsonifyError,
IVectorChainReader,
} from "@connext/vector-types";
import Sinon from "sinon";
import { AddressZero } from "@ethersproject/constants";
import { OutboundChannelUpdateError, InboundChannelUpdateError, ValidationError } from "../errors";
import * as vectorUtils from "../utils";
import * as validation from "../validate";
import * as vectorUpdate from "../update";
describe("validateUpdateParams", () => {
// Test values
const [initiator, responder] = Array(2)
.fill(0)
.map((_) => getRandomChannelSigner());
const channelAddress = mkAddress("0xccc");
// Declare all mocks
let chainReader: Sinon.SinonStubbedInstance<VectorChainReader>;
// Create helpers to create valid contexts
const createValidSetupContext = () => {
const previousState = undefined;
const activeTransfers = [];
const initiatorIdentifier = initiator.publicIdentifier;
const params = createTestUpdateParams(UpdateType.setup, {
channelAddress,
details: { counterpartyIdentifier: responder.publicIdentifier, timeout: DEFAULT_CHANNEL_TIMEOUT.toString() },
});
return { previousState, activeTransfers, initiatorIdentifier, params };
};
const createValidDepositContext = () => {
const activeTransfers = [];
const initiatorIdentifier = initiator.publicIdentifier;
const previousState = createTestChannelStateWithSigners([initiator, responder], UpdateType.setup, {
channelAddress,
nonce: 1,
timeout: DEFAULT_CHANNEL_TIMEOUT.toString(),
});
const params = createTestUpdateParams(UpdateType.deposit, {
channelAddress,
details: {
assetId: AddressZero,
},
});
return { previousState, activeTransfers, initiatorIdentifier, params };
};
const createValidCreateContext = () => {
const activeTransfers = [];
const initiatorIdentifier = initiator.publicIdentifier;
const previousState = createTestChannelStateWithSigners([initiator, responder], UpdateType.deposit, {
channelAddress,
nonce: 4,
timeout: DEFAULT_CHANNEL_TIMEOUT.toString(),
balances: [
{ to: [initiator.address, responder.address], amount: ["7", "17"] },
{ to: [initiator.address, responder.address], amount: ["14", "12"] },
],
assetIds: [AddressZero, mkAddress("0xaaa")],
processedDepositsA: ["10", "6"],
processedDepositsB: ["14", "20"],
});
const transfer = createTestFullHashlockTransferState({
channelAddress,
initiator: initiator.address,
responder: responder.address,
transferTimeout: MINIMUM_TRANSFER_TIMEOUT.toString(),
transferDefinition: mkAddress("0xdef"),
assetId: AddressZero,
transferId: getTransferId(
channelAddress,
previousState.nonce.toString(),
mkAddress("0xdef"),
MINIMUM_TRANSFER_TIMEOUT.toString(),
),
balance: { to: [initiator.address, responder.address], amount: ["3", "0"] },
});
const params = createTestUpdateParams(UpdateType.create, {
channelAddress,
details: {
balance: { ...transfer.balance },
assetId: transfer.assetId,
transferDefinition: transfer.transferDefinition,
transferInitialState: { ...transfer.transferState },
timeout: transfer.transferTimeout,
},
});
return { previousState, activeTransfers, initiatorIdentifier, params, transfer };
};
const createValidResolveContext = () => {
const nonce = 4;
const transfer = createTestFullHashlockTransferState({
channelAddress,
initiator: initiator.address,
responder: responder.address,
transferTimeout: DEFAULT_TRANSFER_TIMEOUT.toString(),
transferDefinition: mkAddress("0xdef"),
assetId: AddressZero,
transferId: getTransferId(
channelAddress,
nonce.toString(),
mkAddress("0xdef"),
DEFAULT_TRANSFER_TIMEOUT.toString(),
),
balance: { to: [initiator.address, responder.address], amount: ["3", "0"] },
transferResolver: undefined,
});
const { root } = generateMerkleTreeData([transfer]);
const previousState = createTestChannelStateWithSigners([initiator, responder], UpdateType.deposit, {
channelAddress,
nonce,
timeout: DEFAULT_CHANNEL_TIMEOUT.toString(),
balances: [
{ to: [initiator.address, responder.address], amount: ["7", "17"] },
{ to: [initiator.address, responder.address], amount: ["14", "12"] },
],
assetIds: [AddressZero, mkAddress("0xaaa")],
processedDepositsA: ["10", "6"],
processedDepositsB: ["14", "20"],
merkleRoot: root,
});
const params = createTestUpdateParams(UpdateType.resolve, {
channelAddress,
details: { transferId: transfer.transferId, transferResolver: { preImage: getRandomBytes32() } },
});
return {
previousState,
activeTransfers: [transfer],
initiatorIdentifier: responder.publicIdentifier,
params,
transfer,
};
};
const callAndVerifyError = async (
signer: IChannelSigner,
params: UpdateParams<any>,
state: FullChannelState | undefined,
activeTransfers: FullTransferState[],
initiatorIdentifier: string,
message: Values<typeof ValidationError.reasons>,
context: any = {},
) => {
const result = await validation.validateUpdateParams(
signer,
chainReader as IVectorChainReader,
params,
state,
activeTransfers,
initiatorIdentifier,
);
const error = result.getError();
expect(error).to.be.ok;
expect(error).to.be.instanceOf(ValidationError);
expect(error?.message).to.be.eq(message);
expect(error?.context).to.containSubset(context ?? {});
expect(error?.context.state).to.be.deep.eq(state);
expect(error?.context.params).to.be.deep.eq(params);
};
beforeEach(() => {
// Set mocks (default to no error)
chainReader = Sinon.createStubInstance(VectorChainReader);
chainReader.getChannelAddress.resolves(Result.ok(channelAddress));
chainReader.create.resolves(Result.ok(true));
});
afterEach(() => {
Sinon.restore();
});
it("should fail if no previous state and is not a setup update", async () => {
const { activeTransfers, initiatorIdentifier, params } = createValidDepositContext();
await callAndVerifyError(
initiator,
params,
undefined,
activeTransfers,
initiatorIdentifier,
ValidationError.reasons.ChannelNotFound,
);
});
it("should fail if previous state is in dispute", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params } = createValidDepositContext();
previousState.inDispute = true;
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiatorIdentifier,
ValidationError.reasons.InDispute,
);
});
it("should fail if params.channelAddress !== previousState.channelAddress", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params } = createValidDepositContext();
previousState.channelAddress = mkAddress("0xddddcccc33334444");
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiatorIdentifier,
ValidationError.reasons.InvalidChannelAddress,
);
});
it("should fail if defundNonces.length !== assetIds.length", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params } = createValidDepositContext();
previousState.defundNonces = [...previousState.defundNonces, "1"];
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiatorIdentifier,
ValidationError.reasons.InvalidArrayLength,
);
});
it("should fail if balances.length !== assetIds.length", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params } = createValidDepositContext();
previousState.balances = [];
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiatorIdentifier,
ValidationError.reasons.InvalidArrayLength,
);
});
it("should fail if processedDepositsA.length !== assetIds.length", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params } = createValidDepositContext();
previousState.processedDepositsA = [...previousState.processedDepositsA, "1"];
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiatorIdentifier,
ValidationError.reasons.InvalidArrayLength,
);
});
it("should fail if defundNonces.processedDepositsB !== assetIds.length", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params } = createValidDepositContext();
previousState.processedDepositsB = [...previousState.processedDepositsB, "1"];
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiatorIdentifier,
ValidationError.reasons.InvalidArrayLength,
);
});
describe("setup params", () => {
it("should work for the initiator", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params } = createValidSetupContext();
const result = await validation.validateUpdateParams(
initiator,
chainReader as IVectorChainReader,
params,
previousState,
activeTransfers,
initiatorIdentifier,
);
expect(result.getError()).to.be.undefined;
expect(chainReader.getChannelAddress.callCount).to.be.eq(1);
});
it("should work for the responder", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params } = createValidSetupContext();
const result = await validation.validateUpdateParams(
responder,
chainReader as IVectorChainReader,
params,
previousState,
activeTransfers,
initiatorIdentifier,
);
expect(result.getError()).to.be.undefined;
expect(chainReader.getChannelAddress.callCount).to.be.eq(1);
});
it("should fail if there is a previous state", async () => {
const { activeTransfers, initiatorIdentifier, params } = createValidSetupContext();
await callAndVerifyError(
initiator,
params,
createTestChannelState(UpdateType.setup).channel,
activeTransfers,
initiatorIdentifier,
ValidationError.reasons.ChannelAlreadySetup,
);
});
it("should fail if chainReader.getChannelAddress fails", async () => {
const { activeTransfers, initiatorIdentifier, params, previousState } = createValidSetupContext();
const chainErr = new ChainError("fail");
chainReader.getChannelAddress.resolves(Result.fail(chainErr));
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiatorIdentifier,
ValidationError.reasons.ChainServiceFailure,
{ chainServiceMethod: "getChannelAddress", chainServiceError: jsonifyError(chainErr) },
);
});
it("should fail if channelAddress is miscalculated", async () => {
const { activeTransfers, initiatorIdentifier, params, previousState } = createValidSetupContext();
chainReader.getChannelAddress.resolves(Result.ok(mkAddress("0x55555")));
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiatorIdentifier,
ValidationError.reasons.InvalidChannelAddress,
);
});
it("should fail if timeout is below min", async () => {
const { activeTransfers, initiatorIdentifier, params, previousState } = createValidSetupContext();
params.details.timeout = "1";
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiatorIdentifier,
ValidationError.reasons.ShortChannelTimeout,
);
});
it("should fail if timeout is above max", async () => {
const { activeTransfers, initiatorIdentifier, params, previousState } = createValidSetupContext();
params.details.timeout = "10000000000000000000";
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiatorIdentifier,
ValidationError.reasons.LongChannelTimeout,
);
});
it("should fail if counterparty === initiator", async () => {
const { activeTransfers, initiatorIdentifier, params, previousState } = createValidSetupContext();
params.details.counterpartyIdentifier = initiatorIdentifier;
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiatorIdentifier,
ValidationError.reasons.InvalidCounterparty,
);
});
});
describe("deposit params", () => {
it("should work for initiator", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params } = createValidDepositContext();
const result = await validation.validateUpdateParams(
initiator,
chainReader as IVectorChainReader,
params,
previousState,
activeTransfers,
initiatorIdentifier,
);
expect(result.getError()).to.be.undefined;
});
it("should work for responder", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params } = createValidDepositContext();
const result = await validation.validateUpdateParams(
responder,
chainReader as IVectorChainReader,
params,
previousState,
activeTransfers,
initiatorIdentifier,
);
expect(result.getError()).to.be.undefined;
});
it("should fail if it is an invalid assetId", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params } = createValidDepositContext();
params.details.assetId = "fail";
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiatorIdentifier,
ValidationError.reasons.InvalidAssetId,
);
});
});
describe("create params", () => {
it("should work for initiator", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params } = createValidCreateContext();
const result = await validation.validateUpdateParams(
initiator,
chainReader as IVectorChainReader,
params,
previousState,
activeTransfers,
initiatorIdentifier,
);
expect(result.getError()).to.be.undefined;
expect(chainReader.create.callCount).to.be.eq(1);
});
it("should work for responder", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params } = createValidCreateContext();
const result = await validation.validateUpdateParams(
responder,
chainReader as IVectorChainReader,
params,
previousState,
activeTransfers,
initiatorIdentifier,
);
expect(result.getError()).to.be.undefined;
expect(chainReader.create.callCount).to.be.eq(1);
});
it("should fail if assetId is not in channel", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params } = createValidCreateContext();
params.details.assetId = mkAddress("0xddddd555555");
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiatorIdentifier,
ValidationError.reasons.AssetNotFound,
);
});
it("should fail if transfer with that id is already active", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params, transfer } = createValidCreateContext();
await callAndVerifyError(
initiator,
params,
previousState,
[...activeTransfers, transfer],
initiatorIdentifier,
ValidationError.reasons.DuplicateTransferId,
);
});
it("should fail if initiator calling, initiator out of funds", async () => {
const { previousState, activeTransfers, params } = createValidCreateContext();
previousState.balances[0] = { to: [initiator.address, responder.address], amount: ["5", "3"] };
params.details.assetId = previousState.assetIds[0];
params.details.balance = { to: [initiator.address, responder.address], amount: ["7", "1"] };
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiator.publicIdentifier,
ValidationError.reasons.InsufficientFunds,
);
});
it("should fail if initiator calling, responder out of funds", async () => {
const { previousState, activeTransfers, params } = createValidCreateContext();
previousState.balances[0] = { to: [initiator.address, responder.address], amount: ["15", "3"] };
params.details.assetId = previousState.assetIds[0];
params.details.balance = { to: [initiator.address, responder.address], amount: ["7", "7"] };
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiator.publicIdentifier,
ValidationError.reasons.InsufficientFunds,
);
});
it("should fail if responder calling, initiator out of funds", async () => {
const { previousState, activeTransfers, params } = createValidCreateContext();
previousState.balances[0] = { to: [initiator.address, responder.address], amount: ["5", "3"] };
params.details.assetId = previousState.assetIds[0];
params.details.balance = { to: [initiator.address, responder.address], amount: ["7", "2"] };
await callAndVerifyError(
responder,
params,
previousState,
activeTransfers,
initiator.publicIdentifier,
ValidationError.reasons.InsufficientFunds,
);
});
it("should fail if responder calling, responder out of funds", async () => {
const { previousState, activeTransfers, params } = createValidCreateContext();
previousState.balances[0] = { to: [initiator.address, responder.address], amount: ["15", "3"] };
params.details.assetId = previousState.assetIds[0];
params.details.balance = { to: [initiator.address, responder.address], amount: ["7", "12"] };
await callAndVerifyError(
responder,
params,
previousState,
activeTransfers,
initiator.publicIdentifier,
ValidationError.reasons.InsufficientFunds,
);
});
it("should fail if timeout is below min", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params } = createValidCreateContext();
params.details.timeout = "1";
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiatorIdentifier,
ValidationError.reasons.TransferTimeoutBelowMin,
);
});
it("should fail if timeout is above max", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params } = createValidCreateContext();
previousState.timeout = MAXIMUM_CHANNEL_TIMEOUT.toString();
params.details.timeout = (MAXIMUM_TRANSFER_TIMEOUT + 10).toString();
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiatorIdentifier,
ValidationError.reasons.TransferTimeoutAboveMax,
);
});
it("should fail if timeout equal to channel timeout", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params } = createValidCreateContext();
params.details.timeout = previousState.timeout;
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiatorIdentifier,
ValidationError.reasons.TransferTimeoutAboveChannel,
);
});
it("should fail if timeout greater than channel timeout", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params } = createValidCreateContext();
params.details.timeout = (parseInt(previousState.timeout) + 1).toString();
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiatorIdentifier,
ValidationError.reasons.TransferTimeoutAboveChannel,
);
});
it("should fail if chainReader.create fails", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params } = createValidCreateContext();
const chainErr = new ChainError("fail");
chainReader.create.resolves(Result.fail(chainErr));
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiatorIdentifier,
ValidationError.reasons.ChainServiceFailure,
{ chainServiceMethod: "create", chainServiceError: jsonifyError(chainErr) },
);
});
it("should fail if chainReader.create returns false", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params } = createValidCreateContext();
chainReader.create.resolves(Result.ok(false));
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiatorIdentifier,
ValidationError.reasons.InvalidInitialState,
);
});
});
describe("resolve params", () => {
it("should work for initiator", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params } = createValidResolveContext();
const result = await validation.validateUpdateParams(
initiator,
chainReader as IVectorChainReader,
params,
previousState,
activeTransfers,
initiatorIdentifier,
);
expect(result.getError()).to.be.undefined;
});
it("should work for responder", async () => {
const { previousState, activeTransfers, initiatorIdentifier, params } = createValidResolveContext();
const result = await validation.validateUpdateParams(
responder,
chainReader as IVectorChainReader,
params,
previousState,
activeTransfers,
initiatorIdentifier,
);
expect(result.getError()).to.be.undefined;
});
it("should fail if transfer is not active", async () => {
const { previousState, initiatorIdentifier, params } = createValidResolveContext();
await callAndVerifyError(
initiator,
params,
previousState,
[],
initiatorIdentifier,
ValidationError.reasons.TransferNotActive,
);
});
it("should fail if transferResolver is not an object", async () => {
const { previousState, initiatorIdentifier, params, activeTransfers } = createValidResolveContext();
params.details.transferResolver = "fail";
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiatorIdentifier,
ValidationError.reasons.InvalidResolver,
);
});
it("should fail if initiator is transfer responder", async () => {
const { previousState, params, activeTransfers } = createValidResolveContext();
await callAndVerifyError(
initiator,
params,
previousState,
activeTransfers,
initiator.publicIdentifier,
ValidationError.reasons.OnlyResponderCanInitiateResolve,
);
});
it("should fail if the transfer has an associated resolver", async () => {
const { previousState, initiatorIdentifier, params, transfer } = createValidResolveContext();
transfer.transferResolver = { preImage: getRandomBytes32() };
await callAndVerifyError(
initiator,
params,
previousState,
[transfer],
initiatorIdentifier,
ValidationError.reasons.TransferResolved,
);
});
});
});
// TODO: validUpdateParamsStub is not working #441
describe.skip("validateParamsAndApplyUpdate", () => {
// Test values
const signer = getRandomChannelSigner();
const params = createTestUpdateParams(UpdateType.create);
const previousState = createTestChannelState(UpdateType.deposit).channel;
const activeTransfers = [];
// Declare all mocks
let chainReader: Sinon.SinonStubbedInstance<VectorChainReader>;
let externalValidationStub: {
validateInbound: Sinon.SinonStub;
validateOutbound: Sinon.SinonStub;
};
let validateUpdateParamsStub: Sinon.SinonStub;
let generateAndApplyUpdateStub: Sinon.SinonStub;
beforeEach(() => {
// Set mocks
chainReader = Sinon.createStubInstance(VectorChainReader);
externalValidationStub = {
validateInbound: Sinon.stub().resolves(Result.ok(undefined)),
validateOutbound: Sinon.stub().resolves(Result.ok(undefined)),
};
validateUpdateParamsStub = Sinon.stub(validation, "validateUpdateParams");
generateAndApplyUpdateStub = Sinon.stub(vectorUpdate, "generateAndApplyUpdate");
});
afterEach(() => {
Sinon.restore();
});
it("should fail if validateUpdateParams fails", async () => {
validateUpdateParamsStub.resolves(Result.fail(new Error("fail")));
const result = await validation.validateParamsAndApplyUpdate(
signer,
chainReader as IVectorChainReader,
externalValidationStub,
params,
previousState,
activeTransfers,
signer.publicIdentifier,
);
expect(result.getError()?.message).to.be.eq(OutboundChannelUpdateError.reasons.OutboundValidationFailed);
expect(result.getError()?.context.params).to.be.deep.eq(params);
expect(result.getError()?.context.state).to.be.deep.eq(previousState);
expect(result.getError()?.context.error).to.be.eq("fail");
expect(result.isError).to.be.true;
});
it("should work", async () => {
generateAndApplyUpdateStub.resolves(Result.ok("pass"));
validateUpdateParamsStub.resolves(Result.ok(undefined));
const result = await validation.validateParamsAndApplyUpdate(
signer,
chainReader as IVectorChainReader,
externalValidationStub,
params,
previousState,
activeTransfers,
signer.publicIdentifier,
);
expect(result.getError()).to.be.undefined;
expect(result.isError).to.be.false;
expect(result.getValue()).to.be.eq("pass");
});
});
describe("validateAndApplyInboundUpdate", () => {
// Test values
let signers: ChannelSigner[];
let previousState: FullChannelState;
let update: ChannelUpdate;
let activeTransfers: FullTransferState[];
const aliceSignature = mkSig("0x11");
const bobSignature = mkSig("0x22");
// Declare all mocks
let chainReader: Sinon.SinonStubbedInstance<VectorChainReader>;
let validateParamsAndApplyUpdateStub: Sinon.SinonStub;
let validateChannelUpdateSignaturesStub: Sinon.SinonStub;
let generateSignedChannelCommitmentStub: Sinon.SinonStub;
let applyUpdateStub: Sinon.SinonStub;
let externalValidationStub: {
validateInbound: Sinon.SinonStub;
validateOutbound: Sinon.SinonStub;
};
// Create helper to run test
const runErrorTest = async (
errorMessage: Values<typeof InboundChannelUpdateError.reasons>,
signer: ChannelSigner = signers[0],
context: any = {},
) => {
const result = await validation.validateAndApplyInboundUpdate(
chainReader as IVectorChainReader,
externalValidationStub,
signer,
update,
previousState,
activeTransfers ?? [],
);
const error = result.getError();
expect(error).to.be.ok;
expect(result.isError).to.be.true;
expect(error?.message).to.be.eq(errorMessage);
expect(error?.context.state).to.be.deep.eq(previousState);
expect(error?.context ?? {}).to.containSubset(context);
return;
};
// Create helper to generate successful env for mocks
// (can be overridden in individual tests)
const prepEnv = () => {
const updatedChannel = createTestChannelState(UpdateType.setup).channel;
const updatedActiveTransfers = undefined;
const updatedTransfer = undefined;
// Need for double signed and single signed
validateChannelUpdateSignaturesStub.resolves(Result.ok(undefined));
// Needed for double signed
chainReader.resolve.resolves(Result.ok({ to: [updatedChannel.alice, updatedChannel.bob], amount: ["10", "2"] }));
applyUpdateStub.returns(
Result.ok({
updatedActiveTransfers,
updatedTransfer,
updatedChannel,
}),
);
// Needed for single signed
externalValidationStub.validateInbound.resolves(Result.ok(undefined));
validateParamsAndApplyUpdateStub.resolves(Result.ok({ updatedChannel, updatedActiveTransfers, updatedTransfer }));
generateSignedChannelCommitmentStub.resolves(Result.ok({ aliceSignature, bobSignature }));
return { aliceSignature, bobSignature, updatedChannel, updatedTransfer, updatedActiveTransfers };
};
beforeEach(() => {
// Set test values
signers = Array(2)
.fill(0)
.map((_) => getRandomChannelSigner());
// Set mocks
chainReader = Sinon.createStubInstance(VectorChainReader);
validateParamsAndApplyUpdateStub = Sinon.stub(validation, "validateParamsAndApplyUpdate");
validateChannelUpdateSignaturesStub = Sinon.stub(vectorUtils, "validateChannelSignatures").resolves(
Result.ok(undefined),
);
generateSignedChannelCommitmentStub = Sinon.stub(vectorUtils, "generateSignedChannelCommitment");
applyUpdateStub = Sinon.stub(vectorUpdate, "applyUpdate");
externalValidationStub = {
validateInbound: Sinon.stub().resolves(Result.ok(undefined)),
validateOutbound: Sinon.stub().resolves(Result.ok(undefined)),
};
});
afterEach(() => {
Sinon.restore();
});
describe("should properly validate update schema", () => {
describe("should fail if update is malformed", () => {
const valid = createTestChannelUpdate(UpdateType.setup);
const tests = [
{
name: "no channelAddress",
overrides: { channelAddress: undefined },
error: "should have required property 'channelAddress'",
},
{
name: "malformed channelAddress",
overrides: { channelAddress: "fail" },
error: 'should match pattern "^0x[a-fA-F0-9]{40}$"',
},
{
name: "no fromIdentifier",
overrides: { fromIdentifier: undefined },
error: "should have required property 'fromIdentifier'",
},
{
name: "malformed fromIdentifier",
overrides: { fromIdentifier: "fail" },
error: 'should match pattern "^vector([a-zA-Z0-9]{50})$"',
},
{
name: "no toIdentifier",
overrides: { toIdentifier: undefined },
error: "should have required property 'toIdentifier'",
},
{
name: "malformed toIdentifier",
overrides: { toIdentifier: "fail" },
error: 'should match pattern "^vector([a-zA-Z0-9]{50})$"',
},
{
name: "no type",
overrides: { type: undefined },
error: "should have required property 'type'",
},
{
name: "malformed type",
overrides: { type: "fail" },
error:
"should be equal to one of the allowed values,should be equal to one of the allowed values,should be equal to one of the allowed values,should be equal to one of the allowed values,should match some schema in anyOf",
},
{
name: "no nonce",
overrides: { nonce: undefined },
error: "should have required property 'nonce'",
},
{
name: "malformed nonce",
overrides: { nonce: "fail" },
error: "should be number",
},
{
name: "no balance",
overrides: { balance: undefined },
error: "should have required property 'balance'",
},
{
name: "malformed balance",
overrides: { balance: "fail" },
error: "should be object",
},
{
name: "no assetId",
overrides: { assetId: undefined },
error: "should have required property 'assetId'",
},
{
name: "malformed assetId",
overrides: { assetId: "fail" },
error: 'should match pattern "^0x[a-fA-F0-9]{40}$"',
},
{
name: "no details",
overrides: { details: undefined },
error: "should have required property 'details'",
},
{
name: "malformed aliceSignature",
overrides: { aliceSignature: "fail" },
error: 'should match pattern "^0x([a-fA-F0-9]{130})$",should be null,should match some schema in anyOf',
},
{
name: "malformed bobSignature",
overrides: { bobSignature: "fail" },
error: 'should match pattern "^0x([a-fA-F0-9]{130})$",should be null,should match some schema in anyOf',
},
];
for (const test of tests) {
it(test.name, async () => {
update = { ...valid, ...(test.overrides ?? {}) } as any;
await runErrorTest(InboundChannelUpdateError.reasons.MalformedUpdate, signers[0], {
updateError: test.error,
});
});
}
});
describe("should fail if setup update details are malformed", () => {
const valid = createTestChannelUpdate(UpdateType.setup);
const tests = [
{
name: "no timeout",
overrides: { timeout: undefined },
error: "should have required property 'timeout'",
},
{
name: "invalid timeout",
overrides: { timeout: "fail" },
error: 'should match pattern "^([0-9])*$"',
},
{
name: "no networkContext",
overrides: { networkContext: undefined },
error: "should have required property 'networkContext'",
},
{
name: "no networkContext.chainId",
overrides: { networkContext: { ...valid.details.networkContext, chainId: undefined } },
error: "should have required property 'chainId'",
},
{
name: "invalid networkContext.chainId",
overrides: { networkContext: { ...valid.details.networkContext, chainId: "fail" } },
error: "should be number",
},
{
name: "no networkContext.channelFactoryAddress",
overrides: { networkContext: { ...valid.details.networkContext, channelFactoryAddress: undefined } },
error: "should have required property 'channelFactoryAddress'",
},
{
name: "invalid networkContext.channelFactoryAddress",
overrides: { networkContext: { ...valid.details.networkContext, channelFactoryAddress: "fail" } },
error: 'should match pattern "^0x[a-fA-F0-9]{40}$"',
},
{
name: "no networkContext.transferRegistryAddress",
overrides: { networkContext: { ...valid.details.networkContext, transferRegistryAddress: undefined } },
error: "should have required property 'transferRegistryAddress'",
},
{
name: "invalid networkContext.transferRegistryAddress",
overrides: { networkContext: { ...valid.details.networkContext, transferRegistryAddress: "fail" } },
error: 'should match pattern "^0x[a-fA-F0-9]{40}$"',
},
];
for (const test of tests) {
it(test.name, async () => {
update = {
...valid,
details: {
...valid.details,
...test.overrides,
},
};
await runErrorTest(InboundChannelUpdateError.reasons.MalformedDetails, signers[0], {
detailsError: test.error,
});
});
}
});
describe("should fail if deposit update details are malformed", () => {
const valid = createTestChannelUpdate(UpdateType.deposit);
const tests = [
{
name: "no totalDepositsAlice",
overrides: { totalDepositsAlice: undefined },
error: "should have required property 'totalDepositsAlice'",
},
{
name: "malformed totalDepositsAlice",
overrides: { totalDepositsAlice: "fail" },
error: 'should match pattern "^([0-9])*$"',
},
{
name: "no totalDepositsBob",
overrides: { totalDepositsBob: undefined },
error: "should have required property 'totalDepositsBob'",
},
{
name: "malformed totalDepositsBob",
overrides: { totalDepositsBob: "fail" },
error: 'should match pattern "^([0-9])*$"',
},
];
for (const test of tests) {
it(test.name, async () => {
update = {
...valid,
details: {
...valid.details,
...test.overrides,
},
};
await runErrorTest(InboundChannelUpdateError.reasons.MalformedDetails, signers[0], {
detailsError: test.error,
});
});
}
});
describe("should fail if create update details are malformed", () => {
const valid = createTestChannelUpdate(UpdateType.create);
const tests = [
{
name: "no transferId",
overrides: { transferId: undefined },
error: "should have required property 'transferId'",
},
{
name: "malformed transferId",
overrides: { transferId: "fail" },
error: 'should match pattern "^0x([a-fA-F0-9]{64})$"',
},
{
name: "no balance",
overrides: { balance: undefined },
error: "should have required property 'balance'",
},
{
name: "malformed balance",
overrides: { balance: "fail" },
error: "should be object",
},
{
name: "no transferDefinition",
overrides: { transferDefinition: undefined },
error: "should have required property 'transferDefinition'",
},
{
name: "malformed transferDefinition",
overrides: { transferDefinition: "fail" },
error: 'should match pattern "^0x[a-fA-F0-9]{40}$"',
},
{
name: "no transferTimeout",
overrides: { transferTimeout: undefined },
error: "should have required property 'transferTimeout'",
},
{
name: "malformed transferTimeout",
overrides: { transferTimeout: "fail" },
error: 'should match pattern "^([0-9])*$"',
},
{
name: "no transferInitialState",
overrides: { transferInitialState: undefined },
error: "should have required property 'transferInitialState'",
},
{
name: "malformed transferInitialState",
overrides: { transferInitialState: "fail" },
error: "should be object",
},
{
name: "no transferEncodings",
overrides: { transferEncodings: undefined },
error: "should have required property 'transferEncodings'",
},
{
name: "malformed transferEncodings",
overrides: { transferEncodings: "fail" },
error: "should be array",
},
{
name: "no merkleProofData",
overrides: { merkleProofData: undefined },
error: "should have required property 'merkleProofData'",
},
{
name: "malformed merkleProofData",
overrides: { merkleProofData: "fail" },
error: "should be array",
},
{
name: "no merkleRoot",
overrides: { merkleRoot: undefined },
error: "should have required property 'merkleRoot'",
},
{
name: "malformed merkleRoot",
overrides: { merkleRoot: "fail" },
error: 'should match pattern "^0x([a-fA-F0-9]{64})$"',
},
{
name: "malformed meta",
overrides: { meta: "fail" },
error: "should be object",
},
];
for (const test of tests) {
it(test.name, async () => {
update = {
...valid,
details: {
...valid.details,
...test.overrides,
},
};
await runErrorTest(InboundChannelUpdateError.reasons.MalformedDetails, signers[0], {
detailsError: test.error,
});
});
}
});
describe("should fail if resolve update details are malformed", () => {
const valid = createTestChannelUpdate(UpdateType.resolve);
const tests = [
{
name: "no transferId",
overrides: { transferId: undefined },
error: "should have required property 'transferId'",
},
{
name: "malformed transferId",
overrides: { transferId: "fail" },
error: 'should match pattern "^0x([a-fA-F0-9]{64})$"',
},
{
name: "no transferDefinition",
overrides: { transferDefinition: undefined },
error: "should have required property 'transferDefinition'",
},
{
name: "malformed transferDefinition",
overrides: { transferDefinition: "fail" },
error: 'should match pattern "^0x[a-fA-F0-9]{40}$"',
},
{
name: "no transferResolver",
overrides: { transferResolver: undefined },
error: "should have required property '.transferResolver'",
},
// {
// name: "malformed transferResolver",
// overrides: { transferResolver: "fail" },
// error: "should be object",
// },
{
name: "no merkleRoot",
overrides: { merkleRoot: undefined },
error: "should have required property 'merkleRoot'",
},
{
name: "malformed merkleRoot",
overrides: { merkleRoot: "fail" },
error: 'should match pattern "^0x([a-fA-F0-9]{64})$"',
},
{
name: "malformed meta",
overrides: { meta: "fail" },
error: "should be object",
},
];
for (const test of tests) {
it(test.name, async () => {
update = {
...valid,
details: {
...valid.details,
...test.overrides,
},
};
await runErrorTest(InboundChannelUpdateError.reasons.MalformedDetails, signers[0], {
detailsError: test.error,
});
});
}
});
});
describe("should handle double signed update", () => {
const updateNonce = 3;
beforeEach(() => {
previousState = createTestChannelState(UpdateType.deposit, { nonce: 2 }).channel;
});
it("should work without hitting validation for UpdateType.resolve", async () => {
const { updatedActiveTransfers, updatedChannel, updatedTransfer } = prepEnv();
update = createTestChannelUpdate(UpdateType.resolve, {
aliceSignature: mkSig("0xaaa"),
bobSignature: mkSig("0xbbb"),
nonce: updateNonce,
});
// Run test
const result = await validation.validateAndApplyInboundUpdate(
chainReader as IVectorChainReader,
externalValidationStub,
signers[0],
update,
previousState,
[createTestFullHashlockTransferState({ transferId: update.details.transferId })],
);
expect(result.isError).to.be.false;
const returned = result.getValue();
expect(returned).to.containSubset({
updatedChannel: {
...updatedChannel,
latestUpdate: {
...updatedChannel.latestUpdate,
aliceSignature: update.aliceSignature,
bobSignature: update.bobSignature,
},
},
updatedActiveTransfers,
updatedTransfer,
});
// Verify call stack
expect(applyUpdateStub.callCount).to.be.eq(1);
expect(chainReader.resolve.callCount).to.be.eq(1);
expect(validateChannelUpdateSignaturesStub.callCount).to.be.eq(1);
expect(validateParamsAndApplyUpdateStub.callCount).to.be.eq(0);
expect(generateSignedChannelCommitmentStub.callCount).to.be.eq(0);
expect(externalValidationStub.validateInbound.callCount).to.be.eq(0);
});
it("should work without hitting validation for all other update types", async () => {
const { updatedActiveTransfers, updatedChannel, updatedTransfer } = prepEnv();
update = createTestChannelUpdate(UpdateType.create, {
aliceSignature: mkSig("0xaaa"),
bobSignature: mkSig("0xbbb"),
nonce: updateNonce,
});
// Run test
const result = await validation.validateAndApplyInboundUpdate(
chainReader as IVectorChainReader,
externalValidationStub,
signers[0],
update,
previousState,
[],
);
expect(result.isError).to.be.false;
const returned = result.getValue();
expect(returned).to.containSubset({
updatedChannel: {
...updatedChannel,
latestUpdate: {
...updatedChannel.latestUpdate,
aliceSignature: update.aliceSignature,
bobSignature: update.bobSignature,
},
},
updatedActiveTransfers,
updatedTransfer,
});
// Verify call stack
expect(applyUpdateStub.callCount).to.be.eq(1);
expect(validateChannelUpdateSignaturesStub.callCount).to.be.eq(1);
expect(chainReader.resolve.callCount).to.be.eq(0);
expect(validateParamsAndApplyUpdateStub.callCount).to.be.eq(0);
expect(generateSignedChannelCommitmentStub.callCount).to.be.eq(0);
expect(externalValidationStub.validateInbound.callCount).to.be.eq(0);
});
it("should fail if chainReader.resolve fails", async () => {
prepEnv();
// Set failing stub
const chainErr = new ChainError("fail");
chainReader.resolve.resolves(Result.fail(chainErr));
// Create update
update = createTestChannelUpdate(UpdateType.resolve, { aliceSignature, bobSignature, nonce: updateNonce });
activeTransfers = [createTestFullHashlockTransferState({ transferId: update.details.transferId })];
await runErrorTest(InboundChannelUpdateError.reasons.CouldNotGetFinalBalance, undefined, {
chainServiceError: jsonifyError(chainErr),
});
});
it("should fail if transfer is inactive", async () => {
prepEnv();
// Create update
update = createTestChannelUpdate(UpdateType.resolve, { aliceSignature, bobSignature, nonce: updateNonce });
activeTransfers = [];
await runErrorTest(InboundChannelUpdateError.reasons.TransferNotActive, signers[0], { existing: [] });
});
it("should fail if applyUpdate fails", async () => {
prepEnv();
// Set failing stub
const err = new ChainError("fail");
applyUpdateStub.returns(Result.fail(err));
// Create update
update = createTestChannelUpdate(UpdateType.setup, { aliceSignature, bobSignature, nonce: updateNonce });
activeTransfers = [];
await runErrorTest(InboundChannelUpdateError.reasons.ApplyUpdateFailed, signers[0], {
applyUpdateError: err.message,
applyUpdateContext: err.context,
});
});
it("should fail if validateChannelUpdateSignatures fails", async () => {
prepEnv();
// Set failing stub
validateChannelUpdateSignaturesStub.resolves(Result.fail(new Error("fail")));
// Create update
update = createTestChannelUpdate(UpdateType.setup, { aliceSignature, bobSignature, nonce: updateNonce });
activeTransfers = [];
await runErrorTest(InboundChannelUpdateError.reasons.BadSignatures, signers[0], {
validateSignatureError: "fail",
});
});
});
it("should fail if update.nonce is not exactly one greater than previous", async () => {
// Set a passing mocked env
prepEnv();
update = createTestChannelUpdate(UpdateType.setup, { nonce: 2 });
await runErrorTest(InboundChannelUpdateError.reasons.InvalidUpdateNonce, signers[0]);
});
it("should fail if externalValidation.validateInbound fails", async () => {
// Set a passing mocked env
prepEnv();
externalValidationStub.validateInbound.resolves(Result.fail(new Error("fail")));
update = createTestChannelUpdate(UpdateType.setup, { nonce: 1, aliceSignature: undefined });
await runErrorTest(InboundChannelUpdateError.reasons.ExternalValidationFailed, signers[0], {
externalValidationError: "fail",
});
});
it("should fail if validateParamsAndApplyUpdate fails", async () => {
// Set a passing mocked env
prepEnv();
validateParamsAndApplyUpdateStub.resolves(Result.fail(new ChainError("fail")));
update = createTestChannelUpdate(UpdateType.setup, { nonce: 1, aliceSignature: undefined });
await runErrorTest(InboundChannelUpdateError.reasons.ApplyAndValidateInboundFailed, signers[0], {
validationError: "fail",
validationContext: {},
});
});
it("should fail if single signed + invalid sig", async () => {
// Set a passing mocked env
prepEnv();
validateChannelUpdateSignaturesStub.resolves(Result.fail(new Error("fail")));
update = createTestChannelUpdate(UpdateType.setup, { nonce: 1, aliceSignature: undefined });
await runErrorTest(InboundChannelUpdateError.reasons.BadSignatures, signers[0], { signatureError: "fail" });
});
it("should fail if generateSignedChannelCommitment fails", async () => {
// Set a passing mocked env
prepEnv();
generateSignedChannelCommitmentStub.resolves(Result.fail(new Error("fail")));
update = createTestChannelUpdate(UpdateType.setup, { nonce: 1, aliceSignature: undefined });
await runErrorTest(InboundChannelUpdateError.reasons.GenerateSignatureFailed, signers[0], {
signatureError: "fail",
});
});
it("should work for a single signed update", async () => {
// Set a passing mocked env
const { updatedActiveTransfers, updatedChannel, updatedTransfer, aliceSignature, bobSignature } = prepEnv();
update = createTestChannelUpdate(UpdateType.setup, { nonce: 1, aliceSignature: undefined });
const result = await validation.validateAndApplyInboundUpdate(
chainReader as IVectorChainReader,
externalValidationStub,
signers[0],
update,
previousState,
activeTransfers ?? [],
);
expect(result.isError).to.be.false;
const returned = result.getValue();
expect(returned).to.containSubset({
updatedChannel: {
...updatedChannel,
latestUpdate: { ...updatedChannel.latestUpdate, aliceSignature, bobSignature },
},
updatedActiveTransfers,
updatedTransfer,
});
// Verify call stack
expect(validateParamsAndApplyUpdateStub.callCount).to.be.eq(1);
expect(validateChannelUpdateSignaturesStub.callCount).to.be.eq(1);
expect(generateSignedChannelCommitmentStub.callCount).to.be.eq(1);
expect(externalValidationStub.validateInbound.callCount).to.be.eq(1);
expect(applyUpdateStub.callCount).to.be.eq(0);
expect(chainReader.resolve.callCount).to.be.eq(0);
});
}); | the_stack |
import { Injectable } from '@angular/core';
import { CoreSites, CoreSitesCommonWSOptions, CoreSitesReadingStrategy } from '@services/sites';
import { CoreWSExternalWarning, CoreWSExternalFile, CoreWSFile } from '@services/ws';
import { CoreTimeUtils } from '@services/utils/time';
import { CoreUtils } from '@services/utils/utils';
import { CoreSite, CoreSiteWSPreSets } from '@classes/site';
import { CoreCourseLogHelper } from '@features/course/services/log-helper';
import { CoreH5P } from '@features/h5p/services/h5p';
import { CoreH5PDisplayOptions } from '@features/h5p/classes/core';
import { CoreCourseCommonModWSOptions } from '@features/course/services/course';
import { makeSingleton, Translate } from '@singletons/index';
import { CoreWSError } from '@classes/errors/wserror';
import { CoreError } from '@classes/errors/error';
import { AddonModH5PActivityAutoSyncData, AddonModH5PActivitySyncProvider } from './h5pactivity-sync';
const ROOT_CACHE_KEY = 'mmaModH5PActivity:';
/**
* Service that provides some features for H5P activity.
*/
@Injectable({ providedIn: 'root' })
export class AddonModH5PActivityProvider {
static readonly COMPONENT = 'mmaModH5PActivity';
static readonly TRACK_COMPONENT = 'mod_h5pactivity'; // Component for tracking.
/**
* Format an attempt's data.
*
* @param attempt Attempt to format.
* @return Formatted attempt.
*/
protected formatAttempt(attempt: AddonModH5PActivityWSAttempt): AddonModH5PActivityAttempt {
const formattedAttempt: AddonModH5PActivityAttempt = attempt;
formattedAttempt.timecreated = attempt.timecreated * 1000; // Convert to milliseconds.
formattedAttempt.timemodified = attempt.timemodified * 1000; // Convert to milliseconds.
formattedAttempt.success = formattedAttempt.success ?? null;
if (!attempt.duration) {
formattedAttempt.durationReadable = '-';
formattedAttempt.durationCompact = '-';
} else {
formattedAttempt.durationReadable = CoreTimeUtils.formatTime(attempt.duration);
formattedAttempt.durationCompact = CoreTimeUtils.formatDurationShort(attempt.duration);
}
return formattedAttempt;
}
/**
* Format attempt data and results.
*
* @param attempt Attempt and results to format.
*/
protected formatAttemptResults(attempt: AddonModH5PActivityWSAttemptResults): AddonModH5PActivityAttemptResults {
const formattedAttempt: AddonModH5PActivityAttemptResults = this.formatAttempt(attempt);
formattedAttempt.results = formattedAttempt.results?.map((result) => this.formatResult(result));
return formattedAttempt;
}
/**
* Format the attempts of a user.
*
* @param data Data to format.
* @return Formatted data.
*/
protected formatUserAttempts(data: AddonModH5PActivityWSUserAttempts): AddonModH5PActivityUserAttempts {
const formatted: AddonModH5PActivityUserAttempts = data;
formatted.attempts = formatted.attempts.map((attempt) => this.formatAttempt(attempt));
if (formatted.scored) {
formatted.scored.attempts = formatted.scored.attempts.map((attempt) => this.formatAttempt(attempt));
}
return formatted;
}
/**
* Format an attempt's result.
*
* @param result Result to format.
*/
protected formatResult(result: AddonModH5PActivityWSResult): AddonModH5PActivityWSResult {
result.timecreated = result.timecreated * 1000; // Convert to milliseconds.
return result;
}
/**
* Get cache key for access information WS calls.
*
* @param id H5P activity ID.
* @return Cache key.
*/
protected getAccessInformationCacheKey(id: number): string {
return ROOT_CACHE_KEY + 'accessInfo:' + id;
}
/**
* Get access information for a given H5P activity.
*
* @param id H5P activity ID.
* @param options Other options.
* @return Promise resolved with the data.
*/
async getAccessInformation(id: number, options: CoreCourseCommonModWSOptions = {}): Promise<AddonModH5PActivityAccessInfo> {
const site = await CoreSites.getSite(options.siteId);
const params: AddonModH5pactivityGetH5pactivityAccessInformationWSParams = {
h5pactivityid: id,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getAccessInformationCacheKey(id),
updateFrequency: CoreSite.FREQUENCY_OFTEN,
component: AddonModH5PActivityProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
return site.read('mod_h5pactivity_get_h5pactivity_access_information', params, preSets);
}
/**
* Get attempt results for all user attempts.
*
* @param id Activity ID.
* @param options Other options.
* @return Promise resolved with the results of the attempt.
*/
async getAllAttemptsResults(
id: number,
options?: AddonModH5PActivityGetAttemptResultsOptions,
): Promise<AddonModH5PActivityAttemptsResults> {
const userAttempts = await this.getUserAttempts(id, options);
const attemptIds = userAttempts.attempts.map((attempt) => attempt.id);
if (attemptIds.length) {
// Get all the attempts with a single call.
return this.getAttemptsResults(id, attemptIds, options);
} else {
// No attempts.
return {
activityid: id,
attempts: [],
warnings: [],
};
}
}
/**
* Get cache key for results WS calls.
*
* @param id Instance ID.
* @param attemptsIds Attempts IDs.
* @return Cache key.
*/
protected getAttemptResultsCacheKey(id: number, attemptsIds: number[]): string {
return this.getAttemptResultsCommonCacheKey(id) + ':' + JSON.stringify(attemptsIds);
}
/**
* Get common cache key for results WS calls.
*
* @param id Instance ID.
* @return Cache key.
*/
protected getAttemptResultsCommonCacheKey(id: number): string {
return ROOT_CACHE_KEY + 'results:' + id;
}
/**
* Get attempt results.
*
* @param id Activity ID.
* @param attemptId Attempt ID.
* @param options Other options.
* @return Promise resolved with the results of the attempt.
*/
async getAttemptResults(
id: number,
attemptId: number,
options?: AddonModH5PActivityGetAttemptResultsOptions,
): Promise<AddonModH5PActivityAttemptResults> {
options = options || {};
const site = await CoreSites.getSite(options.siteId);
const params: AddonModH5pactivityGetResultsWSParams = {
h5pactivityid: id,
attemptids: [attemptId],
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getAttemptResultsCacheKey(id, params.attemptids!),
updateFrequency: CoreSite.FREQUENCY_SOMETIMES,
component: AddonModH5PActivityProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
try {
const response = await site.read<AddonModH5pactivityGetResultsWSResponse>(
'mod_h5pactivity_get_results',
params,
preSets,
);
if (response.warnings?.[0]) {
throw new CoreWSError(response.warnings[0]); // Cannot view attempt.
}
return this.formatAttemptResults(response.attempts[0]);
} catch (error) {
if (CoreUtils.isWebServiceError(error)) {
throw error;
}
// Check if the full list of results is cached. If so, get the results from there.
const cacheOptions: AddonModH5PActivityGetAttemptResultsOptions = {
...options, // Include all the original options.
readingStrategy: CoreSitesReadingStrategy.ONLY_CACHE,
};
const attemptsResults = await AddonModH5PActivity.getAllAttemptsResults(id, cacheOptions);
const attempt = attemptsResults.attempts.find((attempt) => attempt.id == attemptId);
if (!attempt) {
throw error;
}
return attempt;
}
}
/**
* Get attempts results.
*
* @param id Activity ID.
* @param attemptsIds Attempts IDs.
* @param options Other options.
* @return Promise resolved with all the attempts.
*/
async getAttemptsResults(
id: number,
attemptsIds: number[],
options?: AddonModH5PActivityGetAttemptResultsOptions,
): Promise<AddonModH5PActivityAttemptsResults> {
options = options || {};
const site = await CoreSites.getSite(options.siteId);
const params: AddonModH5pactivityGetResultsWSParams = {
h5pactivityid: id,
attemptids: attemptsIds,
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getAttemptResultsCommonCacheKey(id),
updateFrequency: CoreSite.FREQUENCY_SOMETIMES,
component: AddonModH5PActivityProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response = await site.read<AddonModH5pactivityGetResultsWSResponse>(
'mod_h5pactivity_get_results',
params,
preSets,
);
response.attempts = response.attempts.map((attempt) => this.formatAttemptResults(attempt));
return response;
}
/**
* Get deployed file from an H5P activity instance.
*
* @param h5pActivity Activity instance.
* @param options Options
* @return Promise resolved with the file.
*/
async getDeployedFile(
h5pActivity: AddonModH5PActivityData,
options?: AddonModH5PActivityGetDeployedFileOptions,
): Promise<CoreWSFile> {
if (h5pActivity.deployedfile) {
// File already deployed and still valid, use this one.
return h5pActivity.deployedfile;
}
if (!h5pActivity.package || !h5pActivity.package[0]) {
// Shouldn't happen.
throw new CoreError('No H5P package found.');
}
options = options || {};
// Deploy the file in the server.
return CoreH5P.getTrustedH5PFile(
h5pActivity.package[0].fileurl,
options.displayOptions,
options.ignoreCache,
options.siteId,
);
}
/**
* Get cache key for H5P activity data WS calls.
*
* @param courseId Course ID.
* @return Cache key.
*/
protected getH5PActivityDataCacheKey(courseId: number): string {
return ROOT_CACHE_KEY + 'h5pactivity:' + courseId;
}
/**
* Get an H5P activity with key=value. If more than one is found, only the first will be returned.
*
* @param courseId Course ID.
* @param key Name of the property to check.
* @param value Value to search.
* @param options Other options.
* @return Promise resolved with the activity data.
*/
protected async getH5PActivityByField(
courseId: number,
key: string,
value: unknown,
options: CoreSitesCommonWSOptions = {},
): Promise<AddonModH5PActivityData> {
const site = await CoreSites.getSite(options.siteId);
const params: AddonModH5pactivityGetByCoursesWSParams = {
courseids: [courseId],
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getH5PActivityDataCacheKey(courseId),
updateFrequency: CoreSite.FREQUENCY_RARELY,
component: AddonModH5PActivityProvider.COMPONENT,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response = await site.read<AddonModH5pactivityGetByCoursesWSResponse>(
'mod_h5pactivity_get_h5pactivities_by_courses',
params,
preSets,
);
const currentActivity = response.h5pactivities.find((h5pActivity) => h5pActivity[key] == value);
if (currentActivity) {
return currentActivity;
}
throw new CoreError(Translate.instant('addon.mod_h5pactivity.errorgetactivity'));
}
/**
* Get an H5P activity by module ID.
*
* @param courseId Course ID.
* @param cmId Course module ID.
* @param options Other options.
* @return Promise resolved with the activity data.
*/
getH5PActivity(courseId: number, cmId: number, options: CoreSitesCommonWSOptions = {}): Promise<AddonModH5PActivityData> {
return this.getH5PActivityByField(courseId, 'coursemodule', cmId, options);
}
/**
* Get an H5P activity by context ID.
*
* @param courseId Course ID.
* @param contextId Context ID.
* @param options Other options.
* @return Promise resolved with the activity data.
*/
getH5PActivityByContextId(
courseId: number,
contextId: number,
options: CoreSitesCommonWSOptions = {},
): Promise<AddonModH5PActivityData> {
return this.getH5PActivityByField(courseId, 'context', contextId, options);
}
/**
* Get an H5P activity by instance ID.
*
* @param courseId Course ID.
* @param id Instance ID.
* @param options Other options.
* @return Promise resolved with the activity data.
*/
getH5PActivityById(courseId: number, id: number, options: CoreSitesCommonWSOptions = {}): Promise<AddonModH5PActivityData> {
return this.getH5PActivityByField(courseId, 'id', id, options);
}
/**
* Get cache key for attemps WS calls.
*
* @param id Instance ID.
* @param userIds User IDs.
* @return Cache key.
*/
protected getUserAttemptsCacheKey(id: number, userIds: number[]): string {
return this.getUserAttemptsCommonCacheKey(id) + ':' + JSON.stringify(userIds);
}
/**
* Get common cache key for attempts WS calls.
*
* @param id Instance ID.
* @return Cache key.
*/
protected getUserAttemptsCommonCacheKey(id: number): string {
return ROOT_CACHE_KEY + 'attempts:' + id;
}
/**
* Get attempts of a certain user.
*
* @param id Activity ID.
* @param options Other options.
* @return Promise resolved with the attempts of the user.
*/
async getUserAttempts(
id: number,
options: AddonModH5PActivityGetAttemptsOptions = {},
): Promise<AddonModH5PActivityUserAttempts> {
const site = await CoreSites.getSite(options.siteId);
const params: AddonModH5pactivityGetAttemptsWSParams = {
h5pactivityid: id,
userids: [options.userId || site.getUserId()],
};
const preSets: CoreSiteWSPreSets = {
cacheKey: this.getUserAttemptsCacheKey(id, params.userids!),
updateFrequency: CoreSite.FREQUENCY_SOMETIMES,
component: AddonModH5PActivityProvider.COMPONENT,
componentId: options.cmId,
...CoreSites.getReadingStrategyPreSets(options.readingStrategy), // Include reading strategy preSets.
};
const response = await site.read<AddonModH5pactivityGetAttemptsWSResponse>('mod_h5pactivity_get_attempts', params, preSets);
if (response.warnings?.[0]) {
throw new CoreWSError(response.warnings[0]); // Cannot view user attempts.
}
return this.formatUserAttempts(response.usersattempts[0]);
}
/**
* Invalidates access information.
*
* @param id H5P activity ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateAccessInformation(id: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getAccessInformationCacheKey(id));
}
/**
* Invalidates H5P activity data.
*
* @param courseId Course ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateActivityData(courseId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getH5PActivityDataCacheKey(courseId));
}
/**
* Invalidates all attempts results for H5P activity.
*
* @param id Activity ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateAllResults(id: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getAttemptResultsCommonCacheKey(id));
}
/**
* Invalidates results of a certain attempt for H5P activity.
*
* @param id Activity ID.
* @param attemptId Attempt ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateAttemptResults(id: number, attemptId: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getAttemptResultsCacheKey(id, [attemptId]));
}
/**
* Invalidates all users attempts for H5P activity.
*
* @param id Activity ID.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateAllUserAttempts(id: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
await site.invalidateWsCacheForKey(this.getUserAttemptsCommonCacheKey(id));
}
/**
* Invalidates attempts of a certain user for H5P activity.
*
* @param id Activity ID.
* @param userId User ID. If not defined, current user in the site.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the data is invalidated.
*/
async invalidateUserAttempts(id: number, userId?: number, siteId?: string): Promise<void> {
const site = await CoreSites.getSite(siteId);
userId = userId || site.getUserId();
await site.invalidateWsCacheForKey(this.getUserAttemptsCacheKey(id, [userId]));
}
/**
* Delete launcher.
*
* @return Promise resolved when the launcher file is deleted.
*/
async isPluginEnabled(siteId?: string): Promise<boolean> {
const site = await CoreSites.getSite(siteId);
return site.wsAvailable('mod_h5pactivity_get_h5pactivities_by_courses');
}
/**
* Report an H5P activity as being viewed.
*
* @param id H5P activity ID.
* @param name Name of the activity.
* @param siteId Site ID. If not defined, current site.
* @return Promise resolved when the WS call is successful.
*/
logView(id: number, name?: string, siteId?: string): Promise<void> {
const params: AddonModH5pactivityViewH5pactivityWSParams = {
h5pactivityid: id,
};
return CoreCourseLogHelper.logSingle(
'mod_h5pactivity_view_h5pactivity',
params,
AddonModH5PActivityProvider.COMPONENT,
id,
name,
'h5pactivity',
{},
siteId,
);
}
}
export const AddonModH5PActivity = makeSingleton(AddonModH5PActivityProvider);
/**
* Basic data for an H5P activity, exported by Moodle class h5pactivity_summary_exporter.
*/
export type AddonModH5PActivityData = {
id: number; // The primary key of the record.
course: number; // Course id this h5p activity is part of.
name: string; // The name of the activity module instance.
timecreated?: number; // Timestamp of when the instance was added to the course.
timemodified?: number; // Timestamp of when the instance was last modified.
intro: string; // H5P activity description.
introformat: number; // Intro format (1 = HTML, 0 = MOODLE, 2 = PLAIN or 4 = MARKDOWN).
grade?: number; // The maximum grade for submission.
displayoptions: number; // H5P Button display options.
enabletracking: number; // Enable xAPI tracking.
grademethod: number; // Which H5P attempt is used for grading.
contenthash?: string; // Sha1 hash of file content.
coursemodule: number; // Coursemodule.
context: number; // Context ID.
introfiles: CoreWSExternalFile[];
package: CoreWSExternalFile[];
deployedfile?: {
filename?: string; // File name.
filepath?: string; // File path.
filesize?: number; // File size.
fileurl: string; // Downloadable file url.
timemodified?: number; // Time modified.
mimetype?: string; // File mime type.
};
};
/**
* Params of mod_h5pactivity_get_h5pactivities_by_courses WS.
*/
export type AddonModH5pactivityGetByCoursesWSParams = {
courseids?: number[]; // Array of course ids.
};
/**
* Data returned by mod_h5pactivity_get_h5pactivities_by_courses WS.
*/
export type AddonModH5pactivityGetByCoursesWSResponse = {
h5pactivities: AddonModH5PActivityData[];
warnings?: CoreWSExternalWarning[];
};
/**
* Params of mod_h5pactivity_get_h5pactivity_access_information WS.
*/
export type AddonModH5pactivityGetH5pactivityAccessInformationWSParams = {
h5pactivityid: number; // H5p activity instance id.
};
/**
* Data returned by mod_h5pactivity_get_h5pactivity_access_information WS.
*/
export type AddonModH5pactivityGetH5pactivityAccessInformationWSResponse = {
warnings?: CoreWSExternalWarning[];
canview?: boolean; // Whether the user has the capability mod/h5pactivity:view allowed.
canaddinstance?: boolean; // Whether the user has the capability mod/h5pactivity:addinstance allowed.
cansubmit?: boolean; // Whether the user has the capability mod/h5pactivity:submit allowed.
canreviewattempts?: boolean; // Whether the user has the capability mod/h5pactivity:reviewattempts allowed.
};
/**
* Result of WS mod_h5pactivity_get_h5pactivity_access_information.
*/
export type AddonModH5PActivityAccessInfo = AddonModH5pactivityGetH5pactivityAccessInformationWSResponse;
/**
* Params of mod_h5pactivity_get_attempts WS.
*/
export type AddonModH5pactivityGetAttemptsWSParams = {
h5pactivityid: number; // H5p activity instance id.
userids?: number[]; // User ids.
};
/**
* Data returned by mod_h5pactivity_get_attempts WS.
*/
export type AddonModH5pactivityGetAttemptsWSResponse = {
activityid: number; // Activity course module ID.
usersattempts: AddonModH5PActivityWSUserAttempts[]; // The complete users attempts list.
warnings?: CoreWSExternalWarning[];
};
/**
* Params of mod_h5pactivity_get_results WS.
*/
export type AddonModH5pactivityGetResultsWSParams = {
h5pactivityid: number; // H5p activity instance id.
attemptids?: number[]; // Attempt ids.
};
/**
* Data returned by mod_h5pactivity_get_results WS.
*/
export type AddonModH5pactivityGetResultsWSResponse = {
activityid: number; // Activity course module ID.
attempts: AddonModH5PActivityWSAttemptResults[]; // The complete attempts list.
warnings?: CoreWSExternalWarning[];
};
/**
* Attempts results with some calculated data.
*/
export type AddonModH5PActivityAttemptsResults = Omit<AddonModH5pactivityGetResultsWSResponse, 'attempts'> & {
attempts: AddonModH5PActivityAttemptResults[]; // The complete attempts list.
};
/**
* Attempts data for a user as returned by the WS mod_h5pactivity_get_attempts.
*/
export type AddonModH5PActivityWSUserAttempts = {
userid: number; // The user id.
attempts: AddonModH5PActivityWSAttempt[]; // The complete attempts list.
scored?: { // Attempts used to grade the activity.
title: string; // Scored attempts title.
grademethod: string; // Scored attempts title.
attempts: AddonModH5PActivityWSAttempt[]; // List of the grading attempts.
};
};
/**
* Attempt data as returned by the WS mod_h5pactivity_get_attempts.
*/
export type AddonModH5PActivityWSAttempt = {
id: number; // ID of the context.
h5pactivityid: number; // ID of the H5P activity.
userid: number; // ID of the user.
timecreated: number; // Attempt creation.
timemodified: number; // Attempt modified.
attempt: number; // Attempt number.
rawscore: number; // Attempt score value.
maxscore: number; // Attempt max score.
duration: number; // Attempt duration in seconds.
completion?: number; // Attempt completion.
success?: number | null; // Attempt success.
scaled: number; // Attempt scaled.
};
/**
* Attempt and results data as returned by the WS mod_h5pactivity_get_results.
*/
export type AddonModH5PActivityWSAttemptResults = AddonModH5PActivityWSAttempt & {
results?: AddonModH5PActivityWSResult[]; // The results of the attempt.
};
/**
* Attempt result data as returned by the WS mod_h5pactivity_get_results.
*/
export type AddonModH5PActivityWSResult = {
id: number; // ID of the context.
attemptid: number; // ID of the H5P attempt.
subcontent: string; // Subcontent identifier.
timecreated: number; // Result creation.
interactiontype: string; // Interaction type.
description: string; // Result description.
content?: string; // Result extra content.
rawscore: number; // Result score value.
maxscore: number; // Result max score.
duration?: number; // Result duration in seconds.
completion?: number; // Result completion.
success?: number | null; // Result success.
optionslabel?: string; // Label used for result options.
correctlabel?: string; // Label used for correct answers.
answerlabel?: string; // Label used for user answers.
track?: boolean; // If the result has valid track information.
options?: { // The statement options.
description: string; // Option description.
id: number; // Option identifier.
correctanswer: AddonModH5PActivityWSResultAnswer; // The option correct answer.
useranswer: AddonModH5PActivityWSResultAnswer; // The option user answer.
}[];
};
/**
* Result answer as returned by the WS mod_h5pactivity_get_results.
*/
export type AddonModH5PActivityWSResultAnswer = {
answer?: string; // Option text value.
correct?: boolean; // If has to be displayed as correct.
incorrect?: boolean; // If has to be displayed as incorrect.
text?: boolean; // If has to be displayed as simple text.
checked?: boolean; // If has to be displayed as a checked option.
unchecked?: boolean; // If has to be displayed as a unchecked option.
pass?: boolean; // If has to be displayed as passed.
fail?: boolean; // If has to be displayed as failed.
};
/**
* User attempts data with some calculated data.
*/
export type AddonModH5PActivityUserAttempts = Omit<AddonModH5PActivityWSUserAttempts, 'attempts'|'scored'> & {
attempts: AddonModH5PActivityAttempt[]; // The complete attempts list.
scored?: { // Attempts used to grade the activity.
title: string; // Scored attempts title.
grademethod: string; // Scored attempts title.
attempts: AddonModH5PActivityAttempt[]; // List of the grading attempts.
};
};
/**
* Attempt with some calculated data.
*/
export type AddonModH5PActivityAttempt = AddonModH5PActivityWSAttempt & {
durationReadable?: string; // Duration in a human readable format.
durationCompact?: string; // Duration in a "short" human readable format.
};
/**
* Attempt and results data with some calculated data.
*/
export type AddonModH5PActivityAttemptResults = AddonModH5PActivityAttempt & {
results?: AddonModH5PActivityWSResult[]; // The results of the attempt.
};
/**
* Options to pass to getDeployedFile function.
*/
export type AddonModH5PActivityGetDeployedFileOptions = {
displayOptions?: CoreH5PDisplayOptions; // Display options
ignoreCache?: boolean; // Whether to ignore cache. Will fail if offline or server down.
siteId?: string; // Site ID. If not defined, current site.
};
/**
* Options to pass to getAttemptResults function.
*/
export type AddonModH5PActivityGetAttemptResultsOptions = CoreCourseCommonModWSOptions & {
userId?: number; // User ID. If not defined, user of the site.
};
/**
* Options to pass to getAttempts function.
*/
export type AddonModH5PActivityGetAttemptsOptions = AddonModH5PActivityGetAttemptResultsOptions;
/**
* Params of mod_h5pactivity_view_h5pactivity WS.
*/
export type AddonModH5pactivityViewH5pactivityWSParams = {
h5pactivityid: number; // H5P activity instance id.
};
declare module '@singletons/events' {
/**
* Augment CoreEventsData interface with events specific to this service.
*
* @see https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation
*/
export interface CoreEventsData {
[AddonModH5PActivitySyncProvider.AUTO_SYNCED]: AddonModH5PActivityAutoSyncData;
}
} | the_stack |
global["$locale_strings"] = global["$locale_strings"] || {};
var locale_strings = global["$locale_strings"];
locale_strings[0] = "Successful implementation";
locale_strings[1] = "Compilation fails";
locale_strings[3] = "Time: {0} second";
locale_strings[4] = "Script execution failed";
locale_strings[5] = "Compile failed";
locale_strings[6] = "manifest.json generated successfully";
locale_strings[7] = "Total time for native copy: {0} second";
locale_strings[8] = "Project modules can not use both gui and eui, and the eui module is recommended";
locale_strings[1050] = 'Could not find module : {0}'
//create
locale_strings[1001] = "Enter a project name. Example: {color_green}egret create [project_name]{color_normal}";
locale_strings[1002] = "The project already exists";
locale_strings[1003] = "Creating a new project folder ...";
locale_strings[1004] = "Compiling the project ...";
locale_strings[1005] = "Create successfully";
//build
locale_strings[1101] = "Enter a project name. Example: {color_green}egret build [project_name]{color_normal}";
locale_strings[1102] = "bin-debug folder is not contained in the specified project, please implement {color_green} egret build [project_name] -e {color_normal} to initialize the engine";
locale_strings[1103] = "There is a circular dependency among the {0}: error files, please check the class inheritance or static variable initialization references.";
locale_strings[1104] = "Build successfully ";
locale_strings[1105] = "Compile the project:";
locale_strings[1106] = "Scan the project list";
locale_strings[1107] = "Time for scanning: {0} second";
locale_strings[1108] = "Total project compiling time: {0} second";
locale_strings[1109] = "Implement tsc compilation ";
locale_strings[1110] = "Time for tsc compiling: {0} second";
locale_strings[1111] = "{0} tsc compiles and generates js file";
locale_strings[1112] = "{0} uses time: {1} seconds";
locale_strings[1113] = "{0} tsc compiles and generates '.d.ts'";
locale_strings[1114] = "{0} Copy other documents";
locale_strings[1115] = "The total elapsed time of the 3rd party libraries: {0} secs";
locale_strings[1116] = "Not support the compiler option: '{0}' in tsconfig.json.";
locale_strings[1117] = "Warning! The tsconfig.json is not a valid json.";
locale_strings[1118] = "The {0} version of the engine was not found and will be replaced with the default version of the engine. Please install the corresponding version engine in EgretEngine.";
locale_strings[1119] = "Third party library compilation error, you can visit {color_underline} http://developer.egret.com/cn/github/egret-docs/Engine2D/projectConfig/libraryProject/index.html {color_normal} Learn more ";
locale_strings[1120] = "Egret engine 4.1 use the new structure for third-party library upgrades, please upgrade your third-party library first";
locale_strings[1121] = "Your module package.json does not contain the 'typings' attribute, which causes the exported module to not have a TypeScript Definition file (.d.ts), and can not contain smart syntax prompts in TypeScript"
locale_strings[1122] = "Third-party library tsconfig.json must include outFile this attribute";
locale_strings[1123] = "{0} will be adjusted to '{1}'";
locale_strings[1124] = "The egret project in the form of a third-party library does not support the outDir generation rule.";
//compile
locale_strings[1301] = "Cannot find egret_file_list.js or game_file_list.js compiled under the path {0}, please check whether the compile path is correct";
locale_strings[1302] = "Please enter the compile path. Example: {color_green}egret compile --source [your_typescript_source_dir] --output [your_output_dir]{color_normal}";
locale_strings[1303] = "Compilation fails";
locale_strings[1304] = "Parsing manifest.json file fails, check whether the file is in the correct JSON format: \n{0}";
locale_strings[1305] = "Reading launcher / {0} .html fails, check whether the compile path is correct";
locale_strings[1306] = "Fail to find variable definition of the document class 'document_class' in launcher /{0}, please check whether the contents of the file are correct";
locale_strings[1307] = ".ts or .d.ts file {0} does not exist in the module, and cannot be compiled, so please fill.ts or .d.ts in file_list field of the module ";
locale_strings[1308] = "Class or interface name conflict: '{0}' exists in both of the following two files: \n {1} \n {2}";
locale_strings[1309] = "Compile successfully";
locale_strings[1310] = "Scan into changed file list:";
//publish
locale_strings[1401] = "java can't be found or java version is too old (at least java 7), please install the java and execute egret publish -testJava command for test";
locale_strings[1402] = "Start to publish {0} version: {1}";
locale_strings[1403] = "Start to compress js file";
locale_strings[1404] = "Js file compression time: {0} second";
locale_strings[1405] = "Uncompressed js file, and copy js file";
locale_strings[1406] = "Js file copy time: {0} second";
locale_strings[1407] = "Scan version control file";
locale_strings[1408] = "Time to generate version control file: {0} second";
locale_strings[1409] = "Time to copy files to release: {0} second";
locale_strings[1410] = "Start to generate zip package";
locale_strings[1411] = "Time to generate zip package: {0} second";
locale_strings[1412] = "Total time for native copy: {0} seconds";
locale_strings[1413] = "Total to complete the release: {0} second";
locale_strings[1414] = "Fail to generate a zip package, and copy the file to the release";
locale_strings[1415] = "Executing the detection command: {0}";
locale_strings[1416] = "You can modify the JAVA_HOME environment variable to modify JAVA path";
locale_strings[1417] = "Successful detection ";
locale_strings[1418] = "WebP format fail : {0}";
locale_strings[1419] = "Format WebP : {0} / {1}";
locale_strings[1420] = "Zip package failed, there may be special characters in the path";
locale_strings[1421] = "Playing zip package exception!";
locale_strings[1422] = "After the TextureMerger Plugin runs, there is a reference to superior {1} in {0}!";
locale_strings[1423] = "TextureMerger execution error, error code: {0}";
locale_strings[1424] = "Execute command: {0}{1}";
locale_strings[1425] = "The textureMerger item corresponding to {0} does not have a suffix name set, it has been added automatically, please check the code";
locale_strings[1426] = "Please install Texture Merger";
locale_strings[1427] = "Please upgrade Texture Merger to 1.7.0 or later";
locale_strings[1428] = "Unsupported platforms";
locale_strings[1429] = "{0} Introduced an identical TextureMerger result, please check";
locale_strings[1430] = "The configured fileName does not have a resource";
//startserver
locale_strings[1501] = "Unable to start the server, please check the authority or whether the port is occupied";
//create_app
locale_strings[1601] = "Please enter a h5 game project name, and mobile platform support library.Example: {color_green}egret create_app [app_name] -f [h5_game_path] -t [template_path] {color_normal} \n If you do not install the latest mobile platform support library,please download from the following address:\nAndroid: http://www.egret-labs.org/download/egret-android-packager-download.html, \niOS:http://www.egret-labs.org/download/egret-ios-packager-download.html";
locale_strings[1602] = "EgretProperties.json missing or incorrectly formatted. \n Please upgrade egret-core to the latest version from http://www.egret-labs.org/download/egret-download.html";
locale_strings[1603] = "create_app.json is missing in {color_red}{0}{color_normal}.\nPlease download the latest mobile platform support library from the following address \nAndroid: http://www.egret-labs.org/download/egret-android-packager-download.html\niOS: http://www.egret-labs.org/download/egret-ios-packager-download.html";
locale_strings[1604] = "Egret Build command failed";
locale_strings[1605] = "Mobile platform project directory cannot be the same one with html5 project directory, please modify the mobile platform project directory.";
locale_strings[1606] = "Created, total time: {0} second";
locale_strings[1607] = "> copy from project template ...";
locale_strings[1608] = "> replace all configure elements ...";
locale_strings[1609] = "> rename project name ...";
locale_strings[1610] = "Project name is missing. Example:{color_green}egret create_app [app_name] -f [h5_game_path] -t [template_path] {color_normal}";
locale_strings[1611] = "The project is exist, please use another name.Example:{color_green}egret create_app [app_name] -f [h5_game_path] -t [template_path] {color_normal}";
locale_strings[1612] = "The first letter of the project name must be a-z";
locale_strings[1613] = "unzip exception!";
locale_strings[1614] = "The project.properties file could not be found. app_path: {0}";
locale_strings[1615] = "The build.gradle file could not be found. app_path: {0}";
locale_strings[1616] = "The platforms folder could not be found. android_home: {0}";
locale_strings[1617] = "The source.properties file could not be found. platformDir: {0}";
locale_strings[1618] = "The build_tools folder could not be found. android_home: {0}";
locale_strings[1619] = "The source.properties file could not be found. buildToolDir: {0}";
//upgrade
locale_strings[1701] = "Project version is lower than egret version, please implement egret upgrade {your_project} command to upgrade your project, \n do not add braces {} in the commands";
locale_strings[1702] = "Upgrade successfully";
locale_strings[1703] = "Upgrade script completed . Please check {color_underline}{0}{color_normal} for details";
locale_strings[1704] = "Updating to {0}";
locale_strings[1705] = "Update error,pleaet try again after reset engine";
locale_strings[1706] = "Total {color_red}{0}{color_normal} API conflicts,please edit your project then rerun build command";
locale_strings[1707] = "Copy files from {0} to {1} ..";
locale_strings[1711] = "The project directory has been changed,please use the new directory{color_red} '{0}' {color_normal},and use the command {color_red} egret apitest {your-project} {color_normal} testing the difference between the APIs";
locale_strings[1712] = "The testing result was writing in'{0}'";
locale_strings[1713] = "{color_green}Egret QQ group 481169576 {color_normal}";
locale_strings[1714] = "Updating the egretProperties.json";
locale_strings[1715] = "Project testing sucessfully";
locale_strings[1716] = "You use the old 3rd part library {0}.Please make sure these files not used the removed API or use the compatible 3rd party library {1}";
locale_strings[1717] = "upgrade interruption, for the following reasons";
locale_strings[1718] = "5.0.8 later version will delete template/debug/index.html template file, use index.html directly";
locale_strings[1719] = "5.1 for the new feature experience version, only to create a new project, the old project can not be upgraded";
//info
locale_strings[1801] = "Egret version:{0}";
locale_strings[1802] = "Egret installation path:{0}";
//help
locale_strings[1901] = "The help file for {0} command can't be found ";
locale_strings[1902] = "How to use: {0}";
locale_strings[1903] = "How to use: egret <command> [-v]";
locale_strings[1904] = "command list:";
locale_strings[1905] = "Parameter list:";
locale_strings[1906] = "{0} print a detailed log";
locale_strings[1907] = "Use egret help <command> to understand details of each command";
//exml
locale_strings[2001] = "{0}: error EXML file can't be found ";
locale_strings[2002] = "{0}: error XML file error {1}";
locale_strings[2003] = "{0}: error the class definitions corresponding to nodes can't be found \n {1}";
locale_strings[2004] = "{0}: error nodes cannot contain id property with the same name \n {1}";
locale_strings[2005] = "{0}: error property with the name of '{1}' or style name does not exist on the node: \n {2}";
locale_strings[2006] = "{0}: error undefined view state name: '{1}' \n {2}";
locale_strings[2007] = "{0}: error only egret.IVisualElement objects within the container can use the includeIn and excludeFrom properties\n {1}";
locale_strings[2008] = "{0}: error fail to assign values of '{1}' class to property: '{2}' \n {3}";
locale_strings[2009] = "{0}: error only one ID can be referenced in the node property value '{}' label, and complex expression is not allowed to use \n {1}";
locale_strings[2010] = "{0}: error ID referenced by property: '{1}': '{2}' does not exist \n {3}";
locale_strings[2011] = "{0}: error fail to assign more than one child nodes to the same property: '{1}' \n {2}";
locale_strings[2012] = "{0}: error no default property exists on the node, and you must explicitly declare the property name that the child node is assigned to \n {1}";
locale_strings[2013] = "{0}: error view state grammar is not allowed to use on property nodes of Array class \n {1} ";
locale_strings[2014] = "{0}: error assigning the skin class itself to the node property is not allowed \n {1}";
locale_strings[2015] = "{0}: error class definition referenced by node: {1} does not exist \n {2}";
locale_strings[2016] = "{0}: error format error of 'scale9Grid' property value on the node: {1}";
locale_strings[2017] = "{0}: error namespace prefix missing on the node: {1}";
locale_strings[2018] = "{0}: error format error of 'skinName' property value on the node: {1}";
locale_strings[2019] = "{0}: error the container’s child item must be visible nodes: {1}";
locale_strings[2020] = "{0}: error error for child nodes in w: Declarations, the includeIn and excludeFrom properties are not allowed to use \n {1}";
locale_strings[2102] = "{0}: warning no child node can be found on the property code \n {1}";
locale_strings[2103] = "{0}: warning the same property '{1}' on the node is assigned multiple times \n {2}";
locale_strings[2104] = "Warning: There is a duplicate definition for the class name {1} defined by the {0} file."
// android sdk install
locale_strings[2201] = "{0} file(s) will be downloaded!";
locale_strings[2202] = "The total size is {0}MB";
locale_strings[2203] = "Start to download!";
locale_strings[2204] = "{0} downloaded successfully!";
locale_strings[2205] = "This file size is {0}MB";
locale_strings[2206] = "All files are downloaded successfully!";
locale_strings[2207] = "{0} file(s) will be unzipped and installed!";
locale_strings[2208] = "Start to unzip and install!";
locale_strings[2209] = "{0} unzipped and installed successfully!";
locale_strings[2210] = "All files are unzipped and installed successfully!";
locale_strings[2211] = "Android SDK installed successfully!";
locale_strings[8001] = "please input value of the command option {color_green} {0} {color_normal},and it must be one of these: {color_green}[{1}]{color_normal}";
locale_strings[8002] = "{color_red}Please choose the Egret project folder{color_normal}\n\tEgret_Project\t\t{color_gray}//project folder{color_normal}\n\t\t--launcher\t{color_gray}//launcher folder{color_normal}\n\t\t--src\t\t{color_gray}//source code folder{color_normal}";
locale_strings[8003] = "The configuration file {0} not exist";
locale_strings[8004] = "{color_red}Create Native project first and use command --runtime native{color_normal}";
locale_strings[9999] = "unknown error:{0}";
locale_strings[10001] = "Compiler option {0} expects an argument";
locale_strings[10002] = "Unknown Compiler option {0}";
locale_strings[10003] = "TSC is trying to exit, exit code is: {0}";
locale_strings[10004] = "No output file name when minify flag is true";
locale_strings[10006] = "manifest.json has been generated";
locale_strings[10008] = "Duplicate interface or class name:‘{0}’ is defined both in these files :\n{1}\n{2}";
locale_strings[10009] = "{0} is not in the right format, you may need to reinstall Egret.";
locale_strings[10010] = "Auto compile service is running...";
locale_strings[10011] = "Auto compile is done.";
locale_strings[10012] = 'If you are not using auto compile file save, you can enable auto compile by adding "-a" after the "run" command';
locale_strings[10013] = "Egret server is running, you can access by URL: {0}";
locale_strings[10014] = "Error occurred while compiling your code:";
locale_strings[10015] = "{color_red}\"{0}\" is not a valid Egret project folder{color_normal}" +
"\n\tEgret_Project\t\t\t//project folder" +
"\n\t\t--template\t\t//template folder" +
"\n\t\t--libs\t\t\t//library folder" +
"\n\t\t--resource\t\t//resource folder" +
"\n\t\t--src\t\t\t//source code folder" +
"\n\t\t--egretProperties.json\t//project configuration file" +
"\n\t\t--index.html\t\t//launcher file"
;
locale_strings[10016] = "Please visit {0} if the browser didn't open it automatically";
locale_strings[10017] = "Egret project is created, you can execute \"Egret run\" to run the project";
locale_strings[10018] = "Found circular dependency when try to sort the TypeScript files. "
+ "Maybe you are create an instance of a subclass and assign it to a static member, "
+ "or using a subclass in immediately executing codes";
locale_strings[10019] = "Cannot find the projects used to build native apps. These projects are not include on the Github."
+ "Please visit http://www.egret.com to download the Egret Installer. If you have install Egret, please contact us.";
locale_strings[10020] = "Compile service is exit unexpectedly";
locale_strings[10021] = "Error with the folders, Please note the following items: 1. Please check template/runtime/native_require.js, if it’s void, please recreate a new project and replace it.\n 2.Don’t create native project on the desktop, put all the files into a same place like E disk partition.\n Please don’t execute the script immediately after configuration because of operation system refresh. If still doesn’t work after try several times, please send email to XX contact us.";
locale_strings[10022] = "{0} file changes, automatic compilation is closed";
locale_strings[12000] = "Create a new Egret Project";
locale_strings[12001] = "Please select a template";
locale_strings[12002] = "Please set the default screen size";
locale_strings[12003] = "Please select the Scale Mode";
locale_strings[12004] = "Please select modules";
locale_strings[12005] = "Please select the platform";
module helpModule {
export var help_dict = {
"lib_name": "The third pard library name, use the os file-naming conventions",
"common_proj_name": "The project name, use the os file-naming conventions",
"common_app_name": "The mobile application name, use the os file-naming conventions",
"form": "Directions",
"desc": "Description",
"detail": "Detailed parameters",
"info0": "The Egret version, and install path",
"upgrade0": "Upgrade you project when the Egret engine is update",
"ss0": "Start the Egret server, and run your project in browser",
"ss1": "Set the port number",
"ss2": "Whether to use the local IP",
"ss3": "Whether only run the server",
"create_manifest0": "Make a file list manifest.json in the project folder",
"create_manifest1": "Make a file list for all of files in project, if not assigned, only for used files",
"create_app1": "The path of a app project corresponding a H5 project",
"create_app2": "The path of the template",
"pub1": "Publish your project,ues GoogleClosureCompiler to compress the code",
"pub3": "The version after publish, not must be set",
"pub4": "Release to html5 or native, html5 is the default type",
"pub5": "Whether to compress the js code after publish",
"pub6": "Set a password when release to a zip file",
"create1": "Create a new project",
"create2": "The type of the new project, core or eui, core is the default type.",
"create_lib1": "Create a new third part library",
"build0": "Compile the TypeScript files in project.",
"build1": "Compile the TypeScript files in project and copy the Egret engine code",
"build2": "Clean the libs and bin-debug files, it works when use the -e parameter",
//,"build3":"只编译引擎中指定的部分模块,不编译项目;不填则编译全部模块",
"build4": "Compile the exml files and create the ts files",
"build5": "If the native project is exist, it will also be copy to the native project",
//,"build6":"编译游戏时,根据game_file_list获取编译列表",
"build7": "Show the execuing procedure",
"clean": "Clean the code in libs folder, copy these files again, and compile the project"
};
export var help_title = {
//titles,
"create": "Create a new project",
"build": "Compile the TypeScript files in project",
"publish": "Publish the project, ues GoogleClosureCompiler to compress the code",
"run": "Start HttpServer, run the project in you browser",
"clean": "Reset the Egret engin code in the project",
"create_lib": "Create a new third part library",
"create_app": "Create a native app form Html5",
"upgrade": "Upgrade the project code",
"make": "Rebuild the Egret engine source code",
"info": "Get information of the Egret engine"
};
global["helpModule"] = global["helpModule"] || helpModule;
//global["helpModule"]["help_dict"] = help_dict;
} | the_stack |
import * as assert from "assert";
import * as fs from "fs/promises";
import * as G from "glob";
import * as path from "path";
const verbose = process.argv.includes("--verbose");
const moduleCommentRe =
new RegExp(String.raw`\/\*\*\n` // start of doc comment
+ String.raw`((?: \*(?:\n| .+\n))+?)` // #1: doc comment
+ String.raw` \*\/\n` // end of doc comment
+ String.raw`declare module \"(.+?)\"`, // #2: module name
"m");
const docCommentRe =
new RegExp(String.raw`^( *)` // #1: indentation
+ String.raw`\/\*\*\n` // start of doc comment
+ String.raw`((?:\1 \*(?:\n| .+\n))+?)` // #2: doc comment
+ String.raw`\1 \*\/\n` // end of doc comment
+ String.raw`\1export (?:async )?function (\w+)` // #3: function name
+ String.raw`\((.*|\n[\s\S]+?^\1)\)` // #4: parameters
+ String.raw`(?:: )?(.+)[;{]$` // #5: return type (optional)
+ "|" // or
+ String.raw`^ *export namespace (\w+) {\n` // #6: namespace (alternative)
+ String.raw`^( +)`, // #7: namespace indentation
"gm");
function countNewLines(text: string) {
let count = 0;
for (let i = 0; i < text.length; i++) {
if (text.charCodeAt(i) === 10 /* \n */) {
count++;
}
}
return count;
}
const keyMapping: Record<string, keyof Builder.AdditionalCommand> = {
Command: "commands",
Commands: "commands",
Identifier: "identifier",
Identifiers: "identifier",
Keys: "keys",
Keybinding: "keys",
Keybindings: "keys",
Title: "title",
};
const valueConverter: Record<keyof Builder.AdditionalCommand, (x: string) => string> = {
commands(commands) {
return commands
.replace(/^`+|`+$/g, "")
.replace(/MAX_INT/g, `${2 ** 31 - 1}`); // Max integer supported in JSON.
},
identifier(identifier) {
return identifier.replace(/^`+|`+$/g, "");
},
keys(keys) {
return keys;
},
title(title) {
return title;
},
qualifiedIdentifier(qualifiedIdentifier) {
return qualifiedIdentifier;
},
line() {
throw new Error("this should not be called");
},
};
function parseAdditional(qualificationPrefix: string, text: string, textStartLine: number) {
const lines = text.split("\n"),
additional: Builder.AdditionalCommand[] = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (line.length > 2 && line.startsWith("| ") && line.endsWith(" |")) {
const keys = line
.slice(2, line.length - 2) // Remove start and end |.
.split(" | ") // Split into keys.
.map((k) => keyMapping[k.trim()]); // Normalize keys.
i++;
if (/^\|[-| ]+\|$/.test(lines[i])) {
i++;
}
while (i < lines.length) {
const line = lines[i];
if (!line.startsWith("| ") || !line.endsWith(" |")) {
break;
}
i++;
const obj: Builder.AdditionalCommand = { line: textStartLine + i },
values = line.slice(2, line.length - 2).split(" | ");
for (let j = 0; j < values.length; j++) {
const key = keys[j],
value = valueConverter[key](values[j].trim());
(obj as Record<string, any>)[key] = value;
}
if ("identifier" in obj) {
obj.qualifiedIdentifier = qualificationPrefix + obj.identifier;
}
additional.push(obj);
}
}
}
return additional;
}
/**
* Parses all the doc comments of functions in the given string of TypeScript
* code. Examples will be parsed using the given function.
*/
function parseDocComments(code: string, modulePath: string) {
let moduleDoc: string,
moduleDocStartLine: number,
moduleName: string;
const moduleHeaderMatch = moduleCommentRe.exec(code);
if (moduleHeaderMatch !== null) {
moduleDoc = moduleHeaderMatch[1].split("\n").map((line) => line.slice(3)).join("\n");
moduleDocStartLine = code.slice(0, moduleHeaderMatch.index).split("\n").length + 2;
moduleName = moduleHeaderMatch[2].replace(/^\.\//, "");
} else {
moduleDoc = "";
moduleDocStartLine = 0;
moduleName = path.basename(modulePath, ".ts");
}
if (verbose) {
console.log("Parsing doc comments in module", moduleName);
}
const modulePrefix = moduleName === "misc" ? "" : moduleName + ".";
const functions: Builder.ParsedFunction[] = [],
namespaces: string[] = [];
let previousIndentation = 0;
for (let match = docCommentRe.exec(code); match !== null; match = docCommentRe.exec(code)) {
const indentationString = match[1],
docCommentString = match[2],
functionName = match[3],
parametersString = match[4],
returnTypeString = match[5],
enteredNamespace = match[6],
enteredNamespaceIndentation = match[7],
startLine = countNewLines(code.slice(0, match.index)),
endLine = startLine + countNewLines(match[0]);
if (enteredNamespace !== undefined) {
namespaces.push(enteredNamespace);
previousIndentation = enteredNamespaceIndentation.length;
continue;
}
const indentation = indentationString.length,
namespace = namespaces.length === 0 ? undefined : namespaces.join("."),
returnType = returnTypeString.trim(),
parameters = parametersString
.split(/,(?![^:]+?[}>])/g)
.map((p) => p.trim())
.filter((p) => p.length > 0)
.map((p) => {
let match: RegExpExecArray | null;
if (match = /^(\w+\??|.+[}\]]): *(.+)$/.exec(p)) {
return match.slice(1) as [string, string];
}
if (match = /^(\w+) *= *(\d+|true|false)$/.exec(p)) {
const type = match[2] === "true" || match[2] === "false"
? "Argument<boolean>"
: "number";
return [match[1], `${type} = ${match[2]}`] as [string, string];
}
if (match = /^(\w+) *= *(\w+)\.([\w.]+)$/.exec(p)) {
return [match[1], `${match[2]} = ${match[2]}.${match[3]}`] as [string, string];
}
if (match = /^(\.\.\.\w+): *(.+)$/.exec(p)) {
return [match[1], match[2]] as [string, string];
}
throw new Error(`unrecognized parameter pattern ${p}`);
}),
docComment = docCommentString
.split("\n")
.map((line) => line.slice(indentation).replace(/^ \* ?/g, ""))
.join("\n");
if (previousIndentation > indentation) {
namespaces.pop();
previousIndentation = indentation;
}
for (const parameter of parameters) {
if (parameter[0].endsWith("?")) {
// Optional parameters.
parameter[0] = parameter[0].slice(0, parameter[0].length - 1);
parameter[1] += " | undefined";
} else {
const match = /^(.+?)\s+=\s+(.+)$/.exec(parameter[1]);
if (match !== null) {
// Optional parameters with default values.
parameter[1] = match[1] + " | undefined";
}
}
}
const splitDocComment = docComment.split(/\n### Example\n/gm),
properties: Record<string, string> = {},
doc = splitDocComment[0].replace(/^@(param \w+|\w+)(?:\n| ((?:.+\n)(?: {2}.+\n)*))/gm,
(_, k: string, v: string) => {
properties[k] = v?.replace(/\n {2}/g, " ").trim();
return "";
}),
summary = /((?:.+(?:\n|$))+)/.exec(doc)![0].trim().replace(/\.$/, ""),
examplesStrings = splitDocComment.slice(1),
nameWithDot = functionName.replace(/_/g, ".");
let qualifiedName = modulePrefix;
if (namespace !== undefined) {
qualifiedName += namespace + ".";
}
if (nameWithDot === moduleName) {
qualifiedName = qualifiedName.replace(/\.$/, "");
} else {
qualifiedName += nameWithDot;
}
functions.push({
namespace,
name: functionName,
nameWithDot,
qualifiedName,
startLine,
endLine,
doc,
properties,
summary,
examples: examplesStrings,
additional: parseAdditional(modulePrefix, splitDocComment[0], startLine),
parameters,
returnType: returnType.length === 0 ? undefined : returnType,
});
}
docCommentRe.lastIndex = 0;
return {
path: path.relative(path.dirname(__dirname), modulePath).replace(/\\/g, "/"),
name: moduleName,
doc: moduleDoc,
additional: parseAdditional(modulePrefix, moduleDoc, moduleDocStartLine),
functions,
functionNames: [...new Set(functions.map((f) => f.name))],
get commands() {
return getCommands(this);
},
get keybindings() {
return getKeybindings(this);
},
} as Builder.ParsedModule;
}
/**
* Mapping from character to corresponding VS Code keybinding.
*/
export const specialCharacterMapping = {
"~": "s-`",
"!": "s-1",
"@": "s-2",
"#": "s-3",
"$": "s-4",
"%": "s-5",
"^": "s-6",
"&": "s-7",
"*": "s-8",
"(": "s-9",
")": "s-0",
"_": "s--",
"+": "s-=",
"{": "s-[",
"}": "s-]",
"|": "s-\\",
":": "s-;",
'"': "s-'",
"<": "s-,",
">": "s-.",
"?": "s-/",
};
/**
* RegExp for keys of `specialCharacterMapping`.
*/
export const specialCharacterRegExp = /[~!@#$%^&*()_+{}|:"<>?]/g;
/**
* Async wrapper around the `glob` package.
*/
export function glob(pattern: string, ignore?: string) {
return new Promise<string[]>((resolve, reject) => {
G(pattern, { ignore }, (err, matches) => err ? reject(err) : resolve(matches));
});
}
/**
* A class used in .build.ts files.
*/
export class Builder {
private _apiModules?: Builder.ParsedModule[];
private _commandModules?: Builder.ParsedModule[];
/**
* Returns all modules for API files.
*/
public async getApiModules() {
if (this._apiModules !== undefined) {
return this._apiModules;
}
const apiFiles = await glob(`${__dirname}/src/api/**/*.ts`, /* ignore= */ "**/*.build.ts"),
apiModules = await Promise.all(
apiFiles.map((filepath) =>
fs.readFile(filepath, "utf-8").then((code) => parseDocComments(code, filepath))));
return this._apiModules = apiModules.sort((a, b) => a.name.localeCompare(b.name));
}
/**
* Returns all modules for command files.
*/
public async getCommandModules() {
if (this._commandModules !== undefined) {
return this._commandModules;
}
const commandsGlob = `${__dirname}/src/commands/**/*.ts`,
commandFiles = await glob(commandsGlob, /* ignore= */ "**/*.build.ts"),
allCommandModules = await Promise.all(
commandFiles.map((filepath) =>
fs.readFile(filepath, "utf-8").then((code) => parseDocComments(code, filepath)))),
commandModules = allCommandModules.filter((m) => m.doc.length > 0);
return this._commandModules = commandModules.sort((a, b) => a.name.localeCompare(b.name));
}
}
export namespace Builder {
export interface ParsedFunction {
readonly namespace?: string;
readonly name: string;
readonly nameWithDot: string;
readonly qualifiedName: string;
readonly startLine: number;
readonly endLine: number;
readonly doc: string;
readonly properties: Record<string, string>;
readonly summary: string;
readonly examples: string[];
readonly additional: AdditionalCommand[];
readonly parameters: readonly [name: string, type: string][];
readonly returnType: string | undefined;
}
export interface AdditionalCommand {
title?: string;
identifier?: string;
qualifiedIdentifier?: string;
keys?: string;
commands?: string;
line: number;
}
export interface ParsedModule {
readonly path: string;
readonly name: string;
readonly doc: string;
readonly additional: readonly AdditionalCommand[];
readonly functions: readonly ParsedFunction[];
readonly functionNames: readonly string[];
readonly commands: {
readonly id: string;
readonly title: string;
readonly when?: string;
}[];
readonly keybindings: {
readonly title?: string;
readonly key: string;
readonly when: string;
readonly command: string;
readonly args?: any;
}[];
}
}
/**
* Parses the short "`s-a-b` (mode)"-like syntax for defining keybindings into
* a format compatible with VS Code keybindings.
*/
export function parseKeys(keys: string) {
if (keys.length === 0) {
return [];
}
return keys.split(/ *, (?=`)/g).map((keyString) => {
const match = /^(`+)(.+?)\1 \((.+?)\)$/.exec(keyString)!,
keybinding = match[2].trim().replace(
specialCharacterRegExp, (m) => (specialCharacterMapping as Record<string, string>)[m]);
// Reorder to match Ctrl+Shift+Alt+_
let key = "";
if (keybinding.includes("c-")) {
key += "Ctrl+";
}
if (keybinding.includes("s-")) {
key += "Shift+";
}
if (keybinding.includes("a-")) {
key += "Alt+";
}
const remainingKeybinding = keybinding.replace(/[csa]-/g, ""),
whenClauses = ["editorTextFocus"];
for (const tag of match[3].split(", ")) {
switch (tag) {
case "normal":
case "insert":
case "input":
whenClauses.push(`dance.mode == '${tag}'`);
break;
case "recording":
whenClauses.push("dance.isRecording");
break;
case "prompt":
whenClauses.shift(); // Remove "editorTextFocus" clause.
whenClauses.push("inputFocus && !textInputFocus");
break;
default:
throw new Error("unknown keybinding tag " + tag);
}
}
key += remainingKeybinding[0].toUpperCase() + remainingKeybinding.slice(1);
return {
key,
when: whenClauses.join(" && "),
};
});
}
/**
* Returns all defined commands in the given module.
*/
function getCommands(module: Omit<Builder.ParsedModule, "commands">) {
// TODO: improve conditions
return [
...module.functions.map((f) => ({
id: `dance.${f.qualifiedName}`,
title: f.summary,
when: "dance.mode == 'normal'",
})),
...module.additional
.concat(...module.functions.flatMap((f) => f.additional))
.filter((a) => a.identifier !== undefined && a.title !== undefined)
.map((a) => ({
id: `dance.${a.qualifiedIdentifier}`,
title: a.title!,
when: "dance.mode == 'normal'",
})),
].sort((a, b) => a.id.localeCompare(b.id));
}
/**
* Returns all defined keybindings in the given module.
*/
function getKeybindings(module: Omit<Builder.ParsedModule, "keybindings">) {
return [
...module.functions.flatMap((f) => parseKeys(f.properties.keys ?? "").map((key) => ({
...key,
title: f.summary,
command: `dance.${f.qualifiedName}`,
}))),
...module.additional
.concat(...module.functions.flatMap((f) => f.additional))
.flatMap(({ title, keys, commands, qualifiedIdentifier }) => {
const parsedKeys = parseKeys(keys ?? "");
if (qualifiedIdentifier !== undefined) {
return parsedKeys.map((key) => ({
...key,
title,
command: `dance.${qualifiedIdentifier}`,
}));
}
const parsedCommands =
JSON.parse("[" + commands!.replace(/(\w+):/g, "\"$1\":") + "]") as any[];
if (parsedCommands.length === 1) {
let [command]: [string] = parsedCommands[0];
if (command[0] === ".") {
command = "dance" + command;
}
return parsedKeys.map((key) => ({
...key,
title,
command,
args: parsedCommands[0][1],
}));
}
return parsedKeys.map((key) => ({
...key,
title,
command: "dance.run",
args: {
commands: parsedCommands,
},
}));
}),
].sort((a, b) => a.command.localeCompare(b.command));
}
/**
* Given a multiline string, returns the same string with all lines starting
* with an indentation `>= by` reduced by `by` spaces.
*/
export function unindent(by: number, string: string) {
return string.replace(new RegExp(`^ {${by}}`, "gm"), "").replace(/^ +$/gm, "");
}
/**
* Given a multiline string, returns the same string with all lines further
* indented by `by` spaces.
*/
export function indent(by: number, string: string) {
return string.replace(/^/gm, " ".repeat(by)).replace(/^ +$/gm, "");
}
/**
* Updates a .build.ts file.
*/
async function buildFile(fileName: string, builder: Builder) {
const relativeName = path.relative(__dirname, fileName),
relativeNameWithoutBuild = relativeName.replace(/build\.ts$/, ""),
modulePath = `./${relativeNameWithoutBuild}build`;
// Clear module cache if any.
delete require.cache[require.resolve(modulePath)];
const module: { build(builder: Builder): Promise<string> } = require(modulePath),
generatedContent = await module.build(builder);
if (typeof generatedContent === "string") {
// Write result of `build` to the first file we find that has the same name
// as the build.ts file, but with any extension.
const prefix = path.basename(relativeNameWithoutBuild),
outputName = (await fs.readdir(path.dirname(fileName)))
.find((path) => path.startsWith(prefix) && !path.endsWith(".build.ts"))!,
outputPath = path.join(path.dirname(fileName), outputName),
outputContent = await fs.readFile(outputPath, "utf-8"),
outputContentHeader =
/^[\s\S]+?\n.+Content below this line was auto-generated.+\n/m.exec(outputContent)![0];
await fs.writeFile(outputPath, outputContentHeader + generatedContent, "utf-8");
}
}
/**
* The main entry point of the script.
*/
async function main() {
let success = true;
const ensureUpToDate = process.argv.includes("--ensure-up-to-date"),
check = process.argv.includes("--check"),
buildIndex = process.argv.indexOf("--build"),
build = buildIndex === -1 ? "**/*.build.ts" : process.argv[buildIndex + 1];
const contentsBefore: string[] = [],
fileNames = [
`${__dirname}/package.json`,
`${__dirname}/src/commands/README.md`,
`${__dirname}/src/commands/index.ts`,
];
if (ensureUpToDate) {
contentsBefore.push(...await Promise.all(fileNames.map((name) => fs.readFile(name, "utf-8"))));
}
const builder = new Builder(),
filesToBuild = await glob(__dirname + "/" + build),
buildErrors: unknown[] = [];
await Promise.all(
filesToBuild.map((path) => buildFile(path, builder).catch((e) => buildErrors.push(e))));
if (buildErrors.length > 0) {
console.error(buildErrors);
}
if (ensureUpToDate) {
const contentsAfter = await Promise.all(fileNames.map((name) => fs.readFile(name, "utf-8")));
for (let i = 0; i < fileNames.length; i++) {
if (verbose) {
console.log("Checking file", fileNames[i], "for diffs...");
}
// The built-in "assert" module displays a multiline diff if the strings
// are different, so we use it instead of comparing manually.
assert.strictEqual(contentsBefore[i], contentsAfter[i]);
}
}
if (check) {
const filesToCheck = await glob(
`${__dirname}/src/commands/**/*.ts`, /* ignore= */ "**/*.build.ts"),
contentsToCheck = await Promise.all(filesToCheck.map((f) => fs.readFile(f, "utf-8")));
for (let i = 0; i < filesToCheck.length; i++) {
const fileToCheck = filesToCheck[i],
contentToCheck = contentsToCheck[i];
if (contentToCheck.includes("editor.selections")) {
console.error("File", fileToCheck, "includes forbidden access to editor.selections.");
success = false;
}
}
}
return success;
}
if (require.main === module) {
main().then((success) => {
if (!process.argv.includes("--watch")) {
process.exit(success ? 0 : 1);
}
import("chokidar").then((chokidar) => {
const watcher = chokidar.watch([
"**/*.build.ts",
"src/api/*.ts",
"src/commands/*.ts",
"test/suite/commands/*.md",
], {
ignored: "src/commands/load-all.ts",
});
let isGenerating = false;
watcher.on("change", async (path) => {
if (isGenerating) {
return;
}
console.log("Change detected at " + path + ", updating generated files...");
isGenerating = true;
try {
await main();
} finally {
isGenerating = false;
}
});
});
});
} | the_stack |
import {
RowSpanAttributeValue,
PageOptions,
Row,
ListItem,
RowKey,
RowSpan,
CellRenderData,
RowSpanMap,
ViewRow,
Data,
SortState,
RawRowOptions,
} from '@t/store/data';
import { Column, ColumnInfo, ErrorInfo } from '@t/store/column';
import { Filter } from '@t/store/filterLayerState';
import { OptRow, Dictionary } from '@t/options';
import { Range } from '@t/store/selection';
import { observable, observe } from '../helper/observable';
import { isRowHeader, isRowNumColumn, isCheckboxColumn } from '../helper/column';
import {
someProp,
isUndefined,
isBoolean,
isEmpty,
isNumber,
isFunction,
assign,
isNull,
isNil,
} from '../helper/common';
import { createTreeRawData, createTreeCellInfo } from './helper/tree';
import { addUniqueInfoMap, getValidationCode } from './helper/validation';
import { isScrollPagination } from '../query/data';
import { getFormattedValue, setMaxTextMap } from './helper/data';
import {
DEFAULT_PER_PAGE,
DISABLED_PRIORITY_CELL,
DISABLED_PRIORITY_COLUMN,
DISABLED_PRIORITY_NONE,
DISABLED_PRIORITY_ROW,
} from '../helper/constant';
interface DataOption {
data: OptRow[];
column: Column;
pageOptions: PageOptions;
useClientSort: boolean;
id: number;
disabled: boolean;
}
interface DataCreationOption {
lazyObservable?: boolean;
prevRows?: Row[];
disabled?: boolean;
}
interface RelationInfo {
relationMatched?: boolean;
relationListItems?: ListItem[];
}
interface ViewCellInfo {
columnMap: Dictionary<ColumnInfo>;
valueMap: Dictionary<CellRenderData>;
}
interface ViewCellCreationOpt {
isDataModified?: boolean;
prevInvalidStates?: ErrorInfo[];
relationInfo?: RelationInfo;
}
let dataCreationKey = '';
export function generateDataCreationKey() {
dataCreationKey = `@dataKey${Date.now()}`;
return dataCreationKey;
}
function getRelationCbResult(fn: any, relationParams: Dictionary<any>) {
const result = isFunction(fn) ? fn(relationParams) : null;
return isUndefined(result) ? null : result;
}
function getEditable(fn: any, relationParams: Dictionary<any>): boolean {
const result = getRelationCbResult(fn, relationParams);
return result === null ? true : result;
}
function getDisabled(fn: any, relationParams: Dictionary<any>): boolean {
const result = getRelationCbResult(fn, relationParams);
return result === null ? false : result;
}
function getListItems(fn: any, relationParams: Dictionary<any>): ListItem[] {
return getRelationCbResult(fn, relationParams) || [];
}
function getRowHeaderValue(row: Row, columnName: string) {
if (isRowNumColumn(columnName)) {
return row._attributes.rowNum;
}
if (isCheckboxColumn(columnName)) {
return row._attributes.checked;
}
return '';
}
export function createRowSpan(
mainRow: boolean,
rowKey: RowKey,
count: number,
spanCount: number
): RowSpan {
return { mainRow, mainRowKey: rowKey, count, spanCount };
}
function createViewCell(
id: number,
row: Row,
column: ColumnInfo,
{ isDataModified = false, prevInvalidStates, relationInfo = {} }: ViewCellCreationOpt
): CellRenderData {
const { relationMatched = true, relationListItems } = relationInfo;
const { name, formatter, editor, validation, defaultValue } = column;
let value = isRowHeader(name) ? getRowHeaderValue(row, name) : row[name];
if (isNil(value) && !isNil(defaultValue)) {
value = defaultValue;
}
if (!relationMatched) {
value = '';
}
const formatterProps = { row, column, value };
const { disabled, checkDisabled, className: classNameAttr } = row._attributes;
const columnDisabled = !!column.disabled;
const rowDisabled = isCheckboxColumn(name) ? checkDisabled : disabled;
const columnClassName = isUndefined(classNameAttr.column[name]) ? [] : classNameAttr.column[name];
const className = [...classNameAttr.row, ...columnClassName].join(' ');
const _disabledPriority = row._disabledPriority[name];
let cellDisabled = rowDisabled || columnDisabled;
if (_disabledPriority === DISABLED_PRIORITY_CELL) {
cellDisabled = true;
} else if (_disabledPriority === DISABLED_PRIORITY_NONE) {
cellDisabled = false;
} else if (_disabledPriority === DISABLED_PRIORITY_COLUMN) {
cellDisabled = columnDisabled;
} else if (_disabledPriority === DISABLED_PRIORITY_ROW) {
cellDisabled = rowDisabled;
}
const usePrevInvalidStates = !isDataModified && !isNil(prevInvalidStates);
const invalidStates = usePrevInvalidStates
? (prevInvalidStates as ErrorInfo[])
: getValidationCode({ id, value: row[name], row, validation, columnName: name });
return {
editable: !!editor,
className,
disabled: cellDisabled,
invalidStates,
formattedValue: getFormattedValue(formatterProps, formatter, value, relationListItems),
value,
};
}
function createRelationViewCell(
id: number,
name: string,
row: Row,
{ columnMap, valueMap }: ViewCellInfo
) {
const { editable, disabled, value } = valueMap[name];
const { relationMap = {} } = columnMap[name];
Object.keys(relationMap).forEach((targetName) => {
const {
editable: editableCallback,
disabled: disabledCallback,
listItems: listItemsCallback,
} = relationMap[targetName];
const relationCbParams = { value, editable, disabled, row };
const targetEditable = getEditable(editableCallback, relationCbParams);
const targetDisabled = getDisabled(disabledCallback, relationCbParams);
const targetListItems = getListItems(listItemsCallback, relationCbParams);
const targetValue = row[targetName];
const targetEditor = columnMap[targetName].editor;
const targetEditorOptions = targetEditor?.options;
const relationMatched = isFunction(listItemsCallback)
? someProp('value', targetValue, targetListItems)
: true;
const cellData = createViewCell(id, row, columnMap[targetName], {
relationInfo: {
relationMatched,
relationListItems: targetListItems,
},
});
if (!targetEditable) {
cellData.editable = false;
}
if (targetDisabled) {
cellData.disabled = true;
}
// should set the relation list to relationListItemMap for preventing to share relation list in other rows
if (targetEditorOptions) {
targetEditorOptions.relationListItemMap = targetEditorOptions.relationListItemMap || {};
targetEditorOptions.relationListItemMap[row.rowKey] = targetListItems;
}
valueMap[targetName] = cellData;
});
}
export function createViewRow(id: number, row: Row, rawData: Row[], column: Column) {
const { rowKey, sortKey, rowSpanMap, uniqueKey } = row;
const { columnMapWithRelation: columnMap } = column;
const { treeColumnName, treeIcon = true, treeIndentWidth } = column;
const initValueMap: Dictionary<CellRenderData | null> = {};
Object.keys(columnMap).forEach((name) => {
initValueMap[name] = null;
});
const cachedValueMap: Dictionary<CellRenderData> = {};
const valueMap = observable(initValueMap) as Dictionary<CellRenderData>;
const __unobserveFns__: Function[] = [];
Object.keys(columnMap).forEach((name) => {
const { related, relationMap, className } = columnMap[name];
if (className) {
row._attributes.className.column[name] = className.split(' ');
}
// add condition expression to prevent to call watch function recursively
if (!related) {
__unobserveFns__.push(
observe((calledBy: string) => {
const isDataModified = calledBy !== 'className';
cachedValueMap[name] = createViewCell(id, row, columnMap[name], {
isDataModified,
prevInvalidStates: cachedValueMap[name]?.invalidStates,
});
valueMap[name] = cachedValueMap[name];
})
);
}
if (relationMap && Object.keys(relationMap).length) {
__unobserveFns__.push(
observe(() => {
createRelationViewCell(id, name, row, { columnMap, valueMap });
})
);
}
});
return {
rowKey,
sortKey,
uniqueKey,
rowSpanMap,
valueMap,
__unobserveFns__,
...(treeColumnName && {
treeInfo: createTreeCellInfo(rawData, row, treeIndentWidth, treeIcon),
}),
};
}
function getAttributes(row: OptRow, index: number, lazyObservable: boolean, disabled: boolean) {
const defaultAttr = {
rowNum: index + 1,
checked: false,
disabled,
checkDisabled: disabled,
className: {
row: [],
column: {},
},
};
if (row._attributes) {
if (isBoolean(row._attributes.disabled) && isUndefined(row._attributes.checkDisabled)) {
row._attributes.checkDisabled = row._attributes.disabled;
}
if (!isUndefined(row._attributes.className)) {
row._attributes.className = {
row: [],
column: {},
...row._attributes.className,
};
}
}
const attributes = { ...defaultAttr, ...row._attributes };
return lazyObservable ? attributes : observable(attributes);
}
function createRelationListItems(name: string, row: Row, columnMap: Dictionary<ColumnInfo>) {
const { relationMap = {}, editor } = columnMap[name];
const { checkDisabled, disabled: rowDisabled } = row._attributes;
const editable = !!editor;
const disabled = isCheckboxColumn(name) ? checkDisabled : rowDisabled;
const value = row[name];
const relationCbParams = { value, editable, disabled, row };
const relationListItemMap: Dictionary<ListItem[]> = {};
Object.keys(relationMap).forEach((targetName) => {
relationListItemMap[targetName] = getListItems(
relationMap[targetName].listItems,
relationCbParams
);
});
return relationListItemMap;
}
export function setRowRelationListItems(row: Row, columnMap: Dictionary<ColumnInfo>) {
const relationListItemMap = { ...row._relationListItemMap };
Object.keys(columnMap).forEach((name) => {
assign(relationListItemMap, createRelationListItems(name, row, columnMap));
});
row._relationListItemMap = relationListItemMap;
}
function createMainRowSpanMap(rowSpan: RowSpanAttributeValue, rowKey: RowKey) {
const mainRowSpanMap: RowSpanMap = {};
if (!rowSpan) {
return mainRowSpanMap;
}
Object.keys(rowSpan).forEach((columnName) => {
const spanCount = rowSpan[columnName];
mainRowSpanMap[columnName] = createRowSpan(true, rowKey, spanCount, spanCount);
});
return mainRowSpanMap;
}
function createSubRowSpan(prevRowSpanMap: RowSpanMap) {
const subRowSpanMap: RowSpanMap = {};
Object.keys(prevRowSpanMap).forEach((columnName) => {
const prevRowSpan = prevRowSpanMap[columnName];
const { mainRowKey, count, spanCount } = prevRowSpan;
if (spanCount > 1 - count) {
const subRowCount = count >= 0 ? -1 : count - 1;
subRowSpanMap[columnName] = createRowSpan(false, mainRowKey, subRowCount, spanCount);
}
});
return subRowSpanMap;
}
function createRowSpanMap(row: OptRow, rowSpan: RowSpanAttributeValue, prevRow?: Row) {
const rowKey = row.rowKey as RowKey;
let mainRowSpanMap: RowSpanMap = {};
let subRowSpanMap: RowSpanMap = {};
if (!isEmpty(rowSpan)) {
mainRowSpanMap = createMainRowSpanMap(rowSpan, rowKey);
}
if (prevRow) {
const { rowSpanMap: prevRowSpanMap } = prevRow;
if (!isEmpty(prevRowSpanMap)) {
subRowSpanMap = createSubRowSpan(prevRowSpanMap);
}
}
return { ...mainRowSpanMap, ...subRowSpanMap };
}
export function createRawRow(
id: number,
row: OptRow,
index: number,
column: Column,
options: RawRowOptions = {}
) {
// this rowSpan variable is attribute option before creating rowSpanDataMap
const rowSpan = row._attributes?.rowSpan as RowSpanAttributeValue;
const { keyColumnName, prevRow, lazyObservable = false, disabled = false } = options;
if (keyColumnName) {
row.rowKey = row[keyColumnName];
} else if (isUndefined(row.rowKey)) {
row.rowKey = index;
}
row.sortKey = isNumber(row.sortKey) ? row.sortKey : index;
row.uniqueKey = `${dataCreationKey}-${row.rowKey}`;
row._attributes = getAttributes(row, index, lazyObservable, disabled);
row._attributes.rowSpan = rowSpan;
row._disabledPriority = row._disabledPriority || {};
(row as Row).rowSpanMap = (row as Row).rowSpanMap ?? createRowSpanMap(row, rowSpan, prevRow);
setRowRelationListItems(row as Row, column.columnMapWithRelation);
if (column.autoResizingColumn.length) {
setMaxTextMap(column, row as Row);
}
if (lazyObservable) {
addUniqueInfoMap(id, row, column);
}
return (lazyObservable ? row : observable(row)) as Row;
}
export function createData(
id: number,
data: OptRow[],
column: Column,
{ lazyObservable = false, prevRows, disabled = false }: DataCreationOption
) {
generateDataCreationKey();
const { keyColumnName, treeColumnName = '' } = column;
let rawData: Row[];
// Notify when using deprecated option "_attribute.rowSpan".
const isUseRowSpanOption = data.some((row) => row._attributes?.rowSpan);
if (isUseRowSpanOption) {
// eslint-disable-next-line no-console
console.warn(
'The option "_attribute.rowSpan" is deprecated. Please use rowSpan option of column.\nFollow example: http://nhn.github.io/tui.grid/latest/tutorial-example29-dynamic-row-span'
);
}
if (treeColumnName) {
rawData = createTreeRawData({
id,
data,
column,
keyColumnName,
lazyObservable,
disabled,
});
} else {
rawData = data.map((row, index, rows) =>
createRawRow(id, row, index, column, {
keyColumnName,
prevRow: prevRows ? prevRows[index] : (rows[index - 1] as Row),
lazyObservable,
disabled,
})
);
}
const viewData = rawData.map((row: Row) =>
lazyObservable
? ({ rowKey: row.rowKey, sortKey: row.sortKey, uniqueKey: row.uniqueKey } as ViewRow)
: createViewRow(id, row, rawData, column)
);
return { rawData, viewData };
}
let cachedFilteredIndex: Record<RowKey, number | null> = {};
function applyFilterToRawData(
rawData: Row[],
filters: Filter[] | null,
columnMap: Dictionary<ColumnInfo>
) {
let data = rawData;
cachedFilteredIndex = {};
if (filters) {
data = filters.reduce((acc: Row[], filter: Filter) => {
const { conditionFn, columnName } = filter;
const { formatter } = columnMap[columnName];
return acc.filter((row, index) => {
const value = row[columnName];
const relationListItems = row._relationListItemMap[columnName];
const formatterProps = { row, column: columnMap[columnName], value };
const filtered = conditionFn!(
getFormattedValue(formatterProps, formatter, value, relationListItems)
);
// cache the filtered index for performance
if (acc === rawData && filtered) {
cachedFilteredIndex[row.rowKey] = index;
} else if (!filtered) {
cachedFilteredIndex[row.rowKey] = null;
}
return filtered;
});
}, rawData);
}
return data;
}
function createPageOptions(userPageOptions: PageOptions, rawData: Row[]) {
const pageOptions = (isEmpty(userPageOptions)
? {}
: {
useClient: false,
page: 1,
perPage: DEFAULT_PER_PAGE,
type: 'pagination',
...userPageOptions,
totalCount: userPageOptions.useClient ? rawData.length : userPageOptions.totalCount!,
}) as Required<PageOptions>;
if (pageOptions.type === 'pagination') {
pageOptions.position = pageOptions.position || 'bottom';
pageOptions.visiblePages = pageOptions.visiblePages || 10;
}
return pageOptions;
}
export function create({
data,
column,
pageOptions: userPageOptions,
useClientSort,
disabled,
id,
}: DataOption) {
const { rawData, viewData } = createData(id, data, column, { lazyObservable: true, disabled });
const sortState: SortState = {
useClient: useClientSort,
columns: [
{
columnName: 'sortKey',
ascending: true,
},
],
};
const pageOptions = createPageOptions(userPageOptions, rawData);
return observable({
rawData,
viewData,
sortState,
pageOptions,
checkedAllRows: rawData.length ? !rawData.some((row) => !row._attributes.checked) : false,
disabledAllCheckbox: disabled,
filters: null,
loadingState: rawData.length ? 'DONE' : 'EMPTY',
clickedCheckboxRowkey: null,
get filteredRawData() {
if (this.filters) {
// should filter the sliced data which is displayed in viewport in case of client infinite scrolling
const targetData = isScrollPagination(this, true)
? this.rawData.slice(...this.pageRowRange)
: this.rawData;
return applyFilterToRawData(targetData, this.filters, column.allColumnMap);
}
return this.rawData;
},
get filteredIndex() {
const { filteredRawData, filters } = this;
return filters
? filteredRawData
.filter((row) => !isNull(cachedFilteredIndex[row.rowKey]))
.map((row) => cachedFilteredIndex[row.rowKey]!)
: null;
},
get filteredViewData() {
return this.filters
? this.filteredIndex!.map((index) => this.viewData[index])
: this.viewData;
},
get pageRowRange() {
const { useClient, type, page, perPage } = this.pageOptions;
let start = 0;
// should calculate the range through all rawData in case of client infinite scrolling
let end = isScrollPagination(this, true) ? this.rawData.length : this.filteredViewData.length;
if (useClient) {
const pageRowLastIndex = page * perPage;
if (type === 'pagination') {
start = (page - 1) * perPage;
}
end = pageRowLastIndex > 0 && pageRowLastIndex < end ? pageRowLastIndex : end;
}
return [start, end] as Range;
},
} as Data);
} | the_stack |
import { expect } from "chai";
import { ClipVector, Point3d, Transform } from "@itwin/core-geometry";
import { ClipVolume } from "../../../render/webgl/ClipVolume";
import { ClipStack } from "../../../render/webgl/ClipStack";
import { RenderSystem } from "../../../render/RenderSystem";
import { IModelApp } from "../../../IModelApp";
for (let i = 0; i < 2; i++) {
let renderSys: RenderSystem.Options | undefined;
const useFloat = i > 0;
if (!useFloat) {
renderSys = {
useWebGL2: false,
disabledExtensions: ["OES_texture_float"],
};
}
function createClipVector(offset = 0): ClipVector {
const clip = ClipVector.createEmpty();
clip.appendShape([Point3d.create(offset + 1, 1, 0), Point3d.create(offset + 2, 1, 0), Point3d.create(offset + 2, 2, 0), Point3d.create(offset + 1, 2, 0)]);
return clip;
}
describe(`ClipStack (${useFloat ? "floating point texture" : "encoded floats"})`, async () => {
before(async () => {
await IModelApp.startup({ renderSys });
});
after(async () => {
await IModelApp.shutdown();
});
interface Invoked {
updateTexture: boolean;
recomputeTexture: boolean;
uploadTexture: boolean;
allocateGpuBuffer: boolean;
}
class Stack extends ClipStack {
public transform = Transform.createIdentity();
public wantViewClip = true;
public invoked: Invoked = {
updateTexture: false,
recomputeTexture: false,
uploadTexture: false,
allocateGpuBuffer: false,
};
public constructor() {
super(() => this.transform, () => this.wantViewClip);
// Constructor invokes this method - must override afterward.
this.allocateGpuBuffer = () => {
this.invoked.allocateGpuBuffer = true;
return super.allocateGpuBuffer();
};
}
public get cpuBuffer() { return this._cpuBuffer; }
public get gpuBuffer() { return this._gpuBuffer; }
public get numTotalRows() { return this._numTotalRows; }
public get numRowsInUse() { return this._numRowsInUse; }
public get stack() { return this._stack; }
public get isStackDirty() { return this._isStackDirty; }
public pushClip(offset = 0): void {
const clip = createClipVector(offset);
const vol = ClipVolume.create(clip);
expect(vol).not.to.be.undefined;
this.push(vol!);
}
// This is primarily for forcing it to update the texture.
public getTexture() {
return this.texture;
}
public reset() {
this.invoked.uploadTexture = this.invoked.allocateGpuBuffer = this.invoked.updateTexture = this.invoked.recomputeTexture = false;
}
public expectInvoked(expected: Partial<Invoked>) {
if (undefined !== expected.uploadTexture)
expect(this.invoked.uploadTexture).to.equal(expected.uploadTexture);
if (undefined !== expected.updateTexture)
expect(this.invoked.updateTexture).to.equal(expected.updateTexture);
if (undefined !== expected.allocateGpuBuffer)
expect(this.invoked.allocateGpuBuffer).to.equal(expected.allocateGpuBuffer);
if (undefined !== expected.recomputeTexture)
expect(this.invoked.recomputeTexture).to.equal(expected.recomputeTexture);
this.reset();
}
protected override updateTexture() {
this.invoked.updateTexture = true;
super.updateTexture();
}
protected override recomputeTexture() {
this.invoked.recomputeTexture = true;
super.recomputeTexture();
}
protected override uploadTexture() {
this.invoked.uploadTexture = true;
super.uploadTexture();
}
}
it("sets the view clip", () => {
const stack = new Stack();
expect(stack.hasClip).to.be.false;
expect(stack.isStackDirty).to.be.false;
let prevClip = stack.stack[0];
stack.setViewClip(ClipVector.createEmpty(), {});
expect(stack.hasClip).to.be.false;
expect(stack.stack[0]).to.equal(prevClip);
expect(stack.isStackDirty).to.be.false;
const clipVec = createClipVector();
stack.setViewClip(clipVec, {});
expect(stack.hasClip).to.be.true;
expect(stack.stack[0]).not.to.equal(prevClip);
expect(stack.stack[0]).instanceof(ClipVolume);
expect(stack.isStackDirty).to.be.true;
stack.getTexture();
prevClip = stack.stack[0];
stack.setViewClip(clipVec, {});
expect(stack.hasClip).to.be.true;
expect(stack.stack[0]).to.equal(prevClip);
expect(stack.isStackDirty).to.be.false;
stack.setViewClip(createClipVector(1), {});
expect(stack.hasClip).to.be.true;
expect(stack.stack[0]).not.to.equal(prevClip);
expect(stack.isStackDirty).to.be.true;
stack.getTexture();
stack.setViewClip(undefined, {});
expect(stack.hasClip).to.be.false;
expect(stack.stack[0] instanceof ClipVolume).to.be.false;
expect(stack.isStackDirty).to.be.true;
stack.getTexture();
stack.setViewClip(undefined, {});
expect(stack.isStackDirty).to.be.false;
});
it("updates state as clips are pushed and popped", () => {
const stack = new Stack();
expect(stack.stack.length).to.equal(1);
expect(stack.hasClip).to.be.false;
expect(stack.numTotalRows).to.equal(0);
expect(stack.numRowsInUse).to.equal(0);
expect(stack.cpuBuffer.length).to.equal(0);
expect(stack.gpuBuffer.length).to.equal(0);
expect(stack.cpuBuffer.buffer).to.equal(stack.gpuBuffer.buffer);
expect(stack.cpuBuffer === stack.gpuBuffer).to.equal(!useFloat);
expect(stack.startIndex).to.equal(0);
expect(stack.endIndex).to.equal(0);
stack.setViewClip(createClipVector(), {});
expect(stack.stack.length).to.equal(1);
expect(stack.hasClip).to.be.true;
expect(stack.numTotalRows).to.equal(5);
expect(stack.numRowsInUse).to.equal(5);
expect(stack.startIndex).to.equal(0);
expect(stack.endIndex).to.equal(5);
stack.wantViewClip = false;
expect(stack.hasClip).to.be.false;
expect(stack.numTotalRows).to.equal(5);
expect(stack.numRowsInUse).to.equal(5);
expect(stack.startIndex).to.equal(5);
expect(stack.endIndex).to.equal(5);
stack.pushClip();
expect(stack.stack.length).to.equal(2);
expect(stack.hasClip).to.be.true;
expect(stack.numTotalRows).to.equal(10);
expect(stack.numRowsInUse).to.equal(10);
expect(stack.startIndex).to.equal(5);
expect(stack.endIndex).to.equal(10);
stack.wantViewClip = true;
expect(stack.hasClip).to.be.true;
expect(stack.startIndex).to.equal(0);
expect(stack.endIndex).to.equal(10);
stack.pop();
expect(stack.stack.length).to.equal(1);
expect(stack.hasClip).to.be.true;
expect(stack.numTotalRows).to.equal(10);
expect(stack.numRowsInUse).to.equal(5);
expect(stack.cpuBuffer.byteLength).to.equal(0);
expect(stack.startIndex).to.equal(0);
expect(stack.endIndex).to.equal(5);
stack.wantViewClip = false;
expect(stack.hasClip).to.be.false;
stack.wantViewClip = true;
stack.setViewClip(undefined, {});
expect(stack.stack.length).to.equal(1);
expect(stack.hasClip).to.be.false;
expect(stack.numTotalRows).to.equal(10);
expect(stack.numRowsInUse).to.equal(0);
expect(stack.cpuBuffer.byteLength).to.equal(0);
expect(stack.startIndex).to.equal(0);
expect(stack.endIndex).to.equal(0);
stack.setViewClip(createClipVector(), {});
stack.pushClip();
const texture = stack.texture!;
expect(texture).not.to.be.undefined;
expect(texture.width).to.equal(useFloat ? 1 : 4);
expect(texture.height).to.equal(stack.textureHeight);
expect(texture.bytesUsed).to.equal(stack.cpuBuffer.byteLength);
expect(stack.numTotalRows).to.equal(10);
expect(stack.cpuBuffer.byteLength).to.equal(160); // 4 floats per plane * 4 bytes per float * 10 planes
expect(stack.gpuBuffer.buffer).to.equal(stack.cpuBuffer.buffer);
expect(stack.gpuBuffer === stack.cpuBuffer).to.equal(!useFloat);
expect(stack.textureHeight).to.equal(10);
});
it("is marked dirty when a new clip is pushed until texture is updated", () => {
const stack = new Stack();
expect(stack.isStackDirty).to.be.false;
stack.pushClip();
expect(stack.isStackDirty).to.be.true;
expect(stack.texture).not.to.be.undefined;
expect(stack.isStackDirty).to.be.false;
stack.pushClip();
expect(stack.isStackDirty).to.be.true;
expect(stack.texture).not.to.be.undefined;
expect(stack.isStackDirty).to.be.false;
stack.pop();
stack.pop();
expect(stack.isStackDirty).to.be.false;
stack.pushClip();
expect(stack.isStackDirty).to.be.true;
});
it("only recomputes data when dirty", () => {
const stack = new Stack();
expect(stack.isStackDirty).to.be.false;
const tex1 = stack.texture;
expect(tex1).to.be.undefined;
stack.expectInvoked({ allocateGpuBuffer: false, uploadTexture: false, updateTexture: true, recomputeTexture: false });
stack.pushClip();
const tex2 = stack.texture;
expect(tex2).not.to.be.undefined;
stack.expectInvoked({ allocateGpuBuffer: true, uploadTexture: true, updateTexture: true, recomputeTexture: true });
const tex3 = stack.texture;
expect(tex3).to.equal(tex2);
stack.expectInvoked({ allocateGpuBuffer: false, uploadTexture: false, updateTexture: true, recomputeTexture: false });
});
it("recreates texture only when size increases", () => {
const stack = new Stack();
stack.expectInvoked({ allocateGpuBuffer: false, uploadTexture: false, updateTexture: false, recomputeTexture: false });
stack.pushClip();
stack.expectInvoked({ uploadTexture: false, updateTexture: false, allocateGpuBuffer: false, recomputeTexture: false });
const tex1 = stack.texture!;
expect(tex1).not.to.be.undefined;
stack.expectInvoked({ uploadTexture: true, updateTexture: true, allocateGpuBuffer: true, recomputeTexture: true });
stack.pop();
stack.pushClip();
const tex2 = stack.texture!;
expect(tex2).to.equal(tex1);
stack.expectInvoked({ uploadTexture: false, updateTexture: true, allocateGpuBuffer: false, recomputeTexture: true });
stack.pushClip();
const tex3 = stack.texture!;
expect(tex3).not.to.equal(tex1);
stack.expectInvoked({ uploadTexture: true, updateTexture: true, allocateGpuBuffer: true, recomputeTexture: true });
stack.pop();
stack.pop();
stack.pushClip(1);
stack.pushClip(2);
const tex4 = stack.texture!;
expect(tex4).to.equal(tex3);
stack.expectInvoked({ uploadTexture: true, updateTexture: true, allocateGpuBuffer: false, recomputeTexture: true });
});
it("uploads texture data only after it has changed", () => {
const stack = new Stack();
stack.pushClip(1);
const tex1 = stack.texture;
stack.expectInvoked({ allocateGpuBuffer: true, uploadTexture: true, updateTexture: true, recomputeTexture: true });
stack.pop();
stack.pushClip(1);
const tex2 = stack.texture;
expect(tex2).to.equal(tex1);
stack.expectInvoked({ allocateGpuBuffer: false, uploadTexture: false, updateTexture: true, recomputeTexture: true });
stack.pop();
stack.pushClip(2);
const tex3 = stack.texture;
expect(tex3).to.equal(tex2);
stack.expectInvoked({ allocateGpuBuffer: false, uploadTexture: true, updateTexture: true, recomputeTexture: true });
});
it("updates texture when transform changes", () => {
const stack = new Stack();
stack.pushClip();
const tex1 = stack.texture;
stack.expectInvoked({ allocateGpuBuffer: true, uploadTexture: true, updateTexture: true, recomputeTexture: true });
stack.pop();
stack.transform.origin.x += 1;
stack.pushClip();
const tex2 = stack.texture;
expect(tex2).to.equal(tex1);
stack.expectInvoked({ allocateGpuBuffer: false, uploadTexture: true, updateTexture: true, recomputeTexture: true });
stack.pop();
stack.pushClip();
const tex3 = stack.texture;
expect(tex3).to.equal(tex2);
stack.expectInvoked({ allocateGpuBuffer: false, uploadTexture: false, updateTexture: true, recomputeTexture: true });
});
});
} | the_stack |
import {
ITableState,
ModelAssessmentContext,
defaultModelAssessmentContext
} from "@responsible-ai/core-ui";
import { localization } from "@responsible-ai/localization";
import {
Checkbox,
ConstrainMode,
DetailsList,
DetailsListLayoutMode,
DetailsRow,
DetailsRowFields,
getTheme,
MarqueeSelection,
PrimaryButton,
IColumn,
IRenderFunction,
IDetailsRowFieldsProps,
IDetailsRowProps,
IFocusTrapZoneProps,
ISearchBoxStyles,
ISettings,
IStackTokens,
ITheme,
Customizer,
getId,
Layer,
LayerHost,
Panel,
ScrollablePane,
Selection,
SelectionMode,
SearchBox,
Stack,
Text,
TooltipHost,
TooltipOverflowMode
} from "office-ui-fabric-react";
import React from "react";
import { TreeViewParameters } from "../TreeViewParameters/TreeViewParameters";
import { updateItems, updatePercents, sortByPercent } from "./FeatureListUtils";
export interface IFeatureListProps {
isOpen: boolean;
onDismiss: () => void;
saveFeatures: (features: string[]) => void;
features: string[];
theme?: string;
importances: number[];
isEnabled: boolean;
selectedFeatures: string[];
}
const focusTrapZoneProps: IFocusTrapZoneProps = {
forceFocusInsideTrap: false,
isClickableOutsideFocusTrap: true
};
const searchBoxStyles: Partial<ISearchBoxStyles> = { root: { width: 120 } };
// Used to add spacing between example checkboxes
const checkboxStackTokens: IStackTokens = {
childrenGap: "s1",
padding: 1
};
export interface IFeatureListState {
searchedFeatures: string[];
selectedFeatures: string[];
enableApplyButton: boolean;
lastAppliedFeatures: Set<string>;
tableState: ITableState;
maxDepth: number;
numLeaves: number;
minChildSamples: number;
lastAppliedMaxDepth: number;
lastAppliedNumLeaves: number;
lastAppliedMinChildSamples: number;
}
export class FeatureList extends React.Component<
IFeatureListProps,
IFeatureListState
> {
public static contextType = ModelAssessmentContext;
public context: React.ContextType<typeof ModelAssessmentContext> =
defaultModelAssessmentContext;
private layerHostId: string;
private _selection: Selection;
public constructor(props: IFeatureListProps) {
super(props);
const percents = updatePercents(this.props.importances);
const [sortedPercents, sortedFeatures] = sortByPercent(
percents,
this.props.features
);
const searchedFeatures = sortedFeatures;
const tableState = updateItems(
sortedPercents,
sortedFeatures,
searchedFeatures,
this.props.isEnabled
);
this.state = {
enableApplyButton: false,
lastAppliedFeatures: new Set<string>(this.props.features),
lastAppliedMaxDepth: 4,
lastAppliedMinChildSamples: 21,
lastAppliedNumLeaves: 21,
maxDepth: 4,
minChildSamples: 21,
numLeaves: 21,
searchedFeatures,
selectedFeatures: this.props.selectedFeatures,
tableState
};
this.layerHostId = getId("featuresListHost");
this._selection = new Selection({
onSelectionChanged: (): void => {
let newSelectedFeatures = this.getSelectionDetails();
const oldSelectedFeaturesNotSearched =
this.state.selectedFeatures.filter(
(oldSelectedFeature) =>
!this.state.searchedFeatures.includes(oldSelectedFeature)
);
newSelectedFeatures = newSelectedFeatures.concat(
oldSelectedFeaturesNotSearched
);
const enableApplyButton = this.checkEnableApplyButton(
newSelectedFeatures,
this.state.maxDepth,
this.state.numLeaves,
this.state.minChildSamples
);
this.setState({
enableApplyButton,
selectedFeatures: newSelectedFeatures
});
}
});
this.updateSelection();
}
public componentDidUpdate(prevProps: IFeatureListProps): void {
if (this.props.importances !== prevProps.importances) {
this.updateTable();
}
}
public render(): React.ReactNode {
const theme = getTheme();
return (
<Panel
headerText="Feature List"
isOpen={this.props.isOpen}
focusTrapZoneProps={focusTrapZoneProps}
// You MUST provide this prop! Otherwise screen readers will just say "button" with no label.
closeButtonAriaLabel="Close"
isBlocking={false}
onDismiss={this.props.onDismiss}
>
<div className="featuresSelector">
<Stack tokens={checkboxStackTokens} verticalAlign="space-around">
<Stack.Item key="decisionTreeKey" align="start">
<Text key="decisionTreeTextKey" variant="medium">
{this.props.isEnabled
? localization.ErrorAnalysis.FeatureList.treeMapDescription
: localization.ErrorAnalysis.FeatureList
.staticTreeMapDescription}
</Text>
</Stack.Item>
<Stack.Item key="searchKey" align="start">
<SearchBox
placeholder="Search"
styles={searchBoxStyles}
onSearch={this.onSearch.bind(this)}
onClear={this.onSearch.bind(this)}
onChange={(_, newValue?: string): void => {
if (newValue === undefined) {
return;
}
this.onSearch.bind(this)(newValue);
}}
/>
</Stack.Item>
<Customizer
settings={(currentSettings): ISettings => ({
...currentSettings,
hostId: this.layerHostId
})}
>
<Layer>
<ScrollablePane>
<MarqueeSelection
selection={this._selection}
isEnabled={this.props.isEnabled}
>
<DetailsList
items={this.state.tableState.rows}
columns={this.state.tableState.columns}
setKey="set"
layoutMode={DetailsListLayoutMode.fixedColumns}
constrainMode={ConstrainMode.unconstrained}
onRenderItemColumn={this.renderItemColumn.bind(
this,
theme
)}
selectionPreservedOnEmptyClick
ariaLabelForSelectionColumn="Toggle selection"
ariaLabelForSelectAllCheckbox="Toggle selection for all items"
checkButtonAriaLabel="Row checkbox"
selectionMode={
this.props.isEnabled
? SelectionMode.multiple
: SelectionMode.none
}
selection={this._selection}
onRenderRow={this.renderRow.bind(this)}
/>
</MarqueeSelection>
</ScrollablePane>
</Layer>
</Customizer>
<LayerHost
id={this.layerHostId}
style={{
height: "500px",
overflow: "hidden",
position: "relative"
}}
/>
<Stack.Item key="treeViewParameters" align="start">
<TreeViewParameters
updateMaxDepth={this.updateMaxDepth.bind(this)}
updateNumLeaves={this.updateNumLeaves.bind(this)}
updateMinChildSamples={this.updateMinChildSamples.bind(this)}
maxDepth={this.state.maxDepth}
numLeaves={this.state.numLeaves}
minChildSamples={this.state.minChildSamples}
isEnabled={this.props.isEnabled}
/>
</Stack.Item>
{this.props.isEnabled && (
// Remove apply button in static view
<Stack.Item key="applyButtonKey" align="start">
<PrimaryButton
text="Apply"
onClick={this.apply.bind(this)}
allowDisabledFocus
disabled={!this.state.enableApplyButton}
checked={false}
/>
</Stack.Item>
)}
</Stack>
</div>
</Panel>
);
}
private renderRow: IRenderFunction<IDetailsRowProps> = (
props?: IDetailsRowProps
): JSX.Element | null => {
if (!props) {
return <div />;
}
return (
<DetailsRow rowFieldsAs={this.renderRowFields.bind(this)} {...props} />
);
};
private renderRowFields(props: IDetailsRowFieldsProps): JSX.Element {
if (this.props.isEnabled) {
return <DetailsRowFields {...props} />;
}
return (
<span data-selection-disabled>
<DetailsRowFields {...props} />
</span>
);
}
private renderItemColumn(
theme: ITheme,
item: any,
index?: number,
column?: IColumn
): React.ReactNode {
if (column && index !== undefined) {
const fieldContent = item[column.fieldName as keyof any] as string;
switch (column.key) {
case "checkbox":
if (this.state.selectedFeatures.includes(fieldContent)) {
return <Checkbox checked disabled />;
}
return <Checkbox checked={false} disabled />;
case "importances":
return (
<svg width="100px" height="6px">
<g>
<rect
fill={theme.palette.neutralQuaternary}
width="100%"
height="4"
rx="5"
/>
<rect
fill={theme.palette.neutralSecondary}
width={`${fieldContent}%`}
height="4"
rx="5"
/>
</g>
</svg>
);
default:
return (
<TooltipHost
id={column.key}
content={fieldContent}
overflowMode={TooltipOverflowMode.Parent}
>
<span>{fieldContent}</span>
</TooltipHost>
);
}
}
return <span />;
}
private updateSelection(): void {
this._selection.setItems(this.state.tableState.rows);
const featureNames = this.state.tableState.rows.map((row) => row[0]);
featureNames.forEach((feature, index) => {
if (this.state.selectedFeatures.includes(feature)) {
this._selection.setIndexSelected(index, true, true);
}
});
}
private updateTable(): void {
const percents = updatePercents(this.props.importances);
const [sortedPercents, sortedFeatures] = sortByPercent(
percents,
this.props.features
);
const searchedFeatures = sortedFeatures.filter((sortedFeature) =>
this.state.searchedFeatures.includes(sortedFeature)
);
const tableState = updateItems(
sortedPercents,
sortedFeatures,
searchedFeatures,
this.props.isEnabled
);
this.setState(
{
tableState
},
() => {
this.updateSelection();
}
);
}
private getSelectionDetails(): string[] {
const selectedRows = this._selection.getSelection();
const keys = selectedRows.map((row) => row[0] as string);
return keys;
}
private onSearch(searchValue: string): void {
this.setState(
{
searchedFeatures: this.props.features.filter((feature) =>
feature.includes(searchValue)
)
},
() => {
this.updateTable();
}
);
}
private checkEnableApplyButton(
newSelectedFeatures: string[],
maxDepth: number,
numLeaves: number,
minChildSamples: number
): boolean {
return (
this.state.lastAppliedMaxDepth !== maxDepth ||
this.state.lastAppliedNumLeaves !== numLeaves ||
this.state.lastAppliedMinChildSamples !== minChildSamples ||
this.state.lastAppliedFeatures.size !== newSelectedFeatures.length ||
newSelectedFeatures.some(
(selectedFeature) =>
!this.state.lastAppliedFeatures.has(selectedFeature)
)
);
}
private updateMaxDepth(maxDepth: number): void {
const enableApplyButton = this.checkEnableApplyButton(
this.state.selectedFeatures,
maxDepth,
this.state.numLeaves,
this.state.minChildSamples
);
this.setState({
enableApplyButton,
maxDepth
});
}
private updateNumLeaves(numLeaves: number): void {
const enableApplyButton = this.checkEnableApplyButton(
this.state.selectedFeatures,
this.state.maxDepth,
numLeaves,
this.state.minChildSamples
);
this.setState({
enableApplyButton,
numLeaves
});
}
private updateMinChildSamples(minChildSamples: number): void {
const enableApplyButton = this.checkEnableApplyButton(
this.state.selectedFeatures,
this.state.maxDepth,
this.state.numLeaves,
minChildSamples
);
this.setState({
enableApplyButton,
minChildSamples
});
}
private apply(): void {
const selectedFeatures = [...this.state.selectedFeatures];
this.props.saveFeatures(selectedFeatures);
this.context.errorAnalysisData!.maxDepth = this.state.maxDepth;
this.context.errorAnalysisData!.numLeaves = this.state.numLeaves;
this.context.errorAnalysisData!.minChildSamples =
this.state.minChildSamples;
this.setState({
enableApplyButton: false,
lastAppliedFeatures: new Set<string>(selectedFeatures),
lastAppliedMaxDepth: this.state.maxDepth,
lastAppliedMinChildSamples: this.state.minChildSamples,
lastAppliedNumLeaves: this.state.numLeaves
});
}
} | the_stack |
import {
FormControl,
FormGroup,
FormsModule,
ReactiveFormsModule,
Validators,
} from '@angular/forms';
import { IonRadioGroup } from '@ionic/angular';
import { createHostFactory, SpectatorHost } from '@ngneat/spectator';
import { Observable, of } from 'rxjs';
import { DesignTokenHelper } from '@kirbydesign/core';
import { TestHelper } from '../../../testing/test-helper';
import { ListItemTemplateDirective } from '../../list/list.directive';
import { RadioComponent } from '../radio.component';
import { RadioGroupComponent } from './radio-group.component';
const { getColor } = DesignTokenHelper;
describe('RadioGroupComponent', () => {
const createHost = createHostFactory({
component: RadioGroupComponent,
declarations: [RadioComponent, ListItemTemplateDirective],
imports: [TestHelper.ionicModuleForTest, FormsModule, ReactiveFormsModule],
});
describe('with plain binding', () => {
type defaultDataType = { text: string; value: number; disabled?: boolean };
type booleanDataType = { text: string; value: boolean; disabled?: boolean };
let ionRadioGroup: IonRadioGroup;
let ionRadioElements: HTMLIonRadioElement[];
let radios: RadioComponent[];
function radioChecked(index: number): boolean {
return ionRadioElements[index].getAttribute('aria-checked') === 'true';
}
const defaultSelectedIndex = 1;
const textItems: string[] = ['Larry', 'Curly', 'Moe'];
const dataItems: defaultDataType[] = [
{ text: 'Larry', value: 1 },
{ text: 'Curly', value: 2 },
{ text: 'Moe', value: 3 },
];
const enum DataScenarioTypes {
TEXT = 'plain text',
DATA = 'data items with default property names',
BOOLEAN_DATA = 'boolean data items with default property names',
ASYNC_DATA = 'async data items with default property names',
}
const enum TemplateScenarioTypes {
DEFAULT = 'default item template',
CUSTOM = 'custom item template',
SLOTTED = 'slotted radios',
}
const booleanDataItems: booleanDataType[] = [
{ text: 'Larry', value: true },
{ text: 'Curly', value: false },
];
const dataScenarios = [
{
type: DataScenarioTypes.TEXT,
items: textItems,
selected: textItems[defaultSelectedIndex],
},
{
type: DataScenarioTypes.DATA,
items: dataItems,
selected: dataItems[defaultSelectedIndex],
},
{
type: DataScenarioTypes.ASYNC_DATA,
items: dataItems,
selected: dataItems[defaultSelectedIndex],
},
{
type: DataScenarioTypes.BOOLEAN_DATA,
items: booleanDataItems,
selected: booleanDataItems[defaultSelectedIndex],
},
];
dataScenarios.forEach((dataScenario) => {
describe(`when bound to ${dataScenario.type}`, () => {
const itemsTemplateVar =
dataScenario.type === DataScenarioTypes.ASYNC_DATA ? 'items$ | async' : 'items';
const templateScenarios = [
{
type: TemplateScenarioTypes.DEFAULT,
template: `<kirby-radio-group [(value)]="selected" [items]="${itemsTemplateVar}"></kirby-radio-group>`,
},
{
type: TemplateScenarioTypes.SLOTTED,
template: `<kirby-radio-group [(value)]="selected">
<kirby-radio *ngFor="let item of ${itemsTemplateVar}" [value]="item" [text]="item.text || item"></kirby-radio>
</kirby-radio-group>`,
},
{
type: TemplateScenarioTypes.CUSTOM,
template: `<kirby-radio-group [(value)]="selected" [items]="${itemsTemplateVar}">
<div style="display: flex; flex-direction: row;"
*kirbyListItemTemplate="let item; let selected = selected; let index = index"
[attr.is-selected]="selected"
[attr.index]="index"
class="item-template">
<kirby-radio
[value]="item"
[text]="item.text"
[disabled]="item.disabled">
</kirby-radio>
<p class="selected">{{selected}}</p>
<p class="index">{{index}}</p>
</div>
</kirby-radio-group>`,
},
];
templateScenarios.forEach((templateScenario) => {
describe(`with ${templateScenario.type}`, () => {
let spectator: SpectatorHost<
RadioGroupComponent,
{
items: string[] | booleanDataType[] | defaultDataType[];
items$: Observable<string[] | booleanDataType[] | defaultDataType[]>;
selected: string | booleanDataType | defaultDataType;
}
>;
describe('and no pre-selected item', () => {
beforeEach(async () => {
spectator = createHost(templateScenario.template, {
hostProps: {
items: dataScenario.items,
items$: of(null),
selected: null,
},
});
// Set items$ observable after creation, to ensure async rendering:
spectator.setHostInput('items$', of(dataScenario.items));
ionRadioGroup = spectator.query(IonRadioGroup);
const ionRadioGroupElement = spectator.query('ion-radio-group');
await TestHelper.whenReady(ionRadioGroupElement);
radios = spectator.queryAll(RadioComponent);
ionRadioElements = spectator.queryAll('ion-radio');
expect(radios).toHaveLength(dataScenario.items.length);
expect(ionRadioElements).toHaveLength(dataScenario.items.length);
await TestHelper.whenReady(ionRadioElements);
});
describe('selection', () => {
beforeEach(async () => {
// Assert initial state:
expect(ionRadioGroup.value).toBeNull();
// Assert initial state of radios:
expect(ionRadioElements).toHaveLength(dataScenario.items.length);
ionRadioElements.forEach((_, index) => {
expect(radioChecked(index)).toBeFalse();
});
});
it('should not set the value of ion-radio-group', () => {
expect(ionRadioGroup.value).toBeNull();
});
it('should not have any selected radio', () => {
expect(ionRadioElements).toHaveLength(dataScenario.items.length);
ionRadioElements.forEach((_, index) => {
expect(radioChecked(index)).toBeFalse();
});
});
it('should not have selected index', () => {
expect(spectator.component.selectedIndex).toBe(-1);
});
it('should set the value to the corresponding data item when clicking a radio item', () => {
spectator.click(ionRadioElements[0]);
expect(spectator.component.value).toEqual(dataScenario.items[0]);
});
it('should update the bound field when clicking a radio item', () => {
spectator.click(ionRadioElements[0]);
expect(spectator.hostComponent.selected).toEqual(dataScenario.items[0]);
});
it('should emit change event when clicking a radio item', () => {
const onChangeSpy = spyOn(spectator.component.valueChange, 'emit');
spectator.click(ionRadioElements[0]);
expect(onChangeSpy).toHaveBeenCalledTimes(1);
expect(onChangeSpy).toHaveBeenCalledWith(dataScenario.items[0]);
});
it('should update the value of ion-radio-group when the bound field is updated', () => {
spectator.setHostInput('selected', dataScenario.items[2]);
expect(ionRadioGroup.value).toEqual(dataScenario.items[2]);
});
it('should update the selected radio when the bound field is updated', async () => {
spectator.setHostInput('selected', dataScenario.items[0]);
// Wait for radio checked attribute to be updated;
await TestHelper.whenTrue(() => radioChecked(0));
expect(dataScenario.items).not.toHaveLength(0);
ionRadioElements.forEach((_, index) => {
if (index === 0) {
expect(radioChecked(index)).toBeTrue();
} else {
expect(radioChecked(index)).toBeFalse();
}
});
});
it('should not emit change event when the bound field is updated', () => {
const onChangeSpy = spyOn(spectator.component.valueChange, 'emit');
spectator.setHostInput('selected', dataScenario.items[2]);
expect(onChangeSpy).not.toHaveBeenCalled();
});
});
describe('focus', () => {
it('should focus the first radio when none is selected', async () => {
const firstRadio = ionRadioElements[0];
// Wait for tabindex to be rendered:
await TestHelper.whenTrue(() => firstRadio.tabIndex === 0);
spectator.component.focus();
expect(document.activeElement).toEqual(firstRadio);
});
});
});
describe('and pre-selected item', () => {
beforeEach(async () => {
spectator = createHost(templateScenario.template, {
hostProps: {
items: dataScenario.items,
items$: of(null),
selected: dataScenario.selected,
},
});
// Set items$ observable after creation, to ensure async rendering:
spectator.setHostInput('items$', of(dataScenario.items));
ionRadioGroup = spectator.query(IonRadioGroup);
const ionRadioGroupElement = spectator.query('ion-radio-group');
await TestHelper.whenReady(ionRadioGroupElement);
radios = spectator.queryAll(RadioComponent);
ionRadioElements = spectator.queryAll('ion-radio');
expect(radios).toHaveLength(dataScenario.items.length);
expect(ionRadioElements).toHaveLength(dataScenario.items.length);
await TestHelper.whenReady(ionRadioElements);
});
it('should render all items', () => {
expect(radios).toHaveLength(dataScenario.items.length);
expect(ionRadioElements).toHaveLength(dataScenario.items.length);
});
if (templateScenario.type === TemplateScenarioTypes.DEFAULT) {
it('should set the text of each radio to the corresponding text item / item´s `text` property', () => {
const expectedTexts = ['Larry', 'Curly', 'Moe'];
expect(radios.length).toEqual(dataScenario.items.length);
radios.forEach((radio, index) => {
expect(radio.text).toEqual(expectedTexts[index]);
});
});
it('should set the value of each radio to the corresponding data item', () => {
expect(radios.length).toEqual(dataScenario.items.length);
radios.forEach((radio, index) => {
expect(radio.value).toEqual(dataScenario.items[index]);
});
});
}
if (templateScenario.type === TemplateScenarioTypes.CUSTOM) {
it('should set template variable `selected` for each item', () => {
const templateWrappers = spectator.queryAll('div.item-template');
const expectedIsSelectedValues = ['false', 'true', 'false'];
expect(templateWrappers.length).toEqual(dataScenario.items.length);
templateWrappers.forEach((templateWrapper, index) => {
expect(templateWrapper).toHaveAttribute(
'is-selected',
expectedIsSelectedValues[index]
);
});
});
it('should set template variable `index` for each item', () => {
const templateWrappers = spectator.queryAll('div.item-template');
expect(templateWrappers).toHaveLength(dataScenario.items.length);
templateWrappers.forEach((templateWrapper, index) => {
expect(templateWrapper).toHaveAttribute('index', String(index));
});
});
}
describe('selection', () => {
beforeEach(async () => {
// Assert initial state:
expect(ionRadioGroup.value).toBe(dataScenario.selected);
// Assert initial state of radios:
ionRadioElements.forEach((_, index) => {
if (index === defaultSelectedIndex) {
expect(radioChecked(index)).toBeTrue();
} else {
expect(radioChecked(index)).toBeFalse();
}
});
});
it('should set the value of ion-radio-group to the corresponding selected data item', () => {
expect(ionRadioGroup.value).toBe(dataScenario.selected);
});
it('should have selected radio corresponding to the selected data item', () => {
expect(ionRadioElements).toHaveLength(dataScenario.items.length);
ionRadioElements.forEach((_, index) => {
if (index === defaultSelectedIndex) {
expect(radioChecked(index)).toBeTrue();
} else {
expect(radioChecked(index)).toBeFalse();
}
});
});
it('should have selected index corresponding to the selected data item', () => {
expect(spectator.component.selectedIndex).toBe(defaultSelectedIndex);
});
it('should set the value to the corresponding data item when clicking a radio item', () => {
spectator.click(ionRadioElements[0]);
expect(spectator.component.value).toEqual(dataScenario.items[0]);
});
it('should update the bound field when clicking a radio item', () => {
spectator.click(ionRadioElements[0]);
expect(spectator.hostComponent.selected).toEqual(dataScenario.items[0]);
});
it('should emit change event when clicking a radio item', () => {
const onChangeSpy = spyOn(spectator.component.valueChange, 'emit');
spectator.click(ionRadioElements[0]);
expect(onChangeSpy).toHaveBeenCalledTimes(1);
expect(onChangeSpy).toHaveBeenCalledWith(dataScenario.items[0]);
});
it('should update the value of ion-radio-group when the bound field is updated', () => {
spectator.setHostInput('selected', dataScenario.items[2]);
expect(ionRadioGroup.value).toEqual(dataScenario.items[2]);
});
it('should update the selected radio when the bound field is updated', async () => {
const newSelectedItemIndex = 0;
spectator.setHostInput('selected', dataScenario.items[newSelectedItemIndex]);
// Wait for radio checked attribute to be updated;
await TestHelper.whenTrue(() => radioChecked(newSelectedItemIndex));
expect(ionRadioElements.length).not.toBe(0);
ionRadioElements.forEach((_, index) => {
if (index === newSelectedItemIndex) {
expect(radioChecked(index)).toBeTrue();
} else {
expect(radioChecked(index)).toBeFalse();
}
});
});
it('should not emit change event when the bound field is updated', () => {
const onChangeSpy = spyOn(spectator.component.valueChange, 'emit');
spectator.setHostInput('selected', dataScenario.items[2]);
expect(onChangeSpy).not.toHaveBeenCalled();
});
});
describe('enablement', () => {
it('should not disable the radio items by default', () => {
radios.forEach((each) => expect(each.disabled).toBeUndefined());
});
it('should disable the radio items when the kirby-radio-group is disabled', () => {
spectator.setInput('disabled', true);
radios.forEach((each) => expect(each.disabled).toBeTrue());
});
it('should re-enable the radio items when the kirby-radio-group is enabled', () => {
spectator.setInput('disabled', true);
radios.forEach((each) => expect(each.disabled).toBeTrue());
spectator.setInput('disabled', false);
radios.forEach((each) => expect(each.disabled).toBeUndefined());
});
it('should disable the radio items if items are set after the kirby-radio-group is disabled', async () => {
spectator.setHostInput('items', null);
spectator.setInput('disabled', true);
await TestHelper.waitForTimeout(); // Wait a tick
spectator.setHostInput('items', dataScenario.items);
await TestHelper.waitForTimeout(); // Wait a tick
radios = spectator.queryAll(RadioComponent);
radios.forEach((each) => expect(each.disabled).toBeTrue());
});
if (
dataScenario.type !== DataScenarioTypes.TEXT &&
templateScenario.type !== TemplateScenarioTypes.SLOTTED
) {
describe('when data items has disabled property', () => {
beforeEach(() => {
const itemsWithDisabledProperty = dataItems.map((item) => ({ ...item }));
itemsWithDisabledProperty[1].disabled = false;
itemsWithDisabledProperty[2].disabled = true;
spectator.setHostInput('items', itemsWithDisabledProperty);
spectator.setHostInput('items$', of(itemsWithDisabledProperty));
radios = spectator.queryAll(RadioComponent);
});
it('should disable radio when the corresponding data item´s `disabled` property is true', () => {
expect(radios[0].disabled).toBeUndefined();
expect(radios[1].disabled).toBeFalse();
expect(radios[2].disabled).toBeTrue();
});
it('should disable the radio items when the kirby-radio-group is disabled', () => {
spectator.setInput('disabled', true);
radios.forEach((each) => expect(each.disabled).toBeTrue());
});
it('should only re-enable the radio items if the corresponding data item is not disabled when the kirby-radio-group is enabled', () => {
spectator.setInput('disabled', true);
radios.forEach((each) => expect(each.disabled).toBeTrue());
spectator.setInput('disabled', false);
expect(radios[0].disabled).toBeUndefined();
expect(radios[1].disabled).toBeFalse();
expect(radios[2].disabled).toBeTrue();
});
});
}
});
describe('focus', () => {
it('should focus the selected radio', async () => {
const selectedRadio = ionRadioElements[defaultSelectedIndex];
expect(selectedRadio.getAttribute('aria-checked')).toEqual('true');
// Wait for tabindex to be rendered:
await TestHelper.whenTrue(() => selectedRadio.tabIndex === 0);
spectator.component.focus();
expect(document.activeElement).toEqual(selectedRadio);
});
});
describe('hasError', () => {
it('should not have error state by default', () => {
expect(spectator.component.hasError).toBeFalse;
expect(spectator.element.classList).not.toContain('error');
});
it('should apply class `error` when hasError=true', () => {
spectator.setInput('hasError', true);
spectator.detectChanges();
expect(spectator.element.classList).toContain('error');
});
});
describe('when updating items', () => {
describe('by shifting items down', () => {
it('should have selected index corresponding to the selected data item', () => {
const newItems =
dataScenario.type === DataScenarioTypes.TEXT
? ['New Guy'].concat(textItems)
: [{ text: 'New Guy', value: 10 }].concat(
dataScenario.items as defaultDataType[]
); // Convert to allow mixing defaultDataType with booleanDataType
spectator.setHostInput('items', newItems);
spectator.setHostInput('items$', of(newItems));
expect(spectator.component.selectedIndex).toBe(defaultSelectedIndex + 1);
});
});
describe('by shifting items up', () => {
it('should have selected index corresponding to the selected data item', () => {
const newItems = dataScenario.items.slice(1);
spectator.setHostInput('items', newItems);
spectator.setHostInput('items$', of(newItems));
expect(spectator.component.selectedIndex).toBe(defaultSelectedIndex - 1);
});
});
describe('by removing items', () => {
it('should reset value and selected index', () => {
spectator.setHostInput('items', null);
spectator.setHostInput('items$', of(null));
expect(spectator.component.value).toBe(null);
expect(spectator.component.selectedIndex).toBe(-1);
});
});
if (dataScenario.type !== DataScenarioTypes.TEXT) {
describe('by replacing items with new instances', () => {
it('should reset value and selected index', () => {
let newItems: booleanDataType[] | defaultDataType[];
if (DataScenarioTypes.BOOLEAN_DATA) {
newItems = booleanDataItems.map((item) => ({
...item,
value: !item.value,
}));
} else {
newItems = dataItems.map((item) => ({ ...item, value: item.value + 10 }));
}
spectator.setHostInput('items', newItems);
spectator.setHostInput('items$', of(newItems));
expect(spectator.component.value).toBe(null);
expect(spectator.component.selectedIndex).toBe(-1);
});
});
}
});
});
});
});
if (dataScenario.type !== DataScenarioTypes.ASYNC_DATA) {
describe('and configured with selected index', () => {
const templateScenarios = [
TemplateScenarioTypes.DEFAULT,
TemplateScenarioTypes.SLOTTED,
];
templateScenarios.forEach((templateScenario) => {
describe(`with ${templateScenario}`, () => {
let spectator: SpectatorHost<
RadioGroupComponent,
{ items: string[] | defaultDataType[] | booleanDataType[]; selectedIndex: number }
>;
describe('through template one-time string initialization', () => {
it('should set the value to the corresponding data item', () => {
const template =
templateScenario === TemplateScenarioTypes.DEFAULT
? `<kirby-radio-group
[items]="items"
selectedIndex="${defaultSelectedIndex}">
</kirby-radio-group>`
: `<kirby-radio-group selectedIndex="${defaultSelectedIndex}">
<kirby-radio *ngFor="let item of items" [value]="item" [text]="item.text || item"></kirby-radio>
</kirby-radio-group>`;
spectator = createHost(template, {
hostProps: {
items: dataScenario.items,
selectedIndex: null,
},
});
expect(spectator.component.value).toEqual(
dataScenario.items[defaultSelectedIndex]
);
});
});
describe('through template property binding', () => {
const template =
templateScenario === TemplateScenarioTypes.DEFAULT
? `<kirby-radio-group
[items]="items"
[selectedIndex]="selectedIndex">
</kirby-radio-group>`
: `<kirby-radio-group [selectedIndex]="selectedIndex">
<kirby-radio *ngFor="let item of items" [value]="item" [text]="item.text || item"></kirby-radio>
</kirby-radio-group>`;
const createHostFromScenario = (
items = dataScenario.items,
selectedIndex = defaultSelectedIndex
) =>
createHost(template, {
hostProps: {
items,
selectedIndex,
},
});
it('should set the value to the corresponding data item', () => {
spectator = createHostFromScenario();
expect(spectator.component.value).toEqual(
dataScenario.items[defaultSelectedIndex]
);
});
it('set the value to the corresponding data item when setting items after selected index', () => {
spectator = createHostFromScenario(null, defaultSelectedIndex);
expect(spectator.component.value).toBeNull();
spectator.setHostInput('items', dataScenario.items);
expect(spectator.component.value).toEqual(
dataScenario.items[defaultSelectedIndex]
);
});
it('set the value to the corresponding data item when setting selected index after items', () => {
spectator = createHostFromScenario(dataScenario.items, null);
expect(spectator.component.value).toBeNull();
spectator.setHostInput('selectedIndex', defaultSelectedIndex);
expect(spectator.component.value).toEqual(
dataScenario.items[defaultSelectedIndex]
);
});
describe('when changing selected index', () => {
beforeEach(async () => {
spectator = createHostFromScenario();
const ionRadioGroupElement = spectator.query('ion-radio-group');
await TestHelper.whenReady(ionRadioGroupElement);
radios = spectator.queryAll(RadioComponent);
ionRadioElements = spectator.queryAll('ion-radio');
});
it('should have correct new selected item', async () => {
const newSelectedIndex = 0;
spectator.setInput('selectedIndex', newSelectedIndex);
// Wait for radio checked attribute to be updated;
await TestHelper.whenTrue(() => radioChecked(newSelectedIndex));
expect(spectator.component.value).toEqual(
dataScenario.items[newSelectedIndex]
);
expect(ionRadioElements).toHaveLength(dataScenario.items.length);
ionRadioElements.forEach((_, index) => {
if (index === newSelectedIndex) {
expect(radioChecked(index)).toBeTrue();
} else {
expect(radioChecked(index)).toBeFalse();
}
});
});
it('should not emit change event', () => {
const onChangeSpy = spyOn(spectator.component.valueChange, 'emit');
spectator.setInput('selectedIndex', 0);
expect(onChangeSpy).not.toHaveBeenCalled();
});
});
});
if (templateScenario === TemplateScenarioTypes.DEFAULT) {
describe('through input properties', () => {
it('should set the value to the corresponding data item', () => {
spectator = createHost('<kirby-radio-group></kirby-radio-group>', {
props: { selectedIndex: defaultSelectedIndex, items: dataScenario.items },
});
expect(spectator.component.value).toEqual(
dataScenario.items[defaultSelectedIndex]
);
});
it('set the value to the corresponding data item when setting items after selected index', () => {
spectator = createHost('<kirby-radio-group></kirby-radio-group>');
spectator.setInput('selectedIndex', defaultSelectedIndex);
spectator.setInput('items', dataScenario.items);
expect(spectator.component.value).toEqual(
dataScenario.items[defaultSelectedIndex]
);
});
it('set the value to the corresponding data item when setting selected index after items', () => {
spectator = createHost('<kirby-radio-group></kirby-radio-group>');
spectator.setInput('items', dataScenario.items);
spectator.setInput('selectedIndex', defaultSelectedIndex);
expect(spectator.component.value).toEqual(
dataScenario.items[defaultSelectedIndex]
);
});
});
}
});
});
});
}
});
});
describe('when bound to data items with custom property names', () => {
type customDataType = { title: string; value: number; isNotSelectable?: boolean };
let spectator: SpectatorHost<RadioGroupComponent, { items: customDataType[] }>;
const customDataItems = [
{ title: 'Larry', value: 1 },
{ title: 'Curly', value: 2, isNotSelectable: false },
{ title: 'Moe', value: 3, isNotSelectable: true },
];
beforeEach(async () => {
spectator = createHost(
`<kirby-radio-group
[items]="items"
itemTextProperty="title"
itemDisabledProperty="isNotSelectable">
</kirby-radio-group>`,
{
hostProps: {
items: customDataItems,
},
}
);
ionRadioGroup = spectator.query(IonRadioGroup);
const ionRadioGroupElement = spectator.query('ion-radio-group');
await TestHelper.whenReady(ionRadioGroupElement);
radios = spectator.queryAll(RadioComponent);
});
it('should set the text of each radio to the corresponding data item´s `title` property', () => {
expect(radios[0].text).toEqual('Larry');
expect(radios[1].text).toEqual('Curly');
expect(radios[2].text).toEqual('Moe');
});
it('should set the value of each radio to the corresponding data item', () => {
expect(radios[0].value).toEqual(customDataItems[0]);
expect(radios[1].value).toEqual(customDataItems[1]);
expect(radios[2].value).toEqual(customDataItems[2]);
});
it('should disable radio when the corresponding data item´s `isNotSelectable` property is true', () => {
expect(radios[0].disabled).toBeUndefined();
expect(radios[1].disabled).toBeFalse();
expect(radios[2].disabled).toBeTrue();
});
});
});
describe('implementing ControlValueAccessor interface', () => {
const items = ['Bacon', 'Sausage', 'Onion'];
const defaultSelectedIndex = 1;
let ionRadioElements: HTMLIonRadioElement[];
let spectator: SpectatorHost<
RadioGroupComponent,
{
items: string[];
}
>;
beforeEach(async () => {
spectator = createHost(
`<kirby-radio-group [items]="items">
</kirby-radio-group>`,
{
hostProps: {
items: items,
},
}
);
const ionRadioGroupElement = spectator.query('ion-radio-group');
await TestHelper.whenReady(ionRadioGroupElement);
ionRadioElements = spectator.queryAll('ion-radio');
await TestHelper.whenReady(ionRadioElements);
});
describe('when writeValue() function is invoked', () => {
it('should select the radio', () => {
const expectedItem = items[defaultSelectedIndex];
spectator.component.writeValue(expectedItem);
expect(spectator.component.value).toEqual(expectedItem);
});
it('should not emit change event', () => {
const onChangeSpy = spyOn(spectator.component.valueChange, 'emit');
spectator.component.writeValue(items[defaultSelectedIndex]);
expect(onChangeSpy).not.toHaveBeenCalled();
});
});
it('should invoke callback from registerOnChange() function on change', () => {
const expectedItem = items[defaultSelectedIndex];
const onChangeSpy = jasmine.createSpy('_onChangeCallback');
spectator.component.registerOnChange(onChangeSpy);
spectator.component._onChange(expectedItem);
expect(onChangeSpy).toHaveBeenCalledWith(expectedItem);
});
it('should invoke callback from registerOnTouched() function on blur', () => {
const onTouchedSpy = jasmine.createSpy('_onTouched');
spectator.component.registerOnTouched(onTouchedSpy);
ionRadioElements[0].focus();
ionRadioElements[0].blur();
expect(onTouchedSpy).toHaveBeenCalled();
});
describe('when setDisabledState() function is invoked', () => {
it('should set disabled = false when invoked with false', () => {
spectator.component.disabled = true;
spectator.component.setDisabledState(false);
expect(spectator.component.disabled).toBeFalsy();
});
it('should set disabled = true when invoked with true', () => {
spectator.component.disabled = false;
spectator.component.setDisabledState(true);
expect(spectator.component.disabled).toBeTruthy();
});
});
});
describe('when used in a form', () => {
const radioBorderDefault = {
'border-width': '1px',
'border-color': getColor('semi-dark'),
};
const radioBorderErrorState = {
'border-width': '1px',
'border-color': getColor('danger'),
};
let ionRadioGroup: IonRadioGroup;
let ionRadioElements: HTMLIonRadioElement[];
let radios: RadioComponent[];
function radioChecked(index: number): boolean {
return ionRadioElements[index].getAttribute('aria-checked') === 'true';
}
const items = ['Bacon', 'Sausage', 'Onion'];
const defaultSelectedIndex = 1;
describe('with a template-driven form', () => {
let spectator: SpectatorHost<
RadioGroupComponent,
{
items: string[];
selected: string;
}
>;
describe('and no pre-selected item', () => {
beforeEach(async () => {
spectator = createHost(
`<kirby-radio-group [items]="items" [(ngModel)]="selected">
</kirby-radio-group>`,
{
hostProps: {
items: items,
selected: null,
},
}
);
ionRadioGroup = spectator.query(IonRadioGroup);
const ionRadioGroupElement = spectator.query('ion-radio-group');
await TestHelper.whenReady(ionRadioGroupElement);
radios = spectator.queryAll(RadioComponent);
ionRadioElements = spectator.queryAll('ion-radio');
await TestHelper.whenReady(ionRadioElements);
});
describe('selection', () => {
it('should update the bound ngModel when clicking a radio item', () => {
spectator.click(ionRadioElements[0]);
expect(spectator.hostComponent.selected).toEqual(items[0]);
});
it('should update the value of ion-radio-group when the bound ngModel is updated', async () => {
const newSelectedValue = items[0];
await setSelectedOnHostComponent(newSelectedValue);
expect(ionRadioGroup.value).toEqual(newSelectedValue);
});
it('should update the selected radio when the bound ngModel is updated', async () => {
const selectedIndex = 0;
await setSelectedOnHostComponent(items[selectedIndex]);
// Wait for radio checked attribute to be updated;
await TestHelper.whenTrue(() => radioChecked(selectedIndex));
expect(radioChecked(selectedIndex)).toBeTrue();
});
it('should not emit change event when the bound ngModel is updated', async () => {
const onChangeSpy = spyOn(spectator.component.valueChange, 'emit');
await setSelectedOnHostComponent(items[0]);
expect(onChangeSpy).not.toHaveBeenCalled();
});
});
});
describe('and pre-selected item', () => {
beforeEach(async () => {
spectator = createHost(
`<kirby-radio-group [items]="items" [(ngModel)]="selected">
</kirby-radio-group>`,
{
hostProps: {
items: items,
selected: items[defaultSelectedIndex],
},
}
);
await TestHelper.waitForTimeout();
spectator.detectChanges();
ionRadioGroup = spectator.query(IonRadioGroup);
const ionRadioGroupElement = spectator.query('ion-radio-group');
await TestHelper.whenReady(ionRadioGroupElement);
radios = spectator.queryAll(RadioComponent);
ionRadioElements = spectator.queryAll('ion-radio');
await TestHelper.whenReady(ionRadioElements);
await TestHelper.whenTrue(() => radioChecked(defaultSelectedIndex));
});
describe('selection', () => {
let newSelectedIndex: number;
it('should update the bound ngModel when clicking a different radio item', () => {
newSelectedIndex = defaultSelectedIndex + 1;
spectator.click(ionRadioElements[newSelectedIndex]);
expect(spectator.hostComponent.selected).toEqual(items[newSelectedIndex]);
});
it('should update the value of ion-radio-group when the bound ngModel is updated', async () => {
const newSelectedValue = items[defaultSelectedIndex + 1];
await setSelectedOnHostComponent(items[newSelectedValue]);
expect(ionRadioGroup.value).toEqual(items[newSelectedValue]);
});
it('should update the selected radio when the bound ngModel is updated', async () => {
newSelectedIndex = defaultSelectedIndex + 1;
await setSelectedOnHostComponent(items[newSelectedIndex]);
// Wait for radio checked attribute to be updated;
await TestHelper.whenTrue(() => radioChecked(newSelectedIndex));
expect(radioChecked(defaultSelectedIndex)).toBeFalse();
expect(radioChecked(newSelectedIndex)).toBeTrue();
});
it('should not emit change event when the bound ngModel is updated', async () => {
const onChangeSpy = spyOn(spectator.component.valueChange, 'emit');
newSelectedIndex = defaultSelectedIndex + 1;
await setSelectedOnHostComponent(items[newSelectedIndex]);
expect(onChangeSpy).not.toHaveBeenCalled();
});
});
});
describe('error state when ngModel is required', () => {
beforeEach(async () => {
spectator = createHost(
`<kirby-radio-group [items]="items" [(ngModel)]="selected" required>
</kirby-radio-group>`,
{
hostProps: {
items: items,
selected: null,
},
}
);
ionRadioGroup = spectator.query(IonRadioGroup);
const ionRadioGroupElement = spectator.query('ion-radio-group');
await TestHelper.whenReady(ionRadioGroupElement);
radios = spectator.queryAll(RadioComponent);
ionRadioElements = spectator.queryAll('ion-radio');
await TestHelper.whenReady(ionRadioElements);
});
describe('when ngModel is not null', () => {
beforeEach(async () => {
await setSelectedOnHostComponent(items[defaultSelectedIndex]);
});
describe('and component has been touched', () => {
beforeEach(() => {
ionRadioElements[0].focus();
ionRadioElements[0].blur();
spectator.detectChanges();
});
it('should not be in error state', () => {
ionRadioElements.forEach((ionRadioElement) => {
const radioIcon = ionRadioElement.shadowRoot.querySelector('[part=container]');
expect(radioIcon).toHaveComputedStyle(radioBorderDefault);
});
});
});
describe('and component has not been touched', () => {
it('should not be in error state', () => {
ionRadioElements.forEach((ionRadioElement) => {
const radioIcon = ionRadioElement.shadowRoot.querySelector('[part=container]');
expect(radioIcon).toHaveComputedStyle(radioBorderDefault);
});
});
});
});
describe('when ngModel is null', () => {
describe('and component has been touched', () => {
beforeEach(() => {
ionRadioElements[0].focus();
ionRadioElements[0].blur();
spectator.detectChanges();
});
it('should be in error state', () => {
ionRadioElements.forEach((ionRadioElement) => {
const radioIcon = ionRadioElement.shadowRoot.querySelector('[part=container]');
expect(radioIcon).toHaveComputedStyle(radioBorderErrorState);
});
});
});
describe('and component has not been touched', () => {
it('should not be in error state', () => {
ionRadioElements.forEach((ionRadioElement) => {
const radioIcon = ionRadioElement.shadowRoot.querySelector('[part=container]');
expect(radioIcon).toHaveComputedStyle(radioBorderDefault);
});
});
});
});
});
async function setSelectedOnHostComponent(value: any): Promise<void> {
spectator.setHostInput('selected', value);
await TestHelper.waitForTimeout();
spectator.detectChanges();
}
});
describe('with a reactive form', () => {
let favoriteFoodControl: FormControl;
let spectator: SpectatorHost<
RadioGroupComponent,
{
favoriteFoodForm: FormGroup;
items: string[];
}
>;
describe('and no pre-selected item', () => {
beforeEach(async () => {
favoriteFoodControl = new FormControl();
spectator = createHost(
`<form [formGroup]="favoriteFoodForm">
<kirby-radio-group [items]="items" formControlName="favoriteFood">
</kirby-radio-group>
</form>`,
{
hostProps: {
favoriteFoodForm: new FormGroup({
favoriteFood: favoriteFoodControl,
}),
items: items,
},
}
);
ionRadioGroup = spectator.query(IonRadioGroup);
const ionRadioGroupElement = spectator.query('ion-radio-group');
await TestHelper.whenReady(ionRadioGroupElement);
radios = spectator.queryAll(RadioComponent);
ionRadioElements = spectator.queryAll('ion-radio');
await TestHelper.whenReady(ionRadioElements);
});
describe('selection', () => {
it('should update the value of ion-radio-group when the bound form control is set to a value', async () => {
const newFavoriteFood = items[0];
await setFormControlValue(newFavoriteFood);
expect(ionRadioGroup.value).toEqual(newFavoriteFood);
});
it('should update the selected radio when the bound form control is set to a value', async () => {
const selectedIndex = 0;
await setFormControlValue(items[selectedIndex]);
// Wait for radio checked attribute to be updated;
await TestHelper.whenTrue(() => radioChecked(selectedIndex));
expect(radioChecked(selectedIndex)).toBeTrue();
});
it('should not emit change event when the bound form control is set to a value', async () => {
const onChangeSpy = spyOn(spectator.component.valueChange, 'emit');
await setFormControlValue(items[0]);
expect(onChangeSpy).not.toHaveBeenCalled();
});
});
});
describe('and pre-selected item', () => {
beforeEach(async () => {
favoriteFoodControl = new FormControl(items[defaultSelectedIndex]);
spectator = createHost(
`<form [formGroup]="favoriteFoodForm">
<kirby-radio-group [items]="items" formControlName="favoriteFood">
</kirby-radio-group>
</form>`,
{
hostProps: {
favoriteFoodForm: new FormGroup({
favoriteFood: favoriteFoodControl,
}),
items: items,
},
}
);
ionRadioGroup = spectator.query(IonRadioGroup);
const ionRadioGroupElement = spectator.query('ion-radio-group');
await TestHelper.whenReady(ionRadioGroupElement);
radios = spectator.queryAll(RadioComponent);
ionRadioElements = spectator.queryAll('ion-radio');
await TestHelper.whenReady(ionRadioElements);
});
describe('selection', () => {
it('should have selected index corresponding to the selected data item', () => {
expect(spectator.component.selectedIndex).toBe(defaultSelectedIndex);
});
it('should update the bound form control when clicking a different radio item', () => {
spectator.click(ionRadioElements[defaultSelectedIndex]);
expect(favoriteFoodControl.value).toEqual(items[defaultSelectedIndex]);
});
it('should update the value of ion-radio-group when the bound form control is updated', async () => {
const newControlValue = items[defaultSelectedIndex + 1];
await setFormControlValue(newControlValue);
expect(ionRadioGroup.value).toEqual(newControlValue);
});
it('should update the selected radio when the bound form control is updated', async () => {
const newSelectedIndex = defaultSelectedIndex + 1;
await setFormControlValue(items[newSelectedIndex]);
// Wait for radio checked attribute to be updated;
await TestHelper.whenTrue(() => radioChecked(newSelectedIndex));
expect(radioChecked(defaultSelectedIndex)).toBeFalse();
expect(radioChecked(newSelectedIndex)).toBeTrue();
});
it('should not emit change event when the bound form control is updated', async () => {
const onChangeSpy = spyOn(spectator.component.valueChange, 'emit');
await setFormControlValue(items[defaultSelectedIndex + 1]);
expect(onChangeSpy).not.toHaveBeenCalled();
});
});
describe('enablement', () => {
it('should not disable the radio items by default', () => {
radios.forEach((each) => expect(each.disabled).toBeUndefined());
});
it('should disable the radio items when the bound form control is disabled', () => {
favoriteFoodControl.disable();
spectator.detectChanges();
radios.forEach((each) => expect(each.disabled).toBeTrue());
});
it('should re-enable the radio items when the bound form control is enabled', () => {
favoriteFoodControl.disable();
spectator.detectChanges();
radios.forEach((each) => expect(each.disabled).toBeTrue());
favoriteFoodControl.enable();
spectator.detectChanges();
radios.forEach((each) => expect(each.disabled).toBeUndefined());
});
it('should disable the radios if radios are set after the bound form control is disabled', async () => {
spectator.setHostInput('items', null);
favoriteFoodControl.disable();
await TestHelper.waitForTimeout();
spectator.detectChanges();
spectator.setHostInput('items', items);
await TestHelper.waitForTimeout();
spectator.detectChanges();
radios = spectator.queryAll(RadioComponent);
radios.forEach((each) => expect(each.disabled).toBeTrue());
});
});
});
describe('error state when the bound form control is required', () => {
beforeEach(async () => {
favoriteFoodControl = new FormControl(null, Validators.required);
spectator = createHost(
`<form [formGroup]="favoriteFoodForm">
<kirby-radio-group [items]="items" formControlName="favoriteFood">
</kirby-radio-group>
</form>`,
{
hostProps: {
favoriteFoodForm: new FormGroup({
favoriteFood: favoriteFoodControl,
}),
items: items,
},
}
);
ionRadioGroup = spectator.query(IonRadioGroup);
const ionRadioGroupElement = spectator.query('ion-radio-group');
await TestHelper.whenReady(ionRadioGroupElement);
radios = spectator.queryAll(RadioComponent);
ionRadioElements = spectator.queryAll('ion-radio');
await TestHelper.whenReady(ionRadioElements);
});
describe('when the value of the bound form control is not null', () => {
beforeEach(async () => {
await setFormControlValue(items[defaultSelectedIndex]);
});
describe('and the component has been touched', () => {
beforeEach(() => {
ionRadioElements[0].focus();
ionRadioElements[0].blur();
spectator.detectChanges();
});
it('should not be in error state', () => {
ionRadioElements.forEach((ionRadioElement) => {
const radioIcon = ionRadioElement.shadowRoot.querySelector('[part=container]');
expect(radioIcon).toHaveComputedStyle(radioBorderDefault);
});
});
});
describe('and the component has not been touched', () => {
it('should not be in error state', () => {
ionRadioElements.forEach((ionRadioElement) => {
const radioIcon = ionRadioElement.shadowRoot.querySelector('[part=container]');
expect(radioIcon).toHaveComputedStyle(radioBorderDefault);
});
});
});
});
describe('when the value of the bound form control is null', () => {
describe('and the component has been touched', () => {
beforeEach(() => {
ionRadioElements[0].focus();
ionRadioElements[0].blur();
spectator.detectChanges();
});
it('should be in error state', () => {
ionRadioElements.forEach((ionRadioElement) => {
const radioIcon = ionRadioElement.shadowRoot.querySelector('[part=container]');
expect(radioIcon).toHaveComputedStyle(radioBorderErrorState);
});
});
});
describe('and the component has not been touched', () => {
beforeEach(async () => {
await TestHelper.waitForTimeout();
spectator.detectChanges();
});
it('should not be in error state', () => {
ionRadioElements.forEach((ionRadioElement) => {
const radioIcon = ionRadioElement.shadowRoot.querySelector('[part=container]');
expect(radioIcon).toHaveComputedStyle(radioBorderDefault);
});
});
});
});
});
async function setFormControlValue(value: any): Promise<void> {
favoriteFoodControl.setValue(value);
await TestHelper.waitForTimeout();
spectator.detectChanges();
}
});
});
}); | the_stack |
namespace ts {
export interface DocumentHighlights {
fileName: string;
highlightSpans: HighlightSpan[];
}
/* @internal */
export namespace DocumentHighlights {
export function getDocumentHighlights(program: Program, cancellationToken: CancellationToken, sourceFile: SourceFile, position: number, sourceFilesToSearch: readonly SourceFile[]): DocumentHighlights[] | undefined {
const node = getTouchingPropertyName(sourceFile, position);
if (node.parent && (isJsxOpeningElement(node.parent) && node.parent.tagName === node || isJsxClosingElement(node.parent))) {
// For a JSX element, just highlight the matching tag, not all references.
const { openingElement, closingElement } = node.parent.parent;
const highlightSpans = [openingElement, closingElement].map(({ tagName }) => getHighlightSpanForNode(tagName, sourceFile));
return [{ fileName: sourceFile.fileName, highlightSpans }];
}
return getSemanticDocumentHighlights(position, node, program, cancellationToken, sourceFilesToSearch) || getSyntacticDocumentHighlights(node, sourceFile);
}
function getHighlightSpanForNode(node: Node, sourceFile: SourceFile): HighlightSpan {
return {
fileName: sourceFile.fileName,
textSpan: createTextSpanFromNode(node, sourceFile),
kind: HighlightSpanKind.none
};
}
function getSemanticDocumentHighlights(position: number, node: Node, program: Program, cancellationToken: CancellationToken, sourceFilesToSearch: readonly SourceFile[]): DocumentHighlights[] | undefined {
const sourceFilesSet = new Set(sourceFilesToSearch.map(f => f.fileName));
const referenceEntries = FindAllReferences.getReferenceEntriesForNode(position, node, program, sourceFilesToSearch, cancellationToken, /*options*/ undefined, sourceFilesSet);
if (!referenceEntries) return undefined;
const map = arrayToMultiMap(referenceEntries.map(FindAllReferences.toHighlightSpan), e => e.fileName, e => e.span);
const getCanonicalFileName = createGetCanonicalFileName(program.useCaseSensitiveFileNames());
return mapDefined(arrayFrom(map.entries()), ([fileName, highlightSpans]) => {
if (!sourceFilesSet.has(fileName)) {
if (!program.redirectTargetsMap.has(toPath(fileName, program.getCurrentDirectory(), getCanonicalFileName))) {
return undefined;
}
const redirectTarget = program.getSourceFile(fileName);
const redirect = find(sourceFilesToSearch, f => !!f.redirectInfo && f.redirectInfo.redirectTarget === redirectTarget)!;
fileName = redirect.fileName;
Debug.assert(sourceFilesSet.has(fileName));
}
return { fileName, highlightSpans };
});
}
function getSyntacticDocumentHighlights(node: Node, sourceFile: SourceFile): DocumentHighlights[] | undefined {
const highlightSpans = getHighlightSpans(node, sourceFile);
return highlightSpans && [{ fileName: sourceFile.fileName, highlightSpans }];
}
function getHighlightSpans(node: Node, sourceFile: SourceFile): HighlightSpan[] | undefined {
switch (node.kind) {
case SyntaxKind.IfKeyword:
case SyntaxKind.ElseKeyword:
return isIfStatement(node.parent) ? getIfElseOccurrences(node.parent, sourceFile) : undefined;
case SyntaxKind.ReturnKeyword:
return useParent(node.parent, isReturnStatement, getReturnOccurrences);
case SyntaxKind.ThrowKeyword:
return useParent(node.parent, isThrowStatement, getThrowOccurrences);
case SyntaxKind.TryKeyword:
case SyntaxKind.CatchKeyword:
case SyntaxKind.FinallyKeyword:
const tryStatement = node.kind === SyntaxKind.CatchKeyword ? node.parent.parent : node.parent;
return useParent(tryStatement, isTryStatement, getTryCatchFinallyOccurrences);
case SyntaxKind.SwitchKeyword:
return useParent(node.parent, isSwitchStatement, getSwitchCaseDefaultOccurrences);
case SyntaxKind.CaseKeyword:
case SyntaxKind.DefaultKeyword: {
if (isDefaultClause(node.parent) || isCaseClause(node.parent)) {
return useParent(node.parent.parent.parent, isSwitchStatement, getSwitchCaseDefaultOccurrences);
}
return undefined;
}
case SyntaxKind.BreakKeyword:
case SyntaxKind.ContinueKeyword:
return useParent(node.parent, isBreakOrContinueStatement, getBreakOrContinueStatementOccurrences);
case SyntaxKind.ForKeyword:
case SyntaxKind.WhileKeyword:
case SyntaxKind.DoKeyword:
return useParent(node.parent, (n): n is IterationStatement => isIterationStatement(n, /*lookInLabeledStatements*/ true), getLoopBreakContinueOccurrences);
case SyntaxKind.ConstructorKeyword:
return getFromAllDeclarations(isConstructorDeclaration, [SyntaxKind.ConstructorKeyword]);
case SyntaxKind.GetKeyword:
case SyntaxKind.SetKeyword:
return getFromAllDeclarations(isAccessor, [SyntaxKind.GetKeyword, SyntaxKind.SetKeyword]);
case SyntaxKind.AwaitKeyword:
return useParent(node.parent, isAwaitExpression, getAsyncAndAwaitOccurrences);
case SyntaxKind.AsyncKeyword:
return highlightSpans(getAsyncAndAwaitOccurrences(node));
case SyntaxKind.YieldKeyword:
return highlightSpans(getYieldOccurrences(node));
default:
return isModifierKind(node.kind) && (isDeclaration(node.parent) || isVariableStatement(node.parent))
? highlightSpans(getModifierOccurrences(node.kind, node.parent))
: undefined;
}
function getFromAllDeclarations<T extends Node>(nodeTest: (node: Node) => node is T, keywords: readonly SyntaxKind[]): HighlightSpan[] | undefined {
return useParent(node.parent, nodeTest, decl => mapDefined(decl.symbol.declarations, d =>
nodeTest(d) ? find(d.getChildren(sourceFile), c => contains(keywords, c.kind)) : undefined));
}
function useParent<T extends Node>(node: Node, nodeTest: (node: Node) => node is T, getNodes: (node: T, sourceFile: SourceFile) => readonly Node[] | undefined): HighlightSpan[] | undefined {
return nodeTest(node) ? highlightSpans(getNodes(node, sourceFile)) : undefined;
}
function highlightSpans(nodes: readonly Node[] | undefined): HighlightSpan[] | undefined {
return nodes && nodes.map(node => getHighlightSpanForNode(node, sourceFile));
}
}
/**
* Aggregates all throw-statements within this node *without* crossing
* into function boundaries and try-blocks with catch-clauses.
*/
function aggregateOwnedThrowStatements(node: Node): readonly ThrowStatement[] | undefined {
if (isThrowStatement(node)) {
return [node];
}
else if (isTryStatement(node)) {
// Exceptions thrown within a try block lacking a catch clause are "owned" in the current context.
return concatenate(
node.catchClause ? aggregateOwnedThrowStatements(node.catchClause) : node.tryBlock && aggregateOwnedThrowStatements(node.tryBlock),
node.finallyBlock && aggregateOwnedThrowStatements(node.finallyBlock));
}
// Do not cross function boundaries.
return isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateOwnedThrowStatements);
}
/**
* For lack of a better name, this function takes a throw statement and returns the
* nearest ancestor that is a try-block (whose try statement has a catch clause),
* function-block, or source file.
*/
function getThrowStatementOwner(throwStatement: ThrowStatement): Node | undefined {
let child: Node = throwStatement;
while (child.parent) {
const parent = child.parent;
if (isFunctionBlock(parent) || parent.kind === SyntaxKind.SourceFile) {
return parent;
}
// A throw-statement is only owned by a try-statement if the try-statement has
// a catch clause, and if the throw-statement occurs within the try block.
if (isTryStatement(parent) && parent.tryBlock === child && parent.catchClause) {
return child;
}
child = parent;
}
return undefined;
}
function aggregateAllBreakAndContinueStatements(node: Node): readonly BreakOrContinueStatement[] | undefined {
return isBreakOrContinueStatement(node) ? [node] : isFunctionLike(node) ? undefined : flatMapChildren(node, aggregateAllBreakAndContinueStatements);
}
function flatMapChildren<T>(node: Node, cb: (child: Node) => readonly T[] | T | undefined): readonly T[] {
const result: T[] = [];
node.forEachChild(child => {
const value = cb(child);
if (value !== undefined) {
result.push(...toArray(value));
}
});
return result;
}
function ownsBreakOrContinueStatement(owner: Node, statement: BreakOrContinueStatement): boolean {
const actualOwner = getBreakOrContinueOwner(statement);
return !!actualOwner && actualOwner === owner;
}
function getBreakOrContinueOwner(statement: BreakOrContinueStatement): Node | undefined {
return findAncestor(statement, node => {
switch (node.kind) {
case SyntaxKind.SwitchStatement:
if (statement.kind === SyntaxKind.ContinueStatement) {
return false;
}
// falls through
case SyntaxKind.ForStatement:
case SyntaxKind.ForInStatement:
case SyntaxKind.ForOfStatement:
case SyntaxKind.WhileStatement:
case SyntaxKind.DoStatement:
return !statement.label || isLabeledBy(node, statement.label.escapedText);
default:
// Don't cross function boundaries.
// TODO: GH#20090
return isFunctionLike(node) && "quit";
}
});
}
function getModifierOccurrences(modifier: Modifier["kind"], declaration: Node): Node[] {
return mapDefined(getNodesToSearchForModifier(declaration, modifierToFlag(modifier)), node => findModifier(node, modifier));
}
function getNodesToSearchForModifier(declaration: Node, modifierFlag: ModifierFlags): readonly Node[] | undefined {
// Types of node whose children might have modifiers.
const container = declaration.parent as ModuleBlock | SourceFile | Block | CaseClause | DefaultClause | ConstructorDeclaration | MethodDeclaration | FunctionDeclaration | ObjectTypeDeclaration | ObjectLiteralExpression;
switch (container.kind) {
case SyntaxKind.ModuleBlock:
case SyntaxKind.SourceFile:
case SyntaxKind.Block:
case SyntaxKind.CaseClause:
case SyntaxKind.DefaultClause:
// Container is either a class declaration or the declaration is a classDeclaration
if (modifierFlag & ModifierFlags.Abstract && isClassDeclaration(declaration)) {
return [...declaration.members, declaration];
}
else {
return container.statements;
}
case SyntaxKind.Constructor:
case SyntaxKind.MethodDeclaration:
case SyntaxKind.FunctionDeclaration:
return [...container.parameters, ...(isClassLike(container.parent) ? container.parent.members : [])];
case SyntaxKind.ClassDeclaration:
case SyntaxKind.ClassExpression:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.TypeLiteral:
const nodes = container.members;
// If we're an accessibility modifier, we're in an instance member and should search
// the constructor's parameter list for instance members as well.
if (modifierFlag & (ModifierFlags.AccessibilityModifier | ModifierFlags.Readonly)) {
const constructor = find(container.members, isConstructorDeclaration);
if (constructor) {
return [...nodes, ...constructor.parameters];
}
}
else if (modifierFlag & ModifierFlags.Abstract) {
return [...nodes, container];
}
return nodes;
// Syntactically invalid positions that the parser might produce anyway
case SyntaxKind.ObjectLiteralExpression:
return undefined;
default:
Debug.assertNever(container, "Invalid container kind.");
}
}
function pushKeywordIf(keywordList: Push<Node>, token: Node | undefined, ...expected: SyntaxKind[]): boolean {
if (token && contains(expected, token.kind)) {
keywordList.push(token);
return true;
}
return false;
}
function getLoopBreakContinueOccurrences(loopNode: IterationStatement): Node[] {
const keywords: Node[] = [];
if (pushKeywordIf(keywords, loopNode.getFirstToken(), SyntaxKind.ForKeyword, SyntaxKind.WhileKeyword, SyntaxKind.DoKeyword)) {
// If we succeeded and got a do-while loop, then start looking for a 'while' keyword.
if (loopNode.kind === SyntaxKind.DoStatement) {
const loopTokens = loopNode.getChildren();
for (let i = loopTokens.length - 1; i >= 0; i--) {
if (pushKeywordIf(keywords, loopTokens[i], SyntaxKind.WhileKeyword)) {
break;
}
}
}
}
forEach(aggregateAllBreakAndContinueStatements(loopNode.statement), statement => {
if (ownsBreakOrContinueStatement(loopNode, statement)) {
pushKeywordIf(keywords, statement.getFirstToken(), SyntaxKind.BreakKeyword, SyntaxKind.ContinueKeyword);
}
});
return keywords;
}
function getBreakOrContinueStatementOccurrences(breakOrContinueStatement: BreakOrContinueStatement): Node[] | undefined {
const owner = getBreakOrContinueOwner(breakOrContinueStatement);
if (owner) {
switch (owner.kind) {
case SyntaxKind.ForStatement:
case SyntaxKind.ForInStatement:
case SyntaxKind.ForOfStatement:
case SyntaxKind.DoStatement:
case SyntaxKind.WhileStatement:
return getLoopBreakContinueOccurrences(owner as IterationStatement);
case SyntaxKind.SwitchStatement:
return getSwitchCaseDefaultOccurrences(owner as SwitchStatement);
}
}
return undefined;
}
function getSwitchCaseDefaultOccurrences(switchStatement: SwitchStatement): Node[] {
const keywords: Node[] = [];
pushKeywordIf(keywords, switchStatement.getFirstToken(), SyntaxKind.SwitchKeyword);
// Go through each clause in the switch statement, collecting the 'case'/'default' keywords.
forEach(switchStatement.caseBlock.clauses, clause => {
pushKeywordIf(keywords, clause.getFirstToken(), SyntaxKind.CaseKeyword, SyntaxKind.DefaultKeyword);
forEach(aggregateAllBreakAndContinueStatements(clause), statement => {
if (ownsBreakOrContinueStatement(switchStatement, statement)) {
pushKeywordIf(keywords, statement.getFirstToken(), SyntaxKind.BreakKeyword);
}
});
});
return keywords;
}
function getTryCatchFinallyOccurrences(tryStatement: TryStatement, sourceFile: SourceFile): Node[] {
const keywords: Node[] = [];
pushKeywordIf(keywords, tryStatement.getFirstToken(), SyntaxKind.TryKeyword);
if (tryStatement.catchClause) {
pushKeywordIf(keywords, tryStatement.catchClause.getFirstToken(), SyntaxKind.CatchKeyword);
}
if (tryStatement.finallyBlock) {
const finallyKeyword = findChildOfKind(tryStatement, SyntaxKind.FinallyKeyword, sourceFile)!;
pushKeywordIf(keywords, finallyKeyword, SyntaxKind.FinallyKeyword);
}
return keywords;
}
function getThrowOccurrences(throwStatement: ThrowStatement, sourceFile: SourceFile): Node[] | undefined {
const owner = getThrowStatementOwner(throwStatement);
if (!owner) {
return undefined;
}
const keywords: Node[] = [];
forEach(aggregateOwnedThrowStatements(owner), throwStatement => {
keywords.push(findChildOfKind(throwStatement, SyntaxKind.ThrowKeyword, sourceFile)!);
});
// If the "owner" is a function, then we equate 'return' and 'throw' statements in their
// ability to "jump out" of the function, and include occurrences for both.
if (isFunctionBlock(owner)) {
forEachReturnStatement(owner as Block, returnStatement => {
keywords.push(findChildOfKind(returnStatement, SyntaxKind.ReturnKeyword, sourceFile)!);
});
}
return keywords;
}
function getReturnOccurrences(returnStatement: ReturnStatement, sourceFile: SourceFile): Node[] | undefined {
const func = getContainingFunction(returnStatement) as FunctionLikeDeclaration;
if (!func) {
return undefined;
}
const keywords: Node[] = [];
forEachReturnStatement(cast(func.body, isBlock), returnStatement => {
keywords.push(findChildOfKind(returnStatement, SyntaxKind.ReturnKeyword, sourceFile)!);
});
// Include 'throw' statements that do not occur within a try block.
forEach(aggregateOwnedThrowStatements(func.body!), throwStatement => {
keywords.push(findChildOfKind(throwStatement, SyntaxKind.ThrowKeyword, sourceFile)!);
});
return keywords;
}
function getAsyncAndAwaitOccurrences(node: Node): Node[] | undefined {
const func = getContainingFunction(node) as FunctionLikeDeclaration;
if (!func) {
return undefined;
}
const keywords: Node[] = [];
if (func.modifiers) {
func.modifiers.forEach(modifier => {
pushKeywordIf(keywords, modifier, SyntaxKind.AsyncKeyword);
});
}
forEachChild(func, child => {
traverseWithoutCrossingFunction(child, node => {
if (isAwaitExpression(node)) {
pushKeywordIf(keywords, node.getFirstToken(), SyntaxKind.AwaitKeyword);
}
});
});
return keywords;
}
function getYieldOccurrences(node: Node): Node[] | undefined {
const func = getContainingFunction(node) as FunctionDeclaration;
if (!func) {
return undefined;
}
const keywords: Node[] = [];
forEachChild(func, child => {
traverseWithoutCrossingFunction(child, node => {
if (isYieldExpression(node)) {
pushKeywordIf(keywords, node.getFirstToken(), SyntaxKind.YieldKeyword);
}
});
});
return keywords;
}
// Do not cross function/class/interface/module/type boundaries.
function traverseWithoutCrossingFunction(node: Node, cb: (node: Node) => void) {
cb(node);
if (!isFunctionLike(node) && !isClassLike(node) && !isInterfaceDeclaration(node) && !isModuleDeclaration(node) && !isTypeAliasDeclaration(node) && !isTypeNode(node)) {
forEachChild(node, child => traverseWithoutCrossingFunction(child, cb));
}
}
function getIfElseOccurrences(ifStatement: IfStatement, sourceFile: SourceFile): HighlightSpan[] {
const keywords = getIfElseKeywords(ifStatement, sourceFile);
const result: HighlightSpan[] = [];
// We'd like to highlight else/ifs together if they are only separated by whitespace
// (i.e. the keywords are separated by no comments, no newlines).
for (let i = 0; i < keywords.length; i++) {
if (keywords[i].kind === SyntaxKind.ElseKeyword && i < keywords.length - 1) {
const elseKeyword = keywords[i];
const ifKeyword = keywords[i + 1]; // this *should* always be an 'if' keyword.
let shouldCombineElseAndIf = true;
// Avoid recalculating getStart() by iterating backwards.
for (let j = ifKeyword.getStart(sourceFile) - 1; j >= elseKeyword.end; j--) {
if (!isWhiteSpaceSingleLine(sourceFile.text.charCodeAt(j))) {
shouldCombineElseAndIf = false;
break;
}
}
if (shouldCombineElseAndIf) {
result.push({
fileName: sourceFile.fileName,
textSpan: createTextSpanFromBounds(elseKeyword.getStart(), ifKeyword.end),
kind: HighlightSpanKind.reference
});
i++; // skip the next keyword
continue;
}
}
// Ordinary case: just highlight the keyword.
result.push(getHighlightSpanForNode(keywords[i], sourceFile));
}
return result;
}
function getIfElseKeywords(ifStatement: IfStatement, sourceFile: SourceFile): Node[] {
const keywords: Node[] = [];
// Traverse upwards through all parent if-statements linked by their else-branches.
while (isIfStatement(ifStatement.parent) && ifStatement.parent.elseStatement === ifStatement) {
ifStatement = ifStatement.parent;
}
// Now traverse back down through the else branches, aggregating if/else keywords of if-statements.
while (true) {
const children = ifStatement.getChildren(sourceFile);
pushKeywordIf(keywords, children[0], SyntaxKind.IfKeyword);
// Generally the 'else' keyword is second-to-last, so we traverse backwards.
for (let i = children.length - 1; i >= 0; i--) {
if (pushKeywordIf(keywords, children[i], SyntaxKind.ElseKeyword)) {
break;
}
}
if (!ifStatement.elseStatement || !isIfStatement(ifStatement.elseStatement)) {
break;
}
ifStatement = ifStatement.elseStatement;
}
return keywords;
}
/**
* Whether or not a 'node' is preceded by a label of the given string.
* Note: 'node' cannot be a SourceFile.
*/
function isLabeledBy(node: Node, labelName: __String): boolean {
return !!findAncestor(node.parent, owner => !isLabeledStatement(owner) ? "quit" : owner.label.escapedText === labelName);
}
}
} | the_stack |
import {EntitySubscriberInterface} from "./EntitySubscriberInterface";
import {ObjectLiteral} from "../common/ObjectLiteral";
import {QueryRunner} from "../query-runner/QueryRunner";
import {EntityMetadata} from "../metadata/EntityMetadata";
import {BroadcasterResult} from "./BroadcasterResult";
import {ColumnMetadata} from "../metadata/ColumnMetadata";
import {RelationMetadata} from "../metadata/RelationMetadata";
interface BroadcasterEvents {
"BeforeTransactionCommit": () => void;
"AfterTransactionCommit": () => void;
"BeforeTransactionStart": () => void;
"AfterTransactionStart": () => void;
"BeforeTransactionRollback": () => void;
"AfterTransactionRollback": () => void;
"BeforeUpdate": (metadata: EntityMetadata, entity?: ObjectLiteral, databaseEntity?: ObjectLiteral, updatedColumns?: ColumnMetadata[], updatedRelations?: RelationMetadata[]) => void;
"AfterUpdate": (metadata: EntityMetadata, entity?: ObjectLiteral, databaseEntity?: ObjectLiteral, updatedColumns?: ColumnMetadata[], updatedRelations?: RelationMetadata[]) => void;
"BeforeInsert": (metadata: EntityMetadata, entity: ObjectLiteral | undefined) => void;
"AfterInsert": (metadata: EntityMetadata, entity: ObjectLiteral | undefined) => void;
"BeforeRemove": (metadata: EntityMetadata, entity?: ObjectLiteral, databaseEntity?: ObjectLiteral) => void;
"AfterRemove": (metadata: EntityMetadata, entity?: ObjectLiteral, databaseEntity?: ObjectLiteral) => void;
"Load": (metadata: EntityMetadata, entities: ObjectLiteral[]) => void;
}
/**
* Broadcaster provides a helper methods to broadcast events to the subscribers.
*/
export class Broadcaster {
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
constructor(private queryRunner: QueryRunner) {
}
// -------------------------------------------------------------------------
// Public Methods
// -------------------------------------------------------------------------
async broadcast<U extends keyof BroadcasterEvents>(event: U, ...args: Parameters<BroadcasterEvents[U]>): Promise<void> {
const result = new BroadcasterResult();
const broadcastFunction = this[`broadcast${event}Event` as keyof this];
if (typeof broadcastFunction === "function") {
(broadcastFunction as any).call(
this,
result,
...args
);
}
await result.wait();
}
/**
* Broadcasts "BEFORE_INSERT" event.
* Before insert event is executed before entity is being inserted to the database for the first time.
* All subscribers and entity listeners who listened to this event will be executed at this point.
* Subscribers and entity listeners can return promises, it will wait until they are resolved.
*
* Note: this method has a performance-optimized code organization, do not change code structure.
*/
broadcastBeforeInsertEvent(result: BroadcasterResult, metadata: EntityMetadata, entity: undefined | ObjectLiteral): void {
if (entity && metadata.beforeInsertListeners.length) {
metadata.beforeInsertListeners.forEach(listener => {
if (listener.isAllowed(entity)) {
const executionResult = listener.execute(entity);
if (executionResult instanceof Promise)
result.promises.push(executionResult);
result.count++;
}
});
}
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(subscriber => {
if (this.isAllowedSubscriber(subscriber, metadata.target) && subscriber.beforeInsert) {
const executionResult = subscriber.beforeInsert({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
entity: entity,
metadata: metadata
});
if (executionResult instanceof Promise)
result.promises.push(executionResult);
result.count++;
}
});
}
}
/**
* Broadcasts "BEFORE_UPDATE" event.
* Before update event is executed before entity is being updated in the database.
* All subscribers and entity listeners who listened to this event will be executed at this point.
* Subscribers and entity listeners can return promises, it will wait until they are resolved.
*
* Note: this method has a performance-optimized code organization, do not change code structure.
*/
broadcastBeforeUpdateEvent(result: BroadcasterResult, metadata: EntityMetadata, entity?: ObjectLiteral, databaseEntity?: ObjectLiteral, updatedColumns?: ColumnMetadata[], updatedRelations?: RelationMetadata[]): void { // todo: send relations too?
if (entity && metadata.beforeUpdateListeners.length) {
metadata.beforeUpdateListeners.forEach(listener => {
if (listener.isAllowed(entity)) {
const executionResult = listener.execute(entity);
if (executionResult instanceof Promise)
result.promises.push(executionResult);
result.count++;
}
});
}
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(subscriber => {
if (this.isAllowedSubscriber(subscriber, metadata.target) && subscriber.beforeUpdate) {
const executionResult = subscriber.beforeUpdate({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
entity: entity,
metadata: metadata,
databaseEntity: databaseEntity,
updatedColumns: updatedColumns || [],
updatedRelations: updatedRelations || []
});
if (executionResult instanceof Promise)
result.promises.push(executionResult);
result.count++;
}
});
}
}
/**
* Broadcasts "BEFORE_REMOVE" event.
* Before remove event is executed before entity is being removed from the database.
* All subscribers and entity listeners who listened to this event will be executed at this point.
* Subscribers and entity listeners can return promises, it will wait until they are resolved.
*
* Note: this method has a performance-optimized code organization, do not change code structure.
*/
broadcastBeforeRemoveEvent(result: BroadcasterResult, metadata: EntityMetadata, entity?: ObjectLiteral, databaseEntity?: ObjectLiteral): void {
if (entity && metadata.beforeRemoveListeners.length) {
metadata.beforeRemoveListeners.forEach(listener => {
if (listener.isAllowed(entity)) {
const executionResult = listener.execute(entity);
if (executionResult instanceof Promise)
result.promises.push(executionResult);
result.count++;
}
});
}
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(subscriber => {
if (this.isAllowedSubscriber(subscriber, metadata.target) && subscriber.beforeRemove) {
const executionResult = subscriber.beforeRemove({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
entity: entity,
metadata: metadata,
databaseEntity: databaseEntity,
entityId: metadata.getEntityIdMixedMap(databaseEntity)
});
if (executionResult instanceof Promise)
result.promises.push(executionResult);
result.count++;
}
});
}
}
/**
* Broadcasts "AFTER_INSERT" event.
* After insert event is executed after entity is being persisted to the database for the first time.
* All subscribers and entity listeners who listened to this event will be executed at this point.
* Subscribers and entity listeners can return promises, it will wait until they are resolved.
*
* Note: this method has a performance-optimized code organization, do not change code structure.
*/
broadcastAfterInsertEvent(result: BroadcasterResult, metadata: EntityMetadata, entity?: ObjectLiteral): void {
if (entity && metadata.afterInsertListeners.length) {
metadata.afterInsertListeners.forEach(listener => {
if (listener.isAllowed(entity)) {
const executionResult = listener.execute(entity);
if (executionResult instanceof Promise)
result.promises.push(executionResult);
result.count++;
}
});
}
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(subscriber => {
if (this.isAllowedSubscriber(subscriber, metadata.target) && subscriber.afterInsert) {
const executionResult = subscriber.afterInsert({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
entity: entity,
metadata: metadata
});
if (executionResult instanceof Promise)
result.promises.push(executionResult);
result.count++;
}
});
}
}
/**
* Broadcasts "BEFORE_TRANSACTION_START" event.
*/
broadcastBeforeTransactionStartEvent(result: BroadcasterResult): void {
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(subscriber => {
if (subscriber.beforeTransactionStart) {
const executionResult = subscriber.beforeTransactionStart({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
});
if (executionResult instanceof Promise)
result.promises.push(executionResult);
result.count++;
}
});
}
}
/**
* Broadcasts "AFTER_TRANSACTION_START" event.
*/
broadcastAfterTransactionStartEvent(result: BroadcasterResult): void {
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(subscriber => {
if (subscriber.afterTransactionStart) {
const executionResult = subscriber.afterTransactionStart({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
});
if (executionResult instanceof Promise)
result.promises.push(executionResult);
result.count++;
}
});
}
}
/**
* Broadcasts "BEFORE_TRANSACTION_COMMIT" event.
*/
broadcastBeforeTransactionCommitEvent(result: BroadcasterResult): void {
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(subscriber => {
if (subscriber.beforeTransactionCommit) {
const executionResult = subscriber.beforeTransactionCommit({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
});
if (executionResult instanceof Promise)
result.promises.push(executionResult);
result.count++;
}
});
}
}
/**
* Broadcasts "AFTER_TRANSACTION_COMMIT" event.
*/
broadcastAfterTransactionCommitEvent(result: BroadcasterResult): void {
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(subscriber => {
if (subscriber.afterTransactionCommit) {
const executionResult = subscriber.afterTransactionCommit({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
});
if (executionResult instanceof Promise)
result.promises.push(executionResult);
result.count++;
}
});
}
}
/**
* Broadcasts "BEFORE_TRANSACTION_ROLLBACK" event.
*/
broadcastBeforeTransactionRollbackEvent(result: BroadcasterResult): void {
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(subscriber => {
if (subscriber.beforeTransactionRollback) {
const executionResult = subscriber.beforeTransactionRollback({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
});
if (executionResult instanceof Promise)
result.promises.push(executionResult);
result.count++;
}
});
}
}
/**
* Broadcasts "AFTER_TRANSACTION_ROLLBACK" event.
*/
broadcastAfterTransactionRollbackEvent(result: BroadcasterResult): void {
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(subscriber => {
if (subscriber.afterTransactionRollback) {
const executionResult = subscriber.afterTransactionRollback({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
});
if (executionResult instanceof Promise)
result.promises.push(executionResult);
result.count++;
}
});
}
}
/**
* Broadcasts "AFTER_UPDATE" event.
* After update event is executed after entity is being updated in the database.
* All subscribers and entity listeners who listened to this event will be executed at this point.
* Subscribers and entity listeners can return promises, it will wait until they are resolved.
*
* Note: this method has a performance-optimized code organization, do not change code structure.
*/
broadcastAfterUpdateEvent(result: BroadcasterResult, metadata: EntityMetadata, entity?: ObjectLiteral, databaseEntity?: ObjectLiteral, updatedColumns?: ColumnMetadata[], updatedRelations?: RelationMetadata[]): void {
if (entity && metadata.afterUpdateListeners.length) {
metadata.afterUpdateListeners.forEach(listener => {
if (listener.isAllowed(entity)) {
const executionResult = listener.execute(entity);
if (executionResult instanceof Promise)
result.promises.push(executionResult);
result.count++;
}
});
}
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(subscriber => {
if (this.isAllowedSubscriber(subscriber, metadata.target) && subscriber.afterUpdate) {
const executionResult = subscriber.afterUpdate({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
entity: entity,
metadata: metadata,
databaseEntity: databaseEntity,
updatedColumns: updatedColumns || [],
updatedRelations: updatedRelations || []
});
if (executionResult instanceof Promise)
result.promises.push(executionResult);
result.count++;
}
});
}
}
/**
* Broadcasts "AFTER_REMOVE" event.
* After remove event is executed after entity is being removed from the database.
* All subscribers and entity listeners who listened to this event will be executed at this point.
* Subscribers and entity listeners can return promises, it will wait until they are resolved.
*
* Note: this method has a performance-optimized code organization, do not change code structure.
*/
broadcastAfterRemoveEvent(result: BroadcasterResult, metadata: EntityMetadata, entity?: ObjectLiteral, databaseEntity?: ObjectLiteral): void {
if (entity && metadata.afterRemoveListeners.length) {
metadata.afterRemoveListeners.forEach(listener => {
if (listener.isAllowed(entity)) {
const executionResult = listener.execute(entity);
if (executionResult instanceof Promise)
result.promises.push(executionResult);
result.count++;
}
});
}
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(subscriber => {
if (this.isAllowedSubscriber(subscriber, metadata.target) && subscriber.afterRemove) {
const executionResult = subscriber.afterRemove({
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
entity: entity,
metadata: metadata,
databaseEntity: databaseEntity,
entityId: metadata.getEntityIdMixedMap(databaseEntity)
});
if (executionResult instanceof Promise)
result.promises.push(executionResult);
result.count++;
}
});
}
}
/**
* @deprecated Use `broadcastLoadForAllEvent`
*/
broadcastLoadEventsForAll(result: BroadcasterResult, metadata: EntityMetadata, entities: ObjectLiteral[]): void {
return this.broadcastLoadEvent(result, metadata, entities);
}
/**
* Broadcasts "AFTER_LOAD" event for all given entities, and their sub-entities.
* After load event is executed after entity has been loaded from the database.
* All subscribers and entity listeners who listened to this event will be executed at this point.
* Subscribers and entity listeners can return promises, it will wait until they are resolved.
*
* Note: this method has a performance-optimized code organization, do not change code structure.
*/
broadcastLoadEvent(result: BroadcasterResult, metadata: EntityMetadata, entities: ObjectLiteral[]): void {
entities.forEach(entity => {
if (entity instanceof Promise) // todo: check why need this?
return;
// collect load events for all children entities that were loaded with the main entity
if (metadata.relations.length) {
metadata.relations.forEach(relation => {
// in lazy relations we cannot simply access to entity property because it will cause a getter and a database query
if (relation.isLazy && !entity.hasOwnProperty(relation.propertyName))
return;
const value = relation.getEntityValue(entity);
if (value instanceof Object)
this.broadcastLoadEvent(result, relation.inverseEntityMetadata, Array.isArray(value) ? value : [value]);
});
}
if (metadata.afterLoadListeners.length) {
metadata.afterLoadListeners.forEach(listener => {
if (listener.isAllowed(entity)) {
const executionResult = listener.execute(entity);
if (executionResult instanceof Promise)
result.promises.push(executionResult);
result.count++;
}
});
}
if (this.queryRunner.connection.subscribers.length) {
this.queryRunner.connection.subscribers.forEach(subscriber => {
if (this.isAllowedSubscriber(subscriber, metadata.target) && subscriber.afterLoad) {
const executionResult = subscriber.afterLoad!(entity, {
connection: this.queryRunner.connection,
queryRunner: this.queryRunner,
manager: this.queryRunner.manager,
entity: entity,
metadata: metadata
});
if (executionResult instanceof Promise)
result.promises.push(executionResult);
result.count++;
}
});
}
});
}
// -------------------------------------------------------------------------
// Protected Methods
// -------------------------------------------------------------------------
/**
* Checks if subscriber's methods can be executed by checking if its don't listen to the particular entity,
* or listens our entity.
*/
protected isAllowedSubscriber(subscriber: EntitySubscriberInterface<any>, target: Function|string): boolean {
return !subscriber.listenTo ||
!subscriber.listenTo() ||
subscriber.listenTo() === Object ||
subscriber.listenTo() === target ||
subscriber.listenTo().isPrototypeOf(target);
}
} | the_stack |
import {getClassInfoById} from "./Serializable_exJsonFsm";
type StateNode = {
index: number,
state?: State,
transitions: Map<TransitionPredict, number>,
reachCount?: number,
selfReachCount?: number,
endable?: boolean
}
type TransitionPredict = string | boolean | ((condition: any, curStateNode?: StateNode) => boolean);
class State {
public objCache: Map<number, any>;
protected root: State;
protected parent: State;
protected leaf: State;
private stateCache: Map<string, State>;
protected states = new Map<number, StateNode>();
protected allTransitionIsChar = true;
protected currentState: number;
public readonly index: number;
constructor(index?: number, parent?: State) {
this.index = index || 0;
this.parent = parent;
if (parent) {
this.root = parent.root;
}
else {
this.root = this;
this.objCache = new Map<number, any>();
this.stateCache = new Map<string, State>();
}
this.reset();
}
public reuseStateFromCache(constructor: any, index: number = 0, parent: State = null) {
const cacheKey = constructor.name + "_" + index;
let cache = this.stateCache.get(cacheKey);
if (cache == null) {
this.stateCache.set(cacheKey, cache = new constructor(index, parent));
}
else {
cache.parent = parent;
cache.reset();
}
return cache;
}
public reset() {
}
public setParent(parent: State) {
this.parent = parent;
}
/**
* @param from
* @param predict
* @param to
*/
protected addTransition(from: number | State, predict, to: number | State) {
if (typeof predict != "string") {
this.allTransitionIsChar = false;
}
const fromIndex = from instanceof State ? from.index : from;
let fromStateNode = this.states.get(fromIndex);
if (fromStateNode == null) {
this.states.set(fromIndex, fromStateNode = {
index: fromIndex,
state: from instanceof State ? from : null,
transitions: new Map<TransitionPredict, number>()
});
}
const toIndex = to instanceof State ? to.index : to;
let toStateNode = this.states.get(toIndex);
if (toStateNode == null) {
this.states.set(toIndex, toStateNode = {
index: toIndex,
state: to instanceof State ? to : null,
transitions: new Map<TransitionPredict, number>()
});
}
fromStateNode.transitions.set(predict, toStateNode.index);
}
protected addTransitions(from: number | State, predict: string, to: number | State) {
for (let c of predict) {
this.addTransition(from, c, to);
}
}
protected markAsEnd(...states: any[]) {
if (states) {
for (let state of states) {
this.states.get(state).endable = true;
}
}
}
public isCurrentEnd() {
return this.states.get(this.currentState).endable == true;
}
protected _transition(str: string, index: number) {
if (this.leaf && this == this.root) {
return this.leaf._transition(str, index);
}
const condition = str[index];
const fromState = this.currentState;
const fromStateNode = this.states.get(fromState);
this.beforeTransition(fromStateNode, condition);
let transitionTo: number = fromStateNode.transitions.get(condition);
if (transitionTo == null && !this.allTransitionIsChar) {
for (let entry of fromStateNode.transitions) {
// noinspection JSUnfilteredForInLoop
const predict = entry[0];
const predictType = typeof predict;
if (predictType[0] != "s") {
const to = entry[1];
if (predict != null) {
if ((predictType == "function" && (predict as any)(condition, fromStateNode))
|| predict == true) {
transitionTo = to;
break;
}
}
}
}
}
if (transitionTo == null) {
if (fromStateNode.endable && this.parent != null) {
// 当前状态为可结束状态,继续交由父亲state处理
this.root.leaf = null;
return this.parent._transition(str, index);
}
else {
throw new Error(`current state ${this.constructor.name}(${fromState}), bad token(${condition}) at ${index}:
${str}
${str.substring(0, index)}^`);
}
}
this.currentState = transitionTo;
const toStateNode = this.states.get(transitionTo);
if (toStateNode.state) {
this.root.leaf = toStateNode.state;
}
else if (this != this.root) {
this.root.leaf = this;
}
this.afterTransition(fromStateNode, condition, toStateNode);
return true;
}
public transition(str: string) {
for (let i = 0, len = str.length; i < len; i++) {
this._transition(str, i);
}
}
protected beforeTransition(fromStateNode: StateNode, condition: any) {
}
protected afterTransition(fromStateNode: StateNode, condition: any, toStateNode: StateNode) {
}
protected endStateCheck() {
if (!this.isCurrentEnd()) {
throw new Error(`not an end state: ${this.constructor.name}(${this.currentState})`);
}
}
get() {
}
}
class RefState extends State {
private str = "";
public reset() {
if (this.states.size == 0) {
this.addTransition(0, "_", 1);
this.addTransition(1, "0", 2);
this.addTransitions(1, "123456789", 3);
this.addTransitions(3, "0123456789", 3);
this.markAsEnd(2, 3);
}
this.currentState = 0;
this.str = "";
}
protected afterTransition(fromStateNode: StateNode, condition: any, toStateNode: StateNode) {
if (fromStateNode.index == 1 || toStateNode.index == 3) {
this.str += condition;
}
}
get() {
this.endStateCheck();
return this.root.objCache.get(parseInt(this.str));
}
}
class StringState extends State {
private str = "";
private uHexStr = "";
public reset() {
if (this.states.size == 0) {
this.addTransition(0, "\"", 1);
this.addTransition(1, c => c != "\"" && c != "\\", 1);
this.addTransition(1, "\\", 2);
this.addTransition(1, "\"", 5);
this.addTransitions(2, "\"\\/bfnrt", 1);
this.addTransition(2, "u", 3);
this.addTransitions(3, "0123456789abcdef", 4);
this.addTransition(4, (c, stateNode) => stateNode.selfReachCount <= 1 && "0123456789abcdef".indexOf(c) > -1, 4);
this.addTransition(4, (c, stateNode) => stateNode.selfReachCount == 2 && "0123456789abcdef".indexOf(c) > -1, 1);
this.markAsEnd(5);
}
this.currentState = 0;
this.str = "";
}
protected afterTransition(fromStateNode: StateNode, condition: any, toStateNode: StateNode) {
if (fromStateNode.index == 3) {
this.uHexStr += condition;
toStateNode.selfReachCount = 0;
}
else if (fromStateNode.index == 4) {
this.uHexStr += condition;
toStateNode.selfReachCount++;
}
if (toStateNode.index == 1) {
if (fromStateNode.index == 1) {
this.str += condition;
}
else if (fromStateNode.index == 2) {
switch (condition) {
case '"':
this.str += '"';
break;
case "\\":
this.str += "\\";
break;
case "/":
this.str += "/";
break;
case "b":
this.str += "\b";
break;
case "f":
this.str += "\f";
break;
case "n":
this.str += "\n";
break;
case "r":
this.str += "\r";
break;
case "t":
this.str += "\t";
break;
}
}
else if (fromStateNode.index == 4) {
this.str += String.fromCharCode(parseInt(this.uHexStr, 16));
this.uHexStr = "";
}
}
}
get() {
this.endStateCheck();
return this.str;
}
}
class NumberState extends State {
private numberStr = "";
public reset() {
if (this.states.size == 0) {
this.addTransition(0, "0", 1);
this.addTransition(0, "-", 2);
this.addTransitions(0, "123456789", 3);
this.addTransition(1, ".", 4);
this.addTransition(2, "0", 1);
this.addTransitions(2, "123456789", 3);
this.addTransitions(3, "0123456789", 3);
this.addTransition(3, ".", 4);
this.addTransitions(4, "0123456789", 5);
this.addTransitions(5, "0123456789", 5);
this.addTransitions(5, "eE", 6);
this.addTransitions(6, "-+0123456789", 7);
this.addTransitions(7, "0123456789", 7);
}
this.markAsEnd(1, 3, 5, 7);
this.currentState = 0;
this.numberStr = "";
}
protected afterTransition(fromState: StateNode, condition: any, toState: StateNode) {
this.numberStr += condition;
}
get() {
this.endStateCheck();
return parseFloat(this.numberStr);
}
}
class ArrayState extends State {
private arr: any[];
public reset() {
super.reset();
this.addTransition(0, "[", 1);
this.addTransition(1, "]", 2);
this.addTransition(1, true, new ValueState(3, this));
this.addTransition(3, ",", 1);
this.addTransition(3, "]", 2);
this.markAsEnd(2);
this.currentState = 0;
this.arr = [];
}
protected afterTransition(fromState: StateNode, condition: any, toState: StateNode) {
if (fromState.index == 0) {
this.root.objCache.set(this.root.objCache.size, this.arr);
}
else if (toState.index == 3) {
const valueState = toState.state as ValueState;
valueState.reset();
valueState.transition(condition);
}
else if (fromState.index == 3) {
const valueState = fromState.state as ValueState;
this.arr.push(valueState.get());
}
}
get() {
this.endStateCheck();
return this.arr;
}
}
class ObjectState extends State {
private obj = {};
private key: string;
public reset() {
super.reset();
this.addTransition(0, "{", 1);
this.addTransition(1, "}", 2);
this.addTransition(1, (c, state) => c == "_" && state.reachCount == 1, 3);
this.addTransition(3, ":", this.root.reuseStateFromCache(StringState, 4, this));
this.addTransition(4, "}", 2);
this.addTransition(4, ",", 1);
this.addTransition(1, "\"", this.root.reuseStateFromCache(StringState, 5, this));
this.addTransition(5, ":", new ValueState(6, this));
this.addTransition(6, ",", 1);
this.addTransition(6, "}", 2);
this.markAsEnd(2);
this.currentState = 0;
this.obj = {};
}
protected afterTransition(fromState: StateNode, condition: any, toState: StateNode) {
if (toState.index == 1) {
toState.reachCount = (toState.reachCount || 0) + 1;
}
else if (toState.index == 4 || toState.index == 5) {
(toState.state as StringState).setParent(this);
}
else if (toState.index == 6) {
(toState.state as ValueState).reset();
}
if (fromState.index == 1 && toState.state instanceof StringState) {
(toState.state as StringState).transition(condition);
}
else if (fromState.index == 5) {
const keyState = fromState.state as StringState;
this.key = keyState.get();
keyState.reset();
}
else if (fromState.index == 6) {
const valueState = fromState.state as ValueState;
this.obj[this.key] = valueState.get();
this.key = null;
}
else if (fromState.index == 4) {
const classId = (fromState.state as StringState).get();
const serializeClassInfo = getClassInfoById(classId);
if (serializeClassInfo) {
const serializeClass = serializeClassInfo.type;
this.obj = new serializeClass();
this.root.objCache.set(this.root.objCache.size - 1, this.obj);
}
}
else if (fromState.index == 0) {
this.root.objCache.set(this.root.objCache.size, this.obj);
}
}
get() {
this.endStateCheck();
return this.obj;
}
}
export class ValueState extends State {
public reset() {
this.states.clear();
this.states.set(0, {
index: 0,
transitions: new Map<TransitionPredict, number>()
});
this.currentState = 0;
}
protected beforeTransition(fromStateNode: StateNode, condition: any) {
if (fromStateNode.index == 0) {
switch (condition) {
case "t":
this.addTransition(0, "t", 1);
this.addTransition(1, "r", 2);
this.addTransition(2, "u", 3);
this.addTransition(3, "e", 4);
this.markAsEnd(4);
return;
case "f":
this.addTransition(0, "f", 5);
this.addTransition(5, "a", 6);
this.addTransition(6, "l", 7);
this.addTransition(7, "s", 8);
this.addTransition(8, "e", 9);
this.markAsEnd(9);
return;
case "n":
this.addTransition(0, "n", 10);
this.addTransition(10, "u", 11);
this.addTransition(11, "l", 12);
this.addTransition(12, "l", 13);
this.markAsEnd(13);
return;
case "_":
this.addTransition(0, "_", this.root.reuseStateFromCache(RefState, 14, this));
this.markAsEnd(14);
return;
case "\"":
this.addTransition(0, "\"", this.root.reuseStateFromCache(StringState, 15, this));
this.markAsEnd(15);
return;
case "{":
this.addTransition(0, "{", new ObjectState(17, this));
this.markAsEnd(17);
return;
case "[":
this.addTransition(0, "[", new ArrayState(18, this));
this.markAsEnd(18);
return;
}
const predict = c => c == "-" || (c >= "0" && c <= "9");
if (predict(condition)) {
this.addTransition(0, predict, this.root.reuseStateFromCache(NumberState, 16, this));
this.markAsEnd(16);
}
}
}
protected afterTransition(fromState: StateNode, condition: any, toState: StateNode) {
if (fromState.index == 0 && toState.state) {
(toState.state as State).transition(condition);
}
}
get() {
this.endStateCheck();
if (this.currentState == 4) {
return true;
}
else if (this.currentState == 9) {
return false;
}
else if (this.currentState == 13) {
return null;
}
else {
return this.states.get(this.currentState).state.get();
}
}
} | the_stack |
'use strict';
import * as lessScanner from './lessScanner';
import { TokenType } from './cssScanner';
import * as cssParser from './cssParser';
import * as nodes from './cssNodes';
import { ParseError } from './cssErrors';
/// <summary>
/// A parser for LESS
/// http://lesscss.org/
/// </summary>
export class LESSParser extends cssParser.Parser {
public constructor() {
super(new lessScanner.LESSScanner());
}
public _parseStylesheetStatement(isNested: boolean = false): nodes.Node | null {
if (this.peek(TokenType.AtKeyword)) {
return this._parseVariableDeclaration()
|| this._parsePlugin()
|| super._parseStylesheetAtStatement(isNested);
}
return this._tryParseMixinDeclaration()
|| this._tryParseMixinReference()
|| this._parseFunction()
|| this._parseRuleset(true);
}
public _parseImport(): nodes.Node | null {
if (!this.peekKeyword('@import') && !this.peekKeyword('@import-once') /* deprecated in less 1.4.1 */) {
return null;
}
const node = <nodes.Import>this.create(nodes.Import);
this.consumeToken();
// less 1.4.1: @import (css) "lib"
if (this.accept(TokenType.ParenthesisL)) {
if (!this.accept(TokenType.Ident)) {
return this.finish(node, ParseError.IdentifierExpected, [TokenType.SemiColon]);
}
do {
if (!this.accept(TokenType.Comma)) {
break;
}
} while (this.accept(TokenType.Ident));
if (!this.accept(TokenType.ParenthesisR)) {
return this.finish(node, ParseError.RightParenthesisExpected, [TokenType.SemiColon]);
}
}
if (!node.addChild(this._parseURILiteral()) && !node.addChild(this._parseStringLiteral())) {
return this.finish(node, ParseError.URIOrStringExpected, [TokenType.SemiColon]);
}
if (!this.peek(TokenType.SemiColon) && !this.peek(TokenType.EOF)) {
node.setMedialist(this._parseMediaQueryList());
}
return this.finish(node);
}
public _parsePlugin(): nodes.Node | null {
if (!this.peekKeyword('@plugin')) {
return null;
}
const node = this.createNode(nodes.NodeType.Plugin);
this.consumeToken(); // @import
if (!node.addChild(this._parseStringLiteral())) {
return this.finish(node, ParseError.StringLiteralExpected);
}
if (!this.accept(TokenType.SemiColon)) {
return this.finish(node, ParseError.SemiColonExpected);
}
return this.finish(node);
}
public _parseMediaQuery(): nodes.Node | null {
const node = super._parseMediaQuery();
if (!node) {
const node = this.create(nodes.MediaQuery);
if (node.addChild(this._parseVariable())) {
return this.finish(node);
}
return null;
}
return node;
}
public _parseMediaDeclaration(isNested: boolean = false): nodes.Node | null {
return this._tryParseRuleset(isNested)
|| this._tryToParseDeclaration()
|| this._tryParseMixinDeclaration()
|| this._tryParseMixinReference()
|| this._parseDetachedRuleSetMixin()
|| this._parseStylesheetStatement(isNested);
}
public _parseMediaFeatureName(): nodes.Node | null {
return this._parseIdent() || this._parseVariable();
}
public _parseVariableDeclaration(panic: TokenType[] = []): nodes.VariableDeclaration | null {
const node = <nodes.VariableDeclaration>this.create(nodes.VariableDeclaration);
const mark = this.mark();
if (!node.setVariable(this._parseVariable(true))) {
return null;
}
if (this.accept(TokenType.Colon)) {
if (this.prevToken) {
node.colonPosition = this.prevToken.offset;
}
if (node.setValue(this._parseDetachedRuleSet())) {
node.needsSemicolon = false;
} else if (!node.setValue(this._parseExpr())) {
return <nodes.VariableDeclaration>this.finish(node, ParseError.VariableValueExpected, [], panic);
}
node.addChild(this._parsePrio());
} else {
this.restoreAtMark(mark);
return null; // at keyword, but no ':', not a variable declaration but some at keyword
}
if (this.peek(TokenType.SemiColon)) {
node.semicolonPosition = this.token.offset; // not part of the declaration, but useful information for code assist
}
return <nodes.VariableDeclaration>this.finish(node);
}
public _parseDetachedRuleSet(): nodes.Node | null {
let mark = this.mark();
// "Anonymous mixin" used in each() and possibly a generic type in the future
if (this.peekDelim('#') || this.peekDelim('.')) {
this.consumeToken();
if (!this.hasWhitespace() && this.accept(TokenType.ParenthesisL)) {
let node = <nodes.MixinDeclaration>this.create(nodes.MixinDeclaration);
if (node.getParameters().addChild(this._parseMixinParameter())) {
while (this.accept(TokenType.Comma) || this.accept(TokenType.SemiColon)) {
if (this.peek(TokenType.ParenthesisR)) {
break;
}
if (!node.getParameters().addChild(this._parseMixinParameter())) {
this.markError(node, ParseError.IdentifierExpected, [], [TokenType.ParenthesisR]);
}
}
}
if (!this.accept(TokenType.ParenthesisR)) {
this.restoreAtMark(mark);
return null;
}
} else {
this.restoreAtMark(mark);
return null;
}
}
if (!this.peek(TokenType.CurlyL)) {
return null;
}
const content = <nodes.BodyDeclaration>this.create(nodes.BodyDeclaration);
this._parseBody(content, this._parseDetachedRuleSetBody.bind(this));
return this.finish(content);
}
public _parseDetachedRuleSetBody(): nodes.Node | null {
return this._tryParseKeyframeSelector() || this._parseRuleSetDeclaration();
}
public _addLookupChildren(node: nodes.Node): boolean {
if (!node.addChild(this._parseLookupValue())) {
return false;
}
let expectsValue = false;
while (true) {
if (this.peek(TokenType.BracketL)) {
expectsValue = true;
}
if (!node.addChild(this._parseLookupValue())) {
break;
}
expectsValue = false;
}
return !expectsValue;
}
public _parseLookupValue(): nodes.Node | null {
const node = <nodes.Node>this.create(nodes.Node);
const mark = this.mark();
if (!this.accept(TokenType.BracketL)) {
this.restoreAtMark(mark);
return null;
}
if (((node.addChild(this._parseVariable(false, true)) ||
node.addChild(this._parsePropertyIdentifier())) &&
this.accept(TokenType.BracketR)) || this.accept(TokenType.BracketR)) {
return <nodes.Node>node;
}
this.restoreAtMark(mark);
return null;
}
public _parseVariable(declaration: boolean = false, insideLookup: boolean = false): nodes.Variable | null {
const isPropertyReference = !declaration && this.peekDelim('$');
if (!this.peekDelim('@') && !isPropertyReference && !this.peek(TokenType.AtKeyword)) {
return null;
}
const node = <nodes.Variable>this.create(nodes.Variable);
const mark = this.mark();
while (this.acceptDelim('@') || (!declaration && this.acceptDelim('$'))) {
if (this.hasWhitespace()) {
this.restoreAtMark(mark);
return null;
}
}
if (!this.accept(TokenType.AtKeyword) && !this.accept(TokenType.Ident)) {
this.restoreAtMark(mark);
return null;
}
if (!insideLookup && this.peek(TokenType.BracketL)) {
if (!this._addLookupChildren(node)) {
this.restoreAtMark(mark);
return null;
}
}
return <nodes.Variable>node;
}
public _parseTermExpression(): nodes.Node | null {
return this._parseVariable() ||
this._parseEscaped() ||
super._parseTermExpression() || // preference for colors before mixin references
this._tryParseMixinReference(false);
}
public _parseEscaped(): nodes.Node | null {
if (this.peek(TokenType.EscapedJavaScript) ||
this.peek(TokenType.BadEscapedJavaScript)) {
const node = this.createNode(nodes.NodeType.EscapedValue);
this.consumeToken();
return this.finish(node);
}
if (this.peekDelim('~')) {
const node = this.createNode(nodes.NodeType.EscapedValue);
this.consumeToken();
if (this.accept(TokenType.String) || this.accept(TokenType.EscapedJavaScript)) {
return this.finish(node);
} else {
return this.finish(node, ParseError.TermExpected);
}
}
return null;
}
public _parseOperator(): nodes.Node | null {
const node = this._parseGuardOperator();
if (node) {
return node;
} else {
return super._parseOperator();
}
}
public _parseGuardOperator(): nodes.Node | null {
if (this.peekDelim('>')) {
const node = this.createNode(nodes.NodeType.Operator);
this.consumeToken();
this.acceptDelim('=');
return node;
} else if (this.peekDelim('=')) {
const node = this.createNode(nodes.NodeType.Operator);
this.consumeToken();
this.acceptDelim('<');
return node;
} else if (this.peekDelim('<')) {
const node = this.createNode(nodes.NodeType.Operator);
this.consumeToken();
this.acceptDelim('=');
return node;
}
return null;
}
public _parseRuleSetDeclaration(): nodes.Node | null {
if (this.peek(TokenType.AtKeyword)) {
return this._parseKeyframe()
|| this._parseMedia(true)
|| this._parseImport()
|| this._parseSupports(true) // @supports
|| this._parseDetachedRuleSetMixin() // less detached ruleset mixin
|| this._parseVariableDeclaration() // Variable declarations
|| super._parseRuleSetDeclarationAtStatement();
}
return this._tryParseMixinDeclaration()
|| this._tryParseRuleset(true) // nested ruleset
|| this._tryParseMixinReference() // less mixin reference
|| this._parseFunction()
|| this._parseExtend() // less extend declaration
|| super._parseRuleSetDeclaration(); // try css ruleset declaration as the last option
}
public _parseKeyframeIdent(): nodes.Node | null {
return this._parseIdent([nodes.ReferenceType.Keyframe]) || this._parseVariable();
}
public _parseKeyframeSelector(): nodes.Node | null {
return this._parseDetachedRuleSetMixin() // less detached ruleset mixin
|| super._parseKeyframeSelector();
}
public _parseSimpleSelectorBody(): nodes.Node | null {
return this._parseSelectorCombinator() || super._parseSimpleSelectorBody();
}
public _parseSelector(isNested: boolean): nodes.Selector | null {
// CSS Guards
const node = <nodes.Selector>this.create(nodes.Selector);
let hasContent = false;
if (isNested) {
// nested selectors can start with a combinator
hasContent = node.addChild(this._parseCombinator());
}
while (node.addChild(this._parseSimpleSelector())) {
hasContent = true;
const mark = this.mark();
if (node.addChild(this._parseGuard()) && this.peek(TokenType.CurlyL)) {
break;
}
this.restoreAtMark(mark);
node.addChild(this._parseCombinator()); // optional
}
return hasContent ? this.finish(node) : null;
}
public _parseSelectorCombinator(): nodes.Node | null {
if (this.peekDelim('&')) {
const node = this.createNode(nodes.NodeType.SelectorCombinator);
this.consumeToken();
while (!this.hasWhitespace() && (this.acceptDelim('-') || this.accept(TokenType.Num) || this.accept(TokenType.Dimension) || node.addChild(this._parseIdent()) || this.acceptDelim('&'))) {
// support &-foo
}
return this.finish(node);
}
return null;
}
public _parseSelectorIdent(): nodes.Node | null {
if (!this.peekInterpolatedIdent()) {
return null;
}
const node = this.createNode(nodes.NodeType.SelectorInterpolation);
const hasContent = this._acceptInterpolatedIdent(node);
return hasContent ? this.finish(node) : null;
}
public _parsePropertyIdentifier(inLookup: boolean = false): nodes.Identifier | null {
const propertyRegex = /^[\w-]+/;
if (!this.peekInterpolatedIdent() && !this.peekRegExp(this.token.type, propertyRegex)) {
return null;
}
const mark = this.mark();
const node = <nodes.Identifier>this.create(nodes.Identifier);
node.isCustomProperty = this.acceptDelim('-') && this.acceptDelim('-');
let childAdded = false;
if (!inLookup) {
if (node.isCustomProperty) {
childAdded = this._acceptInterpolatedIdent(node);
} else {
childAdded = this._acceptInterpolatedIdent(node, propertyRegex);
}
} else {
if (node.isCustomProperty) {
childAdded = node.addChild(this._parseIdent());
} else {
childAdded = node.addChild(this._parseRegexp(propertyRegex));
}
}
if (!childAdded) {
this.restoreAtMark(mark);
return null;
}
if (!inLookup && !this.hasWhitespace()) {
this.acceptDelim('+');
if (!this.hasWhitespace()) {
this.acceptIdent('_');
}
}
return this.finish(node);
}
private peekInterpolatedIdent() {
return this.peek(TokenType.Ident) ||
this.peekDelim('@') ||
this.peekDelim('$') ||
this.peekDelim('-');
}
public _acceptInterpolatedIdent(node: nodes.Node, identRegex?: RegExp): boolean {
let hasContent = false;
const indentInterpolation = () => {
const pos = this.mark();
if (this.acceptDelim('-')) {
if (!this.hasWhitespace()) {
this.acceptDelim('-');
}
if (this.hasWhitespace()) {
this.restoreAtMark(pos);
return null;
}
}
return this._parseInterpolation();
};
const accept = identRegex ?
(): boolean => this.acceptRegexp(identRegex) :
(): boolean => this.accept(TokenType.Ident);
while (
accept() ||
node.addChild(this._parseInterpolation() ||
this.try(indentInterpolation))
) {
hasContent = true;
if (this.hasWhitespace()) {
break;
}
}
return hasContent;
}
public _parseInterpolation(): nodes.Node | null {
// @{name} Variable or
// ${name} Property
const mark = this.mark();
if (this.peekDelim('@') || this.peekDelim('$')) {
const node = this.createNode(nodes.NodeType.Interpolation);
this.consumeToken();
if (this.hasWhitespace() || !this.accept(TokenType.CurlyL)) {
this.restoreAtMark(mark);
return null;
}
if (!node.addChild(this._parseIdent())) {
return this.finish(node, ParseError.IdentifierExpected);
}
if (!this.accept(TokenType.CurlyR)) {
return this.finish(node, ParseError.RightCurlyExpected);
}
return this.finish(node);
}
return null;
}
public _tryParseMixinDeclaration(): nodes.Node | null {
const mark = this.mark();
const node = <nodes.MixinDeclaration>this.create(nodes.MixinDeclaration);
if (!node.setIdentifier(this._parseMixinDeclarationIdentifier()) || !this.accept(TokenType.ParenthesisL)) {
this.restoreAtMark(mark);
return null;
}
if (node.getParameters().addChild(this._parseMixinParameter())) {
while (this.accept(TokenType.Comma) || this.accept(TokenType.SemiColon)) {
if (this.peek(TokenType.ParenthesisR)) {
break;
}
if (!node.getParameters().addChild(this._parseMixinParameter())) {
this.markError(node, ParseError.IdentifierExpected, [], [TokenType.ParenthesisR]);
}
}
}
if (!this.accept(TokenType.ParenthesisR)) {
this.restoreAtMark(mark);
return null;
}
node.setGuard(this._parseGuard());
if (!this.peek(TokenType.CurlyL)) {
this.restoreAtMark(mark);
return null;
}
return this._parseBody(node, this._parseMixInBodyDeclaration.bind(this));
}
private _parseMixInBodyDeclaration(): nodes.Node | null {
return this._parseFontFace() || this._parseRuleSetDeclaration();
}
private _parseMixinDeclarationIdentifier(): nodes.Identifier | null {
let identifier: nodes.Identifier;
if (this.peekDelim('#') || this.peekDelim('.')) {
identifier = <nodes.Identifier>this.create(nodes.Identifier);
this.consumeToken(); // # or .
if (this.hasWhitespace() || !identifier.addChild(this._parseIdent())) {
return null;
}
} else if (this.peek(TokenType.Hash)) {
identifier = <nodes.Identifier>this.create(nodes.Identifier);
this.consumeToken(); // TokenType.Hash
} else {
return null;
}
identifier.referenceTypes = [nodes.ReferenceType.Mixin];
return this.finish(identifier);
}
public _parsePseudo(): nodes.Node | null {
if (!this.peek(TokenType.Colon)) {
return null;
}
const mark = this.mark();
const node = <nodes.ExtendsReference>this.create(nodes.ExtendsReference);
this.consumeToken(); // :
if (this.acceptIdent('extend')) {
return this._completeExtends(node);
}
this.restoreAtMark(mark);
return super._parsePseudo();
}
public _parseExtend(): nodes.Node | null {
if (!this.peekDelim('&')) {
return null;
}
const mark = this.mark();
const node = <nodes.ExtendsReference>this.create(nodes.ExtendsReference);
this.consumeToken(); // &
if (this.hasWhitespace() || !this.accept(TokenType.Colon) || !this.acceptIdent('extend')) {
this.restoreAtMark(mark);
return null;
}
return this._completeExtends(node);
}
private _completeExtends(node: nodes.ExtendsReference): nodes.Node | null {
if (!this.accept(TokenType.ParenthesisL)) {
return this.finish(node, ParseError.LeftParenthesisExpected);
}
const selectors = node.getSelectors();
if (!selectors.addChild(this._parseSelector(true))) {
return this.finish(node, ParseError.SelectorExpected);
}
while (this.accept(TokenType.Comma)) {
if (!selectors.addChild(this._parseSelector(true))) {
return this.finish(node, ParseError.SelectorExpected);
}
}
if (!this.accept(TokenType.ParenthesisR)) {
return this.finish(node, ParseError.RightParenthesisExpected);
}
return this.finish(node);
}
public _parseDetachedRuleSetMixin(): nodes.Node | null {
if (!this.peek(TokenType.AtKeyword)) {
return null;
}
const mark = this.mark();
const node = <nodes.MixinReference>this.create(nodes.MixinReference);
if (node.addChild(this._parseVariable(true)) && (this.hasWhitespace() || !this.accept(TokenType.ParenthesisL))) {
this.restoreAtMark(mark);
return null;
}
if (!this.accept(TokenType.ParenthesisR)) {
return this.finish(node, ParseError.RightParenthesisExpected);
}
return this.finish(node);
}
public _tryParseMixinReference(atRoot = true): nodes.Node | null {
const mark = this.mark();
const node = <nodes.MixinReference>this.create(nodes.MixinReference);
let identifier = this._parseMixinDeclarationIdentifier();
while (identifier) {
this.acceptDelim('>');
const nextId = this._parseMixinDeclarationIdentifier();
if (nextId) {
node.getNamespaces().addChild(identifier);
identifier = nextId;
} else {
break;
}
}
if (!node.setIdentifier(identifier)) {
this.restoreAtMark(mark);
return null;
}
let hasArguments = false;
if (this.accept(TokenType.ParenthesisL)) {
hasArguments = true;
if (node.getArguments().addChild(this._parseMixinArgument())) {
while (this.accept(TokenType.Comma) || this.accept(TokenType.SemiColon)) {
if (this.peek(TokenType.ParenthesisR)) {
break;
}
if (!node.getArguments().addChild(this._parseMixinArgument())) {
return this.finish(node, ParseError.ExpressionExpected);
}
}
}
if (!this.accept(TokenType.ParenthesisR)) {
return this.finish(node, ParseError.RightParenthesisExpected);
}
identifier.referenceTypes = [nodes.ReferenceType.Mixin];
} else {
identifier.referenceTypes = [nodes.ReferenceType.Mixin, nodes.ReferenceType.Rule];
}
if (this.peek(TokenType.BracketL)) {
if (!atRoot) {
this._addLookupChildren(node);
}
} else {
node.addChild(this._parsePrio());
}
if (!hasArguments && !this.peek(TokenType.SemiColon) && !this.peek(TokenType.CurlyR) && !this.peek(TokenType.EOF)) {
this.restoreAtMark(mark);
return null;
}
return this.finish(node);
}
public _parseMixinArgument(): nodes.Node | null {
// [variableName ':'] expression | variableName '...'
const node = <nodes.FunctionArgument>this.create(nodes.FunctionArgument);
const pos = this.mark();
const argument = this._parseVariable();
if (argument) {
if (!this.accept(TokenType.Colon)) {
this.restoreAtMark(pos);
} else {
node.setIdentifier(argument);
}
}
if (node.setValue(this._parseDetachedRuleSet() || this._parseExpr(true))) {
return this.finish(node);
}
this.restoreAtMark(pos);
return null;
}
public _parseMixinParameter(): nodes.Node | null {
const node = <nodes.FunctionParameter>this.create(nodes.FunctionParameter);
// special rest variable: @rest...
if (this.peekKeyword('@rest')) {
const restNode = this.create(nodes.Node);
this.consumeToken();
if (!this.accept(lessScanner.Ellipsis)) {
return this.finish(node, ParseError.DotExpected, [], [TokenType.Comma, TokenType.ParenthesisR]);
}
node.setIdentifier(this.finish(restNode));
return this.finish(node);
}
// special const args: ...
if (this.peek(lessScanner.Ellipsis)) {
const varargsNode = this.create(nodes.Node);
this.consumeToken();
node.setIdentifier(this.finish(varargsNode));
return this.finish(node);
}
let hasContent = false;
// default variable declaration: @param: 12 or @name
if (node.setIdentifier(this._parseVariable())) {
this.accept(TokenType.Colon);
hasContent = true;
}
if (!node.setDefaultValue(this._parseDetachedRuleSet() || this._parseExpr(true)) && !hasContent) {
return null;
}
return this.finish(node);
}
public _parseGuard(): nodes.LessGuard | null {
if (!this.peekIdent('when')) {
return null;
}
const node = <nodes.LessGuard>this.create(nodes.LessGuard);
this.consumeToken(); // when
node.isNegated = this.acceptIdent('not');
if (!node.getConditions().addChild(this._parseGuardCondition())) {
return <nodes.LessGuard>this.finish(node, ParseError.ConditionExpected);
}
while (this.acceptIdent('and') || this.accept(TokenType.Comma)) {
if (!node.getConditions().addChild(this._parseGuardCondition())) {
return <nodes.LessGuard>this.finish(node, ParseError.ConditionExpected);
}
}
return <nodes.LessGuard>this.finish(node);
}
public _parseGuardCondition(): nodes.Node | null {
if (!this.peek(TokenType.ParenthesisL)) {
return null;
}
const node = this.create(nodes.GuardCondition);
this.consumeToken(); // ParenthesisL
if (!node.addChild(this._parseExpr())) {
// empty (?)
}
if (!this.accept(TokenType.ParenthesisR)) {
return this.finish(node, ParseError.RightParenthesisExpected);
}
return this.finish(node);
}
public _parseFunction(): nodes.Function | null {
const pos = this.mark();
const node = <nodes.Function>this.create(nodes.Function);
if (!node.setIdentifier(this._parseFunctionIdentifier())) {
return null;
}
if (this.hasWhitespace() || !this.accept(TokenType.ParenthesisL)) {
this.restoreAtMark(pos);
return null;
}
if (node.getArguments().addChild(this._parseMixinArgument())) {
while (this.accept(TokenType.Comma) || this.accept(TokenType.SemiColon)) {
if (this.peek(TokenType.ParenthesisR)) {
break;
}
if (!node.getArguments().addChild(this._parseMixinArgument())) {
return this.finish(node, ParseError.ExpressionExpected);
}
}
}
if (!this.accept(TokenType.ParenthesisR)) {
return <nodes.Function>this.finish(node, ParseError.RightParenthesisExpected);
}
return <nodes.Function>this.finish(node);
}
public _parseFunctionIdentifier(): nodes.Identifier | null {
if (this.peekDelim('%')) {
const node = <nodes.Identifier>this.create(nodes.Identifier);
node.referenceTypes = [nodes.ReferenceType.Function];
this.consumeToken();
return this.finish(node);
}
return super._parseFunctionIdentifier();
}
public _parseURLArgument(): nodes.Node | null {
const pos = this.mark();
const node = super._parseURLArgument();
if (!node || !this.peek(TokenType.ParenthesisR)) {
this.restoreAtMark(pos);
const node = this.create(nodes.Node);
node.addChild(this._parseBinaryExpr());
return this.finish(node);
}
return node;
}
} | the_stack |
import request from "supertest";
import { Server } from "http";
import express from "express";
import nock from "nock";
import sinon from "sinon";
import _ from "lodash";
import { expect } from "chai";
import { Record } from "magda-typescript-common/src/generated/registry/api";
import {
arbFlatMap,
lcAlphaNumStringArbNe,
recordArb
} from "magda-typescript-common/src/test/arbitraries";
import jsc from "magda-typescript-common/src/test/jsverify";
import MinionOptions from "../MinionOptions";
import minion from "../index";
import fakeArgv from "./fakeArgv";
import makePromiseQueryable from "./makePromiseQueryable";
import baseSpec from "./baseSpec";
baseSpec(
"webhooks",
(
expressApp: () => express.Express,
expressServer: () => Server,
listenPort: () => number,
beforeEachProperty: () => void
) => {
doWebhookTest("should work synchronously", false);
doWebhookTest("should work asynchronously", true);
function doWebhookTest(caption: string, async: boolean) {
it(caption, () => {
const batchResultsArb = jsc.suchthat(
jsc.array(jsc.bool),
(array) => array.length <= 5
);
const recordWithSuccessArb = (mightFail: boolean) =>
jsc.record({
record: recordArb,
success: mightFail ? jsc.bool : jsc.constant(true)
});
const recordsWithSuccessArrArb = (success: boolean) => {
const baseArb = jsc.array(recordWithSuccessArb(!success));
return success
? baseArb
: jsc.suchthat(baseArb, (combined) =>
combined.some(({ success }) => !success)
);
};
type Batch = {
/** Each record in the batch and whether it should succeed when
* onRecordFound is called */
records: { record: Record; success: boolean }[];
/** Whether the overall batch should succeed - to succeed, every record
* should succeed, to fail then at least one record should fail. */
overallSuccess: boolean;
};
const batchArb = arbFlatMap<boolean[], Batch[]>(
batchResultsArb,
(batchResults) => {
const batchArb = batchResults.map((overallSuccess) =>
recordsWithSuccessArrArb(overallSuccess).smap(
(records) => ({ records, overallSuccess }),
({ records }) => records
)
);
return batchArb.length > 0
? jsc.tuple(batchArb)
: jsc.constant([]);
},
(batches) =>
batches.map(({ overallSuccess }) => overallSuccess)
);
/** Global hook id generator - incremented every time we create another hook */
let lastHookId = 0;
return jsc.assert(
jsc.forall(
batchArb,
lcAlphaNumStringArbNe,
lcAlphaNumStringArbNe,
jsc.integer(1, 10),
jsc.bool,
(
recordsBatches,
domain,
jwtSecret,
concurrency,
enableMultiTenant
) => {
beforeEachProperty();
const registryDomain = "example";
const registryUrl = `http://${registryDomain}.com:80`;
const registryScope = nock(registryUrl);
const tenantDomain = "tenant";
const tenantUrl = `http://${tenantDomain}.com:80`;
const tenantScope = nock(tenantUrl);
const userId =
"b1fddd6f-e230-4068-bd2c-1a21844f1598";
/** All records in all the batches */
const flattenedRecords = _.flatMap(
recordsBatches,
(batch) => batch.records
);
/** Error thrown when the call is *supposed* to fail */
const fakeError = new Error(
"Fake-ass testing error"
);
(fakeError as any).ignore = true;
const internalUrl = `http://${domain}.com`;
const options: MinionOptions = {
argv: fakeArgv({
internalUrl,
registryUrl,
enableMultiTenant,
tenantUrl,
jwtSecret,
userId,
listenPort: listenPort()
}),
id: "id",
aspects: [],
optionalAspects: [],
writeAspectDefs: [],
async,
express: expressApp,
concurrency: concurrency,
onRecordFound: sinon
.stub()
.callsFake((foundRecord: Record) => {
const match = flattenedRecords.find(
({ record: thisRecord }) => {
return (
thisRecord.id ===
foundRecord.id
);
}
);
return match.success
? Promise.resolve()
: Promise.reject(fakeError);
})
};
registryScope.get(/\/hooks\/.*/).reply(200, {
url: internalUrl + "/hook",
config: {
aspects: [],
optionalAspects: [],
includeEvents: false,
includeRecords: true,
includeAspectDefinitions: false,
dereference: true
}
});
registryScope.post(/\/hooks\/.*/).reply(201, {});
tenantScope.get("/tenants").reply(200, []);
return minion(options)
.then(() =>
Promise.all(
recordsBatches.map((batch) => {
lastHookId++;
if (async) {
// If we're running async then we expect that there'll be a call to the registry
// telling it to give more events.
registryScope
.post(
`/hooks/${options.id}/ack`,
{
succeeded:
batch.overallSuccess,
lastEventIdReceived: lastHookId,
// Deactivate if not successful.
...(batch.overallSuccess
? {}
: {
active: false
})
}
)
.reply(201);
}
// Send the hook payload to the minion
const test = request(
expressServer()
)
.post("/hook")
.set(
"Content-Type",
"application/json"
)
.send({
records: batch.records.map(
({ record }) => record
),
deferredResponseUrl: `${registryUrl}/hooks/${lastHookId}`,
lastEventId: lastHookId
})
.expect((response: any) => {
if (
response.status !==
201 &&
response.status !== 500
) {
console.log(response);
}
})
// The hook should only return 500 if it's failed synchronously.
.expect(
async ||
batch.overallSuccess
? 201
: 500
)
.expect((response: any) => {
expect(
!!response.body
.deferResponse
).to.equal(async);
});
const queryable = makePromiseQueryable(
test
);
expect(queryable.isFulfilled()).to
.be.false;
return queryable.then(() =>
batch.records.forEach(
({ record }) =>
expect(
(options.onRecordFound as sinon.SinonStub).calledWith(
record
)
)
)
);
})
)
)
.then(() => {
registryScope.done();
return true;
});
}
),
{}
);
});
}
}
); | the_stack |
import { setTimeout } from "timers/promises";
import {
InputGate,
InputGatedEventTarget,
OutputGate,
runWithInputGateClosed,
waitForOpenInputGate,
waitForOpenOutputGate,
waitUntilOnOutputGate,
} from "@miniflare/shared";
import { noop, triggerPromise } from "@miniflare/shared-test";
import test from "ava";
test("waitForOpenInputGate: waits for input gate in context to open", async (t) => {
const events: number[] = [];
const inputGate = new InputGate();
await inputGate.runWith(async () => {
void inputGate.runWithClosed(async () => {
events.push(1);
await setTimeout();
events.push(2);
});
events.push(3);
await waitForOpenInputGate();
events.push(4);
});
t.deepEqual(events, [3, 1, 2, 4]);
});
test("waitForOpenInputGate: returns immediately if no input gate in context", (t) => {
t.is(waitForOpenInputGate(), undefined);
});
test("runWithInputGateClosed: closes input gate in context and runs closure", async (t) => {
const events: number[] = [];
const inputGate = new InputGate();
await inputGate.runWith(async () => {
void runWithInputGateClosed(async () => {
events.push(1);
await setTimeout();
events.push(2);
});
events.push(3);
await inputGate.waitForOpen();
events.push(4);
});
t.deepEqual(events, [3, 1, 2, 4]);
});
test("runWithInputGateClosed: runs closure without closing input gate in context if concurrency allowed", async (t) => {
const events: number[] = [];
const inputGate = new InputGate();
const [waitTrigger, waitPromise] = triggerPromise<void>();
const [finishTrigger, finishPromise] = triggerPromise<void>();
await inputGate.runWith(async () => {
void runWithInputGateClosed(async () => {
events.push(1);
await waitPromise; // This would deadlock if concurrency wasn't allowed
events.push(2);
finishTrigger();
}, true);
events.push(3);
await inputGate.waitForOpen();
waitTrigger();
events.push(4);
});
await finishPromise;
t.deepEqual(events, [1, 3, 4, 2]);
});
test("runWithInputGateClosed: runs closure if no input gate in context", async (t) => {
// Test will fail if no assertions run
await runWithInputGateClosed(async () => t.pass());
});
test("waitForOpenOutputGate: waits for output gate in context to open", async (t) => {
const events: number[] = [];
const outputGate = new OutputGate();
await outputGate.runWith(async () => {
outputGate.waitUntil(
(async () => {
events.push(1);
await setTimeout();
events.push(2);
})()
);
events.push(3);
await waitForOpenOutputGate();
events.push(4);
});
t.deepEqual(events, [1, 3, 2, 4]);
});
test("waitForOpenOutputGate: returns immediately if no output gate in context", (t) => {
t.is(waitForOpenOutputGate(), undefined);
});
test("waitUntilOnOutputGate: closes output gate in context until promise resolves", async (t) => {
const events: number[] = [];
const outputGate = new OutputGate();
await outputGate.runWith(async () => {
const promise = (async () => {
events.push(1);
await setTimeout();
events.push(2);
})();
t.is(waitUntilOnOutputGate(promise), promise);
events.push(3);
await outputGate.waitForOpen();
events.push(4);
});
t.deepEqual(events, [1, 3, 2, 4]);
});
test("waitUntilOnOutputGate: returns promise without closing output gate in context if unconfirmed allowed", async (t) => {
const events: number[] = [];
const outputGate = new OutputGate();
const [waitTrigger, waitPromise] = triggerPromise<void>();
const [finishTrigger, finishPromise] = triggerPromise<void>();
await outputGate.runWith(async () => {
const promise = (async () => {
events.push(1);
await waitPromise; // This would deadlock if unconfirmed wasn't allowed
events.push(2);
finishTrigger();
})();
t.is(waitUntilOnOutputGate(promise, true), promise);
events.push(3);
await outputGate.waitForOpen();
waitTrigger();
events.push(4);
});
await finishPromise;
t.deepEqual(events, [1, 3, 4, 2]);
});
test("waitUntilOnOutputGate: returns promise if no output gate in context", async (t) => {
const promise = Promise.resolve();
t.is(waitUntilOnOutputGate(promise), promise);
});
test("InputGate: runWith: runs closure with input gate in context", async (t) => {
const inputGate = new InputGate();
await inputGate.runWith(() => t.not(waitForOpenInputGate(), undefined));
});
test("InputGate: runWith: waits for gate to open before running closure", async (t) => {
const events: number[] = [];
const inputGate = new InputGate();
// Close input gate
const [openTrigger, openPromise] = triggerPromise<void>();
void inputGate.runWithClosed(() => openPromise);
await setTimeout();
// This is the same situation as a fetch to a Durable Object that called
// blockConcurrencyWhile in its constructor
const runWithPromise = inputGate.runWith(() => events.push(1));
await setTimeout();
events.push(2);
openTrigger();
await runWithPromise;
t.deepEqual(events, [2, 1]);
});
test("InputGate: waitForOpen: returns if gate already open", async (t) => {
const inputGate = new InputGate();
await inputGate.waitForOpen();
t.pass();
});
test("InputGate: waitForOpen/runWithClosed: waits for gate to open", async (t) => {
const events: number[] = [];
const inputGate = new InputGate();
// Close input gate
const [openTrigger1, openPromise1] = triggerPromise<void>();
const [openTrigger2, openPromise2] = triggerPromise<void>();
void inputGate.runWithClosed(() => {
events.push(1);
return openPromise1;
});
events.push(2); // Should be before 1
void inputGate.runWithClosed(() => openPromise2);
await setTimeout();
const waitForOpenPromise = inputGate.waitForOpen().then(() => events.push(3));
await setTimeout();
events.push(4);
openTrigger1();
// Check requires all promises to resolve before opening
await setTimeout();
t.deepEqual(events, [2, 1, 4]);
openTrigger2();
await waitForOpenPromise;
t.deepEqual(events, [2, 1, 4, 3]);
});
test("InputGate: waitForOpen: waits for gate to open if called concurrently", async (t) => {
const events: number[] = [];
const inputGate = new InputGate();
// This is the same situation as 2 concurrent fetches to a Durable Object
// for unique numbers
function asyncOperation(): Promise<void> {
return inputGate.runWithClosed(async () => {
events.push(1);
await setTimeout();
events.push(2);
});
}
await Promise.all([
inputGate.waitForOpen().then(asyncOperation),
inputGate.waitForOpen().then(asyncOperation),
]);
t.deepEqual(events, [1, 2, 1, 2]); // Not [1, 1, 2, 2]
});
test("InputGate: runWithClosed: allows concurrent execution", async (t) => {
const inputGate = new InputGate();
const [trigger1, promise1] = triggerPromise<void>();
const [trigger2, promise2] = triggerPromise<void>();
await Promise.all([
inputGate.runWithClosed(async () => {
trigger1();
await promise2; // Deadlock if below wasn't executed concurrently
}),
inputGate.runWithClosed(async () => {
trigger2();
await promise1;
}),
]);
t.pass();
});
test("InputGate: runWithClosed: closing child input gate closes parent too", async (t) => {
const events: number[] = [];
const inputGate = new InputGate();
// Close (child) input gate
const [openTrigger, openPromise] = triggerPromise<void>();
inputGate.runWithClosed(async () => {
void runWithInputGateClosed(() => openPromise);
});
await setTimeout();
const waitForOpenPromise = inputGate.waitForOpen().then(() => events.push(1));
await setTimeout();
events.push(2);
openTrigger();
await waitForOpenPromise;
t.deepEqual(events, [2, 1]);
});
test("InputGate: runWithClosed: event delivered to child even though parent input gate closed", async (t) => {
const inputGate = new InputGate();
// This is the same situation as a blockConcurrencyWhile that makes an async
// I/O request
await inputGate.runWithClosed(async () => {
await setTimeout();
await waitForOpenInputGate();
});
t.pass();
});
test("OutputGate: runWith: runs closure with output gate in context", async (t) => {
const outputGate = new OutputGate();
await outputGate.runWith(() => t.not(waitForOpenOutputGate(), undefined));
});
test("OutputGate: runWith: waits for gate to open before returning result", async (t) => {
const events: number[] = [];
const outputGate = new OutputGate();
// Close output gate
const [openTrigger, openPromise] = triggerPromise<void>();
outputGate.waitUntil(openPromise);
const runWithPromise = outputGate.runWith(noop).then(() => events.push(1));
await setTimeout();
events.push(2);
openTrigger();
await runWithPromise;
t.deepEqual(events, [2, 1]);
});
test("OutputGate: waitForOpen/waitUntil: waits for gate to open", async (t) => {
const events: number[] = [];
const outputGate = new OutputGate();
// Close output gate
const [openTrigger1, openPromise1] = triggerPromise<void>();
const [openTrigger2, openPromise2] = triggerPromise<void>();
outputGate.waitUntil(openPromise1);
outputGate.waitUntil(openPromise2);
const runWithPromise = outputGate.waitForOpen().then(() => events.push(1));
await setTimeout();
events.push(2);
openTrigger1();
// Check requires all promises to resolve before opening
await setTimeout();
t.deepEqual(events, [2]);
openTrigger2();
await runWithPromise;
t.deepEqual(events, [2, 1]);
});
test("InputGatedEventTarget: dispatches events with no input gate in context", async (t) => {
const eventTarget = new InputGatedEventTarget<{ test: Event }>();
eventTarget.addEventListener("test", () => t.pass());
eventTarget.dispatchEvent(new Event("test"));
});
test("InputGatedEventTarget: waits for input gate in add listener context to open before dispatching events", async (t) => {
const events: number[] = [];
const inputGate = new InputGate();
const [eventTrigger, eventPromise] = triggerPromise<void>();
const eventTarget = new InputGatedEventTarget<{ test: Event }>();
await inputGate.runWith(() => {
// (e.g. adding WebSocket listener inside Durable Object fetch)
eventTarget.addEventListener("test", () => {
events.push(1);
eventTrigger();
});
});
// Close input gate
const [openTrigger, openPromise] = triggerPromise<void>();
void inputGate.runWithClosed(() => openPromise);
await setTimeout();
events.push(2);
// Note dispatch is outside of input gate context (e.g. delivering WebSocket
// message from network), but still waits for input gate from add listener
// context to open
eventTarget.dispatchEvent(new Event("test"));
events.push(3);
openTrigger();
await eventPromise;
t.deepEqual(events, [2, 3, 1]);
}); | the_stack |
import * as _collections from './_collections';
import * as _tools from './_tools';
import { JsApi } from '../lib/jsapi';
const regPathInstructions = /([MmLlHhVvCcSsQqTtAaZz])\s*/;
const regPathData = /[-+]?(?:\d*\.\d+|\d+\.?)([eE][-+]?\d+)?/g;
const regNumericValues = /[-+]?(\d*\.\d+|\d+\.?)(?:[eE][-+]?\d+)?/;
const referencesProps = _collections.referencesProps;
const defaultStrokeWidth =
_collections.attrsGroupsDefaults.presentation['stroke-width'];
const cleanupOutData = _tools.cleanupOutData;
const removeLeadingZero = _tools.removeLeadingZero;
let prevCtrlPoint: number[];
export interface PathItem {
instruction: string;
data?: number[];
coords?: number[];
base?: number[];
}
export type Point = [number, number];
export type Curve = [number, number, number, number, number, number];
export interface Circle {
center: Point;
radius: number;
}
/**
* Convert path string to JS representation.
*/
export function path2js(path: JsApi) {
// TODO: avoid this caching hackery...
if (path.pathJS) {
return path.pathJS;
}
// prettier-ignore
const paramsLength: {[key: string]: number} = {
// Number of parameters of every path command
H: 1, V: 1, M: 2, L: 2, T: 2, Q: 4, S: 4, C: 6, A: 7,
h: 1, v: 1, m: 2, l: 2, t: 2, q: 4, s: 4, c: 6, a: 7,
};
const pathData: Array<{ instruction: string; data?: number[] }> = [];
let instruction: string;
let startMoveto = false;
// splitting path string into array like ['M', '10 50', 'L', '20 30']
path
.attr('android:pathData')
.value.split(regPathInstructions)
.forEach(data => {
if (!data) {
return;
}
if (!startMoveto) {
if (data === 'M' || data === 'm') {
startMoveto = true;
} else {
return;
}
}
// Instruction item.
if (regPathInstructions.test(data)) {
instruction = data;
// Z - instruction w/o data.
if (instruction === 'Z' || instruction === 'z') {
pathData.push({ instruction: 'z' });
}
} else {
// Data item.
const matchedData = data.match(regPathData);
if (!matchedData) {
return;
}
const matchedNumData = matchedData.map(Number);
// Subsequent moveto pairs of coordinates are threated as implicit lineto commands
// http://www.w3.org/TR/SVG/paths.html#PathDataMovetoCommands
if (instruction === 'M' || instruction === 'm') {
pathData.push({
instruction: pathData.length === 0 ? 'M' : instruction,
data: matchedNumData.splice(0, 2),
});
instruction = instruction === 'M' ? 'L' : 'l';
}
for (const pair = paramsLength[instruction]; matchedNumData.length; ) {
pathData.push({ instruction, data: matchedNumData.splice(0, pair) });
}
}
});
// First moveto is actually absolute. Subsequent coordinates were separated above.
if (pathData.length && pathData[0].instruction === 'm') {
pathData[0].instruction = 'M';
}
// TODO: avoid this caching hackery...
path.pathJS = pathData;
return pathData;
}
/**
* Convert absolute path data coordinates to relative.
*
* @param {Array} path input path data
* @param {Object} params plugin params
* @return {Array} output path data
*/
export function convertToRelative(path: PathItem[]) {
const point = [0, 0];
const subpathPoint = [0, 0];
let baseItem: PathItem;
path.forEach((item, index) => {
let instruction = item.instruction;
const data = item.data;
// data !== !z
if (data) {
// already relative
// recalculate current point
if ('mcslqta'.indexOf(instruction) > -1) {
point[0] += data[data.length - 2];
point[1] += data[data.length - 1];
if (instruction === 'm') {
subpathPoint[0] = point[0];
subpathPoint[1] = point[1];
baseItem = item;
}
} else if (instruction === 'h') {
point[0] += data[0];
} else if (instruction === 'v') {
point[1] += data[0];
}
// convert absolute path data coordinates to relative
// if "M" was not transformed from "m"
// M → m
if (instruction === 'M') {
if (index > 0) {
instruction = 'm';
}
data[0] -= point[0];
data[1] -= point[1];
subpathPoint[0] = point[0] += data[0];
subpathPoint[1] = point[1] += data[1];
baseItem = item;
} else if ('LT'.indexOf(instruction) > -1) {
// L → l
// T → t
instruction = instruction.toLowerCase();
// x y
// 0 1
data[0] -= point[0];
data[1] -= point[1];
point[0] += data[0];
point[1] += data[1];
// C → c
} else if (instruction === 'C') {
instruction = 'c';
// x1 y1 x2 y2 x y
// 0 1 2 3 4 5
data[0] -= point[0];
data[1] -= point[1];
data[2] -= point[0];
data[3] -= point[1];
data[4] -= point[0];
data[5] -= point[1];
point[0] += data[4];
point[1] += data[5];
// S → s
// Q → q
} else if ('SQ'.indexOf(instruction) > -1) {
instruction = instruction.toLowerCase();
// x1 y1 x y
// 0 1 2 3
data[0] -= point[0];
data[1] -= point[1];
data[2] -= point[0];
data[3] -= point[1];
point[0] += data[2];
point[1] += data[3];
// A → a
} else if (instruction === 'A') {
instruction = 'a';
// rx ry x-axis-rotation large-arc-flag sweep-flag x y
// 0 1 2 3 4 5 6
data[5] -= point[0];
data[6] -= point[1];
point[0] += data[5];
point[1] += data[6];
// H → h
} else if (instruction === 'H') {
instruction = 'h';
data[0] -= point[0];
point[0] += data[0];
// V → v
} else if (instruction === 'V') {
instruction = 'v';
data[0] -= point[1];
point[1] += data[0];
}
item.instruction = instruction;
item.data = data;
// store absolute coordinates for later use
item.coords = point.slice(-2);
} else if (instruction === 'z') {
// !data === z, reset current point
if (baseItem) {
item.coords = baseItem.coords;
}
point[0] = subpathPoint[0];
point[1] = subpathPoint[1];
}
item.base = index > 0 ? path[index - 1].coords : [0, 0];
});
return path;
}
/**
* Convert relative Path data to absolute.
*
* @param {Array} data input data
* @return {Array} output data
*/
function relative2absolute(data: PathItem[]) {
const currentPoint = [0, 0];
const subpathPoint = [0, 0];
return data.map(item => {
const instruction = item.instruction;
const itemData = item.data && item.data.slice();
if (instruction === 'M') {
set(currentPoint, itemData);
set(subpathPoint, itemData);
} else if ('mlcsqt'.indexOf(instruction) > -1) {
for (let i = 0; i < itemData.length; i++) {
itemData[i] += currentPoint[i % 2];
}
set(currentPoint, itemData);
if (instruction === 'm') {
set(subpathPoint, itemData);
}
} else if (instruction === 'a') {
itemData[5] += currentPoint[0];
itemData[6] += currentPoint[1];
set(currentPoint, itemData);
} else if (instruction === 'h') {
itemData[0] += currentPoint[0];
currentPoint[0] = itemData[0];
} else if (instruction === 'v') {
itemData[0] += currentPoint[1];
currentPoint[1] = itemData[0];
} else if ('MZLCSQTA'.indexOf(instruction) > -1) {
set(currentPoint, itemData);
} else if (instruction === 'H') {
currentPoint[0] = itemData[0];
} else if (instruction === 'V') {
currentPoint[1] = itemData[0];
} else if (instruction === 'z') {
set(currentPoint, subpathPoint);
}
return instruction === 'z'
? { instruction: 'z' }
: {
instruction: instruction.toUpperCase(),
data: itemData,
};
});
}
/**
* Apply transformation(s) to the Path data.
*
* @param {Object} elem current element
* @param {Array} path input path data
* @param {Object} params whether to apply transforms to stroked lines and transform precision (used for stroke width)
* @return {Array} output path data
*/
export function applyTransforms(
group: JsApi,
elem: JsApi,
path: PathItem[],
params: { transformPrecision: number; applyTransformsStroked: boolean },
) {
// if there are no 'stroke' attr and references to other objects such as
// gradiends or clip-path which are also subjects to transform.
// if (
// !elem.hasAttr('transform') ||
// !elem.attr('transform').value ||
// elem.someAttr(attr => {
// const refProps = referencesProps;
// // tslint:disable-next-line:no-bitwise
// const res = ~refProps.indexOf(attr.name) && ~attr.value.indexOf('url(');
// return !!res;
// })
// ) {
// return path;
// }
const groupAttrs = getGroupAttrs(group);
const matrix = {
name: 'matrix',
data: groupToMatrix(groupAttrs),
};
// const stroke = elem.computedAttr('stroke');
// const id = elem.computedAttr('id');
const transformPrecision = params.transformPrecision;
let newPoint: number[];
// let scale: number;
// if (stroke && stroke !== 'none') {
// if (
// !params.applyTransformsStroked ||
// ((matrix.data[0] !== matrix.data[3] ||
// matrix.data[1] !== -matrix.data[2]) &&
// (matrix.data[0] !== -matrix.data[3] ||
// matrix.data[1] !== matrix.data[2]))
// ) {
// return path;
// }
// // "stroke-width" should be inside the part with ID, otherwise it can be overrided in <use>
// if (id) {
// let idElem = elem;
// let hasStrokeWidth = false;
// do {
// if (idElem.hasAttr('stroke-width')) {
// hasStrokeWidth = true;
// }
// } while (
// !idElem.hasAttr('id', id) &&
// !hasStrokeWidth &&
// (idElem = idElem.parentNode)
// );
// if (!hasStrokeWidth) {
// return path;
// }
// }
// scale = +Math.sqrt(
// matrix.data[0] * matrix.data[0] + matrix.data[1] * matrix.data[1],
// ).toFixed(transformPrecision);
// if (scale !== 1) {
// // TODO: can we avoid the cast to string here?
// const strokeWidth = (elem.computedAttr('stroke-width') ||
// defaultStrokeWidth) as string;
// if (elem.hasAttr('stroke-width')) {
// elem.attrs['stroke-width'].value = elem.attrs['stroke-width'].value
// .trim()
// .replace(regNumericValues, num => removeLeadingZero(+num * scale));
// } else {
// elem.addAttr({
// name: 'stroke-width',
// prefix: '',
// local: 'stroke-width',
// value: strokeWidth.replace(regNumericValues, num =>
// removeLeadingZero(+num * scale),
// ),
// });
// }
// }
// } else if (id) {
// // Stroke and stroke-width can be redefined with <use>
// return path;
// }
path.forEach(pathItem => {
if (pathItem.data) {
// h -> l
if (pathItem.instruction === 'h') {
pathItem.instruction = 'l';
pathItem.data[1] = 0;
// v -> l
} else if (pathItem.instruction === 'v') {
pathItem.instruction = 'l';
pathItem.data[1] = pathItem.data[0];
pathItem.data[0] = 0;
}
// if there is a translate() transform
if (
pathItem.instruction === 'M' &&
(matrix.data[4] !== 0 || matrix.data[5] !== 0)
) {
// then apply it only to the first absoluted M
newPoint = transformPoint(
matrix.data,
pathItem.data[0],
pathItem.data[1],
);
set(pathItem.data, newPoint);
set(pathItem.coords, newPoint);
// clear translate() data from transform matrix
matrix.data[4] = 0;
matrix.data[5] = 0;
} else {
if (pathItem.instruction === 'a') {
transformArc(pathItem.data, matrix.data);
// reduce number of digits in rotation angle
if (Math.abs(pathItem.data[2]) > 80) {
const a = pathItem.data[0];
const rotation = pathItem.data[2];
pathItem.data[0] = pathItem.data[1];
pathItem.data[1] = a;
pathItem.data[2] = rotation + (rotation > 0 ? -90 : 90);
}
newPoint = transformPoint(
matrix.data,
pathItem.data[5],
pathItem.data[6],
);
pathItem.data[5] = newPoint[0];
pathItem.data[6] = newPoint[1];
} else {
for (let i = 0; i < pathItem.data.length; i += 2) {
newPoint = transformPoint(
matrix.data,
pathItem.data[i],
pathItem.data[i + 1],
);
pathItem.data[i] = newPoint[0];
pathItem.data[i + 1] = newPoint[1];
}
}
pathItem.coords[0] =
pathItem.base[0] + pathItem.data[pathItem.data.length - 2];
pathItem.coords[1] =
pathItem.base[1] + pathItem.data[pathItem.data.length - 1];
}
}
});
// remove transform attr
// elem.removeAttr('transform');
return path;
}
export function getGroupAttrs(group: JsApi) {
const px = getGroupAttr(group, 'pivotX', 0);
const py = getGroupAttr(group, 'pivotY', 0);
const sx = getGroupAttr(group, 'scaleX', 1);
const sy = getGroupAttr(group, 'scaleY', 1);
const tx = getGroupAttr(group, 'translateX', 0);
const ty = getGroupAttr(group, 'translateY', 0);
const r = getGroupAttr(group, 'rotation', 0);
return { px, py, sx, sy, tx, ty, r };
}
function getGroupAttr(
group: JsApi,
attrLocalName: string,
defaultValue: number,
) {
const attrName = `android:${attrLocalName}`;
const result = group.hasAttr(attrName)
? +group.attr(attrName).value
: defaultValue;
return result;
}
export type Matrix = [number, number, number, number, number, number];
export interface GroupTransform {
sx: number;
sy: number;
r: number;
tx: number;
ty: number;
px: number;
py: number;
}
/**
* Extracts the x/y scaling from the transformation matrix.
*/
export function getScaling(matrix: Matrix) {
const [a, b, c, d] = matrix;
const sx = (a >= 0 ? 1 : -1) * Math.hypot(a, c);
const sy = (d >= 0 ? 1 : -1) * Math.hypot(b, d);
return { sx, sy };
}
/**
* Extracts the rotation in degrees from the transformation matrix.
*/
export function getRotation(matrix: Matrix) {
return { r: 180 / Math.PI * Math.atan2(-matrix[2], matrix[0]) };
}
/**
* Extracts the x/y translation from the transformation matrix.
*/
export function getTranslation(matrix: Matrix) {
return { tx: matrix[4], ty: matrix[5] };
}
function flattenMatrices(...matrices: Matrix[]) {
const identity: Matrix = [1, 0, 0, 1, 0, 0];
return matrices.reduce((m1, m2) => {
// [a c e] [a' c' e']
// [b d f] * [b' d' f']
// [0 0 1] [0 0 1 ]
return [
m1[0] * m2[0] + m1[2] * m2[1],
m1[1] * m2[0] + m1[3] * m2[1],
m1[0] * m2[2] + m1[2] * m2[3],
m1[1] * m2[2] + m1[3] * m2[3],
m1[0] * m2[4] + m1[2] * m2[5] + m1[4],
m1[1] * m2[4] + m1[3] * m2[5] + m1[5],
];
}, identity);
}
function groupToMatrix({ sx, sy, r, tx, ty, px, py }: GroupTransform) {
const cosr = Math.cos(r * Math.PI / 180);
const sinr = Math.sin(r * Math.PI / 180);
return flattenMatrices(
[1, 0, 0, 1, px, py],
[1, 0, 0, 1, tx, ty],
[cosr, sinr, -sinr, cosr, 0, 0],
[sx, 0, 0, sy, 0, 0],
[1, 0, 0, 1, -px, -py],
);
}
export function flattenGroups(groups: GroupTransform[]) {
return flattenMatrices(...groups.map(groupToMatrix));
}
/**
* Apply transform 3x3 matrix to x-y point.
*
* @param {Array} matrix transform 3x3 matrix
* @param {Array} point x-y point
* @return {Array} point with new coordinates
*/
function transformPoint(matrix: number[], x: number, y: number) {
return [
matrix[0] * x + matrix[2] * y + matrix[4],
matrix[1] * x + matrix[3] * y + matrix[5],
];
}
/**
* Compute Cubic Bézier bounding box.
* @see http://processingjs.nihongoresources.com/bezierinfo/
*/
// export function computeCubicBoundingBox(
// xa: number,
// ya: number,
// xb: number,
// yb: number,
// xc: number,
// yc: number,
// xd: number,
// yd: number,
// ) {
// let minx = Number.POSITIVE_INFINITY;
// let miny = Number.POSITIVE_INFINITY;
// let maxx = Number.NEGATIVE_INFINITY;
// let maxy = Number.NEGATIVE_INFINITY;
// let ts: number[];
// let t: number;
// let x: number;
// let y: number;
// let i: number;
// // X
// if (xa < minx) {
// minx = xa;
// }
// if (xa > maxx) {
// maxx = xa;
// }
// if (xd < minx) {
// minx = xd;
// }
// if (xd > maxx) {
// maxx = xd;
// }
// ts = computeCubicFirstDerivativeRoots(xa, xb, xc, xd);
// for (i = 0; i < ts.length; i++) {
// t = ts[i];
// if (t >= 0 && t <= 1) {
// x = computeCubicBaseValue(t, xa, xb, xc, xd);
// if (x < minx) {
// minx = x;
// }
// if (x > maxx) {
// maxx = x;
// }
// }
// }
// // Y
// if (ya < miny) {
// miny = ya;
// }
// if (ya > maxy) {
// maxy = ya;
// }
// if (yd < miny) {
// miny = yd;
// }
// if (yd > maxy) {
// maxy = yd;
// }
// ts = computeCubicFirstDerivativeRoots(ya, yb, yc, yd);
// for (i = 0; i < ts.length; i++) {
// t = ts[i];
// if (t >= 0 && t <= 1) {
// y = computeCubicBaseValue(t, ya, yb, yc, yd);
// if (y < miny) {
// miny = y;
// }
// if (y > maxy) {
// maxy = y;
// }
// }
// }
// return { minx, miny, maxx, maxy };
// }
// Compute the value for the cubic bezier function at time t.
// function computeCubicBaseValue(
// t: number,
// a: number,
// b: number,
// c: number,
// d: number,
// ) {
// const mt = 1 - t;
// return (
// mt * mt * mt * a + 3 * mt * mt * t * b + 3 * mt * t * t * c + t * t * t * d
// );
// }
// Compute the value for the first derivative of the cubic bezier function at time t.
// function computeCubicFirstDerivativeRoots(
// a: number,
// b: number,
// c: number,
// d: number,
// ) {
// const result = [-1, -1];
// const tl = -a + 2 * b - c;
// const tr = -Math.sqrt(-a * (c - d) + b * b - b * (c + d) + c * c);
// const dn = -a + 3 * b - 3 * c + d;
// if (dn !== 0) {
// result[0] = (tl + tr) / dn;
// result[1] = (tl - tr) / dn;
// }
// return result;
// }
/**
* Compute Quadratic Bézier bounding box.
*
* @see http://processingjs.nihongoresources.com/bezierinfo/
*/
// export function computeQuadraticBoundingBox(
// xa: number,
// ya: number,
// xb: number,
// yb: number,
// xc: number,
// yc: number,
// ) {
// let minx = Number.POSITIVE_INFINITY;
// let miny = Number.POSITIVE_INFINITY;
// let maxx = Number.NEGATIVE_INFINITY;
// let maxy = Number.NEGATIVE_INFINITY;
// let t: number;
// let x: number;
// let y: number;
// // X
// if (xa < minx) {
// minx = xa;
// }
// if (xa > maxx) {
// maxx = xa;
// }
// if (xc < minx) {
// minx = xc;
// }
// if (xc > maxx) {
// maxx = xc;
// }
// t = computeQuadraticFirstDerivativeRoot(xa, xb, xc);
// if (t >= 0 && t <= 1) {
// x = computeQuadraticBaseValue(t, xa, xb, xc);
// if (x < minx) {
// minx = x;
// }
// if (x > maxx) {
// maxx = x;
// }
// }
// // Y
// if (ya < miny) {
// miny = ya;
// }
// if (ya > maxy) {
// maxy = ya;
// }
// if (yc < miny) {
// miny = yc;
// }
// if (yc > maxy) {
// maxy = yc;
// }
// t = computeQuadraticFirstDerivativeRoot(ya, yb, yc);
// if (t >= 0 && t <= 1) {
// y = computeQuadraticBaseValue(t, ya, yb, yc);
// if (y < miny) {
// miny = y;
// }
// if (y > maxy) {
// maxy = y;
// }
// }
// return { minx, miny, maxx, maxy };
// }
// Compute the value for the quadratic bezier function at time t.
// function computeQuadraticBaseValue(t: number, a: number, b: number, c: number) {
// const mt = 1 - t;
// return mt * mt * a + 2 * mt * t * b + t * t * c;
// }
// Compute the value for the first derivative of the quadratic bezier function at time t.
// function computeQuadraticFirstDerivativeRoot(a: number, b: number, c: number) {
// let t = -1;
// const denominator = a - 2 * b + c;
// if (denominator !== 0) {
// t = (a - b) / denominator;
// }
// return t;
// }
/**
* Convert path array to string.
*/
export function js2path(
path: JsApi,
data: PathItem[],
params: {
collapseRepeated: boolean;
leadingZero: boolean;
negativeExtraSpace: boolean;
},
) {
path.pathJS = data;
if (params.collapseRepeated) {
data = collapseRepeated(data);
}
path.attr('android:pathData').value = data.reduce((pathString, item) => {
return (pathString +=
item.instruction + (item.data ? cleanupOutData(item.data, params) : ''));
}, '');
}
/**
* Collapse repeated instructions data.
*/
function collapseRepeated(data: PathItem[]) {
let prev: PathItem;
let prevIndex: number;
// Copy an array and modifieds item to keep original data untouched.
return data.reduce(
(newPath, item) => {
if (prev && item.data && item.instruction === prev.instruction) {
// Concat previous data with current.
if (item.instruction !== 'M') {
prev = newPath[prevIndex] = {
instruction: prev.instruction,
data: prev.data.concat(item.data),
coords: item.coords,
base: prev.base,
};
} else {
prev.data = item.data;
prev.coords = item.coords;
}
} else {
newPath.push(item);
prev = item;
prevIndex = newPath.length - 1;
}
return newPath;
},
[] as PathItem[],
);
}
function set(dest: number[], source: number[]) {
dest[0] = source[source.length - 2];
dest[1] = source[source.length - 1];
return dest;
}
/**
* Checks if two paths have an intersection by checking convex hulls
* collision using Gilbert-Johnson-Keerthi distance algorithm
* http://entropyinteractive.com/2011/04/gjk-algorithm/
*
* @param {Array} path1 JS path representation
* @param {Array} path2 JS path representation
* @return {Boolean}
*/
export function intersects(path1: PathItem[], path2: PathItem[]) {
if (path1.length < 3 || path2.length < 3) {
return false; // Nothing to fill.
}
// Collect points of every subpath.
const points1 = relative2absolute(path1).reduce(gatherPoints, []);
const points2 = relative2absolute(path2).reduce(gatherPoints, []);
// Axis-aligned bounding box check.
if (
points1.maxX <= points2.minX ||
points2.maxX <= points1.minX ||
points1.maxY <= points2.minY ||
points2.maxY <= points1.minY ||
points1.every(set1 => {
return points2.every(set2 => {
return (
set1[set1.maxX][0] <= set2[set2.minX][0] ||
set2[set2.maxX][0] <= set1[set1.minX][0] ||
set1[set1.maxY][1] <= set2[set2.minY][1] ||
set2[set2.maxY][1] <= set1[set1.minY][1]
);
});
})
) {
return false;
}
// Get a convex hull from points of each subpath. Has the most complexity O(n·log n).
const hullNest1 = points1.map(convexHull);
const hullNest2 = points2.map(convexHull);
// Check intersection of every subpath of the first path with every subpath of the second.
return hullNest1.some(hull1 => {
if (hull1.length < 3) {
return false;
}
return hullNest2.some(hull2 => {
if (hull2.length < 3) {
return false;
}
const simplex = [getSupport(hull1, hull2, [1, 0])]; // create the initial simplex
const direction = minus(simplex[0]); // set the direction to point towards the origin
let iterations = 1e4; // infinite loop protection, 10 000 iterations is more than enough
while (true) {
if (iterations-- === 0) {
console.error(
'Error: infinite loop while processing mergePaths plugin.',
);
return true; // true is the safe value that means “do nothing with paths”
}
// add a new point
simplex.push(getSupport(hull1, hull2, direction));
// see if the new point was on the correct side of the origin
if (dot(direction, simplex[simplex.length - 1]) <= 0) {
return false;
}
// process the simplex
if (processSimplex(simplex, direction)) {
return true;
}
}
});
});
type Polygon = number[][] & MinMax;
function getSupport(a: Polygon, b: Polygon, direction: number[]) {
return sub(supportPoint(a, direction), supportPoint(b, minus(direction)));
}
// Computes farthest polygon point in particular direction.
// Thanks to knowledge of min/max x and y coordinates we can choose a quadrant to search in.
// Since we're working on convex hull, the dot product is increasing until we find the farthest point.
function supportPoint(polygon: Polygon, direction: number[]) {
let index =
direction[1] >= 0
? direction[0] < 0 ? polygon.maxY : polygon.maxX
: direction[0] < 0 ? polygon.minX : polygon.minY;
let max = -Infinity;
let value;
while ((value = dot(polygon[index], direction)) > max) {
max = value;
index = ++index % polygon.length;
}
return polygon[(index || polygon.length) - 1];
}
}
function processSimplex(simplex: number[][], direction: number[]) {
// wW only need to handle to 1-simplex and 2-simplex.
if (simplex.length === 2) {
// 1-simplex
const a = simplex[1];
const b = simplex[0];
const AO = minus(simplex[1]);
const AB = sub(b, a);
// AO is in the same direction as AB
if (dot(AO, AB) > 0) {
// get the vector perpendicular to AB facing O
set(direction, orth(AB, a));
} else {
set(direction, AO);
// only A remains in the simplex
simplex.shift();
}
} else {
// 2-simplex
const a = simplex[2]; // [a, b, c] = simplex
const b = simplex[1];
const c = simplex[0];
const AB = sub(b, a);
const AC = sub(c, a);
const AO = minus(a);
const ACB = orth(AB, AC); // the vector perpendicular to AB facing away from C
const ABC = orth(AC, AB); // the vector perpendicular to AC facing away from B
if (dot(ACB, AO) > 0) {
if (dot(AB, AO) > 0) {
// region 4
set(direction, ACB);
simplex.shift(); // simplex = [b, a]
} else {
// region 5
set(direction, AO);
simplex.splice(0, 2); // simplex = [a]
}
} else if (dot(ABC, AO) > 0) {
if (dot(AC, AO) > 0) {
// region 6
set(direction, ABC);
simplex.splice(1, 1); // simplex = [c, a]
} else {
// region 5 (again)
set(direction, AO);
simplex.splice(0, 2); // simplex = [a]
}
} else {
return true; // region 7
}
}
return false;
}
function minus(v: number[]) {
return [-v[0], -v[1]];
}
function sub(v1: number[], v2: number[]) {
return [v1[0] - v2[0], v1[1] - v2[1]];
}
function dot(v1: number[], v2: number[]) {
return v1[0] * v2[0] + v1[1] * v2[1];
}
function orth(v: number[], from: number[]) {
const o = [-v[1], v[0]];
return dot(o, minus(from)) < 0 ? minus(o) : o;
}
interface MinMax {
maxX: number;
maxY: number;
minX: number;
minY: number;
}
function gatherPoints(
points: Array<number[][] & Partial<MinMax>> & Partial<MinMax>,
item: PathItem,
index: number,
path: PathItem[],
) {
let subPath = points.length && points[points.length - 1];
const prev = index && path[index - 1];
let basePoint = subPath.length && subPath[subPath.length - 1];
const data = item.data;
let ctrlPoint = basePoint;
switch (item.instruction) {
case 'M':
points.push((subPath = []));
break;
case 'H':
addPoint(subPath, [data[0], basePoint[1]]);
break;
case 'V':
addPoint(subPath, [basePoint[0], data[0]]);
break;
case 'Q':
addPoint(subPath, data.slice(0, 2));
prevCtrlPoint = [data[2] - data[0], data[3] - data[1]]; // Save control point for shorthand
break;
case 'T':
if (prev.instruction === 'Q' || prev.instruction === 'T') {
ctrlPoint = [
basePoint[0] + prevCtrlPoint[0],
basePoint[1] + prevCtrlPoint[1],
];
addPoint(subPath, ctrlPoint);
prevCtrlPoint = [data[0] - ctrlPoint[0], data[1] - ctrlPoint[1]];
}
break;
case 'C':
// Approximate quibic Bezier curve with middle points between control points
addPoint(subPath, [
0.5 * (basePoint[0] + data[0]),
0.5 * (basePoint[1] + data[1]),
]);
addPoint(subPath, [0.5 * (data[0] + data[2]), 0.5 * (data[1] + data[3])]);
addPoint(subPath, [0.5 * (data[2] + data[4]), 0.5 * (data[3] + data[5])]);
prevCtrlPoint = [data[4] - data[2], data[5] - data[3]]; // Save control point for shorthand
break;
case 'S':
if (prev.instruction === 'C' || prev.instruction === 'S') {
addPoint(subPath, [
basePoint[0] + 0.5 * prevCtrlPoint[0],
basePoint[1] + 0.5 * prevCtrlPoint[1],
]);
ctrlPoint = [
basePoint[0] + prevCtrlPoint[0],
basePoint[1] + prevCtrlPoint[1],
];
}
addPoint(subPath, [
0.5 * (ctrlPoint[0] + data[0]),
0.5 * (ctrlPoint[1] + data[1]),
]);
addPoint(subPath, [0.5 * (data[0] + data[2]), 0.5 * (data[1] + data[3])]);
prevCtrlPoint = [data[2] - data[0], data[3] - data[1]];
break;
case 'A':
// Convert the arc to bezier curves and use the same approximation
const curves = a2c.apply(0, basePoint.concat(data));
for (let cData; (cData = curves.splice(0, 6).map(toAbsolute)).length; ) {
addPoint(subPath, [
0.5 * (basePoint[0] + cData[0]),
0.5 * (basePoint[1] + cData[1]),
]);
addPoint(subPath, [
0.5 * (cData[0] + cData[2]),
0.5 * (cData[1] + cData[3]),
]);
addPoint(subPath, [
0.5 * (cData[2] + cData[4]),
0.5 * (cData[3] + cData[5]),
]);
if (curves.length) {
addPoint(subPath, (basePoint = cData.slice(-2)));
}
}
break;
}
// Save final command coordinates
if (data && data.length >= 2) {
addPoint(subPath, data.slice(-2));
}
return points;
function toAbsolute(n: number, i: number) {
return n + basePoint[i % 2];
}
// Writes data about the extreme points on each axle
function addPoint(p: number[][] & Partial<MinMax>, point: number[]) {
if (!p.length || point[1] > p[p.maxY][1]) {
p.maxY = p.length;
points.maxY = points.length ? Math.max(point[1], points.maxY) : point[1];
}
if (!p.length || point[0] > p[p.maxX][0]) {
p.maxX = p.length;
points.maxX = points.length ? Math.max(point[0], points.maxX) : point[0];
}
if (!p.length || point[1] < p[p.minY][1]) {
p.minY = p.length;
points.minY = points.length ? Math.min(point[1], points.minY) : point[1];
}
if (!p.length || point[0] < p[p.minX][0]) {
p.minX = p.length;
points.minX = points.length ? Math.min(point[0], points.minX) : point[0];
}
p.push(point);
}
}
/**
* Forms a convex hull from set of points of every subpath using monotone chain convex hull algorithm.
* http://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain
*
* @param points An array of [X, Y] coordinates
*/
function convexHull(points: number[][]) {
points.sort((a, b) => (a[0] === b[0] ? a[1] - b[1] : a[0] - b[0]));
const lower = [];
let minY = 0;
let bottom = 0;
for (let i = 0; i < points.length; i++) {
while (
lower.length >= 2 &&
cross(lower[lower.length - 2], lower[lower.length - 1], points[i]) <= 0
) {
lower.pop();
}
if (points[i][1] < points[minY][1]) {
minY = i;
bottom = lower.length;
}
lower.push(points[i]);
}
const upper = [];
let maxY = points.length - 1;
let top = 0;
for (let i = points.length; i--; ) {
while (
upper.length >= 2 &&
cross(upper[upper.length - 2], upper[upper.length - 1], points[i]) <= 0
) {
upper.pop();
}
if (points[i][1] > points[maxY][1]) {
maxY = i;
top = upper.length;
}
upper.push(points[i]);
}
// last points are equal to starting points of the other part
upper.pop();
lower.pop();
const hull: any = lower.concat(upper);
hull.minX = 0; // by sorting
hull.maxX = lower.length;
hull.minY = bottom;
hull.maxY = (lower.length + top) % hull.length;
return hull;
}
function cross(o: number[], a: number[], b: number[]) {
return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
}
/*
* Based on code from Snap.svg (Apache 2 license). http://snapsvg.io/
* Thanks to Dmitry Baranovskiy for his great work!
*/
function a2c(
x1: number,
y1: number,
rx: number,
ry: number,
angle: number,
large_arc_flag: number,
sweep_flag: number,
x2: number,
y2: number,
recursive: number[],
) {
// For more information of where this Math came from visit:
// http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
const _120 = Math.PI * 120 / 180;
const rad = Math.PI / 180 * (+angle || 0);
let res: number[] = [];
const rotateX = (x: number, y: number, r: number) =>
x * Math.cos(r) - y * Math.sin(r);
const rotateY = (x: number, y: number, r: number) =>
x * Math.sin(r) + y * Math.cos(r);
let f1: number;
let f2: number;
let cx: number;
let cy: number;
if (!recursive) {
x1 = rotateX(x1, y1, -rad);
y1 = rotateY(x1, y1, -rad);
x2 = rotateX(x2, y2, -rad);
y2 = rotateY(x2, y2, -rad);
const x = (x1 - x2) / 2;
const y = (y1 - y2) / 2;
let h = x * x / (rx * rx) + y * y / (ry * ry);
if (h > 1) {
h = Math.sqrt(h);
rx = h * rx;
ry = h * ry;
}
const rx2 = rx * rx;
const ry2 = ry * ry;
const k =
(large_arc_flag === sweep_flag ? -1 : 1) *
Math.sqrt(
Math.abs(
(rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x),
),
);
cx = k * rx * y / ry + (x1 + x2) / 2;
cy = k * -ry * x / rx + (y1 + y2) / 2;
f1 = Math.asin(+((y1 - cy) / ry).toFixed(9));
f2 = Math.asin(+((y2 - cy) / ry).toFixed(9));
f1 = x1 < cx ? Math.PI - f1 : f1;
f2 = x2 < cx ? Math.PI - f2 : f2;
if (f1 < 0) {
f1 = Math.PI * 2 + f1;
}
if (f2 < 0) {
f2 = Math.PI * 2 + f2;
}
if (sweep_flag && f1 > f2) {
f1 = f1 - Math.PI * 2;
}
if (!sweep_flag && f2 > f1) {
f2 = f2 - Math.PI * 2;
}
} else {
f1 = recursive[0];
f2 = recursive[1];
cx = recursive[2];
cy = recursive[3];
}
let df = f2 - f1;
if (Math.abs(df) > _120) {
const f2old = f2;
const x2old = x2;
const y2old = y2;
f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1);
x2 = cx + rx * Math.cos(f2);
y2 = cy + ry * Math.sin(f2);
res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [
f2,
f2old,
cx,
cy,
]);
}
df = f2 - f1;
const c1 = Math.cos(f1);
const s1 = Math.sin(f1);
const c2 = Math.cos(f2);
const s2 = Math.sin(f2);
const t = Math.tan(df / 4);
const hx = 4 / 3 * rx * t;
const hy = 4 / 3 * ry * t;
const m = [
-hx * s1,
hy * c1,
x2 + hx * s2 - x1,
y2 - hy * c2 - y1,
x2 - x1,
y2 - y1,
];
if (recursive) {
return m.concat(res);
} else {
res = m.concat(res);
const newRes: number[] = [];
for (let i = 0, n = res.length; i < n; i++) {
newRes[i] =
i % 2
? rotateY(res[i - 1], res[i], rad)
: rotateX(res[i], res[i + 1], rad);
}
return newRes;
}
}
/**
* Applies transformation to an arc. To do so, we represent ellipse as a matrix, multiply it
* by the transformation matrix and use a singular value decomposition to represent in a form
* rotate(θ)·scale(a b)·rotate(φ). This gives us new ellipse params a, b and θ.
* SVD is being done with the formulae provided by Wolffram|Alpha (svd {{m0, m2}, {m1, m3}})
*
* @param {Array} arc [a, b, rotation in deg]
* @param {Array} transform transformation matrix
* @return {Array} arc transformed input arc
*/
function transformArc(arc: number[], transform: Matrix) {
let a = arc[0];
let b = arc[1];
const rot = arc[2] * Math.PI / 180;
const cos = Math.cos(rot);
const sin = Math.sin(rot);
let h =
Math.pow(arc[5] * cos + arc[6] * sin, 2) / (4 * a * a) +
Math.pow(arc[6] * cos - arc[5] * sin, 2) / (4 * b * b);
if (h > 1) {
h = Math.sqrt(h);
a *= h;
b *= h;
}
const ellipse: Matrix = [a * cos, a * sin, -b * sin, b * cos, 0, 0];
const m = flattenMatrices(transform, ellipse);
// Decompose the new ellipse matrix.
const lastCol = m[2] * m[2] + m[3] * m[3];
const squareSum = m[0] * m[0] + m[1] * m[1] + lastCol;
const root = Math.sqrt(
(Math.pow(m[0] - m[3], 2) + Math.pow(m[1] + m[2], 2)) *
(Math.pow(m[0] + m[3], 2) + Math.pow(m[1] - m[2], 2)),
);
if (!root) {
// circle
arc[0] = arc[1] = Math.sqrt(squareSum / 2);
arc[2] = 0;
} else {
const majorAxisSqr = (squareSum + root) / 2;
const minorAxisSqr = (squareSum - root) / 2;
const major = Math.abs(majorAxisSqr - lastCol) > 1e-6;
const s = (major ? majorAxisSqr : minorAxisSqr) - lastCol;
const rowsSum = m[0] * m[2] + m[1] * m[3];
const term1 = m[0] * s + m[2] * rowsSum;
const term2 = m[1] * s + m[3] * rowsSum;
arc[0] = Math.sqrt(majorAxisSqr);
arc[1] = Math.sqrt(minorAxisSqr);
arc[2] =
((major ? term2 < 0 : term1 > 0) ? -1 : 1) *
Math.acos(
(major ? term1 : term2) / Math.sqrt(term1 * term1 + term2 * term2),
) *
180 /
Math.PI;
}
if (transform[0] < 0 !== transform[3] < 0) {
// Flip the sweep flag if coordinates are being flipped horizontally XOR vertically
arc[4] = 1 - arc[4];
}
return arc;
} | the_stack |
import useGqlHandler from "./useGqlHandler";
import { fileLifecyclePlugin, lifecycleEventTracker } from "./mocks/lifecyclePlugin";
const WEBINY_VERSION = process.env.WEBINY_VERSION;
const TAG = "webiny";
enum FileLifecycle {
BEFORE_CREATE = "file:beforeCreate",
AFTER_CREATE = "file:afterCreate",
BEFORE_UPDATE = "file:beforeUpdate",
AFTER_UPDATE = "file:afterUpdate",
BEFORE_BATCH_CREATE = "file:beforeBatchCreate",
AFTER_BATCH_CREATE = "file:afterBatchCreate",
BEFORE_DELETE = "file:beforeDelete",
AFTER_DELETE = "file:afterDelete"
}
const fileData = {
key: "/files/filenameA.png",
name: "filenameA.png",
size: 123456,
type: "image/png",
tags: ["sketch"]
};
describe("File lifecycle events", () => {
const { createFile, updateFile, createFiles, deleteFile } = useGqlHandler({
plugins: [fileLifecyclePlugin]
});
const hookParamsExpected = {
id: expect.any(String),
createdOn: expect.stringMatching(/^20/),
createdBy: {
id: "12345678",
displayName: "John Doe",
type: "admin"
},
tenant: "root",
locale: "en-US",
meta: {
private: false
},
webinyVersion: WEBINY_VERSION
};
beforeEach(() => {
lifecycleEventTracker.reset();
});
test(`it should call "beforeCreate" and "afterCreate" methods`, async () => {
const [createResponse] = await createFile({ data: fileData });
/**
* We expect that file was created.
*/
expect(createResponse).toEqual({
data: {
fileManager: {
createFile: {
data: {
...fileData,
id: expect.any(String)
},
error: null
}
}
}
});
/**
* After that we expect that lifecycle method was triggered.
*/
expect(lifecycleEventTracker.getExecuted(FileLifecycle.BEFORE_CREATE)).toEqual(1);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.AFTER_CREATE)).toEqual(1);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.BEFORE_UPDATE)).toEqual(0);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.AFTER_UPDATE)).toEqual(0);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.BEFORE_BATCH_CREATE)).toEqual(0);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.AFTER_BATCH_CREATE)).toEqual(0);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.BEFORE_DELETE)).toEqual(0);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.AFTER_DELETE)).toEqual(0);
/**
* Parameters that were received in the lifecycle hooks must be valid as well.
*/
const beforeCreate = lifecycleEventTracker.getLast(FileLifecycle.BEFORE_CREATE);
expect(beforeCreate.params[0]).toEqual({
context: expect.any(Object),
data: {
...fileData,
...hookParamsExpected
}
});
const afterCreate = lifecycleEventTracker.getLast(FileLifecycle.AFTER_CREATE);
expect(afterCreate.params[0]).toEqual({
context: expect.any(Object),
data: {
...fileData,
...hookParamsExpected
},
file: {
...fileData,
...hookParamsExpected
}
});
});
test(`it should call "beforeUpdate" and "afterUpdate" methods`, async () => {
const [createResponse] = await createFile({ data: fileData });
const id = createResponse.data.fileManager.createFile.data.id;
const [updateResponse] = await updateFile({
id,
data: {
tags: [...fileData.tags, TAG]
}
});
expect(updateResponse).toEqual({
data: {
fileManager: {
updateFile: {
data: {
...fileData,
tags: [...fileData.tags, TAG]
},
error: null
}
}
}
});
/**
* After that we expect that lifecycle method was triggered.
*/
expect(lifecycleEventTracker.getExecuted(FileLifecycle.BEFORE_CREATE)).toEqual(1);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.AFTER_CREATE)).toEqual(1);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.BEFORE_UPDATE)).toEqual(1);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.AFTER_UPDATE)).toEqual(1);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.BEFORE_BATCH_CREATE)).toEqual(0);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.AFTER_BATCH_CREATE)).toEqual(0);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.BEFORE_DELETE)).toEqual(0);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.AFTER_DELETE)).toEqual(0);
/**
* Parameters that were received in the lifecycle hooks must be valid as well.
*/
const beforeUpdate = lifecycleEventTracker.getLast(FileLifecycle.BEFORE_UPDATE);
expect(beforeUpdate.params[0]).toEqual({
context: expect.any(Object),
original: {
...fileData,
...hookParamsExpected,
id: expect.any(String)
},
data: {
...fileData,
...hookParamsExpected,
tags: [...fileData.tags, TAG]
}
});
const afterUpdate = lifecycleEventTracker.getLast(FileLifecycle.AFTER_UPDATE);
expect(afterUpdate.params[0]).toEqual({
context: expect.any(Object),
original: {
...fileData,
...hookParamsExpected,
id: expect.any(String)
},
data: {
...fileData,
...hookParamsExpected,
tags: [...fileData.tags, TAG]
},
file: {
...fileData,
...hookParamsExpected,
tags: [...fileData.tags, TAG]
}
});
});
test(`it should call "beforeDelete" and "afterDelete" methods`, async () => {
const [createResponse] = await createFile({ data: fileData });
const id = createResponse.data.fileManager.createFile.data.id;
const [deleteResponse] = await deleteFile({
id
});
expect(deleteResponse).toEqual({
data: {
fileManager: {
deleteFile: {
data: true,
error: null
}
}
}
});
/**
* After that we expect that lifecycle method was triggered.
*/
expect(lifecycleEventTracker.getExecuted(FileLifecycle.BEFORE_CREATE)).toEqual(1);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.AFTER_CREATE)).toEqual(1);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.BEFORE_UPDATE)).toEqual(0);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.AFTER_UPDATE)).toEqual(0);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.BEFORE_BATCH_CREATE)).toEqual(0);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.AFTER_BATCH_CREATE)).toEqual(0);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.BEFORE_DELETE)).toEqual(1);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.AFTER_DELETE)).toEqual(1);
/**
* Parameters that were received in the lifecycle hooks must be valid as well.
*/
const beforeDelete = lifecycleEventTracker.getLast(FileLifecycle.BEFORE_DELETE);
expect(beforeDelete.params[0]).toEqual({
context: expect.any(Object),
file: {
...fileData,
...hookParamsExpected
}
});
const afterDelete = lifecycleEventTracker.getLast(FileLifecycle.AFTER_DELETE);
expect(afterDelete.params[0]).toEqual({
context: expect.any(Object),
file: {
...fileData,
...hookParamsExpected
}
});
});
test(`it should call "beforeCreateBatch" and "afterCreateBatch" methods`, async () => {
const [createBatchResponse] = await createFiles({
data: [fileData]
});
expect(createBatchResponse).toEqual({
data: {
fileManager: {
createFiles: {
data: [
{
...fileData,
id: expect.any(String)
}
],
error: null
}
}
}
});
/**
* After that we expect that lifecycle method was triggered.
*/
expect(lifecycleEventTracker.getExecuted(FileLifecycle.BEFORE_CREATE)).toEqual(0);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.AFTER_CREATE)).toEqual(0);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.BEFORE_UPDATE)).toEqual(0);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.AFTER_UPDATE)).toEqual(0);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.BEFORE_BATCH_CREATE)).toEqual(1);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.AFTER_BATCH_CREATE)).toEqual(1);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.BEFORE_DELETE)).toEqual(0);
expect(lifecycleEventTracker.getExecuted(FileLifecycle.AFTER_DELETE)).toEqual(0);
/**
* Parameters that were received in the lifecycle hooks must be valid as well.
*/
const beforeBatchCreate = lifecycleEventTracker.getLast(FileLifecycle.BEFORE_BATCH_CREATE);
expect(beforeBatchCreate.params[0]).toEqual({
context: expect.any(Object),
data: [
{
...fileData,
...hookParamsExpected
}
]
});
const afterBatchCreate = lifecycleEventTracker.getLast(FileLifecycle.AFTER_BATCH_CREATE);
expect(afterBatchCreate.params[0]).toEqual({
context: expect.any(Object),
data: [
{
...fileData,
...hookParamsExpected
}
],
files: [
{
...fileData,
...hookParamsExpected
}
]
});
});
}); | the_stack |
import { createStitches } from '@stitches/react';
import {
gray,
mauve,
slate,
sage,
olive,
sand,
tomato,
red,
crimson,
pink,
plum,
purple,
violet,
indigo,
blue,
sky,
mint,
cyan,
teal,
green,
grass,
lime,
yellow,
amber,
orange,
brown,
bronze,
gold,
grayA,
mauveA,
slateA,
sageA,
oliveA,
sandA,
tomatoA,
redA,
crimsonA,
pinkA,
plumA,
purpleA,
violetA,
indigoA,
blueA,
skyA,
mintA,
cyanA,
tealA,
greenA,
grassA,
limeA,
yellowA,
amberA,
orangeA,
brownA,
bronzeA,
goldA,
whiteA,
blackA,
grayDark,
mauveDark,
slateDark,
sageDark,
oliveDark,
sandDark,
tomatoDark,
redDark,
crimsonDark,
pinkDark,
plumDark,
purpleDark,
violetDark,
indigoDark,
blueDark,
skyDark,
mintDark,
cyanDark,
tealDark,
greenDark,
grassDark,
limeDark,
yellowDark,
amberDark,
orangeDark,
brownDark,
bronzeDark,
goldDark,
grayDarkA,
mauveDarkA,
slateDarkA,
sageDarkA,
oliveDarkA,
sandDarkA,
tomatoDarkA,
redDarkA,
crimsonDarkA,
pinkDarkA,
plumDarkA,
purpleDarkA,
violetDarkA,
indigoDarkA,
blueDarkA,
skyDarkA,
mintDarkA,
cyanDarkA,
tealDarkA,
greenDarkA,
grassDarkA,
limeDarkA,
yellowDarkA,
amberDarkA,
orangeDarkA,
brownDarkA,
bronzeDarkA,
goldDarkA,
} from '@radix-ui/colors';
import type * as Stitches from '@stitches/react';
export type { VariantProps } from '@stitches/react';
export const {
styled,
createTheme,
getCssText,
keyframes,
config,
} = createStitches({
theme: {
colors: {
...gray,
...mauve,
...slate,
...sage,
...olive,
...sand,
...tomato,
...red,
...crimson,
...pink,
...plum,
...purple,
...violet,
...indigo,
...blue,
...sky,
...mint,
...cyan,
...teal,
...green,
...grass,
...lime,
...yellow,
...amber,
...orange,
...brown,
...bronze,
...gold,
...grayA,
...mauveA,
...slateA,
...sageA,
...oliveA,
...sandA,
...tomatoA,
...redA,
...crimsonA,
...pinkA,
...plumA,
...purpleA,
...violetA,
...indigoA,
...blueA,
...skyA,
...mintA,
...cyanA,
...tealA,
...greenA,
...grassA,
...limeA,
...yellowA,
...amberA,
...orangeA,
...brownA,
...bronzeA,
...goldA,
...whiteA,
...blackA,
// Semantic colors
hiContrast: '$slate12',
// loContrast: '$slate1',
loContrast: 'white',
canvas: 'hsl(0 0% 93%)',
panel: 'white',
transparentPanel: 'hsl(0 0% 0% / 97%)',
shadowLight: 'hsl(206 22% 7% / 35%)',
shadowDark: 'hsl(206 22% 7% / 20%)',
},
fonts: {
untitled: 'Untitled Sans, -apple-system, system-ui, sans-serif',
mono: 'Söhne Mono, menlo, monospace',
},
space: {
1: '5px',
2: '10px',
3: '15px',
4: '20px',
5: '25px',
6: '35px',
7: '45px',
8: '65px',
9: '80px',
},
sizes: {
1: '5px',
2: '10px',
3: '15px',
4: '20px',
5: '25px',
6: '35px',
7: '45px',
8: '65px',
9: '80px',
},
// space: {
// 1: '4px',
// 2: '8px',
// 3: '16px',
// 4: '20px',
// 5: '24px',
// 6: '32px',
// 7: '48px',
// 8: '64px',
// 9: '80px',
// },
// sizes: {
// 1: '4px',
// 2: '8px',
// 3: '16px',
// 4: '20px',
// 5: '24px',
// 6: '32px',
// 7: '48px',
// 8: '64px',
// 9: '80px',
// },
fontSizes: {
1: '12px',
2: '13px',
3: '15px',
4: '17px',
5: '19px',
6: '21px',
7: '27px',
8: '35px',
9: '59px',
},
// fontSizes: {
// 1: '11px',
// 2: '12px',
// 3: '15px',
// 4: '17px',
// 5: '20px',
// 6: '22px',
// 7: '28px',
// 8: '36px',
// 9: '60px',
// },
radii: {
1: '4px',
2: '6px',
3: '8px',
4: '12px',
round: '50%',
pill: '9999px',
},
zIndices: {
1: '100',
2: '200',
3: '300',
4: '400',
max: '999',
},
},
media: {
bp1: '(min-width: 520px)',
bp2: '(min-width: 900px)',
bp3: '(min-width: 1200px)',
bp4: '(min-width: 1800px)',
motion: '(prefers-reduced-motion)',
hover: '(any-hover: hover)',
dark: '(prefers-color-scheme: dark)',
light: '(prefers-color-scheme: light)',
},
utils: {
p: (value: Stitches.PropertyValue<'padding'>) => ({
padding: value,
}),
pt: (value: Stitches.PropertyValue<'paddingTop'>) => ({
paddingTop: value,
}),
pr: (value: Stitches.PropertyValue<'paddingRight'>) => ({
paddingRight: value,
}),
pb: (value: Stitches.PropertyValue<'paddingBottom'>) => ({
paddingBottom: value,
}),
pl: (value: Stitches.PropertyValue<'paddingLeft'>) => ({
paddingLeft: value,
}),
px: (value: Stitches.PropertyValue<'paddingLeft'>) => ({
paddingLeft: value,
paddingRight: value,
}),
py: (value: Stitches.PropertyValue<'paddingTop'>) => ({
paddingTop: value,
paddingBottom: value,
}),
m: (value: Stitches.PropertyValue<'margin'>) => ({
margin: value,
}),
mt: (value: Stitches.PropertyValue<'marginTop'>) => ({
marginTop: value,
}),
mr: (value: Stitches.PropertyValue<'marginRight'>) => ({
marginRight: value,
}),
mb: (value: Stitches.PropertyValue<'marginBottom'>) => ({
marginBottom: value,
}),
ml: (value: Stitches.PropertyValue<'marginLeft'>) => ({
marginLeft: value,
}),
mx: (value: Stitches.PropertyValue<'marginLeft'>) => ({
marginLeft: value,
marginRight: value,
}),
my: (value: Stitches.PropertyValue<'marginTop'>) => ({
marginTop: value,
marginBottom: value,
}),
ta: (value: Stitches.PropertyValue<'textAlign'>) => ({ textAlign: value }),
fd: (value: Stitches.PropertyValue<'flexDirection'>) => ({ flexDirection: value }),
fw: (value: Stitches.PropertyValue<'flexWrap'>) => ({ flexWrap: value }),
ai: (value: Stitches.PropertyValue<'alignItems'>) => ({ alignItems: value }),
ac: (value: Stitches.PropertyValue<'alignContent'>) => ({ alignContent: value }),
jc: (value: Stitches.PropertyValue<'justifyContent'>) => ({ justifyContent: value }),
as: (value: Stitches.PropertyValue<'alignSelf'>) => ({ alignSelf: value }),
fg: (value: Stitches.PropertyValue<'flexGrow'>) => ({ flexGrow: value }),
fs: (value: Stitches.PropertyValue<'flexShrink'>) => ({ flexShrink: value }),
fb: (value: Stitches.PropertyValue<'flexBasis'>) => ({ flexBasis: value }),
bc: (value: Stitches.PropertyValue<'backgroundColor'>) => ({
backgroundColor: value,
}),
br: (value: Stitches.PropertyValue<'borderRadius'>) => ({
borderRadius: value,
}),
btrr: (value: Stitches.PropertyValue<'borderTopRightRadius'>) => ({
borderTopRightRadius: value,
}),
bbrr: (value: Stitches.PropertyValue<'borderBottomRightRadius'>) => ({
borderBottomRightRadius: value,
}),
bblr: (value: Stitches.PropertyValue<'borderBottomLeftRadius'>) => ({
borderBottomLeftRadius: value,
}),
btlr: (value: Stitches.PropertyValue<'borderTopLeftRadius'>) => ({
borderTopLeftRadius: value,
}),
bs: (value: Stitches.PropertyValue<'boxShadow'>) => ({ boxShadow: value }),
lh: (value: Stitches.PropertyValue<'lineHeight'>) => ({ lineHeight: value }),
ox: (value: Stitches.PropertyValue<'overflowX'>) => ({ overflowX: value }),
oy: (value: Stitches.PropertyValue<'overflowY'>) => ({ overflowY: value }),
pe: (value: Stitches.PropertyValue<'pointerEvents'>) => ({ pointerEvents: value }),
us: (value: Stitches.PropertyValue<'userSelect'>) => ({
WebkitUserSelect: value,
userSelect: value,
}),
userSelect: (value: Stitches.PropertyValue<'userSelect'>) => ({
WebkitUserSelect: value,
userSelect: value,
}),
size: (value: Stitches.PropertyValue<'width'>) => ({
width: value,
height: value,
}),
appearance: (value: Stitches.PropertyValue<'appearance'>) => ({
WebkitAppearance: value,
appearance: value,
}),
backgroundClip: (value: Stitches.PropertyValue<'backgroundClip'>) => ({
WebkitBackgroundClip: value,
backgroundClip: value,
}),
},
});
export type CSS = Stitches.CSS<typeof config>;
export const darkTheme = createTheme('dark-theme', {
colors: {
...grayDark,
...mauveDark,
...slateDark,
...sageDark,
...oliveDark,
...sandDark,
...tomatoDark,
...redDark,
...crimsonDark,
...pinkDark,
...plumDark,
...purpleDark,
...violetDark,
...indigoDark,
...blueDark,
...skyDark,
...mintDark,
...cyanDark,
...tealDark,
...greenDark,
...grassDark,
...limeDark,
...yellowDark,
...amberDark,
...orangeDark,
...brownDark,
...bronzeDark,
...goldDark,
...grayDarkA,
...mauveDarkA,
...slateDarkA,
...sageDarkA,
...oliveDarkA,
...sandDarkA,
...tomatoDarkA,
...redDarkA,
...crimsonDarkA,
...pinkDarkA,
...plumDarkA,
...purpleDarkA,
...violetDarkA,
...indigoDarkA,
...blueDarkA,
...skyDarkA,
...mintDarkA,
...cyanDarkA,
...tealDarkA,
...greenDarkA,
...grassDarkA,
...limeDarkA,
...yellowDarkA,
...amberDarkA,
...orangeDarkA,
...brownDarkA,
...bronzeDarkA,
...goldDarkA,
// Semantic colors
hiContrast: '$slate12',
loContrast: '$slate1',
canvas: 'hsl(0 0% 15%)',
panel: '$slate3',
transparentPanel: 'hsl(0 100% 100% / 97%)',
shadowLight: 'hsl(206 22% 7% / 35%)',
shadowDark: 'hsl(206 22% 7% / 20%)',
},
}); | the_stack |
namespace ts {
describe("extractFunctions", () => {
testExtractFunction("extractFunction1",
`namespace A {
let x = 1;
function foo() {
}
namespace B {
function a() {
let a = 1;
[#|
let y = 5;
let z = x;
a = y;
foo();|]
}
}
}`);
testExtractFunction("extractFunction2",
`namespace A {
let x = 1;
function foo() {
}
namespace B {
function a() {
[#|
let y = 5;
let z = x;
return foo();|]
}
}
}`);
testExtractFunction("extractFunction3",
`namespace A {
function foo() {
}
namespace B {
function* a(z: number) {
[#|
let y = 5;
yield z;
return foo();|]
}
}
}`);
testExtractFunction("extractFunction4",
`namespace A {
function foo() {
}
namespace B {
async function a(z: number, z1: any) {
[#|
let y = 5;
if (z) {
await z1;
}
return foo();|]
}
}
}`);
testExtractFunction("extractFunction5",
`namespace A {
let x = 1;
export function foo() {
}
namespace B {
function a() {
let a = 1;
[#|
let y = 5;
let z = x;
a = y;
foo();|]
}
}
}`);
testExtractFunction("extractFunction6",
`namespace A {
let x = 1;
export function foo() {
}
namespace B {
function a() {
let a = 1;
[#|
let y = 5;
let z = x;
a = y;
return foo();|]
}
}
}`);
testExtractFunction("extractFunction7",
`namespace A {
let x = 1;
export namespace C {
export function foo() {
}
}
namespace B {
function a() {
let a = 1;
[#|
let y = 5;
let z = x;
a = y;
return C.foo();|]
}
}
}`);
testExtractFunction("extractFunction9",
`namespace A {
export interface I { x: number };
namespace B {
function a() {
[#|let a1: I = { x: 1 };
return a1.x + 10;|]
}
}
}`);
testExtractFunction("extractFunction10",
`namespace A {
export interface I { x: number };
class C {
a() {
let z = 1;
[#|let a1: I = { x: 1 };
return a1.x + 10;|]
}
}
}`);
testExtractFunction("extractFunction11",
`namespace A {
let y = 1;
class C {
a() {
let z = 1;
[#|let a1 = { x: 1 };
y = 10;
z = 42;
return a1.x + 10;|]
}
}
}`);
testExtractFunction("extractFunction12",
`namespace A {
let y = 1;
class C {
b() {}
a() {
let z = 1;
[#|let a1 = { x: 1 };
y = 10;
z = 42;
this.b();
return a1.x + 10;|]
}
}
}`);
// The "b" type parameters aren't used and shouldn't be passed to the extracted function.
// Type parameters should be in syntactic order (i.e. in order or character offset from BOF).
// In all cases, we could use type inference, rather than passing explicit type arguments.
// Note the inclusion of arrow functions to ensure that some type parameters are not from
// targetable scopes.
testExtractFunction("extractFunction13",
`<U1a, U1b>(u1a: U1a, u1b: U1b) => {
function F1<T1a, T1b>(t1a: T1a, t1b: T1b) {
<U2a, U2b>(u2a: U2a, u2b: U2b) => {
function F2<T2a, T2b>(t2a: T2a, t2b: T2b) {
<U3a, U3b>(u3a: U3a, u3b: U3b) => {
[#|t1a.toString();
t2a.toString();
u1a.toString();
u2a.toString();
u3a.toString();|]
}
}
}
}
}`);
// This test is descriptive, rather than normative. The current implementation
// doesn't handle type parameter shadowing.
testExtractFunction("extractFunction14",
`function F<T>(t1: T) {
function G<T>(t2: T) {
[#|t1.toString();
t2.toString();|]
}
}`);
// Confirm that the constraint is preserved.
testExtractFunction("extractFunction15",
`function F<T>(t1: T) {
function G<U extends T[]>(t2: U) {
[#|t2.toString();|]
}
}`, /*includeLib*/ true);
// Confirm that the contextual type of an extracted expression counts as a use.
testExtractFunction("extractFunction16",
`function F<T>() {
const array: T[] = [#|[]|];
}`, /*includeLib*/ true);
// Class type parameter
testExtractFunction("extractFunction17",
`class C<T1, T2> {
M(t1: T1, t2: T2) {
[#|t1.toString()|];
}
}`);
// Function type parameter
testExtractFunction("extractFunction18",
`class C {
M<T1, T2>(t1: T1, t2: T2) {
[#|t1.toString()|];
}
}`);
// Coupled constraints
testExtractFunction("extractFunction19",
`function F<T, U extends T[], V extends U[]>(v: V) {
[#|v.toString()|];
}`, /*includeLib*/ true);
testExtractFunction("extractFunction20",
`const _ = class {
a() {
[#|let a1 = { x: 1 };
return a1.x + 10;|]
}
}`);
// Write + void return
testExtractFunction("extractFunction21",
`function foo() {
let x = 10;
[#|x++;
return;|]
}`);
// Return in finally block
testExtractFunction("extractFunction22",
`function test() {
try {
}
finally {
[#|return 1;|]
}
}`);
// Extraction position - namespace
testExtractFunction("extractFunction23",
`namespace NS {
function M1() { }
function M2() {
[#|return 1;|]
}
function M3() { }
}`);
// Extraction position - function
testExtractFunction("extractFunction24",
`function Outer() {
function M1() { }
function M2() {
[#|return 1;|]
}
function M3() { }
}`);
// Extraction position - file
testExtractFunction("extractFunction25",
`function M1() { }
function M2() {
[#|return 1;|]
}
function M3() { }`);
// Extraction position - class without ctor
testExtractFunction("extractFunction26",
`class C {
M1() { }
M2() {
[#|return 1;|]
}
M3() { }
}`);
// Extraction position - class with ctor in middle
testExtractFunction("extractFunction27",
`class C {
M1() { }
M2() {
[#|return 1;|]
}
constructor() { }
M3() { }
}`);
// Extraction position - class with ctor at end
testExtractFunction("extractFunction28",
`class C {
M1() { }
M2() {
[#|return 1;|]
}
M3() { }
constructor() { }
}`);
// Shorthand property names
testExtractFunction("extractFunction29",
`interface UnaryExpression {
kind: "Unary";
operator: string;
operand: any;
}
function parseUnaryExpression(operator: string): UnaryExpression {
[#|return {
kind: "Unary",
operator,
operand: parsePrimaryExpression(),
};|]
}
function parsePrimaryExpression(): any {
throw "Not implemented";
}`);
// Type parameter as declared type
testExtractFunction("extractFunction30",
`function F<T>() {
[#|let t: T;|]
}`);
// Return in nested function
testExtractFunction("extractFunction31",
`namespace N {
export const value = 1;
() => {
var f: () => number;
[#|f = function (): number {
return value;
}|]
}
}`);
// Return in nested class
testExtractFunction("extractFunction32",
`namespace N {
export const value = 1;
() => {
[#|var c = class {
M() {
return value;
}
}|]
}
}`);
// Selection excludes leading trivia of declaration
testExtractFunction("extractFunction33",
`function F() {
[#|function G() { }|]
}`);
testExtractFunction("extractFunction_RepeatedSubstitution",
`namespace X {
export const j = 10;
export const y = [#|j * j|];
}`);
testExtractFunction("extractFunction_VariableDeclaration_Var", `
[#|var x = 1;
"hello"|]
x;
`);
testExtractFunction("extractFunction_VariableDeclaration_Let_Type", `
[#|let x: number = 1;
"hello";|]
x;
`);
testExtractFunction("extractFunction_VariableDeclaration_Let_NoType", `
[#|let x = 1;
"hello";|]
x;
`);
testExtractFunction("extractFunction_VariableDeclaration_Const_Type", `
[#|const x: number = 1;
"hello";|]
x;
`);
testExtractFunction("extractFunction_VariableDeclaration_Const_NoType", `
[#|const x = 1;
"hello";|]
x;
`);
testExtractFunction("extractFunction_VariableDeclaration_Multiple1", `
[#|const x = 1, y: string = "a";|]
x; y;
`);
testExtractFunction("extractFunction_VariableDeclaration_Multiple2", `
[#|const x = 1, y = "a";
const z = 3;|]
x; y; z;
`);
testExtractFunction("extractFunction_VariableDeclaration_Multiple3", `
[#|const x = 1, y: string = "a";
let z = 3;|]
x; y; z;
`);
testExtractFunction("extractFunction_VariableDeclaration_ConsumedTwice", `
[#|const x: number = 1;
"hello";|]
x; x;
`);
testExtractFunction("extractFunction_VariableDeclaration_DeclaredTwice", `
[#|var x = 1;
var x = 2;|]
x;
`);
testExtractFunction("extractFunction_VariableDeclaration_Writes_Var", `
function f() {
let a = 1;
[#|var x = 1;
a++;|]
a; x;
}`);
testExtractFunction("extractFunction_VariableDeclaration_Writes_Let_NoType", `
function f() {
let a = 1;
[#|let x = 1;
a++;|]
a; x;
}`);
testExtractFunction("extractFunction_VariableDeclaration_Writes_Let_Type", `
function f() {
let a = 1;
[#|let x: number = 1;
a++;|]
a; x;
}`);
// We propagate numericLiteralFlags, but it's not consumed by the emitter,
// so everything comes out decimal. It would be nice to improve this.
testExtractFunction("extractFunction_VariableDeclaration_Writes_Let_LiteralType1", `
function f() {
let a = 1;
[#|let x: 0o10 | 10 | 0b10 = 10;
a++;|]
a; x;
}`);
testExtractFunction("extractFunction_VariableDeclaration_Writes_Let_LiteralType2", `
function f() {
let a = 1;
[#|let x: "a" | 'b' = 'a';
a++;|]
a; x;
}`);
// We propagate numericLiteralFlags, but it's not consumed by the emitter,
// so everything comes out decimal. It would be nice to improve this.
testExtractFunction("extractFunction_VariableDeclaration_Writes_Let_LiteralType1", `
function f() {
let a = 1;
[#|let x: 0o10 | 10 | 0b10 = 10;
a++;|]
a; x;
}`);
testExtractFunction("extractFunction_VariableDeclaration_Writes_Let_TypeWithComments", `
function f() {
let a = 1;
[#|let x: /*A*/ "a" /*B*/ | /*C*/ 'b' /*D*/ = 'a';
a++;|]
a; x;
}`);
testExtractFunction("extractFunction_VariableDeclaration_Writes_Const_NoType", `
function f() {
let a = 1;
[#|const x = 1;
a++;|]
a; x;
}`);
testExtractFunction("extractFunction_VariableDeclaration_Writes_Const_Type", `
function f() {
let a = 1;
[#|const x: number = 1;
a++;|]
a; x;
}`);
testExtractFunction("extractFunction_VariableDeclaration_Writes_Mixed1", `
function f() {
let a = 1;
[#|const x = 1;
let y = 2;
a++;|]
a; x; y;
}`);
testExtractFunction("extractFunction_VariableDeclaration_Writes_Mixed2", `
function f() {
let a = 1;
[#|var x = 1;
let y = 2;
a++;|]
a; x; y;
}`);
testExtractFunction("extractFunction_VariableDeclaration_Writes_Mixed3", `
function f() {
let a = 1;
[#|let x: number = 1;
let y = 2;
a++;|]
a; x; y;
}`);
testExtractFunction("extractFunction_VariableDeclaration_Writes_UnionUndefined", `
function f() {
let a = 1;
[#|let x: number | undefined = 1;
let y: undefined | number = 2;
let z: (undefined | number) = 3;
a++;|]
a; x; y; z;
}`);
testExtractFunction("extractFunction_VariableDeclaration_ShorthandProperty", `
function f() {
[#|let x;|]
return { x };
}`);
testExtractFunction("extractFunction_PreserveTrivia", `
// a
var q = /*b*/ //c
/*d*/ [#|1 /*e*/ //f
/*g*/ + /*h*/ //i
/*j*/ 2|] /*k*/ //l
/*m*/; /*n*/ //o`);
testExtractFunction("extractFunction_NamelessClass", `
export default class {
M() {
[#|1 + 1|];
}
}`);
testExtractFunction("extractFunction_NoDeclarations", `
function F() {
[#|arguments.length|]; // arguments has no declaration
}`);
});
function testExtractFunction(caption: string, text: string, includeLib?: boolean) {
testExtractSymbol(caption, text, "extractFunction", Diagnostics.Extract_function, includeLib);
}
} | the_stack |
enum DayOfWeek {
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday
}
Fayde.CoreLibrary.addEnum(DayOfWeek, "DayOfWeek");
enum DateTimeKind {
Unspecified = 0,
Local = 1,
Utc = 2
}
Fayde.CoreLibrary.addEnum(DateTimeKind, "DateTimeKind");
class DateTime {
private static MAX_TICKS = 8640000000000000;
private static MIN_TICKS = -8640000000000000;
static get MinValue() { return new DateTime(DateTime.MIN_TICKS); }
static get MaxValue() { return new DateTime(DateTime.MAX_TICKS); }
static get Now(): DateTime { return new DateTime(new Date().getTime(), DateTimeKind.Local); }
static get Today(): DateTime { return DateTime.Now.Date; }
static Compare(dt1: DateTime, dt2: DateTime): number {
var t1 = dt1._InternalDate.getTime();
var t2 = dt2._InternalDate.getTime();
if (t1 < t2)
return -1;
if (t1 > t2)
return 1;
return 0;
}
static DaysInMonth(year: number, month: number): number {
var ticks = new Date(year, (month - 1) + 1, 1).getTime() - TimeSpan._TicksPerDay;
var dt = new DateTime(ticks);
return dt.Day;
}
private _InternalDate: Date = null;
private _Kind: DateTimeKind;
constructor();
constructor(dt: Date);
constructor(dt: Date, kind: DateTimeKind);
constructor(ticks: number);
constructor(ticks: number, kind: DateTimeKind);
constructor(year: number, month: number, day: number);
constructor(year: number, month: number, day: number, hour: number, minute: number, second: number);
constructor(year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number);
constructor(year: number, month: number, day: number, hour: number, minute: number, second: number, millisecond: number, kind: DateTimeKind);
constructor(...args: any[]) {
var ticks: number = null;
var kind = DateTimeKind.Unspecified;
var year = 0;
var month = 0;
var day = 0;
var hour = 0;
var minute = 0;
var second = 0;
var millisecond = 0;
if (args.length === 1) { //Ticks
var arg0 = args[0];
if (arg0 instanceof Date) {
ticks = arg0.getTime();
} else {
ticks = args[0];
}
} else if (args.length === 2) { //Ticks,Kind
var arg0 = args[0];
if (arg0 instanceof Date) {
ticks = arg0.getTime();
} else {
ticks = args[0];
}
kind = args[1];
} else if (args.length === 3) { //Year,Month,Day
year = args[0];
month = args[1];
day = args[2];
} else if (args.length === 6) { //Year,Month,Day,Hour,Minute,Second
year = args[0];
month = args[1];
day = args[2];
hour = args[3];
minute = args[4];
second = args[5];
} else if (args.length === 7) { //Year,Month,Day,Hour,Minute,Second,Millisecond
year = args[0];
month = args[1];
day = args[2];
hour = args[3];
minute = args[4];
second = args[5];
millisecond = args[6];
} else if (args.length === 8) { //Year,Month,Day,Hour,Minute,Second,Millisecond,DateTimeKind
year = args[0];
month = args[1];
day = args[2];
hour = args[3];
minute = args[4];
second = args[5];
millisecond = args[6];
kind = args[7];
} else {
ticks = 0;
}
this._Kind = kind || DateTimeKind.Unspecified;
if (isNaN(ticks) || ticks < DateTime.MIN_TICKS || ticks > DateTime.MAX_TICKS) {
throw new Error("DateTime is out of range.");
}
if (ticks != null) {
this._InternalDate = new Date(ticks);
return;
}
var id = this._InternalDate = new Date();
if (this._Kind === DateTimeKind.Utc) {
id.setUTCFullYear(year, month - 1, day);
id.setUTCHours(hour);
id.setUTCMinutes(minute);
id.setUTCSeconds(second);
id.setMilliseconds(millisecond);
} else {
id.setFullYear(year, month - 1, day);
id.setHours(hour);
id.setMinutes(minute);
id.setSeconds(second);
id.setMilliseconds(millisecond);
}
}
get Ticks(): number { return this._InternalDate.getTime(); }
get Kind(): DateTimeKind { return this._Kind; }
get Date(): DateTime {
var t = this._InternalDate.getTime();
var newid = new Date(t);
if (this._Kind === DateTimeKind.Utc) {
newid.setUTCHours(0);
newid.setUTCMinutes(0);
newid.setUTCSeconds(0);
newid.setUTCMilliseconds(0);
} else {
newid.setHours(0);
newid.setMinutes(0);
newid.setSeconds(0);
newid.setMilliseconds(0);
}
return new DateTime(newid.getTime(), this._Kind);
}
get Day(): number {
if (this._Kind === DateTimeKind.Utc)
return this._InternalDate.getUTCDate();
return this._InternalDate.getDate();
}
get DayOfWeek(): DayOfWeek {
if (this._Kind === DateTimeKind.Utc)
return <DayOfWeek>this._InternalDate.getUTCDay();
return <DayOfWeek>this._InternalDate.getDay();
}
get DayOfYear(): number {
var dt = this.Date;
var base = new DateTime(dt.Year, 1, 1, 0, 0, 0, 0, this.Kind);
var diff = new TimeSpan(dt.Ticks - base.Ticks);
return Math.floor(diff.TotalDays);
}
get Hour(): number {
if (this._Kind === DateTimeKind.Utc)
return this._InternalDate.getUTCHours();
return this._InternalDate.getHours();
}
get Millisecond(): number {
if (this._Kind === DateTimeKind.Utc)
return this._InternalDate.getUTCMilliseconds();
return this._InternalDate.getMilliseconds();
}
get Minute(): number {
if (this._Kind === DateTimeKind.Utc)
return this._InternalDate.getUTCMinutes();
return this._InternalDate.getMinutes();
}
get Month(): number {
if (this._Kind === DateTimeKind.Utc)
return this._InternalDate.getUTCMonth() + 1;
return this._InternalDate.getMonth() + 1;
}
get Second(): number {
if (this._Kind === DateTimeKind.Utc)
return this._InternalDate.getUTCSeconds();
return this._InternalDate.getSeconds();
}
get TimeOfDay(): TimeSpan {
var id = this._InternalDate;
if (this._Kind === DateTimeKind.Utc)
return new TimeSpan(0, id.getUTCHours(), id.getUTCMinutes(), id.getUTCSeconds(), id.getUTCMilliseconds());
return new TimeSpan(0, id.getHours(), id.getMinutes(), id.getSeconds(), id.getMilliseconds());
}
get Year(): number {
if (this._Kind === DateTimeKind.Utc)
return this._InternalDate.getUTCFullYear();
return this._InternalDate.getFullYear();
}
AddYears(years: number): DateTime {
var newid = new Date(this._InternalDate.getTime());
var wyears = Math.floor(years);
if (isNaN(wyears)) {
throw new ArgumentOutOfRangeException("years");
}
if (this.Kind === DateTimeKind.Utc) {
newid.setUTCFullYear(newid.getUTCFullYear() + wyears);
} else {
newid.setFullYear(newid.getFullYear() + wyears);
}
return new DateTime(newid, this.Kind);
}
AddMonths(months: number): DateTime {
var newid = new Date(this._InternalDate.getTime());
var wmonths = Math.floor(months);
if (isNaN(wmonths)) {
throw new ArgumentOutOfRangeException("months");
}
if (this.Kind === DateTimeKind.Utc) {
newid.setUTCMonth(newid.getUTCMonth() + wmonths);
} else {
newid.setMonth(newid.getMonth() + wmonths);
}
return new DateTime(newid, this.Kind);
}
AddDays(value: number): DateTime {
return this.Add(TimeSpan.FromDays(value));
}
AddHours(value: number): DateTime {
return this.Add(TimeSpan.FromHours(value));
}
AddMinutes(value: number): DateTime {
return this.Add(TimeSpan.FromMinutes(value));
}
AddSeconds(value: number): DateTime {
return this.Add(TimeSpan.FromSeconds(value));
}
AddMilliseconds(value: number): DateTime {
return this.Add(TimeSpan.FromMilliseconds(value));
}
Add(value: TimeSpan): DateTime {
var newid = new Date(this._InternalDate.getTime());
if (this.Kind === DateTimeKind.Utc) {
newid.setUTCDate(newid.getUTCDate() + value.Days);
newid.setUTCHours(newid.getUTCHours() + value.Hours);
newid.setUTCMinutes(newid.getUTCMinutes() + value.Minutes);
newid.setUTCSeconds(newid.getUTCSeconds() + value.Seconds);
newid.setUTCMilliseconds(newid.getUTCMilliseconds() + value.Milliseconds);
} else {
newid.setDate(newid.getDate() + value.Days);
newid.setHours(newid.getHours() + value.Hours);
newid.setMinutes(newid.getMinutes() + value.Minutes);
newid.setSeconds(newid.getSeconds() + value.Seconds);
newid.setMilliseconds(newid.getMilliseconds() + value.Milliseconds);
}
return new DateTime(newid, this.Kind);
}
AddTicks(value: number): DateTime {
return new DateTime(this.Ticks + value, this.Kind);
}
Subtract(value: DateTime): TimeSpan;
Subtract(value: TimeSpan): DateTime;
Subtract(value: any): any {
if (value instanceof DateTime) {
return new TimeSpan(this.Ticks - value.Ticks);
} else if (value instanceof TimeSpan) {
return new DateTime(this.Ticks - value.Ticks, this.Kind);
}
return new DateTime(this.Ticks, this.Kind);
}
ToUniversalTime(): DateTime {
if (this.Kind === DateTimeKind.Utc)
return new DateTime(this.Ticks, DateTimeKind.Utc);
var id = this._InternalDate;
return new DateTime(id.getUTCFullYear(), id.getUTCMonth() + 1, id.getUTCDate(), id.getUTCHours(), id.getUTCMinutes(), id.getUTCSeconds(), id.getUTCMilliseconds(), DateTimeKind.Utc);
}
toString(format?: string): string {
if (!format)
return Fayde.Localization.FormatSingle(this, "s");
return Fayde.Localization.FormatSingle(this, format);
}
valueOf(): Object {
return this.Ticks;
}
}
Fayde.CoreLibrary.addPrimitive(DateTime);
nullstone.registerTypeConverter(DateTime, (value: any): any => {
if (value instanceof DateTime)
return value;
if (value instanceof Date)
return new DateTime(value);
if (typeof value === "string")
return new DateTime(Date.parse(value));
if (typeof value === "number")
return new DateTime(value);
throw new Exception("Cannot parse DateTime value '" + value + "'");
}); | the_stack |
import { DateTime, DateTimeFormatOptions, Duration, DurationObjectUnits, Settings } from 'luxon';
import { Dic } from './Globals';
import type { ModifiableEntity, Entity, Lite, MListElement, ModelState, MixinEntity } from './Signum.Entities'; //ONLY TYPES or Cyclic problems in Webpack!
import { ajaxGet } from './Services';
import { MList } from "./Signum.Entities";
import * as AppContext from './AppContext';
import { QueryString } from './QueryString';
export function getEnumInfo(enumTypeName: string, enumId: number): MemberInfo {
const ti = tryGetTypeInfo(enumTypeName);
if (!ti || ti.kind != "Enum")
throw new Error(`${enumTypeName} is not an Enum`);
return ti.membersById![enumId];
}
export interface TypeInfo {
kind: KindOfType;
name: string;
fullName: string;
niceName?: string;
nicePluralName?: string;
gender?: string;
entityKind?: EntityKind;
entityData?: EntityData;
toStringFunction?: string;
isLowPopulation?: boolean;
isSystemVersioned?: boolean;
requiresSaveOperation?: boolean;
queryDefined?: boolean;
requiresEntityPack?: boolean;
members: { [name: string]: MemberInfo };
membersById?: { [name: string]: MemberInfo };
hasConstructorOperation?: boolean;
operations?: { [name: string]: OperationInfo };
}
export interface MemberInfo {
name: string,
niceName: string;
type: TypeReference;
isReadOnly?: boolean;
isIgnoredEnum?: boolean;
unit?: string;
format?: string;
required?: boolean;
maxLength?: number;
isMultiline?: boolean;
isVirtualMList?: boolean;
preserveOrder?: boolean;
notVisible?: boolean;
id?: any; //symbols
}
export interface OperationInfo {
key: string,
niceName: string;
operationType: OperationType;
canBeNew?: boolean;
canBeModified?: boolean;
hasCanExecute?: boolean;
hasStates?: boolean;
}
export type OperationType =
"Execute" |
"Delete" |
"Constructor" |
"ConstructorFrom" |
"ConstructorFromMany";
//https://moment.github.io/luxon/docs/manual/formatting.html#formatting-with-tokens--strings-for-cthulhu-
//https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings
export function toLuxonFormat(netFormat: string | undefined, type: "DateOnly" | "DateTime"): string {
if (!netFormat)
return type == "DateOnly" ? "D" : "F";
switch (netFormat) {
case "d": return "D"; // toFormatWithFixes
case "D": return "DDDD";
case "f": return "fff"
case "F": return "FFF";
case "g": return "f";
case "G": return "F";
case "M":
case "m": return "dd LLLL";
case "u": return "yyyy-MM-dd'T'HH:mm:ss";
case "s": return "yyyy-MM-dd'T'HH:mm:ss";
case "o": return "yyyy-MM-dd'T'HH:mm:ss.u";
case "t": return "t";
case "T": return "tt";
case "y": return "LLLL yyyy";
case "Y": return "LLLL yyyy";
default: {
const result = netFormat
.replaceAll("f", "S")
.replaceAll("tt", "A")
.replaceAll("t", "a")
.replaceAll("YYYY", "yyyy")
.replaceAll("YY", "yy")
.replaceAll("dddd", "cccc")
.replaceAll("ddd", "ccc")
.replaceAll("ddd", "ccc")
.replaceAll("T", "'T'");
return result;
}
}
}
const oneDigitCulture = new Set([
"agq", "agq-CM",
"ar-001", "ar-DJ", "ar-ER", "ar-IL", "ar-KM", "ar-MR", "ar-PS", "ar-SD", "ar-SO", "ar-SS", "ar-TD",
"ast", "ast-ES",
"bas", "bas-CM",
"bg", "bg-BG",
"bin", "bin-NG",
"bm", "bm-Latn", "bm-Latn-ML",
"bn", "bn-BD",
"bo", "bo-CN",
"brx", "brx-IN",
"bs", "bs-Cyrl", "bs-Cyrl-BA", "bs-Latn", "bs-Latn-BA",
"ca", "ca-AD", "ca-ES", "ca-ES-valencia", "ca-FR", "ca-IT",
"ccp", "ccp-Cakm", "ccp-Cakm-BD", "ccp-Cakm-IN",
"ceb", "ceb-Latn", "ceb-Latn-PH",
"chr", "chr-Cher", "chr-Cher-US",
"dje", "dje-NE",
"dsb", "dsb-DE",
"dua", "dua-CM",
"dyo", "dyo-SN",
"ee", "ee-GH", "ee-TG",
"el", "el-CY", "el-GR",
"en", "en-AS", "en-AU", "en-BI", "en-GU", "en-HK", "en-JM", "en-MH", "en-MP", "en-MY", "en-NZ", "en-PR", "en-SG", "en-UM", "en-US", "en-VI", "en-ZW",
"es-419", "es-AR", "es-BO", "es-BR", "es-BZ", "es-CO", "es-CR", "es-CU", "es-DO", "es-EC", "es-GQ", "es-GT", "es-HN", "es-NI", "es-PE", "es-PH", "es-PY", "es-SV", "es-US", "es-UY", "es-VE",
"eu", "eu-ES",
"ewo", "ewo-CM",
"ff-Latn-BF", "ff-Latn-CM", "ff-Latn-GH", "ff-Latn-GM", "ff-Latn-GN", "ff-Latn-GW", "ff-Latn-LR", "ff-Latn-MR", "ff-Latn-NE", "ff-Latn-NG", "ff-Latn-SL",
"fi", "fi-FI",
"fil", "fil-PH",
"ha", "ha-Latn", "ha-Latn-GH", "ha-Latn-NE", "ha-Latn-NG",
"haw", "haw-US",
"hr", "hr-BA", "hr-HR",
"hsb", "hsb-DE",
"ibb", "ibb-NG",
"ig", "ig-NG",
"ii", "ii-CN",
"is", "is-IS",
"iu", "iu-Cans", "iu-Cans-CA", "iu-Latn", "iu-Latn-CA",
"kab", "kab-DZ",
"kea", "kea-CV",
"khq", "khq-ML",
"ko-KP",
"kr", "kr-Latn", "kr-Latn-NG",
"ks", "ks-Arab", "ks-Arab-IN",
"ksf", "ksf-CM",
"ksh", "ksh-DE",
"ky", "ky-KG",
"lkt", "lkt-US",
"ln", "ln-AO", "ln-CD", "ln-CF", "ln-CG",
"lo", "lo-LA",
"lu", "lu-CD",
"mfe", "mfe-MU",
"ml", "ml-IN",
"mn-Mong", "mn-Mong-CN", "mn-Mong-MN",
"moh", "moh-CA",
"ms", "ms-BN", "ms-MY", "ms-SG",
"mua", "mua-CM",
"nds", "nds-DE", "nds-NL",
"ne", "ne-IN", "ne-NP",
"nl", "nl-BE", "nl-NL",
"nmg", "nmg-CM",
"nus", "nus-SS",
"pap", "pap-029",
"prs", "prs-AF",
"ps", "ps-AF", "ps-PK",
"rn", "rn-BI",
"se-FI",
"seh", "seh-MZ",
"ses", "ses-ML",
"sg", "sg-CF",
"shi", "shi-Latn", "shi-Latn-MA", "shi-Tfng", "shi-Tfng-MA",
"sk", "sk-SK",
"sl", "sl-SI",
"smn", "smn-FI",
"sms", "sms-FI",
"sq", "sq-AL", "sq-MK", "sq-XK",
"sr", "sr-Cyrl-BA", "sr-Cyrl-ME", "sr-Cyrl-XK", "sr-Latn", "sr-Latn-BA", "sr-Latn-ME", "sr-Latn-RS", "sr-Latn-XK",
"ta-LK", "ta-MY", "ta-SG",
"th", "th-TH",
"to", "to-TO",
"tr", "tr-CY", "tr-TR",
"twq", "twq-NE",
"tzm-Arab", "tzm-Arab-MA",
"ug", "ug-CN",
"ur-IN",
"yav", "yav-CM",
"yo", "yo-BJ", "yo-NG",
"zgh", "zgh-Tfng", "zgh-Tfng-MA",
"zh", "zh-CN", "zh-Hans", "zh-Hans-HK", "zh-Hans-MO", "zh-Hant", "zh-HK", "zh-MO", "zh-SG", "zh-TW",
"zu", "zu-ZA"
]);
export function toFormatWithFixes(dt: DateTime, format: string, options ?: Intl.DateTimeFormatOptions){
if (!oneDigitCulture.has(dt.locale)) {
if (format == "D")
return dt.toLocaleString({ year: "numeric", month: "2-digit", day: "2-digit", ...options });
if (format == "f")
return dt.toLocaleString({ year: "numeric", month: "2-digit", day: "2-digit", hour: "numeric", minute: "numeric", ...options });
if (format == "F")
return dt.toLocaleString({ year: "numeric", month: "2-digit", day: "2-digit", hour: "numeric", minute: "numeric", second: "numeric", ...options });
}
if (format == "EE") //missing
return dt.toFormat("EEE", options).substr(0, 2);
return dt.toFormat(format, options)
}
//https://msdn.microsoft.com/en-us/library/ee372286(v=vs.110).aspx
//https://github.com/jsmreese/moment-duration-format
export function toLuxonDurationFormat(netFormat: string | undefined): string | undefined {
if (netFormat == undefined)
return undefined;
return netFormat.replaceAll("\\:", ":").replaceAll("H", "h");
}
export namespace NumberFormatSettings {
export let defaultNumberFormatLocale: string = null!;
}
//https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings
export function toNumberFormat(format: string | undefined, locale?: string): Intl.NumberFormat {
let loc = locale ?? NumberFormatSettings.defaultNumberFormatLocale;
if (loc.startsWith("es-")) {
loc = "de-DE"; //fix problem for Intl formatting "es" numbers for 4 digits over decimal point
}
return new Intl.NumberFormat(loc, toNumberFormatOptions(format));
}
export function toNumberFormatOptions(format: string | undefined): Intl.NumberFormatOptions | undefined {
if (format == undefined)
return undefined;
const f = format.toUpperCase();
if (f.startsWith("C")) //unit comes separated
return {
style: "decimal",
minimumFractionDigits: parseInt(f.after("C")) || 2,
maximumFractionDigits: parseInt(f.after("C")) || 2,
useGrouping: true,
}
if (f.startsWith("N"))
return {
style: "decimal",
minimumFractionDigits: parseInt(f.after("N")) || 2,
maximumFractionDigits: parseInt(f.after("N")) || 2,
useGrouping: true,
}
if (f.startsWith("D"))
return {
style: "decimal",
maximumFractionDigits: 0,
minimumIntegerDigits: parseInt(f.after("D")) || 1,
useGrouping: false,
}
if (f.startsWith("F"))
return {
style: "decimal",
minimumFractionDigits: parseInt(f.after("F")) || 2,
maximumFractionDigits: parseInt(f.after("F")) || 2,
useGrouping: false,
}
if (f.startsWith("E"))
return {
style: "decimal",
notation: "scientific",
minimumFractionDigits: parseInt(f.after("E")) || 6,
maximumFractionDigits: parseInt(f.after("E")) || 6,
useGrouping: false,
} as any;
if (f.startsWith("P"))
return {
style: "percent",
minimumFractionDigits: parseInt(f.after("P")) || 2,
maximumFractionDigits: parseInt(f.after("P")) || 2,
useGrouping: false,
}
//simple heuristic
var style = f.endsWith("%") ? "percent" : "decimal";
var afterDot = (f.tryBefore("%") ?? f).tryAfter(".") ?? "";
const result: Intl.NumberFormatOptions = {
style: style,
minimumFractionDigits: afterDot.replaceAll("#", "").length,
maximumFractionDigits: afterDot.length,
useGrouping: f.contains(","),
};
if (f.startsWith("+"))
(result as any).signDisplay = "always";
return result;
}
export function valToString(val: any) {
if (val == null)
return "";
return val.toString();
}
export function numberToString(val: any, format?: string) {
if (val == null)
return "";
return toNumberFormat(format).format(val);
}
export function dateToString(val: any, type: "DateOnly" | "DateTime", netFormat?: string) {
if (val == null)
return "";
var m = DateTime.fromISO(val);
return m.toFormat(toLuxonFormat(netFormat, type));
}
export function timeToString(val: any, netFormat?: string) {
if (val == null)
return "";
var duration = Duration.fromISOTime(val);
return duration.toFormat(toLuxonDurationFormat(netFormat) ?? "hh:mm:ss");
}
export interface TypeReference {
name: string;
typeNiceName?: string;
isCollection?: boolean;
isLite?: boolean;
isNotNullable?: boolean;
isEmbedded?: boolean;
}
export type KindOfType = "Entity" | "Enum" | "Message" | "Query" | "SymbolContainer";
export type EntityKind = "SystemString" | "System" | "Relational" | "String" | "Shared" | "Main" | "Part" | "SharedPart";
export const EntityKindValues: EntityKind[] = ["SystemString", "System", "Relational", "String", "Shared", "Main", "Part", "SharedPart"];
export type EntityData = "Master" | "Transactional";
export const EntityDataValues: EntityData[] = ["Master", "Transactional"];
export function getAllTypes(): TypeInfo[] {
return Dic.getValues(_types);
}
export interface TypeInfoDictionary {
[name: string]: TypeInfo
}
let _types: TypeInfoDictionary = {};
let _queryNames: {
[queryKey: string]: MemberInfo
};
export type PseudoType = IType | TypeInfo | string;
export function getTypeName(pseudoType: IType | TypeInfo | string | Lite<Entity> | ModifiableEntity): string {
if ((pseudoType as Lite<Entity>).EntityType)
return (pseudoType as Lite<Entity>).EntityType;
if ((pseudoType as ModifiableEntity).Type)
return (pseudoType as ModifiableEntity).Type;
if ((pseudoType as IType).typeName)
return (pseudoType as IType).typeName;
if ((pseudoType as TypeInfo).name)
return (pseudoType as TypeInfo).name;
if (typeof pseudoType == "string")
return pseudoType as string;
throw new Error("Unexpected pseudoType " + pseudoType);
}
export function isTypeEntity(type: PseudoType): boolean {
const ti = tryGetTypeInfo(type);
return ti != null && ti.kind == "Entity" && !!ti.members["Id"];
}
export function isTypeEnum(type: PseudoType): boolean {
const ti = tryGetTypeInfo(type);
return ti != null && ti.kind == "Enum";
}
export function isTypeModel(type: PseudoType): boolean {
const ti = tryGetTypeInfo(type);
return ti != null && ti.kind == "Entity" && !ti.members["Id"];
}
export function isTypeModifiableEntity(type: TypeReference): boolean {
return type.isEmbedded == true || tryGetTypeInfos(type).every(ti => ti != undefined && (isTypeEntity(ti) || isTypeModel(ti)));
}
export function getTypeInfo(type: PseudoType): TypeInfo {
const typeName = getTypeName(type);
const ti = _types[typeName.toLowerCase()];
if (ti == null)
throw new Error(`Type not found: ${typeName}`);
return ti;
}
export function tryGetTypeInfo(type: PseudoType): TypeInfo | undefined {
const typeName = getTypeName(type);
if (typeName == null)
throw new Error("Unexpected type: " + type);
const ti: TypeInfo | undefined = _types[typeName.toLowerCase()];
return ti;
}
export function isLowPopulationSymbol(type: PseudoType) {
var ti = tryGetTypeInfo(type);
return ti != null && ti.kind == "Entity" && ti.fullName.endsWith("Symbol") && ti.isLowPopulation;
}
export function parseId(ti: TypeInfo, id: string): string | number {
return ti.members["Id"].type.name == "number" ? parseInt(id) : id;
}
export const IsByAll = "[ALL]";
export function getTypeInfos(typeReference: TypeReference | string): TypeInfo[] {
const name = typeof typeReference == "string" ? typeReference : typeReference.name;
if (name == IsByAll || name == "")
return [];
return name.split(", ").map(getTypeInfo);
}
export function tryGetTypeInfos(typeReference: TypeReference | string): (TypeInfo | undefined)[] {
const name = typeof typeReference == "string" ? typeReference : typeReference.name;
if (name == IsByAll || name == "")
return [];
return name.split(", ").map(tryGetTypeInfo);
}
export function getQueryNiceName(queryName: PseudoType | QueryKey): string {
if ((queryName as TypeInfo).kind != undefined)
return (queryName as TypeInfo).nicePluralName!;
if (queryName instanceof Type)
return (queryName as Type<any>).nicePluralName();
if (queryName instanceof QueryKey)
return (queryName as QueryKey).niceName();
if (typeof queryName == "string") {
const str = queryName as string;
const type = _types[str.toLowerCase()];
if (type)
return type.nicePluralName!;
const qn = _queryNames[str.toLowerCase()];
if (qn)
return qn.niceName;
return str;
}
throw new Error("unexpected queryName type");
}
export function getQueryInfo(queryName: PseudoType | QueryKey): MemberInfo | TypeInfo {
if (queryName instanceof QueryKey) {
return queryName.memberInfo();
}
else {
const ti = tryGetTypeInfo(queryName);
if (ti)
return ti;
const mi = _queryNames[(queryName as string).toLowerCase()];
if (mi)
return mi;
throw Error("Unexpected query type");
}
}
export function getQueryKey(queryName: PseudoType | QueryKey): string {
if ((queryName as TypeInfo).kind != undefined)
return (queryName as TypeInfo).name;
if (queryName instanceof Type)
return (queryName as Type<any>).typeName;
if (queryName instanceof QueryKey)
return (queryName as QueryKey).name;
if (typeof queryName == "string") {
const str = queryName as string;
const type = _types[str.toLowerCase()];
if (type)
return type.name;
const qn = _queryNames[str.toLowerCase()];
if (qn)
return qn.name;
return str;
}
throw Error("Unexpected query type");
}
export function isQueryDefined(queryName: PseudoType | QueryKey): boolean {
if ((queryName as TypeInfo).kind != undefined)
return (queryName as TypeInfo).queryDefined || false;
if (queryName instanceof Type) {
var ti = tryGetTypeInfo(queryName)
return ti && ti.queryDefined || false;
}
if (queryName instanceof QueryKey)
return !!_queryNames[queryName.name.toLowerCase()];
if (typeof queryName == "string") {
const str = queryName as string;
const type = _types[str.toLowerCase()];
if (type) {
return type.queryDefined || false;
}
const qn = _queryNames[str.toLowerCase()];
return !!qn;
}
return false;
}
export function reloadTypes(): Promise<void> {
return ajaxGet<TypeInfoDictionary>({
url: "~/api/reflection/types?" + QueryString.stringify({
user: AppContext.currentUser?.id,
userTicks: AppContext.currentUser?.ticks,
culture: AppContext.currentCulture
})
})
.then(types => {
setTypes(types);
onReloadTypes();
});
}
export const onReloadTypesActions: Array<() => void> = [];
export function onReloadTypes() {
onReloadTypesActions.forEach(a => a());
}
export function setTypes(types: TypeInfoDictionary) {
Dic.foreach(types, (k, t) => {
t.name = k;
if (t.members) {
Dic.foreach(t.members, (k2, t2) => t2.name = k2);
Object.freeze(t.members);
if (t.kind == "Enum") {
t.membersById = Dic.getValues(t.members).toObject(a => a.name);
Object.freeze(t.membersById);
}
}
if (t.requiresSaveOperation == undefined && t.entityKind)
t.requiresSaveOperation = calculateRequiresSaveOperation(t.entityKind);
Object.freeze(t);
});
_types = Dic.getValues(types).toObject(a => a.name.toLowerCase());
Object.freeze(_types);
Dic.foreach(types, (k, t) => {
if (t.operations) {
Dic.foreach(t.operations, (k2, t2) => {
t2.key = k2;
const typeName = k2.before(".").toLowerCase();
const memberName = k2.after(".");
const ti = _types[typeName];
if (!ti)
console.error(`Type ${typeName} not found (looking for operatons of ${t.name}). Consider synchronizing of calling ReflectionServer.RegisterLike.`);
else {
const member = ti.members[k2.after(".")];
if (!member)
console.error(`Member ${memberName} not found in ${ti.name} (looking for operatons of ${t.name}). Consider synchronizing of calling ReflectionServer.RegisterLike.`);
else
t2.niceName = member.niceName;
}
});
Object.freeze(t.operations);
}
});
_queryNames = Dic.getValues(types).filter(t => t.kind == "Query")
.flatMap(a => Dic.getValues(a.members))
.toObject(m => m.name.toLocaleLowerCase(), m => m);
Object.freeze(_queryNames);
missingSymbols = missingSymbols.filter(s => {
const m = getMember(s.key);
if (m)
s.id = m.id;
return s.id == null;
});
}
function calculateRequiresSaveOperation(entityKind: EntityKind): boolean {
switch (entityKind) {
case "SystemString": return false;
case "System": return false;
case "Relational": return false;
case "String": return true;
case "Shared": return true;
case "Main": return true;
case "Part": return false;
case "SharedPart": return false;
default: throw new Error("Unexpeced entityKind");
}
}
export interface IBinding<T> {
getValue(): T;
setValue(val: T): void;
suffix: string;
getIsReadonly(): boolean;
getError(): string | undefined;
setError(value: string | undefined): void;
}
export class Binding<T> implements IBinding<T> {
initialValue: T; // For deep compare
suffix: string;
constructor(
public parentObject: any,
public member: string | number,
suffix?: string) {
this.initialValue = this.parentObject[member];
this.suffix = suffix || ("." + member);
}
static create<F, T>(parentValue: F, fieldAccessor: (from: F) => T) {
const memberName = Binding.getSingleMember(fieldAccessor);
return new Binding<T>(parentValue, memberName, "." + memberName);
}
static getSingleMember(fieldAccessor: (from: any) => any) {
const members = getLambdaMembers(fieldAccessor);
if (members.length != 1 || members[0].type != "Member")
throw Error("invalid function 'fieldAccessor'");
return members[0].name;
}
getValue(): T {
if (!this.parentObject)
throw new Error(`Impossible to get '${this.member}' from '${this.parentObject}'`);
return this.parentObject[this.member];
}
setValue(val: T) {
if (!this.parentObject)
throw new Error(`Impossible to set '${this.member}' from '${this.parentObject}'`);
const oldVal = this.parentObject[this.member];
this.parentObject[this.member] = val;
if ((this.parentObject as ModifiableEntity).Type) {
if (oldVal !== val && !sameEntity(oldVal, val) || Array.isArray(oldVal)) {
(this.parentObject as ModifiableEntity).modified = true;
}
}
}
deleteValue() {
if (!this.parentObject)
throw new Error(`Impossible to delete '${this.member}' from '${this.parentObject}'`);
delete this.parentObject[this.member];
}
forceError: string | undefined;
getError(): string | undefined {
if (this.forceError)
return this.forceError;
const parentErrors = (this.parentObject as ModifiableEntity).error;
return parentErrors && parentErrors[this.member];
}
getIsReadonly(): boolean {
const readonlyProperties = (this.parentObject as ModifiableEntity).readonlyProperties;
return readonlyProperties != null && readonlyProperties.contains(this.member as string);
}
setError(value: string | undefined) {
const parent = this.parentObject as ModifiableEntity;
if (!value) {
if (parent.error)
delete parent.error[this.member];
} else {
if (!parent.Type)
return;
if (!parent.error)
parent.error = {};
parent.error[this.member] = value;
}
}
}
export class ReadonlyBinding<T> implements IBinding<T> {
constructor(
public value: T,
public suffix: string) {
}
getValue() {
return this.value;
}
setValue(val: T) {
throw new Error("Readonly Binding");
}
getIsReadonly() {
return true;
}
getError(): string | undefined {
return undefined;
}
setError(value: string | undefined): void {
}
}
export class MListElementBinding<T> implements IBinding<T>{
suffix: string;
constructor(
public mListBinding: IBinding<MList<T>>,
public index: number) {
this.suffix = "[" + this.index.toString() + "].element";
}
getValue() {
var mlist = this.mListBinding.getValue();
if (mlist.length <= this.index) //Some animations?
return undefined as any as T;
return mlist[this.index].element;
}
getMListElement(): MListElement<T> {
var mlist = this.mListBinding.getValue();
return mlist[this.index];
}
setValue(val: T) {
var mlist = this.mListBinding.getValue()
const mle = mlist[this.index];
mle.rowId = null;
mle.element = val;
this.mListBinding.setValue(mlist);
}
getIsReadonly() {
return false; //Not sure
}
getError(): string | undefined {
return undefined;
}
setError(value: string | undefined): void {
}
}
export function createBinding(parentValue: any, lambdaMembers: LambdaMember[]): IBinding<any> {
if (lambdaMembers.length == 0)
return new ReadonlyBinding<any>(parentValue, "");
var suffix = "";
let val = parentValue;
var lastIsIndex = lambdaMembers[lambdaMembers.length - 1].type == "Indexer";
for (let i = 0; i < lambdaMembers.length - (lastIsIndex ? 2 : 1); i++) {
const member = lambdaMembers[i];
switch (member.type) {
case "Member":
val = val[member.name];
suffix += "." + member.name;
break;
case "Mixin":
val = val.mixins[member.name];
suffix += ".mixins[" + member.name + "]";
break;
case "Indexer":
val = val[parseInt(member.name)];
suffix += "[" + member.name + "].element";
break;
default: throw new Error("Unexpected " + member.type);
}
}
const lastMember = lambdaMembers[lambdaMembers.length - 1];
switch (lastMember.type) {
case "Member": return new Binding(val, lastMember.name, suffix + "." + lastMember.name);
case "Mixin": return new ReadonlyBinding(val.mixins[lastMember.name], suffix + ".mixins[" + lastMember.name + "]");
case "Indexer":
const preLastMember = lambdaMembers[lambdaMembers.length - 2];
var binding = new Binding<MList<any>>(val, preLastMember.name, suffix + "." + preLastMember.name)
return new MListElementBinding(binding, parseInt(lastMember.name));
default: throw new Error("Unexpected " + lastMember.type);
}
}
const functionRegex = /^function\s*\(\s*(?<param>[$a-zA-Z_][0-9a-zA-Z_$]*)\s*\)\s*{\s*(\"use strict\"\;)?\s*(var [^;]*;)?\s*return\s*(?<body>[^;]*)\s*;?\s*}$/;
const lambdaRegex = /^\s*\(?\s*(?<param>[$a-zA-Z_][0-9a-zA-Z_$]*)\s*\)?\s*=>\s*(({\s*(\"use strict\"\;)?\s*(var [^;]*;)?\s*return\s*(?<body>[^;]*)\s*;?\s*})|(?<body2>[^;]*))\s*$/;
const memberRegex = /^(.*)\.([$a-zA-Z_][0-9a-zA-Z_$]*)$/;
const memberIndexerRegex = /^(.*)\["([$a-zA-Z_][0-9a-zA-Z_$]*)"\]$/;
const mixinMemberRegex = /^(.*)\.mixins\["([$a-zA-Z_][0-9a-zA-Z_$]*)"\]$/; //Necessary for some crazy minimizers
const getMixinRegexOld = /^Object\([^[]+\["getMixin"\]\)\((.+),[^[]+\["([$a-zA-Z_][0-9a-zA-Z_$]*)"\]\)$/;
const getMixinRegex = /^\(0,[^.]+\.getMixin\)\((.+),[^.]+\.([$a-zA-Z_][0-9a-zA-Z_$]*)\)$/;
const indexRegex = /^(.*)\[(\d+)\]$/;
const fixNullPropagator = /^\(([_\w]+)\s*=\s(.*?)\s*\)\s*===\s*null\s*\|\|\s*\1\s*===\s*void 0\s*\?\s*void 0\s*:\s*\1$/;
const fixNullPropagatorProd = /^\s*null\s*===\(([_\w]+)\s*=\s*(.*?)\s*\)\s*\|\|\s*void 0\s*===\s*\1\s*\?\s*void 0\s*:\s*\1$/;
export function getLambdaMembers(lambda: Function): LambdaMember[] {
var lambdaStr = (lambda as any).toString();
const lambdaMatch = functionRegex.exec(lambdaStr) || lambdaRegex.exec(lambdaStr);
if (lambdaMatch == undefined)
throw Error("invalid function");
const parameter = lambdaMatch.groups!.param;
let body = lambdaMatch.groups!.body ?? lambdaMatch.groups!.body2;
let result: LambdaMember[] = [];
while (body != parameter) {
let m: RegExpExecArray | null;
if (m = mixinMemberRegex.exec(body)) {
result.push({ name: m[2], type: "Mixin" });
body = m[1];
}
else if (m = getMixinRegex.exec(body) ?? getMixinRegexOld.exec(body)) {
result.push({ name: m[2], type: "Mixin" });
body = m[1];
}
else if (m = memberRegex.exec(body) ?? memberIndexerRegex.exec(body)) {
result.push({ name: m[2], type: "Member" });
body = m[1];
}
else if (m = indexRegex.exec(body)) {
result.push({ name: m[2], type: "Indexer" });
body = m[1];
}
else if (m = fixNullPropagator.exec(body) ?? fixNullPropagatorProd.exec(body)) {
body = m[2];
}
else {
throw new Error(`Impossible to extract the properties from: ${body}` +
(body.contains("Mixin") ? "\r\n Consider using subCtx(MyMixin) directly." : null));
}
}
result = result.reverse();
result = result.filter((m, i) => !(m.type == "Member" && m.name == "element" && i > 0 && result[i - 1].type == "Indexer"));
return result;
}
//slighliy different to is, and prevents webpack cycle
function sameEntity(a: any, b: any) {
if (a === b)
return true;
if (a == undefined || b == undefined)
return false;
if ((a as Entity).Type && (b as Entity).Type) {
return (a as Entity).Type == (b as Entity).Type &&
(a as Entity).id != null && (b as Entity).id != null &&
(a as Entity).id == (b as Entity).id;
}
if ((a as Lite<Entity>).EntityType && (b as Lite<Entity>).EntityType) {
return (a as Lite<Entity>).EntityType == (b as Lite<Entity>).EntityType &&
(a as Lite<Entity>).id != null && (b as Lite<Entity>).id != null &&
(a as Lite<Entity>).id == (b as Lite<Entity>).id;
}
return false;
}
export function getFieldMembers(field: string): LambdaMember[] {
if (field.contains(".")) {
var mixinType = field.before(".").after("[").before("]");
var fieldName = field.after(".");
return [
{ type: "Mixin", name: mixinType },
{ type: "Member", name: fieldName.firstLower() }
];
} else {
return [
{ type: "Member", name: field.firstLower() }
];
}
}
export interface LambdaMember {
name: string;
type: MemberType
}
export type MemberType = "Member" | "Mixin" | "Indexer";
export function New(type: PseudoType, props?: any, propertyRoute?: PropertyRoute): ModifiableEntity {
const ti = tryGetTypeInfo(type);
const result = { Type: getTypeName(type), isNew: true, modified: true } as any as ModifiableEntity;
if (ti) {
var e = result as Entity;
var pr = PropertyRoute.root(ti);
initializeMixins(e, pr);
initializeCollections(e, pr);
}
else {
if (propertyRoute) {
initializeCollections(result, propertyRoute);
initializeMixins(result, propertyRoute);
} else {
//Collections or mixins not initialized, but since Embedded typically don't have then, it's not worth the hassle
}
}
if (props) {
Dic.assign(result, props);
result.Type = getTypeName(type);
result.modified = true;
result.isNew = true;
}
return result;
}
function initializeMixins(mod: ModifiableEntity, pr: PropertyRoute) {
var subMembers = pr.subMembers();
Dic.getKeys(subMembers)
.filter(a => a.startsWith("["))
.groupBy(a => a.after("[").before("]"))
.forEach(gr => {
var mixin = ({ Type: gr.key, isNew: true, modified: true, }) as MixinEntity;
initializeCollections(mixin, pr.addMember("Mixin", gr.key, true)!);
if (!mod.mixins)
mod.mixins = {};
mod.mixins[gr.key] = mixin;
});
}
function initializeCollections(mod: ModifiableEntity, pr: PropertyRoute) {
Dic.map(pr.subMembers(), (key, memberInfo) => ({ key, memberInfo }))
.filter(t => t.memberInfo.type.isCollection && !t.key.startsWith("["))
.forEach(t => (mod as any)[t.key.firstLower()] = []);
}
export function clone<T>(original: ModifiableEntity, propertyRoute?: PropertyRoute) {
const ti = tryGetTypeInfo(original.Type);
const result = { Type: original.Type, isNew: true, modified: true } as any as ModifiableEntity;
if (ti) {
var e = result as Entity;
var pr = PropertyRoute.root(ti);
const mixins = Dic.getKeys(ti.members)
.filter(a => a.startsWith("["))
.groupBy(a => a.after("[").before("]"))
.forEach(gr => {
var m = ({ Type: gr.key, isNew: true, modified: true, }) as MixinEntity;
copyProperties(m, (original as Entity).mixins![gr.key], pr.addMember("Mixin", gr.key, true));
if (!e.mixins)
e.mixins = {};
e.mixins[gr.key] = m;
});
copyProperties(e, original, pr);
}
else {
if (!propertyRoute) {
throw new Error("propertyRoute is mandatory for non-Entities");
}
copyProperties(result, original, propertyRoute);
}
return result;
}
function copyProperties(result: any, original: any, pr: PropertyRoute) {
Dic.map(pr.subMembers(), (key, memberInfo) => ({ key, memberInfo }))
.filter(p => p.key != "Id")
.forEach(t => {
var memberName = t.key.firstLower();
var orinalProp = (original as any)[memberName];
var clonedProp = cloneIfNeeded(orinalProp, pr.addMember("Member", t.key, true));
(result as any)[memberName] = clonedProp;
});
}
function cloneCollection<T>(mlist: MList<T>, propertyRoute: PropertyRoute): MList<T> {
var elemPr = PropertyRoute.mlistItem(propertyRoute);
if (propertyRoute.member!.isVirtualMList) {
return mlist.map(mle => ({ rowId: null, element: clone(mle.element as any as Entity, elemPr) as any as T }));
}
return mlist.map(mle => ({ rowId: null, element: cloneIfNeeded(mle.element, elemPr) as T }));
}
function cloneIfNeeded(original: any, pr: PropertyRoute) {
var tr = pr.typeReference();
if (tr.isCollection)
return cloneCollection(original, pr);
if (original === null || original === undefined)
return original;
if (tr.isEmbedded)
return clone(original, pr);
if (tr.name == IsByAll || tryGetTypeInfos(tr.name).length > 0)
return JSON.parse(JSON.stringify(original));
return original; //string, number, boolean, etc...
}
export interface IType {
typeName: string;
}
export function isType(obj: any): obj is IType {
return (obj as IType).typeName != undefined;
}
export function newLite<T extends Entity>(type: Type<T>, id: number | string, toStr?: string): Lite<T>;
export function newLite(typeName: PseudoType, id: number | string, toStr?: string): Lite<Entity>;
export function newLite(type: PseudoType, id: number | string, toStr?: string): Lite<Entity> {
return {
EntityType: getTypeName(type),
id: id,
toStr: toStr
};
}
export type Anonymous<T extends ModifiableEntity> = T & {
/** Represents the 'Entity' column in the query selector */
entity: T
}
export class Type<T extends ModifiableEntity> implements IType {
New(props?: Partial<T>, propertyRoute?: PropertyRoute): T {
if (props && props.Type && (propertyRoute || tryGetTypeInfo(props.Type))) {
if (props.Type != this.typeName)
throw new Error("Cloning with another type");
return clone(props as ModifiableEntity, propertyRoute) as T;
}
return New(this.typeName, props, propertyRoute) as T;
}
constructor(
public typeName: string) { }
tryTypeInfo(): TypeInfo | undefined {
return tryGetTypeInfo(this.typeName);
}
typeInfo(): TypeInfo {
const result = this.tryTypeInfo();
if (!result)
throw new Error(`Type ${this.typeName} has no TypeInfo. \nNote: If is an EmbeddedEntity, start from some main Entity Type containing it to get metadata for the embedded properties (example: MyEntity.propertyRoute(m => m.myEmbedded.someProperty)`);
return result;
}
memberInfo(lambdaToProperty: (v: T) => any): MemberInfo {
var pr = this.propertyRouteAssert(lambdaToProperty);
if (!pr.member)
throw new Error(`${pr.propertyPath()} has no member`);
return pr.member;
}
tryMemberInfo(lambdaToProperty: (v: T) => any): MemberInfo | undefined {
var pr = this.tryPropertyRoute(lambdaToProperty);
return pr?.member;
}
hasMixin(mixinType: Type<MixinEntity>): boolean {
return Dic.getKeys(this.typeInfo().members).some(k => k.startsWith("[" + mixinType.typeName + "]"));
}
mixinMemberInfo<M extends MixinEntity>(mixinType: Type<M>, lambdaToProperty: (v: M) => any): MemberInfo {
var pr = this.mixinPropertyRouteAssert(mixinType, lambdaToProperty);
if (!pr.member)
throw new Error(`${pr.propertyPath()} has no member`);
return pr.member;
}
tryMixinMemberInfo<M extends MixinEntity>(mixinType: Type<M>, lambdaToProperty: (v: M) => any): MemberInfo | undefined {
var pr = this.tryMixinPropertyRoute(mixinType, lambdaToProperty);
return pr?.member;
}
propertyRouteAssert(lambdaToProperty: (v: T) => any): PropertyRoute {
return PropertyRoute.root(this.typeInfo()).addLambda(lambdaToProperty);
}
tryPropertyRoute(lambdaToProperty: (v: T) => any): PropertyRoute | undefined {
var ti = this.tryTypeInfo();
if (ti == null)
return undefined;
return PropertyRoute.root(ti).tryAddLambda(lambdaToProperty);
}
mixinPropertyRouteAssert<M extends MixinEntity>(mixinType: Type<M>, lambdaToProperty: (v: M) => any): PropertyRoute {
return PropertyRoute.root(this.typeInfo()).addMember("Mixin", mixinType.typeName, true).addLambda(lambdaToProperty);
}
tryMixinPropertyRoute<M extends MixinEntity>(mixinType: Type<M>, lambdaToProperty: (v: M) => any): PropertyRoute | undefined {
var ti = this.tryTypeInfo();
if (ti == null)
return undefined;
return PropertyRoute.root(ti).addMember("Mixin", mixinType.typeName, false)?.tryAddLambda(lambdaToProperty);
}
niceName(): string {
const ti = this.typeInfo();
if (!ti.niceName)
throw new Error(`no niceName found for ${ti.name}`);
return ti.niceName;
}
nicePluralName(): string {
const ti = this.typeInfo();
if (!ti.nicePluralName)
throw new Error(`no nicePluralName found for ${ti.name}`);
return ti.nicePluralName;
}
niceCount(count: number): string {
return count + " " + (count == 1 ? this.niceName() : this.nicePluralName());
}
nicePropertyName(lambdaToProperty: (v: T) => any): string {
const member = this.memberInfo(lambdaToProperty);
if (!member.niceName)
throw new Error(`no nicePropertyName found for ${member.name}`);
return member.niceName;
}
isInstance(obj: any): obj is T {
return obj && (obj as ModifiableEntity).Type == this.typeName;
}
cast(obj: any): T {
if (this.isInstance(obj))
return obj;
throw new Error("Unable to cast object to " + this.typeName);
}
isLite(obj: any): obj is Lite<T & Entity> {
return obj && (obj as Lite<Entity>).EntityType == this.typeName;
}
/* Constructs a QueryToken able to generate string like "Name" from a strongly typed lambda like a => a.name
* Note: The QueryToken language is quite different to javascript lambdas (Any, Lites, Nullable, etc)*/
token(): QueryTokenString<Anonymous<T>>;
/** Shortcut for token().append(lambdaToColumn)
* @param lambdaToColumn lambda expression pointing to a property in the anonymous class of the query. For simple columns comming from properties from the entity.
*/
token<S>(lambdaToColumn: (v: Anonymous<T>) => S): QueryTokenString<S>;
/** Shortcut for token().expression<S>(columnName)
* @param columnName property name of some property in the anonymous class of the query. For complex calculated columns that are not a property from the entitiy.
*/
token<S>(columnName: string): QueryTokenString<S>;
token(lambdaToColumn?: ((a: any) => any) | string): QueryTokenString<any> {
if (lambdaToColumn == null)
return new QueryTokenString("");
else if (typeof lambdaToColumn == "string")
return new QueryTokenString(lambdaToColumn);
else
return new QueryTokenString(tokenSequence(lambdaToColumn, true));
}
}
/* Some examples being in ExceptionEntity:
* "User" -> ExceptionEntity.token().append(a => a.user)
* ExceptionEntity.token(a => a.user)
* "Entity.User" -> ExceptionEntity.token().append(a=>a.entity).append(a=>a.user)
* ExceptionEntity.token(a => a.entity.user)
*
*/
export class QueryTokenString<T> {
token: string;
constructor(token: string) {
this.token = token;
}
toString() {
return this.token;
}
static entity<T extends Entity = Entity>() {
return new QueryTokenString<T>("Entity");
}
static count() {
return new QueryTokenString("Count");
}
systemValidFrom() {
return new QueryTokenString(this.token + ".SystemValidFrom");
}
systemValidTo() {
return new QueryTokenString(this.token + ".SystemValidTo");
}
cast<R extends Entity>(t: Type<R>): QueryTokenString<R> {
return new QueryTokenString<R>(this.token + ".(" + t.typeName + ")");
}
/**
* Allows adding some extra property names to a QueryTokenString
* @param lambdaToProperty for a typed lambda like a => a.name will append "Name" to the QueryTokenString
*/
append<S>(lambdaToProperty: (v: T) => S): QueryTokenString<S> {
return new QueryTokenString<S>(this.token + (this.token ? "." : "") + tokenSequence(lambdaToProperty, !this.token));
}
mixin<M extends MixinEntity>(t: Type<M>): QueryTokenString<M> {
return new QueryTokenString<M>(this.token);
}
/**
* Allows to add an extra token to a QueryTokenString given the name and the type. Typically used for registered expressions. Not strongly-typed :(
* @param expressionName name of the token to add (typically a registered expression)
*/
expression<S>(expressionName: string): QueryTokenString<S> {
return new QueryTokenString<S>(this.token + (this.token ? "." : "") + expressionName);
}
any<S = ArrayElement<T>>(): QueryTokenString<S> {
return new QueryTokenString<S>(this.token + ".Any");
}
all<S = ArrayElement<T>>(): QueryTokenString<S> {
return new QueryTokenString<S>(this.token + ".All");
}
anyNo<S = ArrayElement<T>>(): QueryTokenString<S> {
return new QueryTokenString<S>(this.token + ".AnyNo");
}
noOne<S = ArrayElement<T>>(): QueryTokenString<S> {
return new QueryTokenString<S>(this.token + ".NoOne");
}
element<S = ArrayElement<T>>(index = 1): QueryTokenString<S> {
return new QueryTokenString<S>(this.token + (this.token ? "." : "") + "Element" + (index == 1 ? "" : index));
}
count(option?: "Distinct" | "Null" | "NotNull"): QueryTokenString<number> {
return new QueryTokenString<number>(this.token + (this.token ? "." : "") + "Count" + ((option == undefined) ? "" : option));
}
min(): QueryTokenString<T> {
return new QueryTokenString<T>(this.token + ".Min");
}
max(): QueryTokenString<T> {
return new QueryTokenString<T>(this.token + ".Max");
}
sum(): QueryTokenString<T> {
return new QueryTokenString<T>(this.token + ".Sum");
}
average(): QueryTokenString<T> {
return new QueryTokenString<T>(this.token + ".Average");
}
hasValue(): QueryTokenString<boolean> {
return new QueryTokenString<boolean>(this.token + ".HasValue");
}
}
type ArrayElement<ArrayType> = ArrayType extends (infer ElementType)[] ? RemoveMListElement<ElementType> : never;
type RemoveMListElement<Type> = Type extends MListElement<infer S> ? S : Type;
function tokenSequence(lambdaToProperty: Function, isFirst: boolean) {
return getLambdaMembers(lambdaToProperty)
.filter((a, i) => a.name != "entity" || i == 0 && isFirst) //For convinience navigating Lite<T>, 'entity' is removed. If you have a property named Entity, you will need to use expression<S>()
.map(a => a.name == "toStr" ? "ToString" : a.name.firstUpper())
.join(".");
}
export class EnumType<T extends string> {
constructor(public type: string) { }
typeInfo(): TypeInfo {
return getTypeInfo(this.type);
}
values(): T[] {
return Dic.getKeys(this.typeInfo().members) as T[];
}
isDefined(val: any): val is T {
return typeof val == "string" && this.typeInfo().members[val] != null
}
assertDefined(val: any): T {
if (this.isDefined(val))
return val;
throw new Error(`'${val}' is not a valid ${this.type}`)
}
value(val: T): T {
return val;
}
niceTypeName(): string | undefined {
return this.typeInfo().niceName;
}
niceToString(value: T): string {
return this.typeInfo().members[value as string].niceName;
}
}
export class MessageKey {
constructor(
public type: string,
public name: string) { }
propertyInfo(): MemberInfo {
return getTypeInfo(this.type).members[this.name]
}
niceToString(...args: any[]): string {
const msg = this.propertyInfo().niceName;
return args.length ? msg.formatWith(...args) : msg;
}
}
export class QueryKey {
constructor(
public type: string,
public name: string) { }
memberInfo(): MemberInfo {
return getTypeInfo(this.type).members[this.name]
}
niceName(): string {
return this.memberInfo().niceName;
}
}
export interface ISymbol {
Type: string;
key: string;
id?: any;
}
let missingSymbols: ISymbol[] = [];
function getMember(key: string): MemberInfo | undefined {
if (!key.contains("."))
return undefined;
const type = _types[key.before(".").toLowerCase()];
if (!type)
return undefined;
const member: MemberInfo | undefined = type.members[key.after(".")];
return member;
}
export function symbolNiceName(symbol: Entity & ISymbol | Lite<Entity & ISymbol>): string {
if ((symbol as Entity).Type != null) //Don't use isEntity to avoid cycle
{
var m = getMember((symbol as Entity & ISymbol).key);
return m && m.niceName || symbol.toStr!;
}
else {
var m = getMember(symbol.toStr!);
return m && m.niceName || symbol.toStr!;
}
}
export function getSymbol<T extends Entity & ISymbol>(type: Type<T>, key: string) { //Unsafe Type!
const mi = getMember(key);
if (mi == null)
throw new Error(`No Symbol with key '${key}' found`);
var symbol = {
Type: type.typeName,
id: mi.id,
key: key
} as T;
return symbol as T
}
export function registerSymbol(type: string, key: string): any /*ISymbol*/ {
const mi = getMember(key);
var symbol = {
Type: type,
id: mi && mi.id || null,
key: key
} as ISymbol;
if (symbol.id == null)
missingSymbols.push(symbol);
return symbol as any;
}
export class PropertyRoute {
propertyRouteType: PropertyRouteType;
parent?: PropertyRoute; //!Root
rootType?: TypeInfo; //Root
member?: MemberInfo; //Member
mixinName?: string; //Mixin
static root(type: PseudoType) {
const typeInfo = getTypeInfo(type);
if (!typeInfo) {
throw Error(`No TypeInfo for "${getTypeName(type)}" found. Consider calling ReflectionServer.RegisterLike on the server side.`);
}
return new PropertyRoute(undefined, "Root", typeInfo, undefined, undefined);
}
static member(parent: PropertyRoute, member: MemberInfo) {
return new PropertyRoute(parent, "Field", undefined, member, undefined);
}
static mixin(parent: PropertyRoute, mixinName: string) {
return new PropertyRoute(parent, "Mixin", undefined, undefined, mixinName);
}
static mlistItem(parent: PropertyRoute) {
return new PropertyRoute(parent, "MListItem", undefined, undefined, undefined);
}
static liteEntity(parent: PropertyRoute) {
return new PropertyRoute(parent, "LiteEntity", undefined, undefined, undefined);
}
addMembers(propertyString: string): PropertyRoute {
let result: PropertyRoute = this;
const parts = PropertyRoute.parseLambdaMembers(propertyString);
parts.forEach(m => result = result.addMember(m.type, m.name, true));
return result;
}
tryAddMembers(propertyString: string): PropertyRoute | undefined {
let result: PropertyRoute | undefined = this;
const parts = PropertyRoute.parseLambdaMembers(propertyString);
parts.forEach(m => result = result?.addMember(m.type, m.name, false));
return result;
}
static parseLambdaMembers(propertyString: string) {
function splitMixin(text: string): LambdaMember[] {
if (text.length == 0)
return [];
if (text.contains("["))
return [
...splitMixin(text.before("[")),
{ type: "Mixin" as MemberType, name: text.between("[", "]") },
...splitMixin(text.after("]")),
];
return [{ type: "Member", name: text }];
}
function splitDot(text: string): LambdaMember[] {
if (text.contains("."))
return [
...splitMixin(text.before(".")),
...splitDot(text.after("."))
];
return splitMixin(text);
}
function splitIndexer(text: string): LambdaMember[] {
if (text.contains("/"))
return [
...splitDot(text.before("/")),
{ type: "Indexer", name: "0" },
...splitIndexer(text.after("/"))
];
return splitDot(text);
}
return splitIndexer(propertyString);
}
static parseFull(fullPropertyRoute: string): PropertyRoute {
const type = fullPropertyRoute.after("(").before(")");
let propertyString = fullPropertyRoute.after(")");
if (propertyString.startsWith("."))
propertyString = propertyString.substr(1);
return PropertyRoute.root(type).addMembers(propertyString);
}
static parse(rootType: PseudoType, propertyString: string): PropertyRoute {
return PropertyRoute.root(rootType).addMembers(propertyString);
}
static tryParseFull(fullPropertyRoute: string): PropertyRoute | undefined {
const type = fullPropertyRoute.after("(").before(")");
let propertyString = fullPropertyRoute.after(")");
if (propertyString.startsWith("."))
propertyString = propertyString.substr(1);
var ti = tryGetTypeInfo(type);
if (ti == null)
return undefined;
return PropertyRoute.tryParse(type, propertyString);
}
static tryParse(rootType: PseudoType, propertyString: string): PropertyRoute | undefined {
const ti = tryGetTypeInfo(rootType);
if (ti == null)
return undefined;
return PropertyRoute.root(ti).tryAddMembers(propertyString);
}
constructor(
parent: PropertyRoute | undefined,
propertyRouteType: PropertyRouteType,
rootType: TypeInfo | undefined,
member: MemberInfo | undefined,
mixinName: string | undefined) {
this.propertyRouteType = propertyRouteType;
this.parent = parent;
this.rootType = rootType;
this.member = member;
this.mixinName = mixinName;
}
allParents(includeMixins = false): PropertyRoute[] {
if (!includeMixins && this.propertyRouteType == "Mixin")
return this.parent!.allParents(includeMixins);
return [...this.parent == null ? [] : this.parent.allParents(includeMixins), this];
}
addLambda(property: ((val: any) => any) | string): PropertyRoute {
const lambdaMembers = typeof property == "function" ?
getLambdaMembers(property) :
getFieldMembers(property);
let result: PropertyRoute = lambdaMembers.reduce<PropertyRoute>((pr, m) => pr.addLambdaMember(m), this)
return result;
}
tryAddLambda(property: ((val: any) => any) | string): PropertyRoute | undefined {
const lambdaMembers = typeof property == "function" ?
getLambdaMembers(property) :
getFieldMembers(property);
let result: PropertyRoute | undefined = lambdaMembers.reduce<PropertyRoute | undefined>((pr, m) => pr && pr.tryAddLambdaMember(m), this)
return result;
}
typeReference(): TypeReference {
switch (this.propertyRouteType) {
case "Root": return { name: this.rootType!.name };
case "Field": return this.member!.type;
case "Mixin": throw new Error("mixins can not be used alone");
case "MListItem": return { ...this.parent!.typeReference(), isCollection: false };
case "LiteEntity": return { ...this.parent!.typeReference(), isLite: false };
default: throw new Error("Unexpected propertyRouteType");
}
}
typeReferenceInfo(): TypeInfo {
return getTypeInfo(this.typeReference().name);
}
findRootType(): TypeInfo {
switch (this.propertyRouteType) {
case "Root": return this.rootType!;
case "Field": return this.parent!.findRootType();
case "Mixin": return this.parent!.findRootType();
case "MListItem": return this.parent!.findRootType();
case "LiteEntity": return this.parent!.findRootType();
default: throw new Error("Unexpected propertyRouteType");
}
}
propertyPath(): string {
switch (this.propertyRouteType) {
case "Root": throw new Error("Root has no PropertyString");
case "Field": return this.member!.name;
case "Mixin": return (this.parent!.propertyRouteType == "Root" ? "" : this.parent!.propertyPath()) + "[" + this.mixinName + "]";
case "MListItem": return this.parent!.propertyPath() + "/";
case "LiteEntity": return this.parent!.propertyPath() + ".entity";
default: throw new Error("Unexpected propertyRouteType");
}
}
tryAddMember(memberType: MemberType, memberName: string): PropertyRoute | undefined {
try {
return this.addMember(memberType, memberName, false);
} catch (e) {
return undefined;
}
}
addLambdaMember(lm: LambdaMember): PropertyRoute {
return this.addMember(lm.type, lm.type == "Member" ? toCSharp(lm.name) : lm.name, true);
}
tryAddLambdaMember(lm: LambdaMember): PropertyRoute | undefined {
return this.addMember(lm.type, lm.type == "Member" ? toCSharp(lm.name) : lm.name, false);
}
addMember(memberType: MemberType, memberName: string, throwIfNotFound: true): PropertyRoute;
addMember(memberType: MemberType, memberName: string, throwIfNotFound: false): PropertyRoute | undefined;
addMember(memberType: MemberType, memberName: string, throwIfNotFound: boolean): PropertyRoute | undefined {
var getErrorContext = () => ` (adding ${memberType} ${memberName} to ${this.toString()})`;
if (memberType == "Member" || memberType == "Mixin") {
if (this.propertyRouteType == "Field" ||
this.propertyRouteType == "MListItem" ||
this.propertyRouteType == "LiteEntity") {
const ref = this.typeReference();
if (ref.isLite) {
if (memberType == "Member" && memberName == "Entity")
return PropertyRoute.liteEntity(this);
throw new Error("Entity expected");
}
const ti = tryGetTypeInfos(ref).single("Ambiguity due to multiple Implementations" + getErrorContext()); //[undefined]
if (ti) {
if (memberType == "Mixin")
return PropertyRoute.mixin(this, memberName);
else {
const m = ti.members[memberName];
if (!m) {
if (throwIfNotFound)
throw new Error(`member '${memberName}' not found` + getErrorContext());
return undefined;
}
return PropertyRoute.member(PropertyRoute.root(ti), m);
}
} else if (this.propertyRouteType == "LiteEntity") {
throw Error("Unexpected lite case" + getErrorContext());
}
}
if (memberType == "Mixin")
return PropertyRoute.mixin(this, memberName);
else {
const fullMemberName =
this.propertyRouteType == "Root" ? memberName :
this.propertyRouteType == "MListItem" ? this.propertyPath() + memberName :
this.propertyPath() + "." + memberName;
const m = this.findRootType().members[fullMemberName];
if (!m) {
if (throwIfNotFound)
throw new Error(`member '${fullMemberName}' not found` + getErrorContext());
return undefined;
}
return PropertyRoute.member(this, m);
}
}
if (memberType == "Indexer") {
if (this.propertyRouteType != "Field")
throw new Error("invalid indexer at this stage" + getErrorContext());
const tr = this.typeReference();
if (!tr.isCollection)
throw new Error("${this.propertyPath()} is not a collection" + getErrorContext());
return PropertyRoute.mlistItem(this);
}
throw new Error("not implemented" + getErrorContext());
}
static generateAll(type: PseudoType): PropertyRoute[] {
var ti = getTypeInfo(type);
var mixins: string[] = [];
return Dic.getValues(ti.members).flatMap(mi => {
const pr = PropertyRoute.parse(ti, mi.name);
if (pr.typeReference().isCollection)
return [pr, PropertyRoute.mlistItem(pr)];
return [pr];
}).flatMap(pr => {
if (pr.parent && pr.parent.propertyRouteType == "Mixin" && !mixins.contains(pr.parent.propertyPath())) {
mixins.push(pr.parent.propertyPath());
return [pr.parent, pr];
} else
return [pr];
});
}
subMembers(): { [subMemberName: string]: MemberInfo } {
function simpleMembersAfter(type: TypeInfo, path: string) {
return Dic.getValues(type.members)
.filter(m => {
if (m.name == path || !m.name.startsWith(path))
return false;
var suffix = m.name.substring(path.length);
if (suffix.contains("/"))
return false;
if (suffix.startsWith("[") ? suffix.after("].").contains("."): suffix.contains("."))
return false;
return true;
})
.toObject(m => m.name.substring(path.length))
}
function mixinMembers(type: TypeInfo) {
var mixins = Dic.getValues(type.members).filter(a => a.name.startsWith("[")).groupBy(a => a.name.after("[").before("]")).map(a => a.key);
return mixins.flatMap(mn => Dic.getValues(simpleMembersAfter(type, `[${mn}].`))).toObject(a => a.name);
}
switch (this.propertyRouteType) {
case "Root": return {
...simpleMembersAfter(this.findRootType(), ""),
...mixinMembers(this.findRootType())
};
case "Mixin": return simpleMembersAfter(this.findRootType(), this.propertyPath() + ".");
case "LiteEntity": return simpleMembersAfter(this.typeReferenceInfo(), "");
case "Field":
case "MListItem":
{
var tr = this.typeReference();
if (tr.name == IsByAll)
return {};
const ti = tryGetTypeInfos(this.typeReference()).single("Ambiguity due to multiple Implementations"); //[undefined]
if (ti && isTypeEntity(ti))
return simpleMembersAfter(ti, "");
else
return simpleMembersAfter(this.findRootType(), this.propertyPath() + (this.propertyRouteType == "Field" ? "." : ""));
}
default: throw new Error("Unexpected propertyRouteType");
}
}
toString() {
if (this.propertyRouteType == "Root")
return `(${this.findRootType().name})`;
return `(${this.findRootType().name}).${this.propertyPath()}`;
}
}
function toCSharp(name: string) {
var result = name.firstUpper();
if (result == name)
throw new Error(`Name '${name}' should start by lowercase`);
return result;
}
export type PropertyRouteType = "Root" | "Field" | "Mixin" | "LiteEntity" | "MListItem";
export type GraphExplorerMode = "collect" | "set" | "clean";
export class GraphExplorer {
static propagateAll(...args: any[]): GraphExplorer {
const ge = new GraphExplorer("clean", {});
args.forEach(o => ge.isModified(o, ""));
return ge;
}
static setModelState(e: ModifiableEntity, modelState: ModelState | undefined, initialPrefix: string) {
const ge = new GraphExplorer("set", modelState == undefined ? {} : { ...modelState });
ge.isModifiableObject(e, initialPrefix);
if (Dic.getValues(ge.modelState).length) //Assign remaining
{
if (e.error == undefined)
e.error = {};
for (const key in ge.modelState) {
e.error[key] = ge.modelState[key].join("\n");
delete ge.modelState[key];
}
}
}
static collectModelState(e: ModifiableEntity, initialPrefix: string): ModelState {
const ge = new GraphExplorer("collect", {});
ge.isModifiableObject(e, initialPrefix);
return ge.modelState;
}
//cycle detection
private modified: any[] = [];
private notModified: any[] = [];
constructor(mode: GraphExplorerMode, modelState: ModelState) {
this.modelState = modelState;
this.mode = mode;
}
private mode: GraphExplorerMode;
private modelState: ModelState;
isModified(obj: any, modelStatePrefix: string): boolean {
if (obj == undefined)
return false;
const t = typeof obj;
if (t != "object")
return false;
if (this.modified.contains(obj)) {
if (window.exploreGraphDebugMode)
debugger;
return true;
}
if (this.notModified.contains(obj))
return false;
const result = this.isModifiableObject(obj, modelStatePrefix);
if (result) {
if (window.exploreGraphDebugMode)
debugger;
this.modified.push(obj);
return true;
} else {
this.notModified.push(obj);
return false;
}
}
private static specialProperties = ["Type", "id", "isNew", "ticks", "toStr", "modified"];
//The redundant return true / return false are there for debugging
private isModifiableObject(obj: any, modelStatePrefix: string) {
if (obj instanceof Date)
return false;
if (obj instanceof Array) {
let result = false;
for (let i = 0; i < obj.length; i++) {
if (this.isModified(obj[i], modelStatePrefix + "[" + i + "]")) {
if (window.exploreGraphDebugMode)
debugger;
result = true;
}
}
return result;
}
const mle = obj as MListElement<any>;
if (mle.hasOwnProperty && mle.hasOwnProperty("rowId")) {
if (this.isModified(mle.element, modelStatePrefix + ".element")) {
if (window.exploreGraphDebugMode)
debugger;
return true;
}
if (mle.rowId == undefined) {
if (window.exploreGraphDebugMode)
debugger;
return true;
}
return false;
};
const lite = obj as Lite<Entity>
if (lite.EntityType) {
if (lite.entity != undefined && this.isModified(lite.entity, modelStatePrefix + ".entity")) {
if (window.exploreGraphDebugMode)
debugger;
return true;
}
return false;
}
const mod = obj as ModifiableEntity;
if (mod.Type == undefined) { //Other object
let result = false;
for (const p in obj) {
if (obj.hasOwnProperty == null || obj.hasOwnProperty(p)) {
const propertyPrefix = modelStatePrefix + "." + p;
if (this.isModified(obj[p], propertyPrefix)) {
if (window.exploreGraphDebugMode)
debugger;
result = true;
}
}
}
return result;
}
if (this.mode == "collect") {
if (mod.error != undefined) {
for (const p in mod.error) {
const propertyPrefix = modelStatePrefix + "." + p;
if (mod.error[p])
this.modelState[modelStatePrefix + "." + p] = [mod.error[p]];
}
}
}
else if (this.mode == "set") {
mod.error = undefined;
const prefix = modelStatePrefix + ".";
for (const key in this.modelState) {
const propName = key.tryAfter(prefix)
if (propName && !propName.contains(".")) {
if (mod.error == undefined)
mod.error = {};
mod.error[propName] = this.modelState[key].join("\n");
delete this.modelState[key];
}
}
if (mod.error == undefined)
delete mod.error;
}
else if (this.mode == "clean") {
if (mod.error)
delete mod.error
}
for (const p in obj) {
if (obj.hasOwnProperty(p) && !GraphExplorer.specialProperties.contains(p)) {
if (p == "mixins") {
const propertyPrefix = modelStatePrefix + "." + p;
if (this.isModifiedMixinDictionary(obj[p], propertyPrefix)) {
if (window.exploreGraphDebugMode)
debugger;
mod.modified = true;
}
} else {
const propertyPrefix = modelStatePrefix + "." + p;
if (this.isModified(obj[p], propertyPrefix)) {
if (window.exploreGraphDebugMode)
debugger;
mod.modified = true;
}
}
}
}
if ((mod as Entity).isNew) {
if (window.exploreGraphDebugMode)
debugger;
mod.modified = true; //Just in case
if (GraphExplorer.TypesLazilyCreated.push((mod as Entity).Type))
return false;
}
return mod.modified;
}
isModifiedMixinDictionary(mixins: { [name: string]: MixinEntity }, prefix: string) {
if (mixins == undefined)
return false;
var modified = false;
for (const p in mixins) {
const mixinPrefix = prefix + "[" + p + "]";
if (this.isModified(mixins[p], mixinPrefix)) {
if (window.exploreGraphDebugMode)
debugger;
modified = true;
}
}
return modified;
}
static TypesLazilyCreated: string[] = [];
} | the_stack |
'use strict';
import { assert, expect } from 'chai';
import { ChildProcess } from 'child_process';
import { EOL } from 'os';
import * as path from 'path';
import { Observable } from 'rxjs/Observable';
import { Subscriber } from 'rxjs/Subscriber';
import * as sinon from 'sinon';
import { Writable } from 'stream';
import * as TypeMoq from 'typemoq';
import { Range, TextDocument, TextEditor, TextLine, Uri, WorkspaceEdit } from 'vscode';
import { IApplicationShell, ICommandManager, IDocumentManager } from '../../client/common/application/types';
import { Commands, EXTENSION_ROOT_DIR, STANDARD_OUTPUT_CHANNEL } from '../../client/common/constants';
import { ProcessService } from '../../client/common/process/proc';
import {
IProcessServiceFactory,
IPythonExecutionFactory,
IPythonExecutionService,
Output,
} from '../../client/common/process/types';
import {
IConfigurationService,
IDisposableRegistry,
IEditorUtils,
IOutputChannel,
IPersistentState,
IPersistentStateFactory,
IPythonSettings,
ISortImportSettings,
} from '../../client/common/types';
import { createDeferred, createDeferredFromPromise } from '../../client/common/utils/async';
import { Common, Diagnostics } from '../../client/common/utils/localize';
import { noop } from '../../client/common/utils/misc';
import { IServiceContainer } from '../../client/ioc/types';
import { SortImportsEditingProvider } from '../../client/providers/importSortProvider';
import { sleep } from '../core';
suite('Import Sort Provider', () => {
let serviceContainer: TypeMoq.IMock<IServiceContainer>;
let shell: TypeMoq.IMock<IApplicationShell>;
let documentManager: TypeMoq.IMock<IDocumentManager>;
let configurationService: TypeMoq.IMock<IConfigurationService>;
let pythonExecFactory: TypeMoq.IMock<IPythonExecutionFactory>;
let processServiceFactory: TypeMoq.IMock<IProcessServiceFactory>;
let editorUtils: TypeMoq.IMock<IEditorUtils>;
let commandManager: TypeMoq.IMock<ICommandManager>;
let pythonSettings: TypeMoq.IMock<IPythonSettings>;
let persistentStateFactory: TypeMoq.IMock<IPersistentStateFactory>;
let output: TypeMoq.IMock<IOutputChannel>;
let sortProvider: SortImportsEditingProvider;
setup(() => {
serviceContainer = TypeMoq.Mock.ofType<IServiceContainer>();
commandManager = TypeMoq.Mock.ofType<ICommandManager>();
documentManager = TypeMoq.Mock.ofType<IDocumentManager>();
shell = TypeMoq.Mock.ofType<IApplicationShell>();
configurationService = TypeMoq.Mock.ofType<IConfigurationService>();
pythonExecFactory = TypeMoq.Mock.ofType<IPythonExecutionFactory>();
processServiceFactory = TypeMoq.Mock.ofType<IProcessServiceFactory>();
pythonSettings = TypeMoq.Mock.ofType<IPythonSettings>();
editorUtils = TypeMoq.Mock.ofType<IEditorUtils>();
persistentStateFactory = TypeMoq.Mock.ofType<IPersistentStateFactory>();
output = TypeMoq.Mock.ofType<IOutputChannel>();
serviceContainer.setup((c) => c.get(IOutputChannel, STANDARD_OUTPUT_CHANNEL)).returns(() => output.object);
serviceContainer.setup((c) => c.get(IPersistentStateFactory)).returns(() => persistentStateFactory.object);
serviceContainer.setup((c) => c.get(ICommandManager)).returns(() => commandManager.object);
serviceContainer.setup((c) => c.get(IDocumentManager)).returns(() => documentManager.object);
serviceContainer.setup((c) => c.get(IApplicationShell)).returns(() => shell.object);
serviceContainer.setup((c) => c.get(IConfigurationService)).returns(() => configurationService.object);
serviceContainer.setup((c) => c.get(IPythonExecutionFactory)).returns(() => pythonExecFactory.object);
serviceContainer.setup((c) => c.get(IProcessServiceFactory)).returns(() => processServiceFactory.object);
serviceContainer.setup((c) => c.get(IEditorUtils)).returns(() => editorUtils.object);
serviceContainer.setup((c) => c.get(IDisposableRegistry)).returns(() => []);
configurationService.setup((c) => c.getSettings(TypeMoq.It.isAny())).returns(() => pythonSettings.object);
sortProvider = new SortImportsEditingProvider(serviceContainer.object);
});
teardown(() => {
sinon.restore();
});
test('Ensure command is registered', () => {
commandManager
.setup((c) =>
c.registerCommand(
TypeMoq.It.isValue(Commands.Sort_Imports),
TypeMoq.It.isAny(),
TypeMoq.It.isValue(sortProvider),
),
)
.verifiable(TypeMoq.Times.once());
sortProvider.registerCommands();
commandManager.verifyAll();
});
test("Ensure message is displayed when no doc is opened and uri isn't provided", async () => {
documentManager
.setup((d) => d.activeTextEditor)
.returns(() => undefined)
.verifiable(TypeMoq.Times.once());
shell
.setup((s) => s.showErrorMessage(TypeMoq.It.isValue('Please open a Python file to sort the imports.')))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.once());
await sortProvider.sortImports();
shell.verifyAll();
documentManager.verifyAll();
});
test("Ensure message is displayed when uri isn't provided and current doc is non-python", async () => {
const mockEditor = TypeMoq.Mock.ofType<TextEditor>();
const mockDoc = TypeMoq.Mock.ofType<TextDocument>();
mockDoc
.setup((d) => d.languageId)
.returns(() => 'xyz')
.verifiable(TypeMoq.Times.atLeastOnce());
mockEditor
.setup((d) => d.document)
.returns(() => mockDoc.object)
.verifiable(TypeMoq.Times.atLeastOnce());
documentManager
.setup((d) => d.activeTextEditor)
.returns(() => mockEditor.object)
.verifiable(TypeMoq.Times.once());
shell
.setup((s) => s.showErrorMessage(TypeMoq.It.isValue('Please open a Python file to sort the imports.')))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.once());
await sortProvider.sortImports();
mockEditor.verifyAll();
mockDoc.verifyAll();
shell.verifyAll();
documentManager.verifyAll();
});
test('Ensure document is opened', async () => {
const uri = Uri.file('TestDoc');
documentManager
.setup((d) => d.openTextDocument(TypeMoq.It.isValue(uri)))
.verifiable(TypeMoq.Times.atLeastOnce());
documentManager.setup((d) => d.activeTextEditor).verifiable(TypeMoq.Times.never());
shell
.setup((s) => s.showErrorMessage(TypeMoq.It.isAny()))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.never());
await sortProvider.sortImports(uri).catch(noop);
shell.verifyAll();
documentManager.verifyAll();
});
test('Ensure no edits are provided when there is only one line', async () => {
const uri = Uri.file('TestDoc');
const mockDoc = TypeMoq.Mock.ofType<TextDocument>();
mockDoc.setup((d: any) => d.then).returns(() => undefined);
mockDoc
.setup((d) => d.lineCount)
.returns(() => 1)
.verifiable(TypeMoq.Times.atLeastOnce());
documentManager
.setup((d) => d.openTextDocument(TypeMoq.It.isValue(uri)))
.returns(() => Promise.resolve(mockDoc.object))
.verifiable(TypeMoq.Times.atLeastOnce());
shell
.setup((s) => s.showErrorMessage(TypeMoq.It.isAny()))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.never());
const edit = await sortProvider.sortImports(uri);
expect(edit).to.be.equal(undefined, 'not undefined');
shell.verifyAll();
documentManager.verifyAll();
});
test('Ensure no edits are provided when there are no lines', async () => {
const uri = Uri.file('TestDoc');
const mockDoc = TypeMoq.Mock.ofType<TextDocument>();
mockDoc.setup((d: any) => d.then).returns(() => undefined);
mockDoc
.setup((d) => d.lineCount)
.returns(() => 0)
.verifiable(TypeMoq.Times.atLeastOnce());
documentManager
.setup((d) => d.openTextDocument(TypeMoq.It.isValue(uri)))
.returns(() => Promise.resolve(mockDoc.object))
.verifiable(TypeMoq.Times.atLeastOnce());
shell
.setup((s) => s.showErrorMessage(TypeMoq.It.isAny()))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.never());
const edit = await sortProvider.sortImports(uri);
expect(edit).to.be.equal(undefined, 'not undefined');
shell.verifyAll();
documentManager.verifyAll();
});
test('Ensure empty line is added when line does not end with an empty line', async () => {
const uri = Uri.file('TestDoc');
const mockDoc = TypeMoq.Mock.ofType<TextDocument>();
mockDoc.setup((d: any) => d.then).returns(() => undefined);
mockDoc
.setup((d) => d.lineCount)
.returns(() => 10)
.verifiable(TypeMoq.Times.atLeastOnce());
const lastLine = TypeMoq.Mock.ofType<TextLine>();
let editApplied: WorkspaceEdit | undefined;
lastLine
.setup((l) => l.text)
.returns(() => '1234')
.verifiable(TypeMoq.Times.atLeastOnce());
lastLine
.setup((l) => l.range)
.returns(() => new Range(1, 0, 10, 1))
.verifiable(TypeMoq.Times.atLeastOnce());
mockDoc
.setup((d) => d.lineAt(TypeMoq.It.isValue(9)))
.returns(() => lastLine.object)
.verifiable(TypeMoq.Times.atLeastOnce());
documentManager
.setup((d) => d.applyEdit(TypeMoq.It.isAny()))
.callback((e) => (editApplied = e))
.returns(() => Promise.resolve(true))
.verifiable(TypeMoq.Times.atLeastOnce());
documentManager
.setup((d) => d.openTextDocument(TypeMoq.It.isValue(uri)))
.returns(() => Promise.resolve(mockDoc.object))
.verifiable(TypeMoq.Times.atLeastOnce());
shell
.setup((s) => s.showErrorMessage(TypeMoq.It.isAny()))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.never());
sortProvider.provideDocumentSortImportsEdits = () => Promise.resolve(undefined);
await sortProvider.sortImports(uri);
expect(editApplied).not.to.be.equal(undefined, 'Applied edit is undefined');
expect(editApplied!.entries()).to.be.lengthOf(1);
expect(editApplied!.entries()[0][1]).to.be.lengthOf(1);
expect(editApplied!.entries()[0][1][0].newText).to.be.equal(EOL);
shell.verifyAll();
documentManager.verifyAll();
});
test('Ensure no edits are provided when there is only one line (when using provider method)', async () => {
const uri = Uri.file('TestDoc');
const mockDoc = TypeMoq.Mock.ofType<TextDocument>();
mockDoc.setup((d: any) => d.then).returns(() => undefined);
mockDoc
.setup((d) => d.lineCount)
.returns(() => 1)
.verifiable(TypeMoq.Times.atLeastOnce());
documentManager
.setup((d) => d.openTextDocument(TypeMoq.It.isValue(uri)))
.returns(() => Promise.resolve(mockDoc.object))
.verifiable(TypeMoq.Times.atLeastOnce());
shell
.setup((s) => s.showErrorMessage(TypeMoq.It.isAny()))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.never());
const edit = await sortProvider.provideDocumentSortImportsEdits(uri);
expect(edit).to.be.equal(undefined, 'not undefined');
shell.verifyAll();
documentManager.verifyAll();
});
test('Ensure no edits are provided when there are no lines (when using provider method)', async () => {
const uri = Uri.file('TestDoc');
const mockDoc = TypeMoq.Mock.ofType<TextDocument>();
mockDoc.setup((d: any) => d.then).returns(() => undefined);
mockDoc
.setup((d) => d.lineCount)
.returns(() => 0)
.verifiable(TypeMoq.Times.atLeastOnce());
documentManager
.setup((d) => d.openTextDocument(TypeMoq.It.isValue(uri)))
.returns(() => Promise.resolve(mockDoc.object))
.verifiable(TypeMoq.Times.atLeastOnce());
shell
.setup((s) => s.showErrorMessage(TypeMoq.It.isAny()))
.returns(() => Promise.resolve(undefined))
.verifiable(TypeMoq.Times.never());
const edit = await sortProvider.provideDocumentSortImportsEdits(uri);
expect(edit).to.be.equal(undefined, 'not undefined');
shell.verifyAll();
documentManager.verifyAll();
});
test('Ensure stdin is used for sorting (with custom isort path)', async () => {
const uri = Uri.file('something.py');
const mockDoc = TypeMoq.Mock.ofType<TextDocument>();
const processService = TypeMoq.Mock.ofType<ProcessService>();
processService.setup((d: any) => d.then).returns(() => undefined);
mockDoc.setup((d: any) => d.then).returns(() => undefined);
mockDoc
.setup((d) => d.lineCount)
.returns(() => 10)
.verifiable(TypeMoq.Times.atLeastOnce());
mockDoc
.setup((d) => d.getText(TypeMoq.It.isAny()))
.returns(() => 'Hello')
.verifiable(TypeMoq.Times.atLeastOnce());
mockDoc
.setup((d) => d.isDirty)
.returns(() => true)
.verifiable(TypeMoq.Times.never());
mockDoc
.setup((d) => d.uri)
.returns(() => uri)
.verifiable(TypeMoq.Times.atLeastOnce());
documentManager
.setup((d) => d.openTextDocument(TypeMoq.It.isValue(uri)))
.returns(() => Promise.resolve(mockDoc.object))
.verifiable(TypeMoq.Times.atLeastOnce());
pythonSettings
.setup((s) => s.sortImports)
.returns(() => {
return ({ path: 'CUSTOM_ISORT', args: ['1', '2'] } as any) as ISortImportSettings;
})
.verifiable(TypeMoq.Times.once());
processServiceFactory
.setup((p) => p.create(TypeMoq.It.isAny()))
.returns(() => Promise.resolve(processService.object))
.verifiable(TypeMoq.Times.once());
let actualSubscriber: Subscriber<Output<string>>;
const stdinStream = TypeMoq.Mock.ofType<Writable>();
stdinStream.setup((s) => s.write('Hello')).verifiable(TypeMoq.Times.once());
stdinStream
.setup((s) => s.end())
.callback(() => {
actualSubscriber.next({ source: 'stdout', out: 'DIFF' });
actualSubscriber.complete();
})
.verifiable(TypeMoq.Times.once());
const childProcess = TypeMoq.Mock.ofType<ChildProcess>();
childProcess.setup((p) => p.stdin).returns(() => stdinStream.object);
const executionResult = {
proc: childProcess.object,
out: new Observable<Output<string>>((subscriber) => (actualSubscriber = subscriber)),
dispose: noop,
};
const expectedArgs = ['-', '--diff', '1', '2'];
processService
.setup((p) =>
p.execObservable(
TypeMoq.It.isValue('CUSTOM_ISORT'),
TypeMoq.It.isValue(expectedArgs),
TypeMoq.It.isValue({ token: undefined, cwd: path.sep }),
),
)
.returns(() => executionResult)
.verifiable(TypeMoq.Times.once());
const expectedEdit = new WorkspaceEdit();
editorUtils
.setup((e) =>
e.getWorkspaceEditsFromPatch(
TypeMoq.It.isValue('Hello'),
TypeMoq.It.isValue('DIFF'),
TypeMoq.It.isAny(),
),
)
.returns(() => expectedEdit)
.verifiable(TypeMoq.Times.once());
const edit = await sortProvider._provideDocumentSortImportsEdits(uri);
expect(edit).to.be.equal(expectedEdit);
shell.verifyAll();
mockDoc.verifyAll();
documentManager.verifyAll();
});
test('Ensure stdin is used for sorting', async () => {
const uri = Uri.file('something.py');
const mockDoc = TypeMoq.Mock.ofType<TextDocument>();
const processService = TypeMoq.Mock.ofType<ProcessService>();
processService.setup((d: any) => d.then).returns(() => undefined);
mockDoc.setup((d: any) => d.then).returns(() => undefined);
mockDoc
.setup((d) => d.lineCount)
.returns(() => 10)
.verifiable(TypeMoq.Times.atLeastOnce());
mockDoc
.setup((d) => d.getText(TypeMoq.It.isAny()))
.returns(() => 'Hello')
.verifiable(TypeMoq.Times.atLeastOnce());
mockDoc
.setup((d) => d.isDirty)
.returns(() => true)
.verifiable(TypeMoq.Times.never());
mockDoc
.setup((d) => d.uri)
.returns(() => uri)
.verifiable(TypeMoq.Times.atLeastOnce());
documentManager
.setup((d) => d.openTextDocument(TypeMoq.It.isValue(uri)))
.returns(() => Promise.resolve(mockDoc.object))
.verifiable(TypeMoq.Times.atLeastOnce());
pythonSettings
.setup((s) => s.sortImports)
.returns(() => {
return ({ args: ['1', '2'] } as any) as ISortImportSettings;
})
.verifiable(TypeMoq.Times.once());
const processExeService = TypeMoq.Mock.ofType<IPythonExecutionService>();
processExeService.setup((p: any) => p.then).returns(() => undefined);
pythonExecFactory
.setup((p) => p.create(TypeMoq.It.isAny()))
.returns(() => Promise.resolve(processExeService.object))
.verifiable(TypeMoq.Times.once());
let actualSubscriber: Subscriber<Output<string>>;
const stdinStream = TypeMoq.Mock.ofType<Writable>();
stdinStream.setup((s) => s.write('Hello')).verifiable(TypeMoq.Times.once());
stdinStream
.setup((s) => s.end())
.callback(() => {
actualSubscriber.next({ source: 'stdout', out: 'DIFF' });
actualSubscriber.complete();
})
.verifiable(TypeMoq.Times.once());
const childProcess = TypeMoq.Mock.ofType<ChildProcess>();
childProcess.setup((p) => p.stdin).returns(() => stdinStream.object);
const executionResult = {
proc: childProcess.object,
out: new Observable<Output<string>>((subscriber) => (actualSubscriber = subscriber)),
dispose: noop,
};
const importScript = path.join(EXTENSION_ROOT_DIR, 'pythonFiles', 'sortImports.py');
const expectedArgs = [importScript, '-', '--diff', '1', '2'];
processExeService
.setup((p) =>
p.execObservable(
TypeMoq.It.isValue(expectedArgs),
TypeMoq.It.isValue({ token: undefined, cwd: path.sep }),
),
)
.returns(() => executionResult)
.verifiable(TypeMoq.Times.once());
const expectedEdit = new WorkspaceEdit();
editorUtils
.setup((e) =>
e.getWorkspaceEditsFromPatch(
TypeMoq.It.isValue('Hello'),
TypeMoq.It.isValue('DIFF'),
TypeMoq.It.isAny(),
),
)
.returns(() => expectedEdit)
.verifiable(TypeMoq.Times.once());
const edit = await sortProvider._provideDocumentSortImportsEdits(uri);
expect(edit).to.be.equal(expectedEdit);
shell.verifyAll();
mockDoc.verifyAll();
documentManager.verifyAll();
});
test('If a second sort command is initiated before the execution of first one is finished, discard the result from first isort process', async () => {
// ----------------------Common setup between the 2 commands---------------------------
const uri = Uri.file('something.py');
const mockDoc = TypeMoq.Mock.ofType<TextDocument>();
const processService = TypeMoq.Mock.ofType<ProcessService>();
processService.setup((d: any) => d.then).returns(() => undefined);
mockDoc.setup((d: any) => d.then).returns(() => undefined);
mockDoc.setup((d) => d.lineCount).returns(() => 10);
mockDoc.setup((d) => d.getText(TypeMoq.It.isAny())).returns(() => 'Hello');
mockDoc.setup((d) => d.isDirty).returns(() => true);
mockDoc.setup((d) => d.uri).returns(() => uri);
documentManager
.setup((d) => d.openTextDocument(TypeMoq.It.isValue(uri)))
.returns(() => Promise.resolve(mockDoc.object));
pythonSettings
.setup((s) => s.sortImports)
.returns(() => {
return ({ path: 'CUSTOM_ISORT', args: [] } as any) as ISortImportSettings;
});
processServiceFactory
.setup((p) => p.create(TypeMoq.It.isAny()))
.returns(() => Promise.resolve(processService.object));
const result = new WorkspaceEdit();
editorUtils
.setup((e) =>
e.getWorkspaceEditsFromPatch(
TypeMoq.It.isValue('Hello'),
TypeMoq.It.isValue('DIFF'),
TypeMoq.It.isAny(),
),
)
.returns(() => result);
// ----------------------Run the command once----------------------
let firstSubscriber: Subscriber<Output<string>>;
const firstProcessResult = createDeferred<Output<string> | undefined>();
const stdinStream1 = TypeMoq.Mock.ofType<Writable>();
stdinStream1.setup((s) => s.write('Hello'));
stdinStream1
.setup((s) => s.end())
.callback(async () => {
// Wait until the process has returned with results
const processResult = await firstProcessResult.promise;
firstSubscriber.next(processResult);
firstSubscriber.complete();
})
.verifiable(TypeMoq.Times.once());
const firstChildProcess = TypeMoq.Mock.ofType<ChildProcess>();
firstChildProcess.setup((p) => p.stdin).returns(() => stdinStream1.object);
const firstExecutionResult = {
proc: firstChildProcess.object,
out: new Observable<Output<string>>((subscriber) => (firstSubscriber = subscriber)),
dispose: noop,
};
processService
.setup((p) => p.execObservable(TypeMoq.It.isValue('CUSTOM_ISORT'), TypeMoq.It.isAny(), TypeMoq.It.isAny()))
.returns(() => firstExecutionResult);
// The first execution isn't immediately resolved, so don't wait on the promise
const firstExecutionDeferred = createDeferredFromPromise(sortProvider.provideDocumentSortImportsEdits(uri));
// Yield control to the first execution, so all the mock setups are used.
await sleep(1);
// ----------------------Run the command again----------------------
let secondSubscriber: Subscriber<Output<string>>;
const stdinStream2 = TypeMoq.Mock.ofType<Writable>();
stdinStream2.setup((s) => s.write('Hello'));
stdinStream2
.setup((s) => s.end())
.callback(() => {
// The second process immediately returns with results
secondSubscriber.next({ source: 'stdout', out: 'DIFF' });
secondSubscriber.complete();
})
.verifiable(TypeMoq.Times.once());
const secondChildProcess = TypeMoq.Mock.ofType<ChildProcess>();
secondChildProcess.setup((p) => p.stdin).returns(() => stdinStream2.object);
const secondExecutionResult = {
proc: secondChildProcess.object,
out: new Observable<Output<string>>((subscriber) => (secondSubscriber = subscriber)),
dispose: noop,
};
processService.reset();
processService.setup((d: any) => d.then).returns(() => undefined);
processService
.setup((p) => p.execObservable(TypeMoq.It.isValue('CUSTOM_ISORT'), TypeMoq.It.isAny(), TypeMoq.It.isAny()))
.returns(() => secondExecutionResult);
// // The second execution should immediately return with results
let edit = await sortProvider.provideDocumentSortImportsEdits(uri);
// ----------------------Verify results----------------------
expect(edit).to.be.equal(result, 'Second execution result is incorrect');
expect(firstExecutionDeferred.completed).to.equal(false, "The first execution shouldn't finish yet");
stdinStream2.verifyAll();
// The first process returns with results
firstProcessResult.resolve({ source: 'stdout', out: 'DIFF' });
edit = await firstExecutionDeferred.promise;
expect(edit).to.be.equal(undefined, 'The results from the first execution should be discarded');
stdinStream1.verifyAll();
});
test('If isort raises a warning message related to isort5 upgrade guide, show message', async () => {
const _showWarningAndOptionallyShowOutput = sinon.stub(
SortImportsEditingProvider.prototype,
'_showWarningAndOptionallyShowOutput',
);
_showWarningAndOptionallyShowOutput.resolves();
const uri = Uri.file('something.py');
const mockDoc = TypeMoq.Mock.ofType<TextDocument>();
const processService = TypeMoq.Mock.ofType<ProcessService>();
processService.setup((d: any) => d.then).returns(() => undefined);
mockDoc.setup((d: any) => d.then).returns(() => undefined);
mockDoc.setup((d) => d.lineCount).returns(() => 10);
mockDoc.setup((d) => d.getText(TypeMoq.It.isAny())).returns(() => 'Hello');
mockDoc.setup((d) => d.isDirty).returns(() => true);
mockDoc.setup((d) => d.uri).returns(() => uri);
documentManager
.setup((d) => d.openTextDocument(TypeMoq.It.isValue(uri)))
.returns(() => Promise.resolve(mockDoc.object));
pythonSettings
.setup((s) => s.sortImports)
.returns(() => {
return ({ path: 'CUSTOM_ISORT', args: [] } as any) as ISortImportSettings;
});
processServiceFactory
.setup((p) => p.create(TypeMoq.It.isAny()))
.returns(() => Promise.resolve(processService.object));
const result = new WorkspaceEdit();
editorUtils
.setup((e) =>
e.getWorkspaceEditsFromPatch(
TypeMoq.It.isValue('Hello'),
TypeMoq.It.isValue('DIFF'),
TypeMoq.It.isAny(),
),
)
.returns(() => result);
// ----------------------Run the command----------------------
let subscriber: Subscriber<Output<string>>;
const stdinStream = TypeMoq.Mock.ofType<Writable>();
stdinStream.setup((s) => s.write('Hello'));
stdinStream
.setup((s) => s.end())
.callback(() => {
subscriber.next({ source: 'stdout', out: 'DIFF' });
subscriber.next({ source: 'stderr', out: 'Some warning related to isort5 (W0503)' });
subscriber.complete();
})
.verifiable(TypeMoq.Times.once());
const childProcess = TypeMoq.Mock.ofType<ChildProcess>();
childProcess.setup((p) => p.stdin).returns(() => stdinStream.object);
const executionResult = {
proc: childProcess.object,
out: new Observable<Output<string>>((s) => (subscriber = s)),
dispose: noop,
};
processService.reset();
processService.setup((d: any) => d.then).returns(() => undefined);
processService
.setup((p) => p.execObservable(TypeMoq.It.isValue('CUSTOM_ISORT'), TypeMoq.It.isAny(), TypeMoq.It.isAny()))
.returns(() => executionResult);
const edit = await sortProvider.provideDocumentSortImportsEdits(uri);
// ----------------------Verify results----------------------
expect(edit).to.be.equal(result, 'Execution result is incorrect');
assert.ok(_showWarningAndOptionallyShowOutput.calledOnce);
stdinStream.verifyAll();
});
test('If user clicks show output on the isort5 warning prompt, show the Python output', async () => {
const neverShowAgain = TypeMoq.Mock.ofType<IPersistentState<boolean>>();
persistentStateFactory
.setup((p) => p.createGlobalPersistentState(TypeMoq.It.isAny(), false))
.returns(() => neverShowAgain.object);
neverShowAgain.setup((p) => p.value).returns(() => false);
shell
.setup((s) =>
s.showWarningMessage(
Diagnostics.checkIsort5UpgradeGuide(),
Common.openOutputPanel(),
Common.doNotShowAgain(),
),
)
.returns(() => Promise.resolve(Common.openOutputPanel()));
output.setup((o) => o.show(true)).verifiable(TypeMoq.Times.once());
await sortProvider._showWarningAndOptionallyShowOutput();
output.verifyAll();
});
test('If user clicks do not show again on the isort5 warning prompt, do not show the prompt again', async () => {
const neverShowAgain = TypeMoq.Mock.ofType<IPersistentState<boolean>>();
persistentStateFactory
.setup((p) => p.createGlobalPersistentState(TypeMoq.It.isAny(), false))
.returns(() => neverShowAgain.object);
let doNotShowAgainValue = false;
neverShowAgain.setup((p) => p.value).returns(() => doNotShowAgainValue);
neverShowAgain
.setup((p) => p.updateValue(true))
.returns(() => {
doNotShowAgainValue = true;
return Promise.resolve();
});
shell
.setup((s) =>
s.showWarningMessage(
Diagnostics.checkIsort5UpgradeGuide(),
Common.openOutputPanel(),
Common.doNotShowAgain(),
),
)
.returns(() => Promise.resolve(Common.doNotShowAgain()))
.verifiable(TypeMoq.Times.once());
await sortProvider._showWarningAndOptionallyShowOutput();
shell.verifyAll();
await sortProvider._showWarningAndOptionallyShowOutput();
await sortProvider._showWarningAndOptionallyShowOutput();
shell.verifyAll();
});
}); | the_stack |
import {
$Object,
} from '../types/object.js';
import {
Realm,
ExecutionContext,
} from '../realm.js';
import {
$Function,
$BuiltinFunction,
} from '../types/function.js';
import {
$PropertyKey,
$AnyNonEmpty,
$AnyNonEmptyNonError,
$AnyObject,
CompletionType,
} from '../types/_shared.js';
import {
$EnvRec,
} from '../types/environment-record.js';
import {
$CreateDataProperty,
$DefinePropertyOrThrow,
$HasOwnProperty,
$Set,
} from '../operations.js';
import {
$String,
} from '../types/string.js';
import {
$PropertyDescriptor,
$IsDataDescriptor,
} from '../types/property-descriptor.js';
import {
$Number,
} from '../types/number.js';
import {
$Undefined,
} from '../types/undefined.js';
import {
$Boolean,
} from '../types/boolean.js';
import {
$Error,
} from '../types/error.js';
import {
$ParameterDeclaration,
} from '../ast/functions.js';
import {
getBoundNames,
} from '../ast/_shared.js';
import {
$List,
} from '../types/list.js';
// http://www.ecma-international.org/ecma-262/#sec-arguments-exotic-objects
export class $ArgumentsExoticObject extends $Object<'ArgumentsExoticObject'> {
public readonly '[[ParameterMap]]': $AnyObject;
// http://www.ecma-international.org/ecma-262/#sec-createmappedargumentsobject
// 9.4.4.7 CreateMappedArgumentsObject ( func , formals , argumentsList , env )
public constructor(
realm: Realm,
func: $Function,
formals: readonly $ParameterDeclaration[],
argumentsList: readonly $AnyNonEmpty [],
env: $EnvRec,
) {
const intrinsics = realm['[[Intrinsics]]'];
super(realm, 'ArgumentsExoticObject', intrinsics['%ObjectPrototype%'], CompletionType.normal, intrinsics.empty);
const ctx = realm.stack.top;
// 1. Assert: formals does not contain a rest parameter, any binding patterns, or any initializers. It may contain duplicate identifiers.
// 2. Let len be the number of elements in argumentsList.
const len = argumentsList.length;
// 3. Let obj be a newly created arguments exotic object with a [[ParameterMap]] internal slot.
// 4. Set obj.[[GetOwnProperty]] as specified in 9.4.4.1.
// 5. Set obj.[[DefineOwnProperty]] as specified in 9.4.4.2.
// 6. Set obj.[[Get]] as specified in 9.4.4.3.
// 7. Set obj.[[Set]] as specified in 9.4.4.4.
// 8. Set obj.[[Delete]] as specified in 9.4.4.5.
// 9. Set the remainder of obj's essential internal methods to the default ordinary object definitions specified in 9.1.
// 10. Set obj.[[Prototype]] to %ObjectPrototype%.
// 11. Set obj.[[Extensible]] to true.
// 12. Let map be ObjectCreate(null).
const map = new $Object(realm, '[[ParameterMap]]', intrinsics.null, CompletionType.normal, intrinsics.empty);
// 13. Set obj.[[ParameterMap]] to map.
this['[[ParameterMap]]'] = map;
// 14. Let parameterNames be the BoundNames of formals.
const parameterNames = formals.flatMap(getBoundNames);
// 15. Let numberOfParameters be the number of elements in parameterNames.
const numberOfParameters = parameterNames.length;
// 16. Let index be 0.
let index = 0;
// 17. Repeat, while index < len,
while (index < len) {
// 17. a. Let val be argumentsList[index].
const val = argumentsList[index];
// 17. b. Perform CreateDataProperty(obj, ! ToString(index), val).
$CreateDataProperty(ctx, this, new $String(realm, index.toString()), val);
// 17. c. Increase index by 1.
++index;
}
// 18. Perform DefinePropertyOrThrow(obj, "length", PropertyDescriptor { [[Value]]: len, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
const desc = new $PropertyDescriptor(realm, intrinsics.length);
desc['[[Value]]'] = new $Number(realm, len);
// 19. Let mappedNames be a new empty List.
const mappedNames = [] as $String[];
// 20. Let index be numberOfParameters - 1.
index = numberOfParameters - 1;
// 21. Repeat, while index ≥ 0,
while (index >= 0) {
// 21. a. Let name be parameterNames[index].
const name = parameterNames[index];
// 21. b. If name is not an element of mappedNames, then
if (!mappedNames.some(x => x.is(name))) {
// 21. b. i. Add name as an element of the list mappedNames.
mappedNames.push(name);
// 21. b. ii. If index < len, then
if (index < len) {
// 21. b. ii. 1. Let g be MakeArgGetter(name, env).
const g = new $ArgGetter(realm, name, env);
// 21. b. ii. 2. Let p be MakeArgSetter(name, env).
const p = new $ArgSetter(realm, name, env);
// 21. b. ii. 3. Perform map.[[DefineOwnProperty]](! ToString(index), PropertyDescriptor { [[Set]]: p, [[Get]]: g, [[Enumerable]]: false, [[Configurable]]: true }).
const desc = new $PropertyDescriptor(
realm,
new $String(realm, index.toString()),
{
'[[Set]]': p,
'[[Get]]': g,
'[[Enumerable]]': intrinsics.false,
'[[Configurable]]': intrinsics.true,
},
);
map['[[DefineOwnProperty]]'](ctx, desc.name, desc);
}
}
// 21. c. Decrease index by 1.
--index;
}
// 22. Perform ! DefinePropertyOrThrow(obj, @@iterator, PropertyDescriptor { [[Value]]: %ArrayProto_values%, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
const iteratorDesc = new $PropertyDescriptor(
realm,
intrinsics['@@iterator'],
{
'[[Value]]': intrinsics['%ArrayProto_values%'],
'[[Writable]]': intrinsics.true,
'[[Enumerable]]': intrinsics.false,
'[[Configurable]]': intrinsics.true,
},
);
$DefinePropertyOrThrow(ctx, this, iteratorDesc.name, iteratorDesc);
// 23. Perform ! DefinePropertyOrThrow(obj, "callee", PropertyDescriptor { [[Value]]: func, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
const calleeDesc = new $PropertyDescriptor(
realm,
intrinsics.$callee,
{
'[[Value]]': func,
'[[Writable]]': intrinsics.true,
'[[Enumerable]]': intrinsics.false,
'[[Configurable]]': intrinsics.true,
},
);
$DefinePropertyOrThrow(ctx, this, calleeDesc.name, calleeDesc);
// 24. Return obj.
}
// http://www.ecma-international.org/ecma-262/#sec-arguments-exotic-objects-getownproperty-p
// 9.4.4.1 [[GetOwnProperty]] ( P )
public '[[GetOwnProperty]]'(
ctx: ExecutionContext,
P: $PropertyKey,
): $PropertyDescriptor | $Undefined {
// 1. Let args be the arguments object.
// 2. Let desc be OrdinaryGetOwnProperty(args, P).
const desc = super['[[GetOwnProperty]]'](ctx, P) as $PropertyDescriptor | $Undefined;
// 3. If desc is undefined, return desc.
if (desc.isUndefined) {
return desc;
}
// 4. Let map be args.[[ParameterMap]].
const map = this['[[ParameterMap]]'];
// 5. Let isMapped be ! HasOwnProperty(map, P).
const isMapped = ($HasOwnProperty(ctx, map, P) as $Boolean).isTruthy;
// 6. If isMapped is true, then
if (isMapped) {
// 6. a. Set desc.[[Value]] to Get(map, P).
desc['[[Value]]'] = map['[[Get]]'](ctx, P, map) as $AnyNonEmpty;
}
// 7. Return desc.
return desc;
}
// http://www.ecma-international.org/ecma-262/#sec-arguments-exotic-objects-defineownproperty-p-desc
// 9.4.4.2 [[DefineOwnProperty]] ( P , Desc )
public '[[DefineOwnProperty]]'(
ctx: ExecutionContext,
P: $PropertyKey,
Desc: $PropertyDescriptor,
): $Boolean | $Error {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. Let args be the arguments object.
// 2. Let map be args.[[ParameterMap]].
const map = this['[[ParameterMap]]'];
// 3. Let isMapped be HasOwnProperty(map, P).
const isMapped = ($HasOwnProperty(ctx, map, P) as $Boolean).isTruthy;
// 4. Let newArgDesc be Desc.
let newArgDesc = Desc;
// 5. If isMapped is true and IsDataDescriptor(Desc) is true, then
if (isMapped && $IsDataDescriptor(Desc)) {
// 5. a. If Desc.[[Value]] is not present and Desc.[[Writable]] is present and its value is false, then
if (Desc['[[Value]]'].isEmpty && Desc['[[Writable]]'].hasValue && Desc['[[Writable]]'].isFalsey) {
// 5. a. i. Set newArgDesc to a copy of Desc.
newArgDesc = new $PropertyDescriptor(
Desc.realm,
Desc.name,
{
// 5. a. ii. Set newArgDesc.[[Value]] to Get(map, P).
'[[Value]]': map['[[Get]]'](ctx, P, map) as $AnyNonEmpty,
'[[Writable]]': Desc['[[Writable]]'],
'[[Enumerable]]': Desc['[[Enumerable]]'],
'[[Configurable]]': Desc['[[Configurable]]'],
},
);
}
}
// 6. Let allowed be ? OrdinaryDefineOwnProperty(args, P, newArgDesc).
const allowed = super['[[DefineOwnProperty]]'](ctx, P, newArgDesc);
if (allowed.isAbrupt) { return allowed; }
// 7. If allowed is false, return false.
if (allowed.isFalsey) {
return allowed;
}
// 8. If isMapped is true, then
if (isMapped) {
// 8. a. If IsAccessorDescriptor(Desc) is true, then
if (Desc.isAccessorDescriptor) {
// 8. a. i. Call map.[[Delete]](P).
map['[[Delete]]'](ctx, P);
}
}
// 8. b. Else,
else {
// 8. b. i. If Desc.[[Value]] is present, then
if (Desc['[[Value]]'].hasValue) {
// 8. b. i. 1. Let setStatus be Set(map, P, Desc.[[Value]], false).
const setStatus = $Set(ctx, map, P, Desc['[[Value]]'], intrinsics.false);
// 8. b. i. 2. Assert: setStatus is true because formal parameters mapped by argument objects are always writable.
// 8. b. ii. If Desc.[[Writable]] is present and its value is false, then
if (Desc['[[Writable]]'].hasValue && Desc['[[Writable]]'].isFalsey) {
// 8. b. ii. 1. Call map.[[Delete]](P).
map['[[Delete]]'](ctx, P);
}
}
}
// 9. Return true.
return intrinsics.true;
}
// http://www.ecma-international.org/ecma-262/#sec-arguments-exotic-objects-get-p-receiver
// 9.4.4.3 [[Get]] ( P , Receiver )
public '[[Get]]'(
ctx: ExecutionContext,
P: $PropertyKey,
Receiver: $AnyObject,
): $AnyNonEmpty {
// 1. Let args be the arguments object.
// 2. Let map be args.[[ParameterMap]].
const map = this['[[ParameterMap]]'];
// 3. Let isMapped be ! HasOwnProperty(map, P).
const isMapped = ($HasOwnProperty(ctx, map, P) as $Boolean).isTruthy;
// 4. If isMapped is false, then
if (!isMapped) {
// 4. a. Return ? OrdinaryGet(args, P, Receiver).
return super['[[Get]]'](ctx, P, Receiver);
}
// 5. Else map contains a formal parameter mapping for P,
else {
// 5. a. Return Get(map, P).
return map['[[Get]]'](ctx, P, map);
}
}
// http://www.ecma-international.org/ecma-262/#sec-arguments-exotic-objects-set-p-v-receiver
// 9.4.4.4 [[Set]] ( P , V , Receiver )
public '[[Set]]'(
ctx: ExecutionContext,
P: $PropertyKey,
V: $AnyNonEmpty ,
Receiver: $AnyObject,
): $Boolean | $Error {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. Let args be the arguments object.
// 2. If SameValue(args, Receiver) is false, then
// 2. a. Let isMapped be false.
// 3. Else,
// 3. a. Let map be args.[[ParameterMap]].
// 3. b. Let isMapped be ! HasOwnProperty(map, P).
// 4. If isMapped is true, then
// 4. a. Let setStatus be Set(map, P, V, false).
// 4. b. Assert: setStatus is true because formal parameters mapped by argument objects are always writable.
// 5. Return ? OrdinarySet(args, P, V, Receiver).
if (this.is(Receiver)) {
const map = this['[[ParameterMap]]'];
const isMapped = ($HasOwnProperty(ctx, map, P) as $Boolean).isTruthy;
if (isMapped) {
const setStatus = $Set(ctx, map, P, V, intrinsics.false);
}
}
return super['[[Set]]'](ctx, P, V, Receiver);
}
// http://www.ecma-international.org/ecma-262/#sec-arguments-exotic-objects-delete-p
// 9.4.4.5 [[Delete]] ( P )
public '[[Delete]]'(
ctx: ExecutionContext,
P: $PropertyKey,
): $Boolean | $Error {
// 1. Let args be the arguments object.
// 2. Let map be args.[[ParameterMap]].
const map = this['[[ParameterMap]]'];
// 3. Let isMapped be ! HasOwnProperty(map, P).
const isMapped = ($HasOwnProperty(ctx, map, P) as $Boolean).isTruthy;
// 4. Let result be ? OrdinaryDelete(args, P).
const result = super['[[Delete]]'](ctx, P);
if (result.isAbrupt) { return result; }
// 5. If result is true and isMapped is true, then
if (result.isTruthy && isMapped) {
// 5. a. Call map.[[Delete]](P).
map['[[Delete]]'](ctx, P);
}
// 6. Return result.
return result;
}
}
// http://www.ecma-international.org/ecma-262/#sec-makearggetter
export class $ArgGetter extends $BuiltinFunction {
public readonly '[[Name]]': $String;
public readonly '[[Env]]': $EnvRec;
public constructor(
realm: Realm,
name: $String,
env: $EnvRec,
) {
super(realm, 'ArgGetter', realm['[[Intrinsics]]']['%FunctionPrototype%']);
// 3. Set getter.[[Name]] to name.
this['[[Name]]'] = name;
// 4. Set getter.[[Env]] to env.
this['[[Env]]'] = env;
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
argumentsList: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. Let f be the active function object.
// 2. Let name be f.[[Name]].
const name = this['[[Name]]'];
// 3. Let env be f.[[Env]].
const env = this['[[Env]]'];
// 4. Return env.GetBindingValue(name, false).
return env.GetBindingValue(ctx, name, intrinsics.false);
}
}
// http://www.ecma-international.org/ecma-262/#sec-makeargsetter
export class $ArgSetter extends $BuiltinFunction {
public readonly '[[Name]]': $String;
public readonly '[[Env]]': $EnvRec;
public constructor(
realm: Realm,
name: $String,
env: $EnvRec,
) {
super(realm, 'ArgSetter', realm['[[Intrinsics]]']['%FunctionPrototype%']);
// 3. Set getter.[[Name]] to name.
this['[[Name]]'] = name;
// 4. Set getter.[[Env]] to env.
this['[[Env]]'] = env;
}
public performSteps(
ctx: ExecutionContext,
thisArgument: $AnyNonEmptyNonError,
[value]: $List<$AnyNonEmpty>,
NewTarget: $Function | $Undefined,
): $AnyNonEmpty {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. Let f be the active function object.
// 2. Let name be f.[[Name]].
const name = this['[[Name]]'];
// 3. Let env be f.[[Env]].
const env = this['[[Env]]'];
// 4. Return env.SetMutableBinding(name, value, false).
return env.SetMutableBinding(ctx, name, value, intrinsics.false) as $AnyNonEmpty; // TODO: we probably need to change the signature of performSteps to return $Any but that may open a new can of worms, so leave it for now and revisit when we're further down the road and implemented more natives
}
}
// http://www.ecma-international.org/ecma-262/#sec-createunmappedargumentsobject
export function $CreateUnmappedArgumentsObject(
ctx: ExecutionContext,
argumentsList: readonly $AnyNonEmpty [],
): $AnyObject {
const realm = ctx.Realm;
const intrinsics = realm['[[Intrinsics]]'];
// 1. Let len be the number of elements in argumentsList.
const len = argumentsList.length;
// 2. Let obj be ObjectCreate(%ObjectPrototype%, « [[ParameterMap]] »).
const obj = $Object.ObjectCreate(
ctx,
'UnmappedArgumentsObject',
intrinsics['%ObjectPrototype%'],
{
'[[ParameterMap]]': intrinsics.undefined,
},
);
// 3. Set obj.[[ParameterMap]] to undefined.
// 4. Perform DefinePropertyOrThrow(obj, "length", PropertyDescriptor { [[Value]]: len, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
$DefinePropertyOrThrow(
ctx,
obj,
intrinsics.length,
new $PropertyDescriptor(
realm,
intrinsics.length,
{
'[[Value]]': new $Number(realm, len),
'[[Writable]]': intrinsics.true,
'[[Enumerable]]': intrinsics.false,
'[[Configurable]]': intrinsics.true,
},
),
);
// 5. Let index be 0.
let index = 0;
// 6. Repeat, while index < len,
while (index < len) {
// 6. a. Let val be argumentsList[index].
const val = argumentsList[index];
// 6. b. Perform CreateDataProperty(obj, ! ToString(index), val).
$CreateDataProperty(ctx, obj, new $String(realm, index.toString()), val);
// 6. c. Increase index by 1.
++index;
}
// 7. Perform ! DefinePropertyOrThrow(obj, @@iterator, PropertyDescriptor { [[Value]]: %ArrayProto_values%, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }).
$DefinePropertyOrThrow(
ctx,
obj,
intrinsics['@@iterator'],
new $PropertyDescriptor(
realm,
intrinsics['@@iterator'],
{
'[[Value]]': intrinsics['%ArrayProto_values%'],
'[[Writable]]': intrinsics.true,
'[[Enumerable]]': intrinsics.false,
'[[Configurable]]': intrinsics.true,
},
),
);
// 8. Perform ! DefinePropertyOrThrow(obj, "callee", PropertyDescriptor { [[Get]]: %ThrowTypeError%, [[Set]]: %ThrowTypeError%, [[Enumerable]]: false, [[Configurable]]: false }).
$DefinePropertyOrThrow(
ctx,
obj,
intrinsics.$callee,
new $PropertyDescriptor(
realm,
intrinsics.$callee,
{
'[[Get]]': intrinsics['%ThrowTypeError%'],
'[[Set]]': intrinsics['%ThrowTypeError%'],
'[[Enumerable]]': intrinsics.false,
'[[Configurable]]': intrinsics.false,
},
),
);
// 9. Return obj.
return obj;
} | the_stack |
import { ViewChild, Renderer2, EventEmitter, Output, Component, OnInit, Input, Inject, Injectable } from '@angular/core';
import { NgModel } from '@angular/forms';
import { ConfigService } from './config.service';
import { VmdirService } from './vmdir.service';
import { VmdirUtils } from './vmdir.utils';
import { VmdirSchemaService } from './vmdirschema.service';
import { AuthService } from './auth.service';
import { UtilsService } from './utils.service';
import { Routes, RouterModule } from '@angular/router';
import { DOCUMENT } from '@angular/platform-browser';
import { Observable } from "rxjs/Rx";
import { SdeditorComponent } from './sdeditor.component';
import { AttributeFilter } from './customstringfilter';
interface AttribSchema {
attrType:string;
value:string;
}
@Component({
moduleId: module.id,
selector: 'vmdir',
templateUrl: './vmdir.component.html',
})
export class VmdirComponent {
private error:any = '';
listing: string;
listingObj: any;
setDate: any;
schema: string;
schemaObj: any;
errorMsg:string;
aclString:string;
cardHeight:number;
treeHeight:number;
containerHeight:number;
datagridHeight:number;
isEdited:any;
isAddObject:any;
isDateEdited:boolean;
showErrorAlert: boolean;
showSignPost: boolean;
isSdEdited: boolean;
noUpdatesYet: boolean;
confirmDel: boolean;
mustAttrFilter: AttributeFilter = new AttributeFilter();
mayAttrFilter: AttributeFilter = new AttributeFilter();
showSuccessAlert: boolean;
isListEdited: boolean;
attribs: string;
curSchema: string;
curSchemaValue: string[];
confirm: boolean;
attribsMap:Map<string, any>;
attribsMapCopy:any;
schemaMap:Map<string, any>;
defaultActive = 'true';
attribsArr: any[];
schemaMayAttribsArr: any[];
schemaMustAttribsArr: any[];
usersArr: any[];
groupsArr: any[];
signPostObj:any[];
curSchemaMap:Map<string, any>;
setSchemaMustAttribsArr:any[];
setSchemaMayAttribsArr:any[];
rootDN:string;
encodedRootDN:string;
updatedAttributes:Map<string,any>;
updatedAttributesArr:any[];
selectedDN:string;
header:string;
@ViewChild('vmdirForm') formReq: any;
constructor(private renderer:Renderer2, private configService: ConfigService, private utilsService: UtilsService, private vmdirUtils: VmdirUtils, @Inject(DOCUMENT) private document: any, private vmdirSchemaService: VmdirSchemaService, private vmdirService: VmdirService, private authService: AuthService) {
console.log("App component - vmdir");
this.isEdited = false;
this.confirm = false;
this.confirmDel = false;
this.showErrorAlert = false;
this.showSuccessAlert = false;
this.isListEdited = false;
this.isSdEdited = false;
this.isDateEdited = false;
this.showSignPost = false;
}
ngOnInit() {
this.attribsMap = new Map<string,any[]>();
this.updatedAttributes = new Map<string,any[]>();
this.schemaMap = new Map<string,any[]>();
this.curSchemaMap = new Map<string, any>();
this.schemaMayAttribsArr = new Array<AttribSchema>();
this.schemaMustAttribsArr = new Array<AttribSchema>();
this.setSchemaMustAttribsArr = new Array<AttribSchema>();
this.setSchemaMayAttribsArr = new Array<AttribSchema>();
this.usersArr = new Array<any>();
this.groupsArr = new Array<any>();
this.getDirListing();
this.rootDN = this.authService.getRootDN();
this.encodedRootDN = encodeURIComponent(this.rootDN);
this.header = this.rootDN;
this.getRootAttributes();
this.containerHeight = (90/100*window.innerHeight);
this.cardHeight = (85/100*this.containerHeight);
this.datagridHeight = (90/100*this.cardHeight);
this.treeHeight = (80/100*this.containerHeight);
}
getRootAttributes(){
this.selectedDN = this.authService.getRootDnQuery();
this.getAttributes();
}
onSdNotify(message:string){
this.isSdEdited = false;
this.getACLString();
}
onAddNotify(message:string){
this.isAddObject = false;
}
prepareUpdatedAttributesList() {
let result;
this.noUpdatesYet = true;
this.updatedAttributes = new Map<string, any>();
// find dirty input fields
for (let attr of this.setSchemaMayAttribsArr) {// test if original values are different from new values
// test if a value exists originally
if(this.attribsMapCopy[attr.attrType] ){
let origValue = this.attribsMapCopy[attr.attrType].toString();
let newValue = attr.value.toString();
if(origValue != newValue){
this.updatedAttributes[attr.attrType] = attr;
}
}else if(attr.value && attr.value.toString().length > 0){
this.updatedAttributes[attr.attrType] = attr;
}
}
for (let attr of this.setSchemaMustAttribsArr) {// test if original values are different from new values
if(this.attribsMapCopy[attr.attrType] ){
let origValue = this.attribsMapCopy[attr.attrType].toString();
let newValue = attr.value.toString();
if(origValue != newValue){
this.updatedAttributes[attr.attrType] = attr;
}
}else{
this.updatedAttributes[attr.attrType] = attr;
}
}
this.updatedAttributesArr = Object.keys(this.updatedAttributes);
if(this.updatedAttributesArr.length > 0) {
this.noUpdatesYet = false;
}
console.log(this.updatedAttributesArr);
}
handleEdit(){
this.setSchemaMustAttribsArr = this.setSchemaMustAttribsArr.concat(this.schemaMustAttribsArr);
this.setSchemaMayAttribsArr = this.setSchemaMayAttribsArr.concat(this.schemaMayAttribsArr);
}
handleUpdateError(error) {
console.log(error);
this.errorMsg = "Unknown error";
if(error.error_message) {
this.errorMsg = error.error_message;
}
this.showErrorAlert = true;
}
handleDateUpdate(){
console.log(this.setDate);
let dateStr = this.setDate.toISOString();
dateStr = dateStr.replace(/[-:T]/g, '');
if(this.formReq) {
this.formReq['controls'][this.curSchema].setValue(dateStr);
}
}
updateView(valueArr:any[]) {
let l:number = valueArr.length;
if(l > 0 && valueArr[l-1].length == 0){
valueArr.pop();
}
if(this.document.getElementById(this.curSchema).value != this.curSchemaValue.toString()){
this.formReq.form.markAsDirty();
}
this.document.getElementById(this.curSchema).value = this.curSchemaValue;
this.isListEdited = false;
}
trackByFn(index: any, item: any) {
return index;
}
handleListEditCompletion(valueArr:string[]){
console.log(valueArr);
}
submitAttributeUpdates(){
let result;
this.vmdirService.updateAttributes(this.selectedDN, this.attribsMapCopy, this.updatedAttributesArr, this.updatedAttributes, this.schemaMap)
.subscribe(
result => {
console.log(result);
this.getAttributes();
this.isEdited = false;
},
error => {
this.handleUpdateError(error);
});
}
handleListAdd(array:string[]) {
let l:number = array.length;
if((l > 0 && array[l-1].length > 0) || l == 0){
array.push('');
}
}
handleListRemoval(valArray:string[], index:number){
valArray.splice(index, 1);
}
onChildSelected(childDN:string) {
console.log(childDN);
this.selectedDN = childDN;
this.header = decodeURIComponent(this.selectedDN);
this.getAttributes();
}
displayProperties(attrType:string, attrValue:any) {
this.curSchema = attrType;
this.getSchema(attrType, true, attrValue);
}
constructAttribsMap(attribsArr:any[]){
this.attribsMap = new Map<string, any>();
let id = 0;
for (let attr of attribsArr){
if(attr.type == 'objectClass') {
attr.value.push('top');
}
if(attr.type == 'nTSecurityDescriptor'){
attribsArr.splice(id, 1);
}
if(attr.type.includes('TimeStamp')){
if(attr.value && attr.value[0]){
let dateObj = new Date(this.utilsService.toValidTimeStr(attr.value[0]));
attr.value = [dateObj.toString()];
}
}
this.attribsMap[attr.type] = attr.value;
id ++;
}
console.log(this.attribsMap);
}
/* store the schema(single or multi valued) for updated fields and use it while submitting changes*/
storeSchema(cn:string) {
if(!this.schemaMap[cn]) {
for(let schema of this.signPostObj) {
this.curSchemaMap[schema.type] = schema.value;
}
this.schemaMap[cn] = this.signPostObj[0]
console.log(this.schemaMap);
}
}
getAttributes() {
this.formReq.form.markAsPristine();
this.updatedAttributes = new Map<string,any>();
this.updatedAttributesArr = [];
this.schemaMap.clear();
this.showSuccessAlert = false;
this.isEdited = false;
this.showErrorAlert = false;
let attribsObj:any;
this.header = decodeURIComponent(this.selectedDN);
this.vmdirService.getAttributes(this.selectedDN)
.subscribe(
attribs => {
this.attribs = JSON.stringify(attribs);
attribsObj = JSON.parse(this.attribs);
//this.Attributes(this.listingObj.attributes);
console.log(attribsObj.result[0].attributes);
this.attribsArr = attribsObj.result[0].attributes;
this.constructAttribsMap(this.attribsArr);
this.getAllSchemas();
},
error => this.error = <any>error);
this.getACLString();
}
getACLString() {
let sddlString:string = '';
let sddlObj:any;
this.vmdirService.getACLString(this.selectedDN)
.subscribe(
aclstring => {
sddlString = JSON.stringify(aclstring);
sddlObj = JSON.parse(sddlString).result[0];
console.log(sddlObj);
this.aclString = sddlObj.attributes[0].value[0];
console.log(this.aclString);
});
}
deleteEntry() {
console.log(this.selectedDN);
this.vmdirService.delete(this.selectedDN)
.subscribe(
result => {
console.log(result);
this.getDirListing();
/* refresh the directory tree at parent ?*/
},
error => this.error = <any>error);
}
getAllSchemas() {
this.schemaMustAttribsArr = [];
this.schemaMayAttribsArr = [];
this.setSchemaMustAttribsArr = [];
this.setSchemaMayAttribsArr = [];
for (let schemaType of this.attribsMap['objectClass']) {
this.getSchema(schemaType, false, [])
}
this.attribsMapCopy = JSON.parse(JSON.stringify(this.attribsMap));
}
deduplicateArray(arr: any[]) {
for(var i=0; i<arr.length; ++i) {
for(var j=i+1; j<arr.length; ++j) {
if(arr[i].attrType === arr[j].attrType) {
arr.splice(j--, 1);
}
}
}
}
constructSchemaAttribsArr(attributes:any[]) {
for(let attr of attributes){
if (attr.type == 'mayContain' || attr.type == 'systemMayContain') {
for (var i = 0; i < attr.value.length; i ++) {
let o:any = {};
o.attrType = attr.value[i];
if(this.attribsMap[o.attrType]) {
o.value = this.attribsMap[o.attrType];
this.setSchemaMayAttribsArr.push(o);
}
else {
o.value = [];
this.schemaMayAttribsArr.push(o);
}
}
} else if (attr.type == 'mustContain' || attr.type == 'systemMustContain') {
for (var i = 0; i < attr.value.length; i ++) {
let o:any = {};
o.attrType = attr.value[i];
if(this.attribsMap[o.attrType] && o.attrType != 'nTSecurityDescriptor') {
o.value = this.attribsMap[o.attrType];
this.setSchemaMustAttribsArr.push(o);
}
}
}
}
}
constructSchemaMap(schemaName:string, schemaArr:any[]){
this.curSchemaMap = new Map<string, any>();
for(let schema of schemaArr){
this.curSchemaMap[schema.type] = schema.value;
if(schema.type == 'vmwAttributeUsage'){
if(schema.value >= 8){
this.curSchemaMap['readonly'] = true;
}else{
this.curSchemaMap['readonly'] = false;
}
}
}
this.schemaMap[schemaName] = this.curSchemaMap;
console.log(this.schemaMap);
}
setBooleanElement(schemaName:string){
let selectElem = this.renderer.createElement('select');
let inputElem = this.document.getElementById(schemaName);
inputElem.style.display = 'none';
let parent = inputElem.parentElement;
let optionTrue = this.renderer.createElement('option');
let optionFalse = this.renderer.createElement('option');
this.renderer.setAttribute(optionTrue, "value", "TRUE");
this.renderer.appendChild(optionTrue, this.renderer.createText('true'));
this.renderer.setAttribute(optionFalse, "value", "FALSE");
this.renderer.appendChild(optionFalse, this.renderer.createText('false'));
this.renderer.listen(selectElem, 'change', () => {
if(this.formReq) {
this.formReq['controls'][schemaName].setValue(selectElem.value);
}
});
if(inputElem.value.length == 0){
let optionUnset = this.renderer.createElement('option');
this.renderer.appendChild(selectElem, optionUnset);
}else{
if(inputElem.value == 'FALSE'){
this.renderer.setAttribute(optionFalse, "selected", "selected");
}else if(inputElem.value == 'TRUE'){
this.renderer.setAttribute(optionTrue, "selected", "selected");
}
}
this.renderer.appendChild(selectElem, optionTrue);
this.renderer.appendChild(selectElem, optionFalse);
this.renderer.setAttribute(selectElem, 'value', inputElem.value);
this.renderer.insertBefore(parent, selectElem, inputElem);
console.log(inputElem);
console.log(selectElem);
}
setDateTimeElement(schemaName:string){
let inputElem = this.document.getElementById('dateInput');
inputElem.focus();
}
getSchema(schemaName:string, forSignPost:boolean, schemaValue:any) {
console.log("getScemas - component");
this.schemaMap.clear();
this.vmdirSchemaService.getSchema(schemaName)
.subscribe(
schema => {
this.schema = JSON.stringify(schema);
this.schemaObj = JSON.parse(this.schema);
//this.Attributes(this.listingObj.attributes);
console.log(this.schemaObj);
if(!forSignPost) {
this.constructSchemaAttribsArr(this.schemaObj.result[0].attributes);
this.deduplicateArray(this.schemaMustAttribsArr);
this.deduplicateArray(this.schemaMayAttribsArr);
this.deduplicateArray(this.setSchemaMustAttribsArr);
this.deduplicateArray(this.setSchemaMayAttribsArr);
console.log(this.schemaMayAttribsArr);
console.log(this.schemaMustAttribsArr);
console.log(this.setSchemaMustAttribsArr);
console.log(this.setSchemaMayAttribsArr);
}else{ /* for signPost */
this.signPostObj = this.schemaObj.result[0].attributes;
/* remove stuff that need not be displayed */
this.signPostObj.splice(0, 2);
this.signPostObj.pop();
this.signPostObj.pop();
this.vmdirUtils.setAttributeDataType(this.signPostObj)
this.constructSchemaMap(schemaName, this.signPostObj);
this.showSignPost = true;
/* Handle multi value attributes */
if(this.isEdited && 'FALSE' == this.curSchemaMap['isSingleValued'][0] &&
this.curSchemaMap['readonly'] == false){
this.isListEdited = true;
this.curSchemaValue = schemaValue;
}
/* Handle Boolean Attributes */
if(this.isEdited && 'ADSTYPE_BOOLEAN' == this.curSchemaMap['dataType'] &&
this.curSchemaMap['readonly'] == false){
this.setBooleanElement(schemaName);
}
/* Handle Editing security descriptor */
if(this.isEdited && 'ADSTYPE_NT_SECURITY_DESCRIPTOR' == this.curSchemaMap['dataType']){
this.isSdEdited = true;
this.showSignPost = false;
}
/* Handle Date Tiime attributes */
if(this.isEdited && 'ADSTYPE_UTC_TIME' == this.curSchemaMap['dataType'] &&
this.curSchemaMap['readonly'] == false){
this.isDateEdited = true;
//this.setDateTimeElement(schemaName);
}
console.log(this.signPostObj);
}
},
error => this.error = <any>error);
}
getDirListing() {
console.log("getDirListing - app component");
this.vmdirService.getDirListing(null)
.subscribe(
listing => {
this.listing = JSON.stringify(listing);
this.listingObj = JSON.parse(this.listing);
this.utilsService.extractName(this.listingObj.result, true);
console.log(this.listingObj);
},
error => this.error = <any>error);
}
}
@Component({
moduleId: module.id,
selector: "lazy-loaded-level1",
template: `
<ng-template #loadingChild>
<clr-tree-node>
<div align="center">
<span class="spinner spinner-inline">
Loading...
</span>
<span>
Loading subtree...
</span>
</div>
</clr-tree-node>
</ng-template>
<ng-container [clrLoading]="loading">
<clr-tree-node *ngFor="let commonName of listArr">
<button
(click)="selectedDN=commonName.encodedDN ;getAttributes()"
class="clr-treenode-link">
{{commonName.displayName}}
</button>
<ng-template clrIfExpanded>
<lazy-loaded-level1 [(rootDn)]=commonName.dn (onChildSelected)="onRecChildSelected($event)"></lazy-loaded-level1>
</ng-template>
</clr-tree-node>
</ng-container>
<!--/span-->
`
})
export class LazyLoadedLevel1Component{
@Input() rootDn: string;
@Output() onChildSelected = new EventEmitter<string>();
listingObj: any;
// listingObjObs: Observable<any>;
listing: string;
attribs: string;
selectedDN: string;
attribsArr: any[];
listArr:any[];
len:number;
loading: boolean;
private error:any;
constructor(private utilsService: UtilsService, private vmdirService: VmdirService) {
console.log("App component - vmdir");
}
ngOnInit() {
this.loading = true;
// This would be a call to your service that communicates with the server
console.log('------->oninit-lazyloadedcomponent' + this.rootDn);
this.getDirListing();
// console.log(this.listingObjObs);
}
onRecChildSelected(childDN:string) {
console.log("recursively calling emit")
this.onChildSelected.emit(childDN);
}
getAttributes() {
console.log("getAttributes - component");
let attribsObj:any;
this.onChildSelected.emit(this.selectedDN);
}
getDirListing() {
console.log("-------->getting child compoment");
this.loading = true;
this.vmdirService.getDirListing(encodeURIComponent(this.rootDn))
.subscribe(
listing => {
this.listing = JSON.stringify(listing);
this.listingObj = JSON.parse(this.listing);
this.utilsService.extractName(this.listingObj.result, false);
this.listArr = this.listingObj.result;
this.loading = false;
},
error => this.error = <any>error);
}
} | the_stack |
import {
CLASS_DRAG_ACTIVE,
CLASS_DRAG_HOVER,
CLASS_DRAGGED,
DragHandler
} from "./drag-manager"
import {
EVENT_DRAG_MOVE, EVENT_DRAG_START,
EVENT_DRAG_STOP
} from './constants'
import {BrowserJsPlumbInstance, DragGroupSpec} from "./browser-jsplumb-instance"
import { jsPlumbDOMElement} from './element-facade'
import {DragEventParams, Drag, DragStopEventParams, isInsideParent} from "./collicat"
import {
JsPlumbInstance,
RedrawResult,
UIGroup,
SELECTOR_MANAGED_ELEMENT,
ATTRIBUTE_NOT_DRAGGABLE,
CLASS_OVERLAY, cls
} from "@jsplumb/core"
import { FALSE } from "@jsplumb/common"
import {
BoundingBox,
Dictionary,
isString,
forEach,
getFromSetWithFunction,
PointXY,
Size,
intersects
} from "@jsplumb/util"
import {DragSelection} from "./drag-selection"
export type IntersectingGroup = {
groupLoc:GroupLocation
d:number
intersectingElement:Element
}
export type GroupLocation = {
el:Element
r: BoundingBox
group: UIGroup<Element>
}
type DragGroupMemberSpec = { el:jsPlumbDOMElement, elId:string, active:boolean }
type DragGroup = { id:string, members:Set<DragGroupMemberSpec>}
/**
* Base payload for drag events. Contains the element being dragged, the corresponding mouse event, the current position, and the position when drag started.
*/
export interface DragPayload {
el:Element
e:Event
pos:PointXY
originalPosition:PointXY
payload?:Record<string, any>
}
export type DraggedElement = {el:jsPlumbDOMElement, id:string, pos:PointXY, originalPos:PointXY, originalGroup:UIGroup, redrawResult:RedrawResult, reverted:boolean, dropGroup:UIGroup}
/**
* Payload for `drag:stop` event. In addition to the base payload, contains a redraw result object, listing all the connections and endpoints that were affected by the drag.
*/
export interface DragStopPayload {
elements:Array<DraggedElement>
e:Event
el:Element
payload?:Record<string, any>
}
/**
* Payload for `drag:move` event.
*/
export interface DragMovePayload extends DragPayload { }
/**
* Payload for `drag:start` event.
*/
export interface DragStartPayload extends DragPayload { }
function decodeDragGroupSpec(instance:JsPlumbInstance, spec:DragGroupSpec):{id:string, active:boolean} {
if (isString(spec)) {
return { id:spec as string, active:true }
} else {
return {
id:instance.getId(spec as any),
active:(spec as any).active
}
}
}
function isActiveDragGroupMember(dragGroup:DragGroup, el:HTMLElement): boolean {
const details = getFromSetWithFunction(dragGroup.members, (m:DragGroupMemberSpec) => m.el === el)
if (details !== null) {
return details.active === true
} else {
return false
}
}
function getAncestors(el:jsPlumbDOMElement):Array<Element> {
const ancestors:Array<Element> = []
let p = el._jsPlumbParentGroup
while (p != null) {
ancestors.push(p.el)
p = p.group
}
return ancestors
}
export class ElementDragHandler implements DragHandler {
selector: string = "> " + SELECTOR_MANAGED_ELEMENT + ":not(" + cls(CLASS_OVERLAY) + ")"
private _dragOffset:PointXY = null
private _groupLocations:Array<GroupLocation> = []
protected _intersectingGroups:Array<IntersectingGroup> = []
private _currentDragParentGroup:UIGroup<Element> = null
private _dragGroupByElementIdMap:Dictionary<DragGroup> = {}
private _dragGroupMap:Dictionary<DragGroup> = {}
private _currentDragGroup:DragGroup = null
private _currentDragGroupOffsets:Map<string, [PointXY, jsPlumbDOMElement]> = new Map()
private _currentDragGroupSizes:Map<string, Size> = new Map()
private _dragPayload:Record<string, any> = null
protected drag:Drag
originalPosition:PointXY
constructor(protected instance:BrowserJsPlumbInstance, protected _dragSelection:DragSelection) {}
onDragInit(el:Element):Element { return null; }
onDragAbort(el: Element):void {
return null
}
//
//
//
protected getDropGroup():IntersectingGroup|null {
// figure out if there is a group that we're hovering on.
let dropGroup:IntersectingGroup = null
if (this._intersectingGroups.length > 0) {
// we only support one for the time being
let targetGroup = this._intersectingGroups[0].groupLoc.group
let intersectingElement = this._intersectingGroups[0].intersectingElement as jsPlumbDOMElement
let currentGroup = intersectingElement._jsPlumbParentGroup
if (currentGroup !== targetGroup) {
if (currentGroup == null || !currentGroup.overrideDrop(intersectingElement, targetGroup)) {
dropGroup = this._intersectingGroups[0]
}
}
}
return dropGroup
}
onStop(params:DragStopEventParams):void {
const jel = params.drag.getDragElement() as unknown as jsPlumbDOMElement
let dropGroup:IntersectingGroup = this.getDropGroup()
/*
we have `dropGroup`, which is the group that the focus element was perhaps dropped on. we now need to create a list of
elements to process, with their element, id, and offset.
*/
const elementsToProcess:Array<DraggedElement> = []
elementsToProcess.push({
el:jel,
id:this.instance.getId(jel),
pos:params.finalPos,
originalGroup:jel._jsPlumbParentGroup,
redrawResult:null,
originalPos:params.originalPos,
reverted:false,
dropGroup:dropGroup != null ? dropGroup.groupLoc.group : null
})
this._dragSelection.each((el, id, o, s, orig) => {
if (el !== params.el) {
const pp = {
x:o.x,
y:o.y
}
let x = pp.x, y = pp.y
// TODO this is duplicated in dragSelection's update offsets method.
// and of course in the group drag constrain args in the jsplumb constructor
if (el._jsPlumbParentGroup && el._jsPlumbParentGroup.constrain) {
const constrainRect = {
w: el.parentNode.offsetWidth + el.parentNode.scrollLeft,
h: el.parentNode.offsetHeight + el.parentNode.scrollTop
};
x = Math.max(x, 0)
y = Math.max(y, 0)
x = Math.min(x, constrainRect.w - s.w)
y = Math.min(y, constrainRect.h - s.h)
pp.x = x
pp.y = y
}
elementsToProcess.push({
el, id, pos:pp, originalPos:orig, originalGroup:el._jsPlumbParentGroup, redrawResult:null, reverted:false, dropGroup:dropGroup != null ? dropGroup.groupLoc.group : null
})
}
})
// now we have a list of all the elements that have been dragged.
forEach(elementsToProcess, (p:DraggedElement)=> {
let wasInGroup = p.originalGroup != null,
isInOriginalGroup = wasInGroup && isInsideParent(this.instance, p.el, p.pos),
parentOffset = {x:0, y:0}
if (wasInGroup && !isInOriginalGroup) {
if (dropGroup == null) {
// the element may be pruned or orphaned by its group
const orphanedPosition = this._pruneOrOrphan(p, true, true)
if (orphanedPosition.pos != null) {
// if orphaned, update the drag end position.
p.pos = orphanedPosition.pos.pos
} else {
if (!orphanedPosition.pruned && p.originalGroup.revert) {
// if not pruned and the original group has revert set, revert the element.
p.pos = p.originalPos
p.reverted = true
}
}
}
} else if (wasInGroup && isInOriginalGroup) {
parentOffset = this.instance.viewport.getPosition(p.originalGroup.elId)
}
if (dropGroup != null && !isInOriginalGroup) {
this.instance.groupManager.addToGroup(dropGroup.groupLoc.group, false, p.el)
} else {
p.dropGroup = null
}
// if this element was reverted we have to set its position in the DOM.
if (p.reverted) {
this.instance.setPosition(p.el, p.pos)
}
// in all cases we update the viewport.
p.redrawResult = this.instance.setElementPosition(p.el, p.pos.x + parentOffset.x, p.pos.y + parentOffset.y)
this.instance.removeClass(p.el, CLASS_DRAGGED)
this.instance.select({source: p.el}).removeClass(this.instance.elementDraggingClass + " " + this.instance.sourceElementDraggingClass, true)
this.instance.select({target: p.el}).removeClass(this.instance.elementDraggingClass + " " + this.instance.targetElementDraggingClass, true)
// this is the ghost proxy code. ghosts wont have been created for anything other than the main element i think. this code could,
// currently, go outside of this loop (which it is, below).
// if (wasInGroup) {
// let currentGroup: UIGroup<Element> = jel._jsPlumbParentGroup
// if (currentGroup !== p.originalGroup) {
// const originalElement = params.drag.getDragElement(true)
// if (originalGroup.ghost) {
// const o1 = this.instance.getOffset(this.instance.getGroupContentArea(currentGroup))
// const o2 = this.instance.getOffset(this.instance.getGroupContentArea(originalGroup))
// const o = {x: o2.x + params.pos.x - o1.x, y: o2.y + params.pos.y - o1.y}
// originalElement.style.left = o.x + "px"
// originalElement.style.top = o.y + "px"
//
// this.instance.revalidate(originalElement)
// }
// }
// }
})
// ghost proxy - see above.
if (elementsToProcess[0].originalGroup != null) {
let currentGroup: UIGroup<Element> = jel._jsPlumbParentGroup
if (currentGroup !== elementsToProcess[0].originalGroup) {
const originalElement = params.drag.getDragElement(true)
if (elementsToProcess[0].originalGroup.ghost) {
const o1 = this.instance.getOffset(this.instance.getGroupContentArea(currentGroup))
const o2 = this.instance.getOffset(this.instance.getGroupContentArea(elementsToProcess[0].originalGroup))
const o = {x: o2.x + params.pos.x - o1.x, y: o2.y + params.pos.y - o1.y}
originalElement.style.left = o.x + "px"
originalElement.style.top = o.y + "px"
this.instance.revalidate(originalElement)
}
}
}
this.instance.fire<DragStopPayload>(EVENT_DRAG_STOP, {
elements:elementsToProcess,
e:params.e,
el:jel,
payload:this._dragPayload
})
this._cleanup()
}
private _cleanup() {
forEach(this._groupLocations,(groupLoc:GroupLocation) => {
this.instance.removeClass(groupLoc.el, CLASS_DRAG_ACTIVE)
this.instance.removeClass(groupLoc.el, CLASS_DRAG_HOVER)
})
this._currentDragParentGroup = null
this._groupLocations.length = 0
this.instance.hoverSuspended = false
this._dragOffset = null
this._dragSelection.reset()
this._dragPayload = null
this._currentDragGroupOffsets.clear()
this._currentDragGroupSizes.clear()
this._currentDragGroup = null
}
reset() { }
init(drag:Drag) {
this.drag = drag
}
onDrag(params:DragEventParams):void {
const el = params.drag.getDragElement()
const finalPos = params.pos
const elSize = this.instance.getSize(el)
const ui = { x:finalPos.x, y:finalPos.y }
this._intersectingGroups.length = 0
if (this._dragOffset != null) {
ui.x += this._dragOffset.x
ui.y += this._dragOffset.y
}
const _one = (el:HTMLElement, bounds:BoundingBox, findIntersectingGroups:boolean) => {
if (findIntersectingGroups) {
// keep track of the ancestors of each intersecting group we find.
const ancestorsOfIntersectingGroups = new Set<string>()
forEach(this._groupLocations, (groupLoc: GroupLocation) => {
if (!ancestorsOfIntersectingGroups.has(groupLoc.group.id) && intersects(bounds, groupLoc.r)) {
// when a group intersects it should only get the hover class if one of its descendants does not also intersect.
// groupLocations is already sorted by level of nesting
// we don't add the css class to the current group (but we do still add the group to the list of intersecting groups)
if (groupLoc.group !== this._currentDragParentGroup) {
this.instance.addClass(groupLoc.el, CLASS_DRAG_HOVER)
}
this._intersectingGroups.push({
groupLoc,
intersectingElement: params.drag.getDragElement(true),
d: 0
})
// store all this group's ancestor ids in a set, which will preclude them from being added as an intersecting group
forEach(this.instance.groupManager.getAncestors(groupLoc.group), (g: UIGroup<Element>) => ancestorsOfIntersectingGroups.add(g.id))
} else {
this.instance.removeClass(groupLoc.el, CLASS_DRAG_HOVER)
}
})
}
this.instance.setElementPosition(el, bounds.x, bounds.y)
this.instance.fire<DragMovePayload>(EVENT_DRAG_MOVE, {
el:el,
e:params.e,
pos:{x:bounds.x,y:bounds.y},
originalPosition:this.originalPosition,
payload:this._dragPayload
})
}
const elBounds:BoundingBox = { x:ui.x, y:ui.y, w:elSize.w, h:elSize.h }
_one(el, elBounds, true)
this._dragSelection.updatePositions(finalPos, this.originalPosition, (el:jsPlumbDOMElement, id:string, s:Size, b:BoundingBox)=>{
_one(el, b, false)
})
this._currentDragGroupOffsets.forEach((v:[PointXY, jsPlumbDOMElement], k:string) => {
const s = this._currentDragGroupSizes.get(k)
let _b:BoundingBox = {x:elBounds.x + v[0].x, y:elBounds.y + v[0].y, w:s.w, h:s.h}
v[1].style.left = _b.x + "px"
v[1].style.top = _b.y + "px"
_one(v[1], _b, false)
})
}
onStart(params:{e:MouseEvent, el:jsPlumbDOMElement, pos:PointXY, drag:Drag}):boolean {
const el = params.drag.getDragElement() as jsPlumbDOMElement
const elOffset = this.instance.getOffset(el)
this.originalPosition = {x:params.pos.x, y:params.pos.y}
if (el._jsPlumbParentGroup) {
this._dragOffset = this.instance.getOffset(el.offsetParent)
this._currentDragParentGroup = el._jsPlumbParentGroup
}
let cont = true
let nd = el.getAttribute(ATTRIBUTE_NOT_DRAGGABLE)
if (this.instance.elementsDraggable === false || (nd != null && nd !== FALSE)) {
cont = false
}
if (cont) {
this._groupLocations.length = 0
this._intersectingGroups.length = 0
this.instance.hoverSuspended = true
// get the drag element and find its descendants + ancestors. then filter the drag selection to mark any descendant or ancestor inactive,
// as they should not drag when an ancestor of theirs is being dragged.
const originalElement = params.drag.getDragElement(true),
descendants = originalElement.querySelectorAll(SELECTOR_MANAGED_ELEMENT),
ancestors = getAncestors(originalElement),
a:Array<Element> = []
Array.prototype.push.apply(a, descendants)
Array.prototype.push.apply(a, ancestors)
this._dragSelection.filterActiveSet((p:{id:string, jel:jsPlumbDOMElement}) => {
return a.indexOf(p.jel) === -1
})
// ---------------
// init the drag selection positions
this._dragSelection.initialisePositions()
const _one = (_el:jsPlumbDOMElement):any => {
// if drag el not a group
if (!_el._isJsPlumbGroup || this.instance.allowNestedGroups) {
const isNotInAGroup = !_el._jsPlumbParentGroup
const membersAreDroppable = isNotInAGroup || _el._jsPlumbParentGroup.dropOverride !== true
const isGhostOrNotConstrained = !isNotInAGroup && (_el._jsPlumbParentGroup.ghost || _el._jsPlumbParentGroup.constrain !== true)
// in order that there could be other groups this element can be dragged to, it must satisfy these conditions:
// it's not in a group, OR
// it hasn't mandated its elements can't be dropped on other groups
// it hasn't mandated its elements are constrained to the group, unless ghost proxying is turned on.
if (isNotInAGroup || (membersAreDroppable && isGhostOrNotConstrained)) {
forEach(this.instance.groupManager.getGroups(), (group: UIGroup<Element>) => {
// prepare a list of potential droppable groups.
// get the group pertaining to the dragged element. this is null if the element being dragged is not a UIGroup.
const elementGroup = _el._jsPlumbGroup as UIGroup<Element>
if (group.droppable !== false && group.enabled !== false && _el._jsPlumbGroup !== group && !this.instance.groupManager.isDescendant(group, elementGroup)) {
let groupEl = group.el,
s = this.instance.getSize(groupEl),
o = this.instance.getOffset(groupEl),
boundingRect = {x: o.x, y: o.y, w: s.w, h: s.h}
const groupLocation = {el: groupEl, r: boundingRect, group: group}
this._groupLocations.push(groupLocation)
// dont add the active class to the element/group's current parent (if any)
if (group !== this._currentDragParentGroup) {
this.instance.addClass(groupEl, CLASS_DRAG_ACTIVE)
}
}
})
// sort group locations so that nested groups will be processed first in a drop
this._groupLocations.sort((a:GroupLocation, b:GroupLocation) => {
if (this.instance.groupManager.isDescendant(a.group, b.group)) {
return -1
} else if (this.instance.groupManager.isAncestor(b.group, a.group)) {
return 1
} else {
return 0
}
})
}
}
this.instance.select({source: _el}).addClass(this.instance.elementDraggingClass + " " + this.instance.sourceElementDraggingClass, true)
this.instance.select({target: _el}).addClass(this.instance.elementDraggingClass + " " + this.instance.targetElementDraggingClass, true)
// if this event listener returns false it will be piped all the way back to the drag manager and cause
// the drag to be aborted.
return this.instance.fire<DragStartPayload>(EVENT_DRAG_START, {
el:_el,
e:params.e,
originalPosition:this.originalPosition,
pos:this.originalPosition
})
}
const elId = this.instance.getId(el)
this._currentDragGroup = this._dragGroupByElementIdMap[elId]
if (this._currentDragGroup && !isActiveDragGroupMember(this._currentDragGroup, el)) {
// clear the current dragGroup if this element is not an active member, ie. cannot instigate a drag for all members.
this._currentDragGroup = null
}
const dragStartReturn = _one(el); // process the original drag element.
if (dragStartReturn === false) {
this._cleanup()
return false
} else {
this._dragPayload = dragStartReturn
}
if (this._currentDragGroup != null) {
this._currentDragGroupOffsets.clear()
this._currentDragGroupSizes.clear()
this._currentDragGroup.members.forEach((jel:DragGroupMemberSpec) => {
let off = this.instance.getOffset(jel.el)
this._currentDragGroupOffsets.set(jel.elId, [ { x:off.x- elOffset.x, y:off.y - elOffset.y}, jel.el as jsPlumbDOMElement])
this._currentDragGroupSizes.set(jel.elId, this.instance.getSize(jel.el))
_one(jel.el)
})
}
}
return cont
}
addToDragGroup(spec:DragGroupSpec, ...els:Array<Element>) {
const details = decodeDragGroupSpec(this.instance, spec)
let dragGroup = this._dragGroupMap[details.id]
if (dragGroup == null) {
dragGroup = { id: details.id, members: new Set<DragGroupMemberSpec>()}
this._dragGroupMap[details.id] = dragGroup
}
this.removeFromDragGroup(...els)
forEach(els,(el:Element) => {
const elId = this.instance.getId(el)
dragGroup.members.add({elId:elId, el:el as jsPlumbDOMElement, active:details.active})
this._dragGroupByElementIdMap[elId] = dragGroup
})
}
removeFromDragGroup(...els:Array<Element>) {
forEach(els,(el:Element) => {
const id = this.instance.getId(el)
const dragGroup = this._dragGroupByElementIdMap[id]
if (dragGroup != null) {
const s = new Set<DragGroupMemberSpec>()
dragGroup.members.forEach((member) => {
if (member.el !== el) {
s.add(member)
}
})
dragGroup.members = s
delete this._dragGroupByElementIdMap[id]
}
})
}
setDragGroupState (state:boolean, ...els:Array<Element>) {
const elementIds = els.map(el => this.instance.getId(el))
forEach(elementIds,(id:string) => {
const dragGroup = this._dragGroupByElementIdMap[id]
if (dragGroup != null) {
const member = getFromSetWithFunction(dragGroup.members,(m:DragGroupMemberSpec) => m.elId === id)
if (member != null) {
member.active = state
}
}
})
}
/**
* Perhaps prune or orphan the element represented by the given drag params.
* @param params
* @param doNotTransferToAncestor Used when dealing with nested groups. When true, it means remove the element from any groups; when false, which is
* the default, elements that are orphaned will be added to this group's ancestor, if it has one.
* @param isDefinitelyNotInsideParent Used internally when this method is called and we've already done an intersections test. This flag saves us repeating the calculation.
* @internal
*/
private _pruneOrOrphan(params:{el:jsPlumbDOMElement, pos:PointXY }, doNotTransferToAncestor:boolean, isDefinitelyNotInsideParent:boolean):{pruned:boolean, pos?:{id:string, pos:PointXY}} {
const jel = params.el as unknown as jsPlumbDOMElement
let orphanedPosition = {pruned:false, pos:null as any}
if (isDefinitelyNotInsideParent || !isInsideParent(this.instance, jel, params.pos)) {
let group = jel._jsPlumbParentGroup
if (group.prune) {
if (jel._isJsPlumbGroup) {
// remove the group from the instance
this.instance.removeGroup(jel._jsPlumbGroup)
} else {
// instruct the group to remove the element from itself and also from the DOM.
group.remove(params.el, true)
}
orphanedPosition.pruned = true
} else if (group.orphan) {
orphanedPosition.pos = this.instance.groupManager.orphan(params.el, doNotTransferToAncestor)
if (jel._isJsPlumbGroup) {
// remove the nested group from the parent
group.removeGroup(jel._jsPlumbGroup)
} else {
// remove the element from the group's DOM element.
group.remove(params.el)
}
}
}
return orphanedPosition
}
} | the_stack |
import { expect } from 'chai';
import { describe, it } from 'mocha';
import { inspect } from '../../jsutils/inspect';
import { identityFunc } from '../../jsutils/identityFunc';
import { parseValue } from '../../language/parser';
import type { GraphQLType, GraphQLNullableType } from '../definition';
import {
GraphQLList,
GraphQLNonNull,
GraphQLScalarType,
GraphQLObjectType,
GraphQLInterfaceType,
GraphQLUnionType,
GraphQLEnumType,
GraphQLInputObjectType,
} from '../definition';
const ScalarType = new GraphQLScalarType({ name: 'Scalar' });
const ObjectType = new GraphQLObjectType({ name: 'Object', fields: {} });
const InterfaceType = new GraphQLInterfaceType({
name: 'Interface',
fields: {},
});
const UnionType = new GraphQLUnionType({ name: 'Union', types: [ObjectType] });
const EnumType = new GraphQLEnumType({ name: 'Enum', values: { foo: {} } });
const InputObjectType = new GraphQLInputObjectType({
name: 'InputObject',
fields: {},
});
const ListOfScalarsType = new GraphQLList(ScalarType);
const NonNullScalarType = new GraphQLNonNull(ScalarType);
const ListOfNonNullScalarsType = new GraphQLList(NonNullScalarType);
const NonNullListOfScalars = new GraphQLNonNull(ListOfScalarsType);
// istanbul ignore next (Never called and used as a placeholder)
const dummyFunc = () => {
/* empty */
};
describe('Type System: Scalars', () => {
it('accepts a Scalar type defining serialize', () => {
expect(() => new GraphQLScalarType({ name: 'SomeScalar' })).to.not.throw();
});
it('accepts a Scalar type defining specifiedByURL', () => {
expect(
() =>
new GraphQLScalarType({
name: 'SomeScalar',
specifiedByURL: 'https://example.com/foo_spec',
}),
).not.to.throw();
});
it('accepts a Scalar type defining parseValue and parseLiteral', () => {
expect(
() =>
new GraphQLScalarType({
name: 'SomeScalar',
parseValue: dummyFunc,
parseLiteral: dummyFunc,
}),
).to.not.throw();
});
it('provides default methods if omitted', () => {
const scalar = new GraphQLScalarType({ name: 'Foo' });
expect(scalar.serialize).to.equal(identityFunc);
expect(scalar.parseValue).to.equal(identityFunc);
expect(scalar.parseLiteral).to.be.a('function');
});
it('use parseValue for parsing literals if parseLiteral omitted', () => {
const scalar = new GraphQLScalarType({
name: 'Foo',
parseValue(value) {
return 'parseValue: ' + inspect(value);
},
});
expect(scalar.parseLiteral(parseValue('null'))).to.equal(
'parseValue: null',
);
expect(scalar.parseLiteral(parseValue('{ foo: "bar" }'))).to.equal(
'parseValue: { foo: "bar" }',
);
expect(
scalar.parseLiteral(parseValue('{ foo: { bar: $var } }'), { var: 'baz' }),
).to.equal('parseValue: { foo: { bar: "baz" } }');
});
it('rejects a Scalar type without name', () => {
// @ts-expect-error
expect(() => new GraphQLScalarType({})).to.throw('Must provide name.');
});
it('rejects a Scalar type defining serialize with an incorrect type', () => {
expect(
() =>
new GraphQLScalarType({
name: 'SomeScalar',
// @ts-expect-error
serialize: {},
}),
).to.throw(
'SomeScalar must provide "serialize" function. If this custom Scalar is also used as an input type, ensure "parseValue" and "parseLiteral" functions are also provided.',
);
});
it('rejects a Scalar type defining parseLiteral but not parseValue', () => {
expect(
() =>
new GraphQLScalarType({
name: 'SomeScalar',
parseLiteral: dummyFunc,
}),
).to.throw(
'SomeScalar must provide both "parseValue" and "parseLiteral" functions.',
);
});
it('rejects a Scalar type defining parseValue and parseLiteral with an incorrect type', () => {
expect(
() =>
new GraphQLScalarType({
name: 'SomeScalar',
// @ts-expect-error
parseValue: {},
// @ts-expect-error
parseLiteral: {},
}),
).to.throw(
'SomeScalar must provide both "parseValue" and "parseLiteral" functions.',
);
});
it('rejects a Scalar type defining specifiedByURL with an incorrect type', () => {
expect(
() =>
new GraphQLScalarType({
name: 'SomeScalar',
// @ts-expect-error
specifiedByURL: {},
}),
).to.throw(
'SomeScalar must provide "specifiedByURL" as a string, but got: {}.',
);
});
});
describe('Type System: Objects', () => {
it('does not mutate passed field definitions', () => {
const outputFields = {
field1: { type: ScalarType },
field2: {
type: ScalarType,
args: {
id: { type: ScalarType },
},
},
};
const testObject1 = new GraphQLObjectType({
name: 'Test1',
fields: outputFields,
});
const testObject2 = new GraphQLObjectType({
name: 'Test2',
fields: outputFields,
});
expect(testObject1.getFields()).to.deep.equal(testObject2.getFields());
expect(outputFields).to.deep.equal({
field1: {
type: ScalarType,
},
field2: {
type: ScalarType,
args: {
id: { type: ScalarType },
},
},
});
const inputFields = {
field1: { type: ScalarType },
field2: { type: ScalarType },
};
const testInputObject1 = new GraphQLInputObjectType({
name: 'Test1',
fields: inputFields,
});
const testInputObject2 = new GraphQLInputObjectType({
name: 'Test2',
fields: inputFields,
});
expect(testInputObject1.getFields()).to.deep.equal(
testInputObject2.getFields(),
);
expect(inputFields).to.deep.equal({
field1: { type: ScalarType },
field2: { type: ScalarType },
});
});
it('defines an object type with deprecated field', () => {
const TypeWithDeprecatedField = new GraphQLObjectType({
name: 'foo',
fields: {
bar: {
type: ScalarType,
deprecationReason: 'A terrible reason',
},
baz: {
type: ScalarType,
deprecationReason: '',
},
},
});
expect(TypeWithDeprecatedField.getFields().bar).to.include({
name: 'bar',
deprecationReason: 'A terrible reason',
});
expect(TypeWithDeprecatedField.getFields().baz).to.include({
name: 'baz',
deprecationReason: '',
});
});
it('accepts an Object type with a field function', () => {
const objType = new GraphQLObjectType({
name: 'SomeObject',
fields: () => ({
f: { type: ScalarType },
}),
});
expect(objType.getFields()).to.deep.equal({
f: {
name: 'f',
description: undefined,
type: ScalarType,
args: [],
resolve: undefined,
subscribe: undefined,
deprecationReason: undefined,
extensions: {},
astNode: undefined,
},
});
});
it('accepts an Object type with field args', () => {
const objType = new GraphQLObjectType({
name: 'SomeObject',
fields: {
f: {
type: ScalarType,
args: {
arg: { type: ScalarType },
},
},
},
});
expect(objType.getFields()).to.deep.equal({
f: {
name: 'f',
description: undefined,
type: ScalarType,
args: [
{
name: 'arg',
description: undefined,
type: ScalarType,
defaultValue: undefined,
deprecationReason: undefined,
extensions: {},
astNode: undefined,
},
],
resolve: undefined,
subscribe: undefined,
deprecationReason: undefined,
extensions: {},
astNode: undefined,
},
});
});
it('accepts an Object type with array interfaces', () => {
const objType = new GraphQLObjectType({
name: 'SomeObject',
fields: {},
interfaces: [InterfaceType],
});
expect(objType.getInterfaces()).to.deep.equal([InterfaceType]);
});
it('accepts an Object type with interfaces as a function returning an array', () => {
const objType = new GraphQLObjectType({
name: 'SomeObject',
fields: {},
interfaces: () => [InterfaceType],
});
expect(objType.getInterfaces()).to.deep.equal([InterfaceType]);
});
it('accepts a lambda as an Object field resolver', () => {
const objType = new GraphQLObjectType({
name: 'SomeObject',
fields: {
f: {
type: ScalarType,
resolve: dummyFunc,
},
},
});
expect(() => objType.getFields()).to.not.throw();
});
it('rejects an Object type with invalid name', () => {
expect(
() => new GraphQLObjectType({ name: 'bad-name', fields: {} }),
).to.throw('Names must only contain [_a-zA-Z0-9] but "bad-name" does not.');
});
it('rejects an Object type field with undefined config', () => {
const objType = new GraphQLObjectType({
name: 'SomeObject',
fields: {
// @ts-expect-error (must not be undefined)
f: undefined,
},
});
expect(() => objType.getFields()).to.throw(
'SomeObject.f field config must be an object.',
);
});
it('rejects an Object type with incorrectly typed fields', () => {
const objType = new GraphQLObjectType({
name: 'SomeObject',
// @ts-expect-error
fields: [{ field: ScalarType }],
});
expect(() => objType.getFields()).to.throw(
'SomeObject fields must be an object with field names as keys or a function which returns such an object.',
);
});
it('rejects an Object type with incorrectly named fields', () => {
const objType = new GraphQLObjectType({
name: 'SomeObject',
fields: {
'bad-name': { type: ScalarType },
},
});
expect(() => objType.getFields()).to.throw(
'Names must only contain [_a-zA-Z0-9] but "bad-name" does not.',
);
});
it('rejects an Object type with a field function that returns incorrect type', () => {
const objType = new GraphQLObjectType({
name: 'SomeObject',
// @ts-expect-error (Wrong type of return)
fields() {
return [{ field: ScalarType }];
},
});
expect(() => objType.getFields()).to.throw();
});
it('rejects an Object type with incorrectly typed field args', () => {
const objType = new GraphQLObjectType({
name: 'SomeObject',
fields: {
badField: {
type: ScalarType,
// @ts-expect-error
args: [{ badArg: ScalarType }],
},
},
});
expect(() => objType.getFields()).to.throw(
'SomeObject.badField args must be an object with argument names as keys.',
);
});
it('rejects an Object type with incorrectly named field args', () => {
const objType = new GraphQLObjectType({
name: 'SomeObject',
fields: {
badField: {
type: ScalarType,
args: {
'bad-name': { type: ScalarType },
},
},
},
});
expect(() => objType.getFields()).to.throw(
'Names must only contain [_a-zA-Z0-9] but "bad-name" does not.',
);
});
it('rejects an Object type with incorrectly typed interfaces', () => {
const objType = new GraphQLObjectType({
name: 'SomeObject',
fields: {},
// @ts-expect-error
interfaces: {},
});
expect(() => objType.getInterfaces()).to.throw(
'SomeObject interfaces must be an Array or a function which returns an Array.',
);
});
it('rejects an Object type with interfaces as a function returning an incorrect type', () => {
const objType = new GraphQLObjectType({
name: 'SomeObject',
fields: {},
// @ts-expect-error (Expected interfaces to return array)
interfaces() {
return {};
},
});
expect(() => objType.getInterfaces()).to.throw(
'SomeObject interfaces must be an Array or a function which returns an Array.',
);
});
it('rejects an empty Object field resolver', () => {
const objType = new GraphQLObjectType({
name: 'SomeObject',
fields: {
// @ts-expect-error (Expected resolve to be a function)
field: { type: ScalarType, resolve: {} },
},
});
expect(() => objType.getFields()).to.throw(
'SomeObject.field field resolver must be a function if provided, but got: {}.',
);
});
it('rejects a constant scalar value resolver', () => {
const objType = new GraphQLObjectType({
name: 'SomeObject',
fields: {
// @ts-expect-error (Expected resolve to be a function)
field: { type: ScalarType, resolve: 0 },
},
});
expect(() => objType.getFields()).to.throw(
'SomeObject.field field resolver must be a function if provided, but got: 0.',
);
});
it('rejects an Object type with an incorrect type for isTypeOf', () => {
expect(
() =>
new GraphQLObjectType({
name: 'AnotherObject',
fields: {},
// @ts-expect-error
isTypeOf: {},
}),
).to.throw(
'AnotherObject must provide "isTypeOf" as a function, but got: {}.',
);
});
});
describe('Type System: Interfaces', () => {
it('accepts an Interface type defining resolveType', () => {
expect(
() =>
new GraphQLInterfaceType({
name: 'AnotherInterface',
fields: { f: { type: ScalarType } },
}),
).to.not.throw();
});
it('accepts an Interface type with an array of interfaces', () => {
const implementing = new GraphQLInterfaceType({
name: 'AnotherInterface',
fields: {},
interfaces: [InterfaceType],
});
expect(implementing.getInterfaces()).to.deep.equal([InterfaceType]);
});
it('accepts an Interface type with interfaces as a function returning an array', () => {
const implementing = new GraphQLInterfaceType({
name: 'AnotherInterface',
fields: {},
interfaces: () => [InterfaceType],
});
expect(implementing.getInterfaces()).to.deep.equal([InterfaceType]);
});
it('rejects an Interface type with invalid name', () => {
expect(
() => new GraphQLInterfaceType({ name: 'bad-name', fields: {} }),
).to.throw('Names must only contain [_a-zA-Z0-9] but "bad-name" does not.');
});
it('rejects an Interface type with incorrectly typed interfaces', () => {
const objType = new GraphQLInterfaceType({
name: 'AnotherInterface',
fields: {},
// @ts-expect-error
interfaces: {},
});
expect(() => objType.getInterfaces()).to.throw(
'AnotherInterface interfaces must be an Array or a function which returns an Array.',
);
});
it('rejects an Interface type with interfaces as a function returning an incorrect type', () => {
const objType = new GraphQLInterfaceType({
name: 'AnotherInterface',
fields: {},
// @ts-expect-error (Expected Array return)
interfaces() {
return {};
},
});
expect(() => objType.getInterfaces()).to.throw(
'AnotherInterface interfaces must be an Array or a function which returns an Array.',
);
});
it('rejects an Interface type with an incorrect type for resolveType', () => {
expect(
() =>
new GraphQLInterfaceType({
name: 'AnotherInterface',
fields: {},
// @ts-expect-error
resolveType: {},
}),
).to.throw(
'AnotherInterface must provide "resolveType" as a function, but got: {}.',
);
});
});
describe('Type System: Unions', () => {
it('accepts a Union type defining resolveType', () => {
expect(
() =>
new GraphQLUnionType({
name: 'SomeUnion',
types: [ObjectType],
}),
).to.not.throw();
});
it('accepts a Union type with array types', () => {
const unionType = new GraphQLUnionType({
name: 'SomeUnion',
types: [ObjectType],
});
expect(unionType.getTypes()).to.deep.equal([ObjectType]);
});
it('accepts a Union type with function returning an array of types', () => {
const unionType = new GraphQLUnionType({
name: 'SomeUnion',
types: () => [ObjectType],
});
expect(unionType.getTypes()).to.deep.equal([ObjectType]);
});
it('accepts a Union type without types', () => {
const unionType = new GraphQLUnionType({
name: 'SomeUnion',
types: [],
});
expect(unionType.getTypes()).to.deep.equal([]);
});
it('rejects an Union type with invalid name', () => {
expect(
() => new GraphQLUnionType({ name: 'bad-name', types: [] }),
).to.throw('Names must only contain [_a-zA-Z0-9] but "bad-name" does not.');
});
it('rejects an Union type with an incorrect type for resolveType', () => {
expect(
() =>
new GraphQLUnionType({
name: 'SomeUnion',
types: [],
// @ts-expect-error
resolveType: {},
}),
).to.throw(
'SomeUnion must provide "resolveType" as a function, but got: {}.',
);
});
it('rejects a Union type with incorrectly typed types', () => {
const unionType = new GraphQLUnionType({
name: 'SomeUnion',
// @ts-expect-error
types: { ObjectType },
});
expect(() => unionType.getTypes()).to.throw(
'Must provide Array of types or a function which returns such an array for Union SomeUnion.',
);
});
});
describe('Type System: Enums', () => {
it('defines an enum type with deprecated value', () => {
const EnumTypeWithDeprecatedValue = new GraphQLEnumType({
name: 'EnumWithDeprecatedValue',
values: {
foo: { deprecationReason: 'Just because' },
bar: { deprecationReason: '' },
},
});
expect(EnumTypeWithDeprecatedValue.getValues()[0]).to.include({
name: 'foo',
deprecationReason: 'Just because',
});
expect(EnumTypeWithDeprecatedValue.getValues()[1]).to.include({
name: 'bar',
deprecationReason: '',
});
});
it('defines an enum type with a value of `null` and `undefined`', () => {
const EnumTypeWithNullishValue = new GraphQLEnumType({
name: 'EnumWithNullishValue',
values: {
NULL: { value: null },
NAN: { value: NaN },
NO_CUSTOM_VALUE: { value: undefined },
},
});
expect(EnumTypeWithNullishValue.getValues()).to.deep.equal([
{
name: 'NULL',
description: undefined,
value: null,
deprecationReason: undefined,
extensions: {},
astNode: undefined,
},
{
name: 'NAN',
description: undefined,
value: NaN,
deprecationReason: undefined,
extensions: {},
astNode: undefined,
},
{
name: 'NO_CUSTOM_VALUE',
description: undefined,
value: 'NO_CUSTOM_VALUE',
deprecationReason: undefined,
extensions: {},
astNode: undefined,
},
]);
});
it('accepts a well defined Enum type with empty value definition', () => {
const enumType = new GraphQLEnumType({
name: 'SomeEnum',
values: {
FOO: {},
BAR: {},
},
});
expect(enumType.getValue('FOO')).has.property('value', 'FOO');
expect(enumType.getValue('BAR')).has.property('value', 'BAR');
});
it('accepts a well defined Enum type with internal value definition', () => {
const enumType = new GraphQLEnumType({
name: 'SomeEnum',
values: {
FOO: { value: 10 },
BAR: { value: 20 },
},
});
expect(enumType.getValue('FOO')).has.property('value', 10);
expect(enumType.getValue('BAR')).has.property('value', 20);
});
it('rejects an Enum type with invalid name', () => {
expect(
() => new GraphQLEnumType({ name: 'bad-name', values: {} }),
).to.throw('Names must only contain [_a-zA-Z0-9] but "bad-name" does not.');
});
it('rejects an Enum type with incorrectly typed values', () => {
expect(
() =>
new GraphQLEnumType({
name: 'SomeEnum',
// @ts-expect-error
values: [{ FOO: 10 }],
}),
).to.throw('SomeEnum values must be an object with value names as keys.');
});
it('rejects an Enum type with incorrectly named values', () => {
expect(
() =>
new GraphQLEnumType({
name: 'SomeEnum',
values: {
'bad-name': {},
},
}),
).to.throw('Names must only contain [_a-zA-Z0-9] but "bad-name" does not.');
});
it('rejects an Enum type with missing value definition', () => {
expect(
() =>
new GraphQLEnumType({
name: 'SomeEnum',
// @ts-expect-error (must not be null)
values: { FOO: null },
}),
).to.throw(
'SomeEnum.FOO must refer to an object with a "value" key representing an internal value but got: null.',
);
});
it('rejects an Enum type with incorrectly typed value definition', () => {
expect(
() =>
new GraphQLEnumType({
name: 'SomeEnum',
// @ts-expect-error
values: { FOO: 10 },
}),
).to.throw(
'SomeEnum.FOO must refer to an object with a "value" key representing an internal value but got: 10.',
);
});
});
describe('Type System: Input Objects', () => {
describe('Input Objects must have fields', () => {
it('accepts an Input Object type with fields', () => {
const inputObjType = new GraphQLInputObjectType({
name: 'SomeInputObject',
fields: {
f: { type: ScalarType },
},
});
expect(inputObjType.getFields()).to.deep.equal({
f: {
name: 'f',
description: undefined,
type: ScalarType,
defaultValue: undefined,
deprecationReason: undefined,
extensions: {},
astNode: undefined,
},
});
});
it('accepts an Input Object type with a field function', () => {
const inputObjType = new GraphQLInputObjectType({
name: 'SomeInputObject',
fields: () => ({
f: { type: ScalarType },
}),
});
expect(inputObjType.getFields()).to.deep.equal({
f: {
name: 'f',
description: undefined,
type: ScalarType,
defaultValue: undefined,
extensions: {},
deprecationReason: undefined,
astNode: undefined,
},
});
});
it('rejects an Input Object type with invalid name', () => {
expect(
() => new GraphQLInputObjectType({ name: 'bad-name', fields: {} }),
).to.throw(
'Names must only contain [_a-zA-Z0-9] but "bad-name" does not.',
);
});
it('rejects an Input Object type with incorrect fields', () => {
const inputObjType = new GraphQLInputObjectType({
name: 'SomeInputObject',
// @ts-expect-error
fields: [],
});
expect(() => inputObjType.getFields()).to.throw(
'SomeInputObject fields must be an object with field names as keys or a function which returns such an object.',
);
});
it('rejects an Input Object type with fields function that returns incorrect type', () => {
const inputObjType = new GraphQLInputObjectType({
name: 'SomeInputObject',
// @ts-expect-error
fields: () => [],
});
expect(() => inputObjType.getFields()).to.throw(
'SomeInputObject fields must be an object with field names as keys or a function which returns such an object.',
);
});
it('rejects an Input Object type with incorrectly named fields', () => {
const inputObjType = new GraphQLInputObjectType({
name: 'SomeInputObject',
fields: {
'bad-name': { type: ScalarType },
},
});
expect(() => inputObjType.getFields()).to.throw(
'Names must only contain [_a-zA-Z0-9] but "bad-name" does not.',
);
});
});
describe('Input Object fields must not have resolvers', () => {
it('rejects an Input Object type with resolvers', () => {
const inputObjType = new GraphQLInputObjectType({
name: 'SomeInputObject',
fields: {
// @ts-expect-error (Input fields cannot have resolvers)
f: { type: ScalarType, resolve: dummyFunc },
},
});
expect(() => inputObjType.getFields()).to.throw(
'SomeInputObject.f field has a resolve property, but Input Types cannot define resolvers.',
);
});
it('rejects an Input Object type with resolver constant', () => {
const inputObjType = new GraphQLInputObjectType({
name: 'SomeInputObject',
fields: {
// @ts-expect-error (Input fields cannot have resolvers)
f: { type: ScalarType, resolve: {} },
},
});
expect(() => inputObjType.getFields()).to.throw(
'SomeInputObject.f field has a resolve property, but Input Types cannot define resolvers.',
);
});
});
it('Deprecation reason is preserved on fields', () => {
const inputObjType = new GraphQLInputObjectType({
name: 'SomeInputObject',
fields: {
deprecatedField: {
type: ScalarType,
deprecationReason: 'not used anymore',
},
},
});
expect(inputObjType.toConfig()).to.have.nested.property(
'fields.deprecatedField.deprecationReason',
'not used anymore',
);
});
});
describe('Type System: List', () => {
function expectList(type: GraphQLType) {
return expect(() => new GraphQLList(type));
}
it('accepts an type as item type of list', () => {
expectList(ScalarType).to.not.throw();
expectList(ObjectType).to.not.throw();
expectList(UnionType).to.not.throw();
expectList(InterfaceType).to.not.throw();
expectList(EnumType).to.not.throw();
expectList(InputObjectType).to.not.throw();
expectList(ListOfScalarsType).to.not.throw();
expectList(NonNullScalarType).to.not.throw();
});
it('rejects a non-type as item type of list', () => {
// @ts-expect-error
expectList({}).to.throw('Expected {} to be a GraphQL type.');
// @ts-expect-error
expectList(String).to.throw(
'Expected [function String] to be a GraphQL type.',
);
// @ts-expect-error (must provide type)
expectList(null).to.throw('Expected null to be a GraphQL type.');
// @ts-expect-error (must provide type)
expectList(undefined).to.throw('Expected undefined to be a GraphQL type.');
});
});
describe('Type System: Non-Null', () => {
function expectNonNull(type: GraphQLNullableType) {
return expect(() => new GraphQLNonNull(type));
}
it('accepts an type as nullable type of non-null', () => {
expectNonNull(ScalarType).to.not.throw();
expectNonNull(ObjectType).to.not.throw();
expectNonNull(UnionType).to.not.throw();
expectNonNull(InterfaceType).to.not.throw();
expectNonNull(EnumType).to.not.throw();
expectNonNull(InputObjectType).to.not.throw();
expectNonNull(ListOfScalarsType).to.not.throw();
expectNonNull(ListOfNonNullScalarsType).to.not.throw();
});
it('rejects a non-type as nullable type of non-null', () => {
expectNonNull(NonNullScalarType).to.throw(
'Expected Scalar! to be a GraphQL nullable type.',
);
// @ts-expect-error
expectNonNull({}).to.throw('Expected {} to be a GraphQL nullable type.');
// @ts-expect-error
expectNonNull(String).to.throw(
'Expected [function String] to be a GraphQL nullable type.',
);
// @ts-expect-error (must provide type)
expectNonNull(null).to.throw(
'Expected null to be a GraphQL nullable type.',
);
// @ts-expect-error (must provide type)
expectNonNull(undefined).to.throw(
'Expected undefined to be a GraphQL nullable type.',
);
});
});
describe('Type System: test utility methods', () => {
it('stringifies types', () => {
expect(String(ScalarType)).to.equal('Scalar');
expect(String(ObjectType)).to.equal('Object');
expect(String(InterfaceType)).to.equal('Interface');
expect(String(UnionType)).to.equal('Union');
expect(String(EnumType)).to.equal('Enum');
expect(String(InputObjectType)).to.equal('InputObject');
expect(String(NonNullScalarType)).to.equal('Scalar!');
expect(String(ListOfScalarsType)).to.equal('[Scalar]');
expect(String(NonNullListOfScalars)).to.equal('[Scalar]!');
expect(String(ListOfNonNullScalarsType)).to.equal('[Scalar!]');
expect(String(new GraphQLList(ListOfScalarsType))).to.equal('[[Scalar]]');
});
it('JSON.stringifies types', () => {
expect(JSON.stringify(ScalarType)).to.equal('"Scalar"');
expect(JSON.stringify(ObjectType)).to.equal('"Object"');
expect(JSON.stringify(InterfaceType)).to.equal('"Interface"');
expect(JSON.stringify(UnionType)).to.equal('"Union"');
expect(JSON.stringify(EnumType)).to.equal('"Enum"');
expect(JSON.stringify(InputObjectType)).to.equal('"InputObject"');
expect(JSON.stringify(NonNullScalarType)).to.equal('"Scalar!"');
expect(JSON.stringify(ListOfScalarsType)).to.equal('"[Scalar]"');
expect(JSON.stringify(NonNullListOfScalars)).to.equal('"[Scalar]!"');
expect(JSON.stringify(ListOfNonNullScalarsType)).to.equal('"[Scalar!]"');
expect(JSON.stringify(new GraphQLList(ListOfScalarsType))).to.equal(
'"[[Scalar]]"',
);
});
it('Object.toStringifies types', () => {
function toString(obj: unknown): string {
return Object.prototype.toString.call(obj);
}
expect(toString(ScalarType)).to.equal('[object GraphQLScalarType]');
expect(toString(ObjectType)).to.equal('[object GraphQLObjectType]');
expect(toString(InterfaceType)).to.equal('[object GraphQLInterfaceType]');
expect(toString(UnionType)).to.equal('[object GraphQLUnionType]');
expect(toString(EnumType)).to.equal('[object GraphQLEnumType]');
expect(toString(InputObjectType)).to.equal(
'[object GraphQLInputObjectType]',
);
expect(toString(NonNullScalarType)).to.equal('[object GraphQLNonNull]');
expect(toString(ListOfScalarsType)).to.equal('[object GraphQLList]');
});
}); | the_stack |
declare module 'fs' {
import * as stream from 'node:stream';
import { Abortable, EventEmitter } from 'node:events';
import { URL } from 'node:url';
import * as promises from 'node:fs/promises';
export { promises };
/**
* Valid types for path values in "fs".
*/
export type PathLike = string | Buffer | URL;
export type PathOrFileDescriptor = PathLike | number;
export type TimeLike = string | number | Date;
export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void;
export type BufferEncodingOption =
| 'buffer'
| {
encoding: 'buffer';
};
export interface ObjectEncodingOptions {
encoding?: BufferEncoding | null | undefined;
}
export type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null;
export type OpenMode = number | string;
export type Mode = number | string;
export interface StatsBase<T> {
isFile(): boolean;
isDirectory(): boolean;
isBlockDevice(): boolean;
isCharacterDevice(): boolean;
isSymbolicLink(): boolean;
isFIFO(): boolean;
isSocket(): boolean;
dev: T;
ino: T;
mode: T;
nlink: T;
uid: T;
gid: T;
rdev: T;
size: T;
blksize: T;
blocks: T;
atimeMs: T;
mtimeMs: T;
ctimeMs: T;
birthtimeMs: T;
atime: Date;
mtime: Date;
ctime: Date;
birthtime: Date;
}
export interface Stats extends StatsBase<number> {}
/**
* A `<fs.Stats>` object provides information about a file.
*
* Objects returned from {@link stat}, {@link lstat} and {@link fstat} and
* their synchronous counterparts are of this type.
* If `bigint` in the `options` passed to those methods is true, the numeric values
* will be `bigint` instead of `number`, and the object will contain additional
* nanosecond-precision properties suffixed with `Ns`.
*
* ```console
* Stats {
* dev: 2114,
* ino: 48064969,
* mode: 33188,
* nlink: 1,
* uid: 85,
* gid: 100,
* rdev: 0,
* size: 527,
* blksize: 4096,
* blocks: 8,
* atimeMs: 1318289051000.1,
* mtimeMs: 1318289051000.1,
* ctimeMs: 1318289051000.1,
* birthtimeMs: 1318289051000.1,
* atime: Mon, 10 Oct 2011 23:24:11 GMT,
* mtime: Mon, 10 Oct 2011 23:24:11 GMT,
* ctime: Mon, 10 Oct 2011 23:24:11 GMT,
* birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
* ```
*
* `bigint` version:
*
* ```console
* BigIntStats {
* dev: 2114n,
* ino: 48064969n,
* mode: 33188n,
* nlink: 1n,
* uid: 85n,
* gid: 100n,
* rdev: 0n,
* size: 527n,
* blksize: 4096n,
* blocks: 8n,
* atimeMs: 1318289051000n,
* mtimeMs: 1318289051000n,
* ctimeMs: 1318289051000n,
* birthtimeMs: 1318289051000n,
* atimeNs: 1318289051000000000n,
* mtimeNs: 1318289051000000000n,
* ctimeNs: 1318289051000000000n,
* birthtimeNs: 1318289051000000000n,
* atime: Mon, 10 Oct 2011 23:24:11 GMT,
* mtime: Mon, 10 Oct 2011 23:24:11 GMT,
* ctime: Mon, 10 Oct 2011 23:24:11 GMT,
* birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
* ```
* @since v0.1.21
*/
export class Stats {}
/**
* A representation of a directory entry, which can be a file or a subdirectory
* within the directory, as returned by reading from an `<fs.Dir>`. The
* directory entry is a combination of the file name and file type pairs.
*
* Additionally, when {@link readdir} or {@link readdirSync} is called with
* the `withFileTypes` option set to `true`, the resulting array is filled with `<fs.Dirent>` objects, rather than strings or `<Buffer>` s.
* @since v10.10.0
*/
export class Dirent {
/**
* Returns `true` if the `<fs.Dirent>` object describes a regular file.
* @since v10.10.0
*/
isFile(): boolean;
/**
* Returns `true` if the `<fs.Dirent>` object describes a file system
* directory.
* @since v10.10.0
*/
isDirectory(): boolean;
/**
* Returns `true` if the `<fs.Dirent>` object describes a block device.
* @since v10.10.0
*/
isBlockDevice(): boolean;
/**
* Returns `true` if the `<fs.Dirent>` object describes a character device.
* @since v10.10.0
*/
isCharacterDevice(): boolean;
/**
* Returns `true` if the `<fs.Dirent>` object describes a symbolic link.
* @since v10.10.0
*/
isSymbolicLink(): boolean;
/**
* Returns `true` if the `<fs.Dirent>` object describes a first-in-first-out
* (FIFO) pipe.
* @since v10.10.0
*/
isFIFO(): boolean;
/**
* Returns `true` if the `<fs.Dirent>` object describes a socket.
* @since v10.10.0
*/
isSocket(): boolean;
/**
* The file name that this `<fs.Dirent>` object refers to. The type of this
* value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}.
* @since v10.10.0
*/
name: string;
}
/**
* A class representing a directory stream.
*
* Created by {@link opendir}, {@link opendirSync}, or {@link romises.opendir}.
*
* ```js
* import { opendir } from 'fs/promises';
*
* try {
* const dir = await opendir('./');
* for await (const dirent of dir)
* console.log(dirent.name);
* } catch (err) {
* console.error(err);
* }
* ```
*
* When using the async iterator, the `<fs.Dir>` object will be automatically
* closed after the iterator exits.
* @since v12.12.0
*/
export class Dir implements AsyncIterable<Dirent> {
/**
* The read-only path of this directory as was provided to {@link opendir},{@link opendirSync}, or {@link romises.opendir}.
* @since v12.12.0
*/
readonly path: string;
/**
* Asynchronously iterates over the directory via `readdir(3)` until all entries have been read.
*/
[Symbol.asyncIterator](): AsyncIterableIterator<Dirent>;
/**
* Asynchronously close the directory's underlying resource handle.
* Subsequent reads will result in errors.
*
* A promise is returned that will be resolved after the resource has been
* closed.
* @since v12.12.0
*/
close(): Promise<void>;
close(cb: NoParamCallback): void;
/**
* Synchronously close the directory's underlying resource handle.
* Subsequent reads will result in errors.
* @since v12.12.0
*/
closeSync(): void;
/**
* Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `<fs.Dirent>`.
*
* A promise is returned that will be resolved with an `<fs.Dirent>`, or `null`if there are no more directory entries to read.
*
* Directory entries returned by this function are in no particular order as
* provided by the operating system's underlying directory mechanisms.
* Entries added or removed while iterating over the directory might not be
* included in the iteration results.
* @since v12.12.0
* @return containing {fs.Dirent|null}
*/
read(): Promise<Dirent | null>;
read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void;
/**
* Synchronously read the next directory entry as an `<fs.Dirent>`. See the
* POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more detail.
*
* If there are no more directory entries to read, `null` will be returned.
*
* Directory entries returned by this function are in no particular order as
* provided by the operating system's underlying directory mechanisms.
* Entries added or removed while iterating over the directory might not be
* included in the iteration results.
* @since v12.12.0
*/
readSync(): Dirent | null;
}
export interface FSWatcher extends EventEmitter {
/**
* Stop watching for changes on the given `<fs.FSWatcher>`. Once stopped, the `<fs.FSWatcher>` object is no longer usable.
* @since v0.5.8
*/
close(): void;
/**
* events.EventEmitter
* 1. change
* 2. error
*/
addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this;
addListener(event: 'error', listener: (error: Error) => void): this;
addListener(event: 'close', listener: () => void): this;
on(event: string, listener: (...args: any[]) => void): this;
on(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this;
on(event: 'error', listener: (error: Error) => void): this;
on(event: 'close', listener: () => void): this;
once(event: string, listener: (...args: any[]) => void): this;
once(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this;
once(event: 'error', listener: (error: Error) => void): this;
once(event: 'close', listener: () => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this;
prependListener(event: 'error', listener: (error: Error) => void): this;
prependListener(event: 'close', listener: () => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: 'change', listener: (eventType: string, filename: string | Buffer) => void): this;
prependOnceListener(event: 'error', listener: (error: Error) => void): this;
prependOnceListener(event: 'close', listener: () => void): this;
}
/**
* * Extends: `<stream.Readable>`
*
* Instances of `<fs.ReadStream>` are created and returned using the {@link createReadStream} function.
* @since v0.1.93
*/
export class ReadStream extends stream.Readable {
close(): void;
/**
* The number of bytes that have been read so far.
* @since v6.4.0
*/
bytesRead: number;
/**
* The path to the file the stream is reading from as specified in the first
* argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a `<Buffer>`, then`readStream.path` will be a
* `<Buffer>`.
* @since v0.1.93
*/
path: string | Buffer;
/**
* This property is `true` if the underlying file has not been opened yet,
* i.e. before the `'ready'` event is emitted.
* @since v11.2.0, v10.16.0
*/
pending: boolean;
/**
* events.EventEmitter
* 1. open
* 2. close
* 3. ready
*/
addListener(event: 'close', listener: () => void): this;
addListener(event: 'data', listener: (chunk: Buffer | string) => void): this;
addListener(event: 'end', listener: () => void): this;
addListener(event: 'error', listener: (err: Error) => void): this;
addListener(event: 'open', listener: (fd: number) => void): this;
addListener(event: 'pause', listener: () => void): this;
addListener(event: 'readable', listener: () => void): this;
addListener(event: 'ready', listener: () => void): this;
addListener(event: 'resume', listener: () => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
on(event: 'close', listener: () => void): this;
on(event: 'data', listener: (chunk: Buffer | string) => void): this;
on(event: 'end', listener: () => void): this;
on(event: 'error', listener: (err: Error) => void): this;
on(event: 'open', listener: (fd: number) => void): this;
on(event: 'pause', listener: () => void): this;
on(event: 'readable', listener: () => void): this;
on(event: 'ready', listener: () => void): this;
on(event: 'resume', listener: () => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: 'close', listener: () => void): this;
once(event: 'data', listener: (chunk: Buffer | string) => void): this;
once(event: 'end', listener: () => void): this;
once(event: 'error', listener: (err: Error) => void): this;
once(event: 'open', listener: (fd: number) => void): this;
once(event: 'pause', listener: () => void): this;
once(event: 'readable', listener: () => void): this;
once(event: 'ready', listener: () => void): this;
once(event: 'resume', listener: () => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: 'close', listener: () => void): this;
prependListener(event: 'data', listener: (chunk: Buffer | string) => void): this;
prependListener(event: 'end', listener: () => void): this;
prependListener(event: 'error', listener: (err: Error) => void): this;
prependListener(event: 'open', listener: (fd: number) => void): this;
prependListener(event: 'pause', listener: () => void): this;
prependListener(event: 'readable', listener: () => void): this;
prependListener(event: 'ready', listener: () => void): this;
prependListener(event: 'resume', listener: () => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: 'close', listener: () => void): this;
prependOnceListener(event: 'data', listener: (chunk: Buffer | string) => void): this;
prependOnceListener(event: 'end', listener: () => void): this;
prependOnceListener(event: 'error', listener: (err: Error) => void): this;
prependOnceListener(event: 'open', listener: (fd: number) => void): this;
prependOnceListener(event: 'pause', listener: () => void): this;
prependOnceListener(event: 'readable', listener: () => void): this;
prependOnceListener(event: 'ready', listener: () => void): this;
prependOnceListener(event: 'resume', listener: () => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
}
/**
* * Extends `<stream.Writable>`
*
* Instances of `<fs.WriteStream>` are created and returned using the {@link createWriteStream} function.
* @since v0.1.93
*/
export class WriteStream extends stream.Writable {
/**
* Closes `writeStream`. Optionally accepts a
* callback that will be executed once the `writeStream`is closed.
* @since v0.9.4
*/
close(): void;
/**
* The number of bytes written so far. Does not include data that is still queued
* for writing.
* @since v0.4.7
*/
bytesWritten: number;
/**
* The path to the file the stream is writing to as specified in the first
* argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `<Buffer>`, then`writeStream.path` will be a
* `<Buffer>`.
* @since v0.1.93
*/
path: string | Buffer;
/**
* This property is `true` if the underlying file has not been opened yet,
* i.e. before the `'ready'` event is emitted.
* @since v11.2.0
*/
pending: boolean;
/**
* events.EventEmitter
* 1. open
* 2. close
* 3. ready
*/
addListener(event: 'close', listener: () => void): this;
addListener(event: 'drain', listener: () => void): this;
addListener(event: 'error', listener: (err: Error) => void): this;
addListener(event: 'finish', listener: () => void): this;
addListener(event: 'open', listener: (fd: number) => void): this;
addListener(event: 'pipe', listener: (src: stream.Readable) => void): this;
addListener(event: 'ready', listener: () => void): this;
addListener(event: 'unpipe', listener: (src: stream.Readable) => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this;
on(event: 'close', listener: () => void): this;
on(event: 'drain', listener: () => void): this;
on(event: 'error', listener: (err: Error) => void): this;
on(event: 'finish', listener: () => void): this;
on(event: 'open', listener: (fd: number) => void): this;
on(event: 'pipe', listener: (src: stream.Readable) => void): this;
on(event: 'ready', listener: () => void): this;
on(event: 'unpipe', listener: (src: stream.Readable) => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: 'close', listener: () => void): this;
once(event: 'drain', listener: () => void): this;
once(event: 'error', listener: (err: Error) => void): this;
once(event: 'finish', listener: () => void): this;
once(event: 'open', listener: (fd: number) => void): this;
once(event: 'pipe', listener: (src: stream.Readable) => void): this;
once(event: 'ready', listener: () => void): this;
once(event: 'unpipe', listener: (src: stream.Readable) => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: 'close', listener: () => void): this;
prependListener(event: 'drain', listener: () => void): this;
prependListener(event: 'error', listener: (err: Error) => void): this;
prependListener(event: 'finish', listener: () => void): this;
prependListener(event: 'open', listener: (fd: number) => void): this;
prependListener(event: 'pipe', listener: (src: stream.Readable) => void): this;
prependListener(event: 'ready', listener: () => void): this;
prependListener(event: 'unpipe', listener: (src: stream.Readable) => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: 'close', listener: () => void): this;
prependOnceListener(event: 'drain', listener: () => void): this;
prependOnceListener(event: 'error', listener: (err: Error) => void): this;
prependOnceListener(event: 'finish', listener: () => void): this;
prependOnceListener(event: 'open', listener: (fd: number) => void): this;
prependOnceListener(event: 'pipe', listener: (src: stream.Readable) => void): this;
prependOnceListener(event: 'ready', listener: () => void): this;
prependOnceListener(event: 'unpipe', listener: (src: stream.Readable) => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
}
/**
* Asynchronously rename file at `oldPath` to the pathname provided
* as `newPath`. In the case that `newPath` already exists, it will
* be overwritten. If there is a directory at `newPath`, an error will
* be raised instead. No arguments other than a possible exception are
* given to the completion callback.
*
* See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html).
*
* ```js
* import { rename } from 'fs';
*
* rename('oldFile.txt', 'newFile.txt', (err) => {
* if (err) throw err;
* console.log('Rename complete!');
* });
* ```
* @since v0.0.2
*/
export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void;
export namespace rename {
/**
* Asynchronous rename(2) - Change the name or location of a file or directory.
* @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol.
* URL support is _experimental_.
* @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol.
* URL support is _experimental_.
*/
function __promisify__(oldPath: PathLike, newPath: PathLike): Promise<void>;
}
/**
* Renames the file from `oldPath` to `newPath`. Returns `undefined`.
*
* See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details.
* @since v0.1.21
*/
export function renameSync(oldPath: PathLike, newPath: PathLike): void;
/**
* Truncates the file. No arguments other than a possible exception are
* given to the completion callback. A file descriptor can also be passed as the
* first argument. In this case, `fs.ftruncate()` is called.
*
* Passing a file descriptor is deprecated and may result in an error being thrown
* in the future.
*
* See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details.
* @since v0.8.6
*/
export function truncate(path: PathLike, len: number | undefined | null, callback: NoParamCallback): void;
/**
* Asynchronous truncate(2) - Truncate a file to a specified length.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
*/
export function truncate(path: PathLike, callback: NoParamCallback): void;
export namespace truncate {
/**
* Asynchronous truncate(2) - Truncate a file to a specified length.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param len If not specified, defaults to `0`.
*/
function __promisify__(path: PathLike, len?: number | null): Promise<void>;
}
/**
* Truncates the file. Returns `undefined`. A file descriptor can also be
* passed as the first argument. In this case, `fs.ftruncateSync()` is called.
*
* Passing a file descriptor is deprecated and may result in an error being thrown
* in the future.
* @since v0.8.6
*/
export function truncateSync(path: PathLike, len?: number | null): void;
/**
* Truncates the file descriptor. No arguments other than a possible exception are
* given to the completion callback.
*
* See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail.
*
* If the file referred to by the file descriptor was larger than `len` bytes, only
* the first `len` bytes will be retained in the file.
*
* For example, the following program retains only the first four bytes of the
* file:
*
* ```js
* import { open, close, ftruncate } from 'fs';
*
* function closeFd(fd) {
* close(fd, (err) => {
* if (err) throw err;
* });
* }
*
* open('temp.txt', 'r+', (err, fd) => {
* if (err) throw err;
*
* try {
* ftruncate(fd, 4, (err) => {
* closeFd(fd);
* if (err) throw err;
* });
* } catch (err) {
* closeFd(fd);
* if (err) throw err;
* }
* });
* ```
*
* If the file previously was shorter than `len` bytes, it is extended, and the
* extended part is filled with null bytes (`'\0'`):
*
* If `len` is negative then `0` will be used.
* @since v0.8.6
*/
export function ftruncate(fd: number, len: number | undefined | null, callback: NoParamCallback): void;
/**
* Asynchronous ftruncate(2) - Truncate a file to a specified length.
* @param fd A file descriptor.
*/
export function ftruncate(fd: number, callback: NoParamCallback): void;
export namespace ftruncate {
/**
* Asynchronous ftruncate(2) - Truncate a file to a specified length.
* @param fd A file descriptor.
* @param len If not specified, defaults to `0`.
*/
function __promisify__(fd: number, len?: number | null): Promise<void>;
}
/**
* Truncates the file descriptor. Returns `undefined`.
*
* For detailed information, see the documentation of the asynchronous version of
* this API: {@link ftruncate}.
* @since v0.8.6
*/
export function ftruncateSync(fd: number, len?: number | null): void;
/**
* Asynchronously changes owner and group of a file. No arguments other than a
* possible exception are given to the completion callback.
*
* See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail.
* @since v0.1.97
*/
export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void;
export namespace chown {
/**
* Asynchronous chown(2) - Change ownership of a file.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
*/
function __promisify__(path: PathLike, uid: number, gid: number): Promise<void>;
}
/**
* Synchronously changes owner and group of a file. Returns `undefined`.
* This is the synchronous version of {@link chown}.
*
* See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail.
* @since v0.1.97
*/
export function chownSync(path: PathLike, uid: number, gid: number): void;
/**
* Sets the owner of the file. No arguments other than a possible exception are
* given to the completion callback.
*
* See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail.
* @since v0.4.7
*/
export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void;
export namespace fchown {
/**
* Asynchronous fchown(2) - Change ownership of a file.
* @param fd A file descriptor.
*/
function __promisify__(fd: number, uid: number, gid: number): Promise<void>;
}
/**
* Sets the owner of the file. Returns `undefined`.
*
* See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail.
* @since v0.4.7
* @param uid The file's new owner's user id.
* @param gid The file's new group's group id.
*/
export function fchownSync(fd: number, uid: number, gid: number): void;
/**
* Set the owner of the symbolic link. No arguments other than a possible
* exception are given to the completion callback.
*
* See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail.
*/
export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void;
export namespace lchown {
/**
* Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
*/
function __promisify__(path: PathLike, uid: number, gid: number): Promise<void>;
}
/**
* Set the owner for the path. Returns `undefined`.
*
* See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details.
* @param uid The file's new owner's user id.
* @param gid The file's new group's group id.
*/
export function lchownSync(path: PathLike, uid: number, gid: number): void;
/**
* Changes the access and modification times of a file in the same way as {@link utimes}, with the difference that if the path refers to a symbolic
* link, then the link is not dereferenced: instead, the timestamps of the
* symbolic link itself are changed.
*
* No arguments other than a possible exception are given to the completion
* callback.
* @since v14.5.0, v12.19.0
*/
export function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void;
export namespace lutimes {
/**
* Changes the access and modification times of a file in the same way as `fsPromises.utimes()`,
* with the difference that if the path refers to a symbolic link, then the link is not
* dereferenced: instead, the timestamps of the symbolic link itself are changed.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param atime The last access time. If a string is provided, it will be coerced to number.
* @param mtime The last modified time. If a string is provided, it will be coerced to number.
*/
function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise<void>;
}
/**
* Change the file system timestamps of the symbolic link referenced by `path`.
* Returns `undefined`, or throws an exception when parameters are incorrect or
* the operation fails. This is the synchronous version of {@link lutimes}.
* @since v14.5.0, v12.19.0
*/
export function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void;
/**
* Asynchronously changes the permissions of a file. No arguments other than a
* possible exception are given to the completion callback.
*
* See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail.
*
* ```js
* import { chmod } from 'fs';
*
* chmod('my_file.txt', 0o775, (err) => {
* if (err) throw err;
* console.log('The permissions for file "my_file.txt" have been changed!');
* });
* ```
* @since v0.1.30
*/
export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void;
export namespace chmod {
/**
* Asynchronous chmod(2) - Change permissions of a file.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param mode A file mode. If a string is passed, it is parsed as an octal integer.
*/
function __promisify__(path: PathLike, mode: Mode): Promise<void>;
}
/**
* For detailed information, see the documentation of the asynchronous version of
* this API: {@link chmod}.
*
* See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail.
* @since v0.6.7
*/
export function chmodSync(path: PathLike, mode: Mode): void;
/**
* Sets the permissions on the file. No arguments other than a possible exception
* are given to the completion callback.
*
* See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail.
* @since v0.4.7
*/
export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void;
export namespace fchmod {
/**
* Asynchronous fchmod(2) - Change permissions of a file.
* @param fd A file descriptor.
* @param mode A file mode. If a string is passed, it is parsed as an octal integer.
*/
function __promisify__(fd: number, mode: Mode): Promise<void>;
}
/**
* Sets the permissions on the file. Returns `undefined`.
*
* See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail.
* @since v0.4.7
*/
export function fchmodSync(fd: number, mode: Mode): void;
/**
* Changes the permissions on a symbolic link. No arguments other than a possible
* exception are given to the completion callback.
*
* This method is only implemented on macOS.
*
* See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail.
* @deprecated Since v0.4.7
*/
export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void;
export namespace lchmod {
/**
* Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param mode A file mode. If a string is passed, it is parsed as an octal integer.
*/
function __promisify__(path: PathLike, mode: Mode): Promise<void>;
}
/**
* Changes the permissions on a symbolic link. Returns `undefined`.
*
* This method is only implemented on macOS.
*
* See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail.
* @deprecated Since v0.4.7
*/
export function lchmodSync(path: PathLike, mode: Mode): void;
/**
* Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `<fs.Stats>` object.
*
* In case of an error, the `err.code` will be one of `Common System Errors`.
*
* Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended.
* Instead, user code should open/read/write the file directly and handle the
* error raised if the file is not available.
*
* To check if a file exists without manipulating it afterwards, {@link access} is recommended.
*
* For example, given the following directory structure:
*
* ```text
* - txtDir
* -- file.txt
* - app.js
* ```
*
* The next program will check for the stats of the given paths:
*
* ```js
* import { stat } from 'fs';
*
* const pathsToCheck = ['./txtDir', './txtDir/file.txt'];
*
* for (let i = 0; i < pathsToCheck.length; i++) {
* stat(pathsToCheck[i], (err, stats) => {
* console.log(stats.isDirectory());
* console.log(stats);
* });
* }
* ```
*
* The resulting output will resemble:
*
* ```console
* true
* Stats {
* dev: 16777220,
* mode: 16877,
* nlink: 3,
* uid: 501,
* gid: 20,
* rdev: 0,
* blksize: 4096,
* ino: 14214262,
* size: 96,
* blocks: 0,
* atimeMs: 1561174653071.963,
* mtimeMs: 1561174614583.3518,
* ctimeMs: 1561174626623.5366,
* birthtimeMs: 1561174126937.2893,
* atime: 2019-06-22T03:37:33.072Z,
* mtime: 2019-06-22T03:36:54.583Z,
* ctime: 2019-06-22T03:37:06.624Z,
* birthtime: 2019-06-22T03:28:46.937Z
* }
* false
* Stats {
* dev: 16777220,
* mode: 33188,
* nlink: 1,
* uid: 501,
* gid: 20,
* rdev: 0,
* blksize: 4096,
* ino: 14214074,
* size: 8,
* blocks: 8,
* atimeMs: 1561174616618.8555,
* mtimeMs: 1561174614584,
* ctimeMs: 1561174614583.8145,
* birthtimeMs: 1561174007710.7478,
* atime: 2019-06-22T03:36:56.619Z,
* mtime: 2019-06-22T03:36:54.584Z,
* ctime: 2019-06-22T03:36:54.584Z,
* birthtime: 2019-06-22T03:26:47.711Z
* }
* ```
* @since v0.0.2
*/
export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void;
export function stat(
path: PathLike,
options:
| (StatOptions & {
bigint?: false | undefined;
})
| undefined,
callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void
): void;
export function stat(
path: PathLike,
options: StatOptions & {
bigint: true;
},
callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void
): void;
export function stat(path: PathLike, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void;
export namespace stat {
/**
* Asynchronous stat(2) - Get file status.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
*/
function __promisify__(
path: PathLike,
options?: StatOptions & {
bigint?: false | undefined;
}
): Promise<Stats>;
function __promisify__(
path: PathLike,
options: StatOptions & {
bigint: true;
}
): Promise<BigIntStats>;
function __promisify__(path: PathLike, options?: StatOptions): Promise<Stats | BigIntStats>;
}
export interface StatSyncFn<TDescriptor = PathLike> extends Function {
(path: TDescriptor, options?: undefined): Stats;
(
path: TDescriptor,
options?: StatOptions & {
bigint?: false | undefined;
throwIfNoEntry: false;
}
): Stats | undefined;
(
path: TDescriptor,
options: StatOptions & {
bigint: true;
throwIfNoEntry: false;
}
): BigIntStats | undefined;
(
path: TDescriptor,
options?: StatOptions & {
bigint?: false | undefined;
}
): Stats;
(
path: TDescriptor,
options: StatOptions & {
bigint: true;
}
): BigIntStats;
(
path: TDescriptor,
options: StatOptions & {
bigint: boolean;
throwIfNoEntry?: false | undefined;
}
): Stats | BigIntStats;
(path: TDescriptor, options?: StatOptions): Stats | BigIntStats | undefined;
}
/**
* Synchronous stat(2) - Get file status.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
*/
export const statSync: StatSyncFn;
/**
* Invokes the callback with the `<fs.Stats>` for the file descriptor.
*
* See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail.
* @since v0.1.95
*/
export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void;
export function fstat(
fd: number,
options:
| (StatOptions & {
bigint?: false | undefined;
})
| undefined,
callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void
): void;
export function fstat(
fd: number,
options: StatOptions & {
bigint: true;
},
callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void
): void;
export function fstat(fd: number, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void;
export namespace fstat {
/**
* Asynchronous fstat(2) - Get file status.
* @param fd A file descriptor.
*/
function __promisify__(
fd: number,
options?: StatOptions & {
bigint?: false | undefined;
}
): Promise<Stats>;
function __promisify__(
fd: number,
options: StatOptions & {
bigint: true;
}
): Promise<BigIntStats>;
function __promisify__(fd: number, options?: StatOptions): Promise<Stats | BigIntStats>;
}
/**
* Synchronous fstat(2) - Get file status.
* @param fd A file descriptor.
*/
export const fstatSync: StatSyncFn<number>;
/**
* Retrieves the `<fs.Stats>` for the symbolic link referred to by the path.
* The callback gets two arguments `(err, stats)` where `stats` is a `<fs.Stats>` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic
* link, then the link itself is stat-ed, not the file that it refers to.
*
* See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details.
* @since v0.1.30
*/
export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void;
export function lstat(
path: PathLike,
options:
| (StatOptions & {
bigint?: false | undefined;
})
| undefined,
callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void
): void;
export function lstat(
path: PathLike,
options: StatOptions & {
bigint: true;
},
callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void
): void;
export function lstat(path: PathLike, options: StatOptions | undefined, callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void): void;
export namespace lstat {
/**
* Asynchronous lstat(2) - Get file status. Does not dereference symbolic links.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
*/
function __promisify__(
path: PathLike,
options?: StatOptions & {
bigint?: false | undefined;
}
): Promise<Stats>;
function __promisify__(
path: PathLike,
options: StatOptions & {
bigint: true;
}
): Promise<BigIntStats>;
function __promisify__(path: PathLike, options?: StatOptions): Promise<Stats | BigIntStats>;
}
/**
* Synchronous lstat(2) - Get file status. Does not dereference symbolic links.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
*/
export const lstatSync: StatSyncFn;
/**
* Creates a new link from the `existingPath` to the `newPath`. See the POSIX[`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than a
* possible
* exception are given to the completion callback.
* @since v0.1.31
*/
export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void;
export namespace link {
/**
* Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file.
* @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol.
*/
function __promisify__(existingPath: PathLike, newPath: PathLike): Promise<void>;
}
/**
* Creates a new link from the `existingPath` to the `newPath`. See the POSIX[`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`.
* @since v0.1.31
*/
export function linkSync(existingPath: PathLike, newPath: PathLike): void;
/**
* Creates the link called `path` pointing to `target`. No arguments other than a
* possible exception are given to the completion callback.
*
* See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details.
*
* The `type` argument is only available on Windows and ignored on other platforms.
* It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is
* not set, Node.js will autodetect `target` type and use `'file'` or `'dir'`. If
* the `target` does not exist, `'file'` will be used. Windows junction points
* require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path.
*
* Relative targets are relative to the link’s parent directory.
*
* ```js
* import { symlink } from 'fs';
*
* symlink('./mew', './example/mewtwo', callback);
* ```
*
* The above example creates a symbolic link `mewtwo` in the `example` which points
* to `mew` in the same directory:
*
* ```bash
* $ tree example/
* example/
* ├── mew
* └── mewtwo -> ./mew
* ```
* @since v0.1.31
*/
export function symlink(target: PathLike, path: PathLike, type: symlink.Type | undefined | null, callback: NoParamCallback): void;
/**
* Asynchronous symlink(2) - Create a new symbolic link to an existing file.
* @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol.
* @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol.
*/
export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void;
export namespace symlink {
/**
* Asynchronous symlink(2) - Create a new symbolic link to an existing file.
* @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol.
* @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol.
* @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms).
* When using `'junction'`, the `target` argument will automatically be normalized to an absolute path.
*/
function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise<void>;
type Type = 'dir' | 'file' | 'junction';
}
/**
* Returns `undefined`.
*
* For detailed information, see the documentation of the asynchronous version of
* this API: {@link symlink}.
* @since v0.1.31
*/
export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void;
/**
* Reads the contents of the symbolic link referred to by `path`. The callback gets
* two arguments `(err, linkString)`.
*
* See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details.
*
* The optional `options` argument can be a string specifying an encoding, or an
* object with an `encoding` property specifying the character encoding to use for
* the link path passed to the callback. If the `encoding` is set to `'buffer'`,
* the link path returned will be passed as a `<Buffer>` object.
* @since v0.1.31
*/
export function readlink(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void;
/**
* Asynchronous readlink(2) - read value of a symbolic link.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readlink(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void): void;
/**
* Asynchronous readlink(2) - read value of a symbolic link.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readlink(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void): void;
/**
* Asynchronous readlink(2) - read value of a symbolic link.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
*/
export function readlink(path: PathLike, callback: (err: NodeJS.ErrnoException | null, linkString: string) => void): void;
export namespace readlink {
/**
* Asynchronous readlink(2) - read value of a symbolic link.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
function __promisify__(path: PathLike, options?: EncodingOption): Promise<string>;
/**
* Asynchronous readlink(2) - read value of a symbolic link.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
function __promisify__(path: PathLike, options: BufferEncodingOption): Promise<Buffer>;
/**
* Asynchronous readlink(2) - read value of a symbolic link.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
function __promisify__(path: PathLike, options?: EncodingOption): Promise<string | Buffer>;
}
/**
* Returns the symbolic link's string value.
*
* See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details.
*
* The optional `options` argument can be a string specifying an encoding, or an
* object with an `encoding` property specifying the character encoding to use for
* the link path returned. If the `encoding` is set to `'buffer'`,
* the link path returned will be passed as a `<Buffer>` object.
* @since v0.1.31
*/
export function readlinkSync(path: PathLike, options?: EncodingOption): string;
/**
* Synchronous readlink(2) - read value of a symbolic link.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer;
/**
* Synchronous readlink(2) - read value of a symbolic link.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer;
/**
* Asynchronously computes the canonical pathname by resolving `.`, `..` and
* symbolic links.
*
* A canonical pathname is not necessarily unique. Hard links and bind mounts can
* expose a file system entity through many pathnames.
*
* This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions:
*
* 1. No case conversion is performed on case-insensitive file systems.
* 2. The maximum number of symbolic links is platform-independent and generally
* (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports.
*
* The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd`to resolve relative paths.
*
* Only paths that can be converted to UTF8 strings are supported.
*
* The optional `options` argument can be a string specifying an encoding, or an
* object with an `encoding` property specifying the character encoding to use for
* the path passed to the callback. If the `encoding` is set to `'buffer'`,
* the path returned will be passed as a `<Buffer>` object.
*
* If `path` resolves to a socket or a pipe, the function will return a system
* dependent name for that object.
* @since v0.1.31
*/
export function realpath(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void;
/**
* Asynchronous realpath(3) - return the canonicalized absolute pathname.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function realpath(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void;
/**
* Asynchronous realpath(3) - return the canonicalized absolute pathname.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function realpath(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void;
/**
* Asynchronous realpath(3) - return the canonicalized absolute pathname.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
*/
export function realpath(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void;
export namespace realpath {
/**
* Asynchronous realpath(3) - return the canonicalized absolute pathname.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
function __promisify__(path: PathLike, options?: EncodingOption): Promise<string>;
/**
* Asynchronous realpath(3) - return the canonicalized absolute pathname.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
function __promisify__(path: PathLike, options: BufferEncodingOption): Promise<Buffer>;
/**
* Asynchronous realpath(3) - return the canonicalized absolute pathname.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
function __promisify__(path: PathLike, options?: EncodingOption): Promise<string | Buffer>;
/**
* Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html).
*
* The `callback` gets two arguments `(err, resolvedPath)`.
*
* Only paths that can be converted to UTF8 strings are supported.
*
* The optional `options` argument can be a string specifying an encoding, or an
* object with an `encoding` property specifying the character encoding to use for
* the path passed to the callback. If the `encoding` is set to `'buffer'`,
* the path returned will be passed as a `<Buffer>` object.
*
* On Linux, when Node.js is linked against musl libc, the procfs file system must
* be mounted on `/proc` in order for this function to work. Glibc does not have
* this restriction.
* @since v9.2.0
*/
function native(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void;
function native(path: PathLike, options: BufferEncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void): void;
function native(path: PathLike, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void): void;
function native(path: PathLike, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void): void;
}
/**
* Returns the resolved pathname.
*
* For detailed information, see the documentation of the asynchronous version of
* this API: {@link realpath}.
* @since v0.1.31
*/
export function realpathSync(path: PathLike, options?: EncodingOption): string;
/**
* Synchronous realpath(3) - return the canonicalized absolute pathname.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer;
/**
* Synchronous realpath(3) - return the canonicalized absolute pathname.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function realpathSync(path: PathLike, options?: EncodingOption): string | Buffer;
export namespace realpathSync {
function native(path: PathLike, options?: EncodingOption): string;
function native(path: PathLike, options: BufferEncodingOption): Buffer;
function native(path: PathLike, options?: EncodingOption): string | Buffer;
}
/**
* Asynchronously removes a file or symbolic link. No arguments other than a
* possible exception are given to the completion callback.
*
* ```js
* import { unlink } from 'fs';
* // Assuming that 'path/file.txt' is a regular file.
* unlink('path/file.txt', (err) => {
* if (err) throw err;
* console.log('path/file.txt was deleted');
* });
* ```
*
* `fs.unlink()` will not work on a directory, empty or otherwise. To remove a
* directory, use {@link rmdir}.
*
* See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details.
* @since v0.0.2
*/
export function unlink(path: PathLike, callback: NoParamCallback): void;
export namespace unlink {
/**
* Asynchronous unlink(2) - delete a name and possibly the file it refers to.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
*/
function __promisify__(path: PathLike): Promise<void>;
}
/**
* Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`.
* @since v0.1.21
*/
export function unlinkSync(path: PathLike): void;
export interface RmDirOptions {
/**
* If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
* `EPERM` error is encountered, Node.js will retry the operation with a linear
* backoff wait of `retryDelay` ms longer on each try. This option represents the
* number of retries. This option is ignored if the `recursive` option is not
* `true`.
* @default 0
*/
maxRetries?: number | undefined;
/**
* @deprecated since v14.14.0 In future versions of Node.js and will trigger a warning
* `fs.rmdir(path, { recursive: true })` will throw if `path` does not exist or is a file.
* Use `fs.rm(path, { recursive: true, force: true })` instead.
*
* If `true`, perform a recursive directory removal. In
* recursive mode soperations are retried on failure.
* @default false
*/
recursive?: boolean | undefined;
/**
* The amount of time in milliseconds to wait between retries.
* This option is ignored if the `recursive` option is not `true`.
* @default 100
*/
retryDelay?: number | undefined;
}
/**
* Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given
* to the completion callback.
*
* Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on
* Windows and an `ENOTDIR` error on POSIX.
*
* To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`.
* @since v0.0.2
*/
export function rmdir(path: PathLike, callback: NoParamCallback): void;
export function rmdir(path: PathLike, options: RmDirOptions, callback: NoParamCallback): void;
export namespace rmdir {
/**
* Asynchronous rmdir(2) - delete a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
*/
function __promisify__(path: PathLike, options?: RmDirOptions): Promise<void>;
}
/**
* Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`.
*
* Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error
* on Windows and an `ENOTDIR` error on POSIX.
*
* To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`.
* @since v0.1.21
*/
export function rmdirSync(path: PathLike, options?: RmDirOptions): void;
export interface RmOptions {
/**
* When `true`, exceptions will be ignored if `path` does not exist.
* @default false
*/
force?: boolean | undefined;
/**
* If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or
* `EPERM` error is encountered, Node.js will retry the operation with a linear
* backoff wait of `retryDelay` ms longer on each try. This option represents the
* number of retries. This option is ignored if the `recursive` option is not
* `true`.
* @default 0
*/
maxRetries?: number | undefined;
/**
* If `true`, perform a recursive directory removal. In
* recursive mode, operations are retried on failure.
* @default false
*/
recursive?: boolean | undefined;
/**
* The amount of time in milliseconds to wait between retries.
* This option is ignored if the `recursive` option is not `true`.
* @default 100
*/
retryDelay?: number | undefined;
}
/**
* Asynchronously removes files and directories (modeled on the standard POSIX `rm`utility). No arguments other than a possible exception are given to the
* completion callback.
* @since v14.14.0
*/
export function rm(path: PathLike, callback: NoParamCallback): void;
export function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void;
export namespace rm {
/**
* Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility).
*/
function __promisify__(path: PathLike, options?: RmOptions): Promise<void>;
}
/**
* Synchronously removes files and directories (modeled on the standard POSIX `rm`utility). Returns `undefined`.
* @since v14.14.0
*/
export function rmSync(path: PathLike, options?: RmOptions): void;
export interface MakeDirectoryOptions {
/**
* Indicates whether parent folders should be created.
* If a folder was created, the path to the first created folder will be returned.
* @default false
*/
recursive?: boolean | undefined;
/**
* A file mode. If a string is passed, it is parsed as an octal integer. If not specified
* @default 0o777
*/
mode?: Mode | undefined;
}
/**
* Asynchronously creates a directory.
*
* The callback is given a possible exception and, if `recursive` is `true`, the
* first directory path created, `(err, [path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was
* created.
*
* The optional `options` argument can be an integer specifying `mode` (permission
* and sticky bits), or an object with a `mode` property and a `recursive`property indicating whether parent directories should be created. Calling`fs.mkdir()` when `path` is a directory that
* exists results in an error only
* when `recursive` is false.
*
* ```js
* import { mkdir } from 'fs';
*
* // Creates /tmp/a/apple, regardless of whether `/tmp` and /tmp/a exist.
* mkdir('/tmp/a/apple', { recursive: true }, (err) => {
* if (err) throw err;
* });
* ```
*
* On Windows, using `fs.mkdir()` on the root directory even with recursion will
* result in an error:
*
* ```js
* import { mkdir } from 'fs';
*
* mkdir('/', { recursive: true }, (err) => {
* // => [Error: EPERM: operation not permitted, mkdir 'C:\']
* });
* ```
*
* See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details.
* @since v0.1.8
*/
export function mkdir(
path: PathLike,
options: MakeDirectoryOptions & {
recursive: true;
},
callback: (err: NodeJS.ErrnoException | null, path?: string) => void
): void;
/**
* Asynchronous mkdir(2) - create a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders
* should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`.
*/
export function mkdir(
path: PathLike,
options:
| Mode
| (MakeDirectoryOptions & {
recursive?: false | undefined;
})
| null
| undefined,
callback: NoParamCallback
): void;
/**
* Asynchronous mkdir(2) - create a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders
* should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`.
*/
export function mkdir(path: PathLike, options: Mode | MakeDirectoryOptions | null | undefined, callback: (err: NodeJS.ErrnoException | null, path?: string) => void): void;
/**
* Asynchronous mkdir(2) - create a directory with a mode of `0o777`.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
*/
export function mkdir(path: PathLike, callback: NoParamCallback): void;
export namespace mkdir {
/**
* Asynchronous mkdir(2) - create a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders
* should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`.
*/
function __promisify__(
path: PathLike,
options: MakeDirectoryOptions & {
recursive: true;
}
): Promise<string | undefined>;
/**
* Asynchronous mkdir(2) - create a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders
* should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`.
*/
function __promisify__(
path: PathLike,
options?:
| Mode
| (MakeDirectoryOptions & {
recursive?: false | undefined;
})
| null
): Promise<void>;
/**
* Asynchronous mkdir(2) - create a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders
* should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`.
*/
function __promisify__(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise<string | undefined>;
}
/**
* Synchronously creates a directory. Returns `undefined`, or if `recursive` is`true`, the first directory path created.
* This is the synchronous version of {@link mkdir}.
*
* See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details.
* @since v0.1.21
*/
export function mkdirSync(
path: PathLike,
options: MakeDirectoryOptions & {
recursive: true;
}
): string | undefined;
/**
* Synchronous mkdir(2) - create a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders
* should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`.
*/
export function mkdirSync(
path: PathLike,
options?:
| Mode
| (MakeDirectoryOptions & {
recursive?: false | undefined;
})
| null
): void;
/**
* Synchronous mkdir(2) - create a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders
* should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`.
*/
export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined;
/**
* Creates a unique temporary directory.
*
* Generates six random characters to be appended behind a required`prefix` to create a unique temporary directory. Due to platform
* inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms,
* notably the BSDs, can return more than six random characters, and replace
* trailing `X` characters in `prefix` with random characters.
*
* The created directory path is passed as a string to the callback's second
* parameter.
*
* The optional `options` argument can be a string specifying an encoding, or an
* object with an `encoding` property specifying the character encoding to use.
*
* ```js
* import { mkdtemp } from 'fs';
*
* mkdtemp(path.join(os.tmpdir(), 'foo-'), (err, directory) => {
* if (err) throw err;
* console.log(directory);
* // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2
* });
* ```
*
* The `fs.mkdtemp()` method will append the six randomly selected characters
* directly to the `prefix` string. For instance, given a directory `/tmp`, if the
* intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator
* (`require('path').sep`).
*
* ```js
* import { tmpdir } from 'os';
* import { mkdtemp } from 'fs';
*
* // The parent directory for the new temporary directory
* const tmpDir = tmpdir();
*
* // This method is *INCORRECT*:
* mkdtemp(tmpDir, (err, directory) => {
* if (err) throw err;
* console.log(directory);
* // Will print something similar to `/tmpabc123`.
* // A new temporary directory is created at the file system root
* // rather than *within* the /tmp directory.
* });
*
* // This method is *CORRECT*:
* import { sep } from 'path';
* mkdtemp(`${tmpDir}${sep}`, (err, directory) => {
* if (err) throw err;
* console.log(directory);
* // Will print something similar to `/tmp/abc123`.
* // A new temporary directory is created within
* // the /tmp directory.
* });
* ```
* @since v5.10.0
*/
export function mkdtemp(prefix: string, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void;
/**
* Asynchronously creates a unique temporary directory.
* Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function mkdtemp(
prefix: string,
options:
| 'buffer'
| {
encoding: 'buffer';
},
callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void
): void;
/**
* Asynchronously creates a unique temporary directory.
* Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function mkdtemp(prefix: string, options: EncodingOption, callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void): void;
/**
* Asynchronously creates a unique temporary directory.
* Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
*/
export function mkdtemp(prefix: string, callback: (err: NodeJS.ErrnoException | null, folder: string) => void): void;
export namespace mkdtemp {
/**
* Asynchronously creates a unique temporary directory.
* Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
function __promisify__(prefix: string, options?: EncodingOption): Promise<string>;
/**
* Asynchronously creates a unique temporary directory.
* Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
function __promisify__(prefix: string, options: BufferEncodingOption): Promise<Buffer>;
/**
* Asynchronously creates a unique temporary directory.
* Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
function __promisify__(prefix: string, options?: EncodingOption): Promise<string | Buffer>;
}
/**
* Returns the created directory path.
*
* For detailed information, see the documentation of the asynchronous version of
* this API: {@link mkdtemp}.
*
* The optional `options` argument can be a string specifying an encoding, or an
* object with an `encoding` property specifying the character encoding to use.
* @since v5.10.0
*/
export function mkdtempSync(prefix: string, options?: EncodingOption): string;
/**
* Synchronously creates a unique temporary directory.
* Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer;
/**
* Synchronously creates a unique temporary directory.
* Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function mkdtempSync(prefix: string, options?: EncodingOption): string | Buffer;
/**
* Reads the contents of a directory. The callback gets two arguments `(err, files)`where `files` is an array of the names of the files in the directory excluding`'.'` and `'..'`.
*
* See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details.
*
* The optional `options` argument can be a string specifying an encoding, or an
* object with an `encoding` property specifying the character encoding to use for
* the filenames passed to the callback. If the `encoding` is set to `'buffer'`,
* the filenames returned will be passed as `<Buffer>` objects.
*
* If `options.withFileTypes` is set to `true`, the `files` array will contain `<fs.Dirent>` objects.
* @since v0.1.8
*/
export function readdir(
path: PathLike,
options:
| {
encoding: BufferEncoding | null;
withFileTypes?: false | undefined;
}
| BufferEncoding
| undefined
| null,
callback: (err: NodeJS.ErrnoException | null, files: string[]) => void
): void;
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readdir(
path: PathLike,
options:
| {
encoding: 'buffer';
withFileTypes?: false | undefined;
}
| 'buffer',
callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void
): void;
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readdir(
path: PathLike,
options:
| (ObjectEncodingOptions & {
withFileTypes?: false | undefined;
})
| BufferEncoding
| undefined
| null,
callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void
): void;
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
*/
export function readdir(path: PathLike, callback: (err: NodeJS.ErrnoException | null, files: string[]) => void): void;
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options If called with `withFileTypes: true` the result data will be an array of Dirent.
*/
export function readdir(
path: PathLike,
options: ObjectEncodingOptions & {
withFileTypes: true;
},
callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void
): void;
export namespace readdir {
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
function __promisify__(
path: PathLike,
options?:
| {
encoding: BufferEncoding | null;
withFileTypes?: false | undefined;
}
| BufferEncoding
| null
): Promise<string[]>;
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
function __promisify__(
path: PathLike,
options:
| 'buffer'
| {
encoding: 'buffer';
withFileTypes?: false | undefined;
}
): Promise<Buffer[]>;
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
function __promisify__(
path: PathLike,
options?:
| (ObjectEncodingOptions & {
withFileTypes?: false | undefined;
})
| BufferEncoding
| null
): Promise<string[] | Buffer[]>;
/**
* Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options If called with `withFileTypes: true` the result data will be an array of Dirent
*/
function __promisify__(
path: PathLike,
options: ObjectEncodingOptions & {
withFileTypes: true;
}
): Promise<Dirent[]>;
}
/**
* Reads the contents of the directory.
*
* See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details.
*
* The optional `options` argument can be a string specifying an encoding, or an
* object with an `encoding` property specifying the character encoding to use for
* the filenames returned. If the `encoding` is set to `'buffer'`,
* the filenames returned will be passed as `<Buffer>` objects.
*
* If `options.withFileTypes` is set to `true`, the result will contain `<fs.Dirent>` objects.
* @since v0.1.21
*/
export function readdirSync(
path: PathLike,
options?:
| {
encoding: BufferEncoding | null;
withFileTypes?: false | undefined;
}
| BufferEncoding
| null
): string[];
/**
* Synchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readdirSync(
path: PathLike,
options:
| {
encoding: 'buffer';
withFileTypes?: false | undefined;
}
| 'buffer'
): Buffer[];
/**
* Synchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/
export function readdirSync(
path: PathLike,
options?:
| (ObjectEncodingOptions & {
withFileTypes?: false | undefined;
})
| BufferEncoding
| null
): string[] | Buffer[];
/**
* Synchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options If called with `withFileTypes: true` the result data will be an array of Dirent.
*/
export function readdirSync(
path: PathLike,
options: ObjectEncodingOptions & {
withFileTypes: true;
}
): Dirent[];
/**
* Closes the file descriptor. No arguments other than a possible exception are
* given to the completion callback.
*
* Calling `fs.close()` on any file descriptor (`fd`) that is currently in use
* through any other `fs` operation may lead to undefined behavior.
*
* See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail.
* @since v0.0.2
*/
export function close(fd: number, callback?: NoParamCallback): void;
export namespace close {
/**
* Asynchronous close(2) - close a file descriptor.
* @param fd A file descriptor.
*/
function __promisify__(fd: number): Promise<void>;
}
/**
* Closes the file descriptor. Returns `undefined`.
*
* Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use
* through any other `fs` operation may lead to undefined behavior.
*
* See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail.
* @since v0.1.21
*/
export function closeSync(fd: number): void;
/**
* Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details.
*
* `mode` sets the file mode (permission and sticky bits), but only if the file was
* created. On Windows, only the write permission can be manipulated; see {@link chmod}.
*
* The callback gets two arguments `(err, fd)`.
*
* Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented
* by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains
* a colon, Node.js will open a file system stream, as described by[this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams).
*
* Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc.
* @since v0.0.2
* @param flags See `support of file system `flags``.
*/
export function open(path: PathLike, flags: OpenMode, mode: Mode | undefined | null, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void;
/**
* Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
*/
export function open(path: PathLike, flags: OpenMode, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void;
export namespace open {
/**
* Asynchronous open(2) - open and possibly create a file.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`.
*/
function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise<number>;
}
/**
* Returns an integer representing the file descriptor.
*
* For detailed information, see the documentation of the asynchronous version of
* this API: {@link open}.
* @since v0.1.21
*/
export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number;
/**
* Change the file system timestamps of the object referenced by `path`.
*
* The `atime` and `mtime` arguments follow these rules:
*
* * Values can be either numbers representing Unix epoch time in seconds,`Date`s, or a numeric string like `'123456789.0'`.
* * If the value can not be converted to a number, or is `NaN`, `Infinity` or`-Infinity`, an `Error` will be thrown.
* @since v0.4.2
*/
export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void;
export namespace utimes {
/**
* Asynchronously change file timestamps of the file referenced by the supplied path.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param atime The last access time. If a string is provided, it will be coerced to number.
* @param mtime The last modified time. If a string is provided, it will be coerced to number.
*/
function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise<void>;
}
/**
* Returns `undefined`.
*
* For detailed information, see the documentation of the asynchronous version of
* this API: {@link utimes}.
* @since v0.4.2
*/
export function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void;
/**
* Change the file system timestamps of the object referenced by the supplied file
* descriptor. See {@link utimes}.
* @since v0.4.2
*/
export function futimes(fd: number, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void;
export namespace futimes {
/**
* Asynchronously change file timestamps of the file referenced by the supplied file descriptor.
* @param fd A file descriptor.
* @param atime The last access time. If a string is provided, it will be coerced to number.
* @param mtime The last modified time. If a string is provided, it will be coerced to number.
*/
function __promisify__(fd: number, atime: TimeLike, mtime: TimeLike): Promise<void>;
}
/**
* Synchronous version of {@link futimes}. Returns `undefined`.
* @since v0.4.2
*/
export function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void;
/**
* Request that all data for the open file descriptor is flushed to the storage
* device. The specific implementation is operating system and device specific.
* Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other
* than a possible exception are given to the completion callback.
* @since v0.1.96
*/
export function fsync(fd: number, callback: NoParamCallback): void;
export namespace fsync {
/**
* Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device.
* @param fd A file descriptor.
*/
function __promisify__(fd: number): Promise<void>;
}
/**
* Request that all data for the open file descriptor is flushed to the storage
* device. The specific implementation is operating system and device specific.
* Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`.
* @since v0.1.96
*/
export function fsyncSync(fd: number): void;
/**
* Write `buffer` to the file specified by `fd`. If `buffer` is a normal object, it
* must have an own `toString` function property.
*
* `offset` determines the part of the buffer to be written, and `length` is
* an integer specifying the number of bytes to write.
*
* `position` refers to the offset from the beginning of the file where this data
* should be written. If `typeof position !== 'number'`, the data will be written
* at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html).
*
* The callback will be given three arguments `(err, bytesWritten, buffer)` where`bytesWritten` specifies how many _bytes_ were written from `buffer`.
*
* If this method is invoked as its `util.promisify()` ed version, it returns
* a promise for an `Object` with `bytesWritten` and `buffer` properties.
*
* It is unsafe to use `fs.write()` multiple times on the same file without waiting
* for the callback. For this scenario, {@link createWriteStream} is
* recommended.
*
* On Linux, positional writes don't work when the file is opened in append mode.
* The kernel ignores the position argument and always appends the data to
* the end of the file.
* @since v0.0.2
*/
export function write<TBuffer extends NodeJS.ArrayBufferView>(
fd: number,
buffer: TBuffer,
offset: number | undefined | null,
length: number | undefined | null,
position: number | undefined | null,
callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void
): void;
/**
* Asynchronously writes `buffer` to the file referenced by the supplied file descriptor.
* @param fd A file descriptor.
* @param offset The part of the buffer to be written. If not supplied, defaults to `0`.
* @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`.
*/
export function write<TBuffer extends NodeJS.ArrayBufferView>(
fd: number,
buffer: TBuffer,
offset: number | undefined | null,
length: number | undefined | null,
callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void
): void;
/**
* Asynchronously writes `buffer` to the file referenced by the supplied file descriptor.
* @param fd A file descriptor.
* @param offset The part of the buffer to be written. If not supplied, defaults to `0`.
*/
export function write<TBuffer extends NodeJS.ArrayBufferView>(
fd: number,
buffer: TBuffer,
offset: number | undefined | null,
callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void
): void;
/**
* Asynchronously writes `buffer` to the file referenced by the supplied file descriptor.
* @param fd A file descriptor.
*/
export function write<TBuffer extends NodeJS.ArrayBufferView>(fd: number, buffer: TBuffer, callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void): void;
/**
* Asynchronously writes `string` to the file referenced by the supplied file descriptor.
* @param fd A file descriptor.
* @param string A string to write.
* @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
* @param encoding The expected string encoding.
*/
export function write(
fd: number,
string: string,
position: number | undefined | null,
encoding: BufferEncoding | undefined | null,
callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void
): void;
/**
* Asynchronously writes `string` to the file referenced by the supplied file descriptor.
* @param fd A file descriptor.
* @param string A string to write.
* @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
*/
export function write(fd: number, string: string, position: number | undefined | null, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void;
/**
* Asynchronously writes `string` to the file referenced by the supplied file descriptor.
* @param fd A file descriptor.
* @param string A string to write.
*/
export function write(fd: number, string: string, callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void): void;
export namespace write {
/**
* Asynchronously writes `buffer` to the file referenced by the supplied file descriptor.
* @param fd A file descriptor.
* @param offset The part of the buffer to be written. If not supplied, defaults to `0`.
* @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`.
* @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
*/
function __promisify__<TBuffer extends NodeJS.ArrayBufferView>(
fd: number,
buffer?: TBuffer,
offset?: number,
length?: number,
position?: number | null
): Promise<{
bytesWritten: number;
buffer: TBuffer;
}>;
/**
* Asynchronously writes `string` to the file referenced by the supplied file descriptor.
* @param fd A file descriptor.
* @param string A string to write.
* @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
* @param encoding The expected string encoding.
*/
function __promisify__(
fd: number,
string: string,
position?: number | null,
encoding?: BufferEncoding | null
): Promise<{
bytesWritten: number;
buffer: string;
}>;
}
/**
* For detailed information, see the documentation of the asynchronous version of
* this API: {@link write}.
* @since v0.1.21
* @return The number of bytes written.
*/
export function writeSync(fd: number, buffer: NodeJS.ArrayBufferView, offset?: number | null, length?: number | null, position?: number | null): number;
/**
* Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written.
* @param fd A file descriptor.
* @param string A string to write.
* @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position.
* @param encoding The expected string encoding.
*/
export function writeSync(fd: number, string: string, position?: number | null, encoding?: BufferEncoding | null): number;
export type ReadPosition = number | bigint;
/**
* Read data from the file specified by `fd`.
*
* The callback is given the three arguments, `(err, bytesRead, buffer)`.
*
* If the file is not modified concurrently, the end-of-file is reached when the
* number of bytes read is zero.
*
* If this method is invoked as its `util.promisify()` ed version, it returns
* a promise for an `Object` with `bytesRead` and `buffer` properties.
* @since v0.0.2
* @param buffer The buffer that the data will be written to.
* @param offset The position in `buffer` to write the data to.
* @param length The number of bytes to read.
* @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If
* `position` is an integer, the file position will be unchanged.
*/
export function read<TBuffer extends NodeJS.ArrayBufferView>(
fd: number,
buffer: TBuffer,
offset: number,
length: number,
position: ReadPosition | null,
callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void
): void;
export namespace read {
/**
* @param fd A file descriptor.
* @param buffer The buffer that the data will be written to.
* @param offset The offset in the buffer at which to start writing.
* @param length The number of bytes to read.
* @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position.
*/
function __promisify__<TBuffer extends NodeJS.ArrayBufferView>(
fd: number,
buffer: TBuffer,
offset: number,
length: number,
position: number | null
): Promise<{
bytesRead: number;
buffer: TBuffer;
}>;
}
export interface ReadSyncOptions {
/**
* @default 0
*/
offset?: number | undefined;
/**
* @default `length of buffer`
*/
length?: number | undefined;
/**
* @default null
*/
position?: ReadPosition | null | undefined;
}
/**
* Returns the number of `bytesRead`.
*
* For detailed information, see the documentation of the asynchronous version of
* this API: {@link read}.
* @since v0.1.21
*/
export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, offset: number, length: number, position: ReadPosition | null): number;
/**
* Similar to the above `fs.readSync` function, this version takes an optional `options` object.
* If no `options` object is specified, it will default with the above values.
*/
export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number;
/**
* Asynchronously reads the entire contents of a file.
*
* ```js
* import { readFile } from 'fs';
*
* readFile('/etc/passwd', (err, data) => {
* if (err) throw err;
* console.log(data);
* });
* ```
*
* The callback is passed two arguments `(err, data)`, where `data` is the
* contents of the file.
*
* If no encoding is specified, then the raw buffer is returned.
*
* If `options` is a string, then it specifies the encoding:
*
* ```js
* import { readFile } from 'fs';
*
* readFile('/etc/passwd', 'utf8', callback);
* ```
*
* When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an
* error will be returned. On FreeBSD, a representation of the directory's contents
* will be returned.
*
* ```js
* import { readFile } from 'fs';
*
* // macOS, Linux, and Windows
* readFile('<directory>', (err, data) => {
* // => [Error: EISDIR: illegal operation on a directory, read <directory>]
* });
*
* // FreeBSD
* readFile('<directory>', (err, data) => {
* // => null, <data>
* });
* ```
*
* It is possible to abort an ongoing request using an `AbortSignal`. If a
* request is aborted the callback is called with an `AbortError`:
*
* ```js
* import { readFile } from 'fs';
*
* const controller = new AbortController();
* const signal = controller.signal;
* readFile(fileInfo[0].name, { signal }, (err, buf) => {
* // ...
* });
* // When you want to abort the request
* controller.abort();
* ```
*
* The `fs.readFile()` function buffers the entire file. To minimize memory costs,
* when possible prefer streaming via `fs.createReadStream()`.
*
* Aborting an ongoing request does not abort individual operating
* system requests but rather the internal buffering `fs.readFile` performs.
* @since v0.1.29
* @param path filename or file descriptor
*/
export function readFile(
path: PathOrFileDescriptor,
options:
| ({
encoding?: null | undefined;
flag?: string | undefined;
} & Abortable)
| undefined
| null,
callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void
): void;
/**
* Asynchronously reads the entire contents of a file.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* If a file descriptor is provided, the underlying file will _not_ be closed automatically.
* @param options Either the encoding for the result, or an object that contains the encoding and an optional flag.
* If a flag is not provided, it defaults to `'r'`.
*/
export function readFile(
path: PathOrFileDescriptor,
options:
| ({
encoding: BufferEncoding;
flag?: string | undefined;
} & Abortable)
| string,
callback: (err: NodeJS.ErrnoException | null, data: string) => void
): void;
/**
* Asynchronously reads the entire contents of a file.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* If a file descriptor is provided, the underlying file will _not_ be closed automatically.
* @param options Either the encoding for the result, or an object that contains the encoding and an optional flag.
* If a flag is not provided, it defaults to `'r'`.
*/
export function readFile(
path: PathOrFileDescriptor,
options:
| (ObjectEncodingOptions & {
flag?: string | undefined;
} & Abortable)
| string
| undefined
| null,
callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void
): void;
/**
* Asynchronously reads the entire contents of a file.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* If a file descriptor is provided, the underlying file will _not_ be closed automatically.
*/
export function readFile(path: PathOrFileDescriptor, callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void): void;
export namespace readFile {
/**
* Asynchronously reads the entire contents of a file.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* If a file descriptor is provided, the underlying file will _not_ be closed automatically.
* @param options An object that may contain an optional flag.
* If a flag is not provided, it defaults to `'r'`.
*/
function __promisify__(
path: PathOrFileDescriptor,
options?: {
encoding?: null | undefined;
flag?: string | undefined;
} | null
): Promise<Buffer>;
/**
* Asynchronously reads the entire contents of a file.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* URL support is _experimental_.
* If a file descriptor is provided, the underlying file will _not_ be closed automatically.
* @param options Either the encoding for the result, or an object that contains the encoding and an optional flag.
* If a flag is not provided, it defaults to `'r'`.
*/
function __promisify__(
path: PathOrFileDescriptor,
options:
| {
encoding: BufferEncoding;
flag?: string | undefined;
}
| string
): Promise<string>;
/**
* Asynchronously reads the entire contents of a file.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* URL support is _experimental_.
* If a file descriptor is provided, the underlying file will _not_ be closed automatically.
* @param options Either the encoding for the result, or an object that contains the encoding and an optional flag.
* If a flag is not provided, it defaults to `'r'`.
*/
function __promisify__(
path: PathOrFileDescriptor,
options?:
| (ObjectEncodingOptions & {
flag?: string | undefined;
})
| string
| null
): Promise<string | Buffer>;
}
/**
* Returns the contents of the `path`.
*
* For detailed information, see the documentation of the asynchronous version of
* this API: {@link readFile}.
*
* If the `encoding` option is specified then this function returns a
* string. Otherwise it returns a buffer.
*
* Similar to {@link readFile}, when the path is a directory, the behavior of`fs.readFileSync()` is platform-specific.
*
* ```js
* import { readFileSync } from 'fs';
*
* // macOS, Linux, and Windows
* readFileSync('<directory>');
* // => [Error: EISDIR: illegal operation on a directory, read <directory>]
*
* // FreeBSD
* readFileSync('<directory>'); // => <data>
* ```
* @since v0.1.8
* @param path filename or file descriptor
*/
export function readFileSync(
path: PathOrFileDescriptor,
options?: {
encoding?: null | undefined;
flag?: string | undefined;
} | null
): Buffer;
/**
* Synchronously reads the entire contents of a file.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* If a file descriptor is provided, the underlying file will _not_ be closed automatically.
* @param options Either the encoding for the result, or an object that contains the encoding and an optional flag.
* If a flag is not provided, it defaults to `'r'`.
*/
export function readFileSync(
path: PathOrFileDescriptor,
options:
| {
encoding: BufferEncoding;
flag?: string | undefined;
}
| BufferEncoding
): string;
/**
* Synchronously reads the entire contents of a file.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* If a file descriptor is provided, the underlying file will _not_ be closed automatically.
* @param options Either the encoding for the result, or an object that contains the encoding and an optional flag.
* If a flag is not provided, it defaults to `'r'`.
*/
export function readFileSync(
path: PathOrFileDescriptor,
options?:
| (ObjectEncodingOptions & {
flag?: string | undefined;
})
| BufferEncoding
| null
): string | Buffer;
export type WriteFileOptions =
| (ObjectEncodingOptions &
Abortable & {
mode?: Mode | undefined;
flag?: string | undefined;
})
| string
| null;
/**
* When `file` is a filename, asynchronously writes data to the file, replacing the
* file if it already exists. `data` can be a string or a buffer.
*
* When `file` is a file descriptor, the behavior is similar to calling`fs.write()` directly (which is recommended). See the notes below on using
* a file descriptor.
*
* The `encoding` option is ignored if `data` is a buffer.
* If `data` is a normal object, it must have an own `toString` function property.
*
* ```js
* import { writeFile } from 'fs';
*
* const data = new Uint8Array(Buffer.from('Hello Node.js'));
* writeFile('message.txt', data, (err) => {
* if (err) throw err;
* console.log('The file has been saved!');
* });
* ```
*
* If `options` is a string, then it specifies the encoding:
*
* ```js
* import { writeFile } from 'fs';
*
* writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
* ```
*
* It is unsafe to use `fs.writeFile()` multiple times on the same file without
* waiting for the callback. For this scenario, {@link createWriteStream} is
* recommended.
*
* Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that
* performs multiple `write` calls internally to write the buffer passed to it.
* For performance sensitive code consider using {@link createWriteStream}.
*
* It is possible to use an `<AbortSignal>` to cancel an `fs.writeFile()`.
* Cancelation is "best effort", and some amount of data is likely still
* to be written.
*
* ```js
* import { writeFile } from 'fs';
*
* const controller = new AbortController();
* const { signal } = controller;
* const data = new Uint8Array(Buffer.from('Hello Node.js'));
* writeFile('message.txt', data, { signal }, (err) => {
* // When a request is aborted - the callback is called with an AbortError
* });
* // When the request should be aborted
* controller.abort();
* ```
*
* Aborting an ongoing request does not abort individual operating
* system requests but rather the internal buffering `fs.writeFile` performs.
* @since v0.1.29
* @param file filename or file descriptor
*/
export function writeFile(file: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options: WriteFileOptions, callback: NoParamCallback): void;
/**
* Asynchronously writes data to a file, replacing the file if it already exists.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* If a file descriptor is provided, the underlying file will _not_ be closed automatically.
* @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.
*/
export function writeFile(path: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, callback: NoParamCallback): void;
export namespace writeFile {
/**
* Asynchronously writes data to a file, replacing the file if it already exists.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* URL support is _experimental_.
* If a file descriptor is provided, the underlying file will _not_ be closed automatically.
* @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.
* @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag.
* If `encoding` is not supplied, the default of `'utf8'` is used.
* If `mode` is not supplied, the default of `0o666` is used.
* If `mode` is a string, it is parsed as an octal integer.
* If `flag` is not supplied, the default of `'w'` is used.
*/
function __promisify__(path: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): Promise<void>;
}
/**
* Returns `undefined`.
*
* For detailed information, see the documentation of the asynchronous version of
* this API: {@link writeFile}.
* @since v0.1.29
* @param file filename or file descriptor
*/
export function writeFileSync(file: PathOrFileDescriptor, data: string | NodeJS.ArrayBufferView, options?: WriteFileOptions): void;
/**
* Asynchronously append data to a file, creating the file if it does not yet
* exist. `data` can be a string or a `<Buffer>`.
*
* ```js
* import { appendFile } from 'fs';
*
* appendFile('message.txt', 'data to append', (err) => {
* if (err) throw err;
* console.log('The "data to append" was appended to file!');
* });
* ```
*
* If `options` is a string, then it specifies the encoding:
*
* ```js
* import { appendFile } from 'fs';
*
* appendFile('message.txt', 'data to append', 'utf8', callback);
* ```
*
* The `path` may be specified as a numeric file descriptor that has been opened
* for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will
* not be closed automatically.
*
* ```js
* import { open, close, appendFile } from 'fs';
*
* function closeFd(fd) {
* close(fd, (err) => {
* if (err) throw err;
* });
* }
*
* open('message.txt', 'a', (err, fd) => {
* if (err) throw err;
*
* try {
* appendFile(fd, 'data to append', 'utf8', (err) => {
* closeFd(fd);
* if (err) throw err;
* });
* } catch (err) {
* closeFd(fd);
* throw err;
* }
* });
* ```
* @since v0.6.7
* @param path filename or file descriptor
*/
export function appendFile(path: PathOrFileDescriptor, data: string | Uint8Array, options: WriteFileOptions, callback: NoParamCallback): void;
/**
* Asynchronously append data to a file, creating the file if it does not exist.
* @param file A path to a file. If a URL is provided, it must use the `file:` protocol.
* If a file descriptor is provided, the underlying file will _not_ be closed automatically.
* @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.
*/
export function appendFile(file: PathOrFileDescriptor, data: string | Uint8Array, callback: NoParamCallback): void;
export namespace appendFile {
/**
* Asynchronously append data to a file, creating the file if it does not exist.
* @param file A path to a file. If a URL is provided, it must use the `file:` protocol.
* URL support is _experimental_.
* If a file descriptor is provided, the underlying file will _not_ be closed automatically.
* @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string.
* @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag.
* If `encoding` is not supplied, the default of `'utf8'` is used.
* If `mode` is not supplied, the default of `0o666` is used.
* If `mode` is a string, it is parsed as an octal integer.
* If `flag` is not supplied, the default of `'a'` is used.
*/
function __promisify__(file: PathOrFileDescriptor, data: string | Uint8Array, options?: WriteFileOptions): Promise<void>;
}
/**
* Synchronously append data to a file, creating the file if it does not yet
* exist. `data` can be a string or a `<Buffer>`.
*
* ```js
* import { appendFileSync } from 'fs';
*
* try {
* appendFileSync('message.txt', 'data to append');
* console.log('The "data to append" was appended to file!');
* } catch (err) {
* // Handle the error
* }
* ```
*
* If `options` is a string, then it specifies the encoding:
*
* ```js
* import { appendFileSync } from 'fs';
*
* appendFileSync('message.txt', 'data to append', 'utf8');
* ```
*
* The `path` may be specified as a numeric file descriptor that has been opened
* for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will
* not be closed automatically.
*
* ```js
* import { openSync, closeSync, appendFileSync } from 'fs';
*
* let fd;
*
* try {
* fd = openSync('message.txt', 'a');
* appendFileSync(fd, 'data to append', 'utf8');
* } catch (err) {
* // Handle the error
* } finally {
* if (fd !== undefined)
* closeSync(fd);
* }
* ```
* @since v0.6.7
* @param path filename or file descriptor
*/
export function appendFileSync(path: PathOrFileDescriptor, data: string | Uint8Array, options?: WriteFileOptions): void;
/**
* Watch for changes on `filename`. The callback `listener` will be called each
* time the file is accessed.
*
* The `options` argument may be omitted. If provided, it should be an object. The`options` object may contain a boolean named `persistent` that indicates
* whether the process should continue to run as long as files are being watched.
* The `options` object may specify an `interval` property indicating how often the
* target should be polled in milliseconds.
*
* The `listener` gets two arguments the current stat object and the previous
* stat object:
*
* ```js
* import { watchFile } from 'fs';
*
* watchFile('message.text', (curr, prev) => {
* console.log(`the current mtime is: ${curr.mtime}`);
* console.log(`the previous mtime was: ${prev.mtime}`);
* });
* ```
*
* These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`,
* the numeric values in these objects are specified as `BigInt`s.
*
* To be notified when the file was modified, not just accessed, it is necessary
* to compare `curr.mtime` and `prev.mtime`.
*
* When an `fs.watchFile` operation results in an `ENOENT` error, it
* will invoke the listener once, with all the fields zeroed (or, for dates, the
* Unix Epoch). If the file is created later on, the listener will be called
* again, with the latest stat objects. This is a change in functionality since
* v0.10.
*
* Using {@link watch} is more efficient than `fs.watchFile` and`fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and`fs.unwatchFile` when possible.
*
* When a file being watched by `fs.watchFile()` disappears and reappears,
* then the contents of `previous` in the second callback event (the file's
* reappearance) will be the same as the contents of `previous` in the first
* callback event (its disappearance).
*
* This happens when:
*
* * the file is deleted, followed by a restore
* * the file is renamed and then renamed a second time back to its original name
* @since v0.1.31
*/
export function watchFile(
filename: PathLike,
options:
| {
persistent?: boolean | undefined;
interval?: number | undefined;
}
| undefined,
listener: (curr: Stats, prev: Stats) => void
): void;
/**
* Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed.
* @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
*/
export function watchFile(filename: PathLike, listener: (curr: Stats, prev: Stats) => void): void;
/**
* Stop watching for changes on `filename`. If `listener` is specified, only that
* particular listener is removed. Otherwise, _all_ listeners are removed,
* effectively stopping watching of `filename`.
*
* Calling `fs.unwatchFile()` with a filename that is not being watched is a
* no-op, not an error.
*
* Using {@link watch} is more efficient than `fs.watchFile()` and`fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()`and `fs.unwatchFile()` when possible.
* @since v0.1.31
* @param listener Optional, a listener previously attached using `fs.watchFile()`
*/
export function unwatchFile(filename: PathLike, listener?: (curr: Stats, prev: Stats) => void): void;
export interface WatchOptions extends Abortable {
encoding?: BufferEncoding | 'buffer' | undefined;
persistent?: boolean | undefined;
recursive?: boolean | undefined;
}
export type WatchListener<T> = (event: 'rename' | 'change', filename: T) => void;
/**
* Watch for changes on `filename`, where `filename` is either a file or a
* directory.
*
* The second argument is optional. If `options` is provided as a string, it
* specifies the `encoding`. Otherwise `options` should be passed as an object.
*
* The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file
* which triggered the event.
*
* On most platforms, `'rename'` is emitted whenever a filename appears or
* disappears in the directory.
*
* The listener callback is attached to the `'change'` event fired by `<fs.FSWatcher>`, but it is not the same thing as the `'change'` value of`eventType`.
*
* If a `signal` is passed, aborting the corresponding AbortController will close
* the returned `<fs.FSWatcher>`.
* @since v0.5.10
*/
export function watch(
filename: PathLike,
options:
| (WatchOptions & {
encoding: 'buffer';
})
| 'buffer',
listener?: WatchListener<Buffer>
): FSWatcher;
/**
* Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`.
* @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
* @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options.
* If `encoding` is not supplied, the default of `'utf8'` is used.
* If `persistent` is not supplied, the default of `true` is used.
* If `recursive` is not supplied, the default of `false` is used.
*/
export function watch(filename: PathLike, options?: WatchOptions | BufferEncoding | null, listener?: WatchListener<string>): FSWatcher;
/**
* Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`.
* @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
* @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options.
* If `encoding` is not supplied, the default of `'utf8'` is used.
* If `persistent` is not supplied, the default of `true` is used.
* If `recursive` is not supplied, the default of `false` is used.
*/
export function watch(filename: PathLike, options: WatchOptions | string, listener?: WatchListener<string | Buffer>): FSWatcher;
/**
* Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`.
* @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
*/
export function watch(filename: PathLike, listener?: WatchListener<string>): FSWatcher;
/**
* Test whether or not the given path exists by checking with the file system.
* Then call the `callback` argument with either true or false:
*
* ```js
* import { exists } from 'fs';
*
* exists('/etc/passwd', (e) => {
* console.log(e ? 'it exists' : 'no passwd!');
* });
* ```
*
* **The parameters for this callback are not consistent with other Node.js**
* **callbacks.** Normally, the first parameter to a Node.js callback is an `err`parameter, optionally followed by other parameters. The `fs.exists()` callback
* has only one boolean parameter. This is one reason `fs.access()` is recommended
* instead of `fs.exists()`.
*
* Using `fs.exists()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()` is not recommended. Doing
* so introduces a race condition, since other processes may change the file's
* state between the two calls. Instead, user code should open/read/write the
* file directly and handle the error raised if the file does not exist.
*
* **write (NOT RECOMMENDED)**
*
* ```js
* import { exists, open, close } from 'fs';
*
* exists('myfile', (e) => {
* if (e) {
* console.error('myfile already exists');
* } else {
* open('myfile', 'wx', (err, fd) => {
* if (err) throw err;
*
* try {
* writeMyData(fd);
* } finally {
* close(fd, (err) => {
* if (err) throw err;
* });
* }
* });
* }
* });
* ```
*
* **write (RECOMMENDED)**
*
* ```js
* import { open, close } from 'fs';
* open('myfile', 'wx', (err, fd) => {
* if (err) {
* if (err.code === 'EEXIST') {
* console.error('myfile already exists');
* return;
* }
*
* throw err;
* }
*
* try {
* writeMyData(fd);
* } finally {
* close(fd, (err) => {
* if (err) throw err;
* });
* }
* });
* ```
*
* **read (NOT RECOMMENDED)**
*
* ```js
* import { open, close, exists } from 'fs';
*
* exists('myfile', (e) => {
* if (e) {
* open('myfile', 'r', (err, fd) => {
* if (err) throw err;
*
* try {
* readMyData(fd);
* } finally {
* close(fd, (err) => {
* if (err) throw err;
* });
* }
* });
* } else {
* console.error('myfile does not exist');
* }
* });
* ```
*
* **read (RECOMMENDED)**
*
* ```js
* import { open, close } from 'fs';
*
* open('myfile', 'r', (err, fd) => {
* if (err) {
* if (err.code === 'ENOENT') {
* console.error('myfile does not exist');
* return;
* }
*
* throw err;
* }
*
* try {
* readMyData(fd);
* } finally {
* close(fd, (err) => {
* if (err) throw err;
* });
* }
* });
* ```
*
* The "not recommended" examples above check for existence and then use the
* file; the "recommended" examples are better because they use the file directly
* and handle the error, if any.
*
* In general, check for the existence of a file only if the file won’t be
* used directly, for example when its existence is a signal from another
* process.
* @since v0.0.2
* @deprecated Since v1.0.0 - Use {@link stat} or {@link access} instead.
*/
export function exists(path: PathLike, callback: (exists: boolean) => void): void;
export namespace exists {
/**
* @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
* URL support is _experimental_.
*/
function __promisify__(path: PathLike): Promise<boolean>;
}
/**
* Returns `true` if the path exists, `false` otherwise.
*
* For detailed information, see the documentation of the asynchronous version of
* this API: {@link exists}.
*
* `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback`parameter to `fs.exists()` accepts parameters that are inconsistent with other
* Node.js callbacks. `fs.existsSync()` does not use a callback.
*
* ```js
* import { existsSync } from 'fs';
*
* if (existsSync('/etc/passwd'))
* console.log('The path exists.');
* ```
* @since v0.1.21
*/
export function existsSync(path: PathLike): boolean;
export namespace constants {
// File Access Constants
/** Constant for fs.access(). File is visible to the calling process. */
const F_OK: number;
/** Constant for fs.access(). File can be read by the calling process. */
const R_OK: number;
/** Constant for fs.access(). File can be written by the calling process. */
const W_OK: number;
/** Constant for fs.access(). File can be executed by the calling process. */
const X_OK: number;
// File Copy Constants
/** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */
const COPYFILE_EXCL: number;
/**
* Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink.
* If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used.
*/
const COPYFILE_FICLONE: number;
/**
* Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink.
* If the underlying platform does not support copy-on-write, then the operation will fail with an error.
*/
const COPYFILE_FICLONE_FORCE: number;
// File Open Constants
/** Constant for fs.open(). Flag indicating to open a file for read-only access. */
const O_RDONLY: number;
/** Constant for fs.open(). Flag indicating to open a file for write-only access. */
const O_WRONLY: number;
/** Constant for fs.open(). Flag indicating to open a file for read-write access. */
const O_RDWR: number;
/** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */
const O_CREAT: number;
/** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */
const O_EXCL: number;
/**
* Constant for fs.open(). Flag indicating that if path identifies a terminal device,
* opening the path shall not cause that terminal to become the controlling terminal for the process
* (if the process does not already have one).
*/
const O_NOCTTY: number;
/** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */
const O_TRUNC: number;
/** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */
const O_APPEND: number;
/** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */
const O_DIRECTORY: number;
/**
* constant for fs.open().
* Flag indicating reading accesses to the file system will no longer result in
* an update to the atime information associated with the file.
* This flag is available on Linux operating systems only.
*/
const O_NOATIME: number;
/** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */
const O_NOFOLLOW: number;
/** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */
const O_SYNC: number;
/** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */
const O_DSYNC: number;
/** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */
const O_SYMLINK: number;
/** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */
const O_DIRECT: number;
/** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */
const O_NONBLOCK: number;
// File Type Constants
/** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */
const S_IFMT: number;
/** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */
const S_IFREG: number;
/** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */
const S_IFDIR: number;
/** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */
const S_IFCHR: number;
/** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */
const S_IFBLK: number;
/** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */
const S_IFIFO: number;
/** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */
const S_IFLNK: number;
/** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */
const S_IFSOCK: number;
// File Mode Constants
/** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */
const S_IRWXU: number;
/** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */
const S_IRUSR: number;
/** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */
const S_IWUSR: number;
/** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */
const S_IXUSR: number;
/** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */
const S_IRWXG: number;
/** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */
const S_IRGRP: number;
/** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */
const S_IWGRP: number;
/** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */
const S_IXGRP: number;
/** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */
const S_IRWXO: number;
/** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */
const S_IROTH: number;
/** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */
const S_IWOTH: number;
/** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */
const S_IXOTH: number;
/**
* When set, a memory file mapping is used to access the file. This flag
* is available on Windows operating systems only. On other operating systems,
* this flag is ignored.
*/
const UV_FS_O_FILEMAP: number;
}
/**
* Tests a user's permissions for the file or directory specified by `path`.
* The `mode` argument is an optional integer that specifies the accessibility
* checks to be performed. Check `File access constants` for possible values
* of `mode`. It is possible to create a mask consisting of the bitwise OR of
* two or more values (e.g. `fs.constants.W_OK | fs.constants.R_OK`).
*
* The final argument, `callback`, is a callback function that is invoked with
* a possible error argument. If any of the accessibility checks fail, the error
* argument will be an `Error` object. The following examples check if`package.json` exists, and if it is readable or writable.
*
* ```js
* import { access, constants } from 'fs';
*
* const file = 'package.json';
*
* // Check if the file exists in the current directory.
* access(file, constants.F_OK, (err) => {
* console.log(`${file} ${err ? 'does not exist' : 'exists'}`);
* });
*
* // Check if the file is readable.
* access(file, constants.R_OK, (err) => {
* console.log(`${file} ${err ? 'is not readable' : 'is readable'}`);
* });
*
* // Check if the file is writable.
* access(file, constants.W_OK, (err) => {
* console.log(`${file} ${err ? 'is not writable' : 'is writable'}`);
* });
*
* // Check if the file exists in the current directory, and if it is writable.
* access(file, constants.F_OK | fs.constants.W_OK, (err) => {
* if (err) {
* console.error(
* `${file} ${err.code === 'ENOENT' ? 'does not exist' : 'is read-only'}`);
* } else {
* console.log(`${file} exists, and it is writable`);
* }
* });
* ```
*
* Do not use `fs.access()` to check for the accessibility of a file before calling`fs.open()`, `fs.readFile()` or `fs.writeFile()`. Doing
* so introduces a race condition, since other processes may change the file's
* state between the two calls. Instead, user code should open/read/write the
* file directly and handle the error raised if the file is not accessible.
*
* **write (NOT RECOMMENDED)**
*
* ```js
* import { access, open, close } from 'fs';
*
* access('myfile', (err) => {
* if (!err) {
* console.error('myfile already exists');
* return;
* }
*
* open('myfile', 'wx', (err, fd) => {
* if (err) throw err;
*
* try {
* writeMyData(fd);
* } finally {
* close(fd, (err) => {
* if (err) throw err;
* });
* }
* });
* });
* ```
*
* **write (RECOMMENDED)**
*
* ```js
* import { open, close } from 'fs';
*
* open('myfile', 'wx', (err, fd) => {
* if (err) {
* if (err.code === 'EEXIST') {
* console.error('myfile already exists');
* return;
* }
*
* throw err;
* }
*
* try {
* writeMyData(fd);
* } finally {
* close(fd, (err) => {
* if (err) throw err;
* });
* }
* });
* ```
*
* **read (NOT RECOMMENDED)**
*
* ```js
* import { access, open, close } from 'fs';
* access('myfile', (err) => {
* if (err) {
* if (err.code === 'ENOENT') {
* console.error('myfile does not exist');
* return;
* }
*
* throw err;
* }
*
* open('myfile', 'r', (err, fd) => {
* if (err) throw err;
*
* try {
* readMyData(fd);
* } finally {
* close(fd, (err) => {
* if (err) throw err;
* });
* }
* });
* });
* ```
*
* **read (RECOMMENDED)**
*
* ```js
* import { open, close } from 'fs';
*
* open('myfile', 'r', (err, fd) => {
* if (err) {
* if (err.code === 'ENOENT') {
* console.error('myfile does not exist');
* return;
* }
*
* throw err;
* }
*
* try {
* readMyData(fd);
* } finally {
* close(fd, (err) => {
* if (err) throw err;
* });
* }
* });
* ```
*
* The "not recommended" examples above check for accessibility and then use the
* file; the "recommended" examples are better because they use the file directly
* and handle the error, if any.
*
* In general, check for the accessibility of a file only if the file will not be
* used directly, for example when its accessibility is a signal from another
* process.
*
* On Windows, access-control policies (ACLs) on a directory may limit access to
* a file or directory. The `fs.access()` function, however, does not check the
* ACL and therefore may report that a path is accessible even if the ACL restricts
* the user from reading or writing to it.
* @since v0.11.15
*/
export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void;
/**
* Asynchronously tests a user's permissions for the file specified by path.
* @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
*/
export function access(path: PathLike, callback: NoParamCallback): void;
export namespace access {
/**
* Asynchronously tests a user's permissions for the file specified by path.
* @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
* URL support is _experimental_.
*/
function __promisify__(path: PathLike, mode?: number): Promise<void>;
}
/**
* Synchronously tests a user's permissions for the file or directory specified
* by `path`. The `mode` argument is an optional integer that specifies the
* accessibility checks to be performed. Check `File access constants` for
* possible values of `mode`. It is possible to create a mask consisting of
* the bitwise OR of two or more values
* (e.g. `fs.constants.W_OK | fs.constants.R_OK`).
*
* If any of the accessibility checks fail, an `Error` will be thrown. Otherwise,
* the method will return `undefined`.
*
* ```js
* import { accessSync, constants } from 'fs';
*
* try {
* accessSync('etc/passwd', constants.R_OK | constants.W_OK);
* console.log('can read/write');
* } catch (err) {
* console.error('no access!');
* }
* ```
* @since v0.11.15
*/
export function accessSync(path: PathLike, mode?: number): void;
interface StreamOptions {
flags?: string | undefined;
encoding?: BufferEncoding | undefined;
fd?: number | promises.FileHandle | undefined;
mode?: number | undefined;
autoClose?: boolean | undefined;
/**
* @default false
*/
emitClose?: boolean | undefined;
start?: number | undefined;
highWaterMark?: number | undefined;
}
interface ReadStreamOptions extends StreamOptions {
end?: number | undefined;
}
/**
* Unlike the 16 kb default `highWaterMark` for a readable stream, the stream
* returned by this method has a default `highWaterMark` of 64 kb.
*
* `options` can include `start` and `end` values to read a range of bytes from
* the file instead of the entire file. Both `start` and `end` are inclusive and
* start counting at 0, allowed values are in the
* \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is
* omitted or `undefined`, `fs.createReadStream()` reads sequentially from the
* current file position. The `encoding` can be any one of those accepted by `<Buffer>`.
*
* If `fd` is specified, `ReadStream` will ignore the `path` argument and will use
* the specified file descriptor. This means that no `'open'` event will be
* emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `<net.Socket>`.
*
* If `fd` points to a character device that only supports blocking reads
* (such as keyboard or sound card), read operations do not finish until data is
* available. This can prevent the process from exiting and the stream from
* closing naturally.
*
* By default, the stream will emit a `'close'` event after it has been
* destroyed, like most `Readable` streams. Set the `emitClose` option to`false` to change this behavior.
*
* By providing the `fs` option, it is possible to override the corresponding `fs`implementations for `open`, `read`, and `close`. When providing the `fs` option,
* overrides for `open`, `read`, and `close` are required.
*
* ```js
* import { createReadStream } from 'fs';
*
* // Create a stream from some character device.
* const stream = createReadStream('/dev/input/event0');
* setTimeout(() => {
* stream.close(); // This may not close the stream.
* // Artificially marking end-of-stream, as if the underlying resource had
* // indicated end-of-file by itself, allows the stream to close.
* // This does not cancel pending read operations, and if there is such an
* // operation, the process may still not be able to exit successfully
* // until it finishes.
* stream.push(null);
* stream.read(0);
* }, 100);
* ```
*
* If `autoClose` is false, then the file descriptor won't be closed, even if
* there's an error. It is the application's responsibility to close it and make
* sure there's no file descriptor leak. If `autoClose` is set to true (default
* behavior), on `'error'` or `'end'` the file descriptor will be closed
* automatically.
*
* `mode` sets the file mode (permission and sticky bits), but only if the
* file was created.
*
* An example to read the last 10 bytes of a file which is 100 bytes long:
*
* ```js
* import { createReadStream } from 'fs';
*
* createReadStream('sample.txt', { start: 90, end: 99 });
* ```
*
* If `options` is a string, then it specifies the encoding.
* @since v0.1.31
* @return See `Readable Stream`.
*/
export function createReadStream(path: PathLike, options?: string | ReadStreamOptions): ReadStream;
/**
* `options` may also include a `start` option to allow writing data at some
* position past the beginning of the file, allowed values are in the
* \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than replacing
* it may require the `flags` option to be set to `r+` rather than the default `w`.
* The `encoding` can be any one of those accepted by `<Buffer>`.
*
* If `autoClose` is set to true (default behavior) on `'error'` or `'finish'`the file descriptor will be closed automatically. If `autoClose` is false,
* then the file descriptor won't be closed, even if there's an error.
* It is the application's responsibility to close it and make sure there's no
* file descriptor leak.
*
* By default, the stream will emit a `'close'` event after it has been
* destroyed, like most `Writable` streams. Set the `emitClose` option to`false` to change this behavior.
*
* By providing the `fs` option it is possible to override the corresponding `fs`implementations for `open`, `write`, `writev` and `close`. Overriding `write()`without `writev()` can reduce
* performance as some optimizations (`_writev()`)
* will be disabled. When providing the `fs` option, overrides for `open`,`close`, and at least one of `write` and `writev` are required.
*
* Like `<fs.ReadStream>`, if `fd` is specified, `<fs.WriteStream>` will ignore the`path` argument and will use the specified file descriptor. This means that no`'open'` event will be
* emitted. `fd` should be blocking; non-blocking `fd`s
* should be passed to `<net.Socket>`.
*
* If `options` is a string, then it specifies the encoding.
* @since v0.1.31
* @return See `Writable Stream`.
*/
export function createWriteStream(path: PathLike, options?: string | StreamOptions): WriteStream;
/**
* Forces all currently queued I/O operations associated with the file to the
* operating system's synchronized I/O completion state. Refer to the POSIX[`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other
* than a possible
* exception are given to the completion callback.
* @since v0.1.96
*/
export function fdatasync(fd: number, callback: NoParamCallback): void;
export namespace fdatasync {
/**
* Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device.
* @param fd A file descriptor.
*/
function __promisify__(fd: number): Promise<void>;
}
/**
* Forces all currently queued I/O operations associated with the file to the
* operating system's synchronized I/O completion state. Refer to the POSIX[`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`.
* @since v0.1.96
*/
export function fdatasyncSync(fd: number): void;
/**
* Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it
* already exists. No arguments other than a possible exception are given to the
* callback function. Node.js makes no guarantees about the atomicity of the copy
* operation. If an error occurs after the destination file has been opened for
* writing, Node.js will attempt to remove the destination.
*
* `mode` is an optional integer that specifies the behavior
* of the copy operation. It is possible to create a mask consisting of the bitwise
* OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`).
*
* * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already
* exists.
* * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a
* copy-on-write reflink. If the platform does not support copy-on-write, then a
* fallback copy mechanism is used.
* * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to
* create a copy-on-write reflink. If the platform does not support
* copy-on-write, then the operation will fail.
*
* ```js
* import { copyFile, constants } from 'fs';
*
* function callback(err) {
* if (err) throw err;
* console.log('source.txt was copied to destination.txt');
* }
*
* // destination.txt will be created or overwritten by default.
* copyFile('source.txt', 'destination.txt', callback);
*
* // By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
* copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback);
* ```
* @since v8.5.0
* @param src source filename to copy
* @param dest destination filename of the copy operation
* @param mode modifiers for copy operation.
*/
export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void;
export function copyFile(src: PathLike, dest: PathLike, mode: number, callback: NoParamCallback): void;
export namespace copyFile {
function __promisify__(src: PathLike, dst: PathLike, mode?: number): Promise<void>;
}
/**
* Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it
* already exists. Returns `undefined`. Node.js makes no guarantees about the
* atomicity of the copy operation. If an error occurs after the destination file
* has been opened for writing, Node.js will attempt to remove the destination.
*
* `mode` is an optional integer that specifies the behavior
* of the copy operation. It is possible to create a mask consisting of the bitwise
* OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`).
*
* * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already
* exists.
* * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a
* copy-on-write reflink. If the platform does not support copy-on-write, then a
* fallback copy mechanism is used.
* * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to
* create a copy-on-write reflink. If the platform does not support
* copy-on-write, then the operation will fail.
*
* ```js
* import { copyFileSync, constants } from 'fs';
*
* // destination.txt will be created or overwritten by default.
* copyFileSync('source.txt', 'destination.txt');
* console.log('source.txt was copied to destination.txt');
*
* // By using COPYFILE_EXCL, the operation will fail if destination.txt exists.
* copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL);
* ```
* @since v8.5.0
* @param src source filename to copy
* @param dest destination filename of the copy operation
* @param mode modifiers for copy operation.
*/
export function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void;
/**
* Write an array of `ArrayBufferView`s to the file specified by `fd` using`writev()`.
*
* `position` is the offset from the beginning of the file where this data
* should be written. If `typeof position !== 'number'`, the data will be written
* at the current position.
*
* The callback will be given three arguments: `err`, `bytesWritten`, and`buffers`. `bytesWritten` is how many bytes were written from `buffers`.
*
* If this method is `util.promisify()` ed, it returns a promise for an`Object` with `bytesWritten` and `buffers` properties.
*
* It is unsafe to use `fs.writev()` multiple times on the same file without
* waiting for the callback. For this scenario, use {@link createWriteStream}.
*
* On Linux, positional writes don't work when the file is opened in append mode.
* The kernel ignores the position argument and always appends the data to
* the end of the file.
* @since v12.9.0
*/
export function writev(fd: number, buffers: ReadonlyArray<NodeJS.ArrayBufferView>, cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void): void;
export function writev(
fd: number,
buffers: ReadonlyArray<NodeJS.ArrayBufferView>,
position: number,
cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void
): void;
export interface WriteVResult {
bytesWritten: number;
buffers: NodeJS.ArrayBufferView[];
}
export namespace writev {
function __promisify__(fd: number, buffers: ReadonlyArray<NodeJS.ArrayBufferView>, position?: number): Promise<WriteVResult>;
}
/**
* For detailed information, see the documentation of the asynchronous version of
* this API: {@link writev}.
* @since v12.9.0
* @return The number of bytes written.
*/
export function writevSync(fd: number, buffers: ReadonlyArray<NodeJS.ArrayBufferView>, position?: number): number;
/**
* Read from a file specified by `fd` and write to an array of `ArrayBufferView`s
* using `readv()`.
*
* `position` is the offset from the beginning of the file from where data
* should be read. If `typeof position !== 'number'`, the data will be read
* from the current position.
*
* The callback will be given three arguments: `err`, `bytesRead`, and`buffers`. `bytesRead` is how many bytes were read from the file.
*
* If this method is invoked as its `util.promisify()` ed version, it returns
* a promise for an `Object` with `bytesRead` and `buffers` properties.
* @since v13.13.0, v12.17.0
*/
export function readv(fd: number, buffers: ReadonlyArray<NodeJS.ArrayBufferView>, cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void): void;
export function readv(
fd: number,
buffers: ReadonlyArray<NodeJS.ArrayBufferView>,
position: number,
cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void
): void;
export interface ReadVResult {
bytesRead: number;
buffers: NodeJS.ArrayBufferView[];
}
export namespace readv {
function __promisify__(fd: number, buffers: ReadonlyArray<NodeJS.ArrayBufferView>, position?: number): Promise<ReadVResult>;
}
/**
* For detailed information, see the documentation of the asynchronous version of
* this API: {@link readv}.
* @since v13.13.0, v12.17.0
* @return The number of bytes read.
*/
export function readvSync(fd: number, buffers: ReadonlyArray<NodeJS.ArrayBufferView>, position?: number): number;
export interface OpenDirOptions {
encoding?: BufferEncoding | undefined;
/**
* Number of directory entries that are buffered
* internally when reading from the directory. Higher values lead to better
* performance but higher memory usage.
* @default 32
*/
bufferSize?: number | undefined;
}
/**
* Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html).
*
* Creates an `<fs.Dir>`, which contains all further functions for reading from
* and cleaning up the directory.
*
* The `encoding` option sets the encoding for the `path` while opening the
* directory and subsequent read operations.
* @since v12.12.0
*/
export function opendirSync(path: string, options?: OpenDirOptions): Dir;
/**
* Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for
* more details.
*
* Creates an `<fs.Dir>`, which contains all further functions for reading from
* and cleaning up the directory.
*
* The `encoding` option sets the encoding for the `path` while opening the
* directory and subsequent read operations.
* @since v12.12.0
*/
export function opendir(path: string, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void;
export function opendir(path: string, options: OpenDirOptions, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void;
export namespace opendir {
function __promisify__(path: string, options?: OpenDirOptions): Promise<Dir>;
}
export interface BigIntStats extends StatsBase<bigint> {
atimeNs: bigint;
mtimeNs: bigint;
ctimeNs: bigint;
birthtimeNs: bigint;
}
export interface BigIntOptions {
bigint: true;
}
export interface StatOptions {
bigint?: boolean | undefined;
throwIfNoEntry?: boolean | undefined;
}
}
declare module 'node:fs' {
export * from 'fs';
} | the_stack |
import {
CARD_KEY,
CARD_SELECTOR,
CURSOR,
CURSOR_SELECTOR,
DATA_ELEMENT,
DATA_ID,
READY_CARD_KEY,
ROOT_SELECTOR,
} from '../constants';
import Range from '../range';
import {
EditorInterface,
NodeInterface,
RangeInterface,
PluginEntry,
} from '../types';
import { BlockInterface, BlockModelInterface } from '../types/block';
import {
convertMarkdown,
createMarkdownIt,
getDocument,
isEngine,
} from '../utils';
import { Backspace, Enter } from './typing';
import { $ } from '../node';
import { isBlockPlugin } from '../plugin';
import { isNode } from '../node/utils';
import { CardType } from '../card/enum';
class Block implements BlockModelInterface {
private editor: EditorInterface;
constructor(editor: EditorInterface) {
this.editor = editor;
}
init() {
const editor = this.editor;
if (isEngine(editor)) {
const { typing, event } = editor;
//绑定回车事件
const enter = new Enter(editor);
typing
.getHandleListener('enter', 'keydown')
?.on((event) => enter.trigger(event));
//删除事件
const backspace = new Backspace(editor);
typing
.getHandleListener('backspace', 'keydown')
?.on((event) => backspace.trigger(event));
event.on('keyup:space', (event) => this.triggerMarkdown(event));
event.on('keydown:enter', (event) => this.triggerMarkdown(event));
}
}
/**
* 解析markdown
* @param event 事件
*/
triggerMarkdown(event: KeyboardEvent) {
const editor = this.editor;
if (!isEngine(editor) || editor.options.markdown?.mode === false)
return;
const { change } = editor;
let range = change.range.get();
if (!range.collapsed || change.isComposing()) return;
const { startNode, startOffset } = range;
const node =
startNode.type === Node.TEXT_NODE
? startNode
: startNode.children().eq(startOffset - 1);
if (!node) return;
const blockNode = this.closest(node);
if (!editor.node.isRootBlock(blockNode)) return;
const text = node.text().trimEnd();
const cacheRange = range.toPath();
const markdown = createMarkdownIt(editor, 'zero');
const tokens = markdown.parse(text, {});
if (tokens.length === 0) return;
const content = convertMarkdown(editor, markdown, tokens, false);
if (content) {
event.preventDefault();
range.select(blockNode, true);
change.paste(content, range);
change.rangePathBeforeCommand = cacheRange;
change.range.select(range);
return false;
}
return true;
}
pluginCaches: Map<string, BlockInterface> = new Map();
/**
* 根据节点查找block插件实例
* @param node 节点
*/
findPlugin(block: NodeInterface): BlockInterface | undefined {
const { node, schema, plugin } = this.editor;
if (block.length === 0 || !node.isBlock(block)) return;
const markClone = block.get<Element>()!.cloneNode() as Element;
const key = markClone.outerHTML;
let result: BlockInterface | undefined = this.pluginCaches.get(key);
if (result) return result;
for (const pluginName in plugin.components) {
const blockPlugin = plugin.components[pluginName];
if (
isBlockPlugin(blockPlugin) &&
(!blockPlugin.tagName || typeof blockPlugin.tagName === 'string'
? block.name === blockPlugin.tagName
: blockPlugin.tagName.indexOf(block.name) > -1)
) {
const schemaRule = blockPlugin.schema();
if (
Array.isArray(schemaRule)
? schemaRule.find((rule) =>
schema.checkNode(block, rule.attributes),
)
: schema.checkNode(block, schemaRule.attributes)
) {
this.pluginCaches.set(key, blockPlugin);
return blockPlugin;
}
}
}
return result;
}
/**
* 查找Block节点的一级节点。如 div -> H2 返回 H2节点
* @param parentNode 父节点
* @param childNode 子节点
*/
findTop(parentNode: NodeInterface, childNode: NodeInterface) {
const { schema, node, list } = this.editor;
const topParentName = schema.closest(parentNode.name);
const topChildName = schema.closest(childNode.name);
//如果父节点没有级别或者子节点没有级别就返回子节点
if (topParentName === parent.name || topChildName === childNode.name)
return childNode;
//如果父节点的级别大于子节点的级别就返回父节点
if (schema.isAllowIn(parentNode.name, childNode.name))
return parentNode;
//如果父节点是 ul、ol 这样的List列表,并且子节点也是这样的列表,设置ident
if (node.isList(parentNode) && node.isList(childNode)) {
const childIndent =
parseInt(childNode.attributes(list.INDENT_KEY), 10) || 0;
const parentIndent =
parseInt(parentNode.attributes(list.INDENT_KEY), 10) || 0;
childNode.attributes(
list.INDENT_KEY,
parentIndent ? parentIndent + 1 : childIndent + 1,
);
}
//默认返回子节点
return childNode;
}
/**
* 获取最近的block节点,找不到返回 node
* @param node 节点
* @param callback 回调
*/
closest(
node: NodeInterface,
callback: (node: NodeInterface) => boolean = () => true,
) {
const originNode = node;
while (node) {
if (
(node.isEditable() || this.editor.node.isBlock(node)) &&
callback(node)
) {
return node;
}
const parentNode = node.parent();
if (!parentNode) break;
node = parentNode;
}
return originNode;
}
/**
* 在光标位置包裹一个block节点
* @param block 节点
* @param range 光标
*/
wrap(block: NodeInterface | Node | string, range?: RangeInterface) {
const editor = this.editor;
if (!isEngine(editor)) return;
const { change, node, schema, list, mark } = editor;
const safeRange = range || change.range.toTrusty();
const doc = getDocument(safeRange.startContainer);
if (typeof block === 'string' || isNode(block)) {
block = $(block, doc);
} else block = block;
if (!node.isBlock(block)) return;
let blocks: Array<NodeInterface | null> = this.getBlocks(safeRange);
const targetPlugin = this.findPlugin(block);
//一样的block插件不嵌套
blocks = blocks
.map((blockNode) => {
if (!blockNode || blockNode.isCard()) return null;
const wrapBlock = block as NodeInterface;
let blockParent = blockNode?.parent();
while (blockParent && !blockParent.isEditable()) {
blockNode = blockParent;
const parent = blockParent.parent();
if (parent && node.isBlock(parent)) {
blockParent = parent;
} else break;
}
//|| blockParent && !blockParent.equal(blockNode) && !blockParent.isRoot() && node.isBlock(blockParent) && !schema.isAllowIn(wrapBlock.name, blockParent.name)
if (!schema.isAllowIn(wrapBlock.name, blockNode.name)) {
//一样的插件,返回子级
if (this.findPlugin(blockNode) === targetPlugin) {
return blockNode.children();
}
return null;
}
return blockNode;
})
.filter((block) => block !== null);
// 不在段落内
if (blocks.length === 0) {
const root = this.closest(safeRange.startNode);
if (
root.isCard() ||
root.isEditable() ||
!schema.isAllowIn(block.name, root.name)
)
return;
const selection = safeRange.createSelection();
root.children().each((node) => {
(block as NodeInterface).append(node);
});
root.append(block);
selection.move();
return;
}
const selection = safeRange.createSelection();
blocks[0]?.before(block);
blocks.forEach((child) => {
if (child) {
//先移除不能放入块级节点的mark标签
if (targetPlugin) {
child.allChildren().forEach((markNode) => {
if (node.isMark(markNode)) {
const markPlugin = mark.findPlugin(markNode);
if (!markPlugin) return;
if (
targetPlugin.disableMark?.indexOf(
(markPlugin.constructor as PluginEntry)
.pluginName,
)
) {
node.unwrap(markNode);
}
}
});
}
(block as NodeInterface).append(child);
}
});
selection.move();
this.merge(safeRange);
list.merge(undefined, safeRange);
if (!range) change.apply(safeRange);
}
/**
* 移除光标所在block节点包裹
* @param block 节点
* @param range 光标
*/
unwrap(block: NodeInterface | Node | string, range?: RangeInterface) {
const editor = this.editor;
if (!isEngine(editor)) return;
const { change, node } = editor;
const safeRange = range || change.range.toTrusty();
const doc = getDocument(safeRange.startContainer);
if (typeof block === 'string' || isNode(block)) {
block = $(block, doc);
} else block = block;
if (!node.isBlock(block)) return;
const blocks = this.getSiblings(safeRange, block);
if (blocks.length === 0) {
return;
}
const firstNodeParent = blocks[0].node.parent();
if (!firstNodeParent?.inEditor()) {
return;
}
const hasLeft = blocks.some((item) => item.position === 'left');
const hasRight = blocks.some((item) => item.position === 'right');
let leftParent: NodeInterface | undefined = undefined;
if (hasLeft) {
const parent = firstNodeParent;
leftParent = node.clone(parent, false, false);
parent.before(leftParent);
}
let rightParent: NodeInterface | undefined = undefined;
if (hasRight) {
const _parent = blocks[blocks.length - 1].node.parent();
if (_parent) {
rightParent = node.clone(_parent, false, false);
_parent?.after(rightParent);
}
}
// 插入范围的开始和结束标记
const selection = safeRange.createSelection();
const nodeApi = node;
blocks.forEach((item) => {
const status = item.position,
node = item.node,
parent = node.parent();
if (status === 'left') {
leftParent?.append(node);
}
if (status === 'center') {
if (
parent?.name === (block as NodeInterface)?.name &&
parent?.inEditor()
) {
nodeApi.unwrap(parent);
}
}
if (status === 'right') {
rightParent?.append(node);
}
});
// 有序列表被从中间拆开后,剩余的两个部分的需要保持序号连续
if (
leftParent &&
leftParent.name === 'ol' &&
rightParent &&
rightParent.name === 'ol'
) {
rightParent.attributes(
'start',
(parseInt(leftParent.attributes('start'), 10) || 1) +
leftParent.find('li').length,
);
}
selection.move();
if (!range) change.apply(safeRange);
}
/**
* 获取节点相对于光标开始位置、结束位置下的兄弟节点集合
* @param range 光标
* @param block 节点
*/
getSiblings(range: RangeInterface, block: NodeInterface) {
const blocks: Array<{
node: NodeInterface;
position: 'left' | 'center' | 'right';
}> = [];
const nodeApi = this.editor.node;
if (!nodeApi.isBlock(block)) return blocks;
const getTargetBlock = (node: NodeInterface, tagName: string) => {
let block = this.closest(node);
while (block) {
const parent = block.parent();
if (!parent) break;
if (!block.inEditor()) break;
if (block.text().trim() !== parent.text().trim()) break;
if (parent.name === tagName) break;
block = parent;
}
return block;
};
const startBlock = getTargetBlock(range.startNode, block.name);
const endBlock = getTargetBlock(range.endNode, block.name);
const parentBlock = startBlock.parent();
let position: 'left' | 'center' | 'right' = 'left';
let node = parentBlock?.first();
while (node) {
node = $(node);
if (!nodeApi.isBlock(node)) return blocks;
if (!node.inEditor()) return blocks;
if (node[0] === startBlock[0]) {
position = 'center';
}
blocks.push({
position,
node,
});
if (node[0] === endBlock[0]) {
position = 'right';
}
node = node.next();
}
return blocks;
}
/**
* 分割当前光标选中的block节点
* @param range 光标
*/
split(range?: RangeInterface) {
const editor = this.editor;
if (!isEngine(editor)) return;
const { change, mark, nodeId } = editor;
const safeRange = range || change.range.toTrusty();
// 范围为展开状态时先删除内容
if (!safeRange.collapsed) {
change.delete(safeRange);
}
// 获取上面第一个 Block
const block = this.closest(safeRange.startNode);
// 获取的 block 超出编辑范围
if (!block.isEditable() && !block.inEditor()) {
return;
}
if (block.isEditable()) {
// <p>wo</p><cursor /><p>other</p>
// to
// <p>wo</p><p><cursor />other</p>
const sc = safeRange.getStartOffsetNode();
if (sc) {
safeRange
.select(sc, true)
.shrinkToElementNode()
.collapse(false);
}
if (!range) change.apply(safeRange);
return;
}
const cloneRange = safeRange.cloneRange();
cloneRange.shrinkToElementNode().shrinkToTextNode().collapse(true);
const activeMarks = mark.findMarks(cloneRange).filter((mark) => {
// 回车后,默认是否复制makr样式
const plugin = editor.mark.findPlugin(mark);
return (
plugin?.copyOnEnter !== false && plugin?.followStyle !== false
);
});
const sideBlock = this.getBlockByRange({
block: block[0],
range: safeRange,
isLeft: false,
keepDataId: true,
});
const nodeApi = editor.node;
sideBlock.traverse((node) => {
if (
!nodeApi.isVoid(node) &&
(nodeApi.isInline(node) || nodeApi.isMark(node)) &&
nodeApi.isEmpty(node)
) {
node.remove();
}
}, true);
const isEmptyElement = (node: Node) => {
return (
nodeApi.isBlock(node) &&
(node.childNodes.length === 0 ||
(node as HTMLElement).innerText === '')
);
};
if (isEmptyElement(block[0]) && !isEmptyElement(sideBlock[0])) {
nodeId.generate(block, true);
} else {
nodeId.generate(sideBlock, true);
}
block.after(sideBlock);
// <p></p>里面必须要有节点,插入 BR 之后输入文字自动消失
if (nodeApi.isEmpty(block)) {
nodeApi.html(
block,
nodeApi.getBatchAppendHTML(
activeMarks,
activeMarks.length > 0 ? '​' : '<br />',
),
);
}
if (nodeApi.isEmpty(sideBlock)) {
nodeApi.html(
sideBlock,
nodeApi.getBatchAppendHTML(
activeMarks,
activeMarks.length > 0 ? '​' : '<br />',
),
);
}
block.children().each((child) => {
if (nodeApi.isInline(child)) {
editor.inline.repairCursor(child);
}
});
sideBlock.children().each((child) => {
if (nodeApi.isInline(child)) {
editor.inline.repairCursor(child);
}
});
// 重新设置当前选中范围
safeRange.select(sideBlock, true).shrinkToElementNode();
if (
sideBlock.get<Node>()?.childNodes.length === 1 &&
sideBlock.first()?.name === 'br'
) {
safeRange.collapse(false);
} else {
safeRange.collapse(true);
}
if (!range) change.apply(safeRange);
return sideBlock;
}
/**
* 在当前光标位置插入block节点
* @param block 节点
* @param range 光标
* @param splitNode 分割节点,默认为光标开始位置的block节点
*/
insert(
block: NodeInterface | Node | string,
range?: RangeInterface,
splitNode?: (node: NodeInterface) => NodeInterface,
removeCurrentEmptyBlock: boolean = false,
) {
const editor = this.editor;
if (!isEngine(editor)) return;
const { change, node, list, inline } = editor;
const safeRange = range || change.range.toTrusty();
const doc = getDocument(safeRange.startContainer);
if (typeof block === 'string' || isNode(block)) {
block = $(block, doc);
} else block = block;
if (!node.isBlock(block)) return;
// 范围为折叠状态时先删除内容
if (!safeRange.collapsed) {
change.delete(safeRange);
}
// 获取上面第一个 Block
let container = this.closest(safeRange.startNode);
// 超出编辑范围
if (!container.isEditable() && !container.inEditor()) {
if (!range) change.apply(safeRange);
return;
}
// 当前选择范围在段落外面
if (container.isEditable()) {
node.insert(block, safeRange, removeCurrentEmptyBlock);
safeRange.collapse(false);
if (!range) change.apply(safeRange);
return;
}
if (
node.isList(safeRange.startNode) ||
safeRange.startNode.closest('li').length > 0
) {
const fragment = doc.createDocumentFragment();
fragment.appendChild(block[0]);
list.insert(fragment, safeRange);
if (!range) change.apply(safeRange);
return;
}
// <p><cursor /><br /></p>
// to
// <p><br /><cursor /></p>
if (
container.get<Node>()?.childNodes.length === 1 &&
container.first()?.name === 'br'
) {
safeRange.select(container, true).collapse(false);
}
// 插入范围的开始和结束标记
const selection = safeRange.enlargeToElementNode().createSelection();
if (!selection.has()) {
if (!range) change.apply(safeRange);
return;
}
container = splitNode ? splitNode(container) : container;
// 切割 Block
let leftNodes = selection.getNode(container, 'left');
leftNodes.traverse((leftNode) => {
if (leftNode.equal(leftNodes)) return;
if (
node.isBlock(leftNode) &&
(node.isEmpty(leftNode) || list.isEmptyItem(leftNode))
) {
leftNode.remove();
}
});
let rightNodes = selection.getNode(
container,
'right',
true,
(child) => {
if (child.isCard()) {
const parent = child.parent();
if (parent && node.isCustomize(parent)) return false;
}
return true;
},
);
// 清空原父容器,用新的内容代替
const children = container.children();
if (!node.isEmpty(container)) {
children.each((_, index) => {
const child = children.eq(index);
if (!child?.isCard()) {
children.eq(index)?.remove();
}
});
}
rightNodes.traverse((rightNode) => {
if (!rightNode.equal(rightNodes)) return;
if (
node.isBlock(rightNode) &&
(node.isEmpty(rightNode) || list.isEmptyItem(rightNode))
) {
rightNode.remove();
} else if (node.isList(rightNode)) {
list.addBr(rightNode);
}
});
if (
rightNodes.length > 0 &&
!node.isEmpty(rightNodes) &&
!list.isEmptyItem(rightNodes)
) {
const right = rightNodes.clone(false);
editor.nodeId.generate(right, true);
const rightChildren = rightNodes.children();
rightChildren.each((child, index) => {
if (rightChildren.eq(index)?.isCard()) {
const card = editor.card.find(child);
if (card) right.append(card.root);
} else right.append(child);
});
rightNodes = right;
container.after(right);
}
if (
leftNodes.length > 0 &&
!node.isEmpty(leftNodes) &&
!list.isEmptyItem(leftNodes)
) {
let appendChild: NodeInterface | undefined | null = undefined;
const appendToParent = (childrenNodes: NodeInterface) => {
childrenNodes.each((child, index) => {
const childNode = childrenNodes.eq(index);
if (childNode && node.isInline(childNode)) {
inline.repairCursor(childNode);
}
if (childNode?.isCard()) {
appendChild = appendChild
? appendChild.next()
: container.first();
if (appendChild) childrenNodes[index] = appendChild[0];
return;
}
if (appendChild) {
appendChild.after(child);
appendChild = childNode;
} else {
appendChild = childNode;
container.prepend(child);
}
});
};
appendToParent(leftNodes.children());
}
if (container && container.length > 0) {
safeRange.select(container, true);
safeRange.collapse(false);
}
if (selection.focus) selection.focus.remove();
if (selection.anchor) selection.anchor.remove();
// 插入新 Block
node.insert(block, safeRange, removeCurrentEmptyBlock);
if (!range) change.apply(safeRange);
}
/**
* 设置当前光标所在的所有block节点为新的节点或设置新属性
* @param block 需要设置的节点或者节点属性
* @param range 光标
*/
setBlocks(block: string | { [k: string]: any }, range?: RangeInterface) {
const editor = this.editor;
if (!isEngine(editor)) return;
const { node, schema, mark } = editor;
const { change } = editor;
const safeRange = range || change.range.toTrusty();
const doc = getDocument(safeRange.startContainer);
let targetNode: NodeInterface | null = null;
let attributes: { [k: string]: any } = {};
if (typeof block === 'string') {
targetNode = $(block, doc);
attributes = targetNode.attributes();
attributes.style = targetNode.css();
} else {
attributes = block;
}
const blocks = this.getBlocks(safeRange);
// 编辑器根节点,无段落
const { startNode } = safeRange;
if (startNode.isEditable() && blocks.length === 0) {
if (startNode.isCard() || startNode.isEditable()) return;
const newBlock = targetNode || $('<p></p>');
if (!schema.isAllowIn(newBlock.name, startNode.name)) return;
node.setAttributes(newBlock, attributes);
const selection = safeRange.createSelection();
startNode.children().each((node) => {
newBlock.append(node);
});
// 复制全局属性
const globals = schema.data.globals['block'] || {};
const oldAttributes = startNode.attributes();
Object.keys(oldAttributes).forEach((name) => {
if (name !== DATA_ID && name !== 'id' && globals['name']) {
newBlock.attributes(name, oldAttributes[name]);
}
});
// 复制全局样式,及生成 text-align
const globalStyles = globals.style || {};
const styles = startNode.css();
Object.keys(styles).forEach((name) => {
if (!globalStyles[name]) delete styles[name];
});
newBlock.css(styles);
startNode.append(newBlock);
selection.move();
if (!range) change.apply(safeRange);
return;
}
const targetPlugin = targetNode
? this.findPlugin(targetNode)
: undefined;
const selection = safeRange.createSelection();
blocks.forEach((child) => {
// Card 不做处理
if (child.attributes(CARD_KEY)) {
return;
}
if (targetNode) {
// 复制全局属性
const globals = schema.data.globals['block'] || {};
const oldAttributes = child.attributes();
Object.keys(oldAttributes).forEach((name) => {
if (name !== DATA_ID && name !== 'id' && globals['name']) {
targetNode?.attributes(name, oldAttributes[name]);
}
});
// 复制全局样式,及生成 text-align
const globalStyles = globals.style || {};
const styles = child.css();
Object.keys(styles).forEach((name) => {
if (!globalStyles[name]) delete styles[name];
});
targetNode.css(styles);
}
// 相同标签,或者只传入样式属性
if (
!targetNode ||
(this.findPlugin(child) === targetPlugin &&
child.name === targetNode.name)
) {
if (targetNode) attributes = targetNode.attributes();
node.setAttributes(child, attributes);
return;
}
//如果要包裹的节点可以放入到当前节点中,就不操作
if (
targetNode.name !== 'p' &&
schema.isAllowIn(child.name, targetNode.name)
) {
return;
}
//先移除不能放入块级节点的mark标签
if (targetPlugin) {
child.allChildren().forEach((markNode) => {
if (node.isMark(markNode)) {
const markPlugin = mark.findPlugin(markNode);
if (!markPlugin) return;
if (
targetPlugin.disableMark &&
targetPlugin.disableMark.indexOf(
(markPlugin.constructor as PluginEntry)
.pluginName,
) > -1
) {
node.unwrap(markNode);
}
}
});
}
const newNode = node.replace(child, targetNode);
const parent = newNode.parent();
if (
parent &&
!parent.isEditable() &&
!schema.isAllowIn(parent.name, newNode.name)
) {
node.unwrap(parent);
}
});
selection.move();
if (!range) change.apply(safeRange);
}
/**
* 合并当前光标位置相邻的block
* @param range 光标
*/
merge(range?: RangeInterface) {
const editor = this.editor;
if (!isEngine(editor)) return;
const { change, schema } = editor;
const safeRange = range || change.range.toTrusty();
const blocks = this.getBlocks(safeRange);
if (0 === blocks.length) return;
const root = blocks[0].closest(ROOT_SELECTOR);
const tags = schema.getCanMergeTags();
if (tags.length === 0) return;
const block = root.find(tags.join(','));
if (block.length > 0) {
const selection = safeRange.createSelection();
let nextNode = block.next();
while (nextNode && tags.indexOf(nextNode.name) > 0) {
const prevNode = nextNode.prev();
const nextAttributes = nextNode.attributes();
const prevAttributes = prevNode?.attributes();
if (
nextNode.name === prevNode?.name &&
nextAttributes['class'] ===
(prevAttributes
? prevAttributes['class']
: undefined) &&
Object.keys(nextAttributes).join(',') ===
Object.keys(prevAttributes || {}).join(',')
) {
editor.node.merge(prevNode, nextNode);
}
nextNode = nextNode.next();
}
selection.move();
}
if (!range) change.apply(safeRange);
}
/**
* 获取对范围有效果的所有 Block
*/
findBlocks(range: RangeInterface) {
const editor = this.editor;
range = range.cloneRange();
if (range.startNode.isRoot()) range.shrinkToElementNode();
if (
!range.startNode.inEditor() ||
editor.card.find(range.startNode)?.type === CardType.BLOCK
)
return [];
const sc = range.startContainer;
const so = range.startOffset;
const ec = range.endContainer;
const eo = range.endOffset;
let startNode = sc;
let endNode = ec;
if (sc.nodeType === Node.ELEMENT_NODE) {
if (sc.childNodes[so]) {
startNode = sc.childNodes[so] || sc;
}
}
if (ec.nodeType === Node.ELEMENT_NODE) {
if (eo > 0 && ec.childNodes[eo - 1]) {
endNode = ec.childNodes[eo - 1] || sc;
}
}
// 折叠状态时,按右侧位置的方式处理
if (range.collapsed) {
startNode = endNode;
}
// 不存在时添加
const addNode = (
nodes: Array<NodeInterface>,
nodeB: NodeInterface,
preppend?: boolean,
) => {
if (
!nodes.some((nodeA) => {
return nodeA[0] === nodeB[0];
})
) {
if (preppend) {
nodes.unshift(nodeB);
} else {
nodes.push(nodeB);
}
}
};
// 向上寻找
const findNodes = (node: NodeInterface) => {
const nodes = [];
while (node) {
if (node.isEditable()) {
break;
}
if (editor.node.isBlock(node)) {
nodes.push(node);
}
const parent = node.parent();
if (!parent) break;
node = parent;
}
return nodes;
};
const nodes = this.getBlocks(range);
// rang头部应该往数组头部插入节点
findNodes($(startNode)).forEach((node) => {
return addNode(nodes, node, true);
});
const { commonAncestorNode } = range;
const card = editor.card.find(commonAncestorNode, true);
let isEditable = card?.isEditable;
const selectionNodes = isEditable
? card?.getSelectionNodes
? card.getSelectionNodes()
: []
: [];
if (selectionNodes.length === 0) {
isEditable = false;
}
if (!range.collapsed || isEditable) {
findNodes($(endNode)).forEach((node) => {
return addNode(nodes, node);
});
selectionNodes.forEach((commonAncestorNode) => {
commonAncestorNode.traverse(
(child) => {
if (
child.isElement() &&
!child.isCard() &&
editor.node.isBlock(child)
) {
addNode(nodes, child);
}
},
true,
'editable',
);
});
}
return nodes;
}
/**
* 判断范围的 {Edge}Offset 是否在 Block 的开始位置
* @param range 光标
* @param edge start | end
*/
isFirstOffset(range: RangeInterface, edge: 'start' | 'end') {
const { startNode, endNode, startOffset, endOffset } = range;
const container = edge === 'start' ? startNode : endNode;
const offset = edge === 'start' ? startOffset : endOffset;
range = range.cloneRange();
const block = this.closest(container);
range.select(block, true);
range.setEnd(container[0], offset);
const editor = this.editor;
if (!editor.node.isBlock(container)) range.enlargeToElementNode();
const fragment = range.cloneContents();
if (!fragment.firstChild) {
return true;
}
const { node } = editor;
if (
fragment.childNodes.length === 1 &&
$(fragment.firstChild).name === 'br'
) {
return true;
}
const emptyNode = $('<div />');
emptyNode.append(fragment);
return node.isEmpty(emptyNode);
}
/**
* 判断范围的 {Edge}Offset 是否在 Block 的最后位置
* @param range 光标
* @param edge start | end
*/
isLastOffset(range: RangeInterface, edge: 'start' | 'end') {
const { startNode, endNode, startOffset, endOffset } = range;
const container = edge === 'start' ? startNode : endNode;
const offset = edge === 'start' ? startOffset : endOffset;
range = range.cloneRange();
const block = this.closest(container);
range.select(block, true);
range.setStart(container, offset);
const { node } = this.editor;
if (!node.isBlock(container)) range.enlargeToElementNode();
const fragment = range.cloneContents();
if (!fragment.firstChild) {
return true;
}
const emptyNode = $('<div />');
emptyNode.append(fragment);
return 0 >= emptyNode.find('br').length && node.isEmpty(emptyNode);
}
/**
* 获取范围内的所有 Block
* @param range 光标s
*/
getBlocks(range: RangeInterface) {
range = range.cloneRange();
range.shrinkToElementNode();
range.shrinkToTextNode();
const editor = this.editor;
const { node } = editor;
let startBlock = this.closest(range.startNode);
if (range.startNode.isRoot()) {
startBlock = $(range.getStartOffsetNode());
}
let endBlock = this.closest(range.endNode);
if (range.endNode.isRoot()) {
endBlock = $(range.getEndOffsetNode());
}
const closest = this.closest(range.commonAncestorNode);
const blocks: Array<NodeInterface> = [];
let started = false;
const { commonAncestorNode } = range;
const card = editor.card.find(commonAncestorNode, true);
let isEditable = card?.isEditable;
const selectionNodes = isEditable
? card?.getSelectionNodes
? card.getSelectionNodes()
: []
: [closest];
if (selectionNodes.length === 0) {
isEditable = false;
selectionNodes.push(closest);
}
selectionNodes.forEach((selectionNode) => {
selectionNode.traverse(
(node) => {
const child = $(node);
if (child.equal(startBlock)) {
started = true;
}
if (
(started || isEditable) &&
editor.node.isBlock(child) &&
!child.isCard() &&
child.inEditor()
) {
blocks.push(child);
}
if (child.equal(endBlock)) {
started = false;
return false;
}
return;
},
true,
'editable',
);
});
// 未选中文本时忽略该 Block
// 示例:<h3><anchor />word</h3><p><focus />another</p>
if (
blocks.length > 1 &&
this.isFirstOffset(range, 'end') &&
!node.isEmpty(endBlock)
) {
blocks.pop();
}
return blocks;
}
/**
* 获取block节点到光标所在位置的blcok节点
* @param options { block, range, isLeft, clone, keepDataId }
* @returns
*/
getBlockByRange({
block,
range,
isLeft,
clone = false,
keepDataId = false,
}: {
block: NodeInterface | Node;
range: RangeInterface;
isLeft: boolean;
clone?: boolean;
keepDataId?: boolean;
}) {
if (isNode(block)) block = $(block);
const editor = this.editor;
const newRange = Range.create(editor, block.document!);
if (isLeft) {
newRange.select(block, true);
newRange.setEnd(range.startContainer, range.startOffset);
} else {
newRange.select(block, true);
newRange.setStart(range.endContainer, range.endOffset);
}
const fragement = clone
? newRange.cloneContents()
: newRange.extractContents();
const cloneBlock = keepDataId
? block.clone(false)
: editor.node.clone(block, false, false);
cloneBlock.append(fragement);
if (clone) {
cloneBlock.find(CARD_SELECTOR).each((card) => {
const domCard = $(card);
const cardName = domCard.attributes(CARD_KEY);
domCard.attributes(READY_CARD_KEY, cardName);
domCard.removeAttributes(CARD_KEY);
});
}
return cloneBlock;
}
/**
* 获取 Block 左侧文本
* @param block 节点
*/
getLeftText(block: NodeInterface | Node, range?: RangeInterface) {
const editor = this.editor;
if (!isEngine(editor)) return '';
range = range || editor.change.range.get();
const leftBlock = this.getBlockByRange({
block,
range,
isLeft: true,
clone: true,
});
return leftBlock.text().replace(/\u200B/g, '');
}
/**
* 删除 Block 左侧文本
* @param block 节点
*/
removeLeftText(block: NodeInterface | Node, range?: RangeInterface) {
const editor = this.editor;
if (!isEngine(editor)) return;
range = range || editor.change.range.get();
if (isNode(block)) block = $(block);
range.createSelection();
const cursor = block.find(CURSOR_SELECTOR);
let isRemove = false;
// 删除左侧文本节点
block.traverse((node) => {
const child = $(node);
if (child.equal(cursor)) {
cursor.remove();
isRemove = true;
return;
}
if (isRemove && child.isText()) {
child.remove();
}
}, false);
}
/**
* 扁平化block节点,防止错误嵌套
* @param block 节点
* @param root 根节点
*/
flat(block: NodeInterface, root: NodeInterface) {
const editor = this.editor;
if (!isEngine(editor)) return;
const { schema, node } = editor;
const mergeTags = schema.getCanMergeTags();
//获取父级节点
let parentNode = block.parent();
const rootElement = root.fragment ? root[0].parentNode : root.get();
//在根节点内循环
while (
parentNode &&
rootElement &&
parentNode.get() !== rootElement &&
parentNode.inEditor()
) {
//如果是卡片节点,就在父节点前面插入
if (block.isCard()) parentNode.before(block);
else if (
//如果是li标签,并且父级是 ol、ul 列表标签
(node.isList(parentNode) && 'li' === block.name) ||
//如果是父级可合并标签,并且当前节点是根block节点,并且不是 父节点一样的block节点
(mergeTags.indexOf(parentNode.name) > -1 &&
node.isBlock(block) &&
parentNode.name !== block.name)
) {
//复制节点
const cloneNode = node.clone(parentNode, false, false);
//追加到复制的节点
cloneNode.append(block);
//设置新的节点
block = cloneNode;
//将新的节点插入到父节点之前
parentNode.before(block);
} else {
block = node.replace(
block,
node.clone(this.findTop(parentNode, block), false, false),
);
parentNode.before(block);
}
//如果没有子节点就移除
if (!parentNode.first()) parentNode.remove();
//设置新的父节点
parentNode = block.parent();
}
}
/**
* 插入一个空的block节点
* @param range 光标所在位置
* @param block 节点
* @returns
*/
insertEmptyBlock(range: RangeInterface, block: NodeInterface) {
const editor = this.editor;
if (!isEngine(editor)) return;
const { change } = editor;
const { blocks, marks } = change;
const nodeApi = editor.node;
this.insert(block);
if (blocks[0]) {
const styles = blocks[0].css();
block.css(styles);
}
let node = block.find('br');
marks.forEach((mark) => {
// 回车后,默认是否复制makr样式
const plugin = editor.mark.findPlugin(mark);
mark = nodeApi.clone(mark, false, false);
//插件判断
if (
plugin?.copyOnEnter !== false &&
plugin?.followStyle !== false
) {
mark = nodeApi.clone(mark, false, false);
node.before(mark);
mark.append(node);
node = mark;
}
});
node = block.find('br');
const parent = node.parent();
if (parent && nodeApi.isMark(parent)) {
node = nodeApi.replace(node, $('\u200b', null));
}
range.select(node).shrinkToTextNode();
range.collapse(false);
range.scrollIntoView();
change.range.select(range);
}
/**
* 在光标位置插入或分割节点
* @param range 光标所在位置
* @param block 节点
*/
insertOrSplit(range: RangeInterface, block: NodeInterface) {
const cloneRange = range.cloneRange();
cloneRange.enlargeFromTextNode();
if (
this.isLastOffset(range, 'end') ||
(cloneRange.endNode.type === Node.ELEMENT_NODE &&
(block.get<Node>()?.childNodes.length || 0) > 0 &&
cloneRange.endContainer.childNodes[cloneRange.endOffset] ===
block.last()?.get() &&
'br' === block.first()?.name)
) {
const emptyElement = $(`<p><br /></p>`);
if (block.name === 'p') {
const attributes = block.attributes();
Object.keys(attributes).forEach((attributeName) => {
if (attributeName === DATA_ID) return;
emptyElement.attributes(
attributeName,
attributes[attributeName],
);
});
}
this.insertEmptyBlock(range, emptyElement);
} else {
this.split();
}
}
}
export default Block; | the_stack |
import React from 'react';
import { compassIcon } from '../../icons/compassIcon';
import { questionsGlobeIcon } from '../../icons/questionsGlobeIcon';
import { conceptsIcon } from '../../icons/conceptsIcon';
import { communityGlobeIcon } from '../../icons/communityGlobeIcon';
import { BookIcon } from '../../icons/bookIcon'
import { allPostsIcon } from '../../icons/allPostsIcon';
import Home from '@material-ui/icons/Home'
import LocalOffer from '@material-ui/icons/LocalOffer';
import Sort from '@material-ui/icons/Sort'
import Info from '@material-ui/icons/Info';
import LocalLibrary from '@material-ui/icons/LocalLibrary';
import PlaylistAddCheck from '@material-ui/icons/PlaylistAddCheck';
import EventIcon from '@material-ui/icons/Event';
import SupervisedUserCircleIcon from '@material-ui/icons/SupervisedUserCircle';
import { communityPath } from '../../../lib/routes';
import { REVIEW_YEAR } from '../../../lib/reviewUtils';
import { ForumOptions } from '../../../lib/forumTypeUtils';
import { taggingNamePluralCapitalSetting, taggingNamePluralSetting, taggingNameSetting } from '../../../lib/instanceSettings';
// The sidebar / bottom bar of the Forum contain 10 or so similar tabs, unique to each Forum. The
// tabs can appear in
// 1. The always-on sidebar of the homepage (allPosts, etc, [see Layout.jsx]) (Standalone Sidbar)
// 2. The always-on bottom bar of the homepage (etc) on mobile (Standalone FooterMenu)
// 3. The swipeable drawer of any other page (hidden by default) (Drawer Menu)
// 4. The same as 3, but collapsed to make room for table of contents on mobile (Drawer Collapsed
// Menu)
//
// Tab objects support the following properties
// id: string, required, unique; for React map keys. `divider` is a keyword id
// title: string; user facing description
// link: string
// // One of the following 3
// icon: already-rendered-Component
// iconComponent: Component-ready-for-rendering
// compressedIconComponent: Component-ready-for-rendering; only displayed in compressed mode (4)
// tooltip: string|Component; passed into Tooltip `title`; optionaly -- without it the Tooltip
// call is a no-op
// showOnMobileStandalone: boolean; show in (2) Standalone Footer Menu
// showOnCompressed: boolean; show in (4) Drawer Collapsed Menu
// subitem: boolean; display title in smaller text
// loggedOutOnly: boolean; only visible to logged out users
// customComponentName: string; instead of a TabNavigationItem, display this component
//
// See TabNavigation[Footer|Compressed]?Item.jsx for how these are used by the code
type MenuTabDivider = {
id: string
divider: true
showOnCompressed?: boolean
}
type MenuTabCustomComponent = {
id: string
customComponentName: string
}
export type MenuTabRegular = {
id: string
title: string
mobileTitle?: string
link: string
icon?: React.ReactNode
iconComponent?: any // I tried
compressedIconComponent?: any
tooltip?: React.ReactNode
showOnMobileStandalone?: boolean
showOnCompressed?: boolean
subItem?: boolean,
loggedOutOnly?: boolean
}
type MenuTab = MenuTabDivider | MenuTabCustomComponent | MenuTabRegular
export const menuTabs: ForumOptions<Array<MenuTab>> = {
LessWrong: [
{
id: 'home',
title: 'Home',
link: '/',
icon: compassIcon,
tooltip: 'Latest posts, comments and curated content.',
showOnMobileStandalone: true,
showOnCompressed: true,
}, {
id: 'concepts',
title: 'Concepts',
mobileTitle: 'Concepts',
link: '/tags/all',
icon: conceptsIcon,
tooltip: <div>
Get an overview over all the concepts used on LessWrong
</div>,
showOnMobileStandalone: true,
showOnCompressed: true,
}, {
id: 'library',
title: 'Library',
link: '/library',
iconComponent: BookIcon,
tooltip: "Curated collections of LessWrong's best writing.",
showOnMobileStandalone: true,
showOnCompressed: true,
// next 3 are subItems
}, {
id: 'r-az',
title: 'Rationality: A-Z',
link: '/rationality',
tooltip: <div>
<p>
LessWrong was founded by Eliezer Yudkowsky. For two years he wrote a blogpost a day about topics including rationality, science, ambition and artificial intelligence.
</p>
<p>
Those posts have been edited down into this introductory collection, recommended for new users.
</p>
</div>,
subItem: true,
}, {
id: 'codex',
title: 'The Codex',
link: '/codex',
tooltip: 'The Codex is a collection of essays written by Scott Alexander that discuss how good reasoning works, how to learn from the institution of science, and different ways society has been and could be designed.',
subItem: true,
}, {
id: 'hpmor',
title: 'HPMOR',
link: '/hpmor',
tooltip: 'What if Harry Potter was a scientist? What would you do if the universe had magic in it? A story that illustrates many rationality concepts.',
subItem: true,
}, {
id: 'bestoflesswrong',
title: 'Best Of',
link: '/bestoflesswrong',
tooltip: "Top posts from the Annual Review (2018 through " + REVIEW_YEAR + ")",
subItem: true,
}, {
id: 'events',
title: 'Community Events', // Events hide on mobile
mobileTitle: 'Community',
link: communityPath,
icon: communityGlobeIcon,
tooltip: 'Find a meetup near you.',
showOnMobileStandalone: true,
showOnCompressed: true,
}, {
id: 'eventsList',
customComponentName: "EventsList",
}, {
id: 'allPosts',
title: 'All Posts',
link: '/allPosts',
icon: allPostsIcon,
tooltip: 'See all posts, filtered and sorted however you like.',
showOnMobileStandalone: true,
showOnCompressed: true,
}, {
id: 'divider',
divider: true,
showOnCompressed: true,
}, {
id: 'subscribeWidget',
customComponentName: "SubscribeWidget",
}, {
id: 'questions',
title: 'Open Questions',
mobileTitle: 'Questions',
link: '/questions',
tooltip: <div>
<div>• Ask simple newbie questions.</div>
<div>• Collaborate on open research questions.</div>
<div>• Pose and resolve confusions.</div>
</div>,
subItem: true
}, {
id: 'contact',
title: 'Contact Us',
link: '/contact',
subItem: true,
}, {
id: 'about',
title: 'About',
link: '/about',
subItem: true,
compressedIconComponent: Info,
showOnCompressed: true,
}, {
id: 'faq',
title: 'FAQ',
link: '/faq',
subItem: true,
}, {
id: 'donate',
title: "Donate",
link: '/donate',
subItem: true
}
],
AlignmentForum: [
{
id: 'home',
title: 'Home',
link: '/',
icon: compassIcon,
tooltip: 'Latest posts, comments and curated content.',
showOnMobileStandalone: true,
showOnCompressed: true,
}, {
id: 'library',
title: 'Library',
link: '/library',
iconComponent: BookIcon,
tooltip: "Curated collections of the AI Alignment Forum's best writing.",
showOnMobileStandalone: true,
showOnCompressed: true,
}, {
id: 'questions',
title: 'Questions',
link: '/questions',
icon: questionsGlobeIcon,
tooltip: <div>
<div>• Ask simple newbie questions.</div>
<div>• Collaborate on open research questions.</div>
<div>• Pose and resolve confusions.</div>
</div>,
showOnMobileStandalone: true,
showOnCompressed: true,
}, {
id: 'allPosts',
title: 'All Posts',
link: '/allPosts',
icon: allPostsIcon,
tooltip: 'See all posts, filtered and sorted however you like.',
showOnMobileStandalone: true,
showOnCompressed: true,
}, {
id: 'divider',
divider: true,
}, {
id: 'about',
title: 'About',
link: '/about',
subItem: true,
compressedIconComponent: Info,
showOnCompressed: true,
}
],
EAForum: [
{
id: 'home',
title: 'Home',
link: '/',
iconComponent: Home,
tooltip: 'See recent posts on strategies for doing the most good, plus recent activity from all across the Forum.',
showOnMobileStandalone: true,
showOnCompressed: true,
}, {
id: 'allPosts',
title: 'All Posts',
link: '/allPosts',
iconComponent: Sort,
tooltip: 'See all posts, filtered and sorted by date, karma, and more.',
showOnMobileStandalone: false,
showOnCompressed: true,
}, {
id: taggingNamePluralSetting.get(),
title: taggingNamePluralCapitalSetting.get(),
mobileTitle: taggingNamePluralCapitalSetting.get(),
link: `/${taggingNamePluralSetting.get()}/all`,
iconComponent: LocalOffer,
tooltip: `EA concepts directory that anyone can edit. Each ${taggingNameSetting.get()} also has a list of posts that have been tagged with it.`,
showOnMobileStandalone: true,
showOnCompressed: true,
}, {
id: 'library',
title: 'Library',
link: '/library',
iconComponent: LocalLibrary,
tooltip: "Core reading, and sequences of posts building on a common theme",
showOnMobileStandalone: true,
showOnCompressed: true,
}, {
id: 'handbook',
title: 'The EA Handbook',
link: '/handbook',
tooltip: "To help you learn the basics of Effective Altruism, we took some of the best writing and made this handbook. Think of it as the textbook you’d get in your first college course. It explains the core ideas of EA, so that you can start applying them to your own life.",
subItem: true,
}, {
id: 'replacing-guilt',
title: 'Replacing Guilt',
link: '/s/a2LBRPLhvwB83DSGq',
tooltip: "Nate Soares writes about replacing guilt with other feelings and finding better ways to motivate yourself, so you can build a better future without falling apart.",
subItem: true,
}, {
id: 'most-important-century',
title: 'Most Important Century',
link: '/s/isENJuPdB3fhjWYHd',
tooltip: `Holden Karnofsky argues that we may be living in the most important century ever — a time when our decisions could shape the future for billions of years to come.`,
subItem: true,
}, {
id: 'takeAction',
title: 'Take Action',
link: `/${taggingNamePluralSetting.get()}/take-action`,
iconComponent: PlaylistAddCheck,
tooltip: "Opportunities to get involved with impactful work",
loggedOutOnly: true
}, {
id: 'events',
title: 'Events',
link: '/events',
iconComponent: EventIcon,
tooltip: 'Upcoming events near you',
showOnMobileStandalone: true,
showOnCompressed: true
}, {
id: 'eventsList',
customComponentName: "EventsList",
}, {
id: 'community',
title: 'Community',
link: communityPath,
iconComponent: SupervisedUserCircleIcon,
tooltip: 'Join a group near you or meet others online',
showOnMobileStandalone: false,
showOnCompressed: true
}, {
id: 'local-groups',
title: 'Local Groups',
link: '/community',
subItem: true,
}, {
id: 'online-groups',
title: 'Online Groups',
link: '/community#online',
subItem: true,
}, {
id: 'community-members',
title: 'Community Members',
link: '/community#individuals',
subItem: true,
}, {
id: 'divider',
divider: true,
showOnCompressed: true,
}, {
id: 'shortform',
title: 'Shortform',
link: '/shortform',
subItem: true,
}, {
id: 'subscribeWidget',
customComponentName: "SubscribeWidget",
}, {
id: 'intro',
title: 'About EA',
link: 'https://www.effectivealtruism.org',
subItem: true,
}, {
id: 'about',
title: 'About the Forum',
link: '/about',
subItem: true,
compressedIconComponent: Info,
showOnCompressed: true,
}, {
id: 'contact',
title: 'Contact Us',
link: '/contact',
subItem: true,
}
],
default: [
{
id: 'home',
title: 'Home',
link: '/',
iconComponent: Home,
tooltip: 'See recent posts on strategies for doing the most good, plus recent activity from all across the Forum.',
showOnMobileStandalone: true,
showOnCompressed: true,
}, {
id: 'allPosts',
title: 'All Posts',
link: '/allPosts',
iconComponent: Sort,
tooltip: 'See all posts, filtered and sorted by date, karma, and more.',
showOnMobileStandalone: false,
showOnCompressed: true,
}, {
id: 'wiki',
title: 'Wiki',
mobileTitle: 'Wiki',
link: '/tags/all',
iconComponent: LocalOffer,
tooltip: 'Collaboratively edited Tags and Wiki Articles',
showOnMobileStandalone: true,
showOnCompressed: true,
}, {
id: 'library',
title: 'Library',
link: '/library',
iconComponent: LocalLibrary,
tooltip: "Core reading, and sequences of posts building on a common theme",
showOnMobileStandalone: true,
showOnCompressed: true,
}, {
id: 'events',
title: 'Community and Events',
mobileTitle: 'Events',
link: communityPath,
iconComponent: SupervisedUserCircleIcon,
tooltip: 'See groups and events in your area',
showOnMobileStandalone: true,
showOnCompressed: true
}, {
id: 'eventsList',
customComponentName: "EventsList",
}, {
id: 'divider',
divider: true,
showOnCompressed: true,
}, {
id: 'shortform',
title: 'Shortform',
link: '/shortform',
subItem: true,
}, {
id: 'subscribeWidget',
customComponentName: "SubscribeWidget",
}, {
id: 'about',
title: 'About the Forum',
link: '/about',
subItem: true,
compressedIconComponent: Info,
showOnCompressed: true,
}, {
id: 'contact',
title: 'Contact Us',
link: '/contact',
subItem: true,
}
]
}
export default menuTabs; | the_stack |
import { AstNode, AstReflection, Reference } from '../../syntax-tree';
import { isAstNode } from '../../utils/ast-util';
export interface AbstractElement extends AstNode {
readonly $container: ParserRule | Alternatives | Group | UnorderedGroup | Assignment | CrossReference | TerminalRule | TerminalAlternatives | TerminalGroup | NegatedToken | UntilToken | CharacterRange;
cardinality: '?' | '*' | '+'
}
export const AbstractElement = 'AbstractElement';
export function isAbstractElement(item: unknown): item is AbstractElement {
return reflection.isInstance(item, AbstractElement);
}
export interface AbstractRule extends AstNode {
readonly $container: Grammar;
fragment: boolean
name: string
type: string
}
export const AbstractRule = 'AbstractRule';
export function isAbstractRule(item: unknown): item is AbstractRule {
return reflection.isInstance(item, AbstractRule);
}
export interface Condition extends AstNode {
readonly $container: Group | NamedArgument | Disjunction | Conjunction | Negation;
}
export const Condition = 'Condition';
export function isCondition(item: unknown): item is Condition {
return reflection.isInstance(item, Condition);
}
export interface Grammar extends AstNode {
definesHiddenTokens: boolean
hiddenTokens: Array<Reference<AbstractRule>>
imports: Array<GrammarImport>
name: string
rules: Array<AbstractRule>
usedGrammars: Array<Reference<Grammar>>
}
export const Grammar = 'Grammar';
export function isGrammar(item: unknown): item is Grammar {
return reflection.isInstance(item, Grammar);
}
export interface GrammarImport extends AstNode {
readonly $container: Grammar;
path: string
}
export const GrammarImport = 'GrammarImport';
export function isGrammarImport(item: unknown): item is GrammarImport {
return reflection.isInstance(item, GrammarImport);
}
export interface NamedArgument extends AstNode {
readonly $container: RuleCall;
calledByName: boolean
parameter?: Reference<Parameter>
value: Condition
}
export const NamedArgument = 'NamedArgument';
export function isNamedArgument(item: unknown): item is NamedArgument {
return reflection.isInstance(item, NamedArgument);
}
export interface Parameter extends AstNode {
readonly $container: ParserRule;
name: string
}
export const Parameter = 'Parameter';
export function isParameter(item: unknown): item is Parameter {
return reflection.isInstance(item, Parameter);
}
export interface Action extends AbstractElement {
feature: string
operator: '=' | '+='
type: string
}
export const Action = 'Action';
export function isAction(item: unknown): item is Action {
return reflection.isInstance(item, Action);
}
export interface Alternatives extends AbstractElement {
elements: Array<AbstractElement>
}
export const Alternatives = 'Alternatives';
export function isAlternatives(item: unknown): item is Alternatives {
return reflection.isInstance(item, Alternatives);
}
export interface Assignment extends AbstractElement {
feature: string
firstSetPredicated: boolean
operator: '+=' | '=' | '?='
predicated: boolean
terminal: AbstractElement
}
export const Assignment = 'Assignment';
export function isAssignment(item: unknown): item is Assignment {
return reflection.isInstance(item, Assignment);
}
export interface CharacterRange extends AbstractElement {
left: Keyword
right: Keyword
}
export const CharacterRange = 'CharacterRange';
export function isCharacterRange(item: unknown): item is CharacterRange {
return reflection.isInstance(item, CharacterRange);
}
export interface CrossReference extends AbstractElement {
deprecatedSyntax: boolean
terminal: AbstractElement
type: Reference<ParserRule>
}
export const CrossReference = 'CrossReference';
export function isCrossReference(item: unknown): item is CrossReference {
return reflection.isInstance(item, CrossReference);
}
export interface Group extends AbstractElement {
elements: Array<AbstractElement>
firstSetPredicated: boolean
guardCondition: Condition
predicated: boolean
}
export const Group = 'Group';
export function isGroup(item: unknown): item is Group {
return reflection.isInstance(item, Group);
}
export interface Keyword extends AbstractElement {
firstSetPredicated: boolean
predicated: boolean
value: string
}
export const Keyword = 'Keyword';
export function isKeyword(item: unknown): item is Keyword {
return reflection.isInstance(item, Keyword);
}
export interface NegatedToken extends AbstractElement {
terminal: AbstractElement
}
export const NegatedToken = 'NegatedToken';
export function isNegatedToken(item: unknown): item is NegatedToken {
return reflection.isInstance(item, NegatedToken);
}
export interface RegexToken extends AbstractElement {
regex: string
}
export const RegexToken = 'RegexToken';
export function isRegexToken(item: unknown): item is RegexToken {
return reflection.isInstance(item, RegexToken);
}
export interface RuleCall extends AbstractElement {
arguments: Array<NamedArgument>
firstSetPredicated: boolean
predicated: boolean
rule: Reference<AbstractRule>
}
export const RuleCall = 'RuleCall';
export function isRuleCall(item: unknown): item is RuleCall {
return reflection.isInstance(item, RuleCall);
}
export interface TerminalAlternatives extends AbstractElement {
elements: Array<AbstractElement>
}
export const TerminalAlternatives = 'TerminalAlternatives';
export function isTerminalAlternatives(item: unknown): item is TerminalAlternatives {
return reflection.isInstance(item, TerminalAlternatives);
}
export interface TerminalGroup extends AbstractElement {
elements: Array<AbstractElement>
}
export const TerminalGroup = 'TerminalGroup';
export function isTerminalGroup(item: unknown): item is TerminalGroup {
return reflection.isInstance(item, TerminalGroup);
}
export interface TerminalRuleCall extends AbstractElement {
rule: Reference<TerminalRule>
}
export const TerminalRuleCall = 'TerminalRuleCall';
export function isTerminalRuleCall(item: unknown): item is TerminalRuleCall {
return reflection.isInstance(item, TerminalRuleCall);
}
export interface UnorderedGroup extends AbstractElement {
elements: Array<AbstractElement>
}
export const UnorderedGroup = 'UnorderedGroup';
export function isUnorderedGroup(item: unknown): item is UnorderedGroup {
return reflection.isInstance(item, UnorderedGroup);
}
export interface UntilToken extends AbstractElement {
terminal: AbstractElement
}
export const UntilToken = 'UntilToken';
export function isUntilToken(item: unknown): item is UntilToken {
return reflection.isInstance(item, UntilToken);
}
export interface Wildcard extends AbstractElement {
}
export const Wildcard = 'Wildcard';
export function isWildcard(item: unknown): item is Wildcard {
return reflection.isInstance(item, Wildcard);
}
export interface ParserRule extends AbstractRule {
alternatives: AbstractElement
definesHiddenTokens: boolean
entry: boolean
hiddenTokens: Array<Reference<AbstractRule>>
parameters: Array<Parameter>
wildcard: boolean
}
export const ParserRule = 'ParserRule';
export function isParserRule(item: unknown): item is ParserRule {
return reflection.isInstance(item, ParserRule);
}
export interface TerminalRule extends AbstractRule {
hidden: boolean
terminal: AbstractElement
}
export const TerminalRule = 'TerminalRule';
export function isTerminalRule(item: unknown): item is TerminalRule {
return reflection.isInstance(item, TerminalRule);
}
export interface Conjunction extends Condition {
left: Condition
right: Condition
}
export const Conjunction = 'Conjunction';
export function isConjunction(item: unknown): item is Conjunction {
return reflection.isInstance(item, Conjunction);
}
export interface Disjunction extends Condition {
left: Condition
right: Condition
}
export const Disjunction = 'Disjunction';
export function isDisjunction(item: unknown): item is Disjunction {
return reflection.isInstance(item, Disjunction);
}
export interface LiteralCondition extends Condition {
true: boolean
}
export const LiteralCondition = 'LiteralCondition';
export function isLiteralCondition(item: unknown): item is LiteralCondition {
return reflection.isInstance(item, LiteralCondition);
}
export interface Negation extends Condition {
value: Condition
}
export const Negation = 'Negation';
export function isNegation(item: unknown): item is Negation {
return reflection.isInstance(item, Negation);
}
export interface ParameterReference extends Condition {
parameter: Reference<Parameter>
}
export const ParameterReference = 'ParameterReference';
export function isParameterReference(item: unknown): item is ParameterReference {
return reflection.isInstance(item, ParameterReference);
}
export type LangiumGrammarAstType = 'AbstractElement' | 'AbstractRule' | 'Condition' | 'Grammar' | 'GrammarImport' | 'NamedArgument' | 'Parameter' | 'Action' | 'Alternatives' | 'Assignment' | 'CharacterRange' | 'CrossReference' | 'Group' | 'Keyword' | 'NegatedToken' | 'RegexToken' | 'RuleCall' | 'TerminalAlternatives' | 'TerminalGroup' | 'TerminalRuleCall' | 'UnorderedGroup' | 'UntilToken' | 'Wildcard' | 'ParserRule' | 'TerminalRule' | 'Conjunction' | 'Disjunction' | 'LiteralCondition' | 'Negation' | 'ParameterReference';
export type LangiumGrammarAstReference = 'Grammar:hiddenTokens' | 'Grammar:usedGrammars' | 'NamedArgument:parameter' | 'CrossReference:type' | 'RuleCall:rule' | 'TerminalRuleCall:rule' | 'ParserRule:hiddenTokens' | 'ParameterReference:parameter';
export class LangiumGrammarAstReflection implements AstReflection {
getAllTypes(): string[] {
return ['AbstractElement', 'AbstractRule', 'Condition', 'Grammar', 'GrammarImport', 'NamedArgument', 'Parameter', 'Action', 'Alternatives', 'Assignment', 'CharacterRange', 'CrossReference', 'Group', 'Keyword', 'NegatedToken', 'RegexToken', 'RuleCall', 'TerminalAlternatives', 'TerminalGroup', 'TerminalRuleCall', 'UnorderedGroup', 'UntilToken', 'Wildcard', 'ParserRule', 'TerminalRule', 'Conjunction', 'Disjunction', 'LiteralCondition', 'Negation', 'ParameterReference'];
}
isInstance(node: unknown, type: string): boolean {
return isAstNode(node) && this.isSubtype(node.$type, type);
}
isSubtype(subtype: string, supertype: string): boolean {
if (subtype === supertype) {
return true;
}
switch (subtype) {
case Action:
case Alternatives:
case Assignment:
case CharacterRange:
case CrossReference:
case Group:
case Keyword:
case NegatedToken:
case RegexToken:
case RuleCall:
case TerminalAlternatives:
case TerminalGroup:
case TerminalRuleCall:
case UnorderedGroup:
case UntilToken:
case Wildcard: {
return this.isSubtype(AbstractElement, supertype);
}
case ParserRule:
case TerminalRule: {
return this.isSubtype(AbstractRule, supertype);
}
case Conjunction:
case Disjunction:
case LiteralCondition:
case Negation:
case ParameterReference: {
return this.isSubtype(Condition, supertype);
}
default: {
return false;
}
}
}
getReferenceType(referenceId: LangiumGrammarAstReference): string {
switch (referenceId) {
case 'Grammar:hiddenTokens': {
return AbstractRule;
}
case 'Grammar:usedGrammars': {
return Grammar;
}
case 'NamedArgument:parameter': {
return Parameter;
}
case 'CrossReference:type': {
return ParserRule;
}
case 'RuleCall:rule': {
return AbstractRule;
}
case 'TerminalRuleCall:rule': {
return TerminalRule;
}
case 'ParserRule:hiddenTokens': {
return AbstractRule;
}
case 'ParameterReference:parameter': {
return Parameter;
}
default: {
throw new Error(`${referenceId} is not a valid reference id.`);
}
}
}
}
export const reflection = new LangiumGrammarAstReflection(); | the_stack |
import { _SharePointQueryable, ISharePointQueryable } from "../sharepointqueryable.js";
import { extractWebUrl } from "../utils/extractweburl.js";
import { headers, body } from "@pnp/odata";
import { spPost } from "../operations.js";
import { hOP } from "@pnp/common";
import { tag } from "../telemetry.js";
export class _SiteDesigns extends _SharePointQueryable {
constructor(baseUrl: string | ISharePointQueryable, methodName = "") {
const url = typeof baseUrl === "string" ? baseUrl : baseUrl.toUrl();
super(extractWebUrl(url), `_api/Microsoft.Sharepoint.Utilities.WebTemplateExtensions.SiteScriptUtility.${methodName}`);
}
public execute<T>(props: any): Promise<T> {
return spPost<T>(this, body(props, headers({ "Content-Type": "application/json;charset=utf-8" })));
}
/**
* Creates a new site design available to users when they create a new site from the SharePoint home page.
*
* @param creationInfo A sitedesign creation information object
*/
@tag("sd.createSiteDesign")
public createSiteDesign(creationInfo: ISiteDesignCreationInfo): Promise<ISiteDesignInfo> {
return this.clone(SiteDesignsCloneFactory, "CreateSiteDesign").execute<ISiteDesignInfo>({ info: creationInfo });
}
/**
* Applies a site design to an existing site collection.
*
* @param siteDesignId The ID of the site design to apply.
* @param webUrl The URL of the site collection where you want to apply the site design.
*/
@tag("sd.applySiteDesign")
public applySiteDesign(siteDesignId: string, webUrl: string): Promise<void> {
return this.clone(SiteDesignsCloneFactory, "ApplySiteDesign").execute<void>({ siteDesignId: siteDesignId, "webUrl": webUrl });
}
/**
* Gets the list of available site designs
*/
@tag("sd.getSiteDesigns")
public getSiteDesigns(): Promise<ISiteDesignInfo[]> {
return this.clone(SiteDesignsCloneFactory, "GetSiteDesigns").execute<ISiteDesignInfo[]>({});
}
/**
* Gets information about a specific site design.
* @param id The ID of the site design to get information about.
*/
@tag("sd.getSiteDesignMetadata")
public getSiteDesignMetadata(id: string): Promise<ISiteDesignInfo> {
return this.clone(SiteDesignsCloneFactory, "GetSiteDesignMetadata").execute<ISiteDesignInfo>({ id: id });
}
/**
* Updates a site design with new values. In the REST call, all parameters are optional except the site script Id.
* If you had previously set the IsDefault parameter to TRUE and wish it to remain true, you must pass in this parameter again (otherwise it will be reset to FALSE).
* @param updateInfo A sitedesign update information object
*/
@tag("sd.updateSiteDesign")
public updateSiteDesign(updateInfo: ISiteDesignUpdateInfo): Promise<ISiteDesignInfo> {
return this.clone(SiteDesignsCloneFactory, "UpdateSiteDesign").execute<ISiteDesignInfo>({ updateInfo: updateInfo });
}
/**
* Deletes a site design.
* @param id The ID of the site design to delete.
*/
@tag("sd.deleteSiteDesign")
public deleteSiteDesign(id: string): Promise<void> {
return this.clone(SiteDesignsCloneFactory, "DeleteSiteDesign").execute<void>({ id: id });
}
/**
* Gets a list of principals that have access to a site design.
* @param id The ID of the site design to get rights information from.
*/
@tag("sd.getSiteDesignRights")
public getSiteDesignRights(id: string): Promise<ISiteDesignPrincipals[]> {
return this.clone(SiteDesignsCloneFactory, "GetSiteDesignRights").execute<ISiteDesignPrincipals[]>({ id: id });
}
/**
* Grants access to a site design for one or more principals.
* @param id The ID of the site design to grant rights on.
* @param principalNames An array of one or more principals to grant view rights.
* Principals can be users or mail-enabled security groups in the form of "alias" or "alias@<domain name>.com"
* @param grantedRights Always set to 1. This represents the View right.
*/
@tag("sd.grantSiteDesignRights")
public grantSiteDesignRights(id: string, principalNames: string[], grantedRights = 1): Promise<void> {
return this.clone(SiteDesignsCloneFactory, "GrantSiteDesignRights")
.execute<void>({
"grantedRights": grantedRights.toString(),
"id": id,
"principalNames": principalNames,
});
}
/**
* Revokes access from a site design for one or more principals.
* @param id The ID of the site design to revoke rights from.
* @param principalNames An array of one or more principals to revoke view rights from.
* If all principals have rights revoked on the site design, the site design becomes viewable to everyone.
*/
@tag("sd.revokeSiteDesignRights")
public revokeSiteDesignRights(id: string, principalNames: string[]): Promise<void> {
return this.clone(SiteDesignsCloneFactory, "RevokeSiteDesignRights")
.execute<void>({
"id": id,
"principalNames": principalNames,
});
}
/**
* Adds a site design task on the specified web url to be invoked asynchronously.
* @param webUrl The absolute url of the web on where to create the task
* @param siteDesignId The ID of the site design to create a task for
*/
@tag("sd.addSiteDesignTask")
public addSiteDesignTask(webUrl: string, siteDesignId: string): Promise<ISiteDesignTask> {
return this.clone(SiteDesignsCloneFactory, "AddSiteDesignTask")
.execute<ISiteDesignTask>({ "webUrl": webUrl, "siteDesignId": siteDesignId });
}
/**
* Adds a site design task on the current web to be invoked asynchronously.
* @param siteDesignId The ID of the site design to create a task for
*/
@tag("sd.addSiteDesignTaskToCurrentWeb")
public addSiteDesignTaskToCurrentWeb(siteDesignId: string): Promise<ISiteDesignTask> {
return this.clone(SiteDesignsCloneFactory, "AddSiteDesignTaskToCurrentWeb")
.execute<ISiteDesignTask>({ "siteDesignId": siteDesignId });
}
/**
* Retrieves the site design task, if the task has finished running null will be returned
* @param id The ID of the site design task
*/
@tag("sd.getSiteDesignTask")
public async getSiteDesignTask(id: string): Promise<ISiteDesignTask> {
const task = await this.clone(SiteDesignsCloneFactory, "GetSiteDesignTask")
.execute<ISiteDesignTask>({ "taskId": id });
return hOP(task, "ID") ? task : null;
}
/**
* Retrieves a list of site design that have run on a specific web
* @param webUrl The url of the web where the site design was applied
* @param siteDesignId (Optional) the site design ID, if not provided will return all site design runs
*/
@tag("sd.getSiteDesignRun")
public getSiteDesignRun(webUrl: string, siteDesignId?: string): Promise<ISiteDesignRun[]> {
return this.clone(SiteDesignsCloneFactory, "GetSiteDesignRun")
.execute<ISiteDesignRun[]>({ "webUrl": webUrl, siteDesignId: siteDesignId });
}
/**
* Retrieves the status of a site design that has been run or is still running
* @param webUrl The url of the web where the site design was applied
* @param runId the run ID
*/
@tag("sd.getSiteDesignRunStatus")
public getSiteDesignRunStatus(webUrl: string, runId: string): Promise<ISiteScriptActionStatus[]> {
return this.clone(SiteDesignsCloneFactory, "GetSiteDesignRunStatus")
.execute<ISiteScriptActionStatus[]>({ "webUrl": webUrl, runId: runId });
}
}
export interface ISiteDesigns extends _SiteDesigns {}
export const SiteDesigns = (baseUrl: string | ISharePointQueryable, methodName?: string): ISiteDesigns => new _SiteDesigns(baseUrl, methodName);
type SiteDesignsCloneType = ISiteDesigns & ISharePointQueryable & { execute<T>(props: any): Promise<T> };
const SiteDesignsCloneFactory = (baseUrl: string | ISharePointQueryable, methodName = ""): SiteDesignsCloneType => <any>SiteDesigns(baseUrl, methodName);
/**
* Result from creating or retrieving a site design
*
*/
export interface ISiteDesignInfo {
/**
* The ID of the site design to apply.
*/
Id: string;
/**
* The display name of the site design.
*/
Title: string;
/**
* Identifies which base template to add the design to. Use the value 64 for the Team site template, and the value 68 for the Communication site template.
*/
WebTemplate: string;
/**
* An array of one or more site scripts. Each is identified by an ID. The scripts will run in the order listed.
*/
SiteScriptIds: string[];
/**
* The display description of site design.
*/
Description: string;
/**
* The URL of a preview image. If none is specified, SharePoint uses a generic image.
*/
PreviewImageUrl: string;
/**
* The alt text description of the image for accessibility.
*/
PreviewImageAltText: string;
/**
* True if the site design is applied as the default site design; otherwise, false.
* For more information see Customize a default site design https://docs.microsoft.com/en-us/sharepoint/dev/declarative-customization/customize-default-site-design.
*/
IsDefault: boolean;
/**
* The version number of the site design
*/
Version: string;
}
/**
* Data for creating a site design
*
*/
export interface ISiteDesignCreationInfo {
/**
* The display name of the site design.
*/
Title: string;
/**
* Identifies which base template to add the design to. Use the value 64 for the Team site template, and the value 68 for the Communication site template.
*/
WebTemplate: string;
/**
* An array of one or more site scripts. Each is identified by an ID. The scripts will run in the order listed.
*/
SiteScriptIds?: string[];
/**
* (Optional) The display description of site design.
*/
Description?: string;
/**
* (Optional) The URL of a preview image. If none is specified, SharePoint uses a generic image.
*/
PreviewImageUrl?: string;
/**
* (Optional) The alt text description of the image for accessibility.
*/
PreviewImageAltText?: string;
/**
* (Optional) True if the site design is applied as the default site design; otherwise, false.
* For more information see Customize a default site design https://docs.microsoft.com/en-us/sharepoint/dev/declarative-customization/customize-default-site-design.
*/
IsDefault?: boolean;
}
/**
* Data for updating a site design
*
*/
export interface ISiteDesignUpdateInfo {
/**
* The ID of the site design to apply.
*/
Id: string;
/**
* (Optional) The new display name of the updated site design.
*/
Title?: string;
/**
* (Optional) The new template to add the site design to. Use the value 64 for the Team site template, and the value 68 for the Communication site template.
*/
WebTemplate?: string;
/**
* (Optional) A new array of one or more site scripts. Each is identified by an ID. The scripts run in the order listed.
*/
SiteScriptIds?: string[];
/**
* (Optional) The new display description of the updated site design.
*/
Description?: string;
/**
* (Optional) The new URL of a preview image.
*/
PreviewImageUrl?: string;
/**
* (Optional) The new alt text description of the image for accessibility.
*/
PreviewImageAltText?: string;
/**
* (Optional) True if the site design is applied as the default site design; otherwise, false.
* For more information see Customize a default site design https://docs.microsoft.com/en-us/sharepoint/dev/declarative-customization/customize-default-site-design.
* If you had previously set the IsDefault parameter to TRUE and wish it to remain true, you must pass in this parameter again (otherwise it will be reset to FALSE).
*/
IsDefault?: boolean;
}
/**
* Result from retrieving the rights for a site design
*
*/
export interface ISiteDesignPrincipals {
/**
* Display name
*/
DisplayName: string;
/**
* The principal name
*/
PrincipalName: string;
/**
* The principal name
*/
Rights: number;
}
export interface ISiteDesignTask {
/**
* The ID of the site design task
*/
ID: string;
/**
* Logonname of the user who created the task
*/
LogonName: string;
/**
* The ID of the site design the task is running on
*/
SiteDesignID: string;
/**
* The ID of the site collection
*/
SiteID: string;
/**
* The ID of the web
*/
WebID: string;
}
export interface ISiteScriptActionStatus {
/**
* Action index
*/
ActionIndex: number;
/**
* Action key
*/
ActionKey: string;
/**
* Action title
*/
ActionTitle: string;
/**
* Last modified
*/
LastModified: number;
/**
* Ordinal index
*/
OrdinalIndex: string;
/**
* Outcome code
*/
OutcomeCode: number;
/**
* Outcome text
*/
OutcomeText: string;
/**
* Site script id
*/
SiteScriptID: string;
/**
* Site script index
*/
SiteScriptIndex: number;
/**
* Site script title
*/
SiteScriptTitle: string;
}
export interface ISiteDesignRun {
/**
* The ID of the site design run
*/
ID: string;
/**
* The ID of the site design that was applied
*/
SiteDesignID: string;
/**
* The title of the site design that was applied
*/
SiteDesignTitle: string;
/**
* The version of the site design that was applied
*/
SiteDesignVersion: number;
/**
* The site id where the site design was applied
*/
SiteID: string;
/**
* The start time when the site design was applied
*/
StartTime: number;
/**
* The web id where the site design was applied
*/
WebID: string;
} | the_stack |
import { Notifier } from 'coc-helper';
import { Uri, window, workspace } from 'coc.nvim';
import fs from 'fs';
import { homedir } from 'os';
import pathLib from 'path';
import { argOptions } from '../../../arg/argOptions';
import { getRevealAuto, getRevealWhenOpen } from '../../../config';
import { diagnosticHighlights } from '../../../diagnostic/highlights';
import { onBufEnter } from '../../../events';
import { gitHighlights } from '../../../git/highlights';
import { gitManager } from '../../../git/manager';
import { internalHighlightGroups } from '../../../highlight/internalColors';
import { hlGroupManager } from '../../../highlight/manager';
import { fileList } from '../../../lists/files';
import { startCocList } from '../../../lists/runner';
import { RootStrategyStr } from '../../../types';
import { Explorer } from '../../../types/pkg-config';
import {
fsAccess,
fsLstat,
fsReaddir,
fsStat,
getExtensions,
isWindows,
listDrive,
logger,
normalizePath,
} from '../../../util';
import { RendererSource } from '../../../view/rendererSource';
import { ViewSource } from '../../../view/viewSource';
import { BaseTreeNode, ExplorerSource } from '../../source';
import { sourceManager } from '../../sourceManager';
import { fileArgOptions } from './argOptions';
import { loadFileActions } from './fileActions';
import { fileColumnRegistrar } from './fileColumnRegistrar';
import './load';
export interface FileNode extends BaseTreeNode<FileNode, 'root' | 'child'> {
name: string;
fullpath: string;
directory: boolean;
readonly: boolean;
executable: boolean;
readable: boolean;
writable: boolean;
hidden: boolean;
symbolicLink: boolean;
lstat?: fs.Stats;
}
const hlg = hlGroupManager.linkGroup.bind(hlGroupManager);
const directoryHighlight = hlg('FileDirectory', 'Directory');
export const fileHighlights = {
title: hlg('FileRoot', 'Constant'),
hidden: hlg('FileHidden', 'Comment'),
rootName: hlg('FileRootName', 'Identifier'),
expandIcon: hlg('FileExpandIcon', 'Directory'),
fullpath: hlg('FileFullpath', 'Comment'),
filename: hlg('FileFilename', 'None'),
directory: directoryHighlight,
directoryExpanded: hlg('FileDirectoryExpanded', directoryHighlight.group),
directoryCollapsed: hlg('FileDirectoryCollapsed', directoryHighlight.group),
linkTarget: hlg('FileLinkTarget', 'Comment'),
gitStaged: hlg('FileGitStaged', gitHighlights.gitStaged.group),
gitUnstaged: hlg('FileGitUnstaged', gitHighlights.gitUnstaged.group),
gitRootStaged: hlg('FileGitRootStaged', 'Comment'),
gitRootUnstaged: hlg('FileGitRootUnstaged', 'Operator'),
indentLine: hlg('IndentLine', internalHighlightGroups.CommentColor),
clip: hlg('FileClip', 'Statement'),
size: hlg('FileSize', 'Constant'),
readonly: hlg('FileReadonly', 'Operator'),
modified: hlg('FileModified', 'Operator'),
timeAccessed: hlg('TimeAccessed', 'Identifier'),
timeModified: hlg('TimeModified', 'Identifier'),
timeCreated: hlg('TimeCreated', 'Identifier'),
diagnosticError: hlg(
'FileDiagnosticError',
diagnosticHighlights.diagnosticError.group,
),
diagnosticWarning: hlg(
'FileDiagnosticWarning',
diagnosticHighlights.diagnosticWarning.group,
),
filenameDiagnosticError: hlg('FileFilenameDiagnosticError', 'CocErrorSign'),
filenameDiagnosticWarning: hlg(
'FileFilenameDiagnosticWarning',
'CocWarningSign',
),
};
export class FileSource extends ExplorerSource<FileNode> {
scheme = 'file';
showHidden: boolean = this.config.get<boolean>('file.showHiddenFiles')!;
showOnlyGitChange: boolean = false;
copiedNodes: Set<FileNode> = new Set();
cutNodes: Set<FileNode> = new Set();
view: ViewSource<FileNode> = new ViewSource<FileNode>(
this,
fileColumnRegistrar,
{
type: 'root',
isRoot: true,
uid: this.helper.getUid(pathLib.sep),
name: 'root',
fullpath: homedir(),
expandable: true,
directory: true,
readonly: true,
executable: false,
readable: true,
writable: true,
hidden: false,
symbolicLink: true,
lstat: undefined,
},
);
rootStrategies: RootStrategyStr[] = [];
get root() {
return this.view.rootNode.fullpath;
}
set root(root: string) {
this.view.rootNode.uid = this.helper.getUid(root);
this.view.rootNode.fullpath = root;
this.view.rootNode.children = undefined;
}
getHiddenRules() {
return this.config.get<{
extensions: string[];
filenames: string[];
patternMatches: string[];
}>('file.hiddenRules')!;
}
isHidden(filename: string) {
const hiddenRules = this.getHiddenRules();
const { basename, extensions } = getExtensions(filename);
const extname = extensions[extensions.length - 1];
return (
hiddenRules.filenames.includes(basename) ||
hiddenRules.extensions.includes(extname) ||
hiddenRules.patternMatches.some((pattern) =>
new RegExp(pattern).test(filename),
)
);
}
isGitChange(parentNode: FileNode, filename: string): boolean {
return !!gitManager.getMixedStatus(
parentNode.fullpath + '/' + filename,
false,
);
}
getColumnConfig<T>(name: string, defaultValue?: T): T {
return this.config.get('file.column.' + name, defaultValue)!;
}
async init() {
if (getRevealAuto(this.config)) {
this.disposables.push(
onBufEnter(async (bufnr) => {
if (bufnr === this.explorer.bufnr) {
return;
}
if (!this.explorer.visible()) {
return;
}
if (this.explorer.isFloating) {
return;
}
await this.view.sync(async (r) => {
const fullpath = this.bufManager.getBufferNode(bufnr)?.fullpath;
if (!fullpath) {
return;
}
const [revealNode, notifiers] = await this.revealNodeByPathNotifier(
r,
fullpath,
);
if (revealNode) {
await Notifier.runAll(notifiers);
}
});
}, 200),
);
}
this.disposables.push(
this.events.on('loaded', () => {
this.copiedNodes.clear();
this.cutNodes.clear();
}),
);
loadFileActions(this.action);
}
async open() {
await this.view.parseTemplate(
'root',
await this.explorer.args.value(fileArgOptions.fileRootTemplate),
await this.explorer.args.value(fileArgOptions.fileRootLabelingTemplate),
);
await this.view.parseTemplate(
'child',
await this.explorer.args.value(fileArgOptions.fileChildTemplate),
await this.explorer.args.value(fileArgOptions.fileChildLabelingTemplate),
);
this.root = this.explorer.root;
this.rootStrategies = this.explorer.argValues.rootStrategies;
}
async cd(fullpath: string) {
const { nvim } = this;
const escapePath = (await nvim.call('fnameescape', fullpath)) as string;
type CdCmd = Explorer['explorer.file.cdCommand'];
let cdCmd: CdCmd;
const tabCd = this.config.get<boolean>('file.tabCD');
if (tabCd !== undefined) {
logger.error(
'explorer.file.tabCD has been deprecated, please use explorer.file.cdCommand instead of it',
);
if (tabCd) {
cdCmd = 'tcd';
} else {
cdCmd = 'cd';
}
} else {
cdCmd = this.config.get<CdCmd>('file.cdCommand');
}
if (cdCmd === 'tcd') {
if (workspace.isNvim || (await nvim.call('exists', [':tcd']))) {
await nvim.command('tcd ' + escapePath);
// eslint-disable-next-line no-restricted-properties
window.showMessage(`Tab's CWD is: ${fullpath}`);
}
} else if (cdCmd === 'cd') {
await nvim.command('cd ' + escapePath);
// eslint-disable-next-line no-restricted-properties
window.showMessage(`CWD is: ${fullpath}`);
}
}
async openedNotifier(renderer: RendererSource<FileNode>, isFirst: boolean) {
const args = this.explorer.args;
const revealPath = await this.explorer.revealPath();
if (!revealPath) {
if (isFirst) {
return this.locator.gotoRootNotifier({ col: 1 });
}
return Notifier.noop();
}
const hasRevealPath = args.has(argOptions.reveal);
if (
getRevealAuto(this.config) ||
getRevealWhenOpen(this.config, this.explorer.argValues.revealWhenOpen) ||
hasRevealPath
) {
const [revealNode, notifiers] = await this.revealNodeByPathNotifier(
renderer,
revealPath,
);
if (revealNode !== undefined) {
return Notifier.combine(notifiers);
} else if (isFirst) {
return Notifier.combine([
...notifiers,
await this.locator.gotoRootNotifier({ col: 1 }),
]);
}
} else if (isFirst) {
return this.locator.gotoRootNotifier({ col: 1 });
}
return Notifier.noop();
}
getPutTargetNode(node: FileNode) {
if (node.isRoot) {
return this.view.rootNode;
} else if (node.expandable && this.view.isExpanded(node)) {
return node;
} else if (node.parent) {
return node.parent;
} else {
return this.view.rootNode;
}
}
getPutTargetDir(node: FileNode) {
return this.getPutTargetNode(node).fullpath;
}
async searchByCocList(
path: string,
{
recursive,
noIgnore,
strict,
}: {
recursive: boolean;
noIgnore: boolean;
strict: boolean;
},
) {
const listArgs = strict ? ['--strict'] : [];
const task = await startCocList(
this.explorer,
fileList,
{
showHidden: this.showHidden,
showIgnores: noIgnore,
rootPath: path,
recursive,
revealCallback: async (loc) => {
await task.waitExplorerShow();
await this.view.sync(async (r) => {
const [, notifiers] = await this.revealNodeByPathNotifier(
r,
Uri.parse(loc.uri).fsPath,
);
await Notifier.runAll(notifiers);
});
},
},
listArgs,
);
task.waitExplorerShow()?.catch(logger.error);
}
filterForReveal(path: string, root: string) {
const filter = this.config.get('file.reveal.filter');
const relativePath = path.slice(root.length);
// filter by literals
for (const literal of filter.literals ?? []) {
if (relativePath.includes(literal)) {
return true;
}
}
// filter by patterns
for (const pattern of filter.patterns ?? []) {
if (new RegExp(pattern).test(relativePath)) {
return true;
}
}
return false;
}
async revealNodeByPathNotifier(
renderer: RendererSource<FileNode>,
path: string,
{
startNode = this.view.rootNode,
goto = true,
render = true,
compact,
}: {
startNode?: FileNode;
/**
* @default true
*/
goto?: boolean;
/**
* @default true
*/
render?: boolean;
compact?: boolean;
} = {},
): Promise<[FileNode | undefined, Notifier[]]> {
path = normalizePath(path);
if (this.filterForReveal(path, startNode.fullpath)) {
return [undefined, []];
}
const notifiers: Notifier[] = [];
const revealRecursive = async (
path: string,
{
startNode,
goto,
render,
}: { startNode: FileNode; goto: boolean; render: boolean },
): Promise<FileNode | undefined> => {
if (path === startNode.fullpath) {
return startNode;
} else if (
startNode.directory &&
path.startsWith(startNode.fullpath + pathLib.sep)
) {
let foundNode: FileNode | undefined = undefined;
const isRender = render && !this.view.isExpanded(startNode);
if (!startNode.children) {
startNode.children = await this.loadInitedChildren(startNode);
}
for (const child of startNode.children) {
const childFoundNode = await revealRecursive(path, {
startNode: child,
goto: false,
render: isRender ? false : render,
});
foundNode = childFoundNode;
if (foundNode) {
await this.view.expand(startNode, {
compact,
uncompact: false,
render: false,
});
break;
}
}
if (foundNode) {
if (isRender) {
const renderNotifier = await renderer.renderNotifier({
node: startNode,
});
if (renderNotifier) {
notifiers.push(renderNotifier);
}
}
if (goto) {
notifiers.push(await this.locator.gotoNodeNotifier(foundNode));
notifiers.push(
Notifier.create(() => this.nvim.command('redraw!', true)),
);
}
}
return foundNode;
}
return;
};
const foundNode = await revealRecursive(path, {
startNode,
goto,
render,
});
return [foundNode, notifiers];
}
sortFiles(files: FileNode[]) {
return files.sort((a, b) => {
if (a.directory && !b.directory) {
return -1;
} else if (b.directory && !a.directory) {
return 1;
} else {
return a.name.localeCompare(b.name);
}
});
}
async loadChildren(parentNode: FileNode): Promise<FileNode[]> {
let filenames: string[];
if (isWindows && parentNode.fullpath === '') {
filenames = await listDrive();
} else {
filenames = await fsReaddir(parentNode.fullpath);
}
const files = await Promise.all(
filenames.map(async (filename) => {
try {
if (
this.showOnlyGitChange &&
!this.isGitChange(parentNode, filename)
) {
return;
}
const hidden = this.isHidden(filename);
if (!this.showHidden && hidden) {
return;
}
const fullpath = normalizePath(
pathLib.join(parentNode.fullpath, filename),
);
const stat = await fsStat(fullpath).catch(() => {});
const lstat = await fsLstat(fullpath).catch(() => {});
const executable = await fsAccess(fullpath, fs.constants.X_OK);
const writable = await fsAccess(fullpath, fs.constants.W_OK);
const readable = await fsAccess(fullpath, fs.constants.R_OK);
const directory =
isWindows && /^[A-Za-z]:[\\\/]$/.test(fullpath)
? true
: stat
? stat.isDirectory()
: false;
const child: FileNode = {
type: 'child',
uid: this.helper.getUid(fullpath),
expandable: directory,
name: filename,
fullpath,
directory: directory,
readonly: !writable && readable,
executable,
readable,
writable,
hidden,
symbolicLink: lstat ? lstat.isSymbolicLink() : false,
lstat: lstat || undefined,
};
return child;
} catch (error) {
logger.error(error);
return;
}
}),
);
return this.sortFiles(files.filter((r): r is FileNode => !!r));
}
}
sourceManager.registerSource('file', FileSource); | the_stack |
import { createElement, remove } from '@syncfusion/ej2-base';
import { CircularGauge, ILoadedEventArgs } from '../../../src/index';
import { IPrintEventArgs } from '../../../src/circular-gauge/model/interface';
import { PdfPageOrientation } from '@syncfusion/ej2-pdf-export';
import { beforePrint } from '../../../src/circular-gauge/model/constants';
import { Legend, Annotations } from '../../../src/circular-gauge/index';
import {profile , inMB, getMemoryProfile} from '../../common.spec';
import { Print} from '../../../src/circular-gauge/model/print';
import {ImageExport } from '../../../src/circular-gauge/model/image-export';
import {PdfExport } from '../../../src/circular-gauge/model/pdf-export';
CircularGauge.Inject(Print, ImageExport, PdfExport);
export function getElementByID(id: string): Element {
return document.getElementById(id);
}
describe('Circulargauge axis testing', () => {
beforeAll(() => {
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)
return;
}
});
describe('Circulargauge axis testing with print and export', () => {
let circulargaugeObj: CircularGauge;
let mapElements: Element;
let tempElement: Element;
mapElements = createElement('div', { id: 'container' });
tempElement = createElement('div', { id: 'tempElement' });
(<any>window).open = () => {
return {
document: { write: () => { }, close: () => { } },
close: () => { }, print: () => { }, focus: () => { }, moveTo: () => { }, resizeTo: () => { }
};
};
beforeAll(() => {
document.body.appendChild(mapElements);
document.body.appendChild(tempElement);
circulargaugeObj = new CircularGauge({
allowImageExport:true,
allowPrint:true,
allowPdfExport:true,
width: "300px",
height: "300px",
axes: [{ }],
loaded: (args: Object): void => {
circulargaugeObj.print();
}
});
circulargaugeObj.appendTo('#container');
});
afterAll((): void => {
remove(mapElements);
circulargaugeObj.destroy();
});
it(' checking a print', (done: Function) => {
circulargaugeObj.beforePrint = (args: IPrintEventArgs): void => {
expect(args.htmlContent.outerHTML.indexOf('<div><div id="container" class="e-lib e-control e-circulargauge"') > -1).toBe(true);
done();
};
circulargaugeObj.print();
});
it('Checking argument cancel', (done: Function) => {
circulargaugeObj.beforePrint = (args: IPrintEventArgs): void => {
args.cancel = true;
expect(args.htmlContent.outerHTML.indexOf('<div><div id="container" class="e-lib e-control e-circulargauge"') > -1).toBe(true);
done();
};
circulargaugeObj.print();
circulargaugeObj.refresh();
});
it('Checking to print in multiple element', (done: Function) => {
circulargaugeObj.loaded = (args: Object): void => {
circulargaugeObj.print(['container', 'tempElement']);
};
circulargaugeObj.beforePrint = (args: IPrintEventArgs): void => {
expect(args.htmlContent.outerHTML.indexOf('tempElement') > -1).toBe(true);
done();
};
circulargaugeObj.print(['container', 'tempElement']);
});
it('Checking to print direct element', (done: Function) => {
circulargaugeObj.loaded = (args: Object): void => {
circulargaugeObj.print(document.getElementById('container'));
};
circulargaugeObj.beforePrint = (args: IPrintEventArgs): void => {
expect(args.htmlContent.outerHTML.indexOf('<div><div id="container" class="e-lib e-control e-circulargauge"') > -1).toBe(true);
done();
};
circulargaugeObj.refresh();
});
it('Checking to print single element', (done: Function) => {
circulargaugeObj.loaded = (args: Object): void => {
circulargaugeObj.print('tempElement');
};
circulargaugeObj.beforePrint = (args: IPrintEventArgs): void => {
expect(args.htmlContent.outerHTML.indexOf('<div id="tempElement"') > -1).toBe(true);
done();
};
circulargaugeObj.refresh();
});
it('Checking export', (done: Function) => {
circulargaugeObj.export('JPEG', 'map', 1, true);
setTimeout(() => {
expect('').toBe("");
done();
}, 500);
circulargaugeObj.refresh();
});
it('Checking export - SVG', (done: Function) => {
circulargaugeObj.export('SVG', 'map');
setTimeout(() => {
expect('').toBe("");
done();
}, 500);
});
it('Checking export - PDF', (done: Function) => {
circulargaugeObj.export('PDF', 'map');
setTimeout(() => {
expect('').toBe("");
done();
}, 500);
});
it('Checking export - PDF - Potrait', (done: Function) => {
circulargaugeObj.export('PDF', 'map', PdfPageOrientation.Portrait, true);
setTimeout(() => {
expect('').toBe("");
done();
}, 500);
});
});
describe('Testing the print and export with considering orientation and download option', () => {
let circulargaugeObj: CircularGauge;
let mapElements: Element;
let temp: Element;
mapElements = createElement('div', { id: 'container' });
temp = createElement('div', { id: 'tempElement' });
(<any>window).open = () => {
return {
document: { write: () => { }, close: () => { } },
close: () => { }, print: () => { }, focus: () => { }, moveTo: () => { }, resizeTo: () => { }
};
};
beforeAll(() => {
document.body.appendChild(mapElements);
document.body.appendChild(temp);
circulargaugeObj = new CircularGauge({
allowImageExport:true,
allowPdfExport:true,
allowPrint:true,
width: "300px",
height: "300px",
axes: [{
radius: '80%',
startAngle: 230,
endAngle: 130,
majorTicks: {
width: 0
},
lineStyle: { width: 8, color: '#E0E0E0' },
minorTicks: {
width: 0
},
labelStyle: {
font: {
color: '#424242',
fontFamily: 'Roboto',
size: '12px',
fontWeight: 'Regular'
},
offset: -5
},
pointers: [{
animation: { enable: false },
value: 60,
radius: '75%',
color: '#F8C7FD',
pointerWidth: 7,
needleStartWidth:6,
needleEndWidth:10,
cap:
{
radius:8
},
needleTail: {
length: '25%',
}
}]
}],
loaded: (args: Object): void => {
circulargaugeObj.print();
}
});
circulargaugeObj.appendTo('#container');
});
afterAll((): void => {
circulargaugeObj.destroy();
remove(mapElements);
});
it('Checking to print in multiple element', (done: Function) => {
circulargaugeObj.loaded = (args: Object): void => {
circulargaugeObj.print(['container', 'tempElement']);
};
circulargaugeObj.beforePrint = (args: IPrintEventArgs): void => {
expect(args.htmlContent.outerHTML.indexOf('tempElement') > -1).toBe(true);
done();
};
circulargaugeObj.print(['container', 'tempElement']);
circulargaugeObj.refresh();
});
it('Checking export', (done: Function) => {
circulargaugeObj.export('JPEG', 'map',1, false);
setTimeout(() => {
expect('').toBe("");
done();
}, 500);
circulargaugeObj.refresh();
});
it('Checking export - SVG', (done: Function) => {
circulargaugeObj.export('SVG', 'map', 1, false);
setTimeout(() => {
expect('').toBe("");
done();
}, 500);
circulargaugeObj.refresh();
});
it('Checking export - PDF', (done: Function) => {
circulargaugeObj.export('PNG', 'map',1, false);
setTimeout(() => {
expect('').toBe("");
done();
}, 500);
circulargaugeObj.refresh();
});
it('Checking export - PDF - Potrait', (done: Function) => {
circulargaugeObj.export('PDF', 'map', PdfPageOrientation.Portrait,true);
setTimeout(() => {
expect('').toBe("");
done();
}, 500);
circulargaugeObj.refresh();
});
it('Checking export - PDF - Potrait', (done: Function) => {
circulargaugeObj.export('PDF', 'map', PdfPageOrientation.Portrait,false);
let element: Element =document.getElementById("container_CircularGaugeBorder");
setTimeout(() => {
expect(element.getAttribute("height")).toBe("300");
done();
}, 500);
circulargaugeObj.refresh();
});
it('Checking the height property after export', (done: Function) => {
circulargaugeObj.export('PDF', 'map', PdfPageOrientation.Portrait,true);
let element: Element =document.getElementById("container_CircularGaugeBorder");
setTimeout(() => {
expect(element.getAttribute("height")).toBe("300");
done();
}, 500);
circulargaugeObj.refresh();
});
it('Checking the width property after export', (done: Function) => {
circulargaugeObj.export('PDF', 'map', PdfPageOrientation.Portrait,true);
let element: Element =document.getElementById("container_CircularGaugeBorder");
setTimeout(() => {
expect(element.getAttribute("width")).toBe("300");
done();
circulargaugeObj.refresh();
}, 500);
});
it('Checking the opacity after export', (done: Function) => {
circulargaugeObj.export('PDF', 'map', PdfPageOrientation.Portrait,true);
let element: Element =document.getElementById("container_CircularGaugeBorder");
setTimeout(() => {
expect(element.getAttribute("opacity")).toBe("null");
done();
circulargaugeObj.refresh();
}, 500);
});
it('Checking the Fill Property after export', (done: Function) => {
circulargaugeObj.export('PDF', 'map', PdfPageOrientation.Portrait,true);
let element: Element =document.getElementById("container_CircularGaugeBorder");
setTimeout(() => {
expect(element.getAttribute("fill")).toBe("#FFFFFF");
done();
}, 500);
circulargaugeObj.refresh();
});
it('Checking to print single element', (done: Function) => {
circulargaugeObj.loaded = (args: Object): void => {
circulargaugeObj.print('tempElement');
};
circulargaugeObj.beforePrint = (args: IPrintEventArgs): void => {
expect(args.htmlContent.outerHTML.indexOf('<div id="tempElement"') > -1).toBe(true);
done();
};
circulargaugeObj.print('tempElement');
circulargaugeObj.refresh();
});
});
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);
});
}); | the_stack |
import type { IMethod, IType, KeyedCollection, IApiModel } from './sdkModels'
import { EnumType, ArrayType } from './sdkModels'
interface ITypeDelta {
lhs: string
rhs: string
}
enum DiffCompare {
RightMissing = -1,
Equal = 0,
LeftMissing = 1,
}
export interface DiffCount {
changed: number
added: number
removed: number
}
export type TypeDelta = KeyedCollection<ITypeDelta>
export type DiffTracker = (lKey: string, rKey: string) => number
export const startCount = (): DiffCount => {
return { changed: 0, added: 0, removed: 0 }
}
const diffCompare = (lKey: string, rKey: string) => {
if (lKey && rKey) return lKey.localeCompare(rKey)
if (lKey) return DiffCompare.RightMissing
return DiffCompare.LeftMissing
}
export const countDiffs = (
count: DiffCount,
lKeys: string[],
rKeys: string[],
comparer: DiffTracker = diffCompare
) => {
lKeys = lKeys.sort((a, b) => a.localeCompare(b))
rKeys = rKeys.sort((a, b) => a.localeCompare(b))
let l = 0
let r = 0
while (l < lKeys.length || r < rKeys.length) {
const lk = lKeys[l]
const rk = rKeys[r]
const comp = comparer(lk, rk)
switch (comp) {
case DiffCompare.LeftMissing: {
count.added++
r++
break
}
case DiffCompare.RightMissing: {
count.removed++
l++
break
}
default: {
l++
r++
}
}
}
return count
}
export const compareEnumTypes = (
lType: IType,
rType: IType,
count: DiffCount
) => {
const lNum = lType as EnumType
const rNum = rType as EnumType
const lKeys = lNum.values.map((v) => v.toString())
const rKeys = rNum.values.map((v) => v.toString())
countDiffs(count, lKeys, rKeys)
const lVal = JSON.stringify(lKeys)
const rVal = JSON.stringify(rKeys)
if (lVal === rVal) return
return {
lhs: lVal,
rhs: rVal,
}
}
/**
* Compares two types and returns an object of non-matching entries
* @param lType
* @param rType
* @param count change tracking
*/
export const compareTypes = (lType: IType, rType: IType, count: DiffCount) => {
if (lType instanceof EnumType) {
return compareEnumTypes(lType, rType, count)
}
if (lType instanceof ArrayType) {
lType = lType.elementType
}
if (rType instanceof ArrayType) {
rType = rType.elementType
}
if (lType.asHashString() === rType.asHashString()) return
const diff: TypeDelta = {}
countDiffs(
count,
Object.keys(lType.properties),
Object.keys(rType.properties),
(lKey, rKey) => {
const comp = diffCompare(lKey, rKey)
switch (comp) {
case DiffCompare.LeftMissing: {
diff[rKey] = {
lhs: '',
rhs: rType.properties[rKey].summary(),
}
break
}
case DiffCompare.RightMissing: {
diff[lKey] = {
lhs: lType.properties[lKey].summary(),
rhs: '',
}
break
}
default: {
const lhsVal = lType.properties[lKey]
const rhsVal = rType.properties[rKey]
const lhs = lhsVal.summary()
const rhs = rhsVal.summary()
if (lhs !== rhs) {
count.changed++
diff[lKey] = {
lhs,
rhs,
}
}
}
}
return comp
}
)
if (Object.keys(diff).length === 0) return
return diff
}
/**
* Compares the params of two methods and returns the signature of both methods
* if non matching.
* @param lMethod
* @param rMethod
* @param count change tracking
*/
export const compareParams = (
lMethod: IMethod,
rMethod: IMethod,
count: DiffCount
) => {
const lParams = {}
const rParams = {}
lMethod.allParams.forEach((p) => (lParams[p.name] = p))
rMethod.allParams.forEach((p) => (rParams[p.name] = p))
// TODO typediff the matching body types?
countDiffs(
count,
Object.keys(lParams),
Object.keys(rParams),
(lKey, rKey) => {
const comp = diffCompare(lKey, rKey)
if (comp === 0) {
const lsh = lParams[lKey].signature()
const rsh = rParams[rKey].signature()
if (lsh !== rsh) {
count.changed++
}
}
return comp
}
)
const lSignature = lMethod.signature()
const rSignature = rMethod.signature()
if (lSignature === rSignature) return
return {
lhs: lSignature,
rhs: rSignature,
}
}
/**
* Compares the bodies of two methods and returns diffs if there are any
* @param lMethod
* @param rMethod
* @param count change tracking
*/
export const compareBodies = (
lMethod: IMethod,
rMethod: IMethod,
count: DiffCount
) => {
const lParams = {}
const rParams = {}
lMethod.bodyParams.forEach((p) => (lParams[p.name] = p))
rMethod.bodyParams.forEach((p) => (rParams[p.name] = p))
// TODO typediff the matching body types?
countDiffs(count, Object.keys(lParams), Object.keys(rParams))
const lSide = lMethod.bodyParams.map((p) => {
return {
name: p.name,
type: p.type.fullName,
required: p.required,
}
})
const rSide = rMethod.bodyParams.map((p) => {
return {
name: p.name,
type: p.type.fullName,
required: p.required,
}
})
if (JSON.stringify(lSide) === JSON.stringify(rSide)) return
count.changed++
return {
lhs: lSide,
rhs: rSide,
}
}
/**
* Compare two response lists, returning diff
* @param lMethod
* @param rMethod
* @param count change tracking
*/
export const compareResponses = (
lMethod: IMethod,
rMethod: IMethod,
count: DiffCount
) => {
// TODO deep type comparison? Probably diff all types instead
const lSide = lMethod.responses.map((r) => {
return {
statusCode: r.statusCode,
mediaType: r.mediaType,
type: r.type.fullName,
}
})
const rSide = rMethod.responses.map((r) => {
return {
statusCode: r.statusCode,
mediaType: r.mediaType,
type: r.type.fullName,
}
})
if (JSON.stringify(lSide) === JSON.stringify(rSide)) return
count.changed++
return {
lhs: lSide,
rhs: rSide,
}
}
export const csvHeaderRow =
'method name,"Op + URI",left status,right status,typeDiff,paramDiff,bodyDiff,responseDiff,diffCount'
export const csvDiffRow = (diff: DiffRow) => `
${diff.name},${diff.id},${diff.lStatus},${diff.rStatus},${diff.typeDiff},${
diff.paramsDiff
},${diff.bodyDiff},${diff.responseDiff},${JSON.stringify(diff.diffCount)}`
export const mdHeaderRow = `
| method name | Op + URI | 3.1 | 4.0 | typeDiff | paramDiff | bodyDiff | responseDiff | diffCount |
| ------------ | -------- | --- | --- | ------------ | --------- | -------- | ------------ | --------- |`
export const mdDiffRow = (diff: DiffRow) => `
| ${diff.name} | ${diff.id} | ${diff.lStatus} | ${diff.rStatus} | ${
diff.typeDiff
} | ${diff.paramsDiff} | ${diff.bodyDiff} | ${
diff.responseDiff
} | ${JSON.stringify(diff.diffCount)} |`
const diffToString = (diff: any) => {
if (!diff) return ''
const result = JSON.stringify(diff, null, 2)
if (result === '{}') return ''
return `"${result.replace(/"/g, "'")}"`
}
export interface ComputeDiffInputs {
lMethod?: IMethod
rMethod?: IMethod
}
export interface DiffRow {
/** Method name */
name: string
/** Method operation and path */
id: string
/** Method status in both specs */
lStatus: string
rStatus: string
/** Method type diff if any */
typeDiff: string
/** Method params diff if any */
paramsDiff: string
/** Body diff if any */
bodyDiff: string
/** Response diff if any */
responseDiff: string
/** Count of differences */
diffCount: DiffCount
}
/**
* Computes the diff of two methods
* @param lMethod
* @param rMethod
*/
const computeDiff = (lMethod?: IMethod, rMethod?: IMethod) => {
if (!lMethod && !rMethod) throw new Error('At least one method is required.')
const count = startCount()
const countStatus = () => {
if (!rMethod) {
count.removed++
} else if (!lMethod) {
count.added++
} else {
if (lMethod.status !== rMethod.status) count.changed++
}
}
let result: DiffRow
countStatus()
if (lMethod) {
const typeDiff = rMethod
? diffToString(compareTypes(lMethod.type, rMethod.type, count))
: ''
const paramsDiff = rMethod
? diffToString(compareParams(lMethod, rMethod, count))
: ''
const bodyDiff = rMethod
? diffToString(compareBodies(lMethod, rMethod, count))
: ''
const responseDiff = rMethod
? diffToString(compareResponses(lMethod, rMethod, count))
: ''
result = {
name: lMethod.name,
id: lMethod.id,
lStatus: lMethod.status,
rStatus: rMethod ? rMethod.status : '',
typeDiff,
paramsDiff,
bodyDiff,
responseDiff,
diffCount: count,
}
} else if (!lMethod && rMethod) {
result = {
name: rMethod.name,
id: rMethod.id,
lStatus: '',
rStatus: rMethod.status,
typeDiff: '',
paramsDiff: '',
bodyDiff: '',
responseDiff: '',
diffCount: count,
}
}
return result!
}
export type DiffFilter = (
delta: DiffRow,
lMethod?: IMethod,
rMethod?: IMethod
) => boolean
/**
* Include when:
* - lMethod is missing
* - rMethod is missing
* - params differ
* - types differ
* @param delta
* @param lMethod
* @param rMethod
*/
export const includeDiffs: DiffFilter = (delta, lMethod, rMethod) =>
!lMethod ||
!rMethod! ||
delta.lStatus !== delta.rStatus ||
!!delta.paramsDiff ||
!!delta.typeDiff ||
!!delta.bodyDiff ||
!!delta.responseDiff
/**
* Compares two specs and returns a diff object
* @param lSpec left-side spec
* @param rSpec right-side spec
* @param include evaluates to true if the comparison should be included
*/
export const compareSpecs = (
lSpec: IApiModel,
rSpec: IApiModel,
include: DiffFilter = includeDiffs
) => {
const specSort = (a: IMethod, b: IMethod) => a.id.localeCompare(b.id)
const lMethods = Object.values(lSpec.methods).sort(specSort)
const rMethods = Object.values(rSpec.methods).sort(specSort)
const lLength = lMethods.length
const rLength = rMethods.length
let lIndex = 0
let rIndex = 0
const diff: DiffRow[] = []
while (lIndex < lLength || rIndex < rLength) {
let lMethod: IMethod | undefined = lMethods[lIndex]
let rMethod: IMethod | undefined = rMethods[rIndex]
if (!lMethod) {
rIndex++
} else if (!rMethod) {
lIndex++
} else if (lMethod.id < rMethod.id) {
rMethod = undefined
lIndex++
} else if (rMethod.id < lMethod.id) {
lMethod = undefined
rIndex++
} else {
lIndex++
rIndex++
}
const delta = computeDiff(lMethod, rMethod)
if (include(delta, lMethod, rMethod)) {
diff.push(delta)
}
}
return diff
} | the_stack |
import path, { resolve } from "path";
import fs from "fs-extra";
import chalk from "chalk";
import { BuilderContext, createBuilder } from "@angular-devkit/architect";
import { JsonObject } from "@angular-devkit/core";
import { DevServerBuildOutput, runWebpack, runWebpackDevServer } from "@angular-devkit/build-webpack";
import { forkJoin, from, Observable, of } from "rxjs";
import { concatMap, map, switchMap } from "rxjs/operators";
import {
getSourceRoot,
loadEnvironmentVariables,
OUT_FILENAME,
WebpackBuildEvent,
writePackageJson,
} from "@apployees-nx/common-build-utils";
import { IBuildWebserverBuilderOptions } from "../../utils/common/webserver-types";
import { normalizeBuildOptions } from "../../utils/common/normalize";
import { getServerConfig } from "../../utils/server/server-config";
import { getClientConfig } from "../../utils/client/client-config";
import { checkBrowsers } from "react-dev-utils/browsersHelper";
import FileSizeReporter from "react-dev-utils/FileSizeReporter";
import { choosePort, createCompiler, prepareUrls, printInstructions } from "../../utils/client/WebpackDevServerUtils";
import errorOverlayMiddleware from "react-dev-utils/errorOverlayMiddleware";
import evalSourceMapMiddleware from "react-dev-utils/evalSourceMapMiddleware";
import _ from "lodash";
import webpack, { Configuration } from "webpack";
import escape from "escape-string-regexp";
import WebpackDevServer from "webpack-dev-server";
import noopServiceWorkerMiddleware from "react-dev-utils/noopServiceWorkerMiddleware";
(process as NodeJS.EventEmitter).on("uncaughtException", async (thrown: any) => {
console.error("Uncaught error:", thrown);
process.exit(1);
});
const measureFileSizesBeforeBuild = FileSizeReporter.measureFileSizesBeforeBuild;
const printFileSizesAfterBuild = FileSizeReporter.printFileSizesAfterBuild;
// These sizes are pretty large. We'll warn for bundles exceeding them.
const WARN_AFTER_BUNDLE_GZIP_SIZE = 512 * 1024;
const WARN_AFTER_CHUNK_GZIP_SIZE = 1024 * 1024;
const isInteractive = process.stdout.isTTY;
try {
require("dotenv").config();
} catch (e) {
console.error("Error while loading dotenv config.");
console.error(e);
}
export default createBuilder<JsonObject & IBuildWebserverBuilderOptions>(run);
interface IWebpackDevServerReference {
server: WebpackDevServer & { sockWrite: Function; sockets: any };
}
function run(
options: JsonObject & IBuildWebserverBuilderOptions,
context: BuilderContext,
): Observable<WebpackBuildEvent> {
const nodeEnv: string = options.dev ? "development" : "production";
// do this otherwise our bootstrapped @apployees-nx/node actually replaces this
// to "development" or "production" at build time.
const nodeEnvKey = "NODE_ENV";
const babelEnvKey = "BABEL_ENV";
process.env[nodeEnvKey] = nodeEnv;
process.env[babelEnvKey] = nodeEnv;
const devServer: IWebpackDevServerReference = { server: null };
const devSocket = {
warnings: (warnings) => {
devServer.server.sockWrite(devServer.server.sockets, "warnings", warnings);
},
errors: (errors) => {
devServer.server.sockWrite(devServer.server.sockets, "errors", errors);
},
};
let yarnExists;
let devClientFirstTimeComplete = false,
devServerFirstTimeComplete = false;
return from(getSourceRoot(context)).pipe(
map((sourceRoot) => normalizeBuildOptions(options, context, sourceRoot)),
switchMap((options: IBuildWebserverBuilderOptions) =>
checkBrowsers(path.resolve(options.root, options.sourceRoot), isInteractive).then(() => options),
),
switchMap((options: IBuildWebserverBuilderOptions) => {
yarnExists = fs.existsSync(path.resolve(options.root, "yarn.lock"));
loadEnvironmentVariables(options, context);
if (options.dev) {
return choosePort(options.devHost, options.devAppPort).then((appPort) => {
if (_.isNil(appPort)) {
throw new Error("Could not start because we could not find a port for app server.");
}
options.devAppPort = appPort;
process.env.PORT = appPort;
return choosePort(options.devHost, options.devWebpackPort).then((webpackPort) => {
if (_.isNil(webpackPort)) {
throw new Error("Could not start because we could not find a port for the webpack server.");
}
options.devWebpackPort = webpackPort;
process.env.DEV_PORT = webpackPort;
const protocol = options.devHttps ? "https" : "http";
options.assetsUrl = `${protocol}://${options.devHost}:${webpackPort}/`;
// eslint-disable-next-line @typescript-eslint/camelcase
options.devUrls_calculated = prepareUrls(protocol, options.devHost, appPort);
return options;
});
});
} else {
return Promise.resolve(options);
}
}),
switchMap((options: IBuildWebserverBuilderOptions) => {
if (!options.dev) {
return measureFileSizesBeforeBuild(
options.publicOutputFolder_calculated,
).then((previousFileSizesForPublicFolder) => [options, previousFileSizesForPublicFolder]);
} else {
return Promise.resolve([options, null]);
}
}),
map(([options, previousFileSizesForPublicFolder]) => {
// Remove all content but keep the directory so that
// if you're in it, you don't end up in Trash
fs.emptyDirSync(options.outputPath);
return [options, previousFileSizesForPublicFolder];
}),
map(([options, previousFileSizesForPublicFolder]) => {
if (!fs.existsSync(options.appHtml) || !fs.existsSync(options.clientMain) || !fs.existsSync(options.serverMain)) {
throw new Error("One of appHtml, clientMain, or serverMain is not specified.");
}
let serverConfig = getServerConfig(options, context, true);
if (options.serverWebpackConfig) {
serverConfig = __non_webpack_require__(options.serverWebpackConfig)(serverConfig, {
options,
configuration: context.target.configuration,
});
}
let clientConfig = getClientConfig(options, context, false);
if (options.clientWebpackConfig) {
clientConfig = __non_webpack_require__(options.clientWebpackConfig)(clientConfig, {
options,
configuration: context.target.configuration,
});
}
// remove the output directory before we go further
return [options, serverConfig, clientConfig, previousFileSizesForPublicFolder];
}),
concatMap(
([options, serverConfig, clientConfig, previousFileSizesForPublicFolder]: [
IBuildWebserverBuilderOptions,
Configuration,
Configuration,
object,
]) => {
if (options.dev) {
/**
* Run the webpack for server and webpack dev server for client.
*/
return forkJoin(
runWebpack(serverConfig, context, {
logging: (stats) => {
context.logger.info(stats.toString(serverConfig.stats));
devServerFirstTimeComplete = true;
if (devClientFirstTimeComplete && devServerFirstTimeComplete) {
printInstructions(context.target.project, options.devUrls_calculated, yarnExists);
}
},
webpackFactory: (config: Configuration) =>
of(
createCompiler({
webpack: webpack,
config: serverConfig,
appName: context.target.project + " - Server",
useYarn: yarnExists,
tscCompileOnError: true,
useTypeScript: true,
devSocket: devSocket,
urls: options.devUrls_calculated,
}),
),
}),
runWebpackDevServer(clientConfig, context, {
logging: (stats) => {
context.logger.info(stats.toString(clientConfig.stats));
devClientFirstTimeComplete = true;
if (devClientFirstTimeComplete && devServerFirstTimeComplete) {
printInstructions(context.target.project, options.devUrls_calculated, yarnExists);
}
},
devServerConfig: createWebpackServerOptions(options, context, devServer),
webpackFactory: (config: webpack.Configuration) =>
of(
createCompiler({
webpack: webpack,
config: clientConfig,
appName: context.target.project + " - Client",
useYarn: yarnExists,
tscCompileOnError: true,
useTypeScript: true,
devSocket: devSocket,
urls: options.devUrls_calculated,
}) as webpack.Compiler,
),
}).pipe(
map((output) => {
output.baseUrl = options.devUrls_calculated.localUrlForBrowser;
return output;
}),
),
of(options),
);
} else {
/**
* Run the webpack for server and webpack for client.
*/
return forkJoin(
runWebpack(serverConfig, context, {
logging: (stats) => {
context.logger.info(stats.toString(serverConfig.stats));
},
}),
runWebpack(clientConfig, context, {
logging: (stats) => {
context.logger.info(stats.toString(clientConfig.stats));
console.log(previousFileSizesForPublicFolder);
context.logger.info("\n\nFile sizes of files in /public after gzip:\n");
printFileSizesAfterBuild(
stats,
previousFileSizesForPublicFolder,
options.publicOutputFolder_calculated,
WARN_AFTER_BUNDLE_GZIP_SIZE,
WARN_AFTER_CHUNK_GZIP_SIZE,
);
},
}),
of(options),
);
}
},
),
map(
([serverBuildEvent, clientBuildEventOrDevServerBuildOutput, options]: [
WebpackBuildEvent,
WebpackBuildEvent | DevServerBuildOutput,
IBuildWebserverBuilderOptions,
]) => {
if (!options.dev) {
serverBuildEvent.success = serverBuildEvent.success && clientBuildEventOrDevServerBuildOutput.success;
serverBuildEvent.error = serverBuildEvent.error && clientBuildEventOrDevServerBuildOutput.error;
serverBuildEvent.outfile = resolve(context.workspaceRoot, options.outputPath, OUT_FILENAME);
return [serverBuildEvent as WebpackBuildEvent, options];
} else {
return [clientBuildEventOrDevServerBuildOutput as DevServerBuildOutput, options];
}
},
),
map(
([clientBuildEventOrDevServerBuildOutput, options]: [
WebpackBuildEvent & DevServerBuildOutput,
IBuildWebserverBuilderOptions,
]) => {
// we only consider server external dependencies and libraries because it is the server
// code that is run by node, not the browser code.
if (!options.dev) {
writePackageJson(options, context, options.serverExternalDependencies, options.serverExternalLibraries);
printHostingInstructions(options);
return clientBuildEventOrDevServerBuildOutput;
} else {
printInstructions(context.target.project, options.devUrls_calculated, yarnExists);
return clientBuildEventOrDevServerBuildOutput;
}
},
),
);
}
function printHostingInstructions(options: IBuildWebserverBuilderOptions) {
const assetsPath = options.assetsUrl;
// eslint-disable-next-line @typescript-eslint/camelcase
const publicOutputFolder_calculated = options.publicOutputFolder_calculated;
const buildFolder = options.outputPath;
console.log(
`\n\n\n\nThe project was built assuming all static assets are served from the path '${chalk.green(assetsPath)}'.`,
);
console.log();
if (assetsPath.startsWith("/")) {
console.log(
`All of your static assets will be served from the rendering server (specifically from ${chalk.green(
publicOutputFolder_calculated,
)}).`,
);
console.log("\nWe recommend serving static assets from a CDN in production.");
console.log(
`\nYou can control this with the ${chalk.cyan(
"ASSETS_URL",
)} environment variable and set its value to the CDN URL for your next build.`,
);
console.log();
}
console.log(`The ${chalk.cyan(buildFolder)} folder is ready to be deployed.`);
console.log();
console.log("You may run the app with node:");
console.log();
console.log(` ${chalk.cyan("node")} ${buildFolder}`);
console.log();
}
function createWebpackServerOptions(
options: IBuildWebserverBuilderOptions,
context: BuilderContext,
serverReference: IWebpackDevServerReference,
) {
const config: WebpackDevServer.Configuration & { logLevel?: string } = {
// this needs to remain disabled because our webpackdevserver runs on a
// different port than the server app.
disableHostCheck: true,
// Enable gzip compression of generated files.
compress: true,
// Enable hot reloading server. It will provide /sockjs-node/ endpoint
// for the WebpackDevServer client so it can learn when the files were
// updated. The WebpackDevServer client is included as an entry point
// in the Webpack development configuration. Note that only changes
// to CSS are currently hot reloaded. JS changes will refresh the browser.
hot: true,
// It is important to tell WebpackDevServer to use the same "root" path
// as we specified in the config. In development, we always serve from /.
publicPath: process.env.ASSETS_URL || options.assetsUrl,
// WebpackDevServer is noisy by default so we emit custom message instead
// by listening to the compiler events with `compiler.hooks[...].tap` calls above.
quiet: true,
// Silence WebpackDevServer's own logs since they're generally not useful.
// It will still show compile warnings and errors with this setting.
logLevel: "warn",
// Reportedly, this avoids CPU overload on some systems.
// https://github.com/facebook/create-react-app/issues/293
// src/node_modules is not ignored to support absolute imports
// https://github.com/facebook/create-react-app/issues/1065
watchOptions: {
ignored: ignoredFiles(path.resolve(options.root, options.sourceRoot)),
},
host: options.devHost,
port: options.devWebpackPort,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
"Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization",
},
overlay: false,
historyApiFallback: {
// Paths with dots should still use the history fallback.
// See https://github.com/facebook/create-react-app/issues/387.
disableDotRule: true,
},
public: options.devUrls_calculated.lanUrlForConfig,
https: options.devHttps,
before(app, server) {
serverReference.server = server as any;
// This lets us fetch source contents from webpack for the error overlay
app.use(evalSourceMapMiddleware(server));
// This lets us open files from the runtime error overlay.
app.use(errorOverlayMiddleware());
// This service worker file is effectively a 'no-op' that will reset any
// previous service worker registered for the same host:port combination.
// We do this in development to avoid hitting the production cache if
// it used the same host and port.
// https://github.com/facebook/create-react-app/issues/2272#issuecomment-302832432
app.use(noopServiceWorkerMiddleware());
},
};
return config;
}
function ignoredFiles(appSrc) {
return new RegExp(`^(?!${escape(path.normalize(appSrc + "/").replace(/[\\]+/g, "/"))}).+/node_modules/`, "g");
}
// eslint-disable-next-line @typescript-eslint/camelcase
declare function __non_webpack_require__(string): any; | the_stack |
import * as vscode from 'vscode';
import { PipelineExplorer, pipelineExplorer } from './pipeline/pipelineExplorer';
import { Pipeline } from './tekton/pipeline';
import { PipelineRun } from './tekton/pipelinerun';
import { Task } from './tekton/task';
import { TaskRun } from './tekton/taskrun';
import { Platform } from './util/platform';
import path = require('path');
import fsx = require('fs-extra');
import * as k8s from 'vscode-kubernetes-tools-api';
import { ClusterTask } from './tekton/clustertask';
import { PipelineResource } from './tekton/pipelineresource';
import { registerYamlSchemaSupport } from './yaml-support/tkn-yaml-schema';
import { setCommandContext, CommandContext, enterZenMode, exitZenMode, refreshCustomTree, removeItemFromCustomTree } from './commands';
import { customTektonExplorer } from './pipeline/customTektonExplorer';
import { TektonItem } from './tekton/tektonitem';
import { showPipelinePreview, registerPipelinePreviewContext } from './pipeline/pipeline-preview';
import { k8sCommands } from './kubernetes';
import { initializeTknEditing } from './yaml-support/tkn-editing';
import { ToolsConfig } from './tools';
import { TKN_RESOURCE_SCHEME, TKN_RESOURCE_SCHEME_READONLY, tektonVfsProvider } from './util/tekton-vfs';
import { updateTektonResource } from './tekton/deploy';
import { deleteFromExplorer, deleteFromCustom } from './commands/delete';
import { addTrigger } from './tekton/trigger';
import { triggerDetection } from './util/detection';
import { showDiagnosticData } from './tekton/diagnostic';
import { TriggerTemplate } from './tekton/triggertemplate';
import { TektonHubTasksViewProvider } from './hub/hub-view';
import { registerLogDocumentProvider } from './util/log-in-editor';
import { openPipelineRunTemplate, openTaskRunTemplate } from './tekton/generate-template';
import sendTelemetry, { startTelemetry, telemetryLogError, TelemetryProperties } from './telemetry';
import { cli, createCliCommand } from './cli';
import { getVersion, tektonVersionType } from './util/tknversion';
import { TektonNode } from './tree-view/tekton-node';
import { checkClusterStatus } from './util/check-cluster-status';
import { getClusterVersions } from './cluster-version';
import { debug } from './debugger/debug';
import { debugExplorer } from './debugger/debugExplorer';
import { showDebugContinue } from './debugger/debug-continue';
import { cancelTaskRun } from './debugger/cancel-taskrun';
import { showDebugFailContinue } from './debugger/debug-fail-continue';
import { openContainerInTerminal } from './debugger/show-in-terminal';
export let contextGlobalState: vscode.ExtensionContext;
let k8sExplorer: k8s.ClusterExplorerV1 | undefined = undefined;
export async function activate(context: vscode.ExtensionContext): Promise<void> {
contextGlobalState = context;
migrateFromTkn018();
startTelemetry(context);
const hubViewProvider = new TektonHubTasksViewProvider(context.extensionUri);
const disposables = [
vscode.commands.registerCommand('tekton.about', () => execute(Pipeline.about, 'tekton.about')),
vscode.commands.registerCommand('tekton.pipeline.preview', () => execute(showPipelinePreview, 'tekton.pipeline.preview')),
vscode.commands.registerCommand('tekton.output', () => execute(Pipeline.showTektonOutput, 'tekton.output')),
vscode.commands.registerCommand('tekton.explorer.refresh', () => execute(Pipeline.refresh, 'tekton.explorer.refresh')),
vscode.commands.registerCommand('k8s.tekton.pipeline.start', (context) => execute(k8sCommands.startPipeline, context, 'k8s.tekton.pipeline.start')),
vscode.commands.registerCommand('k8s.tekton.task.start', (context) => execute(k8sCommands.startTask, context, 'k8s.tekton.task.start')),
vscode.commands.registerCommand('tekton.pipeline.start', (context) => execute(Pipeline.start, context, 'tekton.pipeline.start')),
vscode.commands.registerCommand('tekton.addTrigger', (context) => execute(addTrigger, context, 'tekton.addTrigger')),
vscode.commands.registerCommand('tekton.pipeline.start.palette', (context) => execute(Pipeline.start, context, 'tekton.pipeline.start.palette')),
vscode.commands.registerCommand('tekton.openInEditor', (context) => execute(TektonItem.openInEditor, context, 'tekton.openInEditor')),
vscode.commands.registerCommand('tekton.edit', (context) => execute(TektonItem.openInEditor, context, 'tekton.edit')),
vscode.commands.registerCommand('tekton.pipeline.restart', (context) => execute(Pipeline.restart, context, 'tekton.pipeline.restart')),
vscode.commands.registerCommand('tekton.pipeline.describe', (context) => execute(Pipeline.describe, context)),
vscode.commands.registerCommand('tekton.pipeline.describe.palette', (context) => execute(Pipeline.describe, context)),
vscode.commands.registerCommand('tekton.explorerView.delete', (context) => deleteFromExplorer(context, 'tekton.explorerView.delete')),
vscode.commands.registerCommand('tekton.customView.delete', (context) => deleteFromCustom(context), 'tekton.customView.delete'),
vscode.commands.registerCommand('tekton.pipelineresource.describe', (context) => execute(PipelineResource.describe, context)),
vscode.commands.registerCommand('tekton.pipelineresource.describe.palette', (context) => execute(PipelineResource.describe, context)),
vscode.commands.registerCommand('tekton.pipelinerun.describe', (context) => execute(PipelineRun.describe, context)),
vscode.commands.registerCommand('tekton.pipelinerun.describe.palette', (context) => execute(PipelineRun.describe, context)),
vscode.commands.registerCommand('tekton.pipelinerun.restart', (context) => execute(PipelineRun.restart, context, 'tekton.pipelinerun.restart')),
vscode.commands.registerCommand('tekton.showDiagnosticDataAction', (context) => execute(showDiagnosticData, context, 'tekton.showDiagnosticDataAction')),
vscode.commands.registerCommand('tekton.taskrun.restart', (context) => execute(TaskRun.restartTaskRun, context, 'tekton.taskrun.restart')),
vscode.commands.registerCommand('tekton.pipelinerun.logs', (context) => execute(PipelineRun.logs, context)),
vscode.commands.registerCommand('tekton.pipelinerun.logs.palette', (context) => execute(PipelineRun.logs, context)),
vscode.commands.registerCommand('tekton.pipelinerun.followLogs', (context) => execute(PipelineRun.followLogs, context)),
vscode.commands.registerCommand('tekton.pipelinerun.followLogs.palette', (context) => execute(PipelineRun.followLogs, context)),
vscode.commands.registerCommand('tekton.pipelinerun.cancel', (context) => execute(PipelineRun.cancel, context)),
vscode.commands.registerCommand('tekton.pipelinerun.cancel.palette', (context) => execute(PipelineRun.cancel, context)),
vscode.commands.registerCommand('tekton.triggerTemplate.url', (context) => execute(TriggerTemplate.copyExposeUrl, context, 'tekton.triggerTemplate.url')),
vscode.commands.registerCommand('tekton.task.start', (context) => execute(Task.start, context, 'tekton.task.start')),
vscode.commands.registerCommand('tekton.task.start.palette', (context) => execute(Task.start, context, 'tekton.task.start.palette')),
vscode.commands.registerCommand('tekton.clusterTask.start', (context) => execute(ClusterTask.start, context, 'tekton.clusterTask.start')),
vscode.commands.registerCommand('tekton.taskrun.list', (context) => execute(TaskRun.listFromPipelineRun, context)),
vscode.commands.registerCommand('tekton.taskrun.list.palette', (context) => execute(TaskRun.listFromPipelineRun, context)),
vscode.commands.registerCommand('tekton.taskrun.listFromTask.palette', (context) => execute(TaskRun.listFromTask, context)),
vscode.commands.registerCommand('tekton.taskrun.logs', (context) => execute(TaskRun.logs, context)),
vscode.commands.registerCommand('tekton.taskrun.logs.palette', (context) => execute(TaskRun.logs, context)),
vscode.commands.registerCommand('tekton.taskrun.followLogs', (context) => execute(TaskRun.followLogs, context)),
vscode.commands.registerCommand('tekton.taskrun.followLogs.palette', (context) => execute(TaskRun.followLogs, context)),
vscode.commands.registerCommand('tekton.explorer.reportIssue', () => PipelineExplorer.reportIssue('tekton.explorer.reportIssue')),
vscode.commands.registerCommand('_tekton.explorer.more', expandMoreItem),
vscode.commands.registerCommand('tekton.explorer.enterZenMode', enterZenMode),
vscode.commands.registerCommand('tekton.custom.explorer.exitZenMode', exitZenMode),
vscode.commands.registerCommand('tekton.pipelineRun.template', (context) => execute(openPipelineRunTemplate, context)),
vscode.commands.registerCommand('tekton.custom.explorer.refresh', () => refreshCustomTree('tekton.custom.explorer.refresh')),
vscode.commands.registerCommand('tekton.custom.explorer.removeItem', () => removeItemFromCustomTree('tekton.custom.explorer.removeItem')),
vscode.commands.registerCommand('k8s.tekton.run.logs', k8sCommands.showLogs),
vscode.commands.registerCommand('k8s.tekton.run.followLogs', k8sCommands.followLogs),
vscode.commands.registerCommand('tekton.open.condition', (context) => execute(TaskRun.openConditionDefinition, context, 'tekton.open.condition')),
vscode.commands.registerCommand('tekton.open.task', (context) => execute(TaskRun.openDefinition, context, 'tekton.open.task')),
vscode.commands.registerCommand('tekton.open.task.palette', (context) => execute(TaskRun.openDefinition, context, 'tekton.open.task.palette')),
vscode.commands.registerCommand('tekton.view.pipelinerun.diagram', (context) => execute(PipelineRun.showDiagram, context)),
vscode.commands.registerCommand('tekton.taskrun.template', (context) => execute(openTaskRunTemplate, context, 'tekton.taskrun.template')),
vscode.commands.registerCommand('tekton.taskrun.debug', (context) => execute(debug, context, 'tekton.taskrun.debug')),
vscode.commands.registerCommand('debug.continue', (context) => execute(showDebugContinue, context, 'debug.continue')),
vscode.commands.registerCommand('debug.failContinue', (context) => execute(showDebugFailContinue, context, 'debug.failContinue')),
vscode.commands.registerCommand('debug.exit', (context) => execute(cancelTaskRun, context, 'debug.exit')),
vscode.commands.registerCommand('debug.terminal', (context) => execute(openContainerInTerminal, context, 'debug.terminal')),
hubViewProvider,
vscode.window.registerWebviewViewProvider('tektonHubTasks', hubViewProvider),
pipelineExplorer,
debugExplorer,
registerLogDocumentProvider(),
// Temporarily loaded resource providers
vscode.workspace.registerFileSystemProvider(TKN_RESOURCE_SCHEME, tektonVfsProvider, { isCaseSensitive: true, }),
vscode.workspace.registerFileSystemProvider(TKN_RESOURCE_SCHEME_READONLY, tektonVfsProvider, { isCaseSensitive: true, isReadonly: true }),
];
disposables.forEach((e) => context.subscriptions.push(e));
detectTknCli().then(() => {
triggerDetection();
});
if (ToolsConfig.getTknLocation('kubectl')) {
checkClusterStatus(true); // watch Tekton resources when all required dependency are installed
}
getClusterVersions().then((version) => {
const telemetryProps: TelemetryProperties = {
identifier: 'cluster.version',
};
for (const [key, value] of Object.entries(version)) {
telemetryProps[key] = value;
}
sendTelemetry('tekton.cluster.version', telemetryProps)
})
setCommandContext(CommandContext.TreeZenMode, false);
setCommandContext(CommandContext.PipelinePreview, false);
const k8sExplorerApi = await k8s.extension.clusterExplorer.v1;
if (k8sExplorerApi.available) {
k8sExplorer = k8sExplorerApi.api;
const nodeContributor = k8sExplorer.nodeSources.groupingFolder(
'Tekton Pipelines',
'context',
k8sExplorer.nodeSources.resourceFolder('ClusterTasks', 'ClusterTasks', 'ClusterTask', 'clustertask').if(isTekton),
k8sExplorer.nodeSources.resourceFolder('Tasks', 'Tasks', 'Task', 'task').if(isTekton),
k8sExplorer.nodeSources.resourceFolder('TaskRuns', 'TaskRuns', 'TaskRun', 'taskruns').if(isTekton),
k8sExplorer.nodeSources.resourceFolder('Pipelines', 'Pipelines', 'Pipeline', 'pipelines').if(isTekton),
k8sExplorer.nodeSources.resourceFolder('PipelineRuns', 'PipelineRuns', 'PipelineRun', 'pipelineruns').if(isTekton),
k8sExplorer.nodeSources.resourceFolder('Pipeline Resources', 'PipelineResources', 'PipelineResources', 'pipelineresources').if(isTekton),
k8sExplorer.nodeSources.resourceFolder('TriggerTemplates', 'TriggerTemplates', 'TriggerTemplates', 'triggerTemplates').if(isTekton),
k8sExplorer.nodeSources.resourceFolder('TriggerBinding', 'TriggerBinding', 'TriggerBinding', 'triggerBinding').if(isTekton),
k8sExplorer.nodeSources.resourceFolder('EventListener', 'EventListener', 'EventListener', 'eventListener').if(isTekton),
k8sExplorer.nodeSources.resourceFolder('Conditions', 'Conditions', 'Conditions', 'conditions').if(isTekton),
).at(undefined);
k8sExplorer.registerNodeContributor(nodeContributor);
}
const configurationApi = await k8s.extension.configuration.v1_1;
if (configurationApi.available) {
const confApi = configurationApi.api;
confApi.onDidChangeContext(() => {
if (ToolsConfig.getTknLocation('kubectl')) {
checkClusterStatus(true);
}
pipelineExplorer.refresh();
});
}
vscode.workspace.onDidSaveTextDocument(async (document: vscode.TextDocument) => {
await updateTektonResource(document);
});
registerYamlSchemaSupport(context);
registerPipelinePreviewContext();
initializeTknEditing(context);
}
async function isTekton(): Promise<boolean> {
const kubectl = await k8s.extension.kubectl.v1;
if (kubectl.available) {
const sr = await kubectl.api.invokeCommand('api-versions');
if (!sr || sr.code !== 0) {
return false;
}
return sr.stdout.includes('tekton.dev/'); // Naive check to keep example simple!
}
}
// this method is called when your extension is deactivated
// eslint-disable-next-line @typescript-eslint/no-empty-function
export function deactivate(): void {
}
async function detectTknCli(): Promise<void> {
setCommandContext(CommandContext.TknCli, false);
// start detecting 'tkn' on extension start
const tknPath = await ToolsConfig.detectOrDownload('tkn');
if (tknPath) {
setCommandContext(CommandContext.TknCli, true);
sendVersionToTelemetry('tkn.version', tknPath);
}
if (ToolsConfig.getTknLocation('kubectl')) {
sendVersionToTelemetry('kubectl.version', `${ToolsConfig.getTknLocation('kubectl')} -o json`);
}
}
async function sendVersionToTelemetry(commandId: string, cmd: string): Promise<void> {
const telemetryProps: TelemetryProperties = {
identifier: commandId,
};
const result = await cli.execute(createCliCommand(`${cmd} version`));
if (result.error) {
telemetryLogError(commandId, result.error);
} else {
let version: unknown;
if (commandId === 'tkn.version') {
version = getVersion(result.stdout);
} else if (commandId === 'kubectl.version') {
version = JSON.parse(result.stdout);
}
for (const [key, value] of Object.entries(version)) {
if (commandId === 'tkn.version') {
telemetryProps[tektonVersionType[key]] = `${value}`;
} else {
telemetryProps[key] = `v${value['major']}.${value['minor']}`;
}
}
sendTknAndKubectlVersionToTelemetry(commandId, telemetryProps);
}
}
async function sendTknAndKubectlVersionToTelemetry(commandId: string, telemetryProps: TelemetryProperties): Promise<void> {
sendTelemetry(commandId, telemetryProps);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function execute<T>(command: (...args: T[]) => Promise<any> | void, ...params: T[]): any | undefined {
try {
const res = command.call(null, ...params);
return res && res.then
? res.then((result: string) => {
displayResult(result);
}).catch((err: Error) => {
vscode.window.showErrorMessage(err.message ? err.message : err.toString());
})
: undefined;
} catch (err) {
vscode.window.showErrorMessage(err);
}
}
function displayResult(result?: string): void {
if (result && typeof result === 'string') {
vscode.window.showInformationMessage(result);
}
}
function migrateFromTkn018(): void {
const newCfgDir = path.join(Platform.getUserHomePath(), '.tkn');
const newCfg = path.join(newCfgDir, 'tkn-config.yaml');
const oldCfg = path.join(Platform.getUserHomePath(), '.kube', 'tkn');
if (!fsx.existsSync(newCfg) && fsx.existsSync(oldCfg)) {
fsx.ensureDirSync(newCfgDir);
fsx.copyFileSync(oldCfg, newCfg);
}
}
function expandMoreItem(context: number, parent: TektonNode, treeViewId: string): void {
parent.visibleChildren += context;
if (treeViewId === 'tektonPipelineExplorerView') {
pipelineExplorer.refresh(parent);
}
if (treeViewId === 'tektonCustomTreeView') {
customTektonExplorer.refresh(parent);
}
} | the_stack |
import React, { useCallback, useEffect, useState } from 'react'
import {
View,
Text,
Platform,
TouchableOpacity,
ScrollView,
Alert,
StyleSheet,
StatusBar,
} from 'react-native'
import RNFS from 'react-native-fs'
import { useTranslation } from 'react-i18next'
import { SafeAreaView } from 'react-native-safe-area-context'
import beapi from '@berty-tech/api'
import { berty } from '@berty-tech/api/root.pb'
import { GRPCError, Service } from '@berty-tech/grpc-bridge'
import { bridge as rpcBridge } from '@berty-tech/grpc-bridge/rpc'
import { useMsgrContext } from '@berty-tech/store/context'
export const accountService = Service(beapi.account.AccountService, rpcBridge, null)
const styles = StyleSheet.create({
safeViewContainer: {
backgroundColor: '#000000',
height: '100%',
},
page: {
margin: 12,
marginBottom: 60,
flexDirection: 'column',
},
footerButton: {
borderColor: '#c0c0c0',
borderRadius: 6,
borderStyle: 'solid',
borderWidth: 1,
margin: 2,
padding: 8,
flex: 1,
},
button: {
borderColor: '#c0c0c0',
borderRadius: 6,
borderStyle: 'solid',
borderBottomWidth: 1,
margin: 2,
padding: 5,
flex: 1,
},
text: {
color: '#00ff00',
fontFamily: Platform.OS === 'ios' ? 'Courier New' : 'monospace',
},
header1: {
fontWeight: 'bold',
fontSize: 38,
},
header2: {
fontWeight: 'bold',
fontSize: 22,
},
bold: { fontWeight: 'bold' },
textError: { color: '#ff0000', fontWeight: 'bold' },
})
const getRootDir = () => {
switch (Platform.OS) {
case 'ios': // Check GoBridge.swift
case 'android': // Check GoBridgeModule.java
return RNFS.DocumentDirectoryPath + '/berty'
default:
throw new Error('unsupported platform')
}
}
const confirmActionWrapper = (title: string, action: () => void, t: any) => () => {
Alert.alert(title, '', [
{
text: t('debug.inspector.confirm-alert.button-confirm'),
onPress: action,
style: 'destructive',
},
{
text: t('debug.inspector.confirm-alert.button-cancel'),
onPress: () => {},
style: 'cancel',
},
])
}
class FSItem {
fileName: string = ''
metadataFileFound: boolean = false
messengerDBFound: boolean = false
ipfsConfigFound: boolean = false
}
const fetchFSAccountList = (updateAccountFSFiles: (arg: Array<FSItem>) => void, t: any) => {
const f = async () => {
const files = await RNFS.readDir(getRootDir())
const items: Array<FSItem> = []
for (const file of files) {
const fsi = new FSItem()
try {
await RNFS.stat(getRootDir() + '/' + file.name + '/account_meta')
fsi.metadataFileFound = true
} catch (e) {}
try {
await RNFS.stat(getRootDir() + '/' + file.name + '/account0/messenger.sqlite')
fsi.messengerDBFound = true
} catch (e) {}
try {
await RNFS.stat(getRootDir() + '/' + file.name + '/ipfs/config')
fsi.ipfsConfigFound = true
} catch (e) {}
fsi.fileName = file.name
items.push(fsi)
}
updateAccountFSFiles(items.sort((a, b) => a.fileName.localeCompare(b.fileName)))
}
f().catch((err: Error) => {
console.warn(err)
Alert.alert(t('debug.inspector.errors.listing-files-failed'), err.message)
})
}
const fetchProtoAccountList = (
updateAccountProtoEntries: (arg: { [key: string]: berty.account.v1.IAccountMetadata }) => void,
t: any,
) => {
const f = async () => {
const resp = await accountService.listAccounts({})
if (!resp) {
updateAccountProtoEntries({})
return
}
const allAccounts = (await resp).accounts.reduce<{
[key: string]: berty.account.v1.IAccountMetadata
}>((all, e) => ({ ...all, [e.accountId!]: e }), {})
updateAccountProtoEntries(allAccounts)
}
f().catch((err: Error) => {
console.warn(err)
if (err instanceof GRPCError) {
Alert.alert(t('debug.inspector.errors.listing-accounts-failed-grpc'), err.error.message)
} else {
Alert.alert(t('debug.inspector.errors.listing-accounts-failed'), err.message)
}
})
}
const accountAction = async (
accountId: string,
setLastUpdate: React.Dispatch<React.SetStateAction<number>>,
t: any,
) => {
let title = t('debug.inspector.accounts.action-delete.file-exists', { accountId: accountId })
try {
const stat = await RNFS.stat(getRootDir() + '/' + accountId)
if (stat.isFile()) {
title = t('debug.inspector.accounts.action-delete.file-exists', { accountId: accountId })
} else {
title = t('debug.inspector.accounts.action-delete.account-exists', { accountId: accountId })
}
} catch (err) {
console.warn(err)
Alert.alert(t('debug.inspector.accounts.action-delete.fs-read-error'), err.message)
return
}
Alert.alert(title, t('debug.inspector.accounts.action-delete.actions-title'), [
{
text: t('debug.inspector.accounts.action-delete.action-account-manager'),
onPress: confirmActionWrapper(
t('debug.inspector.accounts.action-delete.action-account-manager-confirm'),
() => {
// close account if necessary
accountService
.closeAccount({})
.catch((err: Error) => {
console.warn(err)
Alert.alert(t('debug.inspector.accounts.action-delete.error-close'), err.message)
})
// delete account
.then(() => accountService.deleteAccount({ accountId: accountId }))
.then(() => Alert.alert(t('debug.inspector.accounts.action-delete.success-feedback')))
.catch((err: Error) => {
console.warn(err)
Alert.alert(t('debug.inspector.accounts.action-delete.error-delete'), err.message)
})
.finally(() => setLastUpdate(Date.now()))
},
t,
),
style: 'destructive',
},
{
text: t('debug.inspector.accounts.action-delete.action-force-delete'),
onPress: confirmActionWrapper(
t('debug.inspector.accounts.action-delete.action-force-delete-confirm'),
() => {
RNFS.unlink(getRootDir() + '/' + accountId)
.then(() => Alert.alert(t('debug.inspector.accounts.action-delete.success-feedback')))
.catch((err: Error) => {
console.warn(err)
Alert.alert(t('debug.inspector.accounts.action-delete.error-delete'), err.message)
})
.finally(() => setLastUpdate(Date.now()))
},
t,
),
style: 'destructive',
},
{
text: t('debug.inspector.accounts.action-delete.action-cancel'),
onPress: () => {},
style: 'cancel',
},
])
}
// const ExportAllAppData = () => {
// const { t }: { t: any } = useTranslation()
//
// return (
// <TouchableOpacity style={{ flex: 1 }}>
// <View style={[styles.button]}>
// <Text style={[styles.text, styles.bold]}>{t('debug.inspector.dump.button')}</Text>
// </View>
// </TouchableOpacity>
// )
// }
const AccountsInspector: React.FC<{
lastRefresh: Number
setLastUpdate: React.Dispatch<React.SetStateAction<number>>
}> = ({ lastRefresh, setLastUpdate }) => {
const [accountFSFiles, updateAccountFSFiles] = useState<Array<FSItem>>([])
const [accountProtoEntries, updateAccountProtoEntries] = useState<{
[key: string]: berty.account.v1.IAccountMetadata
}>({})
const { t }: { t: any } = useTranslation()
useEffect(
() => fetchFSAccountList(updateAccountFSFiles, t),
[updateAccountFSFiles, lastRefresh, t],
)
useEffect(
() => fetchProtoAccountList(updateAccountProtoEntries, t),
[updateAccountProtoEntries, lastRefresh, t],
)
return (
<>
{accountFSFiles.map(acc => {
const isMetaLoaded = accountProtoEntries.hasOwnProperty(acc.fileName)
return (
<TouchableOpacity
key={acc.fileName}
onPress={() => accountAction(acc.fileName, setLastUpdate, t)}
>
<View style={[{ paddingBottom: 2, paddingTop: 2 }, styles.button]}>
<Text numberOfLines={1} style={[styles.bold, styles.text]}>
{acc.fileName}
</Text>
<View>
{isMetaLoaded ? (
<>
{accountProtoEntries[acc.fileName].name ? (
<Text numberOfLines={1} style={[styles.text]}>
{t('debug.inspector.accounts.infos.aligned.name', {
name: accountProtoEntries[acc.fileName].name,
})}
</Text>
) : null}
{accountProtoEntries[acc.fileName].creationDate ? (
<Text numberOfLines={1} style={[styles.text]}>
{t('debug.inspector.accounts.infos.aligned.created', {
created: new Date(
parseInt(accountProtoEntries[acc.fileName].creationDate, 10) / 1000,
).toUTCString(),
})}
</Text>
) : null}
{accountProtoEntries[acc.fileName].lastOpened ? (
<Text numberOfLines={1} style={[styles.text]}>
{t('debug.inspector.accounts.infos.aligned.opened', {
opened: new Date(
parseInt(accountProtoEntries[acc.fileName].lastOpened, 10) / 1000,
).toUTCString(),
})}
</Text>
) : null}
{accountProtoEntries[acc.fileName].error ? (
<Text style={[styles.text]}>
{t('debug.inspector.accounts.infos.aligned.error', {
error: accountProtoEntries[acc.fileName].error,
})}
</Text>
) : null}
</>
) : (
<>
<Text numberOfLines={1} style={[styles.text, styles.textError]}>
{t('debug.inspector.accounts.data-not-found')}
</Text>
</>
)}
<>
{!isMetaLoaded && (
<>
{acc.metadataFileFound && (
<Text style={[styles.text, styles.textError]} numberOfLines={1}>
{t('debug.inspector.accounts.status.metadata-found')}
</Text>
)}
{acc.ipfsConfigFound && (
<Text style={[styles.text, styles.textError]} numberOfLines={1}>
{t('debug.inspector.accounts.status.ipfs-repo-config-found')}
</Text>
)}
{acc.messengerDBFound && (
<Text style={[styles.text, styles.textError]} numberOfLines={1}>
{t('debug.inspector.accounts.status.messenger-db-found')}
</Text>
)}
</>
)}
{isMetaLoaded && !accountProtoEntries[acc.fileName].error && (
<>
{!acc.metadataFileFound && (
<Text style={[styles.text, styles.textError]} numberOfLines={1}>
{t('debug.inspector.accounts.status.metadata-not-found')}
</Text>
)}
{!acc.ipfsConfigFound && (
<Text style={[styles.text, styles.textError]} numberOfLines={1}>
{t('debug.inspector.accounts.status.ipfs-repo-config-not-found')}
</Text>
)}
{!acc.messengerDBFound && (
<Text style={[styles.text, styles.textError]} numberOfLines={1}>
{t('debug.inspector.accounts.status.messenger-db-not-found')}
</Text>
)}
</>
)}
</>
</View>
</View>
</TouchableOpacity>
)
})}
</>
)
}
const AppInspector: React.FC<{ embedded: boolean; error: Error | null }> = ({
embedded,
error,
}) => {
const [lastUpdate, setLastUpdate] = useState(Date.now())
const { t }: { t: any } = useTranslation()
const { setDebugMode } = useMsgrContext()
const refresh = useCallback(() => setLastUpdate(Date.now()), [setLastUpdate])
return (
<SafeAreaView style={[styles.safeViewContainer]}>
<StatusBar backgroundColor='black' barStyle='light-content' />
<View style={{ paddingHorizontal: 12, flexDirection: 'column' }}>
<Text style={[styles.text, styles.header1]}>{t('debug.inspector.title')}</Text>
<View style={{ paddingVertical: 12 }}>
<Text style={[styles.text, styles.header2]}>{t('debug.inspector.errors.title')}</Text>
{error ? (
<View style={[styles.button]}>
<Text style={[styles.text]}>❌ {t('debug.inspector.errors.header-reported')}</Text>
<Text style={[styles.bold]}>{error.message}</Text>
<Text>{error.stack}</Text>
</View>
) : (
<Text style={[styles.text, styles.bold, styles.button]}>
✅ {t('debug.inspector.errors.header-all-clear')}
</Text>
)}
</View>
</View>
<ScrollView style={[styles.page]} contentContainerStyle={{ paddingBottom: 30 }}>
<Text style={[styles.text, styles.header2]}>{t('debug.inspector.accounts.title')}</Text>
{embedded ? (
<AccountsInspector lastRefresh={lastUpdate} setLastUpdate={setLastUpdate} />
) : (
<Text style={[styles.text]}>
❌ {t('debug.inspector.accounts.unsupported-remote-mode')}
</Text>
)}
</ScrollView>
<View style={{ position: 'absolute', bottom: 30, left: 0, right: 0 }}>
<View style={{ flexDirection: 'row', paddingHorizontal: 12 }}>
<TouchableOpacity onPress={refresh} style={{ flex: 1 }}>
<View style={[styles.footerButton]}>
<Text style={[styles.text, styles.bold, { textAlign: 'center' }]}>
{t('debug.inspector.refresh')}
</Text>
</View>
</TouchableOpacity>
{/*<ExportAllAppData />*/}
<TouchableOpacity onPress={() => setDebugMode(false)} style={{ flex: 1 }}>
<View style={[styles.footerButton]}>
<Text style={[styles.text, styles.bold, { textAlign: 'center' }]}>
{t('debug.inspector.hide-button')}
</Text>
</View>
</TouchableOpacity>
</View>
</View>
</SafeAreaView>
)
}
export default AppInspector | the_stack |
import {
EventRef,
TFolder,
Plugin,
TFile,
ButtonComponent,
getAllTags,
debounce,
TAbstractFile,
normalizePath,
MarkdownView,
} from "obsidian";
import { Queue } from "./queue";
import { LogTo } from "./logger";
import {
ReviewFileModal,
ReviewNoteModal,
ReviewBlockModal,
} from "./views/modals";
import { IWSettings, DefaultSettings } from "./settings";
import { IWSettingsTab } from "./views/settings-tab";
import { StatusBar } from "./views/status-bar";
import { QueueLoadModal } from "./views/queue-modal";
import { LinkEx } from "./helpers/link-utils";
import { FileUtils } from "./helpers/file-utils";
import { BulkAdderModal } from "./views/bulk-adding";
import { BlockUtils } from "./helpers/block-utils";
import { FuzzyNoteAdder } from "./views/fuzzy-note-adder";
import { MarkdownTableRow } from "./markdown";
import { NextRepScheduler } from "./views/next-rep-schedule";
import { EditDataModal } from "./views/edit-data";
import { DateParser } from "./helpers/parse-date";
import { CreateQueueModal } from "./views/create-queue";
export default class IW extends Plugin {
public settings: IWSettings;
public statusBar: StatusBar;
public queue: Queue;
//
// Utils
public readonly links: LinkEx = new LinkEx(this.app);
public readonly files: FileUtils = new FileUtils(this.app);
public readonly blocks: BlockUtils = new BlockUtils(this.app);
public readonly dates: DateParser = new DateParser(this.app);
private autoAddNewNotesOnCreateEvent: EventRef;
private checkTagsOnModifiedEvent: EventRef;
private tagMap: Map<TFile, Set<string>> = new Map();
async loadConfig() {
this.settings = this.settings = Object.assign(
{},
DefaultSettings,
await this.loadData()
);
}
getQueueFiles() {
const abstractFiles = this.app.vault.getAllLoadedFiles();
const queueFiles = abstractFiles.filter((file: TAbstractFile) => {
return (
file instanceof TFile &&
file.parent.path === this.settings.queueFolderPath &&
file.extension === "md"
);
});
return <TFile[]>queueFiles;
}
getDefaultQueuePath() {
return normalizePath(
[this.settings.queueFolderPath, this.settings.queueFileName].join("/")
);
}
createTagMap() {
const notes: TFile[] = this.app.vault.getMarkdownFiles();
for (const note of notes) {
const fileCachedData = this.app.metadataCache.getFileCache(note) || {};
const tags = new Set(getAllTags(fileCachedData) || []);
this.tagMap.set(note, tags);
}
}
async onload() {
LogTo.Console("Loading...");
await this.loadConfig();
this.addSettingTab(new IWSettingsTab(this.app, this));
this.registerCommands();
this.subscribeToEvents();
}
randomWithinInterval(min: number, max: number) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
checkTagsOnModified() {
this.checkTagsOnModifiedEvent = this.app.vault.on(
"modify",
debounce(
async (file) => {
if (!(file instanceof TFile) || file.extension !== "md") {
return;
}
const fileCachedData =
this.app.metadataCache.getFileCache(file) || {};
const currentTags = new Set(getAllTags(fileCachedData) || []);
const lastTags = this.tagMap.get(file) || new Set<string>();
let setsEqual = (a: Set<string>, b: Set<string>) =>
a.size === b.size && [...a].every((value) => b.has(value));
if (setsEqual(new Set(currentTags), new Set(lastTags))) {
LogTo.Debug("No tag changes.");
return;
}
LogTo.Debug("Updating tags.");
this.tagMap.set(file, currentTags);
const newTags = [...currentTags].filter((x) => !lastTags.has(x)); // set difference
LogTo.Debug("Added new tags: " + newTags.toString());
const queueFiles = this.getQueueFiles();
LogTo.Debug("Queue Files: " + queueFiles.toString());
const queueTagMap = this.settings.queueTagMap;
const newQueueTags = newTags
.map((tag) => tag.substr(1))
.filter((tag) =>
Object.values(queueTagMap).some((arr) => arr.contains(tag))
);
LogTo.Debug("New Queue Tags: " + newQueueTags.toString());
for (const queueTag of newQueueTags) {
const addToQueueFiles = queueFiles
.filter((f) => queueTagMap[f.name.substr(0, f.name.length - 3)])
.filter((f) =>
queueTagMap[f.name.substr(0, f.name.length - 3)].contains(
queueTag
)
);
for (const queueFile of addToQueueFiles) {
const queue = new Queue(this, queueFile.path);
LogTo.Debug(`Adding ${file.name} to ${queueFile.name}`);
const link = this.files.toLinkText(file);
const min = this.settings.defaultPriorityMin;
const max = this.settings.defaultPriorityMax;
const priority = this.randomWithinInterval(min, max);
const date = this.dates.parseDate(
this.settings.defaultFirstRepDate
);
const row = new MarkdownTableRow(link, priority, "", 1, date);
await queue.add(row);
}
}
// already debounced 2 secs but not throttled, true on resetTimer throttles the callback
},
3000,
true
)
);
}
autoAddNewNotesOnCreate() {
if (this.settings.autoAddNewNotes) {
this.autoAddNewNotesOnCreateEvent = this.app.vault.on(
"create",
async (file) => {
if (!(file instanceof TFile) || file.extension !== "md") {
return;
}
let link = this.files.toLinkText(file);
let min = this.settings.defaultPriorityMin;
let max = this.settings.defaultPriorityMax;
let priority = this.randomWithinInterval(min, max);
let row = new MarkdownTableRow(link, priority, "");
LogTo.Console("Auto adding new note to default queue: " + link);
await this.queue.add(row);
}
);
} else {
if (this.autoAddNewNotesOnCreateEvent) {
this.app.vault.offref(this.autoAddNewNotesOnCreateEvent);
this.autoAddNewNotesOnCreateEvent = undefined;
}
}
}
async getSearchLeafView() {
return this.app.workspace.getLeavesOfType("search")[0]?.view;
}
async getFound() {
const view = await this.getSearchLeafView();
if (!view) {
LogTo.Console("Failed to get search leaf view.");
return [];
}
// @ts-ignore
return Array.from(view.dom.resultDomLookup.keys());
}
async addSearchButton() {
const view = await this.getSearchLeafView();
if (!view) {
LogTo.Console("Failed to add button to the search pane.");
return;
}
(<any>view).addToQueueButton = new ButtonComponent(
view.containerEl.children[0].firstChild as HTMLElement
)
.setClass("nav-action-button")
.setIcon("sheets-in-box")
.setTooltip("Add to IW Queue")
.onClick(async () => await this.addSearchResultsToQueue());
}
async getSearchResults(): Promise<TFile[]> {
return (await this.getFound()) as TFile[];
}
async addSearchResultsToQueue() {
const files = await this.getSearchResults();
const pairs = files.map((file) =>
this.links.createAbsoluteLink(normalizePath(file.path), "")
);
if (pairs && pairs.length > 0) {
new BulkAdderModal(
this,
this.queue.queuePath,
"Bulk Add Search Results",
pairs
).open();
} else {
LogTo.Console("No files to add.", true);
}
}
async updateStatusBar() {
const table = await this.queue.loadTable();
this.statusBar.updateCurrentRep(table?.currentRep());
this.statusBar.updateCurrentQueue(this.queue.queuePath);
}
async loadQueue(file: string) {
if (file && file.length > 0) {
this.queue = new Queue(this, file);
await this.updateStatusBar();
LogTo.Console("Loaded Queue: " + file, true);
} else {
LogTo.Console("Failed to load queue.", true);
}
}
registerCommands() {
//
// Queue Creation
this.addCommand({
id: "create-new-iw-queue",
name: "Create and load a new queue.",
callback: () => new CreateQueueModal(this).open(),
hotkeys: [],
});
//
// Queue Browsing
this.addCommand({
id: "open-queue-current-pane",
name: "Open queue in current pane.",
callback: () => this.queue.goToQueue(false),
hotkeys: [],
});
this.addCommand({
id: "open-queue-new-pane",
name: "Open queue in new pane.",
callback: () => this.queue.goToQueue(true),
hotkeys: [],
});
//
// Repetitions
this.addCommand({
id: "current-iw-repetition",
name: "Current repetition.",
callback: async () => await this.queue.goToCurrentRep(),
hotkeys: [],
});
this.addCommand({
id: "dismiss-current-repetition",
name: "Dismiss current repetition.",
callback: async () => {
await this.queue.dismissCurrent();
},
hotkeys: [],
});
this.addCommand({
id: "next-iw-repetition-schedule",
name: "Next repetition and manually schedule.",
callback: async () => {
const table = await this.queue.loadTable();
if (!table || !table.hasReps()) {
LogTo.Console("No repetitions!", true);
return;
}
const currentRep = table.currentRep();
if (await this.queue.nextRepetition()) {
new NextRepScheduler(this, currentRep, table).open();
}
},
});
this.addCommand({
id: "next-iw-repetition",
name: "Next repetition.",
callback: async () => await this.queue.nextRepetition(),
hotkeys: [],
});
this.addCommand({
id: "edit-current-rep-data",
name: "Edit current rep data. ",
callback: async () => {
const table = await this.queue.loadTable();
if (!table || !table.hasReps()) {
LogTo.Debug("No repetitions!", true);
return;
}
const curRep = table.currentRep();
if (!curRep) {
LogTo.Debug("No current repetition!", true);
return;
}
new EditDataModal(this, curRep, table).open();
await this.updateStatusBar();
},
hotkeys: [],
});
//
// Element Adding.
this.addCommand({
id: "add-links-in-selected-text",
name: "Add links in selected text.",
checkCallback: (checking) => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
const editor = view?.editor;
const file = view?.file;
if (file && editor) {
if (!checking) {
const links = this.app.metadataCache.getFileCache(file).links ?? [];
if (!links || links.length === 0) {
LogTo.Debug("Active note does not contain any links.", true);
return;
}
const selection = editor.getSelection();
if (!selection || selection.length === 0) {
LogTo.Debug("No selected text.", true);
return;
}
const selectedLinks = Array.from(
links
.filter((link) => selection.contains(link.original))
.map((link) =>
this.links.createAbsoluteLink(link.link, file.path)
)
.filter((link) => link !== null && link.length > 0)
.reduce((set, link) => set.add(link), new Set<string>())
);
if (!selectedLinks || selectedLinks.length === 0) {
LogTo.Debug("No selected links.", true);
return;
}
LogTo.Debug("Selected links: " + selectedLinks.toString());
new BulkAdderModal(
this,
this.queue.queuePath,
"Bulk Add Links",
selectedLinks
).open();
}
return true;
}
return false;
},
});
this.addCommand({
id: "bulk-add-blocks",
name: "Bulk add blocks with references to queue.",
checkCallback: (checking) => {
const file = this.files.getActiveNoteFile();
if (file != null) {
if (!checking) {
const refs = this.app.metadataCache.getFileCache(file).blocks;
if (!refs) {
LogTo.Debug("File does not contain any blocks with references.");
} else {
const fileLink = this.app.metadataCache.fileToLinktext(
file,
"",
true
);
const linkPaths = Object.keys(refs).map(
(l) => fileLink + "#^" + l
);
new BulkAdderModal(
this,
this.queue.queuePath,
"Bulk Add Block References",
linkPaths
).open();
}
}
return true;
}
return false;
},
});
this.addCommand({
id: "note-add-iw-queue",
name: "Add note to queue.",
checkCallback: (checking: boolean) => {
if (this.files.getActiveNoteFile() !== null) {
if (!checking) {
new ReviewNoteModal(this).open();
}
return true;
}
return false;
},
});
this.addCommand({
id: "fuzzy-note-add-iw-queue",
name: "Add note to queue through a fuzzy finder",
callback: () => new FuzzyNoteAdder(this).open(),
hotkeys: [],
});
this.addCommand({
id: "block-add-iw-queue",
name: "Add block to queue.",
checkCallback: (checking: boolean) => {
if (this.files.getActiveNoteFile() != null) {
if (!checking) {
new ReviewBlockModal(this).open();
}
return true;
}
return false;
},
hotkeys: [],
});
this.addCommand({
id: "add-links-within-note",
name: "Add links within note to queue.",
checkCallback: (checking: boolean) => {
const file = this.files.getActiveNoteFile();
if (file !== null) {
if (!checking) {
const links = this.links.getLinksIn(file);
if (links && links.length > 0) {
new BulkAdderModal(
this,
this.queue.queuePath,
"Bulk Add Links",
links
).open();
} else {
LogTo.Console("No links in the current file.", true);
}
}
return true;
}
return false;
},
hotkeys: [],
});
//
// Queue Loading
this.addCommand({
id: "load-iw-queue",
name: "Load a queue.",
callback: () => {
new QueueLoadModal(this).open();
},
hotkeys: [],
});
}
createStatusBar() {
this.statusBar = new StatusBar(this.addStatusBarItem(), this);
this.statusBar.initStatusBar();
}
subscribeToEvents() {
this.app.workspace.onLayoutReady(async () => {
this.createStatusBar();
const queuePath = this.getDefaultQueuePath();
await this.loadQueue(queuePath);
this.createTagMap();
this.checkTagsOnModified();
this.addSearchButton();
this.autoAddNewNotesOnCreate();
});
this.registerEvent(
this.app.workspace.on("file-menu", (menu, file, _: string) => {
if (file == null) {
return;
}
if (file instanceof TFile && file.extension === "md") {
menu.addItem((item) => {
item
.setTitle(`Add File to IW Queue`)
.setIcon("sheets-in-box")
.onClick((_) => {
new ReviewFileModal(this, file.path).open();
});
});
} else if (file instanceof TFolder) {
menu.addItem((item) => {
item
.setTitle(`Add Folder to IW Queue`)
.setIcon("sheets-in-box")
.onClick((_) => {
const pairs = this.app.vault
.getMarkdownFiles()
.filter((f) => this.files.isDescendantOf(f, file))
.map((f) =>
this.links.createAbsoluteLink(normalizePath(f.path), "")
);
if (pairs && pairs.length > 0) {
new BulkAdderModal(
this,
this.queue.queuePath,
"Bulk Add Folder Notes",
pairs
).open();
} else {
LogTo.Console("Folder contains no files!", true);
}
});
});
}
})
);
}
async removeSearchButton() {
let searchView = await this.getSearchLeafView();
let btn = (<any>searchView)?.addToQueueButton;
if (btn) {
btn.buttonEl?.remove();
btn = null;
}
}
unsubscribeFromEvents() {
for (let e of [
this.autoAddNewNotesOnCreateEvent,
this.checkTagsOnModifiedEvent,
]) {
this.app.vault.offref(e);
e = undefined;
}
}
async onunload() {
LogTo.Console("Disabled and unloaded.");
await this.removeSearchButton();
this.unsubscribeFromEvents();
}
} | the_stack |
import { IDatePickerStrings } from "office-ui-fabric-react";
export const DayPickerStrings: IDatePickerStrings = {
months: [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December",
],
shortMonths: [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
],
days: [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
],
shortDays: ["S", "M", "T", "W", "T", "F", "S"],
goToToday: "Go to today",
prevMonthAriaLabel: "Go to previous month",
nextMonthAriaLabel: "Go to next month",
prevYearAriaLabel: "Go to previous year",
nextYearAriaLabel: "Go to next year",
closeButtonAriaLabel: "Close date picker",
isRequiredErrorMessage: "Field is required.",
invalidInputErrorMessage: "Invalid date format.",
// isOutOfBoundsErrorMessage: `Date must be between ${minDate.toLocaleDateString()}-${maxDate.toLocaleDateString()}`,
};
export const languages = [
{ languageTag: "af-ZA", displayName: "Afrikaans – South Africa" },
{ languageTag: "sq-AL", displayName: "Albanian – Albania" },
{ languageTag: "ar-DZ", displayName: "Arabic – Algeria" },
{ languageTag: "ar-BH", displayName: "Arabic – Bahrain" },
{ languageTag: "ar-EG", displayName: "Arabic – Egypt" },
{ languageTag: "ar-IQ", displayName: "Arabic – Iraq" },
{ languageTag: "ar-JO", displayName: "Arabic – Jordan" },
{ languageTag: "ar-KW", displayName: "Arabic – Kuwait" },
{ languageTag: "ar-LB", displayName: "Arabic – Lebanon" },
{ languageTag: "ar-LY", displayName: "Arabic – Libya" },
{ languageTag: "ar-MA", displayName: "Arabic – Morocco" },
{ languageTag: "ar-OM", displayName: "Arabic – Oman" },
{ languageTag: "ar-QA", displayName: "Arabic – Qatar" },
{ languageTag: "ar-SA", displayName: "Arabic – Saudi Arabia" },
{ languageTag: "ar-SY", displayName: "Arabic – Syria" },
{ languageTag: "ar-TN", displayName: "Arabic – Tunisia" },
{ languageTag: "ar-AE", displayName: "Arabic – United Arab Emirates" },
{ languageTag: "ar-YE", displayName: "Arabic – Yemen" },
{ languageTag: "hy-AM", displayName: "Armenian – Armenia" },
{ languageTag: "Cy-az-AZ", displayName: "Azeri (Cyrillic) – Azerbaijan" },
{ languageTag: "Lt-az-AZ", displayName: "Azeri (Latin) – Azerbaijan" },
{ languageTag: "eu-ES", displayName: "Basque – Basque" },
{ languageTag: "be-BY", displayName: "Belarusian – Belarus" },
{ languageTag: "bg-BG", displayName: "Bulgarian – Bulgaria" },
{ languageTag: "ca-ES", displayName: "Catalan – Catalan" },
{ languageTag: "zh-CN", displayName: "Chinese – China" },
{ languageTag: "zh-HK", displayName: "Chinese – Hong Kong SAR" },
{ languageTag: "zh-MO", displayName: "Chinese – Macau SAR" },
{ languageTag: "zh-SG", displayName: "Chinese – Singapore" },
{ languageTag: "zh-TW", displayName: "Chinese – Taiwan" },
{ languageTag: "zh-CHS", displayName: "Chinese (Simplified)" },
{ languageTag: "zh-CHT", displayName: "Chinese (Traditional)" },
{ languageTag: "hr-HR", displayName: "Croatian – Croatia" },
{ languageTag: "cs-CZ", displayName: "Czech – Czech Republic" },
{ languageTag: "da-DK", displayName: "Danish – Denmark" },
{ languageTag: "div-MV", displayName: "Dhivehi – Maldives" },
{ languageTag: "nl-BE", displayName: "Dutch – Belgium" },
{ languageTag: "nl-NL", displayName: "Dutch – The Netherlands" },
{ languageTag: "en-AU", displayName: "English – Australia" },
{ languageTag: "en-BZ", displayName: "English – Belize" },
{ languageTag: "en-CA", displayName: "English – Canada" },
{ languageTag: "en-CB", displayName: "English – Caribbean" },
{ languageTag: "en-IE", displayName: "English – Ireland" },
{ languageTag: "en-JM", displayName: "English – Jamaica" },
{ languageTag: "en-NZ", displayName: "English – New Zealand" },
{ languageTag: "en-PH", displayName: "English – Philippines" },
{ languageTag: "en-ZA", displayName: "English – South Africa" },
{ languageTag: "en-TT", displayName: "English – Trinidad and Tobago" },
{ languageTag: "en-GB", displayName: "English – United Kingdom" },
{ languageTag: "en-US", displayName: "English – United States" },
{ languageTag: "en-ZW", displayName: "English – Zimbabwe" },
{ languageTag: "et-EE", displayName: "Estonian – Estonia" },
{ languageTag: "fo-FO", displayName: "Faroese – Faroe Islands" },
{ languageTag: "fa-IR", displayName: "Farsi – Iran" },
{ languageTag: "fi-FI", displayName: "Finnish – Finland" },
{ languageTag: "fr-BE", displayName: "French – Belgium" },
{ languageTag: "fr-CA", displayName: "French – Canada" },
{ languageTag: "fr-FR", displayName: "French – France" },
{ languageTag: "fr-LU", displayName: "French – Luxembourg" },
{ languageTag: "fr-MC", displayName: "French – Monaco" },
{ languageTag: "fr-CH", displayName: "French – Switzerland" },
{ languageTag: "gl-ES", displayName: "Galician – Galician" },
{ languageTag: "ka-GE", displayName: "Georgian – Georgia" },
{ languageTag: "de-AT", displayName: "German – Austria" },
{ languageTag: "de-DE", displayName: "German – Germany" },
{ languageTag: "de-LI", displayName: "German – Liechtenstein" },
{ languageTag: "de-LU", displayName: "German – Luxembourg" },
{ languageTag: "de-CH", displayName: "German – Switzerland" },
{ languageTag: "el-GR", displayName: "Greek – Greece" },
{ languageTag: "gu-IN", displayName: "Gujarati – India" },
{ languageTag: "he-IL", displayName: "Hebrew – Israel" },
{ languageTag: "hi-IN", displayName: "Hindi – India" },
{ languageTag: "hu-HU", displayName: "Hungarian – Hungary" },
{ languageTag: "is-IS", displayName: "Icelandic – Iceland" },
{ languageTag: "id-ID", displayName: "Indonesian – Indonesia" },
{ languageTag: "it-IT", displayName: "Italian – Italy" },
{ languageTag: "it-CH", displayName: "Italian – Switzerland" },
{ languageTag: "ja-JP", displayName: "Japanese – Japan" },
{ languageTag: "kn-IN", displayName: "Kannada – India" },
{ languageTag: "kk-KZ", displayName: "Kazakh – Kazakhstan" },
{ languageTag: "kok-IN", displayName: "Konkani – India" },
{ languageTag: "ko-KR", displayName: "Korean – Korea" },
{ languageTag: "ky-KZ", displayName: "Kyrgyz – Kazakhstan" },
{ languageTag: "lv-LV", displayName: "Latvian – Latvia" },
{ languageTag: "lt-LT", displayName: "Lithuanian – Lithuania" },
{ languageTag: "mk-MK", displayName: "Macedonian (FYROM)" },
{ languageTag: "ms-BN", displayName: "Malay – Brunei" },
{ languageTag: "ms-MY", displayName: "Malay – Malaysia" },
{ languageTag: "mr-IN", displayName: "Marathi – India" },
{ languageTag: "mn-MN", displayName: "Mongolian – Mongolia" },
{ languageTag: "nb-NO", displayName: "Norwegian (Bokmål) – Norway" },
{ languageTag: "nn-NO", displayName: "Norwegian (Nynorsk) – Norway" },
{ languageTag: "pl-PL", displayName: "Polish – Poland" },
{ languageTag: "pt-BR", displayName: "Portuguese – Brazil" },
{ languageTag: "pt-PT", displayName: "Portuguese – Portugal" },
{ languageTag: "pa-IN", displayName: "Punjabi – India" },
{ languageTag: "ro-RO", displayName: "Romanian – Romania" },
{ languageTag: "ru-RU", displayName: "Russian – Russia" },
{ languageTag: "sa-IN", displayName: "Sanskrit – India" },
{ languageTag: "Cy-sr-SP", displayName: "Serbian (Cyrillic) – Serbia" },
{ languageTag: "Lt-sr-SP", displayName: "Serbian (Latin) – Serbia" },
{ languageTag: "sk-SK", displayName: "Slovak – Slovakia" },
{ languageTag: "sl-SI", displayName: "Slovenian – Slovenia" },
{ languageTag: "es-AR", displayName: "Spanish – Argentina" },
{ languageTag: "es-BO", displayName: "Spanish – Bolivia" },
{ languageTag: "es-CL", displayName: "Spanish – Chile" },
{ languageTag: "es-CO", displayName: "Spanish – Colombia" },
{ languageTag: "es-CR", displayName: "Spanish – Costa Rica" },
{ languageTag: "es-DO", displayName: "Spanish – Dominican Republic" },
{ languageTag: "es-EC", displayName: "Spanish – Ecuador" },
{ languageTag: "es-SV", displayName: "Spanish – El Salvador" },
{ languageTag: "es-GT", displayName: "Spanish – Guatemala" },
{ languageTag: "es-HN", displayName: "Spanish – Honduras" },
{ languageTag: "es-MX", displayName: "Spanish – Mexico" },
{ languageTag: "es-NI", displayName: "Spanish – Nicaragua" },
{ languageTag: "es-PA", displayName: "Spanish – Panama" },
{ languageTag: "es-PY", displayName: "Spanish – Paraguay" },
{ languageTag: "es-PE", displayName: "Spanish – Peru" },
{ languageTag: "es-PR", displayName: "Spanish – Puerto Rico" },
{ languageTag: "es-ES", displayName: "Spanish – Spain" },
{ languageTag: "es-UY", displayName: "Spanish – Uruguay" },
{ languageTag: "es-VE", displayName: "Spanish – Venezuela" },
{ languageTag: "sw-KE", displayName: "Swahili – Kenya" },
{ languageTag: "sv-FI", displayName: "Swedish – Finland" },
{ languageTag: "sv-SE", displayName: "Swedish – Sweden" },
{ languageTag: "syr-SY", displayName: "Syriac – Syria" },
{ languageTag: "ta-IN", displayName: "Tamil – India" },
{ languageTag: "tt-RU", displayName: "Tatar – Russia" },
{ languageTag: "te-IN", displayName: "Telugu – India" },
{ languageTag: "th-TH", displayName: "Thai – Thailand" },
{ languageTag: "tr-TR", displayName: "Turkish – Turkey" },
{ languageTag: "uk-UA", displayName: "Ukrainian – Ukraine" },
{ languageTag: "ur-PK", displayName: "Urdu – Pakistan" },
{ languageTag: "Cy-uz-UZ", displayName: "Uzbek (Cyrillic) – Uzbekistan" },
{ languageTag: "Lt-uz-UZ", displayName: "Uzbek (Latin) – Uzbekistan" },
{ languageTag: "vi-VN", displayName: "Vietnamese – Vietnam" },
];
export const DirectoryPropertyName = [
"UserPrincipalName",
"Fax2",
"StreetAddress",
"PostalCode",
"StateOrProvince",
"Alias",
"CustomAttribute1",
"CustomAttribute2",
"CustomAttribute3",
"CustomAttribute4",
"CustomAttribute5",
"CustomAttribute6",
"CustomAttribute7",
"CustomAttribute8",
"CustomAttribute9",
"CustomAttribute10",
"CustomAttribute11",
"CustomAttribute12",
"CustomAttribute13",
"CustomAttr§ibute14",
"CustomAttribute15",
]; | the_stack |
import { BasicCredentialHandler } from "azure-devops-node-api/handlers/basiccreds";
import { DiskCache } from "../lib/diskcache";
import { getCredentialStore } from "../lib/credstore";
import { repeatStr } from "../lib/common";
import { TfsConnection } from "../lib/connection";
import { WebApi, getBasicHandler } from "azure-devops-node-api/WebApi";
import { EOL as eol } from "os";
import _ = require("lodash");
import args = require("./arguments");
import { blue, cyan, gray, green, yellow, magenta, reset as resetColors, stripColors } from "colors";
import command = require("../lib/command");
import common = require("./common");
import clipboardy = require("clipboardy");
import { writeFile } from "fs";
import loader = require("../lib/loader");
import path = require("path");
import fsUtils = require("./fsUtils");
import { promisify } from "util";
import trace = require("./trace");
import version = require("./version");
export interface CoreArguments {
[key: string]: args.Argument<any>;
project: args.StringArgument;
root: args.ExistingDirectoriesArgument;
authType: args.StringArgument;
serviceUrl: args.StringArgument;
password: args.SilentStringArgument;
token: args.SilentStringArgument;
save: args.BooleanArgument;
username: args.StringArgument;
output: args.StringArgument;
json: args.BooleanArgument;
fiddler: args.BooleanArgument;
proxy: args.StringArgument;
help: args.BooleanArgument;
noPrompt: args.BooleanArgument;
noColor: args.BooleanArgument;
debugLogStream: args.StringArgument;
}
export interface Executor<TResult> {
(cmd?: command.TFXCommand): Promise<TResult>;
}
export abstract class TfCommand<TArguments extends CoreArguments, TResult> {
protected commandArgs: TArguments = <TArguments>{};
private groupedArgs: { [key: string]: string[] };
private initialized: Promise<Executor<any>>;
protected webApi: WebApi;
protected description: string = "A suite of command line tools to interact with Azure DevOps Services.";
public connection: TfsConnection;
protected abstract serverCommand;
/**
* @param serverCommand True to initialize the WebApi object during init phase.
*/
constructor(public passedArgs: string[]) {
this.setCommandArgs();
}
/**
* Returns a promise that is resolved when this command is initialized and
* ready to be executed.
*/
public ensureInitialized(): Promise<Executor<any>> {
return this.initialized || this.initialize();
}
protected initialize(): Promise<Executor<any>> {
this.initialized = this.commandArgs.help.val().then(needHelp => {
if (needHelp) {
return this.run.bind(this, this.getHelp.bind(this));
} else {
// Set the fiddler proxy
return this.commandArgs.fiddler
.val()
.then(useProxy => {
if (useProxy) {
process.env.HTTP_PROXY = "http://127.0.0.1:8888";
}
})
.then(() => {
// Set custom proxy
return this.commandArgs.proxy.val(true).then(proxy => {
if (proxy) {
process.env.HTTP_PROXY = proxy;
}
});
})
.then(() => {
// Set the no-prompt flag
return this.commandArgs.noPrompt.val(true).then(noPrompt => {
common.NO_PROMPT = noPrompt;
});
})
.then(() => {
// If --no-color specified, Patch console.log to never output color bytes
return this.commandArgs.noColor.val(true).then(noColor => {
if (noColor) {
console.log = logNoColors;
}
});
})
.then(() => {
// Set the cached service url
return this.commandArgs.serviceUrl.val(true).then(serviceUrl => {
if (!serviceUrl && !process.env["TFX_BYPASS_CACHE"] && common.EXEC_PATH.join("") !== "login") {
let diskCache = new DiskCache("tfx");
return diskCache.itemExists("cache", "connection").then(isConnection => {
let connectionUrlPromise: Promise<string>;
if (!isConnection) {
connectionUrlPromise = Promise.resolve<string>(null);
} else {
connectionUrlPromise = diskCache.getItem("cache", "connection");
}
return connectionUrlPromise.then(url => {
if (url) {
this.commandArgs.serviceUrl.setValue(url);
}
});
});
} else {
return Promise.resolve<void>(null);
}
});
})
.then(() => {
let apiPromise = Promise.resolve<any>(null);
if (this.serverCommand) {
apiPromise = this.getWebApi().then(_ => {});
}
return apiPromise.then(() => {
return this.run.bind(this, this.exec.bind(this));
});
});
}
});
return this.initialized;
}
private getGroupedArgs(): { [key: string]: string[] } {
if (!this.groupedArgs) {
let group: { [key: string]: string[] } = {};
let currentArg = null;
this.passedArgs.forEach(arg => {
if (_.startsWith(arg, "--")) {
currentArg = _.camelCase(arg.substr(2));
group[currentArg] = [];
return;
}
// short args/alias support - allow things like -abc "cat" "dog"
// which means the same as --arg-a --arg-b --arg-c "cat" "dog"
if (_.startsWith(arg, "-")) {
const shorthandArgs = arg.substr(1).split("");
for (const shArg of shorthandArgs) {
const shorthandArg = "-" + shArg;
group[shorthandArg] = [];
currentArg = shorthandArg;
}
return;
}
if (currentArg) {
group[currentArg].push(arg);
}
});
this.groupedArgs = group;
}
return this.groupedArgs;
}
/**
* Registers an argument that this command can accept from the command line
*
* @param name Name of the argument. This is what is passed in on the command line, e.g. "authType"
* is passed in with --auth-type. Can be an array for aliases, but the first item is how the
* argument's value is accessed, e.g. this.commandArgs.authType.val().
* An argument can have one shorthand argument: a dash followed by a single letter. This is
* passed at the command line with a single dash, e.g. -u. Multiple boolean shorthand arguments
* can be passed with a single dash: -abcd. See setCommandArgs for usage examples.
* @param friendlyName Name to display to the user in help.
* @param description Description to display in help.
* @param ctor Constructor for the type of argument this is (e.g. string, number, etc.)
* @param defaultValue Default value of the argument, null for no default, undefined to prompt the user.
*/
protected registerCommandArgument<T extends args.Argument<any>>(
name: string | string[],
friendlyName: string,
description: string,
ctor: new (
name: string,
friendlyName: string,
description: string,
value: string | string[] | Promise<string[]>,
hasDefaultValue?: boolean,
argAliases?: string[],
undocumented?: boolean,
promptDefault?: string,
) => T,
defaultValue?: string | string[] | (() => Promise<string[]>),
undocumented: boolean = false,
promptDefault?: string,
): void {
const fixedArgNames = (typeof name === "string" ? [name] : name).map(a => (a.substr(0, 2) === "--" ? a.substr(0, 2) : a));
const argName = fixedArgNames[0];
const argAliases = fixedArgNames.slice(1);
let groupedArgs = this.getGroupedArgs();
let argValue = groupedArgs[argName];
if (argValue === undefined) {
for (const alias of argAliases) {
if (groupedArgs[alias]) {
argValue = groupedArgs[alias];
break;
}
}
}
if (argValue) {
this.commandArgs[argName] = new ctor(argName, friendlyName, description, argValue, false, argAliases, undocumented);
} else {
let def: string | string[] | Promise<string[]> = null;
if (typeof defaultValue === "function") {
def = defaultValue();
} else {
def = defaultValue;
}
this.commandArgs[argName] = new ctor(
argName,
friendlyName,
description,
def,
true,
argAliases,
undocumented,
promptDefault,
);
}
}
/**
* Register arguments that may be used with this command.
*/
protected setCommandArgs(): void {
this.registerCommandArgument(["project", "-p"], "Project name", null, args.StringArgument);
this.registerCommandArgument(["root", "-r"], "Root directory", null, args.ExistingDirectoriesArgument, ".");
this.registerCommandArgument(
["authType"],
"Authentication Method",
"Method of authentication ('pat' or 'basic').",
args.StringArgument,
"pat",
);
this.registerCommandArgument(
["serviceUrl", "-u"],
"Service URL",
"URL to the service you will connect to, e.g. https://youraccount.visualstudio.com/DefaultCollection.",
args.StringArgument,
);
this.registerCommandArgument(
["password"],
"Password",
"Password to use for basic authentication.",
args.SilentStringArgument,
);
this.registerCommandArgument(["token", "-t"], "Personal access token", null, args.SilentStringArgument);
this.registerCommandArgument(
["save"],
"Save settings",
"Save arguments for the next time a command in this command group is run.",
args.BooleanArgument,
"false",
);
this.registerCommandArgument(["username"], "Username", "Username to use for basic authentication.", args.StringArgument);
this.registerCommandArgument(
["output"],
"Output destination",
"Method to use for output. Options: friendly, json, clipboard.",
args.StringArgument,
"friendly",
);
this.registerCommandArgument(["json"], "Output as JSON", "Alias for --output json.", args.BooleanArgument, "false");
this.registerCommandArgument(
["fiddler"],
"Use Fiddler proxy",
"Set up the fiddler proxy for HTTP requests (for debugging purposes).",
args.BooleanArgument,
"false",
);
this.registerCommandArgument(
["proxy"],
"Proxy server",
"Use the specified proxy server for HTTP traffic.",
args.StringArgument,
null,
);
this.registerCommandArgument(["help", "-h"], "Help", "Get help for any command.", args.BooleanArgument, "false");
this.registerCommandArgument(
["noPrompt"],
"No Prompt",
"Do not prompt the user for input (instead, raise an error).",
args.BooleanArgument,
"false",
);
this.registerCommandArgument(
"includeUndocumented",
"Include undocumented commands?",
"Show help for commands and options that are undocumented (use at your own risk!)",
args.BooleanArgument,
"false",
);
this.registerCommandArgument(
"traceLevel",
"Trace Level",
`Tracing threshold can be specified as "none", "info" (default), and "debug".`,
args.StringArgument,
null,
);
this.registerCommandArgument(
"noColor",
"No colored output",
"Do not emit bytes that affect text color in any output.",
args.BooleanArgument,
"false",
);
this.registerCommandArgument(
"debugLogStream",
"Debug message logging stream (stdout | stderr)",
"Stream used for writing debug logs (stdout or stderr)",
args.StringArgument,
"stdout",
);
}
/**
* Return a list of registered arguments that should be displayed when help is emitted.
*/
protected getHelpArgs(): string[] {
return [];
}
/**
* Get a BasicCredentialHandler based on the command arguments:
* If username & password are passed in, use those.
* If token is passed in, use that.
* Else, check the authType - if it is "pat", prompt for a token
* If it is "basic", prompt for username and password.
*/
protected getCredentials(serviceUrl: string, useCredStore: boolean = true): Promise<BasicCredentialHandler> {
return Promise.all([
this.commandArgs.authType.val(),
this.commandArgs.token.val(true),
this.commandArgs.username.val(true),
this.commandArgs.password.val(true),
]).then(values => {
const [authType, token, username, password] = values;
if (username && password) {
return getBasicHandler(username, password);
} else {
if (token) {
return getBasicHandler("OAuth", token);
} else {
let getCredentialPromise;
if (useCredStore) {
getCredentialPromise = getCredentialStore("tfx").getCredential(serviceUrl, "allusers");
} else {
getCredentialPromise = Promise.reject("not using cred store.");
}
return getCredentialPromise
.then((credString: string) => {
if (credString.length <= 6) {
throw "Could not get credentials from credential store.";
}
if (credString.substr(0, 3) === "pat") {
return getBasicHandler("OAuth", credString.substr(4));
} else if (credString.substr(0, 5) === "basic") {
let rest = credString.substr(6);
let unpwDividerIndex = rest.indexOf(":");
let username = rest.substr(0, unpwDividerIndex);
let password = rest.substr(unpwDividerIndex + 1);
if (username && password) {
return getBasicHandler(username, password);
} else {
throw "Could not get credentials from credential store.";
}
}
})
.catch(() => {
if (authType.toLowerCase() === "pat") {
return this.commandArgs.token.val().then(token => {
return getBasicHandler("OAuth", token);
});
} else if (authType.toLowerCase() === "basic") {
return this.commandArgs.username.val().then(username => {
return this.commandArgs.password.val().then(password => {
return getBasicHandler(username, password);
});
});
} else {
throw new Error("Unsupported auth type. Currently, 'pat' and 'basic' auth are supported.");
}
});
}
}
});
}
public getWebApi(): Promise<WebApi> {
return this.commandArgs.serviceUrl.val().then(url => {
return this.getCredentials(url).then(handler => {
this.connection = new TfsConnection(url);
this.webApi = new WebApi(url, handler);
return this.webApi;
});
});
}
public run(main: (cmd?: command.TFXCommand) => Promise<any>, cmd?: command.TFXCommand): Promise<void> {
return main(cmd).then(result => {
return this.output(result).then(() => {
return this.dispose();
});
});
}
/**
* exec does some work and resolves to some kind of output. This method may
* log/trace during execution, but produces one single output in the end.
*/
protected abstract exec(): Promise<TResult>;
/**
* Should be called after exec. In here we will write settings to fs if necessary.
*/
public dispose(): Promise<void> {
let newToCache = {};
return this.commandArgs.save.val().then(shouldSave => {
if (shouldSave) {
let cacheKey =
path.resolve().replace("/.[]/g", "-") +
"." +
common.EXEC_PATH.slice(0, common.EXEC_PATH.length - 1).join("/");
let getValuePromises: Promise<void>[] = [];
Object.keys(this.commandArgs).forEach(arg => {
let argObj = <args.Argument<any>>this.commandArgs[arg];
if (!argObj.hasDefaultValue) {
let pr = argObj.val().then(value => {
// don't cache these 5 options.
if (["username", "password", "save", "token", "help"].indexOf(arg) < 0) {
_.set(newToCache, cacheKey + "." + arg, value);
}
});
getValuePromises.push(pr);
}
});
return Promise.all(getValuePromises).then<void>(() => {
return args.getOptionsCache().then(existingCache => {
// custom shallow-ish merge of cache properties.
let newInThisCommand = _.get(newToCache, cacheKey);
if (!_.get(existingCache, cacheKey)) {
_.set(existingCache, cacheKey, {});
}
if (newInThisCommand) {
Object.keys(newInThisCommand).forEach(key => {
_.set(existingCache, cacheKey + "." + key, newInThisCommand[key]);
});
new DiskCache("tfx").setItem(
"cache",
"command-options",
JSON.stringify(existingCache, null, 4).replace(/\n/g, eol),
);
}
});
});
} else {
return Promise.resolve<void>(null);
}
});
}
/**
* Gets help (as a string) for the given command
*/
public async getHelp(cmd: command.TFXCommand): Promise<string> {
const includeUndocumented = await this.commandArgs.includeUndocumented.val();
this.commandArgs.output.setValue("help");
let result = eol;
let continuedHierarchy: command.CommandHierarchy = cmd.commandHierarchy;
cmd.execPath.forEach(segment => {
continuedHierarchy = continuedHierarchy[segment];
});
if (continuedHierarchy === null) {
// Need help with a particular command
let singleArgData = (argName: string, maxArgLen: number) => {
// Lodash's kebab adds a dash between letters and numbers, so this is just a hack to avoid that.
let argKebab = argName === "json5" ? "json5" : _.kebabCase(argName);
const argObj = this.commandArgs[argName];
const shorthandArg = argObj.aliases.filter(a => a.length === 2 && a.substr(0, 1) === "-")[0];
if (shorthandArg) {
argKebab = `${argKebab}, ${shorthandArg}`;
}
if (argObj.undocumented && !includeUndocumented) {
return "";
}
return (
" --" +
argKebab +
" " +
repeatStr(" ", maxArgLen - argKebab.length) +
gray(argObj.description || argObj.friendlyName + ".") +
eol
);
};
let commandName = cmd.execPath[cmd.execPath.length - 1];
result +=
cyan("Syntax: ") +
eol +
cyan("tfx ") +
yellow(cmd.execPath.join(" ")) +
green(" --arg1 arg1val1 arg1val2[...]") +
gray(" --arg2 arg2val1 arg2val2[...]") +
eol +
eol;
return loader
.load(cmd.execPath, ["--service-url", "null"])
.then(tfCommand => {
result += cyan("Command: ") + commandName + eol;
result += tfCommand.description + eol + eol;
result += cyan("Arguments: ") + eol;
let uniqueArgs = this.getHelpArgs();
uniqueArgs = _.uniq(uniqueArgs);
let maxArgLen = uniqueArgs.map(a => _.kebabCase(a)).reduce((a, b) => Math.max(a, b.length), 0);
if (uniqueArgs.length === 0) {
result += "[No arguments for this command]" + eol;
}
uniqueArgs.forEach(arg => {
result += singleArgData(arg, maxArgLen);
});
if (this.serverCommand) {
result += eol + cyan("Global server command arguments:") + eol;
["authType", "username", "password", "token", "serviceUrl", "fiddler", "proxy"].forEach(arg => {
result += singleArgData(arg, 11);
});
}
result += eol + cyan("Global arguments:") + eol;
["help", "save", "noColor", "noPrompt", "output", "json", "traceLevel", "debugLogStream"].forEach(arg => {
result += singleArgData(arg, 9);
});
result +=
eol +
gray(
"To see more commands, type " +
resetColors("tfx " + cmd.execPath.slice(0, cmd.execPath.length - 1).join(" ") + " --help"),
);
})
.then(() => {
return result;
});
} else {
// Need help with a suite of commands
// There is a weird coloring bug when colors are nested, so we don't do that.
result +=
cyan("Available ") +
"commands" +
cyan(" and ") +
yellow("command groups") +
cyan(" in " + ["tfx"].concat(cmd.execPath).join(" / ") + ":") +
eol;
let commandDescriptionPromises: Promise<void>[] = [];
Object.keys(continuedHierarchy).forEach(command => {
if (command === "default") {
return;
}
let pr = loader.load(cmd.execPath.concat([command]), ["--service-url", "null"]).then(tfCommand => {
let coloredCommand = command;
if (continuedHierarchy[command] !== null) {
coloredCommand = yellow(command);
}
result += " - " + coloredCommand + gray(": " + tfCommand.description) + eol;
});
commandDescriptionPromises.push(pr);
});
return Promise.all(commandDescriptionPromises)
.then(() => {
result +=
eol +
eol +
gray("For help with an individual command, type ") +
resetColors("tfx " + cmd.execPath.join(" ") + " <command> --help") +
eol;
})
.then(() => {
return result;
});
}
}
/**
* Display a copyright banner.
*/
public showBanner(): Promise<void> {
return this.commandArgs.json
.val(true)
.then(useJson => {
if (useJson) {
this.commandArgs.output.setValue("json");
}
})
.then(() => {
return version.getTfxVersion().then(async semVer => {
const [outputType, traceLevel, debugLogStream] = await Promise.all([
this.commandArgs.output.val(),
this.commandArgs.traceLevel.val(),
this.commandArgs.debugLogStream.val(),
]);
switch (debugLogStream) {
case "stdout":
trace.debugLogStream = console.log;
break;
case "stderr":
trace.debugLogStream = console.error;
break;
default:
throw new Error("Parameter --debug-log-stream must have value 'stdout' or 'stderr'.");
}
switch (traceLevel && traceLevel.toLowerCase()) {
case "none":
trace.traceLevel = trace.TraceLevel.None;
break;
case "debug":
trace.traceLevel = trace.TraceLevel.Debug;
break;
case "info":
trace.traceLevel = trace.TraceLevel.Info;
break;
default:
trace.traceLevel = outputType === "friendly" ? trace.TraceLevel.Info : trace.TraceLevel.None;
}
trace.info(gray("TFS Cross Platform Command Line Interface v" + semVer.toString()));
trace.info(gray("Copyright Microsoft Corporation"));
});
});
}
/**
* Takes data and pipes it to the appropriate output mechanism
*/
public output(data: any): Promise<void> {
return this.commandArgs.output.val().then(outputDestination => {
switch (outputDestination.toLowerCase()) {
case "friendly":
this.friendlyOutput(data);
break;
case "json":
this.jsonOutput(data);
break;
case "help":
this.friendlyOutputConstant(data);
break;
case "clip":
case "clipboard":
let clipboardText = this.getClipboardOutput(data);
return clipboardy.write(clipboardText);
default:
return fsUtils.canWriteTo(path.resolve(outputDestination)).then(canWrite => {
if (canWrite) {
let fileContents = this.getFileOutput(data);
return promisify(writeFile)(outputDestination, fileContents);
} else {
throw new Error("Cannot write output to " + outputDestination);
}
});
}
return Promise.resolve<void>(null);
});
}
/**
* Given the output object, gets the string that is copied to the clipboard when
* clipboard output is requested.
*/
protected getClipboardOutput(data: any): string {
return this.getOutputString(data);
}
/**
* Given the output object, gets the string that is written to a destination
* file when a file name is given as the output destination
*/
protected getFileOutput(data: any): string {
return this.getOutputString(data);
}
private getOutputString(data: any): string {
let outputString = "";
try {
outputString = JSON.stringify(data, null, 4);
} catch (e) {
if (data && data.toString) {
outputString = data.toString();
} else {
outputString = data + "";
}
}
return outputString;
}
/**
* Gets a nicely formatted output string for friendly output
*/
protected friendlyOutput(data: any): void {
this.friendlyOutputConstant(data);
}
private friendlyOutputConstant(data: any): void {
if (typeof data === "string") {
console.log(data);
} else {
try {
console.log(JSON.stringify(data, null, 4));
} catch (e) {
console.log(data + "");
}
}
}
/**
* Gets a string of valid JSON when JSON output is requested.
* Probably no need to override this one.
*/
protected jsonOutput(data: any): void {
try {
console.log(stripColors(JSON.stringify(data, null, 4)));
} catch (e) {
throw new Error("Could not stringify JSON output.");
}
}
}
const originalConsoleLog = console.log.bind(console);
function logNoColors(...args: string[]) {
originalConsoleLog.apply(console, args.map(stripColors));
} | the_stack |
import { InputBlock as _InputBlock } from '@slack/types'
import { JSXSlackError } from '../../error'
import {
JSXSlack,
cleanMeta,
createComponent,
createElementInternal,
BuiltInComponent,
} from '../../jsx'
import { DistributedProps, coerceToInteger } from '../../utils'
import {
plainText,
inputDispatchActionConfig,
InputDispatchActionProps,
} from '../composition/utils'
import { PlainTextInput } from '../elements/PlainTextInput'
import {
ActionProps,
AutoFocusibleProps,
focusOnLoadFromProps,
} from '../elements/utils'
import { resolveTagName } from '../utils'
import { LayoutBlockProps } from './utils'
type InputBlock = _InputBlock & { dispatch_action?: boolean }
interface InputLayoutProps extends LayoutBlockProps {
children: JSXSlack.Node
/** The label string for the interactive element. */
label: string
/**
* By setting `true`, the input element will dispatch
* [`block_actions` payload](https://api.slack.com/reference/interaction-payloads/block-actions)
* when used this.
*/
dispatchAction?: boolean
/** Set a helpful text appears under the element. */
hint?: string
/** A HTML-compatible alias into `hint` prop. */
title?: string
/**
* Set whether any value must be filled when user confirms modal.
*
* @remarks
* HTML-compatible `required` prop means reversed `optional` field in Slack
* API. _Please notice jsx-slack's default `required: false` is different from
* Slack's default `optional: false`._
*/
required?: boolean
}
interface InputComponentBaseProps extends Omit<InputLayoutProps, 'children'> {
/**
* A string of unique identifier for the implicit parent `input` layout block.
*
* @remarks
* _This is only working in input components enabled by defining `label` prop._
*/
blockId?: string
/**
* By setting `true`, the input element will dispatch
* [`block_actions` payload](https://api.slack.com/reference/interaction-payloads/block-actions)
* when used this.
*
* @remarks
* _This is only working in input components enabled by defining `label` prop._
*/
dispatchAction?: boolean
/**
* Set `label` prop for the implicit parent `input` layout block, to display
* the label string.
*
* @remarks
* Please notice that this prop is **always required** in input components,
* and _**never** in interactive elements for `<Section>` and `<Actions>`._
*/
label: string
/**
* Set a helpful text appears under the element.
*
* @remarks
* _This is only working in input components enabled by defining `label` prop._
*/
hint?: string
/**
* Set whether any value must be filled when user confirms modal.
*
* @remarks
* _This is only working in input components enabled by defining `label` prop._
*
* HTML-compatible `required` prop means reversed `optional` field in Slack
* API. _Please notice jsx-slack's default `required: false` is different from
* Slack's default `optional: false`._
*/
required?: boolean
}
export interface InputTextProps
extends Omit<InputComponentBaseProps, 'dispatchAction'>,
ActionProps,
AutoFocusibleProps,
InputDispatchActionProps {
children?: never
/**
* Select input type from `text`, `hidden`, and `submit`.
*
* The default type is `text`, for the input layout block with single-text
* element.
*/
type?: 'text'
/**
* Set the maximum number of characters user can enter into the text element.
*/
maxLength?: number
/**
* Set the minimum number of characters user can enter into the text element.
*/
minLength?: number
/**
* The placeholder text shown in empty text field.
*
* Please notice the text input element cannot use emoji shorthand unlike the
* other many plain text fields.
*/
placeholder?: string
/**
* The _initial_ value of the input element.
*
* This prop would rather similar to `defaultValue` than `value` in React. A
* defined value would be filled to the element only when the view was opened.
* [`views.update`](https://api.slack.com/methods/views.update) cannot
* update the text changed by user even if changed this prop.
*/
value?: string
}
interface InputHiddenProps {
children?: never
type: 'hidden'
/**
* @doc-input-hidden
* A key of private metadata JSON to store.
*/
name: string
/**
* @doc-input-hidden
* A value of private metadata JSON to store.
*
* It must be able to serializable into JSON (except while using custom
* transformer in the container).
* */
value: any
}
interface InputSubmitProps {
children?: never
type: 'submit'
/**
* @doc-input-submit
* The label string of submit button for the modal.
*
* If the parent `<Modal>` has defined `submit` prop, this value will ignore.
*/
value: string
}
export type InputComponentProps<
P extends {}, // eslint-disable-line @typescript-eslint/ban-types
T extends {} = {} // eslint-disable-line @typescript-eslint/ban-types
> = DistributedProps<P | (P & InputComponentBaseProps & T)>
export type InputProps = DistributedProps<
InputLayoutProps | InputTextProps | InputHiddenProps | InputSubmitProps
>
export const knownInputs = [
'channels_select',
'checkboxes',
'conversations_select',
'datepicker',
'external_select',
'multi_channels_select',
'multi_conversations_select',
'multi_external_select',
'multi_static_select',
'multi_users_select',
'plain_text_input',
'radio_buttons',
'static_select',
'timepicker',
'users_select',
]
const ElementValidator = ({ element, from }): any => {
if (typeof element !== 'object')
throw new JSXSlackError(
`${from} has invalid value as an element of input layout block.`
)
if (!knownInputs.includes(element.type)) {
const generator = resolveTagName(element)
throw new JSXSlackError(
`${from} has detected an invalid type as the element of input layout block: "${
element.type
}"${generator ? ` (Provided by ${generator})` : ''}`,
element
)
}
return cleanMeta(element)
}
export const wrapInInput = <T extends object>(
obj: T,
props: Omit<Partial<InputLayoutProps>, 'children'>,
generatedFrom?: BuiltInComponent<any>
): T | InputBlock => {
// Require to pass through the element into JSX for normalize as JSON certainly
const element: any = cleanMeta(
<ElementValidator
element={obj}
from={
generatedFrom
? `<${generatedFrom.$$jsxslackComponent.name}>`
: 'Input layout block'
}
/>
)
if (props.label) {
const hint = props.hint || props.title
return {
type: 'input',
block_id: props.blockId || props.id,
label: plainText(props.label),
hint: hint ? plainText(hint) : undefined,
optional: !props.required,
dispatch_action:
props.dispatchAction !== undefined ? !!props.dispatchAction : undefined,
element,
}
}
return obj
}
/**
* `<Input>` has various usages: Input component for single text element,
* helpers for the container, and Slack-style
* [`input` layout block](https://api.slack.com/reference/messaging/blocks#input).
*
* It should place on immidiate children of container component.
*
* ---
*
* ### Input component for single-text
*
* `<Input label="..." />` means the input component for single text element and
* will render `input` layout block containing with single-line plain text
* input.
*
* It has an interface very similar to `<input>` HTML element, but an important
* difference is to require defining `label` prop.
*
* ```jsx
* <Modal title="My App">
* <Input label="Title" name="title" maxLength={80} required />
* </Modal>
* ```
*
* ---
*
* ### Store hidden values to modal and home tab
*
* `<Input type="hidden" />` can assign hidden values for the private metadata
* JSON of `<Modal>` and `<Home>` with a familiar way in HTML form.
*
* ```jsx
* <Modal title="modal">
* <Input type="hidden" name="foo" value="bar" />
* <Input type="hidden" name="userId" value={123} />
* <Input type="hidden" name="data" value={[{ hidden: 'value' }]} />
* </Modal>
* ```
*
* Take care that the maximum length validation by Slack will still apply for
* stringified JSON. The value like string and array that cannot predict the
* length might over the limit of JSON string length easily (3000 characters).
*
* The best practice is only storing the value of a pointer to reference data
* stored elsewhere. It's better not to store complex data as hidden value
* directly.
*
* When the parent `<Modal>` or `<Home>` has assigned `privateMetadata` prop,
* hidden values may override by assigned string or manipulate through the
* custom transformer.
*
* ---
*
* ### Set the label of submit button for modal
*
* `<Input type="submit" />` can set the label of submit button for the current
* modal. It's meaning just an alias into `submit` prop of `<Modal>`, but JSX
* looks like more natural HTML form.
*
* ```jsx
* <Modal title="Example">
* <Input name="name" label="Name" />
* <Input type="submit" value="Send" />
* </Modal>
* ```
* ---
*
* ### Slack-style `input` layout block
*
* `<Input>` also can render
* [`input` layout block](https://api.slack.com/reference/messaging/blocks#input)
* as same usage as other components for Slack layout block. Please place one of
* the available interactive component as a child.
*
* ```jsx
* <Modal title="Register" submit="OK" close="Cancel">
* <Input label="User" title="Please select user." required>
* <UsersSelect placeholder="Choose user..." />
* </Input>
* </Modal>
* ```
*
* #### Available interactive components
*
* - `<Select>`
* - `<ExternalSelect>`
* - `<UsersSelect>`
* - `<ConversationsSelect>` *
* - `<ChannelsSelect>` *
* - `<DatePicker>`
* - `<TimePicker>`
* - `<CheckboxGroup>`
* - `<RadioButtonGroup>`
*
* __*__: Some components have unique properties only for input components. You
* cannot define them to the interactive component wrapped in `<Input>` layout
* block because TypeScript would throw error while compile.
*
* **NOTE**: _We usually recommend to use input components instead of using
* `<Input>` layout block._ This usage is provided for user that want templating
* with Slack API style rather than HTML style.
*
* @return The partial JSON for `input` layout block or internal JSX element
*/
export const Input: BuiltInComponent<InputProps> = createComponent<
InputProps,
InputBlock | {} // eslint-disable-line @typescript-eslint/ban-types
>('Input', (props) => {
if (props.type === 'hidden' || props.type === 'submit') return {}
return wrapInInput(
props.children ||
cleanMeta(
<PlainTextInput
actionId={props.actionId || props.name}
initialValue={props.value}
maxLength={coerceToInteger(props.maxLength)}
minLength={coerceToInteger(props.minLength)}
placeholder={props.placeholder}
dispatchActionConfig={inputDispatchActionConfig(props)}
focusOnLoad={focusOnLoadFromProps(props)}
/>
),
{
...props,
dispatchAction:
props.dispatchAction === undefined ? undefined : !!props.dispatchAction,
},
Input
)
}) | the_stack |
import React from "react";
import { safe } from "../utils";
import { HostApi } from "../webview-api";
import { LocateRepoButton } from "./LocateRepoButton";
import {
ApplyMarkerRequestType,
CompareMarkerRequestType,
EditorSelectRangeRequestType,
EditorHighlightRangeRequestType
} from "../ipc/webview.protocol";
import {
Capabilities,
CodemarkPlus,
DidChangeDocumentMarkersNotificationType,
GetCodemarkRangeRequestType,
TelemetryRequestType
} from "@codestream/protocols/agent";
import { injectIntl, WrappedComponentProps } from "react-intl";
import { CodeStreamState } from "../store";
import { connect } from "react-redux";
import { getById } from "../store/repos/reducer";
import Icon from "./Icon";
import { CSMarker } from "@codestream/protocols/api";
import { getVisibleRanges } from "../store/editorContext/reducer";
import { getDocumentFromMarker, highlightRange } from "./api-functions";
import { Marker } from "./Marker";
import { debounce } from "lodash-es";
interface State {
hasDiff: boolean;
currentContent?: string;
currentBranch?: string;
currentCommitHash?: string;
diff?: string;
warning?: string;
textDocumentUri: string;
startLine: number;
endLine: number;
scrollingCodeBlock: boolean;
expandCodeBlock: boolean;
}
interface ConnectedProps {
repoName: string;
textEditorUri: string;
firstVisibleLine?: number;
lastVisibleLine?: number;
editorHasFocus: boolean;
jumpToMarker?: boolean;
jumpToMarkerId?: string;
currentReviewId?: string;
}
type IntlProps = WrappedComponentProps<"intl">;
interface InheritedProps {
codemark: CodemarkPlus;
marker: CSMarker;
markerIndex: number;
numMarkers?: number;
capabilities: Capabilities;
isAuthor: boolean;
alwaysRenderCode?: boolean;
jumpToMarker?: boolean;
jumpToMarkerId?: string;
selected: boolean;
disableDiffCheck?: boolean;
disableHighlightOnHover?: boolean;
noMargin?: boolean;
}
type Props = InheritedProps & ConnectedProps & IntlProps;
class MarkerActions extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = {
hasDiff: false,
textDocumentUri: "",
startLine: 0,
endLine: 0,
expandCodeBlock: false,
scrollingCodeBlock: false
};
this._codeBlockDiv = null;
}
private _disposables: { dispose(): void }[] = [];
private _codeBlockDiv: HTMLPreElement | null;
private _mounted: boolean = false;
private _highlightDisposable?: { dispose(): void };
private _jumped = false;
private _isJumping = false;
private _getDocumentFromMarkerDebounced = debounce(getDocumentFromMarker, 1000, {
leading: true
});
getDocumentFromMarkerDebounced(markerId: string, source: string) {
return this._getDocumentFromMarkerDebounced(markerId, source);
}
componentDidMount() {
this._mounted = true;
if (this.props.jumpToMarker) {
this.jump(this.props.marker).then(success => {
this._jumped = true;
if (success) this.ensureMarkerInView();
this.openCodemark().then(_ => {
if (this.props.selected) {
this.startCheckingDiffs();
}
});
});
} else if (this.props.selected) {
this.startCheckingDiffs();
}
if (this._codeBlockDiv && this._codeBlockDiv.scrollHeight > this._codeBlockDiv.offsetHeight)
this.setState({ scrollingCodeBlock: true });
}
// why do we use this? jump has the same arg as componentDidMount
componentDidUpdate(prevProps, prevState) {
if (!this.props.marker || !this.props.jumpToMarker) {
this._jumped = false;
return;
}
if (!this._jumped) {
if (this._isJumping) {
return;
}
this._isJumping = true;
this.jump(this.props.marker).then(success => {
this._jumped = true;
this._isJumping = false;
if (success) this.ensureMarkerInView();
});
}
}
componentWillUnmount() {
this._mounted = false;
this._disposables.forEach(d => d.dispose());
}
private startCheckingDiffs() {
if (this.props.disableDiffCheck) return;
if (!this._mounted) return;
this.checkDiffs(false);
this._disposables.push(
HostApi.instance.on(DidChangeDocumentMarkersNotificationType, ({ textDocument }) => {
if (this.props.textEditorUri === textDocument.uri) {
this.checkDiffs(false);
}
})
);
}
async openCodemark() {
const { codemark, marker } = this.props;
// when would his be true?
if (codemark == null || marker == null) return;
try {
if (marker.repoId) {
const response = await this.getDocumentFromMarkerDebounced(marker.id, "openCodemark");
if (response) {
const { success } = await HostApi.instance.send(EditorSelectRangeRequestType, {
uri: response.textDocument.uri,
// Ensure we put the cursor at the right line (don't actually select the whole range)
selection: {
start: response.range.start,
end: response.range.start,
cursor: response.range.start
},
preserveFocus: true
});
this.setState({
warning: success ? undefined : "FILE_NOT_FOUND",
textDocumentUri: response.textDocument.uri
});
if (success) {
this.ensureMarkerInView();
this._toggleCodeHighlight(true);
}
} else {
// assumption based on GetDocumentFromMarkerRequestType api requiring the workspace to be available
this.setState({ warning: "REPO_NOT_IN_WORKSPACE" });
}
} else this.setState({ warning: "NO_REMOTE" });
} catch (error) {}
}
ensureMarkerInView() {
if (!this.props.codemark || !this.props.jumpToMarker || !this._codeBlockDiv) return;
setTimeout(() => {
if (this._codeBlockDiv) {
this._codeBlockDiv.scrollIntoView({
behavior: "smooth"
});
}
}, 50);
}
async checkDiffs(jump: boolean) {
const { codemark, marker, jumpToMarker } = this.props;
if (codemark == null || marker == null) return;
try {
const response = await HostApi.instance.send(GetCodemarkRangeRequestType, {
codemarkId: codemark.id,
markerId: marker.id
});
this.setState({
hasDiff: response.diff !== undefined,
currentContent: response.currentContent,
currentBranch: response.currentBranch,
diff: response.diff
});
} catch (error) {}
try {
if (marker.repoId) {
const response = await this.getDocumentFromMarkerDebounced(marker.id, "checkDiffs");
if (response) {
if (jumpToMarker && jump) {
const { success } = await HostApi.instance.send(EditorSelectRangeRequestType, {
uri: response.textDocument.uri,
// Ensure we put the cursor at the right line (don't actually select the whole range)
selection: {
start: response.range.start,
end: response.range.start,
cursor: response.range.start
},
preserveFocus: true
});
this.setState({ warning: success ? undefined : "FILE_NOT_FOUND" });
} else {
// this.setState({ warning: undefined });
}
} else {
// assumption based on GetDocumentFromMarkerRequestType api requiring the workspace to be available
this.setState({ warning: "REPO_NOT_IN_WORKSPACE" });
}
} else this.setState({ warning: "NO_REMOTE" });
} catch (error) {}
}
handleClickJump = async event => {
event.preventDefault();
HostApi.instance.send(TelemetryRequestType, {
eventName: "Jumped To Code",
properties: {}
});
await this.jump(this.props.marker);
};
jump = async (marker: CSMarker) => {
try {
const response = await this.getDocumentFromMarkerDebounced(marker.id, "jump");
if (response) {
const { success } = await HostApi.instance.send(EditorSelectRangeRequestType, {
uri: response.textDocument.uri,
// Ensure we put the cursor at the right line (don't actually select the whole range)
selection: {
start: response.range.start,
end: response.range.start,
cursor: response.range.start
},
preserveFocus: true
});
if (success) {
highlightRange({
range: response.range,
uri: response.textDocument.uri,
highlight: true
});
this._disposables.push({
dispose() {
highlightRange({
range: response.range,
uri: response.textDocument.uri,
highlight: false
});
}
});
}
this.setState({
textDocumentUri: response.textDocument.uri,
warning: success ? undefined : "FILE_NOT_FOUND"
});
return success;
} else {
// assumption based on GetDocumentFromMarkerRequestType api requiring the workspace to be available
this.setState({
warning: "REPO_NOT_IN_WORKSPACE"
});
}
} catch (ex) {
console.error(ex);
}
return false;
};
handleClickApplyPatch = async (event, marker) => {
event.preventDefault();
HostApi.instance.send(TelemetryRequestType, {
eventName: "Apply",
properties: { "Author?": this.props.isAuthor }
});
await this.jump(marker);
HostApi.instance.send(ApplyMarkerRequestType, { marker });
};
handleClickCompare = (event, marker) => {
event.preventDefault();
event.stopPropagation();
HostApi.instance.send(TelemetryRequestType, {
eventName: "Compare",
properties: { "Author?": this.props.isAuthor }
});
HostApi.instance.send(CompareMarkerRequestType, { marker });
};
handleClickOpenRevision = (event, marker) => {
event.preventDefault();
// HostApi.instance.send(OpenRevisionMarkerRequestType, { marker });
};
getWarningMessage() {
const { intl } = this.props;
switch (this.state.warning) {
case "NO_REMOTE": {
const message = intl.formatMessage({
id: "codeBlock.noRemote",
defaultMessage: "This code does not have a remote URL associated with it."
});
const learnMore = intl.formatMessage({ id: "learnMore" });
return (
<span>
{message}{" "}
<a href="https://docs.codestream.com/userguide/faq/git-issues/">{learnMore}</a>
</span>
);
}
case "FILE_NOT_FOUND": {
return (
<span>
{intl.formatMessage({
id: "codeBlock.fileNotFound",
defaultMessage: "You don’t currently have this file in your repo."
})}
</span>
);
}
case "REPO_NOT_IN_WORKSPACE": {
return (
<span>
<span>
{intl.formatMessage(
{
id: "codeBlock.repoMissing",
defaultMessage: "You don’t currently have the {repoName} repo open."
},
{ repoName: this.props.repoName }
)}
<LocateRepoButton
repoId={
this.props.codemark &&
this.props.codemark.markers &&
this.props.codemark.markers[0]
? this.props.codemark.markers[0].repoId
: undefined
}
repoName={this.props.repoName}
callback={async success => {
this.setState({ warning: success ? undefined : "REPO_NOT_IN_WORKSPACE" });
if (success) {
this.openCodemark();
}
}}
></LocateRepoButton>
</span>
</span>
);
}
case "UNKNOWN_LOCATION":
default: {
return (
<span>
{intl.formatMessage({
id: "codeBlock.locationUnknown",
defaultMessage: "Unknown code block location."
})}
</span>
);
}
}
}
render() {
const { codemark, marker, selected, firstVisibleLine = 0, lastVisibleLine = 0 } = this.props;
const { startLine, endLine } = this.state;
if (codemark == null || marker == null) return null;
let {
codemarkCompare: canCompare = false,
codemarkApply: canApply = false,
codemarkOpenRevision: canOpenRevision = false
} = this.props.capabilities;
let ref;
if (marker.commitHashWhenCreated) {
ref = marker.commitHashWhenCreated.substr(0, 8);
if ((canCompare || canApply) && !this.state.hasDiff) {
canCompare = false;
canApply = false;
}
} else {
ref = "";
canCompare = false;
canApply = false;
canOpenRevision = false;
}
const canJump =
true ||
this.state.textDocumentUri !== this.props.textEditorUri ||
endLine < firstVisibleLine ||
startLine > lastVisibleLine;
// we can't check entirelyDeleted because we don't have a DocumentMarker but rather a CSMarker
// let entirelyDeleted = false;
// if (marker && marker.location && marker.location.meta && marker.location.meta.entirelyDeleted)
// entirelyDeleted = true;
return (
<>
{(this.props.alwaysRenderCode || this.state.hasDiff || this.state.warning || canJump) &&
this.renderCodeblock(marker)}
{/*(canCompare || canApply || canOpenRevision || canJump) && selected && !this.state.warning && (
<div
className={cx("button-spread", { "no-padding": this.props.noMargin })}
id={codemark.id}
key="left"
>
{this.state.hasDiff && (
<div className="left">
<Icon name="alert" /> This code has changed
</div>
)}
<div className="right" key="right">
{canApply && (
<Tooltip title="Apply patch to current buffer" placement="bottomRight" delay={1}>
<div
className="codemark-actions-button"
onClick={e => this.handleClickApplyPatch(e, marker)}
>
Apply
</div>
</Tooltip>
)}
{canCompare && (
<Tooltip title="Compare current code to original" placement="bottomRight" delay={1}>
<div
className="codemark-actions-button"
onClick={e => this.handleClickCompare(e, marker)}
>
Compare
</div>
</Tooltip>
) }
{canOpenRevision && (
<a
id="open-revision-button"
className="control-button"
tabIndex={4}
onClick={e => this.handleClickOpenRevision(e, marker)}
>
Open {ref}
</a>
)}
</div>
</div>
)*/}
</>
);
}
toggleExpandCodeBlock = () => {
this.setState({ expandCodeBlock: !this.state.expandCodeBlock });
};
private _toggleCodeHighlight = (highlight: boolean) => {
if (!this.props.selected) return;
// if we're looking at a review, don't try to highlight the code.
// the logic about state.textDocumentUri assumes a traditional
// codemark which has been clicked on, so too much breaks from a UI
// perspective, for little gain.
// https://trello.com/c/Q0aNjRVh/3717-prevent-vsc-from-switching-to-file-when-its-not-open-in-a-separate-pane
if (this.props.currentReviewId) return;
// there are cases we know that we don't want to highlight on
// hover, for example in the activity feed
if (this.props.disableHighlightOnHover) return;
if (!highlight && this._highlightDisposable) {
this._highlightDisposable.dispose();
this._highlightDisposable = undefined;
return;
}
if (this.state.textDocumentUri === this.props.textEditorUri) {
this.getDocumentFromMarkerDebounced(this.props.marker.id, "_toggleCodeHighlight").then(
info => {
if (info) {
HostApi.instance.send(EditorHighlightRangeRequestType, {
uri: info.textDocument.uri,
range: info.range,
highlight
});
this._highlightDisposable = {
dispose() {
HostApi.instance.send(EditorHighlightRangeRequestType, {
uri: info.textDocument.uri,
range: info.range,
highlight: false
});
}
};
}
}
);
}
};
renderCodeblock(marker) {
const { scrollingCodeBlock, expandCodeBlock, warning, hasDiff, currentContent } = this.state;
if (marker === undefined) return;
const sideMargin = this.props.noMargin ? "0" : "10px";
return (
<div
className={`related${warning ? "" : " clickable-marker"}`}
style={{
padding: "0",
marginBottom: "20px",
marginTop: "20px",
marginLeft: sideMargin,
marginRight: sideMargin,
position: "relative"
}}
onMouseEnter={e => {
e.preventDefault();
this._toggleCodeHighlight(true);
}}
onMouseLeave={e => {
e.preventDefault();
this._toggleCodeHighlight(false);
}}
onClick={e => !warning && this.handleClickJump(e)}
>
<Marker
marker={marker}
hasDiff={hasDiff && !warning}
currentContent={currentContent}
diff={this.state.diff}
/>
{warning && (
<div className="repo-warning">
<Icon name="alert" /> {this.getWarningMessage()}
</div>
)}
{!warning && (
<div className="code-buttons">
{scrollingCodeBlock && (
<Icon
title={expandCodeBlock ? "Collapse this code block" : "Expand this code block"}
placement="bottomRight"
name={expandCodeBlock ? "fold" : "unfold"}
className="clickable"
onClick={this.toggleExpandCodeBlock}
/>
)}
<Icon
title={"Jump to this range in " + marker.file}
placement="bottomRight"
name="link-external"
className="clickable"
onClick={e => this.handleClickJump(e)}
/>
</div>
)}
</div>
);
}
}
const mapStateToProps = (state: CodeStreamState, props: InheritedProps) => {
const { editorContext, context } = state;
//console.log(ownState);
const textEditorVisibleRanges = getVisibleRanges(editorContext);
const numVisibleRanges = textEditorVisibleRanges.length;
let lastVisibleLine = 1;
let firstVisibleLine = 1;
if (numVisibleRanges > 0) {
const lastVisibleRange = textEditorVisibleRanges[numVisibleRanges - 1];
lastVisibleLine = lastVisibleRange!.end.line;
firstVisibleLine = textEditorVisibleRanges[0].start.line;
}
const repoName = safe(() => getById(state.repos, props.marker.repoId).name) || "";
return {
repoName,
// fileNameToFilterFor: editorContext.activeFile,
textEditorUri: editorContext.textEditorUri || "",
firstVisibleLine,
lastVisibleLine,
editorHasFocus: context.hasFocus,
currentReviewId: state.context.currentReviewId
};
};
export default connect(mapStateToProps)(injectIntl(MarkerActions)); | the_stack |
declare class TKAlert extends NSObject implements UIGestureRecognizerDelegate {
static alloc(): TKAlert; // inherited from NSObject
static new(): TKAlert; // inherited from NSObject
readonly actions: NSArray<TKAlertAction>;
actionsLayout: TKAlertActionsLayout;
readonly alertView: TKAlertView;
allowParallaxEffect: boolean;
animationDuration: number;
attributedMessage: NSAttributedString;
attributedTitle: NSAttributedString;
readonly buttonsView: TKAlertButtonsView;
readonly contentView: TKAlertContentView;
customFrame: CGRect;
delegate: TKAlertDelegate;
dismissMode: TKAlertDismissMode;
dismissTimeout: number;
readonly headerView: TKAlertContentView;
message: string;
readonly style: TKAlertStyle;
swipeDismissDirection: TKAlertSwipeDismissDirection;
tintColor: UIColor;
title: string;
visible: 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
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
actionAtIndex(index: number): TKAlertAction;
addAction(action: TKAlertAction): void;
addActionWithTitleHandler(title: string, handler: (p1: TKAlert, p2: TKAlertAction) => boolean): TKAlertAction;
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
dismiss(animated: boolean): void;
gestureRecognizerShouldBeRequiredToFailByGestureRecognizer(gestureRecognizer: UIGestureRecognizer, otherGestureRecognizer: UIGestureRecognizer): boolean;
gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer): boolean;
gestureRecognizerShouldReceivePress(gestureRecognizer: UIGestureRecognizer, press: UIPress): boolean;
gestureRecognizerShouldReceiveTouch(gestureRecognizer: UIGestureRecognizer, touch: UITouch): boolean;
gestureRecognizerShouldRecognizeSimultaneouslyWithGestureRecognizer(gestureRecognizer: UIGestureRecognizer, otherGestureRecognizer: UIGestureRecognizer): boolean;
gestureRecognizerShouldRequireFailureOfGestureRecognizer(gestureRecognizer: UIGestureRecognizer, otherGestureRecognizer: UIGestureRecognizer): boolean;
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;
removeAction(action: TKAlertAction): void;
removeActionAtIndex(index: number): void;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
self(): this;
shake(): void;
show(animated: boolean): void;
}
declare class TKAlertAction extends NSObject {
static actionWithTitleHandler(title: string, handler: (p1: TKAlert, p2: TKAlertAction) => boolean): TKAlertAction;
static alloc(): TKAlertAction; // inherited from NSObject
static new(): TKAlertAction; // inherited from NSObject
backgroundColor: UIColor;
cornerRadius: number;
font: UIFont;
handler: (p1: TKAlert, p2: TKAlertAction) => boolean;
tag: number;
title: string;
titleColor: UIColor;
constructor(o: { title: string; handler: (p1: TKAlert, p2: TKAlertAction) => boolean; });
initWithTitleHandler(title: string, handler: (p1: TKAlert, p2: TKAlertAction) => boolean): this;
}
declare const enum TKAlertActionsLayout {
Horizontal = 0,
Vertical = 1
}
declare const enum TKAlertAnimation {
Scale = 0,
Fade = 1,
SlideFromLeft = 2,
SlideFromTop = 3,
SlideFromRight = 4,
SlideFromBottom = 5
}
declare const enum TKAlertBackgroundStyle {
Blur = 0,
Dim = 1,
None = 2
}
declare class TKAlertButtonsView extends TKView {
static alloc(): TKAlertButtonsView; // inherited from NSObject
static appearance(): TKAlertButtonsView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKAlertButtonsView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKAlertButtonsView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKAlertButtonsView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKAlertButtonsView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKAlertButtonsView; // inherited from UIAppearance
static new(): TKAlertButtonsView; // inherited from NSObject
}
declare class TKAlertContentView extends TKView {
static alloc(): TKAlertContentView; // inherited from NSObject
static appearance(): TKAlertContentView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKAlertContentView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKAlertContentView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKAlertContentView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKAlertContentView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKAlertContentView; // inherited from UIAppearance
static new(): TKAlertContentView; // inherited from NSObject
alert: TKAlert;
readonly imageView: UIImageView;
readonly textLabel: UILabel;
}
interface TKAlertDelegate extends NSObjectProtocol {
alertButtonForAction?(alert: TKAlert, action: TKAlertAction): UIButton;
alertDidDismiss?(alert: TKAlert): void;
alertDidDismissWithAction?(alert: TKAlert, action: TKAlertAction): void;
alertDidShow?(alert: TKAlert): void;
alertWillDismiss?(alert: TKAlert): void;
alertWillShow?(alert: TKAlert): void;
}
declare var TKAlertDelegate: {
prototype: TKAlertDelegate;
};
declare const enum TKAlertDismissMode {
None = 0,
Tap = 1,
Swipe = 2
}
declare class TKAlertStyle extends TKStyleNode {
static alloc(): TKAlertStyle; // inherited from NSObject
static new(): TKAlertStyle; // inherited from NSObject
backgroundColor: UIColor;
backgroundDimAlpha: number;
backgroundStyle: TKAlertBackgroundStyle;
backgroundTintColor: UIColor;
buttonHeight: number;
buttonSpacing: number;
buttonsInset: UIEdgeInsets;
centerFrame: boolean;
contentHeight: number;
contentInset: UIEdgeInsets;
contentSeparatorWidth: number;
cornerRadius: number;
dismissAnimation: TKAlertAnimation;
headerHeight: number;
maxWidth: number;
messageColor: UIColor;
showAnimation: TKAlertAnimation;
titleColor: UIColor;
titleSeparatorWidth: number;
}
declare const enum TKAlertSwipeDismissDirection {
Horizontal = 0,
Vertical = 1
}
declare class TKAlertView extends TKView {
static alloc(): TKAlertView; // inherited from NSObject
static appearance(): TKAlertView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKAlertView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKAlertView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKAlertView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKAlertView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKAlertView; // inherited from UIAppearance
static new(): TKAlertView; // inherited from NSObject
alert: TKAlert;
readonly buttonsView: TKAlertButtonsView;
readonly contentView: TKAlertContentView;
readonly headerView: TKAlertContentView;
}
declare const enum TKAutoCompleteCompletionMode {
StartsWith = 0,
Contains = 1
}
declare class TKAutoCompleteController extends UIViewController {
static alloc(): TKAutoCompleteController; // inherited from NSObject
static new(): TKAutoCompleteController; // inherited from NSObject
autocomplete: TKAutoCompleteTextView;
}
interface TKAutoCompleteDataSource extends NSObjectProtocol {
autoCompleteCompletionForPrefix?(autocomplete: TKAutoCompleteTextView, prefix: string): NSArray<TKAutoCompleteToken>;
autoCompleteCompletionsForString?(autocomplete: TKAutoCompleteTextView, input: string): void;
}
declare var TKAutoCompleteDataSource: {
prototype: TKAutoCompleteDataSource;
};
interface TKAutoCompleteDelegate extends NSObjectProtocol {
autoCompleteDidAddToken?(autocomplete: TKAutoCompleteTextView, token: TKAutoCompleteToken): void;
autoCompleteDidAutoComplete?(autocomplete: TKAutoCompleteTextView, completion: string): void;
autoCompleteDidRemoveToken?(autocomplete: TKAutoCompleteTextView, token: TKAutoCompleteToken): void;
autoCompleteDidSelectToken?(autocomplete: TKAutoCompleteTextView, token: TKAutoCompleteToken): void;
autoCompleteDidStartEditing?(autocomplete: TKAutoCompleteTextView): void;
autoCompleteShouldAddToken?(autocomplete: TKAutoCompleteTextView, token: TKAutoCompleteToken): boolean;
autoCompleteShouldRemoveToken?(autocomplete: TKAutoCompleteTextView, token: TKAutoCompleteToken): boolean;
autoCompleteSuggestionListUpdated?(autocomplete: TKAutoCompleteTextView, suggestionList: NSArray<TKAutoCompleteToken>): void;
autoCompleteViewForToken?(autocomplete: TKAutoCompleteTextView, token: TKAutoCompleteToken): TKAutoCompleteTokenView;
autoCompleteWillShowSuggestionList?(autocomplete: TKAutoCompleteTextView, suggestionList: NSArray<TKAutoCompleteToken>): void;
}
declare var TKAutoCompleteDelegate: {
prototype: TKAutoCompleteDelegate;
};
declare const enum TKAutoCompleteDisplayMode {
Plain = 0,
Tokens = 1
}
declare const enum TKAutoCompleteLayoutMode {
Horizontal = 0,
Wrap = 1
}
declare const enum TKAutoCompleteSuggestMode {
Suggest = 0,
Append = 1,
SuggestAppend = 2
}
interface TKAutoCompleteSuggestViewDelegate extends NSObjectProtocol {
selectedItem: TKAutoCompleteToken;
hide(): void;
populateWithItems(items: NSArray<TKAutoCompleteToken>): void;
reloadSuggestions(): void;
shouldAlwaysHideSuggestionView(): boolean;
show(): void;
}
declare var TKAutoCompleteSuggestViewDelegate: {
prototype: TKAutoCompleteSuggestViewDelegate;
};
declare class TKAutoCompleteSuggestionCell extends TKListViewCell {
static alloc(): TKAutoCompleteSuggestionCell; // inherited from NSObject
static appearance(): TKAutoCompleteSuggestionCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKAutoCompleteSuggestionCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKAutoCompleteSuggestionCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKAutoCompleteSuggestionCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKAutoCompleteSuggestionCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKAutoCompleteSuggestionCell; // inherited from UIAppearance
static new(): TKAutoCompleteSuggestionCell; // inherited from NSObject
}
declare class TKAutoCompleteTextView extends TKView {
static alloc(): TKAutoCompleteTextView; // inherited from NSObject
static appearance(): TKAutoCompleteTextView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKAutoCompleteTextView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKAutoCompleteTextView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKAutoCompleteTextView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKAutoCompleteTextView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKAutoCompleteTextView; // inherited from UIAppearance
static new(): TKAutoCompleteTextView; // inherited from NSObject
allowCustomTokens: boolean;
allowTokenHighlighting: boolean;
autocompleteInset: number;
readonly closeButton: UIButton;
readonly contentView: TKView;
readonly currentWrapHeight: number;
dataSource: TKAutoCompleteDataSource;
delegate: TKAutoCompleteDelegate;
displayMode: TKAutoCompleteDisplayMode;
readonly imageView: UIImageView;
layoutMode: TKAutoCompleteLayoutMode;
maximumTokensCount: number;
maximumWrapHeight: number;
minimumCharactersToSearch: number;
readonly noResultsLabel: UILabel;
readOnly: boolean;
showAllItemsInitially: boolean;
suggestMode: TKAutoCompleteSuggestMode;
suggestionView: UIView;
suggestionViewHeight: number;
suggestionViewOutOfFrame: boolean;
readonly textField: UITextField;
readonly titleLabel: UILabel;
tokenInset: number;
tokeninzingSymbols: NSArray<string>;
addToken(token: TKAutoCompleteToken): void;
completeSuggestionViewPopulation(suggestions: NSArray<any>): void;
insertTokenAtIndex(token: TKAutoCompleteToken, index: number): void;
removeAllTokens(): void;
removeToken(token: TKAutoCompleteToken): void;
removeTokenAtIndex(index: number): void;
resetAutocomplete(): void;
resetAutocompleteState(): void;
tokenAtIndex(index: number): TKAutoCompleteToken;
tokens(): NSArray<any>;
}
declare class TKAutoCompleteToken extends NSObject {
static alloc(): TKAutoCompleteToken; // inherited from NSObject
static new(): TKAutoCompleteToken; // inherited from NSObject
attributedText: NSAttributedString;
image: UIImage;
text: string;
constructor(o: { text: string; });
initWithText(text: string): this;
}
declare class TKAutoCompleteTokenRemoveButton extends UIButton {
static alloc(): TKAutoCompleteTokenRemoveButton; // inherited from NSObject
static appearance(): TKAutoCompleteTokenRemoveButton; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKAutoCompleteTokenRemoveButton; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKAutoCompleteTokenRemoveButton; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKAutoCompleteTokenRemoveButton; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKAutoCompleteTokenRemoveButton; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKAutoCompleteTokenRemoveButton; // inherited from UIAppearance
static buttonWithType(buttonType: UIButtonType): TKAutoCompleteTokenRemoveButton; // inherited from UIButton
static new(): TKAutoCompleteTokenRemoveButton; // inherited from NSObject
}
declare class TKAutoCompleteTokenView extends TKView implements UIKeyInput {
static alloc(): TKAutoCompleteTokenView; // inherited from NSObject
static appearance(): TKAutoCompleteTokenView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKAutoCompleteTokenView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKAutoCompleteTokenView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKAutoCompleteTokenView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKAutoCompleteTokenView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKAutoCompleteTokenView; // inherited from UIAppearance
static new(): TKAutoCompleteTokenView; // inherited from NSObject
highlightedView: UIView;
readonly imageView: UIImageView;
isHighlighted: boolean;
owner: TKAutoCompleteTextView;
removeButton: UIButton;
readonly textLabel: UILabel;
token: TKAutoCompleteToken;
tokenInset: number;
autocapitalizationType: UITextAutocapitalizationType; // inherited from UITextInputTraits
autocorrectionType: UITextAutocorrectionType; // inherited from UITextInputTraits
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
enablesReturnKeyAutomatically: boolean; // inherited from UITextInputTraits
readonly hasText: boolean; // inherited from UIKeyInput
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
keyboardAppearance: UIKeyboardAppearance; // inherited from UITextInputTraits
keyboardType: UIKeyboardType; // inherited from UITextInputTraits
returnKeyType: UIReturnKeyType; // inherited from UITextInputTraits
secureTextEntry: boolean; // inherited from UITextInputTraits
spellCheckingType: UITextSpellCheckingType; // inherited from UITextInputTraits
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
textContentType: string; // inherited from UITextInputTraits
readonly // inherited from NSObjectProtocol
constructor(o: { token: TKAutoCompleteToken; });
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
deleteBackward(): void;
initWithToken(token: TKAutoCompleteToken): this;
insertText(text: string): void;
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 TKBalloonShape extends TKShape {
static alloc(): TKBalloonShape; // inherited from NSObject
static new(): TKBalloonShape; // inherited from NSObject
arrowOffset: number;
arrowPosition: TKBalloonShapeArrowPosition;
arrowSize: CGSize;
cornerRadius: number;
useStrictArrowPosition: boolean;
constructor(o: { arrowPosition: TKBalloonShapeArrowPosition; size: CGSize; });
initWithArrowPositionSize(arrowPosition: TKBalloonShapeArrowPosition, size: CGSize): this;
}
declare const enum TKBalloonShapeArrowPosition {
None = 0,
Left = 1,
Right = 2,
Top = 3,
Bottom = 4,
LeftTop = 5,
LeftBottom = 6,
RightTop = 7,
RightBottom = 8,
TopLeft = 9,
TopRight = 10,
BottomLeft = 11,
BottomRight = 12
}
declare class TKCalendar extends TKView {
static alloc(): TKCalendar; // inherited from NSObject
static appearance(): TKCalendar; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendar; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendar; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendar; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendar; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendar; // inherited from UIAppearance
static dateWithYearMonthDayWithCalendar(year: number, month: number, day: number, calendar: NSCalendar): Date;
static isDateEqualToDateWithComponentsWithCalendar(date1: Date, date2: Date, components: NSCalendarUnit, calendar: NSCalendar): boolean;
static new(): TKCalendar; // inherited from NSObject
allowPinchZoom: boolean;
calendar: NSCalendar;
dataSource: TKCalendarDataSource;
delegate: TKCalendarDelegate;
readonly displayedDate: Date;
locale: NSLocale;
maxDate: Date;
minDate: Date;
readonly presenter: TKCalendarPresenter;
selectedDate: Date;
selectedDates: NSArray<any>;
selectedDatesRange: TKDateRange;
selectionMode: TKCalendarSelectionMode;
theme: TKTheme;
viewMode: TKCalendarViewMode;
clearSelection(): void;
eventsForDate(date: Date): NSArray<any>;
navigateBack(animated: boolean): void;
navigateForward(animated: boolean): void;
navigateToDateAnimated(date: Date, animated: boolean): void;
reloadData(): void;
}
declare class TKCalendarCell extends UIView {
static alloc(): TKCalendarCell; // inherited from NSObject
static appearance(): TKCalendarCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarCell; // inherited from UIAppearance
static new(): TKCalendarCell; // inherited from NSObject
readonly label: UILabel;
owner: TKCalendar;
applyStyleForState(state: number): void;
style(): TKCalendarCellStyle;
updateVisuals(): void;
}
declare const enum TKCalendarCellAlignment {
Left = 1,
Right = 2,
Top = 4,
Bottom = 8,
HorizontalCenter = 16,
VerticalCenter = 32
}
declare class TKCalendarCellStyle extends TKStyleNode {
static alloc(): TKCalendarCellStyle; // inherited from NSObject
static new(): TKCalendarCellStyle; // inherited from NSObject
backgroundColor: UIColor;
bottomBorderColor: UIColor;
bottomBorderWidth: number;
leftBorderColor: UIColor;
leftBorderWidth: number;
rightBorderColor: UIColor;
rightBorderWidth: number;
shape: TKShape;
shapeFill: TKFill;
shapeStroke: TKStroke;
textAlignment: TKCalendarCellAlignment;
textColor: UIColor;
textFont: UIFont;
textInsets: UIEdgeInsets;
topBorderColor: UIColor;
topBorderWidth: number;
}
declare const enum TKCalendarCellType {
Day = 0,
DayName = 1,
WeekNumber = 2,
Title = 3,
MonthName = 4,
YearNumber = 5
}
interface TKCalendarDataSource extends NSObjectProtocol {
calendarEventsForDate?(calendar: TKCalendar, date: Date): NSArray<any>;
calendarEventsFromDateToDateWithCallback?(calendar: TKCalendar, startDate: Date, endDate: Date, eventsCallback: (p1: NSArray<any>) => void): void;
}
declare var TKCalendarDataSource: {
prototype: TKCalendarDataSource;
};
declare class TKCalendarDayCell extends TKCalendarCell {
static alloc(): TKCalendarDayCell; // inherited from NSObject
static appearance(): TKCalendarDayCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarDayCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarDayCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarDayCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarDayCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarDayCell; // inherited from UIAppearance
static new(): TKCalendarDayCell; // inherited from NSObject
readonly date: Date;
readonly events: NSArray<any>;
state: TKCalendarDayState;
attachWithCalendarWithDate(owner: TKCalendar, date: Date): void;
drawEventsRect(context: any, rect: CGRect): void;
stateForDate(date: Date): TKCalendarDayState;
style(): TKCalendarDayCellStyle;
textAttributesForEvent(event: TKCalendarEventProtocol): NSDictionary<any, any>;
textForEvent(event: TKCalendarEventProtocol): string;
}
declare const enum TKCalendarDayCellEventOrientation {
Horizontal = 1,
Vertical = 2
}
declare class TKCalendarDayCellStyle extends TKCalendarCellStyle {
static alloc(): TKCalendarDayCellStyle; // inherited from NSObject
static new(): TKCalendarDayCellStyle; // inherited from NSObject
allDayEventTextColor: UIColor;
defaultSelectionColor: UIColor;
displayEventsAsText: boolean;
eventAlignment: TKCalendarCellAlignment;
eventFont: UIFont;
eventInsets: UIEdgeInsets;
eventOrientation: TKCalendarDayCellEventOrientation;
eventShape: TKShape;
eventSpacing: number;
eventTextColor: UIColor;
maxEventsCount: number;
stretchEvents: boolean;
useDefaultSelectionStyle: boolean;
wrapEventText: boolean;
}
declare class TKCalendarDayNameCell extends TKCalendarCell {
static alloc(): TKCalendarDayNameCell; // inherited from NSObject
static appearance(): TKCalendarDayNameCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarDayNameCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarDayNameCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarDayNameCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarDayNameCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarDayNameCell; // inherited from UIAppearance
static new(): TKCalendarDayNameCell; // inherited from NSObject
attachWithCalendarWithDayOffset(owner: TKCalendar, index: number): void;
}
declare const enum TKCalendarDayState {
Today = 1,
Weekend = 2,
CurrentMonth = 4,
CurrentYear = 8,
Selected = 16,
FirstInSelection = 32,
LastInSelection = 64,
MidInSelection = 128,
Disabled = 256
}
declare class TKCalendarDayView extends UIView implements UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
static alloc(): TKCalendarDayView; // inherited from NSObject
static appearance(): TKCalendarDayView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarDayView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarDayView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarDayView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarDayView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarDayView; // inherited from UIAppearance
static new(): TKCalendarDayView; // inherited from NSObject
readonly allDayEvents: NSArray<TKCalendarEventProtocol>;
readonly allDayEventsView: TKCalendarDayViewAllDayEventsView;
readonly calendar: NSCalendar;
dataSource: TKCalendarDayViewDataSource;
readonly date: Date;
delegate: TKCalendarDayViewDelegate;
readonly emptyView: UIView;
readonly events: NSArray<TKCalendarEventProtocol>;
readonly eventsView: TKCalendarDayViewEventsView;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
attachWithEventsForDateWithCalendar(events: NSArray<TKCalendarEventProtocol>, date: Date, calendar: NSCalendar): void;
class(): typeof NSObject;
collectionViewCanFocusItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewCanMoveItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewCanPerformActionForItemAtIndexPathWithSender(collectionView: UICollectionView, action: string, indexPath: NSIndexPath, sender: any): boolean;
collectionViewCellForItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): UICollectionViewCell;
collectionViewDidDeselectItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): void;
collectionViewDidEndDisplayingCellForItemAtIndexPath(collectionView: UICollectionView, cell: UICollectionViewCell, indexPath: NSIndexPath): void;
collectionViewDidEndDisplayingSupplementaryViewForElementOfKindAtIndexPath(collectionView: UICollectionView, view: UICollectionReusableView, elementKind: string, indexPath: NSIndexPath): void;
collectionViewDidHighlightItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): void;
collectionViewDidSelectItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): void;
collectionViewDidUnhighlightItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): void;
collectionViewDidUpdateFocusInContextWithAnimationCoordinator(collectionView: UICollectionView, context: UICollectionViewFocusUpdateContext, coordinator: UIFocusAnimationCoordinator): void;
collectionViewIndexPathForIndexTitleAtIndex(collectionView: UICollectionView, title: string, index: number): NSIndexPath;
collectionViewLayoutInsetForSectionAtIndex(collectionView: UICollectionView, collectionViewLayout: UICollectionViewLayout, section: number): UIEdgeInsets;
collectionViewLayoutMinimumInteritemSpacingForSectionAtIndex(collectionView: UICollectionView, collectionViewLayout: UICollectionViewLayout, section: number): number;
collectionViewLayoutMinimumLineSpacingForSectionAtIndex(collectionView: UICollectionView, collectionViewLayout: UICollectionViewLayout, section: number): number;
collectionViewLayoutReferenceSizeForFooterInSection(collectionView: UICollectionView, collectionViewLayout: UICollectionViewLayout, section: number): CGSize;
collectionViewLayoutReferenceSizeForHeaderInSection(collectionView: UICollectionView, collectionViewLayout: UICollectionViewLayout, section: number): CGSize;
collectionViewLayoutSizeForItemAtIndexPath(collectionView: UICollectionView, collectionViewLayout: UICollectionViewLayout, indexPath: NSIndexPath): CGSize;
collectionViewMoveItemAtIndexPathToIndexPath(collectionView: UICollectionView, sourceIndexPath: NSIndexPath, destinationIndexPath: NSIndexPath): void;
collectionViewNumberOfItemsInSection(collectionView: UICollectionView, section: number): number;
collectionViewPerformActionForItemAtIndexPathWithSender(collectionView: UICollectionView, action: string, indexPath: NSIndexPath, sender: any): void;
collectionViewShouldDeselectItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewShouldHighlightItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewShouldSelectItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewShouldShowMenuForItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewShouldUpdateFocusInContext(collectionView: UICollectionView, context: UICollectionViewFocusUpdateContext): boolean;
collectionViewTargetContentOffsetForProposedContentOffset(collectionView: UICollectionView, proposedContentOffset: CGPoint): CGPoint;
collectionViewTargetIndexPathForMoveFromItemAtIndexPathToProposedIndexPath(collectionView: UICollectionView, originalIndexPath: NSIndexPath, proposedIndexPath: NSIndexPath): NSIndexPath;
collectionViewTransitionLayoutForOldLayoutNewLayout(collectionView: UICollectionView, fromLayout: UICollectionViewLayout, toLayout: UICollectionViewLayout): UICollectionViewTransitionLayout;
collectionViewViewForSupplementaryElementOfKindAtIndexPath(collectionView: UICollectionView, kind: string, indexPath: NSIndexPath): UICollectionReusableView;
collectionViewWillDisplayCellForItemAtIndexPath(collectionView: UICollectionView, cell: UICollectionViewCell, indexPath: NSIndexPath): void;
collectionViewWillDisplaySupplementaryViewForElementKindAtIndexPath(collectionView: UICollectionView, view: UICollectionReusableView, elementKind: string, indexPath: NSIndexPath): void;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
indexPathForPreferredFocusedViewInCollectionView(collectionView: UICollectionView): NSIndexPath;
indexTitlesForCollectionView(collectionView: UICollectionView): NSArray<string>;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
numberOfSectionsInCollectionView(collectionView: UICollectionView): number;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
scrollViewDidEndDecelerating(scrollView: UIScrollView): void;
scrollViewDidEndDraggingWillDecelerate(scrollView: UIScrollView, decelerate: boolean): void;
scrollViewDidEndScrollingAnimation(scrollView: UIScrollView): void;
scrollViewDidEndZoomingWithViewAtScale(scrollView: UIScrollView, view: UIView, scale: number): void;
scrollViewDidScroll(scrollView: UIScrollView): void;
scrollViewDidScrollToTop(scrollView: UIScrollView): void;
scrollViewDidZoom(scrollView: UIScrollView): void;
scrollViewShouldScrollToTop(scrollView: UIScrollView): boolean;
scrollViewWillBeginDecelerating(scrollView: UIScrollView): void;
scrollViewWillBeginDragging(scrollView: UIScrollView): void;
scrollViewWillBeginZoomingWithView(scrollView: UIScrollView, view: UIView): void;
scrollViewWillEndDraggingWithVelocityTargetContentOffset(scrollView: UIScrollView, velocity: CGPoint, targetContentOffset: interop.Pointer | interop.Reference<CGPoint>): void;
self(): this;
viewForZoomingInScrollView(scrollView: UIScrollView): UIView;
}
declare class TKCalendarDayViewAllDayEventCell extends UICollectionViewCell implements TKCalendarDayViewEventCellProtocol {
static alloc(): TKCalendarDayViewAllDayEventCell; // inherited from NSObject
static appearance(): TKCalendarDayViewAllDayEventCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarDayViewAllDayEventCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarDayViewAllDayEventCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarDayViewAllDayEventCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarDayViewAllDayEventCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarDayViewAllDayEventCell; // inherited from UIAppearance
static new(): TKCalendarDayViewAllDayEventCell; // inherited from NSObject
readonly label: UILabel;
readonly style: TKCalendarDayViewAllDayEventCellStyle;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly event: TKCalendarEventProtocol; // inherited from TKCalendarDayViewEventCellProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
attachWithEvent(event: TKCalendarEventProtocol): void;
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
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 TKCalendarDayViewAllDayEventCellStyle extends TKStyleNode {
static alloc(): TKCalendarDayViewAllDayEventCellStyle; // inherited from NSObject
static new(): TKCalendarDayViewAllDayEventCellStyle; // inherited from NSObject
backgroundColor: UIColor;
textColor: UIColor;
textFont: UIFont;
textInsets: UIEdgeInsets;
}
declare class TKCalendarDayViewAllDayEventsView extends UIView {
static alloc(): TKCalendarDayViewAllDayEventsView; // inherited from NSObject
static appearance(): TKCalendarDayViewAllDayEventsView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarDayViewAllDayEventsView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarDayViewAllDayEventsView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarDayViewAllDayEventsView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarDayViewAllDayEventsView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarDayViewAllDayEventsView; // inherited from UIAppearance
static new(): TKCalendarDayViewAllDayEventsView; // inherited from NSObject
readonly date: Date;
readonly events: NSArray<TKCalendarEventProtocol>;
readonly eventsView: UICollectionView;
readonly labelView: UIView;
readonly style: TKCalendarDayViewAllDayEventsViewStyle;
attachWithEventsForDate(events: NSArray<TKCalendarEventProtocol>, date: Date): void;
createEventsView(): UICollectionView;
createLabelView(): UIView;
updateLayout(): void;
}
declare class TKCalendarDayViewAllDayEventsViewStyle extends TKStyleNode {
static alloc(): TKCalendarDayViewAllDayEventsViewStyle; // inherited from NSObject
static new(): TKCalendarDayViewAllDayEventsViewStyle; // inherited from NSObject
eventHeight: number;
eventsPerRow: number;
eventsViewInsets: UIEdgeInsets;
itemSpacing: number;
labelInsets: UIEdgeInsets;
labelWidth: number;
lineSpacing: number;
maxVisibleLines: number;
}
interface TKCalendarDayViewDataSource extends NSObjectProtocol {
createAllDayEventsViewInDayView(dayView: TKCalendarDayView): TKCalendarDayViewAllDayEventsView;
createEventsViewInDayView(dayView: TKCalendarDayView): TKCalendarDayViewEventsView;
dayViewAllDayEventCellForItemAtIndexPath(dayView: TKCalendarDayView, indexPath: NSIndexPath): UICollectionViewCell;
dayViewEventCellForItemAtIndexPath(dayView: TKCalendarDayView, indexPath: NSIndexPath): UICollectionViewCell;
dayViewNumberOfAllDayEventsInSection(dayView: TKCalendarDayView, section: number): number;
dayViewNumberOfEventsInSection(dayView: TKCalendarDayView, section: number): number;
dayViewUpdateCell(dayView: TKCalendarDayView, cell: UICollectionViewCell): void;
}
declare var TKCalendarDayViewDataSource: {
prototype: TKCalendarDayViewDataSource;
};
interface TKCalendarDayViewDelegate extends NSObjectProtocol {
allDayViewSizeInDayView(dayView: TKCalendarDayView): CGSize;
dayViewAllDaylayoutInsetForSectionAtIndex(dayView: TKCalendarDayView, layout: UICollectionViewLayout, section: number): UIEdgeInsets;
dayViewAllDaylayoutMinimumInteritemSpacingForSectionAtIndex(dayView: TKCalendarDayView, layout: UICollectionViewLayout, section: number): number;
dayViewAllDaylayoutMinimumLineSpacingForSectionAtIndex(dayView: TKCalendarDayView, layout: UICollectionViewLayout, section: number): number;
dayViewAllDaylayoutSizeForItemAtIndexPath(dayView: TKCalendarDayView, layout: UICollectionViewLayout, indexPath: NSIndexPath): CGSize;
dayViewDidSelectEvent(dayView: TKCalendarDayView, event: TKCalendarEventProtocol): void;
}
declare var TKCalendarDayViewDelegate: {
prototype: TKCalendarDayViewDelegate;
};
declare class TKCalendarDayViewEventCell extends UICollectionViewCell implements TKCalendarDayViewEventCellProtocol {
static alloc(): TKCalendarDayViewEventCell; // inherited from NSObject
static appearance(): TKCalendarDayViewEventCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarDayViewEventCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarDayViewEventCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarDayViewEventCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarDayViewEventCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarDayViewEventCell; // inherited from UIAppearance
static new(): TKCalendarDayViewEventCell; // inherited from NSObject
readonly style: TKCalendarDayViewEventCellStyle;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly event: TKCalendarEventProtocol; // inherited from TKCalendarDayViewEventCellProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
attachWithEvent(event: TKCalendarEventProtocol): void;
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
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 TKCalendarDayViewEventCellProtocol extends NSObjectProtocol {
event: TKCalendarEventProtocol;
attachWithEvent(event: TKCalendarEventProtocol): void;
}
declare var TKCalendarDayViewEventCellProtocol: {
prototype: TKCalendarDayViewEventCellProtocol;
};
declare class TKCalendarDayViewEventCellStyle extends TKStyleNode {
static alloc(): TKCalendarDayViewEventCellStyle; // inherited from NSObject
static new(): TKCalendarDayViewEventCellStyle; // inherited from NSObject
decorationWidth: number;
detailFont: UIFont;
detailInsets: UIEdgeInsets;
detailNumberOfLines: number;
insets: UIEdgeInsets;
textColor: UIColor;
titleFont: UIFont;
titleInsets: UIEdgeInsets;
titleNumberOfLines: number;
transparency: number;
}
declare class TKCalendarDayViewEventsLayout extends UICollectionViewLayout {
static alloc(): TKCalendarDayViewEventsLayout; // inherited from NSObject
static new(): TKCalendarDayViewEventsLayout; // inherited from NSObject
}
declare class TKCalendarDayViewEventsView extends UICollectionView {
static alloc(): TKCalendarDayViewEventsView; // inherited from NSObject
static appearance(): TKCalendarDayViewEventsView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarDayViewEventsView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarDayViewEventsView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarDayViewEventsView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarDayViewEventsView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarDayViewEventsView; // inherited from UIAppearance
static new(): TKCalendarDayViewEventsView; // inherited from NSObject
allowZoom: boolean;
readonly calendar: NSCalendar;
readonly date: Date;
endTime: number;
readonly events: NSArray<TKCalendarEventProtocol>;
interval: number;
maxZoom: number;
minZoom: number;
startTime: number;
readonly style: TKCalendarDayViewEventsViewStyle;
zoom: number;
attachWithEventsForDateWithCalendar(events: NSArray<TKCalendarEventProtocol>, date: Date, calendar: NSCalendar): void;
labelForTimeInterval(interval: number): string;
labelSize(): CGSize;
labels(): NSArray<NSAttributedString>;
offsetForComponents(components: NSDateComponents): number;
offsetForHourMinuteSecond(hour: number, minute: number, second: number): number;
slotsCount(): number;
timeLineHeight(): number;
updateLayout(): void;
}
declare class TKCalendarDayViewEventsViewStyle extends TKStyleNode {
static alloc(): TKCalendarDayViewEventsViewStyle; // inherited from NSObject
static new(): TKCalendarDayViewEventsViewStyle; // inherited from NSObject
bottomOffset: number;
eventsLeadingOffset: number;
eventsSpacing: number;
eventsTrailingOffset: number;
labelFormatter: NSDateFormatter;
labelOffset: number;
labelTextAlignment: NSTextAlignment;
labelTextColor: UIColor;
labelTextSize: number;
minEventHeight: number;
separatorColor: UIColor;
separatorLeadingOffset: number;
separatorSpacing: number;
separatorTrailingOffset: number;
separatorWidth: number;
topOffset: number;
}
declare class TKCalendarDayViewPresenter extends TKCalendarPresenterBase {
static alloc(): TKCalendarDayViewPresenter; // inherited from NSObject
static appearance(): TKCalendarDayViewPresenter; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarDayViewPresenter; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarDayViewPresenter; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarDayViewPresenter; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarDayViewPresenter; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarDayViewPresenter; // inherited from UIAppearance
static new(): TKCalendarDayViewPresenter; // inherited from NSObject
dayNamesHidden: boolean;
readonly dayNamesView: UIView;
readonly dayView: TKCalendarDayView;
readonly owner: TKCalendar;
readonly style: TKCalendarDayViewPresenterStyle;
titleHidden: boolean;
readonly titleView: UIView;
weekHidden: boolean;
weekNumbersHidden: boolean;
readonly weekView: UIView;
weekendsHidden: boolean;
cellForDate(date: Date): TKCalendarDayCell;
createCellWithType(cellType: TKCalendarCellType): TKCalendarCell;
}
declare class TKCalendarDayViewPresenterStyle extends TKStyleNode {
static alloc(): TKCalendarDayViewPresenterStyle; // inherited from NSObject
static new(): TKCalendarDayViewPresenterStyle; // inherited from NSObject
backgroundColor: UIColor;
columnSpacing: number;
dayCellHeight: number;
dayNameCellHeight: number;
dayNameTextEffect: TKCalendarTextEffect;
titleCellHeight: number;
weekNumberCellWidth: number;
}
declare class TKCalendarDayViewTimeLine extends UICollectionReusableView {
static alloc(): TKCalendarDayViewTimeLine; // inherited from NSObject
static appearance(): TKCalendarDayViewTimeLine; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarDayViewTimeLine; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarDayViewTimeLine; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarDayViewTimeLine; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarDayViewTimeLine; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarDayViewTimeLine; // inherited from UIAppearance
static new(): TKCalendarDayViewTimeLine; // inherited from NSObject
readonly owner: TKCalendarDayViewEventsView;
}
declare class TKCalendarDayViewTimeLineLayoutAttributes extends UICollectionViewLayoutAttributes {
static alloc(): TKCalendarDayViewTimeLineLayoutAttributes; // inherited from NSObject
static layoutAttributesForCellWithIndexPath(indexPath: NSIndexPath): TKCalendarDayViewTimeLineLayoutAttributes; // inherited from UICollectionViewLayoutAttributes
static layoutAttributesForDecorationViewOfKindWithIndexPath(decorationViewKind: string, indexPath: NSIndexPath): TKCalendarDayViewTimeLineLayoutAttributes; // inherited from UICollectionViewLayoutAttributes
static layoutAttributesForDecorationViewOfKindWithIndexPathWithOwner(decorationViewKind: string, indexPath: NSIndexPath, owner: TKCalendarDayViewEventsView): TKCalendarDayViewTimeLineLayoutAttributes;
static layoutAttributesForSupplementaryViewOfKindWithIndexPath(elementKind: string, indexPath: NSIndexPath): TKCalendarDayViewTimeLineLayoutAttributes; // inherited from UICollectionViewLayoutAttributes
static new(): TKCalendarDayViewTimeLineLayoutAttributes; // inherited from NSObject
readonly owner: TKCalendarDayViewEventsView;
}
declare class TKCalendarDefaultTheme extends TKTheme {
static alloc(): TKCalendarDefaultTheme; // inherited from NSObject
static new(): TKCalendarDefaultTheme; // inherited from NSObject
}
interface TKCalendarDelegate extends NSObjectProtocol {
calendarDidChangedViewModeFromTo?(calendar: TKCalendar, previousViewMode: TKCalendarViewMode, viewMode: TKCalendarViewMode): void;
calendarDidDeselectedDate?(calendar: TKCalendar, date: Date): void;
calendarDidNavigateToDate?(calendar: TKCalendar, date: Date): void;
calendarDidSelectDate?(calendar: TKCalendar, date: Date): void;
calendarDidTapCell?(calendar: TKCalendar, cell: TKCalendarDayCell): void;
calendarShapeForEvent?(calendar: TKCalendar, event: TKCalendarEventProtocol): TKShape;
calendarShouldSelectDate?(calendar: TKCalendar, date: Date): boolean;
calendarTextForEvent?(calendar: TKCalendar, event: TKCalendarEventProtocol): string;
calendarUpdateVisualsForCell?(calendar: TKCalendar, cell: TKCalendarCell): void;
calendarViewForCellOfKind?(calendar: TKCalendar, cellType: TKCalendarCellType): TKCalendarCell;
calendarWillNavigateToDate?(calendar: TKCalendar, date: Date): void;
}
declare var TKCalendarDelegate: {
prototype: TKCalendarDelegate;
};
declare class TKCalendarEvent extends NSObject implements TKCalendarEventProtocol {
static alloc(): TKCalendarEvent; // inherited from NSObject
static new(): TKCalendarEvent; // inherited from NSObject
content: string;
location: string;
allDay: boolean; // inherited from TKCalendarEventProtocol
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
detail: string; // inherited from TKCalendarEventProtocol
endDate: Date; // inherited from TKCalendarEventProtocol
eventColor: UIColor; // inherited from TKCalendarEventProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
startDate: Date; // inherited from TKCalendarEventProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
title: string; // inherited from TKCalendarEventProtocol
readonly // inherited from NSObjectProtocol
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
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 TKCalendarEventKitDataSource extends NSObject implements TKCalendarDataSource {
static alloc(): TKCalendarEventKitDataSource; // inherited from NSObject
static new(): TKCalendarEventKitDataSource; // inherited from NSObject
readonly calendars: NSArray<any>;
delegate: TKCalendarEventKitDataSourceDelegate;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
calendarEventsForDate(calendar: TKCalendar, date: Date): NSArray<any>;
calendarEventsFromDateToDateWithCallback(calendar: TKCalendar, startDate: Date, endDate: Date, eventsCallback: (p1: NSArray<any>) => void): void;
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
createCalendarEventInCalendar(event: EKEvent, calendar: EKCalendar): TKCalendarEventProtocol;
getCalendarsWithBlock(callbackBlock: (p1: NSArray<any>) => void): void;
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 TKCalendarEventKitDataSourceDelegate extends NSObjectProtocol {
shouldImportEvent?(event: EKEvent): boolean;
shouldImportEventsFromCalendar?(calendar: EKCalendar): boolean;
}
declare var TKCalendarEventKitDataSourceDelegate: {
prototype: TKCalendarEventKitDataSourceDelegate;
};
interface TKCalendarEventProtocol extends NSObjectProtocol {
allDay: boolean;
detail: string;
endDate: Date;
eventColor: UIColor;
startDate: Date;
title: string;
}
declare var TKCalendarEventProtocol: {
prototype: TKCalendarEventProtocol;
};
declare class TKCalendarFlowPresenter extends UIView implements TKCalendarPresenter {
static alloc(): TKCalendarFlowPresenter; // inherited from NSObject
static appearance(): TKCalendarFlowPresenter; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarFlowPresenter; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarFlowPresenter; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarFlowPresenter; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarFlowPresenter; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarFlowPresenter; // inherited from UIAppearance
static new(): TKCalendarFlowPresenter; // inherited from NSObject
readonly collectionView: UICollectionView;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
dateFromPoint(pt: CGPoint): Date;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
navigateBack(animated: boolean): boolean;
navigateForward(animated: boolean): boolean;
navigateToDateAnimated(date: Date, animated: boolean): void;
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;
update(reset: boolean): void;
updateState(lastSelected: Date): void;
}
declare class TKCalendarIPadTheme extends TKTheme {
static alloc(): TKCalendarIPadTheme; // inherited from NSObject
static new(): TKCalendarIPadTheme; // inherited from NSObject
}
declare const enum TKCalendarInlineEventsViewMode {
None = 0,
Inline = 1,
Popover = 2
}
declare class TKCalendarInlineView extends TKView implements UITableViewDataSource, UITableViewDelegate {
static alloc(): TKCalendarInlineView; // inherited from NSObject
static appearance(): TKCalendarInlineView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarInlineView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarInlineView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarInlineView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarInlineView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarInlineView; // inherited from UIAppearance
static new(): TKCalendarInlineView; // inherited from NSObject
dayCell: TKCalendarDayCell;
desiredWidthInPopoverMode: number;
fixedHeight: boolean;
maxHeight: number;
owner: TKCalendarMonthPresenter;
rowHeight: number;
readonly tableView: UITableView;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
indexPathForPreferredFocusedViewInTableView(tableView: UITableView): NSIndexPath;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
numberOfSectionsInTableView(tableView: UITableView): number;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
scrollViewDidEndDecelerating(scrollView: UIScrollView): void;
scrollViewDidEndDraggingWillDecelerate(scrollView: UIScrollView, decelerate: boolean): void;
scrollViewDidEndScrollingAnimation(scrollView: UIScrollView): void;
scrollViewDidEndZoomingWithViewAtScale(scrollView: UIScrollView, view: UIView, scale: number): void;
scrollViewDidScroll(scrollView: UIScrollView): void;
scrollViewDidScrollToTop(scrollView: UIScrollView): void;
scrollViewDidZoom(scrollView: UIScrollView): void;
scrollViewShouldScrollToTop(scrollView: UIScrollView): boolean;
scrollViewWillBeginDecelerating(scrollView: UIScrollView): void;
scrollViewWillBeginDragging(scrollView: UIScrollView): void;
scrollViewWillBeginZoomingWithView(scrollView: UIScrollView, view: UIView): void;
scrollViewWillEndDraggingWithVelocityTargetContentOffset(scrollView: UIScrollView, velocity: CGPoint, targetContentOffset: interop.Pointer | interop.Reference<CGPoint>): void;
sectionIndexTitlesForTableView(tableView: UITableView): NSArray<string>;
self(): this;
tableViewAccessoryButtonTappedForRowWithIndexPath(tableView: UITableView, indexPath: NSIndexPath): void;
tableViewAccessoryTypeForRowWithIndexPath(tableView: UITableView, indexPath: NSIndexPath): UITableViewCellAccessoryType;
tableViewCanEditRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): boolean;
tableViewCanFocusRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): boolean;
tableViewCanMoveRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): boolean;
tableViewCanPerformActionForRowAtIndexPathWithSender(tableView: UITableView, action: string, indexPath: NSIndexPath, sender: any): boolean;
tableViewCellForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): UITableViewCell;
tableViewCommitEditingStyleForRowAtIndexPath(tableView: UITableView, editingStyle: UITableViewCellEditingStyle, indexPath: NSIndexPath): void;
tableViewDidDeselectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): void;
tableViewDidEndDisplayingCellForRowAtIndexPath(tableView: UITableView, cell: UITableViewCell, indexPath: NSIndexPath): void;
tableViewDidEndDisplayingFooterViewForSection(tableView: UITableView, view: UIView, section: number): void;
tableViewDidEndDisplayingHeaderViewForSection(tableView: UITableView, view: UIView, section: number): void;
tableViewDidEndEditingRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): void;
tableViewDidHighlightRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): void;
tableViewDidSelectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): void;
tableViewDidUnhighlightRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): void;
tableViewDidUpdateFocusInContextWithAnimationCoordinator(tableView: UITableView, context: UITableViewFocusUpdateContext, coordinator: UIFocusAnimationCoordinator): void;
tableViewEditActionsForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): NSArray<UITableViewRowAction>;
tableViewEditingStyleForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): UITableViewCellEditingStyle;
tableViewEstimatedHeightForFooterInSection(tableView: UITableView, section: number): number;
tableViewEstimatedHeightForHeaderInSection(tableView: UITableView, section: number): number;
tableViewEstimatedHeightForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): number;
tableViewHeightForFooterInSection(tableView: UITableView, section: number): number;
tableViewHeightForHeaderInSection(tableView: UITableView, section: number): number;
tableViewHeightForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): number;
tableViewIndentationLevelForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): number;
tableViewMoveRowAtIndexPathToIndexPath(tableView: UITableView, sourceIndexPath: NSIndexPath, destinationIndexPath: NSIndexPath): void;
tableViewNumberOfRowsInSection(tableView: UITableView, section: number): number;
tableViewPerformActionForRowAtIndexPathWithSender(tableView: UITableView, action: string, indexPath: NSIndexPath, sender: any): void;
tableViewSectionForSectionIndexTitleAtIndex(tableView: UITableView, title: string, index: number): number;
tableViewShouldHighlightRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): boolean;
tableViewShouldIndentWhileEditingRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): boolean;
tableViewShouldShowMenuForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): boolean;
tableViewShouldUpdateFocusInContext(tableView: UITableView, context: UITableViewFocusUpdateContext): boolean;
tableViewTargetIndexPathForMoveFromRowAtIndexPathToProposedIndexPath(tableView: UITableView, sourceIndexPath: NSIndexPath, proposedDestinationIndexPath: NSIndexPath): NSIndexPath;
tableViewTitleForDeleteConfirmationButtonForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): string;
tableViewTitleForFooterInSection(tableView: UITableView, section: number): string;
tableViewTitleForHeaderInSection(tableView: UITableView, section: number): string;
tableViewViewForFooterInSection(tableView: UITableView, section: number): UIView;
tableViewViewForHeaderInSection(tableView: UITableView, section: number): UIView;
tableViewWillBeginEditingRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): void;
tableViewWillDeselectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): NSIndexPath;
tableViewWillDisplayCellForRowAtIndexPath(tableView: UITableView, cell: UITableViewCell, indexPath: NSIndexPath): void;
tableViewWillDisplayFooterViewForSection(tableView: UITableView, view: UIView, section: number): void;
tableViewWillDisplayHeaderViewForSection(tableView: UITableView, view: UIView, section: number): void;
tableViewWillSelectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): NSIndexPath;
viewForZoomingInScrollView(scrollView: UIScrollView): UIView;
}
declare class TKCalendarInlineViewTableViewCell extends UITableViewCell {
static alloc(): TKCalendarInlineViewTableViewCell; // inherited from NSObject
static appearance(): TKCalendarInlineViewTableViewCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarInlineViewTableViewCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarInlineViewTableViewCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarInlineViewTableViewCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarInlineViewTableViewCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarInlineViewTableViewCell; // inherited from UIAppearance
static new(): TKCalendarInlineViewTableViewCell; // inherited from NSObject
readonly style: TKCalendarInlineViewTableViewCellStyle;
attachWithCellEventIndex(cell: TKCalendarDayCell, index: number): void;
updateTextForEventWithCell(event: TKCalendarEventProtocol, cell: TKCalendarDayCell): void;
}
declare class TKCalendarInlineViewTableViewCellStyle extends TKStyleNode {
static alloc(): TKCalendarInlineViewTableViewCellStyle; // inherited from NSObject
static new(): TKCalendarInlineViewTableViewCellStyle; // inherited from NSObject
backgroundColor: UIColor;
eventColor: UIColor;
eventFont: UIFont;
separatorColor: UIColor;
shapeSize: CGSize;
timeColor: UIColor;
timeFont: UIFont;
}
declare class TKCalendarMonthCell extends UICollectionViewCell {
static alloc(): TKCalendarMonthCell; // inherited from NSObject
static appearance(): TKCalendarMonthCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarMonthCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarMonthCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarMonthCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarMonthCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarMonthCell; // inherited from UIAppearance
static new(): TKCalendarMonthCell; // inherited from NSObject
readonly monthView: TKCalendarMonthView;
attachWithCalendarPresenterWithYearAndMonth(owner: TKCalendar, presenter: TKCalendarYearPresenter, year: number, month: number): void;
}
declare class TKCalendarMonthNameCell extends TKCalendarCell {
static alloc(): TKCalendarMonthNameCell; // inherited from NSObject
static appearance(): TKCalendarMonthNameCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarMonthNameCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarMonthNameCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarMonthNameCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarMonthNameCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarMonthNameCell; // inherited from UIAppearance
static new(): TKCalendarMonthNameCell; // inherited from NSObject
readonly date: Date;
state: TKCalendarMonthNameState;
attachWithCalendarWithDate(owner: TKCalendar, date: Date): void;
}
declare const enum TKCalendarMonthNameState {
Selected = 1,
Disabled = 2
}
declare class TKCalendarMonthNamesPresenter extends TKCalendarPresenterBase {
static alloc(): TKCalendarMonthNamesPresenter; // inherited from NSObject
static appearance(): TKCalendarMonthNamesPresenter; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarMonthNamesPresenter; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarMonthNamesPresenter; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarMonthNamesPresenter; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarMonthNamesPresenter; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarMonthNamesPresenter; // inherited from UIAppearance
static new(): TKCalendarMonthNamesPresenter; // inherited from NSObject
columns: number;
readonly contentView: UIView;
}
declare class TKCalendarMonthPresenter extends TKCalendarPresenterBase {
static alloc(): TKCalendarMonthPresenter; // inherited from NSObject
static appearance(): TKCalendarMonthPresenter; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarMonthPresenter; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarMonthPresenter; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarMonthPresenter; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarMonthPresenter; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarMonthPresenter; // inherited from UIAppearance
static new(): TKCalendarMonthPresenter; // inherited from NSObject
readonly contentView: UIView;
dayNamesHidden: boolean;
equalWeekNumber: boolean;
headerIsSticky: boolean;
readonly headerView: UIView;
inlineEventsView: TKCalendarInlineView;
inlineEventsViewMode: TKCalendarInlineEventsViewMode;
readonly owner: TKCalendar;
readonly style: TKCalendarMonthPresenterStyle;
titleHidden: boolean;
weekNumbersHidden: boolean;
weekendsHidden: boolean;
cellForDate(date: Date): TKCalendarDayCell;
createCellWithType(cellType: TKCalendarCellType): TKCalendarCell;
dateForRowCol(row: number, col: number): Date;
hideInlineEvents(animated: boolean): void;
showInlineEventsForCellAnimated(cell: TKCalendarDayCell, animated: boolean): void;
updateInlineView(): void;
}
interface TKCalendarMonthPresenterDelegate extends TKCalendarPresenterDelegate {
monthPresenterInlineEventSelected?(presenter: TKCalendarMonthPresenter, event: TKCalendarEventProtocol): void;
monthPresenterInlineEventsViewDidHideForCell?(presenter: TKCalendarMonthPresenter, cell: TKCalendarDayCell): void;
monthPresenterInlineEventsViewDidShowForCell?(presenter: TKCalendarMonthPresenter, cell: TKCalendarDayCell): void;
monthPresenterUpdateVisualsForInlineEventCell?(presenter: TKCalendarMonthPresenter, cell: TKCalendarInlineViewTableViewCell): void;
}
declare var TKCalendarMonthPresenterDelegate: {
prototype: TKCalendarMonthPresenterDelegate;
};
declare class TKCalendarMonthPresenterStyle extends TKStyleNode {
static alloc(): TKCalendarMonthPresenterStyle; // inherited from NSObject
static new(): TKCalendarMonthPresenterStyle; // inherited from NSObject
backgroundColor: UIColor;
columnSpacing: number;
dayNameCellHeight: number;
dayNameTextEffect: TKCalendarTextEffect;
monthNameTextEffect: TKCalendarTextEffect;
popoverColor: UIColor;
rowSpacing: number;
titleCellHeight: number;
weekNumberCellWidth: number;
}
declare class TKCalendarMonthTitleCell extends TKCalendarTitleCell {
static alloc(): TKCalendarMonthTitleCell; // inherited from NSObject
static appearance(): TKCalendarMonthTitleCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarMonthTitleCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarMonthTitleCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarMonthTitleCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarMonthTitleCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarMonthTitleCell; // inherited from UIAppearance
static new(): TKCalendarMonthTitleCell; // inherited from NSObject
layoutMode: TKCalendarMonthTitleCellLayoutMode;
nextMonthButton: UIButton;
nextYearButton: UIButton;
previousMonthButton: UIButton;
previousYearButton: UIButton;
readonly yearLabel: UILabel;
}
declare const enum TKCalendarMonthTitleCellLayoutMode {
Month = 0,
MonthWithButtons = 1,
MonthAndYearWithButtons = 2
}
declare class TKCalendarMonthView extends UIView {
static alloc(): TKCalendarMonthView; // inherited from NSObject
static appearance(): TKCalendarMonthView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarMonthView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarMonthView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarMonthView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarMonthView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarMonthView; // inherited from UIAppearance
static new(): TKCalendarMonthView; // inherited from NSObject
readonly date: Date;
attachWithCalendarPresenterWithYearAndMonth(owner: TKCalendar, presenter: TKCalendarYearPresenter, year: number, month: number): void;
}
declare class TKCalendarMonthViewController extends UIViewController {
static alloc(): TKCalendarMonthViewController; // inherited from NSObject
static new(): TKCalendarMonthViewController; // inherited from NSObject
readonly contentView: TKCalendar;
readonly todayButton: UIBarButtonItem;
}
declare class TKCalendarNavigationController extends UINavigationController {
static alloc(): TKCalendarNavigationController; // inherited from NSObject
static new(): TKCalendarNavigationController; // inherited from NSObject
}
interface TKCalendarPresenter extends NSObjectProtocol {
dateFromPoint(pt: CGPoint): Date;
navigateBack(animated: boolean): boolean;
navigateForward(animated: boolean): boolean;
navigateToDateAnimated(date: Date, animated: boolean): void;
update(reset: boolean): void;
updateState(lastSelected: Date): void;
}
declare var TKCalendarPresenter: {
prototype: TKCalendarPresenter;
};
declare class TKCalendarPresenterBase extends UIView implements TKCalendarPresenter {
static alloc(): TKCalendarPresenterBase; // inherited from NSObject
static appearance(): TKCalendarPresenterBase; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarPresenterBase; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarPresenterBase; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarPresenterBase; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarPresenterBase; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarPresenterBase; // inherited from UIAppearance
static new(): TKCalendarPresenterBase; // inherited from NSObject
delegate: TKCalendarPresenterDelegate;
panGestureSensitivity: number;
transitionDuration: number;
transitionIsReverse: boolean;
transitionIsVertical: boolean;
transitionMode: TKCalendarTransitionMode;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
dateFromPoint(pt: CGPoint): Date;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
navigateBack(animated: boolean): boolean;
navigateForward(animated: boolean): boolean;
navigateToDateAnimated(date: Date, animated: boolean): void;
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;
update(reset: boolean): void;
updateState(lastSelected: Date): void;
}
interface TKCalendarPresenterDelegate extends NSObjectProtocol {
presenterBeginTransition?(presenter: TKCalendarPresenter, transition: TKViewTransition): void;
presenterFinishTransitionIsCanceled?(presenter: TKCalendarPresenter, transition: TKViewTransition, canceled: boolean): void;
}
declare var TKCalendarPresenterDelegate: {
prototype: TKCalendarPresenterDelegate;
};
declare const enum TKCalendarSelectionMode {
None = 0,
Single = 1,
Multiple = 2,
Range = 3
}
declare const enum TKCalendarTextEffect {
None = 0,
Uppercase = 1,
Lowercase = 2
}
declare class TKCalendarTitleCell extends TKCalendarCell {
static alloc(): TKCalendarTitleCell; // inherited from NSObject
static appearance(): TKCalendarTitleCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarTitleCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarTitleCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarTitleCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarTitleCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarTitleCell; // inherited from UIAppearance
static new(): TKCalendarTitleCell; // inherited from NSObject
attachWithCalendarWithText(owner: TKCalendar, text: string): void;
}
declare const enum TKCalendarTransitionMode {
None = 0,
Flip = 1,
Fold = 2,
Float = 3,
Card = 4,
Rotate = 5,
Scroll = 6
}
declare const enum TKCalendarViewMode {
Week = 0,
Month = 1,
MonthNames = 2,
Year = 3,
YearNumbers = 4,
Flow = 5,
Day = 6
}
declare class TKCalendarWeekNumberCell extends TKCalendarCell {
static alloc(): TKCalendarWeekNumberCell; // inherited from NSObject
static appearance(): TKCalendarWeekNumberCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarWeekNumberCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarWeekNumberCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarWeekNumberCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarWeekNumberCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarWeekNumberCell; // inherited from UIAppearance
static new(): TKCalendarWeekNumberCell; // inherited from NSObject
attachWithCalendarWithWeekNumber(owner: TKCalendar, weekNumber: number): void;
}
declare class TKCalendarWeekPresenter extends TKCalendarMonthPresenter {
static alloc(): TKCalendarWeekPresenter; // inherited from NSObject
static appearance(): TKCalendarWeekPresenter; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarWeekPresenter; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarWeekPresenter; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarWeekPresenter; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarWeekPresenter; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarWeekPresenter; // inherited from UIAppearance
static new(): TKCalendarWeekPresenter; // inherited from NSObject
}
declare class TKCalendarYearNumberCell extends TKCalendarCell {
static alloc(): TKCalendarYearNumberCell; // inherited from NSObject
static appearance(): TKCalendarYearNumberCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarYearNumberCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarYearNumberCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarYearNumberCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarYearNumberCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarYearNumberCell; // inherited from UIAppearance
static new(): TKCalendarYearNumberCell; // inherited from NSObject
readonly date: Date;
state: TKCalendarYearNumberState;
attachWithCalendarWithDate(owner: TKCalendar, date: Date): void;
}
declare const enum TKCalendarYearNumberState {
Selected = 1,
Disabled = 2
}
declare class TKCalendarYearNumbersPresenter extends TKCalendarPresenterBase {
static alloc(): TKCalendarYearNumbersPresenter; // inherited from NSObject
static appearance(): TKCalendarYearNumbersPresenter; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarYearNumbersPresenter; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarYearNumbersPresenter; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarYearNumbersPresenter; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarYearNumbersPresenter; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarYearNumbersPresenter; // inherited from UIAppearance
static new(): TKCalendarYearNumbersPresenter; // inherited from NSObject
columns: number;
rows: number;
}
declare class TKCalendarYearPresenter extends UIView implements TKCalendarPresenter {
static alloc(): TKCalendarYearPresenter; // inherited from NSObject
static appearance(): TKCalendarYearPresenter; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarYearPresenter; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarYearPresenter; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarYearPresenter; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarYearPresenter; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarYearPresenter; // inherited from UIAppearance
static new(): TKCalendarYearPresenter; // inherited from NSObject
readonly collectionView: UICollectionView;
columns: number;
delegate: TKCalendarYearPresenterDelegate;
monthCellClass: typeof NSObject;
readonly style: TKCalendarYearPresenterStyle;
titleViewClass: typeof 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
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
dateFromPoint(pt: CGPoint): Date;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
navigateBack(animated: boolean): boolean;
navigateForward(animated: boolean): boolean;
navigateToDateAnimated(date: Date, animated: boolean): void;
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;
update(reset: boolean): void;
updateState(lastSelected: Date): void;
}
interface TKCalendarYearPresenterDelegate extends NSObjectProtocol {
calendarDrawBackgroundForYearMonthDateInRect?(calendar: TKCalendar, year: number, month: number, date: number, rect: CGRect): void;
calendarTextAttributesForYearMonthDate?(calendar: TKCalendar, year: number, month: number, date: number): NSDictionary<any, any>;
calendarYearPresenterTextForYearMonth?(calendar: TKCalendar, presenter: TKCalendarYearPresenter, year: number, month: number): string;
}
declare var TKCalendarYearPresenterDelegate: {
prototype: TKCalendarYearPresenterDelegate;
};
declare class TKCalendarYearPresenterStyle extends TKStyleNode {
static alloc(): TKCalendarYearPresenterStyle; // inherited from NSObject
static new(): TKCalendarYearPresenterStyle; // inherited from NSObject
dayFont: UIFont;
dayNameFont: UIFont;
dayNameTextColor: UIColor;
dayNameTextEffect: TKCalendarTextEffect;
dayTextColor: UIColor;
monthNameFont: UIFont;
monthNameTextAlignment: NSTextAlignment;
monthNameTextColor: UIColor;
monthNameTextEffect: TKCalendarTextEffect;
monthsPerPage: number;
todayShape: TKShape;
todayShapeFill: TKFill;
todayShapeStroke: TKStroke;
todayTextColor: UIColor;
weekendTextColor: UIColor;
}
declare class TKCalendarYearTitleView extends UICollectionReusableView {
static alloc(): TKCalendarYearTitleView; // inherited from NSObject
static appearance(): TKCalendarYearTitleView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCalendarYearTitleView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCalendarYearTitleView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCalendarYearTitleView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCalendarYearTitleView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCalendarYearTitleView; // inherited from UIAppearance
static new(): TKCalendarYearTitleView; // inherited from NSObject
readonly view: TKCalendarTitleCell;
attachWithCalendarWithText(owner: TKCalendar, text: string): void;
}
declare class TKCalendarYearViewController extends UIViewController implements TKCalendarDelegate {
static alloc(): TKCalendarYearViewController; // inherited from NSObject
static new(): TKCalendarYearViewController; // inherited from NSObject
readonly contentView: TKCalendar;
delegate: TKCalendarYearViewControllerDelegate;
readonly selectedItemRect: CGRect;
readonly todayButton: UIBarButtonItem;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
calendarDidChangedViewModeFromTo(calendar: TKCalendar, previousViewMode: TKCalendarViewMode, viewMode: TKCalendarViewMode): void;
calendarDidDeselectedDate(calendar: TKCalendar, date: Date): void;
calendarDidNavigateToDate(calendar: TKCalendar, date: Date): void;
calendarDidSelectDate(calendar: TKCalendar, date: Date): void;
calendarDidTapCell(calendar: TKCalendar, cell: TKCalendarDayCell): void;
calendarShapeForEvent(calendar: TKCalendar, event: TKCalendarEventProtocol): TKShape;
calendarShouldSelectDate(calendar: TKCalendar, date: Date): boolean;
calendarTextForEvent(calendar: TKCalendar, event: TKCalendarEventProtocol): string;
calendarUpdateVisualsForCell(calendar: TKCalendar, cell: TKCalendarCell): void;
calendarViewForCellOfKind(calendar: TKCalendar, cellType: TKCalendarCellType): TKCalendarCell;
calendarWillNavigateToDate(calendar: TKCalendar, date: Date): void;
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
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 TKCalendarYearViewControllerDelegate extends NSObjectProtocol {
navigatedToMonthViewController(monthViewController: TKCalendarMonthViewController): void;
}
declare var TKCalendarYearViewControllerDelegate: {
prototype: TKCalendarYearViewControllerDelegate;
};
declare class TKChart extends TKView {
static alloc(): TKChart; // inherited from NSObject
static appearance(): TKChart; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKChart; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKChart; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKChart; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKChart; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKChart; // inherited from UIAppearance
static new(): TKChart; // inherited from NSObject
allowAnimations: boolean;
allowPanDeceleration: boolean;
allowTrackball: boolean;
animationDuration: number;
readonly annotations: NSArray<any>;
readonly axes: NSArray<any>;
dataPointSelectionMode: TKChartSelectionMode;
dataSource: TKChartDataSource;
delegate: TKChartDelegate;
readonly gridStyle: TKChartGridStyle;
handleDoubleTap: boolean;
insets: UIEdgeInsets;
readonly legend: TKChartLegendView;
readonly plotView: TKChartPlotView;
plotViewInsets: UIEdgeInsets;
readonly selectedPoints: NSArray<TKChartSelectionInfo>;
readonly selectedSeries: NSArray<TKChartSeries>;
selectionMode: TKChartSelectionMode;
readonly series: NSArray<TKChartSeries>;
seriesSelectionMode: TKChartSelectionMode;
theme: TKTheme;
readonly title: TKChartTitleView;
readonly trackball: TKChartTrackball;
xAxis: TKChartAxis;
yAxis: TKChartAxis;
zoomMode: TKChartZoomMode;
addAnnotation(annotation: TKChartAnnotation): void;
addAxis(axis: TKChartAxis): void;
addSeries(series: TKChartSeries): void;
animate(): void;
beginUpdates(): void;
dequeueReusableSeriesWithIdentifier(identifier: string): any;
deselect(info: TKChartSelectionInfo): void;
endUpdates(): void;
hitTestForPoint(point: CGPoint): TKChartSelectionInfo;
paletteItemForPointInSeries(index: number, series: TKChartSeries): TKChartPaletteItem;
paletteItemForSeriesAtIndex(series: TKChartSeries, index: number): TKChartPaletteItem;
reloadData(): void;
removeAllAnnotations(): void;
removeAllData(): void;
removeAnnotation(annotation: TKChartAnnotation): void;
removeAxis(axis: TKChartAxis): boolean;
removeSeries(series: TKChartSeries): void;
select(info: TKChartSelectionInfo): void;
update(): void;
updateAnnotations(): void;
visualPointForSeriesDataPointIndex(series: TKChartSeries, dataPointIndex: number): TKChartVisualPoint;
visualPointsForSeries(series: TKChartSeries): NSArray<TKChartVisualPoint>;
}
declare class TKChartAbsoluteVolumeOscillator extends TKChartMACDIndicator {
static alloc(): TKChartAbsoluteVolumeOscillator; // inherited from NSObject
static new(): TKChartAbsoluteVolumeOscillator; // inherited from NSObject
}
declare class TKChartAccumulationDistributionLine extends TKChartFinancialIndicator {
static alloc(): TKChartAccumulationDistributionLine; // inherited from NSObject
static new(): TKChartAccumulationDistributionLine; // inherited from NSObject
}
declare class TKChartAdaptiveMovingAverageIndicator extends TKChartFinancialIndicator {
static alloc(): TKChartAdaptiveMovingAverageIndicator; // inherited from NSObject
static new(): TKChartAdaptiveMovingAverageIndicator; // inherited from NSObject
fastPeriod: number;
period: number;
slowPerod: number;
}
declare class TKChartAnnotation extends NSObject {
static alloc(): TKChartAnnotation; // inherited from NSObject
static new(): TKChartAnnotation; // inherited from NSObject
hidden: boolean;
zPosition: TKChartAnnotationZPosition;
annotationWasAddedToChartWithLayer(chart: TKChart, layer: CALayer): void;
annotationWillBeRemovedFromChart(chart: TKChart): void;
drawInContext(context: any): void;
layoutInRectForChartInLayer(bounds: CGRect, chart: TKChart, layer: CALayer): void;
locationOfValueWithAxisInBounds(value: any, axis: TKChartAxis, bounds: CGRect): number;
}
declare class TKChartAnnotationStyle extends TKStyleNode {
static alloc(): TKChartAnnotationStyle; // inherited from NSObject
static new(): TKChartAnnotationStyle; // inherited from NSObject
}
declare const enum TKChartAnnotationZPosition {
BelowSeries = 0,
AboveSeries = 1
}
declare class TKChartAreaSeries extends TKChartLineSeries {
static alloc(): TKChartAreaSeries; // inherited from NSObject
static new(): TKChartAreaSeries; // inherited from NSObject
}
declare class TKChartAverageTrueRangeIndicator extends TKChartTrueRangeIndicator {
static alloc(): TKChartAverageTrueRangeIndicator; // inherited from NSObject
static new(): TKChartAverageTrueRangeIndicator; // inherited from NSObject
period: number;
}
declare class TKChartAxis extends NSObject {
static alloc(): TKChartAxis; // inherited from NSObject
static new(): TKChartAxis; // inherited from NSObject
allowPan: boolean;
allowZoom: boolean;
attributedTitle: NSAttributedString;
customLabels: NSDictionary<any, any>;
hidden: boolean;
readonly isVertical: boolean;
labelFormat: string;
labelFormatter: NSFormatter;
readonly majorTickCount: number;
normalizedPan: number;
pan: number;
readonly plotMode: TKChartAxisPlotMode;
position: TKChartAxisPosition;
range: TKRange;
style: TKChartAxisStyle;
title: string;
readonly visibleRange: TKRange;
zoom: number;
zoomRange: TKRange;
constructor(o: { minimum: any; andMaximum: any; });
constructor(o: { minimum: any; andMaximum: any; position: TKChartAxisPosition; });
constructor(o: { range: TKRange; });
formatValue(value: any): string;
initWithMinimumAndMaximum(minimum: any, maximum: any): this;
initWithMinimumAndMaximumPosition(minimum: any, maximum: any, position: TKChartAxisPosition): this;
initWithRange(range: TKRange): this;
numericValue(value: any): number;
panToDataPoint(dataPoint: TKChartData): void;
renderForChart(chart: TKChart): TKChartAxisRender;
tickValue(index: number): any;
}
declare const enum TKChartAxisClippingMode {
Visible = 0,
Hidden = 1
}
declare const enum TKChartAxisLabelAlignment {
Left = 1,
Right = 2,
Top = 4,
Bottom = 8,
HorizontalCenter = 16,
VerticalCenter = 32
}
declare const enum TKChartAxisLabelFitMode {
None = 0,
Multiline = 1,
Rotate = 2
}
declare class TKChartAxisLabelStyle extends TKChartLabelStyle {
static alloc(): TKChartAxisLabelStyle; // inherited from NSObject
static new(): TKChartAxisLabelStyle; // inherited from NSObject
clipAxisLabels: boolean;
firstLabelTextAlignment: TKChartAxisLabelAlignment;
firstLabelTextOffset: UIOffset;
fitMode: TKChartAxisLabelFitMode;
lastLabelTextAlignment: TKChartAxisLabelAlignment;
lastLabelTextOffset: UIOffset;
maxLabelClippingMode: TKChartAxisClippingMode;
minLabelClippingMode: TKChartAxisClippingMode;
rotationAngle: number;
textAlignment: TKChartAxisLabelAlignment;
textOffset: UIOffset;
}
declare class TKChartAxisMajorTickStyle extends TKChartAxisTickStyle {
static alloc(): TKChartAxisMajorTickStyle; // inherited from NSObject
static new(): TKChartAxisMajorTickStyle; // inherited from NSObject
maxTickClippingMode: TKChartAxisClippingMode;
minTickClippingMode: TKChartAxisClippingMode;
}
declare const enum TKChartAxisPlotMode {
OnTicks = 0,
BetweenTicks = 1
}
declare const enum TKChartAxisPosition {
Left = 0,
Right = 1,
Top = 2,
Bottom = 3
}
declare class TKChartAxisRender extends TKChartRender {
static alloc(): TKChartAxisRender; // inherited from NSObject
static layer(): TKChartAxisRender; // inherited from CALayer
static new(): TKChartAxisRender; // inherited from NSObject
readonly axis: TKChartAxis;
readonly isVertical: boolean;
constructor(o: { axis: TKChartAxis; chart: TKChart; });
boundsRect(): CGRect;
initWithAxisChart(axis: TKChartAxis, chart: TKChart): this;
sizeThatFits(size: CGSize): CGSize;
}
declare class TKChartAxisStyle extends TKStyleNode {
static alloc(): TKChartAxisStyle; // inherited from NSObject
static new(): TKChartAxisStyle; // inherited from NSObject
backgroundFill: TKFill;
readonly labelStyle: TKChartAxisLabelStyle;
lineHidden: boolean;
lineLocation: number;
lineStroke: TKStroke;
readonly majorTickStyle: TKChartAxisMajorTickStyle;
readonly minorTickStyle: TKChartAxisTickStyle;
readonly titleStyle: TKChartAxisTitleStyle;
}
declare class TKChartAxisTickStyle extends TKStyleNode {
static alloc(): TKChartAxisTickStyle; // inherited from NSObject
static new(): TKChartAxisTickStyle; // inherited from NSObject
ticksFill: TKFill;
ticksHidden: boolean;
ticksLength: number;
ticksOffset: number;
ticksStroke: TKStroke;
ticksWidth: number;
}
declare const enum TKChartAxisTitleAlignment {
Center = 0,
LeftOrTop = 1,
RightOrBottom = 2
}
declare class TKChartAxisTitleStyle extends TKChartLabelStyle {
static alloc(): TKChartAxisTitleStyle; // inherited from NSObject
static new(): TKChartAxisTitleStyle; // inherited from NSObject
alignment: TKChartAxisTitleAlignment;
rotationAngle: number;
textOffset: number;
}
declare class TKChartBalloonAnnotation extends TKChartPointAnnotation {
static alloc(): TKChartBalloonAnnotation; // inherited from NSObject
static new(): TKChartBalloonAnnotation; // inherited from NSObject
attributedText: NSAttributedString;
size: CGSize;
readonly style: TKChartBalloonAnnotationStyle;
text: string;
view: UIView;
constructor(o: { text: string; });
constructor(o: { text: string; point: TKChartData; forSeries: TKChartSeries; });
constructor(o: { text: string; point: TKChartData; forXAxis: TKChartAxis; forYAxis: TKChartAxis; });
constructor(o: { text: string; x: any; y: any; forSeries: TKChartSeries; });
constructor(o: { text: string; x: any; y: any; forXAxis: TKChartAxis; forYAxis: TKChartAxis; });
initWithText(text: string): this;
initWithTextPointForSeries(text: string, point: TKChartData, series: TKChartSeries): this;
initWithTextPointForXAxisForYAxis(text: string, point: TKChartData, xAxis: TKChartAxis, yAxis: TKChartAxis): this;
initWithTextXYForSeries(text: string, xValue: any, yValue: any, series: TKChartSeries): this;
initWithTextXYForXAxisForYAxis(text: string, xValue: any, yValue: any, xAxis: TKChartAxis, yAxis: TKChartAxis): this;
}
declare class TKChartBalloonAnnotationStyle extends TKChartAnnotationStyle {
static alloc(): TKChartBalloonAnnotationStyle; // inherited from NSObject
static new(): TKChartBalloonAnnotationStyle; // inherited from NSObject
arrowSize: CGSize;
cornerRadius: number;
distanceFromPoint: number;
fill: TKFill;
font: UIFont;
horizontalAlign: TKChartBalloonHorizontalAlignment;
insets: UIEdgeInsets;
stroke: TKStroke;
textAlignment: NSTextAlignment;
textColor: UIColor;
textOrientation: TKChartBalloonAnnotationTextOrientation;
verticalAlign: TKChartBalloonVerticalAlignment;
}
declare const enum TKChartBalloonAnnotationTextOrientation {
Vertical = 0,
Horizontal = 1
}
declare const enum TKChartBalloonHorizontalAlignment {
Center = 0,
Left = 1,
Right = 2
}
declare const enum TKChartBalloonVerticalAlignment {
Center = 0,
Top = 1,
Bottom = 2
}
declare class TKChartBandAnnotation extends TKChartAnnotation {
static alloc(): TKChartBandAnnotation; // inherited from NSObject
static new(): TKChartBandAnnotation; // inherited from NSObject
axis: TKChartAxis;
range: TKRange;
readonly style: TKChartBandAnnotationStyle;
constructor(o: { range: TKRange; forAxis: TKChartAxis; });
constructor(o: { range: TKRange; forAxis: TKChartAxis; withFill: TKFill; withStroke: TKStroke; });
initWithRangeForAxis(aRange: TKRange, anAxis: TKChartAxis): this;
initWithRangeForAxisWithFillWithStroke(aRange: TKRange, anAxis: TKChartAxis, fill: TKFill, stroke: TKStroke): this;
}
declare class TKChartBandAnnotationStyle extends TKChartGridLineAnnotationStyle {
static alloc(): TKChartBandAnnotationStyle; // inherited from NSObject
static new(): TKChartBandAnnotationStyle; // inherited from NSObject
fill: TKFill;
}
declare class TKChartBandIndicator extends TKChartFinancialIndicator {
static alloc(): TKChartBandIndicator; // inherited from NSObject
static new(): TKChartBandIndicator; // inherited from NSObject
}
declare class TKChartBandVisualPoint extends TKChartVisualPoint {
static alloc(): TKChartBandVisualPoint; // inherited from NSObject
static new(): TKChartBandVisualPoint; // inherited from NSObject
signalY: number;
constructor(o: { point: CGPoint; signalY: number; });
initWithPointSignalY(point: CGPoint, signalY: number): this;
}
declare class TKChartBarSeries extends TKChartSeries {
static alloc(): TKChartBarSeries; // inherited from NSObject
static new(): TKChartBarSeries; // inherited from NSObject
allowClustering: boolean;
gapLength: number;
maxBarHeight: number;
minBarHeight: number;
}
declare class TKChartBollingerBandIndicator extends TKChartBandIndicator {
static alloc(): TKChartBollingerBandIndicator; // inherited from NSObject
static new(): TKChartBollingerBandIndicator; // inherited from NSObject
period: number;
width: number;
}
declare class TKChartBubbleDataPoint extends NSObject implements TKChartData {
static alloc(): TKChartBubbleDataPoint; // inherited from NSObject
static dataPointWithXYArea(xValue: any, yValue: any, area: number): TKChartBubbleDataPoint;
static new(): TKChartBubbleDataPoint; // inherited from NSObject
area: number;
dataXValue: any;
dataYValue: any;
readonly close: number; // inherited from TKChartData
readonly dataName: string; // inherited from TKChartData
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly high: number; // inherited from TKChartData
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly low: number; // inherited from TKChartData
readonly open: number; // inherited from TKChartData
readonly signalYValue: any; // inherited from TKChartData
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly volume: number; // inherited from TKChartData
readonly // inherited from NSObjectProtocol
constructor(o: { x: any; y: any; area: number; });
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
initWithXYArea(xValue: any, yValue: any, area: 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;
}
declare class TKChartBubbleSeries extends TKChartScatterSeries {
static alloc(): TKChartBubbleSeries; // inherited from NSObject
static new(): TKChartBubbleSeries; // inherited from NSObject
biggestBubbleDiameterForAutoscale: number;
scale: number;
}
declare class TKChartBubbleVisualPoint extends TKChartVisualPoint {
static alloc(): TKChartBubbleVisualPoint; // inherited from NSObject
static new(): TKChartBubbleVisualPoint; // inherited from NSObject
diameter: number;
}
declare class TKChartCandlestickBar extends TKChartOhlcBar {
static alloc(): TKChartCandlestickBar; // inherited from NSObject
static new(): TKChartCandlestickBar; // inherited from NSObject
}
declare class TKChartCandlestickSeries extends TKChartOhlcSeries {
static alloc(): TKChartCandlestickSeries; // inherited from NSObject
static new(): TKChartCandlestickSeries; // inherited from NSObject
}
declare class TKChartCategory extends NSObject {
static alloc(): TKChartCategory; // inherited from NSObject
static categoryWithDescription(description: string): TKChartCategory;
static new(): TKChartCategory; // inherited from NSObject
constructor(o: { description: string; });
initWithDescription(description: string): this;
}
declare class TKChartCategoryAxis extends TKChartAxis {
static alloc(): TKChartCategoryAxis; // inherited from NSObject
static new(): TKChartCategoryAxis; // inherited from NSObject
baseline: number;
readonly categories: NSArray<any>;
readonly majorTickInterval: number;
minorTickInterval: number;
offset: number;
constructor(o: { categories: NSArray<any>; });
constructor(o: { categories: NSArray<any>; andRange: TKRange; });
addCategoriesFromArray(categories: NSArray<any>): void;
addCategory(category: any): void;
initWithCategories(categories: NSArray<any>): this;
initWithCategoriesAndRange(categories: NSArray<any>, range: TKRange): this;
removeAllCategories(): void;
removeCategoriesInArray(categories: NSArray<any>): void;
removeCategory(category: any): void;
setPlotMode(plotMode: TKChartAxisPlotMode): void;
}
declare class TKChartChaikinOscillator extends TKChartFinancialIndicator {
static alloc(): TKChartChaikinOscillator; // inherited from NSObject
static new(): TKChartChaikinOscillator; // inherited from NSObject
longPeriod: number;
shortPeriod: number;
}
declare class TKChartColumnSeries extends TKChartSeries {
static alloc(): TKChartColumnSeries; // inherited from NSObject
static new(): TKChartColumnSeries; // inherited from NSObject
allowClustering: boolean;
gapLength: number;
maxColumnWidth: number;
minColumnWidth: number;
}
declare class TKChartCommodityChannelIndex extends TKChartFinancialIndicator {
static alloc(): TKChartCommodityChannelIndex; // inherited from NSObject
static new(): TKChartCommodityChannelIndex; // inherited from NSObject
period: number;
}
declare class TKChartCrossLineAnnotation extends TKChartPointAnnotation {
static alloc(): TKChartCrossLineAnnotation; // inherited from NSObject
static new(): TKChartCrossLineAnnotation; // inherited from NSObject
readonly style: TKChartCrossLineAnnotationStyle;
}
declare const enum TKChartCrossLineAnnotationOrientation {
Horizontal = 1,
Vertical = 2
}
declare class TKChartCrossLineAnnotationStyle extends TKChartAnnotationStyle {
static alloc(): TKChartCrossLineAnnotationStyle; // inherited from NSObject
static new(): TKChartCrossLineAnnotationStyle; // inherited from NSObject
horizontalLineStroke: TKStroke;
insets: UIEdgeInsets;
orientation: TKChartCrossLineAnnotationOrientation;
pointShape: TKShape;
pointShapeFill: TKFill;
pointShapeInsets: UIEdgeInsets;
pointShapeStroke: TKStroke;
verticalLineStroke: TKStroke;
}
interface TKChartData extends NSObjectProtocol {
area?: number;
close?: number;
dataName?: string;
dataXValue: any;
dataYValue: any;
high?: number;
low?: number;
open?: number;
signalYValue?: any;
volume?: number;
}
declare var TKChartData: {
prototype: TKChartData;
};
declare class TKChartDataPoint extends NSObject implements TKChartData {
static alloc(): TKChartDataPoint; // inherited from NSObject
static dataPointWithXY(xValue: any, yValue: any): TKChartDataPoint;
static dataPointWithXYName(xValue: any, yValue: any, name: string): TKChartDataPoint;
static new(): TKChartDataPoint; // inherited from NSObject
dataName: string;
dataXValue: any;
dataYValue: any;
readonly area: number; // inherited from TKChartData
readonly close: number; // inherited from TKChartData
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly high: number; // inherited from TKChartData
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly low: number; // inherited from TKChartData
readonly open: number; // inherited from TKChartData
readonly signalYValue: any; // inherited from TKChartData
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly volume: number; // inherited from TKChartData
readonly // inherited from NSObjectProtocol
constructor(o: { name: string; value: any; });
constructor(o: { x: any; y: any; });
constructor(o: { x: any; y: any; name: string; });
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
initWithNameValue(name: string, value: any): this;
initWithXY(xValue: any, yValue: any): this;
initWithXYName(xValue: any, yValue: any, name: string): 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 TKChartDataSource extends NSObjectProtocol {
chartDataPointAtIndexForSeriesAtIndex?(chart: TKChart, dataIndex: number, seriesIndex: number): TKChartData;
chartDataPointsForSeriesAtIndex?(chart: TKChart, seriesIndex: number): NSArray<any>;
chartNumberOfDataPointsForSeriesAtIndex?(chart: TKChart, seriesIndex: number): number;
numberOfSeriesForChart(chart: TKChart): number;
seriesForChartAtIndex(chart: TKChart, index: number): TKChartSeries;
}
declare var TKChartDataSource: {
prototype: TKChartDataSource;
};
declare class TKChartDateTimeAxis extends TKChartAxis {
static alloc(): TKChartDateTimeAxis; // inherited from NSObject
static new(): TKChartDateTimeAxis; // inherited from NSObject
baseline: Date;
majorTickInterval: number;
majorTickIntervalUnit: TKChartDateTimeAxisIntervalUnit;
minorTickIntervalUnit: TKChartDateTimeAxisIntervalUnit;
offset: Date;
constructor(o: { minimumDate: Date; andMaximumDate: Date; });
initWithMinimumDateAndMaximumDate(minDate: Date, maxDate: Date): this;
setMajorTickCount(tickCount: number): void;
setPlotMode(plotMode: TKChartAxisPlotMode): void;
}
declare const enum TKChartDateTimeAxisIntervalUnit {
Seconds = 0,
Minutes = 1,
Hours = 2,
Days = 3,
Weeks = 4,
Months = 5,
Years = 6,
Custom = 7
}
declare class TKChartDateTimeCategoryAxis extends TKChartAxis {
static alloc(): TKChartDateTimeCategoryAxis; // inherited from NSObject
static new(): TKChartDateTimeCategoryAxis; // inherited from NSObject
baseline: Date;
readonly categories: NSArray<any>;
dateComponent: NSCalendarUnit;
readonly majorTickInterval: number;
minorTickInterval: number;
offset: Date;
constructor(o: { minimumDate: Date; andMaximumDate: Date; });
initWithMinimumDateAndMaximumDate(minDate: Date, maxDate: Date): this;
removeAllCategories(): void;
setPlotMode(plotMode: TKChartAxisPlotMode): void;
}
interface TKChartDelegate extends NSObjectProtocol {
chartAnimationForSeriesWithStateInRect?(chart: TKChart, series: TKChartSeries, state: TKChartSeriesRenderState, rect: CGRect): CAAnimation;
chartAttributedTextForAxisValueAtIndex?(chart: TKChart, axis: TKChartAxis, value: any, index: number): NSAttributedString;
chartDidDeselectPointInSeriesAtIndex?(chart: TKChart, point: TKChartData, series: TKChartSeries, index: number): void;
chartDidDeselectSeries?(chart: TKChart, series: TKChartSeries): void;
chartDidPan?(chart: TKChart): void;
chartDidSelectPointInSeriesAtIndex?(chart: TKChart, point: TKChartData, series: TKChartSeries, index: number): void;
chartDidSelectSeries?(chart: TKChart, series: TKChartSeries): void;
chartDidTapOnLegendItem?(chart: TKChart, legendItem: TKChartLegendItem): void;
chartDidZoom?(chart: TKChart): void;
chartLabelForDataPointPropertyInSeriesAtIndex?(chart: TKChart, dataPoint: TKChartData, propertyName: string, series: TKChartSeries, dataIndex: number): TKChartPointLabel;
chartLegendItemForSeriesAtIndex?(chart: TKChart, series: TKChartSeries, index: number): TKChartLegendItem;
chartPaletteItemForPointInSeries?(chart: TKChart, index: number, series: TKChartSeries): TKChartPaletteItem;
chartPaletteItemForSeriesAtIndex?(chart: TKChart, series: TKChartSeries, index: number): TKChartPaletteItem;
chartPointLabelRenderForSeriesWithRender?(chart: TKChart, series: TKChartSeries, render: TKChartSeriesRender): TKChartPointLabelRender;
chartShapeForSeriesAtIndex?(chart: TKChart, series: TKChartSeries, index: number): TKShape;
chartTextForAxisValueAtIndex?(chart: TKChart, axis: TKChartAxis, value: any, index: number): string;
chartTextForLabelAtPointPropertyInSeriesAtIndex?(chart: TKChart, dataPoint: TKChartData, propertyName: string, series: TKChartSeries, dataIndex: number): string;
chartTrackballDidHideSelection?(chart: TKChart, selection: NSArray<any>): void;
chartTrackballDidTrackSelection?(chart: TKChart, selection: NSArray<any>): void;
chartUpdateLegendItemForSeriesAtIndex?(chart: TKChart, item: TKChartLegendItem, series: TKChartSeries, index: number): void;
chartWillPan?(chart: TKChart): void;
chartWillZoom?(chart: TKChart): void;
}
declare var TKChartDelegate: {
prototype: TKChartDelegate;
};
declare class TKChartDetrendedPriceOscillator extends TKChartFinancialIndicator {
static alloc(): TKChartDetrendedPriceOscillator; // inherited from NSObject
static new(): TKChartDetrendedPriceOscillator; // inherited from NSObject
period: number;
}
declare class TKChartDonutSeries extends TKChartPieSeries {
static alloc(): TKChartDonutSeries; // inherited from NSObject
static new(): TKChartDonutSeries; // inherited from NSObject
innerRadius: number;
}
declare class TKChartEaseOfMovementIndicator extends TKChartFinancialIndicator {
static alloc(): TKChartEaseOfMovementIndicator; // inherited from NSObject
static new(): TKChartEaseOfMovementIndicator; // inherited from NSObject
period: number;
}
declare class TKChartExponentialMovingAverageIndicator extends TKChartSimpleMovingAverageIndicator {
static alloc(): TKChartExponentialMovingAverageIndicator; // inherited from NSObject
static new(): TKChartExponentialMovingAverageIndicator; // inherited from NSObject
}
declare class TKChartFastStochasticIndicator extends TKChartSignalLineIndicator {
static alloc(): TKChartFastStochasticIndicator; // inherited from NSObject
static new(): TKChartFastStochasticIndicator; // inherited from NSObject
period: number;
signalPeriod: number;
}
declare class TKChartFinancialDataPoint extends NSObject implements TKChartData {
static alloc(): TKChartFinancialDataPoint; // inherited from NSObject
static dataPointWithXOpenHighLowClose(xValue: any, open: number, high: number, low: number, close: number): TKChartFinancialDataPoint;
static dataPointWithXOpenHighLowCloseVolume(xValue: any, open: number, high: number, low: number, close: number, volume: number): TKChartFinancialDataPoint;
static new(): TKChartFinancialDataPoint; // inherited from NSObject
close: number;
dataName: string;
dataXValue: any;
dataYValue: any;
high: number;
low: number;
open: number;
volume: number;
readonly area: number; // inherited from TKChartData
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly signalYValue: any; // inherited from TKChartData
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
constructor(o: { x: any; open: number; high: number; low: number; close: number; volume: number; });
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
initWithXOpenHighLowCloseVolume(xValue: any, open: number, high: number, low: number, close: number, volume: 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;
}
declare class TKChartFinancialIndicator extends TKChartSeries {
static alloc(): TKChartFinancialIndicator; // inherited from NSObject
static new(): TKChartFinancialIndicator; // inherited from NSObject
marginForHitDetection: number;
series: TKChartSeries;
constructor(o: { series: TKChartSeries; });
initWithSeries(series: TKChartSeries): this;
}
declare class TKChartForceIndexIndicator extends TKChartFinancialIndicator {
static alloc(): TKChartForceIndexIndicator; // inherited from NSObject
static new(): TKChartForceIndexIndicator; // inherited from NSObject
period: number;
}
declare class TKChartFullStochasticIndicator extends TKChartSlowStochasticIndicator {
static alloc(): TKChartFullStochasticIndicator; // inherited from NSObject
static new(): TKChartFullStochasticIndicator; // inherited from NSObject
smoothPeriod: number;
}
declare const enum TKChartGridDrawMode {
HorizontalFirst = 0,
VerticalFirst = 1
}
declare class TKChartGridLineAnnotation extends TKChartAnnotation {
static alloc(): TKChartGridLineAnnotation; // inherited from NSObject
static new(): TKChartGridLineAnnotation; // inherited from NSObject
axis: TKChartAxis;
readonly style: TKChartGridLineAnnotationStyle;
value: any;
constructor(o: { value: any; forAxis: TKChartAxis; });
constructor(o: { value: any; forAxis: TKChartAxis; withStroke: TKStroke; });
initWithValueForAxis(value: any, axis: TKChartAxis): this;
initWithValueForAxisWithStroke(value: any, axis: TKChartAxis, stroke: TKStroke): this;
}
declare class TKChartGridLineAnnotationStyle extends TKChartAnnotationStyle {
static alloc(): TKChartGridLineAnnotationStyle; // inherited from NSObject
static new(): TKChartGridLineAnnotationStyle; // inherited from NSObject
stroke: TKStroke;
}
declare class TKChartGridStyle extends TKStyleNode {
static alloc(): TKChartGridStyle; // inherited from NSObject
static new(): TKChartGridStyle; // inherited from NSObject
backgroundFill: TKFill;
drawOrder: TKChartGridDrawMode;
horizontalAlternateFill: TKFill;
horizontalFill: TKFill;
horizontalLineAlternateStroke: TKStroke;
horizontalLineStroke: TKStroke;
horizontalLinesHidden: boolean;
verticalAlternateFill: TKFill;
verticalFill: TKFill;
verticalLineAlternateStroke: TKStroke;
verticalLineStroke: TKStroke;
verticalLinesHidden: boolean;
zPosition: TKChartGridZPosition;
}
declare const enum TKChartGridZPosition {
BelowSeries = 0,
AboveSeries = 1
}
declare class TKChartLabelStyle extends TKStyleNode {
static alloc(): TKChartLabelStyle; // inherited from NSObject
static new(): TKChartLabelStyle; // inherited from NSObject
font: UIFont;
shadowColor: UIColor;
shadowOffset: CGSize;
textColor: UIColor;
textHidden: boolean;
}
declare class TKChartLayerAnnotation extends TKChartPointAnnotation {
static alloc(): TKChartLayerAnnotation; // inherited from NSObject
static new(): TKChartLayerAnnotation; // inherited from NSObject
layer: CALayer;
constructor(o: { layer: CALayer; });
constructor(o: { layer: CALayer; point: TKChartData; forSeries: TKChartSeries; });
constructor(o: { layer: CALayer; point: TKChartData; forXAxis: TKChartAxis; forYAxis: TKChartAxis; });
constructor(o: { layer: CALayer; x: any; y: any; forSeries: TKChartSeries; });
constructor(o: { layer: CALayer; x: any; y: any; forXAxis: TKChartAxis; forYAxis: TKChartAxis; });
initWithLayer(layer: CALayer): this;
initWithLayerPointForSeries(layer: CALayer, point: TKChartData, series: TKChartSeries): this;
initWithLayerPointForXAxisForYAxis(layer: CALayer, point: TKChartData, xAxis: TKChartAxis, yAxis: TKChartAxis): this;
initWithLayerXYForSeries(layer: CALayer, xValue: any, yValue: any, series: TKChartSeries): this;
initWithLayerXYForXAxisForYAxis(layer: CALayer, xValue: any, yValue: any, xAxis: TKChartAxis, yAxis: TKChartAxis): this;
}
declare class TKChartLegendContainer extends TKCoreStackLayoutView {
static alloc(): TKChartLegendContainer; // inherited from NSObject
static appearance(): TKChartLegendContainer; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKChartLegendContainer; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKChartLegendContainer; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKChartLegendContainer; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKChartLegendContainer; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKChartLegendContainer; // inherited from UIAppearance
static new(): TKChartLegendContainer; // inherited from NSObject
readonly itemCount: number;
preferredSize: CGSize;
addItem(item: TKChartLegendItem): void;
indexOfItem(item: TKChartLegendItem): number;
itemAtIndex(index: number): TKChartLegendItem;
removeAllItems(): void;
}
declare class TKChartLegendItem extends UIView {
static alloc(): TKChartLegendItem; // inherited from NSObject
static appearance(): TKChartLegendItem; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKChartLegendItem; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKChartLegendItem; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKChartLegendItem; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKChartLegendItem; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKChartLegendItem; // inherited from UIAppearance
static new(): TKChartLegendItem; // inherited from NSObject
icon: UIView;
label: UILabel;
selectionInfo: TKChartSelectionInfo;
readonly stack: TKCoreStackLayout;
style: TKChartLegendItemStyle;
tap(tapRecognizer: UITapGestureRecognizer): void;
update(): void;
}
declare class TKChartLegendItemStyle extends TKStyleNode {
static alloc(): TKChartLegendItemStyle; // inherited from NSObject
static new(): TKChartLegendItemStyle; // inherited from NSObject
fill: TKFill;
iconSize: CGSize;
readonly labelStyle: TKChartLabelStyle;
stroke: TKStroke;
}
declare const enum TKChartLegendOffsetOrigin {
TopLeft = 0,
TopRight = 1,
BottomLeft = 2,
BottomRight = 3
}
declare const enum TKChartLegendPosition {
Left = 0,
Right = 1,
Top = 2,
Bottom = 3,
Floating = 4
}
declare class TKChartLegendStyle extends TKStyleNode {
static alloc(): TKChartLegendStyle; // inherited from NSObject
static new(): TKChartLegendStyle; // inherited from NSObject
fill: TKFill;
insets: UIEdgeInsets;
offset: UIOffset;
offsetOrigin: TKChartLegendOffsetOrigin;
position: TKChartLegendPosition;
stroke: TKStroke;
}
declare class TKChartLegendView extends TKView {
static alloc(): TKChartLegendView; // inherited from NSObject
static appearance(): TKChartLegendView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKChartLegendView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKChartLegendView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKChartLegendView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKChartLegendView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKChartLegendView; // inherited from UIAppearance
static new(): TKChartLegendView; // inherited from NSObject
allowSelection: boolean;
chart: TKChart;
readonly container: TKChartLegendContainer;
showTitle: boolean;
readonly style: TKChartLegendStyle;
readonly titleLabel: UILabel;
constructor(o: { chart: TKChart; });
initWithChart(chart: TKChart): this;
reloadItems(): void;
update(): void;
}
declare class TKChartLineSeries extends TKChartSeries {
static alloc(): TKChartLineSeries; // inherited from NSObject
static new(): TKChartLineSeries; // inherited from NSObject
displayNilValuesAsGaps: boolean;
marginForHitDetection: number;
}
declare class TKChartLogarithmicAxis extends TKChartNumericAxis {
static alloc(): TKChartLogarithmicAxis; // inherited from NSObject
static new(): TKChartLogarithmicAxis; // inherited from NSObject
exponentStep: number;
logarithmBase: number;
}
declare class TKChartMACDIndicator extends TKChartSignalLineIndicator {
static alloc(): TKChartMACDIndicator; // inherited from NSObject
static new(): TKChartMACDIndicator; // inherited from NSObject
longPeriod: number;
shortPeriod: number;
signalPeriod: number;
}
declare class TKChartMarketFacilitationIndex extends TKChartFinancialIndicator {
static alloc(): TKChartMarketFacilitationIndex; // inherited from NSObject
static new(): TKChartMarketFacilitationIndex; // inherited from NSObject
gapLength: number;
maxColumnWidth: number;
minColumnWidth: number;
range: number;
}
declare class TKChartMedianPriceIndicator extends TKChartFinancialIndicator {
static alloc(): TKChartMedianPriceIndicator; // inherited from NSObject
static new(): TKChartMedianPriceIndicator; // inherited from NSObject
}
declare class TKChartModifiedMovingAverageIndicator extends TKChartExponentialMovingAverageIndicator {
static alloc(): TKChartModifiedMovingAverageIndicator; // inherited from NSObject
static new(): TKChartModifiedMovingAverageIndicator; // inherited from NSObject
}
declare class TKChartMoneyFlowIndexIndicator extends TKChartFinancialIndicator {
static alloc(): TKChartMoneyFlowIndexIndicator; // inherited from NSObject
static new(): TKChartMoneyFlowIndexIndicator; // inherited from NSObject
period: number;
}
declare class TKChartMovingAverageEnvelopesIndicator extends TKChartBandIndicator {
static alloc(): TKChartMovingAverageEnvelopesIndicator; // inherited from NSObject
static new(): TKChartMovingAverageEnvelopesIndicator; // inherited from NSObject
envelopesPercentage: number;
period: number;
}
declare class TKChartNegativeVolumeIndexIndicator extends TKChartFinancialIndicator {
static alloc(): TKChartNegativeVolumeIndexIndicator; // inherited from NSObject
static new(): TKChartNegativeVolumeIndexIndicator; // inherited from NSObject
}
declare class TKChartNumericAxis extends TKChartAxis {
static alloc(): TKChartNumericAxis; // inherited from NSObject
static new(): TKChartNumericAxis; // inherited from NSObject
baseline: number;
labelDisplayMode: TKChartNumericAxisLabelDisplayMode;
majorTickInterval: number;
minorTickInterval: number;
offset: number;
}
declare const enum TKChartNumericAxisLabelDisplayMode {
Value = 0,
Percentage = 1
}
declare class TKChartOhlcBar extends TKChartVisualPoint {
static alloc(): TKChartOhlcBar; // inherited from NSObject
static new(): TKChartOhlcBar; // inherited from NSObject
bodyWidth: number;
closeValue: number;
highValue: number;
lowValue: number;
openValue: number;
constructor(o: { point: TKChartFinancialDataPoint; atIndex: number; series: TKChartSeries; render: TKChartSeriesRender; });
drawInContext(ctx: any): void;
initWithPointAtIndexSeriesRender(data: TKChartFinancialDataPoint, index: number, series: TKChartSeries, render: TKChartSeriesRender): this;
}
declare class TKChartOhlcSeries extends TKChartColumnSeries {
static alloc(): TKChartOhlcSeries; // inherited from NSObject
static new(): TKChartOhlcSeries; // inherited from NSObject
}
declare class TKChartOnBalanceVolumeIndicator extends TKChartFinancialIndicator {
static alloc(): TKChartOnBalanceVolumeIndicator; // inherited from NSObject
static new(): TKChartOnBalanceVolumeIndicator; // inherited from NSObject
}
declare class TKChartPalette extends NSObject {
static alloc(): TKChartPalette; // inherited from NSObject
static new(): TKChartPalette; // inherited from NSObject
readonly items: NSArray<any>;
readonly itemsCount: number;
addPaletteItem(item: TKChartPaletteItem): void;
addPaletteItems(items: NSArray<any>): void;
clearPalette(): void;
insertPaletteItemAtIndex(item: TKChartPaletteItem, index: number): void;
paletteItemAtIndex(index: number): TKChartPaletteItem;
replacePaletteItemAtIndex(item: TKChartPaletteItem, index: number): void;
}
declare class TKChartPaletteItem extends NSObject {
static alloc(): TKChartPaletteItem; // inherited from NSObject
static new(): TKChartPaletteItem; // inherited from NSObject
static paletteItemWithDrawables(drawables: NSArray<any>): TKChartPaletteItem;
static paletteItemWithFill(fill: TKFill): TKChartPaletteItem;
static paletteItemWithStroke(stroke: TKStroke): TKChartPaletteItem;
static paletteItemWithStrokeAndFill(stroke: TKStroke, fill: TKFill): TKChartPaletteItem;
drawables: NSArray<any>;
fill: TKFill;
font: UIFont;
stroke: TKStroke;
textColor: UIColor;
constructor(o: { drawables: NSArray<any>; });
constructor(o: { fill: TKFill; });
constructor(o: { stroke: TKStroke; });
constructor(o: { stroke: TKStroke; andFill: TKFill; });
initWithDrawables(drawables: NSArray<any>): this;
initWithFill(fill: TKFill): this;
initWithStroke(stroke: TKStroke): this;
initWithStrokeAndFill(stroke: TKStroke, fill: TKFill): this;
}
declare class TKChartPercentagePriceOscillator extends TKChartMACDIndicator {
static alloc(): TKChartPercentagePriceOscillator; // inherited from NSObject
static new(): TKChartPercentagePriceOscillator; // inherited from NSObject
}
declare class TKChartPercentageVolumeOscillator extends TKChartMACDIndicator {
static alloc(): TKChartPercentageVolumeOscillator; // inherited from NSObject
static new(): TKChartPercentageVolumeOscillator; // inherited from NSObject
}
declare class TKChartPieSeries extends TKChartSeries {
static alloc(): TKChartPieSeries; // inherited from NSObject
static new(): TKChartPieSeries; // inherited from NSObject
adjustSizeToFit: boolean;
displayPercentage: boolean;
endAngle: number;
expandRadius: number;
labelDisplayMode: TKChartPieSeriesLabelDisplayMode;
outerRadius: number;
radiusInset: number;
rotationAngle: number;
rotationDeceleration: number;
rotationEnabled: boolean;
selectionAngle: number;
startAngle: number;
}
declare const enum TKChartPieSeriesLabelDisplayMode {
Inside = 1,
Outside = 2
}
declare class TKChartPieVisualPoint extends TKChartVisualPoint {
static alloc(): TKChartPieVisualPoint; // inherited from NSObject
static new(): TKChartPieVisualPoint; // inherited from NSObject
distanceFromCenter: number;
startAngle: number;
}
declare class TKChartPlotView extends TKView implements UIGestureRecognizerDelegate {
static alloc(): TKChartPlotView; // inherited from NSObject
static appearance(): TKChartPlotView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKChartPlotView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKChartPlotView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKChartPlotView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKChartPlotView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKChartPlotView; // inherited from UIAppearance
static new(): TKChartPlotView; // inherited from NSObject
readonly chart: TKChart;
readonly doubleTapGestureRecognizer: UITapGestureRecognizer;
handleTap: boolean;
readonly longPressRecognizer: UILongPressGestureRecognizer;
readonly panZoomRecognizer: UIGestureRecognizer;
readonly rotateOneFingerRecognizer: UIGestureRecognizer;
readonly rotateTwoFingerRecognizer: UIRotationGestureRecognizer;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
constructor(o: { chart: TKChart; });
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
gestureRecognizerShouldBeRequiredToFailByGestureRecognizer(gestureRecognizer: UIGestureRecognizer, otherGestureRecognizer: UIGestureRecognizer): boolean;
gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer): boolean;
gestureRecognizerShouldReceivePress(gestureRecognizer: UIGestureRecognizer, press: UIPress): boolean;
gestureRecognizerShouldReceiveTouch(gestureRecognizer: UIGestureRecognizer, touch: UITouch): boolean;
gestureRecognizerShouldRecognizeSimultaneouslyWithGestureRecognizer(gestureRecognizer: UIGestureRecognizer, otherGestureRecognizer: UIGestureRecognizer): boolean;
gestureRecognizerShouldRequireFailureOfGestureRecognizer(gestureRecognizer: UIGestureRecognizer, otherGestureRecognizer: UIGestureRecognizer): boolean;
hitTestForPoint(point: CGPoint): TKChartSelectionInfo;
initWithChart(chart: TKChart): 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;
renderForSeries(series: TKChartSeries): TKChartSeriesRender;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
self(): this;
}
declare class TKChartPointAnnotation extends TKChartAnnotation {
static alloc(): TKChartPointAnnotation; // inherited from NSObject
static new(): TKChartPointAnnotation; // inherited from NSObject
offset: UIOffset;
position: TKChartData;
series: TKChartSeries;
xAxis: TKChartAxis;
yAxis: TKChartAxis;
constructor(o: { point: TKChartData; forSeries: TKChartSeries; });
constructor(o: { point: TKChartData; forXAxis: TKChartAxis; forYAxis: TKChartAxis; });
constructor(o: { x: any; y: any; forSeries: TKChartSeries; });
constructor(o: { x: any; y: any; forXAxis: TKChartAxis; forYAxis: TKChartAxis; });
initWithPointForSeries(point: TKChartData, series: TKChartSeries): this;
initWithPointForXAxisForYAxis(point: TKChartData, xAxis: TKChartAxis, yAxis: TKChartAxis): this;
initWithXYForSeries(xValue: any, yValue: any, series: TKChartSeries): this;
initWithXYForXAxisForYAxis(xValue: any, yValue: any, xAxis: TKChartAxis, yAxis: TKChartAxis): this;
locationInRectForChart(bounds: CGRect, chart: TKChart): CGPoint;
}
declare class TKChartPointLabel extends NSObject {
static alloc(): TKChartPointLabel; // inherited from NSObject
static new(): TKChartPointLabel; // inherited from NSObject
readonly dataPoint: TKChartData;
readonly series: TKChartSeries;
readonly style: TKChartPointLabelStyle;
text: string;
constructor(o: { point: TKChartData; series: TKChartSeries; text: string; });
drawInContextInRectForVisualPointColor(ctx: any, bounds: CGRect, visualPoint: TKChartVisualPoint, paletteTextColor: UIColor): void;
initWithPointSeriesText(point: TKChartData, series: TKChartSeries, text: string): this;
sizeThatFits(size: CGSize): CGSize;
}
declare const enum TKChartPointLabelClipMode {
Hidden = 0,
Visible = 1
}
declare const enum TKChartPointLabelLayoutMode {
Manual = 0,
Auto = 1
}
declare const enum TKChartPointLabelOrientation {
Vertical = 0,
Horizontal = 1
}
declare class TKChartPointLabelRender extends NSObject {
static alloc(): TKChartPointLabelRender; // inherited from NSObject
static new(): TKChartPointLabelRender; // inherited from NSObject
readonly chartDelegate: TKChartDelegate;
readonly render: TKChartSeriesRender;
constructor(o: { render: TKChartSeriesRender; });
initWithRender(render: TKChartSeriesRender): this;
isPointInsideRect(point: CGPoint, rect: CGRect): boolean;
labelForDataPointPropertyInSeriesAtIndex(dataPoint: TKChartData, propertyName: string, series: TKChartSeries, dataIndex: number): TKChartPointLabel;
locationForDataPointForSeriesInRect(dataPoint: TKChartData, series: TKChartSeries, rect: CGRect): CGPoint;
renderPointLabelsForSeriesInRectContext(series: TKChartSeries, bounds: CGRect, ctx: any): void;
}
declare class TKChartPointLabelStyle extends TKChartLabelStyle {
static alloc(): TKChartPointLabelStyle; // inherited from NSObject
static new(): TKChartPointLabelStyle; // inherited from NSObject
blurRadius: number;
clipMode: TKChartPointLabelClipMode;
cornerRadius: number;
fill: TKFill;
formatter: NSFormatter;
insets: UIEdgeInsets;
labelOffset: UIOffset;
layoutMode: TKChartPointLabelLayoutMode;
stringFormat: string;
stroke: TKStroke;
textAlignment: NSTextAlignment;
textOrientation: TKChartPointLabelOrientation;
}
declare class TKChartPositiveVolumeIndexIndicator extends TKChartFinancialIndicator {
static alloc(): TKChartPositiveVolumeIndexIndicator; // inherited from NSObject
static new(): TKChartPositiveVolumeIndexIndicator; // inherited from NSObject
}
declare class TKChartPriceVolumeTrendIndicator extends TKChartFinancialIndicator {
static alloc(): TKChartPriceVolumeTrendIndicator; // inherited from NSObject
static new(): TKChartPriceVolumeTrendIndicator; // inherited from NSObject
}
declare class TKChartRangeBarSeries extends TKChartBarSeries {
static alloc(): TKChartRangeBarSeries; // inherited from NSObject
static new(): TKChartRangeBarSeries; // inherited from NSObject
}
declare class TKChartRangeColumnSeries extends TKChartColumnSeries {
static alloc(): TKChartRangeColumnSeries; // inherited from NSObject
static new(): TKChartRangeColumnSeries; // inherited from NSObject
}
declare class TKChartRangeDataPoint extends NSObject implements TKChartData {
static alloc(): TKChartRangeDataPoint; // inherited from NSObject
static dataPointWithXLowHigh(xValue: any, lowValue: any, highValue: any): TKChartRangeDataPoint;
static dataPointWithYLowHigh(yValue: any, lowValue: any, highValue: any): TKChartRangeDataPoint;
static new(): TKChartRangeDataPoint; // inherited from NSObject
dataXValue: any;
dataYValue: any;
high: any;
low: any;
readonly area: number; // inherited from TKChartData
readonly close: number; // inherited from TKChartData
readonly dataName: string; // inherited from TKChartData
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly open: number; // inherited from TKChartData
readonly signalYValue: any; // inherited from TKChartData
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly volume: number; // inherited from TKChartData
readonly // inherited from NSObjectProtocol
constructor(o: { x: any; low: any; high: any; });
constructor(o: { y: any; low: any; high: any; });
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
initWithXLowHigh(xValue: any, lowValue: any, highValue: any): this;
initWithYLowHigh(yValue: any, lowValue: any, highValue: any): 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 TKChartRangeVisualPoint extends TKChartVisualPoint {
static alloc(): TKChartRangeVisualPoint; // inherited from NSObject
static new(): TKChartRangeVisualPoint; // inherited from NSObject
high: number;
low: number;
constructor(o: { point: CGPoint; low: number; high: number; });
initWithPointLowHigh(point: CGPoint, low: number, high: number): this;
}
declare class TKChartRapidAdaptiveVarianceIndicator extends TKChartFinancialIndicator {
static alloc(): TKChartRapidAdaptiveVarianceIndicator; // inherited from NSObject
static new(): TKChartRapidAdaptiveVarianceIndicator; // inherited from NSObject
longPeriod: number;
shortPeriod: number;
}
declare class TKChartRateOfChangeIndicator extends TKChartFinancialIndicator {
static alloc(): TKChartRateOfChangeIndicator; // inherited from NSObject
static new(): TKChartRateOfChangeIndicator; // inherited from NSObject
period: number;
}
declare class TKChartRelativeMomentumIndex extends TKChartFinancialIndicator {
static alloc(): TKChartRelativeMomentumIndex; // inherited from NSObject
static new(): TKChartRelativeMomentumIndex; // inherited from NSObject
momentum: number;
period: number;
}
declare class TKChartRelativeStrengthIndex extends TKChartFinancialIndicator {
static alloc(): TKChartRelativeStrengthIndex; // inherited from NSObject
static new(): TKChartRelativeStrengthIndex; // inherited from NSObject
period: number;
}
declare class TKChartRender extends CALayer {
static alloc(): TKChartRender; // inherited from NSObject
static layer(): TKChartRender; // inherited from CALayer
static new(): TKChartRender; // inherited from NSObject
readonly chart: TKChart;
constructor(o: { chart: TKChart; });
initWithChart(chart: TKChart): this;
setup(): void;
update(): void;
}
declare class TKChartScatterSeries extends TKChartSeries {
static alloc(): TKChartScatterSeries; // inherited from NSObject
static new(): TKChartScatterSeries; // inherited from NSObject
marginForHitDetection: number;
}
declare class TKChartSelectionInfo extends NSObject implements NSCopying {
static alloc(): TKChartSelectionInfo; // inherited from NSObject
static hitTestInfoWithSeriesDataPointIndex(series: TKChartSeries, dataPointIndex: number): TKChartSelectionInfo;
static hitTestInfoWithSeriesDataPointIndexDistance(series: TKChartSeries, dataPointIndex: number, distance: number): TKChartSelectionInfo;
static new(): TKChartSelectionInfo; // inherited from NSObject
readonly dataPoint: TKChartData;
readonly dataPointIndex: number;
readonly distance: number;
readonly location: CGPoint;
readonly series: TKChartSeries;
constructor(o: { series: TKChartSeries; dataPointIndex: number; });
constructor(o: { series: TKChartSeries; dataPointIndex: number; distance: number; });
copyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
initWithSeriesDataPointIndex(series: TKChartSeries, dataPointIndex: number): this;
initWithSeriesDataPointIndexDistance(series: TKChartSeries, dataPointIndex: number, distance: number): this;
}
declare const enum TKChartSelectionMode {
None = 0,
Single = 1,
Multiple = 2
}
declare class TKChartSeries extends NSObject {
static alloc(): TKChartSeries; // inherited from NSObject
static new(): TKChartSeries; // inherited from NSObject
hidden: boolean;
readonly index: number;
readonly isSelected: boolean;
readonly items: NSArray<any>;
readonly reuseIdentifier: string;
selection: TKChartSeriesSelection;
selectionMode: TKChartSeriesSelectionMode;
sortMode: TKChartSeriesSortMode;
stackInfo: TKChartStackInfo;
readonly style: TKChartSeriesStyle;
tag: number;
title: string;
visibleInLegend: boolean;
readonly visiblePoints: NSArray<any>;
readonly visiblePointsInternal: NSArray<any>;
xAxis: TKChartAxis;
yAxis: TKChartAxis;
constructor(o: { items: NSArray<any>; });
constructor(o: { items: NSArray<any>; forKeys: NSDictionary<any, any>; });
constructor(o: { items: NSArray<any>; forKeys: NSDictionary<any, any>; reuseIdentifier: string; });
constructor(o: { items: NSArray<any>; reuseIdentifier: string; });
constructor(o: { items: NSArray<any>; xValueKey: string; yValueKey: string; });
dataPointAtIndex(dataIndex: number): TKChartData;
initWithItems(items: NSArray<any>): this;
initWithItemsForKeys(items: NSArray<any>, keys: NSDictionary<any, any>): this;
initWithItemsForKeysReuseIdentifier(items: NSArray<any>, keys: NSDictionary<any, any>, reuseIdentifier: string): this;
initWithItemsReuseIdentifier(items: NSArray<any>, reuseIdentifier: string): this;
initWithItemsXValueKeyYValueKey(items: NSArray<any>, xValueKey: string, yValueKey: string): this;
pointIsSelected(index: number): boolean;
prepareForReuse(): void;
renderForChart(chart: TKChart): TKChartSeriesRender;
visiblePointsForAxis(axis: TKChartAxis): NSArray<any>;
}
declare class TKChartSeriesRender extends TKChartRender {
static alloc(): TKChartSeriesRender; // inherited from NSObject
static layer(): TKChartSeriesRender; // inherited from CALayer
static locationOfValueForAxisInRect(numericValue: number, axis: TKChartAxis, bounds: CGRect): number;
static new(): TKChartSeriesRender; // inherited from NSObject
readonly series: NSArray<any>;
readonly seriesRenderStates: TKMutableArray;
constructor(o: { chart: TKChart; forSeries: NSArray<any>; });
addSeries(series: TKChartSeries): boolean;
createVisualPointPointIndexInSeries(data: TKChartData, index: number, series: TKChartSeries): TKChartVisualPoint;
hitTestForPoint(point: CGPoint): TKChartSelectionInfo;
initWithChartForSeries(chart: TKChart, series: NSArray<any>): this;
isCompatibleWithSeries(series: TKChartSeries): boolean;
locationOfPointInSeries(data: TKChartData, series: TKChartSeries): CGPoint;
locationOfXNumericValueInSeries(numericValue: number, series: TKChartSeries): number;
locationOfYNumericValueInSeries(numericValue: number, series: TKChartSeries): number;
pointFromDataPointIndexInSeries(point: TKChartData, index: number, series: TKChartSeries): TKChartVisualPoint;
selectionWillChangeForSeriesAndPoint(series: TKChartSeries, pointIndex: number): void;
}
declare class TKChartSeriesRenderState extends NSObject {
static alloc(): TKChartSeriesRenderState; // inherited from NSObject
static new(): TKChartSeriesRenderState; // inherited from NSObject
readonly index: number;
readonly oldPoints: TKMutableArray;
points: TKMutableArray;
constructor(o: { index: number; });
animationKeyPathForPointAtIndex(pointIndex: number): string;
initWithIndex(index: number): this;
}
declare const enum TKChartSeriesSelection {
NotSet = 0,
None = 1,
Series = 2,
DataPoint = 3,
DataPointMultiple = 4
}
declare const enum TKChartSeriesSelectionMode {
None = 0,
Series = 1,
DataPoint = 2
}
declare const enum TKChartSeriesSortMode {
None = 0,
XAxis = 1,
YAxis = 2
}
declare class TKChartSeriesStyle extends TKStyleNode {
static alloc(): TKChartSeriesStyle; // inherited from NSObject
static new(): TKChartSeriesStyle; // inherited from NSObject
fill: TKFill;
palette: TKChartPalette;
paletteMode: TKChartSeriesStylePaletteMode;
pointLabelStyle: TKChartPointLabelStyle;
pointShape: TKShape;
shapeMode: TKChartSeriesStyleShapeMode;
shapePalette: TKChartPalette;
stroke: TKStroke;
}
declare const enum TKChartSeriesStylePaletteMode {
UseSeriesIndex = 0,
UseItemIndex = 1
}
declare const enum TKChartSeriesStyleShapeMode {
ShowOnMiddlePointsOnly = 0,
AlwaysShow = 1
}
declare class TKChartSignalLineIndicator extends TKChartFinancialIndicator {
static alloc(): TKChartSignalLineIndicator; // inherited from NSObject
static new(): TKChartSignalLineIndicator; // inherited from NSObject
readonly isSignalState: boolean;
}
declare class TKChartSimpleMovingAverageIndicator extends TKChartFinancialIndicator {
static alloc(): TKChartSimpleMovingAverageIndicator; // inherited from NSObject
static new(): TKChartSimpleMovingAverageIndicator; // inherited from NSObject
period: number;
}
declare class TKChartSlowStochasticIndicator extends TKChartFastStochasticIndicator {
static alloc(): TKChartSlowStochasticIndicator; // inherited from NSObject
static new(): TKChartSlowStochasticIndicator; // inherited from NSObject
}
declare class TKChartSplineAreaSeries extends TKChartAreaSeries {
static alloc(): TKChartSplineAreaSeries; // inherited from NSObject
static new(): TKChartSplineAreaSeries; // inherited from NSObject
}
declare class TKChartSplineSeries extends TKChartLineSeries {
static alloc(): TKChartSplineSeries; // inherited from NSObject
static new(): TKChartSplineSeries; // inherited from NSObject
}
declare class TKChartStackInfo extends NSObject {
static alloc(): TKChartStackInfo; // inherited from NSObject
static new(): TKChartStackInfo; // inherited from NSObject
stackID: any;
stackMode: TKChartStackMode;
constructor(o: { ID: any; withStackMode: TKChartStackMode; });
initWithIDWithStackMode(aStackID: any, aStackMode: TKChartStackMode): this;
}
declare const enum TKChartStackMode {
Stack = 0,
Stack100 = 1
}
declare class TKChartStandardDeviationIndicator extends TKChartSimpleMovingAverageIndicator {
static alloc(): TKChartStandardDeviationIndicator; // inherited from NSObject
static new(): TKChartStandardDeviationIndicator; // inherited from NSObject
}
declare class TKChartStyle extends TKStyleNode {
static alloc(): TKChartStyle; // inherited from NSObject
static new(): TKChartStyle; // inherited from NSObject
}
declare class TKChartTRIXIndicator extends TKChartSimpleMovingAverageIndicator {
static alloc(): TKChartTRIXIndicator; // inherited from NSObject
static new(): TKChartTRIXIndicator; // inherited from NSObject
}
declare const enum TKChartTitlePosition {
Left = 0,
Right = 1,
Top = 2,
Bottom = 3
}
declare class TKChartTitleStyle extends TKStyleNode {
static alloc(): TKChartTitleStyle; // inherited from NSObject
static new(): TKChartTitleStyle; // inherited from NSObject
}
declare class TKChartTitleView extends UILabel {
static alloc(): TKChartTitleView; // inherited from NSObject
static appearance(): TKChartTitleView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKChartTitleView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKChartTitleView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKChartTitleView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKChartTitleView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKChartTitleView; // inherited from UIAppearance
static new(): TKChartTitleView; // inherited from NSObject
position: TKChartTitlePosition;
style: TKChartTitleStyle;
}
declare class TKChartTrackball extends NSObject {
static alloc(): TKChartTrackball; // inherited from NSObject
static new(): TKChartTrackball; // inherited from NSObject
hideMode: TKChartTrackballHideMode;
readonly isVisible: boolean;
readonly line: TKChartTrackballLineAnnotation;
marginForHitDetection: number;
minimumPressDuration: number;
orientation: TKChartTrackballOrientation;
snapMode: TKChartTrackballSnapMode;
readonly tooltip: TKChartTrackballTooltipAnnotation;
constructor(o: { chart: TKChart; });
hide(): void;
initWithChart(chart: TKChart): this;
showAtPoint(point: CGPoint): void;
}
declare const enum TKChartTrackballHideMode {
OnTouchUp = 0,
OnSecondTouch = 1
}
declare class TKChartTrackballLineAnnotation extends TKChartAnnotation {
static alloc(): TKChartTrackballLineAnnotation; // inherited from NSObject
static new(): TKChartTrackballLineAnnotation; // inherited from NSObject
selectedPoints: NSArray<any>;
style: TKChartCrossLineAnnotationStyle;
constructor(o: { trackball: TKChartTrackball; });
initWithTrackball(trackball: TKChartTrackball): this;
updateContent(): void;
}
declare const enum TKChartTrackballOrientation {
Horizontal = 0,
Vertical = 1
}
declare const enum TKChartTrackballPinPosition {
None = 0,
Left = 1,
Right = 2,
Top = 3,
Bottom = 4
}
declare const enum TKChartTrackballSnapMode {
ClosestPoint = 0,
AllClosestPoints = 1
}
declare class TKChartTrackballTooltipAnnotation extends TKChartBalloonAnnotation {
static alloc(): TKChartTrackballTooltipAnnotation; // inherited from NSObject
static new(): TKChartTrackballTooltipAnnotation; // inherited from NSObject
pinPosition: TKChartTrackballPinPosition;
constructor(o: { trackball: TKChartTrackball; });
initWithTrackball(trackball: TKChartTrackball): this;
updateContent(): void;
}
declare class TKChartTriangularMovingAverageIndicator extends TKChartSimpleMovingAverageIndicator {
static alloc(): TKChartTriangularMovingAverageIndicator; // inherited from NSObject
static new(): TKChartTriangularMovingAverageIndicator; // inherited from NSObject
}
declare class TKChartTrueRangeIndicator extends TKChartFinancialIndicator {
static alloc(): TKChartTrueRangeIndicator; // inherited from NSObject
static new(): TKChartTrueRangeIndicator; // inherited from NSObject
}
declare class TKChartTypicalPriceIndicator extends TKChartFinancialIndicator {
static alloc(): TKChartTypicalPriceIndicator; // inherited from NSObject
static new(): TKChartTypicalPriceIndicator; // inherited from NSObject
}
declare class TKChartUltimateOscillator extends TKChartFinancialIndicator {
static alloc(): TKChartUltimateOscillator; // inherited from NSObject
static new(): TKChartUltimateOscillator; // inherited from NSObject
longPeriod: number;
middlePeriod: number;
shortPeriod: number;
}
declare class TKChartViewAnnotation extends TKChartPointAnnotation {
static alloc(): TKChartViewAnnotation; // inherited from NSObject
static new(): TKChartViewAnnotation; // inherited from NSObject
view: UIView;
constructor(o: { view: UIView; });
constructor(o: { view: UIView; point: TKChartData; forSeries: TKChartSeries; });
constructor(o: { view: UIView; point: TKChartData; forXAxis: TKChartAxis; forYAxis: TKChartAxis; });
constructor(o: { view: UIView; x: any; y: any; forSeries: TKChartSeries; });
constructor(o: { view: UIView; x: any; y: any; forXAxis: TKChartAxis; forYAxis: TKChartAxis; });
initWithView(aView: UIView): this;
initWithViewPointForSeries(aView: UIView, point: TKChartData, series: TKChartSeries): this;
initWithViewPointForXAxisForYAxis(aView: UIView, point: TKChartData, xAxis: TKChartAxis, yAxis: TKChartAxis): this;
initWithViewXYForSeries(aView: UIView, xValue: any, yValue: any, series: TKChartSeries): this;
initWithViewXYForXAxisForYAxis(aView: UIView, xValue: any, yValue: any, xAxis: TKChartAxis, yAxis: TKChartAxis): this;
}
declare class TKChartViewController extends UIViewController implements TKChartDataSource, TKChartDelegate {
static alloc(): TKChartViewController; // inherited from NSObject
static new(): TKChartViewController; // inherited from NSObject
readonly chart: TKChart;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
chartAnimationForSeriesWithStateInRect(chart: TKChart, series: TKChartSeries, state: TKChartSeriesRenderState, rect: CGRect): CAAnimation;
chartAttributedTextForAxisValueAtIndex(chart: TKChart, axis: TKChartAxis, value: any, index: number): NSAttributedString;
chartDataPointAtIndexForSeriesAtIndex(chart: TKChart, dataIndex: number, seriesIndex: number): TKChartData;
chartDataPointsForSeriesAtIndex(chart: TKChart, seriesIndex: number): NSArray<any>;
chartDidDeselectPointInSeriesAtIndex(chart: TKChart, point: TKChartData, series: TKChartSeries, index: number): void;
chartDidDeselectSeries(chart: TKChart, series: TKChartSeries): void;
chartDidPan(chart: TKChart): void;
chartDidSelectPointInSeriesAtIndex(chart: TKChart, point: TKChartData, series: TKChartSeries, index: number): void;
chartDidSelectSeries(chart: TKChart, series: TKChartSeries): void;
chartDidTapOnLegendItem(chart: TKChart, legendItem: TKChartLegendItem): void;
chartDidZoom(chart: TKChart): void;
chartLabelForDataPointPropertyInSeriesAtIndex(chart: TKChart, dataPoint: TKChartData, propertyName: string, series: TKChartSeries, dataIndex: number): TKChartPointLabel;
chartLegendItemForSeriesAtIndex(chart: TKChart, series: TKChartSeries, index: number): TKChartLegendItem;
chartNumberOfDataPointsForSeriesAtIndex(chart: TKChart, seriesIndex: number): number;
chartPaletteItemForPointInSeries(chart: TKChart, index: number, series: TKChartSeries): TKChartPaletteItem;
chartPaletteItemForSeriesAtIndex(chart: TKChart, series: TKChartSeries, index: number): TKChartPaletteItem;
chartPointLabelRenderForSeriesWithRender(chart: TKChart, series: TKChartSeries, render: TKChartSeriesRender): TKChartPointLabelRender;
chartShapeForSeriesAtIndex(chart: TKChart, series: TKChartSeries, index: number): TKShape;
chartTextForAxisValueAtIndex(chart: TKChart, axis: TKChartAxis, value: any, index: number): string;
chartTextForLabelAtPointPropertyInSeriesAtIndex(chart: TKChart, dataPoint: TKChartData, propertyName: string, series: TKChartSeries, dataIndex: number): string;
chartTrackballDidHideSelection(chart: TKChart, selection: NSArray<any>): void;
chartTrackballDidTrackSelection(chart: TKChart, selection: NSArray<any>): void;
chartUpdateLegendItemForSeriesAtIndex(chart: TKChart, item: TKChartLegendItem, series: TKChartSeries, index: number): void;
chartWillPan(chart: TKChart): void;
chartWillZoom(chart: TKChart): void;
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
numberOfSeriesForChart(chart: TKChart): number;
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;
seriesForChartAtIndex(chart: TKChart, index: number): TKChartSeries;
}
declare class TKChartVisualPoint extends NSObject implements NSCopying, UIDynamicItem {
static alloc(): TKChartVisualPoint; // inherited from NSObject
static new(): TKChartVisualPoint; // inherited from NSObject
readonly CGPoint: CGPoint;
animator: UIDynamicAnimator;
readonly doubleValue: number;
opacity: number;
scaleFactor: number;
x: number;
y: number;
readonly bounds: CGRect; // inherited from UIDynamicItem
center: CGPoint; // inherited from UIDynamicItem
readonly collisionBoundingPath: UIBezierPath; // inherited from UIDynamicItem
readonly collisionBoundsType: UIDynamicItemCollisionBoundsType; // inherited from UIDynamicItem
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
transform: CGAffineTransform; // inherited from UIDynamicItem
readonly // inherited from NSObjectProtocol
constructor(o: { point: CGPoint; });
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
copyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
initWithPoint(point: CGPoint): 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 TKChartWeightedCloseIndicator extends TKChartFinancialIndicator {
static alloc(): TKChartWeightedCloseIndicator; // inherited from NSObject
static new(): TKChartWeightedCloseIndicator; // inherited from NSObject
}
declare class TKChartWeightedMovingAverageIndicator extends TKChartSimpleMovingAverageIndicator {
static alloc(): TKChartWeightedMovingAverageIndicator; // inherited from NSObject
static new(): TKChartWeightedMovingAverageIndicator; // inherited from NSObject
}
declare class TKChartWilliamsPercentIndicator extends TKChartFinancialIndicator {
static alloc(): TKChartWilliamsPercentIndicator; // inherited from NSObject
static new(): TKChartWilliamsPercentIndicator; // inherited from NSObject
period: number;
}
declare const enum TKChartZoomMode {
Symmetric = 0,
SingleSide = 1
}
declare class TKCheckShape extends TKShape {
static alloc(): TKCheckShape; // inherited from NSObject
static new(): TKCheckShape; // inherited from NSObject
}
declare class TKCheckView extends TKView {
static alloc(): TKCheckView; // inherited from NSObject
static appearance(): TKCheckView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCheckView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCheckView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCheckView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCheckView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCheckView; // inherited from UIAppearance
static new(): TKCheckView; // inherited from NSObject
checkFill: TKFill;
checkShape: TKShape;
checkStroke: TKStroke;
isChecked: boolean;
}
declare class TKCollectionViewCell extends UICollectionViewCell {
static alloc(): TKCollectionViewCell; // inherited from NSObject
static appearance(): TKCollectionViewCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCollectionViewCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCollectionViewCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCollectionViewCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCollectionViewCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCollectionViewCell; // inherited from UIAppearance
static new(): TKCollectionViewCell; // inherited from NSObject
readonly label: UILabel;
}
interface TKCoreLayout extends NSObjectProtocol {
alignmentMode?: TKCoreLayoutAlignmentMode;
desiredSize: CGSize;
stretchMode?: TKCoreLayoutStretchMode;
arrange(rect: CGRect): void;
itemWasAddedInLayout?(layout: TKCoreLayout): void;
itemWasRemoved?(): void;
measure(size: CGSize): CGSize;
}
declare var TKCoreLayout: {
prototype: TKCoreLayout;
};
declare const enum TKCoreLayoutAlignmentMode {
Left = 1,
Top = 2,
Right = 4,
Bottom = 8,
HorizontalCenter = 16,
VerticalCenter = 32
}
declare class TKCoreLayoutItem extends NSObject implements TKCoreLayout {
static alloc(): TKCoreLayoutItem; // inherited from NSObject
static new(): TKCoreLayoutItem; // inherited from NSObject
readonly content: any;
margin: UIEdgeInsets;
sizingMode: TKCoreLayoutSizingMode;
alignmentMode: TKCoreLayoutAlignmentMode; // inherited from TKCoreLayout
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly desiredSize: CGSize; // inherited from TKCoreLayout
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
stretchMode: TKCoreLayoutStretchMode; // inherited from TKCoreLayout
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
constructor(o: { layer: CALayer; });
constructor(o: { layout: TKCoreLayout; });
constructor(o: { view: UIView; });
arrange(rect: CGRect): void;
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
initWithLayer(aLayer: CALayer): this;
initWithLayout(aLayout: TKCoreLayout): this;
initWithView(aView: UIView): this;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
itemWasAddedInLayout(layout: TKCoreLayout): void;
itemWasRemoved(): void;
measure(size: CGSize): CGSize;
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 TKCoreLayoutSizingMode {
Fixed = 0,
Fit = 1
}
declare const enum TKCoreLayoutStretchMode {
None = 0,
Horizontal = 1,
Vertical = 2
}
declare class TKCoreStackLayout extends NSObject implements NSFastEnumeration, TKCoreLayout {
static alloc(): TKCoreStackLayout; // inherited from NSObject
static new(): TKCoreStackLayout; // inherited from NSObject
readonly count: number;
itemOrder: TKCoreStackLayoutItemOrder;
itemSpacing: number;
readonly items: NSArray<any>;
orientation: TKCoreStackLayoutOrientation;
alignmentMode: TKCoreLayoutAlignmentMode; // inherited from TKCoreLayout
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly desiredSize: CGSize; // inherited from TKCoreLayout
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
stretchMode: TKCoreLayoutStretchMode; // inherited from TKCoreLayout
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
[Symbol.iterator](): Iterator<any>;
addItem(item: TKCoreLayout): boolean;
arrange(rect: CGRect): void;
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
indexOfItem(layoutItem: TKCoreLayout): number;
insertItemAtIndex(item: TKCoreLayout, index: number): boolean;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
itemAtIndex(index: number): TKCoreLayout;
itemWasAddedInLayout(layout: TKCoreLayout): void;
itemWasRemoved(): void;
lastItem(): TKCoreLayout;
measure(size: CGSize): CGSize;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
removeAllItems(): void;
removeItem(item: TKCoreLayout): boolean;
removeItemAtIndex(index: number): boolean;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
self(): this;
}
declare const enum TKCoreStackLayoutItemOrder {
Normal = 0,
Reverse = 1
}
declare const enum TKCoreStackLayoutOrientation {
Horizontal = 0,
Vertical = 1
}
declare class TKCoreStackLayoutView extends UIScrollView {
static alloc(): TKCoreStackLayoutView; // inherited from NSObject
static appearance(): TKCoreStackLayoutView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKCoreStackLayoutView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKCoreStackLayoutView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKCoreStackLayoutView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKCoreStackLayoutView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKCoreStackLayoutView; // inherited from UIAppearance
static new(): TKCoreStackLayoutView; // inherited from NSObject
stack: TKCoreStackLayout;
}
declare class TKDataForm extends UIView {
static alloc(): TKDataForm; // inherited from NSObject
static appearance(): TKDataForm; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataForm; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataForm; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataForm; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataForm; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataForm; // inherited from UIAppearance
static new(): TKDataForm; // inherited from NSObject
allowScroll: boolean;
commitMode: TKDataFormCommitMode;
dataSource: TKDataFormDataSource;
delegate: TKDataFormDelegate;
groupSpacing: number;
readOnly: boolean;
validationMode: TKDataFormValidationMode;
constructor(o: { JSONAnnotationsResource: string; ofType: string; });
commit(): void;
editorValueChanged(editor: TKDataFormEditor): void;
groupViewForGroup(group: TKEntityPropertyGroup): TKEntityPropertyGroupView;
hasValidationErrors(): boolean;
initWithJSONAnnotationsResourceOfType(resourceName: string, type: string): this;
registerEditorForProperty(editorClass: typeof NSObject, propertyName: string): void;
registerEditorForPropertyOfClass(editorClass: typeof NSObject, propertyClass: typeof NSObject): void;
registerEditorForPropertyOfType(editorClass: typeof NSObject, propertyType: TKEntityPropertyType): void;
reloadData(): void;
setEditorOnFocus(editor: TKDataFormEditor): void;
setupWithJSONAnnotationsString(str: string): void;
update(): void;
updateEditorForProperty(property: TKEntityProperty): void;
}
declare class TKDataFormAccessoryView extends UIView {
static alloc(): TKDataFormAccessoryView; // inherited from NSObject
static appearance(): TKDataFormAccessoryView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormAccessoryView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormAccessoryView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormAccessoryView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormAccessoryView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormAccessoryView; // inherited from UIAppearance
static new(): TKDataFormAccessoryView; // inherited from NSObject
readonly doneBarItem: UIBarButtonItem;
readonly nextBarItem: UIBarButtonItem;
readonly previousBarItem: UIBarButtonItem;
readonly toolbar: UIToolbar;
}
declare class TKDataFormAutoCompleteInlineEditor extends TKDataFormEditor {
static alloc(): TKDataFormAutoCompleteInlineEditor; // inherited from NSObject
static appearance(): TKDataFormAutoCompleteInlineEditor; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormAutoCompleteInlineEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormAutoCompleteInlineEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormAutoCompleteInlineEditor; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormAutoCompleteInlineEditor; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormAutoCompleteInlineEditor; // inherited from UIAppearance
static new(): TKDataFormAutoCompleteInlineEditor; // inherited from NSObject
autoCompleteView: TKAutoCompleteTextView;
dataSource: TKDataSource;
options: NSArray<any>;
selectedItem: string;
}
declare class TKDataFormAutocompleteController extends TKAutoCompleteController implements TKAutoCompleteDelegate {
static alloc(): TKDataFormAutocompleteController; // inherited from NSObject
static new(): TKDataFormAutocompleteController; // inherited from NSObject
readonly dataSource: TKDataSource;
editor: TKDataFormAutocompleteEditor;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
autoCompleteDidAddToken(autocomplete: TKAutoCompleteTextView, token: TKAutoCompleteToken): void;
autoCompleteDidAutoComplete(autocomplete: TKAutoCompleteTextView, completion: string): void;
autoCompleteDidRemoveToken(autocomplete: TKAutoCompleteTextView, token: TKAutoCompleteToken): void;
autoCompleteDidSelectToken(autocomplete: TKAutoCompleteTextView, token: TKAutoCompleteToken): void;
autoCompleteDidStartEditing(autocomplete: TKAutoCompleteTextView): void;
autoCompleteShouldAddToken(autocomplete: TKAutoCompleteTextView, token: TKAutoCompleteToken): boolean;
autoCompleteShouldRemoveToken(autocomplete: TKAutoCompleteTextView, token: TKAutoCompleteToken): boolean;
autoCompleteSuggestionListUpdated(autocomplete: TKAutoCompleteTextView, suggestionList: NSArray<TKAutoCompleteToken>): void;
autoCompleteViewForToken(autocomplete: TKAutoCompleteTextView, token: TKAutoCompleteToken): TKAutoCompleteTokenView;
autoCompleteWillShowSuggestionList(autocomplete: TKAutoCompleteTextView, suggestionList: NSArray<TKAutoCompleteToken>): void;
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
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 TKDataFormAutocompleteEditor extends TKDataFormViewControllerEditor {
static alloc(): TKDataFormAutocompleteEditor; // inherited from NSObject
static appearance(): TKDataFormAutocompleteEditor; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormAutocompleteEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormAutocompleteEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormAutocompleteEditor; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormAutocompleteEditor; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormAutocompleteEditor; // inherited from UIAppearance
static new(): TKDataFormAutocompleteEditor; // inherited from NSObject
readonly accessoryImageView: UIImageView;
options: NSArray<any>;
placeholder: string;
selectedItem: string;
readonly selectedOptionLabel: TKLabel;
showAccessoryImage: boolean;
}
declare const enum TKDataFormCommitMode {
Immediate = 0,
OnLostFocus = 1,
Manual = 2
}
interface TKDataFormConverter extends NSObjectProtocol {
convertFrom(source: any): any;
convertTo(source: any): any;
}
declare var TKDataFormConverter: {
prototype: TKDataFormConverter;
};
declare class TKDataFormCustomEditor extends TKDataFormEditor {
static alloc(): TKDataFormCustomEditor; // inherited from NSObject
static appearance(): TKDataFormCustomEditor; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormCustomEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormCustomEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormCustomEditor; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormCustomEditor; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormCustomEditor; // inherited from UIAppearance
static new(): TKDataFormCustomEditor; // inherited from NSObject
delegate: TKDataFormCustomEditorDelegate;
readonly editorView: UIView;
notifyValueChange(): void;
}
interface TKDataFormCustomEditorDelegate extends NSObjectProtocol {
editorShouldApplyValueEditorView(editor: TKDataFormCustomEditor, value: NSObject, view: UIView): void;
editorWillCreateView(editor: TKDataFormCustomEditor): UIView;
editorWillReturnValueEditorView(editor: TKDataFormCustomEditor, view: UIView): NSObject;
}
declare var TKDataFormCustomEditorDelegate: {
prototype: TKDataFormCustomEditorDelegate;
};
interface TKDataFormDataSource extends NSObjectProtocol {
dataFormEditorClassForProperty?(dataForm: TKDataForm, property: TKEntityProperty): typeof NSObject;
dataFormGroupAtIndex(dataForm: TKDataForm, groupIndex: number): TKEntityPropertyGroup;
dataFormNumberOfPropertiesInGroup(dataForm: TKDataForm, groupIndex: number): number;
dataFormPropertyInGroupAtIndex(dataForm: TKDataForm, groupIndex: number, propertyIndex: number): TKEntityProperty;
dataFormSetValueForProperty(dataForm: TKDataForm, value: any, property: TKEntityProperty): boolean;
dataFormTitleForHeaderInGroup?(dataForm: TKDataForm, groupIndex: number): string;
indexOfGroupInDataForm(group: TKEntityPropertyGroup): number;
numberOfGroupsInDataForm?(dataForm: TKDataForm): number;
}
declare var TKDataFormDataSource: {
prototype: TKDataFormDataSource;
};
declare class TKDataFormDatePickerEditor extends TKDataFormInlineEditor {
static alloc(): TKDataFormDatePickerEditor; // inherited from NSObject
static appearance(): TKDataFormDatePickerEditor; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormDatePickerEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormDatePickerEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormDatePickerEditor; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormDatePickerEditor; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormDatePickerEditor; // inherited from UIAppearance
static new(): TKDataFormDatePickerEditor; // inherited from NSObject
dateFormatter: NSDateFormatter;
readonly datePicker: UIDatePicker;
placeholder: string;
}
declare class TKDataFormDecimalEditor extends TKDataFormTextFieldEditor {
static alloc(): TKDataFormDecimalEditor; // inherited from NSObject
static appearance(): TKDataFormDecimalEditor; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormDecimalEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormDecimalEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormDecimalEditor; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormDecimalEditor; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormDecimalEditor; // inherited from UIAppearance
static new(): TKDataFormDecimalEditor; // inherited from NSObject
}
interface TKDataFormDelegate extends NSObjectProtocol {
dataFormCreateEditorForProperty?(dataForm: TKDataForm, property: TKEntityProperty): TKDataFormEditor;
dataFormDidCollapseGroupView?(dataForm: TKDataForm, groupView: TKEntityPropertyGroupView): void;
dataFormDidCommitProperty?(dataForm: TKDataForm, property: TKEntityProperty): void;
dataFormDidDeselectEditorForProperty?(dataForm: TKDataForm, editor: TKDataFormEditor, property: TKEntityProperty): void;
dataFormDidEditProperty?(dataForm: TKDataForm, property: TKEntityProperty): void;
dataFormDidExpandGroupView?(dataForm: TKDataForm, groupView: TKEntityPropertyGroupView): void;
dataFormDidFinishEditorIntitialization?(dataForm: TKDataForm): void;
dataFormDidSelectEditorForProperty?(dataForm: TKDataForm, editor: TKDataFormEditor, property: TKEntityProperty): void;
dataFormDidValidatePropertyEditor?(dataForm: TKDataForm, property: TKEntityProperty, editor: TKDataFormEditor): void;
dataFormHeightForEditorInGroupAtIndex?(dataForm: TKDataForm, groupIndex: number, editorIndex: number): number;
dataFormHeightForHeaderInGroup?(dataForm: TKDataForm, groupIndex: number): number;
dataFormInitViewControllerForEditor?(dataForm: TKDataForm, viewController: UIViewController, editor: TKDataFormViewControllerEditor): void;
dataFormSetupEditorForProperty?(dataForm: TKDataForm, editor: TKDataFormEditor, property: TKEntityProperty): void;
dataFormUpdateEditorForProperty?(dataForm: TKDataForm, editor: TKDataFormEditor, property: TKEntityProperty): void;
dataFormUpdateGroupViewForGroupAtIndex?(dataForm: TKDataForm, groupView: TKEntityPropertyGroupView, groupIndex: number): void;
dataFormValidatePropertyEditor?(dataForm: TKDataForm, property: TKEntityProperty, editor: TKDataFormEditor): boolean;
dataFormViewForHeaderInGroup?(dataForm: TKDataForm, groupIndex: number): TKEntityPropertyGroupTitleView;
dataFormWillCommitProperty?(dataForm: TKDataForm, property: TKEntityProperty): boolean;
inputAccessoryViewForDataForm?(dataForm: TKDataForm): TKDataFormAccessoryView;
}
declare var TKDataFormDelegate: {
prototype: TKDataFormDelegate;
};
declare class TKDataFormEditor extends UIView {
static alloc(): TKDataFormEditor; // inherited from NSObject
static appearance(): TKDataFormEditor; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormEditor; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormEditor; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormEditor; // inherited from UIAppearance
static new(): TKDataFormEditor; // inherited from NSObject
readonly editor: UIView;
enabled: boolean;
readonly feedbackImageView: TKImageView;
readonly feedbackLabel: UILabel;
readonly gridLayout: TKGridLayout;
readonly imageView: TKImageView;
readonly isTextEditor: boolean;
owner: TKDataForm;
property: TKEntityProperty;
readonly selected: boolean;
selectedView: TKView;
readonly style: TKDataFormEditorStyle;
readonly textLabel: TKLabel;
value: any;
constructor(o: { property: TKEntityProperty; });
constructor(o: { property: TKEntityProperty; owner: TKDataForm; });
initWithProperty(property: TKEntityProperty): this;
initWithPropertyOwner(property: TKEntityProperty, owner: TKDataForm): this;
update(): void;
updateControlValue(): void;
}
declare class TKDataFormEditorStyle extends TKStyleNode {
static alloc(): TKDataFormEditorStyle; // inherited from NSObject
static new(): TKDataFormEditorStyle; // inherited from NSObject
accessoryArrowSize: CGSize;
accessoryArrowStroke: TKStroke;
editorOffset: UIOffset;
feedbackImageSize: CGSize;
feedbackImageViewOffset: UIOffset;
feedbackLabelOffset: UIOffset;
fill: TKFill;
imageViewOffset: UIOffset;
imageViewSize: CGSize;
insets: UIEdgeInsets;
separatorColor: TKFill;
separatorLeadingSpace: number;
separatorTrailingSpace: number;
stroke: TKStroke;
textLabelDisplayMode: TKDataFormEditorTextLabelDisplayMode;
textLabelOffset: UIOffset;
}
declare const enum TKDataFormEditorTextLabelDisplayMode {
Show = 0,
Hidden = 1
}
declare class TKDataFormEmailEditor extends TKDataFormTextFieldEditor {
static alloc(): TKDataFormEmailEditor; // inherited from NSObject
static appearance(): TKDataFormEmailEditor; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormEmailEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormEmailEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormEmailEditor; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormEmailEditor; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormEmailEditor; // inherited from UIAppearance
static new(): TKDataFormEmailEditor; // inherited from NSObject
}
declare class TKDataFormEmailValidator extends TKDataFormPropertyValidator {
static alloc(): TKDataFormEmailValidator; // inherited from NSObject
static new(): TKDataFormEmailValidator; // inherited from NSObject
}
declare class TKDataFormEntityDataSource extends TKEntity implements TKDataFormDataSource {
static alloc(): TKDataFormEntityDataSource; // inherited from NSObject
static entityWithObject(sourceObject: NSObject): TKDataFormEntityDataSource; // inherited from TKEntity
static new(): TKDataFormEntityDataSource; // 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
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
dataFormEditorClassForProperty(dataForm: TKDataForm, property: TKEntityProperty): typeof NSObject;
dataFormGroupAtIndex(dataForm: TKDataForm, groupIndex: number): TKEntityPropertyGroup;
dataFormNumberOfPropertiesInGroup(dataForm: TKDataForm, groupIndex: number): number;
dataFormPropertyInGroupAtIndex(dataForm: TKDataForm, groupIndex: number, propertyIndex: number): TKEntityProperty;
dataFormSetValueForProperty(dataForm: TKDataForm, value: any, property: TKEntityProperty): boolean;
dataFormTitleForHeaderInGroup(dataForm: TKDataForm, groupIndex: number): string;
indexOfGroupInDataForm(group: TKEntityPropertyGroup): number;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
numberOfGroupsInDataForm(dataForm: TKDataForm): number;
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 TKDataFormGroupTitleStyle extends TKStyleNode {
static alloc(): TKDataFormGroupTitleStyle; // inherited from NSObject
static new(): TKDataFormGroupTitleStyle; // inherited from NSObject
fill: TKFill;
insets: UIEdgeInsets;
separatorColor: TKFill;
separatorLeadingSpace: number;
separatorTrailingSpace: number;
stroke: TKStroke;
}
declare class TKDataFormInlineEditor extends TKDataFormEditor {
static alloc(): TKDataFormInlineEditor; // inherited from NSObject
static appearance(): TKDataFormInlineEditor; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormInlineEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormInlineEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormInlineEditor; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormInlineEditor; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormInlineEditor; // inherited from UIAppearance
static new(): TKDataFormInlineEditor; // inherited from NSObject
readonly accessoryImageView: UIImageView;
displayMode: TKDataFormInlineEditorDisplayMode;
readonly editorValueLabel: TKLabel;
showAccessoryImage: boolean;
}
declare const enum TKDataFormInlineEditorDisplayMode {
Inline = 0,
Modal = 1
}
declare class TKDataFormMaximumLengthValidator extends TKDataFormPropertyValidator {
static alloc(): TKDataFormMaximumLengthValidator; // inherited from NSObject
static new(): TKDataFormMaximumLengthValidator; // inherited from NSObject
maximumLegth: number;
constructor(o: { maximumLength: number; });
initWithMaximumLength(maximumLength: number): this;
}
declare class TKDataFormMinimumLengthValidator extends TKDataFormPropertyValidator {
static alloc(): TKDataFormMinimumLengthValidator; // inherited from NSObject
static new(): TKDataFormMinimumLengthValidator; // inherited from NSObject
minimumLength: number;
constructor(o: { minimumLength: number; });
initWithMinimumLength(minimumLength: number): this;
}
declare class TKDataFormMultilineTextEditor extends TKDataFormEditor implements UITextViewDelegate {
static alloc(): TKDataFormMultilineTextEditor; // inherited from NSObject
static appearance(): TKDataFormMultilineTextEditor; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormMultilineTextEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormMultilineTextEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormMultilineTextEditor; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormMultilineTextEditor; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormMultilineTextEditor; // inherited from UIAppearance
static new(): TKDataFormMultilineTextEditor; // inherited from NSObject
dynamicHeight: boolean;
maxDynamicHeight: number;
readonly textView: UITextView;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
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;
scrollViewDidEndDecelerating(scrollView: UIScrollView): void;
scrollViewDidEndDraggingWillDecelerate(scrollView: UIScrollView, decelerate: boolean): void;
scrollViewDidEndScrollingAnimation(scrollView: UIScrollView): void;
scrollViewDidEndZoomingWithViewAtScale(scrollView: UIScrollView, view: UIView, scale: number): void;
scrollViewDidScroll(scrollView: UIScrollView): void;
scrollViewDidScrollToTop(scrollView: UIScrollView): void;
scrollViewDidZoom(scrollView: UIScrollView): void;
scrollViewShouldScrollToTop(scrollView: UIScrollView): boolean;
scrollViewWillBeginDecelerating(scrollView: UIScrollView): void;
scrollViewWillBeginDragging(scrollView: UIScrollView): void;
scrollViewWillBeginZoomingWithView(scrollView: UIScrollView, view: UIView): void;
scrollViewWillEndDraggingWithVelocityTargetContentOffset(scrollView: UIScrollView, velocity: CGPoint, targetContentOffset: interop.Pointer | interop.Reference<CGPoint>): void;
self(): this;
textViewDidBeginEditing(textView: UITextView): void;
textViewDidChange(textView: UITextView): void;
textViewDidChangeSelection(textView: UITextView): void;
textViewDidEndEditing(textView: UITextView): void;
textViewShouldBeginEditing(textView: UITextView): boolean;
textViewShouldChangeTextInRangeReplacementText(textView: UITextView, range: NSRange, text: string): boolean;
textViewShouldEndEditing(textView: UITextView): boolean;
textViewShouldInteractWithTextAttachmentInRange(textView: UITextView, textAttachment: NSTextAttachment, characterRange: NSRange): boolean;
textViewShouldInteractWithTextAttachmentInRangeInteraction(textView: UITextView, textAttachment: NSTextAttachment, characterRange: NSRange, interaction: UITextItemInteraction): boolean;
textViewShouldInteractWithURLInRange(textView: UITextView, URL: NSURL, characterRange: NSRange): boolean;
textViewShouldInteractWithURLInRangeInteraction(textView: UITextView, URL: NSURL, characterRange: NSRange, interaction: UITextItemInteraction): boolean;
viewForZoomingInScrollView(scrollView: UIScrollView): UIView;
}
declare class TKDataFormNamePhoneEditor extends TKDataFormTextFieldEditor {
static alloc(): TKDataFormNamePhoneEditor; // inherited from NSObject
static appearance(): TKDataFormNamePhoneEditor; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormNamePhoneEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormNamePhoneEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormNamePhoneEditor; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormNamePhoneEditor; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormNamePhoneEditor; // inherited from UIAppearance
static new(): TKDataFormNamePhoneEditor; // inherited from NSObject
}
declare class TKDataFormNonEmptyValidator extends TKDataFormPropertyValidator {
static alloc(): TKDataFormNonEmptyValidator; // inherited from NSObject
static new(): TKDataFormNonEmptyValidator; // inherited from NSObject
}
declare class TKDataFormNumberEditor extends TKDataFormTextFieldEditor {
static alloc(): TKDataFormNumberEditor; // inherited from NSObject
static appearance(): TKDataFormNumberEditor; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormNumberEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormNumberEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormNumberEditor; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormNumberEditor; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormNumberEditor; // inherited from UIAppearance
static new(): TKDataFormNumberEditor; // inherited from NSObject
formatter: NSNumberFormatter;
}
declare class TKDataFormOptionsEditor extends TKDataFormViewControllerEditor {
static alloc(): TKDataFormOptionsEditor; // inherited from NSObject
static appearance(): TKDataFormOptionsEditor; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormOptionsEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormOptionsEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormOptionsEditor; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormOptionsEditor; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormOptionsEditor; // inherited from UIAppearance
static new(): TKDataFormOptionsEditor; // inherited from NSObject
readonly accessoryImageView: UIImageView;
options: NSArray<any>;
selectedIndex: number;
readonly selectedOptionLabel: TKLabel;
showAccessoryImage: boolean;
}
declare class TKDataFormOptionsViewController extends UITableViewController {
static alloc(): TKDataFormOptionsViewController; // inherited from NSObject
static new(): TKDataFormOptionsViewController; // inherited from NSObject
editor: TKDataFormOptionsEditor;
items: NSArray<any>;
}
declare class TKDataFormPasswordEditor extends TKDataFormTextFieldEditor {
static alloc(): TKDataFormPasswordEditor; // inherited from NSObject
static appearance(): TKDataFormPasswordEditor; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormPasswordEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormPasswordEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormPasswordEditor; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormPasswordEditor; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormPasswordEditor; // inherited from UIAppearance
static new(): TKDataFormPasswordEditor; // inherited from NSObject
}
declare class TKDataFormPhoneEditor extends TKDataFormTextFieldEditor {
static alloc(): TKDataFormPhoneEditor; // inherited from NSObject
static appearance(): TKDataFormPhoneEditor; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormPhoneEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormPhoneEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormPhoneEditor; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormPhoneEditor; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormPhoneEditor; // inherited from UIAppearance
static new(): TKDataFormPhoneEditor; // inherited from NSObject
}
declare class TKDataFormPhoneValidator extends TKDataFormPropertyValidator {
static alloc(): TKDataFormPhoneValidator; // inherited from NSObject
static new(): TKDataFormPhoneValidator; // inherited from NSObject
}
declare class TKDataFormPickerViewEditor extends TKDataFormInlineEditor {
static alloc(): TKDataFormPickerViewEditor; // inherited from NSObject
static appearance(): TKDataFormPickerViewEditor; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormPickerViewEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormPickerViewEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormPickerViewEditor; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormPickerViewEditor; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormPickerViewEditor; // inherited from UIAppearance
static new(): TKDataFormPickerViewEditor; // inherited from NSObject
options: NSArray<any>;
readonly pickerView: UIPickerView;
selectedIndex: number;
}
declare class TKDataFormPropertyValidator extends NSObject implements TKDataFormValidator {
static alloc(): TKDataFormPropertyValidator; // inherited from NSObject
static new(): TKDataFormPropertyValidator; // inherited from NSObject
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
errorMessage: string; // inherited from TKDataFormValidator
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
positiveMessage: string; // inherited from TKDataFormValidator
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
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;
validateProperty(property: TKEntityProperty): boolean;
}
declare class TKDataFormRangeValidator extends TKDataFormPropertyValidator {
static alloc(): TKDataFormRangeValidator; // inherited from NSObject
static new(): TKDataFormRangeValidator; // inherited from NSObject
range: TKRange;
constructor(o: { range: TKRange; });
initWithRange(range: TKRange): this;
}
declare class TKDataFormSegmentedEditor extends TKDataFormEditor {
static alloc(): TKDataFormSegmentedEditor; // inherited from NSObject
static appearance(): TKDataFormSegmentedEditor; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormSegmentedEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormSegmentedEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormSegmentedEditor; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormSegmentedEditor; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormSegmentedEditor; // inherited from UIAppearance
static new(): TKDataFormSegmentedEditor; // inherited from NSObject
options: NSArray<any>;
readonly segmentedControl: UISegmentedControl;
selectedIndex: number;
}
declare class TKDataFormSliderEditor extends TKDataFormEditor {
static alloc(): TKDataFormSliderEditor; // inherited from NSObject
static appearance(): TKDataFormSliderEditor; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormSliderEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormSliderEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormSliderEditor; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormSliderEditor; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormSliderEditor; // inherited from UIAppearance
static new(): TKDataFormSliderEditor; // inherited from NSObject
readonly sliderView: UISlider;
stepValue: number;
}
declare class TKDataFormStepperEditor extends TKDataFormEditor {
static alloc(): TKDataFormStepperEditor; // inherited from NSObject
static appearance(): TKDataFormStepperEditor; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormStepperEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormStepperEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormStepperEditor; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormStepperEditor; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormStepperEditor; // inherited from UIAppearance
static new(): TKDataFormStepperEditor; // inherited from NSObject
formatter: NSNumberFormatter;
readonly stepperView: UIStepper;
readonly valueLabel: UILabel;
}
declare class TKDataFormStringToDateConverter extends NSObject implements TKDataFormConverter {
static alloc(): TKDataFormStringToDateConverter; // inherited from NSObject
static new(): TKDataFormStringToDateConverter; // inherited from NSObject
format: string;
locale: NSLocale;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
convertFrom(source: any): any;
convertTo(source: any): any;
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 TKDataFormStringToTimeConverter extends NSObject implements TKDataFormConverter {
static alloc(): TKDataFormStringToTimeConverter; // inherited from NSObject
static new(): TKDataFormStringToTimeConverter; // inherited from NSObject
format: string;
locale: NSLocale;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
convertFrom(source: any): any;
convertTo(source: any): any;
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 TKDataFormSwitchEditor extends TKDataFormEditor {
static alloc(): TKDataFormSwitchEditor; // inherited from NSObject
static appearance(): TKDataFormSwitchEditor; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormSwitchEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormSwitchEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormSwitchEditor; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormSwitchEditor; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormSwitchEditor; // inherited from UIAppearance
static new(): TKDataFormSwitchEditor; // inherited from NSObject
readonly switchView: UISwitch;
}
declare class TKDataFormTextFieldEditor extends TKDataFormEditor implements UITextFieldDelegate {
static alloc(): TKDataFormTextFieldEditor; // inherited from NSObject
static appearance(): TKDataFormTextFieldEditor; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormTextFieldEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormTextFieldEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormTextFieldEditor; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormTextFieldEditor; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormTextFieldEditor; // inherited from UIAppearance
static new(): TKDataFormTextFieldEditor; // inherited from NSObject
readonly textField: TKTextField;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
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;
textFieldDidBeginEditing(textField: UITextField): void;
textFieldDidEndEditing(textField: UITextField): void;
textFieldDidEndEditingReason(textField: UITextField, reason: UITextFieldDidEndEditingReason): void;
textFieldShouldBeginEditing(textField: UITextField): boolean;
textFieldShouldChangeCharactersInRangeReplacementString(textField: UITextField, range: NSRange, string: string): boolean;
textFieldShouldClear(textField: UITextField): boolean;
textFieldShouldEndEditing(textField: UITextField): boolean;
textFieldShouldReturn(textField: UITextField): boolean;
}
declare class TKDataFormTimePickerEditor extends TKDataFormDatePickerEditor {
static alloc(): TKDataFormTimePickerEditor; // inherited from NSObject
static appearance(): TKDataFormTimePickerEditor; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormTimePickerEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormTimePickerEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormTimePickerEditor; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormTimePickerEditor; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormTimePickerEditor; // inherited from UIAppearance
static new(): TKDataFormTimePickerEditor; // inherited from NSObject
}
declare const enum TKDataFormValidationMode {
Immediate = 0,
OnLostFocus = 1,
Manual = 2
}
interface TKDataFormValidator extends NSObjectProtocol {
errorMessage: string;
positiveMessage: string;
validateProperty(property: TKEntityProperty): boolean;
}
declare var TKDataFormValidator: {
prototype: TKDataFormValidator;
};
declare class TKDataFormViewController extends UIViewController implements TKDataFormDataSource, TKDataFormDelegate {
static alloc(): TKDataFormViewController; // inherited from NSObject
static new(): TKDataFormViewController; // inherited from NSObject
readonly dataForm: TKDataForm;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
dataFormCreateEditorForProperty(dataForm: TKDataForm, property: TKEntityProperty): TKDataFormEditor;
dataFormDidCollapseGroupView(dataForm: TKDataForm, groupView: TKEntityPropertyGroupView): void;
dataFormDidCommitProperty(dataForm: TKDataForm, property: TKEntityProperty): void;
dataFormDidDeselectEditorForProperty(dataForm: TKDataForm, editor: TKDataFormEditor, property: TKEntityProperty): void;
dataFormDidEditProperty(dataForm: TKDataForm, property: TKEntityProperty): void;
dataFormDidExpandGroupView(dataForm: TKDataForm, groupView: TKEntityPropertyGroupView): void;
dataFormDidFinishEditorIntitialization(dataForm: TKDataForm): void;
dataFormDidSelectEditorForProperty(dataForm: TKDataForm, editor: TKDataFormEditor, property: TKEntityProperty): void;
dataFormDidValidatePropertyEditor(dataForm: TKDataForm, property: TKEntityProperty, editor: TKDataFormEditor): void;
dataFormEditorClassForProperty(dataForm: TKDataForm, property: TKEntityProperty): typeof NSObject;
dataFormGroupAtIndex(dataForm: TKDataForm, groupIndex: number): TKEntityPropertyGroup;
dataFormHeightForEditorInGroupAtIndex(dataForm: TKDataForm, groupIndex: number, editorIndex: number): number;
dataFormHeightForHeaderInGroup(dataForm: TKDataForm, groupIndex: number): number;
dataFormInitViewControllerForEditor(dataForm: TKDataForm, viewController: UIViewController, editor: TKDataFormViewControllerEditor): void;
dataFormNumberOfPropertiesInGroup(dataForm: TKDataForm, groupIndex: number): number;
dataFormPropertyInGroupAtIndex(dataForm: TKDataForm, groupIndex: number, propertyIndex: number): TKEntityProperty;
dataFormSetValueForProperty(dataForm: TKDataForm, value: any, property: TKEntityProperty): boolean;
dataFormSetupEditorForProperty(dataForm: TKDataForm, editor: TKDataFormEditor, property: TKEntityProperty): void;
dataFormTitleForHeaderInGroup(dataForm: TKDataForm, groupIndex: number): string;
dataFormUpdateEditorForProperty(dataForm: TKDataForm, editor: TKDataFormEditor, property: TKEntityProperty): void;
dataFormUpdateGroupViewForGroupAtIndex(dataForm: TKDataForm, groupView: TKEntityPropertyGroupView, groupIndex: number): void;
dataFormValidatePropertyEditor(dataForm: TKDataForm, property: TKEntityProperty, editor: TKDataFormEditor): boolean;
dataFormViewForHeaderInGroup(dataForm: TKDataForm, groupIndex: number): TKEntityPropertyGroupTitleView;
dataFormWillCommitProperty(dataForm: TKDataForm, property: TKEntityProperty): boolean;
indexOfGroupInDataForm(group: TKEntityPropertyGroup): number;
inputAccessoryViewForDataForm(dataForm: TKDataForm): TKDataFormAccessoryView;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
numberOfGroupsInDataForm(dataForm: TKDataForm): number;
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 TKDataFormViewControllerEditor extends TKDataFormEditor {
static alloc(): TKDataFormViewControllerEditor; // inherited from NSObject
static appearance(): TKDataFormViewControllerEditor; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKDataFormViewControllerEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKDataFormViewControllerEditor; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKDataFormViewControllerEditor; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKDataFormViewControllerEditor; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKDataFormViewControllerEditor; // inherited from UIAppearance
static new(): TKDataFormViewControllerEditor; // inherited from NSObject
createViewController(): UIViewController;
presentViewController(): void;
}
declare class TKDataSource extends NSObject implements NSURLConnectionDataDelegate, NSURLConnectionDelegate, TKAutoCompleteDataSource, TKCalendarDataSource, TKCalendarDelegate, TKChartDataSource, TKChartDelegate, TKListViewDataSource, TKListViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDataSource, UITableViewDelegate {
static alloc(): TKDataSource; // inherited from NSObject
static new(): TKDataSource; // inherited from NSObject
allowItemsReorder: boolean;
currentItem: any;
displayKey: string;
readonly filterDescriptors: NSArray<TKDataSourceFilterDescriptor>;
formatter: NSFormatter;
readonly groupDescriptors: NSArray<TKDataSourceGroupDescriptor>;
groupItemSourceKey: string;
itemSource: any;
readonly items: NSArray<any>;
mapClass: typeof NSObject;
mapCollectionsRecursively: boolean;
propertyMap: NSDictionary<any, any>;
readonly settings: TKDataSourceSettings;
readonly sortDescriptors: NSArray<TKDataSourceSortDescriptor>;
valueKey: string;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
constructor(o: { array: NSArray<any>; });
constructor(o: { array: NSArray<any>; displayKey: string; });
constructor(o: { array: NSArray<any>; displayKey: string; valueKey: string; });
constructor(o: { dataFromJSONResource: string; ofType: string; rootItemKeyPath: string; });
constructor(o: { dataFromURL: string; dataFormat: TKDataSourceDataFormat; rootItemKeyPath: string; completion: (p1: NSError) => void; });
constructor(o: { itemSource: any; });
constructor(o: { JSONString: string; });
addFilterDescriptor(filterDescriptor: TKDataSourceFilterDescriptor): void;
addGroupDescriptor(groupDescriptor: TKDataSourceGroupDescriptor): void;
addSortDescriptor(sortDescriptor: TKDataSourceSortDescriptor): void;
autoCompleteCompletionForPrefix(autocomplete: TKAutoCompleteTextView, prefix: string): NSArray<TKAutoCompleteToken>;
autoCompleteCompletionsForString(autocomplete: TKAutoCompleteTextView, input: string): void;
calendarDidChangedViewModeFromTo(calendar: TKCalendar, previousViewMode: TKCalendarViewMode, viewMode: TKCalendarViewMode): void;
calendarDidDeselectedDate(calendar: TKCalendar, date: Date): void;
calendarDidNavigateToDate(calendar: TKCalendar, date: Date): void;
calendarDidSelectDate(calendar: TKCalendar, date: Date): void;
calendarDidTapCell(calendar: TKCalendar, cell: TKCalendarDayCell): void;
calendarEventsForDate(calendar: TKCalendar, date: Date): NSArray<any>;
calendarEventsFromDateToDateWithCallback(calendar: TKCalendar, startDate: Date, endDate: Date, eventsCallback: (p1: NSArray<any>) => void): void;
calendarShapeForEvent(calendar: TKCalendar, event: TKCalendarEventProtocol): TKShape;
calendarShouldSelectDate(calendar: TKCalendar, date: Date): boolean;
calendarTextForEvent(calendar: TKCalendar, event: TKCalendarEventProtocol): string;
calendarUpdateVisualsForCell(calendar: TKCalendar, cell: TKCalendarCell): void;
calendarViewForCellOfKind(calendar: TKCalendar, cellType: TKCalendarCellType): TKCalendarCell;
calendarWillNavigateToDate(calendar: TKCalendar, date: Date): void;
chartAnimationForSeriesWithStateInRect(chart: TKChart, series: TKChartSeries, state: TKChartSeriesRenderState, rect: CGRect): CAAnimation;
chartAttributedTextForAxisValueAtIndex(chart: TKChart, axis: TKChartAxis, value: any, index: number): NSAttributedString;
chartDataPointAtIndexForSeriesAtIndex(chart: TKChart, dataIndex: number, seriesIndex: number): TKChartData;
chartDataPointsForSeriesAtIndex(chart: TKChart, seriesIndex: number): NSArray<any>;
chartDidDeselectPointInSeriesAtIndex(chart: TKChart, point: TKChartData, series: TKChartSeries, index: number): void;
chartDidDeselectSeries(chart: TKChart, series: TKChartSeries): void;
chartDidPan(chart: TKChart): void;
chartDidSelectPointInSeriesAtIndex(chart: TKChart, point: TKChartData, series: TKChartSeries, index: number): void;
chartDidSelectSeries(chart: TKChart, series: TKChartSeries): void;
chartDidTapOnLegendItem(chart: TKChart, legendItem: TKChartLegendItem): void;
chartDidZoom(chart: TKChart): void;
chartLabelForDataPointPropertyInSeriesAtIndex(chart: TKChart, dataPoint: TKChartData, propertyName: string, series: TKChartSeries, dataIndex: number): TKChartPointLabel;
chartLegendItemForSeriesAtIndex(chart: TKChart, series: TKChartSeries, index: number): TKChartLegendItem;
chartNumberOfDataPointsForSeriesAtIndex(chart: TKChart, seriesIndex: number): number;
chartPaletteItemForPointInSeries(chart: TKChart, index: number, series: TKChartSeries): TKChartPaletteItem;
chartPaletteItemForSeriesAtIndex(chart: TKChart, series: TKChartSeries, index: number): TKChartPaletteItem;
chartPointLabelRenderForSeriesWithRender(chart: TKChart, series: TKChartSeries, render: TKChartSeriesRender): TKChartPointLabelRender;
chartShapeForSeriesAtIndex(chart: TKChart, series: TKChartSeries, index: number): TKShape;
chartTextForAxisValueAtIndex(chart: TKChart, axis: TKChartAxis, value: any, index: number): string;
chartTextForLabelAtPointPropertyInSeriesAtIndex(chart: TKChart, dataPoint: TKChartData, propertyName: string, series: TKChartSeries, dataIndex: number): string;
chartTrackballDidHideSelection(chart: TKChart, selection: NSArray<any>): void;
chartTrackballDidTrackSelection(chart: TKChart, selection: NSArray<any>): void;
chartUpdateLegendItemForSeriesAtIndex(chart: TKChart, item: TKChartLegendItem, series: TKChartSeries, index: number): void;
chartWillPan(chart: TKChart): void;
chartWillZoom(chart: TKChart): void;
class(): typeof NSObject;
collectionViewCanFocusItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewCanMoveItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewCanPerformActionForItemAtIndexPathWithSender(collectionView: UICollectionView, action: string, indexPath: NSIndexPath, sender: any): boolean;
collectionViewCellForItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): UICollectionViewCell;
collectionViewDidDeselectItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): void;
collectionViewDidEndDisplayingCellForItemAtIndexPath(collectionView: UICollectionView, cell: UICollectionViewCell, indexPath: NSIndexPath): void;
collectionViewDidEndDisplayingSupplementaryViewForElementOfKindAtIndexPath(collectionView: UICollectionView, view: UICollectionReusableView, elementKind: string, indexPath: NSIndexPath): void;
collectionViewDidHighlightItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): void;
collectionViewDidSelectItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): void;
collectionViewDidUnhighlightItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): void;
collectionViewDidUpdateFocusInContextWithAnimationCoordinator(collectionView: UICollectionView, context: UICollectionViewFocusUpdateContext, coordinator: UIFocusAnimationCoordinator): void;
collectionViewIndexPathForIndexTitleAtIndex(collectionView: UICollectionView, title: string, index: number): NSIndexPath;
collectionViewMoveItemAtIndexPathToIndexPath(collectionView: UICollectionView, sourceIndexPath: NSIndexPath, destinationIndexPath: NSIndexPath): void;
collectionViewNumberOfItemsInSection(collectionView: UICollectionView, section: number): number;
collectionViewPerformActionForItemAtIndexPathWithSender(collectionView: UICollectionView, action: string, indexPath: NSIndexPath, sender: any): void;
collectionViewShouldDeselectItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewShouldHighlightItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewShouldSelectItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewShouldShowMenuForItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewShouldUpdateFocusInContext(collectionView: UICollectionView, context: UICollectionViewFocusUpdateContext): boolean;
collectionViewTargetContentOffsetForProposedContentOffset(collectionView: UICollectionView, proposedContentOffset: CGPoint): CGPoint;
collectionViewTargetIndexPathForMoveFromItemAtIndexPathToProposedIndexPath(collectionView: UICollectionView, originalIndexPath: NSIndexPath, proposedIndexPath: NSIndexPath): NSIndexPath;
collectionViewTransitionLayoutForOldLayoutNewLayout(collectionView: UICollectionView, fromLayout: UICollectionViewLayout, toLayout: UICollectionViewLayout): UICollectionViewTransitionLayout;
collectionViewViewForSupplementaryElementOfKindAtIndexPath(collectionView: UICollectionView, kind: string, indexPath: NSIndexPath): UICollectionReusableView;
collectionViewWillDisplayCellForItemAtIndexPath(collectionView: UICollectionView, cell: UICollectionViewCell, indexPath: NSIndexPath): void;
collectionViewWillDisplaySupplementaryViewForElementKindAtIndexPath(collectionView: UICollectionView, view: UICollectionReusableView, elementKind: string, indexPath: NSIndexPath): void;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
connectionCanAuthenticateAgainstProtectionSpace(connection: NSURLConnection, protectionSpace: NSURLProtectionSpace): boolean;
connectionDidCancelAuthenticationChallenge(connection: NSURLConnection, challenge: NSURLAuthenticationChallenge): void;
connectionDidFailWithError(connection: NSURLConnection, error: NSError): void;
connectionDidFinishLoading(connection: NSURLConnection): void;
connectionDidReceiveAuthenticationChallenge(connection: NSURLConnection, challenge: NSURLAuthenticationChallenge): void;
connectionDidReceiveData(connection: NSURLConnection, data: NSData): void;
connectionDidReceiveResponse(connection: NSURLConnection, response: NSURLResponse): void;
connectionDidSendBodyDataTotalBytesWrittenTotalBytesExpectedToWrite(connection: NSURLConnection, bytesWritten: number, totalBytesWritten: number, totalBytesExpectedToWrite: number): void;
connectionNeedNewBodyStream(connection: NSURLConnection, request: NSURLRequest): NSInputStream;
connectionShouldUseCredentialStorage(connection: NSURLConnection): boolean;
connectionWillCacheResponse(connection: NSURLConnection, cachedResponse: NSCachedURLResponse): NSCachedURLResponse;
connectionWillSendRequestForAuthenticationChallenge(connection: NSURLConnection, challenge: NSURLAuthenticationChallenge): void;
connectionWillSendRequestRedirectResponse(connection: NSURLConnection, request: NSURLRequest, response: NSURLResponse): NSURLRequest;
enumerate(enumeratorBlock: (p1: any) => void): void;
filter(filterBlock: (p1: any) => boolean): void;
filterWithQuery(filterQuery: string): void;
formatText(formatTextBlock: (p1: any, p2: TKDataSourceGroup) => string): void;
group(keyForItem: (p1: any) => any): void;
groupComparator(keyForItem: (p1: any) => any, comparatorBlock: (p1: any, p2: any) => NSComparisonResult): void;
groupWithKey(propertyName: string): void;
groupWithKeyComparator(propertyName: string, comparatorBlock: (p1: any, p2: any) => NSComparisonResult): void;
indexPathForPreferredFocusedViewInCollectionView(collectionView: UICollectionView): NSIndexPath;
indexPathForPreferredFocusedViewInTableView(tableView: UITableView): NSIndexPath;
indexTitlesForCollectionView(collectionView: UICollectionView): NSArray<string>;
initWithArray(items: NSArray<any>): this;
initWithArrayDisplayKey(items: NSArray<any>, displayKey: string): this;
initWithArrayDisplayKeyValueKey(items: NSArray<any>, displayKey: string, valueKey: string): this;
initWithDataFromJSONResourceOfTypeRootItemKeyPath(name: string, type: string, rootItemKeyPath: string): this;
initWithDataFromURLDataFormatRootItemKeyPathCompletion(url: string, dataFormat: TKDataSourceDataFormat, rootItemKeyPath: string, completion: (p1: NSError) => void): this;
initWithItemSource(itemSource: any): this;
initWithJSONString(str: string): this;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
listViewCellForItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): TKListViewCell;
listViewDidDeselectItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): void;
listViewDidFinishSwipeCellAtIndexPathWithOffset(listView: TKListView, cell: TKListViewCell, indexPath: NSIndexPath, offset: CGPoint): void;
listViewDidHighlightItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): void;
listViewDidLongPressCellAtIndexPath(listView: TKListView, cell: TKListViewCell, indexPath: NSIndexPath): void;
listViewDidPullWithOffset(listView: TKListView, offset: number): void;
listViewDidReorderItemFromIndexPathToIndexPath(listView: TKListView, originalIndexPath: NSIndexPath, targetIndexPath: NSIndexPath): void;
listViewDidSelectItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): void;
listViewDidSwipeCellAtIndexPathWithOffset(listView: TKListView, cell: TKListViewCell, indexPath: NSIndexPath, offset: CGPoint): void;
listViewDidUnhighlightItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): void;
listViewNumberOfItemsInSection(listView: TKListView, section: number): number;
listViewShouldDeselectItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): boolean;
listViewShouldHighlightItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): boolean;
listViewShouldLoadMoreDataAtIndexPath(listView: TKListView, indexPath: NSIndexPath): boolean;
listViewShouldRefreshOnPull(listView: TKListView): boolean;
listViewShouldSelectItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): boolean;
listViewShouldSwipeCellAtIndexPath(listView: TKListView, cell: TKListViewCell, indexPath: NSIndexPath): boolean;
listViewViewForSupplementaryElementOfKindAtIndexPath(listView: TKListView, kind: string, indexPath: NSIndexPath): TKListViewReusableCell;
listViewWillReorderItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): void;
loadDataFromJSONResourceOfTypeRootItemKeyPath(name: string, type: string, rootItemKeyPath: string): void;
loadDataFromJSONStringRootItemKeyPath(string: string, rootItemKeyPath: string): void;
loadDataFromURLDataFormatRootItemKeyPathCompletion(url: string, dataFormat: TKDataSourceDataFormat, rootItemKeyPath: string, completion: (p1: NSError) => void): void;
map(mapBlock: (p1: any) => any): void;
moveItemAtIndexToIndex(fromIndex: number, toIndex: number): void;
numberOfSectionsInCollectionView(collectionView: UICollectionView): number;
numberOfSectionsInListView(listView: TKListView): number;
numberOfSectionsInTableView(tableView: UITableView): number;
numberOfSeriesForChart(chart: TKChart): number;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
reduceWith(initialValue: any, reduceBlock: (p1: any, p2: any) => any): any;
reloadData(): void;
removeAllFilterDescriptors(): void;
removeAllGroupDescriptors(): void;
removeAllSortDescriptors(): void;
removeFilterDescriptor(filterDescriptor: TKDataSourceFilterDescriptor): void;
removeGroupDescriptor(groupDescriptor: TKDataSourceGroupDescriptor): void;
removeSortDescriptor(sortDescriptor: TKDataSourceSortDescriptor): void;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
scrollViewDidEndDecelerating(scrollView: UIScrollView): void;
scrollViewDidEndDraggingWillDecelerate(scrollView: UIScrollView, decelerate: boolean): void;
scrollViewDidEndScrollingAnimation(scrollView: UIScrollView): void;
scrollViewDidEndZoomingWithViewAtScale(scrollView: UIScrollView, view: UIView, scale: number): void;
scrollViewDidScroll(scrollView: UIScrollView): void;
scrollViewDidScrollToTop(scrollView: UIScrollView): void;
scrollViewDidZoom(scrollView: UIScrollView): void;
scrollViewShouldScrollToTop(scrollView: UIScrollView): boolean;
scrollViewWillBeginDecelerating(scrollView: UIScrollView): void;
scrollViewWillBeginDragging(scrollView: UIScrollView): void;
scrollViewWillBeginZoomingWithView(scrollView: UIScrollView, view: UIView): void;
scrollViewWillEndDraggingWithVelocityTargetContentOffset(scrollView: UIScrollView, velocity: CGPoint, targetContentOffset: interop.Pointer | interop.Reference<CGPoint>): void;
sectionIndexTitlesForTableView(tableView: UITableView): NSArray<string>;
self(): this;
seriesForChartAtIndex(chart: TKChart, index: number): TKChartSeries;
sort(comparatorBlock: (p1: any, p2: any) => NSComparisonResult): void;
sortWithKeyAscending(propertyName: string, ascending: boolean): void;
tableViewAccessoryButtonTappedForRowWithIndexPath(tableView: UITableView, indexPath: NSIndexPath): void;
tableViewAccessoryTypeForRowWithIndexPath(tableView: UITableView, indexPath: NSIndexPath): UITableViewCellAccessoryType;
tableViewCanEditRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): boolean;
tableViewCanFocusRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): boolean;
tableViewCanMoveRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): boolean;
tableViewCanPerformActionForRowAtIndexPathWithSender(tableView: UITableView, action: string, indexPath: NSIndexPath, sender: any): boolean;
tableViewCellForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): UITableViewCell;
tableViewCommitEditingStyleForRowAtIndexPath(tableView: UITableView, editingStyle: UITableViewCellEditingStyle, indexPath: NSIndexPath): void;
tableViewDidDeselectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): void;
tableViewDidEndDisplayingCellForRowAtIndexPath(tableView: UITableView, cell: UITableViewCell, indexPath: NSIndexPath): void;
tableViewDidEndDisplayingFooterViewForSection(tableView: UITableView, view: UIView, section: number): void;
tableViewDidEndDisplayingHeaderViewForSection(tableView: UITableView, view: UIView, section: number): void;
tableViewDidEndEditingRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): void;
tableViewDidHighlightRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): void;
tableViewDidSelectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): void;
tableViewDidUnhighlightRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): void;
tableViewDidUpdateFocusInContextWithAnimationCoordinator(tableView: UITableView, context: UITableViewFocusUpdateContext, coordinator: UIFocusAnimationCoordinator): void;
tableViewEditActionsForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): NSArray<UITableViewRowAction>;
tableViewEditingStyleForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): UITableViewCellEditingStyle;
tableViewEstimatedHeightForFooterInSection(tableView: UITableView, section: number): number;
tableViewEstimatedHeightForHeaderInSection(tableView: UITableView, section: number): number;
tableViewEstimatedHeightForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): number;
tableViewHeightForFooterInSection(tableView: UITableView, section: number): number;
tableViewHeightForHeaderInSection(tableView: UITableView, section: number): number;
tableViewHeightForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): number;
tableViewIndentationLevelForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): number;
tableViewMoveRowAtIndexPathToIndexPath(tableView: UITableView, sourceIndexPath: NSIndexPath, destinationIndexPath: NSIndexPath): void;
tableViewNumberOfRowsInSection(tableView: UITableView, section: number): number;
tableViewPerformActionForRowAtIndexPathWithSender(tableView: UITableView, action: string, indexPath: NSIndexPath, sender: any): void;
tableViewSectionForSectionIndexTitleAtIndex(tableView: UITableView, title: string, index: number): number;
tableViewShouldHighlightRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): boolean;
tableViewShouldIndentWhileEditingRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): boolean;
tableViewShouldShowMenuForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): boolean;
tableViewShouldUpdateFocusInContext(tableView: UITableView, context: UITableViewFocusUpdateContext): boolean;
tableViewTargetIndexPathForMoveFromRowAtIndexPathToProposedIndexPath(tableView: UITableView, sourceIndexPath: NSIndexPath, proposedDestinationIndexPath: NSIndexPath): NSIndexPath;
tableViewTitleForDeleteConfirmationButtonForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): string;
tableViewTitleForFooterInSection(tableView: UITableView, section: number): string;
tableViewTitleForHeaderInSection(tableView: UITableView, section: number): string;
tableViewViewForFooterInSection(tableView: UITableView, section: number): UIView;
tableViewViewForHeaderInSection(tableView: UITableView, section: number): UIView;
tableViewWillBeginEditingRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): void;
tableViewWillDeselectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): NSIndexPath;
tableViewWillDisplayCellForRowAtIndexPath(tableView: UITableView, cell: UITableViewCell, indexPath: NSIndexPath): void;
tableViewWillDisplayFooterViewForSection(tableView: UITableView, view: UIView, section: number): void;
tableViewWillDisplayHeaderViewForSection(tableView: UITableView, view: UIView, section: number): void;
tableViewWillSelectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): NSIndexPath;
textFromItemInGroup(item: any, group: TKDataSourceGroup): string;
valueForItemInGroup(item: any, group: TKDataSourceGroup): any;
viewForZoomingInScrollView(scrollView: UIScrollView): UIView;
}
declare class TKDataSourceAutoCompleteSettings extends NSObject {
static alloc(): TKDataSourceAutoCompleteSettings; // inherited from NSObject
static new(): TKDataSourceAutoCompleteSettings; // inherited from NSObject
completionMode: TKAutoCompleteCompletionMode;
highlightColor: UIColor;
highlightMatch: boolean;
valueKey: string;
createToken(createToken: (p1: number, p2: any) => TKAutoCompleteToken): void;
}
declare class TKDataSourceCalendarSettings extends NSObject {
static alloc(): TKDataSourceCalendarSettings; // inherited from NSObject
static new(): TKDataSourceCalendarSettings; // inherited from NSObject
defaultEventColor: UIColor;
endDateKey: string;
eventColorKey: string;
startDateKey: string;
}
declare class TKDataSourceChartSettings extends NSObject {
static alloc(): TKDataSourceChartSettings; // inherited from NSObject
static new(): TKDataSourceChartSettings; // inherited from NSObject
createPoint(createPoint: (p1: number, p2: number, p3: any) => TKChartData): void;
createSeries(createSeries: (p1: TKDataSourceGroup) => TKChartSeries): void;
}
declare class TKDataSourceCollectionViewSettings extends NSObject {
static alloc(): TKDataSourceCollectionViewSettings; // inherited from NSObject
static new(): TKDataSourceCollectionViewSettings; // inherited from NSObject
createCell(cellIdForItem: (p1: UICollectionView, p2: NSIndexPath, p3: any) => UICollectionViewCell): void;
initCell(initCellWithItem: (p1: UICollectionView, p2: NSIndexPath, p3: UICollectionViewCell, p4: any) => void): void;
}
declare const enum TKDataSourceDataFormat {
JSON = 0
}
declare class TKDataSourceFilterDescriptor extends NSObject {
static alloc(): TKDataSourceFilterDescriptor; // inherited from NSObject
static new(): TKDataSourceFilterDescriptor; // inherited from NSObject
readonly filterBlock: (p1: any) => boolean;
readonly query: string;
constructor(o: { block: (p1: any) => boolean; });
constructor(o: { query: string; });
evaluate(item: any): boolean;
initWithBlock(filterBlock: (p1: any) => boolean): this;
initWithQuery(query: string): this;
}
declare class TKDataSourceGroup extends NSObject {
static alloc(): TKDataSourceGroup; // inherited from NSObject
static new(): TKDataSourceGroup; // inherited from NSObject
displayKey: string;
items: NSArray<any>;
key: any;
valueKey: string;
constructor(o: { items: NSArray<any>; });
constructor(o: { items: NSArray<any>; valueKey: string; });
constructor(o: { items: NSArray<any>; valueKey: string; displayKey: string; });
initWithItems(items: NSArray<any>): this;
initWithItemsValueKey(items: NSArray<any>, valueKey: string): this;
initWithItemsValueKeyDisplayKey(items: NSArray<any>, valueKey: string, displayKey: string): this;
}
declare class TKDataSourceGroupDescriptor extends NSObject {
static alloc(): TKDataSourceGroupDescriptor; // inherited from NSObject
static new(): TKDataSourceGroupDescriptor; // inherited from NSObject
readonly comparatorBlock: (p1: any, p2: any) => NSComparisonResult;
readonly keyForItemBlock: (p1: any) => any;
propertyName: string;
constructor(o: { block: (p1: any) => any; });
constructor(o: { block: (p1: any) => any; comparator: (p1: any, p2: any) => NSComparisonResult; });
constructor(o: { property: string; });
constructor(o: { property: string; comparator: (p1: any, p2: any) => NSComparisonResult; });
initWithBlock(keyForItemBlock: (p1: any) => any): this;
initWithBlockComparator(keyForItemBlock: (p1: any) => any, comparatorBlock: (p1: any, p2: any) => NSComparisonResult): this;
initWithProperty(propertyName: string): this;
initWithPropertyComparator(propertyName: string, comparatorBlock: (p1: any, p2: any) => NSComparisonResult): this;
keyForItem(item: any): any;
}
declare class TKDataSourceListViewSettings extends NSObject {
static alloc(): TKDataSourceListViewSettings; // inherited from NSObject
static new(): TKDataSourceListViewSettings; // inherited from NSObject
defaultCellClass: typeof NSObject;
defaultCellID: string;
createCell(createCellBlock: (p1: TKListView, p2: NSIndexPath, p3: any) => TKListViewCell): void;
createSupplementaryView(createViewBlock: (p1: TKListView, p2: NSIndexPath, p3: string, p4: TKDataSourceGroup) => TKListViewReusableCell): void;
initCell(initCellBlock: (p1: TKListView, p2: NSIndexPath, p3: TKListViewCell, p4: any) => void): void;
initFooter(initFooterBlock: (p1: TKListView, p2: NSIndexPath, p3: TKListViewFooterCell, p4: TKDataSourceGroup) => void): void;
initHeader(initHeaderBlock: (p1: TKListView, p2: NSIndexPath, p3: TKListViewHeaderCell, p4: TKDataSourceGroup) => void): void;
}
declare class TKDataSourceSettings extends NSObject {
static alloc(): TKDataSourceSettings; // inherited from NSObject
static new(): TKDataSourceSettings; // inherited from NSObject
readonly autocomplete: TKDataSourceAutoCompleteSettings;
readonly calendar: TKDataSourceCalendarSettings;
readonly chart: TKDataSourceChartSettings;
readonly collectionView: TKDataSourceCollectionViewSettings;
readonly listView: TKDataSourceListViewSettings;
readonly tableView: TKDataSourceTableViewSettings;
}
declare class TKDataSourceSortDescriptor extends NSObject {
static alloc(): TKDataSourceSortDescriptor; // inherited from NSObject
static new(): TKDataSourceSortDescriptor; // inherited from NSObject
ascending: boolean;
readonly comparator: (p1: any, p2: any) => NSComparisonResult;
readonly descriptor: NSSortDescriptor;
propertyName: string;
constructor(o: { comparator: (p1: any, p2: any) => NSComparisonResult; });
constructor(o: { property: string; ascending: boolean; });
initWithComparator(comparator: (p1: any, p2: any) => NSComparisonResult): this;
initWithPropertyAscending(propertyName: string, ascending: boolean): this;
}
declare class TKDataSourceTableViewSettings extends NSObject {
static alloc(): TKDataSourceTableViewSettings; // inherited from NSObject
static new(): TKDataSourceTableViewSettings; // inherited from NSObject
createCell(createCellForItem: (p1: UITableView, p2: NSIndexPath, p3: any) => UITableViewCell): void;
initCell(initCellWithItem: (p1: UITableView, p2: NSIndexPath, p3: UITableViewCell, p4: any) => void): void;
}
declare class TKDateRange extends NSObject {
static alloc(): TKDateRange; // inherited from NSObject
static new(): TKDateRange; // inherited from NSObject
endDate: Date;
readonly isNormalized: boolean;
startDate: Date;
constructor(o: { start: Date; end: Date; });
containsDate(date: Date): boolean;
initWithStartEnd(startDate: Date, endDate: Date): this;
normalize(): void;
}
interface TKDrawing extends NSObjectProtocol {
insets?: UIEdgeInsets;
drawInContextWithPath(context: any, path: any): void;
drawInContextWithRect(context: any, rect: CGRect): void;
}
declare var TKDrawing: {
prototype: TKDrawing;
};
declare class TKEntity extends NSObject {
static alloc(): TKEntity; // inherited from NSObject
static entityWithObject(sourceObject: NSObject): TKEntity;
static new(): TKEntity; // inherited from NSObject
readonly defaultGroup: TKEntityPropertyGroup;
readonly groups: NSArray<any>;
readonly properties: NSArray<any>;
sourceObject: NSObject;
constructor(o: { dataFromJSONResource: string; ofType: string; rootItemKeyPath: string; });
constructor(o: { JSONFromURL: string; rootItemKeyPath: string; completion: (p1: NSError) => void; });
constructor(o: { JSONString: string; rootItemKeyPath: string; });
constructor(o: { object: NSObject; });
constructor(o: { object: NSObject; propertyNames: NSArray<any>; });
addGroup(group: TKEntityPropertyGroup): void;
addGroupWithNamePropertyNames(name: string, propertyNames: NSArray<any>): TKEntityPropertyGroup;
commit(): boolean;
groupAtIndex(index: number): TKEntityPropertyGroup;
groupWithName(groupName: string): TKEntityPropertyGroup;
initWithDataFromJSONResourceOfTypeRootItemKeyPath(name: string, type: string, rootItemKeyPath: string): this;
initWithJSONFromURLRootItemKeyPathCompletion(url: string, rootItemKeyPath: string, completion: (p1: NSError) => void): this;
initWithJSONStringRootItemKeyPath(str: string, rootItemKeyPath: string): this;
initWithObject(sourceObject: NSObject): this;
initWithObjectPropertyNames(sourceObject: NSObject, propertyNames: NSArray<any>): this;
insertGroupAtIndex(group: TKEntityPropertyGroup, index: number): void;
objectForKeyedSubscript(propertyName: string): TKEntityProperty;
propertyWithName(propertyName: string): TKEntityProperty;
removeAllGroups(): void;
removeGroup(group: TKEntityPropertyGroup): void;
removeGroupAtIndex(index: number): void;
setSourceObjectWithProperties(sourceObject: NSObject, properties: NSArray<any>): void;
setSourceObjectWithPropertyNames(sourceObject: NSObject, propertyNames: NSArray<any>): void;
validate(): NSArray<any>;
writeJSONToStream(outputStream: NSOutputStream): NSError;
writeJSONToString(): string;
}
declare class TKEntityProperty extends NSObject {
static alloc(): TKEntityProperty; // inherited from NSObject
static new(): TKEntityProperty; // inherited from NSObject
autoCompleteDisplayMode: TKAutoCompleteDisplayMode;
converter: TKDataFormConverter;
displayName: string;
editorClass: typeof NSObject;
errorImage: UIImage;
errorMessage: string;
formatter: NSFormatter;
groupName: string;
hidden: boolean;
hintText: string;
image: UIImage;
index: number;
isNullable: boolean;
readonly isValid: boolean;
layoutInfo: TKLayoutInfo;
readonly name: string;
readonly originalValue: any;
readonly owner: TKEntity;
pickersUseIndexValue: boolean;
positiveImage: UIImage;
positiveMessage: string;
readonly propertyClass: typeof NSObject;
range: TKRange;
readOnly: boolean;
required: boolean;
step: number;
type: TKEntityPropertyType;
validators: NSArray<any>;
valueCandidate: any;
valuesProvider: NSArray<any>;
readonly wasValidated: boolean;
constructor(o: { entity: TKEntity; forPropertyName: string; });
commit(): boolean;
initWithEntityForPropertyName(owner: TKEntity, propertyName: string): this;
validate(): boolean;
}
declare class TKEntityPropertyGroup extends NSObject {
static alloc(): TKEntityPropertyGroup; // inherited from NSObject
static new(): TKEntityPropertyGroup; // inherited from NSObject
hidden: boolean;
name: string;
owner: TKEntity;
readonly properties: NSArray<any>;
[index: number]: TKEntityProperty;
constructor(o: { name: string; properties: NSArray<any>; });
constructor(o: { name: string; properties: NSArray<any>; orderByPropertyIndex: boolean; });
addProperty(property: TKEntityProperty): void;
initWithNameProperties(name: string, properties: NSArray<any>): this;
initWithNamePropertiesOrderByPropertyIndex(name: string, properties: NSArray<any>, orderByPropertyIndex: boolean): this;
insertPropertyAtIndex(property: TKEntityProperty, index: number): void;
objectAtIndexedSubscript(index: number): TKEntityProperty;
objectForKeyedSubscript(propertyName: string): TKEntityProperty;
propertyAtIndex(index: number): TKEntityProperty;
propertyWithName(name: string): TKEntityProperty;
removeAllProperties(): void;
removeProperty(property: TKEntityProperty): void;
removePropertyAtIndex(index: number): void;
}
declare class TKEntityPropertyGroupEditorsView extends UIView {
static alloc(): TKEntityPropertyGroupEditorsView; // inherited from NSObject
static appearance(): TKEntityPropertyGroupEditorsView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKEntityPropertyGroupEditorsView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKEntityPropertyGroupEditorsView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKEntityPropertyGroupEditorsView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKEntityPropertyGroupEditorsView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKEntityPropertyGroupEditorsView; // inherited from UIAppearance
static new(): TKEntityPropertyGroupEditorsView; // inherited from NSObject
readonly items: NSArray<any>;
layout: TKLayout;
addItem(item: UIView): void;
addItemAtIndex(item: UIView, index: number): void;
removeAllItems(): void;
removeItem(item: UIView): void;
updateLayout(): void;
}
declare const enum TKEntityPropertyGroupTitleIndicatorPosition {
Left = 0,
Right = 1
}
declare class TKEntityPropertyGroupTitleView extends UIView {
static alloc(): TKEntityPropertyGroupTitleView; // inherited from NSObject
static appearance(): TKEntityPropertyGroupTitleView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKEntityPropertyGroupTitleView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKEntityPropertyGroupTitleView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKEntityPropertyGroupTitleView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKEntityPropertyGroupTitleView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKEntityPropertyGroupTitleView; // inherited from UIAppearance
static new(): TKEntityPropertyGroupTitleView; // inherited from NSObject
allowIndicatorAnimation: boolean;
indicatorPosition: TKEntityPropertyGroupTitleIndicatorPosition;
indicatorView: UIView;
itemSpacing: number;
readonly style: TKDataFormGroupTitleStyle;
readonly titleLabel: TKLabel;
}
declare class TKEntityPropertyGroupTitleViewIndicator extends UIView {
static alloc(): TKEntityPropertyGroupTitleViewIndicator; // inherited from NSObject
static appearance(): TKEntityPropertyGroupTitleViewIndicator; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKEntityPropertyGroupTitleViewIndicator; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKEntityPropertyGroupTitleViewIndicator; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKEntityPropertyGroupTitleViewIndicator; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKEntityPropertyGroupTitleViewIndicator; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKEntityPropertyGroupTitleViewIndicator; // inherited from UIAppearance
static new(): TKEntityPropertyGroupTitleViewIndicator; // inherited from NSObject
fillColor: TKSolidFill;
size: CGSize;
strokeColor: TKStroke;
}
declare class TKEntityPropertyGroupView extends UIView {
static alloc(): TKEntityPropertyGroupView; // inherited from NSObject
static appearance(): TKEntityPropertyGroupView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKEntityPropertyGroupView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKEntityPropertyGroupView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKEntityPropertyGroupView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKEntityPropertyGroupView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKEntityPropertyGroupView; // inherited from UIAppearance
static new(): TKEntityPropertyGroupView; // inherited from NSObject
collapsible: boolean;
readonly editorsContainer: TKEntityPropertyGroupEditorsView;
readonly group: TKEntityPropertyGroup;
readonly isCollapsed: boolean;
titleView: TKEntityPropertyGroupTitleView;
}
declare const enum TKEntityPropertyType {
Unknown = 0,
Numeric = 1,
Integer = 2,
Double = 3,
Bool = 4,
String = 5,
Date = 6
}
declare class TKFill extends NSObject implements NSCopying, TKDrawing {
static alloc(): TKFill; // inherited from NSObject
static new(): TKFill; // inherited from NSObject
alpha: number;
cornerRadius: number;
corners: UIRectCorner;
shadowBlur: number;
shadowColor: UIColor;
shadowOffset: CGSize;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
insets: UIEdgeInsets; // inherited from TKDrawing
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
copyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
drawFillInContextWithPath(context: any, path: any): void;
drawFillInContextWithRect(context: any, rect: CGRect): void;
drawInContextWithPath(context: any, path: any): void;
drawInContextWithRect(context: any, rect: CGRect): void;
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 TKGauge extends TKView {
static alloc(): TKGauge; // inherited from NSObject
static appearance(): TKGauge; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKGauge; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKGauge; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKGauge; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKGauge; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKGauge; // inherited from UIAppearance
static new(): TKGauge; // inherited from NSObject
delegate: TKGaugeDelegate;
insets: UIEdgeInsets;
readonly labelSubtitle: UILabel;
labelSubtitleOffset: CGPoint;
readonly labelTitle: UILabel;
labelTitleOffset: CGPoint;
rectWithInsets: CGRect;
readonly scales: NSArray<TKGaugeScale>;
addScale(scale: TKGaugeScale): void;
insertScaleAtIndex(scale: TKGaugeScale, index: number): void;
removeAllScales(): void;
removeScale(scale: TKGaugeScale): void;
removeScaleAtIndex(index: number): void;
scaleAtIndex(index: number): TKGaugeScale;
}
interface TKGaugeDelegate extends NSObjectProtocol {
gaugeTextForLabel?(gauge: TKGauge, label: any): string;
gaugeValueChangedForScale?(gauge: TKGauge, value: number, scale: TKGaugeScale): void;
}
declare var TKGaugeDelegate: {
prototype: TKGaugeDelegate;
};
declare class TKGaugeIndicator extends CALayer {
static alloc(): TKGaugeIndicator; // inherited from NSObject
static layer(): TKGaugeIndicator; // inherited from CALayer
static new(): TKGaugeIndicator; // inherited from NSObject
allowTouch: boolean;
fill: TKFill;
owner: TKGaugeScale;
stroke: TKStroke;
value: number;
}
declare class TKGaugeLabels extends NSObject {
static alloc(): TKGaugeLabels; // inherited from NSObject
static new(): TKGaugeLabels; // inherited from NSObject
color: UIColor;
count: number;
font: UIFont;
formatter: NSFormatter;
hidden: boolean;
labelFormat: string;
offset: number;
position: TKGaugeLabelsPosition;
}
declare const enum TKGaugeLabelsPosition {
Inner = 0,
Outer = 1
}
declare class TKGaugeLinearScale extends TKGaugeScale {
static alloc(): TKGaugeLinearScale; // inherited from NSObject
static layer(): TKGaugeLinearScale; // inherited from CALayer
static new(): TKGaugeLinearScale; // inherited from NSObject
endPoint: number;
offset: number;
startPoint: number;
}
declare class TKGaugeNeedle extends TKGaugeIndicator {
static alloc(): TKGaugeNeedle; // inherited from NSObject
static layer(): TKGaugeNeedle; // inherited from CALayer
static new(): TKGaugeNeedle; // inherited from NSObject
circleFill: TKFill;
circleInnerRadius: number;
circleRadius: number;
circleStroke: TKStroke;
length: number;
offset: number;
topWidth: number;
width: number;
constructor(o: { value: number; });
constructor(o: { value: number; length: number; });
initWithValue(value: number): this;
initWithValueLength(value: number, length: number): this;
setValueAnimatedWithDurationMediaTimingFunction(value: number, duration: number, functionName: string): void;
}
declare class TKGaugeRadialScale extends TKGaugeScale {
static alloc(): TKGaugeRadialScale; // inherited from NSObject
static layer(): TKGaugeRadialScale; // inherited from CALayer
static new(): TKGaugeRadialScale; // inherited from NSObject
endAngle: number;
radius: number;
startAngle: number;
}
declare class TKGaugeScale extends CALayer {
static alloc(): TKGaugeScale; // inherited from NSObject
static layer(): TKGaugeScale; // inherited from CALayer
static new(): TKGaugeScale; // inherited from NSObject
fill: TKFill;
readonly indicators: NSArray<TKGaugeIndicator>;
readonly labels: TKGaugeLabels;
owner: TKGauge;
range: TKRange;
readonly segments: NSArray<TKGaugeSegment>;
stroke: TKStroke;
readonly ticks: TKGaugeTicks;
constructor(o: { minimum: any; maximum: any; });
constructor(o: { range: TKRange; });
addIndicator(indicator: TKGaugeIndicator): void;
addSegment(segment: TKGaugeSegment): void;
denormalize(value: number): number;
indicatorAtIndex(index: number): TKGaugeIndicator;
initWithMinimumMaximum(minimum: any, maximum: any): this;
initWithRange(range: TKRange): this;
insertIndicatorAtIndex(indicator: TKGaugeIndicator, index: number): void;
insertSegmentAtIndex(segment: TKGaugeSegment, index: number): void;
locationForValue(value: number): number;
removeAllIndicators(): void;
removeAllSegments(): void;
removeIndicator(indicator: TKGaugeIndicator): void;
removeIndicatorAtIndex(index: number): void;
removeSegment(segment: TKGaugeSegment): void;
removeSegmentAtIndex(index: number): void;
segmentAtIndex(index: number): TKGaugeSegment;
textForValue(value: number): string;
valueForPoint(point: CGPoint): number;
}
declare class TKGaugeSegment extends CALayer {
static alloc(): TKGaugeSegment; // inherited from NSObject
static layer(): TKGaugeSegment; // inherited from CALayer
static new(): TKGaugeSegment; // inherited from NSObject
allowTouch: boolean;
cap: TKGaugeSegmentCap;
fill: TKFill;
location: number;
owner: TKGaugeScale;
range: TKRange;
stroke: TKStroke;
width: number;
width2: number;
constructor(o: { minimum: any; maximum: any; });
constructor(o: { range: TKRange; });
initWithMinimumMaximum(minimum: any, maximum: any): this;
initWithRange(range: TKRange): this;
setRangeAnimatedWithDurationMediaTimingFunction(value: TKRange, duration: number, functionName: string): void;
}
declare const enum TKGaugeSegmentCap {
Round = 0,
Edge = 1
}
declare class TKGaugeTicks extends NSObject {
static alloc(): TKGaugeTicks; // inherited from NSObject
static new(): TKGaugeTicks; // inherited from NSObject
hidden: boolean;
majorTicksCount: number;
majorTicksFill: TKFill;
majorTicksLength: number;
majorTicksStroke: TKStroke;
majorTicksWidth: number;
minorTicksCount: number;
minorTicksFill: TKFill;
minorTicksLength: number;
minorTicksStroke: TKStroke;
minorTicksWidth: number;
offset: number;
position: TKGaugeTicksPosition;
}
declare const enum TKGaugeTicksPosition {
Inner = 0,
Outer = 1
}
declare class TKGradientFill extends TKFill {
static alloc(): TKGradientFill; // inherited from NSObject
static new(): TKGradientFill; // inherited from NSObject
colors: NSArray<UIColor>;
locations: NSArray<number>;
constructor(o: { colors: NSArray<any>; });
constructor(o: { colors: NSArray<any>; cornerRadius: number; });
constructor(o: { colors: NSArray<any>; locations: NSArray<any>; });
constructor(o: { colors: NSArray<any>; locations: NSArray<any>; cornerRadius: number; });
initWithColors(colors: NSArray<any>): this;
initWithColorsCornerRadius(colors: NSArray<any>, cornerRadius: number): this;
initWithColorsLocations(colors: NSArray<any>, locations: NSArray<any>): this;
initWithColorsLocationsCornerRadius(colors: NSArray<any>, locations: NSArray<any>, cornerRadius: number): this;
}
declare const enum TKGradientRadiusType {
Pixels = 0,
RectMin = 1,
RectMax = 2
}
declare class TKGridLayout extends NSObject implements TKLayout {
static alloc(): TKGridLayout; // inherited from NSObject
static new(): TKGridLayout; // inherited from NSObject
readonly arrangedViews: NSArray<any>;
readonly definitions: NSArray<any>;
horizontalSpacing: number;
minColumnsWidth: number;
minRowsHeight: number;
verticalSpacing: number;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
frame: CGRect; // inherited from TKLayout
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
orientation: TKLayoutOrientation; // inherited from TKLayout
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
constructor(o: { frame: CGRect; });
addArrangedView(view: UIView): void;
addDefinition(definition: TKGridLayoutCellDefinition): void;
addDefinitionForViewAtRowColumnRowSpanColumnSpan(view: UIView, row: number, column: number, rowSpan: number, columnSpan: number): TKGridLayoutCellDefinition;
arrangeViewWithLayoutInfo(view: UIView, layoutInfo: TKLayoutInfo): void;
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
definitionForView(view: UIView): TKGridLayoutCellDefinition;
initWithFrame(frame: CGRect): this;
insertArrangedViewAtIndex(view: UIView, index: number): void;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
layoutArrangedViews(): void;
measurePreferredSizeThatFitsSize(size: CGSize): CGSize;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
removeAllArrangedViews(): void;
removeAllDefinitions(): void;
removeArrangedView(view: UIView): void;
removeDefinition(definition: TKGridLayoutCellDefinition): void;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
self(): this;
setHeightForRow(height: number, row: number): void;
setWidthForColumn(width: number, col: number): void;
}
declare const enum TKGridLayoutAlignment {
Top = 1,
Left = 2,
Bottom = 4,
Right = 8,
Center = 16,
CenterVertical = 32,
CenterHorizontal = 64,
Fill = 128,
FillVertical = 256,
FillHorizontal = 512
}
declare class TKGridLayoutCellDefinition extends NSObject {
static alloc(): TKGridLayoutCellDefinition; // inherited from NSObject
static new(): TKGridLayoutCellDefinition; // inherited from NSObject
alignment: TKGridLayoutAlignment;
column: number;
columnSpan: number;
contentOffset: UIOffset;
row: number;
rowSpan: number;
view: UIView;
constructor(o: { view: UIView; });
constructor(o: { view: UIView; atRow: number; column: number; });
constructor(o: { view: UIView; atRow: number; column: number; rowSpan: number; columnSpan: number; });
initWithView(view: UIView): this;
initWithViewAtRowColumn(view: UIView, row: number, col: number): this;
initWithViewAtRowColumnRowSpanColumnSpan(view: UIView, row: number, col: number, rowSpan: number, colSpan: number): this;
}
declare class TKImageFill extends TKFill {
static alloc(): TKImageFill; // inherited from NSObject
static imageFillWithImage(image: UIImage): TKImageFill;
static imageFillWithImageCornerRadius(image: UIImage, cornerRadius: number): TKImageFill;
static new(): TKImageFill; // inherited from NSObject
image: UIImage;
resizingMode: TKImageFillResizingMode;
constructor(o: { image: UIImage; });
constructor(o: { image: UIImage; cornerRadius: number; });
initWithImage(image: UIImage): this;
initWithImageCornerRadius(image: UIImage, cornerRadius: number): this;
}
declare const enum TKImageFillResizingMode {
Tile = 0,
Stretch = 1,
None = 2
}
declare class TKImageView extends UIImageView {
static alloc(): TKImageView; // inherited from NSObject
static appearance(): TKImageView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKImageView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKImageView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKImageView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKImageView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKImageView; // inherited from UIAppearance
static new(): TKImageView; // inherited from NSObject
}
declare class TKLabel extends UILabel {
static alloc(): TKLabel; // inherited from NSObject
static appearance(): TKLabel; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKLabel; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKLabel; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKLabel; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKLabel; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKLabel; // inherited from UIAppearance
static new(): TKLabel; // inherited from NSObject
textInsets: UIEdgeInsets;
}
declare class TKLayer extends CALayer {
static alloc(): TKLayer; // inherited from NSObject
static layer(): TKLayer; // inherited from CALayer
static new(): TKLayer; // inherited from NSObject
fill: TKFill;
shape: TKShape;
stroke: TKStroke;
sizeThatFits(size: CGSize): CGSize;
sizeToFit(): void;
}
interface TKLayout extends NSObjectProtocol {
arrangedViews: NSArray<any>;
frame: CGRect;
orientation: TKLayoutOrientation;
addArrangedView(view: UIView): void;
arrangeViewWithLayoutInfo(view: UIView, layoutInfo: TKLayoutInfo): void;
insertArrangedViewAtIndex(view: UIView, index: number): void;
layoutArrangedViews(): void;
measurePreferredSizeThatFitsSize(size: CGSize): CGSize;
removeAllArrangedViews(): void;
removeArrangedView(view: UIView): void;
}
declare var TKLayout: {
prototype: TKLayout;
};
declare class TKLayoutInfo extends NSObject {
static alloc(): TKLayoutInfo; // inherited from NSObject
static new(): TKLayoutInfo; // inherited from NSObject
column: number;
columnSpan: number;
row: number;
rowSpan: number;
constructor(o: { row: number; column: number; rowSpan: number; columnSpan: number; });
initWithRowColumnRowSpanColumnSpan(row: number, column: number, rowSpan: number, columnSpan: number): this;
}
declare const enum TKLayoutOrientation {
Horizontal = 0,
Vertical = 1
}
declare class TKLinearGauge extends TKGauge {
static alloc(): TKLinearGauge; // inherited from NSObject
static appearance(): TKLinearGauge; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKLinearGauge; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKLinearGauge; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKLinearGauge; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKLinearGauge; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKLinearGauge; // inherited from UIAppearance
static new(): TKLinearGauge; // inherited from NSObject
labelOrientation: TKLinearGaugeOrientation;
labelPosition: TKLinearGaugeLabelPosition;
labelSpacing: number;
orientation: TKLinearGaugeOrientation;
}
declare const enum TKLinearGaugeLabelPosition {
TopOrLeft = 0,
BottomOrRight = 1
}
declare const enum TKLinearGaugeOrientation {
Horizontal = 0,
Vertical = 1
}
declare class TKLinearGradientFill extends TKGradientFill {
static alloc(): TKLinearGradientFill; // inherited from NSObject
static linearGradientFillWithColors(colors: NSArray<any>): TKLinearGradientFill;
static linearGradientFillWithColorsLocationsStartPointEndPoint(colors: NSArray<any>, locations: NSArray<any>, startPoint: CGPoint, endPoint: CGPoint): TKLinearGradientFill;
static linearGradientFillWithColorsStartPointEndPoint(colors: NSArray<any>, startPoint: CGPoint, endPoint: CGPoint): TKLinearGradientFill;
static new(): TKLinearGradientFill; // inherited from NSObject
static reverse(fill: TKLinearGradientFill): TKLinearGradientFill;
endPoint: CGPoint;
startPoint: CGPoint;
constructor(o: { colors: NSArray<any>; locations: NSArray<any>; startPoint: CGPoint; endPoint: CGPoint; });
constructor(o: { colors: NSArray<any>; startPoint: CGPoint; endPoint: CGPoint; });
initWithColorsLocationsStartPointEndPoint(colors: NSArray<any>, locations: NSArray<any>, startPoint: CGPoint, endPoint: CGPoint): this;
initWithColorsStartPointEndPoint(colors: NSArray<any>, startPoint: CGPoint, endPoint: CGPoint): this;
}
declare class TKListView extends UIView implements UICollectionViewDataSource, UICollectionViewDelegate {
static alloc(): TKListView; // inherited from NSObject
static appearance(): TKListView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKListView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKListView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKListView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKListView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKListView; // inherited from UIAppearance
static new(): TKListView; // inherited from NSObject
allowsCellReorder: boolean;
allowsCellSwipe: boolean;
allowsMultipleSelection: boolean;
allowsPullToRefresh: boolean;
autoRestrictSwipeDirection: boolean;
autoScrollTreshold: number;
backgroundView: UIView;
cellSwipeAnimationDuration: number;
cellSwipeLimits: UIEdgeInsets;
cellSwipeTreshold: number;
contentInset: UIEdgeInsets;
contentOffset: CGPoint;
dataSource: TKListViewDataSource;
delegate: TKListViewDelegate;
deselectOnSecondTap: boolean;
readonly indexPathsForSelectedItems: NSArray<any>;
readonly indexPathsForVisibleItems: NSArray<NSIndexPath>;
layout: UICollectionViewLayout;
loadOnDemandBufferSize: number;
loadOnDemandMode: TKListViewLoadOnDemandMode;
loadOnDemandView: TKListViewLoadOnDemandView;
readonly numberOfSections: number;
pullToRefreshTreshold: number;
pullToRefreshView: TKListViewPullToRefreshView;
reorderMode: TKListViewReorderMode;
scrollDirection: TKListViewScrollDirection;
selectionBehavior: TKListViewSelectionBehavior;
readonly visibleCells: NSArray<TKListViewCell>;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
cellForItemAtIndexPath(indexPath: NSIndexPath): TKListViewCell;
class(): typeof NSObject;
clearSelectedItems(): void;
collectionViewCanFocusItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewCanMoveItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewCanPerformActionForItemAtIndexPathWithSender(collectionView: UICollectionView, action: string, indexPath: NSIndexPath, sender: any): boolean;
collectionViewCellForItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): UICollectionViewCell;
collectionViewDidDeselectItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): void;
collectionViewDidEndDisplayingCellForItemAtIndexPath(collectionView: UICollectionView, cell: UICollectionViewCell, indexPath: NSIndexPath): void;
collectionViewDidEndDisplayingSupplementaryViewForElementOfKindAtIndexPath(collectionView: UICollectionView, view: UICollectionReusableView, elementKind: string, indexPath: NSIndexPath): void;
collectionViewDidHighlightItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): void;
collectionViewDidSelectItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): void;
collectionViewDidUnhighlightItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): void;
collectionViewDidUpdateFocusInContextWithAnimationCoordinator(collectionView: UICollectionView, context: UICollectionViewFocusUpdateContext, coordinator: UIFocusAnimationCoordinator): void;
collectionViewIndexPathForIndexTitleAtIndex(collectionView: UICollectionView, title: string, index: number): NSIndexPath;
collectionViewMoveItemAtIndexPathToIndexPath(collectionView: UICollectionView, sourceIndexPath: NSIndexPath, destinationIndexPath: NSIndexPath): void;
collectionViewNumberOfItemsInSection(collectionView: UICollectionView, section: number): number;
collectionViewPerformActionForItemAtIndexPathWithSender(collectionView: UICollectionView, action: string, indexPath: NSIndexPath, sender: any): void;
collectionViewShouldDeselectItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewShouldHighlightItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewShouldSelectItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewShouldShowMenuForItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): boolean;
collectionViewShouldUpdateFocusInContext(collectionView: UICollectionView, context: UICollectionViewFocusUpdateContext): boolean;
collectionViewTargetContentOffsetForProposedContentOffset(collectionView: UICollectionView, proposedContentOffset: CGPoint): CGPoint;
collectionViewTargetIndexPathForMoveFromItemAtIndexPathToProposedIndexPath(collectionView: UICollectionView, originalIndexPath: NSIndexPath, proposedIndexPath: NSIndexPath): NSIndexPath;
collectionViewTransitionLayoutForOldLayoutNewLayout(collectionView: UICollectionView, fromLayout: UICollectionViewLayout, toLayout: UICollectionViewLayout): UICollectionViewTransitionLayout;
collectionViewViewForSupplementaryElementOfKindAtIndexPath(collectionView: UICollectionView, kind: string, indexPath: NSIndexPath): UICollectionReusableView;
collectionViewWillDisplayCellForItemAtIndexPath(collectionView: UICollectionView, cell: UICollectionViewCell, indexPath: NSIndexPath): void;
collectionViewWillDisplaySupplementaryViewForElementKindAtIndexPath(collectionView: UICollectionView, view: UICollectionReusableView, elementKind: string, indexPath: NSIndexPath): void;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
deleteItemsAtIndexPaths(indexPaths: NSArray<any>): void;
dequeueLoadOnDemandCellForIndexPath(indexPath: NSIndexPath): TKListViewCell;
dequeueReusableCellWithReuseIdentifierForIndexPath(identifier: string, indexPath: NSIndexPath): any;
dequeueReusableSupplementaryViewOfKindWithReuseIdentifierForIndexPath(elementKind: string, identifier: string, indexPath: NSIndexPath): any;
deselectItemAtIndexPathAnimated(indexPath: NSIndexPath, animated: boolean): void;
didLoadDataOnDemand(): void;
didRefreshOnPull(): void;
endSwipe(animated: boolean): void;
indexPathForCell(cell: UICollectionViewCell): NSIndexPath;
indexPathForItemAtPoint(point: CGPoint): NSIndexPath;
indexPathForPreferredFocusedViewInCollectionView(collectionView: UICollectionView): NSIndexPath;
indexTitlesForCollectionView(collectionView: UICollectionView): NSArray<string>;
insertItemsAtIndexPaths(indexPaths: NSArray<any>): void;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
moveItemAtIndexPathToIndexPath(indexPath: NSIndexPath, newIndexPath: NSIndexPath): void;
numberOfItemsInSection(section: number): number;
numberOfSectionsInCollectionView(collectionView: UICollectionView): number;
performBatchUpdatesCompletion(updates: () => void, completion: (p1: boolean) => void): void;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
registerClassForCellWithReuseIdentifier(cellClass: typeof NSObject, identifier: string): void;
registerClassForSupplementaryViewOfKindWithReuseIdentifier(viewClass: typeof NSObject, elementKind: string, identifier: string): void;
registerLoadOnDemandCell(cellClass: typeof NSObject): void;
registerNibForCellReuseIdentifier(nib: UINib, identifier: string): void;
registerNibForSupplementaryViewOfKindWithReuseIdentifier(nib: UINib, elementKind: string, identifier: string): void;
reloadData(): void;
reloadItemsAtIndexPaths(indexPaths: NSArray<any>): void;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
scrollToItemAtIndexPathAtScrollPositionAnimated(indexPath: NSIndexPath, scrollPosition: UICollectionViewScrollPosition, animated: boolean): void;
scrollViewDidEndDecelerating(scrollView: UIScrollView): void;
scrollViewDidEndDraggingWillDecelerate(scrollView: UIScrollView, decelerate: boolean): void;
scrollViewDidEndScrollingAnimation(scrollView: UIScrollView): void;
scrollViewDidEndZoomingWithViewAtScale(scrollView: UIScrollView, view: UIView, scale: number): void;
scrollViewDidScroll(scrollView: UIScrollView): void;
scrollViewDidScrollToTop(scrollView: UIScrollView): void;
scrollViewDidZoom(scrollView: UIScrollView): void;
scrollViewShouldScrollToTop(scrollView: UIScrollView): boolean;
scrollViewWillBeginDecelerating(scrollView: UIScrollView): void;
scrollViewWillBeginDragging(scrollView: UIScrollView): void;
scrollViewWillBeginZoomingWithView(scrollView: UIScrollView, view: UIView): void;
scrollViewWillEndDraggingWithVelocityTargetContentOffset(scrollView: UIScrollView, velocity: CGPoint, targetContentOffset: interop.Pointer | interop.Reference<CGPoint>): void;
selectItemAtIndexPathAnimatedScrollPosition(indexPath: NSIndexPath, animated: boolean, scrollPosition: UICollectionViewScrollPosition): void;
self(): this;
viewForZoomingInScrollView(scrollView: UIScrollView): UIView;
}
declare class TKListViewCell extends TKListViewReusableCell {
static alloc(): TKListViewCell; // inherited from NSObject
static appearance(): TKListViewCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKListViewCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKListViewCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKListViewCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKListViewCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKListViewCell; // inherited from UIAppearance
static new(): TKListViewCell; // inherited from NSObject
contentInsets: UIEdgeInsets;
readonly detailTextLabel: UILabel;
readonly imageView: UIImageView;
offsetContentViewInMultipleSelection: boolean;
reorderHandle: UIView;
readonly swipeBackgroundView: UIView;
shouldSelect(): boolean;
}
declare class TKListViewCellBackgroundView extends TKView {
static alloc(): TKListViewCellBackgroundView; // inherited from NSObject
static appearance(): TKListViewCellBackgroundView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKListViewCellBackgroundView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKListViewCellBackgroundView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKListViewCellBackgroundView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKListViewCellBackgroundView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKListViewCellBackgroundView; // inherited from UIAppearance
static new(): TKListViewCellBackgroundView; // inherited from NSObject
allowsMultipleSelection: boolean;
checkInset: number;
readonly checkView: TKCheckView;
isSelectedBackground: boolean;
isVertical: boolean;
updateStyle(): void;
}
interface TKListViewDataSource extends NSObjectProtocol {
listViewCellForItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): TKListViewCell;
listViewNumberOfItemsInSection(listView: TKListView, section: number): number;
listViewViewForSupplementaryElementOfKindAtIndexPath?(listView: TKListView, kind: string, indexPath: NSIndexPath): TKListViewReusableCell;
numberOfSectionsInListView?(listView: TKListView): number;
}
declare var TKListViewDataSource: {
prototype: TKListViewDataSource;
};
interface TKListViewDelegate extends UIScrollViewDelegate {
listViewDidDeselectItemAtIndexPath?(listView: TKListView, indexPath: NSIndexPath): void;
listViewDidFinishSwipeCellAtIndexPathWithOffset?(listView: TKListView, cell: TKListViewCell, indexPath: NSIndexPath, offset: CGPoint): void;
listViewDidHighlightItemAtIndexPath?(listView: TKListView, indexPath: NSIndexPath): void;
listViewDidLongPressCellAtIndexPath?(listView: TKListView, cell: TKListViewCell, indexPath: NSIndexPath): void;
listViewDidPullWithOffset?(listView: TKListView, offset: number): void;
listViewDidReorderItemFromIndexPathToIndexPath?(listView: TKListView, originalIndexPath: NSIndexPath, targetIndexPath: NSIndexPath): void;
listViewDidSelectItemAtIndexPath?(listView: TKListView, indexPath: NSIndexPath): void;
listViewDidSwipeCellAtIndexPathWithOffset?(listView: TKListView, cell: TKListViewCell, indexPath: NSIndexPath, offset: CGPoint): void;
listViewDidUnhighlightItemAtIndexPath?(listView: TKListView, indexPath: NSIndexPath): void;
listViewShouldDeselectItemAtIndexPath?(listView: TKListView, indexPath: NSIndexPath): boolean;
listViewShouldHighlightItemAtIndexPath?(listView: TKListView, indexPath: NSIndexPath): boolean;
listViewShouldLoadMoreDataAtIndexPath?(listView: TKListView, indexPath: NSIndexPath): boolean;
listViewShouldRefreshOnPull?(listView: TKListView): boolean;
listViewShouldSelectItemAtIndexPath?(listView: TKListView, indexPath: NSIndexPath): boolean;
listViewShouldSwipeCellAtIndexPath?(listView: TKListView, cell: TKListViewCell, indexPath: NSIndexPath): boolean;
listViewWillReorderItemAtIndexPath?(listView: TKListView, indexPath: NSIndexPath): void;
}
declare var TKListViewDelegate: {
prototype: TKListViewDelegate;
};
declare var TKListViewElementKindSectionFooter: string;
declare var TKListViewElementKindSectionHeader: string;
declare class TKListViewFooterCell extends TKListViewReusableCell {
static alloc(): TKListViewFooterCell; // inherited from NSObject
static appearance(): TKListViewFooterCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKListViewFooterCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKListViewFooterCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKListViewFooterCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKListViewFooterCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKListViewFooterCell; // inherited from UIAppearance
static new(): TKListViewFooterCell; // inherited from NSObject
}
declare class TKListViewGridLayout extends TKListViewLinearLayout {
static alloc(): TKListViewGridLayout; // inherited from NSObject
static new(): TKListViewGridLayout; // inherited from NSObject
lineSpacing: number;
spanCount: number;
}
declare class TKListViewHeaderCell extends TKListViewReusableCell {
static alloc(): TKListViewHeaderCell; // inherited from NSObject
static appearance(): TKListViewHeaderCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKListViewHeaderCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKListViewHeaderCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKListViewHeaderCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKListViewHeaderCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKListViewHeaderCell; // inherited from UIAppearance
static new(): TKListViewHeaderCell; // inherited from NSObject
}
declare const enum TKListViewItemAlignment {
Stretch = 0,
Left = 1,
Center = 2,
Right = 3
}
declare const enum TKListViewItemAnimation {
Default = 0,
Fade = 1,
Scale = 2,
Slide = 3
}
declare class TKListViewLinearLayout extends UICollectionViewLayout {
static alloc(): TKListViewLinearLayout; // inherited from NSObject
static new(): TKListViewLinearLayout; // inherited from NSObject
animationDuration: number;
delegate: TKListViewLinearLayoutDelegate;
dynamicItemSize: boolean;
footerReferenceSize: CGSize;
headerReferenceSize: CGSize;
itemAlignment: TKListViewItemAlignment;
itemAppearAnimation: TKListViewItemAnimation;
itemDeleteAnimation: TKListViewItemAnimation;
itemInsertAnimation: TKListViewItemAnimation;
itemSize: CGSize;
itemSpacing: number;
owner: TKListView;
scrollDirection: TKListViewScrollDirection;
calculatedItemWidth(): number;
initFooterAttributesAtPoint(attributes: UICollectionViewLayoutAttributes, point: CGPoint): CGPoint;
initHeaderAttributesAtPoint(attributes: UICollectionViewLayoutAttributes, point: CGPoint): CGPoint;
initItemAttributesAtPointLastInSection(attributes: UICollectionViewLayoutAttributes, point: CGPoint, lastInSection: boolean): CGPoint;
layoutSectionAtPoint(section: number, location: CGPoint): CGPoint;
}
interface TKListViewLinearLayoutDelegate extends NSObjectProtocol {
listViewLayoutSizeForItemAtIndexPath(listView: TKListView, layout: TKListViewLinearLayout, indexPath: NSIndexPath): CGSize;
}
declare var TKListViewLinearLayoutDelegate: {
prototype: TKListViewLinearLayoutDelegate;
};
declare class TKListViewLoadOnDemandCell extends TKListViewCell {
static alloc(): TKListViewLoadOnDemandCell; // inherited from NSObject
static appearance(): TKListViewLoadOnDemandCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKListViewLoadOnDemandCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKListViewLoadOnDemandCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKListViewLoadOnDemandCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKListViewLoadOnDemandCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKListViewLoadOnDemandCell; // inherited from UIAppearance
static new(): TKListViewLoadOnDemandCell; // inherited from NSObject
activityIndicator: UIActivityIndicatorView;
updateState(): void;
}
declare const enum TKListViewLoadOnDemandMode {
None = 0,
Manual = 1,
Auto = 2
}
declare class TKListViewLoadOnDemandView extends UIView {
static alloc(): TKListViewLoadOnDemandView; // inherited from NSObject
static appearance(): TKListViewLoadOnDemandView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKListViewLoadOnDemandView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKListViewLoadOnDemandView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKListViewLoadOnDemandView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKListViewLoadOnDemandView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKListViewLoadOnDemandView; // inherited from UIAppearance
static new(): TKListViewLoadOnDemandView; // inherited from NSObject
}
declare class TKListViewPullToRefreshView extends UIView {
static alloc(): TKListViewPullToRefreshView; // inherited from NSObject
static appearance(): TKListViewPullToRefreshView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKListViewPullToRefreshView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKListViewPullToRefreshView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKListViewPullToRefreshView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKListViewPullToRefreshView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKListViewPullToRefreshView; // inherited from UIAppearance
static new(): TKListViewPullToRefreshView; // inherited from NSObject
readonly activityIndicator: UIActivityIndicatorView;
startAnimating(): void;
stopAnimating(): void;
}
declare class TKListViewReorderHandle extends UIView {
static alloc(): TKListViewReorderHandle; // inherited from NSObject
static appearance(): TKListViewReorderHandle; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKListViewReorderHandle; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKListViewReorderHandle; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKListViewReorderHandle; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKListViewReorderHandle; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKListViewReorderHandle; // inherited from UIAppearance
static new(): TKListViewReorderHandle; // inherited from NSObject
lineInsets: UIEdgeInsets;
lineStroke: TKStroke;
rowCount: number;
rowSpacing: number;
}
declare const enum TKListViewReorderMode {
WithHandle = 0,
WithLongPress = 1
}
declare class TKListViewReusableCell extends UICollectionViewCell {
static alloc(): TKListViewReusableCell; // inherited from NSObject
static appearance(): TKListViewReusableCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKListViewReusableCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKListViewReusableCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKListViewReusableCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKListViewReusableCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKListViewReusableCell; // inherited from UIAppearance
static new(): TKListViewReusableCell; // inherited from NSObject
readonly textLabel: UILabel;
}
declare const enum TKListViewScrollDirection {
Vertical = 0,
Horizontal = 1
}
declare const enum TKListViewSelectionBehavior {
None = 0,
Press = 1,
LongPress = 2
}
declare class TKListViewStaggeredLayout extends TKListViewGridLayout {
static alloc(): TKListViewStaggeredLayout; // inherited from NSObject
static new(): TKListViewStaggeredLayout; // inherited from NSObject
alignLastLine: boolean;
}
declare class TKMutableArray extends NSObject implements NSFastEnumeration {
static alloc(): TKMutableArray; // inherited from NSObject
static new(): TKMutableArray; // inherited from NSObject
readonly array: NSArray<any>;
[index: number]: any;
[Symbol.iterator](): Iterator<any>;
constructor(o: { array: NSArray<any>; });
addObject(object: any): void;
count(): number;
firstObject(): any;
initWithArray(array: NSArray<any>): this;
lastObject(): any;
objectAtIndex(index: number): any;
objectAtIndexedSubscript(idx: number): any;
removeObject(object: any): void;
removeObjectAtIndex(index: number): void;
setObjectAtIndexedSubscript(obj: any, idx: number): void;
}
declare class TKObservableArray extends NSObject implements NSFastEnumeration {
static alloc(): TKObservableArray; // inherited from NSObject
static new(): TKObservableArray; // inherited from NSObject
readonly array: NSArray<any>;
readonly count: number;
delegate: TKObservableArrayDelegate;
[index: number]: any;
[Symbol.iterator](): Iterator<any>;
addObject(object: any): void;
containsObject(object: any): boolean;
indexOfObject(object: any): number;
objectAtIndex(index: number): any;
objectAtIndexedSubscript(idx: number): any;
removeObject(object: any): void;
removeObjectAtIndex(index: number): void;
setObjectAtIndexedSubscript(obj: any, idx: number): void;
}
interface TKObservableArrayDelegate extends NSObjectProtocol {
didAddObjectAtIndex?(object: any, index: number): void;
didRemoveObjectAtIndex?(object: any, index: number): void;
didSetObjectAtIndexOfOldObject?(object: any, index: number, oldObject: any): void;
}
declare var TKObservableArrayDelegate: {
prototype: TKObservableArrayDelegate;
};
declare class TKPredefinedShape extends TKShape {
static alloc(): TKPredefinedShape; // inherited from NSObject
static new(): TKPredefinedShape; // inherited from NSObject
static shapeWithTypeAndSize(type: TKShapeType, size: CGSize): TKPredefinedShape;
readonly type: TKShapeType;
constructor(o: { type: TKShapeType; andSize: CGSize; });
initWithTypeAndSize(type: TKShapeType, size: CGSize): this;
}
declare class TKRadialGauge extends TKGauge {
static alloc(): TKRadialGauge; // inherited from NSObject
static appearance(): TKRadialGauge; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKRadialGauge; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKRadialGauge; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKRadialGauge; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKRadialGauge; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKRadialGauge; // inherited from UIAppearance
static new(): TKRadialGauge; // inherited from NSObject
labelSpacing: number;
}
declare class TKRadialGradientFill extends TKGradientFill {
static alloc(): TKRadialGradientFill; // inherited from NSObject
static new(): TKRadialGradientFill; // inherited from NSObject
static radialGradientFillWithColors(colors: NSArray<any>): TKRadialGradientFill;
static reverse(fill: TKRadialGradientFill): TKRadialGradientFill;
endCenter: CGPoint;
endRadius: number;
gradientRadiusType: TKGradientRadiusType;
startCenter: CGPoint;
startRadius: number;
constructor(o: { colors: NSArray<any>; startCenter: CGPoint; startRadius: number; endCenter: CGPoint; endRadius: number; });
constructor(o: { colors: NSArray<any>; startCenter: CGPoint; startRadius: number; endCenter: CGPoint; endRadius: number; radiusType: TKGradientRadiusType; });
initWithColorsStartCenterStartRadiusEndCenterEndRadius(colors: NSArray<any>, startCenter: CGPoint, startRadius: number, endCenter: CGPoint, endRadius: number): this;
initWithColorsStartCenterStartRadiusEndCenterEndRadiusRadiusType(colors: NSArray<any>, startCenter: CGPoint, startRadius: number, endCenter: CGPoint, endRadius: number, radiusType: TKGradientRadiusType): this;
}
declare class TKRange extends NSObject {
static alloc(): TKRange; // inherited from NSObject
static new(): TKRange; // inherited from NSObject
static rangeWithMinimumAndMaximum(minimum: any, maximum: any): TKRange;
static rangeWithMinimumIndexAndMaximumIndex(minimumIndex: number, maximumIndex: number): TKRange;
maximum: any;
minimum: any;
constructor(o: { minimum: any; andMaximum: any; });
initWithMinimumAndMaximum(minimum: any, maximum: any): this;
setMinimumAndMaximum(minimum: any, maximum: any): void;
setMinimumAndMaximumCalcWithCurrent(minimum: any, maximum: any, includeCurrentRange: boolean): void;
}
declare const enum TKRectSide {
Top = 1,
Bottom = 2,
Left = 4,
Right = 8,
All = -1
}
declare class TKShape extends NSObject {
static alloc(): TKShape; // inherited from NSObject
static new(): TKShape; // inherited from NSObject
readonly insets: UIEdgeInsets;
size: CGSize;
constructor(o: { size: CGSize; });
drawInContextWithCenterDrawings(context: any, center: CGPoint, drawings: NSArray<any>): void;
drawInContextWithCenterDrawingsScale(context: any, center: CGPoint, drawings: NSArray<any>, scale: number): void;
initWithSize(size: CGSize): this;
}
declare const enum TKShapeType {
None = 0,
Square = 1,
Circle = 2,
TriangleUp = 3,
TriangleDown = 4,
Rhombus = 5,
Pentagon = 6,
Hexagon = 7,
Star = 8,
Heart = 9
}
declare class TKSideDrawer extends TKView {
static alloc(): TKSideDrawer; // inherited from NSObject
static appearance(): TKSideDrawer; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKSideDrawer; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKSideDrawer; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKSideDrawer; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKSideDrawer; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKSideDrawer; // inherited from UIAppearance
static findSideDrawerAtIndexForViewController(index: number, viewController: UIViewController): TKSideDrawer;
static new(): TKSideDrawer; // inherited from NSObject
allowEdgeSwipe: boolean;
allowGestures: boolean;
allowScroll: boolean;
cancelTransition: boolean;
content: UIView;
delegate: TKSideDrawerDelegate;
edgeSwipeTreshold: number;
footerView: UIView;
headerView: UIView;
readonly hostview: UIView;
readonly isVisible: boolean;
position: TKSideDrawerPosition;
readonly sections: NSArray<any>;
readonly style: TKSideDrawerStyle;
theme: TKTheme;
title: string;
transition: TKSideDrawerTransitionType;
transitionDuration: number;
transitionManager: TKSideDrawerTransition;
width: number;
addSection(section: TKSideDrawerSection): void;
addSectionWithTitle(title: string): TKSideDrawerSection;
addSectionWithTitleImage(title: string, image: UIImage): TKSideDrawerSection;
dismiss(): void;
insertSectionAtIndex(section: TKSideDrawerSection, index: number): void;
removeAllSections(): void;
removeSection(section: TKSideDrawerSection): void;
selectItemAtIndexPath(indexPath: NSIndexPath): void;
show(): void;
showWithTransition(transition: TKSideDrawerTransitionType): void;
}
declare const enum TKSideDrawerBlurType {
None = 0,
Dynamic = 1,
Static = 2
}
declare class TKSideDrawerController extends UIViewController {
static alloc(): TKSideDrawerController; // inherited from NSObject
static new(): TKSideDrawerController; // inherited from NSObject
contentController: UIViewController;
readonly defaultSideDrawer: TKSideDrawer;
readonly sideDrawers: NSArray<any>;
constructor(o: { content: UIViewController; });
addSideDrawer(sideDrawer: TKSideDrawer): void;
addSideDrawerAtPosition(position: TKSideDrawerPosition): TKSideDrawer;
initWithContent(contentController: UIViewController): this;
removeAllSideDrawers(): void;
removeSideDrawer(sideDrawer: TKSideDrawer): void;
}
declare class TKSideDrawerDefaultTheme extends TKTheme {
static alloc(): TKSideDrawerDefaultTheme; // inherited from NSObject
static new(): TKSideDrawerDefaultTheme; // inherited from NSObject
}
interface TKSideDrawerDelegate extends NSObjectProtocol {
didDismissSideDrawer?(sideDrawer: TKSideDrawer): void;
didPanSideDrawer?(sideDrawer: TKSideDrawer): void;
didShowSideDrawer?(sideDrawer: TKSideDrawer): void;
sideDrawerCellForItemAtIndexPath?(sideDrawer: TKSideDrawer, indexPath: NSIndexPath): TKSideDrawerTableViewCell;
sideDrawerDidSelectItemAtIndexPath?(sideDrawer: TKSideDrawer, indexPath: NSIndexPath): void;
sideDrawerHeightForItemAtIndexPath?(sideDrawer: TKSideDrawer, indexPath: NSIndexPath): number;
sideDrawerUpdateVisualsForItemAtIndexPath?(sideDrawer: TKSideDrawer, indexPath: NSIndexPath): void;
sideDrawerUpdateVisualsForSection?(sideDrawer: TKSideDrawer, sectionIndex: number): void;
sideDrawerViewForHeaderInSection?(sideDrawer: TKSideDrawer, sectionIndex: number): UIView;
willDismissSideDrawer?(sideDrawer: TKSideDrawer): void;
willShowSideDrawer?(sideDrawer: TKSideDrawer): void;
}
declare var TKSideDrawerDelegate: {
prototype: TKSideDrawerDelegate;
};
declare class TKSideDrawerHeader extends TKView {
static alloc(): TKSideDrawerHeader; // inherited from NSObject
static appearance(): TKSideDrawerHeader; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKSideDrawerHeader; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKSideDrawerHeader; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKSideDrawerHeader; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKSideDrawerHeader; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKSideDrawerHeader; // inherited from UIAppearance
static new(): TKSideDrawerHeader; // inherited from NSObject
actionButton: UIButton;
buttonPosition: TKSideDrawerHeaderButtonPosition;
contentInsets: UIEdgeInsets;
imagePosition: TKSideDrawerItemImagePosition;
readonly imageView: UIImageView;
readonly separator: UIView;
separatorColor: TKFill;
readonly stack: TKCoreStackLayout;
readonly titleLabel: UILabel;
constructor(o: { title: string; });
constructor(o: { title: string; button: UIButton; });
constructor(o: { title: string; button: UIButton; image: UIImage; });
constructor(o: { title: string; image: UIImage; });
initWithTitle(title: string): this;
initWithTitleButton(title: string, button: UIButton): this;
initWithTitleButtonImage(title: string, button: UIButton, image: UIImage): this;
initWithTitleImage(title: string, image: UIImage): this;
}
declare const enum TKSideDrawerHeaderButtonPosition {
Left = 0,
Right = 1,
Top = 2,
Bottom = 3
}
declare class TKSideDrawerItem extends NSObject {
static alloc(): TKSideDrawerItem; // inherited from NSObject
static new(): TKSideDrawerItem; // inherited from NSObject
contentAlignment: TKSideDrawerTableViewCellContentAlignment;
image: UIImage;
readonly style: TKSideDrawerItemStyle;
title: string;
constructor(o: { title: string; });
constructor(o: { title: string; image: UIImage; });
initWithTitle(title: string): this;
initWithTitleImage(title: string, image: UIImage): this;
}
declare const enum TKSideDrawerItemImagePosition {
Left = 0,
Right = 1,
Top = 2,
Bottom = 3
}
declare class TKSideDrawerItemStyle extends TKStyleNode {
static alloc(): TKSideDrawerItemStyle; // inherited from NSObject
static new(): TKSideDrawerItemStyle; // inherited from NSObject
contentInsets: UIEdgeInsets;
fill: TKFill;
font: UIFont;
imagePosition: TKSideDrawerItemImagePosition;
separatorColor: TKFill;
stroke: TKStroke;
textAlignment: NSTextAlignment;
textColor: UIColor;
}
declare const enum TKSideDrawerPosition {
Left = 0,
Right = 1,
Top = 2,
Bottom = 3
}
declare class TKSideDrawerSection extends TKSideDrawerItem {
static alloc(): TKSideDrawerSection; // inherited from NSObject
static new(): TKSideDrawerSection; // inherited from NSObject
readonly items: NSArray<any>;
addItem(item: TKSideDrawerItem): void;
addItemWithTitle(title: string): TKSideDrawerItem;
addItemWithTitleImage(title: string, image: UIImage): TKSideDrawerItem;
insertItemAtIndex(item: TKSideDrawerItem, index: number): void;
removeAllItems(): void;
removeItem(item: TKSideDrawerItem): void;
}
declare const enum TKSideDrawerShadowMode {
None = 0,
Hostview = 1,
SideDrawer = 2
}
declare class TKSideDrawerStyle extends TKStyleNode {
static alloc(): TKSideDrawerStyle; // inherited from NSObject
static new(): TKSideDrawerStyle; // inherited from NSObject
blurEffect: UIBlurEffectStyle;
blurTintColor: UIColor;
blurType: TKSideDrawerBlurType;
dimOpacity: number;
footerHeight: number;
headerHeight: number;
itemHeight: number;
sectionHeaderHeight: number;
shadowMode: TKSideDrawerShadowMode;
shadowOffset: CGSize;
shadowOpacity: number;
shadowRadius: number;
}
declare class TKSideDrawerTableView extends UITableView implements UITableViewDataSource, UITableViewDelegate {
static alloc(): TKSideDrawerTableView; // inherited from NSObject
static appearance(): TKSideDrawerTableView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKSideDrawerTableView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKSideDrawerTableView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKSideDrawerTableView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKSideDrawerTableView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKSideDrawerTableView; // inherited from UIAppearance
static new(): TKSideDrawerTableView; // inherited from NSObject
sideDrawer: TKSideDrawer;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
constructor(o: { sideDrawer: TKSideDrawer; });
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
indexPathForPreferredFocusedViewInTableView(tableView: UITableView): NSIndexPath;
initWithSideDrawer(sideDrawer: TKSideDrawer): this;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
numberOfSectionsInTableView(tableView: UITableView): number;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
scrollViewDidEndDecelerating(scrollView: UIScrollView): void;
scrollViewDidEndDraggingWillDecelerate(scrollView: UIScrollView, decelerate: boolean): void;
scrollViewDidEndScrollingAnimation(scrollView: UIScrollView): void;
scrollViewDidEndZoomingWithViewAtScale(scrollView: UIScrollView, view: UIView, scale: number): void;
scrollViewDidScroll(scrollView: UIScrollView): void;
scrollViewDidScrollToTop(scrollView: UIScrollView): void;
scrollViewDidZoom(scrollView: UIScrollView): void;
scrollViewShouldScrollToTop(scrollView: UIScrollView): boolean;
scrollViewWillBeginDecelerating(scrollView: UIScrollView): void;
scrollViewWillBeginDragging(scrollView: UIScrollView): void;
scrollViewWillBeginZoomingWithView(scrollView: UIScrollView, view: UIView): void;
scrollViewWillEndDraggingWithVelocityTargetContentOffset(scrollView: UIScrollView, velocity: CGPoint, targetContentOffset: interop.Pointer | interop.Reference<CGPoint>): void;
sectionIndexTitlesForTableView(tableView: UITableView): NSArray<string>;
self(): this;
tableViewAccessoryButtonTappedForRowWithIndexPath(tableView: UITableView, indexPath: NSIndexPath): void;
tableViewAccessoryTypeForRowWithIndexPath(tableView: UITableView, indexPath: NSIndexPath): UITableViewCellAccessoryType;
tableViewCanEditRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): boolean;
tableViewCanFocusRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): boolean;
tableViewCanMoveRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): boolean;
tableViewCanPerformActionForRowAtIndexPathWithSender(tableView: UITableView, action: string, indexPath: NSIndexPath, sender: any): boolean;
tableViewCellForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): UITableViewCell;
tableViewCommitEditingStyleForRowAtIndexPath(tableView: UITableView, editingStyle: UITableViewCellEditingStyle, indexPath: NSIndexPath): void;
tableViewDidDeselectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): void;
tableViewDidEndDisplayingCellForRowAtIndexPath(tableView: UITableView, cell: UITableViewCell, indexPath: NSIndexPath): void;
tableViewDidEndDisplayingFooterViewForSection(tableView: UITableView, view: UIView, section: number): void;
tableViewDidEndDisplayingHeaderViewForSection(tableView: UITableView, view: UIView, section: number): void;
tableViewDidEndEditingRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): void;
tableViewDidHighlightRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): void;
tableViewDidSelectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): void;
tableViewDidUnhighlightRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): void;
tableViewDidUpdateFocusInContextWithAnimationCoordinator(tableView: UITableView, context: UITableViewFocusUpdateContext, coordinator: UIFocusAnimationCoordinator): void;
tableViewEditActionsForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): NSArray<UITableViewRowAction>;
tableViewEditingStyleForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): UITableViewCellEditingStyle;
tableViewEstimatedHeightForFooterInSection(tableView: UITableView, section: number): number;
tableViewEstimatedHeightForHeaderInSection(tableView: UITableView, section: number): number;
tableViewEstimatedHeightForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): number;
tableViewHeightForFooterInSection(tableView: UITableView, section: number): number;
tableViewHeightForHeaderInSection(tableView: UITableView, section: number): number;
tableViewHeightForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): number;
tableViewIndentationLevelForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): number;
tableViewMoveRowAtIndexPathToIndexPath(tableView: UITableView, sourceIndexPath: NSIndexPath, destinationIndexPath: NSIndexPath): void;
tableViewNumberOfRowsInSection(tableView: UITableView, section: number): number;
tableViewPerformActionForRowAtIndexPathWithSender(tableView: UITableView, action: string, indexPath: NSIndexPath, sender: any): void;
tableViewSectionForSectionIndexTitleAtIndex(tableView: UITableView, title: string, index: number): number;
tableViewShouldHighlightRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): boolean;
tableViewShouldIndentWhileEditingRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): boolean;
tableViewShouldShowMenuForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): boolean;
tableViewShouldUpdateFocusInContext(tableView: UITableView, context: UITableViewFocusUpdateContext): boolean;
tableViewTargetIndexPathForMoveFromRowAtIndexPathToProposedIndexPath(tableView: UITableView, sourceIndexPath: NSIndexPath, proposedDestinationIndexPath: NSIndexPath): NSIndexPath;
tableViewTitleForDeleteConfirmationButtonForRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): string;
tableViewTitleForFooterInSection(tableView: UITableView, section: number): string;
tableViewTitleForHeaderInSection(tableView: UITableView, section: number): string;
tableViewViewForFooterInSection(tableView: UITableView, section: number): UIView;
tableViewViewForHeaderInSection(tableView: UITableView, section: number): UIView;
tableViewWillBeginEditingRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): void;
tableViewWillDeselectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): NSIndexPath;
tableViewWillDisplayCellForRowAtIndexPath(tableView: UITableView, cell: UITableViewCell, indexPath: NSIndexPath): void;
tableViewWillDisplayFooterViewForSection(tableView: UITableView, view: UIView, section: number): void;
tableViewWillDisplayHeaderViewForSection(tableView: UITableView, view: UIView, section: number): void;
tableViewWillSelectRowAtIndexPath(tableView: UITableView, indexPath: NSIndexPath): NSIndexPath;
viewForZoomingInScrollView(scrollView: UIScrollView): UIView;
}
declare class TKSideDrawerTableViewCell extends UITableViewCell {
static alloc(): TKSideDrawerTableViewCell; // inherited from NSObject
static appearance(): TKSideDrawerTableViewCell; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKSideDrawerTableViewCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKSideDrawerTableViewCell; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKSideDrawerTableViewCell; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKSideDrawerTableViewCell; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKSideDrawerTableViewCell; // inherited from UIAppearance
static new(): TKSideDrawerTableViewCell; // inherited from NSObject
item: TKSideDrawerItem;
separator: UIView;
readonly stack: TKCoreStackLayout;
update(): void;
}
declare const enum TKSideDrawerTableViewCellContentAlignment {
Left = 0,
Right = 1,
Center = 2
}
declare class TKSideDrawerTransition extends NSObject {
static alloc(): TKSideDrawerTransition; // inherited from NSObject
static new(): TKSideDrawerTransition; // inherited from NSObject
sideDrawer: TKSideDrawer;
constructor(o: { sideDrawer: TKSideDrawer; });
dismiss(): void;
handleGesture(gestureRecognizer: UIGestureRecognizer): void;
initWithSideDrawer(sideDrawer: TKSideDrawer): this;
show(): void;
transitionBegan(showing: boolean): void;
transitionEnded(showing: boolean): void;
}
declare const enum TKSideDrawerTransitionType {
SlideInOnTop = 0,
Reveal = 1,
Push = 2,
SlideAlong = 3,
ReverseSlideOut = 4,
ScaleUp = 5,
FadeIn = 6,
ScaleDownPusher = 7,
Custom = 8
}
declare class TKSideDrawerView extends UIView {
static alloc(): TKSideDrawerView; // inherited from NSObject
static appearance(): TKSideDrawerView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKSideDrawerView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKSideDrawerView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKSideDrawerView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKSideDrawerView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKSideDrawerView; // inherited from UIAppearance
static new(): TKSideDrawerView; // inherited from NSObject
readonly defaultSideDrawer: TKSideDrawer;
mainView: UIView;
readonly sideDrawers: NSArray<TKSideDrawer>;
constructor(o: { frame: CGRect; mainView: UIView; });
addSideDrawer(sideDrawer: TKSideDrawer): void;
addSideDrawerAtPosition(position: TKSideDrawerPosition): TKSideDrawer;
attachDrawerToWindow(): void;
detachDrawerFromWindow(): void;
initWithFrameMainView(frame: CGRect, mainView: UIView): this;
removeAllSideDrawers(): void;
removeSideDrawer(sideDrawer: TKSideDrawer): void;
}
declare class TKSlideView extends UIView {
static alloc(): TKSlideView; // inherited from NSObject
static appearance(): TKSlideView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKSlideView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKSlideView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKSlideView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKSlideView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKSlideView; // inherited from UIAppearance
static new(): TKSlideView; // inherited from NSObject
currentView: UIView;
delegate: TKSlideViewDelegate;
disableSwipe: boolean;
slideDirection: TKSwipeDirection;
next(): void;
previous(): void;
}
interface TKSlideViewDelegate extends NSObjectProtocol {
slideViewDidSlideToView?(view: UIView): void;
slideViewWillSlideToView?(view: UIView): boolean;
}
declare var TKSlideViewDelegate: {
prototype: TKSlideViewDelegate;
};
declare class TKSolidFill extends TKFill {
static alloc(): TKSolidFill; // inherited from NSObject
static new(): TKSolidFill; // inherited from NSObject
static solidFillWithColor(color: UIColor): TKSolidFill;
static solidFillWithColorCornerRadius(color: UIColor, cornerRadius: number): TKSolidFill;
color: UIColor;
constructor(o: { color: UIColor; });
constructor(o: { color: UIColor; cornerRadius: number; });
initWithColor(color: UIColor): this;
initWithColorCornerRadius(color: UIColor, cornerRadius: number): this;
}
declare class TKStackLayout extends NSObject implements TKLayout {
static alloc(): TKStackLayout; // inherited from NSObject
static new(): TKStackLayout; // inherited from NSObject
alignment: TKStackLayoutAlignment;
readonly arrangedViews: NSArray<any>;
distribution: TKStackLayoutDistribution;
spacing: number;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
frame: CGRect; // inherited from TKLayout
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
orientation: TKLayoutOrientation; // inherited from TKLayout
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
constructor(o: { frame: CGRect; });
addArrangedView(view: UIView): void;
arrangeViewWithLayoutInfo(view: UIView, layoutInfo: TKLayoutInfo): void;
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
initWithFrame(frame: CGRect): this;
insertArrangedViewAtIndex(view: UIView, index: number): void;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
layoutArrangedViews(): void;
measurePreferredSizeThatFitsSize(size: CGSize): CGSize;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
removeAllArrangedViews(): void;
removeArrangedView(view: UIView): void;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
self(): this;
}
declare const enum TKStackLayoutAlignment {
Fill = 0,
Top = 1,
Center = 2,
Bottom = 3,
Leading = 4,
Trailing = 5
}
declare const enum TKStackLayoutDistribution {
None = 0,
FillEqually = 1,
FillProportionally = 2
}
declare class TKStroke extends NSObject implements NSCopying, TKDrawing {
static alloc(): TKStroke; // inherited from NSObject
static new(): TKStroke; // inherited from NSObject
static strokeWithColor(color: UIColor): TKStroke;
static strokeWithColorWidth(color: UIColor, width: number): TKStroke;
static strokeWithColorWidthCornerRadius(color: UIColor, width: number, cornerRadius: number): TKStroke;
static strokeWithFill(fill: TKFill): TKStroke;
static strokeWithFillWidth(fill: TKFill, width: number): TKStroke;
static strokeWithFillWidthCornerRadius(fill: TKFill, width: number, cornerRadius: number): TKStroke;
allowsAntialiasing: boolean;
color: UIColor;
cornerRadius: number;
corners: UIRectCorner;
dashPattern: NSArray<any>;
fill: TKFill;
lineCap: CGLineCap;
lineJoin: CGLineJoin;
miterLimit: number;
phase: number;
shadowBlur: number;
shadowColor: UIColor;
shadowOffset: CGSize;
strokeSides: TKRectSide;
width: number;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
insets: UIEdgeInsets; // inherited from TKDrawing
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
constructor(o: { color: UIColor; });
constructor(o: { color: UIColor; width: number; });
constructor(o: { fill: TKFill; });
constructor(o: { fill: TKFill; width: number; });
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
copyWithZone(zone: interop.Pointer | interop.Reference<any>): any;
drawInContextWithPath(context: any, path: any): void;
drawInContextWithRect(context: any, rect: CGRect): void;
initWithColor(color: UIColor): this;
initWithColorWidth(color: UIColor, width: number): this;
initWithFill(fill: TKFill): this;
initWithFillWidth(fill: TKFill, width: 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;
}
declare class TKStyleID extends NSObject {
static alloc(): TKStyleID; // inherited from NSObject
static new(): TKStyleID; // inherited from NSObject
conditionClass: typeof NSObject;
state: number;
stylableClass: typeof NSObject;
constructor(o: { class: typeof NSObject; withState: number; });
initWithClassWithState(aStylableClass: typeof NSObject, aState: number): this;
}
declare class TKStyleNode extends NSObject {
static alloc(): TKStyleNode; // inherited from NSObject
static new(): TKStyleNode; // inherited from NSObject
readonly isThemeBlock: boolean;
styleID: TKStyleID;
beginThemeBlock(): void;
canSetValue(value: number): boolean;
endThemeBlock(): void;
resetLocalValues(): void;
}
declare class TKSuggestionListView extends TKListView implements TKAutoCompleteSuggestViewDelegate, TKListViewDataSource, TKListViewDelegate {
static alloc(): TKSuggestionListView; // inherited from NSObject
static appearance(): TKSuggestionListView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKSuggestionListView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKSuggestionListView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKSuggestionListView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKSuggestionListView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKSuggestionListView; // inherited from UIAppearance
static new(): TKSuggestionListView; // inherited from NSObject
items: NSArray<TKAutoCompleteToken>;
owner: TKAutoCompleteTextView;
readonly progressBar: UIProgressView;
selectedIndexPath: NSIndexPath;
selectedItem: TKAutoCompleteToken;
readonly debugDescription: string; // inherited from NSObjectProtocol
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
readonly // inherited from NSObjectProtocol
constructor(o: { autoComplete: TKAutoCompleteTextView; });
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
hide(): void;
initWithAutoComplete(autocomplete: TKAutoCompleteTextView): this;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
listViewCellForItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): TKListViewCell;
listViewDidDeselectItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): void;
listViewDidFinishSwipeCellAtIndexPathWithOffset(listView: TKListView, cell: TKListViewCell, indexPath: NSIndexPath, offset: CGPoint): void;
listViewDidHighlightItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): void;
listViewDidLongPressCellAtIndexPath(listView: TKListView, cell: TKListViewCell, indexPath: NSIndexPath): void;
listViewDidPullWithOffset(listView: TKListView, offset: number): void;
listViewDidReorderItemFromIndexPathToIndexPath(listView: TKListView, originalIndexPath: NSIndexPath, targetIndexPath: NSIndexPath): void;
listViewDidSelectItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): void;
listViewDidSwipeCellAtIndexPathWithOffset(listView: TKListView, cell: TKListViewCell, indexPath: NSIndexPath, offset: CGPoint): void;
listViewDidUnhighlightItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): void;
listViewNumberOfItemsInSection(listView: TKListView, section: number): number;
listViewShouldDeselectItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): boolean;
listViewShouldHighlightItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): boolean;
listViewShouldLoadMoreDataAtIndexPath(listView: TKListView, indexPath: NSIndexPath): boolean;
listViewShouldRefreshOnPull(listView: TKListView): boolean;
listViewShouldSelectItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): boolean;
listViewShouldSwipeCellAtIndexPath(listView: TKListView, cell: TKListViewCell, indexPath: NSIndexPath): boolean;
listViewViewForSupplementaryElementOfKindAtIndexPath(listView: TKListView, kind: string, indexPath: NSIndexPath): TKListViewReusableCell;
listViewWillReorderItemAtIndexPath(listView: TKListView, indexPath: NSIndexPath): void;
numberOfSectionsInListView(listView: TKListView): number;
performSelector(aSelector: string): any;
performSelectorWithObject(aSelector: string, object: any): any;
performSelectorWithObjectWithObject(aSelector: string, object1: any, object2: any): any;
populateWithItems(items: NSArray<TKAutoCompleteToken>): void;
reloadSuggestions(): void;
respondsToSelector(aSelector: string): boolean;
retainCount(): number;
scrollViewDidEndDecelerating(scrollView: UIScrollView): void;
scrollViewDidEndDraggingWillDecelerate(scrollView: UIScrollView, decelerate: boolean): void;
scrollViewDidEndScrollingAnimation(scrollView: UIScrollView): void;
scrollViewDidEndZoomingWithViewAtScale(scrollView: UIScrollView, view: UIView, scale: number): void;
scrollViewDidScroll(scrollView: UIScrollView): void;
scrollViewDidScrollToTop(scrollView: UIScrollView): void;
scrollViewDidZoom(scrollView: UIScrollView): void;
scrollViewShouldScrollToTop(scrollView: UIScrollView): boolean;
scrollViewWillBeginDecelerating(scrollView: UIScrollView): void;
scrollViewWillBeginDragging(scrollView: UIScrollView): void;
scrollViewWillBeginZoomingWithView(scrollView: UIScrollView, view: UIView): void;
scrollViewWillEndDraggingWithVelocityTargetContentOffset(scrollView: UIScrollView, velocity: CGPoint, targetContentOffset: interop.Pointer | interop.Reference<CGPoint>): void;
self(): this;
shouldAlwaysHideSuggestionView(): boolean;
show(): void;
viewForZoomingInScrollView(scrollView: UIScrollView): UIView;
}
declare const enum TKSwipeDirection {
Horizontal = 0,
Vertical = 1
}
declare class TKTab extends NSObject {
static alloc(): TKTab; // inherited from NSObject
static new(): TKTab; // inherited from NSObject
contentView: UIView;
readonly title: string;
view: TKTabItemView;
constructor(o: { title: string; });
constructor(o: { title: string; andView: UIView; });
initWithTitle(title: string): this;
initWithTitleAndView(title: string, view: UIView): this;
}
declare const enum TKTabAlignment {
Top = 0,
Bottom = 1,
Left = 2,
Right = 3,
Center = 4,
Stretch = 5
}
declare class TKTabItemView extends UIView {
static alloc(): TKTabItemView; // inherited from NSObject
static appearance(): TKTabItemView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKTabItemView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKTabItemView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKTabItemView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKTabItemView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKTabItemView; // inherited from UIAppearance
static new(): TKTabItemView; // inherited from NSObject
accentColor: UIColor;
deselectedBackgroundColor: UIColor;
deselectedForegroundColor: UIColor;
deselectedImage: UIImage;
imageView: UIImageView;
selected: boolean;
selectedBackgroundColor: UIColor;
selectedForegroundColor: UIColor;
selectedImage: UIImage;
textView: UILabel;
}
interface TKTabLayout extends NSObjectProtocol {
delegate: TKTabLayoutDelegate;
maxVisibleTabs: number;
selectedTabMarker: UIView;
selectedTabMarkerHeight: number;
tabAlignment: TKTabAlignment;
tabHeight: number;
tabWidth: number;
didAddTab(tab: TKTab): void;
didRemoveTab(tab: TKTab): void;
didSelectTabDeselectedTab(selectedTab: TKTab, deselectedTab: TKTab): void;
layoutTabsInFrame(frame: CGRect): void;
load(tabView: TKTabStrip): void;
unload(): void;
updateSelectedTabMarkerForTab(selectedTab: TKTab): void;
}
declare var TKTabLayout: {
prototype: TKTabLayout;
};
declare class TKTabLayoutBase extends NSObject implements TKTabLayout {
static alloc(): TKTabLayoutBase; // inherited from NSObject
static new(): TKTabLayoutBase; // inherited from NSObject
readonly debugDescription: string; // inherited from NSObjectProtocol
delegate: TKTabLayoutDelegate; // inherited from TKTabLayout
readonly description: string; // inherited from NSObjectProtocol
readonly hash: number; // inherited from NSObjectProtocol
readonly isProxy: boolean; // inherited from NSObjectProtocol
maxVisibleTabs: number; // inherited from TKTabLayout
selectedTabMarker: UIView; // inherited from TKTabLayout
selectedTabMarkerHeight: number; // inherited from TKTabLayout
readonly superclass: typeof NSObject; // inherited from NSObjectProtocol
tabAlignment: TKTabAlignment; // inherited from TKTabLayout
tabHeight: number; // inherited from TKTabLayout
tabWidth: number; // inherited from TKTabLayout
readonly // inherited from NSObjectProtocol
class(): typeof NSObject;
conformsToProtocol(aProtocol: any /* Protocol */): boolean;
didAddTab(tab: TKTab): void;
didRemoveTab(tab: TKTab): void;
didSelectTabDeselectedTab(selectedTab: TKTab, deselectedTab: TKTab): void;
isEqual(object: any): boolean;
isKindOfClass(aClass: typeof NSObject): boolean;
isMemberOfClass(aClass: typeof NSObject): boolean;
layoutTabsInFrame(frame: CGRect): void;
load(tabView: TKTabStrip): void;
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;
unload(): void;
updateSelectedTabMarkerForTab(selectedTab: TKTab): void;
}
interface TKTabLayoutDelegate extends NSObjectProtocol {
layoutSelectedTabMarker(availableSpace: CGRect): CGRect;
}
declare var TKTabLayoutDelegate: {
prototype: TKTabLayoutDelegate;
};
declare class TKTabOverflowLayout extends TKTabLayoutBase {
static alloc(): TKTabOverflowLayout; // inherited from NSObject
static new(): TKTabOverflowLayout; // inherited from NSObject
readonly overflowButton: UIButton;
readonly overflowPopup: UIView;
}
declare class TKTabScrollLayout extends TKTabLayoutBase {
static alloc(): TKTabScrollLayout; // inherited from NSObject
static new(): TKTabScrollLayout; // inherited from NSObject
readonly scrollView: UIScrollView;
tabSpacing: number;
}
declare class TKTabStrip extends UIView {
static alloc(): TKTabStrip; // inherited from NSObject
static appearance(): TKTabStrip; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKTabStrip; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKTabStrip; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKTabStrip; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKTabStrip; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKTabStrip; // inherited from UIAppearance
static new(): TKTabStrip; // inherited from NSObject
animateSelectedMarker: boolean;
delegate: TKTabStripDelegate;
layout: TKTabLayout;
selectedTab: TKTab;
selectedTabMarker: UIView;
selectedTabMarkerHeight: number;
tabs: TKObservableArray;
canSelectTab(tab: TKTab): boolean;
findTabForContentView(view: UIView): TKTab;
findTabForView(view: UIView): TKTab;
requestLayout(): void;
}
interface TKTabStripDelegate extends NSObjectProtocol {
tabStripDidSelectTab?(tab: TKTab): void;
tabStripWillSelectTab?(tab: TKTab): boolean;
}
declare var TKTabStripDelegate: {
prototype: TKTabStripDelegate;
};
declare class TKTabView extends UIView {
static alloc(): TKTabView; // inherited from NSObject
static appearance(): TKTabView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKTabView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKTabView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKTabView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKTabView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKTabView; // inherited from UIAppearance
static new(): TKTabView; // inherited from NSObject
delegate: TKTabViewDelegate;
selectedTab: TKTab;
slideView: TKSlideView;
tabStrip: TKTabStrip;
tabs: TKObservableArray;
tabsPosition: TKTabViewPosition;
constructor(o: { viewControllers: NSArray<any>; });
addTabWithTitle(title: string): TKTab;
addTabWithTitleAndContentView(title: string, contentView: UIView): TKTab;
addTabWithTitleViewAndContentView(title: string, view: TKTabItemView, contentView: UIView): TKTab;
initWithViewControllers(controllers: NSArray<any>): this;
removeTab(tab: TKTab): boolean;
removeTabWithTitle(title: string): void;
tabWithTitle(title: string): TKTab;
}
interface TKTabViewDelegate extends NSObjectProtocol {
adjustSlideViewLayout?(availableSpace: CGRect): CGRect;
adjustTabStripLayout?(availableSpace: CGRect): CGRect;
contentViewForTab?(tab: TKTab): UIView;
tabViewDidSelectTab?(tab: TKTab): void;
tabViewWillSelectTab?(tab: TKTab): boolean;
viewForTab?(tab: TKTab): TKTabItemView;
}
declare var TKTabViewDelegate: {
prototype: TKTabViewDelegate;
};
declare const enum TKTabViewPosition {
Top = 0,
Bottom = 1,
Left = 2,
Right = 3
}
declare class TKTextField extends UITextField {
static alloc(): TKTextField; // inherited from NSObject
static appearance(): TKTextField; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKTextField; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKTextField; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKTextField; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKTextField; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKTextField; // inherited from UIAppearance
static new(): TKTextField; // inherited from NSObject
textInsets: UIEdgeInsets;
}
declare class TKTheme extends NSObject {
static alloc(): TKTheme; // inherited from NSObject
static new(): TKTheme; // inherited from NSObject
}
declare class TKView extends UIView {
static alloc(): TKView; // inherited from NSObject
static appearance(): TKView; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKView; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKView; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKView; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKView; // inherited from UIAppearance
static new(): TKView; // inherited from NSObject
static versionString(): string;
drawables: NSArray<any>;
fill: TKFill;
layout: TKCoreLayout;
shape: TKShape;
stroke: TKStroke;
}
declare class TKViewTransition extends UIView {
static alloc(): TKViewTransition; // inherited from NSObject
static appearance(): TKViewTransition; // inherited from UIAppearance
static appearanceForTraitCollection(trait: UITraitCollection): TKViewTransition; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedIn(trait: UITraitCollection, ContainerClass: typeof NSObject): TKViewTransition; // inherited from UIAppearance
static appearanceForTraitCollectionWhenContainedInInstancesOfClasses(trait: UITraitCollection, containerTypes: NSArray<typeof NSObject>): TKViewTransition; // inherited from UIAppearance
static appearanceWhenContainedIn(ContainerClass: typeof NSObject): TKViewTransition; // inherited from UIAppearance
static appearanceWhenContainedInInstancesOfClasses(containerTypes: NSArray<typeof NSObject>): TKViewTransition; // inherited from UIAppearance
static new(): TKViewTransition; // inherited from NSObject
readonly isForward: boolean;
readonly isVertical: boolean;
transitionDuration: number;
direction(): TKViewTransitionDirection;
orientation(): TKViewTransitionOrientation;
}
declare const enum TKViewTransitionDirection {
Forward = 0,
Backward = 1
}
declare const enum TKViewTransitionOrientation {
Horizontal = 0,
Vertical = 1
}
declare class TelerikUI extends NSObject {
static alloc(): TelerikUI; // inherited from NSObject
static loadClasses(): void;
static new(): TelerikUI; // inherited from NSObject
static versionString(): string;
} | the_stack |
import { cparser } from "codsen-parser";
import { Ranges } from "ranges-push";
import { rApply } from "ranges-apply";
import { traverse } from "ast-monkey-traverse-with-lookahead";
import { version as v } from "../package.json";
const version: string = v;
const htmlCommentRegex = /<!--([\s\S]*?)-->/g;
const ranges = new Ranges();
function isObj(something: any): boolean {
return (
something && typeof something === "object" && !Array.isArray(something)
);
}
interface Obj {
[key: string]: any;
}
// the plan is to use defaults on the UI, so export them as first-class citizen
interface Opts {
cssStylesContent: string;
alwaysCenter: boolean;
}
const defaults: Opts = {
cssStylesContent: "",
alwaysCenter: false,
};
/**
* Visual helper to place templating code around table tags into correct places
*/
function patcher(str: string, generalOpts?: Partial<Opts>): { result: string } {
// insurance
// ---------------------------------------------------------------------------
// if inputs are wrong, just return what was given
if (typeof str !== "string" || str.length === 0) {
return { result: str };
}
// setup
// ---------------------------------------------------------------------------
// clone the defaults, don't mutate the input argument object
const opts = { ...defaults, ...generalOpts };
if (
opts.cssStylesContent &&
// if not a string was passed
(typeof opts.cssStylesContent !== "string" ||
// or it was empty of full of whitespace
!opts.cssStylesContent.trim())
) {
opts.cssStylesContent = "";
}
console.log(
`059 ${`\u001b[${32}m${`FINAL`}\u001b[${39}m`} ${`\u001b[${33}m${`opts`}\u001b[${39}m`} = ${JSON.stringify(
opts,
null,
4
)}`
);
// the bizness
// ---------------------------------------------------------------------------
// traversal is done from a callback, same like Array.prototype.forEach()
// you don't assign anything, as in "const x = traverse(..." -
// instead, you do the deed inside the callback function
//
// ensure that we don't traverse inside comment tokens
// practically we achieve that by comparing does current path start with
// and of the known comment token paths:
const knownCommentTokenPaths: string[] = [];
console.log(`079 ${`\u001b[${36}m${`COMMENCE THE TRAVERSE`}\u001b[${39}m`}`);
traverse(cparser(str), (token, _val, innerObj) => {
/* istanbul ignore else */
if (
isObj(token) &&
(token as Obj).type === "comment" &&
!knownCommentTokenPaths.some((oneOfRecordedPaths) =>
innerObj.path.startsWith(oneOfRecordedPaths)
)
) {
knownCommentTokenPaths.push(innerObj.path);
} else if (
// tags are always stuck in an array, "root" level is array too
// ast-monkey reports array elements as "key" and "value" is undefined.
// if this was object, "key" would be key of key/value pair, "value"
// would be value of the key/value pair.
//
// The tag itself is a plain object:
isObj(token) &&
// filter by type and tag name
(token as Obj).type === "tag" &&
(token as Obj).tagName === "table" &&
!knownCommentTokenPaths.some((oneOfKnownCommentPaths) =>
innerObj.path.startsWith(oneOfKnownCommentPaths)
) &&
// ensure it's not closing, otherwise closing tags will be caught too:
!(token as Obj).closing &&
// we wrap either raw text or esp template tag nodes only:
(token as Obj).children.some((childNodeObj: Obj) =>
["text", "esp"].includes(childNodeObj.type)
)
) {
// so this table does have some text nodes straight inside TABLE tag
console.log(
`113 ${`\u001b[${32}m${`TABLE caught!`}\u001b[${39}m`} Path: ${
innerObj.path
}`
);
// find out how many TD's are there on TR's that have TD's (if any exist)
// then, that value, if greater then 1 will be the colspan value -
// we'll wrap this text node's contents with one TR and one TD - but
// set TD colspan to this value:
let colspanVal = 1;
// if td we decide the colspan contains some attributes, we'll note
// down the range of where first attrib starts and last attrib ends
// then slice that range and insert of every td, along the colspan
let centered = false;
let firstTrFound: Obj = {};
if (
// some TR's exist inside this TABLE tag
(token as Obj).children.some(
(childNodeObj: Obj) =>
childNodeObj.type === "tag" &&
childNodeObj.tagName === "tr" &&
!childNodeObj.closing &&
(firstTrFound = childNodeObj)
)
) {
console.log(`140 ${`\u001b[${32}m${`TR`}\u001b[${39}m`} found`);
// console.log(
// `108 ${`\u001b[${33}m${`firstTrFound`}\u001b[${39}m`} = ${JSON.stringify(
// firstTrFound,
// null,
// 4
// )}`
// );
// colspanVal is equal to the count of TD's inside children[] array
// the only condition - we count consecutive TD's, any ESP or text
// token breaks the counting
let count = 0;
// console.log(
// `132 FILTER ${`\u001b[${33}m${`firstTrFound.children`}\u001b[${39}m`} = ${JSON.stringify(
// firstTrFound.children,
// null,
// 4
// )}`
// );
for (
let i = 0, len = (firstTrFound as any).children.length;
i < len;
i++
) {
const obj = (firstTrFound as any).children[i];
// console.log(
// `141 ---------------- ${`\u001b[${33}m${`obj`}\u001b[${39}m`} = ${JSON.stringify(
// obj,
// null,
// 4
// )}`
// );
// count consecutive TD's
if (obj.type === "tag" && obj.tagName === "td") {
if (!obj.closing) {
// detect center-alignment
centered = obj.attribs.some(
(attrib: Obj) =>
(attrib.attribName === "align" &&
attrib.attribValueRaw === "center") ||
(attrib.attribName === "style" &&
/text-align:\s*center/i.test(attrib.attribValueRaw))
);
count++;
if (count > colspanVal) {
colspanVal = count;
}
}
// else - ignore closing tags
} else if (
obj.type !== "text" ||
obj.value.replace(htmlCommentRegex, "").trim()
) {
// reset
count = 0;
}
// console.log(
// `174 ${`\u001b[${33}m${`count`}\u001b[${39}m`} = ${JSON.stringify(
// count,
// null,
// 4
// )}`
// );
}
}
console.log(
`212 ${`\u001b[${32}m${`FINAL`}\u001b[${39}m`} ${`\u001b[${33}m${`colspanVal`}\u001b[${39}m`} = ${JSON.stringify(
colspanVal,
null,
4
)}`
);
//
//
//
// T Y P E I.
//
//
//
// -----------------------------------------------------------------------------
console.log(" ");
console.log(
`230 ${`\u001b[${35}m${`TYPE I.`}\u001b[${39}m`}`
);
console.log(" ");
// now filter all "text" type children nodes from this TABLE tag
// this key below is the table tag we filtered in the beginning
(token as Obj).children
// filter out text nodes:
.filter((childNodeObj: Obj) =>
["text", "esp"].includes(childNodeObj.type)
)
// wrap each with TR+TD with colspan:
.forEach((obj: Obj) => {
console.log(
`244 -------------------- ${`\u001b[${32}m${`PROCESSING INSIDE TABLE`}\u001b[${39}m`} --------------------`
);
console.log(
`247 text node, ${`\u001b[${33}m${`obj`}\u001b[${39}m`} = ${JSON.stringify(
obj,
null,
4
)}`
);
console.log(" ");
console.log(
`255 ${
obj.value.trim()
? `${`\u001b[${32}m${`this one needs wrapping`}\u001b[${39}m`}`
: `${`\u001b[${31}m${`this one does not need wrapping`}\u001b[${39}m`}`
}`
);
if (obj.value.replace(htmlCommentRegex, "").trim()) {
// There will always be whitespace in nicely formatted tags,
// so ignore text tokens which have values that trim to zero length.
//
// Since trimmed value of zero length is already falsey, we don't
// need to do
// "if (obj.value.trim().length)" or
// "if (obj.value.trim() === "")" or
// "if (obj.value.trim().length === 0)"
//
ranges.push(
obj.start,
obj.end,
`\n<tr>\n <td${
colspanVal > 1 ? ` colspan="${colspanVal}"` : ""
}${opts.alwaysCenter || centered ? ` align="center"` : ""}${
opts.cssStylesContent ? ` style="${opts.cssStylesContent}"` : ""
}>\n ${obj.value.trim()}\n </td>\n</tr>\n`
);
}
});
//
//
//
// T Y P E II.
//
//
//
// -----------------------------------------------------------------------------
console.log(" ");
console.log(
`294 ${`\u001b[${35}m${`TYPE II.`}\u001b[${39}m`}`
);
console.log(" ");
(token as Obj).children
// filter out text nodes:
.filter(
(obj: Obj) =>
obj.type === "tag" && obj.tagName === "tr" && !obj.closing
)
.forEach((trTag: Obj) => {
// console.log(
// `224 ██ ${`\u001b[${33}m${`trTag`}\u001b[${39}m`} = ${JSON.stringify(
// trTag,
// null,
// 4
// )}`
// );
// we use for loop because we need to look back, what token was
// before, plus filter
let doNothing = false;
for (let i = 0, len = trTag.children.length; i < len; i++) {
console.log(
`319 -------------------- ${`\u001b[${32}m${`PROCESSING INSIDE TR`}\u001b[${39}m`} --------------------`
);
const childNodeObj = trTag.children[i];
// deactivate
if (
doNothing &&
childNodeObj.type === "comment" &&
childNodeObj.closing
) {
doNothing = false;
continue;
}
// if a child node is opening comment node, activate doNothing
// until closing counterpart is found
if (
!doNothing &&
childNodeObj.type === "comment" &&
!childNodeObj.closing
) {
doNothing = true;
}
if (
!doNothing &&
["text", "esp"].includes(childNodeObj.type) &&
childNodeObj.value.trim()
) {
console.log(
`349 ██ ${`\u001b[${33}m${`childNodeObj`}\u001b[${39}m`} = ${JSON.stringify(
childNodeObj,
null,
4
)}`
);
console.log(" ");
console.log(
`358 ${
childNodeObj.value.trim()
? `${`\u001b[${32}m${`this one needs wrapping`}\u001b[${39}m`}`
: `${`\u001b[${31}m${`this one does not need wrapping`}\u001b[${39}m`}`
}`
);
if (childNodeObj.value.trim()) {
// There will always be whitespace in nicely formatted tags,
// so ignore text tokens which have values that trim to zero length.
console.log(
`369 ${`\u001b[${33}m${`i`}\u001b[${39}m`} = ${JSON.stringify(
i,
null,
4
)}`
);
if (!i) {
console.log(`377 it's the first element, so TR is behind`);
ranges.push(
childNodeObj.start,
childNodeObj.end,
`\n <td${
colspanVal > 1 ? ` colspan="${colspanVal}"` : ""
}${opts.alwaysCenter || centered ? ` align="center"` : ""}${
opts.cssStylesContent
? ` style="${opts.cssStylesContent}"`
: ""
}>\n ${childNodeObj.value.trim()}\n </td>\n</tr>\n<tr>\n`
);
} else if (i && len > 1 && i === len - 1) {
console.log(`390 it's the last element, closing TR is next`);
ranges.push(
childNodeObj.start,
childNodeObj.end,
`\n</tr>\n<tr>\n <td${
colspanVal > 1 ? ` colspan="${colspanVal}"` : ""
}${opts.alwaysCenter || centered ? ` align="center"` : ""}${
opts.cssStylesContent
? ` style="${opts.cssStylesContent}"`
: ""
}>\n ${childNodeObj.value.trim()}\n </td>\n`
);
} else {
console.log(`403 the previous tag was TD`);
ranges.push(
childNodeObj.start,
childNodeObj.end,
`\n</tr>\n<tr>\n <td${
colspanVal > 1 ? ` colspan="${colspanVal}"` : ""
}${opts.alwaysCenter || centered ? ` align="center"` : ""}${
opts.cssStylesContent
? ` style="${opts.cssStylesContent}"`
: ""
}>\n ${childNodeObj.value.trim()}\n </td>\n</tr>\n<tr>\n`
);
}
}
}
}
});
console.log(
`422 ---------------------------- ${`\u001b[${32}m${`DONE`}\u001b[${39}m`} ----------------------------`
);
}
});
console.log(
`428 after traversal, ${`\u001b[${33}m${`knownCommentTokenPaths`}\u001b[${39}m`} = ${JSON.stringify(
knownCommentTokenPaths,
null,
4
)}`
);
console.log(" ");
console.log(`436 ${`\u001b[${32}m${`FINAL RETURN`}\u001b[${39}m`}`);
if (ranges.current()) {
const result = rApply(str, ranges.current());
ranges.wipe();
console.log(
`442 ${`\u001b[${32}m${`RETURN`}\u001b[${39}m`} ${`\u001b[${33}m${`result`}\u001b[${39}m`} = ${result}`
);
return { result };
}
return { result: str };
}
export { patcher, defaults, version }; | the_stack |
import path from 'path';
import fs from 'fs-extra';
// package program
import packageJson from './package.json';
// plugins
import shlp from 'sei-helper';
import m3u8 from 'm3u8-parsed';
import streamdl from 'hls-download';
// custom modules
import * as fontsData from './modules/module.fontsData';
import * as langsData from './modules/module.langsData';
import * as yamlCfg from './modules/module.cfg-loader';
import * as yargs from './modules/module.app-args';
import Merger, { Font, MergerInput, SubtitleInput } from './modules/module.merger';
export type sxItem = {
language: langsData.LanguageItem,
path: string,
file: string
title: string,
fonts: Font[]
}
// args
// load req
import { domain, api } from './modules/module.api-urls';
import * as reqModule from './modules/module.req';
import { CrunchySearch } from './@types/crunchySearch';
import { CrunchyEpisodeList, Item } from './@types/crunchyEpisodeList';
import { CrunchyDownloadOptions, CrunchyEpMeta, CrunchyMuxOptions, CurnchyMultiDownload, DownloadedMedia, ParseItem, SeriesSearch, SeriesSearchItem } from './@types/crunchyTypes';
import { ObjectInfo } from './@types/objectInfo';
import parseFileName, { Variable } from './modules/module.filename';
import { PlaybackData } from './@types/playbackData';
import { downloaded } from './modules/module.downloadArchive';
import parseSelect from './modules/module.parseSelect';
import { AvailableFilenameVars, getDefault } from './modules/module.args';
import { AuthData, AuthResponse, Episode, ResponseBase, SearchData, SearchResponse, SearchResponseItem } from './@types/messageHandler';
import { ServiceClass } from './@types/serviceClassInterface';
export default class Crunchy implements ServiceClass {
public cfg: yamlCfg.ConfigObject;
private token: Record<string, any>;
private req: reqModule.Req;
private cmsToken: {
cms?: Record<string, string>
} = {};
constructor(private debug = false) {
this.cfg = yamlCfg.loadCfg();
this.token = yamlCfg.loadCRToken();
this.req = new reqModule.Req(domain, false, false);
}
public checkToken(): boolean {
return Object.keys(this.cmsToken.cms ?? {}).length > 0;
}
public async cli() {
console.log(`\n=== Multi Downloader NX ${packageJson.version} ===\n`);
const argv = yargs.appArgv(this.cfg.cli);
// load binaries
this.cfg.bin = await yamlCfg.loadBinCfg();
if (argv.allDubs) {
argv.dubLang = langsData.dubLanguageCodes;
}
// select mode
if (argv.silentAuth && !argv.auth) {
await this.doAuth({
username: argv.username ?? await shlp.question('[Q] LOGIN/EMAIL'),
password: argv.password ?? await shlp.question('[Q] PASSWORD ')
});
}
if(argv.dlFonts){
await this.getFonts();
}
else if(argv.auth){
await this.doAuth({
username: argv.username ?? await shlp.question('[Q] LOGIN/EMAIL'),
password: argv.password ?? await shlp.question('[Q] PASSWORD ')
});
}
else if(argv.cmsindex){
await this.refreshToken();
await this.getCmsData();
}
else if(argv.new){
await this.refreshToken();
await this.getNewlyAdded();
}
else if(argv.search && argv.search.length > 2){
await this.refreshToken();
await this.doSearch({ ...argv, search: argv.search as string });
}
else if(argv.series && argv.series.match(/^[0-9A-Z]{9}$/)){
await this.refreshToken();
await this.logSeriesById(argv.series as string);
const selected = await this.downloadFromSeriesID(argv.series, { ...argv });
if (selected.isOk) {
for (const select of selected.value) {
if (!(await this.downloadEpisode(select, {...argv, skipsubs: false }))) {
console.log(`[ERROR] Unable to download selected episode ${select.episodeNumber}`);
return false;
}
}
}
return true;
}
else if(argv['movie-listing'] && argv['movie-listing'].match(/^[0-9A-Z]{9}$/)){
await this.refreshToken();
await this.logMovieListingById(argv['movie-listing'] as string);
}
else if(argv.s && argv.s.match(/^[0-9A-Z]{9}$/)){
await this.refreshToken();
if (argv.dubLang.length > 1) {
console.log('[INFO] One show can only be downloaded with one dub. Use --srz instead.');
}
argv.dubLang = [argv.dubLang[0]];
const selected = await this.getSeasonById(argv.s, argv.numbers, argv.e, argv.but, argv.all);
if (selected.isOk) {
for (const select of selected.value) {
if (!(await this.downloadEpisode(select, {...argv, skipsubs: false }))) {
console.log(`[ERROR] Unable to download selected episode ${select.episodeNumber}`);
return false;
}
}
}
return true;
}
else if(argv.e){
await this.refreshToken();
const selected = await this.getObjectById(argv.e, false);
for (const select of selected as Partial<CrunchyEpMeta>[]) {
if (!(await this.downloadEpisode(select as CrunchyEpMeta, {...argv, skipsubs: false }))) {
console.log(`[ERROR] Unable to download selected episode ${select.episodeNumber}`);
return false;
}
}
return true;
}
else{
console.log('[INFO] No option selected or invalid value entered. Try --help.');
}
}
public async getFonts() {
console.log('[INFO] Downloading fonts...');
const fonts = Object.values(fontsData.fontFamilies).reduce((pre, curr) => pre.concat(curr));
for(const f of fonts) {
const fontLoc = path.join(this.cfg.dir.fonts, f);
if(fs.existsSync(fontLoc) && fs.statSync(fontLoc).size != 0){
console.log(`[INFO] ${f} already downloaded!`);
}
else{
const fontFolder = path.dirname(fontLoc);
if(fs.existsSync(fontLoc) && fs.statSync(fontLoc).size == 0){
fs.unlinkSync(fontLoc);
}
try{
fs.ensureDirSync(fontFolder);
}
catch(e){
console.log();
}
const fontUrl = fontsData.root + f;
const getFont = await this.req.getData<Buffer>(fontUrl, { binary: true });
if(getFont.ok && getFont.res){
fs.writeFileSync(fontLoc, getFont.res.body);
console.log(`[INFO] Downloaded: ${f}`);
}
else{
console.log(`[WARN] Failed to download: ${f}`);
}
}
}
console.log('[INFO] All required fonts downloaded!');
}
public async doAuth(data: AuthData): Promise<AuthResponse> {
const authData = new URLSearchParams({
'username': data.username,
'password': data.password,
'grant_type': 'password',
'scope': 'offline_access'
}).toString();
const authReqOpts: reqModule.Params = {
method: 'POST',
headers: api.beta_authHeaderMob,
body: authData
};
const authReq = await this.req.getData(api.beta_auth, authReqOpts);
if(!authReq.ok || !authReq.res){
console.log('[ERROR] Authentication failed!');
return { isOk: false, reason: new Error('Authentication failed') };
}
this.token = JSON.parse(authReq.res.body);
this.token.expires = new Date(Date.now() + this.token.expires_in);
yamlCfg.saveCRToken(this.token);
await this.getProfile();
console.log('[INFO] Your Country: %s', this.token.country);
return { isOk: true, value: undefined };
}
public async doAnonymousAuth(){
const authData = new URLSearchParams({
'grant_type': 'client_id',
'scope': 'offline_access',
}).toString();
const authReqOpts: reqModule.Params = {
method: 'POST',
headers: api.beta_authHeaderMob,
body: authData
};
const authReq = await this.req.getData(api.beta_auth, authReqOpts);
if(!authReq.ok || !authReq.res){
console.log('[ERROR] Authentication failed!');
return;
}
this.token = JSON.parse(authReq.res.body);
this.token.expires = new Date(Date.now() + this.token.expires_in);
yamlCfg.saveCRToken(this.token);
}
public async getProfile() : Promise<boolean> {
if(!this.token.access_token){
console.log('[ERROR] No access token!');
return false;
}
const profileReqOptions = {
headers: {
Authorization: `Bearer ${this.token.access_token}`,
},
useProxy: true
};
const profileReq = await this.req.getData(api.beta_profile, profileReqOptions);
if(!profileReq.ok || !profileReq.res){
console.log('[ERROR] Get profile failed!');
return false;
}
const profile = JSON.parse(profileReq.res.body);
console.log('[INFO] USER: %s (%s)', profile.username, profile.email);
return true;
}
public async refreshToken( ifNeeded = false ){
if(!this.token.access_token && !this.token.refresh_token || this.token.access_token && !this.token.refresh_token){
await this.doAnonymousAuth();
}
else{
if (ifNeeded)
return;
if(Date.now() > new Date(this.token.expires).getTime()){
//console.log('[WARN] The token has expired compleatly. I will try to refresh the token anyway, but you might have to reauth.');
}
const authData = new URLSearchParams({
'refresh_token': this.token.refresh_token,
'grant_type': 'refresh_token',
'scope': 'offline_access'
}).toString();
const authReqOpts: reqModule.Params = {
method: 'POST',
headers: api.beta_authHeaderMob,
body: authData
};
const authReq = await this.req.getData(api.beta_auth, authReqOpts);
if(!authReq.ok || !authReq.res){
console.log('[ERROR] Authentication failed!');
return;
}
this.token = JSON.parse(authReq.res.body);
this.token.expires = new Date(Date.now() + this.token.expires_in);
yamlCfg.saveCRToken(this.token);
}
if(this.token.refresh_token){
await this.getProfile();
}
else{
console.log('[INFO] USER: Anonymous');
}
await this.getCMStoken();
}
public async getCMStoken(){
if(!this.token.access_token){
console.log('[ERROR] No access token!');
return;
}
const cmsTokenReqOpts = {
headers: {
Authorization: `Bearer ${this.token.access_token}`,
},
useProxy: true
};
const cmsTokenReq = await this.req.getData(api.beta_cmsToken, cmsTokenReqOpts);
if(!cmsTokenReq.ok || !cmsTokenReq.res){
console.log('[ERROR] Authentication CMS token failed!');
return;
}
this.cmsToken = JSON.parse(cmsTokenReq.res.body);
console.log('[INFO] Your Country: %s\n', this.cmsToken.cms?.bucket.split('/')[1]);
}
public async getCmsData(){
// check token
if(!this.cmsToken.cms){
console.log('[ERROR] Authentication required!');
return;
}
// opts
const indexReqOpts = [
api.beta_cms,
this.cmsToken.cms.bucket,
'/index?',
new URLSearchParams({
'Policy': this.cmsToken.cms.policy,
'Signature': this.cmsToken.cms.signature,
'Key-Pair-Id': this.cmsToken.cms.key_pair_id,
}),
].join('');
const indexReq = await this.req.getData(indexReqOpts);
if(!indexReq.ok || ! indexReq.res){
console.log('[ERROR] Get CMS index FAILED!');
return;
}
console.log(JSON.parse(indexReq.res.body));
}
public async doSearch(data: SearchData): Promise<SearchResponse>{
if(!this.token.access_token){
console.log('[ERROR] Authentication required!');
return { isOk: false, reason: new Error('Not authenticated') };
}
const searchReqOpts = {
headers: {
Authorization: `Bearer ${this.token.access_token}`,
},
useProxy: true
};
const searchParams = new URLSearchParams({
q: data.search,
n: '5',
start: data.page ? `${(data.page-1)*5}` : '0',
type: data['search-type'] ?? getDefault('search-type', this.cfg.cli),
locale: data['search-locale'] ?? getDefault('search-locale', this.cfg.cli),
}).toString();
const searchReq = await this.req.getData(`${api.beta_search}?${searchParams}`, searchReqOpts);
if(!searchReq.ok || ! searchReq.res){
console.log('[ERROR] Search FAILED!');
return { isOk: false, reason: new Error('Search failed. No more information provided') };
}
const searchResults = JSON.parse(searchReq.res.body) as CrunchySearch;
if(searchResults.total < 1){
console.log('[INFO] Nothing Found!');
return { isOk: true, value: [] };
}
const searchTypesInfo = {
'top_results': 'Top results',
'series': 'Found series',
'movie_listing': 'Found movie lists',
'episode': 'Found episodes'
};
for(const search_item of searchResults.items){
console.log('[INFO] %s:', searchTypesInfo[search_item.type as keyof typeof searchTypesInfo]);
// calculate pages
const itemPad = parseInt(new URL(search_item.__href__, domain.api_beta).searchParams.get('start') || '');
const pageCur = itemPad > 0 ? Math.ceil(itemPad/5) + 1 : 1;
const pageMax = Math.ceil(search_item.total/5);
// pages per category
if(search_item.total < 1){
console.log(' [INFO] Nothing Found...');
}
if(search_item.total > 0){
if(pageCur > pageMax){
console.log(' [INFO] Last page is %s...', pageMax);
continue;
}
for(const item of search_item.items){
await this.logObject(item);
}
console.log(` [INFO] Total results: ${search_item.total} (Page: ${pageCur}/${pageMax})`);
}
}
const toSend = searchResults.items.filter(a => a.type === 'series' || a.type === 'movie_listing');
return { isOk: true, value: toSend.map(a => {
return a.items.map((a): SearchResponseItem => {
const images = (a.images.poster_tall ?? [[ { source: '/notFound.png' } ]])[0];
return {
id: a.id,
image: images[Math.floor(images.length / 2)].source,
name: a.title,
rating: -1,
desc: a.description
};
});
}).reduce((pre, cur) => pre.concat(cur))};
}
public async logObject(item: ParseItem, pad?: number, getSeries?: boolean, getMovieListing?: boolean){
if(this.debug){
console.log(item);
}
pad = pad ?? 2;
getSeries = getSeries === undefined ? true : getSeries;
getMovieListing = getMovieListing === undefined ? true : getMovieListing;
item.isSelected = item.isSelected === undefined ? false : item.isSelected;
if(!item.type) {
item.type = item.__class__;
}
const oTypes = {
'series': 'Z', // SRZ
'season': 'S', // VOL
'episode': 'E', // EPI
'movie_listing': 'F', // FLM
'movie': 'M', // MED
};
// check title
item.title = item.title != '' ? item.title : 'NO_TITLE';
// static data
const oMetadata = [],
oBooleans = [],
tMetadata = item.type + '_metadata',
iMetadata = (Object.prototype.hasOwnProperty.call(item, tMetadata) ? item[tMetadata as keyof ParseItem] : item) as Record<string, any>,
iTitle = [ item.title ];
// set object booleans
if(iMetadata.duration_ms){
oBooleans.push(shlp.formatTime(iMetadata.duration_ms/1000));
}
if(iMetadata.is_simulcast){
oBooleans.push('SIMULCAST');
}
if(iMetadata.is_mature){
oBooleans.push('MATURE');
}
if(iMetadata.is_subbed){
oBooleans.push('SUB');
}
if(iMetadata.is_dubbed){
oBooleans.push('DUB');
}
if(item.playback && item.type != 'movie_listing'){
oBooleans.push('STREAM');
}
// set object metadata
if(iMetadata.season_count){
oMetadata.push(`Seasons: ${iMetadata.season_count}`);
}
if(iMetadata.episode_count){
oMetadata.push(`EPs: ${iMetadata.episode_count}`);
}
if(item.season_number && !iMetadata.hide_season_title && !iMetadata.hide_season_number){
oMetadata.push(`Season: ${item.season_number}`);
}
if(item.type == 'episode'){
if(iMetadata.episode){
iTitle.unshift(iMetadata.episode);
}
if(!iMetadata.hide_season_title && iMetadata.season_title){
iTitle.unshift(iMetadata.season_title);
}
}
if(item.is_premium_only){
iTitle[0] = `☆ ${iTitle[0]}`;
}
// display metadata
if(item.hide_metadata){
iMetadata.hide_metadata = item.hide_metadata;
}
const showObjectMetadata = oMetadata.length > 0 && !iMetadata.hide_metadata ? true : false;
const showObjectBooleans = oBooleans.length > 0 && !iMetadata.hide_metadata ? true : false;
// make obj ids
const objects_ids = [];
objects_ids.push(oTypes[item.type as keyof typeof oTypes] + ':' + item.id);
if(item.seq_id){
objects_ids.unshift(item.seq_id);
}
if(item.f_num){
objects_ids.unshift(item.f_num);
}
if(item.s_num){
objects_ids.unshift(item.s_num);
}
if(item.external_id){
objects_ids.push(item.external_id);
}
if(item.ep_num){
objects_ids.push(item.ep_num);
}
// show entry
console.log(
'%s%s[%s] %s%s%s',
''.padStart(item.isSelected ? pad-1 : pad, ' '),
item.isSelected ? '✓' : '',
objects_ids.join('|'),
iTitle.join(' - '),
showObjectMetadata ? ` (${oMetadata.join(', ')})` : '',
showObjectBooleans ? ` [${oBooleans.join(', ')}]` : '',
);
if(item.last_public){
console.log(''.padStart(pad+1, ' '), '- Last updated:', item.last_public);
}
if(item.subtitle_locales){
iMetadata.subtitle_locales = item.subtitle_locales;
}
if(iMetadata.subtitle_locales && iMetadata.subtitle_locales.length > 0){
console.log(
'%s- Subtitles: %s',
''.padStart(pad + 2, ' '),
langsData.parseSubtitlesArray(iMetadata.subtitle_locales)
);
}
if(item.availability_notes){
console.log(
'%s- Availability notes: %s',
''.padStart(pad + 2, ' '),
item.availability_notes.replace(/\[[^\]]*\]?/gm, '')
);
}
if(item.type == 'series' && getSeries){
await this.logSeriesById(item.id, pad, true);
console.log();
}
if(item.type == 'movie_listing' && getMovieListing){
await this.logMovieListingById(item.id, pad+2);
console.log();
}
}
public async logSeriesById(id: string, pad?: number, hideSeriesTitle?: boolean){
// parse
pad = pad || 0;
hideSeriesTitle = hideSeriesTitle !== undefined ? hideSeriesTitle : false;
// check token
if(!this.cmsToken.cms){
console.log('[ERROR] Authentication required!');
return;
}
// opts
const seriesReqOpts = [
api.beta_cms,
this.cmsToken.cms.bucket,
'/series/',
id,
'?',
new URLSearchParams({
'Policy': this.cmsToken.cms.policy,
'Signature': this.cmsToken.cms.signature,
'Key-Pair-Id': this.cmsToken.cms.key_pair_id,
}),
].join('');
const seriesSeasonListReqOpts = [
api.beta_cms,
this.cmsToken.cms.bucket,
'/seasons?',
new URLSearchParams({
'series_id': id,
'Policy': this.cmsToken.cms.policy,
'Signature': this.cmsToken.cms.signature,
'Key-Pair-Id': this.cmsToken.cms.key_pair_id,
}),
].join('');
// reqs
if(!hideSeriesTitle){
const seriesReq = await this.req.getData(seriesReqOpts);
if(!seriesReq.ok || !seriesReq.res){
console.log('[ERROR] Series Request FAILED!');
return;
}
const seriesData = JSON.parse(seriesReq.res.body);
await this.logObject(seriesData, pad, false);
}
// seasons list
const seriesSeasonListReq = await this.req.getData(seriesSeasonListReqOpts);
if(!seriesSeasonListReq.ok || !seriesSeasonListReq.res){
console.log('[ERROR] Series Request FAILED!');
return;
}
// parse data
const seasonsList = JSON.parse(seriesSeasonListReq.res.body) as SeriesSearch;
if(seasonsList.total < 1){
console.log('[INFO] Series is empty!');
return;
}
for(const item of seasonsList.items){
await this.logObject(item, pad+2);
}
}
public async logMovieListingById(id: string, pad?: number){
pad = pad || 2;
if(!this.cmsToken.cms){
console.log('[ERROR] Authentication required!');
return;
}
const movieListingReqOpts = [
api.beta_cms,
this.cmsToken.cms.bucket,
'/movies?',
new URLSearchParams({
'movie_listing_id': id,
'Policy': this.cmsToken.cms.policy,
'Signature': this.cmsToken.cms.signature,
'Key-Pair-Id': this.cmsToken.cms.key_pair_id,
}),
].join('');
const movieListingReq = await this.req.getData(movieListingReqOpts);
if(!movieListingReq.ok || !movieListingReq.res){
console.log('[ERROR] Movie Listing Request FAILED!');
return;
}
const movieListing = JSON.parse(movieListingReq.res.body);
if(movieListing.total < 1){
console.log('[INFO] Movie Listing is empty!');
return;
}
for(const item of movieListing.items){
this.logObject(item, pad);
}
}
public async getNewlyAdded(page?: number){
if(!this.token.access_token){
console.log('[ERROR] Authentication required!');
return;
}
const newlyAddedReqOpts = {
headers: {
Authorization: `Bearer ${this.token.access_token}`,
},
useProxy: true
};
const newlyAddedParams = new URLSearchParams({
sort_by: 'newly_added',
n: '25',
start: (page ? (page-1)*25 : 0).toString(),
}).toString();
const newlyAddedReq = await this.req.getData(`${api.beta_browse}?${newlyAddedParams}`, newlyAddedReqOpts);
if(!newlyAddedReq.ok || !newlyAddedReq.res){
console.log('[ERROR] Get newly added FAILED!');
return;
}
const newlyAddedResults = JSON.parse(newlyAddedReq.res.body);
console.log('[INFO] Newly added:');
for(const i of newlyAddedResults.items){
await this.logObject(i, 2);
}
// calculate pages
const itemPad = parseInt(new URL(newlyAddedResults.__href__, domain.api_beta).searchParams.get('start') as string);
const pageCur = itemPad > 0 ? Math.ceil(itemPad/5) + 1 : 1;
const pageMax = Math.ceil(newlyAddedResults.total/5);
console.log(` [INFO] Total results: ${newlyAddedResults.total} (Page: ${pageCur}/${pageMax})`);
}
public async getSeasonById(id: string, numbers: number, e: string|undefined, but: boolean, all: boolean) : Promise<ResponseBase<CrunchyEpMeta[]>> {
if(!this.cmsToken.cms){
console.log('[ERROR] Authentication required!');
return { isOk: false, reason: new Error('Authentication required') };
}
const showInfoReqOpts = [
api.beta_cms,
this.cmsToken.cms.bucket,
'/seasons/',
id,
'?',
new URLSearchParams({
'Policy': this.cmsToken.cms.policy,
'Signature': this.cmsToken.cms.signature,
'Key-Pair-Id': this.cmsToken.cms.key_pair_id,
}),
].join('');
const showInfoReq = await this.req.getData(showInfoReqOpts);
if(!showInfoReq.ok || !showInfoReq.res){
console.log('[ERROR] Show Request FAILED!');
return { isOk: false, reason: new Error('Show request failed. No more information provided.') };
}
const showInfo = JSON.parse(showInfoReq.res.body);
this.logObject(showInfo, 0);
const reqEpsListOpts = [
api.beta_cms,
this.cmsToken.cms.bucket,
'/episodes?',
new URLSearchParams({
'season_id': id,
'Policy': this.cmsToken.cms.policy,
'Signature': this.cmsToken.cms.signature,
'Key-Pair-Id': this.cmsToken.cms.key_pair_id,
}),
].join('');
const reqEpsList = await this.req.getData(reqEpsListOpts);
if(!reqEpsList.ok || !reqEpsList.res){
console.log('[ERROR] Episode List Request FAILED!');
return { isOk: false, reason: new Error('Episode List request failed. No more information provided.') };
}
const episodeList = JSON.parse(reqEpsList.res.body) as CrunchyEpisodeList;
const epNumList: {
ep: number[],
sp: number
} = { ep: [], sp: 0 };
const epNumLen = numbers;
if(episodeList.total < 1){
console.log(' [INFO] Season is empty!');
return { isOk: true, value: [] };
}
const doEpsFilter = parseSelect(e as string);
const selectedMedia: CrunchyEpMeta[] = [];
episodeList.items.forEach((item) => {
item.hide_season_title = true;
if(item.season_title == '' && item.series_title != ''){
item.season_title = item.series_title;
item.hide_season_title = false;
item.hide_season_number = true;
}
if(item.season_title == '' && item.series_title == ''){
item.season_title = 'NO_TITLE';
}
const epNum = item.episode;
let isSpecial = false;
item.isSelected = false;
if(!epNum.match(/^\d+$/) || epNumList.ep.indexOf(parseInt(epNum, 10)) > -1){
isSpecial = true;
epNumList.sp++;
}
else{
epNumList.ep.push(parseInt(epNum, 10));
}
const selEpId = (
isSpecial
? 'S' + epNumList.sp.toString().padStart(epNumLen, '0')
: '' + parseInt(epNum, 10).toString().padStart(epNumLen, '0')
);
// set data
const images = (item.images.thumbnail ?? [[ { source: '/notFound.png' } ]])[0];
const epMeta: CrunchyEpMeta = {
data: [
{
mediaId: item.id
}
],
seasonTitle: item.season_title,
episodeNumber: item.episode,
episodeTitle: item.title,
seasonID: item.season_id,
season: item.season_number,
showID: id,
e: selEpId,
image: images[Math.floor(images.length / 2)].source
};
if(item.playback){
epMeta.data[0].playback = item.playback;
}
// find episode numbers
if((but && item.playback && !doEpsFilter.isSelected([selEpId, item.id])) || (all && item.playback) || (!but && doEpsFilter.isSelected([selEpId, item.id]) && !item.isSelected && item.playback)){
selectedMedia.push(epMeta);
item.isSelected = true;
}
// show ep
item.seq_id = selEpId;
this.logObject(item);
});
// display
if(selectedMedia.length < 1){
console.log('\n[INFO] Episodes not selected!\n');
}
console.log();
return { isOk: true, value: selectedMedia };
}
public async downloadEpisode(data: CrunchyEpMeta, options: CrunchyDownloadOptions): Promise<boolean> {
const res = await this.downloadMediaList(data, options);
if (res === undefined || res.error) {
return false;
} else {
await this.muxStreams(res.data, { ...options, output: res.fileName });
downloaded({
service: 'crunchy',
type: 's'
}, data.showID, [data.episodeNumber]);
}
return true;
}
public async getObjectById(e?: string, earlyReturn?: boolean): Promise<ObjectInfo|Partial<CrunchyEpMeta>[]|undefined> {
if(!this.cmsToken.cms){
console.log('[ERROR] Authentication required!');
return;
}
const doEpsFilter = parseSelect(e as string);
if(doEpsFilter.values.length < 1){
console.log('\n[INFO] Objects not selected!\n');
return;
}
// node crunchy-beta -e G6497Z43Y,GRZXCMN1W,G62PEZ2E6,G25FVGDEK,GZ7UVPVX5
console.log('[INFO] Requested object ID: %s', doEpsFilter.values.join(', '));
const objectReqOpts = [
api.beta_cms,
this.cmsToken.cms.bucket,
'/objects/',
doEpsFilter.values.join(','),
'?',
new URLSearchParams({
'Policy': this.cmsToken.cms.policy,
'Signature': this.cmsToken.cms.signature,
'Key-Pair-Id': this.cmsToken.cms.key_pair_id,
}),
].join('');
const objectReq = await this.req.getData(objectReqOpts);
if(!objectReq.ok || !objectReq.res){
console.log('[ERROR] Objects Request FAILED!');
if(objectReq.error && objectReq.error.res && objectReq.error.res.body){
const objectInfo = JSON.parse(objectReq.error.res.body as string);
console.log('[INFO] Body:', JSON.stringify(objectInfo, null, '\t'));
objectInfo.error = true;
return objectInfo;
}
return;
}
const objectInfo = JSON.parse(objectReq.res.body) as ObjectInfo;
if(earlyReturn){
return objectInfo;
}
const selectedMedia = [];
for(const item of objectInfo.items){
if(item.type != 'episode' && item.type != 'movie'){
await this.logObject(item, 2, true, false);
continue;
}
const epMeta: Partial<CrunchyEpMeta> = {};
switch (item.type) {
case 'episode':
item.s_num = 'S:' + item.episode_metadata.season_id;
epMeta.data = [
{
mediaId: 'E:'+ item.id
}
];
epMeta.seasonTitle = item.episode_metadata.season_title;
epMeta.episodeNumber = item.episode_metadata.episode;
epMeta.episodeTitle = item.title;
break;
case 'movie':
item.f_num = 'F:' + item.movie_metadata?.movie_listing_id;
epMeta.data = [
{
mediaId: 'M:'+ item.id
}
];
epMeta.seasonTitle = item.movie_metadata?.movie_listing_title;
epMeta.episodeNumber = 'Movie';
epMeta.episodeTitle = item.title;
break;
}
if(item.playback){
epMeta.data[0].playback = item.playback;
selectedMedia.push(epMeta);
item.isSelected = true;
}
await this.logObject(item, 2);
}
console.log();
return selectedMedia;
}
public async downloadMediaList(medias: CrunchyEpMeta, options: CrunchyDownloadOptions) : Promise<{
data: DownloadedMedia[],
fileName: string,
error: boolean
} | undefined> {
let mediaName = '...';
let fileName;
const variables: Variable[] = [];
if(medias.seasonTitle && medias.episodeNumber && medias.episodeTitle){
mediaName = `${medias.seasonTitle} - ${medias.episodeNumber} - ${medias.episodeTitle}`;
}
const files: DownloadedMedia[] = [];
if(medias.data.every(a => !a.playback)){
console.log('[WARN] Video not available!');
return undefined;
}
let dlFailed = false;
for (const mMeta of medias.data) {
console.log(`[INFO] Requesting: [${mMeta.mediaId}] ${mediaName}`);
const playbackReq = await this.req.getData(mMeta.playback as string);
if(!playbackReq.ok || !playbackReq.res){
console.log('[ERROR] Request Stream URLs FAILED!');
return undefined;
}
const pbData = JSON.parse(playbackReq.res.body) as PlaybackData;
variables.push(...([
['title', medias.episodeTitle],
['episode', isNaN(parseInt(medias.episodeNumber)) ? medias.episodeNumber : parseInt(medias.episodeNumber)],
['service', 'CR'],
['showTitle', medias.seasonTitle],
['season', medias.season]
] as [AvailableFilenameVars, string|number][]).map((a): Variable => {
return {
name: a[0],
replaceWith: a[1],
type: typeof a[1]
} as Variable;
}));
let streams = [];
let hsLangs: string[] = [];
const pbStreams = pbData.streams;
for(const s of Object.keys(pbStreams)){
if(s.match(/hls/) && !s.match(/drm/) && !s.match(/trailer/)){
const pb = Object.values(pbStreams[s]).map(v => {
v.hardsub_lang = v.hardsub_locale
? langsData.fixAndFindCrLC(v.hardsub_locale).locale
: v.hardsub_locale;
if(v.hardsub_lang && hsLangs.indexOf(v.hardsub_lang) < 0){
hsLangs.push(v.hardsub_lang);
}
return {
...v,
...{ format: s }
};
});
streams.push(...pb);
}
}
if(streams.length < 1){
console.log('[WARN] No full streams found!');
return undefined;
}
const audDub = langsData.findLang(langsData.fixLanguageTag(pbData.audio_locale) || '').code;
hsLangs = langsData.sortTags(hsLangs);
streams = streams.map((s) => {
s.audio_lang = audDub;
s.hardsub_lang = s.hardsub_lang ? s.hardsub_lang : '-';
s.type = `${s.format}/${s.audio_lang}/${s.hardsub_lang}`;
return s;
});
if(options.hslang != 'none'){
if(hsLangs.indexOf(options.hslang) > -1){
console.log('[INFO] Selecting stream with %s hardsubs', langsData.locale2language(options.hslang).language);
streams = streams.filter((s) => {
if(s.hardsub_lang == '-'){
return false;
}
return s.hardsub_lang == options.hslang ? true : false;
});
}
else{
console.log('[WARN] Selected stream with %s hardsubs not available', langsData.locale2language(options.hslang).language);
if(hsLangs.length > 0){
console.log('[WARN] Try other hardsubs stream:', hsLangs.join(', '));
}
dlFailed = true;
}
}
else{
streams = streams.filter((s) => {
if(s.hardsub_lang != '-'){
return false;
}
return true;
});
if(streams.length < 1){
console.log('[WARN] Raw streams not available!');
if(hsLangs.length > 0){
console.log('[WARN] Try hardsubs stream:', hsLangs.join(', '));
}
dlFailed = true;
}
console.log('[INFO] Selecting raw stream');
}
let curStream:
undefined|typeof streams[0]
= undefined;
if(!dlFailed){
options.kstream = typeof options.kstream == 'number' ? options.kstream : 1;
options.kstream = options.kstream > streams.length ? 1 : options.kstream;
streams.forEach((s, i) => {
const isSelected = options.kstream == i + 1 ? '✓' : ' ';
console.log('[INFO] Full stream found! (%s%s: %s )', isSelected, i + 1, s.type);
});
console.log('[INFO] Downloading video...');
curStream = streams[options.kstream-1];
console.log('[INFO] Playlists URL: %s (%s)', curStream.url, curStream.type);
}
if(!options.novids && !dlFailed && curStream !== undefined){
const streamPlaylistsReq = await this.req.getData(curStream.url);
if(!streamPlaylistsReq.ok || !streamPlaylistsReq.res){
console.log('[ERROR] CAN\'T FETCH VIDEO PLAYLISTS!');
dlFailed = true;
}
else{
const streamPlaylists = m3u8(streamPlaylistsReq.res.body);
const plServerList: string[] = [],
plStreams: Record<string, Record<string, string>> = {},
plQuality: {
str: string,
dim: string,
RESOLUTION: {
width: number,
height: number
}
}[] = [];
for(const pl of streamPlaylists.playlists){
// set quality
const plResolution = pl.attributes.RESOLUTION;
const plResolutionText = `${plResolution.width}x${plResolution.height}`;
// parse uri
const plUri = new URL(pl.uri);
let plServer = plUri.hostname;
// set server list
if(plUri.searchParams.get('cdn')){
plServer += ` (${plUri.searchParams.get('cdn')})`;
}
if(!plServerList.includes(plServer)){
plServerList.push(plServer);
}
// add to server
if(!Object.keys(plStreams).includes(plServer)){
plStreams[plServer] = {};
}
if(
plStreams[plServer][plResolutionText]
&& plStreams[plServer][plResolutionText] != pl.uri
&& typeof plStreams[plServer][plResolutionText] != 'undefined'
){
console.log(`[WARN] Non duplicate url for ${plServer} detected, please report to developer!`);
}
else{
plStreams[plServer][plResolutionText] = pl.uri;
}
// set plQualityStr
const plBandwidth = Math.round(pl.attributes.BANDWIDTH/1024);
const qualityStrAdd = `${plResolutionText} (${plBandwidth}KiB/s)`;
const qualityStrRegx = new RegExp(qualityStrAdd.replace(/(:|\(|\)|\/)/g, '\\$1'), 'm');
const qualityStrMatch = !plQuality.map(a => a.str).join('\r\n').match(qualityStrRegx);
if(qualityStrMatch){
plQuality.push({
str: qualityStrAdd,
dim: plResolutionText,
RESOLUTION: plResolution
});
}
}
options.x = options.x > plServerList.length ? 1 : options.x;
const plSelectedServer = plServerList[options.x - 1];
const plSelectedList = plStreams[plSelectedServer];
plQuality.sort((a, b) => {
const aMatch = a.dim.match(/[0-9]+/) || [];
const bMatch = b.dim.match(/[0-9]+/) || [];
return parseInt(aMatch[0]) - parseInt(bMatch[0]);
});
let quality = options.q;
if (quality > plQuality.length) {
console.log(`[WARN] The requested quality of ${options.q} is greater than the maximun ${plQuality.length}.\n[WARN] Therefor the maximum will be capped at ${plQuality.length}.`);
quality = plQuality.length;
}
const selPlUrl = quality === 0 ? plSelectedList[plQuality[plQuality.length - 1].dim as string] :
plSelectedList[plQuality.map(a => a.dim)[quality - 1]] ? plSelectedList[plQuality.map(a => a.dim)[quality - 1]] : '';
console.log(`[INFO] Servers available:\n\t${plServerList.join('\n\t')}`);
console.log(`[INFO] Available qualities:\n\t${plQuality.map((a, ind) => `[${ind+1}] ${a.str}`).join('\n\t')}`);
if(selPlUrl != ''){
variables.push({
name: 'height',
type: 'number',
replaceWith: quality === 0 ? plQuality[plQuality.length - 1].RESOLUTION.height as number : plQuality[quality - 1].RESOLUTION.height
}, {
name: 'width',
type: 'number',
replaceWith: quality === 0 ? plQuality[plQuality.length - 1].RESOLUTION.width as number : plQuality[quality - 1].RESOLUTION.width
});
const lang = langsData.languages.find(a => a.code === curStream?.audio_lang);
if (!lang) {
console.log(`[ERROR] Unable to find language for code ${curStream.audio_lang}`);
return;
}
console.log(`[INFO] Selected quality: ${Object.keys(plSelectedList).find(a => plSelectedList[a] === selPlUrl)} @ ${plSelectedServer}`);
console.log('[INFO] Stream URL:', selPlUrl);
// TODO check filename
fileName = parseFileName(options.fileName, variables, options.numbers, options.override).join(path.sep);
const outFile = parseFileName(options.fileName + '.' + (mMeta.lang?.name || lang.name), variables, options.numbers, options.override).join(path.sep);
console.log(`[INFO] Output filename: ${outFile}`);
const chunkPage = await this.req.getData(selPlUrl);
if(!chunkPage.ok || !chunkPage.res){
console.log('[ERROR] CAN\'T FETCH VIDEO PLAYLIST!');
dlFailed = true;
}
else{
const chunkPlaylist = m3u8(chunkPage.res.body);
const totalParts = chunkPlaylist.segments.length;
const mathParts = Math.ceil(totalParts / options.partsize);
const mathMsg = `(${mathParts}*${options.partsize})`;
console.log('[INFO] Total parts in stream:', totalParts, mathMsg);
const tsFile = path.isAbsolute(outFile as string) ? outFile : path.join(this.cfg.dir.content, outFile);
const split = outFile.split(path.sep).slice(0, -1);
split.forEach((val, ind, arr) => {
const isAbsolut = path.isAbsolute(outFile as string);
if (!fs.existsSync(path.join(isAbsolut ? '' : this.cfg.dir.content, ...arr.slice(0, ind), val)))
fs.mkdirSync(path.join(isAbsolut ? '' : this.cfg.dir.content, ...arr.slice(0, ind), val));
});
const dlStreamByPl = await new streamdl({
output: `${tsFile}.ts`,
timeout: options.timeout,
m3u8json: chunkPlaylist,
// baseurl: chunkPlaylist.baseUrl,
threads: options.partsize,
fsRetryTime: options.fsRetryTime * 1000,
override: options.force,
callback: options.callbackMaker ? options.callbackMaker({
fileName: `${path.isAbsolute(outFile) ? outFile.slice(this.cfg.dir.content.length) : outFile}`,
image: medias.image,
parent: {
title: medias.seasonTitle
},
title: medias.episodeTitle,
language: lang
}) : undefined
}).download();
if(!dlStreamByPl.ok){
console.log(`[ERROR] DL Stats: ${JSON.stringify(dlStreamByPl.parts)}\n`);
dlFailed = true;
}
files.push({
type: 'Video',
path: `${tsFile}.ts`,
lang: lang
});
}
}
else{
console.log('[ERROR] Quality not selected!\n');
dlFailed = true;
}
}
}
else if(options.novids){
fileName = parseFileName(options.fileName, variables, options.numbers, options.override).join(path.sep);
console.log('[INFO] Downloading skipped!');
}
if(options.dlsubs.indexOf('all') > -1){
options.dlsubs = ['all'];
}
if(options.hslang != 'none'){
console.log('[WARN] Subtitles downloading disabled for hardsubs streams.');
options.skipsubs = true;
}
if(!options.skipsubs && options.dlsubs.indexOf('none') == -1){
if(pbData.subtitles && Object.values(pbData.subtitles).length > 0){
const subsData = Object.values(pbData.subtitles);
const subsDataMapped = subsData.map((s) => {
const subLang = langsData.fixAndFindCrLC(s.locale);
return {
...s,
locale: subLang,
language: subLang.locale
};
});
const subsArr = langsData.sortSubtitles<typeof subsDataMapped[0]>(subsDataMapped, 'language');
for(const subsIndex in subsArr){
const subsItem = subsArr[subsIndex];
const langItem = subsItem.locale;
const sxData: Partial<sxItem> = {};
sxData.language = langItem;
sxData.file = langsData.subsFile(fileName as string, subsIndex, langItem);
sxData.path = path.join(this.cfg.dir.content, sxData.file);
if (files.some(a => a.type === 'Subtitle' && (a.language.cr_locale == langItem.cr_locale || a.language.locale == langItem.locale)))
continue;
if(options.dlsubs.includes('all') || options.dlsubs.includes(langItem.locale)){
const subsAssReq = await this.req.getData(subsItem.url);
if(subsAssReq.ok && subsAssReq.res){
let sBody = '\ufeff' + subsAssReq.res.body;
const sBodySplit = sBody.split('\r\n');
sBodySplit.splice(2, 0, 'ScaledBorderAndShadow: yes');
sBody = sBodySplit.join('\r\n');
sxData.title = sBody.split('\r\n')[1].replace(/^Title: /, '');
sxData.title = `${langItem.language} / ${sxData.title}`;
sxData.fonts = fontsData.assFonts(sBody) as Font[];
fs.writeFileSync(sxData.path, sBody);
console.log(`[INFO] Subtitle downloaded: ${sxData.file}`);
files.push({
type: 'Subtitle',
...sxData as sxItem
});
}
else{
console.log(`[WARN] Failed to download subtitle: ${sxData.file}`);
}
}
}
}
else{
console.log('[WARN] Can\'t find urls for subtitles!');
}
}
else{
console.log('[INFO] Subtitles downloading skipped!');
}
}
return {
error: dlFailed,
data: files,
fileName: fileName ? (path.isAbsolute(fileName) ? fileName : path.join(this.cfg.dir.content, fileName)) || './unknown' : './unknown'
};
}
public async muxStreams(data: DownloadedMedia[], options: CrunchyMuxOptions) {
this.cfg.bin = await yamlCfg.loadBinCfg();
if (options.novids || data.filter(a => a.type === 'Video').length === 0)
return console.log('[INFO] Skip muxing since no vids are downloaded');
const merger = new Merger({
onlyVid: [],
skipSubMux: options.skipSubMux,
onlyAudio: [],
output: `${options.output}.${options.mp4 ? 'mp4' : 'mkv'}`,
subtitles: data.filter(a => a.type === 'Subtitle').map((a) : SubtitleInput => {
if (a.type === 'Video')
throw new Error('Never');
return {
file: a.path,
language: a.language
};
}),
simul: false,
fonts: Merger.makeFontsList(this.cfg.dir.fonts, data.filter(a => a.type === 'Subtitle') as sxItem[]),
videoAndAudio: data.filter(a => a.type === 'Video').map((a) : MergerInput => {
if (a.type === 'Subtitle')
throw new Error('Never');
return {
lang: a.lang,
path: a.path,
};
}),
videoTitle: options.videoTitle,
options: {
ffmpeg: options.ffmpegOptions,
mkvmerge: options.mkvmergeOptions
}
});
const bin = Merger.checkMerger(this.cfg.bin, options.mp4, options.forceMuxer);
// collect fonts info
// mergers
let isMuxed = false;
if (bin.MKVmerge) {
await merger.merge('mkvmerge', bin.MKVmerge);
isMuxed = true;
} else if (bin.FFmpeg) {
await merger.merge('ffmpeg', bin.FFmpeg);
isMuxed = true;
} else{
console.log('\n[INFO] Done!\n');
return;
}
if (isMuxed && !options.nocleanup)
merger.cleanUp();
}
public async listSeriesID(id: string): Promise<{ list: Episode[], data: Record<string, {
items: Item[];
langs: langsData.LanguageItem[];
}>}> {
await this.refreshToken();
const parsed = await this.parseSeriesById(id);
if (!parsed)
return { data: {}, list: [] };
const result = this.parseSeriesResult(parsed);
const episodes : Record<string, {
items: Item[],
langs: langsData.LanguageItem[]
}> = {};
for(const season of Object.keys(result) as unknown as number[]) {
for (const key of Object.keys(result[season])) {
const s = result[season][key];
(await this.getSeasonDataById(s))?.items.forEach(a => {
if (Object.prototype.hasOwnProperty.call(episodes, `S${a.season_number}E${a.episode_number || a.episode}`)) {
const item = episodes[`S${a.season_number}E${a.episode_number || a.episode}`];
item.items.push(a);
item.langs.push(langsData.languages.find(a => a.code == key) as langsData.LanguageItem);
} else {
episodes[`S${a.season_number}E${a.episode_number || a.episode}`] = {
items: [a],
langs: [langsData.languages.find(a => a.code == key) as langsData.LanguageItem]
};
}
});
}
}
const itemIndexes = {
sp: 1,
no: 1
};
for (const key of Object.keys(episodes)) {
const item = episodes[key];
const isSpecial = !item.items[0].episode.match(/^\d+$/);
episodes[`${isSpecial ? 'S' : 'E'}${itemIndexes[isSpecial ? 'sp' : 'no']}`] = item;
if (isSpecial)
itemIndexes.sp++;
else
itemIndexes.no++;
delete episodes[key];
}
for (const key of Object.keys(episodes)) {
const item = episodes[key];
console.log(`[${key}] ${
item.items.find(a => !a.season_title.match(/\(\w+ Dub\)/))?.season_title ?? item.items[0].season_title.replace(/\(\w+ Dub\)/g, '').trimEnd()
} - Season ${item.items[0].season_number} - ${item.items[0].title} [${
item.items.map((a, index) => {
return `${a.is_premium_only ? '☆ ' : ''}${item.langs[index].name}`;
}).join(', ')
}]`);
}
return { data: episodes, list: Object.entries(episodes).map(([key, value]) => {
const images = (value.items[0].images.thumbnail ?? [[ { source: '/notFound.png' } ]])[0];
const seconds = Math.floor(value.items[0].duration_ms / 1000);
return {
e: key.startsWith('E') ? key.slice(1) : key,
lang: value.langs.map(a => a.code),
name: value.items[0].title,
season: value.items[0].season_number.toString(),
seasonTitle: value.items[0].season_title.replace(/\(\w+ Dub\)/g, '').trimEnd(),
episode: value.items[0].episode_number?.toString() ?? value.items[0].episode ?? '?',
id: value.items[0].season_id,
img: images[Math.floor(images.length / 2)].source,
description: value.items[0].description,
time: `${Math.floor(seconds / 60)}:${seconds % 60}`
};
})};
}
public async downloadFromSeriesID(id: string, data: CurnchyMultiDownload) : Promise<ResponseBase<CrunchyEpMeta[]>> {
const { data: episodes } = await this.listSeriesID(id);
console.log();
console.log('-'.repeat(30));
console.log();
const selected = this.itemSelectMultiDub(episodes, data.dubLang, data.but, data.all, data.e);
for (const key of Object.keys(selected)) {
const item = selected[key];
console.log(`[S${item.season}E${item.episodeNumber}] - ${item.episodeTitle} [${
item.data.map(a => {
return `✓ ${a.lang?.name || 'Unknown Language'}`;
}).join(', ')
}]`);
}
return { isOk: true, value: Object.values(selected) };
}
public itemSelectMultiDub (eps: Record<string, {
items: Item[],
langs: langsData.LanguageItem[]
}>, dubLang: string[], but?: boolean, all?: boolean, e?: string, ) {
const doEpsFilter = parseSelect(e as string);
const ret: Record<string, CrunchyEpMeta> = {};
for (const key of Object.keys(eps)) {
const itemE = eps[key];
itemE.items.forEach((item, index) => {
if (!dubLang.includes(itemE.langs[index].code))
return;
item.hide_season_title = true;
if(item.season_title == '' && item.series_title != ''){
item.season_title = item.series_title;
item.hide_season_title = false;
item.hide_season_number = true;
}
if(item.season_title == '' && item.series_title == ''){
item.season_title = 'NO_TITLE';
}
const epNum = key.startsWith('E') ? key.slice(1) : key;
// set data
const images = (item.images.thumbnail ?? [[ { source: '/notFound.png' } ]])[0];
const epMeta: CrunchyEpMeta = {
data: [
{
mediaId: item.id
}
],
seasonTitle: itemE.items.find(a => !a.season_title.match(/\(\w+ Dub\)/))?.season_title ?? itemE.items[0].season_title.replace(/\(\w+ Dub\)/g, '').trimEnd(),
episodeNumber: item.episode,
episodeTitle: item.title,
seasonID: item.season_id,
season: item.season_number,
showID: item.series_id,
e: epNum,
image: images[Math.floor(images.length / 2)].source
};
if(item.playback){
epMeta.data[0].playback = item.playback;
}
// find episode numbers
if(item.playback && ((but && !doEpsFilter.isSelected([epNum, item.id])) || (all || (doEpsFilter.isSelected([epNum, item.id])) && !but))) {
if (Object.prototype.hasOwnProperty.call(ret, key)) {
const epMe = ret[key];
epMe.data.push({
lang: itemE.langs[index],
...epMeta.data[0]
});
} else {
epMeta.data[0].lang = itemE.langs[index];
ret[key] = {
...epMeta
};
}
}
// show ep
item.seq_id = epNum;
});
}
return ret;
}
public parseSeriesResult (seasonsList: SeriesSearch) : Record<number, Record<string, SeriesSearchItem>> {
const ret: Record<number, Record<string, SeriesSearchItem>> = {};
for (const item of seasonsList.items) {
for (const lang of langsData.languages) {
if (!Object.prototype.hasOwnProperty.call(ret, item.season_number))
ret[item.season_number] = {};
if (item.title.includes(`(${lang.name} Dub)`) || item.title.includes(`(${lang.name})`)) {
ret[item.season_number][lang.code] = item;
} else if (item.is_subbed && !item.is_dubbed && lang.code == 'jpn') {
ret[item.season_number][lang.code] = item;
} else if (item.is_dubbed && lang.code === 'eng' && !langsData.languages.some(a => item.title.includes(`(${a.name})`) || item.title.includes(`(${a.name} Dub)`))) { // Dubbed with no more infos will be treated as eng dubs
ret[item.season_number][lang.code] = item;
}
}
}
return ret;
}
public async parseSeriesById(id: string) {
if(!this.cmsToken.cms){
console.log('[ERROR] Authentication required!');
return;
}
const seriesSeasonListReqOpts = [
api.beta_cms,
this.cmsToken.cms.bucket,
'/seasons?',
new URLSearchParams({
'series_id': id,
'Policy': this.cmsToken.cms.policy,
'Signature': this.cmsToken.cms.signature,
'Key-Pair-Id': this.cmsToken.cms.key_pair_id,
}),
].join('');
// seasons list
const seriesSeasonListReq = await this.req.getData(seriesSeasonListReqOpts);
if(!seriesSeasonListReq.ok || !seriesSeasonListReq.res){
console.log('[ERROR] Series Request FAILED!');
return;
}
// parse data
const seasonsList = JSON.parse(seriesSeasonListReq.res.body) as SeriesSearch;
if(seasonsList.total < 1){
console.log('[INFO] Series is empty!');
return;
}
return seasonsList;
}
public async getSeasonDataById(item: SeriesSearchItem, log = false){
if(!this.cmsToken.cms){
console.log('[ERROR] Authentication required!');
return;
}
const showInfoReqOpts = [
api.beta_cms,
this.cmsToken.cms.bucket,
'/seasons/',
item.id,
'?',
new URLSearchParams({
'Policy': this.cmsToken.cms.policy,
'Signature': this.cmsToken.cms.signature,
'Key-Pair-Id': this.cmsToken.cms.key_pair_id,
}),
].join('');
const showInfoReq = await this.req.getData(showInfoReqOpts);
if(!showInfoReq.ok || !showInfoReq.res){
console.log('[ERROR] Show Request FAILED!');
return;
}
const showInfo = JSON.parse(showInfoReq.res.body);
if (log)
this.logObject(showInfo, 0);
const reqEpsListOpts = [
api.beta_cms,
this.cmsToken.cms.bucket,
'/episodes?',
new URLSearchParams({
'season_id': item.id as string,
'Policy': this.cmsToken.cms.policy,
'Signature': this.cmsToken.cms.signature,
'Key-Pair-Id': this.cmsToken.cms.key_pair_id,
}),
].join('');
const reqEpsList = await this.req.getData(reqEpsListOpts);
if(!reqEpsList.ok || !reqEpsList.res){
console.log('[ERROR] Episode List Request FAILED!');
return;
}
const episodeList = JSON.parse(reqEpsList.res.body) as CrunchyEpisodeList;
if(episodeList.total < 1){
console.log(' [INFO] Season is empty!');
return;
}
return episodeList;
}
} | the_stack |
import {
isNumberString,
isValidInteger,
isIPV6,
isIPV4,
isIP,
isPort,
isStringEndsWith,
isProtocolString,
isRangedSemVer,
isEncryptedPassphrase,
isHexString,
isCsv,
isString,
isBoolean,
isSInt32,
isBytes,
isUInt32,
isSInt64,
isUInt64,
} from '../src/validation';
describe('validation', () => {
describe('#isNumberString', () => {
it('should return false when number is not string', () => {
const invalidFunction = isNumberString as (input: any) => boolean;
return expect(invalidFunction(1)).toBeFalse();
});
it('should return false when string contains non number', () => {
return expect(isNumberString('12345abc68789')).toBeFalse();
});
it('should return false for empty string value', () => {
return expect(isNumberString('')).toBeFalse();
});
it('should return false for null value', () => {
return expect(isNumberString(null)).toBeFalse();
});
it('should return true when string contains only number', () => {
return expect(isNumberString('1234568789')).toBeTrue();
});
});
describe('#isValidInteger', () => {
it('should return false when string was provided', () => {
return expect(isValidInteger('1234')).toBeFalse();
});
it('should return false when float was provided', () => {
return expect(isValidInteger(123.4)).toBeFalse();
});
it('should return true when integer was provided', () => {
return expect(isValidInteger(6)).toBeTrue();
});
it('should return true when negative integer was provided', () => {
return expect(isValidInteger(-6)).toBeTrue();
});
});
describe('#isHexString', () => {
it('should return true when valid hex was provided', () => {
return expect(
isHexString('215b667a32a5cd51a94c9c2046c11fffb08c65748febec099451e3b164452bc'),
).toBeTrue();
});
it('should return false when number was provided', () => {
return expect(isHexString(123.4)).toBeFalse();
});
it('should return false when non hex string was provided', () => {
return expect(
isHexString('zzzzzzza32a5cd51a94c9c2046c11fffb08c65748febec099451e3b164452bc'),
).toBeFalse();
});
});
describe('#isEncryptedPassphrase', () => {
it('should return true when value is valid encrypted passphrase', () => {
return expect(
isEncryptedPassphrase(
'iterations=1&salt=d3e4c10d1f889d45fc1f23dd1a55a4ed&cipherText=c030aae98cb41b3cadf6cf8b71d8dc1304c709696880e09c6c5f41361666ced2ce804407ac99c05799f06ea513be9cb80bbb824db6e0e69fa252f3ce2fe654d34d4f7344fcaeafe143d3b1&iv=03414e5d5e79f22c04f20a57&tag=5025de28a5134e2cf6c4cc3a3212723b&version=1',
),
).toBeTrue();
});
it('should return false when value includes invalid query', () => {
return expect(
isEncryptedPassphrase('cipherText=abcd1234&&iterations=10000&iv=ef012345'),
).toBeFalse();
});
it('should return false when value is empty', () => {
return expect(isEncryptedPassphrase('')).toBeFalse();
});
it('should return true when 24 words bip39 Mnemonic was encrypted', () => {
return expect(
isEncryptedPassphrase(
'iterations=1000000&cipherText=d8d8bd8a883cd5a8a5b0c0a5ee7221f5fcd93bad0ab7675d156bec831f2aee8c10c683eb472188dd28e6caa1e9ed3d3f2769b9265c5a11e28428775cd0697ad023dc6f4b780f37f18ac03a2c14b51def04ec0391e7d258c0c65e3910b65812c61aebb8b098537a4240111a8c1509cffdc970b7cd0885c32811a0d5e7cd4539740fad661dd4c8a131a0438e7d17ed54e8d5127a81a663a0af127b01&iv=87a17399fe06332c2775dd75&salt=3503a17ea682784b490f22cf9d728563&tag=23be4e96c71d31eae005b29502179862&version=1',
),
).toBeTrue();
});
});
describe('#isRangedSemVer', () => {
it('should return true when it is valid ranged semver', () => {
return expect(isRangedSemVer('>=10.0')).toBeTrue();
});
it('should return false when value is not valid ranged semver', () => {
return expect(isRangedSemVer('>>10.0')).toBeFalse();
});
});
describe('#isProtocolString', () => {
it('should return true when it is protocol version', () => {
return expect(isProtocolString('10.0')).toBeTrue();
});
it('should return false when value is semver', () => {
return expect(isProtocolString('1.0.2')).toBeFalse();
});
});
describe('#isIPV4', () => {
it('should return true when the value is IPV4', () => {
return expect(isIPV4('127.0.0.0')).toBeTrue();
});
it('should return false when the value is not IPV4', () => {
return expect(isIPV4('FE80:0000:0000:0000:0202:B3FF:FE1E:8329')).toBeFalse();
});
});
describe('#isIPV6', () => {
it('should return true when the value is IPV6', () => {
return expect(isIPV6('FE80:0000:0000:0000:0202:B3FF:FE1E:8329')).toBeTrue();
});
it('should return false when the value is not IPV6', () => {
return expect(isIPV6('127.0.0.0')).toBeFalse();
});
});
describe('#isIP', () => {
it('should return true when the value is IPV6', () => {
return expect(isIP('FE80:0000:0000:0000:0202:B3FF:FE1E:8329')).toBeTrue();
});
it('should return true when the value is IPV4', () => {
return expect(isIP('127.0.0.0')).toBeTrue();
});
it('should return false when the value is not ip', () => {
return expect(isIP('0.0.0.0.0.0')).toBeFalse();
});
});
describe('#isPort', () => {
it('should return true when the value is port', () => {
return expect(isPort('3000')).toBeTrue();
});
it('should return true when the value is invalid port number', () => {
return expect(isPort('999999')).toBeFalse();
});
it('should return false when the value is not number', () => {
return expect(isPort('abc')).toBeFalse();
});
});
describe('#isStringEndsWith', () => {
it('should return true when the value ends with suffix', () => {
return expect(isStringEndsWith('sample', ['le', 'e'])).toBeTrue();
});
it('should return false when the suffix does not match', () => {
return expect(isStringEndsWith('samp', ['le', 'e'])).toBeFalse();
});
});
describe('#isCsv', () => {
it('should return true when the value is a CSV string', () => {
const csvString = '64,9,77,23,12,26,29,28,2008';
return expect(isCsv(csvString)).toBeTrue();
});
it('should return false when the value is not a CSV string', () => {
const csvString = 0 as any;
return expect(isCsv(csvString)).toBeFalse();
});
it('should return true when the value is empty string', () => {
const csvString = '';
return expect(isCsv(csvString)).toBeTrue();
});
it('should return false when the value is undefined', () => {
const csvString = undefined as any;
return expect(isCsv(csvString)).toBeFalse();
});
it('should return false when the value is an array of string', () => {
const csvString = ['64', '12'] as any;
return expect(isCsv(csvString)).toBeFalse();
});
});
describe('#isBytes', () => {
it('should return false when number was provided', () => {
return expect(isBytes(1234)).toBeFalse();
});
it('should return false when boolean was provided', () => {
return expect(isBytes(false)).toBeFalse();
});
it('should return false when bigint was provided', () => {
return expect(isBytes(BigInt(9))).toBeFalse();
});
it('should return false when string was provided', () => {
return expect(isBytes('lisk test 12345')).toBeFalse();
});
it('should return true when buffer was provided', () => {
return expect(isBytes(Buffer.from('lisk', 'utf8'))).toBeTrue();
});
});
describe('#isString', () => {
it('should return false when number was provided', () => {
return expect(isString(1234)).toBeFalse();
});
it('should return false when boolean was provided', () => {
return expect(isString(false)).toBeFalse();
});
it('should return false when bigint was provided', () => {
return expect(isString(BigInt(9))).toBeFalse();
});
it('should return false when buffer was provided', () => {
return expect(isString(Buffer.from('lisk', 'utf8'))).toBeFalse();
});
it('should return true when string was provided', () => {
return expect(isString('lisk test 12345')).toBeTrue();
});
});
describe('#isBoolean', () => {
it('should return false when number was provided', () => {
return expect(isBoolean(1234)).toBeFalse();
});
it('should return false when bigint was provided', () => {
return expect(isBoolean(BigInt(9))).toBeFalse();
});
it('should return false when buffer was provided', () => {
return expect(isBoolean(Buffer.from('lisk', 'utf8'))).toBeFalse();
});
it('should return false when string was provided', () => {
return expect(isBoolean('lisk test 12345')).toBeFalse();
});
it('should return true when boolean was provided', () => {
expect(isBoolean(false)).toBeTrue();
return expect(isBoolean(true)).toBeTrue();
});
});
describe('#isSInt32', () => {
it('should return false when string was provided', () => {
return expect(isSInt32('1234')).toBeFalse();
});
it('should return false when bigint was provided', () => {
return expect(isSInt32(BigInt(9))).toBeFalse();
});
it('should return false when buffer was provided', () => {
return expect(isSInt32(Buffer.from('lisk', 'utf8'))).toBeFalse();
});
it('should return false when a boolean was provided', () => {
return expect(isSInt32(true)).toBeFalse();
});
it('should return false when the number is just over the limit of sint32', () => {
return expect(isSInt32(2147483648)).toBeFalse();
});
it('should return false when a number "-2147483648" which is just below the limit of sint32', () => {
return expect(isSInt32(-2147483648)).toBeFalse();
});
it('should return true when a valid number was provided', () => {
return expect(isSInt32(2147483647)).toBeTrue();
});
it('should return true when a valid negative number is provided "-2147483644"', () => {
return expect(isSInt32(-2147483644)).toBeTrue();
});
});
describe('#isUInt32', () => {
it('should return false when string was provided', () => {
return expect(isUInt32('1234')).toBeFalse();
});
it('should return false when bigint was provided', () => {
return expect(isUInt32(BigInt(9))).toBeFalse();
});
it('should return false when buffer was provided', () => {
return expect(isUInt32(Buffer.from('lisk', 'utf8'))).toBeFalse();
});
it('should return false when a boolean was provided', () => {
return expect(isUInt32(true)).toBeFalse();
});
it('should return false when a negative number was provided', () => {
return expect(isUInt32(-12)).toBeFalse();
});
it('should return false when the number is just over the limit of isUInt32 "4294967295"', () => {
return expect(isUInt32(4294967296)).toBeFalse();
});
it('should return true when a valid number was provided', () => {
return expect(isUInt32(4294967294)).toBeTrue();
});
});
describe('#isSInt64', () => {
it('should return false when string was provided', () => {
return expect(isSInt64('1234')).toBeFalse();
});
it('should return false when buffer was provided', () => {
return expect(isSInt64(Buffer.from('lisk', 'utf8'))).toBeFalse();
});
it('should return false when a boolean was provided', () => {
return expect(isSInt64(true)).toBeFalse();
});
it('should return false when a bigint was provided over the limit "BigInt(9223372036854775807)"', () => {
return expect(isSInt64(BigInt(9223372036854775810))).toBeFalse();
});
it('should return false when a bigint was provided below the limit "BigInt(-92233720368547758102)"', () => {
return expect(isSInt64(BigInt(-92233720368547758102))).toBeFalse();
});
it('should return true when a valid bigint was provided', () => {
return expect(isSInt64(BigInt(98986))).toBeTrue();
});
it('should return true when a valid negative bigint was provided', () => {
return expect(isSInt64(BigInt(-100))).toBeTrue();
});
});
describe('#isUInt64', () => {
it('should return false when string was provided', () => {
return expect(isUInt64('1234')).toBeFalse();
});
it('should return false when buffer was provided', () => {
return expect(isUInt64(Buffer.from('lisk', 'utf8'))).toBeFalse();
});
it('should return false when a number was provided', () => {
return expect(isUInt64(4294967294)).toBeFalse();
});
it('should return false when a boolean was provided', () => {
return expect(isUInt64(true)).toBeFalse();
});
it('should return false when a negative number was provided', () => {
return expect(isUInt64(-12)).toBeFalse();
});
it('should return false when a bigint was provided over the limit "BigInt(18446744073709551620)"', () => {
return expect(isSInt64(BigInt(18446744073709551620))).toBeFalse();
});
it('should return true when a valid bigint was provided', () => {
return expect(isUInt64(BigInt(98986))).toBeTrue();
});
});
}); | the_stack |
import React from 'react'
import { CountryData } from '../types'
export interface IntlTelInputProps {
/**
* Container CSS class name.
* @default 'intl-tel-input'
*/
containerClassName?: string
/**
* Text input CSS class name.
* @default ''
*/
inputClassName?: string
/**
* It's used as `input` field `name` attribute.
* @default ''
*/
fieldName?: string
/**
* It's used as `input` field `id` attribute.
* @default ''
*/
fieldId?: string
/**
* The value of the input field. Useful for making input value controlled from outside the component.
*/
value?: string
/**
* The value used to initialize input. This will only work on uncontrolled component.
* @default ''
*/
defaultValue?: string
/**
* Countries data can be configured, it defaults to data defined in `AllCountries`.
* @default AllCountries.getCountries()
*/
countriesData?: CountryData[] | null
/**
* Whether or not to allow the dropdown. If disabled, there is no dropdown arrow, and the selected flag is not clickable.
* Also we display the selected flag on the right instead because it is just a marker of state.
* @default true
*/
allowDropdown?: boolean
/**
* If there is just a dial code in the input: remove it on blur, and re-add it on focus.
* @default true
*/
autoHideDialCode?: boolean
/**
* Add or remove input placeholder with an example number for the selected country.
* @default true
*/
autoPlaceholder?: boolean
/**
* Change the placeholder generated by autoPlaceholder. Must return a string.
* @default null
*/
customPlaceholder?:
| ((placeholder: string, selectedCountryData: CountryData) => string)
| null
/**
* Don't display the countries you specify. (Array)
* @default []
*/
excludeCountries?: string[]
/**
* Format the input value during initialisation.
* @default true
*/
formatOnInit?: boolean
/**
* Display the country dial code next to the selected flag so it's not part of the typed number.
* Note that this will disable nationalMode because technically we are dealing with international numbers,
* but with the dial code separated.
* @default false
*/
separateDialCode?: boolean
/**
* Default country.
* @default ''
*/
defaultCountry?: string
/**
* GeoIp lookup function.
* @default null
*/
geoIpLookup?: (countryCode: string) => void
/**
* Don't insert international dial codes.
* @default true
*/
nationalMode?: boolean
/**
* Number type to use for placeholders.
* @default 'MOBILE'
*/
numberType?: string
/**
* The function which can catch the "no this default country" exception.
* @default null
*/
noCountryDataHandler?: (countryCode: string) => void
/**
* Display only these countries.
* @default []
*/
onlyCountries?: string[]
/**
* The countries at the top of the list. defaults to United States and United Kingdom.
* @default ['us', 'gb']
*/
preferredCountries?: string[]
/**
* Optional validation callback function. It returns validation status, input box value and selected country data.
* @default null
*/
onPhoneNumberChange?: (
isValid: boolean,
value: string,
selectedCountryData: CountryData,
fullNumber: string,
extension: string,
) => void
/**
* Optional validation callback function. It returns validation status, input box value and selected country data.
* @default null
*/
onPhoneNumberBlur?: (
isValid: boolean,
value: string,
selectedCountryData: CountryData,
fullNumber: string,
extension: string,
event: React.FocusEvent<HTMLInputElement>,
) => void
/**
* Optional validation callback function. It returns validation status, input box value and selected country data.
* @default null
*/
onPhoneNumberFocus?: (
isValid: boolean,
value: string,
selectedCountryData: CountryData,
fullNumber: string,
extension: string,
event: React.FocusEvent<HTMLInputElement>,
) => void
/**
* Allow main app to do things when a country is selected.
* @default null
*/
onSelectFlag?: (
currentNumber: string,
selectedCountryData: CountryData,
fullNumber: string,
isValid: boolean,
) => void
/**
* Disable this component.
* @default false
*/
disabled?: boolean
/**
* Static placeholder for input controller. When defined it takes priority over autoPlaceholder.
*/
placeholder?: string
/**
* Enable auto focus
* @default false
*/
autoFocus?: boolean
/**
* Set the value of the autoComplete attribute on the input.
* For example, set it to phone to tell the browser where to auto complete phone numbers.
* @default 'off'
*/
autoComplete?: string
/**
* Style object for the wrapper div. Useful for setting 100% width on the wrapper, etc.
*/
style?: React.CSSProperties
/**
* Render fullscreen flag dropdown when mobile useragent is detected.
* The dropdown element is rendered as a direct child of document.body
* @default true
*/
useMobileFullscreenDropdown?: boolean
/**
* Pass through arbitrary props to the tel input element.
* @default {}
*/
telInputProps?: React.InputHTMLAttributes<HTMLInputElement>
/**
* Format the number.
* @default true
*/
format?: boolean
/**
* Allow main app to do things when flag icon is clicked.
* @default null
*/
onFlagClick?: (event: React.MouseEvent<HTMLDivElement, MouseEvent>) => void
}
export interface IntlTelInputState {
showDropdown: boolean
highlightedCountry: number
value: string
disabled: boolean
readonly: boolean
offsetTop: number
outerHeight: number
placeholder: string
title: string
countryCode: string
dialCode: string
cursorPosition: any
}
export default class IntlTelInput extends React.Component<
IntlTelInputProps,
IntlTelInputState
> {
//#region Properties
wrapperClass: {
[key: string]: boolean
}
defaultCountry?: string
autoCountry: string
tempCountry: string
startedLoadingAutoCountry: boolean
dropdownContainer?: React.ElementType | ''
isOpening: boolean
isMobile: boolean
preferredCountries: CountryData[]
countries: CountryData[]
countryCodes: {
[key: string]: string[]
}
windowLoaded: boolean
query: string
selectedCountryData?: CountryData
// prop copies
autoHideDialCode: boolean
nationalMode: boolean
allowDropdown: boolean
// refs
/**
* `<div>` HTML element of the `FlagDropDown` React component.
*/
flagDropDown: HTMLDivElement | null
/**
* `<input>` HTML element of the `TelInput` React component.
*/
tel: HTMLInputElement | null
// NOTE:
// The underscore.deferred package doesn't have known type definitions.
// The closest counterpart is jquery's Deferred object, which it claims to derive itself from.
// These two are equivalent if you log it in console:
//
// underscore.deferred
// var deferred = new _.Deferred()
//
// jquery
// var deferred = $.Deferred()
deferreds: JQuery.Deferred<any, any, any>[]
autoCountryDeferred: JQuery.Deferred<any, any, any>
utilsScriptDeferred: JQuery.Deferred<any, any, any>
//#endregion
//#region Methods
/**
* Updates flag when value of defaultCountry props change
*/
updateFlagOnDefaultCountryChange(countryCode?: string): void
getTempCountry(countryCode?: string): CountryData['iso2'] | 'auto'
/**
* set the input value and update the flag
*/
setNumber(number: string, preventFocus?: boolean): void
setFlagDropdownRef(ref: HTMLDivElement | null): void
setTelRef(ref: HTMLInputElement | null): void
/**
* select the given flag, update the placeholder and the active list item
*
* Note: called from setInitialState, updateFlagFromNumber, selectListItem, setCountry, updateFlagOnDefaultCountryChange
*/
setFlag(countryCode?: string, isInit?: boolean): void
/**
* get the extension from the current number
*/
getExtension(number?: string): string
/**
* format the number to the given format
*/
getNumber(number?: string, format?: string): string
/**
* get the input val, adding the dial code if separateDialCode is enabled
*/
getFullNumber(number?: string): string
/**
* try and extract a valid international dial code from a full telephone number
*/
getDialCode(number: string): string
/**
* check if the given number contains an unknown area code from
*/
isUnknownNanp(number?: string, dialCode?: string): boolean
/**
* add a country code to countryCodes
*/
addCountryCode(
countryCodes: {
[key: string]: string[]
},
iso2: string,
dialCode: string,
priority?: number,
): {
[key: string]: string[]
}
processAllCountries(): void
/**
* process the countryCodes map
*/
processCountryCodes(): void
/**
* process preferred countries - iterate through the preferences,
* fetching the country data for each one
*/
processPreferredCountries(): void
/**
* set the initial state of the input value and the selected flag
*/
setInitialState(): void
initRequests(): void
loadCountryFromLocalStorage(): string
loadAutoCountry(): void
cap(number?: string): string | undefined
removeEmptyDialCode(): void
/**
* highlight the next/prev item in the list (and ensure it is visible)
*/
handleUpDownKey(key?: number): void
/**
* select the currently highlighted item
*/
handleEnterKey(): void
/**
* find the first list item whose name starts with the query string
*/
searchForCountry(query: string): void
formatNumber(number?: string): string
/**
* update the input's value to the given val (format first if possible)
*/
updateValFromNumber(
number?: string,
doFormat?: boolean,
doNotify?: boolean,
): void
/**
* check if need to select a new flag based on the given number
*/
updateFlagFromNumber(number?: string, isInit?: boolean): void
/**
* filter the given countries using the process function
*/
filterCountries(
countryArray: string[],
processFunc: (iso2: string) => void,
): void
/**
* prepare all of the country data, including onlyCountries and preferredCountries options
*/
processCountryData(): void
handleOnBlur(event: React.FocusEvent<HTMLInputElement>): void
handleOnFocus(event: React.FocusEvent<HTMLInputElement>): void
bindDocumentClick(): void
unbindDocumentClick(): void
clickSelectedFlag(event: React.MouseEvent<HTMLDivElement, MouseEvent>): void
/**
* update the input placeholder to an
* example number from the currently selected country
*/
updatePlaceholder(props?: IntlTelInputProps): void
toggleDropdown(status?: boolean): void
/**
* check if an element is visible within it's container, else scroll until it is
*/
scrollTo(element: Element, middle?: boolean): void
/**
* replace any existing dial code with the new one
*
* Note: called from _setFlag
*/
updateDialCode(newDialCode?: string, hasSelectedListItem?: boolean): string
generateMarkup(): void
handleSelectedFlagKeydown(event: React.KeyboardEvent<HTMLDivElement>): void
/**
* validate the input val - assumes the global function isValidNumber (from libphonenumber)
*/
isValidNumber(number?: string): boolean
formatFullNumber(number?: string): string
notifyPhoneNumberChange(number?: string): void
/**
* remove the dial code if separateDialCode is enabled
*/
beforeSetNumber(
number?: string,
props?: IntlTelInputProps,
): string | undefined
handleWindowScroll(): void
handleDocumentKeyDown(event: KeyboardEvent): void
handleDocumentClick(event: MouseEvent): void
/**
* Either notify phoneNumber changed if component is controlled
*/
handleInputChange(event: React.FocusEvent<HTMLInputElement>): void
changeHighlightCountry(showDropdown: boolean, selectedIndex: number): void
loadUtils(): void
/**
* this is called when the geoip call returns
*/
autoCountryLoaded(): void
//#endregion
} | the_stack |
import fetch from "node-fetch";
export class CurseForge {
/**
* Get a curse addon.
* @param addonId The id of the addon.
*/
async getAddon(addonId: number): Promise<CurseAddon> {
return CurseAddon.create(this, addonId);
}
/**
* Get an array of curse addons.
* @param addonIds An array of ids for multiple addons.
*/
async getMultipleAddons(addonIds: number[]): Promise<CurseAddon[]> {
const addons: CurseAddon[] = [];
for (const id of addonIds) {
addons.push(await CurseAddon.create(this, id));
}
return addons;
}
/**
* Get an array of addons with the search results for the given query.
* @param query The CurseSearchQuery to use. See documentation of CurseSearchQuery for more info.
*/
async searchForAddons(query: CurseSearchQuery): Promise<CurseAddon[]> {
const params = new URLSearchParams();
Object.entries(query).forEach((e) => {
if (e[1]) params.append(e[0], e[1].toString());
});
const response = (await this.rawRequest("GET", `addon/search?${params}`)) as unknown[];
return response.map((x: CurseAddonInfo) => new CurseAddon(this, x.id, x));
}
/**
* Get a CurseFeaturedAddonsResponse for the given query. See documentation of CurseFeaturedAddonsResponse for more info.
* @param query The CurseFeaturedAddonsQuery to use. See documentation of CurseFeaturedAddonsQuery for more info.
*/
async getFeaturedAddons(query: CurseFeaturedAddonsQuery): Promise<CurseFeaturedAddonsResponse> {
return this.rawRequest("POST", "addon/featured", query);
}
/**
* Get a CurseFingerprintResponse for given fingerprints. See documentation of CurseFingerprintResponse for more info.
* @param fingerprints An array of murmurhash2 values of each file without whitespaces.
*/
async getAddonByFingerprint(fingerprints: number[]): Promise<CurseFingerprintResponse> {
return this.rawRequest("POST", "fingerprint", fingerprints);
}
/**
* Get an array of all available mod loaders.
*/
async getModloaderList(): Promise<CurseModLoader[]> {
return this.rawRequest("GET", "minecraft/modloader");
}
/**
* Get an array of all available curse categories.
*/
async getCategoryInfoList(): Promise<CurseCategoryInfo[]> {
return this.rawRequest("GET", "https://addons-ecs.forgesvc.net/api/v2/category");
}
/**
* Get information of a specific category.
* @param categoryId The id of the category you want information for.
*/
async getCategoryInfo(categoryId: number): Promise<CurseCategoryInfo> {
return this.rawRequest("GET", `category/${categoryId}`);
}
/**
* Get information of a specific section.
* @param sectionId The id of the section you want information for.
*/
async getCategorySectionInfo(sectionId: number): Promise<CurseCategoryInfo[]> {
return this.rawRequest("GET", `category/section/${sectionId}`);
}
/**
* Get an array of all games information.
* @param supportsAddons Optional parameter if only addons are displayed which support addons. Defaults to true.
*/
async getGamesInfoList(supportsAddons?: boolean): Promise<CurseGameInfo[]> {
let param = "game";
if (!supportsAddons) param += "?false";
return this.rawRequest("GET", param);
}
/**
* Get the game info of a specific game.
* @param gameId The id of the game you want information for.
*/
async getGameInfo(gameId: number): Promise<CurseGameInfo> {
return this.rawRequest("GET", `game/${gameId}`);
}
/**
* Get the UTC time when the database was last updated.
*/
async getDatabaseTimestamp(): Promise<Date> {
const response = await fetch("https://addons-ecs.forgesvc.net/api/v2/addon/timestamp", {
method: "GET",
});
return new Date(await response.text());
}
/**
* Get the UTC time when the minecraft versions were last updated.
*/
async getMinecraftVersionTimestamp(): Promise<Date> {
const response = await fetch("https://addons-ecs.forgesvc.net/api/v2/minecraft/version/timestamp", {
method: "GET",
});
return new Date(await response.text());
}
/**
* Get the UTC time when the mod loader list was last updated.
*/
async getModLoaderTimestamp(): Promise<Date> {
const response = await fetch("https://addons-ecs.forgesvc.net/api/v2/minecraft/modloader/timestamp", {
method: "GET",
});
return new Date(await response.text());
}
/**
* Get the UTC time when the categories were last updated.
*/
async getCategoryTimestamp(): Promise<Date> {
const response = await fetch("https://addons-ecs.forgesvc.net/api/v2/category/timestamp", {
method: "GET",
});
return new Date(await response.text());
}
/**
* Get the UTC time when the games were last updated.
*/
async getGameTimestamp(): Promise<Date> {
const response = await fetch("https://addons-ecs.forgesvc.net/api/v2/game/timestamp", {
method: "GET",
});
return new Date(await response.text());
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// //
// METHODS FROM HERE ONWARDS UNTIL END OF CLASS CurseForge ARE NOT MEANT TO BE CALLED BY BUNDLES. //
// THEY MAY GIVE MORE POSSIBILITIES BUT YOU CAN ALSO BREAK MUCH WITH IT. CALL THEM AT YOUR OWN RISK. //
// //
///////////////////////////////////////////////////////////////////////////////////////////////////////////
// eslint-disable-next-line
async rawRequest(method: HttpMethod, endpoint: string, data?: any): Promise<any> {
const response = await fetch(`https://addons-ecs.forgesvc.net/api/v2/${endpoint}`, {
method: method,
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: data === undefined ? undefined : JSON.stringify(data),
});
return response.json();
}
}
/**
* A curse addon such as a Minecraft mod.
*/
export class CurseAddon {
constructor(
private readonly curse: CurseForge,
public readonly addonId: number,
public readonly info: CurseAddonInfo,
) {}
/**
* Creates an addon.
* @param curse The CurseForge instance.
* @param addonId The id of the addon you want to create.
*/
static async create(curse: CurseForge, addonId: number): Promise<CurseAddon> {
const response: CurseAddonInfo = await curse.rawRequest("GET", `addon/${addonId}`);
return new CurseAddon(curse, addonId, response);
}
/**
* Get all files of the addon.
*/
async getFiles(): Promise<CurseFileInfo[]> {
return this.curse.rawRequest("GET", `addon/${this.addonId}/files`);
}
/**
* Get the description of an CurseAddon. It's raw html or markdown as a string.
*/
async getAddonDescription(): Promise<string> {
const response = await fetch(`https://addons-ecs.forgesvc.net/api/v2/addon/${this.addonId}/description`, {
method: "GET",
});
return response.text();
}
}
/**
* A file from an addon.
*/
export class CurseFile {
readonly addon: CurseAddon;
readonly fileId: number;
readonly info: CurseFileInfo;
constructor(addon: CurseAddon, fileId: number, info: CurseFileInfo) {
this.addon = addon;
this.fileId = fileId;
this.info = info;
}
/**
* Creates a file.
* @param curse The CurseForge instance.
* @param addon The parent addon of the file.
* @param fileId The id of the specific file.
*/
static async create(curse: CurseForge, addon: CurseAddon, fileId: number): Promise<CurseFile> {
const response: CurseFileInfo = await curse.rawRequest("GET", `addon/${addon.addonId}/file/${fileId}`);
return new CurseFile(addon, fileId, response);
}
/**
* Get the download url of the file.
*/
getDownloadUrl(): string {
return this.info.downloadUrl;
}
/**
* Get the changelog of a file.
* It is raw html or markdown as a string.
*/
async getFileChangelog(): Promise<string> {
const respone = await fetch(
`https://addons-ecs.forgesvc.net/api/v2/addon/${this.addon.addonId}/file/${this.fileId}/changelog`,
{
method: "GET",
},
);
return respone.text();
}
}
export type CurseGameInfo = {
/**
* The game id
*/
id: number;
/**
* The game name
*/
name: string;
/**
* The slug used in urls
*/
slug: string;
/**
* The date when the game was last modified
*/
dateModified: string;
/**
* The files of the game
*/
gameFiles: CurseGameFile[];
fileParsingRules: CurseParsingRule[];
/**
* The category sections of a game
*/
categorySections: CurseCategorySection[];
maxFreeStorage: number;
maxPremiumStorage: number;
maxFileSize: number;
addonSettingsFolderFilter: string | null;
addonSettingsStartingFolder: string | null;
addonSettingsFileFilter: string | null;
addonSettingsFileRemovalFilter: string | null;
/**
* Whether the game supports addons or not
*/
supportsAddons: boolean;
supportsPartnerAddons: boolean;
supportedClientConfiguration: number;
/**
* Whether the game supports notifications or not
*/
supportsNotifications: boolean;
profilerAddonId: number;
/**
* The category id on Twitch of the game
*/
twitchGameId: number;
clientGameSettingsId: number;
};
export type CurseParsingRule = {
commentStripPattern: string;
fileExtension: string;
inclusionPattern: string;
gameId: number;
id: number;
};
export type CurseGameFile = {
/**
* The id of a games file
*/
id: number;
/**
* The game id
*/
gameId: number;
/**
* Whether a file is required for the game or not
*/
isRequired: boolean;
/**
* The file name
*/
fileName: string;
/**
* The file type id
*/
fileType: number;
/**
* The platform type id
*/
platformType: number;
};
export type CurseGameDetectionHint = {
id: number;
hintType: number;
hintPath: string;
hintKey: string | null;
hintOptions: number;
/**
* The game id
*/
gameId: number;
};
export type CurseModLoader = {
/**
* The loader name
*/
name: string;
/**
* The game version the loader is for
*/
gameVersion: string;
/**
* Whether it's the latest loader version for the game version or not
*/
latest: boolean;
/**
* Whether it's the recommended loader version for the game version or not
*/
recommended: boolean;
/**
* The date when the loader was last modified
*/
dateModified: string;
};
export type CurseAddonInfo = {
/**
* The addon id
*/
id: number;
/**
* The addon name
*/
name: string;
/**
* All users marked as owner or author
*/
authors: CurseAddonAuthor[];
/**
* All attachments such as the logo or screenshots
*/
attachments: CurseAddonAttachment[];
/**
* The url to the addon
*/
websiteUrl: string;
/**
* The game id
*/
gameId: number;
/**
* The small summary shown on overview sites
*/
summary: string;
/**
* The default files id
*/
defaultFileId: number;
/**
* The download count
*/
downloadCount: number;
/**
* The latest release, beta and alpha file
*/
latestFiles: LatestCurseFileInfo[];
/**
* The categories the addon is included in
*/
categories: CurseCategory[];
/**
* The CurseProjectStatus
*/
status: number;
/**
* The primary category id
*/
primaryCategoryId: number;
/**
* The category section the project is included in
*/
categorySection: CurseCategorySection;
/**
* The slug used in urls
*/
slug: string;
/**
* The basic information about latest release, beta and alpha of each game version
*/
gameVersionLatestFiles: CurseGameVersionLatestFile[];
isFeatured: boolean;
/**
* The value used for sorting by popularity
*/
popularityScore: number;
/**
* The current popularity rank of the game
*/
gamePopularityRank: number;
/**
* The primary language
*/
primaryLanguage: string;
/**
* The games slug used in urls
*/
gameSlug: string;
/**
* The games name
*/
gameName: string;
/**
* The portal you find the addon on
*/
portalName: string;
/**
* The date when the addon was last modified
*/
dateModified: string;
/**
* The date when the addon was created
*/
dateCreated: string;
/**
* The date when the last file was added
*/
dateReleased: string;
/**
* Whether the addon is public visible or not
*/
isAvailable: boolean;
/**
* Whether the addon is in experimental state or not
*/
isExperiemental: boolean;
};
export type CurseAddonAuthor = {
/**
* The authors name
*/
name: string;
/**
* The url to the authors profile
*/
url: string;
/**
* The project id the title data is correct for
*/
projectId: number;
id: number;
/**
* The id for the authors title in the project
* null for owner
*/
projectTitleId: number | null;
/**
* The name for the authors title in the project
* null for owner
*/
projectTitleTitle: string | null;
/**
* The user id
*/
userId: number;
/**
* The twitch id of the users linked twitch account
*/
twitchId: number;
};
export type CurseAddonAttachment = {
/**
* The attachment id
*/
id: number;
/**
* The project id
*/
projectId: number;
/**
* The attachment description
*/
description: string;
/**
* Whether it's the logo or not
*/
isDefault: boolean;
/**
* Thr url to a compressed version
*/
thumbnailUrl: string;
/**
* The attachment name
*/
title: string;
/**
* The url to an uncompressed version
*/
url: string;
/**
* The attachment status
*/
status: number;
};
export type CurseFileInfo = {
/**
* The file id
*/
id: number;
/**
* The displayed name
*/
displayName: string;
/**
* The real file name
*/
fileName: string;
/**
* The date the file was uploaded
*/
fileDate: string;
/**
* The file size in byte
*/
fileLength: number;
/**
* The CurseReleaseType
*/
releaseType: number;
/**
* The CurseFileStatus
*/
fileStatus: number;
/**
* The url where the file can be downloaded
*/
downloadUrl: string;
/**
* Whether it's an additional file or not
*/
isAlternate: boolean;
/**
* The id of the additional file
*/
alternateFileId: number;
/**
* All the dependencies
*/
dependencies: CurseDependency[];
/**
* Whether the file is public visible or not
*/
isAvailable: boolean;
/**
* All the modules of the file
*/
modules: CurseModule[];
/**
* The murmurhash2 fingerprint without whitespaces
*/
packageFingerprint: number;
/**
* The game versions the file is for
*/
gameVersion: string[];
installMetadata: unknown;
/**
* The file id of the corresponding server pack
*/
serverPackFileId: number | null;
/**
* Whether the file has an install script or not
*/
hasInstallScript: boolean;
/**
* The date the game version was released
*/
gameVersionDateReleased: string;
gameVersionFlavor: unknown;
};
export type LatestCurseFileInfo = CurseFileInfo & {
sortableGameVersion: CurseSortableGameVersion[];
/**
* The changelog
*/
changelog: string | null;
/**
* Whether the file is compatible with client or not
*/
isCompatibleWithClient: boolean;
categorySectionPackageType: number;
restrictProjectFileAccess: number;
/**
* The CurseProjectStatus
*/
projectStatus: number;
renderCacheId: number;
fileLegacyMappingId: number | null;
/**
* The id of the files addon
*/
projectId: number;
parentProjectFileId: number | null;
parentFileLegacyMappingId: number | null;
fileTypeId: number | null;
exposeAsAlternative: unknown;
packageFingerprintId: number;
gameVersionMappingId: number;
gameVersionId: number;
/**
* The game id
*/
gameId: number;
/**
* Whether this is a server pack or not
*/
isServerPack: boolean;
// disable because it's not present in latest file
gameVersionFlavor: undefined;
};
export type CurseGameVersionLatestFile = {
/**
* The game version
*/
gameVersion: string;
/**
* The file id
*/
projectFileId: number;
/**
* The file name
*/
projectFileName: string;
/**
* The file type
*/
fileType: number;
gameVersionFlavor: unknown;
};
export type CurseCategory = {
/**
* The category id
*/
categoryId: number;
/**
* The category name
*/
name: string;
/**
* The url to the category
*/
url: string;
/**
* The url to the avatar
*/
avatarUrl: string;
/**
* The id to the parent category section
*/
parentId: number;
/**
* The id to the root category section
*/
rootId: number;
/**
* The project id
*/
projectId: number;
avatarId: number;
/**
* The game id
*/
gameId: number;
};
export type CurseCategorySection = {
/**
* The category section id
*/
id: number;
/**
* The game id the section is for
*/
gameId: number;
/**
* The section name
*/
name: string;
packageType: number;
/**
* The path where the files should be downloaded to
*/
path: string;
initialInclusionPattern: string;
extraIncludePattern: unknown;
/**
* The game category id. This value can be used for `sectionId` in
* a search query.
*/
gameCategoryId: number;
};
export type CurseCategoryInfo = {
/**
* The category id
*/
id: number;
/**
* The category name
*/
name: string;
/**
* The category slug used in urls
*/
slug: string;
/**
* The url to the avatar
*/
avatarUrl: string;
/**
* The date the category was last updated
*/
dateModified: string;
/**
* The parent game category id
*/
parentGameCategoryId: number | null;
/**
* The root game category id. For root categories, this is null.
*/
rootGameCategoryId: number | null;
/**
* The game id the category belongs to
*/
gameId: number;
};
export type CurseDependency = {
/**
* The addon id
*/
addonId: number;
/**
* The CurseDependencyType
*/
type: number;
};
export type CurseModule = {
/**
* The folder/file name
*/
foldername: string;
/**
* The folder/file fingerprint
*/
fingerprint: number;
};
export type CurseSortableGameVersion = {
gameVersionPadded: string;
gameVersion: string;
gameVersionReleaseDate: string;
gameVersionName: string;
};
export type CurseFingerprintResponse = {
isCacheBuilt: boolean;
/**
* All exact matches of the given fingerprints
*/
exactMatches: CurseFileInfo[];
/**
* The fingerprints which matched
*/
exactFingerprints: number[];
/**
* All files which matched partially
*/
partialMatches: CurseFileInfo[];
/**
* The fingerprints which matched partially
*/
partialMatchFingerprints: number[];
/**
* All fingerprints you sent
*/
installedFingerprints: number[];
/**
* All fingerprints which didn't match
*/
unmatchedFingerprints: number[];
};
export type CurseFeaturedAddonsResponse = {
/**
* All featured files which matched the query
*/
Featured: CurseFileInfo[];
/**
* All popular files which matched the query
*/
Popular: CurseFileInfo[];
/**
* All recently updated files which matched the query
*/
RecentlyUpdated: CurseFileInfo[];
};
export type CurseReleaseType = "release" | "beta" | "alpha";
export type CurseDependencyType = "embedded_library" | "optional" | "required" | "tool" | "incompatible" | "include";
export type CurseFileStatus =
| "status_1"
| "status_2"
| "status_3"
| "approved"
| "rejected"
| "status_6"
| "deleted"
| "archived";
export type CurseProjectStatus =
| "new"
| "status_2"
| "status_3"
| "approved"
| "status_5"
| "status_6"
| "status_7"
| "status_8"
| "deleted";
export type CurseSearchQuery = {
/**
* Id of a category to search in. This is not for root categories.
* Root categories should use sectionId instead.
*/
categoryID?: number;
gameId: number;
gameVersion?: string;
index?: number;
pageSize?: number;
searchFilter?: string;
/**
* Id of a category to search in. This is only for root categories.
* Other categories should use categoryID instead.
*/
sectionId?: number;
sort?: number;
};
export type CurseFeaturedAddonsQuery = {
GameId: number;
addonIds?: number[];
featuredCount?: number;
popularCount?: number;
updatedCount?: number;
};
export class MagicValues {
private static readonly RELEASE: Record<CurseReleaseType, number> = {
alpha: 3,
beta: 2,
release: 1,
};
private static readonly RELEASE_INVERSE: Record<number, CurseReleaseType> = MagicValues.inverse(
MagicValues.RELEASE,
);
private static readonly DEPENDENCY: Record<CurseDependencyType, number> = {
include: 6,
incompatible: 5,
tool: 4,
required: 3,
optional: 2,
embedded_library: 1,
};
private static readonly DEPENDENCY_INVERSE: Record<number, CurseDependencyType> = MagicValues.inverse(
MagicValues.DEPENDENCY,
);
private static readonly FILE_STATUS: Record<CurseFileStatus, number> = {
archived: 8,
deleted: 7,
status_6: 6,
rejected: 5,
approved: 4,
status_3: 3,
status_2: 2,
status_1: 1,
};
private static readonly FILE_STATUS_INVERSE: Record<number, CurseFileStatus> = MagicValues.inverse(
MagicValues.FILE_STATUS,
);
private static readonly PROJECT_STATUS: Record<CurseProjectStatus, number> = {
deleted: 9,
status_8: 8,
status_7: 7,
status_6: 6,
status_5: 5,
approved: 4,
status_3: 3,
status_2: 2,
new: 1,
};
private static readonly PROJECT_STATUS_INVERSE: Record<number, CurseProjectStatus> = MagicValues.inverse(
MagicValues.PROJECT_STATUS,
);
static releaseType(value: number): CurseReleaseType;
static releaseType(value: CurseReleaseType): number;
static releaseType(value: never): unknown {
return MagicValues.mapMagicValue(value, MagicValues.RELEASE, MagicValues.RELEASE_INVERSE);
}
static dependencyType(value: number): CurseDependencyType;
static dependencyType(value: CurseDependencyType): number;
static dependencyType(value: never): unknown {
return MagicValues.mapMagicValue(value, MagicValues.DEPENDENCY, MagicValues.DEPENDENCY_INVERSE);
}
static fileStatus(value: number): CurseFileStatus;
static fileStatus(value: CurseFileStatus): number;
static fileStatus(value: never): unknown {
return MagicValues.mapMagicValue(value, MagicValues.FILE_STATUS, MagicValues.FILE_STATUS_INVERSE);
}
static projectStatus(value: number): CurseProjectStatus;
static projectStatus(value: CurseProjectStatus): number;
static projectStatus(value: never): unknown {
return MagicValues.mapMagicValue(value, MagicValues.PROJECT_STATUS, MagicValues.PROJECT_STATUS_INVERSE);
}
private static mapMagicValue(
value: number | string,
map: Record<string, number>,
inverse: Record<number, string>,
): number | string | undefined {
if (typeof value === "number") {
return inverse[value];
} else {
return map[value];
}
}
private static inverse<T extends string | number | symbol, U extends string | number | symbol>(
record: Record<T, U>,
): Record<U, T> {
const inverse: Record<U, T> = {} as Record<U, T>;
for (const key in record) {
// noinspection JSUnfilteredForInLoop
inverse[record[key]] = key;
}
return inverse;
}
}
export type HttpMethod = "GET" | "HEAD" | "POST" | "PUT" | "DELETE" | "CONNECT" | "OPTIONS" | "TRACE" | "PATCH"; | the_stack |
import { setupContentBuilder } from './RicosContentBuilder';
import {
ImageData,
PluginContainerData_Width_Type,
PluginContainerData_Alignment,
RichContent,
Node_Type,
ParagraphData,
TextStyle_TextAlignment,
Decoration_Type,
AppEmbedData,
AppEmbedData_AppType,
PollData,
} from 'ricos-schema';
import { TableCell } from '../types/contentApi';
import { RichText } from '../types/node-refined-types';
describe('Ricos Content Builder', () => {
it('should implement ContentBuilder', () => {
const generateKey = () => 'foo';
const api = setupContentBuilder(generateKey);
expect(api.addAppEmbed).toBeDefined();
expect(api.addBulletList).toBeDefined();
expect(api.addButton).toBeDefined(); // TODO: API should accept url
expect(api.addCode).toBeDefined();
expect(api.addCollapsibleList).toBeDefined();
expect(api.addDivider).toBeDefined();
expect(api.addEmbed).toBeDefined();
expect(api.addFile).toBeDefined(); // TODO: API should accept url
expect(api.addGallery).toBeDefined(); // TODO: API should accept urls
expect(api.addGif).toBeDefined(); // TODO: API should accept url
expect(api.addHeading).toBeDefined();
expect(api.addHtml).toBeDefined(); // TODO: API should accept url
expect(api.addImage).toBeDefined(); // TODO: API should accept url
expect(api.addLinkPreview).toBeDefined(); // TODO: API should accept url
expect(api.addMap).toBeDefined(); // TODO: API should accept address
expect(api.addOrderedList).toBeDefined();
expect(api.addParagraph).toBeDefined();
expect(api.addPoll).toBeDefined();
expect(api.addTable).toBeDefined();
expect(api.addVideo).toBeDefined(); // TODO: API should accept url
});
it('should add image node to content', () => {
const generateKey = () => 'foo';
const api = setupContentBuilder(generateKey);
const imageData: ImageData = {
containerData: {
width: { size: PluginContainerData_Width_Type.SMALL },
alignment: PluginContainerData_Alignment.CENTER,
},
};
const expected: RichContent = {
nodes: [
{
type: Node_Type.IMAGE,
imageData,
nodes: [],
id: 'foo',
},
],
};
const actual = api.addImage({ data: imageData, content: { nodes: [] } });
expect(actual).toEqual(expected);
});
it('should add a paragraph with text to content', () => {
const generateKey = () => 'foo';
const api = setupContentBuilder(generateKey);
const paragraphData: ParagraphData = {
textStyle: {
textAlignment: TextStyle_TextAlignment.RIGHT,
},
};
const expected: RichContent = {
nodes: [
{
type: Node_Type.PARAGRAPH,
id: 'foo',
paragraphData,
nodes: [
{
id: '',
type: Node_Type.TEXT,
textData: {
text: 'test paragraph',
decorations: [],
},
nodes: [],
},
],
},
],
};
const actual = api.addParagraph({
text: 'test paragraph',
data: paragraphData,
content: { nodes: [] },
});
expect(actual).toEqual(expected);
});
it('should add bullet list with string items to content', () => {
const generateKey = () => 'foo';
const api = setupContentBuilder(generateKey);
const paragraphData: ParagraphData = {
textStyle: {
textAlignment: TextStyle_TextAlignment.RIGHT,
},
};
const expected: RichContent = {
nodes: [
{
type: Node_Type.BULLETED_LIST,
id: 'foo',
nodes: [
{
type: Node_Type.LIST_ITEM,
id: 'foo',
nodes: [
{
type: Node_Type.PARAGRAPH,
id: 'foo',
paragraphData,
nodes: [
{
id: '',
type: Node_Type.TEXT,
textData: {
text: 'item1',
decorations: [],
},
nodes: [],
},
],
},
],
},
{
type: Node_Type.LIST_ITEM,
id: 'foo',
nodes: [
{
type: Node_Type.PARAGRAPH,
id: 'foo',
paragraphData,
nodes: [
{
id: '',
type: Node_Type.TEXT,
textData: {
text: 'item2',
decorations: [],
},
nodes: [],
},
],
},
],
},
],
},
],
};
const actual = api.addBulletList({
items: ['item1', 'item2'],
data: paragraphData,
content: { nodes: [] },
});
expect(actual).toEqual(expected);
});
it('should add ordered list with mixed items to content', () => {
const generateKey = () => 'foo';
const api = setupContentBuilder(generateKey);
const paragraphData: ParagraphData = {
textStyle: {
textAlignment: TextStyle_TextAlignment.RIGHT,
},
};
const textDataItem1 = {
text: 'item1',
decorations: [{ type: Decoration_Type.BOLD }],
};
const listItem2 = {
text: [{ text: 'item2', decorations: [{ type: Decoration_Type.ITALIC }] }],
data: { textStyle: { textAlignment: TextStyle_TextAlignment.AUTO }, indentation: 2 },
};
const expected: RichContent = {
nodes: [
{
type: Node_Type.ORDERED_LIST,
id: 'foo',
nodes: [
{
type: Node_Type.LIST_ITEM,
id: 'foo',
nodes: [
{
type: Node_Type.PARAGRAPH,
id: 'foo',
paragraphData,
nodes: [
{
id: '',
type: Node_Type.TEXT,
textData: {
text: 'item1',
decorations: [{ type: Decoration_Type.BOLD }],
},
nodes: [],
},
],
},
],
},
{
type: Node_Type.LIST_ITEM,
id: 'foo',
nodes: [
{
type: Node_Type.PARAGRAPH,
id: 'foo',
paragraphData: {
textStyle: { textAlignment: TextStyle_TextAlignment.AUTO },
indentation: 2,
},
nodes: [
{
id: '',
type: Node_Type.TEXT,
textData: {
text: 'item2',
decorations: [{ type: Decoration_Type.ITALIC }],
},
nodes: [],
},
],
},
],
},
{
type: Node_Type.LIST_ITEM,
id: 'foo',
nodes: [
{
type: Node_Type.PARAGRAPH,
id: 'foo',
paragraphData,
nodes: [
{
id: '',
type: Node_Type.TEXT,
textData: {
text: 'item3',
decorations: [],
},
nodes: [],
},
],
},
],
},
],
},
],
};
const actual = api.addOrderedList({
items: [textDataItem1, listItem2, 'item3'],
data: paragraphData,
content: { nodes: [] },
});
expect(actual).toEqual(expected);
});
it('should add AppEmbed to content', () => {
const content = { nodes: [] };
const appEmbedData: AppEmbedData = {
type: AppEmbedData_AppType.EVENT,
itemId: 'assa',
name: 'Birthday party',
imageSrc: 'https://static.wixstatic.com/media/8bb438_8307fc32bdf4455ab3033c542da4c6c7.jpg',
url: 'https://static.wixstatic.com/media/8bb438_8307fc32bdf4455ab3033c542da4c6c7.jpg',
eventData: { scheduling: 'now', location: 'home' },
};
const expected = { nodes: [{ type: Node_Type.APP_EMBED, id: 'foo', appEmbedData, nodes: [] }] };
const generateKey = () => 'foo';
const api = setupContentBuilder(generateKey);
const actual = api.addAppEmbed({ data: appEmbedData, content });
expect(actual).toEqual(expected);
});
it('should add a table 3x3', () => {
const expected = {
nodes: [
{
type: 'TABLE',
id: 'foo',
nodes: [
{
type: 'TABLE_ROW',
id: 'foo',
nodes: [
{
type: 'TABLE_CELL',
id: 'foo',
nodes: [
{
type: 'PARAGRAPH',
id: 'foo',
nodes: [
{
type: 'TEXT',
id: '',
nodes: [],
textData: {
text: '1-1',
decorations: [],
},
},
],
paragraphData: {
textStyle: {
textAlignment: 'AUTO',
},
indentation: 0,
},
},
],
tableCellData: {
cellStyle: {
verticalAlignment: 'TOP',
},
borderColors: {},
},
},
{
type: 'TABLE_CELL',
id: 'foo',
nodes: [
{
type: 'PARAGRAPH',
id: 'foo',
nodes: [
{
type: 'TEXT',
id: '',
nodes: [],
textData: {
text: '1-2',
decorations: [],
},
},
],
paragraphData: {
textStyle: {
textAlignment: 'AUTO',
},
indentation: 0,
},
},
],
tableCellData: {
cellStyle: {
verticalAlignment: 'TOP',
},
borderColors: {},
},
},
{
type: 'TABLE_CELL',
id: 'foo',
nodes: [
{
type: 'PARAGRAPH',
id: 'foo',
nodes: [
{
type: 'TEXT',
id: '',
nodes: [],
textData: {
text: '1-3',
decorations: [],
},
},
],
paragraphData: {
textStyle: {
textAlignment: 'AUTO',
},
indentation: 0,
},
},
],
tableCellData: {
cellStyle: {
verticalAlignment: 'TOP',
},
borderColors: {},
},
},
],
},
{
type: 'TABLE_ROW',
id: 'foo',
nodes: [
{
type: 'TABLE_CELL',
id: 'foo',
nodes: [
{
type: 'PARAGRAPH',
id: 'foo',
nodes: [
{
type: 'TEXT',
id: '',
nodes: [],
textData: {
text: '2-1',
decorations: [],
},
},
],
paragraphData: {
textStyle: {
textAlignment: 'AUTO',
},
indentation: 0,
},
},
],
tableCellData: {
cellStyle: {
verticalAlignment: 'TOP',
},
borderColors: {},
},
},
{
type: 'TABLE_CELL',
id: 'foo',
nodes: [
{
type: 'PARAGRAPH',
id: 'foo',
nodes: [
{
type: 'TEXT',
id: '',
nodes: [],
textData: {
text: '2-2',
decorations: [],
},
},
],
paragraphData: {
textStyle: {
textAlignment: 'AUTO',
},
indentation: 0,
},
},
],
tableCellData: {
cellStyle: {
verticalAlignment: 'TOP',
},
borderColors: {},
},
},
{
type: 'TABLE_CELL',
id: 'foo',
nodes: [
{
type: 'PARAGRAPH',
id: 'foo',
nodes: [
{
type: 'TEXT',
id: '',
nodes: [],
textData: {
text: '2-3',
decorations: [],
},
},
],
paragraphData: {
textStyle: {
textAlignment: 'AUTO',
},
indentation: 0,
},
},
],
tableCellData: {
cellStyle: {
verticalAlignment: 'TOP',
},
borderColors: {},
},
},
],
},
{
type: 'TABLE_ROW',
id: 'foo',
nodes: [
{
type: 'TABLE_CELL',
id: 'foo',
nodes: [
{
type: 'PARAGRAPH',
id: 'foo',
nodes: [
{
type: 'TEXT',
id: '',
nodes: [],
textData: {
text: '3-1',
decorations: [],
},
},
],
paragraphData: {
textStyle: {
textAlignment: 'AUTO',
},
indentation: 0,
},
},
],
tableCellData: {
cellStyle: {
verticalAlignment: 'TOP',
},
borderColors: {},
},
},
{
type: 'TABLE_CELL',
id: 'foo',
nodes: [
{
type: 'PARAGRAPH',
id: 'foo',
nodes: [
{
type: 'TEXT',
id: '',
nodes: [],
textData: {
text: '3-2',
decorations: [],
},
},
],
paragraphData: {
textStyle: {
textAlignment: 'AUTO',
},
indentation: 0,
},
},
],
tableCellData: {
cellStyle: {
verticalAlignment: 'TOP',
},
borderColors: {},
},
},
{
type: 'TABLE_CELL',
id: 'foo',
nodes: [
{
type: 'PARAGRAPH',
id: 'foo',
nodes: [
{
type: 'TEXT',
id: '',
nodes: [],
textData: {
text: '',
decorations: [],
},
},
],
paragraphData: {
textStyle: {
textAlignment: 'AUTO',
},
indentation: 0,
},
},
],
tableCellData: {
cellStyle: {
verticalAlignment: 'TOP',
},
borderColors: {},
},
},
],
},
],
tableData: {
containerData: {
alignment: 'CENTER',
textWrap: true,
width: { size: 'CONTENT' },
},
dimensions: {
colsWidthRatio: [10, 10, 10],
rowsHeight: [47, 47, 47],
colsMinWidth: [120, 120, 120],
},
},
},
],
};
const generateKey = () => 'foo';
const api = setupContentBuilder(generateKey);
// 3x3 cell matrix of paragraphs
const cells: TableCell[][] = Array(3)
.fill(0)
.map((_, i) =>
Array(3)
.fill(0)
.map((_, j) => ({
content: api.addParagraph({
text: `${i + 1}-${j + 1}`,
content: { nodes: [] },
}),
}))
);
// remove last cell
cells[2].pop();
const actual = api.addTable({ cells, content: { nodes: [] } });
expect(actual).toEqual(expected);
});
it('should add collapsible list', () => {
const expected = {
nodes: [
{
type: 'COLLAPSIBLE_LIST',
id: 'foo',
nodes: [
{
type: 'COLLAPSIBLE_ITEM',
id: 'foo',
nodes: [
{
type: 'COLLAPSIBLE_ITEM_TITLE',
id: 'foo',
nodes: [
{
type: 'PARAGRAPH',
id: 'foo',
nodes: [
{
type: 'TEXT',
id: '',
nodes: [],
textData: {
text: 'title',
decorations: [
{
type: 'BOLD',
},
],
},
},
],
paragraphData: {
textStyle: {
textAlignment: 'AUTO',
},
indentation: 0,
},
},
],
},
{
type: 'COLLAPSIBLE_ITEM_BODY',
id: 'foo',
nodes: [
{
type: 'DIVIDER',
id: 'foo',
nodes: [],
dividerData: {
lineStyle: 'SINGLE',
width: 'LARGE',
alignment: 'CENTER',
containerData: {
alignment: 'CENTER',
width: {
size: 'CONTENT',
},
textWrap: false,
},
},
},
],
},
],
},
],
collapsibleListData: {
initialExpandedItems: 'FIRST',
direction: 'LTR',
containerData: {
alignment: 'CENTER',
textWrap: true,
width: {
size: 'CONTENT',
},
},
expandOnlyOne: false,
},
},
],
};
const generateKey = () => 'foo';
const api = setupContentBuilder(generateKey);
const actual = api.addCollapsibleList({
items: [
{
title: api.addParagraph({
text: { text: 'title', decorations: [{ type: Decoration_Type.BOLD }] },
content: { nodes: [] },
}) as RichText,
content: api.addDivider({ content: { nodes: [] } }),
},
],
content: { nodes: [] },
});
expect(actual).toEqual(expected);
});
it('should add Poll to content', () => {
const content = { nodes: [] };
const expected = {
nodes: [
{
type: Node_Type.POLL,
id: 'foo',
pollData: {
containerData: {
alignment: 'CENTER',
textWrap: true,
width: {
size: 'CONTENT',
},
},
design: {
options: {
borderRadius: 0,
},
poll: {
background: {
type: 'IMAGE',
},
borderRadius: 0,
},
},
layout: {
options: {
enableImage: false,
},
poll: {
direction: 'LTR',
enableImage: false,
type: 'LIST',
},
},
poll: {
options: [],
settings: {
permissions: {
allowMultipleVotes: false,
view: 'VOTERS',
vote: 'SITE_MEMBERS',
},
showVoters: true,
showVotesCount: true,
},
title: '',
},
},
nodes: [],
},
],
};
const generateKey = () => 'foo';
const api = setupContentBuilder(generateKey);
const actual = api.addPoll({ content });
expect(actual).toEqual(expected);
});
}); | the_stack |
import './setup';
import {DOM} from 'aurelia-pal';
import {Container} from 'aurelia-dependency-injection';
import {configure as configureBindingLanguage} from 'aurelia-templating-binding';
import {
ViewCompiler,
ViewResources,
HtmlBehaviorResource,
BehaviorInstruction,
ViewSlot
} from 'aurelia-templating';
import {Repeat} from '../src/repeat';
import {If} from '../src/if';
import {Compose} from '../src/compose';
import {OneTimeBindingBehavior} from '../src/binding-mode-behaviors';
import {metadata} from 'aurelia-metadata';
import {TaskQueue} from 'aurelia-task-queue';
import {ObserverLocator} from 'aurelia-binding';
import {viewsRequireLifecycle} from '../src/analyze-view-factory';
import './test-interfaces';
// create the root container.
let container = new Container();
// register the standard binding language implementation.
configureBindingLanguage({ container });
// create the root view resources.
function createViewResources(container) {
let resources = new ViewResources();
// repeat
let resource = metadata.get(metadata.resource, Repeat) as HtmlBehaviorResource;
resource.target = Repeat;
resource.initialize(container, Repeat);
resources.registerAttribute('repeat', resource, 'repeat');
// if
resource = metadata.get(metadata.resource, If) as HtmlBehaviorResource;
resource.target = If;
resource.initialize(container, If);
resources.registerAttribute('if', resource, 'if');
// compose
resource = metadata.get(metadata.resource, Compose) as HtmlBehaviorResource;
resource.target = Compose;
resource.initialize(container, Compose);
resources.registerElement('compose', resource);
container.registerInstance(ViewResources, resources);
// slice value converter
resources.registerValueConverter('slice', { toView: array => array ? array.slice(0) : array });
// no-op value converter
resources.registerValueConverter('noopValueConverter', { toView: value => value });
// toLength value converter
resources.registerValueConverter('toLength', { toView: collection => collection ? (collection.length || collection.size || 0) : 0 });
// no-op binding behavior
resources.registerBindingBehavior('noopBehavior', { bind: () => {/**/}, unbind: () => {/**/} });
// oneTime binding behavior
resources.registerBindingBehavior('oneTime', new OneTimeBindingBehavior());
}
createViewResources(container);
// create the view compiler.
let viewCompiler = container.get(ViewCompiler);
// create the host element and view-slot for all the tests
let host = DOM.createElement('div');
DOM.appendNode(host);
let viewSlot = new ViewSlot(host, true);
// creates a controller given a html template string and a viewmodel instance.
function createController(template, viewModel, viewsRequireLifecycle?: boolean) {
let childContainer = container.createChild();
let viewFactory = viewCompiler.compile(template);
if (viewsRequireLifecycle !== undefined) {
for (let id in viewFactory.instructions) {
let targetInstruction = viewFactory.instructions[id];
for (let behaviorInstruction of targetInstruction.behaviorInstructions) {
if (behaviorInstruction.attrName === 'repeat') {
behaviorInstruction.viewFactory._viewsRequireLifecycle = viewsRequireLifecycle;
}
}
}
}
let metadata = new HtmlBehaviorResource();
function App() {
//
}
metadata.initialize(childContainer, App);
metadata.elementName = metadata.htmlName = 'app';
let controller = metadata.create(childContainer, BehaviorInstruction.dynamic(host, viewModel, viewFactory));
controller.automate();
viewSlot.removeAll();
viewSlot.add(controller.view);
return controller;
}
// functions to test repeat output
function select(controller, selector) {
return Array.prototype.slice.call(host.querySelectorAll(selector));
}
function selectContent(controller, selector) {
return select(controller, selector).map(el => el.textContent);
}
// async queue
function createAssertionQueue() {
let queue = [];
let next;
next = () => {
if (queue.length) {
setTimeout(() => {
let func = queue.shift();
if (func) {
func();
}
next();
});
}
};
return func => {
queue.push(func);
if (queue.length === 1) {
next();
}
};
}
let nq = createAssertionQueue();
// convenience methods for checking whether a property or collection is being observed.
let observerLocator = container.get(ObserverLocator);
function hasSubscribers(obj, propertyName) {
return observerLocator.getObserver(obj, propertyName).hasSubscribers();
}
function hasArraySubscribers(array) {
return observerLocator.getArrayObserver(array).hasSubscribers();
}
function hasMapSubscribers(map) {
return observerLocator.getMapObserver(map).hasSubscribers();
}
function hasSetSubscribers(set) {
return observerLocator.getSetObserver(set).hasSubscribers();
}
function describeArrayTests(viewsRequireLifecycle) {
let viewModel, controller;
function validateContextualData(isObject = false) {
let views = controller.view.children[0].children;
for (let i = 0; i < viewModel.items.length; i++) {
if (!isObject) {
expect(views[i].bindingContext.item).toBe(viewModel.items[i]);
} else {
expect(views[i].bindingContext.item.id).toBe(viewModel.items[i].id);
expect(views[i].bindingContext.item.text).toBe(viewModel.items[i].text);
}
let overrideContext = views[i].overrideContext;
expect(overrideContext.parentOverrideContext.bindingContext).toBe(viewModel);
expect(overrideContext.bindingContext).toBe(views[i].bindingContext);
let first = i === 0;
let last = i === viewModel.items.length - 1;
let even = i % 2 === 0;
expect(overrideContext.$index).toBe(i);
expect(overrideContext.$first).toBe(first);
expect(overrideContext.$last).toBe(last);
expect(overrideContext.$middle).toBe(!first && !last);
expect(overrideContext.$odd).toBe(!even);
expect(overrideContext.$even).toBe(even);
}
}
function validateState() {
// validate DOM
let expectedContent = viewModel.items.map(x => x === null || x === undefined ? '' : x.toString());
expect(selectContent(controller, 'div')).toEqual(expectedContent);
// validate contextual data
validateContextualData();
}
function validateObjectState() {
// validate DOM
let expectedContent = viewModel.items.map(x => x === null || x === undefined ? '' : x.text.toString());
expect(selectContent(controller, 'div')).toEqual(expectedContent);
// validate contextual data
validateContextualData(true);
}
describe('direct expression', () => {
beforeEach(() => {
let template = `<template><div repeat.for="item of items">\${item}</div></template>`;
viewModel = { items: ['a', 'b', 'c'] };
controller = createController(template, viewModel, viewsRequireLifecycle);
validateState();
});
afterEach(() => {
controller.unbind();
expect(hasSubscribers(viewModel, 'items')).toBe(false);
expect(hasArraySubscribers(viewModel.items)).toBe(false);
});
it('handles push', done => {
viewModel.items.push('d');
nq(() => validateState());
nq(() => viewModel.items.push('e', 'f'));
nq(() => validateState());
nq(() => viewModel.items.push());
nq(() => validateState());
nq(() => done());
});
it('handles pop', done => {
viewModel.items.pop();
nq(() => validateState());
nq(() => {
viewModel.items.pop();
viewModel.items.pop();
});
nq(() => validateState());
nq(() => viewModel.items.pop());
nq(() => validateState());
nq(() => done());
});
it('handles unshift', done => {
viewModel.items.unshift('z');
nq(() => validateState());
nq(() => viewModel.items.unshift('y', 'x'));
nq(() => validateState());
nq(() => viewModel.items.unshift());
nq(() => validateState());
nq(() => done());
});
it('handles shift', done => {
viewModel.items.shift();
nq(() => validateState());
nq(() => {
viewModel.items.shift();
viewModel.items.shift();
});
nq(() => validateState());
nq(() => viewModel.items.shift());
nq(() => validateState());
nq(() => done());
});
it('handles sort and reverse', done => {
viewModel.items.reverse();
nq(() => validateState());
nq(() => viewModel.items.sort());
nq(() => validateState());
nq(() => viewModel.items.reverse());
nq(() => validateState());
nq(() => viewModel.items.sort());
nq(() => validateState());
nq(() => done());
});
it('handles push and sort', done => {
let template = `<template><div repeat.for="item of items">\${item}</div></template>`;
viewModel = { items: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] };
controller = createController(template, viewModel, true);
validateState();
nq(() => {
viewModel.items.push('x');
viewModel.items.sort((a, b) => {/**/});
});
nq(() => validateState());
nq(() => done());
});
it('handles push and reverse', done => {
let template = `<template><div repeat.for="item of items">\${item}</div></template>`;
viewModel = { items: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] };
controller = createController(template, viewModel, true);
validateState();
nq(() => {
viewModel.items.push('x');
viewModel.items.reverse();
});
nq(() => validateState());
nq(() => done());
});
it('handles sort and sort', done => {
let template = `<template><div repeat.for="item of items">\${item}</div></template>`;
viewModel = { items: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] };
controller = createController(template, viewModel, true);
validateState();
nq(() => {
viewModel.items.sort((a, b) => a === b ? 0 : (a > b ? 1 : -1));
viewModel.items.sort((a, b) => a === b ? 0 : (a > b ? -1 : 1));
viewModel.items.sort((a, b) => a === b ? 0 : (a > b ? 1 : -1));
});
nq(() => validateState());
nq(() => done());
});
it('handles reverse and reverse', done => {
let template = `<template><div repeat.for="item of items">\${item}</div></template>`;
viewModel = { items: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'] };
controller = createController(template, viewModel, true);
validateState();
nq(() => {
viewModel.items.reverse();
viewModel.items.reverse();
});
nq(() => validateState());
nq(() => done());
});
it('handles splice', done => {
viewModel.items.splice(2, 1, 'x', 'y');
nq(() => validateState());
nq(() => done());
});
// todo: splice edge cases... negative, no-args, invalid args, etc
it('handles property change', done => {
let observer = observerLocator.getArrayObserver(viewModel.items);
viewModel.items = null;
nq(() => {
expect(select(controller, 'div').length).toBe(0);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => {
viewModel.items = ['x', 'y', 'z'];
observer = observerLocator.getArrayObserver(viewModel.items);
});
nq(() => {
validateState();
viewModel.items = undefined;
});
nq(() => {
expect(select(controller, 'div').length).toBe(0);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => viewModel.items = []);
nq(() => validateState());
nq(() => done());
});
});
describe('reuse elements', () => {
beforeEach(() => {
let template = `<template><div repeat.for="item of items">\${item}</div></template>`;
viewModel = { items: ['a', 'b', 'c'] };
controller = createController(template, viewModel, viewsRequireLifecycle);
validateState();
});
afterEach(() => {
controller.unbind();
expect(hasSubscribers(viewModel, 'items')).toBe(false);
expect(hasArraySubscribers(viewModel.items)).toBe(false);
});
it('handles untouched items (new Array instance)', done => {
let observer = observerLocator.getArrayObserver(viewModel.items);
let divs;
nq(() => {
divs = select(controller, 'div');
expect(observer.hasSubscribers()).toBe(true);
});
nq(() => {
viewModel.items = ['a', 'b', 'c'];
});
nq(() => validateState());
nq(() => {
const newDivs = select(controller, 'div');
expect(newDivs[0]).toBe(divs[0]);
expect(newDivs[1]).toBe(divs[1]);
expect(newDivs[2]).toBe(divs[2]);
expect(newDivs.length).toBe(3);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => done());
});
it('handles new item at the end', done => {
let observer = observerLocator.getArrayObserver(viewModel.items);
let divs;
nq(() => {
divs = select(controller, 'div');
expect(observer.hasSubscribers()).toBe(true);
});
nq(() => {
viewModel.items = ['a', 'b', 'c', 'new'];
});
nq(() => validateState());
nq(() => {
const newDivs = select(controller, 'div');
expect(newDivs[0]).toBe(divs[0]);
expect(newDivs[1]).toBe(divs[1]);
expect(newDivs[2]).toBe(divs[2]);
expect(newDivs[3].innerText).toBe('new');
expect(newDivs.length).toBe(4);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => done());
});
it('handles new item at the beginning', done => {
let observer = observerLocator.getArrayObserver(viewModel.items);
let divs;
nq(() => {
divs = select(controller, 'div');
expect(observer.hasSubscribers()).toBe(true);
});
nq(() => {
viewModel.items = ['new', 'a', 'b', 'c'];
});
nq(() => validateState());
nq(() => {
const newDivs = select(controller, 'div');
expect(newDivs[0].innerText).toBe('new');
if (viewsRequireLifecycle) {
expect(newDivs[1]).toBe(divs[0]);
expect(newDivs[2]).toBe(divs[1]);
expect(newDivs[3]).toBe(divs[2]);
} else {
expect(newDivs[1].innerText).toBe('a');
expect(newDivs[2].innerText).toBe('b');
expect(newDivs[3].innerText).toBe('c');
}
expect(newDivs.length).toBe(4);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => done());
});
it('handles new item in the middle', done => {
let observer = observerLocator.getArrayObserver(viewModel.items);
let divs;
nq(() => {
divs = select(controller, 'div');
expect(observer.hasSubscribers()).toBe(true);
});
nq(() => {
viewModel.items = ['a', 'b', 'new', 'c'];
});
nq(() => validateState());
nq(() => {
const newDivs = select(controller, 'div');
if (viewsRequireLifecycle) {
expect(newDivs[0]).toBe(divs[0]);
expect(newDivs[1]).toBe(divs[1]);
expect(newDivs[3]).toBe(divs[2]);
} else {
expect(newDivs[0].innerText).toBe('a');
expect(newDivs[1].innerText).toBe('b');
expect(newDivs[3].innerText).toBe('c');
}
expect(newDivs[2].innerText).toBe('new');
expect(newDivs.length).toBe(4);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => done());
});
it('handles removed item at the beginning', done => {
let observer = observerLocator.getArrayObserver(viewModel.items);
let divs;
nq(() => {
divs = select(controller, 'div');
expect(observer.hasSubscribers()).toBe(true);
});
nq(() => {
viewModel.items = ['b', 'c'];
});
nq(() => validateState());
nq(() => {
const newDivs = select(controller, 'div');
if (viewsRequireLifecycle) {
expect(newDivs[0]).toBe(divs[1]);
expect(newDivs[1]).toBe(divs[2]);
} else {
expect(newDivs[0].innerText).toBe('b');
expect(newDivs[1].innerText).toBe('c');
}
expect(newDivs.length).toBe(2);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => done());
});
it('handles removed item in the middle', done => {
let observer = observerLocator.getArrayObserver(viewModel.items);
let divs;
nq(() => {
divs = select(controller, 'div');
expect(observer.hasSubscribers()).toBe(true);
});
nq(() => {
viewModel.items = ['a', 'c'];
});
nq(() => validateState());
nq(() => {
const newDivs = select(controller, 'div');
if (viewsRequireLifecycle) {
expect(newDivs[0]).toBe(divs[0]);
expect(newDivs[1]).toBe(divs[2]);
} else {
expect(newDivs[0].innerText).toBe('a');
expect(newDivs[1].innerText).toBe('c');
}
expect(newDivs.length).toBe(2);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => done());
});
it('handles removed item at the end', done => {
let observer = observerLocator.getArrayObserver(viewModel.items);
let divs;
nq(() => {
divs = select(controller, 'div');
expect(observer.hasSubscribers()).toBe(true);
});
nq(() => {
viewModel.items = ['a', 'b'];
});
nq(() => validateState());
nq(() => {
const newDivs = select(controller, 'div');
if (viewsRequireLifecycle) {
expect(newDivs[0]).toBe(divs[0]);
expect(newDivs[1]).toBe(divs[1]);
} else {
expect(newDivs[0].innerText).toBe('a');
expect(newDivs[1].innerText).toBe('b');
}
expect(newDivs.length).toBe(2);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => done());
});
it('handles removed all items', done => {
let observer = observerLocator.getArrayObserver(viewModel.items);
let divs;
nq(() => {
divs = select(controller, 'div');
expect(observer.hasSubscribers()).toBe(true);
});
nq(() => {
viewModel.items = [];
});
nq(() => validateState());
nq(() => {
const newDivs = select(controller, 'div');
expect(newDivs.length).toBe(0);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => done());
});
it('handles moved items', done => {
let observer = observerLocator.getArrayObserver(viewModel.items);
let divs;
nq(() => {
divs = select(controller, 'div');
expect(observer.hasSubscribers()).toBe(true);
});
nq(() => {
viewModel.items = ['c', 'b', 'a'];
});
nq(() => validateState());
nq(() => {
const newDivs = select(controller, 'div');
if (viewsRequireLifecycle) {
expect(newDivs[0]).toBe(divs[2]);
expect(newDivs[1]).toBe(divs[1]);
expect(newDivs[2]).toBe(divs[0]);
} else {
expect(newDivs[0].innerText).toBe('c');
expect(newDivs[1].innerText).toBe('b');
expect(newDivs[2].innerText).toBe('a');
}
expect(newDivs.length).toBe(3);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => done());
});
it('handles untouched, moved, added and removed items at once', done => {
let observer = observerLocator.getArrayObserver(viewModel.items);
let divs;
nq(() => {
divs = select(controller, 'div');
expect(observer.hasSubscribers()).toBe(true);
});
nq(() => {
viewModel.items = ['c', 'b', 'new'];
});
nq(() => validateState());
nq(() => {
const newDivs = select(controller, 'div');
if (viewsRequireLifecycle) {
expect(newDivs[0]).toBe(divs[2]);
expect(newDivs[1]).toBe(divs[1]);
} else {
expect(newDivs[0].innerText).toBe('c');
expect(newDivs[1].innerText).toBe('b');
}
expect(newDivs[2].innerText).toBe('new');
expect(newDivs.length).toBe(3);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => done());
});
it('handles duplicate items at the end', done => {
let observer = observerLocator.getArrayObserver(viewModel.items);
let divs;
nq(() => {
divs = select(controller, 'div');
expect(observer.hasSubscribers()).toBe(true);
});
nq(() => {
viewModel.items = ['a', 'b', 'c', 'c'];
});
nq(() => validateState());
nq(() => {
const newDivs = select(controller, 'div');
if (viewsRequireLifecycle) {
expect(newDivs[0]).toBe(divs[0]);
expect(newDivs[1]).toBe(divs[1]);
expect(newDivs[2]).toBe(divs[2]);
} else {
expect(newDivs[0].innerText).toBe('a');
expect(newDivs[1].innerText).toBe('b');
expect(newDivs[2].innerText).toBe('c');
}
expect(newDivs[3].innerText).toBe('c');
expect(newDivs.length).toBe(4);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => {
viewModel.items = ['a', 'b', 'c'];
});
nq(() => {
const newDivs = select(controller, 'div');
expect(newDivs[0]).toBe(divs[0]);
expect(newDivs[1]).toBe(divs[1]);
expect(newDivs[2]).toBe(divs[2]);
expect(newDivs.length).toBe(3);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => validateState());
nq(() => done());
});
it('handles multiple duplicate items in various places', done => {
let observer = observerLocator.getArrayObserver(viewModel.items);
let divs;
nq(() => {
divs = select(controller, 'div');
expect(observer.hasSubscribers()).toBe(true);
});
nq(() => {
viewModel.items = ['a', 'a', 'b', 'b', 'c', 'c'];
});
nq(() => validateState());
nq(() => {
const newDivs = select(controller, 'div');
if (viewsRequireLifecycle) {
expect(newDivs[0]).toBe(divs[0]);
expect(newDivs[2]).toBe(divs[1]);
expect(newDivs[4]).toBe(divs[2]);
} else {
expect(newDivs[0].innerText).toBe('a');
expect(newDivs[2].innerText).toBe('b');
expect(newDivs[4].innerText).toBe('c');
}
expect(newDivs[1].innerText).toBe('a');
expect(newDivs[3].innerText).toBe('b');
expect(newDivs[5].innerText).toBe('c');
expect(newDivs.length).toBe(6);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => {
viewModel.items = ['a', 'b', 'c'];
});
nq(() => {
const newDivs = select(controller, 'div');
if (viewsRequireLifecycle) {
expect(newDivs[0]).toBe(divs[0]);
expect(newDivs[1]).toBe(divs[1]);
expect(newDivs[2]).toBe(divs[2]);
} else {
// reuse old divs with new values
expect(newDivs[0]).toBe(divs[0]);
expect(newDivs[1]).toBe(divs[1]);
expect(newDivs[2]).toBe(divs[2]);
expect(newDivs[0].innerText).toBe('a');
expect(newDivs[1].innerText).toBe('b');
expect(newDivs[2].innerText).toBe('c');
}
expect(newDivs.length).toBe(3);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => validateState());
nq(() => done());
});
it('handles adding multiple items when none existed', done => {
let observer;
nq(() => {
viewModel.items = [];
});
nq(() => validateState());
nq(() => {
viewModel.items = ['a', 'b', 'c'];
observer = observerLocator.getArrayObserver(viewModel.items);
});
nq(() => {
const newDivs = select(controller, 'div');
expect(newDivs[0].innerText).toBe('a');
expect(newDivs[1].innerText).toBe('b');
expect(newDivs[2].innerText).toBe('c');
expect(newDivs.length).toBe(3);
expect(observer.hasSubscribers()).toBe(true);
});
nq(() => done());
});
});
describe('reuse elements with a matcher', () => {
beforeEach(() => {
let template = `<template><div repeat.for="item of items" matcher.bind="matcher">\${item.text}</div></template>`;
viewModel = {
items: [{ id: 0, text: 'a' }, { id: 1, text: 'b' }, { id: 2, text: 'c' }],
matcher: (a, b) => a.id === b.id
};
controller = createController(template, viewModel, viewsRequireLifecycle);
validateObjectState();
});
afterEach(() => {
controller.unbind();
expect(hasSubscribers(viewModel, 'items')).toBe(false);
expect(hasArraySubscribers(viewModel.items)).toBe(false);
});
it('handles new items, same content', done => {
let observer = observerLocator.getArrayObserver(viewModel.items);
let divs;
nq(() => {
divs = select(controller, 'div');
});
nq(() => {
viewModel.items = [{ id: 0, text: 'a' }, { id: 1, text: 'b' }, { id: 2, text: 'c' }];
});
nq(() => validateObjectState());
nq(() => {
const newDivs = select(controller, 'div');
if (viewsRequireLifecycle) {
expect(newDivs[0]).toBe(divs[0]);
expect(newDivs[1]).toBe(divs[1]);
expect(newDivs[2]).toBe(divs[2]);
} else {
expect(newDivs[0].innerText).toBe('a');
expect(newDivs[1].innerText).toBe('b');
expect(newDivs[2].innerText).toBe('c');
}
expect(newDivs.length).toBe(3);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => done());
});
it('handles new items, different content', done => {
let observer = observerLocator.getArrayObserver(viewModel.items);
let divs;
nq(() => {
divs = select(controller, 'div');
});
nq(() => {
viewModel.items = [{ id: 0, text: 'a' }, { id: 1, text: 'c' }, { id: 2, text: 'b' }];
});
nq(() => validateObjectState());
nq(() => {
const newDivs = select(controller, 'div');
expect(newDivs[0]).toBe(divs[0]);
expect(newDivs[1]).toBe(divs[1]);
expect(newDivs[2]).toBe(divs[2]);
expect(newDivs[0].innerText).toBe('a');
expect(newDivs[1].innerText).toBe('c');
expect(newDivs[2].innerText).toBe('b');
expect(newDivs.length).toBe(3);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => done());
});
it('handles new items shifted, same content', done => {
let observer = observerLocator.getArrayObserver(viewModel.items);
let divs;
nq(() => {
divs = select(controller, 'div');
});
nq(() => {
viewModel.items = [{ id: 1, text: 'b' }, { id: 2, text: 'c' }, { id: 0, text: 'a' }];
});
nq(() => validateObjectState());
nq(() => {
const newDivs = select(controller, 'div');
if (viewsRequireLifecycle) {
expect(newDivs[0]).toBe(divs[1]);
expect(newDivs[1]).toBe(divs[2]);
expect(newDivs[2]).toBe(divs[0]);
} else {
expect(newDivs[0]).toBe(divs[0]);
expect(newDivs[1]).toBe(divs[1]);
expect(newDivs[2]).toBe(divs[2]);
}
expect(newDivs[0].innerText).toBe('b');
expect(newDivs[1].innerText).toBe('c');
expect(newDivs[2].innerText).toBe('a');
expect(newDivs.length).toBe(3);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => done());
});
it('handles new items shifted with new content', done => {
let observer = observerLocator.getArrayObserver(viewModel.items);
let divs;
nq(() => {
divs = select(controller, 'div');
});
nq(() => {
viewModel.items = [{ id: 1, text: 'new' }, { id: 2, text: 'new' }, { id: 0, text: 'new' }];
});
nq(() => validateObjectState());
nq(() => {
const newDivs = select(controller, 'div');
if (viewsRequireLifecycle) {
expect(newDivs[0]).toBe(divs[1]);
expect(newDivs[1]).toBe(divs[2]);
expect(newDivs[2]).toBe(divs[0]);
} else {
expect(newDivs[0]).toBe(divs[0]);
expect(newDivs[1]).toBe(divs[1]);
expect(newDivs[2]).toBe(divs[2]);
}
expect(newDivs[0].innerText).toBe('new');
expect(newDivs[1].innerText).toBe('new');
expect(newDivs[2].innerText).toBe('new');
expect(newDivs.length).toBe(3);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => done());
});
});
describe('with converter that returns original instance', () => {
beforeEach(() => {
let template = `<template><div repeat.for="item of items | noopValueConverter">\${item}</div></template>`;
viewModel = { items: ['a', 'b', 'c'] };
controller = createController(template, viewModel, viewsRequireLifecycle);
validateState();
});
afterEach(() => {
controller.unbind();
expect(hasSubscribers(viewModel, 'items')).toBe(false);
expect(hasArraySubscribers(viewModel.items)).toBe(false);
});
it('handles mutation', done => {
viewModel.items.push('d');
nq(() => validateState());
nq(() => viewModel.items.pop());
nq(() => validateState());
nq(() => viewModel.items.reverse());
nq(() => validateState());
nq(() => done());
});
it('handles property change', done => {
let observer = observerLocator.getArrayObserver(viewModel.items);
viewModel.items = null;
nq(() => {
expect(select(controller, 'div').length).toBe(0);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => {
viewModel.items = ['x', 'y', 'z'];
observer = observerLocator.getArrayObserver(viewModel.items);
});
nq(() => {
validateState();
viewModel.items = undefined;
});
nq(() => {
expect(select(controller, 'div').length).toBe(0);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => viewModel.items = []);
nq(() => validateState());
nq(() => done());
});
});
describe('with converter and behavior', () => {
beforeEach(() => {
let template = `<template><div repeat.for="item of items | slice & noopBehavior">\${item}</div></template>`;
viewModel = { items: ['a', 'b', 'c'] };
controller = createController(template, viewModel, viewsRequireLifecycle);
validateState();
});
afterEach(() => {
controller.unbind();
expect(hasSubscribers(viewModel, 'items')).toBe(false);
expect(hasArraySubscribers(viewModel.items)).toBe(false);
});
it('handles mutation', done => {
viewModel.items.push('d');
nq(() => validateState());
nq(() => viewModel.items.pop());
nq(() => validateState());
nq(() => viewModel.items.reverse());
nq(() => validateState());
nq(() => done());
});
it('handles property change', done => {
let observer = observerLocator.getArrayObserver(viewModel.items);
viewModel.items = null;
nq(() => {
expect(select(controller, 'div').length).toBe(0);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => {
viewModel.items = ['x', 'y', 'z'];
observer = observerLocator.getArrayObserver(viewModel.items);
});
nq(() => {
validateState();
viewModel.items = undefined;
});
nq(() => {
expect(select(controller, 'div').length).toBe(0);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => viewModel.items = []);
nq(() => validateState());
nq(() => done());
});
});
describe('with converter that changes type', () => {
beforeEach(() => {
let template = `<template><div repeat.for="item of items | toLength">\${item}</div></template>`;
viewModel = { items: [0, 1, 2] };
controller = createController(template, viewModel, viewsRequireLifecycle);
validateState();
});
afterEach(() => {
controller.unbind();
expect(hasSubscribers(viewModel, 'items')).toBe(false);
expect(hasArraySubscribers(viewModel.items)).toBe(false);
});
it('handles mutation', done => {
viewModel.items.push(3);
nq(() => validateState());
nq(() => viewModel.items.pop());
nq(() => validateState());
nq(() => done());
});
it('handles property change', done => {
let observer = observerLocator.getArrayObserver(viewModel.items);
viewModel.items = null;
nq(() => {
expect(select(controller, 'div').length).toBe(0);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => {
viewModel.items = [0, 1, 2];
observer = observerLocator.getArrayObserver(viewModel.items);
});
nq(() => {
validateState();
viewModel.items = undefined;
});
nq(() => {
expect(select(controller, 'div').length).toBe(0);
expect(observer.hasSubscribers()).toBe(false);
});
nq(() => viewModel.items = []);
nq(() => validateState());
nq(() => done());
});
});
it('oneTime does not observe changes', () => {
let template = `<template><div repeat.for="item of items & oneTime">\${item}</div></template>`;
viewModel = { items: [0, 1, 2] };
controller = createController(template, viewModel, viewsRequireLifecycle);
validateState();
expect(hasSubscribers(viewModel, 'items')).toBe(false);
expect(hasArraySubscribers(viewModel.items)).toBe(false);
controller.unbind();
});
}
describe('Repeat array (pure)', describeArrayTests.bind(this, true));
describe('Repeat array (not pure)', describeArrayTests.bind(this, false));
xdescribe('instancesChanges and instancesMutated together', () => {
it('handles together correctly', () => {
let template = `<template><section if.bind='show'><div repeat.for="item of items">\${item}</div></section></template>`;
let viewModel = {
show: false,
// items: [{ a: 'a' }, { a: 'b' }]
items: null
};
let controller = createController(template, viewModel, false);
let taskQueue = container.get(TaskQueue);
taskQueue.queueMicroTask(() => {
viewModel.show = true;
viewModel.items = ['a', 'b', 'c', 'd'];
viewModel.items.splice(1, 1, { a: 'bb' });
viewModel.items.push({ a: 'aa' });
});
taskQueue.flushMicroTaskQueue();
taskQueue.queueMicroTask(() => {
console.log(host.children.length, select(controller, 'div').length);
});
});
});
describe('Repeat map [k, v]', () => {
let viewModel, controller;
let obj = {};
function validateState() {
// validate DOM
let expectedContent = [];
if (viewModel.items !== null && viewModel.items !== undefined) {
const toString = x => x === null || x === undefined ? '' : x.toString();
expectedContent = Array.from(viewModel.items.entries()).map(([k, v]) => `${toString(k)},${toString(v)}`);
}
expect(selectContent(controller, 'div')).toEqual(expectedContent);
// validate contextual data
let views = controller.view.children[0].children;
let items = viewModel.items ? Array.from(viewModel.items.entries()) : [];
for (let i = 0; i < items.length; i++) {
expect(views[i].bindingContext.k).toBe(items[i][0]);
expect(views[i].bindingContext.v).toBe(items[i][1]);
let overrideContext = views[i].overrideContext;
expect(overrideContext.parentOverrideContext.bindingContext).toBe(viewModel);
expect(overrideContext.bindingContext).toBe(views[i].bindingContext);
let first = i === 0;
let last = i === items.length - 1;
let even = i % 2 === 0;
expect(overrideContext.$index).toBe(i);
expect(overrideContext.$first).toBe(first);
expect(overrideContext.$last).toBe(last);
expect(overrideContext.$middle).toBe(!first && !last);
expect(overrideContext.$odd).toBe(!even);
expect(overrideContext.$even).toBe(even);
}
}
beforeEach(() => {
let template = `<template><div repeat.for="[k, v] of items">\${k},\${v}</div></template>`;
viewModel = { items: new Map<any, any>([
['a', 'b'],
['test', 0],
[obj, null],
['hello world', undefined],
[6, 7]
]) };
controller = createController(template, viewModel);
validateState();
});
afterEach(() => {
controller.unbind();
expect(hasSubscribers(viewModel, 'items')).toBe(false);
expect(hasMapSubscribers(viewModel.items)).toBe(false);
});
it('handles set', done => {
viewModel.items.set('x', 'y');
nq(() => validateState());
nq(() => viewModel.items.set(999, 24234));
nq(() => validateState());
nq(() => viewModel.items.set('a', null));
nq(() => validateState());
nq(() => done());
});
it('handles delete', done => {
viewModel.items.delete(6);
nq(() => validateState());
nq(() => viewModel.items.delete()); // no args
nq(() => validateState());
nq(() => viewModel.items.delete('a'));
nq(() => validateState());
nq(() => viewModel.items.delete(null));
nq(() => validateState());
nq(() => viewModel.items.delete(undefined));
nq(() => validateState());
nq(() => viewModel.items.delete(obj));
nq(() => validateState());
nq(() => done());
});
it('handles clear', done => {
viewModel.items.clear();
nq(() => validateState());
nq(() => viewModel.items.clear());
nq(() => validateState());
nq(() => done());
});
it('handles property change', done => {
viewModel.items = null;
nq(() => validateState());
nq(() => viewModel.items = new Map([['a', 'b']]));
nq(() => validateState());
nq(() => viewModel.items = undefined);
nq(() => validateState());
nq(() => viewModel.items = new Map([['a', 'b'], ['x', 'y']]));
nq(() => validateState());
nq(() => done());
});
it('oneTime does not observe changes', () => {
let template = `<template><div repeat.for="[k, v] of items & oneTime">\${k},\${v}</div></template>`;
viewModel = { items: new Map<any, any>([
['a', 'b'],
['test', 0],
[obj, null],
['hello world', undefined],
[6, 7]
]) };
controller = createController(template, viewModel);
validateState();
expect(hasMapSubscribers(viewModel.items)).toBe(false);
});
});
describe('Repeat set', () => {
let viewModel, controller;
let obj = {};
function validateState() {
// validate DOM
let expectedContent = [];
if (viewModel.items !== null && viewModel.items !== undefined) {
const toString = x => x === null || x === undefined ? '' : x.toString();
expectedContent = Array.from(viewModel.items.values()).map(item => `${toString(item)}`);
// let expectedContent = viewModel.items.map(x => x === null || x === undefined ? '' : x.toString());
}
expect(selectContent(controller, 'div')).toEqual(expectedContent);
// validate contextual data
let views = controller.view.children[0].children;
let items = viewModel.items ? Array.from(viewModel.items.entries()) : [];
for (let i = 0; i < items.length; i++) {
expect(views[i].bindingContext.item).toBe(items[i][0]);
let overrideContext = views[i].overrideContext;
expect(overrideContext.parentOverrideContext.bindingContext).toBe(viewModel);
expect(overrideContext.bindingContext).toBe(views[i].bindingContext);
let first = i === 0;
let last = i === items.length - 1;
let even = i % 2 === 0;
expect(overrideContext.$index).toBe(i);
expect(overrideContext.$first).toBe(first);
expect(overrideContext.$last).toBe(last);
expect(overrideContext.$middle).toBe(!first && !last);
expect(overrideContext.$odd).toBe(!even);
expect(overrideContext.$even).toBe(even);
}
}
beforeEach(() => {
let template = `<template><div repeat.for="item of items">\${item}</div></template>`;
viewModel = { items: new Set(['a', 'b', 0, null, obj, undefined, 7]) };
// viewModel = { items: new Map([['a', 'b'], ['test', 0], [obj, null], ['hello world', undefined], [6, 7]]) };
controller = createController(template, viewModel);
validateState();
});
afterEach(() => {
controller.unbind();
expect(hasSubscribers(viewModel, 'items')).toBe(false);
expect(hasMapSubscribers(viewModel.items)).toBe(false);
});
it('can render set', done => {
nq(() => validateState());
nq(() => done());
});
it('handles add', done => {
viewModel.items.add('x');
nq(() => validateState());
nq(() => viewModel.items.add(999));
nq(() => validateState());
nq(() => viewModel.items.add('a'));
nq(() => validateState());
nq(() => done());
});
it('handles delete', done => {
viewModel.items.delete(6);
nq(() => validateState());
nq(() => viewModel.items.delete()); // no args
nq(() => validateState());
nq(() => viewModel.items.delete('a'));
nq(() => validateState());
nq(() => viewModel.items.delete(null));
nq(() => validateState());
nq(() => viewModel.items.delete(undefined));
nq(() => validateState());
nq(() => viewModel.items.delete(obj));
nq(() => validateState());
nq(() => done());
});
it('handles clear', done => {
viewModel.items.clear();
nq(() => validateState());
nq(() => viewModel.items.clear());
nq(() => validateState());
nq(() => done());
});
it('handles property change', done => {
viewModel.items = null;
nq(() => validateState());
nq(() => viewModel.items = new Set(['a', 'b']));
nq(() => validateState());
nq(() => viewModel.items = undefined);
nq(() => validateState());
nq(() => viewModel.items = new Set(['x', 'y']));
nq(() => validateState());
nq(() => done());
});
it('oneTime does not observe changes', () => {
let template = `<template><div repeat.for="item of items & oneTime">\${item}</div></template>`;
viewModel = { items: new Set(['a', 'b', 0, null, obj, undefined, 7]) };
controller = createController(template, viewModel);
validateState();
expect(hasSetSubscribers(viewModel.items)).toBe(false);
});
});
describe('Repeat number', () => {
let viewModel, controller;
function validateState() {
// validate DOM
let expectedContent = [];
if (viewModel.items > 0) {
for (let i = 0; i < viewModel.items; i++) {
expectedContent.push(i.toString());
}
}
expect(selectContent(controller, 'div')).toEqual(expectedContent);
// validate contextual data
let views = controller.view.children[0].children;
for (let i = 0; i < viewModel.items; i++) {
expect(views[i].bindingContext.item).toBe(i);
let overrideContext = views[i].overrideContext;
expect(overrideContext.parentOverrideContext.bindingContext).toBe(viewModel);
expect(overrideContext.bindingContext).toBe(views[i].bindingContext);
let first = i === 0;
let last = i === viewModel.items - 1;
let even = i % 2 === 0;
expect(overrideContext.$index).toBe(i);
expect(overrideContext.$first).toBe(first);
expect(overrideContext.$last).toBe(last);
expect(overrideContext.$middle).toBe(!first && !last);
expect(overrideContext.$odd).toBe(!even);
expect(overrideContext.$even).toBe(even);
}
}
beforeEach(() => {
let template = `<template><div repeat.for="item of items">\${item}</div></template>`;
viewModel = { items: 10 };
controller = createController(template, viewModel);
validateState();
});
afterEach(() => {
controller.unbind();
expect(hasSubscribers(viewModel, 'items')).toBe(false);
});
it('handles property change', done => {
viewModel.items = 5;
nq(() => validateState());
nq(() => viewModel.items = 12);
nq(() => validateState());
nq(() => done());
});
it('oneTime does not observe changes', () => {
let template = `<template><div repeat.for="item of items & oneTime">\${item}</div></template>`;
viewModel = { items: 3 };
controller = createController(template, viewModel);
validateState();
expect(hasSubscribers(viewModel, 'items')).toBe(false);
controller.unbind();
});
});
describe('Repeat object converted to collection', () => {
let viewModel, controller;
});
describe('analyze-view-factory', () => {
it('analyzes repeat', () => {
let template = `<template><div repeat.for="item of items">\${item}</div></template>`,
viewFactory = viewCompiler.compile(template);
expect(viewsRequireLifecycle(viewFactory)).toBe(false);
});
it('analyzes nested repeat', () => {
let template = `<template><div repeat.for="x of y"><div repeat.for="a of b"></div></div></template>`,
viewFactory = viewCompiler.compile(template);
expect(viewsRequireLifecycle(viewFactory)).toBe(false);
});
it('analyzes nested repeat 2', () => {
let template = `<template><div repeat.for="x of y"><div repeat.for="a of b"><div repeat.for="foo of bar"></div></div></div></template>`,
viewFactory = viewCompiler.compile(template);
expect(viewsRequireLifecycle(viewFactory)).toBe(false);
});
it('analyzes repeat with compose', () => {
let template = `<template><compose repeat.for="item of items"></compose></template>`,
viewFactory = viewCompiler.compile(template);
expect(viewsRequireLifecycle(viewFactory)).toBe(true);
template = `<template><div repeat.for="item of items"><compose></compose></div></template>`,
viewFactory = viewCompiler.compile(template);
expect(viewsRequireLifecycle(viewFactory)).toBe(true);
});
}); | the_stack |
import type { NextFunction } from 'connect';
import type http from 'http';
import type { AstroConfig, ManifestData, RouteCache, RouteData } from '../../@types/astro';
import type { LogOptions } from '../logger';
import type { HmrContext, ModuleNode } from '../vite';
import path from 'path';
import { fileURLToPath } from 'url';
import { promisify } from 'util';
import connect from 'connect';
import mime from 'mime';
import { polyfill } from '@astropub/webapi';
import { performance } from 'perf_hooks';
import stripAnsi from 'strip-ansi';
import vite from '../vite.js';
import { defaultLogOptions, error, info } from '../logger.js';
import { ssr } from '../ssr/index.js';
import { STYLE_EXTENSIONS } from '../ssr/css.js';
import { collectResources } from '../ssr/html.js';
import { createRouteManifest, matchRoute } from '../ssr/routing.js';
import { createVite } from '../create-vite.js';
import * as msg from './messages.js';
import notFoundTemplate, { subpathNotUsedTemplate } from './template/4xx.js';
import serverErrorTemplate from './template/5xx.js';
export interface DevOptions {
logging: LogOptions;
}
export interface DevServer {
hostname: string;
port: number;
server: connect.Server;
stop(): Promise<void>;
}
/** `astro dev` */
export default async function dev(config: AstroConfig, options: DevOptions = { logging: defaultLogOptions }): Promise<DevServer> {
// polyfill WebAPIs to globalThis for Node v12, Node v14, and Node v16
polyfill(globalThis, {
exclude: 'window document',
});
// start dev server
const server = new AstroDevServer(config, options);
await server.start();
// attempt shutdown
process.on('SIGTERM', () => server.stop());
return {
hostname: server.hostname,
port: server.port,
server: server.app,
stop: () => server.stop(),
};
}
/** Dev server */
export class AstroDevServer {
app: connect.Server = connect();
config: AstroConfig;
devRoot: string;
hostname: string;
httpServer: http.Server | undefined;
logging: LogOptions;
manifest: ManifestData;
mostRecentRoute?: RouteData;
origin: string;
port: number;
routeCache: RouteCache = {};
site: URL | undefined;
url: URL;
viteServer: vite.ViteDevServer | undefined;
constructor(config: AstroConfig, options: DevOptions) {
this.config = config;
this.hostname = config.devOptions.hostname || 'localhost';
this.logging = options.logging;
this.port = config.devOptions.port;
this.origin = `http://${this.hostname}:${this.port}`;
this.site = config.buildOptions.site ? new URL(config.buildOptions.site) : undefined;
this.devRoot = this.site ? this.site.pathname : '/';
this.url = new URL(this.devRoot, this.origin);
this.manifest = createRouteManifest({ config }, this.logging);
}
async start() {
const devStart = performance.now();
// Setup the dev server and connect it to Vite (via middleware)
this.viteServer = await this.createViteServer();
this.app.use(this.viteServer.middlewares);
this.app.use((req, res, next) => this.handleRequest(req, res, next));
this.app.use((req, res, next) => this.renderError(req, res, next));
// Listen on port (and retry if taken)
await this.listen(devStart);
}
async stop() {
if (this.viteServer) {
await this.viteServer.close();
}
if (this.httpServer) {
await promisify(this.httpServer.close.bind(this.httpServer))();
}
}
public async handleHotUpdate({ file, modules }: HmrContext): Promise<void | ModuleNode[]> {
const { viteServer } = this;
if (!viteServer) throw new Error(`AstroDevServer.start() not called`);
for (const module of modules) {
viteServer.moduleGraph.invalidateModule(module);
}
const route = this.mostRecentRoute;
const [pathname, search = undefined] = (route?.pathname ?? '/').split('?');
if (!route) {
viteServer.ws.send({
type: 'full-reload',
});
return [];
}
try {
const filePath = new URL(`./${route.component}`, this.config.projectRoot);
// try to update the most recent route
const html = await ssr({
astroConfig: this.config,
filePath,
logging: this.logging,
mode: 'development',
origin: this.origin,
pathname,
route,
routeCache: this.routeCache,
viteServer,
});
// collect style tags to be reloaded (needed for Tailwind HMR, etc.)
let invalidatedModules: vite.ModuleNode[] = [];
await Promise.all(
collectResources(html)
.filter(({ href }) => {
if (!href) return false;
const ext = path.extname(href);
return STYLE_EXTENSIONS.has(ext);
})
.map(async ({ href }) => {
const viteModule =
viteServer.moduleGraph.getModuleById(`${href}?direct`) ||
(await viteServer.moduleGraph.getModuleByUrl(`${href}?direct`)) ||
viteServer.moduleGraph.getModuleById(href) ||
(await viteServer.moduleGraph.getModuleByUrl(href));
if (viteModule) {
invalidatedModules.push(viteModule);
viteServer.moduleGraph.invalidateModule(viteModule);
}
})
);
// TODO: log update
viteServer.ws.send({
type: 'custom',
event: 'astro:reload',
data: { html },
});
for (const viteModule of invalidatedModules) {
// Note: from the time viteServer.moduleGraph.invalidateModule() is called above until now, CSS
// is building in the background. For things like Tailwind, this can take some time. If the
// CSS is still processing by the time HMR fires, we’ll end up with stale styles on the page.
// TODO: fix this hack by figuring out how to add these styles to the { modules } above
setTimeout(() => {
viteServer.ws.send({
type: 'update',
updates: [
{
type: viteModule.type === 'js' ? 'js-update' : 'css-update',
path: viteModule.id || viteModule.file || viteModule.url,
acceptedPath: viteModule.url,
timestamp: Date.now(),
},
],
});
}, 150);
}
return [];
} catch (e) {
const err = e as Error;
// eslint-disable-next-line
console.error(err.stack);
viteServer.ws.send({
type: 'full-reload',
});
return [];
}
}
/** Expose dev server to this.port */
public listen(devStart: number): Promise<void> {
let showedPortTakenMsg = false;
return new Promise<void>((resolve, reject) => {
const appListen = () => {
this.httpServer = this.app.listen(this.port, this.hostname, () => {
info(this.logging, 'astro', msg.devStart({ startupTime: performance.now() - devStart }));
info(this.logging, 'astro', msg.devHost({ host: `http://${this.hostname}:${this.port}${this.devRoot}` }));
resolve();
});
this.httpServer?.on('error', onError);
};
const onError = (err: NodeJS.ErrnoException) => {
if (err.code && err.code === 'EADDRINUSE') {
if (!showedPortTakenMsg) {
info(this.logging, 'astro', msg.portInUse({ port: this.port }));
showedPortTakenMsg = true; // only print this once
}
this.port++;
return appListen(); // retry
} else {
error(this.logging, 'astro', err.stack);
this.httpServer?.removeListener('error', onError);
reject(err); // reject
}
};
appListen();
});
}
private async createViteServer() {
const viteConfig = await createVite(
vite.mergeConfig(
{
mode: 'development',
server: {
middlewareMode: 'ssr',
host: this.hostname,
},
},
this.config.vite || {}
),
{ astroConfig: this.config, logging: this.logging, devServer: this }
);
const viteServer = await vite.createServer(viteConfig);
const pagesDirectory = fileURLToPath(this.config.pages);
viteServer.watcher.on('add', (file) => {
// Only rebuild routes if new file is a page.
if (!file.startsWith(pagesDirectory)) {
return;
}
this.routeCache = {};
this.manifest = createRouteManifest({ config: this.config }, this.logging);
});
viteServer.watcher.on('unlink', (file) => {
// Only rebuild routes if deleted file is a page.
if (!file.startsWith(pagesDirectory)) {
return;
}
this.routeCache = {};
this.manifest = createRouteManifest({ config: this.config }, this.logging);
});
viteServer.watcher.on('change', () => {
// No need to rebuild routes on file content changes.
// However, we DO want to clear the cache in case
// the change caused a getStaticPaths() return to change.
this.routeCache = {};
});
return viteServer;
}
/** The primary router (runs before Vite, in case we need to modify or intercept anything) */
private async handleRequest(req: http.IncomingMessage, res: http.ServerResponse, next: NextFunction) {
if (!this.viteServer) throw new Error(`AstroDevServer.start() not called`);
let [pathname, search = undefined] = (req.url || '/').split('?'); // original request
const reqStart = performance.now();
let filePath: URL | undefined;
try {
let routePathname: string = pathname;
// If using a subpath, ensure that the user has included the pathname
// such as /blog in the URL.
if (this.devRoot !== '/') {
if (pathname.startsWith(this.devRoot)) {
// This includes the subpath, so strip off the subpath so that
// matchRoute finds this route.
routePathname = pathname.substr(this.devRoot.length) || '';
if (!routePathname.startsWith('/')) {
routePathname = '/' + routePathname;
}
} else {
// Not using the subpath, so forward to Vite's middleware
next();
return;
}
}
const route = matchRoute(routePathname, this.manifest);
// 404: continue to Vite
if (!route) {
// Send through, stripping off the `/blog/` part so that Vite matches it.
const newPathname = routePathname.startsWith('/') ? routePathname : '/' + routePathname;
req.url = newPathname;
next();
return;
}
// handle .astro and .md pages
filePath = new URL(`./${route.component}`, this.config.projectRoot);
const html = await ssr({
astroConfig: this.config,
filePath,
logging: this.logging,
mode: 'development',
origin: this.origin,
pathname: routePathname,
route,
routeCache: this.routeCache,
viteServer: this.viteServer,
});
this.mostRecentRoute = route;
info(this.logging, 'astro', msg.req({ url: pathname, statusCode: 200, reqTime: performance.now() - reqStart }));
res.writeHead(200, {
'Content-Type': mime.getType('.html') as string,
'Content-Length': Buffer.byteLength(html, 'utf8'),
});
res.write(html);
res.end();
} catch (err: any) {
const statusCode = 500;
await this.viteServer.moduleGraph.invalidateAll();
this.viteServer.ws.send({ type: 'error', err });
let html = serverErrorTemplate({
statusCode,
title: 'Internal Error',
tabTitle: '500: Error',
message: stripAnsi(err.message),
url: err.url || undefined,
stack: stripAnsi(err.stack),
});
html = await this.viteServer.transformIndexHtml(pathname, html, pathname);
info(this.logging, 'astro', msg.req({ url: pathname, statusCode: 500, reqTime: performance.now() - reqStart }));
res.writeHead(statusCode, {
'Content-Type': mime.getType('.html') as string,
'Content-Length': Buffer.byteLength(html, 'utf8'),
});
res.write(html);
res.end();
}
}
/** Render error page */
private async renderError(req: http.IncomingMessage, res: http.ServerResponse, next: NextFunction) {
if (!this.viteServer) throw new Error(`AstroDevServer.start() not called`);
const pathname = req.url || '/';
const reqStart = performance.now();
let html = '';
const statusCode = 404;
// attempt to load user-given page
const relPages = this.config.pages.href.replace(this.config.projectRoot.href, '');
const userDefined404 = this.manifest.routes.find((route) => route.component === relPages + '404.astro');
if (userDefined404) {
html = await ssr({
astroConfig: this.config,
filePath: new URL(`./${userDefined404.component}`, this.config.projectRoot),
logging: this.logging,
mode: 'development',
pathname: `/${userDefined404.component}`,
origin: this.origin,
routeCache: this.routeCache,
viteServer: this.viteServer,
});
}
// if not found, fall back to default template
else {
if (pathname === '/' && !pathname.startsWith(this.devRoot)) {
html = subpathNotUsedTemplate(this.devRoot, pathname);
} else {
html = notFoundTemplate({ statusCode, title: 'Not found', tabTitle: '404: Not Found', pathname });
}
}
info(this.logging, 'astro', msg.req({ url: pathname, statusCode, reqTime: performance.now() - reqStart }));
res.writeHead(statusCode, {
'Content-Type': mime.getType('.html') as string,
'Content-Length': Buffer.byteLength(html, 'utf8'),
});
res.write(html);
res.end();
}
} | the_stack |
import { Injectable } from '@angular/core';
// import { AngularFireAuth } from '@angular/fire/auth';
// firebase
import * as firebase from 'firebase/app';
import 'firebase/auth';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { ReplaySubject } from 'rxjs/ReplaySubject';
import { environment } from '../../environments/environment';
import { Http, Headers, RequestOptions } from '@angular/http';
import { Globals } from '../utils/globals';
import { supports_html5_storage, supports_html5_session } from '../utils/utils';
import { AppConfigService } from './app-config.service';
import { StorageService } from './storage.service';
import { componentRefresh } from '@angular/core/src/render3/instructions';
@Injectable()
export class AuthService_old {
// public user: Observable<firebase.User>;
// public user: firebase.User;
public user: any;
private token: string;
obsLoggedUser = new ReplaySubject<number>(1);
unsubscribe: any;
API_URL: string;
constructor(
// private firebaseAuth: AngularFireAuth,
public http: Http,
public g: Globals,
public appConfigService: AppConfigService,
private storageService: StorageService,
) {
this.API_URL = appConfigService.getConfig().apiUrl;
}
initialize() {
const tiledeskTokenTEMP = this.storageService.getItem('tiledeskToken');
this.g.wdLog([' ---------------- AuthService initialize ---------------- ']);
/** SIGIN WITH JWT CUSTOM TOKEN */
// aggiungo nel local storage e mi autentico
// this.g.wdLog(['controllo se è stato passato un token: ', this.g.jwt]);
// if (this.g.jwt) {
// // mi loggo con custom token passato nell'url
// this.g.wdLog([' ---------------- mi loggo con custom token passato nell url ---------------- ']);
// this.authenticationWithCustomToken(this.g.jwt);
// this.g.tiledeskToken = this.g.jwt;
// } else
if (tiledeskTokenTEMP && tiledeskTokenTEMP !== undefined) {
this.g.tiledeskToken = tiledeskTokenTEMP;
// SONO già loggato
this.g.wdLog([' ---------------- SONO già loggato ---------------- ']);
this.authenticationWithCustomToken(this.g.tiledeskToken);
} else {
// NON sono loggato;
this.g.wdLog([' ---------------- NON sono loggato ---------------- ']);
this.obsLoggedUser.next(0);
}
}
// onAuthStateChanged() {
// const that = this;
// that.g.wdLog(['-------------------- >>>> onAuthStateChanged <<<< ------------------------']);
// // https://stackoverflow.com/questions/37370224/firebase-stop-listening-onauthstatechanged
// this.unsubscribe = firebase.auth().onAuthStateChanged(user => {
// if (!user) {
// that.g.wdLog(['NO CURRENT USER PASSO NULL']);
// if (that.g.isLogout === false ) {
// that.obsLoggedUser.next(0);
// }
// } else {
// that.g.wdLog(['that.environment.shemaVersion', environment.shemaVersion]);
// that.g.wdLog(['shemaVersion', that.storageService.getItemWithoutProjectId('shemaVersion')]);
// const tiledeskTokenTEMP = that.storageService.getItem('tiledeskToken');
// const shemaVersionTEMP = that.storageService.getItemWithoutProjectId('shemaVersion');
// if (environment.shemaVersion !== shemaVersionTEMP) {
// that.signOut(0);
// } else if (!tiledeskTokenTEMP || tiledeskTokenTEMP === undefined) {
// that.signOut(0);
// } else {
// that.g.wdLog(['PASSO CURRENT USER']);
// that.user = firebase.auth().currentUser;
// that.g.wdLog(['onAuthStateChanged']);
// that.getIdToken();
// that.obsLoggedUser.next(firebase.auth().currentUser);
// }
// }
// });
// }
getCurrentUser() {
this.g.wdLog([' ---------------- getCurrentUser ---------------- ']);
return firebase.auth().currentUser;
}
reloadCurrentUser() {
return firebase.auth().currentUser.reload();
// .then(() => {
// // console.log(firebase.auth().currentUser);
// return firebase.auth().currentUser;
// });
}
getIdToken() {
this.g.wdLog(['getIdToken CURRENT USER']);
// that.g.wdLog(['Notification permission granted.');
const that = this;
firebase.auth().currentUser.getIdToken()/* true: forceRefresh */
.then(function(idToken) {
that.token = idToken;
that.g.wdLog(['******************** ---------------> idToken.', idToken]);
return idToken;
}).catch(function(error) {
console.error('idToken ERROR: ', error);
return;
});
}
getToken() {
return this.token;
}
// -------------- BEGIN SIGN IN ANONYMOUSLY -------------- //
resigninAnonymousAuthentication() {
const that = this;
const tiledeskToken = this.g.tiledeskToken;
if (tiledeskToken) {
this.resigninAnonymously(tiledeskToken)
.subscribe(response => {
if (response.token) {
that.g.tiledeskToken = tiledeskToken;
that.storageService.setItem('tiledeskToken', tiledeskToken);
// that.storageService.setItemWithoutProjectId('tiledeskToken', tiledeskToken);
// const newTiledeskToken = response.token;
// console.log('tiledeskToken 1: ', tiledeskToken);
// console.log('tiledeskToken 2: ', newTiledeskToken);
}
});
}
}
/** */
authenticationWithCustomToken(tiledeskToken: string) {
const that = this;
this.g.wdLog(['tiledeskToken::: ', tiledeskToken]);
if (tiledeskToken) {
this.createFirebaseToken(tiledeskToken, this.g.projectid)
.subscribe(firebaseToken => {
that.authenticateFirebaseCustomToken(firebaseToken);
}, error => {
console.log('createFirebaseToken: ', error);
that.signOut(-1);
});
}
}
/** */
anonymousAuthentication() {
const that = this;
this.g.wdLog(['anonymousAuthentication: ']);
const tiledeskToken = that.storageService.getItem('tiledeskToken');
if (tiledeskToken) {
that.createFirebaseToken(tiledeskToken, that.g.projectid)
.subscribe(firebaseToken => {
that.authenticateFirebaseCustomToken(firebaseToken);
}, error => {
console.log('createFirebaseToken: ', error);
that.signOut(-1);
});
} else {
this.signinAnonymously()
.subscribe(response => {
that.g.wdLog(['signinAnonymously: ', response]);
if (response.token) {
that.g.wdLog(['salvo tiledesk token:: ', response.token]);
that.g.tiledeskToken = response.token;
// remove tiledeskToken from storage
// this.storageService.removeItemForSuffix('_tiledeskToken');
that.storageService.setItem('tiledeskToken', response.token);
// that.storageService.setItemWithoutProjectId('tiledeskToken', tiledeskToken);
that.createFirebaseToken(response.token, that.g.projectid)
.subscribe(firebaseToken => {
that.authenticateFirebaseCustomToken(firebaseToken);
}, error => {
console.log('createFirebaseToken: ', error);
that.signOut(-1);
});
}
}, error => {
console.log('Error creating firebase token: ', error);
that.signOut(-1);
});
}
}
/** */
private resigninAnonymously(tiledeskToken) {
const url = this.API_URL + 'auth/resigninAnonymously';
this.g.wdLog(['url', url]);
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', tiledeskToken);
const body = {
'id_project': this.g.projectid
};
this.g.wdLog(['------------------> body: ', JSON.stringify(body)]);
return this.http
.post(url, JSON.stringify(body), { headers })
.map((response) => response.json());
}
/** */
private signinAnonymously() {
const url = this.API_URL + 'auth/signinAnonymously';
this.g.wdLog(['url', url]);
const headers = new Headers();
headers.append('Content-Type', 'application/json');
const body = {
'id_project': this.g.projectid
};
this.g.wdLog(['------------------> body: ', JSON.stringify(body)]);
return this.http
.post(url, JSON.stringify(body), { headers })
.map((response) => response.json());
}
public signInWithCustomToken(token: string) {
this.g.wdLog(['salvo tiledesk token:: ', token]);
this.g.tiledeskToken = token;
this.storageService.setItem('tiledeskToken', token);
// this.storageService.setItemWithoutProjectId('tiledeskToken', token);
this.g.autoStart = true;
const url = this.API_URL + 'auth/signinWithCustomToken';
this.g.wdLog(['url', url]);
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', token);
return this.http
.post(url, null, { headers })
.map((response) => response.json());
}
/** */
// token è un Tiledesk token ritorna Firebase Token
public createFirebaseToken(token, projectId?) {
// const url = this.API_URL + projectId + '/firebase/createtoken';
const url = this.API_URL + 'chat21/firebase/auth/createCustomToken';
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', token);
return this.http
.post(url, null, { headers })
.map((response) => response.text());
}
/** */
authenticateFirebaseCustomToken(token) {
this.g.wdLog(['1 - authService.authenticateFirebaseCustomToken', token]);
this.g.firebaseToken = token;
this.storageService.setItemWithoutProjectId('firebaseToken', token);
const that = this;
firebase.auth().setPersistence(this.getFirebaseAuthPersistence()).then(function() {
// Sign-out successful.
that.g.wdLog(['2 - authService.signInWithCustomToken', token]);
firebase.auth().signInWithCustomToken(token)
.then(function(response) {
// console.log('-------------- signInWithCustomToken -------------------', response);
that.g.setParameter('signInWithCustomToken', true);
that.storageService.setItemWithoutProjectId('shemaVersion', environment.storage_prefix);
that.user = response.user;
if (that.unsubscribe) {
that.unsubscribe();
}
that.g.wdLog(['obsLoggedUser - authService.authenticateFirebaseCustomToken']);
that.obsLoggedUser.next(200);
})
.catch(function(error) {
// console.log('---------------------------------');
const errorCode = error.code;
const errorMessage = error.message;
if (errorCode === 'auth/invalid-custom-token') {
// alert('The token you provided is not valid.');
} else {
console.error(error);
}
// if (that.unsubscribe) {
// that.unsubscribe();
// }
// that.g.wdLog(['authenticateFirebaseCustomToken ERROR: ', error]);
// that.signOut(-1);
});
})
.catch(function(error) {
console.error('Error setting firebase auth persistence', error);
that.signOut(-1);
});
}
// -------------- END SIGN IN ANONYMOUSLY -------------- //
/** */
authenticateFirebaseAnonymously() {
this.g.wdLog(['authenticateFirebaseAnonymously']);
const that = this;
firebase.auth().setPersistence(this.getFirebaseAuthPersistence()).then(function() {
firebase.auth().signInAnonymously()
.then(function(user) {
that.user = user;
if (that.unsubscribe) {
that.unsubscribe();
}
that.g.wdLog(['authenticateFirebaseAnonymously']);
that.getIdToken();
that.obsLoggedUser.next(200);
})
.catch(function(error) {
const errorCode = error.code;
const errorMessage = error.message;
if (that.unsubscribe) {
that.unsubscribe();
}
that.g.wdLog(['signInAnonymously ERROR: ', errorCode, errorMessage]);
that.signOut(-1);
});
})
.catch(function(error) {
console.error('Error setting firebase auth persistence', error);
that.signOut(-1);
});
}
authenticateFirebaseWithEmailAndPassword(email, password) {
const that = this;
firebase.auth().setPersistence(this.getFirebaseAuthPersistence()).then(function() {
firebase.auth().signInWithEmailAndPassword(email, password)
.then(function(user) {
that.user = user;
if (that.unsubscribe) {
that.unsubscribe();
}
that.getIdToken();
that.g.wdLog(['authenticateFirebaseWithEmailAndPassword']);
that.obsLoggedUser.next(200);
})
.catch(function(error) {
const errorCode = error.code;
const errorMessage = error.message;
if (that.unsubscribe) {
that.unsubscribe();
}
that.g.wdLog(['authenticateFirebaseWithEmailAndPassword ERROR: ', errorCode, errorMessage]);
that.signOut(-1);
});
})
.catch(function(error) {
console.error('Error setting firebase auth persistence', error);
that.signOut(-1);
});
}
// signOut() {
// return firebase.auth().signOut();
// // .then(function() {
// // // Sign-out successful.
// // }).catch(function(error) {
// // // An error happened.
// // });
// }
// signup(email: string, password: string) {
// this.firebaseAuth
// .auth
// .createUserWithEmailAndPassword(email, password)
// .then(value => {
// that.g.wdLog(['Success!', value);
// })
// .catch(err => {
// that.g.wdLog(['Something went wrong:', err.message);
// });
// }
// login(email: string, password: string) {
// this.firebaseAuth.auth.signInWithEmailAndPassword(email, password)
// .then(value => {
// that.g.wdLog(['Nice, it worked!');
// })
// .catch(err => {
// that.g.wdLog(['Something went wrong:', err.message);
// });
// }
signOut(codice: number) {
const that = this;
// return this.firebaseAuth.auth.signOut()
return firebase.auth().signOut()
.then(value => {
that.g.wdLog(['Nice, signOut OK!', value]);
that.hideIFrame();
if (that.unsubscribe) {
that.unsubscribe();
}
that.g.wdLog(['signOut', codice]);
that.g.wdLog(['obsLoggedUser', codice]);
that.obsLoggedUser.next(codice);
})
.catch(err => {
that.g.wdLog(['Something went wrong in signOut:', err.message]);
// that.obsLoggedUser.next(firebase.auth().currentUser);
that.obsLoggedUser.next(400);
});
}
hideIFrame() {
const divWidgetContainer = this.g.windowContext.document.getElementById('tiledesk-container');
if (divWidgetContainer) {
divWidgetContainer.classList.add('closed');
divWidgetContainer.classList.remove('open');
}
}
// /jwt/decode?project_id=123
public decode(token, projectId) {
const url = this.API_URL + projectId + '/jwt/decode';
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Authorization', 'JWT ' + token);
return this.http
.post(url, null, { headers })
.map((response) => response.json());
}
getFirebaseAuthPersistence() {
return firebase.auth.Auth.Persistence.NONE;
/*
if (this.g.persistence === 'local') {
// console.log('getFirebaseAuthPersistence local');
if (supports_html5_storage()) {
return firebase.auth.Auth.Persistence.LOCAL;
} else {
return firebase.auth.Auth.Persistence.NONE;
}
} else if (this.g.persistence === 'session') {
// console.log('getFirebaseAuthPersistence session');
if (supports_html5_session()) {
return firebase.auth.Auth.Persistence.SESSION;
} else {
return firebase.auth.Auth.Persistence.NONE;
}
} else if (this.g.persistence === 'none') {
return firebase.auth.Auth.Persistence.NONE;
} else {
// console.log('getFirebaseAuthPersistence local as else');
if (supports_html5_storage()) {
return firebase.auth.Auth.Persistence.LOCAL;
} else {
return firebase.auth.Auth.Persistence.NONE;
}
}
*/
}
} | the_stack |
declare namespace GoogleAppsScript {
namespace Mirror {
namespace Collection {
namespace Timeline {
interface AttachmentsCollection {
// Retrieves an attachment on a timeline item by item ID and attachment ID.
get(itemId: string, attachmentId: string): Mirror.Schema.Attachment;
// Adds a new attachment to a timeline item.
insert(itemId: string): Mirror.Schema.Attachment;
// Adds a new attachment to a timeline item.
insert(itemId: string, mediaData: any): Mirror.Schema.Attachment;
// Returns a list of attachments for a timeline item.
list(itemId: string): Mirror.Schema.AttachmentsListResponse;
// Deletes an attachment from a timeline item.
remove(itemId: string, attachmentId: string): void;
}
}
interface AccountsCollection {
// Inserts a new account for a user
insert(resource: Schema.Account, userToken: string, accountType: string, accountName: string): Mirror.Schema.Account;
}
interface ContactsCollection {
// Gets a single contact by ID.
get(id: string): Mirror.Schema.Contact;
// Inserts a new contact.
insert(resource: Schema.Contact): Mirror.Schema.Contact;
// Retrieves a list of contacts for the authenticated user.
list(): Mirror.Schema.ContactsListResponse;
// Updates a contact in place. This method supports patch semantics.
patch(resource: Schema.Contact, id: string): Mirror.Schema.Contact;
// Deletes a contact.
remove(id: string): void;
// Updates a contact in place.
update(resource: Schema.Contact, id: string): Mirror.Schema.Contact;
}
interface LocationsCollection {
// Gets a single location by ID.
get(id: string): Mirror.Schema.Location;
// Retrieves a list of locations for the user.
list(): Mirror.Schema.LocationsListResponse;
}
interface SettingsCollection {
// Gets a single setting by ID.
get(id: string): Mirror.Schema.Setting;
}
interface SubscriptionsCollection {
// Creates a new subscription.
insert(resource: Schema.Subscription): Mirror.Schema.Subscription;
// Retrieves a list of subscriptions for the authenticated user and service.
list(): Mirror.Schema.SubscriptionsListResponse;
// Deletes a subscription.
remove(id: string): void;
// Updates an existing subscription in place.
update(resource: Schema.Subscription, id: string): Mirror.Schema.Subscription;
}
interface TimelineCollection {
Attachments?: Mirror.Collection.Timeline.AttachmentsCollection | undefined;
// Gets a single timeline item by ID.
get(id: string): Mirror.Schema.TimelineItem;
// Inserts a new item into the timeline.
insert(resource: Schema.TimelineItem): Mirror.Schema.TimelineItem;
// Inserts a new item into the timeline.
insert(resource: Schema.TimelineItem, mediaData: any): Mirror.Schema.TimelineItem;
// Retrieves a list of timeline items for the authenticated user.
list(): Mirror.Schema.TimelineListResponse;
// Retrieves a list of timeline items for the authenticated user.
list(optionalArgs: object): Mirror.Schema.TimelineListResponse;
// Updates a timeline item in place. This method supports patch semantics.
patch(resource: Schema.TimelineItem, id: string): Mirror.Schema.TimelineItem;
// Deletes a timeline item.
remove(id: string): void;
// Updates a timeline item in place.
update(resource: Schema.TimelineItem, id: string): Mirror.Schema.TimelineItem;
// Updates a timeline item in place.
update(resource: Schema.TimelineItem, id: string, mediaData: any): Mirror.Schema.TimelineItem;
}
}
namespace Schema {
interface Account {
authTokens?: Mirror.Schema.AuthToken[] | undefined;
features?: string[] | undefined;
password?: string | undefined;
userData?: Mirror.Schema.UserData[] | undefined;
}
interface Attachment {
contentType?: string | undefined;
contentUrl?: string | undefined;
id?: string | undefined;
isProcessingContent?: boolean | undefined;
}
interface AttachmentsListResponse {
items?: Mirror.Schema.Attachment[] | undefined;
kind?: string | undefined;
}
interface AuthToken {
authToken?: string | undefined;
type?: string | undefined;
}
interface Command {
type?: string | undefined;
}
interface Contact {
acceptCommands?: Mirror.Schema.Command[] | undefined;
acceptTypes?: string[] | undefined;
displayName?: string | undefined;
id?: string | undefined;
imageUrls?: string[] | undefined;
kind?: string | undefined;
phoneNumber?: string | undefined;
priority?: number | undefined;
sharingFeatures?: string[] | undefined;
source?: string | undefined;
speakableName?: string | undefined;
type?: string | undefined;
}
interface ContactsListResponse {
items?: Mirror.Schema.Contact[] | undefined;
kind?: string | undefined;
}
interface Location {
accuracy?: number | undefined;
address?: string | undefined;
displayName?: string | undefined;
id?: string | undefined;
kind?: string | undefined;
latitude?: number | undefined;
longitude?: number | undefined;
timestamp?: string | undefined;
}
interface LocationsListResponse {
items?: Mirror.Schema.Location[] | undefined;
kind?: string | undefined;
}
interface MenuItem {
action?: string | undefined;
contextual_command?: string | undefined;
id?: string | undefined;
payload?: string | undefined;
removeWhenSelected?: boolean | undefined;
values?: Mirror.Schema.MenuValue[] | undefined;
}
interface MenuValue {
displayName?: string | undefined;
iconUrl?: string | undefined;
state?: string | undefined;
}
interface Notification {
collection?: string | undefined;
itemId?: string | undefined;
operation?: string | undefined;
userActions?: Mirror.Schema.UserAction[] | undefined;
userToken?: string | undefined;
verifyToken?: string | undefined;
}
interface NotificationConfig {
deliveryTime?: string | undefined;
level?: string | undefined;
}
interface Setting {
id?: string | undefined;
kind?: string | undefined;
value?: string | undefined;
}
interface Subscription {
callbackUrl?: string | undefined;
collection?: string | undefined;
id?: string | undefined;
kind?: string | undefined;
notification?: Mirror.Schema.Notification | undefined;
operation?: string[] | undefined;
updated?: string | undefined;
userToken?: string | undefined;
verifyToken?: string | undefined;
}
interface SubscriptionsListResponse {
items?: Mirror.Schema.Subscription[] | undefined;
kind?: string | undefined;
}
interface TimelineItem {
attachments?: Mirror.Schema.Attachment[] | undefined;
bundleId?: string | undefined;
canonicalUrl?: string | undefined;
created?: string | undefined;
creator?: Mirror.Schema.Contact | undefined;
displayTime?: string | undefined;
etag?: string | undefined;
html?: string | undefined;
id?: string | undefined;
inReplyTo?: string | undefined;
isBundleCover?: boolean | undefined;
isDeleted?: boolean | undefined;
isPinned?: boolean | undefined;
kind?: string | undefined;
location?: Mirror.Schema.Location | undefined;
menuItems?: Mirror.Schema.MenuItem[] | undefined;
notification?: Mirror.Schema.NotificationConfig | undefined;
pinScore?: number | undefined;
recipients?: Mirror.Schema.Contact[] | undefined;
selfLink?: string | undefined;
sourceItemId?: string | undefined;
speakableText?: string | undefined;
speakableType?: string | undefined;
text?: string | undefined;
title?: string | undefined;
updated?: string | undefined;
}
interface TimelineListResponse {
items?: Mirror.Schema.TimelineItem[] | undefined;
kind?: string | undefined;
nextPageToken?: string | undefined;
}
interface UserAction {
payload?: string | undefined;
type?: string | undefined;
}
interface UserData {
key?: string | undefined;
value?: string | undefined;
}
}
}
interface Mirror {
Accounts?: Mirror.Collection.AccountsCollection | undefined;
Contacts?: Mirror.Collection.ContactsCollection | undefined;
Locations?: Mirror.Collection.LocationsCollection | undefined;
Settings?: Mirror.Collection.SettingsCollection | undefined;
Subscriptions?: Mirror.Collection.SubscriptionsCollection | undefined;
Timeline?: Mirror.Collection.TimelineCollection | undefined;
// Create a new instance of Account
newAccount(): Mirror.Schema.Account;
// Create a new instance of Attachment
newAttachment(): Mirror.Schema.Attachment;
// Create a new instance of AuthToken
newAuthToken(): Mirror.Schema.AuthToken;
// Create a new instance of Command
newCommand(): Mirror.Schema.Command;
// Create a new instance of Contact
newContact(): Mirror.Schema.Contact;
// Create a new instance of Location
newLocation(): Mirror.Schema.Location;
// Create a new instance of MenuItem
newMenuItem(): Mirror.Schema.MenuItem;
// Create a new instance of MenuValue
newMenuValue(): Mirror.Schema.MenuValue;
// Create a new instance of Notification
newNotification(): Mirror.Schema.Notification;
// Create a new instance of NotificationConfig
newNotificationConfig(): Mirror.Schema.NotificationConfig;
// Create a new instance of Subscription
newSubscription(): Mirror.Schema.Subscription;
// Create a new instance of TimelineItem
newTimelineItem(): Mirror.Schema.TimelineItem;
// Create a new instance of UserAction
newUserAction(): Mirror.Schema.UserAction;
// Create a new instance of UserData
newUserData(): Mirror.Schema.UserData;
}
}
declare var Mirror: GoogleAppsScript.Mirror; | the_stack |
import { createBrowserHistory } from 'history';
import invert from 'lodash/invert';
import get from 'lodash/get';
import { renderRoutes } from 'react-router-config';
import { Router } from 'react-router';
import { HashRouter } from 'react-router-dom';
import { render, hydrate } from 'react-dom';
import {
Hook,
AsyncSeriesHook,
AsyncParallelBailHook,
SyncHook,
} from 'tapable';
import RouteHandler from '../router/handler';
import ErrorBoundary from '../components/ErrorBoundary';
import { generateMeta } from '../utils/seo';
import possibleStandardNames from '../utils/reactPossibleStandardNames';
import AbstractPlugin from '../abstract-plugin';
import { ICompiledRoute } from '../@types/route';
const possibleHtmlNames = invert(possibleStandardNames);
const getPossibleHtmlName = (key: string): string => possibleHtmlNames[key] || key;
type HistoryLocation = {
pathname: string;
search?: string;
hash?: string;
key?: string;
state?: any;
};
export default class ClientHandler extends AbstractPlugin {
historyUnlistener = null;
routeHandler: RouteHandler | null = null;
history: any;
updatePageMetaTimeout: any = 0;
loaded = false;
hooks: {
beforeRender: AsyncSeriesHook<any>;
locationChange: AsyncParallelBailHook<any, any>;
postMetaUpdate: AsyncParallelBailHook<any, any>;
appStart: AsyncSeriesHook<any>,
beforeLoadData: AsyncSeriesHook<any>;
renderRoutes: AsyncSeriesHook<any>;
renderComplete: SyncHook<any, any>;
[s: string]: Hook<any, any> | AsyncSeriesHook<any>,
};
options: {
env: any;
};
constructor(options: { env: any; }) {
super();
this.manageHistoryChange = this.manageHistoryChange.bind(this);
window.PAW_HISTORY = window.PAW_HISTORY || createBrowserHistory({
basename: options.env.appRootUrl,
});
this.history = window.PAW_HISTORY;
if (
this.historyUnlistener
&& typeof this.historyUnlistener === 'function'
) {
// @ts-ignore
this.historyUnlistener();
}
this.historyUnlistener = this.history.listen(this.manageHistoryChange);
this.hooks = {
locationChange: new AsyncParallelBailHook(['location', 'action']),
appStart: new AsyncSeriesHook([]),
postMetaUpdate: new AsyncParallelBailHook(['location', 'action']),
beforeLoadData: new AsyncSeriesHook(['setParams', 'getParams']),
beforeRender: new AsyncSeriesHook(['Application']),
renderRoutes: new AsyncSeriesHook(['AppRoutes']),
renderComplete: new SyncHook(),
};
this.options = options;
this.manageServiceWorker();
}
useHashRouter() {
return (this.options.env.singlePageApplication && this.options.env.hashedRoutes);
}
getCurrentRoutes(location: HistoryLocation | typeof window.location = window.location) {
if (!this.routeHandler) return [];
const routes = this.routeHandler.getRoutes();
const pathname = this.useHashRouter()
? (location.hash || '').replace('#', '')
: window.location.pathname;
return RouteHandler.matchRoutes(
routes,
pathname.replace(
this.options.env.appRootUrl,
'',
),
);
}
manageHistoryChange(location: HistoryLocation, action: string) {
if (!this.loaded) return;
this.hooks.locationChange.callAsync(location, action, () => null);
if (this.routeHandler) {
this.updatePageMeta(location, action)
.catch((e) => {
// eslint-disable-next-line
console.log(e);
});
}
}
// eslint-disable-next-line class-methods-use-this
getTitle(metaTitle: string): string {
const appName = process.env.APP_NAME || '';
const titleSeparator = process.env.PAGE_TITLE_SEPARATOR || '|';
if (!appName) {
return metaTitle;
}
if (metaTitle === appName) {
return metaTitle;
}
if (!metaTitle && appName) {
return appName;
}
return `${metaTitle} ${titleSeparator} ${appName}`;
}
async updatePageMeta(location: HistoryLocation, action = '') {
const updatePageMetaOnIdle = async (deadline: any) => {
if (deadline.timeRemaining() > 0 || deadline.didTimeout) {
if (this.routeHandler === null) return false;
const currentRoutes = this.getCurrentRoutes(location);
const promises: Promise<any> [] = [];
let seoData = {};
const pwaSchema = this.routeHandler.getPwaSchema();
const seoSchema = this.routeHandler.getDefaultSeoSchema();
currentRoutes.forEach((r: { route: ICompiledRoute, match: any }) => {
if (r.route && r.route.component && r.route.component.preload) {
promises.push(r.route.component.preload(undefined, {
route: r.route,
match: r.match,
}).promise);
}
});
await Promise.all(promises);
currentRoutes.forEach((r: { route: ICompiledRoute, match: any }) => {
let routeSeo = {};
if (r.route.getRouteSeo) {
routeSeo = r.route.getRouteSeo();
}
seoData = { ...seoData, ...routeSeo };
});
const metaTags = generateMeta(seoData, {
seoSchema,
pwaSchema,
baseUrl: window.location.origin,
url: window.location.href,
});
metaTags.forEach((meta) => {
let metaSearchStr = 'meta';
let firstMetaSearchStr = '';
const htmlMeta: any = {};
if (meta.name === 'title') {
document.title = this.getTitle(meta.content);
}
Object.keys(meta).forEach((key) => {
htmlMeta[getPossibleHtmlName(key)] = meta[key];
if (!firstMetaSearchStr) {
firstMetaSearchStr = `meta[${getPossibleHtmlName(key)}=${JSON.stringify(meta[key])}]`;
}
metaSearchStr += `[${getPossibleHtmlName(key)}=${JSON.stringify(meta[key])}]`;
});
const alreadyExists = document.querySelector(metaSearchStr);
if (!alreadyExists) {
const previousExists = document.querySelector(firstMetaSearchStr);
if (previousExists && previousExists.remove) {
previousExists.remove();
}
const metaElement = document.createElement('meta');
Object.keys(htmlMeta).forEach((htmlMetaKey) => {
metaElement.setAttribute(htmlMetaKey, htmlMeta[htmlMetaKey]);
});
document.getElementsByTagName('head')[0].appendChild(metaElement);
}
});
if (action) {
this.hooks.postMetaUpdate.callAsync(location, action, () => null);
}
} else {
if (this.updatePageMetaTimeout) {
window.cancelIdleCallback(this.updatePageMetaTimeout);
}
/**
* Update page meta tag once the window is idle
*/
window.requestIdleCallback(updatePageMetaOnIdle);
}
return true;
};
if (this.updatePageMetaTimeout) {
this.updatePageMetaTimeout = window.cancelIdleCallback(this.updatePageMetaTimeout);
}
/**
* Update page meta tag once the window is idle
*/
this.updatePageMetaTimeout = window.requestIdleCallback(updatePageMetaOnIdle);
return true;
}
manageServiceWorker() {
const isSafari = /^((?!chrome|android).)*safari/i.test(window.navigator.userAgent);
const disableInSafari = !this.options.env.safariServiceWorker;
let registerServiceWorker = this.options.env.serviceWorker;
if (disableInSafari && isSafari) {
registerServiceWorker = false;
}
if (registerServiceWorker) {
this.hooks.renderComplete.tap('AddServiceWorker', (err) => {
if (err) return;
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register(
`${this.options.env.appRootUrl}/sw.js`,
).catch(() => null);
}
});
} else {
// remove previously registered service worker
this.hooks.renderComplete.tap('RemoveServiceWorker', (err) => {
if (err) return;
if ('serviceWorker' in navigator) {
navigator.serviceWorker.getRegistrations().then((registrations) => {
registrations.forEach(registration => registration.unregister());
});
}
});
}
}
getRenderer() {
const { env } = this.options;
const root = get(env, 'clientRootElementId', 'app');
const domRootReference = document.getElementById(root);
return (
env.serverSideRender
&& !env.singlePageApplication
&& domRootReference
&& domRootReference.innerHTML !== ''
) ? hydrate : render;
}
async preloadCurrentRoutes() {
if (!this.routeHandler) return false;
const routes = this.routeHandler.getRoutes();
const currentPageRoutes = RouteHandler.matchRoutes(
routes,
window.location.pathname.replace(
this.options.env.appRootUrl,
'',
),
);
const { preloadManager: { setParams, getParams } } = this.routeHandler.routeCompiler;
await new Promise(r => this
.hooks
.beforeLoadData
.callAsync(
setParams,
getParams,
r,
));
const promises: Promise<any> [] = [];
if (window.PAW_PRELOADED_DATA) {
const preloadedData = window.PAW_PRELOADED_DATA;
currentPageRoutes.forEach((r: { route: ICompiledRoute, match: any }, i: number) => {
if (
(typeof preloadedData[i] !== 'undefined')
&& r.route && r.route.component && r.route.component.preload
) {
const preloadInit = r.route.component.preload(preloadedData[i], {
route: r.route,
match: r.match,
});
promises.push(preloadInit.promise);
} else if (r.route && r.route.component && r.route.component.preload) {
const preloadInit = r.route.component.preload(undefined, {
route: r.route,
match: r.match,
});
promises.push(preloadInit.promise);
}
});
} else {
currentPageRoutes.forEach((r: { route: ICompiledRoute, match: any }) => {
if (r.route && r.route.component && r.route.component.preload) {
const preloadInit = r.route.component.preload(undefined, {
route: r.route,
match: r.match,
});
promises.push(preloadInit.promise);
}
});
}
return Promise.all(promises);
}
async renderApplication() {
if (!this.routeHandler) return false;
const root = get(this.options.env, 'clientRootElementId', 'app');
const domRootReference = document.getElementById(root);
const renderer = this.getRenderer();
const routes = this.routeHandler.getRoutes();
const currentPageRoutes = this.getCurrentRoutes();
const components: any = {};
components.appRouter = this.useHashRouter() ? HashRouter : Router;
let routerParams: any = {
history: this.history,
};
if (this.options.env.singlePageApplication && this.options.env.hashedRoutes) {
routerParams = {};
}
const appRoutes = {
renderedRoutes: (
<ErrorBoundary
ErrorComponent={this.routeHandler.getErrorComponent()}
NotFoundComponent={this.routeHandler.get404Component()}
>
{renderRoutes(routes)}
</ErrorBoundary>
),
setRenderedRoutes: (r: JSX.Element) => {
appRoutes.renderedRoutes = r;
},
getRenderedRoutes: () => appRoutes.renderedRoutes,
};
await (
new Promise(r => this.hooks.renderRoutes.callAsync(
{
setRenderedRoutes: appRoutes.setRenderedRoutes,
getRenderedRoutes: appRoutes.getRenderedRoutes,
},
r,
)));
const children = (
<components.appRouter basename={this.options.env.appRootUrl} {...routerParams}>
{appRoutes.renderedRoutes}
</components.appRouter>
);
const application = {
children,
currentRoutes: currentPageRoutes.slice(0),
routes: routes.slice(0),
};
return new Promise((resolve) => {
this.hooks.beforeRender.callAsync(application, async () => {
// Render according to routes!
renderer(
(
<ErrorBoundary>
{application.children}
</ErrorBoundary>
),
domRootReference,
() => {
window.PAW_PRELOADED_DATA = null;
delete window.PAW_PRELOADED_DATA;
const preloadedElement = document.getElementById('__pawjs_preloaded');
if (preloadedElement && preloadedElement.remove) {
preloadedElement.remove();
}
this.hooks.renderComplete.call();
resolve(null);
},
);
});
});
}
async run({ routeHandler }: { routeHandler: RouteHandler }) {
this.routeHandler = routeHandler;
// On app start
await new Promise(r => this
.hooks
.appStart
.callAsync(
r,
));
const { env } = this.options;
const root = get(env, 'clientRootElementId', 'app');
if (!document.getElementById(root)) {
// eslint-disable-next-line
console.warn(`#${root} element not found in HTML, thus cannot proceed further`);
return false;
}
await this.preloadCurrentRoutes();
if (!this.options.env.serverSideRender) {
this.updatePageMeta(this.history.location);
}
/**
* Render application only if loaded
*/
const idleTimeout = 0;
const renderOnIdle = (deadline: any) => {
if (deadline.timeRemaining() > 0 || deadline.didTimeout) {
this.renderApplication();
this.loaded = true;
} else {
if (idleTimeout) {
window.cancelIdleCallback(idleTimeout);
}
window.requestIdleCallback(renderOnIdle);
}
};
window.requestIdleCallback(renderOnIdle);
return true;
}
} | the_stack |
import * as assert from 'assert';
import { IFileService, FileChangeType, IFileChange, IFileSystemProviderWithFileReadWriteCapability, IStat, FileType, FileSystemProviderCapabilities } from 'vs/platform/files/common/files';
import { FileService } from 'vs/platform/files/common/fileService';
import { NullLogService } from 'vs/platform/log/common/log';
import { Schemas } from 'vs/base/common/network';
import { URI } from 'vs/base/common/uri';
import { FileUserDataProvider } from 'vs/platform/userData/common/fileUserDataProvider';
import { dirname, isEqual, joinPath } from 'vs/base/common/resources';
import { VSBuffer } from 'vs/base/common/buffer';
import { DisposableStore, IDisposable, Disposable } from 'vs/base/common/lifecycle';
import { Emitter, Event } from 'vs/base/common/event';
import { InMemoryFileSystemProvider } from 'vs/platform/files/common/inMemoryFilesystemProvider';
import { AbstractNativeEnvironmentService } from 'vs/platform/environment/common/environmentService';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import product from 'vs/platform/product/common/product';
const ROOT = URI.file('tests').with({ scheme: 'vscode-tests' });
class TestEnvironmentService extends AbstractNativeEnvironmentService {
constructor(private readonly _appSettingsHome: URI) {
super(Object.create(null), Object.create(null), { _serviceBrand: undefined, ...product });
}
override get userRoamingDataHome() { return this._appSettingsHome.with({ scheme: Schemas.vscodeUserData }); }
}
suite('FileUserDataProvider', () => {
let testObject: IFileService;
let userDataHomeOnDisk: URI;
let backupWorkspaceHomeOnDisk: URI;
let environmentService: IEnvironmentService;
const disposables = new DisposableStore();
let fileUserDataProvider: FileUserDataProvider;
setup(async () => {
const logService = new NullLogService();
testObject = disposables.add(new FileService(logService));
const fileSystemProvider = disposables.add(new InMemoryFileSystemProvider());
disposables.add(testObject.registerProvider(ROOT.scheme, fileSystemProvider));
userDataHomeOnDisk = joinPath(ROOT, 'User');
const backupHome = joinPath(ROOT, 'Backups');
backupWorkspaceHomeOnDisk = joinPath(backupHome, 'workspaceId');
await testObject.createFolder(userDataHomeOnDisk);
await testObject.createFolder(backupWorkspaceHomeOnDisk);
environmentService = new TestEnvironmentService(userDataHomeOnDisk);
fileUserDataProvider = new FileUserDataProvider(ROOT.scheme, fileSystemProvider, Schemas.vscodeUserData, logService);
disposables.add(fileUserDataProvider);
disposables.add(testObject.registerProvider(Schemas.vscodeUserData, fileUserDataProvider));
});
teardown(() => disposables.clear());
test('exists return false when file does not exist', async () => {
const exists = await testObject.exists(environmentService.settingsResource);
assert.strictEqual(exists, false);
});
test('read file throws error if not exist', async () => {
try {
await testObject.readFile(environmentService.settingsResource);
assert.fail('Should fail since file does not exist');
} catch (e) { }
});
test('read existing file', async () => {
await testObject.writeFile(joinPath(userDataHomeOnDisk, 'settings.json'), VSBuffer.fromString('{}'));
const result = await testObject.readFile(environmentService.settingsResource);
assert.strictEqual(result.value.toString(), '{}');
});
test('create file', async () => {
const resource = environmentService.settingsResource;
const actual1 = await testObject.createFile(resource, VSBuffer.fromString('{}'));
assert.strictEqual(actual1.resource.toString(), resource.toString());
const actual2 = await testObject.readFile(joinPath(userDataHomeOnDisk, 'settings.json'));
assert.strictEqual(actual2.value.toString(), '{}');
});
test('write file creates the file if not exist', async () => {
const resource = environmentService.settingsResource;
const actual1 = await testObject.writeFile(resource, VSBuffer.fromString('{}'));
assert.strictEqual(actual1.resource.toString(), resource.toString());
const actual2 = await testObject.readFile(joinPath(userDataHomeOnDisk, 'settings.json'));
assert.strictEqual(actual2.value.toString(), '{}');
});
test('write to existing file', async () => {
const resource = environmentService.settingsResource;
await testObject.writeFile(joinPath(userDataHomeOnDisk, 'settings.json'), VSBuffer.fromString('{}'));
const actual1 = await testObject.writeFile(resource, VSBuffer.fromString('{a:1}'));
assert.strictEqual(actual1.resource.toString(), resource.toString());
const actual2 = await testObject.readFile(joinPath(userDataHomeOnDisk, 'settings.json'));
assert.strictEqual(actual2.value.toString(), '{a:1}');
});
test('delete file', async () => {
await testObject.writeFile(joinPath(userDataHomeOnDisk, 'settings.json'), VSBuffer.fromString(''));
await testObject.del(environmentService.settingsResource);
const result = await testObject.exists(joinPath(userDataHomeOnDisk, 'settings.json'));
assert.strictEqual(false, result);
});
test('resolve file', async () => {
await testObject.writeFile(joinPath(userDataHomeOnDisk, 'settings.json'), VSBuffer.fromString(''));
const result = await testObject.resolve(environmentService.settingsResource);
assert.ok(!result.isDirectory);
assert.ok(result.children === undefined);
});
test('exists return false for folder that does not exist', async () => {
const exists = await testObject.exists(environmentService.snippetsHome);
assert.strictEqual(exists, false);
});
test('exists return true for folder that exists', async () => {
await testObject.createFolder(joinPath(userDataHomeOnDisk, 'snippets'));
const exists = await testObject.exists(environmentService.snippetsHome);
assert.strictEqual(exists, true);
});
test('read file throws error for folder', async () => {
await testObject.createFolder(joinPath(userDataHomeOnDisk, 'snippets'));
try {
await testObject.readFile(environmentService.snippetsHome);
assert.fail('Should fail since read file is not supported for folders');
} catch (e) { }
});
test('read file under folder', async () => {
await testObject.createFolder(joinPath(userDataHomeOnDisk, 'snippets'));
await testObject.writeFile(joinPath(userDataHomeOnDisk, 'snippets', 'settings.json'), VSBuffer.fromString('{}'));
const resource = joinPath(environmentService.snippetsHome, 'settings.json');
const actual = await testObject.readFile(resource);
assert.strictEqual(actual.resource.toString(), resource.toString());
assert.strictEqual(actual.value.toString(), '{}');
});
test('read file under sub folder', async () => {
await testObject.createFolder(joinPath(userDataHomeOnDisk, 'snippets', 'java'));
await testObject.writeFile(joinPath(userDataHomeOnDisk, 'snippets', 'java', 'settings.json'), VSBuffer.fromString('{}'));
const resource = joinPath(environmentService.snippetsHome, 'java/settings.json');
const actual = await testObject.readFile(resource);
assert.strictEqual(actual.resource.toString(), resource.toString());
assert.strictEqual(actual.value.toString(), '{}');
});
test('create file under folder that exists', async () => {
await testObject.createFolder(joinPath(userDataHomeOnDisk, 'snippets'));
const resource = joinPath(environmentService.snippetsHome, 'settings.json');
const actual1 = await testObject.createFile(resource, VSBuffer.fromString('{}'));
assert.strictEqual(actual1.resource.toString(), resource.toString());
const actual2 = await testObject.readFile(joinPath(userDataHomeOnDisk, 'snippets', 'settings.json'));
assert.strictEqual(actual2.value.toString(), '{}');
});
test('create file under folder that does not exist', async () => {
const resource = joinPath(environmentService.snippetsHome, 'settings.json');
const actual1 = await testObject.createFile(resource, VSBuffer.fromString('{}'));
assert.strictEqual(actual1.resource.toString(), resource.toString());
const actual2 = await testObject.readFile(joinPath(userDataHomeOnDisk, 'snippets', 'settings.json'));
assert.strictEqual(actual2.value.toString(), '{}');
});
test('write to not existing file under container that exists', async () => {
await testObject.createFolder(joinPath(userDataHomeOnDisk, 'snippets'));
const resource = joinPath(environmentService.snippetsHome, 'settings.json');
const actual1 = await testObject.writeFile(resource, VSBuffer.fromString('{}'));
assert.strictEqual(actual1.resource.toString(), resource.toString());
const actual = await testObject.readFile(joinPath(userDataHomeOnDisk, 'snippets', 'settings.json'));
assert.strictEqual(actual.value.toString(), '{}');
});
test('write to not existing file under container that does not exists', async () => {
const resource = joinPath(environmentService.snippetsHome, 'settings.json');
const actual1 = await testObject.writeFile(resource, VSBuffer.fromString('{}'));
assert.strictEqual(actual1.resource.toString(), resource.toString());
const actual = await testObject.readFile(joinPath(userDataHomeOnDisk, 'snippets', 'settings.json'));
assert.strictEqual(actual.value.toString(), '{}');
});
test('write to existing file under container', async () => {
await testObject.createFolder(joinPath(userDataHomeOnDisk, 'snippets'));
await testObject.writeFile(joinPath(userDataHomeOnDisk, 'snippets', 'settings.json'), VSBuffer.fromString('{}'));
const resource = joinPath(environmentService.snippetsHome, 'settings.json');
const actual1 = await testObject.writeFile(resource, VSBuffer.fromString('{a:1}'));
assert.strictEqual(actual1.resource.toString(), resource.toString());
const actual = await testObject.readFile(joinPath(userDataHomeOnDisk, 'snippets', 'settings.json'));
assert.strictEqual(actual.value.toString(), '{a:1}');
});
test('write file under sub container', async () => {
const resource = joinPath(environmentService.snippetsHome, 'java/settings.json');
const actual1 = await testObject.writeFile(resource, VSBuffer.fromString('{}'));
assert.strictEqual(actual1.resource.toString(), resource.toString());
const actual = await testObject.readFile(joinPath(userDataHomeOnDisk, 'snippets', 'java', 'settings.json'));
assert.strictEqual(actual.value.toString(), '{}');
});
test('delete throws error for folder that does not exist', async () => {
try {
await testObject.del(environmentService.snippetsHome);
assert.fail('Should fail the folder does not exist');
} catch (e) { }
});
test('delete not existing file under container that exists', async () => {
await testObject.createFolder(joinPath(userDataHomeOnDisk, 'snippets'));
try {
await testObject.del(joinPath(environmentService.snippetsHome, 'settings.json'));
assert.fail('Should fail since file does not exist');
} catch (e) { }
});
test('delete not existing file under container that does not exists', async () => {
try {
await testObject.del(joinPath(environmentService.snippetsHome, 'settings.json'));
assert.fail('Should fail since file does not exist');
} catch (e) { }
});
test('delete existing file under folder', async () => {
await testObject.createFolder(joinPath(userDataHomeOnDisk, 'snippets'));
await testObject.writeFile(joinPath(userDataHomeOnDisk, 'snippets', 'settings.json'), VSBuffer.fromString('{}'));
await testObject.del(joinPath(environmentService.snippetsHome, 'settings.json'));
const exists = await testObject.exists(joinPath(userDataHomeOnDisk, 'snippets', 'settings.json'));
assert.strictEqual(exists, false);
});
test('resolve folder', async () => {
await testObject.createFolder(joinPath(userDataHomeOnDisk, 'snippets'));
await testObject.writeFile(joinPath(userDataHomeOnDisk, 'snippets', 'settings.json'), VSBuffer.fromString('{}'));
const result = await testObject.resolve(environmentService.snippetsHome);
assert.ok(result.isDirectory);
assert.ok(result.children !== undefined);
assert.strictEqual(result.children!.length, 1);
assert.strictEqual(result.children![0].resource.toString(), joinPath(environmentService.snippetsHome, 'settings.json').toString());
});
test('read backup file', async () => {
await testObject.writeFile(joinPath(backupWorkspaceHomeOnDisk, 'backup.json'), VSBuffer.fromString('{}'));
const result = await testObject.readFile(joinPath(backupWorkspaceHomeOnDisk.with({ scheme: environmentService.userRoamingDataHome.scheme }), `backup.json`));
assert.strictEqual(result.value.toString(), '{}');
});
test('create backup file', async () => {
await testObject.createFile(joinPath(backupWorkspaceHomeOnDisk.with({ scheme: environmentService.userRoamingDataHome.scheme }), `backup.json`), VSBuffer.fromString('{}'));
const result = await testObject.readFile(joinPath(backupWorkspaceHomeOnDisk, 'backup.json'));
assert.strictEqual(result.value.toString(), '{}');
});
test('write backup file', async () => {
await testObject.writeFile(joinPath(backupWorkspaceHomeOnDisk, 'backup.json'), VSBuffer.fromString('{}'));
await testObject.writeFile(joinPath(backupWorkspaceHomeOnDisk.with({ scheme: environmentService.userRoamingDataHome.scheme }), `backup.json`), VSBuffer.fromString('{a:1}'));
const result = await testObject.readFile(joinPath(backupWorkspaceHomeOnDisk, 'backup.json'));
assert.strictEqual(result.value.toString(), '{a:1}');
});
test('resolve backups folder', async () => {
await testObject.writeFile(joinPath(backupWorkspaceHomeOnDisk, 'backup.json'), VSBuffer.fromString('{}'));
const result = await testObject.resolve(backupWorkspaceHomeOnDisk.with({ scheme: environmentService.userRoamingDataHome.scheme }));
assert.ok(result.isDirectory);
assert.ok(result.children !== undefined);
assert.strictEqual(result.children!.length, 1);
assert.strictEqual(result.children![0].resource.toString(), joinPath(backupWorkspaceHomeOnDisk.with({ scheme: environmentService.userRoamingDataHome.scheme }), `backup.json`).toString());
});
});
class TestFileSystemProvider implements IFileSystemProviderWithFileReadWriteCapability {
constructor(readonly onDidChangeFile: Event<readonly IFileChange[]>) { }
readonly capabilities: FileSystemProviderCapabilities = FileSystemProviderCapabilities.FileReadWrite;
readonly onDidChangeCapabilities: Event<void> = Event.None;
watch(): IDisposable { return Disposable.None; }
stat(): Promise<IStat> { throw new Error('Not Supported'); }
mkdir(resource: URI): Promise<void> { throw new Error('Not Supported'); }
rename(): Promise<void> { throw new Error('Not Supported'); }
readFile(resource: URI): Promise<Uint8Array> { throw new Error('Not Supported'); }
readdir(resource: URI): Promise<[string, FileType][]> { throw new Error('Not Supported'); }
writeFile(): Promise<void> { throw new Error('Not Supported'); }
delete(): Promise<void> { throw new Error('Not Supported'); }
}
suite('FileUserDataProvider - Watching', () => {
let testObject: FileUserDataProvider;
const disposables = new DisposableStore();
const rootFileResource = joinPath(ROOT, 'User');
const rootUserDataResource = rootFileResource.with({ scheme: Schemas.vscodeUserData });
const fileEventEmitter: Emitter<readonly IFileChange[]> = new Emitter<readonly IFileChange[]>();
disposables.add(fileEventEmitter);
setup(() => {
testObject = disposables.add(new FileUserDataProvider(rootFileResource.scheme, new TestFileSystemProvider(fileEventEmitter.event), Schemas.vscodeUserData, new NullLogService()));
});
teardown(() => disposables.clear());
test('file added change event', done => {
disposables.add(testObject.watch(rootUserDataResource, { excludes: [], recursive: false }));
const expected = joinPath(rootUserDataResource, 'settings.json');
const target = joinPath(rootFileResource, 'settings.json');
disposables.add(testObject.onDidChangeFile(e => {
if (isEqual(e[0].resource, expected) && e[0].type === FileChangeType.ADDED) {
done();
}
}));
fileEventEmitter.fire([{
resource: target,
type: FileChangeType.ADDED
}]);
});
test('file updated change event', done => {
disposables.add(testObject.watch(rootUserDataResource, { excludes: [], recursive: false }));
const expected = joinPath(rootUserDataResource, 'settings.json');
const target = joinPath(rootFileResource, 'settings.json');
disposables.add(testObject.onDidChangeFile(e => {
if (isEqual(e[0].resource, expected) && e[0].type === FileChangeType.UPDATED) {
done();
}
}));
fileEventEmitter.fire([{
resource: target,
type: FileChangeType.UPDATED
}]);
});
test('file deleted change event', done => {
disposables.add(testObject.watch(rootUserDataResource, { excludes: [], recursive: false }));
const expected = joinPath(rootUserDataResource, 'settings.json');
const target = joinPath(rootFileResource, 'settings.json');
disposables.add(testObject.onDidChangeFile(e => {
if (isEqual(e[0].resource, expected) && e[0].type === FileChangeType.DELETED) {
done();
}
}));
fileEventEmitter.fire([{
resource: target,
type: FileChangeType.DELETED
}]);
});
test('file under folder created change event', done => {
disposables.add(testObject.watch(rootUserDataResource, { excludes: [], recursive: false }));
const expected = joinPath(rootUserDataResource, 'snippets', 'settings.json');
const target = joinPath(rootFileResource, 'snippets', 'settings.json');
disposables.add(testObject.onDidChangeFile(e => {
if (isEqual(e[0].resource, expected) && e[0].type === FileChangeType.ADDED) {
done();
}
}));
fileEventEmitter.fire([{
resource: target,
type: FileChangeType.ADDED
}]);
});
test('file under folder updated change event', done => {
disposables.add(testObject.watch(rootUserDataResource, { excludes: [], recursive: false }));
const expected = joinPath(rootUserDataResource, 'snippets', 'settings.json');
const target = joinPath(rootFileResource, 'snippets', 'settings.json');
disposables.add(testObject.onDidChangeFile(e => {
if (isEqual(e[0].resource, expected) && e[0].type === FileChangeType.UPDATED) {
done();
}
}));
fileEventEmitter.fire([{
resource: target,
type: FileChangeType.UPDATED
}]);
});
test('file under folder deleted change event', done => {
disposables.add(testObject.watch(rootUserDataResource, { excludes: [], recursive: false }));
const expected = joinPath(rootUserDataResource, 'snippets', 'settings.json');
const target = joinPath(rootFileResource, 'snippets', 'settings.json');
disposables.add(testObject.onDidChangeFile(e => {
if (isEqual(e[0].resource, expected) && e[0].type === FileChangeType.DELETED) {
done();
}
}));
fileEventEmitter.fire([{
resource: target,
type: FileChangeType.DELETED
}]);
});
test('event is not triggered if not watched', async () => {
const target = joinPath(rootFileResource, 'settings.json');
let triggered = false;
testObject.onDidChangeFile(() => triggered = true);
fileEventEmitter.fire([{
resource: target,
type: FileChangeType.DELETED
}]);
if (triggered) {
assert.fail('event should not be triggered');
}
});
test('event is not triggered if not watched 2', async () => {
disposables.add(testObject.watch(rootUserDataResource, { excludes: [], recursive: false }));
const target = joinPath(dirname(rootFileResource), 'settings.json');
let triggered = false;
testObject.onDidChangeFile(() => triggered = true);
fileEventEmitter.fire([{
resource: target,
type: FileChangeType.DELETED
}]);
if (triggered) {
assert.fail('event should not be triggered');
}
});
}); | the_stack |
import * as fs from "fs";
import * as fsExtra from "fs-extra";
import * as https from "https";
import * as path from "path";
import * as R from "ramda";
import * as vscode from "vscode";
import {
BASE_RESOURCES_CONFIG,
BASE_STATES_CONFIG,
CLI_HOSTED_SKILL_TYPE,
DEFAULT_PROFILE,
GIT_MESSAGES,
SKILL,
SKILL_FOLDER,
} from "../constants";
import {AskError, logAskError} from "../exceptions";
import {Logger} from "../logger";
import {SkillInfo} from "../models/types";
import {CommandContext, SmapiClientFactory, SmapiResource, Utils} from "../runtime";
import {getSkillNameFromLocales} from "../utils/skillHelper";
import {openWorkspaceFolder} from "../utils/workspaceHelper";
import {getOrInstantiateGitApi, GitInTerminalHelper, isGitInstalled} from "./gitHelper";
import {checkAskPrePushScript, checkAuthInfoScript, checkGitCredentialHelperScript} from "./s3ScriptChecker";
import {createSkillPackageFolder, syncSkillPackage} from "./skillPackageHelper";
export async function executeClone(context: CommandContext, skillInfo: SmapiResource<SkillInfo>) {
try {
const skillFolderUri = await createSkillFolder(skillInfo);
if (skillFolderUri === undefined) {
return;
}
// Create progress bar and run next steps
await vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: "Downloading skill",
cancellable: false,
},
async (progress, token) => {
await cloneSkill(skillInfo, skillFolderUri.fsPath, context.extensionContext, progress);
},
);
const skillName = getSkillNameFromLocales(skillInfo.data.skillSummary.nameByLocale!);
const cloneSkillMsg = `Skill ${skillName} was cloned successfully and added to workspace. The skill is located at ${skillFolderUri.fsPath}`;
Logger.info(cloneSkillMsg);
vscode.window.showInformationMessage(cloneSkillMsg);
// Add skill folder to workspace
await openWorkspaceFolder(skillFolderUri);
return;
} catch (err) {
throw logAskError(`Skill clone failed`, err, true);
}
}
async function createSkillFolder(skillInfo: SmapiResource<SkillInfo>): Promise<vscode.Uri | undefined> {
Logger.verbose(`Calling method: createSkillFolder, args: `, skillInfo);
const selectedFolderArray = await vscode.window.showOpenDialog({
openLabel: "Select project folder",
canSelectFiles: false,
canSelectFolders: true,
canSelectMany: false,
});
if (selectedFolderArray === undefined) {
return undefined;
}
const projectFolder = selectedFolderArray[0];
const skillName = getSkillNameFromLocales(skillInfo.data.skillSummary.nameByLocale!);
const filteredProjectName = Utils.filterNonAlphanumeric(skillName);
const skillFolderAbsPath = path.join(projectFolder.fsPath, filteredProjectName);
// create skill folder in project path
if (fs.existsSync(skillFolderAbsPath)) {
Logger.debug(`Skill folder ${skillFolderAbsPath} already exists.`);
const errorMessage = `Skill folder ${skillFolderAbsPath} already exists. Would you like to overwrite it?`;
const overWriteSelection = await vscode.window.showInformationMessage(errorMessage, ...["Yes", "No"]);
if (overWriteSelection === "Yes") {
Logger.debug(`Confirmed skill folder overwrite option. Overwriting ${skillFolderAbsPath}.`);
fsExtra.removeSync(skillFolderAbsPath);
} else {
return undefined;
}
}
fs.mkdirSync(skillFolderAbsPath);
return vscode.Uri.file(skillFolderAbsPath);
}
async function setupGitFolder(skillInfo: SmapiResource<SkillInfo>, targetPath: string, context: vscode.ExtensionContext): Promise<void> {
try {
Logger.verbose(`Calling method: setupGitFolder, args: `, skillInfo, targetPath);
let profile = Utils.getCachedProfile(context);
profile = profile ?? DEFAULT_PROFILE;
const smapiClient = SmapiClientFactory.getInstance(profile, context);
const skillId = skillInfo.data.skillSummary.skillId!;
const credentialsList = await smapiClient.generateCredentialsForAlexaHostedSkillV1(skillId, {
repository: skillInfo.data.hostedSkillMetadata?.alexaHosted?.repository!,
});
const repositoryCredentials = credentialsList.repositoryCredentials;
if (!repositoryCredentials || !repositoryCredentials.username || !repositoryCredentials.password) {
throw new Error("Failed to retrieve hosted skill credentials from the service.");
}
const gitHelper = new GitInTerminalHelper(targetPath, Logger.logLevel);
const repoUrl = skillInfo.data.hostedSkillMetadata?.alexaHosted?.repository?.url;
if (!repoUrl) {
throw new Error("Failed to retrieve hosted skill repo URL from the service.");
}
await downloadGitCredentialScript(targetPath, context);
gitHelper.init();
gitHelper.configureCredentialHelper(repoUrl, profile, skillId);
gitHelper.addOrigin(repoUrl);
/**
* Since gitHelper commands are failing due to execSync
* not waiting to call next command, calling the following
* set of git commands through inbuilt git extension
*/
await vscode.commands.executeCommand("git.openRepository", targetPath);
const gitApi = await getOrInstantiateGitApi(context);
const repo = gitApi?.getRepository(vscode.Uri.file(targetPath));
await repo?.fetch();
await repo?.checkout("prod");
await repo?.checkout("master");
await setPrePushHookScript(targetPath, context);
} catch (err) {
throw logAskError(`Git folder setup failed for ${targetPath}`, err);
}
}
function createAskResourcesConfig(projectPath: string, profile: string | undefined, skillId: string): void {
Logger.verbose(`Calling method: createAskResourcesConfig, args: `, projectPath, profile, skillId);
profile = profile ?? DEFAULT_PROFILE;
const askResourcesPath = path.join(projectPath, SKILL_FOLDER.ASK_RESOURCES_JSON_CONFIG);
let askResourcesJson = R.clone(BASE_RESOURCES_CONFIG);
askResourcesJson = R.set(R.lensPath(["profiles", profile, "skillId"]), skillId, askResourcesJson);
askResourcesJson = R.set(R.lensPath(["profiles", profile, "skillInfrastructure", "type"]), CLI_HOSTED_SKILL_TYPE, askResourcesJson);
fs.writeFileSync(askResourcesPath, JSON.stringify(askResourcesJson, null, 2));
}
function createAskStateConfig(projectPath: string, profile: string, skillId: string): void {
Logger.verbose(`Calling method: createAskStateConfig, args: `, projectPath, profile, skillId);
const askStatesPath = path.join(projectPath, SKILL_FOLDER.HIDDEN_ASK_FOLDER, SKILL_FOLDER.ASK_STATES_JSON_CONFIG);
let askStatesJson = R.clone(BASE_STATES_CONFIG);
askStatesJson = R.set(R.lensPath(["profiles", profile, "skillId"]), skillId, askStatesJson);
fs.writeFileSync(askStatesPath, JSON.stringify(askStatesJson, null, 2));
}
function downloadScriptFile(scriptUrl: string, filePath: string, chmod: string): Promise<void> {
Logger.verbose(`Calling method: downloadScriptFile, args: `, scriptUrl, filePath, chmod);
const file = fs.createWriteStream(filePath);
return new Promise((resolve, reject) => {
const request = https.get(scriptUrl, (resp) => {
resp.pipe(file);
fs.chmodSync(filePath, chmod);
resolve();
});
request.on("error", (err) => {
reject(logAskError("Download script failed ", err));
});
request.end();
});
}
async function setPrePushHookScript(projectPath: string, context: vscode.ExtensionContext): Promise<void> {
Logger.verbose(`Calling method: setPrePushHookScript, args: `, projectPath);
await checkAuthInfoScript(context);
await checkAskPrePushScript(context);
const scriptUrl = SKILL.GIT_HOOKS_SCRIPTS.PRE_PUSH.URL;
const scriptFilePath = path.join(
projectPath,
SKILL_FOLDER.HIDDEN_GIT_FOLDER.NAME,
SKILL_FOLDER.HIDDEN_GIT_FOLDER.HOOKS.NAME,
SKILL_FOLDER.HIDDEN_GIT_FOLDER.HOOKS.PRE_PUSH,
);
const chmod = SKILL.GIT_HOOKS_SCRIPTS.PRE_PUSH.CHMOD;
await downloadScriptFile(scriptUrl, scriptFilePath, chmod);
}
async function downloadGitCredentialScript(projectPath: string, context: vscode.ExtensionContext): Promise<void> {
Logger.verbose(`Calling method: downloadGitCredentialScript, args: `, projectPath);
await checkAuthInfoScript(context);
await checkGitCredentialHelperScript(context);
}
function checkGitInstallation() {
Logger.verbose(`Calling method: checkGitInstallation`);
if (!isGitInstalled()) {
throw new AskError(GIT_MESSAGES.GIT_NOT_FOUND);
}
}
export async function cloneSkill(
skillInfo: SmapiResource<SkillInfo>,
targetPath: string,
context: vscode.ExtensionContext,
progressBar?: vscode.Progress<{message: string; increment: number}>,
): Promise<void> {
Logger.verbose(`Calling method: cloneSkill, args: `, skillInfo, targetPath);
checkGitInstallation();
const incrAmount: number = !progressBar ? 0 : 25;
fs.mkdirSync(path.join(targetPath, SKILL_FOLDER.HIDDEN_ASK_FOLDER));
const profile = Utils.getCachedProfile(context) ?? DEFAULT_PROFILE;
if (skillInfo.data.isHosted) {
await setupGitFolder(skillInfo, targetPath, context);
if (progressBar) {
progressBar.report({
increment: incrAmount,
message: "Git access set. Checking skill metadata files...",
});
}
}
createAskResourcesConfig(targetPath, profile, skillInfo.data.skillSummary.skillId!);
createAskStateConfig(targetPath, profile, skillInfo.data.skillSummary.skillId!);
if (progressBar) {
progressBar.report({
increment: incrAmount,
message: "Skill metadata files checked. Checking skill package...",
});
}
GitInTerminalHelper.addFilesToIgnore(targetPath, filesToIgnore());
createSkillPackageFolder(targetPath);
if (progressBar) {
progressBar.report({
increment: incrAmount,
message: "Skill package created. Syncing from service...",
});
}
const skillPkgPath = path.join(targetPath, SKILL_FOLDER.SKILL_PACKAGE.NAME);
await syncSkillPackage(skillPkgPath, skillInfo.data.skillSummary.skillId!, context, "development");
if (progressBar) {
progressBar.report({
increment: incrAmount,
message: "Skill package sync'd.",
});
}
}
function filesToIgnore(): string[] {
const nodeModules = `${SKILL_FOLDER.LAMBDA.NAME}/${SKILL_FOLDER.LAMBDA.NODE_MODULES}`;
return [SKILL_FOLDER.ASK_RESOURCES_JSON_CONFIG, SKILL_FOLDER.HIDDEN_ASK_FOLDER, SKILL_FOLDER.HIDDEN_VSCODE, nodeModules, ".DS_Store"];
} | the_stack |
const letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$'.split('')
const digits = '1234567890'.split('')
const keywords = [
// javascript
'break', 'case', 'catch', 'class', 'const', 'continue',
'debugger', 'default', 'delete', 'do', 'else', 'export',
'extends', 'finally', 'for', 'function', 'if', 'import',
'in', 'instanceof', 'new', 'return', 'super', 'switch',
'this', 'throw', 'try', 'typeof', 'var', 'void', 'while',
'with', 'yield',
// literal kinds
'true', 'false', 'null',
// additional
'from', 'join', 'where', 'orderby', 'select', 'groupby', 'into',
]
function isLetter(input: string): boolean {
return letters.includes(input)
}
function isDigit(input: string): boolean {
return digits.includes(input)
}
function isKeyword(input: string): boolean {
return keywords.includes(input)
}
export class InvalidTokenCharacterError extends Error {
constructor(offset: number, value: string) {
super(`Invalid character '${value}' at offset ${offset}`)
}
}
export interface TokenBase { value: string, offset: number, length: number }
export enum TokenKind {
// Raw
NewLine, Return, Tabspace, Whitespace, Add, Subtract, Multiply,
Divide, Modulo, EqualSign, Tilde, ExclaimationMark, QuestionMark,
Ampersand, GreaterThan, LessThan, ForwardSlash, BackSlash,
Pipe, Letter, Digit, DoubleQuote, SingleQuote, Colon, SemiColon,
Dot, Comma, BraceLeft, BraceRight, ParenLeft, ParenRight,
BracketLeft, BracketRight,
// Reduced
Number, Word, String, Keyword,
// External
Parameter
}
// Raw
export type Newline = { kind: TokenKind.NewLine } & TokenBase
export type Return = { kind: TokenKind.Return } & TokenBase
export type Tabspace = { kind: TokenKind.Tabspace } & TokenBase
export type Whitespace = { kind: TokenKind.Whitespace } & TokenBase
export type Add = { kind: TokenKind.Add } & TokenBase
export type Subtract = { kind: TokenKind.Subtract } & TokenBase
export type Multiply = { kind: TokenKind.Multiply } & TokenBase
export type Divide = { kind: TokenKind.Divide } & TokenBase
export type Modulo = { kind: TokenKind.Modulo } & TokenBase
export type Equals = { kind: TokenKind.EqualSign } & TokenBase
export type Tilde = { kind: TokenKind.Tilde } & TokenBase
export type ExclaimationMark = { kind: TokenKind.ExclaimationMark } & TokenBase
export type QuestionMark = { kind: TokenKind.QuestionMark } & TokenBase
export type Ampersand = { kind: TokenKind.Ampersand } & TokenBase
export type GreaterThan = { kind: TokenKind.GreaterThan } & TokenBase
export type LessThan = { kind: TokenKind.LessThan } & TokenBase
export type ForwardSlash = { kind: TokenKind.ForwardSlash } & TokenBase
export type BackSlash = { kind: TokenKind.BackSlash } & TokenBase
export type Pipe = { kind: TokenKind.Pipe } & TokenBase
export type Letter = { kind: TokenKind.Letter } & TokenBase
export type Digit = { kind: TokenKind.Digit } & TokenBase
export type DoubleQuote = { kind: TokenKind.DoubleQuote } & TokenBase
export type SingleQuote = { kind: TokenKind.SingleQuote } & TokenBase
export type Colon = { kind: TokenKind.Colon } & TokenBase
export type SemiColon = { kind: TokenKind.SemiColon } & TokenBase
export type Dot = { kind: TokenKind.Dot } & TokenBase
export type Comma = { kind: TokenKind.Comma } & TokenBase
export type CurlyOpen = { kind: TokenKind.BraceLeft } & TokenBase
export type CurlyClose = { kind: TokenKind.BraceRight } & TokenBase
export type BraceOpen = { kind: TokenKind.ParenLeft } & TokenBase
export type BraceClose = { kind: TokenKind.ParenRight } & TokenBase
export type BracketOpen = { kind: TokenKind.BracketLeft } & TokenBase
export type BracketClose = { kind: TokenKind.BracketRight } & TokenBase
// Reduced
export type Number = { kind: TokenKind.Number } & TokenBase
export type Word = { kind: TokenKind.Word } & TokenBase
export type String = { kind: TokenKind.String } & TokenBase
export type Keyword = { kind: TokenKind.Keyword } & TokenBase
// Parameter
export type ParameterToken = { kind: TokenKind.Parameter, offset: number, length: number, index: number, value: any }
export type Token = Newline | Return | Tabspace | Whitespace | Add | Subtract | Multiply |
Divide | Modulo | Letter | Digit | Equals | Tilde | ExclaimationMark | QuestionMark | QuestionMark |
Ampersand | GreaterThan | LessThan | ForwardSlash | BackSlash | Pipe | DoubleQuote |
SingleQuote | Colon | SemiColon | Dot | Comma | CurlyOpen | CurlyClose | BraceOpen |
BraceClose | BracketOpen | BracketClose | Number | Word | String | Keyword | ParameterToken
export function scan(inputs: Input[]): Token[] {
const tokens = [] as Token[]
let parameterIndex = 0
for (const input of inputs) {
const value = input.value
const offset = input.offset
const length = input.length
const options = { value, offset, length }
if (input.type === InputType.Parameter) {
const index = parameterIndex
parameterIndex += 1
tokens.push({ kind: TokenKind.Parameter, ...options, index })
continue
}
switch (value) {
case ' ': { tokens.push({ kind: TokenKind.Whitespace, ...options }); break }
case '\n': { tokens.push({ kind: TokenKind.NewLine, ...options }); break }
case '\r': { tokens.push({ kind: TokenKind.Return, ...options }); break }
case '\t': { tokens.push({ kind: TokenKind.Tabspace, ...options }); break }
case '+': { tokens.push({ kind: TokenKind.Add, ...options }); break }
case '-': { tokens.push({ kind: TokenKind.Subtract, ...options }); break }
case '*': { tokens.push({ kind: TokenKind.Multiply, ...options }); break }
case '/': { tokens.push({ kind: TokenKind.Divide, ...options }); break }
case '%': { tokens.push({ kind: TokenKind.Modulo, ...options }); break }
case '=': { tokens.push({ kind: TokenKind.EqualSign, ...options }); break }
case '~': { tokens.push({ kind: TokenKind.Tilde, ...options }); break }
case '!': { tokens.push({ kind: TokenKind.ExclaimationMark, ...options }); break }
case '?': { tokens.push({ kind: TokenKind.QuestionMark, ...options }); break }
case '&': { tokens.push({ kind: TokenKind.Ampersand, ...options }); break }
case '>': { tokens.push({ kind: TokenKind.GreaterThan, ...options }); break }
case '<': { tokens.push({ kind: TokenKind.LessThan, ...options }); break }
case '/': { tokens.push({ kind: TokenKind.ForwardSlash, ...options }); break }
case '\\': { tokens.push({ kind: TokenKind.BackSlash, ...options }); break }
case '|': { tokens.push({ kind: TokenKind.Pipe, ...options }); break }
case "'": { tokens.push({ kind: TokenKind.SingleQuote, ...options }); break }
case '"': { tokens.push({ kind: TokenKind.DoubleQuote, ...options }); break }
case ':': { tokens.push({ kind: TokenKind.Colon, ...options }); break }
case ';': { tokens.push({ kind: TokenKind.SemiColon, ...options }); break }
case '.': { tokens.push({ kind: TokenKind.Dot, ...options }); break }
case ',': { tokens.push({ kind: TokenKind.Comma, ...options }); break }
case '{': { tokens.push({ kind: TokenKind.BraceLeft, ...options }); break }
case '}': { tokens.push({ kind: TokenKind.BraceRight, ...options }); break }
case '[': { tokens.push({ kind: TokenKind.BracketLeft, ...options }); break }
case ']': { tokens.push({ kind: TokenKind.BracketRight, ...options }); break }
case '(': { tokens.push({ kind: TokenKind.ParenLeft, ...options }); break }
case ')': { tokens.push({ kind: TokenKind.ParenRight, ...options }); break }
default: {
if (isLetter(value)) {
tokens.push({ kind: TokenKind.Letter, ...options })
} else if (isDigit(value)) {
tokens.push({ kind: TokenKind.Digit, ...options })
} else {
throw new InvalidTokenCharacterError(offset, value)
}
}
}
}
return tokens
}
/** Reduces a consecutive sequence of 'from' token kinds into the given reduced 'to' token kind. */
function reduce(tokens: Token[], from: TokenKind, to: TokenKind): Token[] {
const output = [] as Token[]
while (tokens.length > 0) {
const current = tokens.shift()!
if (current.kind !== from) {
output.push(current)
continue
}
const buffer = [current] as Token[]
while (tokens.length > 0) {
const next = tokens.shift()!
if (next.kind === current.kind) {
buffer.push(next)
} else {
tokens.unshift(next)
break
}
}
const kind = to
const value = buffer.map(c => c.value).join('')
const offset = current.offset
const length = buffer.reduce((acc, c) => acc + c.length, 0)
output.push({ kind, value, offset, length } as Token)
}
return output
}
export class UnclosedStringError extends Error {
constructor() { super('Unclosed quoted string') }
}
/** Reduces all for all quoted strings. */
function reduce_strings(tokens: Token[]): Token[] {
const output = [] as Token[]
while (tokens.length > 0) {
const current = tokens.shift()!
if (current.kind !== TokenKind.DoubleQuote &&
current.kind !== TokenKind.SingleQuote) {
output.push(current)
continue
}
const buffer = [current] as Token[]
let ended = false
while (tokens.length > 0) {
const next = tokens.shift()!
buffer.push(next)
if (next.kind === current.kind) {
const kind = TokenKind.String
const offset = current.offset
const length = buffer.reduce((acc, c) => acc + c.length, 0)
const value = buffer.map(c => c.value).join('')
output.push({ kind, value, offset, length })
ended = true
break
}
}
if (!ended) {
throw new UnclosedStringError()
}
}
return output
}
/** Reduces number sequences with decimal places. */
function reduce_numbers(tokens: Token[]): Token[] {
const output = [] as Token[]
while (tokens.length > 0) {
const current = tokens.shift()!
// test '.1'
if (current.kind === TokenKind.Dot && tokens.length > 0) {
const next = tokens.shift()!
if (next.kind === TokenKind.Number) {
const kind = TokenKind.Number
const offset = current.offset
const buffer = [current, next]
const length = buffer.reduce((acc, c) => acc + c.length, 0)
const value = buffer.map(c => c.value).join('')
output.push({ kind, value, offset, length })
continue
} else {
output.push(current)
tokens.unshift(next)
continue
}
}
// test '1.1'
if (current.kind === TokenKind.Number && tokens.length >= 2) {
const next_0 = tokens.shift()!
const next_1 = tokens.shift()!
if (next_0.kind === TokenKind.Dot && next_1.kind === TokenKind.Number) {
const kind = TokenKind.Number
const offset = current.offset
const buffer = [current, next_0, next_1]
const length = buffer.reduce((acc, c) => acc + c.length, 0)
const value = buffer.map(c => c.value).join('')
output.push({ kind, value, offset, length })
} else if (next_0.kind === TokenKind.Dot && next_1.kind !== TokenKind.Number) {
tokens.unshift(next_1)
const kind = TokenKind.Number
const offset = current.offset
const buffer = [current, next_0]
const length = buffer.reduce((acc, c) => acc + c.length, 0)
const value = buffer.map(c => c.value).join('')
output.push({ kind, value, offset, length })
} else {
tokens.unshift(next_1)
tokens.unshift(next_0)
output.push(current)
}
}
// test '1.'
else if (current.kind === TokenKind.Number && tokens.length >= 1) {
const next_0 = tokens.shift()!
if (next_0.kind === TokenKind.Dot) {
const kind = TokenKind.Number
const offset = current.offset
const buffer = [current, next_0]
const length = buffer.reduce((acc, c) => acc + c.length, 0)
const value = buffer.map(c => c.value).join('')
output.push({ kind, value, offset, length })
} else {
tokens.unshift(next_0)
output.push(current)
}
} else {
output.push(current)
}
}
return output
}
function concat_word_to_numbers(tokens: Token[]): Token[] {
const output = [] as Token[]
while (tokens.length > 0) {
const word = tokens.shift()!
if (word.kind === TokenKind.Word && tokens.length > 0) {
const number = tokens.shift()!
if (number.kind === TokenKind.Number && number.value.indexOf('.') === -1) {
const kind = TokenKind.Word
const value = [word.value, number.value].join('')
const offset = word.offset
const length = word.length + number.length
output.push({ kind, value, offset, length })
continue
}
output.push(word)
output.push(number)
continue
}
output.push(word)
}
return output
}
function remap_keywords(tokens: Token[]): Token[] {
const output = [] as Token[]
while (tokens.length > 0) {
const token = tokens.shift()!
if (token.kind === TokenKind.Word && isKeyword(token.value)) {
const kind = TokenKind.Keyword
const value = token.value
const offset = token.offset
const length = token.length
output.push({ kind, value, offset, length })
continue
}
output.push(token)
}
return output
}
function filter(tokens: Token[], omit: TokenKind[]) {
const output = [] as Token[]
while (tokens.length > 0) {
const token = tokens.shift()!
if (!omit.includes(token.kind)) {
output.push(token)
}
}
return output
}
// -------------------------------------------------------
// TokenStream
// -------------------------------------------------------
export class TokenStream {
constructor(private tokens: Token[], private index: number) { }
public get length(): number { return this.tokens.length - this.index }
public shift(): Token { return this.tokens[this.index++] }
public clone(): TokenStream { return new TokenStream(this.tokens, this.index) }
public toString() {
return {
// consumed: this.tokens.slice(0, this.index),
remaining: this.tokens.slice(this.index)
}
}
}
/** Tokenizes the given string with optional tokens to omit. */
export function tokenize(input: Input[], omit: TokenKind[] = []): TokenStream {
const tokens_0 = scan(input)
const tokens_1 = reduce(tokens_0, TokenKind.Letter, TokenKind.Word)
const tokens_2 = reduce(tokens_1, TokenKind.Digit, TokenKind.Number)
const tokens_3 = reduce(tokens_2, TokenKind.Whitespace, TokenKind.Whitespace)
const tokens_4 = concat_word_to_numbers(tokens_3)
const tokens_5 = reduce_strings(tokens_4)
const tokens_6 = reduce_numbers(tokens_5)
const tokens_7 = remap_keywords(tokens_6)
return new TokenStream(filter(tokens_7, omit), 0)
}
// -------------------------------------------------------
// Inputs
// -------------------------------------------------------
export enum InputType { Character, Parameter }
export type InputCharacter = { type: InputType.Character, value: string, offset: number, length: number }
export type InputParameter = { type: InputType.Parameter, value: any, offset: number, length: number }
export type Input = InputCharacter | InputParameter
/** Resolves character and parameter inputs from the users tagged template literal. */
export function input(...args: any[]): Input[] {
const parts = args.shift() as string[]
const params = args
const buffer = [] as Input[]
let offset = 0
for (const part of parts) {
for (let i = 0; i < part.length; i++) {
const type = InputType.Character
const value = part.charAt(i)
buffer.push({ type, value, offset, length: 1 })
offset += 1
}
if (params.length > 0) {
const type = InputType.Parameter
const value = params.shift()
buffer.push({ type, value, offset, length: 1 })
offset += 1
}
}
return buffer
} | the_stack |
import { StatementTypes } from "../../chef/javascript/components/statements/statement";
import { Expression, Operation, VariableReference } from "../../chef/javascript/components/value/expression";
import { ArgumentList } from "../../chef/javascript/components/constructs/function";
import { Value, Type, ValueTypes } from "../../chef/javascript/components/value/value";
import { replaceVariables, cloneAST, newOptionalVariableReference, newOptionalVariableReferenceFromChain, aliasVariables } from "../../chef/javascript/utils/variables";
import { getSlice, getElement, thisDataVariable } from "../helpers";
import { BindingAspect, IBinding, VariableReferenceArray, NodeData } from "../template";
import { HTMLElement, Node } from "../../chef/html/html";
import { ObjectLiteral } from "../../chef/javascript/components/value/object";
import { Component } from "../../component";
const valueParam = new VariableReference("value");
export function makeSetFromBinding(
component: Component,
binding: IBinding,
nodeData: WeakMap<Node, NodeData>,
variableChain: VariableReferenceArray,
globals: Array<VariableReference> = []
): Array<StatementTypes> {
const statements: Array<StatementTypes> = [];
const elementStatement = binding.element ? getElement(binding.element, nodeData, component.templateElement) : null;
const isElementNullable = binding.element ? nodeData.get(binding.element)?.nullable ?? false : false;
// getSlice will return the trailing portion from the for iterator statement thing
const variableReference = VariableReference.fromChain(...getSlice(variableChain) as Array<string>) as VariableReference;
let newValue: ValueTypes | null = null;
if (binding.expression) {
const clonedExpression = cloneAST(binding.expression) as ValueTypes;
replaceVariables(clonedExpression, valueParam, [variableReference]);
aliasVariables(clonedExpression, thisDataVariable, [valueParam, ...globals]);
newValue = clonedExpression;
}
switch (binding.aspect) {
case BindingAspect.InnerText:
// Gets the index of the fragment and alters the data property of the
// fragment (which exists on CharacterData) to the string value
if (isElementNullable) {
statements.push(new Expression({
lhs: new VariableReference("tryAssignData"),
operation: Operation.Call,
rhs: new ArgumentList([
newOptionalVariableReferenceFromChain(
elementStatement!,
"childNodes",
binding.fragmentIndex!,
),
newValue!
])
}));
} else {
statements.push(new Expression({
lhs: VariableReference.fromChain(
elementStatement!,
"childNodes",
binding.fragmentIndex!,
"data"
),
operation: Operation.Assign,
rhs: newValue!
}));
}
break;
case BindingAspect.Conditional: {
const { clientRenderMethod, identifier } = nodeData.get(binding.element!) ?? {};
const callConditionalSwapFunction = new Expression({
lhs: VariableReference.fromChain("conditionalSwap", "call"),
operation: Operation.Call,
rhs: new ArgumentList([
new VariableReference("this"),
newValue!, // TODO temp non null
new Value(Type.string, identifier!),
VariableReference.fromChain("this", clientRenderMethod!.actualName!)
])
});
statements.push(callConditionalSwapFunction);
break;
}
case BindingAspect.Iterator: {
const clientRenderFunction = nodeData.get(binding.element!)!.clientRenderMethod!;
const renderNewElement = new Expression({
lhs: VariableReference.fromChain("this", clientRenderFunction.actualName!),
operation: Operation.Call,
rhs: new VariableReference("value")
});
const addNewElementToTheParent = new Expression({
lhs: isElementNullable ?
newOptionalVariableReferenceFromChain(elementStatement!, "append") :
VariableReference.fromChain(elementStatement!, "append"),
operation: isElementNullable ? Operation.OptionalCall : Operation.Call,
rhs: renderNewElement
});
statements.push(addNewElementToTheParent);
break;
}
case BindingAspect.Attribute:
const attribute = binding.attribute!;
if (HTMLElement.booleanAttributes.has(attribute)) {
statements.push(new Expression({
lhs: new VariableReference(attribute, elementStatement!),
operation: Operation.Assign,
rhs: newValue!
}));
} else {
const setAttributeRef = isElementNullable ? newOptionalVariableReference("setAttribute", elementStatement!) : new VariableReference("setAttribute", elementStatement!);
statements.push(new Expression({
lhs: setAttributeRef,
operation: isElementNullable ? Operation.OptionalCall : Operation.Call,
rhs: new ArgumentList([
new Value(Type.string, attribute),
newValue!
])
}));
}
break;
case BindingAspect.Data:
if (isElementNullable) {
statements.push(new Expression({
lhs: new VariableReference("tryAssignData"),
operation: Operation.Call,
rhs: new ArgumentList([
elementStatement!,
newValue!
])
}));
} else {
if (newValue! instanceof ObjectLiteral) {
// TODO only supports { x: y } or { x } atm (rhs has to be VariableReference)
// TODO rather than === valueParam should be has valueParam to parse expressions
const [property, value] = Array.from(newValue.values.entries())
.find(([_, val]) => val instanceof VariableReference && val.name === "value")!;
statements.push(
new Expression({
lhs: VariableReference.fromChain(elementStatement!, "data", property as string),
operation: Operation.Assign,
rhs: value
})
);
} else {
statements.push(new Expression({
lhs: new VariableReference("data", elementStatement!),
operation: Operation.Assign,
rhs: newValue!
}));
}
}
break;
case BindingAspect.DocumentTitle:
statements.push(new Expression({
lhs: VariableReference.fromChain("document", "title"),
operation: Operation.Assign,
rhs: newValue!
}));
break;
case BindingAspect.InnerHTML: {
if (isElementNullable) {
statements.push(new Expression({
lhs: new VariableReference("tryAssignData"),
operation: Operation.Call,
rhs: new ArgumentList([
elementStatement!,
newValue!,
new Value(Type.string, "innerHTML")
])
}));
} else {
statements.push(new Expression({
lhs: new VariableReference("innerHTML", elementStatement!),
operation: Operation.Assign,
rhs: newValue!
}));
}
break;
}
case BindingAspect.Style:
const styleObject = new VariableReference("style", elementStatement!);
// Converts background-color -> backgroundColor which is the key JS uses
const styleKey = binding.styleKey!.replace(/(?:-)([a-z])/g, (_, m) => m.toUpperCase());
statements.push(new Expression({
lhs: new VariableReference(styleKey, styleObject),
operation: Operation.Assign,
rhs: newValue!
}));
break;
case BindingAspect.ServerParameter:
const name = (binding.expression as VariableReference).name;
const resetData = new Expression({
lhs: VariableReference.fromChain("this", "_d"),
operation: Operation.Assign,
rhs: new ObjectLiteral(new Map([[name, new VariableReference("value")]]))
});
const removeDataProxy = new Expression({
lhs: VariableReference.fromChain("this", "_pC"),
operation: Operation.Delete
});
const clearElementCache = new Expression({
lhs: VariableReference.fromChain("this", "_eC", "clear"),
operation: Operation.Call
});
const renderCall = new Expression({
lhs: VariableReference.fromChain("this", "render"),
operation: Operation.Call,
});
statements.push(resetData, removeDataProxy, clearElementCache, renderCall);
break;
default:
throw Error(`Unknown aspect ${BindingAspect[binding.aspect]}`)
}
return statements;
}
export function setLengthForIteratorBinding(binding: IBinding, nodeData: WeakMap<Node, NodeData>): StatementTypes {
if (binding.aspect !== BindingAspect.Iterator) throw Error("Expected iterator binding");
const getElemExpression = getElement(binding.element!, nodeData, null);
// Uses the setLength helper to assist with sorting cache and removing from DOM
return new Expression({
lhs: new VariableReference("setLength"),
operation: Operation.Call,
rhs: new ArgumentList([
getElemExpression,
new VariableReference("value")
])
});
} | the_stack |
module Apiman {
export var ConsumerApiRedirectController = _module.controller("Apiman.ConsumerApiRedirectController",
['$q', '$scope', 'OrgSvcs', 'PageLifecycle', '$routeParams',
($q, $scope, OrgSvcs, PageLifecycle, $routeParams) => {
var orgId = $routeParams.org;
var apiId = $routeParams.api;
var pageData = {
versions: $q(function(resolve, reject) {
OrgSvcs.query({ organizationId: orgId, entityType: 'apis', entityId: apiId, versionsOrActivity: 'versions' }, resolve, reject);
})
};
PageLifecycle.loadPage('ConsumerApiRedirect', undefined, pageData, $scope, function() {
var version = $scope.versions[0].version;
for (var i = 0; i < $scope.versions.length; i++) {
var v = $scope.versions[i];
if (v.status == 'Published') {
version = v.version;
break;
}
}
PageLifecycle.forwardTo('/browse/orgs/{0}/{1}/{2}', orgId, apiId, version);
});
}]);
export var ConsumerApiController = _module.controller("Apiman.ConsumerApiController",
['$q', '$scope', 'OrgSvcs', 'PageLifecycle', '$routeParams',
($q, $scope, OrgSvcs, PageLifecycle, $routeParams) => {
$scope.params = $routeParams;
$scope.chains = {};
$scope.getPolicyChain = function(plan) {
var planId = plan.planId;
if (!$scope.chains[planId]) {
OrgSvcs.get({ organizationId: $routeParams.org, entityType: 'apis', entityId: $routeParams.api, versionsOrActivity: 'versions', version: $routeParams.version, policiesOrActivity: 'plans', policyId: plan.planId, policyChain : 'policyChain' }, function(policyReply) {
$scope.chains[planId] = policyReply.policies;
}, function(error) {
$scope.chains[planId] = [];
});
}
};
var pageData = {
version: $q(function(resolve, reject) {
OrgSvcs.get({ organizationId: $routeParams.org, entityType: 'apis', entityId: $routeParams.api, versionsOrActivity: 'versions', version: $routeParams.version }, resolve, reject);
}),
versions: $q(function(resolve, reject) {
OrgSvcs.query({ organizationId: $routeParams.org, entityType: 'apis', entityId: $routeParams.api, versionsOrActivity: 'versions' }, function(versions) {
var publishedVersions = [];
angular.forEach(versions, function(version) {
if (version.version == $routeParams.version) {
$scope.selectedApiVersion = version;
}
if (version.status == 'Published') {
publishedVersions.push(version);
}
});
resolve(publishedVersions);
}, reject);
}),
publicEndpoint: $q(function(resolve, reject) {
OrgSvcs.get({ organizationId: $routeParams.org, entityType: 'apis', entityId: $routeParams.api, versionsOrActivity: 'versions', version: $routeParams.version, policiesOrActivity: 'endpoint' }, resolve, function(error) {
resolve({
managedEndpoint: 'Not available.'
});
});
}),
plans: $q(function(resolve, reject) {
OrgSvcs.query({ organizationId: $routeParams.org, entityType: 'apis', entityId: $routeParams.api, versionsOrActivity: 'versions', version: $routeParams.version, policiesOrActivity: 'plans' }, resolve, reject);
})
};
$scope.setVersion = function(apiVersion) {
PageLifecycle.redirectTo('/browse/orgs/{0}/{1}/{2}', $routeParams.org, $routeParams.api, apiVersion.version);
};
PageLifecycle.loadPage('ConsumerApi', undefined, pageData, $scope, function() {
$scope.api = $scope.version.api;
$scope.org = $scope.api.organization;
PageLifecycle.setPageTitle('consumer-api', [ $scope.api.name ]);
});
// Tooltip
$scope.tooltipTxt = 'Copy to clipboard';
// Called on clicking the button the tooltip is attached to
$scope.tooltipChange = function() {
$scope.tooltipTxt = 'Copied!';
};
// Call when the mouse leaves the button the tooltip is attached to
$scope.tooltipReset = function() {
setTimeout(function() {
$scope.tooltipTxt = 'Copy to clipboard';
}, 100);
};
// Copy-to-Clipboard
// Called if copy-to-clipboard functionality was successful
$scope.copySuccess = function () {
//console.log('Copied!');
};
// Called if copy-to-clipboard functionality was unsuccessful
$scope.copyFail = function (err) {
//console.error('Error!', err);
};
}]);
export var ConsumerApiDefController = _module.controller("Apiman.ConsumerApiDefController",
['$q', '$rootScope', '$scope', 'OrgSvcs', 'PageLifecycle', '$routeParams', '$window', 'Logger', 'ApiDefinitionSvcs', 'Configuration', 'SwaggerUIContractService',
($q, $rootScope, $scope, OrgSvcs, PageLifecycle, $routeParams, $window, Logger, ApiDefinitionSvcs, Configuration, SwaggerUIContractService) => {
$scope.params = $routeParams;
$scope.chains = {};
var pageData = {
version: $q(function(resolve, reject) {
OrgSvcs.get({ organizationId: $routeParams.org, entityType: 'apis', entityId: $routeParams.api, versionsOrActivity: 'versions', version: $routeParams.version }, resolve, reject);
}),
publicEndpoint: $q(function(resolve, reject) {
OrgSvcs.get({ organizationId: $routeParams.org, entityType: 'apis', entityId: $routeParams.api, versionsOrActivity: 'versions', version: $routeParams.version, policiesOrActivity: 'endpoint' }, resolve, function(error) {
resolve({
managedEndpoint: 'Not available.'
});
});
})
};
const DisableTryItOutPlugin = function() {
return {
statePlugins: {
spec: {
wrapSelectors: {
allowTryItOutFor: () => () => false
}
}
}
}
};
// SwaggerUI Plugins
const DisableAuthorizePlugin = function() {
return {
wrapComponents: {
authorizeBtn: () => () => null
}
}
};
$scope.$on("$locationChangeStart", function(event, new_url, old_url){
//check if new requested url contains /def
//If not remove X-API-Key
if (new_url.indexOf("/def") == -1){
// console.log("Success");
SwaggerUIContractService.removeXAPIKey();
}
});
PageLifecycle.loadPage('ConsumerApiDef', undefined, pageData, $scope, function() {
$scope.api = $scope.version.api;
$scope.org = $scope.api.organization;
$scope.hasError = false;
let hasPublicPublishedAPI = ($scope.version.publicAPI && $scope.version.status == "Published") ? true : false;
let hasContract = (SwaggerUIContractService.getXAPIKey() && $scope.version.status == "Published") ? true : false;
PageLifecycle.setPageTitle('consumer-api-def', [ $scope.api.name ]);
if (($scope.version.definitionType == 'SwaggerJSON' || $scope.version.definitionType == 'SwaggerYAML') && SwaggerUIBundle) {
var url = ApiDefinitionSvcs.getApimanDefinitionUrl($scope.params.org, $scope.params.api, $scope.params.version);
Logger.debug("!!!!! Using definition URL: {0}", url);
$scope.definitionStatus = 'loading';
let ui;
let swaggerOptions = <any>{
url: url,
dom_id: "#swagger-ui-container",
validatorUrl: "https://online.swagger.io/validator",
presets: [
SwaggerUIBundle.presets.apis
],
layout: "BaseLayout",
sorter : "alpha",
requestInterceptor: function(request) {
// Only add auth header to requests where the URL matches the one specified above.
if (request.url === url) {
request.headers.Authorization = Configuration.getAuthorizationHeader();
}
// Send the API-Key always as parameter if the URL is not the URL whrere the SwaggerFile comes from
// to avoid CORS Problems with the backend
if (SwaggerUIContractService.getXAPIKey() && request.url !== url){
let requestUrl = URI(request.url);
requestUrl.addSearch("apikey", SwaggerUIContractService.getXAPIKey());
request.url = requestUrl.toString();
}
return request;
},
onComplete: function() {
$scope.$apply(function() {
$scope.definitionStatus = 'complete';
});
if (SwaggerUIContractService.getXAPIKey()){
ui.preauthorizeApiKey("X-API-Key", SwaggerUIContractService.getXAPIKey());
}
},
// do error handling in the responseInterceptor
responseInterceptor: function (response) {
if (response.status == 500 && response.ok === false) {
$scope.$apply(function() {
$scope.definitionStatus = 'error';
$scope.hasError = true;
});
}
return response;
}
};
// Remove try-out and authorize if the API is not public or has no contract
if (!(hasContract || hasPublicPublishedAPI)){
swaggerOptions.plugins = [];
swaggerOptions.plugins.push(DisableTryItOutPlugin, DisableAuthorizePlugin);
}
ui = SwaggerUIBundle(swaggerOptions);
$scope.hasDefinition = true;
} else {
$scope.hasDefinition = false;
}
});
}]);
} | the_stack |
import { TestBed, inject, fakeAsync } from '@angular/core/testing';
import * as sinon from 'sinon';
import * as chai from 'chai';
let should = chai.should();
let assert = chai.assert;
import { EditorFile } from './editor-file';
import { FileService } from './file.service';
import { ModelFile, BusinessNetworkDefinition, Script, AclFile, QueryFile } from 'composer-common';
import { ClientService } from './client.service';
describe('FileService', () => {
let sandbox;
let mockClientService;
let businessNetworkDefMock;
let modelFileMock;
let aclFileMock;
let scriptFileMock;
let queryFileMock;
beforeEach(() => {
modelFileMock = sinon.createStubInstance(ModelFile);
scriptFileMock = sinon.createStubInstance(Script);
aclFileMock = sinon.createStubInstance(AclFile);
queryFileMock = sinon.createStubInstance(QueryFile);
businessNetworkDefMock = sinon.createStubInstance(BusinessNetworkDefinition);
mockClientService = sinon.createStubInstance(ClientService);
sandbox = sinon.sandbox.create();
TestBed.configureTestingModule({
providers: [FileService,
{provide: ClientService, useValue: mockClientService}]
});
});
describe('getFile', () => {
it('should return model files when provided with the model file type', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the model', 'model');
let file2 = new EditorFile('2', '2', 'this is the 2 model', 'model');
let testModels = new Map<string, EditorFile>();
testModels.set('1', file);
testModels.set('2', file2);
fileService['modelFiles'] = testModels;
let testFile = fileService.getFile('1', 'model');
testFile.getId().should.equal('1');
testFile.getContent().should.equal('this is the model');
testFile.getType().should.equal('model');
})));
it('should return script files when provided with the script file type', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the script', 'script');
let file2 = new EditorFile('2', '2', 'this is the 2 script', 'script');
let testScripts = new Map<string, EditorFile>();
testScripts.set('1', file);
testScripts.set('2', file2);
fileService['scriptFiles'] = testScripts;
let testFile = fileService.getFile('1', 'script');
testFile.getId().should.equal('1');
testFile.getContent().should.equal('this is the script');
testFile.getType().should.equal('script');
})));
it('should return the query file when provided with the query file type', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the query', 'query');
fileService['queryFile'] = file;
let testFile = fileService.getFile('1', 'query');
testFile.getId().should.equal('1');
testFile.getContent().should.equal('this is the query');
testFile.getType().should.equal('query');
})));
it('should return the acl file when provided with the acl file type', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the acl', 'acl');
fileService['aclFile'] = file;
let testFile = fileService.getFile('1', 'acl');
testFile.getId().should.equal('1');
testFile.getContent().should.equal('this is the acl');
testFile.getType().should.equal('acl');
})));
it('should return the readme file when provided with the readme file type', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the readme', 'readme');
fileService['readMe'] = file;
let testFile = fileService.getFile('1', 'readme');
testFile.getId().should.equal('1');
testFile.getContent().should.equal('this is the readme');
testFile.getType().should.equal('readme');
})));
it('should return the packageJson file when provided with the package file type', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the packageJson', 'package');
fileService['packageJson'] = file;
let testFile = fileService.getFile('1', 'package');
testFile.getId().should.equal('1');
testFile.getContent().should.equal('this is the packageJson');
testFile.getType().should.equal('package');
})));
it('should throw an error if none of the above cases are matched', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let type = 'octopus';
(() => {
fileService.getFile(id, type);
}).should.throw(/Type passed must be one of readme, acl, query, script, model or packageJson/);
})));
});
describe('getReadMe', () => {
it('should return the readme file', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the readme', 'readme');
fileService['readMe'] = file;
let testReadMeFile = fileService.getEditorReadMe();
testReadMeFile.getId().should.equal('1');
testReadMeFile.getContent().should.equal('this is the readme');
testReadMeFile.getType().should.equal('readme');
})));
});
describe('getEditorModelFiles', () => {
it('should return all of the model files', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the model', 'model');
let file2 = new EditorFile('2', '2', 'this is the model 2', 'model');
let testModels = new Map<string, EditorFile>();
testModels.set('1', file);
testModels.set('2', file2);
fileService['modelFiles'] = testModels;
let testModelsArray = fileService.getEditorModelFiles();
testModelsArray[0].getId().should.equal('1');
testModelsArray[0].getContent().should.equal('this is the model');
testModelsArray[0].getType().should.equal('model');
testModelsArray[1].getId().should.equal('2');
testModelsArray[1].getContent().should.equal('this is the model 2');
testModelsArray[1].getType().should.equal('model');
})));
});
describe('getScriptFiles', () => {
it('should return all of the script files', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the script', 'script');
let file2 = new EditorFile('2', '2', 'this is the script 2', 'script');
let testScripts = new Map<string, EditorFile>();
testScripts.set('1', file);
testScripts.set('2', file2);
fileService['scriptFiles'] = testScripts;
let testScriptsArray = fileService.getEditorScriptFiles();
testScriptsArray[0].getId().should.equal('1');
testScriptsArray[0].getContent().should.equal('this is the script');
testScriptsArray[0].getType().should.equal('script');
testScriptsArray[1].getId().should.equal('2');
testScriptsArray[1].getContent().should.equal('this is the script 2');
testScriptsArray[1].getType().should.equal('script');
})));
});
describe('getAclFile', () => {
it('should return the acl file', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the acl', 'acl');
fileService['aclFile'] = file;
let testAclFile = fileService.getEditorAclFile();
testAclFile.getId().should.equal('1');
testAclFile.getContent().should.equal('this is the acl');
testAclFile.getType().should.equal('acl');
})));
});
describe('getQueryFile', () => {
it('should return the query file', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the query', 'query');
fileService['queryFile'] = file;
let testQueryFile = fileService.getEditorQueryFile();
testQueryFile.getId().should.equal('1');
testQueryFile.getContent().should.equal('this is the query');
testQueryFile.getType().should.equal('query');
})));
});
describe('getPackageFile', () => {
it('should return the package file', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the package', 'package');
fileService['packageJson'] = file;
let testPackageFile = fileService.getEditorPackageFile();
testPackageFile.getId().should.equal('1');
testPackageFile.getContent().should.equal('this is the package');
testPackageFile.getType().should.equal('package');
})));
});
describe('getEditorFiles', () => {
it('should return an empty array if no files stored in the file service', fakeAsync(inject([FileService], (fileService: FileService) => {
let testArray = fileService.getEditorFiles();
})));
it('should return the readme if only readme stored in the file service', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the readme', 'readme');
fileService['readMe'] = file;
let testArray = fileService.getEditorFiles();
testArray[0].getId().should.equal('1');
testArray[0].getContent().should.equal('this is the readme');
testArray[0].getType().should.equal('readme');
})));
it('should return readme + model files if they are only items stored in the file service', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the readme', 'readme');
let file2 = new EditorFile('1', '1', 'this is the model', 'model');
let testModels = new Map<string, EditorFile>();
testModels.set('1', file2);
fileService['readMe'] = file;
fileService['modelFiles'] = testModels;
let testArray = fileService.getEditorFiles();
testArray[0].getId().should.equal('1');
testArray[0].getContent().should.equal('this is the readme');
testArray[0].getType().should.equal('readme');
testArray[1].getId().should.equal('1');
testArray[1].getContent().should.equal('this is the model');
testArray[1].getType().should.equal('model');
})));
it('should return readme + model + script files if they are only items stored in the file service', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the readme', 'readme');
let file2 = new EditorFile('1', '1', 'this is the model', 'model');
let file3 = new EditorFile('1', '1', 'this is the script', 'script');
let testModels = new Map<string, EditorFile>();
let testScripts = new Map<string, EditorFile>();
testModels.set('1', file2);
testScripts.set('1', file3);
fileService['readMe'] = file;
fileService['modelFiles'] = testModels;
fileService['scriptFiles'] = testScripts;
let testArray = fileService.getEditorFiles();
testArray[0].getId().should.equal('1');
testArray[0].getContent().should.equal('this is the readme');
testArray[0].getType().should.equal('readme');
testArray[1].getId().should.equal('1');
testArray[1].getContent().should.equal('this is the model');
testArray[1].getType().should.equal('model');
testArray[2].getId().should.equal('1');
testArray[2].getContent().should.equal('this is the script');
testArray[2].getType().should.equal('script');
})));
it('should return readme + model + script + acl files if they are only items stored in the file service', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the readme', 'readme');
let file2 = new EditorFile('1', '1', 'this is the model', 'model');
let file3 = new EditorFile('1', '1', 'this is the script', 'script');
let file4 = new EditorFile('1', '1', 'this is the acl', 'acl');
let testModels = new Map<string, EditorFile>();
let testScripts = new Map<string, EditorFile>();
testModels.set('1', file2);
testScripts.set('1', file3);
fileService['readMe'] = file;
fileService['modelFiles'] = testModels;
fileService['scriptFiles'] = testScripts;
fileService['aclFile'] = file4;
let testArray = fileService.getEditorFiles();
testArray[0].getId().should.equal('1');
testArray[0].getContent().should.equal('this is the readme');
testArray[0].getType().should.equal('readme');
testArray[1].getId().should.equal('1');
testArray[1].getContent().should.equal('this is the model');
testArray[1].getType().should.equal('model');
testArray[2].getId().should.equal('1');
testArray[2].getContent().should.equal('this is the script');
testArray[2].getType().should.equal('script');
testArray[3].getId().should.equal('1');
testArray[3].getContent().should.equal('this is the acl');
testArray[3].getType().should.equal('acl');
})));
it('should return readme + model + script + acl + query files if they are only items stored in the file service', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the readme', 'readme');
let file2 = new EditorFile('1', '1', 'this is the model', 'model');
let file3 = new EditorFile('1', '1', 'this is the script', 'script');
let file4 = new EditorFile('1', '1', 'this is the acl', 'acl');
let file5 = new EditorFile('1', '1', 'this is the query', 'query');
let testModels = new Map<string, EditorFile>();
let testScripts = new Map<string, EditorFile>();
testModels.set('1', file2);
testScripts.set('1', file3);
fileService['readMe'] = file;
fileService['modelFiles'] = testModels;
fileService['scriptFiles'] = testScripts;
fileService['aclFile'] = file4;
fileService['queryFile'] = file5;
let testArray = fileService.getEditorFiles();
testArray[0].getId().should.equal('1');
testArray[0].getContent().should.equal('this is the readme');
testArray[0].getType().should.equal('readme');
testArray[1].getId().should.equal('1');
testArray[1].getContent().should.equal('this is the model');
testArray[1].getType().should.equal('model');
testArray[2].getId().should.equal('1');
testArray[2].getContent().should.equal('this is the script');
testArray[2].getType().should.equal('script');
testArray[3].getId().should.equal('1');
testArray[3].getContent().should.equal('this is the acl');
testArray[3].getType().should.equal('acl');
testArray[4].getId().should.equal('1');
testArray[4].getContent().should.equal('this is the query');
testArray[4].getType().should.equal('query');
})));
it('should return readme + pacakage + model + script + acl + query files if they are only items stored in the file service', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the readme', 'readme');
let file2 = new EditorFile('1', '1', 'this is the model', 'model');
let file3 = new EditorFile('1', '1', 'this is the script', 'script');
let file4 = new EditorFile('1', '1', 'this is the acl', 'acl');
let file5 = new EditorFile('1', '1', 'this is the query', 'query');
let file6 = new EditorFile('1', '1', 'this is the package', 'package');
let testModels = new Map<string, EditorFile>();
let testScripts = new Map<string, EditorFile>();
testModels.set('1', file2);
testScripts.set('1', file3);
fileService['readMe'] = file;
fileService['modelFiles'] = testModels;
fileService['scriptFiles'] = testScripts;
fileService['aclFile'] = file4;
fileService['queryFile'] = file5;
fileService['packageJson'] = file6;
let testArray = fileService.getEditorFiles();
testArray[0].getId().should.equal('1');
testArray[0].getContent().should.equal('this is the readme');
testArray[0].getType().should.equal('readme');
testArray[1].getId().should.equal('1');
testArray[1].getContent().should.equal('this is the package');
testArray[1].getType().should.equal('package');
testArray[2].getId().should.equal('1');
testArray[2].getContent().should.equal('this is the model');
testArray[2].getType().should.equal('model');
testArray[3].getId().should.equal('1');
testArray[3].getContent().should.equal('this is the script');
testArray[3].getType().should.equal('script');
testArray[4].getId().should.equal('1');
testArray[4].getContent().should.equal('this is the acl');
testArray[4].getType().should.equal('acl');
testArray[5].getId().should.equal('1');
testArray[5].getContent().should.equal('this is the query');
testArray[5].getType().should.equal('query');
})));
});
describe('addFile', () => {
it('should add a new model file if one with the same ID does not exist', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let displayID = '1';
let content = 'this is the model';
let type = 'model';
fileService.addFile(id, displayID, content, type);
let testModels = fileService.getEditorModelFiles();
testModels[0].getId().should.equal('1');
testModels[0].getContent().should.equal('this is the model');
testModels[0].getType().should.equal('model');
fileService['dirty'].should.equal(true);
})));
it('should throw an error when trying to add a model file with existing ID', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the model', 'model');
let testModels = new Map<string, EditorFile>();
testModels.set('1', file);
fileService['modelFiles'] = testModels;
let id = '1';
let displayID = '1';
let content = 'this is the model';
let type = 'model';
(() => {
fileService.addFile(id, displayID, content, type);
}).should.throw(/FileService already contains model file with ID: 1/);
fileService['dirty'].should.equal(false);
})));
it('should add a new script file if one with the same ID does not exist', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let displayID = '1';
let content = 'this is the script';
let type = 'script';
fileService.addFile(id, displayID, content, type);
let testScripts = fileService.getEditorScriptFiles();
testScripts[0].getId().should.equal('1');
testScripts[0].getContent().should.equal('this is the script');
testScripts[0].getType().should.equal('script');
fileService['dirty'].should.equal(true);
})));
it('should throw an error when trying to add a script file with existing ID', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the script', 'script');
let testScripts = new Map<string, EditorFile>();
testScripts.set('1', file);
fileService['scriptFiles'] = testScripts;
let id = '1';
let displayID = '1';
let content = 'this is the script';
let type = 'script';
(() => {
fileService.addFile(id, displayID, content, type);
}).should.throw(/FileService already contains script file with ID: 1/);
fileService['dirty'].should.equal(false);
})));
it('should add a new query file if one with the same ID does not exist', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let displayID = '1';
let content = 'this is the query';
let type = 'query';
fileService.addFile(id, displayID, content, type);
let testQuery = fileService.getEditorQueryFile();
testQuery.getId().should.equal('1');
testQuery.getContent().should.equal('this is the query');
testQuery.getType().should.equal('query');
fileService['dirty'].should.equal(true);
})));
it('should throw an error when trying to add a query file with existing ID', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the query', 'query');
fileService['queryFile'] = file;
let id = '1';
let displayID = '1';
let content = 'this is the query';
let type = 'query';
(() => {
fileService.addFile(id, displayID, content, type);
}).should.throw(/FileService already contains a query file/);
fileService['dirty'].should.equal(false);
})));
it('should add a new acl file if one with the same ID does not exist', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let displayID = '1';
let content = 'this is the acl';
let type = 'acl';
fileService.addFile(id, displayID, content, type);
let testAcl = fileService.getEditorAclFile();
testAcl.getId().should.equal('1');
testAcl.getContent().should.equal('this is the acl');
testAcl.getType().should.equal('acl');
fileService['dirty'].should.equal(true);
})));
it('should throw an error when trying to add an acl file with existing ID', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the acl', 'acl');
fileService['aclFile'] = file;
let id = '1';
let displayID = '1';
let content = 'this is the acl';
let type = 'acl';
(() => {
fileService.addFile(id, displayID, content, type);
}).should.throw(/FileService already contains an acl file/);
fileService['dirty'].should.equal(false);
})));
it('should add a new readme if one with the same ID does not exist', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let displayID = '1';
let content = 'this is the readme';
let type = 'readme';
fileService.addFile(id, displayID, content, type);
let testReadMe = fileService.getEditorReadMe();
testReadMe.getId().should.equal('1');
testReadMe.getContent().should.equal('this is the readme');
testReadMe.getType().should.equal('readme');
fileService['dirty'].should.equal(true);
})));
it('should throw an error when trying to add a readme file with existing ID', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the readme', 'readme');
fileService['readMe'] = file;
let id = '1';
let displayID = '1';
let content = 'this is the readme';
let type = 'readme';
(() => {
fileService.addFile(id, displayID, content, type);
}).should.throw(/FileService already contains a readme file/);
fileService['dirty'].should.equal(false);
})));
it('should add a new package if one with the same ID does not exist', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let displayID = '1';
let content = 'this is the package';
let type = 'package';
fileService.addFile(id, displayID, content, type);
let testPackage = fileService.getEditorPackageFile();
testPackage.getId().should.equal('1');
testPackage.getContent().should.equal('this is the package');
testPackage.getType().should.equal('package');
fileService['dirty'].should.equal(true);
})));
it('should throw an error when trying to add a package file with existing ID', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the package', 'package');
fileService['packageJson'] = file;
let id = '1';
let displayID = '1';
let content = 'this is the package';
let type = 'package';
(() => {
fileService.addFile(id, displayID, content, type);
}).should.throw(/FileService already contains a package.json file/);
fileService['dirty'].should.equal(false);
})));
it('should default to throwing an error', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let displayID = '1';
let content = 'this is the octopus';
let type = 'octopus';
(() => {
fileService.addFile(id, displayID, content, type);
}).should.throw(/Attempted addition of unknown file type: octopus/);
fileService['dirty'].should.equal(false);
})));
});
describe('incrementBusinessNetworkVersion', () => {
it('should increment prerelease version in the packageJson file', inject([FileService], (fileService: FileService) => {
let businessNetworkChangedSpy = sinon.spy(fileService.businessNetworkChanged$, 'next');
let file = new EditorFile('package', 'package', JSON.stringify({name: 'composer-ftw', version: '1.0.0'}), 'package');
fileService['packageJson'] = file;
fileService.incrementBusinessNetworkVersion();
fileService['packageJson'].getContent().should.equal('{\n "name": "composer-ftw",\n "version": "1.0.1-deploy.0"\n}');
fileService['dirty'].should.equal(false);
businessNetworkChangedSpy.should.have.been.calledWith(true);
}));
});
describe('updateBusinessNetworkVersion', () => {
it('should update version in the packageJson file', inject([FileService], (fileService: FileService) => {
let file = new EditorFile('package', 'package', JSON.stringify({name: 'composer-ftw', version: '1.0.0'}), 'package');
fileService['packageJson'] = file;
sinon.stub(fileService, 'validateFile').returns(null);
let updatedPackageFile = fileService.updateBusinessNetworkVersion('1.0.1-test.0');
updatedPackageFile.getContent().should.equal('{\n "name": "composer-ftw",\n "version": "1.0.1-test.0"\n}');
fileService['packageJson'].should.deep.equal(updatedPackageFile);
fileService['dirty'].should.equal(true);
}));
});
describe('updateFile', () => {
it('should update the correct model file', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the model', 'model');
let testModels = new Map<string, EditorFile>();
let id = '1';
let content = 'this is the NEW model';
let type = 'model';
testModels.set('1', file);
sinon.stub(fileService, 'getModelFile');
sinon.stub(fileService, 'validateFile').returns(null);
fileService['modelFiles'] = testModels;
fileService.updateFile(id, content, type);
let testFile = fileService.getFile('1', 'model');
testFile.getId().should.equal('1');
testFile.getContent().should.equal('this is the NEW model');
testFile.getType().should.equal('model');
fileService['dirty'].should.equal(true);
})));
it('should update the correct model file with a namespace change', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the model', 'model');
let testModels = new Map<string, EditorFile>();
let id = '1';
let content = 'this is the NEW model';
let type = 'model';
testModels.set('1', file);
sinon.stub(fileService, 'getModelFile').returns({getName: sinon.stub().returns('myName')});
sinon.stub(fileService, 'modelNamespaceCollides').returns(false);
sinon.stub(fileService, 'createModelFile').returns({
getNamespace: sinon.stub().returns('myNamespace'),
getName: sinon.stub().returns('myName'),
getDefinitions: sinon.stub().returns('myDefs')
});
sinon.stub(fileService, 'validateFile').returns(null);
let addFileStub = sinon.stub(fileService, 'addFile').returns('myFile');
let deleteFileStub = sinon.stub(fileService, 'deleteFile');
fileService['modelFiles'] = testModels;
let result = fileService.updateFile(id, content, type);
result.should.equal('myFile');
let testFile = fileService.getFile('1', 'model');
testFile.getId().should.equal('1');
testFile.getContent().should.equal('this is the NEW model');
testFile.getType().should.equal('model');
deleteFileStub.should.have.been.called;
fileService['dirty'].should.equal(true);
})));
it('should return if namespace collides', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the model', 'model');
let testModels = new Map<string, EditorFile>();
let id = '1';
let content = 'this is the NEW model';
let type = 'model';
testModels.set('1', file);
let addFileStub = sinon.stub(fileService, 'addFile').returns('myFile');
sinon.stub(fileService, 'getModelFile').returns({getName: sinon.stub().returns('myName')});
sinon.stub(fileService, 'modelNamespaceCollides').returns(true);
sinon.stub(fileService, 'createModelFile').returns({
getNamespace: sinon.stub().returns('myNamespace'),
getName: sinon.stub().returns('myName'),
getDefinitions: sinon.stub().returns('myDefs')
});
sinon.stub(fileService, 'validateFile').returns(null);
fileService['modelFiles'] = testModels;
fileService.updateFile(id, content, type);
fileService['dirty'].should.equal(false);
addFileStub.should.not.have.been.called;
})));
it('should throw an error if validate file returns a message for model files', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the model', 'model');
let testModels = new Map<string, EditorFile>();
let id = '1';
let content = 'this is the NEW model';
let type = 'model';
testModels.set('1', file);
sinon.stub(fileService, 'getModelFile').returns({getName: sinon.stub().returns('myName')});
sinon.stub(fileService, 'createModelFile').returns({
getNamespace: sinon.stub().returns('myNamespace'),
getName: sinon.stub().returns('myName'),
getDefinitions: sinon.stub().returns('myDefs')
});
sinon.stub(fileService, 'validateFile').returns('Validator error message');
fileService['modelFiles'] = testModels;
(() => {
fileService.updateFile(id, content, type);
}).should.throw(/Validator error message/);
fileService['dirty'].should.equal(false);
})));
it('should throw an error if there is no model file with the given ID', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let content = 'this is the NEW model';
let type = 'model';
(() => {
fileService.updateFile(id, content, type);
}).should.throw(/File does not exist of type model and id 1/);
fileService['dirty'].should.equal(false);
})));
it('should update the correct model file with a not namespace', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the model', 'model');
let testModels = new Map<string, EditorFile>();
let id = '1';
let content = 'this is the NEW model';
let type = 'model';
testModels.set('1', file);
sinon.stub(fileService, 'getModelFile').returns({getName: sinon.stub().returns('myName')});
sinon.stub(fileService, 'createModelFile').returns({
getNamespace: sinon.stub().returns('1'),
getName: sinon.stub().returns('myName'),
getDefinitions: sinon.stub().returns('myDefs')
});
sinon.stub(fileService, 'modelNamespaceCollides').returns(false);
sinon.stub(fileService, 'validateFile').returns(null);
let addFileStub = sinon.stub(fileService, 'addFile');
fileService['modelFiles'] = testModels;
fileService.updateFile(id, content, type);
let testFile = fileService.getFile('1', 'model');
testFile.getId().should.equal('1');
testFile.getContent().should.equal('this is the NEW model');
testFile.getType().should.equal('model');
addFileStub.should.not.have.been.called;
fileService['dirty'].should.equal(true);
})));
it('should update the correct script file', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the script', 'script');
let testScripts = new Map<string, EditorFile>();
sinon.stub(fileService, 'validateFile').returns(null);
let id = '1';
let content = 'this is the NEW script';
let type = 'script';
testScripts.set('1', file);
fileService['scriptFiles'] = testScripts;
fileService.updateFile(id, content, type);
let testFile = fileService.getFile('1', 'script');
testFile.getId().should.equal('1');
testFile.getContent().should.equal('this is the NEW script');
testFile.getType().should.equal('script');
fileService['dirty'].should.equal(true);
})));
it('should through an error if validate file on the script returns something', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the script', 'script');
let testScripts = new Map<string, EditorFile>();
sinon.stub(fileService, 'validateFile').returns('Validator error message');
let id = '1';
let content = 'this is the NEW script';
let type = 'script';
testScripts.set('1', file);
fileService['scriptFiles'] = testScripts;
(() => {
fileService.updateFile(id, content, type);
}).should.throw(/Validator error message/);
fileService['dirty'].should.equal(false);
})));
it('should throw an error if there is no script file with the given ID', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let content = 'this is the NEW script';
let type = 'script';
(() => {
fileService.updateFile(id, content, type);
}).should.throw(/File does not exist of type script and id 1/);
fileService['dirty'].should.equal(false);
})));
it('should update the correct query file', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the query', 'query');
let id = '1';
let content = 'this is the NEW query';
let type = 'query';
fileService['queryFile'] = file;
sinon.stub(fileService, 'validateFile').returns(null);
fileService.updateFile(id, content, type);
let testFile = fileService.getFile('1', 'query');
testFile.getId().should.equal('1');
testFile.getContent().should.equal('this is the NEW query');
testFile.getType().should.equal('query');
fileService['dirty'].should.equal(true);
})));
it('should through an error if validate file on the query returns something', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the query', 'query');
let id = '1';
let content = 'this is the NEW query';
let type = 'query';
fileService['queryFile'] = file;
sinon.stub(fileService, 'validateFile').returns('Validator error message');
(() => {
fileService.updateFile(id, content, type);
}).should.throw(/Validator error message/);
fileService['dirty'].should.equal(false);
})));
it('should throw an error if there is no query file with the given ID', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let content = 'this is the NEW query';
let type = 'query';
(() => {
fileService.updateFile(id, content, type);
}).should.throw(/Query file does not exist in file service/);
fileService['dirty'].should.equal(false);
})));
it('should update the correct acl file', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the acl', 'acl');
sinon.stub(fileService, 'validateFile').returns(null);
let id = '1';
let content = 'this is the NEW acl';
let type = 'acl';
fileService['aclFile'] = file;
fileService.updateFile(id, content, type);
let testFile = fileService.getFile('1', 'acl');
testFile.getId().should.equal('1');
testFile.getContent().should.equal('this is the NEW acl');
testFile.getType().should.equal('acl');
fileService['dirty'].should.equal(true);
})));
it('should through an error if validate file on the acl returns something', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the acl', 'acl');
sinon.stub(fileService, 'validateFile').returns('Validator error message');
let id = '1';
let content = 'this is the NEW acl';
let type = 'acl';
fileService['aclFile'] = file;
(() => {
fileService.updateFile(id, content, type);
}).should.throw(/Validator error message/);
fileService['dirty'].should.equal(false);
})));
it('should throw an error if there is no acl file with the given ID', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let content = 'this is the NEW acl';
let type = 'acl';
(() => {
fileService.updateFile(id, content, type);
}).should.throw(/Acl file does not exist in file service/);
fileService['dirty'].should.equal(false);
})));
it('should update the correct readme file', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the readme', 'readme');
let id = '1';
let content = 'this is the NEW readme';
let type = 'readme';
fileService['readMe'] = file;
fileService.updateFile(id, content, type);
let testFile = fileService.getFile('1', 'readme');
testFile.getId().should.equal('1');
testFile.getContent().should.equal('this is the NEW readme');
testFile.getType().should.equal('readme');
fileService['dirty'].should.equal(true);
})));
it('should throw an error if there is no readme file with the given ID', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let content = 'this is the NEW readme';
let type = 'readme';
(() => {
fileService.updateFile(id, content, type);
}).should.throw(/ReadMe file does not exist in file service/);
fileService['dirty'].should.equal(false);
})));
it('should update the correct packageJson file', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', '{"name" : "this is the NEW packageJson"}', 'package');
let id = '1';
let content = '{"name" : "this is the NEW packageJson"}';
let type = 'package';
fileService['packageJson'] = file;
sinon.stub(fileService, 'validateFile').returns(null);
fileService.updateFile(id, content, type);
let testFile = fileService.getFile('1', 'package');
testFile.getId().should.equal('1');
testFile.getContent().should.deep.equal('{"name" : "this is the NEW packageJson"}');
testFile.getType().should.equal('package');
fileService['dirty'].should.equal(true);
})));
it('should through an error if validate file on the packageJSON returns something', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', '{"name" : "this is the NEW packageJson"}', 'package');
let id = '1';
let content = '{"name" : "this is the NEW packageJson"}';
let type = 'package';
fileService['packageJson'] = file;
sinon.stub(fileService, 'validateFile').returns('Validator error message');
(() => {
fileService.updateFile(id, content, type);
}).should.throw(/Validator error message/);
fileService['dirty'].should.equal(false);
})));
it('should throw an error if there is no packageJson file with the given ID', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let content = 'this is the NEW packageJson';
let type = 'package';
(() => {
fileService.updateFile(id, content, type);
}).should.throw(/PackageJson file does not exist in file service/);
fileService['dirty'].should.equal(false);
})));
it('should default to throwing an error', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let content = 'this is the octopus';
let type = 'octopus';
(() => {
fileService.updateFile(id, content, type);
}).should.throw(/Attempted update of unknown file type: octopus/);
fileService['dirty'].should.equal(false);
})));
});
describe('deleteFile', () => {
it('should delete the correct model file', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the model', 'model');
let testModels = new Map<string, EditorFile>();
testModels.set('1', file);
fileService['modelFiles'] = testModels;
let id = '1';
let type = 'model';
fileService.deleteFile(id, type);
should.not.exist(testModels.get('1'));
fileService['dirty'].should.equal(true);
})));
it('should delete the correct script file', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the script', 'script');
let testScripts = new Map<string, EditorFile>();
testScripts.set('1', file);
fileService['scriptFiles'] = testScripts;
let id = '1';
let type = 'script';
fileService.deleteFile(id, type);
should.not.exist(testScripts.get('1'));
fileService['dirty'].should.equal(true);
})));
it('should delete the correct query file', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the query', 'query');
let id = '1';
let type = 'query';
fileService['queryFile'] = file;
fileService.deleteFile(id, type);
let testQuery = fileService.getEditorQueryFile();
should.not.exist(testQuery);
fileService['dirty'].should.equal(true);
})));
it('should delete the correct acl file', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the acl', 'acl');
let id = '1';
let type = 'acl';
fileService['aclFile'] = file;
fileService.deleteFile(id, type);
let testAcl = fileService.getEditorAclFile();
should.not.exist(testAcl);
fileService['dirty'].should.equal(true);
})));
it('should delete the correct readme file', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the readme', 'readme');
let id = '1';
let type = 'readme';
fileService['readMe'] = file;
fileService.deleteFile(id, type);
let testReadMe = fileService.getEditorReadMe();
should.not.exist(testReadMe);
fileService['dirty'].should.equal(true);
})));
it('should delete the correct package file', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the package', 'package');
let id = '1';
let type = 'package';
fileService['packageJson'] = file;
fileService.deleteFile(id, type);
let testPackage = fileService.getEditorPackageFile();
should.not.exist(testPackage);
fileService['dirty'].should.equal(true);
})));
it('should default to throwing an error', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let type = 'octopus';
(() => {
fileService.deleteFile(id, type);
}).should.throw(/Attempted deletion of file unknown type: octopus/);
fileService['dirty'].should.equal(false);
})));
it('should unset the current file if it was deleted', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the model', 'model');
let testModels = new Map<string, EditorFile>();
testModels.set('1', file);
fileService['currentFile'] = file;
fileService['modelFiles'] = testModels;
let id = '1';
let type = 'model';
fileService.deleteFile(id, type);
should.not.exist(fileService['currentFile']);
should.not.exist(testModels.get('1'));
fileService['dirty'].should.equal(true);
})));
});
describe('deleteAllFiles', () => {
it('should delete all files', fakeAsync(inject([FileService], (fileService: FileService) => {
let file = new EditorFile('1', '1', 'this is the readme', 'readme');
let file2 = new EditorFile('1', '1', 'this is the model', 'model');
let file3 = new EditorFile('1', '1', 'this is the script', 'script');
let file4 = new EditorFile('1', '1', 'this is the acl', 'acl');
let file5 = new EditorFile('1', '1', 'this is the query', 'query');
let testModels = new Map<string, EditorFile>();
let testScripts = new Map<string, EditorFile>();
testModels.set('1', file2);
testScripts.set('1', file3);
fileService['readMe'] = file;
fileService['modelFiles'] = testModels;
fileService['scriptFiles'] = testScripts;
fileService['aclFile'] = file4;
fileService['queryFile'] = file5;
fileService.deleteAllFiles();
let testReadMe = fileService.getEditorReadMe();
let testAcl = fileService.getEditorAclFile();
let testQuery = fileService.getEditorQueryFile();
should.not.exist(testReadMe);
should.not.exist(testModels.get('1'));
should.not.exist(testScripts.get('1'));
should.not.exist(testAcl);
should.not.exist(testQuery);
fileService['dirty'].should.equal(true);
})));
});
describe('replaceFile', () => {
it('should throw an error if there in no model file with the given "file to replace" ID', fakeAsync(inject([FileService], (fileService: FileService) => {
let oldId = '1';
let newId = '2';
let content = 'this is the replacement model file';
let type = 'model';
(() => {
fileService.replaceFile(oldId, newId, content, type);
}).should.throw(/There is no existing file of type model with the id 1/);
fileService['dirty'].should.equal(false);
})));
it('should throw an error if there is an existing model file with the given replacement file ID', fakeAsync(inject([FileService], (fileService: FileService) => {
let oldId = '2';
let newId = '3';
let content = 'this is the replacement model file';
let type = 'model';
let file = new EditorFile('2', '2', 'this is the model', 'model');
let file2 = new EditorFile('3', '3', 'this is the other model', 'model');
let testModels = new Map<string, EditorFile>();
testModels.set('2', file);
testModels.set('3', file2);
fileService['modelFiles'] = testModels;
(() => {
fileService.replaceFile(oldId, newId, content, type);
}).should.throw(/There is an existing file of type model with the id 2/);
fileService['dirty'].should.equal(false);
})));
it('should throw an error if there in no script file with the given "file to replace" ID', fakeAsync(inject([FileService], (fileService: FileService) => {
let oldId = '1';
let newId = '2';
let content = 'this is the replacement script file';
let type = 'script';
(() => {
fileService.replaceFile(oldId, newId, content, type);
}).should.throw(/There is no existing file of type script with the id 1/);
fileService['dirty'].should.equal(false);
})));
it('should throw an error if there is an existing script file with the given replacement file ID', fakeAsync(inject([FileService], (fileService: FileService) => {
let oldId = '2';
let newId = '3';
let content = 'this is the replacement script file';
let type = 'script';
let file = new EditorFile('2', '2', 'this is the script', 'script');
let file2 = new EditorFile('3', '3', 'this is the other script', 'script');
let testScripts = new Map<string, EditorFile>();
testScripts.set('2', file);
testScripts.set('3', file2);
fileService['scriptFiles'] = testScripts;
(() => {
fileService.replaceFile(oldId, newId, content, type);
}).should.throw(/There is an existing file of type script with the id 2/);
fileService['dirty'].should.equal(false);
})));
it('should default to throw an error', fakeAsync(inject([FileService], (fileService: FileService) => {
let oldId = '1';
let newId = '2';
let content = 'this is the replacement octopus';
let type = 'octopus';
(() => {
fileService.replaceFile(oldId, newId, content, type);
}).should.throw(/Attempted replace of ununsupported file type: octopus/);
fileService['dirty'].should.equal(false);
})));
it('should correctly replace a model file', fakeAsync(inject([FileService], (fileService: FileService) => {
let oldId = '1';
let newId = '2';
let content = 'this is the replacement model file';
let type = 'model';
modelFileMock.getNamespace.returns('model-ns');
modelFileMock.getName.returns('model-name');
sinon.stub(fileService, 'createModelFile').returns(modelFileMock);
let file = new EditorFile('1', '1', 'this is the model', 'model');
let testModels = new Map<string, EditorFile>();
testModels.set('1', file);
fileService['modelFiles'] = testModels;
let replacedFile = fileService.replaceFile(oldId, newId, content, type);
fileService['dirty'].should.equal(true);
})));
it('should correctly replace a model file', fakeAsync(inject([FileService], (fileService: FileService) => {
let oldId = '1';
let newId = '2';
let content = 'this is the replacement model file';
let type = 'model';
modelFileMock.getNamespace.returns('model-ns');
modelFileMock.getName.returns('model-name');
let createmodelMock = sinon.stub(fileService, 'createModelFile');
createmodelMock.onCall(0).throws();
createmodelMock.onCall(1).returns(modelFileMock);
let file = new EditorFile('1', '1', 'this is the model', 'model');
let testModels = new Map<string, EditorFile>();
testModels.set('1', file);
fileService['modelFiles'] = testModels;
let replacedFile = fileService.replaceFile(oldId, newId, content, type);
fileService['dirty'].should.equal(true);
})));
it('should correctly replace a model file', fakeAsync(inject([FileService], (fileService: FileService) => {
let oldId = '1';
let newId = '2';
let content = 'this is the replacement model file';
let type = 'model';
modelFileMock.getNamespace.returns('model-ns');
modelFileMock.getName.returns('model-name');
let createmodelMock = sinon.stub(fileService, 'createModelFile');
createmodelMock.onCall(0).throws();
createmodelMock.onCall(1).throws();
createmodelMock.onCall(2).returns(modelFileMock);
let file = new EditorFile('1', '1', 'this is the model', 'model');
let testModels = new Map<string, EditorFile>();
testModels.set('1', file);
fileService['modelFiles'] = testModels;
(() => {
fileService.replaceFile(oldId, newId, content, type);
}).should.throw();
fileService['dirty'].should.equal(false);
})));
it('should correctly replace a script file', fakeAsync(inject([FileService], (fileService: FileService) => {
let oldId = '1';
let newId = '2';
let content = 'this is the replacement script file';
let type = 'script';
let file = new EditorFile('1', '1', 'this is the script', 'script');
let testScripts = new Map<string, EditorFile>();
testScripts.set('1', file);
fileService['scriptFiles'] = testScripts;
let replacedFile = fileService.replaceFile(oldId, newId, content, type);
replacedFile.getId().should.equal('2');
replacedFile.getContent().should.equal('this is the script');
replacedFile.getType().should.equal('script');
fileService['dirty'].should.equal(true);
})));
});
describe('validateFile', () => {
it('should validate a given model file', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let type = 'model';
let testModels = new Map<string, EditorFile>();
let testScripts = new Map<string, EditorFile>();
businessNetworkDefMock.getModelManager.returns({getModelFile: sinon.stub()});
fileService['currentBusinessNetwork'] = businessNetworkDefMock;
let mockModelFile = sinon.createStubInstance(EditorFile);
mockModelFile.validate.returns(null);
// cases to throw if validation slips in to incorrect case.
let mockScriptFile = sinon.createStubInstance(EditorFile);
mockScriptFile.validate.throws('should not be called');
let mockAclFile = sinon.createStubInstance(EditorFile);
mockAclFile.validate.throws('should not be called');
let mockQueryFile = sinon.createStubInstance(EditorFile);
mockScriptFile.validate.throws('should not be called');
testModels.set('1', mockModelFile);
testScripts.set('1', mockScriptFile);
fileService['modelFiles'] = testModels;
fileService['scriptFiles'] = testScripts;
fileService['aclFile'] = mockAclFile;
fileService['queryFile'] = mockQueryFile;
should.not.exist(fileService.validateFile(id, type));
})));
it('should throw an error if namespace collides given model file', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let type = 'model';
let testModels = new Map<string, EditorFile>();
let testScripts = new Map<string, EditorFile>();
businessNetworkDefMock.getModelManager.returns({getModelFile: sinon.stub().returns({getName: sinon.stub().returns('myName')})});
fileService['currentBusinessNetwork'] = businessNetworkDefMock;
sinon.stub(fileService, 'createModelFile').returns({getNamespace: sinon.stub().returns('myNamespace')});
let mockNamspaceCollides = sinon.stub(fileService, 'modelNamespaceCollides').returns(true);
let mockModelFile = sinon.createStubInstance(EditorFile);
mockModelFile.validate.returns(null);
// cases to throw if validation slips in to incorrect case.
let mockScriptFile = sinon.createStubInstance(EditorFile);
mockScriptFile.validate.throws('should not be called');
let mockAclFile = sinon.createStubInstance(EditorFile);
mockAclFile.validate.throws('should not be called');
let mockQueryFile = sinon.createStubInstance(EditorFile);
mockScriptFile.validate.throws('should not be called');
testModels.set('1', mockModelFile);
testScripts.set('1', mockScriptFile);
fileService['modelFiles'] = testModels;
fileService['scriptFiles'] = testScripts;
fileService['aclFile'] = mockAclFile;
fileService['queryFile'] = mockQueryFile;
let result = fileService.validateFile(id, type);
result.toString().should.equal('Error: The namespace collides with existing model namespace myNamespace');
})));
it('should validate if already exists', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let type = 'model';
let testModels = new Map<string, EditorFile>();
let testScripts = new Map<string, EditorFile>();
businessNetworkDefMock.getModelManager.returns({getModelFile: sinon.stub().returns({getName: sinon.stub().returns('myName')})});
fileService['currentBusinessNetwork'] = businessNetworkDefMock;
sinon.stub(fileService, 'createModelFile').returns({getNamespace: sinon.stub().returns('myNamespace')});
let mockNamspaceCollides = sinon.stub(fileService, 'modelNamespaceCollides').returns(false);
let mockModelFile = sinon.createStubInstance(EditorFile);
mockModelFile.validate.returns(null);
// cases to throw if validation slips in to incorrect case.
let mockScriptFile = sinon.createStubInstance(EditorFile);
mockScriptFile.validate.throws('should not be called');
let mockAclFile = sinon.createStubInstance(EditorFile);
mockAclFile.validate.throws('should not be called');
let mockQueryFile = sinon.createStubInstance(EditorFile);
mockScriptFile.validate.throws('should not be called');
testModels.set('1', mockModelFile);
testScripts.set('1', mockScriptFile);
fileService['modelFiles'] = testModels;
fileService['scriptFiles'] = testScripts;
fileService['aclFile'] = mockAclFile;
fileService['queryFile'] = mockQueryFile;
should.not.exist(fileService.validateFile(id, type));
})));
it('should validate a given script file', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let type = 'script';
let testScripts = new Map<string, EditorFile>();
let testModels = new Map<string, EditorFile>();
fileService['currentBusinessNetwork'] = businessNetworkDefMock;
let mockScriptFile = sinon.createStubInstance(EditorFile);
mockScriptFile.validate.returns(null);
// cases to throw if validation slips in to incorrect case.
let mockModelFile = sinon.createStubInstance(EditorFile);
mockModelFile.validate.throws('should not be called');
let mockAclFile = sinon.createStubInstance(EditorFile);
mockAclFile.validate.throws('should not be called');
let mockQueryFile = sinon.createStubInstance(EditorFile);
mockQueryFile.validate.throws('should not be called');
testScripts.set('1', mockScriptFile);
testModels.set('1', mockModelFile);
fileService['modelFiles'] = testModels;
fileService['scriptFiles'] = testScripts;
fileService['aclFile'] = mockAclFile;
fileService['queryFile'] = mockQueryFile;
should.not.exist(fileService.validateFile(id, type));
})));
it('should validate a given acl file', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let type = 'acl';
let testScripts = new Map<string, EditorFile>();
let testModels = new Map<string, EditorFile>();
fileService['currentBusinessNetwork'] = businessNetworkDefMock;
let mockAclFile = sinon.createStubInstance(EditorFile);
mockAclFile.validate.returns(null);
// cases to throw if validation slips in to incorrect case.
let mockScriptFile = sinon.createStubInstance(EditorFile);
mockScriptFile.validate.throws('should not be called');
let mockModelFile = sinon.createStubInstance(EditorFile);
mockModelFile.validate.throws('should not be called');
let mockQueryFile = sinon.createStubInstance(EditorFile);
mockScriptFile.validate.throws('should not be called');
testModels.set('1', mockModelFile);
testScripts.set('1', mockScriptFile);
fileService['modelFiles'] = testModels;
fileService['scriptFiles'] = testScripts;
fileService['aclFile'] = mockAclFile;
fileService['queryFile'] = mockQueryFile;
should.not.exist(fileService.validateFile(id, type));
})));
it('should validate a given query file', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let type = 'query';
let testScripts = new Map<string, EditorFile>();
let testModels = new Map<string, EditorFile>();
fileService['currentBusinessNetwork'] = businessNetworkDefMock;
let mockQueryFile = sinon.createStubInstance(EditorFile);
mockQueryFile.validate.returns(null);
// cases to throw if validation slips in to incorrect case.
let mockScriptFile = sinon.createStubInstance(EditorFile);
mockScriptFile.validate.throws('should not be called');
let mockAclFile = sinon.createStubInstance(EditorFile);
mockAclFile.validate.throws('should not be called');
let mockModelFile = sinon.createStubInstance(EditorFile);
mockModelFile.validate.throws('should not be called');
testModels.set('1', mockModelFile);
testScripts.set('1', mockScriptFile);
fileService['modelFiles'] = testModels;
fileService['scriptFiles'] = testScripts;
fileService['aclFile'] = mockAclFile;
fileService['queryFile'] = mockQueryFile;
should.not.exist(fileService.validateFile(id, type));
})));
it('should successfully validate package file', inject([FileService], (fileService: FileService) => {
mockClientService.getDeployedBusinessNetworkVersion.returns('1.0.0');
fileService['currentBusinessNetwork'] = businessNetworkDefMock;
businessNetworkDefMock.getMetadata.returns({
getName: sinon.stub().returns('myName')
});
let packageFile = new EditorFile('package', 'package', 'myContent', 'package');
packageFile.setJsonContent({name: 'myName', version: '1.0.1'});
fileService['packageJson'] = packageFile;
should.not.exist(fileService.validateFile('package', 'package'));
}));
it('should validate package file and throw an error if the package name changes', inject([FileService], (fileService: FileService) => {
mockClientService.getDeployedBusinessNetworkVersion.returns('1.0.0');
fileService['currentBusinessNetwork'] = businessNetworkDefMock;
businessNetworkDefMock.getMetadata.returns({
getName: sinon.stub().returns('oldName')
});
let packageFile = new EditorFile('package', 'package', 'myContent', 'package');
packageFile.setJsonContent({name: 'myName', version: '1.0.1'});
fileService['packageJson'] = packageFile;
let result = fileService.validateFile('package', 'package');
result.toString().should.contain('Unsupported attempt to update Business Network Name.');
}));
it('should validate package file and throw an error if the version matches the deployed version', inject([FileService], (fileService: FileService) => {
mockClientService.getDeployedBusinessNetworkVersion.returns('1.0.0');
fileService['currentBusinessNetwork'] = businessNetworkDefMock;
businessNetworkDefMock.getMetadata.returns({
getName: sinon.stub().returns('myName')
});
let packageFile = new EditorFile('package', 'package', 'myContent', 'package');
packageFile.setJsonContent({name: 'myName', version: '1.0.0'});
fileService['packageJson'] = packageFile;
let result = fileService.validateFile('package', 'package');
result.toString().should.contain('The Business Network has already been deployed at the current version.');
}));
it('should validate package file and throw an error if the version older than the deployed version', inject([FileService], (fileService: FileService) => {
mockClientService.getDeployedBusinessNetworkVersion.returns('1.0.1');
fileService['currentBusinessNetwork'] = businessNetworkDefMock;
businessNetworkDefMock.getMetadata.returns({
getName: sinon.stub().returns('myName')
});
let packageFile = new EditorFile('package', 'package', 'myContent', 'package');
packageFile.setJsonContent({name: 'myName', version: '1.0.0'});
fileService['packageJson'] = packageFile;
let result = fileService.validateFile('package', 'package');
result.toString().should.contain('A more recent version of the Business Network has already been deployed.');
}));
it('should throw an error when no match with provided file type', fakeAsync(inject([FileService], (fileService: FileService) => {
let id = '1';
let type = 'octopus';
let result = fileService.validateFile(id, type);
result.toString().should.contain('Attempted validation of unknown file of type: octopus');
})));
});
describe('set and get current file', () => {
it('should set and get the current file for the editor', inject([FileService], (fileService: FileService) => {
let TEST = {name: 'foo', val: 'bar'};
assert.isNull(fileService.getCurrentFile());
fileService.setCurrentFile(TEST);
assert.equal(fileService.getCurrentFile(), TEST);
}));
});
describe('loadFiles', () => {
let deleteAllFileStub;
let addFileStub;
let getFilesStub;
let aclStub;
let queryStub;
let metaStub;
beforeEach(inject([FileService], (fileService: FileService) => {
deleteAllFileStub = sinon.stub(fileService, 'deleteAllFiles');
addFileStub = sinon.stub(fileService, 'addFile');
getFilesStub = sinon.stub(fileService, 'getEditorFiles').returns(['myFiles']);
sinon.stub(fileService, 'getModelFiles').returns([{
getNamespace: sinon.stub().returns('myNameSpace'),
getName: sinon.stub().returns('myName'),
getDefinitions: sinon.stub().returns('myDefs')
}]);
sinon.stub(fileService, 'getScripts').returns([{
getIdentifier: sinon.stub().returns('myId'),
getContents: sinon.stub().returns('contents')
}]);
aclStub = sinon.stub(fileService, 'getAclFile').returns({
getIdentifier: sinon.stub().returns('myId'),
getDefinitions: sinon.stub().returns('myDefs')
});
queryStub = sinon.stub(fileService, 'getQueryFile').returns({
getIdentifier: sinon.stub().returns('myId'),
getDefinitions: sinon.stub().returns('myDefs')
});
metaStub = sinon.stub(fileService, 'getMetaData').returns({
getPackageJson: sinon.stub().returns('myJson'),
getREADME: sinon.stub().returns('myReadMe')
});
}));
it('should load all the files', inject([FileService], (fileService: FileService) => {
let result = fileService.loadFiles();
result.should.deep.equal(['myFiles']);
deleteAllFileStub.should.have.been.called;
addFileStub.firstCall.should.have.been.calledWith('myNameSpace', 'myName', 'myDefs', 'model');
addFileStub.secondCall.should.have.been.calledWith('myId', 'myId', 'contents', 'script');
addFileStub.thirdCall.should.have.been.calledWith('myId', 'myId', 'myDefs', 'acl');
addFileStub.getCall(3).should.have.been.calledWith('myId', 'myId', 'myDefs', 'query');
addFileStub.getCall(4).should.have.been.calledWith('readme', 'README.md', 'myReadMe', 'readme');
addFileStub.getCall(5).should.have.been.calledWith('package', 'package.json', '"myJson"', 'package');
getFilesStub.should.have.been.called;
fileService['dirty'].should.deep.equal(false);
should.not.exist(fileService['currentFile']);
}));
it('should load files without acl, query, package and readme', inject([FileService], (fileService: FileService) => {
aclStub.returns(null);
queryStub.returns(null);
metaStub.returns({getREADME: sinon.stub(), getPackageJson: sinon.stub()});
let result = fileService.loadFiles();
result.should.deep.equal(['myFiles']);
deleteAllFileStub.should.have.been.called;
addFileStub.firstCall.should.have.been.calledWith('myNameSpace', 'myName', 'myDefs', 'model');
addFileStub.secondCall.should.have.been.calledWith('myId', 'myId', 'contents', 'script');
addFileStub.callCount.should.equal(2);
getFilesStub.should.have.been.called;
fileService['dirty'].should.deep.equal(false);
should.not.exist(fileService['currentFile']);
}));
it('should load all the files and unset currentFile', inject([FileService], (fileService: FileService) => {
let file = {
getType: sinon.stub().returns('model'),
getContent: sinon.stub().returns('myContent'),
getId: sinon.stub().returns('myId')
};
let file2 = {
getType: sinon.stub().returns('script'),
getContent: sinon.stub().returns('myContent'),
getId: sinon.stub().returns('myId')
};
fileService['currentFile'] = file;
getFilesStub.returns([file2]);
let result = fileService.loadFiles();
result[0].should.deep.equal(file2);
deleteAllFileStub.should.have.been.called;
addFileStub.firstCall.should.have.been.calledWith('myNameSpace', 'myName', 'myDefs', 'model');
addFileStub.secondCall.should.have.been.calledWith('myId', 'myId', 'contents', 'script');
addFileStub.thirdCall.should.have.been.calledWith('myId', 'myId', 'myDefs', 'acl');
addFileStub.getCall(3).should.have.been.calledWith('myId', 'myId', 'myDefs', 'query');
addFileStub.getCall(4).should.have.been.calledWith('readme', 'README.md', 'myReadMe', 'readme');
getFilesStub.should.have.been.called;
fileService['dirty'].should.deep.equal(false);
should.not.exist(fileService['currentFile']);
}));
it('should load all the files and keep currentFile', inject([FileService], (fileService: FileService) => {
let file = {
getType: sinon.stub().returns('model'),
getContent: sinon.stub().returns('myContent'),
getId: sinon.stub().returns('myId')
};
fileService['currentFile'] = file;
getFilesStub.returns([file]);
let result = fileService.loadFiles();
result.should.deep.equal([file]);
deleteAllFileStub.should.have.been.called;
addFileStub.firstCall.should.have.been.calledWith('myNameSpace', 'myName', 'myDefs', 'model');
addFileStub.secondCall.should.have.been.calledWith('myId', 'myId', 'contents', 'script');
addFileStub.thirdCall.should.have.been.calledWith('myId', 'myId', 'myDefs', 'acl');
addFileStub.getCall(3).should.have.been.calledWith('myId', 'myId', 'myDefs', 'query');
addFileStub.getCall(4).should.have.been.calledWith('readme', 'README.md', 'myReadMe', 'readme');
getFilesStub.should.have.been.called;
this.dirty = false;
fileService['currentFile'].should.deep.equal(file);
}));
});
describe('updateBusinessNetwork', () => {
let updateBusinessNetworkFileStub;
beforeEach(inject([FileService], (fileService: FileService) => {
updateBusinessNetworkFileStub = sinon.stub(fileService, 'updateBusinessNetworkFile');
}));
it('should update a model file', inject([FileService], (fileService: FileService) => {
let editorFile = new EditorFile('myId', 'myDisplayId', 'myContent', 'model');
sinon.stub(fileService, 'getModelFile').returns('myFile');
fileService.updateBusinessNetwork('oldId', editorFile);
updateBusinessNetworkFileStub.should.have.been.calledWith('oldId', 'myContent', 'model');
}));
it('should add a model file', inject([FileService], (fileService: FileService) => {
let editorFile = new EditorFile('myId', 'myDisplayId', 'myContent', 'model');
sinon.stub(fileService, 'getModelFile');
let mockModelManager = {
addModelFile: sinon.stub()
};
businessNetworkDefMock.getModelManager.returns(mockModelManager);
fileService['currentBusinessNetwork'] = businessNetworkDefMock;
fileService.updateBusinessNetwork('oldId', editorFile);
mockModelManager.addModelFile.should.have.been.calledWith('myContent', 'myDisplayId');
}));
it('should update a script file', inject([FileService], (fileService: FileService) => {
let editorFile = new EditorFile('myId', 'myDisplayId', 'myContent', 'script');
sinon.stub(fileService, 'getScriptFile').returns('myFile');
fileService.updateBusinessNetwork('oldId', editorFile);
updateBusinessNetworkFileStub.should.have.been.calledWith('oldId', 'myContent', 'script');
}));
it('should add a script file', inject([FileService], (fileService: FileService) => {
let editorFile = new EditorFile('myId', 'myDisplayId', 'myContent', 'script');
sinon.stub(fileService, 'getScriptFile');
sinon.stub(fileService, 'createScriptFile').returns('myScriptFile');
let mockScriptManager = {
addScript: sinon.stub()
};
businessNetworkDefMock.getScriptManager.returns(mockScriptManager);
fileService['currentBusinessNetwork'] = businessNetworkDefMock;
fileService.updateBusinessNetwork('oldId', editorFile);
mockScriptManager.addScript.should.have.been.calledWith('myScriptFile');
}));
it('should update a acl file', inject([FileService], (fileService: FileService) => {
let editorFile = new EditorFile('myId', 'myDisplayId', 'myContent', 'acl');
sinon.stub(fileService, 'getAclFile').returns('myFile');
fileService.updateBusinessNetwork('oldId', editorFile);
updateBusinessNetworkFileStub.should.have.been.calledWith('oldId', 'myContent', 'acl');
}));
it('should add a acl file', inject([FileService], (fileService: FileService) => {
let editorFile = new EditorFile('myId', 'myDisplayId', 'myContent', 'acl');
sinon.stub(fileService, 'getAclFile');
sinon.stub(fileService, 'createAclFile').returns('myAclFile');
let mockAclManager = {
setAclFile: sinon.stub()
};
businessNetworkDefMock.getAclManager.returns(mockAclManager);
fileService['currentBusinessNetwork'] = businessNetworkDefMock;
fileService.updateBusinessNetwork('oldId', editorFile);
mockAclManager.setAclFile.should.have.been.calledWith('myAclFile');
}));
it('should update a query file', inject([FileService], (fileService: FileService) => {
let editorFile = new EditorFile('myId', 'myDisplayId', 'myContent', 'query');
sinon.stub(fileService, 'getQueryFile').returns('myFile');
fileService.updateBusinessNetwork('oldId', editorFile);
updateBusinessNetworkFileStub.should.have.been.calledWith('oldId', 'myContent', 'query');
}));
it('should add a query file', inject([FileService], (fileService: FileService) => {
let editorFile = new EditorFile('myId', 'myDisplayId', 'myContent', 'query');
sinon.stub(fileService, 'getQueryFile');
sinon.stub(fileService, 'createQueryFile').returns('myQueryFile');
let mockQueryManager = {
setQueryFile: sinon.stub()
};
businessNetworkDefMock.getQueryManager.returns(mockQueryManager);
fileService['currentBusinessNetwork'] = businessNetworkDefMock;
fileService.updateBusinessNetwork('oldId', editorFile);
mockQueryManager.setQueryFile.should.have.been.calledWith('myQueryFile');
}));
it('should update read me', inject([FileService], (fileService: FileService) => {
let editorFile = new EditorFile('myId', 'myDisplayId', 'myContent', 'readme');
fileService.updateBusinessNetwork('oldId', editorFile);
updateBusinessNetworkFileStub.should.have.been.calledWith('oldId', 'myContent', 'readme');
}));
it('should update package json', inject([FileService], (fileService: FileService) => {
let editorFile = new EditorFile('myId', 'myDisplayId', 'myContent', 'package');
fileService.updateBusinessNetwork('oldId', editorFile);
updateBusinessNetworkFileStub.should.have.been.calledWith('oldId', 'myContent', 'package');
}));
it('should throw an error when no match with provided file type', inject([FileService], (fileService: FileService) => {
let editorFile = new EditorFile('octopusId', 'octopusDisplayId', 'octopusContent', 'octopus');
(() => {
fileService.updateBusinessNetwork('oldId', editorFile);
}).should.throw(/Attempted update of unknown file of type: octopus/);
fileService['dirty'].should.equal(false);
}));
});
describe('createAclFile', () => {
let mockBusinessNetwork;
beforeEach(() => {
mockBusinessNetwork = sinon.createStubInstance(BusinessNetworkDefinition);
});
it('should create an ACL file', fakeAsync(inject([FileService], (service: FileService) => {
service['currentBusinessNetwork'] = mockBusinessNetwork;
let allRule = 'rule SystemACL {description: "System ACL to permit all access" participant: "org.hyperledger.composer.system.Participant" operation: ALL resource: "org.hyperledger.composer.system.**" action: ALLOW}';
let aclFile = service.createAclFile('permissions', allRule);
aclFile.should.be.instanceOf(AclFile);
mockBusinessNetwork.getModelManager.should.have.been.called;
})));
});
describe('getModelFile', () => {
it('should get the model file', inject([FileService], (service: FileService) => {
service['currentBusinessNetwork'] = businessNetworkDefMock;
let modelManagerMock = {
getModelFile: sinon.stub().returns(modelFileMock)
};
businessNetworkDefMock.getModelManager.returns(modelManagerMock);
let result = service.getModelFile('testId');
result.should.deep.equal(modelFileMock);
modelManagerMock.getModelFile.should.have.been.calledWith('testId');
}));
});
describe('updateBusinessNetworkFile', () => {
let businessNetworkChangedSpy;
let modelManagerMock;
let namespaceChangedSpy;
let mockNamespaceCollide;
beforeEach(inject([FileService], (service: FileService) => {
service['currentBusinessNetwork'] = businessNetworkDefMock;
mockNamespaceCollide = sinon.stub(service, 'modelNamespaceCollides').returns(false);
businessNetworkChangedSpy = sinon.spy(service.businessNetworkChanged$, 'next');
namespaceChangedSpy = sinon.spy(service.namespaceChanged$, 'next');
modelManagerMock = {
addModelFile: sinon.stub(),
updateModelFile: sinon.stub(),
deleteModelFile: sinon.stub(),
getModelFile: sinon.stub().returns(modelFileMock),
};
}));
it('should update a model file if id matches namespace', inject([FileService], (service: FileService) => {
modelFileMock.getNamespace.returns('model-ns');
modelFileMock.getName.returns('model.cto');
businessNetworkDefMock.getModelManager.returns(modelManagerMock);
let mockCreateModelFile = sinon.stub(service, 'createModelFile').returns(modelFileMock);
let result = service.updateBusinessNetworkFile('model-ns', 'my-model-content', 'model');
modelManagerMock.updateModelFile.should.have.been.calledWith(modelFileMock);
modelManagerMock.addModelFile.should.not.have.been.called;
should.not.exist(result);
}));
it('should replace a model file if id does not match namespace', inject([FileService], (service: FileService) => {
businessNetworkDefMock.getModelManager.returns(modelManagerMock);
modelFileMock.getNamespace.returns('model-ns');
modelFileMock.getName.returns('model.cto');
let mockCreateModelFile = sinon.stub(service, 'createModelFile').returns(modelFileMock);
let result = service.updateBusinessNetworkFile('diff-model-ns', 'my-model-content', 'model');
modelManagerMock.addModelFile.should.have.been.calledWith(modelFileMock);
should.not.exist(result);
}));
it('should notify if model file namespace changes', inject([FileService], (service: FileService) => {
businessNetworkDefMock.getModelManager.returns(modelManagerMock);
modelFileMock.getNamespace.returns('new-model-ns');
modelManagerMock.getModelFile.returns(modelFileMock);
let mockCreateModelFile = sinon.stub(service, 'createModelFile').returns(modelFileMock);
service.updateBusinessNetworkFile('model-ns', 'my-model-content', 'model');
namespaceChangedSpy.should.have.been.calledWith('new-model-ns');
}));
it('should update a script file', inject([FileService], (service: FileService) => {
let scriptManagerMock = {
createScript: sinon.stub().returns(scriptFileMock),
addScript: sinon.stub()
};
businessNetworkDefMock.getScriptManager.returns(scriptManagerMock);
let result = service.updateBusinessNetworkFile('script', 'my-script', 'script');
scriptManagerMock.createScript.should.have.been.calledWith('script', 'JS', 'my-script');
scriptManagerMock.addScript.should.have.been.calledWith(scriptFileMock);
should.not.exist(result);
}));
it('should update a acl file', inject([FileService], (service: FileService) => {
let aclManagerMock = {
setAclFile: sinon.stub()
};
businessNetworkDefMock.getAclManager.returns(aclManagerMock);
let mockCreateAclFile = sinon.stub(service, 'createAclFile').returns(aclFileMock);
let result = service.updateBusinessNetworkFile('acl', 'my-acl', 'acl');
aclManagerMock.setAclFile.should.have.been.calledWith(aclFileMock);
should.not.exist(result);
}));
it('should update a query file', inject([FileService], (service: FileService) => {
let queryManagerMock = {
setQueryFile: sinon.stub()
};
businessNetworkDefMock.getQueryManager.returns(queryManagerMock);
let mockCreateQueryFile = sinon.stub(service, 'createQueryFile').returns(queryFileMock);
// call function
let result = service.updateBusinessNetworkFile('query', 'my-query', 'query');
queryManagerMock.setQueryFile.should.have.been.calledWith(queryFileMock);
should.not.exist(result);
}));
it('should update a package.json file', inject([FileService], (service: FileService) => {
let mockSetPackage = sinon.stub(service, 'setBusinessNetworkPackageJson');
let packageJson = JSON.stringify({name: 'my name'});
// call function
let result = service.updateBusinessNetworkFile('package', packageJson, 'package');
mockSetPackage.should.have.been.calledWith(packageJson);
}));
it('should update a readme file', inject([FileService], (service: FileService) => {
let mockSetReadme = sinon.stub(service, 'setBusinessNetworkReadme');
// call function
let result = service.updateBusinessNetworkFile('readme.md', 'read this', 'readme');
mockSetReadme.should.have.been.calledWith('read this');
}));
it('should not replace a model file if id does not match namespace and file is invalid', inject([FileService], (service: FileService) => {
let error = new Error('invalid');
modelManagerMock = {
addModelFile: sinon.stub().throws(error),
updateModelFile: sinon.stub().throws(error),
deleteModelFile: sinon.stub(),
getModelFile: sinon.stub().returns(modelFileMock)
};
businessNetworkDefMock.getModelManager.returns(modelManagerMock);
modelFileMock.getNamespace.returns('new-model');
let mockCreateModelFile = sinon.stub(service, 'createModelFile').returns(modelFileMock);
try {
service.updateBusinessNetworkFile('model', 'my-model', 'model');
} catch (e) {
e.should.deep.equal(error);
}
}));
it('should not update an invalid script file', inject([FileService], (service: FileService) => {
let error = new Error('invalid');
let scriptManagerMock = {
createScript: sinon.stub().throws(error),
addScript: sinon.stub()
};
businessNetworkDefMock.getScriptManager.returns(scriptManagerMock);
try {
service.updateBusinessNetworkFile('script', 'my-script', 'script');
} catch (e) {
e.should.deep.equal(error);
}
}));
it('should not update an invalid acl file', inject([FileService], (service: FileService) => {
let error = new Error('invalid');
let aclManagerMock = {
setAclFile: sinon.stub().throws(error)
};
businessNetworkDefMock.getAclManager.returns(aclManagerMock);
let mockCreateAclFile = sinon.stub(service, 'createAclFile').returns(aclFileMock);
try {
service.updateBusinessNetworkFile('acl', 'my-acl', 'acl');
} catch (e) {
e.should.deep.equal(error);
}
}));
it('should not update a model file if namespace collision detected', inject([FileService], (service: FileService) => {
let error = new Error('The namespace collides with existing model namespace new-model');
modelManagerMock = {
addModelFile: sinon.stub(),
updateModelFile: sinon.stub(),
deleteModelFile: sinon.stub(),
getModelFile: sinon.stub().returns(modelFileMock)
};
mockNamespaceCollide.returns(true);
businessNetworkDefMock.getModelManager.returns(modelManagerMock);
modelFileMock.getNamespace.returns('new-model');
let mockCreateModelFile = sinon.stub(service, 'createModelFile').returns(modelFileMock);
try {
service.updateBusinessNetworkFile('model', 'my-model', 'model');
} catch (e) {
e.toString().should.equal(error.toString());
}
modelManagerMock.updateModelFile.should.not.have.been.called;
}));
it('should return error message if type is invalid', inject([FileService], (service: FileService) => {
let error = new Error('Attempted update of unknown file of type: wombat');
try {
service.updateBusinessNetworkFile('bad.file', 'content of wombat type', 'wombat');
} catch (e) {
e.toString().should.equal(error.toString());
}
}));
});
describe('replaceBusinessNetworkFile', () => {
it('should handle error case by notifying and returning error message in string', inject([FileService], (service: FileService) => {
service['currentBusinessNetwork'] = businessNetworkDefMock;
(service['currentBusinessNetwork'].getModelManager as any).throws(new Error('Forced Error'));
let businessNetworkChangedSpy = sinon.spy(service.businessNetworkChanged$, 'next');
let response = service.replaceBusinessNetworkFile('oldId', 'newId', 'content', 'model');
businessNetworkChangedSpy.should.have.been.calledWith(false);
response.should.equal('Error: Forced Error');
}));
it('should replace a model file by model manager update', inject([FileService], (service: FileService) => {
let modelManagerMock = {
updateModelFile: sinon.stub()
};
businessNetworkDefMock.getModelManager.returns(modelManagerMock);
service['currentBusinessNetwork'] = businessNetworkDefMock;
let mockCreateModelFile = sinon.stub(service, 'createModelFile').returns(modelFileMock);
let businessNetworkChangedSpy = sinon.spy(service.businessNetworkChanged$, 'next');
// Call the method (model)
let response = service.replaceBusinessNetworkFile('oldId', 'newId', 'content', 'model');
// Check correct items were called with correct parameters
modelManagerMock.updateModelFile.should.have.been.calledWith(modelFileMock, 'newId');
businessNetworkChangedSpy.should.have.been.calledWith(true);
should.not.exist(response);
}));
it('should replace a script file by deletion and addition', inject([FileService], (service: FileService) => {
let scriptManagerMock = {
createScript: sinon.stub().returns(scriptFileMock),
addScript: sinon.stub(),
deleteScript: sinon.stub()
};
businessNetworkDefMock.getScriptManager.returns(scriptManagerMock);
service['currentBusinessNetwork'] = businessNetworkDefMock;
let businessNetworkChangedSpy = sinon.spy(service.businessNetworkChanged$, 'next');
// Call the method (script)
let response = service.replaceBusinessNetworkFile('oldId', 'newId', 'content', 'script');
// Check correct items were called with correct parameters
scriptManagerMock.addScript.should.have.been.calledWith(scriptFileMock);
scriptManagerMock.deleteScript.should.have.been.calledWith('oldId');
businessNetworkChangedSpy.should.have.been.calledWith(true);
should.not.exist(response);
}));
it('should return error message if type is invalid', inject([FileService], (service: FileService) => {
let result = service.replaceBusinessNetworkFile('oldId', 'newId', 'content', 'wombat');
result.should.equal('Error: Attempted replace of ununsupported file type: wombat');
}));
});
describe('modelNamespaceCollides', () => {
let modelManagerMock;
let mockCreateBusinessNetwork;
let mockFile0 = sinon.createStubInstance(ModelFile);
mockFile0.getNamespace.returns('name0');
let mockFile1 = sinon.createStubInstance(ModelFile);
mockFile1.getNamespace.returns('name1');
let mockFile2 = sinon.createStubInstance(ModelFile);
mockFile2.getNamespace.returns('name2');
let mockFile3 = sinon.createStubInstance(ModelFile);
mockFile3.getNamespace.returns('name3');
let mockFile4 = sinon.createStubInstance(ModelFile);
mockFile4.getNamespace.returns('name4');
beforeEach(inject([FileService], (service: FileService) => {
modelManagerMock = {
getModelFiles: sinon.stub().returns([mockFile0, mockFile1, mockFile2, mockFile3, mockFile4])
};
businessNetworkDefMock.getModelManager.returns(modelManagerMock);
service['currentBusinessNetwork'] = businessNetworkDefMock;
}));
it('should return true if namespace collision detected', inject([FileService], (service: FileService) => {
let result = service.modelNamespaceCollides('name1', 'something-different');
result.should.be.equal(true);
}));
it('should return false if no namespace collision detected with new name', inject([FileService], (service: FileService) => {
let result = service.modelNamespaceCollides('not-in-list', 'something-different');
result.should.be.equal(false);
}));
it('should handle no previousNamespace being passed', inject([FileService], (service: FileService) => {
let result = service.modelNamespaceCollides('new-namespace', null);
result.should.be.equal(false);
}));
it('should handle no model files existing in BND', inject([FileService], (service: FileService) => {
modelManagerMock = {
getModelFiles: sinon.stub().returns([])
};
let result = service.modelNamespaceCollides('not-in-list', 'something-different');
result.should.be.equal(false);
}));
});
describe('getScriptFile', () => {
it('should get the script file', inject([FileService], (service: FileService) => {
let scriptManagerMock = {
getScript: sinon.stub().returns(scriptFileMock)
};
businessNetworkDefMock.getScriptManager.returns(scriptManagerMock);
service['currentBusinessNetwork'] = businessNetworkDefMock;
let result = service.getScriptFile('testId');
result.should.deep.equal(scriptFileMock);
scriptManagerMock.getScript.should.have.been.calledWith('testId');
}));
});
describe('getAclFile', () => {
it('should get the acl file', inject([FileService], (service: FileService) => {
let aclManagerMock = {
getAclFile: sinon.stub().returns(aclFileMock)
};
businessNetworkDefMock.getAclManager.returns(aclManagerMock);
service['currentBusinessNetwork'] = businessNetworkDefMock;
let result = service.getAclFile();
result.should.deep.equal(aclFileMock);
aclManagerMock.getAclFile.should.have.been.called;
}));
});
describe('getQueryFile', () => {
it('should get the query file', inject([FileService], (service: FileService) => {
let queryManagerMock = {
getQueryFile: sinon.stub().returns(queryFileMock)
};
businessNetworkDefMock.getQueryManager.returns(queryManagerMock);
service['currentBusinessNetwork'] = businessNetworkDefMock;
let result = service.getQueryFile();
result.should.deep.equal(queryFileMock);
queryManagerMock.getQueryFile.should.have.been.called;
}));
});
describe('createQueryFile', () => {
let mockBusinessNetwork;
beforeEach(() => {
mockBusinessNetwork = sinon.createStubInstance(BusinessNetworkDefinition);
});
it('should create a Query file', fakeAsync(inject([FileService], (service: FileService) => {
service['currentBusinessNetwork'] = mockBusinessNetwork;
let queryFile = service.createQueryFile('query', '');
queryFile.should.be.instanceOf(QueryFile);
mockBusinessNetwork.getModelManager.should.have.been.called;
})));
});
describe('setBusinessNetwork...', () => {
beforeEach(inject([FileService], (service: FileService) => {
let modelManagerMock = {
getModelFiles: sinon.stub().returns([modelFileMock, modelFileMock]),
addModelFiles: sinon.stub()
};
let aclManagerMock = {
setAclFile: sinon.stub(),
getAclFile: sinon.stub().returns(aclFileMock)
};
let scriptManagerMock = {
getScripts: sinon.stub().returns([scriptFileMock, scriptFileMock]),
addScript: sinon.stub()
};
let queryManagerMock = {
setQueryFile: sinon.stub(),
getQueryFile: sinon.stub().returns(queryFileMock)
};
businessNetworkDefMock.getModelManager.returns(modelManagerMock);
businessNetworkDefMock.getScriptManager.returns(scriptManagerMock);
businessNetworkDefMock.getAclManager.returns(aclManagerMock);
businessNetworkDefMock.getQueryManager.returns(queryManagerMock);
service['currentBusinessNetwork'] = businessNetworkDefMock;
}));
it('should set business network readme', inject([FileService], (service: FileService) => {
let businessNetworkChangedSpy = sinon.spy(service.businessNetworkChanged$, 'next');
businessNetworkDefMock.getMetadata.returns({
setReadme: sinon.stub()
});
service.setBusinessNetworkReadme('my readme');
businessNetworkDefMock.setReadme.should.have.been.calledWith('my readme');
}));
it('should set business network packageJson', inject([FileService], (service: FileService) => {
businessNetworkDefMock.getMetadata.returns({
getName: sinon.stub().returns('my name')
});
let packageJson = {name: 'my name', version: 'my version', description: 'my description'};
service.setBusinessNetworkPackageJson(JSON.stringify(packageJson, null, 2));
businessNetworkDefMock.setPackageJson.should.have.been.calledWith(packageJson);
}));
});
describe('getModelFiles', () => {
it('should get model files', inject([FileService], (service: FileService) => {
let modelManagerMock = {
getModelFiles: sinon.stub().returns([modelFileMock, modelFileMock])
};
businessNetworkDefMock.getModelManager.returns(modelManagerMock);
sinon.stub(service, 'getBusinessNetwork').returns(businessNetworkDefMock);
let result = service.getModelFiles();
result.length.should.equal(2);
result[0].should.deep.equal(modelFileMock);
result[1].should.deep.equal(modelFileMock);
}));
it('should not get sys model files', inject([FileService], (service: FileService) => {
let sysModel = sinon.createStubInstance(ModelFile);
sysModel.systemModelFile = true;
let modelManagerMock = {
getModelFiles: sinon.stub().returns([modelFileMock, modelFileMock, sysModel])
};
businessNetworkDefMock.getModelManager.returns(modelManagerMock);
sinon.stub(service, 'getBusinessNetwork').returns(businessNetworkDefMock);
let result = service.getModelFiles(false);
result.length.should.equal(2);
result[0].should.deep.equal(modelFileMock);
result[1].should.deep.equal(modelFileMock);
}));
});
describe('getScripts', () => {
it('should get script files', inject([FileService], (service: FileService) => {
let scriptManagerMock = {
getScripts: sinon.stub().returns([scriptFileMock, scriptFileMock])
};
businessNetworkDefMock.getScriptManager.returns(scriptManagerMock);
service['currentBusinessNetwork'] = businessNetworkDefMock;
let result = service.getScripts();
result.length.should.equal(2);
result[0].should.deep.equal(scriptFileMock);
result[1].should.deep.equal(scriptFileMock);
}));
});
describe('getMetaData', () => {
it('should get the metadata', inject([FileService], (service: FileService) => {
businessNetworkDefMock.getMetadata.returns({metadata: 'my metadata'});
service['currentBusinessNetwork'] = businessNetworkDefMock;
let result = service.getMetaData();
result.should.deep.equal({metadata: 'my metadata'});
businessNetworkDefMock.getMetadata.should.have.been.called;
}));
});
describe('getBusinessNetworkName', () => {
it('should get the name', inject([FileService], (service: FileService) => {
sinon.stub(service, 'getBusinessNetwork').returns(businessNetworkDefMock);
businessNetworkDefMock.getMetadata.returns({
getName: sinon.stub().returns('my name')
});
let result = service.getBusinessNetworkName();
result.should.equal('my name');
}));
});
describe('getBusinessNetworkVersion', () => {
it('should get the name', inject([FileService], (service: FileService) => {
sinon.stub(service, 'getBusinessNetwork').returns(businessNetworkDefMock);
businessNetworkDefMock.getMetadata.returns({
getVersion: sinon.stub().returns('1.0.0')
});
let result = service.getBusinessNetworkVersion();
result.should.equal('1.0.0');
}));
});
describe('getBusinessNetworkDescription', () => {
it('should get the description', inject([FileService], (service: FileService) => {
sinon.stub(service, 'getBusinessNetwork').returns(businessNetworkDefMock);
businessNetworkDefMock.getMetadata.returns({
getDescription: sinon.stub().returns('my description')
});
let result = service.getBusinessNetworkDescription();
result.should.equal('my description');
}));
});
describe('getBusinessNetwork', () => {
it('should get the businessNetwork', inject([FileService], (service: FileService) => {
service['currentBusinessNetwork'] = businessNetworkDefMock;
let result = service.getBusinessNetwork();
result.should.deep.equal(businessNetworkDefMock);
}));
});
describe('changesDeployed', () => {
it('should set dirty to false', inject([FileService], (service: FileService) => {
service['dirty'] = true;
service.changesDeployed();
service['dirty'].should.deep.equal(false);
}));
});
describe('isDirty', () => {
it('should return dirty', inject([FileService], (service: FileService) => {
service['dirty'] = true;
service.isDirty().should.deep.equal(true);
}));
it('should return dirty', inject([FileService], (service: FileService) => {
service['dirty'] = false;
service.isDirty().should.deep.equal(false);
}));
});
}); | the_stack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.